-6

对于河内塔,输出应如下所示:

 ?-move(3,[1,2,3],[],[],A1,B1,C).

 A1=[].
 B1=[1,2,3]
 C=[].

我知道该怎么做:

move(1,[H|T],B,C,A1,B1,C) :-  
                       A1 = T,
                       B1 = [H|B],
                       C1 = C.  
move(N,A,B,C,A1,B1,C) :- 
                       N>1, 
                       M is N-1, 
                       move(M,[H|T],C,B,A1,B1,C), 
                       move(1,[H|T],B,_,A1,B1,C), 
                       move(M,C,B,[H|T],A1,B1,C).

但下一个问题是:“重写程序以在每次移动后提供塔的插图”。它的输出应该是这样的:

?- move(3,tower(a,[1,2,3]),tower(b,[]),tower(c,[]),A,B,C).
   a[2 3] b[1] C[]
   a[3] b[1] C[2]
   a[3] b[] C[1 2]
   a[] b[3] C[1 2]
   a[1] b[3] C[2]
   a[1] b[2 3] C[]
   a[] b[1 2 3] C[]
   A = tower(a, [])
   B = tower(b,[1, 2, 3])
   C = tower(c,[])

如何才能做到这一点?

4

1 回答 1

1

您可以使用以下谓词打印空格分隔的列表:

write_list_([]) :- write(']').
write_list_([X|Xs]) :- write(' '), write(X), write_list_(Xs).

write_list([]) :- write('[]').
write_list([X|Xs]) :- write('['), write(X), write_list_(Xs).
于 2012-05-26T08:26:50.037 回答