修改if和else替换

时间:2016-06-06 02:50:20

标签: prolog

我有一个它的大小(N,M)的网格,我的目标是找到同一行和列中的第一个单元格 例如:如果我在电路板中间有一个电池,那么它周围将有四个电池,垂直和垂直

首先尝试

neighbor(X,Y,L):- Y1 is Y-1,Y2 is Y+1,X1 is X-1,X2 is X+1, % Assign values of the neighbors cells
in_grid(X,Y1),append([],[(X,Y1)],L1),%check and add to the list
in_grid(X,Y2),append(L1,[(X,Y2)],L2),
in_grid(X1,Y),append(L2,[(X1,Y)],L3),
in_grid(X2,Y),append(L3,[(X2,Y)],L).

这就是我定义 in_grid 谓词

的方式
in_grid(X,Y):-size(N,M),between(1,N,X),between(1,M,Y).

PS:大小(N,M)是动态的

这个代码在中间的单元格中工作正常,但在其他单元格中它给我False

另一次尝试

neighbor1(X,Y,L):- Y1 is Y-1,Y2 is Y+1,X1 is X-1,X2 is X+1, % Assign values of the neighbors cells
% it should works for grid's size(3,3)
((Y1=<0)->append([],[],L1),append([(X,Y1)],[],L1)), % check and add to the list
((Y2>=4)->append([],L1,L2),append([(X,Y2)],L1,L2)),
((X1=<0)->append([],L2,L3),append([(X1,Y)],L2,L3)),
((X2>=4)->append([],L3,L),append([(X2,Y)],L3,L)).

它也给了我假,我不知道为什么.. 我正在使用 SWI-Prolog 7.3.19

任何帮助

1 个答案:

答案 0 :(得分:0)

我认为你可以保持简单:假设大小(N,M)N是行数,M列数:

% G: list of lists of values
% R: row index
% C: column index
% N: a neighbour of R,C
neighbor(G,R,C,N) :-
  cell(G,R+1,C,N) ; cell(G,R,C+1,N) ; cell(G,R-1,C,N) ; cell(G,R,C-1,N).

cell(G,R,C,N) :- Y is R, X is C, nth1(X,G,Row), nth1(Y,Row,N).

编辑示例:

?- neighbor([[a,b,c],[d,e,f],[g,h,i]],2,2,N).
N = f ;
N = h ;
N = d ;
N = b.
相关问题