×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Zach Gover
Added: Sep 22, 2018 11:55 AM
Modified: Sep 22, 2018 11:59 AM
Views: 3440
  1. /**
  2.  * Retrieve an array of all possible unique orders based on the multiplier count
  3.  * provided in the parameter
  4.  *
  5.  * @param multiplier the amount of variants for each combinations (exponent power)
  6.  * @param combo0 first element to act as 0 (binary)
  7.  * @param combo1 second element to act as 2 (binary)
  8.  *
  9.  * @return array the combinations
  10.  */
  11. function binaryCombos ( multiplier = 2, combo0 = '0', combo1 = '1' ) {
  12.     var combos   = [];
  13.     var exponent = 2;
  14.  
  15.     for ( var i = 0; i < Math.pow( exponent, multiplier ); i++ ) {
  16.         var variants = [];
  17.  
  18.         for ( var x = 0; x < multiplier; x++ ) {
  19.  
  20.             // Shift bit then 'and it' with 1
  21.             if ( ( i >> x ) & 1 ) {
  22.                 variants.push( 1 );
  23.             } else {
  24.                 variants.push( 0 );
  25.             }
  26.         }
  27.  
  28.         combos.push( variants );
  29.     }
  30.  
  31.     return combos;
  32. }
  33.  
  34. var combos = binaryCombos( 3 );
  35.  
  36. /**
  37.  * Output each combo
  38.  *
  39.  * EXMAPLE OUTPUT:      0,0,0 debugger eval code:38:5
  40.  *                              1,0,0 debugger eval code:38:5
  41.  *                              0,1,0 debugger eval code:38:5
  42.  *                              1,1,0 debugger eval code:38:5
  43.  *                              0,0,1 debugger eval code:38:5
  44.  *                              1,0,1 debugger eval code:38:5
  45.  *                              0,1,1 debugger eval code:38:5
  46.  *                              1,1,1 debugger eval code:38:5
  47.  */
  48. for ( var i = 0; i < combos.length; i++ ) {
  49.     console.log( combos[ i ].join( ',' ) );
  50. }