Skip to content

Instantly share code, notes, and snippets.

@venkatperi
Last active September 22, 2019 03:20
Show Gist options
  • Save venkatperi/8ac5f995028ee9b5877b2cf95ae521cb to your computer and use it in GitHub Desktop.
Save venkatperi/8ac5f995028ee9b5877b2cf95ae521cb to your computer and use it in GitHub Desktop.
/**
* Given an array of size 'n' and a number 'r' (r <= n), this generator returns all
* nCr permutation subarrays of the array.
*
* @param arr - array
* @param r number
*/
function* permutations(arr, r, prefix = []) {
for (let i = 0; i < arr.length - r + 1; i++) {
let x = [...prefix, arr[i]]
if (r > 1)
yield* permutations(arr.slice(i + 1), r - 1, x)
else
yield x
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment