Hanoi Tower(Towers of Hanoi)

十年热恋 提交于 2020-01-20 06:59:08

问题


I'm trying to do the Towers of Hanoi problem, what I have tried so far:

move(1,[H|T],B,C,A1,B1,C) :-  
  A1 = T,
  B1 = [H|B].
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).

but this code does not work, I need get the result is looks like this:

?-move(3,[1,2,3],[],[],A1,B1,C).
  and the results:
  A1=[].
  B1=[1,2,3]
  C=[].

can someone help me fix my code up and can get the result like that? This is very important for me, I really need help. this is what i did but with some problems:

move(N,[H|T],[],[],A1,B1,C) :-
      N > 1,
      M is N - 1,   
      move(N,[H|M],[H|_],[],A1,B1,C),
      move(M,[_|M],[H|_],[H|_],A1,B1,C),
      move(M,[_|M],[],[H|T],A1,B1,C),
      move(M,[],[_|T],[H|T],A1,B1,C),
      move(M,[H|_],[_|T],[H|T],A1,B1,C),
      move(M,[H|_],[_|T],[],A1,B1,C),
      move(M,[],[H|T],[],A1,B1,C).
      move(N,[H|T],[],[]) :- write(A1), nl,
                             write(B1), nl,
                             write(C).

回答1:


This is the instruction by instruction of solving towers of Hanoi problem.

   move(1,X,Y,_) :-  
        write('Move top disk from '), 
        write(X), 
        write(' to '), 
        write(Y), 
        nl. 
    move(N,X,Y,Z) :- 
        N>1, 
        M is N-1, 
        move(M,X,Z,Y), 
        move(1,X,Y,_), 
        move(M,Z,Y,X).

Attack the problem in such a way: In the instruction by instruction solution we don't change the contents of X,Y or Z. But in your problem, you will eventually change the contents of them.

UPDATE: Since it is declared that this is not a homework question, here is the full answer:

towersOfHanoi(N,A,B,C,A4,B4,C4) :- move(N,A,B,C,A4,B4,C4),!.

move(1,[H|T],B,C,A1,B1,C1) :-  A1 = T,
                               B1 = [H|B],
                               C1 = C.
move(N,A,B,C,A4,B4,C4) :-   N>1, 
                            M is N-1, 
                            move(M,A,C,B,A1,C1,B1), 
                            move(1,A1,B1,C1,A2,B2,C2), 
                            move(M,C2,B2,A2,C4,B4,A4).


来源:https://stackoverflow.com/questions/10762824/hanoi-towertowers-of-hanoi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!