Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

prolog - Hanoi Tower(Towers of Hanoi)

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).
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...