Hanoi Towers (prologue)

everyone knows the famous prologue hanoi

and you can find it HERE

and its big, but when I write this query, move around (3, left, right, center).

does not show these results

Move top disk from left to right Move top disk from left to center Move top disk from right to center Move top disk from left to right Move top disk from center to left Move top disk from center to right Move top disk from left to right 

what i got

 Trace: >> RETURN: nl() Trace: >> RETURN: hanoi(1,left,right,center) Trace: >> RETURN: hanoi(2,center,right,left) Trace: >> RETURN: hanoi(3,left,right,center) True 1 Solution 

since I can let him print the results in the best possible way, and can I name the disks so that the program will name them to me, to show the results as the next "move drive A from left to right" "

Sorry if I ask a lot, but to god I love PROLOG.

+4
source share
2 answers

First of all, what prologue do you use to get these results? It looks like you have a debugger turned on or something like that. I highly recommend SWI-Prolog , which gives the correct results.

As for the name of the disks, yes you can do it. Consider something like this:

 move([Disc],X,Y,_) :- write('Move disk '), write(Disc), write(' from '), write(X), write(' to '), write(Y), nl. move([Bottom|Rest],Start,Swap,Goal) :- move(Rest,Start,Swap,Goal), move([Bottom],Start,Goal,_), move(Rest,Swap,Goal,Start). 

When you run move([biggest,middle,smallest], left, center, right). , you will get the following results:

 Move disk smallest from left to center Move disk middle from left to right Move disk smallest from center to right Move disk biggest from left to right Move disk smallest from center to right Move disk middle from center to left Move disk smallest from right to left 

The trick is that this is a bottom-up algorithm. Essentially it comes down to:

  • Move everything on top of the bottom drive to swap (which is a recursive step)
  • Move the lower drive to the target.
  • Move everything else from swap to target

Since it is bottom-up, you must specify a list starting from the bottommost drive.

+3
source

I assume that you need to edit the edit forever, so I will just post the fix here. There is an error in the code posted by Pesto. The correct version (with more beautiful output formatting) is as follows:

 move([Disc],X,_,Y) :- format("Move disk ~w from ~w to ~w\n", [Disc, X, Y]). move([Bottom|Rest],Start,Swap,Goal) :- move(Rest,Start,Goal,Swap), move([Bottom],Start,_,Goal), move(Rest,Swap,Start,Goal). 

Checked under GNU Prolog.

0
source

All Articles