gpt4 book ai didi

java - 增加索引后如何递归添加?

转载 作者:行者123 更新时间:2023-12-02 03:47:37 24 4
gpt4 key购买 nike

我目前正在做一项家庭作业,目标是仅递归地执行此操作(无循环)。我非常确定我可以重载并添加辅助方法,这是我完成此任务的唯一方法。

所以问题是,我有一个 int 数组 A = {1,2,3,4} (或类似的东西),我需要用 {10,9,7,4} 创建一个返回的数组

10 = 1+2+3+4

9 = 2+3+4

7 = 3+4

4 = 4

我想使用这样的东西(不是工作代码)

int counter = 0;
public int[] r(int[] numbers){
return r(number, counter);
}

public int[] r(int[] numbers, int index){
int sum = 0;
// base case to check if next value exists otherwise end it

// this would be a helper method instead of a for loop
for(int x=index; x<numbers.length; x++){
sum += numbers[x];
}

numbers[index] = sum;
index++;
return r(numbers, index);
}

但是,我不知道该怎么做。这也是我接触递归的第一周,所以这对我来说有点困惑。我得到了正确的数组,但在 numeric[index] = sum 上有一个 ArrayIndexOutOfBoundsException ,并且在 return 语句 return r(numbers, index) 上有一个 ArrayIndexOutOfBoundsException ,我不知道如何修复它。有什么想法吗?

最佳答案

我认为这会给你正确的答案:

public static int[] slideAndSumArrayElements(int[] array, int[] result, int index) {
// base case - stop when the index is same as the array.length
if (index == array.length) {
return result;
}
else {
// Add all elements of the array starting from the index position till length of the array and store the result in result[index]
result[index] = addArrayElementsRecursively(array, index);

// slide the main array by incrementing the index
return slideAndSumArrayElements(array, result, index + 1);
}
}

public static int addArrayElementsRecursively(int[] arr, int index){
// base case - when the index is same as the original array len stop
if (arr.length == index){
return 0;
}

// add progressively each element of the given array
return arr[index] + addArrayElementsRecursively(arr, index + 1);
}

public static void arraySum(){
int[] array = {1, 2, 3, 4};
int[] result = new int[array.length];

result = slideAndSumArrayElements(array, result, 0);
}

输出数组或结果将是: [10,9,7,4]

关于java - 增加索引后如何递归添加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36166796/

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