Home > Enterprise >  Algorithm to get possible combinations
Algorithm to get possible combinations

Time:10-07

I need an algorithm to get all the possible combinations for 2 characters, in a sequence of 3 characters

Input

caractersAllowed[2] = [A,B]
sequenceTable[3] = [0,0,0]

Output

[A,A,A]
[A,A,B]
[A,B,A]
[A,B,B]
[B,A,A]
[B,A,B]
[B,B,B]

CodePudding user response:

A simple recursion should do the job:

rec(chars, current_word, size){
    if(size == 0) print(current_word);
    else{
        foreach char c in chars{
            rec(chars, current_word   c, size - 1)
        }
    }
}

Then, you just need to call rec([A,B], "", 3).

  • Related