-
Notifications
You must be signed in to change notification settings - Fork 0
/
fluids2.js
40 lines (30 loc) · 985 Bytes
/
fluids2.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
const getCombinations = (volume, containers) => {
const combinations = [];
const combine = (array, carry = []) => {
for (let i = 0; i < array.length; i++) {
const root = array[i];
const nodes = [...array.slice(i, i), ...array.slice(i + 1)];
const nextCarry = [...carry, root];
if (nextCarry.reduce((a, b) => a + b, 0) === volume) {
combinations.push(nextCarry);
}
combine(nodes, nextCarry);
}
};
combine(containers, []);
return combinations;
};
const fluids = (volume, containers) => {
containers = containers
.split('\n')
.map((x) => parseInt(x))
.sort((a, b) => b - a);
const combinationLengths = getCombinations(volume, containers)
.map((combination) => combination.length);
const minimum = Math.min(...combinationLengths);
const minimumCombinations = combinationLengths
.filter((length) => length === minimum)
.length;
return minimumCombinations;
};
module.exports = fluids;