gpt4 book ai didi

java - 如何从 for 循环关系中创建循环关系

转载 作者:行者123 更新时间:2023-11-30 05:33:31 25 4
gpt4 key购买 nike

这是我的第一篇文章,而且我对 Java 很陌生,正在尝试制作一个小程序来给出所有从 0 到给定数字的唯一数字。例如,对于输入:4,输出将是:

    1234
1243
1324
1342
1423
....

依此类推,4也意味着输出将在一个范围内1000 < x < 10000,其中 x 是输出。

我尝试过制作这样的循环关系方法,但找不到任何有用的东西。因此,我创建了一个 for 循环关系,它可以提供我想要的内容,但仅适用于 4 的输入。我还有一个方法来检查数字是否唯一。 boolean check(int[] array) {...} 如果数字唯一,则返回 true

public static void thing(int num) {
int[] arr = new int[num];
for(int a = 1; a <= 4; a++) {
arr[0] = a;
for(int b = 0; b <= 4; b++) {
arr[1] = b;
for(int c = 0; c <= 4; c++) {
arr[2] = c;
for(int d = 0; d <= 4; d++) {
arr[3] = d;
if(check(arr)) {
System.out.println(arr[0] + "" + arr[1] + "" + arr[2] + "" + arr[3]);
//here in the result it would print the array like in fibonacci I guess
}
}
}
}
}
}

所以,现在,我需要控制每种情况所需的循环数量,并且我需要的是由输入设置的深度。正如我之前所说,输出的形式为:

    1234
1243
....
....
4312
4321

顺序并不重要,但它会运行。如果我错误地认为重复可以解决问题,请帮助我找到可以解决问题的方法。谢谢

最佳答案

正如 WJS 所提到的,您正在寻找排列算法。有许多不同的方法,但这是一种简单的方法:

class HeapAlgo {
//Prints the array
private void printArr(int a[], int n) {
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
System.out.println();
}

//Generating permutation using Heap Algorithm
private void heapPermutation(int a[], int size, int n) {
// if size becomes 1 then prints the obtained
// permutation
if (size == 1)
printArr(a, n);

for (int i = 0; i < size; i++) {
heapPermutation(a, size - 1, n);

// if size is odd, swap first and last
// element
if (size % 2 == 1) {
int temp = a[0];
a[0] = a[size - 1];
a[size - 1] = temp;
}

// If size is even, swap ith and last
// element
else {
int temp = a[i];
a[i] = a[size - 1];
a[size - 1] = temp;
}
}
}

// Driver code
public static void main(String[] args) {
HeapAlgo obj = new HeapAlgo();
int[] a = {1, 2, 3};
obj.heapPermutation(a, a.length, a.length);
}
}

来源:heap permutations

关于java - 如何从 for 循环关系中创建循环关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57080787/

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