Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript arrays - Finding the number of combinations of 2 elements

I come from a Ruby background, which features an enumerable class. In Ruby, I can easily find combinations of array elements.

array.combination(2).count

I know that JavaScript doesn't feature such built in functions, so I was wondering how I could implement this in JS. I was thinking something like

I have an array as follows

var numbers = [9,7,12]
var combos = []
for (var i = 0; i < numbers.length; i++)  {
  combos.push([numbers[i], numbers[i+1])
}

By the way, the possible combos are

[9,7], [9,12] and [7,12]

so by calling the length function on this array, 3 would be returned.

Any ideas?

like image 299
Josh Winters Avatar asked Mar 20 '15 14:03

Josh Winters


2 Answers

How about:

for (var i = 0; i < numbers.length; i++)
    for (var j = i + 1; j < numbers.length; j++)
        combos.push([numbers[i], numbers[j]]);
like image 123
JuniorCompressor Avatar answered Nov 15 '22 04:11

JuniorCompressor


Are you strictly talking about 2-combinations of the array or are you interested in a k-combinations solution?

Found this in this gist

function k_combinations(set, k) {
var i, j, combs, head, tailcombs;

if (k > set.length || k <= 0) {
    return [];
}

if (k == set.length) {
    return [set];
}

if (k == 1) {
    combs = [];
    for (i = 0; i < set.length; i++) {
        combs.push([set[i]]);
    }
    return combs;
}

// Assert {1 < k < set.length}

combs = [];
for (i = 0; i < set.length - k + 1; i++) {
    head = set.slice(i, i+1);
    tailcombs = k_combinations(set.slice(i + 1), k - 1);
    for (j = 0; j < tailcombs.length; j++) {
        combs.push(head.concat(tailcombs[j]));
    }
}
return combs;
}
like image 38
Cihan Köseoğlu Avatar answered Nov 15 '22 05:11

Cihan Köseoğlu