Skip to content

Commit 7e43526

Browse files
committed
add knapsack DP solution get 30/60
1 parent 1e43010 commit 7e43526

File tree

6 files changed

+672
-0
lines changed

6 files changed

+672
-0
lines changed
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
import java.io.*;
2+
import java.util.List;
3+
4+
5+
import java.util.ArrayList;
6+
7+
/**
8+
* The class <code>Solver</code> is an implementation of a greedy algorithm to solve the knapsack problem.
9+
*
10+
*/
11+
public class Solver {
12+
13+
/**
14+
* The main class
15+
*/
16+
public static void main(String[] args) {
17+
try {
18+
solve(args);
19+
} catch (IOException e) {
20+
e.printStackTrace();
21+
}
22+
}
23+
24+
/**
25+
* Read the instance, solve it, and print the solution in the standard output
26+
*/
27+
public static void solve(String[] args) throws IOException {
28+
String fileName = null;
29+
30+
// get the temp file name
31+
for(String arg : args){
32+
if(arg.startsWith("-file=")){
33+
fileName = arg.substring(6);
34+
}
35+
}
36+
if(fileName == null)
37+
return;
38+
39+
// read the lines out of the file
40+
List<String> lines = new ArrayList<String>();
41+
42+
BufferedReader input = new BufferedReader(new FileReader(fileName));
43+
try {
44+
String line = null;
45+
while (( line = input.readLine()) != null){
46+
lines.add(line);
47+
}
48+
}
49+
finally {
50+
input.close();
51+
}
52+
53+
54+
// parse the data in the file
55+
String[] firstLine = lines.get(0).split("\\s+");
56+
int items = Integer.parseInt(firstLine[0]);
57+
int capacity = Integer.parseInt(firstLine[1]);
58+
59+
int[] values = new int[items];
60+
int[] weights = new int[items];
61+
62+
for(int i=1; i < items+1; i++){
63+
String line = lines.get(i);
64+
String[] parts = line.split("\\s+");
65+
66+
values[i-1] = Integer.parseInt(parts[0]);
67+
weights[i-1] = Integer.parseInt(parts[1]);
68+
}
69+
70+
// a trivial greedy algorithm for filling the knapsack
71+
// it takes items in-order until the knapsack is full
72+
73+
KnapsackSolver solver = new DPSolver();
74+
solver.solve(items,capacity,values,weights);
75+
76+
}
77+
public static void output(int value,int opt,int[] taken) {
78+
System.out.println(value+" "+opt);
79+
int items = taken.length;
80+
for(int i=0; i < items; i++){
81+
System.out.print(taken[i]+" ");
82+
}
83+
System.out.println("");
84+
}
85+
}
86+
87+
88+
interface KnapsackSolver{
89+
public void solve(int n,int K,int[] values,int[] weights);
90+
}
91+
92+
class DPSolver implements KnapsackSolver{
93+
private static final int MAX_SOLVE_SPACE = 100000000;
94+
public void solve(int n,int K,int[] values,int[] weights){
95+
if(n * K > MAX_SOLVE_SPACE)
96+
System.err.printf("need memory %d, but MAX_SOLVE_SPACE is %d\n",n*K,MAX_SOLVE_SPACE);
97+
int maxv;
98+
int opt =1;
99+
int[] token = new int[n];
100+
int[][] dp = new int[K+1][n];
101+
for(int k = 1 ; k <= K ; ++k){
102+
dp[k][0] = (k >=weights[0]? values[0] : 0);
103+
for(int j = 1 ; j < n ; ++j){
104+
dp[k][j] = dp[k][j-1];
105+
if(k-weights[j] >=0 && dp[k][j] < dp[k-weights[j]][j-1] + values[j])
106+
dp[k][j] = dp[k-weights[j]][j-1] + values[j];
107+
}
108+
}
109+
110+
maxv = dp[K][n-1];
111+
int k = K;
112+
for(int j = n-1 ; j >0 ; --j ){
113+
if(k >= weights[j] && dp[k][j] == dp[k-weights[j]][j-1] +values[j]){
114+
token[j] =1;
115+
k -=weights[j];
116+
}
117+
}
118+
if(dp[k][0] !=0)token[0] =1;
119+
Solver.output(maxv, opt, token);
120+
}
121+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
_le-pVv_EeasJA5dVmWj2w
2+
Knapsack
3+
awPVV, ./data/ks_30_0, solver.py, Knapsack Problem 1
4+
hHYWS, ./data/ks_50_0, solver.py, Knapsack Problem 2
5+
JwWnx, ./data/ks_200_0, solver.py, Knapsack Problem 3
6+
Z2tMt, ./data/ks_400_0, solver.py, Knapsack Problem 4
7+
PUIxa, ./data/ks_1000_0, solver.py, Knapsack Problem 5
8+
AKXWc, ./data/ks_10000_0, solver.py, Knapsack Problem 6
137 KB
Binary file not shown.
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#!/usr/bin/python
2+
# -*- coding: utf-8 -*-
3+
4+
from collections import namedtuple
5+
Item = namedtuple("Item", ['index', 'value', 'weight'])
6+
7+
def solve_it(input_data):
8+
# Modify this code to run your optimization algorithm
9+
10+
# parse the input
11+
lines = input_data.split('\n')
12+
13+
firstLine = lines[0].split()
14+
item_count = int(firstLine[0])
15+
capacity = int(firstLine[1])
16+
17+
items = []
18+
19+
for i in range(1, item_count+1):
20+
line = lines[i]
21+
parts = line.split()
22+
items.append(Item(i-1, int(parts[0]), int(parts[1])))
23+
24+
# a trivial greedy algorithm for filling the knapsack
25+
# it takes items in-order until the knapsack is full
26+
value = 0
27+
weight = 0
28+
taken = [0]*len(items)
29+
30+
for item in items:
31+
if weight + item.weight <= capacity:
32+
taken[item.index] = 1
33+
value += item.value
34+
weight += item.weight
35+
36+
# prepare the solution in the specified output format
37+
output_data = str(value) + ' ' + str(0) + '\n'
38+
output_data += ' '.join(map(str, taken))
39+
return output_data
40+
41+
42+
if __name__ == '__main__':
43+
import sys
44+
if len(sys.argv) > 1:
45+
file_location = sys.argv[1].strip()
46+
with open(file_location, 'r') as input_data_file:
47+
input_data = input_data_file.read()
48+
print(solve_it(input_data))
49+
else:
50+
print('This test requires an input file. Please select one from the data directory. (i.e. python solver.py ./data/ks_4_0)')
51+
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#!/usr/bin/python
2+
# -*- coding: utf-8 -*-
3+
4+
import os
5+
from subprocess import Popen, PIPE
6+
7+
def solve_it(input_data):
8+
9+
# Writes the inputData to a temporay file
10+
11+
tmp_file_name = 'tmp.data'
12+
tmp_file = open(tmp_file_name, 'w')
13+
tmp_file.write(input_data)
14+
tmp_file.close()
15+
16+
# Runs the command: java Solver -file=tmp.data
17+
os.system("javac .\Solver.java")
18+
process = Popen(['java', 'Solver', '-file=' + tmp_file_name], stdout=PIPE)
19+
(stdout, stderr) = process.communicate()
20+
# removes the temporay file
21+
os.remove(tmp_file_name)
22+
23+
return stdout.strip().decode('utf-8')
24+
25+
26+
import sys
27+
28+
if __name__ == '__main__':
29+
if len(sys.argv) > 1:
30+
file_location = sys.argv[1].strip()
31+
with open(file_location, 'r') as input_data_file:
32+
input_data = input_data_file.read()
33+
print(solve_it(input_data))
34+
else:
35+
print('This test requires an input file. Please select one from the data directory. (i.e. python solver.py ./data/ks_4_0)')
36+

0 commit comments

Comments
 (0)