7

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 :)

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
ILoveToCode
  • 73
  • 1
  • 3
  • Would you know how many columns you may have? – Chandu Mar 11 '11 at 04:57
  • Seeing that I know the width of each square, I could calculate the number of columns and the number of rows by width^2. – ILoveToCode Mar 11 '11 at 04:58
  • I don't think knowing the width of each square doesn't give number of columns in a grid... – Chandu Mar 11 '11 at 05:00
  • Sure it does. Since each sub-grid (in this case each sub-grid is 2x2) is a square, and the whole puzzle is also a square, it works fine. width=2, so width^2=4. If the puzzle were a 9x9 one, each sub-grid would be 3 wide, so width^2=9. – ILoveToCode Mar 11 '11 at 05:01
  • Maybe I am missing something but how would you know the number of columns would be 4 and not 8, 16 etc... – Chandu Mar 11 '11 at 05:04
  • This is homework, right (we can usually tell because 4-5 people post pretty much the same question at the same time). If so, please tag it 'homework'. – Jim Garrison Mar 11 '11 at 05:15
  • If you look at it carefully, it does. The width of each square also says how many squares there will be in each row, meaning that the square of that width will equal the number of cells in each row. The same calculation applies to columns, since everything is a square. – ILoveToCode Mar 11 '11 at 05:21
  • 1
    @Jim: Nope, this isn't homework, but I'll definitely keep that etiquette in mind if I do post a homework question. Thanks :) – ILoveToCode Mar 11 '11 at 05:43

3 Answers3

7
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;
}
levis501
  • 4,117
  • 23
  • 25
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;
null0pointer
  • 1,533
  • 3
  • 15
  • 29
0
squareX = 1 + (cellX - 1) / cellsPerSquareX;
squareY = 1 + (cellY - 1) / cellsPerSquareY;
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521