数独谜题

来自 PostgreSQL 维基
跳转到导航跳转到搜索

趣味代码片段

数独谜题

适用于 PostgreSQL

8.4

编写语言

SQL

依赖


Marcin Mańk 在 pgsql-general 发布,基于 Anton Scheffer 的 Oracle 版本 版本

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;