ILoveToCode ILoveToCode - 2 months ago 8
Java Question

Sudoku - Find Current Square Based on Row,Column

enter image description here

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|4

How could I go about calculating this? Any suggestions would be appreciated. Either a Java-specific method, or just an algorithm would be fine :)

Answer
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;
}