How to get all the possible 3 letter permutations? [duplicate]

会有一股神秘感。 提交于 2019-11-27 07:01:36

For a variable amount of letter combinations, you can do the following:

var alphabet = "abcdefghijklmnopqrstuvwxyz";
var q = alphabet.Select(x => x.ToString());
int size = 4;
for (int i = 0; i < size - 1; i++)
    q = q.SelectMany(x => alphabet, (x, y) => x + y);

foreach (var item in q)
    Console.WriteLine(item);
var alphabet = "abcdefghijklmnopqrstuvwxyz";
//or var alphabet = Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (char)i);

var query = from a in alphabet
            from b in alphabet
            from c in alphabet
            select "" + a + b + c;

foreach (var item in query)
{
    Console.WriteLine(item);
}

__EDIT__

For a general solution, you can use the CartesianProduct here

int N = 4;
var result = Enumerable.Range(0, N).Select(_ => alphabet).CartesianProduct();
foreach (var item in result)
{
    Console.WriteLine(String.Join("",item));
}

// Eric Lippert’s Blog
// Computing a Cartesian Product with LINQ
// http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
    // base case: 
    IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() };
    foreach (var sequence in sequences)
    {
        var s = sequence; // don't close over the loop variable 
        // recursive case: use SelectMany to build the new product out of the old one 
        result =
            from seq in result
            from item in s
            select seq.Concat(new[] { item });
    }
    return result;
}

Here's a very simple solution:

for(char first = 'a'; first <= (int)'z'; first++)
    for(char second = 'a'; second <= (int)'z'; second++)
        for(char third = 'a'; third <= (int)'z'; third++)
            Console.WriteLine(first.ToString() + second + third);

You have 26^3 counts for 3 "digits". Just iterate from 'a' to 'z' in three loops.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!