【问题标题】:Find All Possible Permutations In Certain Range C#查找特定范围内所有可能的排列 C#
【发布时间】:2015-09-30 21:58:43
【问题描述】:

我想编写一个程序来从雅虎财经中查找所有有效的股票代码,我已经找到了这个:Quickest way to enumerate the alphabet 但是,我不希望它从 A - Z 开始,然后是 AA - AZ,然后是 ABA - ABZ 等等。做这个的最好方式是什么?更清楚的例子:A B C D 等。 AA AB AC AD 等。 ABA ABB ABC ABD 等。

【问题讨论】:

标签: c# permutation stocks


【解决方案1】:

使用 Eric Lippert 的Cartesian Product

var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int maxlen = 3;

var query = Enumerable.Range(1, maxlen)
            .SelectMany(i => Enumerable.Repeat(chars, i)
                             .CartesianProduct()
                             .Select(x => String.Concat(x)));


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

PS:只是为了完整性:

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;
}

【讨论】:

    【解决方案2】:

    不确定它有多快,但当我需要做类似的事情时,我做了以下事情:

            for (int i = 0; i < numCols && i < 26; i++)
            {
                char start = 'A';
                char colChar = (char)(start + (char)(i));
                Console.WriteLine(string.Format("{0}", colChar), typeof(string));
            }
            for (int i = 26; i < 52 && i < numCols; i++)
            {
                char start = 'A';
                char colChar = (char)(start + (char)(i-26));
                Console.WriteLine(string.Format("A{0}", colChar), typeof(string));
            }
    

    第二个 for 循环显然只返回 AA 到 AZ,但如果你把它放在一个函数中,将第一个 A 作为输入,那么你可以循环遍历 A-Z 的第一个字符,你就会得到所有两个字符的结果.创建带有 2 个字符输入作为前面的字符串的第三个函数将为您提供三个字符集。

    26*26*26 是很多输出,但上面的模式应该会为您提供。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      相关资源
      最近更新 更多