Skip to content

Instantly share code, notes, and snippets.

@sergiks
Created April 27, 2015 18:00
Show Gist options
  • Save sergiks/81575a176311d0cb3a9b to your computer and use it in GitHub Desktop.
Save sergiks/81575a176311d0cb3a9b to your computer and use it in GitHub Desktop.
All combinations of at least two array elements
/**
* Test to figure out combinations of at least two elements of provided array.
*
* by Sergei Sokolov, hello@sergeisokolov.com, 2015 April 27, St. Petersburg.
* Fiddle: http://jsfiddle.net/sergiks/2ojgqxk1/
*/
function comb(a) {
var l, cursor, mask, tail, out=[];
l = a.length;
if( l<2 || l>32) {
console.error('Array should be at least 2, at max 32 elements. Provided is '+l+'-long. Fail.');
return;
}
$('body').append( $('<div class="b-src">Source: [' + a.join(', ') + ']</div>'));
for( cursor=0; cursor<l-1; cursor++) { // cursor points to the first element of any combi
tail = Math.pow( 2, l-cursor-1); // 1 + max value of "the rest" after the cursor
for( mask=1; mask<tail; mask++) { // at least 1-bit-on mask to the tail: [01, 10, 11] for tail=4
// mask indicates which additional elements to pick
// mask to offset (cursor + 1)
bit = 0x1; // test each bit of mask, if
combi = [ a[cursor]];
for( b=0; b<tail; b++) {
if( bit & mask) combi.push( a[ b+cursor+1]);
bit = bit << 1;
}
out.push( combi);
$('body').append( $('<div>' + combi.join(', ') + '</div>'));
}
}
return out;
}
comb( [0,1,2,3]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment