Sudoku Board Prolog程序

时间:2018-11-12 14:52:38

标签: prolog

我有这段代码可以在输出文本文件中显示数独板的所有可能解决方案,但是我也想向控制台显示第一个可能的解决方案。我的程序挂起并且没有终止,因此我无法向控制台添加任何内容。任何帮助将不胜感激。

这是数独板的代码。

:- use_module(library(clpfd)). 


sudoku(Rows) :- 
    length(Rows, 9), 
    maplist(length_list(9), Rows), 
    append(Rows, Vs), 
    Vs ins 1..9, maplist(all_distinct, Rows), 
    transpose(Rows, Columns), 
    maplist(all_distinct, Columns), 
    Rows = [A,B,C,D,E,F,G,H,I], 
    blocks(A, B, C), blocks(D, E, F), blocks(G, H, I).

length_list(L, Ls) :- length(Ls, L). 

blocks([], [], []). 
blocks([A,B,C|Bs1], [D,E,F|Bs2], [G,H,I|Bs3]) :- 
    all_distinct([A,B,C,D,E,F,G,H,I]), blocks(Bs1, Bs2, Bs3). 

random_list([X1,X2,X3,X4,X5,X6,X7,X8,X9]) :-
    random_between(1,9,X1),
    random_between(1,9,X2),
    random_between(1,9,X3),
    random_between(1,9,X4),
    random_between(1,9,X5),
    random_between(1,9,X6),
    random_between(1,9,X7),
    random_between(1,9,X8),
    random_between(1,9,X9).

random_list_norep(A) :-
    repeat,
    random_list(A),
    all_distinct(A).


sudokugen(A,B,C, D,E,F, G,H,I) :- 
    random_list_norep([R1,R2,R3,R4,R5,R6,R7,R8,R9]),
    sudoku([[R1|A], [R2|B], [R3|C],     
            [R4|D], [R5|E], [R6|F], 
            [R7|G], [R8|H], [R9|I]]),
    labeling([], A),
    labeling([], B),
    labeling([], C),
    labeling([], D),
    labeling([], E),
    labeling([], F),
    labeling([], G),
    labeling([], H),
    labeling([], I).

rand_list_print([X]) :-
    random_between(0,9,A),
    (   A == 0 ->  print(X), write("]") ; write("_]")).
rand_list_print([X|Xs]) :-
    random_between(0,3,A),
    (   A == 0 ->  print(X), write(", ") ; write("_, ")),
    rand_list_print(Xs).

rand_printall(A,B,C) :-
    write("["), rand_list_print(A), write(", "),
    write("["), rand_list_print(B), write(", "),
    write("["), rand_list_print(C), nl.


sudoku1() :-
    tell('sudoku-sol.txt'),
    (
        sudokugen(A,B,C,D,E,F,G,H,I),
        print(A), write(", "), print(B), write(", "), print(C), nl,
        print(D), write(", "), print(E), write(", "), print(F), nl,
        print(G), write(", "), print(H), write(", "), print(I), nl,
        nl,
        rand_printall(A,B,C),
        rand_printall(D,E,F),
        rand_printall(G,H,I),
        fail
    ;
        told
    ).

0 个答案:

没有答案