gpt4 book ai didi

java - 创建多个嵌套循环以生成两个遍历数组长度的数字

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

如标题所示,我一直在考虑创建旨在实现一个目的的多个嵌套循环。通过数组的每个可能位置移动 0-9 之间的两个生成的随机数。

例如,App 生成第一个数字 (fNum) 1 和第二个数字 (sNum) 6。然后将这些数字移动到包含 ABC 的数组中。然而,firstNum 和 secondNum 还需要尝试所有可能的组合,因此每个循环都需要不同。

-1ABC6
-A1BC6
-AB1C6
-ABC16
-ABC61
-AB6C1
-A6BC1
-6ABC1
-A6B1C
-A61BC
-A16BC
-A1B6C
-A1BC6

等等……

我相信最好的方法是创建一个生成计数器的方法,它会增加我可以调用的数字。

    private int getNextNumber(int num) {

if (num == 0) {
return num;
} else {
num++;
}

if (num < 10) {
return num;
} else {
return -1;
}

}

然后我将需要多个嵌套循环...我决定进行多个循环,这将无限进行。

            while (j < maxlen) {
//J = 0 and maxlen = length of text so in this case 3 as it is ABC
//Add two numbers and check against answer

while (fNum != -1 || sNum != -1) {

//incrememnt numbers
fNum = getNextNumber(fNum);
System.out.println(fNum);

sNum = getNextNumber(sNum);
System.out.println(fNum);

}

String textIni = "ABC";
int lenOfText = textIni.length();
char[] split = textIni.toCharArray();

for (int i = 0; i < lenOfText; i++) {
//here it will look at the length of the Text and
//try the possible positions it could be at....
//maybe wiser to do a longer loop but I am not too sure
}
}

最佳答案

由于您不需要存储所有可能的组合,我们将通过迭代解决方案仅使用 O(n) 存储来节省一些内存。我建议您使用一个基本的实现,但不要指望在大型数组上使用它,因为它具有 O(n³) 的复杂性。

public static void generateCombinationsIterative(List<Integer> original, int fnum, int snum) {
int size = original.size();
for (int i=0 ; i<=size ; i++) {
List<Integer> tmp = new ArrayList<>(original);
tmp.add(i,fnum);
for (int j=0 ; j<=size + 1 ; j++) {
tmp.add(j,snum);
System.out.print(tmp + (i == size && j == size + 1 ? "" : ", "));
tmp.remove(j);
}
}
}

对于您的文化,这里有一个递归解决方案的示例,它会占用大量内存,因此如果您不需要生成结果列表,请不要使用它。尽管如此,这是一个更通用的解决方案,可以处理任意数量的要插入的元素。

public static List<List<Integer>> generateCombinations(List<Integer> original, Deque<Integer> toAdd) {
if (toAdd.isEmpty()) {
List<List<Integer>> res = new ArrayList<>();
res.add(original);
return res;
}

int element = toAdd.pop();
List<List<Integer>> res = new LinkedList<>();
for (int i=0 ; i<=original.size() ; i++)
// you must make a copy of toAdd, otherwise each recursive call will perform
// a pop() on it and the result will be wrong
res.addAll(generateCombinations(insertAt(original,element,i),new LinkedList<>(toAdd)));
return res;
}

// a helper function for a clear code
public static List<Integer> insertAt(List<Integer> input, int element, int index) {
List<Integer> result = new ArrayList<>(input);
result.add(index,element);
return result;
}

请注意,为了从动态数据结构中受益,我没有使用任何数组,但是您可以这样调用方法:

int[] arr  = { 1,2,3 };
int fnum = 4, snum = 5;
generateCombinationsIterative(Arrays.asList(arr),fnum,snum);
generateCombinations(Arrays.asList(arr),new LinkedList<>(Arrays.asList(fnum,snum));

请注意,这两种方法都以相同的顺序生成组合。

关于java - 创建多个嵌套循环以生成两个遍历数组长度的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26760349/

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