通过最小转置数C - >生成所有排列。 C #

时间:2017-10-26 22:04:56

标签: c# c permutation

我想将此代码转换为C#,但有些错误。我不想用指针做那件事。谁能知道如何快速改善它?这是通过最小转置次数生成所有排列。这是我想要转换的代码。 a link

def enqueue(self, item):
    self.items.insert(0, item[:])

1 个答案:

答案 0 :(得分:0)

我复制/粘贴了它很容易转换为C#

的C程序

您遇到的一些主要问题:int[] I = P;没有制作新数组。将int n = Int32.Parse(Console.ReadLine());更改为n = Int32.Parse(Console.ReadLine());。编译器应该给你关于初始化的警告。

swap更改为swap(ref int i, ref int j),这更像是C版本,并且更加通用。

class Program
{
    private int[] P;
    private int count, n;

    public int silnia(int n)
    {
        return (n == 1 || n == 0) ? 1 : silnia(n - 1) * n;
    }

    public void swap(ref int i, ref int j)
    {
        int temp = i;
        i = j;
        j = temp;
    }

    public int B(int m, int i)
    {
        if ((m % 2 == 0) && (m > 2))
        {
            if (i < (m - 1))
                return i;
            else
                return m - 2;
        }
        else
            return m - 1;
    }

    public void PERM(int m)
    {
        int[] I = new int[m + 1];

        for (int i = 1; i <= m; i++)
            I[i] = 1;
        int Mi = 1;

        while (count < silnia(m))
        {
            if (I[Mi] == Mi)
            {
                if (I[Mi] == 1 && Mi == 1)
                {
                    count++;
                    Console.Write("{0}:\t", count);
                    for (int i = 1; i <= n; i++)
                        Console.Write("{0} ", P[i]);
                    Console.WriteLine();
                }
                for (int i = 1; i <= Mi; i++)
                    I[i] = 1;
                Mi++;
            }
            if (I[Mi] < Mi)
            {
                int i = I[Mi];
                swap(ref P[B(Mi, i)], ref P[Mi]);
                I[Mi]++;
                Mi = 1;
            }
        }
    }

    public void getData()
    {
        Console.WriteLine("Podaj ilość elementów: ");
        n = Int32.Parse(Console.ReadLine());
        P = new int[n + 1]; 
        for (int i = 1; i <= n; i++)
            P[i] = i;
        count = 0;
        PERM(n);
    }

    static void Main(string[] args)
    {
        Program prog = new Program();
        prog.getData();
        Console.ReadKey();
    }
}