AOA Experiment 6
AOA Experiment 6
6
Fraction Knapsack
Date of Performance: 05/03/2025
Date of Submission: 12/03/2025
Experiment No. 6
Theory:
The knapsack problem states that − given a set of items, holding weights and profit
values, one must determine the subset of the items to be added in a knapsack such
that, the total weight of the items must not exceed the limit of the knapsack and its
total profit value is maximum.
The knapsack problem or rucksack problem is a problem in combinatorial
optimization: Given a set of items, each with a mass and a value, determine the
number of each item to include in a collection so that the total weight is less than or
equal to a given limit and the total value is as large as possible. It derives its name
from the problem faced by someone who is constrained by a fixed size knapsack and
must fill it with the most valuable items. The most common problem being solved is
the 0-1 knapsack problem, which restricts the number xi of copies of each kind of item
to zero or one.
In Knapsack problem we are given:
1. n objects
2. Knapsack with capacity m.
3. An object iis associated with profit Wi.
4. Object i is associated with profit Pi.
5. Object i is placed in knapsack we get profit Pi Xi .
Here objects can be broken into pieces (Xi Values) The Objective of Knapsack
problem is to maximize the profit.
Example:
Find an optimal solution for fractional Knapsack problem.
Where,
Number of objects = 7
Capacity of Knapsack = 15
P1,P2,P3,P4,P5,P6,P7 = (10,5,15,7,6,18,3)
W1,W2,W3,W4,W5,W6,W7 = (2,3,5,7,1,4,1)
Solution:
Object 1 2 3 4 5 6 7
Pi 10 5 15 7 6 18 3
Wi 2 3 5 7 1 4 1
Pi/Wi 5 1.67 3 1 6 4.5 3
Algorithm:
Step 2: O(n.logn)
Sort objects in decreasing order of Profit / Weight Ratio
Step 3: // Add all the profit by considering the weight capacity of fractional knapsack.
For i=1 to N
O(n)
if M > 0 AND Wi <= M
M = M –Wi
P = P + Pi
else
break
if M > 0 Then
P = P + Pi * (M/Wi)
Step 4:
Display Total Profit
id[j + 1] = tempId;
value[j + 1] = tempValue;
weight[j + 1] = tempWeight;
}
}
}
}
void knapsack(char id[], int value[], int weight[], int n, int capacity) {
int currentWeight = 0;
int totalValue = 0;
int selected[n];
int main() {
int n, capacity;
printf("Enter the number of items: ");
scanf("%d", &n);
printf("Enter the knapsack capacity: ");
scanf("%d", &capacity);
char id[n];
int value[n];
int weight[n];
return 0;
}
Output:
Conclusion:
The knapsack algorithm implemented in this C program effectively maximizes value within a
given capacity using a greedy approach based on value-to-weight ratios. It sorts items by their
efficiency and iteratively includes them if they fit, providing detailed output for each step. The
program's step-by-step display shows the decision process, current contents, and running totals
clearly. Ultimately, it produces an optimized solution with a final list of selected items and their
total value and weight.