递归地查找并行数组上的值



我需要编写一个递归方法,该方法使用两个并行数组和单词来查找,查找指定的单词,并将每次索引在另一个数组上匹配的值相加。例如:

array1 = "Toyota", "Honda", "Honda", "Toyota", "Toyota", ......n

array2 = 22500, 18000, 29000, 22500, 32000, ....... n

如果我说我需要查找单词"Toyota",那么它应该在找到索引时对第二个数组上的值求和。在这种情况下,它应该求和,22500+22500+32000

我如何制作递归方法,使其采用适当的参数并递归进行计算。我将使用硬编码值。

这就是我到目前为止所拥有的。我很确定我的递归方法需要更多的参数,但我会看看是否有人能帮我

static int printRecursively(int A[], int N) {
if(N <= 0) {
return 0;
}
return (printRecursively(A, N - 1) + A[N -1]);
}
}

从位置0处的"光标"开始。然后返回该位置的数字和从相同方法调用返回的任何和的总和,光标值为cursor+1。如果cursor+1处没有任何内容,则表示您已到达数组的末尾,在这种情况下,只返回该位置的数字。

public static void main(String[] args) {
String arr1[] = new String[]{"Toyota", "Honda", "Honda", "Toyota", "Toyota"};
int arr2[] = new int[]{22500, 18000, 29000, 22500, 32000};
System.out.println(getSum(arr1, arr2, "Toyota", 0));
}
private static int getSum(String arr1[], int arr2[], String word, int cursor) {
if (cursor == arr1.length - 1) return arr1[arr1.length - 1].equals(word) ? arr2[arr2.length - 1] : 0;
return arr1[cursor].equals(word)
? arr2[cursor] + getSum(arr1, arr2, word, cursor + 1)
: getSum(arr1, arr2, word, cursor + 1);
}

输出

77000

我认为您当前的数据结构不适合这个问题。相反,我建议使用汽车价值的哈希图:

Map<String, List<Integer>> map = new HashMap<>();
List<Integer> values = Arrays.asList(22500, 22500, 32000);
map.put("Toyota", values);
values = Arrays.asList(18000, 29000);
map.put("Honda", values);

然后,为了获得给定汽车的值总和,我们可以很容易地使用流:

int sum = map.get("Toyota").stream().reduce(0, (a, b) -> a + b);

一般来说,实现这一点的一个好方法是表示汽车是钥匙的数据,以及该钥匙所指向的值。

以下类似的东西可能适合您的需求

public static int recursiveSum(String search, String[] names, int[] values, int start) {
// Check that the two arrays are of the same length
// And that start does not exceed the bounds of either
if((names.length != values.length) || start > names.length)
return 0;
// If the value at the 'start' of the array is the one we're looking for
if(names[start].equals(search)) {
return values[start] + recursiveSum(search, names, values, start + 1);
} else {
// Otherwise just skip onto the next value of the arrays
return recursiveSum(search, names, values, start + 1);
}
}

recursiveSum("Toyota", names, values, 0)

最新更新