; ハノイの塔を解くプログラム
MAIN   START
       LD      GR0,N
       LD      GR1,A
       LD      GR2,B
       LD      GR3,C
       CALL    HANOI       ; hanoi(3, A, B, C)
       RET

; hanoi(N, X, Y, Z)
HANOI  CPA     GR0,=1      ; if N == 1 then
       JZE     DISP        ;  move it, return
       SUBA    GR0,=1      ; N - 1
       PUSH    0,GR2       ; swap GR2 GR3
       LD      GR2,GR3
       POP     GR3
       CALL    HANOI       ; hanoi(N-1, X, Z, Y)
       ST      GR1,MSG1
       ST      GR2,MSG2    ; now GR2 holds Z
       OUT     MSG,LNG     ; 'from X to Z'
       PUSH    0,GR2       ; rotate registers
       LD      GR2,GR1
       LD      GR1,GR3
       POP     GR3
       CALL    HANOI       ; hanoi(N-1, Y, X, Z)
       PUSH    0,GR2       ; restore registers
       LD      GR2,GR1
       POP     GR1
       ADDA    GR0,=1      ; also N has restored
       RET

DISP   ST      GR1,MSG1    ; 'from X to Z'
       ST      GR3,MSG2
       OUT     MSG,LNG
       RET

N      DC      3        ; 輪の総数
LNG    DC      11       ; メッセージの長さ
A      DC      'A'
B      DC      'B'
C      DC      'C'
MSG    DC      'from '
MSG1   DS      1
       DC      ' to '
MSG2   DS      1
       END
