This is my problem my knapsack code is given below and I am not getting the expected output it should give me the maximum profit that I could have gained from the inputted elements
# include <stdio.h>
void knapsack(int n, float weight[], float profit[], float capacity){
float x[20], tp=0;
int i, j, u;
u = capacity;
for (int i = 0; i < n; i++)
x[i] = 0.0;
for (int i = 0; i < n; i++)
{
if (weight[i]>u)
break;
else
{
x[i] = 1.0;
tp = tp + profit[i];
u = u-weight[i];
}
}
if (i<n)
x[i] = u/weight[i];
tp = tp + (x[i] * profit[i]);
printf("nThe result vector is:-");
for (int i = 0; i < n; i++)
printf("%ft", x[i]);
printf("nMaximum profit is:-%f",tp);
}
int main(){
float weight[20], profit[20], capacity;
int num, i, j;
float ratio[20], temp;
printf("nEnter the no. of items:-");
scanf("%d",&num);
printf("nEnter the weights and profits of each item:-");
for (int i = 0; i < num; i++)
{
scanf("%f %f",&weight[i], &profit[i]);
}
printf("nEnter the capacity of knapsack:-");
scanf("%f",&capacity);
for (int i = 0; i < num; i++)
{
ratio[i] = profit[i] / weight[i];
}
for (int i = 0; i < num; i++)
{
for (int j = i+1; j < num; j++)
{
if (ratio[i] < ratio[j])
{
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
}
}
knapsack(num, weight, profit, capacity);
return 0;
}
input tried: Enter the no. of items:-5
Enter the weights and profits of each item:-50 120
50 110
50 130
50 160
40 150
Enter the capacity of knapsack:-70 output expected:The result vector is:- 1.000000 0.400000 0.000000 0.000000 0.000000
Maximum profit is:- 214.000000
output I am getting: “Enter the weights and profits of each item:-50 120
50 110
50 130
50 160
40 150
Enter the capacity of knapsack:-70″ this is the whole input after giving this input nothing is showing as output
AR Naeem is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1