Listing permutations of different combination of characters

后端 未结 2 1185
孤独总比滥情好
孤独总比滥情好 2021-01-29 12:49

The closest SO topic I found is here: Listing all permutations of a string/integer

But how would I make use of this for different sets of characters for each position in

2条回答
  •  情深已故
    2021-01-29 13:20

    Use this code:

    public static List GenerateCombinations(char[][] characters)
    {
        var combinations = new List();
        GenerateCombinations(0, characters, new char[characters.GetLength(0)], combinations);
        return combinations;
    }
    
    private static void GenerateCombinations(int level, char[][] characters, char[] current, List combinations)
    {
        if (level == characters.GetLength(0))
        {
            combinations.Add(new string(current));
            return;
        }
    
        foreach (var character in characters[level])
        {
            current[level] = character;
            GenerateCombinations(level + 1, characters, current, combinations);
        }
    }
    

    Example of using it:

    public static void Main()
    {
        var characters = new[]
                         {
                             new[] { 'a', 'b' },
                             new[] { 'a', 'b' },
                             new[] { '1', '2' }
                         };
    
        var combinations = GenerateCombinations(characters);
        foreach (var combination in combinations)
        {
            Console.WriteLine(combination);
        }
    }
    

    Output:

    aa1
    aa2
    ab1
    ab2
    ba1
    ba2
    bb1
    bb2
    

提交回复
热议问题