Skip to content

Instantly share code, notes, and snippets.

@nishidy
Last active August 22, 2016 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nishidy/0e716776b9b6606a667046ea564dfa43 to your computer and use it in GitHub Desktop.
Save nishidy/0e716776b9b6606a667046ea564dfa43 to your computer and use it in GitHub Desktop.
Tower of hanoi with arbitrary disks showing the move among rods
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define RODS 3
#define MAX_DISKS 20
#define WAIT 300000
int disk_locations[MAX_DISKS] = {0};
int disks = 0;
int move_count = 0;
void print(){
char stacks[MAX_DISKS][100] = {'\0'};
int flags[MAX_DISKS] = {0};
int row,rod,disk,horiz,empty,stack,i,j;
for(row=0;row<disks;row++){
stack = 0;
for(rod=0;rod<RODS;rod++){
empty=1;
for(disk=disks-1;disk>=0;disk--){
if(disk_locations[disk] == rod && !flags[disk]){
for(horiz=0;horiz<disks-disk-1;horiz++){
stacks[row][stack++] = ' ';
}
for(horiz=disks-disk-1;horiz<disks;horiz++){
stacks[row][stack++] = '=';
}
stacks[row][stack++] = '|';
for(horiz=disks-disk-1;horiz<disks;horiz++){
stacks[row][stack++] = '=';
}
for(horiz=0;horiz<disks-disk-1;horiz++){
stacks[row][stack++] = ' ';
}
flags[disk] = 1;
empty=0;
break;
}
}
if(empty){
for(horiz=0;horiz<disks;horiz++){
stacks[row][stack++] = ' ';
}
stacks[row][stack++] = '|';
for(horiz=0;horiz<disks;horiz++){
stacks[row][stack++] = ' ';
}
}
}
}
for(i=disks-1;i>=0;i--){
j=0;
while(stacks[i][j]!='\0'){
printf("%c",stacks[i][j++]);
}
printf("\n");
}
printf("\n");
}
void move(int num, int src, int dst){
int i;
move_count += 1;
for(i=0;i<disks;i++){
if(disk_locations[i]==src){
disk_locations[i] = dst;
break;
}
}
print();
usleep(WAIT);
}
void hanoi(int src, int tmp, int dst, int num){
if(num>0){
hanoi(src,dst,tmp,num-1);
printf("\033[2J[#%d] %d : %d to %d\n",move_count,num,src,dst);
move(num,src,dst);
hanoi(tmp,src,dst,num-1);
}
}
int main(int argc, char* argv[]){
int num = atoi(argv[1]);
disks = num;
printf("\033[2J[#%d]\n",move_count);
move(num,0,0);
hanoi(0,1,2,num);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment