CS 2734
Computer Organization II
If your SSN is even then write Hanoi below
else if your SSN is odd then write Comb below
/* Tower of Hanoi problem: given n discs of decreasing size
* on a peg numbered 1, show how to move them all to peg
* number 2, using peg number 3. The rules state that you
* must not place a disc on a smaller disc, though you can
* place a disc on an empty peg or on a larger disc.
*/
#include <stdio.h>
void hanoi(int n, int start, int finish, int extra);
void main(void)
{
int n;
scanf("%d", &n);
hanoi(n, 1, 2, 3);
}
void hanoi(int n, int start, int finish, int extra)
{
if (n != 0) {
hanoi(n-1, start, extra, finish);
printf("Move disc %d from %d to %d.\n", n, start, finish);
hanoi(n-1, extra, finish, start);
}
}
Along with sample output:
4
Move disc 1 from 1 to 3.
Move disc 2 from 1 to 2.
Move disc 1 from 3 to 2.
Move disc 3 from 1 to 3.
Move disc 1 from 2 to 1.
Move disc 2 from 2 to 3.
Move disc 1 from 1 to 3.
Move disc 4 from 1 to 2.
Move disc 1 from 3 to 2.
Move disc 2 from 3 to 1.
Move disc 1 from 2 to 1.
Move disc 3 from 3 to 2.
Move disc 1 from 1 to 3.
Move disc 2 from 1 to 2.
Move disc 1 from 3 to 2.
/* Number of combinations of n things taken k at a time.
* Use a recursive algorithm to calculate.
*/
#include <stdio.h>
void main()
{ int N, K, C;
printf("Enter values for N and K>>>");
scanf("%d %d", &N, &K);
C = Comb(N, K);
printf("C = Comb(%d, %d) is %d\n", N, K, C);
return;
}
int Comb(int N, int K)
{
printf("Call Comb with N and K = %d %d\n", N, K);
if (N == K || K == 0)
return 1;
else return Comb(N-1, K) + Comb(N-1, K-1);
}
Along with sample output:
Enter values for N and K>>>5
2
Call Comb with N and K = 5 2
Call Comb with N and K = 4 2
Call Comb with N and K = 3 2
Call Comb with N and K = 2 2
Call Comb with N and K = 2 1
Call Comb with N and K = 1 1
Call Comb with N and K = 1 0
Call Comb with N and K = 3 1
Call Comb with N and K = 2 1
Call Comb with N and K = 1 1
Call Comb with N and K = 1 0
Call Comb with N and K = 2 0
Call Comb with N and K = 4 1
Call Comb with N and K = 3 1
Call Comb with N and K = 2 1
Call Comb with N and K = 1 1
Call Comb with N and K = 1 0
Call Comb with N and K = 2 0
Call Comb with N and K = 3 0
C = Comb(5, 2) is 10
For checkoff: