0

Consider this code which generates all combinations of items in a list (in this case characters in a string):

function combinations(str) {
    var fn = function(active, rest, a) {
        if (!active && !rest)
            return;
        if (!rest) {
            a.push(active);
        } else {
            fn(active + rest[0], rest.slice(1), a);
            fn(active, rest.slice(1), a);
        }
        return a;
    }
    return fn("", str, []);
}

console.log(combinations("abcd")) // => ["abcd", "abc", "abd", "ab", "acd", "ac", "ad", "a", "bcd", "bc", "bd", "b", "cd", "c", "d"]

The output above includes characters not in (continuous) sequential order, for example "abd" never occurs sequentially in the input string.

What if instead I want to generate every sequential range within a string? (or array of items, doesn't matter to me)

so that (order of the output doesn't matter):

console.log(combinations("abcd")) // => ["a", "b", "ab", "c", "bc", "abc", "d", "cd", "bcd", "abcd"]
J.Todd
  • 517
  • 1
  • 8
  • 28

0 Answers0