Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2cfac1b

Browse files
an additional test case
1 parent b73ef69 commit 2cfac1b

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

‎src/algorithms/knapsack-fractional.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
// tag::snippet[]
2+
/**
3+
*
4+
* @param {Array} input array of objects with the shape {value, weight}
5+
* @param {Number} max maximum weight for knapsack
6+
*/
27
function solveFractionalKnapsack(input, max) {
38
let weight = 0;
49
let value = 0;

‎src/algorithms/knapsack-fractional.spec.js‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,4 +64,24 @@ describe('solveFractionalKnapsack', () => {
6464
expect(knapsack.weight).toBeCloseTo(1);
6565
expect(knapsack.value).toBeCloseTo(1);
6666
});
67+
68+
it('should solve take fractional items with non-integer max weight', () => {
69+
const maxWeight = 7.5;
70+
const items = [
71+
{ value: 1, weight: 1 },
72+
{ value: 4, weight: 3 },
73+
{ value: 5, weight: 4 },
74+
{ value: 7, weight: 5 },
75+
];
76+
77+
const knapsack = solveFractionalKnapsack(items, maxWeight);
78+
79+
expect(knapsack.weight).toBeCloseTo(7.5);
80+
expect(knapsack.value).toBeCloseTo(7 + ((2.5 / 3) * 4));
81+
expect(knapsack.items.length).toEqual(2);
82+
expect(knapsack.items).toEqual(expect.arrayContaining([
83+
{ value: 7, weight: 5, proportion: 1 },
84+
{ value: 4, weight: 3, proportion: (2.5 / 3) },
85+
]));
86+
});
6787
});

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /