towers of hanoi - what is wrong with this code?
I'm trying to write a program, that solves the logical game "towers of hanoi" for n.
If you newer heard of it, heres the game's description from wikipedia:
The problem with my program is: it DOES solve the problem IF there are 1-3 disks, but if the is 4, or more, it simply never ends.
The Tower of Hanoi or Towers of Hanoi is a mathematical game or puzzle. It consists of three pegs, and a number of disks of different sizes which can slide onto any peg. The puzzle starts with the disks neatly stacked in order of size on one peg, the smallest at the top, thus making a conical shape.
The objective of the game is to move the entire stack to another peg, obeying the following rules:
* Only one disk may be moved at a time.
* Each move consists of taking the upper disk from one of the pegs and sliding it onto another peg, on top of the other disks that may already be present on that peg.
* No disk may be placed on top of a smaller disk.
Here's the code:
In my program, three global integer arrays (a,b and c) represent the three pegs, and the disks are represented as integers. The smaller the integer is, the bigger disk it represent. The smallest integer (and biggest disk) is 1.
int main (void)
scanf("%d",&i); /*how many disks should be*/
while (i-1 >= 0) /*this is the part where the program puts the "disks" on the first "peg"*/
while (c[i] != 0) /*the program writes out the contents of the third peg, represented as the "c" array*/
while(*(ki+i) != 0)
if (i == 1) /*if theres only one disk, just put it on the right peg*/
if (i > 1) /*if there are more than one disks, use recursion: put all the disks except the last one on the "second" peg*/
put(ki,ce); /*and after that, put that last one on the right peg*/
while(*(from+(i+1)) != 0)
while(*(to+j) != 0)
In the beginning, all the "disks" are in the "a" array, from 1 to n (depending on how many disks you want: the program asks you this in the beginning). The end of the three arrays are represented by a "0" after the last integer (this way it is easy to measure how "tall" the peg is).
The program uses a recursive function to solve this problem.