JSFiddle - React, Tailwind, and code Playground

by stchangg

JavaScript

// print out all possible combinations
// combinations range from 1:length of string
// "21" == "12"

// abc
// a
// b
// c
// ab
// ac
// bc
// abc

// abcd
// abcd + comb(abc) + comb(abd) + comb(acd) + comb(bcd)

function comb( str, included, combinations ) {
  var len = included.length;
  var combination = [];
  var i;
  var numIncluded = 0;
  
  // build the current combination and count number of included
  for ( i=0; i<len; i++ ) {
    if ( included[i] === true ) {
      combination.push( str.charAt(i) );
      numIncluded++;
    }
  }
  
  // base case: size(included) == 0
  if ( numIncluded === 0 ) {
    return;
  
  // print out current combination, using all included letters
  } else {
    combinations[combination.join("")] = true;
  }
    
  // recursive case

  // then, for each of the included letters
  for ( i=0; i<len; i++ ) {
    // set to false
    if ( included[i] === true ) {
      included[i] = false;
      comb( str, included, combinations );
      included[i] = true;
    }
  }
}

function findComb( str ) {
  var included = [];
  var len = str.length;
  
  for ( var i=0; i<len; i++ ) {
    included[i] = true;
  }
  
  var combinations = {};
  comb( str, included, combinations );
  
  Object.print( combinations );
}

Object.print = function( obj ) {
  var key;
  for ( key in obj ) {
    debug( key );
  }
};

function debug( str ) {
  document.write( str + "<br/>" );
}

var str = "abcd";
findComb( str );