-2

我目前正在研究一个应该代表竞技场/剧院座位系统的二维阵列。我需要产生 20% 的座位来填补。它是一个 5 x 5 阵列。我需要为要填充的阵列生成 5 个随机座位/行组合。(我正在使用随机数生成器)所有帮助将不胜感激。

到目前为止,这是我的代码:

public class Project5b 
{
  static int NUMBER_OF_ROWS = 5;
  static int NUMBER_OF_SEATS = 5;
  static boolean DEBUG = true;
  public int RandomInt(int i1, int i2) {
    int result = (int) (Math.random() * (i1 - i2 + i1)); // check formula
    return result;
  }
  public static void main(String[] args) {
    int seat = 1;
    int row = 2;
    boolean[][] a_theater;
    a_theater = new boolean[NUMBER_OF_ROWS][NUMBER_OF_SEATS];
    for (row = 1; row <= NUMBER_OF_ROWS; row++) {
      for (seat = 1; seat <= NUMBER_OF_SEATS; seat++) {
        a_theater[row - 1][seat - 1] = false;
      }
    }
    if (DEBUG) {
      for (row = 1; row <= NUMBER_OF_ROWS; row++) {
        for (seat = 1; seat <= NUMBER_OF_SEATS; seat++) {
          System.out.println("row" + " " + row + " " + "seat" + " " + seat + " "
              + a_theater[row - 1][seat - 1]);
        }
      }
    }
  }
}

谢谢!

4

3 回答 3

1

替换这个你的循环:

for (row = 1; row <= NUMBER_OF_ROWS; row++) {
  for (seat = 1; seat <= NUMBER_OF_SEATS; seat++) {
    a_theater[row - 1][seat - 1] = false;
  }
}

通过这个代码块:

  int filledNumber = 0;
  Random r = new Random();
  int maxFilled = (int)(NUMBER_OF_ROWS*NUMBER_OF_SEATS * 0.2);
  for(row = 1; row <=NUMBER_OF_ROWS;  row++){
      for(seat = 1; seat <=NUMBER_OF_SEATS; seat++){
        boolean filled = filledNumber <= maxFilled && r.nextBoolean();
        a_theater[row -1][seat -1] = filled;
        if (filled) filledNumber++;             
      }
  }

升级版:

1)固定铸造从doubleint

2) 显示必须将哪个代码块替换为建议的代码块

于 2013-01-14T14:32:26.403 回答
1

我建议以下代码段,您可以根据需要进行调整

确保所有值最初都设置为 0,Arrays.fill()会这样做。

Random rand = new Random(); //instead of Math.random()
int count = 0;
while (count < 5) {
    int randI = rand.nextInt(5); //generate random index
    int randJ = rand.nextInt(5); //generate random index
    boolean randVal = rand.nextBoolean(); //generate random value
    if (!array[randI][randJ]) { // check whether assigned earlier
        array[randI][randJ] = randVal;
        count++;
    }
}
于 2013-01-14T14:33:56.637 回答
0

您将要为该行和该行中的座位生成随机值,因此一对随机值 5 次。

使用for循环构造并查看 java 的Random类来生成数字。您还需要检查以确保您设置了 5 个不同的随机座位,并且不会意外地将同一个座位设置为 true 两次。

于 2013-01-14T14:33:42.437 回答