Towers of Hanoi: Difference between revisions

Content added Content deleted
m (→‎Python recursive: (separating composition of the solution from its display))
m (→‎simple text moves: added/changed comments and whitespace, simplified the program, used a template for the output section.)
Line 3,574: Line 3,574:
parse arg N . /*get optional number of disks from CL.*/
parse arg N . /*get optional number of disks from CL.*/
if N=='' | N=="," then N=3 /*Not specified? Then use the default.*/
if N=='' | N=="," then N=3 /*Not specified? Then use the default.*/
#=0 /*#: the number of disk moves (so far)*/
#= 0 /*#: the number of disk moves (so far)*/
z=2**N - 1 /*Z: " " " minimum # of moves.*/
z= 2**N - 1 /*Z: " " " minimum # of moves.*/
call mov 1, 3, N /*move the top disk, then recurse ··· */
call mov 1, 3, N /*move the top disk, then recurse ··· */
say /* [↓] Display the minimum # of moves.*/
say
say 'The minimum number of moves to solve a ' N"-disk Tower of Hanoi is " z
say 'The minimum number of moves to solve a ' N"─disk Tower of Hanoi is " z
exit /*stick a fork in it, we're all done. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
mov: procedure expose # z; parse arg @1,@2,@3; L= length(z)
dsk: #=#+1 /*bump the (disk) move counter by one. */
say 'step' right(#, length(z))": move disk on tower" arg(1) '───►' arg(2)
if @3==1 then do; #= # + 1 /*bump the (disk) move counter by one. */
return /* [↑] display the move message (text)*/
say 'step' right(#, L)": move disk on tower" @1 '───►' @2
end
/*──────────────────────────────────────────────────────────────────────────────────────*/
mov: procedure expose # z; parse arg @1, @2, @3
else do; call mov @1, 6 -@1 -@2, @3 -1
if @3==1 then call dsk @1, @2
call mov @1, @2, 1
else do; call mov @1, 6-@1-@2, @3-1
call mov 6 - @1 - @2, @2, @3 -1
call mov @1, @2, 1
end
call mov 6-@1-@2, @2, @3-1
return /* [↑] this subroutine uses recursion.*/</lang>
{{out|output|text=&nbsp; when using the default input:}}
end
return</lang>
'''output''' &nbsp; when using the default input:
<pre>
<pre>
step 1: move disk on tower 1 ───► 3
step 1: move disk on tower 1 ───► 3