A solution for Project Three
Below is the listing for a possible solution to the project.
/* MCS 275 Project Three: Knapsack */
#include <stdio.h>
#include <stdlib.h>
void knapsack ( int n );
/* prints out subsets of n elements on screen */
void all_sets ( int n, int k, int a[n], int w[n],
int max, int freq[max], int *cnt );
/* recursive version of all subsets */
int main()
{
int n;
printf("Solving the knapsack problem.\n");
printf("Give number of items : "); scanf("%d", &n);
knapsack(n);
return 0;
}
void knapsack ( int n )
{
int i,a[n],w[n],max,cnt=0;
int *freq;
for (i = 0; i < n; i++)
{
a[i] = 0;
printf("Give weight of item %d : ", i+1);
scanf("%d", &w[i]);
}
printf("Give maximal admitted weight : ");
scanf("%d",&max);
printf("All ways to pack %d items, with total weight <= %d :\n", n, max);
freq = (int*)calloc(max+1,sizeof(int));
all_sets(n,0,a,w,max,freq,&cnt);
printf("Admitted solutions : %d, all with total weight <= %d :\n", cnt, max);
for (i = 0; i <= max; i++)
printf(" number of solutions with total weight = %d : %d\n", i, freq[i]);
}
void all_sets ( int n, int k, int a[n], int w[n], int max,
int freq[max], int *cnt )
{
int i,sum = 0;
if (k == n)
{
for (i = 0; i < n; i++)
{
printf(" %d", a[i]);
if (a[i]==1) sum = sum + w[i];
}
printf(" total weight : %d", sum);
if (sum <= max)
{
printf(" admitted, less than or equal to %d.\n", max);
*cnt = *cnt+1;
freq[sum]++;
}
else
printf(" is heavier than %d, not admitted!\n", max);
}
else
{
all_sets(n,k+1,a,w,max,freq,cnt);
a[k] = 1;
all_sets(n,k+1,a,w,max,freq,cnt);
a[k] = 0;
}
}