home *** CD-ROM | disk | FTP | other *** search
/ SGI Developer Toolbox 6.1 / SGI Developer Toolbox 6.1 - Disc 1.iso / toolbox / src / exampleCode / opengl / GLUT / progs / contrib / engine.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-11-11  |  1.3 KB  |  76 lines

  1.  
  2. /* hanoi solver for hanoi2 */
  3.  
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <assert.h>
  7. #include <unistd.h>
  8.  
  9. static int num_disks[3] = {0,0,0};
  10.  
  11. static void
  12. move_disk(int from, int to, int fd)
  13. {
  14.     char buf[3];
  15.  
  16.     assert(from != to);
  17.     num_disks[from] --;
  18.     num_disks[to] ++;
  19. #ifdef TEST_ENGINE
  20.     printf("%d --> %d\n", from, to);
  21. #else
  22.     buf[0] = 'M';
  23.     buf[1] = (char)from;
  24.     buf[2] = (char)to;
  25.     if (3 != write(fd, buf, 3)) {
  26.     perror("can't write");
  27.     exit(1);
  28.     }
  29. #endif
  30. }
  31.  
  32. static void
  33. move_disks(int from, int to, int n, int fd)
  34. {
  35.     static int other_table[9] = { -1, 2, 1, 2, -1, 0, 1, 0, -1 };
  36.     int other;
  37.  
  38.     assert(from != to);
  39.     other = other_table[from*3 + to];
  40.     assert(other != -1);
  41.     if (n == 1) {
  42.     move_disk(from, to, fd);
  43.     }
  44.     else {
  45.         move_disks(from, other, n-1, fd);
  46.     move_disk(from, to, fd);
  47.     move_disks(other, to, n-1, fd);
  48.     }
  49. }
  50.  
  51. void
  52. engine(int *args)
  53. {
  54.     num_disks[0] = args[0];
  55.     while(1) {
  56.     move_disks(0, 2, args[0], args[1]);
  57.     move_disks(2, 0, args[0], args[1]);
  58.     }
  59. }
  60.  
  61.  
  62. #ifdef TEST_ENGINE
  63. int
  64. main(int argc, char *argv[])
  65. {
  66.     int engine_args[2];
  67.  
  68.     if (argc > 1) {
  69.     engine_args[0] = atoi(argv[1]);
  70.     }
  71.     engine_args[1] = 1;
  72.     engine(n, engine_args);
  73.     return 0;             /* ANSI C requires main to return int. */
  74. }
  75. #endif
  76.