简体   繁体   中英

How to get all the combinations for an array of a specific length

Let's say I have this array of characters I want to use:

var acceptableCharacters = ['a','b','c','d'];

I'd like to get all possible combinations of this array, say from a length of 2 to 4 , so the output might look something like this

aa
ab
ac
ad
ba
bb
bc
bd
ca
cb
cc
cd
da
db
dc
dd

...And so on...

The generator should be able to meet these conditions:

  • Aims for all combinations between 2 lengths, or allows itself to accept any different length
  • Letters can repeat themself

I'm not really sure where to start, so some starter code would be nice.

edit:

    var characters = ['a','b','c','d'];
    var combinations = [];
    for(var i=2;i<=4;i++) {
        var str = "";
        for(var c of characters) {
            str+=c;
            // 'a' spam
        }
        combinations.push(str);
    };
    console.log( combinations );

I don't know how to iterate the characters ¯_(ツ)_/¯

It looks like this:

ab
abc
abcd

The issue I see with your code is that you need a nested loop for each additional combination length, ie for length 2 you need a double-nested iteration, for length 3 a triple-nested iteration, and so on.

Took a stab at an implementation using recursion. It recurses down to the base case of length 1 and builds up the result set.

 const characters = ["a", "b", "c", "d"]; const combinations = (arr, min = 1, max) => { const combination = (arr, depth) => { if (depth === 1) { return arr; } else { const result = combination(arr, depth - 1).flatMap((val) => arr.map((char) => val + char) ); return arr.concat(result); } }; return combination(arr, max).filter((val) => val.length >= min); }; const result = combinations(characters, 2, 4); console.log(`Combinations: ${result.length}`, result);

Here's a non-recursive version; it ended up being a bit simpler.

 const characters = ["a", "b", "c", "d"]; const combinations = (arr, min = 1, max) => [...Array(max).keys()].reduce( (result) => arr.concat(result.flatMap((val) => arr.map((char) => val + char))), [] ).filter((val) => val.length >= min); const result = combinations(characters, 2, 4); console.log(`Combinations: ${result.length}`, result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM