xxxxxxxxxx
/*
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;
}
}
xxxxxxxxxx
#include<bits/stdc++.h>
using namespace std;
float p[100],w[100];
float x[100];
void knapsack(int m,int n)
{
for(int i = 1; i<n; i++)
{
int maX = i;
for(int j =i+1;j<=n;j++)
{
if(p[j]/w[j] > p[maX]/w[maX])
{
maX = j;
}
}
swap(p[maX],p[i]);
swap(w[maX],w[i]);
}
int u = m;
int i;
for(i=1;i<=n;i++)
{
if(w[i]>u)
break;
x[i] = 1;
u = u-w[i];
}
if(i<=n)
{
x[i] = u/w[i];
}
}
void profit_calculation(int n)
{
float sum = 0;
for(int i = 1;i<=n;i++)
sum += x[i]*p[i];
cout<<sum;
}
int main()
{
int n; // n is the number of items
cout<<"Enter the no. of items:";
cin>>n;
for(int i = 1;i<=n;i++)
{
cin>>p[i]>>w[i]; // Enter Profit space Weight respectively
}
cout<<endl;
knapsack(60,4);
cout<<"After Sorting according to unit profit: "<<endl;
cout<<"profit: ";
for(int i = 1;i<=n;i++)
cout<<p[i]<<" ";
cout<<endl<<"Weight: ";
for(int i = 1;i<=n;i++)
cout<<w[i]<<" ";
cout<<endl;
cout<<"You can take the items respectively portion of:"<<endl;
for(int i = 1;i<=n;i++)
cout<<x[i]<<" ";
cout<<endl;
cout<<"your total profit is: ";
profit_calculation(n);
return 0;
}
xxxxxxxxxx
# Structure for an item which stores weight and
# corresponding value of Item
class Item:
def __init__(self, value, weight):
self.value = value
self.weight = weight
def __repr__(self):
return " value:% s weight:% s" % (self.value, self.weight) #used to print THE CLASSES LISTS
# Main greedy function to solve problem
def fractionalKnapsack(W, arr):
# sorting Item on basis of ratio
arr.sort(key=lambda x: (x.value/x.weight), reverse=True)
# Uncomment to see new order of Items with their
# ratio
# for item in arr:
# print(item.value, item.weight, item.value/item.weight)
# Result(value in Knapsack)
finalvalue = 0.0
# Looping through all Items
for item in arr:
# If adding Item won't overflow, add it completely
if item.weight <= W:
W -= item.weight
finalvalue += item.value
# If we can't add current Item, add fractional part
# of it
else:
finalvalue += item.value * W / item.weight
break
# Returning final value
return finalvalue
import random
import matplotlib.pyplot as plt
import time
timeList=[]
fornnumberList=[]
for i in range(6):
no=random.choice(range(6))
numList=random.sample(range(10,100,5),no)#for 'no' random numbers
num=random.choice(numList) #used for weights
print("Limit Weight",num)
numpList=random.sample(range(10,100,6),no)
#nump=random.choice(numpList) #num and nump instead of here if used in function each time a new number shows up
start_time=time.time()
arrayList=[]
for i in range(no):
arrayList.append(Item(random.choice(numpList),random.choice(numList)))
print(arrayList)
fractionalKnapsack(num,arrayList)#enter the function here
print("knapsack value",fractionalKnapsack(num,arrayList))
end_time=time.time()
final_time= end_time- start_time
timeList.append(final_time)
fornnumberList.append(no)
x=timeList
y=fornnumberList
plt.xlabel("Time taken")
plt.ylabel("For 'x' random numbers")
plt.plot(x, y)
plt.scatter(x,y)