-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathhanoi.n
93 lines (77 loc) · 1.44 KB
/
hanoi.n
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using Nemerle.Collections;
using Nemerle.IO;
module Hanoi {
mutable stacks : array [list [int]];
print_stacks () : void
{
def loop (max, i) {
if (i >= stacks.Length) max
else {
def len = NList.Length (stacks[i]);
loop (if (len > max) len else max, i + 1)
}
};
def maxval = loop (0, 0);
for (mutable i = 0; i < maxval; i++) {
for (mutable j = 0; j < stacks.Length; j++) {
def off = maxval - NList.Length (stacks[j]);
if (i <= off - 1)
printf (" |")
else
printf (" %d", NList.Nth (stacks[j], i - off))
};
printf ("\n");
};
printf ("\n");
}
move (a : int, b : int) : void
{
match (stacks[a]) {
| head :: tail =>
stacks[a] = tail;
stacks[b] = head :: stacks[b];
print_stacks ()
| [] => assert(false)
}
}
solve (n : int, a : int, b : int, c : int) : void
{
when (n > 0) {
solve (n - 1, a, c, b);
move (a, b);
solve (n - 1, c, b, a);
}
}
Main () : void
{
mutable height = 0;
scanf ("%d", height);
def loop (n) { if (n == 0) [] else n :: loop (n - 1) };
stacks = array [NList.Rev (loop (height)), [], []];
print_stacks ();
solve (height, 0, 2, 1)
}
}
/*
BEGIN-INPUT
3
END-INPUT
BEGIN-OUTPUT
1 | |
2 | |
3 | |
2 | |
3 | 1
3 2 1
| 1 |
3 2 |
| 1 |
| 2 3
1 2 3
| | 2
1 | 3
| | 1
| | 2
| | 3
END-OUTPUT
*/