如何在Java中随机填充数组?

我正在编写一个从整数n创建2D数组的程序。 然后我必须使用从1到n n数组大小的值填充数组, 并检查它是否是魔术方块。 我现在这样做的方式现在从1到n n数组大小填充数组。 我该如何随机制作?

我的代码:

System.out.print("Enter an whole number: "); int n = scan.nextInt(); int [][] magic = new int [n][n]; for (int row = 0; row < magic.length; row++) { for(int col = 0; col < magic[row].length; col++) magic[row][col] = ((row * n) + 1) + col; } 

创建一个拖曳的数字列表以添加到您的数组,如下所示:

  List numbers = new ArrayList(); for (int i=1; i<=n*n; i++) numbers.add(i); Collections.shuffle(numbers); int [][] magic = new int [n][n]; int index = 0; for (int row = 0; row < magic.length; row++) { for(int col = 0; col < magic[row].length; col++) magic[row][col] = numbers.get(index++); } 

你需要改变价值观。 您可以随机播放每一行,然后是每列,但我建议您将所有值放在一个大的n * n 1D数组中并随机播放,然后填充2D数组。

要创建从0到n * n-1的随机方形矩阵:

 System.out.print("Enter an whole number: "); int n = scan.nextInt(); int size = n * n; // create see dvalues List values = new ArrayList(size); for (int i=0; i 

使用范围1到n * n只需稍加修改即可。

第一阶段使用唯一值对范围进行种子化,然后使用标准函数Collections.shuffle()随机化顺序。