Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jpillora
Last active September 7, 2020 15:52
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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]
Copy link

ghost commented Aug 24, 2013

Error in code (line 10)

"if(!x) return set;" blocks 0
it should be "if(typeof x === 'undefined') return set;"

In general

this is not permutation in lexicographic order. it's an array of all combinations for 0 to all elements.
a lexicographic order permutation for set=[1,2]
with 2 chosen elements should return [[1,2],[2,1]]
for 0 to all elements should return [[],[1],[2],[1,2],[2,1]]

[] should be omitted from results (conceptually -> you never ask for combination of anything for combining nothing)

@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