gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:32:29 25 4
gpt4 key购买 nike

我想将此代码转换为 C#,但有些问题。我不想用指针来做到这一点。有谁知道如何尽快改进吗?这是通过最少数量的转置生成所有排列。这是我想要转换的代码。 a link .

namespace Algorytm8
{
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(int i, int j)
{
int pom;
pom = P[i];
P[i] = P[j];
P[j] = pom;
}
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 Mi;
int[] I = P;
for (int i = 1; i <= m; i++)
{
I[i] = 1;
}
Mi = 1;
while (count < silnia(m))
{
if (I[Mi]==Mi)
{
if (I[Mi]==1 && Mi==1)
{
count++;
Console.Write(count);
for (int i = 1; i <= n; i++)
{
Console.Write(P[i]);
}
Console.Write("\n");
}
for (int i = 1; i <= Mi; i++)
{
I[i] = 1;
}
Mi++;
}
if (I[Mi] < Mi)
{
int i = I[Mi];
swap(b(Mi, i), Mi);
I[Mi]++;
Mi = 1;
}
}
}
public void getData()
{
Console.WriteLine("Podaj ilość elementów: ");
int n = Int32.Parse(Console.ReadLine());
P = new int[n];
for (int i = 0; i < n; i++)
{
P[i] = i + 1;
}
perm(n - 1);
}
static void Main(string[] args)
{
Program p = new Program();
p.getData();
Console.ReadKey();
}
}
}

最佳答案

我复制/粘贴了 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();
}
}

关于c# - 通过最小转置数生成所有排列 C -> C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46964545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com