kernelthread.com

Plan 9 rc Shell

The Towers of Hanoi as a Plan 9 rc Shell script.

#! /bin/rc # # The Towers Of Hanoi # rc # Copyright (C) 1998 Amit Singh. All Rights Reserved. # http://hanoi.kernelthread.com # # Tested under rc release 1.5 # # rc is a shell designed by Tom Duff of Bell Labs to replace the Bourne # shell in Plan 9 # Programming in rc (arithmetic and so on) is a *BIG* pain # Modify this appropriately # EXPR = /usr/bin/expr esp = 0; # stack pointer STACK = (); # the stack (actually a list) _sfTO = 2; # stack frame entry _sfFR = 0; # stack frame entry _sfUS = 1; # stack frame entry _sfNU = 3; # stack frame entry _sfEN = Z; # stack frame entry remain = 0; popped = X; # The following stack.XXX functions implement a (slow) # stack - $EXPR is an external program :-( # fn stack.init { STACK = (); popped = X; esp = 0; } fn stack.push { STACK = ($STACK $1) esp = `{ $EXPR $esp + 1 } } fn stack.pop { if (!~ $esp 0) { popped = $STACK($esp) esp = `{ $EXPR $esp - 1 } i = 0 TSTACK = () while (!~ $i $esp) { i = `{ $EXPR $i + 1 } TSTACK = ($TSTACK $STACK($i)) } STACK = $TSTACK } else { echo 'stack empty!' } } fn stack.show { if (!~ $esp -1) { echo -n $STACK echo -n ' ' echo $esp elements } } fn inithanoi { remain = 0 stack.init _sfTO = 2; _sfFR = 0; _sfUS = 1; _sfNU = 3; _sfEN = Z; popped = X; } fn moveit { echo -n 'move ' echo -n $1 echo -n ' --> ' echo $2 } fn dohanoi { inithanoi stack.push $1 stack.push 1 stack.push 3 stack.push 0 while (!~ $esp 0) { stack.pop _sfEN = $popped stack.pop _sfTO = $popped stack.pop _sfFR = $popped stack.pop _sfNU = $popped remain = `{ $EXPR 6 - $_sfFR - $_sfTO } if (!~ $_sfEN 0) { moveit $_sfFR $_sfTO n_1 = `{ $EXPR $_sfNU - 1 } stack.push $n_1 stack.push $remain stack.push $_sfTO stack.push 0 } else { if (!~ $_sfNU 1) { stack.push $_sfNU stack.push $_sfFR stack.push $_sfTO stack.push 1 n_1 = `{ $EXPR $_sfNU - 1 } stack.push $n_1 stack.push $_sfFR stack.push $remain stack.push 0 } else { moveit $_sfFR $_sfTO } } } } fn hanoi { dohanoi $1 exit 0 } hanoi $*

Download

hanoi.rc