河内塔(河内塔) [英] 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).
推荐答案
这是解决河内问题之塔的逐条说明.
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).
以以下方式解决问题:在逐条指令解决方案中,我们不会更改X,Y或Z的内容.但是在您遇到的问题中,最终您将更改它们的内容.
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).
这篇关于河内塔(河内塔)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!