Skip to content
Snippets Groups Projects
Select Git revision
  • 4ff440eaac9aee21bd0a6c7f5ce7927ee4cd9b94
  • master default
2 results

hanoi-9a.c

Blame
  • Forked from Peter Gerwinski / hp
    341 commits behind the upstream repository.
    hanoi-9a.c 1.12 KiB
    #include <stdio.h>
    #include <error.h>
    
    #define DISKS 32
    
    int n[3], tower[3][DISKS];
    
    void display (void)
    {
      printf ("\n");
      for (int i = 0; i < 3; i++)
        {
          printf ("tower %d:", i);
          for (int j = 0; j < n[i]; j++)
            printf (" %d", tower[i][j]);
          printf ("\n");
        }
    }
    
    void move (int from, int to, int disks)
    {
      if (disks == 1)
        {
          if (n[from] <= 0)
            error (1, 0, "trying to move disk from empty tower");
          if (n[to] > 0 && tower[to][n[to] - 1] < tower[from][n[from] - 1])
            error (1, 0, "trying to move larger disk on smaller one");
          tower[to][n[to]] = tower[from][n[from] - 1];
          n[to]++;
          n[from]--;
          static int counter = 1;
          if (counter++ >= 100000000)
            {
              display ();
              counter = 1;
            }
        }
      else
        {
          int help = 0 + 1 + 2 - from - to;
          move (from, help, disks - 1);
          move (from, to, 1);
          move (help, to, disks - 1);
        }
    }
    
    int main (void)
    {
      n[0] = DISKS;
      for (int i = 0; i < DISKS; i++)
        tower[0][i] = DISKS - i;
      n[1] = 0;
      n[2] = 0;
      display ();
      move (0, 2, DISKS);
      display ();
      return 0;
    }