home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / misc / volume16 / hanoi / part01 / hanoimod.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-02-15  |  1.5 KB  |  84 lines

  1. /*****************************************
  2.  * hanoi.c --
  3.  *  Towers of Hanoi program as in _The Age of Intelligent Machines_
  4.  *  by Raymond Kurzweil with main routine written by Sameer Parekh
  5.  *  (zane@ddsw1.MCS.COM)
  6.  *  and with display routine by Sameer Parekh
  7.  *****************************************/
  8.  
  9.  
  10. mvdisk(number, destination, position, max)
  11. int number, destination, max;
  12. int *position;
  13. {
  14. int i, j;
  15. position[number] = destination;
  16. /* Display set */
  17.  
  18. printf("\n");
  19. for(i = 1; i < 4; i++) {
  20.     printf("%d\t", i);
  21.     for(j = max; j > 0; j--) {
  22.         if (position[j] == i) {
  23.             printf("%d ", j);
  24.             }
  25.         }
  26.     printf("\n");
  27.     }
  28. }
  29.  
  30. void hanoi(original, destination, free, number_of_disks, position, max)
  31. int original, destination, free, number_of_disks, max;
  32. int *position;
  33. {
  34. if (number_of_disks == 1) {
  35.     mvdisk(1, destination, position, max);
  36.     return;
  37.     }
  38.  
  39. hanoi(original, free, destination, number_of_disks - 1, position, max);
  40.  
  41. mvdisk(number_of_disks, destination, position, max);
  42.  
  43. hanoi(free, destination, original, number_of_disks - 1, position, max);
  44.  
  45. return;
  46. }
  47.  
  48. init(position, max)
  49. int *position;
  50. int max;
  51. {
  52. int i;
  53. for(i = 1; i < (max + 1); i++) {
  54.     position[i] = 1;
  55.     }
  56. }
  57.  
  58. int main(argc, argv)
  59. int argc;
  60. char **argv;
  61.  
  62. {
  63. int *position;
  64. int max;
  65. int number;
  66. if (argc != 2) {
  67.     printf("Usage: %s <number of disks>\n", argv[0]);
  68.     exit(1);
  69.     }
  70. number = atoi(argv[1]);
  71.  
  72. if (number < 1) {
  73.     puts("Argument not appropriate!");
  74.     exit(1);
  75.     }
  76. position = malloc(number);
  77. max = number;
  78. init(position, max);
  79.  
  80. hanoi(1, 2, 3, number, position, max);
  81. }
  82.  
  83.  
  84.