Home > OS >  How to index a 3x3 subblock of a 9x9 Sudoku board
How to index a 3x3 subblock of a 9x9 Sudoku board

Time:01-09

I'm working on a Sudoku solver (for a Leet problem) and I'm able to manipulate the 9 x 9 array of numbers in terms of rows and columns pretty easily using basic indexing, e.g., board[row,:] or board[:,col]. Each of these slices a 1D array from the 2D array.

I'd like to do the equivalent for the 3 x 3 subblocks of a Sudoku board, in the following sense. I'd like to define a Python function iBlock that takes as argument the block row and block column numbers, and returns something such that board[something] addresses the 9 elements of a subblock such that board[something] could be used as follows:

board[something] = [ 3, 7, 2, 1, 4, 5, 9, 8, 6 ]

would have the effect of transforming the full 9 x 9 board from

. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . - - - . . .
. . . - - - . . .
. . . - - - . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .

to:

. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . 3 7 2 . . .
. . . 1 4 5 . . .
. . . 9 8 6 . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .

and I'd like to be able to use board[something] on the rhs of an assignment as well.

So the question is... what is something so that things would work as above?

CodePudding user response:

Hopfully this information helps. I would use numpy and slicing.

Here is a small example that hopefully produces your desired results:

import numpy as np

mat = np.zeros((9,9))
start = 3
end = 6
mat[start:end,start:end] = np.array([ 3, 7, 2, 1, 4, 5, 9, 8, 6 ]).reshape((3,3))

print(mat)
[[0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 3. 7. 2. 0. 0. 0.]
 [0. 0. 0. 1. 4. 5. 0. 0. 0.]
 [0. 0. 0. 9. 8. 6. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]]

CodePudding user response:

Noodling around, I think I found the solution:

def iBlock( R, C ):
    return ( [3*R,3*R,3*R,3*R 1,3*R 1,3*R 1,3*R 2,3*R 2,3*R 2],
             [3*C,3*C 1,3*C 2,3*C,3*C 1,3*C 2,3*C,3*C 1,3*C 2] )
iBlock(1,2)
=> ([3, 3, 3, 4, 4, 4, 5, 5, 5], [6, 7, 8, 6, 7, 8, 6, 7, 8])

a = np.zeros((9,9))
a[ iBlock(1,2) ] = range(1,10)

a =>
array([[0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 1., 2., 3.],
       [0., 0., 0., 0., 0., 0., 4., 5., 6.],
       [0., 0., 0., 0., 0., 0., 7., 8., 9.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0.]])
  •  Tags:  
  • Related