Given a Set
, generate all subsets of length n.
Sample input:
set = new Set(['a', 'b', 'c']), length = 2
Sample output:
Set {'a', 'b'}, Set {'a', 'c'}, Set {'b', 'c'}
How to do this efficiently, without converting the Set
to an Array
?
I already have a good solution for arrays as input:
function* subsets(array, length, start = 0) {
if (start >= array.length || length < 1) {
yield new Set();
} else {
while (start <= array.length - length) {
let first = array[start];
for (subset of subsets(array, length - 1, start + 1)) {
subset.add(first);
yield subset;
}
++start;
}
}
}
let array = ['a', 'b', 'c', 'd'];
for (subset of subsets(array, 2)) {
console.log(...subset);
}
However, I couldn't come up with an efficient implementation for sets without converting the set to an array - wich I would like to avoid in favour of e.g. purely using iterators.