1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

順列をC#で

Last updated at Posted at 2013-04-25
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        var ps = "0123".Permute(3);
        Console.WriteLine(string.Join(",", ps.Select(x => new string(x.ToArray()))));
    }
}

public static class EnumerableEx
{
    public static IEnumerable<IEnumerable<T>> Dist<T>(this IEnumerable<T> source, T element)
    {
        if (source.Any())
        {
            var head = source.First();
            var tail = source.Skip(1);
            yield return Enumerable.Repeat(element, 1).Concat(source);
            foreach (var source2 in tail.Dist(element))
                yield return Enumerable.Repeat(head, 1).Concat(source2);
        }
        else
        {
            yield return Enumerable.Repeat(element, 1);
        }
    }

    public static IEnumerable<IEnumerable<T>> Permute<T>(this IEnumerable<T> source)
    {
        if (source.Any())
        {
            var head = source.First();
            var tail = source.Skip(1);
            foreach (var source2 in tail.Permute())
                foreach (var source3 in source2.Dist(head))
                    yield return source3;
        }
        else
        {
            yield return Enumerable.Empty<T>();
        }
    }

    public static IEnumerable<IEnumerable<T>> Permute<T>(this IEnumerable<T> source, int c)
    {
        if (c == 0)
        {
            yield return Enumerable.Empty<T>();
        }
        else if (source.Any())
        {
            var head = source.First();
            var tail = source.Skip(1);
            foreach (var source2 in tail.Permute(c))
                yield return source2;
            foreach (var source2 in tail.Permute(c - 1))
                foreach (var source3 in source2.Dist(head))
                    yield return source3;
        }
    }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?