# !/usr/local/bin/kermit +

; From: "Nguyen, Dat" <dnguyen@siemens-emis.com>
; To: "'Frank da Cruz'" <fdc@columbia.edu>
; Subject: A Faster Towers of Hanoi Script
; Date: Tue, 15 Jan 2002 10:00:48 -0600
;
; You are very thorough in verifying input parameters, sometimes at the
; expense of the execution of recursive macro.  I reworked the Tower_Of_Hanoi
; script to separate the verification of the inputs and the execution of the
; recursive computation.  I think this pattern is applicable to similar
; recursive macros.
;
; h a n o i  --  Towers Of Hanoi
;
; Author:  Dat Thuc Nguyen, 21 Sep 2001
;  Revised 15 Jan 2002
;
; \%1 Number_of_Discs
; \%2 Start_Peg
; \%3 Goal_Peg

define Tower_Of_Hanoi {
    if < \v(argc) 4 exit 1 Usage: hanoi ndisks startpeg goalpeg
    if not numeric \%1 exit 1 \%1: not a number
    if not numeric \%2 exit 1 \%2: not a number
    if not numeric \%3 exit 1 \%3: not a number
    if ( < \%1 1 || < \%2 1 || < \%3 1 ) exit 1 Numbers must be positive
    if ( > \%2 3 || > \%3 3 ) exit 1 Peg must be 1 or 2 or 3
    if ( = \%2 \%3 ) exit 1 Peg numbers must be distinct

    local recursive
    define recursive {
        if = 1 \%1 {
            echo Move Top Disc from peg \%2 to peg \%3.
        } else {
            (recursive (- \%1 1) \%2 (- 6 (+ \%2 \%3)))
            recursive 1 \%2 \%3
            (recursive (- \%1 1) (- 6 (+ \%2 \%3)) \%3)
        }
    }
    recursive \%1 \%2 \%3
    exit 0
}
