Reputation: 439
I need to construct a 8x8 array filled with numbers from 0 to 7, but there can't be any duplicates in rows and columns. Also, the seqence produced should be random.
For instance:
0 1 2 3 4 5 6 7
1 2 3 4 5 6 7 0
2 3 4 5 6 7 0 1
3 4 5 6 7 0 1 2
4 5 6 7 0 1 2 3
5 6 7 0 1 2 3 4
6 7 0 1 2 3 4 5
7 0 1 2 3 4 5 6
is a valid array since there are no duplicates in any row / column.
I started off with this code, however it obviously crashes whenever it runs out of possible numbers to choose from.
int[][] array = new int[8][8];
List <Integer> numbers = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6,7));
Collections.shuffle(numbers);
//populate first row
for(int i = 0; i <= 7; i++) {
array[0][i] = numbers.get(i);
}
//populate the rest of array
for(int i = 1; i <= 7; i++) {
Collections.shuffle(numbers);
for(int j = 0; j <= 7; j++) {
Deque<Integer> numbersToPickFrom = new ArrayDeque<>(numbers);
//Remove duplicates from above
for (int k = 0; k < i ; k++)
numbersToPickFrom.remove(array[k][j]);
//Remove duplicates from left
for (int k = 0; k < j ; k++)
numbersToPickFrom.remove(array[i][k]);
array[i][j] = numbersToPickFrom.pop();
System.out.print(array[i][j]+" ");
}
System.out.print("\n");
}
Output:
3 4 5 7 6 0 2 1
4 5 6 2 0 7 3 Exception in thread "main" java.util.NoSuchElementException
at java.util.ArrayDeque.removeFirst(ArrayDeque.java:280)
at java.util.ArrayDeque.pop(ArrayDeque.java:517)
at kamisado_logic.Board.createRandomSquares(Board.java:209)
at kamisado_util.ThreadDriver.main(ThreadDriver.java:17)
I feel like my approach is faaar from the best one, any tips would be much appreciated.
Upvotes: 3
Views: 1632
Reputation: 99
Your problem is very similar to generating sudoku grid, with a few constraints removed :
You could look at sudoku generation algorithm, and remove the parts you don't need. Here are a few hints to start :
Upvotes: 2