Skip to content

Instantly share code, notes, and snippets.

@jpillora
Last active September 7, 2020 15:52
Show Gist options
  • Save jpillora/4435759 to your computer and use it in GitHub Desktop.
Save jpillora/4435759 to your computer and use it in GitHub Desktop.
Array/String combinations in JavaScript
//Explaination:
// start with the empty set
// extract the head element
// copy each element in the set with the current head element appended
// recurse
var combinations = function(set) {
return (function acc(xs, set) {
var x = xs[0];
if(typeof x === "undefined")
return set;
for(var i = 0, l = set.length; i < l; ++i)
set.push(set[i].concat(x));
return acc(xs.slice(1), set);
})(set, [[]]).slice(1);
};
//works with arrays
show(combinations([0,1,2,3,4]));
//and strings
show(combinations("abcd"));
function show(arr) {
arr.forEach(function(p) {
console.log("["+p.join(",")+"]");
});
}
// Outputs:
// [0]
// [1]
// [0,1]
// [2]
// [0,2]
// [1,2]
// [0,1,2]
// [3]
// [0,3]
// [1,3]
// [0,1,3]
// [2,3]
// [0,2,3]
// [1,2,3]
// [0,1,2,3]
//
// [a]
// [b]
// [a,b]
// [c]
// [a,c]
// [b,c]
// [a,b,c]
// [d]
// [a,d]
// [b,d]
// [a,b,d]
// [c,d]
// [a,c,d]
// [b,c,d]
// [a,b,c,d]
@jpillora
Copy link
Author

Fixed

@foluis
Copy link

foluis commented Aug 5, 2016

Input: "ababb"
Output: Should include "abbba" or "babab". Also result repeat items

@harshalyeole-tudip
Copy link

harshalyeole-tudip commented Nov 24, 2016

Is there any way I can use this on an array of strings instead of a single string?
Input : [ "aaa", "bbb", "ccc" ]
output: ["aaa", "bbb", "ccc", "aaa bbb", "aaa ccc, "bbb ccc", "aaa bbb ccc"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment