Sudoku - find the current area based on the row, column

enter image description here

Based on the above coordinates in the image above, I would like to be able to calculate which β€œsquare” is highlighted in red, the selected cell belongs.

I solve the sudoku puzzle, and I have access to the width of each square, as well as the row / column that the cell is in.

I had problems calculating the "number" of the square to which the cell belongs (they start from 1 and increase from left to right, from top to bottom), so the number of squares is higher:

1 | 2
3 | 4

How could I calculate this? We appreciate any suggestions. Either a Java-specific method, or just an algorithm will be fine :)

+3
source share
3
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;
}
+3
squareX = 1 + (cellX - 1) / cellsPerSquareX;
squareY = 1 + (cellY - 1) / cellsPerSquareY;
0
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;
0

All Articles