So given input = [1, 2, 3] and k=2 this would return:
1 2
1 3
2 1
2 3
3 1
3 2
This is the closest to what I am looking for, but not quite: http://algorithms.tutorialhorizon.com/print-all-combinations-of-subset-of-size-k-from-given-array/
function subsetsOfSize(a, used, startIndex, currentSize, k) {
if (currentSize === k) {
for (var i = 0; i < a.length; i++) {
if (used[i])
console.log(a[i]);
}
console.log('-');
return;
}
if (startIndex === a.length)
return;
used[startIndex] = true;
subsetsOfSize(a, used, startIndex+1, currentSize+1, k);
used[startIndex] = false;
subsetsOfSize(a, used, startIndex+1, currentSize, k);
}
var input = [1,2,3];
subsetsOfSize(input, Array(input.length).fill(false), 0, 0, 2);^ Missing results such as 2 1, 3 1, 3 2, etc.
Secondly, I am not sure if I am naming this problem correctly because solutions to "all combinations of subset of size k" do not give the expected answer.
from Given an array, how to generate all combinations of subset size k?
No comments:
Post a Comment