Created
August 8, 2018 18:01
-
-
Save denchistyakov/ef21fc25e6bb5bdaefe6ec038cb45472 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function next_combination(a, n) { | |
let k = a.length; | |
for (let i = k - 1; i>= 0; --i) { | |
if (a[i] < n - k + i + 1) { | |
++a[i]; | |
for (let j = i + 1; j < k; ++j) { | |
a[j] = a[j - 1] + 1; | |
} | |
return true; | |
} | |
} | |
return false; | |
} | |
function chooseBestSum2(t, k, ls) { | |
let acc = []; | |
for (let i = 0; i < k; i++) { | |
acc.push(i); | |
} | |
let result = [acc.slice()]; | |
while (next_combination(acc, ls.length - 1)) { | |
result.push(acc.slice()); | |
} | |
const maxTravel = result | |
.reduce((acc, item) => { | |
acc.push(item.map(idx => ls[idx]).reduce((acc, item) => acc += item)); | |
return acc; | |
}, []) | |
.filter(sum => sum <= t) | |
.reduce((acc, sum) => { | |
if (sum > acc) { | |
acc = sum; | |
} | |
return acc; | |
}, 0); | |
return (maxTravel === 0) ? null : maxTravel; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment