-
Notifications
You must be signed in to change notification settings - Fork 0
/
batoh.js
executable file
·268 lines (238 loc) · 8.45 KB
/
batoh.js
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#!/usr/bin/node
"use strict";
var LineByLineReader = require('line-by-line');
var genSolver = require('./genetic.js');
var config = {};
try {
config = require('./config.js');
} catch(e) {
console.error(e.message);
console.error("Cannot load ./config.js, trying ./config.default.js");
config = require('./config.default.js');
}
function loadSolveProblems(file, solvers) {
var lr = new LineByLineReader(file);
lr.on('error', function (err) {
console.log("Error reading the file", JSON.stringify(err));
});
var data = [];
lr.on('line', function (line) {
var linearr = line.split(" ");
var things = [];
for(var i=3; i<linearr.length; i+=2) {
things.push({'weight':parseInt(linearr[i]), 'price':parseInt(linearr[i+1])});
}
console.log("Solving problem ID:",linearr[0]);
data.push({id:linearr[0], thingCount: things.length, resolvers:{}});
solvers.forEach(function(solver){
var hrstart = process.hrtime();
console.log(' '+solver.name+':');
var solution = null;
for(var i = 0; i< config.repeats; i++) {
solution = solver(parseInt(linearr[0]), parseInt(linearr[2]), things);
if(config.dontRepeat[solver.name]) {
break;
}
}
var hrend = process.hrtime(hrstart);
console.log(' Solution:',linearr[0], things.length, solution.price, solution.weight, JSON.stringify(solution.solution));
var time = (hrend[0] + hrend[1]/1000000000);
if(!config.dontRepeat[solver.name])
time = time / config.repeats;
console.log(' Time:', time.toFixed(6), 's');
data[data.length-1].resolvers[solver.name] = {time: time, price: solution.price, weight: solution.weight};
});
console.log(" ");
});
lr.on('end', function () {
console.log("Finished");
var times = {};
var relativeErrors = {};
solvers.forEach(function(solver) {
times[solver.name] = 0;
relativeErrors[solver.name] = {max:0, total:0};
});
data.forEach(function(instance) {
for(var resolverName in instance.resolvers) {
var resolver = instance.resolvers[resolverName];
times[resolverName] += resolver.time;
if(config.computeRelativeErrors) {
var relativeError = (instance.resolvers[config.relativeErrorBase].price - resolver.price)/instance.resolvers[config.relativeErrorBase].price;
relativeErrors[resolverName].total+=relativeError;
if(relativeErrors[resolverName].max < relativeError) {
relativeErrors[resolverName].max = relativeError;
}
}
}
});
console.log("Mean runtime:");
solvers.forEach(function(solver) {
console.log(' ' + solver.name+":", (times[solver.name]/data.length).toFixed(6), 's');
});
if(config.computeRelativeErrors) {
console.log("Mean relative error:");
solvers.forEach(function(solver) {
console.log(' ' + solver.name+":", (relativeErrors[solver.name].total/data.length).toFixed(5));
});
console.log("Max relative error:");
solvers.forEach(function(solver) {
console.log(' ' + solver.name+":", relativeErrors[solver.name].max.toFixed(5));
});
}
console.log("\n\n");
if(config.showRawResults)
console.log(JSON.stringify(data));
});
}
function bruteSolver(problemId, maxWeight, thingList) {
var globalsolution = {'solution':null, 'price':null, 'weight':null};
var resolve = function(solution, pricesofar, weightsofar) {
var position = solution.length;
if(position == thingList.length) {
if(weightsofar <= maxWeight && (globalsolution.price === null || pricesofar > globalsolution.price)) {
globalsolution.solution = solution.slice();
globalsolution.price = pricesofar;
globalsolution.weight = weightsofar;
}
return;
}
solution.push(0);
resolve(solution, pricesofar, weightsofar);
solution.pop();
solution.push(1);
resolve(solution, pricesofar+thingList[position].price, weightsofar + thingList[position].weight);
solution.pop();
}
resolve([], 0, 0);
return globalsolution;
}
function simpleHeuristicSolver(problemId, maxWeight, thingList) {
var solution = {'solution':[], 'price':null, 'weight':null};
thingList.sort(function(a,b) {
return (b.price/b.weight - a.price/a.weight);
});
thingList.forEach(function(thing) {
if(solution.weight + thing.weight <= maxWeight) {
solution.solution.push(1);
solution.price += thing.price;
solution.weight +=thing.weight;
}
else {
solution.solution.push(0);
}
});
return solution;
}
function bbSolver(problemId, maxWeight, thingList) {
var globalsolution = {'solution':null, 'price':null, 'weight':null};
var cumulativePrices = [];
cumulativePrices[thingList.length] = 0;
for(var i=thingList.length-1; i>=0; i--) {
cumulativePrices[i] = thingList[i].price + cumulativePrices[i+1];
}
var resolve = function(solution, pricesofar, weightsofar) {
var position = solution.length;
if(position == thingList.length) {
if(globalsolution.price === null || pricesofar > globalsolution.price) {
globalsolution.solution = solution.slice();
globalsolution.price = pricesofar;
globalsolution.weight = weightsofar;
}
return;
}
if(pricesofar+cumulativePrices[position+1] > globalsolution.price || globalsolution.price === null) {
solution.push(0);
resolve(solution, pricesofar, weightsofar);
solution.pop();
}
if(weightsofar+thingList[position].weight <= maxWeight && (pricesofar+cumulativePrices[position] > globalsolution.price||globalsolution.price === null)) {
solution.push(1);
resolve(solution, pricesofar+thingList[position].price, weightsofar + thingList[position].weight);
solution.pop();
}
}
resolve([], 0, 0);
return globalsolution;
}
function fptasSolver(problemId, maxWeight, thingList, desiredRelErr) {
var infMin = function(x,y) {
if(typeof y == 'undefined' || isNaN(y)) {
return x;
}
if(typeof x == 'undefined' || isNaN(x) || y < x) {
return y;
}
return x;
}
var globalsolution = {'solution':null, 'price':null, 'weight':null};
var pricemax = thingList.reduce(function(max, thing) {
return thing.price>max?thing.price:max;
},0);
var junkBits = Math.floor(Math.log(desiredRelErr*pricemax/thingList.length)/Math.log(2));
if(junkBits < 0) {
junkBits = 0;
}
var pricesum = 0;
thingList.forEach(function(thing) {
thing.cPrice = thing.price >> junkBits;
pricesum+= thing.cPrice;
});
var dynTable = new Array(pricesum+1);
for(var i=0; i<dynTable.length; i++){
dynTable[i] = new Array(thingList.length);
}
dynTable[0][-1] = 0;
for(var thing=0;thing<thingList.length;thing++) {
for(var price=0; price<dynTable.length; price++) {
if(price-thingList[thing].cPrice >= 0) {
dynTable[price][thing] = infMin(dynTable[price][thing-1],
dynTable[price-thingList[thing].cPrice][thing-1] + thingList[thing].weight);
}
else {
dynTable[price][thing] = dynTable[price][thing-1];
}
}
}
for(var i = dynTable.length-1; i>=0;i--) {
if(dynTable[i][thingList.length-1] <= maxWeight) {
globalsolution.price = i;
globalsolution.weight = dynTable[i][thingList.length-1];
break;
}
}
if(globalsolution.price !== null) {
var column = thingList.length-1;
var row = globalsolution.price;
globalsolution.price = 0;
globalsolution.solution = [];
while(column >= 0) {
if(dynTable[row][column] == dynTable[row][column-1]) {
globalsolution.solution.push(0);
}
else {
globalsolution.solution.push(1);
row -= thingList[column].cPrice;
globalsolution.price += thingList[column].price;
}
column--;
}
globalsolution.solution.reverse();
}
return globalsolution;
}
function dynSolver(problemId, maxWeight, thingList) {
return fptasSolver(problemId, maxWeight, thingList, 0);
}
function fptas01Solver(problemId, maxWeight, thingList) {
return fptasSolver(problemId, maxWeight, thingList, 0.1);
}
function fptas05Solver(problemId, maxWeight, thingList) {
return fptasSolver(problemId, maxWeight, thingList, 0.5);
}
function fptas09Solver(problemId, maxWeight, thingList) {
return fptasSolver(problemId, maxWeight, thingList, 0.9);
}
function fptas1Solver(problemId, maxWeight, thingList) {
return fptasSolver(problemId, maxWeight, thingList, 1);
}
loadSolveProblems( process.argv[2], [dynSolver, genSolver]);