Instantly share code, notes, and snippets.

Abhishek-dev2/same_disks.c Created Nov 16, 2016

Tower of Hanoi problem with some disks of same size
 #include #include int count = 0; int **arr; void swap(int i,int j) { int temp = arr[i][0]; arr[i][0] = arr[j][0]; arr[j][0] = temp; temp = arr[i][1]; arr[i][1] = arr[j][1]; arr[j][1] = temp; } //This function is finding the index at which median is present. int partition(int start,int end) { int wall = start,i; int pivot = arr[end][0]; for(i = start;i < end;i++) { if(arr[i][0] < pivot) { swap(i, wall); wall++; } } swap(wall,end); return wall; } int qSort(int start,int end) { if(start < end) { int wall = partition(start, end); qSort(start, wall - 1); qSort(wall + 1, end); } } void toh(char source, char destination,char via, int num,int size_top) { int i; if(num == 1) { for(i = 0;i < arr[size_top - 1][1];i++) { count++; printf("%d. Move disk of size %d from %c to %c\n",count, arr[size_top - 1][0], source, destination); } } else { toh(source, via, destination, num - 1, size_top); for(i = 0;i < arr[num - 1][1];i++) { count++; printf("%d. Move disk of size %d from %c to %c\n",count, arr[num - 1][0], source, destination); } toh(via, destination, source, num - 1, size_top); } } int main() { int n,i; //Scanning printf("Enter no. of different sizes of disk : "); scanf("%d",&n); //Creating n * 2 arr = (int **)malloc(n * sizeof(int *)); for (i = 0; i < n; i++) arr[i] = (int *)malloc(2 * sizeof(int)); //Scanning n * 2 for(i = 0;i < n;i++) { printf("Enter size and number : "); scanf("%d %d",&arr[i][0],&arr[i][1]); } //Sorting qSort(0, n - 1); toh('A', 'C', 'B', n, 1); printf("Total moves = %d\n",count); free(arr); return 0; }