|
| 1 | +import test from 'ava'; |
| 2 | + |
| 3 | +import {all, map} from '@aureooms/js-itertools'; |
| 4 | + |
| 5 | +import { |
| 6 | + integerValuesKnapsack, |
| 7 | + integerWeightsKnapsack, |
| 8 | +} from '../../src'; |
| 9 | + |
| 10 | +const macro = (t, solve, _name, v, w, n, W, opt, approx) => { |
| 11 | + t.is(n, v.length); |
| 12 | + t.is(n, w.length); |
| 13 | + const result = solve(v, w, n, W); |
| 14 | + if (approx === undefined) { |
| 15 | + t.is(opt, result); |
| 16 | + } else { |
| 17 | + t.true(result >= approx * opt); |
| 18 | + } |
| 19 | +}; |
| 20 | + |
| 21 | +macro.title = (title, solve, name, v, w, n, W, opt, approx) => |
| 22 | + title |
| 23 | + ? `${title} (${name || solve.name})` |
| 24 | + : approx === undefined |
| 25 | + ? `${name || solve.name}(${JSON.stringify(v)}, ${JSON.stringify( |
| 26 | + w, |
| 27 | + )}, ${n}, ${W}) = ${opt}` |
| 28 | + : `${name || solve.name}(${JSON.stringify(v)}, ${JSON.stringify( |
| 29 | + w, |
| 30 | + )}, ${n}, ${W}) >= ${approx} * ${opt}`; |
| 31 | + |
| 32 | +const solvers = [ |
| 33 | + { |
| 34 | + solve: integerValuesKnapsack, |
| 35 | + hypothesis: (v) => all(map((x) => Number.isInteger(x), v)), |
| 36 | + }, |
| 37 | + { |
| 38 | + solve: integerWeightsKnapsack, |
| 39 | + hypothesis: (_, w) => all(map((x) => Number.isInteger(x), w)), |
| 40 | + }, |
| 41 | +]; |
| 42 | + |
| 43 | +const instances = [ |
| 44 | + { |
| 45 | + title: 'wikipedia 0-1 knapsack example', |
| 46 | + v: [505, 352, 458, 220, 354, 414, 498, 545, 473, 543], |
| 47 | + w: [23, 26, 20, 18, 32, 27, 29, 26, 30, 27], |
| 48 | + n: 10, |
| 49 | + W: 67, |
| 50 | + opt: 1270, |
| 51 | + }, |
| 52 | + { |
| 53 | + title: 'https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10', |
| 54 | + v: [60, 100, 120], |
| 55 | + w: [10, 20, 30], |
| 56 | + n: 3, |
| 57 | + W: 50, |
| 58 | + opt: 220, |
| 59 | + }, |
| 60 | +]; |
| 61 | + |
| 62 | +for (const {title, v, w, n, W, opt} of instances) { |
| 63 | + for (const {solve, name, hypothesis, approx} of solvers) { |
| 64 | + if (!hypothesis || hypothesis(v, w, n, W)) { |
| 65 | + test(title, macro, solve, name, v, w, n, W, opt, approx); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments