LoginSignup
3
1

More than 5 years have passed since last update.

配列の要素で作る順列 (Permutation) をC#で

Posted at

いろいろ書き方はありますが、与えられた配列の要素を入れ替えていくやり方を紹介します。

using System;

class Program
{
    static void Main(string[] args)
    {
        var str = "abcde";
        Permute(str.ToCharArray(), x => Console.WriteLine(new string(x)));
    }

    public static void Permute<T>(T[] array, Action<T[]> action)
    {
        Permute(array, 0, array.Length, action);
    }

    private static void Permute<T>(T[] array, int pos, int count, Action<T[]> action)
    {
        if (count == 0)
        {
            action(array);
            return;
        }
        for (var i = 0; i < count; i++)
        {
            Swap(array, pos, pos + i);
            Permute(array, pos + 1, count - 1, action);
            Swap(array, pos, pos + i);
        }
    }

    private static void Swap<T>(T[] array, int x, int y)
    {
        var temp = array[x];
        array[x] = array[y];
        array[y] = temp;
    }
}
3
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
3
1