Skip to content

Instantly share code, notes, and snippets.

@dead-claudia
Created October 23, 2017 15:49
Show Gist options
  • Save dead-claudia/38fa928ae25d80b79ad032a57c9f3090 to your computer and use it in GitHub Desktop.
Save dead-claudia/38fa928ae25d80b79ad032a57c9f3090 to your computer and use it in GitHub Desktop.
Permutation of array and its subsets with repetition
// Note: this uses generators exclusively to avoid blowing up your RAM - 10-item
// arrays will produce about 11 billion entries. You can use
// `repeatedPermutationWithSubsetsCount` with the length to see how many items
// will be produced.
function *permRep(array, data, index) {
if (index === data.length) {
yield data.slice()
} else {
for (let i = 0; i < array.length; i++) {
data[index] = array[i]
yield* permRep(array, data, index + 1)
}
}
}
function *repeatedPermutationWithSubsets(array) {
const data = []
for (let i = 0; i < array.length; i++) {
yield* permRep(array, data, 0)
data.push(undefined)
}
yield* permRep(array, data, 0)
}
// Note:
// l+1
// l k l - 1
// ∑ l = ---------- , where l = `length`
// k=0 l - 1
function repeatedPermutationWithSubsetsCount(length) {
return (Math.pow(length, length + 1) - 1) / (length - 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment