Ada PGM 7
Ada PGM 7
#include <stdio.h>
double temp;
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;
double discreteKnapsack(int n, double weight[], double profit[], double ratio[], double capacity) {
break;
} else {
Totalvalue += profit[i];
capacity -= weight[i];
return Totalvalue;
double continuousKnapsack(int n, double weight[], double profit[], double ratio[], double capacity) {
break;
} else {
Totalvalue += profit[i];
capacity -= weight[i];
return Totalvalue;
int main() {
int n, choice;
printf("Enter the number of items: ");
scanf("%d", &n);
scanf("%lf", &capacity);
scanf("%d", &choice);
double Totalvalue;
if (choice == 1) {
} else if (choice == 2) {
Totalvalue = continuousKnapsack(n, weight, profit, ratio, capacity);
} else {
printf("Invalid choice!\n");
return 0;
Explanation:
1. Sorting Function: sortItems sorts the items based on their value-to-weight ratio in
descending order.
2. Discrete Knapsack Function: discreteKnapsack solves the discrete knapsack
problem.
3. Continuous Knapsack Function: continuousKnapsack solves the continuous knapsack
problem.
4. Main Function: The main function collects user input, sorts the items, prompts the user
for the type of knapsack problem, and displays the result
Output:
Number of items: 3
Weight and profit for each item:
o Item 0: Weight = 10, Profit = 60
o Item 1: Weight = 20, Profit = 100
o Item 2: Weight = 30, Profit = 120
Knapsack capacity: 50
Choice: 1 (Discrete Knapsack)
Discrete Knapsack Problem
In the discrete knapsack problem, the program will select items based on their value-to-weight
ratio until the capacity is full or no more items can be added.
1. Compute the value-to-weight ratios:
o Item 0: 6010=6.0\frac{60}{10} = 6.01060=6.0
o Item 1: 10020=5.0\frac{100}{20} = 5.020100=5.0
o Item 2: 12030=4.0\frac{120}{30} = 4.030120=4.0
2. Sort the items based on these ratios (descending order):
o Item 0: Weight = 10, Profit = 60, Ratio = 6.0
o Item 1: Weight = 20, Profit = 100, Ratio = 5.0
o Item 2: Weight = 30, Profit = 120, Ratio = 4.0
3. Select items until the capacity is full:
o Add Item 0: Remaining capacity = 50 - 10 = 40, Total value = 60
o Add Item 1: Remaining capacity = 40 - 20 = 20, Total value = 160
o Item 2 can't be added completely since its weight (30) exceeds the remaining
capacity (20).
Output for Discrete Knapsack:
Enter the number of items: 3