So i'm trying to get all the possible entries that can be put into a Sudoku single square. I have a 9x9 2D array, which is further divided into 3x3 subarrays. I want to write a method that takes a row & column combination in its parameters and returns all possible entries that can be made at that specific position. The first 2 for-loops of my method takes all the already existing non-zero values in the entire row & entire column that is specified and stores them in an array (alreadyInUse),this will at a later stage be used to figure out what numbers are not already used. The third for-loop should, using the row,column combination, find the specific subarray and add its entries to the alreadyInUse-array.
Is there any way to find the row,column of the subarray using given row,column of the 2D array?
// Method for calculating all possibilities at specific position
public int[] getPossibilities(int col, int row){
int [] possibilities;
int [] alreadyInUse = null;
int currentIndex = 0;
if(sudoku[row][col] != 0){
return new int[]{sudoku[col][row]};
}
else{
alreadyInUse = new int[26];
//Go into Row x and store all available numbers in an alreadyInUse
for(int i=0; i<sudoku.length; i++){
if(sudoku[row][i] !=0){
alreadyInUse[currentIndex] = sudoku[row][i];
currentIndex++;
}
}
for(int j=0; j<sudoku.length; j++){
if(sudoku[j][col] !=0){
alreadyInUse[currentIndex] = sudoku[j][col];
currentIndex++;
}
}
for(int k=...???
}
return possibilities;
}
You can use modulus to filter out the sub array. For example, one way to do it would be to use the expression n - (n % 3)
. For example, if row is column 8 (the last column in a 0 indexed array), this expression will return 6. It will also return 6 for column 6, but it will return 3 for column 5.
Then, once you have the top left cell, you can loop through all 9 cells using a nested loop, three at a time.
Here's relevant code:
int x_left = (row - (row % 3));
int y_top = (col - (col % 3));
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
if(sudoku[i + x_left][j + y_top] != 0) {
alreadyInUse[currentIndex] = sudoku[i + x_left][j + y_top];
currentIndex++;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.