2016年5月9日月曜日

開発環境

7つの言語 7つの世界 (Bruce A. Tate (著)、まつもとゆきひろ (監訳)、田和 勝 (翻訳)、オーム社)の第4章(Prolog)、4.4(3日目: ラスベガスをぶっとばせ)、セルフスタディ3日目.(数独ソルバー)を取り組んでみる。

セルフスタディ3日目.(数独ソルバー)

コード(Emacs)

printRows([]).
printRows([Head|Tail]) :-
    print(Head),
    print('\n'),
    printRows(Tail).

valid([]).
valid([Head|Tail]) :-
    fd_all_different(Head),
    valid(Tail).

sudoku(Puzzle, Solution) :-
    Solution = Puzzle,
    Puzzle = [S11, S12, S13, S14, S15, S16,
              S21, S22, S23, S24, S25, S26,
              S31, S32, S33, S34, S35, S36,
              S41, S42, S43, S44, S45, S46,
              S51, S52, S53, S54, S55, S56,
              S61, S62, S63, S64, S65, S66],
    
    fd_domain(Solution, 1, 6),
    
    Row1 = [S11, S12, S13, S14, S15, S16],
    Row2 = [S21, S22, S23, S24, S25, S26],
    Row3 = [S31, S32, S33, S34, S35, S36],
    Row4 = [S41, S42, S43, S44, S45, S46],
    Row5 = [S51, S52, S53, S54, S55, S56],
    Row6 = [S61, S62, S63, S64, S65, S66],
    
    Col1 = [S11, S21, S31, S41, S51, S61],
    Col2 = [S12, S22, S32, S42, S52, S62],
    Col3 = [S13, S23, S33, S43, S53, S63],
    Col4 = [S14, S24, S34, S44, S54, S64],
    Col5 = [S15, S25, S35, S45, S55, S65],
    Col6 = [S16, S26, S36, S46, S56, S66],
    
    Block1 = [S11, S12, S21, S22, S31, S32],
    Block2 = [S13, S14, S23, S24, S33, S34],
    Block3 = [S15, S16, S25, S26, S35, S36],    
    Block4 = [S41, S42, S51, S52, S61, S62],
    Block5 = [S43, S44, S53, S54, S63, S64],
    Block6 = [S45, S46, S55, S56, S65, S66],
    
    valid([Row1, Row2, Row3, Row4, Row5, Row6,
           Col1, Col2, Col3, Col4, Col5, Col6,
           Block1, Block2, Block3, Block4, Block5, Block6]),
    printRows([Row1, Row2, Row3, Row4, Row5, Row6]).

入出力結果(Terminal)

GNU Prolog 1.4.4 (64 bits)
Compiled Feb  5 2016, 06:20:25 with /opt/local/bin/gcc-apple-4.2
By Daniel Diaz
Copyright (C) 1999-2013 Daniel Diaz
| ?- ['sudoku6x6.pl'].
compiling .../sudoku6x6.pl for byte code...
.../sudoku6x6.pl compiled, 47 lines read - 10157 bytes written, 24 ms

(6 ms) yes
| ?- sudoku([
1, 2, 3, 4, 5, 6,
3, 4, 5, 6, 1, 2,
5, 6, 1, 2, 3, 4,
2, 1, 4, 3, 6, 5,
4, 3, 6, 5, 2, 1,
_, _, _, _, _, _],
Solution).
[1,2,3,4,5,6]
[3,4,5,6,1,2]
[5,6,1,2,3,4]
[2,1,4,3,6,5]
[4,3,6,5,2,1]
[6,5,2,1,4,3]

Solution = [1,2,3,4,5,6,3,4,5,6,1,2,5,6,1,2,3,4,2,1,4,3,6,5,4,3,6,5,2,1,6,5,2,1,4,3]

yes
| ?- 


Process prolog finished

0 コメント:

コメントを投稿