Sudoku - Find Current Square Based on Row,Column
Based on the above coordinates in the above image, I'd like to be able to calculate which "square" as highlighted in red, the selected cell belongs to.
I'm solving a sudoku puzzle, and I have access to the width of each square, as well as the row/column at which the cell are located.
I'm having trouble calculating the "number" of the square that the cell belongs to (they start at 1, and increase from left-to-right, top-to-bottom), so that the numbers of the squares above are:
1|2
3|4How could I go about calculating t开发者_运维百科his? Any suggestions would be appreciated. Either a Java-specific method, or just an algorithm would be fine :)
int numMajorRows = 2;
int numMajorCols = 2;
int width = 2;
// assuming row and col also start at 1.
int squareNumber(int row, int col) {
int majorRow = (row-1) / width; // zero based majorRow
int majorCol = (col-1) / width; // zero based majorCol
return majorCol + majorRow * numMajorCols + 1;
}
int width = 2;
int nCols = Math.pow(width, 2);
int nRows = Math.pow(width, 2);
int cellRow = 2;
int cellCol = 2;
int squareRow = (cellRow - 1) / nRows;
int squareCol = (cellCol - 1) / nCols;
int squareNum = (squareRow * width) + squareCol + 1;
squareX = 1 + (cellX - 1) / cellsPerSquareX;
squareY = 1 + (cellY - 1) / cellsPerSquareY;
精彩评论