Skip to content

Instantly share code, notes, and snippets.

@StevePotter
Last active March 15, 2019 15:36
Show Gist options
  • Save StevePotter/e7e263431f4097fc79d04da50225948a to your computer and use it in GitHub Desktop.
Save StevePotter/e7e263431f4097fc79d04da50225948a to your computer and use it in GitHub Desktop.
Problem is: calculate all subsets of a given set. Like [1,2,3] will give [[1,2], [1,3], [2,3], [1,2,3]]
/*
Takes an array of indices within a set and increments them one
position, returning null if it cannot be incremented.
Example: if a set has 4 elements:
[0,1] -> [0,2]
[0,3] -> [1,2]
[1,2] -> [1,3]
[2,3] -> null
*/
const incrementPosition = (indices, indexToIncrement, maxIndex) => {
const newIndices = [...indices]
newIndices[indexToIncrement]++
// bump subsequent positions
for(let currOrdinal = indexToIncrement + 1; currOrdinal < indices.length; currOrdinal++) {
newIndices[currOrdinal] = newIndices[currOrdinal - 1] + 1
}
let isValid = true
for (const currIndex of newIndices) {
if (currIndex > maxIndex) {
isValid = false
}
}
if (isValid) return newIndices
if (indexToIncrement === 0) {
return null
}
return incrementPosition(indices, indexToIncrement - 1, maxIndex)
}
/*
Gets all possible subsets of a set.
*/
const subsets = (set) => {
const subsets = []
for (let subSetSize = 1; subSetSize < set.length; subSetSize++ ) {
let indices = []
for(let i = 0; i < subSetSize; i++) {
indices.push(i)
}
while (indices) {
const subset = indices.map((index) => set[index])
subsets.push(subset)
indices = incrementPosition(indices, indices.length - 1, set.length - 1)
}
}
return subsets
}
// use it right now: https://repl.it/repls/LimeJubilantDeprecatedsoftware
console.log(subsets([9, 21, 3, 2, 5, 11]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment