Posts

Showing posts with the label hanoi

Unary math Towers of Hanoi in naked (D)ASH and BASH

The following solution assumes neither BASH extensions, nor any external executables. Hence it could be ran from a preboot environment like a frugal initrd. A slight compromise was to use unary math. Did you know, that you can access an animated version from Emacs by typing M-x hanoi ? pop(){  shift  echo $* } top(){  echo $1 } print_towers(){  echo "a=[" $a "], b=[" $b "], c=[" $c "]" } hanoi(){  [ "$n" ] || return  local ln  ln=$(pop $n)  n=$ln  hanoi $1 $3 $2  print_towers  echo "$1 -> $2"  eval $2=\"$(eval top \$$1) $(echo \$$2)\"  eval $1=\"$(eval pop \$$1)\"  n=$ln  hanoi $3 $2 $1 } main(){  a="1 2 3 4 5"  b=  c=  n=$a  hanoi a b c  print_towers } main "$@"