gpt4 book ai didi

Java 排列

转载 作者:行者123 更新时间:2023-11-30 05:08:16 27 4
gpt4 key购买 nike

我正在尝试运行我的代码,以便它打印循环排列,尽管我目前只能让它执行第一个排列。它正确运行到我标记的点,但我看不出出了什么问题。我认为 while 循环中没有中断,但我不确定。确实需要一些帮助。

package permutation;

public class Permutation {
static int DEFAULT = 100;

public static void main(String[] args) {
int n = DEFAULT;
if (args.length > 0)
n = Integer.parseInt(args[0]);

int[] OA = new int[n];
for (int i = 0; i < n; i++)
OA[i] = i + 1;

System.out.println("The original array is:");
for (int i = 0; i < OA.length; i++)
System.out.print(OA[i] + " ");
System.out.println();

System.out.println("A permutation of the original array is:");
OA = generateRandomPermutation(n);
printArray(OA);
printPemutation(OA);
}

static int[] generateRandomPermutation(int n)// (a)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;

for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
int swap = A[r];
A[r] = A[i];
A[i] = swap;
}
return A;
}

static void printArray(int A[]) {
for (int i = 0; i < A.length; i++)
System.out.print(A[i] + " ");
System.out.println();
}

static void printPemutation(int p[])// (b)
{
System.out
.println("The permutation is represented by the cyclic notation:");
int[] B = new int[p.length];
int m = 0;
while (m < p.length)// this is the point at which my code screws up
{
if (!check(B, m)) {
B = parenthesis(p, m);
printParenthesis(B);
m++;
} else
m++;
}// if not there are then repeat
}

static int[] parenthesis(int p[], int i) {
int[] B = new int[p.length];
for (int a = p[i], j = 0; a != B[0]; a = p[a - 1], j++) {
B[j] = a;
}
return B;
}

static void printParenthesis(int B[]) {
System.out.print("( ");
for (int i = 0; i < B.length && B[i] != 0; i++)
System.out.print(B[i] + " ");
System.out.print(")");
}

static boolean check(int B[], int m) {
int i = 0;
boolean a = false;
while (i < B.length || !a) {
if ((ispresent(m, B, i))){
a = true;
break;
}
else
i++;
}
return a;
}

static boolean ispresent(int m, int B[], int i) {
return m == B[i] && m < B.length;
}
}

最佳答案

除此之外,您应该在 check(B, p[m]) 中检查 p[m] 而不是 m:

在 static void printPemutation(int p[]) 中:

while (m < p.length){
if (!check(B, p[m])) {
B = parenthesis(p, m);
printParenthesis(B);
}
m++;
}

然后

static boolean check(int B[], int m) {
int i = 0;
while (i < B.length) {
if (m == B[i]) {
return true;
}
i++;
}
return false;
}

这在某种程度上可以满足您的需求,但我担心并不总是......

关于Java 排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4340897/

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