Listing permutations of different combination of characters

后端 未结 2 1159
孤独总比滥情好
孤独总比滥情好 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:45

    If the length is fixed you could use this simple query which creates a cartesian product:

    string chars = "ab";
    int[] digits = { 1, 2 };
    var query = from c1 in chars 
                from c2 in chars 
                from d1 in digits 
                select string.Format("{0}{1}{2}", c1, c2, d1);
    string[] possibleCombinations = query.ToArray();
    

    Result:

    aa1
    aa2
    ab1
    ab2
    ba1
    ba2
    bb1
    bb2
    

    Edit: For what it's worth, lambda as requested(query syntax is much more readable):

    possibleCombinations = chars
        .SelectMany(c1 => chars
            .SelectMany(c2 => digits
                .Select(d1 => string.Format("{0}{1}{2}", c1, c2, d1))))
        .ToArray();
    

    If you need an approach which handles a dynamic length you could have a look at this:

    Dynamic Generation of All Possible Combinations of Index of an Array

提交回复
热议问题