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.
Set
, wouldn't it be nice if we could just work on the givenSet
instead of copying all its elements to anArray
first? I suppose iterating through sets is fast or will be fast in the future, faster than first converting everything to an array and iterating that instead. And it will always be more space efficient. – Sherillsherilyn