Towers of Hanoi: Difference between revisions

Content added Content deleted
(Added Fōrmulæ)
(→‎{{header|Python}}: A variant which separates computation from display)
Line 3,372: Line 3,372:
Move disk 1 from peg 2 to peg 3
Move disk 1 from peg 2 to peg 3
</pre>
</pre>


Or, separating the composition of the data from its display:

<lang python># hanoi :: Int -> String -> String -> String -> [(String, String)]
def hanoi(n, a, b, c):
def go(n, a, b, c):
p = n - 1
return (
go(p, a, c, b) + [(a, b)] + go(p, c, b, a)
) if 0 < n else []
return go(n, a, b, c)


# TEST AND DISPLAY -----------------------------------

# justifyRight :: Int -> Char -> String -> String
def justifyRight(n):
return lambda cFiller: lambda s: (
((n * cFiller) + s)[-n:]
)


for step in map(
lambda xy: justifyRight(5)(' ')(xy[0]) + ' -> ' + xy[1],
hanoi(4, 'left', 'right', 'mid')
):
print(step)
</lang>
{{Out}}
<pre> left -> mid
left -> right
mid -> right
left -> mid
right -> left
right -> mid
left -> mid
left -> right
mid -> right
mid -> left
right -> left
mid -> right
left -> mid
left -> right
mid -> right</pre>



==={{libheader|VPython}}===
==={{libheader|VPython}}===