forked from sachith-1/helloAlgorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFKnapsack.java
More file actions
89 lines (58 loc) · 1.85 KB
/
FKnapsack.java
File metadata and controls
89 lines (58 loc) · 1.85 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.util.Arrays;
public class FKnapsack {
public static void main(String[] args) {
int[] vals = { 10, 15, 40, 20, 25, 5 };
int[] wts = { 5, 3, 4, 10, 6, 1 };
System.out.println(getMaxValue(vals, wts, 20, 6));
}
public static double getMaxValue(int[] values, int[] weights, int capacity) {
return getMaxValue(values, weights, capacity, values.length);
}
public static double getMaxValue(int[] values, int[] weights, int capacity, int n) {
Item[] items = new Item[n];
int added = 0;
double cp = 0;
for (int i = 0; i < n; i++) {
items[i] = new Item(weights[i], values[i]);
}
Arrays.sort(items);
for (Item i : items) {
if (i.wt + added <= capacity) {
added += i.wt;
cp += i.val;
if (added == capacity) {
break;
}
} else {
double ratio = (capacity - added) * 1.0 / i.wt;
cp += i.val * ratio;
break;
}
}
return cp;
}
static class Item implements Comparable<Item> {
int wt, val;
double vbw;
public Item(int wt, int val) {
this.wt = wt;
this.val = val;
vbw = val * 1.0 / wt;
}
@Override
public int compareTo(Item i) {
double temp = i.vbw - this.vbw;
if (temp != 0)
return temp > 0 ? 1 : -1;
temp = i.val - this.val;
if (temp != 0)
return temp > 0 ? 1 : -1;
temp = this.wt - i.wt;
return temp >= 0 ? 1 : -1;
}
@Override
public String toString() {
return "Item [val=" + val + ", vbw=" + vbw + ", wt=" + wt + "]";
}
}
}