Fractional Knapsack
Fractional Knapsack
h>
struct Item {
char name[20];
float value;
float weight;
};
void swap(struct Item* a, struct Item* b) {
struct Item temp = *a;
*a = *b;
*b = temp;
}
void sortItems(struct Item items[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if ((items[j].value / items[j].weight) < (items[j + 1].value / items[j
+ 1].weight)) {
swap(&items[j], &items[j + 1]);
}
}
}
}
float fractionalKnapsack(struct Item items[], int n, float capacity, float x[]) {
sortItems(items, n);
float totalValue = 0.0;
float totalWeight = 0.0;
for (int i = 0; i < n; i++) {
if (totalWeight + items[i].weight <= capacity) {
x[i] = 1.0;
totalWeight += items[i].weight;
totalValue += items[i].value;
} else {
x[i] = (capacity - totalWeight) / items[i].weight;
totalValue += items[i].value * x[i];
break;
}
}
return totalValue;
}
int main() {
int n;
float capacity;
printf("Enter the number of items: ");
scanf("%d", &n);
struct Item items[n];
float x[n];
for (int i = 0; i < n; i++) {
printf("Enter name, weight, and value of item %d: ", i + 1);
scanf("%s %f %f", items[i].name, &items[i].weight, &items[i].value);
}
printf("Enter the capacity of the knapsack: ");
scanf("%f", &capacity);
for (int i = 0; i < n; i++) {
x[i] = 0.0;
}
float maxValue = fractionalKnapsack(items, n, capacity, x);
printf("Maximum value: %.2f\n", maxValue);
printf("The fractions of items in the knapsack are: \n");
for (int i = 0; i < n; i++) {
printf("Item %d (%s): %.2f\n", i + 1, items[i].name, x[i]);
}
printf("Vector array x: ");
for (int i = 0; i < n; i++) {
printf("%.2f ", x[i]);
}
printf("\n");
return 0;
}