Sudoku puzzle

From PostgreSQL wiki
Jump to navigationJump to search

Fun Snippets

Sudoku puzzle

Works with PostgreSQL

8.4

Written in

SQL

Depends on

Nothing


Published by Marcin Mańk in pgsql-general, based on an Oracle version by Anton Scheffer

WITH RECURSIVE x( s, ind ) AS
( SELECT sud, position( ' ' IN sud )
  FROM  (SELECT '53  7    6  195    98    6 8   6   34  8 3  17   2   6 6    28    419  5    8  79'::text 
             AS sud) xx
  UNION ALL
  SELECT substr( s, 1, ind - 1 ) || z || substr( s, ind + 1 )
       , position(' ' in repeat('x',ind) || substr( s, ind + 1 ) )
  FROM x
     ,  (SELECT gs::text AS z FROM generate_series(1,9) gs) z
  WHERE ind > 0
  AND NOT EXISTS ( SELECT null
                   FROM generate_series(1,9) lp
                   WHERE z.z = substr( s, ( (ind - 1 ) / 9 ) * 9 + lp, 1 )
                   OR    z.z = substr( s, mod( ind - 1, 9 ) - 8 + lp * 9, 1 )
                   OR    z.z = substr( s, mod( ( ( ind - 1 ) / 3 ), 3 ) * 3
                                      + ( ( ind - 1 ) / 27 ) * 27 + lp
                                      + ( ( lp - 1 ) / 3 ) * 6
                                   , 1 )
                 )
)
SELECT s
FROM x
WHERE ind = 0;