Expand file tree Collapse file tree 2 files changed +25
-0
lines changed Original file line number Diff line number Diff line change 1
1
// 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
+ */
2
7
function solveFractionalKnapsack ( input , max ) {
3
8
let weight = 0 ;
4
9
let value = 0 ;
Original file line number Diff line number Diff line change @@ -64,4 +64,24 @@ describe('solveFractionalKnapsack', () => {
64
64
expect ( knapsack . weight ) . toBeCloseTo ( 1 ) ;
65
65
expect ( knapsack . value ) . toBeCloseTo ( 1 ) ;
66
66
} ) ;
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
+ } ) ;
67
87
} ) ;
0 commit comments