Last active
March 13, 2020 21:12
-
-
Save panarch/0f514944af3a6bba6edbcc4dc5e4b0a6 to your computer and use it in GitHub Desktop.
[JavaScript] Pick k items over size n array (nCk) - using Generator and flatMap
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
const items = ['Foo', 'Bar', 'Dog', 'Cat', 'Tea']; | |
const indexes = [0, 1, 2, 3, 4]; | |
console.log(''); | |
console.log('-------------------'); | |
console.log('Pick 2 items using flatMap'); | |
const picked = indexes.flatMap(i => | |
indexes | |
.slice(i + 1) | |
.map(j => [items[i], items[j]]) | |
); | |
console.log(picked); | |
console.log('-------------------'); | |
console.log(''); | |
console.log(''); | |
console.log('-------------------'); | |
console.log('Pick 2 items using Generator'); | |
function* genPicker() { | |
for (const i of indexes) { | |
for (const j of indexes.slice(i + 1)) { | |
yield [items[i], items[j]]; | |
} | |
} | |
} | |
console.log([...genPicker()]); | |
console.log('-------------------'); | |
console.log(''); |
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
const items = ['Foo', 'Bar', 'Dog', 'Cat', 'Tea']; | |
const indexes = [0, 1, 2, 3, 4]; | |
console.log(''); | |
console.log('-------------------'); | |
console.log('Pick k items using flatMap (default k is 3)'); | |
function pickByFlatMap(k) { | |
function pick(k, i = 0, v = []) { | |
const sliced = indexes.slice(i); | |
const concat = j => v.concat(items[j]); | |
return ( | |
k === 1 ? | |
sliced.map(j => concat(j)) : | |
sliced.flatMap(j => pick(k - 1, j + 1, concat(j))) | |
); | |
} | |
return pick(k); | |
} | |
console.log(pickByFlatMap(3)); | |
console.log('-------------------'); | |
console.log(''); | |
console.log(''); | |
console.log('-------------------'); | |
console.log('Pick k items using Generator (default k is 3)'); | |
function pickByGenerator(k) { | |
function* pick(k, i = 0, v = []) { | |
for (const j of indexes.slice(i)) { | |
const v2 = v.concat(items[j]); | |
if (k === 1) { | |
yield v2; | |
} else { | |
yield* pick(k - 1, j + 1, v2); | |
} | |
} | |
} | |
return [...pick(k)]; | |
} | |
console.log(pickByGenerator(3)); | |
console.log('-------------------'); | |
console.log(''); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment