2012/04/01(Sun)C# で next_permutation を使いたいので

はてブ数 2012/04/01 4:54 プログラミング::C# つーさ

わざわざこういうものを再生産しないといけないところにC#の不便さを感じる。
今日の250が落ちたのはこいつがバグってたせい……ぐぅ。

class Algorithm {
    public static void Swap<T>(ref T x, ref T y) { T tmp = x; x = y; y = tmp; }

    public static bool NextPermutation<T>(T[] array, int index, int length, Comparison<T> comp) {
        if (length <= 1) return false;
        for (int i = length - 1; i > 0; i--) {
            int k = i - 1;
            if (comp (array[k], array[i]) < 0) {
                int j = Array.FindLastIndex(array, delegate(T x) { return comp(array[k], x) < 0; });
                Swap(ref array[k], ref array[j]);
                Array.Reverse(array, i, length - i);
                return true;
            }
        }
        Array.Reverse(array, index, length);
        return false;
    }
    
    public static bool NextPermutation<T>(T[] array) where T : IComparable {
        return NextPermutation(array, 0, array.Length, Comparer<T>.Default.Compare);
    }
}

public class Program {
    static void Main() {
        int[] array = {5,1,4,3,2};
        while (Algorithm.NextPermutation(array)) ; // あるいは Array.Sort(array);
        do
        {
            Console.WriteLine(string.Join(", ", Array.ConvertAll<int, string>(array, i => i.ToString())));
        } while (Algorithm.NextPermutation(array));
    }
}