Towers of Hanoi: Difference between revisions

Content added Content deleted
(→‎{{header|AppleScript}}: Added alternative example.)
m (→‎{{header|AppleScript}}: Modified own example to eliminate tail calls.)
Line 290:
----
More illustratively:
 
''(I've now eliminated the recursive ''|move|()'' handler's tail calls. So it's now only called 2 ^ (n - 1) times as opposed to 2 ^ (n + 1) - 1 with full recursion. The maximum call depth of n is only reached once, whereas with full recursion, the maximum depth was n + 1 and this was reached 2 ^ n times.)''
 
<lang applescript>on hanoi(n)
Line 305 ⟶ 307:
on |move|(n, source, target, aux)
ifrepeat with (n >from n to 2 by -1 -- Tail call 0)elimination thenrepeat.
|move|(n - 1, source, aux, target)
set sourceTowerRefend toof item sourcetarget of my towerRefs to n
set end oftell item targetsource of my towerRefs to endset its contents to reverse of sourceTowerRefrest of its reverse
set sourceTowerRef's contents to reverse of rest of reverse of sourceTowerRef
set m to m + 1
set end of my process to ¬
Line 316 ⟶ 317:
t2 & tower2, ¬
t3 & tower3}
|move|(n - 1, aux, target,tell source)
end if set source to aux
set aux to it
end tell
end repeat
-- Specific code for n = 1:
set end of item target of my towerRefs to 1
tell item source of my towerRefs to set sourceTowerRef'sits contents to reverse of rest of reverseits of sourceTowerRefreverse
set m to m + 1
set end of my process to ¬
{(m as text) & ". move disc 1 from tower " & source & (" to tower " & target & ":"), ¬
t1 & tower1, ¬
t2 & tower2, ¬
t3 & tower3}
end |move|
end script
Line 328 ⟶ 341:
set AppleScript's text item delimiters to ", "
set o's process to {"Starting with " & n & " discs on tower 1:", t1 & o's tower1, t2, t3}
if (n > 0) then tell o to |move|(n, 1, 2, 3)
set end of o's process to "That's it!"
set AppleScript's text item delimiters to linefeed