Skip to content

Instantly share code, notes, and snippets.

@RitamChakraborty
Last active July 29, 2019 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RitamChakraborty/4ee19cd728052a830636ea83b31c75f4 to your computer and use it in GitHub Desktop.
Save RitamChakraborty/4ee19cd728052a830636ea83b31c75f4 to your computer and use it in GitHub Desktop.
Knapsack Problem
import java.text.DecimalFormat;
/*
1 2 3 4 5 6 7
10 5 15 7 6 18 3
2 3 5 7 1 4 1
5 1.6 3 0 6 4.5 3
5 1 14 1 X 6
1 2 12 2 X 5
6 4 8 4 X 4.5
3 5 3 5 X 3
7 1 2 1 X 3
2 2 0 2 X 1.67
55.2
*/
public class KnapsackProblem {
public static void main(String[] args) {
int[] weights = {2, 3, 5, 7, 1, 4, 1};
int[] profits = {10, 5, 15, 7, 6, 18, 3};
System.out.println(getMaxProfit(weights, profits, 15, 7));
}
private static double getMaxProfit(int[] weights, int[] profits, int maxCapacity, int n) {
double[] profitWeightRatios = new double[n];
for (int i = 0; i < n; i++) {
profitWeightRatios[i] = Double.parseDouble(new DecimalFormat("#.##")
.format((double) profits[i] / (double) weights[i]));
}
for (int i = 0; i < n - 1; i++) {
for (int j = (i + 1); j < n; j++) {
if (profitWeightRatios[i] >= profitWeightRatios[j]) {
swap(profitWeightRatios, i, j);
swap(weights, i, j);
}
}
}
double maxProfit = 0;
for (int i = n - 1; i >= 0; i--) {
if (maxCapacity == 0) {
break;
}
if (maxCapacity - weights[i] < 0) {
maxProfit += (double) maxCapacity * profitWeightRatios[i];
maxCapacity = 0;
} else {
maxCapacity -= weights[i];
maxProfit += (double) weights[i] * profitWeightRatios[i];
}
}
return maxProfit;
}
private static void swap(double[] arr, int a, int b) {
double temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
private static void swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment