-2

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 a string?

An example: I specify a string length of "3". The first two position should be either "a" or "b", but the last position should be either "1" or "2", e.g:

aa1
ba1
ab1
bb1
aa2
ab2
ba2
bb2
Community
  • 1
  • 1
filur
  • 2,116
  • 6
  • 24
  • 47

2 Answers2

2

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

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Thank you. Just out of curiosity, could you show me the solution using lambda instead of linq? – filur Jan 27 '15 at 14:59
  • 1
    @filur: i've added method syntax. – Tim Schmelter Jan 27 '15 at 15:09
  • FWIW, `chars.SelectMany(c1 => chars, (c1, c2) => new { c1, c2 }).SelectMany(τ0 => digits, (τ0, d1) => string.Format("{0}{1}{2}", τ0.c1, τ0.c2, d1))` is the slightly-nicer (hah) lambda translation that the compiler will make. – Rawling Jan 27 '15 at 15:26
2

Use this code:

public static List<string> GenerateCombinations(char[][] characters)
{
    var combinations = new List<string>();
    GenerateCombinations(0, characters, new char[characters.GetLength(0)], combinations);
    return combinations;
}

private static void GenerateCombinations(int level, char[][] characters, char[] current, List<string> 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
Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123