pr-2中的水壶

时间:2013-11-01 12:05:16

标签: prolog infinite-loop non-termination water-jug-problem

我正在尝试解决swi-prolog中的2水壶问题:鉴于2个容器分别为4加仑和3加仑,我想找到在容器中获得2加仑容量4和0的步骤其他

我使用bfs和dfs:http://kartikkukreja.wordpress.com/2013/10/11/water-jug-problem/在C ++中编写了这个问题的程序。现在,我正试图解决prolog中的问题。我是语言的新手,我的代码不会终止。

这是我到目前为止的代码:

% state(0, 0) is the initial state
% state(2, 0) is the goal state
% Jugs 1 and 2 have capacities 4 and 3 respectively
% P is a path to the goal state
% C is the list of visited states

solution(P) :-
    path(0, 0, [state(0, 0)], P).

path(2, 0, [state(2, 0)|_], _).

path(0, 2, C, P) :-
not(member(state(2, 0), C)),
path(2, 0, [state(2, 0)|C], R),
P = ['Pour 2 gallons from 3-Gallon jug to 4-gallon.'|R].

path(X, Y, C, P) :-
X < 4,
not(member(state(4, Y), C)),
path(4, Y, [state(4, Y)|C], R),
P = ['Fill the 4-Gallon Jug.'|R].

path(X, Y, C, P) :-
Y < 3,
not(member(state(X, 3), C)),
path(X, 3, [state(X, 3)|C], R),
P = ['Fill the 3-Gallon Jug.'|R].

path(X, Y, C, P) :-
X > 0,
not(member(state(0, Y), C)),
path(0, Y, [state(0, Y)|C], R),
P = ['Empty the 4-Gallon jug on ground.'|R].

path(X, Y, C, P) :-
Y > 0,
not(member(state(X, 0), C)),
path(X, 0, [state(X, 0)|C], R),
P = ['Empty the 3-Gallon jug on ground.'|R].

path(X, Y, C, P) :-
X + Y >= 4,
X < 4,
Y > 0,
NEW_Y = Y - (4 - X),
not(member(state(4, NEW_Y), C)),
path(4, NEW_Y, [state(4, NEW_Y)|C], R),
P = ['Pour water from 3-Gallon jug to 4-gallon until it is full.'|R].

path(X, Y, C, P) :-
X + Y >=3,
X > 0,
Y < 3,
NEW_X = X - (3 - Y),
not(member(state(NEW_X, 3), C)),
path(NEW_X, 3, [state(NEW_X, 3)|C], R),
P = ['Pour water from 4-Gallon jug to 3-gallon until it is full.'|R].

path(X, Y, C, P) :-
X + Y =< 4,
Y > 0,
NEW_X = X + Y,
not(member(state(NEW_X, 0), C)),
path(NEW_X, 0, [state(NEW_X, 0)|C], R),
P = ['Pour all the water from 3-Gallon jug to 4-gallon.'|R].

path(X, Y, C, P) :-
X + Y =< 3,
X > 0,
NEW_Y = X + Y,
not(member(state(0, NEW_Y), C)),
path(0, NEW_Y, [state(0, NEW_Y)|C], R),
P = ['Pour all the water from 4-Gallon jug to 3-gallon.'|R].

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

Prolog 中的“equal”运算符不执行算术运算,但统一其两个参数。 尝试(例如)替换此

NEW_Y = Y - (4 - X)

NEW_Y is Y - (4 - X)
OT:与任何其他语言一样,Prolog也受益于代码分解:大多数路径/ 4规则暴露相同的模式,因此代码可以使用帮助器谓词更加干净:再次,对于实例

path(0, 2, C, P) :-
  not(member(state(2, 0), C)),
  path(2, 0, [state(2, 0)|C], R),
  P = ['Pour 2 gallons from 3-Gallon jug to 4-gallon.'|R].

可能是

path(0, 2, C, ['Pour 2 gallons from 3-Gallon jug to 4-gallon.'|R]) :-
  upd_path(2, 0, C, R).

给定的

upd_path(X, Y, C, R).
      not(member(state(X, Y), C)),
      path(X, Y, [state(X, Y)|C], R).

编辑:另一个OT提示:使用memberchk / 2而不是member / 2。它更有效,可以更容易跟踪执行,具有确定性。

编辑此外,递归的基本情况不会关闭描述列表:尝试

path(2, 0, [state(2, 0)|_], []).