想法是拥有一个二维数组NxN,其中所有元素(从0到N * N的数字)都位于随机位置。要生成我使用的随机数:

 // Creates a set so we avoid repetition of generated numbers
        Set<Integer> generatedNumbers = new LinkedHashSet<Integer>();
        while (generatedNumbers.size() < numberOfElements){
            Integer next = rng.nextInt(numberOfElements) ;
            generatedNumbers.add(next);
        }


现在,我需要将元素复制到二维数组。基本上是这样的:

   for (Integer number: generatedNumbers){
            // Here I'd like to have:
           // 1st iteration: board[0][0] = number
          // 2nd iteration: board[0][1] = number
          // ...
          // last iteration: board[3][3] = number
        }


哪里:

board = new int[boardSize][boardSize];


对于这种特殊情况,boardSize = 4。
顺便说一句,如果有更好的方法可以达到相同目的,但是使用不同的方法,我很乐于阅读。

最佳答案

如果我理解正确,您想将一个集合中的数字随机分配到一个二维数组中。这是一个基于您提供给我们的工作代码,可以完成此工作:

public static Integer[][] getRandomNumbersArray(int base)
{
    Random rng = new Random();
    int numberOfElements = base * base;

    // Let's use a list so we access by index
    List<Integer> generatedNumbers = new ArrayList<>();

    for (int i = 0; i < numberOfElements; i++)
    {
        // Generate our random number
        Integer next = rng.nextInt(numberOfElements) ;

        // Check if the number is already added
        if (!generatedNumbers.contains(next)) {
            generatedNumbers.add(next);
        }
        // Number was a duplicate, redo loop cycle
        else i--;
    }
    // Create our board array here
    Integer[][] array = new Integer[base][base];

    // Index used to access the list
    int i1 = 0;

    for (int i2 = 0; i2 < base; i2++)
    {
        // Populate board row
        for (int i3 = 0; i3 < base; i3++, i1++) {
            array[i2][i3] = generatedNumbers.get(i1);
        }
    }
    return array;
}

public static void main(String[] args)
{
    Integer[][] array = getRandomNumbersArray(4);

    System.out.println("Here is how our board looks like:");
    for (int i = 0; i < array.length; i++) {
        System.out.println(Arrays.toString(array[i]));
    }
}


输出量

Here is how our board looks like:
[8, 7, 11, 3]
[15, 5, 1, 0]
[2, 9, 10, 12]
[13, 4, 6, 14]

09-05 09:34