01 Feb 2024
Forth und Hanoi - rekursiv und flott
Schnelles Hanoi-Beispiel in Forth, Rekursiv.
Danke, Internet!
: left ." left" ;
: right ." right" ;
: middle ." middle" ;
: move-disk ( v t f n -- v t f )
dup 0= if drop exit then
1- >r
rot swap r@ ( t v f n-1 ) recurse
rot swap
2dup cr ." Move disk from " execute ." to " execute
swap rot r> ( f t v n-1 ) recurse
swap rot
;
: hanoi ( n -- )
1 max >r ['] right ['] middle ['] left r> move-disk drop drop drop
;
Demo
gforth hanoi.4th
Gforth 0.7.3, Copyright (C) 1995-2008 Free Software Foundation, Inc.
Gforth comes with ABSOLUTELY NO WARRANTY; for details type `license'
Type `bye' to exit
4 hanoi
Move disk from left to right
Move disk from left to middle
Move disk from right to middle
Move disk from left to right
Move disk from middle to left
Move disk from middle to right
Move disk from left to right
Move disk from left to middle
Move disk from right to middle
Move disk from right to left
Move disk from middle to left
Move disk from right to middle
Move disk from left to right
Move disk from left to middle
Move disk from right to middle ok