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 allCombs( str ) {
var remaining = str.split("");
var numCalls = { value: 0 };
var combos = comb( "", remaining, {}, numCalls );
Object.print(combos);
debug(numCalls.value);
}
function comb( curr, remaining, combinations, numCalls ) {
numCalls.value++;
var len = remaining.length;
if ( len === 0 ) {
combinations[curr] = true;
return;
}
var char = remaining.shift();
// include the character
comb( curr.concat(char), remaining, combinations, numCalls);
// don't include the character
comb( curr, remaining, combinations, numCalls );
remaining.push(char);
return combinations;
}
// helper methods
Object.size = function ( obj ) {
var key, size = 0;
for ( key in obj ) {
if (obj.hasOwnProperty(key)) size ++;
}
return size;
};
Object.print = function( obj ) {
var key, count=0;
for ( key in obj ) {
debug( key );
count++;
}
debug( count );
};
function debug( str ) {
document.write( str + "<br/>" );
}
// execute
var str = "abcde";
allCombs( str );