prolog - SWI-Prolog 中的水壶拼图

标签 prolog water-jug-problem

我是 AI 和 Prolog 新手。我试图在 SWI Prolog 中实现 2 个水壶问题。但是,我的解决方案是返回全局堆栈溢出

我知道这个问题过去已经被问过,并且有很多答案/解决方案,作为一个完全的新手,我的方法有点天真,因此我想知道我做错了什么。

问题:

有两个水壶,一个容量为 4 加仑,另一个容量可达 3 加仑。我需要 4 加仑水壶中的 2 加仑,另一个应该是空的。

代码如下:

member(X, [X|R]).
member(X, [Y|R]) :- member(X,R).

append([X|Y], Z, [X|W]) :- append(Y,Z,W).
append([], X, X).

/*                                                                                                                                            
production rules for the water jug problem                                                                                                    
*/
maneuver(X, Y, Z):-X=:=2, Y=:=0, write('done').
maneuver(X, Y, Z):-X<4, \+ member(Z, (4,Y)), append(Z, [(4,Y)], A), write('Fill 4 gallon jug\n'), maneuver(4,Y,A).
maneuver(X, Y, Z):-Y<3, \+ member(Z, (X,3)), append(Z, [(X,3)], A), write('Fill 3 gallon jug\b'), maneuver(X,3,A).
maneuver(X, Y, Z):-X>0, \+ member(Z, (0,Y)), append(Z, [(0,Y)], A), write('Empty the 4 gallon jug\n'), maneuver(0,Y,A).
maneuver(X, Y, Z):-Y>0, \+ member(Z, (X,0)), append(Z, [(X,0)], A), write('Empty the 3 gallon jug\n'), maneuver(X,0,A).
maneuver(X, Y, Z):-X+Y>=4, Y>0, \+ member(Z, (4,Y-(4-X))), append(Z, [(4,Y-(4-X))], A), write('Pour from 3 gallon jug to 4 gallon jug\n'), ma$
maneuver(X, Y, Z):-X+Y>=3, X>0, \+ member(Z, (X-(3-Y),3)), append(Z, [(X-(3-Y),3)], A), write('Pour from 4 gallon jug to 3 gallon jug\n'), ma$
maneuver(X, Y, Z):-X+Y=<4, Y>0, \+ member(Z, (X+Y, 0)), append(Z, [(X+Y, 0)], A), write('Pour the water in the 3 gallon jug into the 4 gallon$
maneuver(X, Y, Z):-X+Y=<4, Y>0, \+ member(Z, (0, X+Y)), append(Z, [(0, X+Y)], A), write('Pour the water in the 4 gallon jug into the 3 gallon$

这是输出。

Fill 4 gallon jug
Fill 3 gallon juEmpty the 4 gallon jug
Fill 4 gallon jug
Empty the 4 gallon jug
Fill 4 gallon jug
Empty the 4 gallon jug
Fill 4 gallon jug
Empty the 4 gallon jug
Fill 4 gallon jug
Empty the 4 gallon jug
Fill 4 gallon jug
Empty the 4 gallon jug
Fill 4 gallon jug
Empty the 4 gallon jug
...

最佳答案

在 Prolog 中,输出操作“描述”没有什么意义,因为任何失败的操作序列都将被撤消,从而尝试任何可用的替代方案。 然后我要采取的第一步是“装饰性的”:移开可以从解决方案的两个相邻步骤(列表 Z)推断出的描述,并添加一个解决方案参数来进行操作。

另一个重要的改进:您的所有步骤都重复相同的 - 错误 - 模式:例如

\+ member(Z, (4,Y)), append(Z, [(4,Y)], A)

制作一个“子例程”(并纠正错误,我认为这会导致循环):

update(State, Step, Updated) :-
   \+ member(Step, State),
   append(State, [Step], Updated).

关于prolog - SWI-Prolog 中的水壶拼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18040196/

相关文章:

database - Prolog 在单独的数据库文本文件上插入、修改和删除事实

prolog - 我用于解决 3 壶水难题的序言程序有什么问题?

prolog - 为什么 = := give an error when the variable is not instantiated, 可以但 == 不行?

prolog - 如何查找数据库中所有prolog规则

Prolog:将列表列表中每个元素的值加倍并返回一个列表

networking - Prolog 中的网络模块化优化