如何使用yield return和recursion获得字母的每种组合? [英] How do I get every combination of letters using yield return and recursion?

查看:200
本文介绍了如何使用yield return和recursion获得字母的每种组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个类似的字符串列表,可能有几十个列表:

I have several lists of strings like so, from a possible list of several dozen:

1: { "A", "B", "C" }
2: { "1", "2", "3" }
3: { "D", "E", "F" }

这三个仅作为示例,用户可以从几十个具有不同数量元素的相似列表中进行选择.再举一个例子,对于用户来说,这也是一个非常有效的选择:

These three were only picked as an example, and the user can pick from several dozen similar lists with varying number of elements. For another example, this is also a perfectly valid selection for a user:

25: { } // empty
 4: { "%", "!", "$", "@" }
16: { "I", "a", "b", "Y" }
 8: { ")", "z", "!", "8" }

我想做的是在保持列表的顺序"的同时,尽可能地使用字符串的所有组合.换句话说,假设我们正在查看第一个列表,则第一个组合将是A1D,然后是A1E,然后是A1F,然后是B1D,然后是B1E,依此类推.到目前为止,我已经编写了此递归算法:

What I want to do is get every combination of strings possible while keeping the 'order' of the lists. In other words, assuming we're looking at the first list, the first combination will be A1D, then A1E, then A1F, then B1D, then B1E, and so on and so forth. So far I've written this recursive algorithm:

public void Tester()
{
    var 2dList = new List { list1, list2, list3 };
    var answer = ReturnString(2dList).ToList();

    answer.ForEach(Console.WriteLine);
}

public IEnumerable<string> ReturnString(List<List<string>> list)
{
    if (!list.Any())
    {
        yield return null;
    }
    else
    {
        // for each letter in the top-most list...
        foreach (var letter in list.First())
        {
            // get the remaining lists minus the first one
            var nextList = list.Where(x => x != list.First()).ToList();

            // get the letter and recurse down to find the next
            yield return letter + ReturnString(nextList);
        }
    }
}

但是,我得到的却是:

AStringGeneration.StringGenerator+<ReturnString>d__11
BStringGeneration.StringGenerator+<ReturnString>d__11
CStringGeneration.StringGenerator+<ReturnString>d__11

StringGenerationReturnString所在类的名称.当我在yield return letter + ...行上放置断点时,它似乎遍历ABC,但是实际上并不递归.我不确定这是怎么回事.谁能解释我的算法出了什么问题?

StringGeneration is the name of the class that ReturnString is in. When I put a breakpoint on the yield return letter + ... line, it seems to iterate through A, B, and C, but doesn't actually recurse. I'm not sure what's going on here. Can anyone explain what is wrong with my algorithm?

推荐答案

您需要枚举迭代器:

foreach(string s in ReturnString(...)) {
    Console.WriteLine(s);
}

这也适用于每次迭代:

foreach(string tail in ReturnString(nextList))
    yield return letter + tail;

此外,我怀疑您可以在此处使用SelectMany进行某些操作.

Also, I suspect you can do something with SelectMany here.

这篇关于如何使用yield return和recursion获得字母的每种组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆