gpt4 book ai didi

java - 随机化返回并将数组大小加倍

转载 作者:行者123 更新时间:2023-12-01 15:49:05 25 4
gpt4 key购买 nike

我目前有这段代码。

当前发生的情况是,正在接收两个数组,并且数组 A 的索引的所有可能的顺序组合都被存储为单独数组的列表,每个数组的大小与数组 B 相同。当前要做的事情此 sizeA 必须小于 sizeB。

import java.util.*;


public class Main {

public static void main(final String[] args) throws FileNotFoundException {

ArrayList<String> storeB= new ArrayList();
ArrayList<String> storeA = new ArrayList();

Scanner scannerB = new Scanner(new File("fileB"));
Scanner scannerA = new Scanner(new File("fileA"));

while(scannerB.hasNext()) {
String b = scannerB.next();{
storeB.add(b);

}
}



while(scannerA.hasNext()) {
String A = scannerA.next();{
storeA.add(A);

}

}

final int sizeA = storeA.size();
final int sizeB = storeB.size();


final List<int[]> combinations = getOrderings(sizeA-1, sizeB);


for(final int[] combo : combinations) {

for(final int value : combo) {
System.out.print(value + " ");
}
System.out.println();

}

}

private static List<int[]> getOrderings(final int maxIndex, final int size) {


final List<int[]> result = new ArrayList<int[]>();

if(maxIndex == 0) {
final int[] array = new int[size];
Arrays.fill(array, maxIndex);
result.add(array);
return result;
}

// creating an array for each occurence of maxIndex, and generating each head
//recursively

for(int i = 1; i < size - maxIndex + 1; ++i) {

//Generating every possible head for the array
final List<int[]> heads = getOrderings(maxIndex - 1, size - i);

//Combining every head with the tail
for(final int[] head : heads) {
final int[] array = new int[size];
System.arraycopy(head, 0, array, 0, head.length);

//Filling the tail of the array with i maxIndex values
for(int j = 1; j <= i; ++j)
array[size - j] = maxIndex;
result.add(array);
}

}

return result;

}

}

我想知道,无论 sizeA 和 sizeB 如何,如何修改它以创建双倍 sizeB 的数组并重复每个索引值。所以如果我们有: [0,1,1,2]这将变成: [0,0,1,1,1,1,2,2]即复制每个值并将其放在旁边。

此外,我如何消除其中的递归,以便在每次调用时不生成所有可能的组合,而是随机生成单个数组而不是数组列表。

谢谢。

最佳答案

So if we had: [0,1,1,2] this would become: [0,0,1,1,1,1,2,2] i.e duplicating each value and placing it next to it.

public int[] getArray(int originSize) {
// Create a array double the size of originSize
int[] result = new int[originSize * 2];

// Iterate through 0 to originSize - 1 (This are your indicies)
for (int i = 0, j = 0; i < originSize; ++i, j+=2)
{
// i is the index to insert into the new array.
// j holds the current position in the new array.

// On the first iteration i = 0 is written onto the
// position 0 and 1 in the new array
// after that j is incremented by 2
// to step over the written values.
result[j] = i;
result[j+1] = i;
}

return result;
}

关于java - 随机化返回并将数组大小加倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6492048/

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