Thursday, April 25, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  123] [ 4]  / answers: 1 / hits: 52976  / 13 Years ago, fri, april 22, 2011, 12:00:00

I need to get all possible subsets of an array with a minimum of 2 items and an unknown maximum. Anyone that can help me out a bit?


Say I have the following array:


[1, 2, 3]

How do I get this?


[
[1, 2],
[1, 3],
[2, 3],
[1, 2, 3]
]

More From » arrays

 Answers
37

After stealing this JavaScript combination generator, I added a parameter to supply the minimum length resulting in,



var combine = function(a, min) {
var fn = function(n, src, got, all) {
if (n == 0) {
if (got.length > 0) {
all[all.length] = got;
}
return;
}
for (var j = 0; j < src.length; j++) {
fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all);
}
return;
}
var all = [];
for (var i = min; i < a.length; i++) {
fn(i, a, [], all);
}
all.push(a);
return all;
}


To use, supply an array, and the minimum subset length desired,



var subsets = combine([1, 2, 3], 2);


Output is,



[[1, 2], [1, 3], [2, 3], [1, 2, 3]]

[#92613] Wednesday, April 20, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rhett

Total Points: 671
Total Questions: 100
Total Answers: 102

Location: Hong Kong
Member since Tue, Oct 19, 2021
3 Years ago
rhett questions
Thu, Oct 28, 21, 00:00, 3 Years ago
Mon, Aug 2, 21, 00:00, 3 Years ago
Fri, Dec 11, 20, 00:00, 3 Years ago
Fri, Aug 7, 20, 00:00, 4 Years ago
Thu, Mar 26, 20, 00:00, 4 Years ago
;