Skip to content

Instantly share code, notes, and snippets.

@nootanghimire
Created June 24, 2014 17:03
Show Gist options
  • Save nootanghimire/bf7c38594f9607bbe839 to your computer and use it in GitHub Desktop.
Save nootanghimire/bf7c38594f9607bbe839 to your computer and use it in GitHub Desktop.
tower-of-hanoi-recursive
/**
* @author Nootan Ghimire <[email protected]>
* @desc Implementation of Solution Tower of hanoi in C. (Recursive implementation)
*/
#include <stdio.h>
/**
* Includes for benchmarking
*/
#include <sys/time.h>
#include <sys/resource.h>
/**
* gets current time (high resolution)
* @return double : time
*/
double get_time()
{
struct timeval t;
struct timezone tzp;
gettimeofday(&t, &tzp);
return t.tv_sec + t.tv_usec*1e-6;
}
/**
* moves (tower of hanoi) discs from pegs
* @param num int
* @param source_peg int
* @param using_peg int
* @param destination_peg int
*/
void move(int num, int source_peg, int using_peg, int destination_peg){
/* Make sure there is only one (largest) disc on source_peg */
if(num>1){
move(num-1, source_peg, destination_peg, using_peg);
}
/* Move that largest Disc to destination */
fprintf(stdout, "Moved Disc %d from Peg %d to Peg %d\n",num,source_peg,destination_peg );
/* If there is anything else in the auxilary, move that to destination */
if(num>1){
move(num-1,using_peg,source_peg,destination_peg);
}
}
/**
* main function
* @return program_status_code
*/
int main(){
double d1, d2;
d1 = get_time();
move(20,1,2,3);
d2 = get_time();
fprintf(stdout, "%lf\n", d2-d1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment