Last active
September 7, 2020 15:52
-
-
Save jpillora/4435759 to your computer and use it in GitHub Desktop.
Array/String combinations in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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] |
Input: "ababb"
Output: Should include "abbba" or "babab". Also result repeat items
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
Fixed