Skip to content
Snippets Groups Projects
Select Git revision
  • 0ba264323975d1dc4dd71499afc9d06ee4ce3d5e
  • master default
2 results

hanoi-4.c

Blame
  • Forked from Peter Gerwinski / hp
    328 commits behind the upstream repository.
    hanoi-4.c 844 B
    #include <stdio.h>
    #include <error.h>
    
    #define DISKS 4
    
    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]--;
        }
    }
    
    int main (void)
    {
      n[0] = DISKS;
      for (int i = 0; i < DISKS; i++)
        tower[0][i] = DISKS - i;
      n[1] = 0;
      n[2] = 0;
      move (0, 2, 1);
      display ();
      return 0;
    }