我嘗試在swi-prolog中編寫一個二進制數獨求解器。 (二進制數獨解釋爲here)prolog數獨求解器耗盡全局堆棧
問題是我現在用完了全局堆棧。我給它2 GB應該是綽綽有餘。我是否使用有缺陷的算法?有沒有什麼我可以做得更好,以避免遇到這樣的小拼圖缺乏全球堆棧錯誤?
更多信息:我已經在4X4拼圖上用完了,第一個約束只應用了6^4種可能性。 你可以查詢這個問題:
problems(2,Field),binary_sudoku(Field).
代碼在這裏:
:-use_module(library(clpfd)).
valid_row(Row) :-
Row ins 0..1,
length(Row,L),
sum(Row,#=,L/2).
matrixNth1(Matr,X,Y,El) :-
nth1(Y,Matr,CurRow),
nth1(X,CurRow,El).
all_diff([]).
all_diff([X|Y]) :-
maplist(dif(X),Y),
all_diff(Y).
valid(_,1,1).
valid(Rows,1,Y) :-
length(Rows,Y).
valid(Rows,X,1) :-
length(Rows,X).
valid(Rows,X,X) :-
length(Rows,X).
valid(Rows,X,Y) :-
matrixNth1(Rows,X,Y,0).
valid(Rows,X,Y):-
AboveY is Y-1,
matrixNth1(Rows,X,AboveY,0).
valid(Rows,X,Y):-
BelowY is Y+1,
matrixNth1(Rows,X,BelowY,0).
valid(Rows,X,Y):-
LeftX is X-1,
matrixNth1(Rows,LeftX,Y,0).
valid(Rows,X,Y):-
RightX is X+1,
matrixNth1(Rows,RightX,Y,0).
binary_sudoku(Rows) :-
length(Rows,Height),
transpose(Rows,Cols),
length(Cols,Height),
maplist(valid_row,Rows),
foreach(between(1,Height,X),foreach(between(1,Height,Y),valid(Rows,X,Y))),
all_diff(Rows),all_diff(Cols).
problems(1,[[_,_],[_,_]]).
problems(2,[[_,_,_,_],[_,_,_,_],[_,_,_,_],[_,_,_,_]]).
你是如何查詢的解決方案嗎?你爲什麼定義自己的'all_diff'而不是使用'all_different/1'或'all_distinct/1'已經可用?爲什麼你不提前設置「全部不同」限制? – 2013-12-10 06:03:03
我應該補充說,這是我在序言中第一次做的,對我來說,所有對我來說似乎都很笨重/神奇...... all_distinct沒有工作,因爲它限制整數不同,而我想要列表整數是不同的。 無論如何,all_diff在這裏並不是問題,對於非唯一行/列的解決方案非常少。就我所知,它對我的雙foreach循環有一個問題。 – camel
那麼你在2x2電路板上有解決方案嗎?你如何查詢獲得它? – 2013-12-10 09:41:38