我做了这个hanoi算法,现在我想增加每次迭代并打印它。有人可以帮忙吗?谢谢!
以下是我的尝试:
increase(X,Y):-Y is X+1.
hanoi(N):-move(N,left,middle,right,0).
move(0,_,_,_,_):-!.
move(N,A,B,C,NUM):- M is N-1,increase(NUM,NUM1),
move(M,A,C,B,NUM1),
print(A,B,NUM1),
increase(NUM1,NUM2),
move(M,C,B,A,NUM2).
print(A,B,M):- write(M),
write(': MOVE DISK FROM '),
write(A),
write(' TO '),
write(B),nl.
我希望它看起来像这样,每个例子:
?-hanoi(2).
1: MOVE DISK FROM left TO right
2: MOVE DISK FROM left TO middle
3: MOVE DISK FROM right TO middle
但数字显示的顺序错误:
?- hanoi(2).
2: MOVE DISK FROM left TO right
1: MOVE DISK FROM left TO middle
3: MOVE DISK FROM right TO middle
true.
答案 0 :(得分:2)
:-op(900,xfx,'TO').
% hanoi(N,A,B,C,Moves) <- Moves is the list of moves to
% move N disks from peg A to peg C,
% using peg B as intermediary peg
hanoi(0,A,B,C,[]).
hanoi(N,A,B,C,Moves):-
N1 is N-1,
hanoi(N1,A,C,B,Moves1),
hanoi(N1,B,A,C,Moves2),
append(Moves1,[A 'TO' C|Moves2],Moves).
print_hanoi(Size):-
hanoi(Size,left,middle,right,Moves),
length(Moves,L),
numlist(1,L,Is),
maplist(print_row,Is,Moves).
print_row(I,M):-
format("~w. MOVE DISK FROM ~w\n",[I,M]).
查询:
?- print_hanoi(3).
1. MOVE DISK FROM left TO right
2. MOVE DISK FROM left TO middle
3. MOVE DISK FROM right TO middle
4. MOVE DISK FROM left TO right
5. MOVE DISK FROM middle TO left
6. MOVE DISK FROM middle TO right
7. MOVE DISK FROM left TO right