I have a program due in the morning using Prolog.
I am implementing Towers of Hanoi.
What I need help with is each time that it prints Move disc number # from _ to _
. I need to increment a counter saying Move X: "String"
String being the previous statement of what to move.
At the end of the program I need to print the total number of moves taken to accomplish the puzzle. I currently have my program setup recursively bottom-up.
One common problem is keeping IO mixed with the calculation. It is better to isolate IO by having a wrapper predicate with an argument that becomes instantiated with the result.
Consider this (code is meant to demonstrate the addition of a counter, not solve the problem):
% one move
move(1,X,Y,_,_,1) :-
write('Move top disk from '),
write(X), write(' to '), write(Y), nl.
move(N,X,Y,Z,Count,Counter) :-
N>1,
M is N-1,
Countplus is Count*2, % binary recursion tree
move(M,X,Z,Y,Countplus,C1),
move(1,X,Y,_,Countplus,C2),
move(M,Z,Y,X,Countplus,C3),
Counter is C1+C2+C3. % sum of moves
towers(N,X,Y,Z) :-
Count is N*N-1,
move(N,X,Y,Z,Count,Counter),
% you can now do whatever you want with Counter, e.g. print it:
write('The number of steps required with '),
write(N), write(' disks is '), write(Count), write('.').
Even if the above code is not related to what you have, the same procedure applies: add arguments to transfer the Counter and use recursion to increment it.
Alternatively, there are global variables but are usually frowned upon as they are ease to misuse and write procedural programs.