代码之家  ›  专栏  ›  技术社区  ›  john

如何在prolog中为数独游戏设置列表中的值

  •  3
  • john  · 技术社区  · 7 年前

    :- use_rendering(sudoku).
    
    :- use_module(library(clpfd)).
    sudoku(Rows) :-
        length(Rows, 9), maplist(same_length(Rows), Rows),
        append(Rows, Vs), Vs ins 1..9,
        maplist(all_distinct, Rows),
        transpose(Rows, Columns),
        maplist(all_distinct, Columns),
        Rows = [As,Bs,Cs,Ds,Es,Fs,Gs,Hs,Is],
        blocks(As, Bs, Cs),
        blocks(Ds, Es, Fs),
        blocks(Gs, Hs, Is).
    
    blocks([], [], []).
    blocks([N1,N2,N3|Ns1], [N4,N5,N6|Ns2], [N7,N8,N9|Ns3]) :-
        all_distinct([N1,N2,N3,N4,N5,N6,N7,N8,N9]),
        blocks(Ns1, Ns2, Ns3).
    
    problem(1, [[_,_,_,_,_,_,_,_,_],
            [_,_,_,_,_,3,_,8,5],
            [_,_,1,_,2,_,_,_,_],
            [_,_,_,5,_,7,_,_,_],
            [_,_,4,_,_,_,1,_,_],
            [_,9,_,_,_,_,_,_,_],
            [5,_,_,_,_,_,_,7,3],
            [_,_,2,_,1,_,_,_,_],
            [_,_,_,_,4,_,_,_,9]]).
    
    
            %problem(1, Rows), sudoku(Rows), maplist(portray_clause, Rows).
    

    我想做一个新的主函数,它接收一个三元组列表作为输入,形式为[3,7,2],[5,1,9]…],因此 每个空间坐标轴对应于网格内已包含值的框。例如 值2和[5,1,9]表示第5行第1列中的框包含值9

    这是我个人的学习,谢谢

    1 回复  |  直到 7 年前
        1
  •  1
  •   Daniel Lyons Paulo Moura    7 年前

    我想你只需要这样一个谓词:

    board_value([R,C,V], Board) :-
        nth1(R, Board, Row),
        nth1(C, Row, V).
    

    这样使用:

    ?- Board = [[_,_,_,_,_,_,_,_,_],
                [_,_,_,_,_,3,_,8,5],
                [_,_,1,_,2,_,_,_,_],
                [_,_,_,5,_,7,_,_,_],
                [_,_,4,_,_,_,1,_,_],
                [_,9,_,_,_,_,_,_,_],
                [5,_,_,_,_,_,_,7,3],
                [_,_,2,_,1,_,_,_,_],
                [_,_,_,_,4,_,_,_,9]], 
       board_value([5,2,1], Board), 
       write(Board).
    
    [[_6,_8,_10,_12,_14,_16,_18,_20,_22],
     [_24,_26,_28,_30,_32,3,_34,8,5],
     [_36,_38,1,_40,2,_42,_44,_46,_48],
     [_50,_52,_54,5,_56,7,_58,_60,_62],
     [_64,1,4,_68,_70,_72,1,_74,_76],
     [_78,9,_80,_82,_84,_86,_88,_90,_92],
     [5,_94,_96,_98,_100,_102,_104,7,3],
     [_106,_108,2,_110,1,_112,_114,_116,_118],
     [_120,_122,_124,_126,4,_128,_130,_132,9]]
    Board = [[_6, _8, _10, _12, _14, _16, _18, _20|...], [_24, _26, _28, _30, _32, 3, _34|...], [_36, _38, 1, _40, 2, _42|...], [_50, _52, _54, 5, _56|...], [_64, 1, 4, _68|...], [_78, 9, _80|...], [5, _94|...], [_106|...], [...|...]].
    

    这可能不明显,但第5行的第2列现在是1。希望这有帮助!