所以我试图使用prolog
使用深度优先搜索方法来解决以下问题考虑以下问题:Rowena有三个没有标记的眼镜 不同尺寸:3盎司,5盎司和8盎司。最大的 玻璃满了。 Rowena可以做些什么来获得4盎司的液体 每个较大的两个眼镜?
我做了移动状态和一切,我使用了在线发现的深度优先搜索版本,到目前为止这里是代码
%stack
empty_stack([]).
member_stack(E, S) :- member(E, S).
stack(E, S, [E|S]).
go(Start, Goal) :-
empty_stack(Empty_been_list),
stack(Start, Empty_been_list, Been_list),
path(Start, Goal, Been_list).
% path implements a depth first search in PROLOG
% Current state = goal, print out been list
path(Goal, Goal, Been_list) :-
reverse_print_stack(Been_list).
path(State, Goal, Been_list) :-
move(State, Next),
\+ (member_stack(Next, Been_list)),
stack(Next, Been_list, New_been_list),
path(Next, Goal, New_been_list), !.
reverse_print_stack(S) :-
empty_stack(S).
reverse_print_stack(S) :-
stack(E, Rest, S),
reverse_print_stack(Rest),
write(E), nl.
%move rule #1: Pour Large into Medium (L--> M)
%move(oldstate,newstate)
move([L, M, S], [NewLarge,NewMedium,S]) :-
L > 0, %We can't pour from large if Large is empty
M < 5, %We can't pour into the medium if medium is full
Diff is min(5 - M, L),
Diff > 0,
NewLarge is L - Diff, %calculate the new Large
NewMedium is M + Diff. %calculate the new Medium
% move rule #2: Pour Large into Small (L--> S)
move([L, M, S], [NewLarge,M,NewSmall]) :-
L > 0, %We can't pour from large if Large is empty
S < 3, %We can't pour into the small if small is full
Diff is min(5 - S, L),
Diff > 0,
NewLarge is L - Diff, %calculate the new Large
NewSmall is S + Diff. %calculate the new Small
% move rule #3: Pour Medium into Large (M--> L)
move([L, M, S], [NewLarge,NewMedium,S]) :-
L < 8, %We can't pour into the large if the large is full
M > 0, %We can't pour from Medium if medium is empty
Diff is min(8 - L, M),
Diff > 0,
NewMedium is M - Diff, %calculate the new Medium
NewLarge is L + Diff. %calculate the new Large
% move rule #4: Pour Medium into small (M--> S)
move([L, M, S], [L, NewMedium,NewSmall]) :-
M > 0, %We can't pour from Medium if Medium is empty
S < 3, %We can't pour into the small if small is full
Diff is min(5 - S, M),
Diff > 0,
NewMedium is M - Diff, %calculate the new Medium
NewSmall is S + Diff. %calculate the new Small
% move rule #5: Pour small into large (S--> L)
move([L, M, S], [NewLarge,M,NewSmall]) :-
L < 8, %We can't pour into the large if the large is full
S > 0, %We can't pour from Small if Small is empty
Diff is min(8 - L, S),
Diff > 0,
NewSmall is S - Diff, %calculate the new Small
NewLarge is L + Diff. %calculate the new Large
% move rule #6: Pour small into medium (S --> M)
move([L, M, S], [L,NewMedium,NewSmall]) :-
M < 5, %We can't pour into the large if the large is full
S > 0, %We can't pour from Medium if medium is empty
Diff is min(8 - M, S),
Diff > 0,
NewSmall is S - Diff, %calculate the new Small
NewMedium is M + Diff. %calculate the new Medium
现在它编译和翻转但是每当我尝试执行go([8,0,0],[4,4,0])
[8,0,0]
是初始状态而[4,4,0]
是我的目标状态时,我得到的答案是否定的!而不是深度优先搜索解决方案,它打印每个州......等等。
我试图跟踪它,它告诉我马上有一个例外。有办法解决这个问题吗?