LTCMiner cloud mining
Posts

ADA Program 7

 

7. Fractional / Continuous Knapsack (Greedy)

#include <stdio.h>

typedef struct {
    int id;
    float weight;
    float profit;
    float ratio;
} Item;

void sortItems(Item items[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (items[i].ratio < items[j].ratio) {
                Item temp = items[i];
                items[i] = items[j];
                items[j] = temp;
            }
        }
    }
}

void discreteKnapsackGreedy(Item items[], int n, float capacity) {
    float totalProfit = 0.0f;
    float remaining = capacity;
    for (int i = 0; i < n; i++) {
        if (items[i].weight <= remaining) {
            remaining = remaining-items[i].weight;
            totalProfit =totalProfit+ items[i].profit;
        }
    }
    printf("Discrete (0/1) Greedy Approximation Profit: %f \n", totalProfit);
}

void continuousKnapsack(Item items[], int n, float capacity) {
    float totalProfit = 0.0f;
    float remaining = capacity;
    for (int i = 0; i < n; i++) {
        if (items[i].weight <= remaining) {
            remaining = remaining-items[i].weight;
            totalProfit = totalProfit+ items[i].profit;
        } else if (remaining > 0) {
            totalProfit = totalProfit+ items[i].profit * (remaining / items[i].weight);
            break;
        }
    }
    printf("\n Continuous (Fractional) Knapsack Profit: %.2f\n", totalProfit);
}

int main() {
    int n;
    float capacity;
    printf("Enter number of items: ");
    scanf("%d", &n);
    Item items[n];
    for (int i = 0; i < n; i++) {
        items[i].id = i + 1;
        printf("Enter weight and profit for item %d: ", i + 1);
        scanf("%f %f", &items[i].weight, &items[i].profit);
        items[i].ratio = items[i].profit / items[i].weight;
    }
    printf("Enter knapsack capacity: ");
    scanf("%f", &capacity);
    sortItems(items, n);
    discreteKnapsackGreedy(items, n, capacity);
    continuousKnapsack(items, n, capacity);
    return 0;
}
OR
OR




Getting Info...
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.