Corp769 said the important thing in his first sentence: Given an index to a zero-based row-major array, you find the row by dividing by the width, the column is then the remainder.

If you consider how you calculate the index in the first place,

Code:

index = x + y * width

elementary algebra tells you how to solve the inverse:

Code:

x = index / width
y = index % width

where

/ is integer division, and

% gives you the remainder. (

% is called the modulus operator,

MOD in math and some programming languages.)

For a 9x9 sudoku, the indices to a (zero-based row-major) array are

Code:

0 1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16 17
18 19 20 21 22 23 24 25 26
27 28 29 30 31 32 33 34 35
36 37 38 39 40 41 42 43 44
45 46 47 48 49 50 51 52 53
54 55 56 57 58 59 60 61 62
63 64 65 66 67 68 69 70 71
72 73 74 75 76 77 78 79 80

In order to support other configurations, let's use constants

Code:

boxwidth = 3 /* Width of a small box */
boxheight = 3 /* Height of a small box */
hboxes = 3 /* Boxes horizontally */
vboxes = 3 /* Boxes vertically */
width = boxwidth * hboxes
height = boxheight * vboxes

Given an index

*i* into the array, finding the overall row and column should be obvious now:

Code:

y = i / width
x = i % width

To find which column and row

*of boxes* that is in, just do the same again for each of the coordinates.

Code:

boxy = y / boxheight /* Box row */
innery = y % boxheight /* Row within the box */
boxx = x / boxwidth /* Box column */
innerx = x % boxwidth /* Column within the box */

If you want to calculate the

*index* of the box (here, 0 to 8), you do the inverse operation, multiply row by width and add the column:

Code:

box = boxx + hboxes * boxy

If you are interested why I qualified my post with "zero-based row-major array", not all programming languages arrange arrays like this.

According to Wikipedia, Fortran, R, MATLAB and Octave use column-major order for arrays -- i.e. transposed compared to above, swapping width and height, and row and column. In Fortran for example, array indices also start at 1 by default -- making arrays in Fortran "one-based column-major arrays":

Code:

fortran_column = 1 + (fortran_index - 1) / height
fortran_row = 1 + MOD(fortran_index - 1, height)
fortran_index = fortran_row + (fortran_column - 1) * height

Hope this helps.