Towers of Hanoi: Difference between revisions

m
→‎{{header|AppleScript}}: Added source and destination parameters to own code's main handler. Removed auxiliary tower parameter from recursive handler.
m (→‎{{header|AppleScript}}: Modified own example to eliminate tail calls.)
m (→‎{{header|AppleScript}}: Added source and destination parameters to own code's main handler. Removed auxiliary tower parameter from recursive handler.)
Line 293:
''(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, source, target)
set t1 to tab & "tower 1: " & tab
set t2 to tab & "tower 2: " & tab
Line 306:
property process : missing value
on |move|(n, source, target, aux)
set aux to 6 - source - target
repeat with n from n to 2 by -1 -- Tail call elimination repeat.
|move|(n - 1, source, aux, target)
set end of item target of my towerRefs to n
tell item source of my towerRefs to set its contents to reverse of rest of its reverse
Line 335 ⟶ 336:
repeat with i from n to 1 by -1
set end of item source of o's tower1towerRefs to i
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ", "
set o's process to {"Starting with " & n & (" discs on tower 1:", t1 & o's(source tower1,& t2":")), t3}¬
if (n > 0) thent1 tell& o's to |move|(ntower1, 1,t2 2& o's tower2, 3)t3 & o's tower3}
if (n > 0) then tell o to |move|(n, source, target)
set end of o's process to "That's it!"
set AppleScript's text item delimiters to linefeed
Line 351 ⟶ 353:
 
-- Test:
set numberOfDiscs to 3
hanoi(3)</lang>
set sourceTower to 1
set destinationTower to 2
hanoi(numberOfDiscs, sourceTower, destinationTower)</lang>
 
{{Out}}
557

edits