Permalink
Fetching contributors…
Cannot retrieve contributors at this time
71 lines (62 sloc) 1.4 KB
using Nemerle.IO;
module Hanoi {
mutable tops : array [array [int]];
mutable numbers : array [int];
mutable n : int;
mutable move_no : int;
show_top (k : int, n : int) : void
{
if (tops[k][n] == 0) printf (" | ")
else printf ("(%d)", tops[k][n]);
printf (" ")
}
show_tops () : void
{
for (mutable i = n; i >= 1; i = i - 1) {
show_top (1, i);
show_top (2, i);
show_top (3, i);
printf ("\n")
}
}
move (a : int, b : int) : void
{
printf ("%d -(%d)-> %d\n", a, move_no, b);
tops[b][numbers[b]] = tops[a][numbers[a]-1];
tops[a][numbers[a]-1] = 0;
numbers[a] = numbers[a] - 1;
numbers[b] = numbers[b] + 1;
move_no = move_no + 1;
show_tops ();
}
hanoi (n : int, a : int, b : int, c : int) : void
{
when (n > 0) {
hanoi (n - 1, a, c, b);
move (a, b);
hanoi (n - 1, c, b, a);
}
}
init () : void
{
printf ("the tower of hanoi (please type the size ?) ");
scanf ("%d", n);
numbers = array (n + 1);
tops = array [null, array (n + 1), array (n + 1), array (n + 1)];
for (mutable i = 1; i <= n; i = i + 1) {
tops[1][n - i + 1] = i;
tops[2][n - i + 1] = 0;
tops[3][n - i + 1] = 0;
};
numbers[1] = n + 1;
numbers[2] = 1;
numbers[3] = 1;
move_no = 1;
show_tops ();
}
Main () : void
{
init ();
hanoi (n, 1, 3, 2);
}
}