How was this formula derived?

74 Views Asked by At

I am solving this question on LeetCode.com:

Determine if a Sudoku is valid. The following one, for example, is valid:

enter image description here

One of the highly upvoted solutions uses a formula (taking advantage of integer division):

k = i / 3 * 3 + j / 3;

Now, this formula essentially maps a 3x3 matrix into a unique number such that this new 1 digit number can be used to refer to this particular grid (useful to represent it as an element of an array). For example:

The following represents the 'mapping' of the 9x9 into a 3x3 grid (I have also marked those in the image above):

0 | 1 | 2
3 | 4 | 5
6 | 7 | 8

Suppose, i=5 and j=6, (bottom-left index of the central grid on the right), then k (taking advantage of integer division):

k = 5 / 3 * 3 + 6 / 3 = 1 * 3 + 2 = 5

Where does this formula come from?

1

There are 1 best solutions below

4
On BEST ANSWER

This formula is for a function which is a composition of two functions:

$$(i,j)\mapsto(i/3,j/3)$$

(where the symbol '$/$' denotes integral division) and:

$$(i,j)\mapsto 3i+j$$

which maps pairs $(0,0),(0,1),(0,2),(1,0),\ldots,(2,2)$ to $0,1,2,\ldots,9$, respectively.

The first map converts the co-ordinates of a square in Sudoku to the co-ordinates of its containing $3\times 3$ square in the $3\times 3$ grid of the $3\times 3$ squares.

In your example, it maps $(5,6)\mapsto(1,2)$ because the little $1\times 1$ square at position $(5,6)$ is in the $3\times 3$ square which is in the $1$st row, $2$nd column among all $3\times 3$ squares (right middle-row $3\times 3$ square). Note all indexes are $0$-based.

The second map then maps that into the index $0-9$ of the $3\times 3$ square.

In your example $(1,2)\mapsto 5$, which is the index of the right middle-row square using the convention that you already have mentioned in your question.