-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursiveKnapsack.java
More file actions
79 lines (68 loc) · 2.3 KB
/
RecursiveKnapsack.java
File metadata and controls
79 lines (68 loc) · 2.3 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
/*
* javac RecursiveKnapsack.java
* java RecursiveKnapsack
*/
import java.io.*;
import java.util.*;
import java.math.*;
class RecursiveKnapsackAlgo{
int[] v;
int[] w;
int W;
int nElems;
// improving run time by caching results, reduce number of recursive calls
HashMap<String,Integer> cache = new HashMap<String,Integer>();
public RecursiveKnapsackAlgo(int W, int numOfItems){
v = new int[numOfItems + 1];
w = new int[numOfItems + 1];
this.W = W;
nElems = 1;
// initialization
v[0] = 0;
w[0] = 0;
}
public void insert(int v_i, int w_i){
v[nElems] = v_i;
w[nElems] = w_i;
nElems++;
}
public int recursiveKnapsack(int i,int x){
if(i < 0){
return 0;
}
Integer sol = cache.get(i+":"+x);
if(sol == null){
if(w[i] > x){
sol = recursiveKnapsack(i-1, x);
} else{
sol = Math.max(recursiveKnapsack(i-1, x), recursiveKnapsack(i-1, x-w[i]) + v[i]);
}
cache.put(i+":"+x, sol);
}
return sol;
}
}
class RecursiveKnapsack{
public static void main(String[] args) throws IOException{
try{
RecursiveKnapsackAlgo ka = read_file_and_populate("knapsack1.txt");
System.out.println("optimal value = " + ka.recursiveKnapsack((ka.v.length-1), ka.W));
ka = read_file_and_populate("knapsack_big.txt");
System.out.println("optimal value (large knapsack problem) = " + ka.recursiveKnapsack((ka.v.length-1), ka.W));
}catch (IOException e){
e.printStackTrace();
}
}
public static RecursiveKnapsackAlgo read_file_and_populate(String file_loc) throws IOException{
FileInputStream fil = new FileInputStream(file_loc);
BufferedReader br = new BufferedReader(new InputStreamReader(fil));
String element = br.readLine();
String[] line = element.split("\\s+");
RecursiveKnapsackAlgo ka = new RecursiveKnapsackAlgo(Integer.parseInt(line[0]), Integer.parseInt(line[1]));;
while( (element = br.readLine()) != null ){
line = element.split("\\s+");
ka.insert(Integer.parseInt(line[0]), Integer.parseInt(line[1]));
}
return ka;
}
}