我想這個問題與蠻力的方法和它的工作原理。 花費不到1秒生成一個獨特的9×9板。
輸出:
1 2 3 4 5 6 7 8 9
2 6 8 9 7 4 1 3 5
6 3 5 7 9 1 2 4 8
9 5 4 8 6 2 3 1 7
5 4 7 1 2 8 9 6 3
8 1 9 6 3 7 5 2 4
4 9 2 3 8 5 6 7 1
7 8 6 5 1 3 4 9 2
3 7 1 2 4 9 8 5 6
下面是我的代碼:
public static void main(String[] args){
int size = 9;
int[][] board= new int[size][size];
board[0] = Util.createOrderedArray(size, 1);
for(int x=1; x<size; x++){
board[x] = Util.createOrderedArray(size, 1);
do{
Util.shuffle(board[x]);
}while(!Util.compare2DArray(board[x], board, 0, x));
}
Util.print(board);
}
我寫了一個自定義的Util類中的所有幫助我的方法。
final class Util
{
public static void shuffle(int[] num){
Random rnd = new Random();
for(int x=0; x<num.length; x++)
swap(num, x, rnd.nextInt(num.length));
}
public static void swap(int[] num, int a, int b){
int temp = num[a];
num[a] = num[b];
num[b] = temp;
}
public static int[] createOrderedArray(int size, int startValue){
int[] num = new int[size];
for(int x=0; x<num.length; x++)
num[x] = x+startValue;
return num;
}
//Return TRUE if array vs arrays is COMPLETELY different
public static boolean compare2DArray(int[] num1, int[][] num2, int start, int end){
for(int x=start; x<end; x++)
if(!compareArray(num1, num2[x]))
return false;
return true;
}
//Return TRUE if arrays are COMPLETELY different
public static boolean compareArray(int[] num1, int[] num2){
if(num1.length != num2.length)
return false;
for(int x=0; x<num1.length; x++)
if(num1[x] == num2[x])
return false;
return true;
}
public static void print(int[][] num){
for(int x=0; x<num.length; x++){
for(int y=0; y<num[0].length; y++)
System.out.print(num[x][y] + " ");
System.out.println("");
}
}
}
這是通過強力方法來完成。如果你想優雅地做,它會更有效率,如果我們遞歸地做,所以沒有不必要的循環浪費。
這個輸出看起來像我期望從這個代碼。它是純粹的(僞)隨機... – dotvav
我知道,我想給它一些條件,以便我可以重新生成它incase在行或列有重複。 –
@AND您將使用的最大可能的二維數組大小是多少?只有3 x 3? – user3437460