トップページに戻る    次のSQLServerのサンプルへ    前のSQLServerのサンプルへ

2-2 数独を解く

SQLパズル

数独を解きます。


SQL

with rec(LV,Val) as(
select 1,
cast('080701050'
   + '002040900'
   + '930000074'
   + '800104006'
   + '006000100'
   + '700903008'
   + '240000015'
   + '007050300'
   + '050807040' as char(81))
union all
select LV+1,
cast(case when subString(Val,LV,1) = '0'
          then Stuff(Val,LV,1,cast(cnt as char(1)))
          else Val end as char(81))
from rec,(select 1 as cnt union all select 2 union all
          select 3        union all select 4 union all
          select 5        union all select 6 union all
          select 7        union all select 8 union all
          select 9) b
where LV <= 81
  and (subString(Val,LV,1) = '0' or cnt=1)
  and (subString(Val,LV,1) !='0'
    or (CharIndex(cast(cnt as char(1)),subString(Val,(LV-1)/9*9+1,9))  = 0 /*横チェック*/
    and CharIndex(cast(cnt as char(1)),subString(Val,(LV-1)%9+1   ,1)) = 0 /*縦チェック*/
    and CharIndex(cast(cnt as char(1)),subString(Val,(LV-1)%9+1+ 9,1)) = 0
    and CharIndex(cast(cnt as char(1)),subString(Val,(LV-1)%9+1+18,1)) = 0
    and CharIndex(cast(cnt as char(1)),subString(Val,(LV-1)%9+1+27,1)) = 0
    and CharIndex(cast(cnt as char(1)),subString(Val,(LV-1)%9+1+36,1)) = 0
    and CharIndex(cast(cnt as char(1)),subString(Val,(LV-1)%9+1+45,1)) = 0
    and CharIndex(cast(cnt as char(1)),subString(Val,(LV-1)%9+1+54,1)) = 0
    and CharIndex(cast(cnt as char(1)),subString(Val,(LV-1)%9+1+63,1)) = 0
    and CharIndex(cast(cnt as char(1)),subString(Val,(LV-1)%9+1+72,1)) = 0
    /*正方形チェック*/
    and CharIndex(cast(cnt as char(1)),subString(Val,((LV-1)%9)/3*3+1+9*((LV-1)/9/3*3)   ,3))=0
    and CharIndex(cast(cnt as char(1)),subString(Val,((LV-1)%9)/3*3+1+9*((LV-1)/9/3*3)+ 9,3))=0
    and CharIndex(cast(cnt as char(1)),subString(Val,((LV-1)%9)/3*3+1+9*((LV-1)/9/3*3)+18,3))=0)))
select Val from rec
where LV = 82
go


解説

手続き型言語を使ったほうが楽そうですねぇ
C#のサンプル集 8-8 数独
Javaアルゴリズムパズル 3-7 数独
DB2 SQLパズル 再帰with句10 数独を解く
PostgreSQLパズル 再帰with句10 数独を解く

実行結果
Val
---------------------------------------------------------------------------------
684791253572348961931526874823174596496285137715963428248639715167452389359817642