随机数范围为1-8,期望输出为1,1,2,2,4,4,3,3,5,5,6,6,7,7,8,8?

时间:2014-12-12 14:01:05

标签: java arrays

我有关于如何生成范围为1-8的随机数的问题,我只需要2对这些数字而不是1,1,1或3,3,3。这是我已经导入java.util.random的代码:

          int[][] displayArray = new int[4][4];
        int[][] fieldArray = new int[4][4];

        //generates random Values where "i" represents rows and "j" represents columns
        for (int i = 0; i < fieldArray.length; i++) {
            for (int j = 0; j < fieldArray.length; j++) {
                fieldArray[i][j] = (int) (Math.random() * 8); //generates table with randomized numbers.
            }
        }

        //Print the values
        for (int i = 0; i < fieldArray.length; i++) {          
            for (int j = 0; j < fieldArray.length; j++) {
                 System.out.print("[" + fieldArray[i][j] + "]" + "\t");                     
                }
       // Every time we finish printing a row we jump to the next line.
            System.out.print("\n");
            }

  }

2 个答案:

答案 0 :(得分:3)

for (int j = 0; j < fieldArray.length; j++) {

应该是

for (int j = 0; j < fieldArray[i].length; j++) {

在这两个地方。另外,我更喜欢

Random rand = new Random();
int val = rand.nextInt(8) + 1; // <-- a random number between 1 and 8.

但使用Math.random()您还需要添加+ 1,因为您将包含0(并排除8),

fieldArray[i][j] = 1 + (int) (Math.random() * 8);

答案 1 :(得分:2)

您不希望拥有随机数字,而是您的数字的随机顺序Collections.shuffle()提供了一种方法(在List中随机化顺序)。

此代码适用于任何四边形尺寸(> 0),创建一个填充数字的四边形数组,从1开始,每个数字包含两次,如果可能的话(对于奇数四边形尺寸,您会获得奇数个数字):< / p>

    int quadSize = 4; //4x4 = 16 tiles, containing the numbers 1-8 twice

    List<Integer> values = new ArrayList<>(quadSize * quadSize);

    // add  number twice (1,1,2,2, ....)
    int num = 0;
    boolean first = false;
    while (values.size() < quadSize * quadSize) {
        if (!first) {
            num++;
        }
        values.add(num);
        first = !first;
    }

    // Shuffle the values (random order)
    Collections.shuffle(values);

    // fill into two-dimensional array
    int[][] fieldArray = new int[quadSize][quadSize];
    int index = 0;
    for (int value : values) {
        fieldArray[index / quadSize][index % quadSize] = value;
        index++;
    }

使用您的打印方法输出:

[5] [7] [1] [6] 
[2] [3] [8] [3] 
[6] [8] [5] [1] 
[4] [2] [7] [4]