Skip to content

Commit d860624

Browse files
♻️ refactor(knapsackUnboundedGreedy): Extract reusable code.
1 parent 453c64c commit d860624

File tree

4 files changed

+22
-10
lines changed

4 files changed

+22
-10
lines changed

src/Item.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import assert from 'assert';
2+
3+
export default function Item(weight, value) {
4+
assert(weight > 0);
5+
this.w = weight;
6+
this.v = value;
7+
}

src/index.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,31 @@
1+
import Item from './Item';
12
import integerValuesKnapsack from './integerValuesKnapsack';
23
import integerValuesKnapsackUnbounded from './integerValuesKnapsackUnbounded';
34
import integerWeightsKnapsack from './integerWeightsKnapsack';
45
import integerWeightsKnapsackUnbounded from './integerWeightsKnapsackUnbounded';
56
import knapsackApprox from './knapsackApprox';
67
import knapsackUnboundedGreedy from './knapsackUnboundedGreedy';
8+
import orderedByDecreasingUtility from './orderedByDecreasingUtility';
79

810
/* eslint import/no-anonymous-default-export: [2, {"allowObject": true}] */
911
export default {
12+
Item,
1013
integerValuesKnapsack,
1114
integerValuesKnapsackUnbounded,
1215
integerWeightsKnapsack,
1316
integerWeightsKnapsackUnbounded,
1417
knapsackApprox,
1518
knapsackUnboundedGreedy,
19+
orderedByDecreasingUtility,
1620
};
1721

1822
export {
23+
Item,
1924
integerValuesKnapsack,
2025
integerValuesKnapsackUnbounded,
2126
integerWeightsKnapsack,
2227
integerWeightsKnapsackUnbounded,
2328
knapsackApprox,
2429
knapsackUnboundedGreedy,
30+
orderedByDecreasingUtility,
2531
};

src/knapsackUnboundedGreedy.js

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import assert from 'assert';
2-
import {fn, decreasing} from '@aureooms/js-compare';
32
import {map, range, sorted} from '@aureooms/js-itertools';
43

4+
import Item from './Item';
5+
import orderedByDecreasingUtility from './orderedByDecreasingUtility';
6+
57
/**
68
* 1/2-approximation to the unbounded knapsack problem.
79
* Runs in O(n log n) time.
@@ -35,13 +37,4 @@ const subroutine = (W, items) => {
3537
return value;
3638
};
3739

38-
function Item(weight, value) {
39-
assert(weight > 0);
40-
this.w = weight;
41-
this.v = value;
42-
}
43-
44-
const utility = (x) => x.v / x.w;
45-
const orderedByDecreasingUtility = fn(decreasing, utility);
46-
4740
export default knapsackUnboundedGreedy;

src/orderedByDecreasingUtility.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import {fn, decreasing} from '@aureooms/js-compare';
2+
3+
const utility = (x) => x.v / x.w;
4+
const orderedByDecreasingUtility = fn(decreasing, utility);
5+
6+
export default orderedByDecreasingUtility;

0 commit comments

Comments
 (0)