C# String permutation

后端 未结 6 856
一个人的身影
一个人的身影 2020-12-11 07:27

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 a

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-11 08:24

    Permutations are very easy to do.

    /// 
    /// Returns all permutations of the input .
    /// 
    /// The list of items to permute.
    /// A collection containing all permutations of the input .
    public static IEnumerable> Permutations(this IEnumerable source)
    {
        if (source == null)
            throw new ArgumentNullException("source");
        // Ensure that the source IEnumerable is evaluated only once
        return permutations(source.ToArray());
    }
    
    private static IEnumerable> permutations(IEnumerable 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);
    }
    

提交回复
热议问题