What's a good way for figuring out all possible words of a given length

后端 未结 12 1804
一生所求
一生所求 2021-02-04 17:27

I\'m trying to create an algorithm in C# which produces the following output strings:

AAAA
AAAB
AAAC
...and so on...
ZZZX
ZZZY
ZZZZ

What is the

12条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-04 17:57

    well, if the length is a constant 4, then this would handle it:

    public static IEnumerable GetWords()
    {
        for (Char c1 = 'A'; c1 <= 'Z'; c1++)
        {
            for (Char c2 = 'A'; c2 <= 'Z'; c2++)
            {
                for (Char c3 = 'A'; c3 <= 'Z'; c3++)
                {
                    for (Char c4 = 'A'; c4 <= 'Z'; c4++)
                    {
                        yield return "" + c1 + c2 + c3 + c4;
                    }
                }
            }
        }
    }
    

    if the length is a parameter, this recursive solution would handle it:

    public static IEnumerable GetWords(Int32 length)
    {
        if (length <= 0)
            yield break;
    
        for (Char c = 'A'; c <= 'Z'; c++)
        {
            if (length > 1)
            {
                foreach (String restWord in GetWords(length - 1))
                    yield return c + restWord;
            }
            else
                yield return "" + c;
        }
    }
    

提交回复
热议问题