我希望有人可以帮助我。
基本上,我正在尝试创建一个方法,将一个二维数组作为参数,并从1到9返回9行和9列随机数(想想数独谜题),其中行中没有数字可以重复,也不会重复列中的任何数字。
我几乎就在那里(我认为),但我无法在行(东到西)和列(从北到南)中重复数字。
这是我的代码......
/**
* This method generates a 9x9 2D array and randomly places numbers between 1 and 9 in each cell.
* Each row containing numbers 1 through 9 should not have any repeating numbers going across.
* Each column containing numbers 1 through 9 should not have any repeating numbers going down.
* @param array the array that will be generated
*/
public static void generatePuzzle(int[][] array) {
array = new int[9][9]; //creates array of size N
//generates random numbers 1 inclusive to # exclusive
List<Integer> randomList = new ArrayList<Integer>();
for (int i = 0; i < 9; i++){
randomList.add(i + 1);
}
Collections.shuffle(randomList);
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
array[i][j] = randomList.get(j);
}
// Shuffle the list again to get different values for the next line
Collections.shuffle(randomList);
System.out.println(randomList);
}
}
非常感谢您的任何指示和帮助,您可以给予!!