Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

Fractional Knapsack


/*
class Item {
    int value, weight;
    Item(int x, int y){
        this.value = x;
        this.weight = y;
    }
}
*/

class CompareElements implements Comparator<Item>
{
    @Override
    public int compare(Item a, Item b)
    {
        double val1= (double)a.value/a.weight;
        double val2= (double)b.value/b.weight;
        
        if(val1>val2)
        return -1;
        
        else if(val2>val1)
        return 1;
        
        else
        return 0;
    }
}

class Solution
{
    //Function to get the maximum total value in the knapsack.
    double fractionalKnapsack(int W, Item arr[], int n) 
    {
        Arrays.sort(arr, new CompareElements());
        
        double currentValue=0;
        
        for(int i = 0 ; i<n;i++)
        {
            if(arr[i].weight<=W)
            {
                currentValue+=arr[i].value;
                W-=arr[i].weight;
            }
            else
            {
                currentValue+= ((double)arr[i].value/(double)arr[i].weight)*(double)W;
                break;
            }
        }
        return currentValue;
    }
}
Source by paste.ubuntu.com #
 
PREVIOUS NEXT
Tagged: #Fractional #Knapsack
ADD COMMENT
Topic
Name
5+5 =