0% found this document useful (0 votes)
27 views3 pages

Fracknap

The document describes an algorithm to solve the fractional knapsack problem. It defines a struct to represent items with weight and value. It sorts the items by value-to-weight ratio and fills the knapsack taking items in this order, taking fractions where the item exceeds the remaining capacity.

Uploaded by

retrodumb100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views3 pages

Fracknap

The document describes an algorithm to solve the fractional knapsack problem. It defines a struct to represent items with weight and value. It sorts the items by value-to-weight ratio and fills the knapsack taking items in this order, taking fractions where the item exceeds the remaining capacity.

Uploaded by

retrodumb100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

#include <stdio.

h>

#include <stdlib.h>

// Structure to represent an item

struct Item {

int weight;

int value;

double ratio; // Value-to-weight ratio

};

int compare(const void *a, const void *b) {

const struct Item *item1 = (struct Item *)a;

const struct Item *item2 = (struct Item *)b;

return (item2->ratio - item1->ratio > 0) ? 1 : -1;

double fractionalKnapsack(int capacity, struct Item items[], int n) {

// Calculate the value-to-weight ratio for each item

for (int i = 0; i < n; i++) {

items[i].ratio = (double)items[i].value / items[i].weight;

// Sort items based on the value-to-weight ratio in descending order

qsort(items, n, sizeof(items[0]), compare);

// Initialize variables

double totalValue = 0.0;

int currentWeight = 0;

for (int i = 0; i < n; i++) {


if (currentWeight + items[i].weight <= capacity) {

// Take the whole item

currentWeight += items[i].weight;

totalValue += items[i].value;

} else {

// Take a fraction of the item

double remainingCapacity = capacity - currentWeight;

totalValue += items[i].ratio * remainingCapacity;

break; // Knapsack is full

return totalValue;

int main() {

int n, capacity;

// Input the number of items and the capacity of the knapsack

printf("Enter the number of items: ");

scanf("%d", &n);

printf("Enter the capacity of the knapsack: ");

scanf("%d", &capacity);

// Input the weight and value of each item

struct Item items[n];

for (int i = 0; i < n; i++) {

printf("Enter weight and value for item %d: ", i + 1);

scanf("%d %d", &items[i].weight, &items[i].value);


}

// Solve the Fractional Knapsack Problem

double result = fractionalKnapsack(capacity, items, n);

printf("Maximum value in Knapsack = %.2f\n", result);

return 0;

You might also like