forked from dimpeshpanwar/Java-Advance-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFractionalKnapsackSolver.java
More file actions
65 lines (51 loc) · 1.79 KB
/
FractionalKnapsackSolver.java
File metadata and controls
65 lines (51 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.*;
class FractionalKnapsackSolver {
static class ItemComparator implements Comparator<int[]> {
public int compare(int[] a, int[] b) {
double a1 = (1.0 * a[0]) / a[1];
double b1 = (1.0 * b[0]) / b[1];
return Double.compare(b1, a1);
}
}
static double fractionalKnapsack(int[] val, int[] wt, int capacity) {
int n = val.length;
int[][] items = new int[n][2];
for (int i = 0; i < n; i++) {
items[i][0] = val[i];
items[i][1] = wt[i];
}
Arrays.sort(items, new ItemComparator());
double res = 0.0;
int currentCapacity = capacity;
for (int i = 0; i < n; i++) {
if (items[i][1] <= currentCapacity) {
res += items[i][0];
currentCapacity -= items[i][1];
} else {
res += (1.0 * items[i][0] / items[i][1]) * currentCapacity;
break;
}
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of items: ");
int n = sc.nextInt();
int[] val = new int[n];
int[] wt = new int[n];
System.out.println("Enter the values of the items:");
for (int i = 0; i < n; i++) {
val[i] = sc.nextInt();
}
System.out.println("Enter the weights of the items:");
for (int i = 0; i < n; i++) {
wt[i] = sc.nextInt();
}
System.out.print("Enter the capacity of the knapsack: ");
int capacity = sc.nextInt();
double result = fractionalKnapsack(val, wt, capacity);
System.out.println("Maximum value in knapsack = " + result);
sc.close();
}
}