sudoku check subgrid error
Hi can anyone tell me what im doing wrong 开发者_开发问答here? i want to check each subgrid for repeated values in a 9by 9 square.
my method works first by creating each subgrid a one dimensional array which can then check each row for each subgrid. and for it to go to each subgrid i provide its coordinates myself. it checks the first grid 0,0 but does not check other subgrids for repeated values.
can anyone tell me what im doing wrong?
public class SudokuPlayer
{
private int [][] game;
public enum CellState { EMPTY, FIXED, PLAYED };
private CellState[][] gamestate;
private int [][] copy;
private static final int GRID_SIZE=9;
private boolean whichGameToReset;
private int len;
private int stateSize;
private int row;
private int col;
private boolean coordinates(int startX, int startY)
{
row=startX;
col=startY;
if(isBoxValid()==false)
{
return false;
}
return true;
}
public boolean check()
{
if(coordinates(0,0)==false)
{
return false;
}
if(coordinates(0,3)==false)
{
return false;
}
if(coordinates(0,6)==false)
{
return false;
}
if(coordinates(1,0)==false)
{
return false;
}
if( coordinates(1,3)==false)
{
return false;
}
if( coordinates(1,6)==false)
{
return false;
}
if(coordinates(2,0)==false)
{
return false;
}
if(coordinates(2,3)==false)
{
return false;
}
if(coordinates(2,6)==false)
{
return false;
}
return true;
}
private boolean isBoxValid()
{
int[] arrayCopy = new int[game.length];
int currentRow = (row/3)*3;
int currentCol = (col/3)*3;
int i = 0;
for ( int r =currentRow; r < 3; r++)
{
for( int c =currentCol; c < 3; c++)
{
arrayCopy[i] = game[r][c];
i++;
}
}
for ( int p =0; p < arrayCopy.length; p++)
{
for ( int j = p+1; j < arrayCopy.length; j++)
{
if ( arrayCopy[p] == arrayCopy[j] && arrayCopy[j]!=0)
{
return false;
}
}
}
return true;
}
}
The problem is in your isBoxValid() method. You are initializing r
and c
to be currentRow
and currentCol
, respectively, but you run the loop up to a hard coded value of 3, not 3+currentRow
or 3+currentCol
. When currentRow and currentCol are 0, it works fine, but for other numbers, not so much.
Oh, another thing that's nice about writing concise code: it's easier to see where your errors are. Take another look at the numbers you've hard-coded into check()
: you're incrementing the columns by 3 and the rows by 1. That would be much easier to spot if you compressed it into a pair of for
loops.
精彩评论