C#字符串置换 [英] C# String permutation

查看:158
本文介绍了C#字符串置换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有5个字符串,如:一,二,三,四和五个一。我需要得到这些字符串的所有排列。我已经探索所有的互联网资源,但所有的解决方案是如此庞大,这对我来说很难理解它,并将其集成到我的程序。结果
所以,也许你知道任何简单的解决方案如何得到排列。

I have 5 strings, such as: "one", "two", "three", "four", and "five". I need to get all permutations of these strings. I've explored all internet resources, but all solutions are so bulky and it's hard for me to understand it and integrate it to my program.
So, maybe you know any easy solution how to get permutations.

推荐答案

排列是很容易做到的。

/// <summary>
/// Returns all permutations of the input <see cref="IEnumerable{T}"/>.
/// </summary>
/// <param name="source">The list of items to permute.</param>
/// <returns>A collection containing all permutations of the input <see cref="IEnumerable&lt;T&gt;"/>.</returns>
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> source)
{
    if (source == null)
        throw new ArgumentNullException("source");
    // Ensure that the source IEnumerable is evaluated only once
    return permutations(source.ToArray());
}

private static IEnumerable<IEnumerable<T>> permutations<T>(IEnumerable<T> source)
{
    var c = source.Count();
    if (c == 1)
        yield return source;
    else
        for (int i = 0; i < c; i++)
            foreach (var p in permutations(source.Take(i).Concat(source.Skip(i + 1))))
                yield return source.Skip(i).Take(1).Concat(p);
}

这篇关于C#字符串置换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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