0

我正在尝试解决 swi-prolog 中的 2 水罐问题:给定 2 个容量分别为 4 和 3 加仑的水罐,我想找到在容量为 4 的水罐中获得 2 加仑的水罐和另一个容量为 0 的水罐的步骤。

我使用 bfs 和 dfs 在 C++ 中为这个问题编写了程序:http: //kartikkukreja.wordpress.com/2013/10/11/water-jug-problem/。现在,我正在尝试解决 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].

任何帮助表示赞赏。

4

1 回答 1

0

Prolog 中的“等于”运算符执行算术运算,而是统一了它的两个参数。尝试(例如)替换这个

NEW_Y = Y - (4 - X)

NEW_Y is Y - (4 - X)

OT:Prolog 也像任何其他语言一样受益于代码分解:大多数path/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)|_], []).
于 2013-11-01T14:29:04.623 回答