c - Hanoi Towers - iterative, using lists -
i want write standard hanoi towers algorythm, using 3 rods, , n discs. i'd learn how use lists, thought combine this.
i thought creating 3 elements, each representing single rod. every 1 of them have discs[] array, , example if rod have 5 discs array contain [1, 2, 3, 4, 5] elements.
ok, implemented structures etc, question - how solve hanoi towers iterative?
is ok loop on rods, , every disc check can go, , move first checked position - , repeat loop?
no need overcomplicate life lists. use arrays.
#include <stdio.h> #define disks 4 // 10 max int stacks[3][disks]; int sps[3]; void init(int from) { int i; sps[2] = sps[1] = sps[0] = 0; (i = 0; < disks; i++) stacks[from][i] = disks - i; // disk radius sps[from] = disks; } void print(void) { int i, j, k; (i = disks - 1; >= 0; i--) { (j = 0; j < 3; j++) { if (sps[j] > i) { (k = 0; k < 10 - stacks[j][i]; k++) printf(" "); (k = 0; k < 2 * stacks[j][i]; k++) printf("x"); (k = 0; k < 10 - stacks[j][i]; k++) printf(" "); } else { printf(" "); // 10 * 2 } printf(" "); } printf("\n"); } printf("_________/\\_________ _________/\\_________ _________/\\_________\n\n"); } void solve(int to, int from, int cnt) { int other = ^ ^ 3; if (!cnt) return; solve(other, from, cnt - 1); stacks[to][sps[to]++] = stacks[from][--sps[from]]; print(); solve(to, other, cnt - 1); } int main(void) { init(0); print(); solve(2, 0, disks); return 0; } output (ideone):
xx xxxx xxxxxx xxxxxxxx _________/\_________ _________/\_________ _________/\_________ xxxx xxxxxx xxxxxxxx xx _________/\_________ _________/\_________ _________/\_________ xxxxxx xxxxxxxx xx xxxx _________/\_________ _________/\_________ _________/\_________ xxxxxx xx xxxxxxxx xxxx _________/\_________ _________/\_________ _________/\_________ xx xxxxxxxx xxxxxx xxxx _________/\_________ _________/\_________ _________/\_________ xx xxxxxxxx xxxxxx xxxx _________/\_________ _________/\_________ _________/\_________ xx xxxx xxxxxxxx xxxxxx _________/\_________ _________/\_________ _________/\_________ xx xxxx xxxxxxxx xxxxxx _________/\_________ _________/\_________ _________/\_________ xx xxxx xxxxxx xxxxxxxx _________/\_________ _________/\_________ _________/\_________ xxxx xx xxxxxx xxxxxxxx _________/\_________ _________/\_________ _________/\_________ xx xxxx xxxxxx xxxxxxxx _________/\_________ _________/\_________ _________/\_________ xx xxxx xxxxxx xxxxxxxx _________/\_________ _________/\_________ _________/\_________ xx xxxxxx xxxx xxxxxxxx _________/\_________ _________/\_________ _________/\_________ xxxxxx xxxx xx xxxxxxxx _________/\_________ _________/\_________ _________/\_________ xxxx xxxxxx xx xxxxxxxx _________/\_________ _________/\_________ _________/\_________ xx xxxx xxxxxx xxxxxxxx _________/\_________ _________/\_________ _________/\_________
Comments
Post a Comment