Skip to content

Commit

Permalink
Merge pull request #86 from darshmgandhi/master
Browse files Browse the repository at this point in the history
Knapsack in Java for Hacktober Issue #1
  • Loading branch information
Harshita-Kanal authored Nov 18, 2020
2 parents 78572e3 + cc65761 commit 68e8527
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions java_knapsack.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import java.util.Scanner;

public class java_knapsack {

public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Knapsack Problem...\nEnter number of items: ");
int numberOfItems = sc.nextInt();
System.out.print("Enter maximum weight of the container: ");
int maxWeight = sc.nextInt();
int randomProfit[] = new int[numberOfItems];
int randomWeight[] = new int[numberOfItems];
int ascendingProfit[] = new int[numberOfItems];
int ascendingWeight[] = new int[numberOfItems];
int descendingProfit[] = new int[numberOfItems];
int descendingWeight[] = new int[numberOfItems];
System.out.println("Random Order");
System.out.print("Enter weights for " + numberOfItems + " items in random order(Spaces in betweeen): ");
for (int i = 0; i < numberOfItems; i++) {
randomWeight[i] = sc.nextInt();
}
System.out.print("Enter profits for corresponding " + numberOfItems + " items(Spaces in betweeen): ");
for (int i = 0; i < numberOfItems; i++) {
randomProfit[i] = sc.nextInt();
}
double randomTotal = fractionalKnapsack(randomProfit, randomWeight, maxWeight);
System.out.println("Total Profit: " + randomTotal);
}

public static double fractionalKnapsack(int profit[], int weight[], int maxWeight) {
double profitPerWeight[] = new double[profit.length];
int maxPW = -1;
double totalProfit = 0;
int j;
for (int i = 0; i < profit.length; i++) {
profitPerWeight[i] = (double)profit[i] / (double)weight[i];
}
while (true) {
j = 0;
while (j < profit.length) {
if (weight[j] > 0) {
maxPW = j;
break;
}
j++;
}
if (j == profit.length) {
break;
}
for (int i = j + 1; i < profit.length; i++) {
if (profitPerWeight[i] > profitPerWeight[maxPW] && weight[i] > 0) {
maxPW = i;
}
}
if (weight[maxPW] <= maxWeight) {
maxWeight -= weight[maxPW];
totalProfit += profit[maxPW];
weight[maxPW] = 0;
if (maxWeight == 0) {
break;
}
} else {
totalProfit += maxWeight * profitPerWeight[maxPW];
break;
}
}
return totalProfit;
}

}

0 comments on commit 68e8527

Please sign in to comment.