Sudoku fun:
9 x 9 sudoku in sql solver
with solved_sudoku( sudoku, empty_cell_position ) as
(select sudoku, instr( sudoku, ‘ ‘ )
from ( select ‘ 3 7 6 1 98 6 8 6 34 8 3 17 2 6 6 28 419 5 8 79’ sudoku from dual )
union all
select substr( sudoku, 1, empty_cell_position – 1 ) || empty_cell || substr( sudoku, empty_cell_position + 1 )
, instr( sudoku, ‘ ‘, empty_cell_position + 1 ) from solved_sudoku,
( select to_char( rownum ) empty_cell from dual connect by rownum 0
and not exists ( select null from ( select rownum step from dual connect by rownum <= 9)
where empty_cell = substr( sudoku, trunc( ( empty_cell_position – 1 ) / 9 ) * 9 + step, 1 )
/* 1. Find out the non-existence of figure 1 – 9 for the empty_cell horizontally,
empty_cell_position (n) = 1 to 81 (9 x 9), step (m) = 1 to 9,
formula of position (p) = trunc((n-1)/9)*9+m
when n, m = 1, p = 1
when n = 2, m = 1, p = 1
when n, m = 2, p = 2
when n = 2, m = 3, p = 3
when n, m = 3, p = 3
when n = 8, m = 8, p = 8
when n = 9, m = 9, p = 9
when n = 81, m = 1, p = 73
when n = 81, m = 2, p = 74
.
.
.
when n = 81, m = 9, p = 81 */
or empty_cell = substr( sudoku, mod( empty_cell_position – 1, 9 ) – 8 + step * 9, 1 )
/* 2. Find out the non-existence of figure 1 – 9 for the empty_cell vertically,
empty_cell_position (n) = 1 to 81 (9 x 9), step (m) = 1 to 9,
formula of position (p) = mod( n – 1, 9 ) – 8 + m * 9
when n, m = 1, p = 1
when n = 2, m = 1, p = 1
when n, m = 2, p = 11
when n = 2, m = 3, p = 20
when n, m = 3, p = 21
when n = 8, m = 8, p = 71
when n = 9, m = 9, p = 81
when n = 81, m = 1, p = 9
when n = 81, m = 2, p = 18
.
.
.
when n = 81, m = 9, p = 81 */
or empty_cell = substr( sudoku, mod( trunc( ( empty_cell_position – 1 ) / 3 ), 3 ) * 3
+ trunc( ( empty_cell_position – 1 ) / 27 ) * 27 + step
+ trunc( ( step – 1 ) / 3 ) * 6, 1 )))
/* 3. Find out the non-existence of figure 1 – 9 for the empty_cell within the 3 x 3 block,
empty_cell_position (n) = 1 to 81 (9 x 9), step (m) = 1 to 9,
formula of position (p) = mod( n – 1, 9 ) – 8 + m * 9
when n, m = 1, p = 1
when n = 2, m = 1, p = 1
when n, m = 2, p = 2
when n = 2, m = 3, p = 3
when n, m = 3, p = 3
when n = 8, m = 8, p = 26
when n = 9, m = 9, p = 27
when n = 81, m = 1, p = 61
when n = 81, m = 2, p = 62
.
.
.
when n = 81, m = 9, p = 81 */
select sudoku from solved_sudoku where empty_cell_position = 0
code works. Keep updating Cognos TM1 online training Bangalore
It's so nice article thank you for sharing a valuable content. Power BI Online Training