Created
April 27, 2015 18:00
-
-
Save sergiks/81575a176311d0cb3a9b to your computer and use it in GitHub Desktop.
All combinations of at least two array elements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Test to figure out combinations of at least two elements of provided array. | |
* | |
* by Sergei Sokolov, [email protected], 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