Search code examples
prologtowers-of-hanoi

Increment each iteration in tower of hanoi - PROLOG


I made this hanoi algorithm and now i want to increment each iteration and print it. Can anyone help? Thank you!

Here is what I tried:

increase(X,Y):-Y is X+1.

hanoi(N):-move(N,left,middle,right,0).
move(0,_,_,_,_):-!.
move(N,A,B,C,NUM):- M is N-1,increase(NUM,NUM1),
                    move(M,A,C,B,NUM1),
                    print(A,B,NUM1),
                    increase(NUM1,NUM2),
                    move(M,C,B,A,NUM2).

print(A,B,M):- write(M),
               write(': MOVE DISK FROM '),
               write(A),
               write(' TO '),
               write(B),nl.

I want it to appear like this, per example:

?-hanoi(2).
1: MOVE DISK FROM left TO right
2: MOVE DISK FROM left TO middle
3: MOVE DISK FROM right TO middle

But the numbers show up in the wrong order:

?- hanoi(2).
2: MOVE DISK FROM left TO right
1: MOVE DISK FROM left TO middle
3: MOVE DISK FROM right TO middle
true.

Solution

  • Hanoi from Simply Logical https://www.cs.bris.ac.uk/~flach/SL/SL.pdf then added a separate print predicate.

    :-op(900,xfx,'TO').
    % hanoi(N,A,B,C,Moves) <- Moves is the list of moves to
    % move N disks from peg A to peg C,
    % using peg B as intermediary peg
    hanoi(0,A,B,C,[]).
    hanoi(N,A,B,C,Moves):-
      N1 is N-1,
      hanoi(N1,A,C,B,Moves1),
      hanoi(N1,B,A,C,Moves2),
      append(Moves1,[A 'TO' C|Moves2],Moves).
    
    print_hanoi(Size):-
      hanoi(Size,left,middle,right,Moves),
      length(Moves,L),
      numlist(1,L,Is),
      maplist(print_row,Is,Moves).
    
    print_row(I,M):-
      format("~w. MOVE DISK FROM ~w\n",[I,M]).
    

    Query:

     ?- print_hanoi(3).
     1. MOVE DISK FROM left TO right
     2. MOVE DISK FROM left TO middle
     3. MOVE DISK FROM right TO middle
     4. MOVE DISK FROM left TO right
     5. MOVE DISK FROM middle TO left
     6. MOVE DISK FROM middle TO right
     7. MOVE DISK FROM left TO right