コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】配列やリストから組合せを取得できる拡張メソッド

はじめに

上記サイト様が、リストから組み合わせを取得できる関数を公開されております
こちらを少し修正して、配列やリストから組合せを取得できる拡張メソッドを作りました

ソースコード

using System.Collections.Generic;
using System.Linq;

public static class IListExt
{
    public static IEnumerable<List<T>> Combination<T>( this IList<T> self, int n )
    {
        return Enumerable.Range( 0, n - 1 )
            .Aggregate(
                Enumerable.Range( 0, self.Count - n + 1 )
                    .Select( num => new List<int> { num } ),
                ( list, _ ) => list.SelectMany(
                    c =>
                        Enumerable.Range( c.Max() + 1, self.Count - c.Max() - 1 )
                            .Select( num => new List<int>( c ) { num } )
                )
            )
            .Select(
                c => c
                    .Select( num => self[ num ] )
                    .ToList()
            );
    }
}

使用例

using System;
using System.Linq;
using System.Text;

public static class Program
{
    private static void Main()
    {
        var array = new[] { 1, 2, 3, 4, 5 };
        var results = array
                .Combination( 3 )
                .ToArray()
            ;

        Console.WriteLine( "組合せの数:" + results.Length );
        Console.WriteLine();

        foreach ( var result in results )
        {
            var sb = new StringBuilder();

            foreach ( var n in result )
            {
                sb.Append( $"{n}, " );
            }

            Console.WriteLine( sb );
        }
    }
}
組合せの数:10

1, 2, 3,
1, 2, 4,
1, 2, 5,
1, 3, 4,
1, 3, 5,
1, 4, 5,
2, 3, 4,
2, 3, 5,
2, 4, 5,
3, 4, 5,

組合せの数が正しいかどうかは下記のサイト様で確認できます

関連記事