Palak Goel 11232753 4C2
PROJECT-2
AIM:- In the supermarket there are n packages (n ≤ 100) the package i has weight
W[i] ≤ 100 and value V[i] ≤ 100. A thief breaks into the supermarket; the thief
cannot carry weight exceeding M (M ≤ 100). The problem to be solved here is:
which packages the thief will take away to get the highest value
CODE:-
import java.util.Arrays;
import java.util.Comparator;
public class GreedyKnapsack {
static class Item {
int value;
int weight;
double ratio;
public Item(int value, int weight) {
this.value = value;
this.weight = weight;
this.ratio = (double) value / weight;
}
public double getRatio() {
return this.ratio;
}
}
public static double fractionalKnapsack(int capacity, Item[] items) {
Arrays.sort(items, Comparator.comparingDouble(Item::getRatio).reversed());
double totalValue = 0;
int currentWeight = 0;
21
MMEC,Mullana
Palak Goel 11232753 4C2
for (Item item : items) {
if (currentWeight + item.weight <= capacity) {
currentWeight += item.weight;
totalValue += item.value;
System.out.println("Added item with value " + item.value + " and weight " + item.weight);
} else {
int remainingCapacity = capacity - currentWeight;
if (remainingCapacity > 0) {
double fraction = (double) remainingCapacity / item.weight;
totalValue += item.value * fraction;
currentWeight = capacity;
System.out.println("Added fraction (" + fraction + ") of item with value " + item.value + "
and weight " + item.weight);
break;
}
}
}
System.out.println("Total value in Knapsack = " + totalValue);
return totalValue;
}
public static void main(String[] args) {
int capacity = 80;
Item[] items = {
new Item(10, 8),
new Item(15, 2),
new Item(100, 30),
new Item(50, 10),
new Item(60, 40),
new Item(70, 70),
new Item(100, 20),
22
MMEC,Mullana
Palak Goel 11232753 4C2
new Item(5, 1),
new Item(19, 2),
new Item(10, 3),
};
double maxValue = fractionalKnapsack(capacity, items);
System.out.println("Maximum possible value for theif to take: " + maxValue);
}
}
OUTPUT:-
23
MMEC,Mullana