
Sponsored
Sponsored
This approach simply involves directly iterating through the elements of the array using a loop, starting with the initial value. For each element, apply the reducer function and update the accumulated result. This approach mimics the behavior of the JavaScript Array.reduce method.
Time Complexity: O(n), where n is the number of elements in the array because we loop through each element once.
Space Complexity: O(1), as we use only a fixed amount of additional space.
In this C implementation, the reduce function takes an array, its size, a function pointer fn, and an initial value. It iteratively processes each element of the array, updating the result with the output of the given function fn. The helper function sum simply adds two integers.
This approach employs a recursive strategy to apply the reducer function on each element of the array. By defining a base case for the recursion (i.e., an empty array returns the initial value), the recursion continues until all elements are processed. Care must be taken with recursion due to stack size limitations for large inputs.
Time Complexity: O(n), for traversing each element.
Space Complexity: O(n), due to recursion stack consumption.
1#include <iostream>
2#include <vector>
3
4int reduce_recursive(std::vector<int>::iterator begin, std::vector<int>::iterator end, int (*fn)(int, int), int init) {
5 if (begin == end) return init;
6 return fn(reduce_recursive(begin + 1, end, fn, init), *begin);
7}
8
9int sum(int accum, int curr) {
10 return accum + curr;
11}
12
13int main() {
14 std::vector<int> nums = {1, 2, 3, 4};
15 int init = 0;
16 int result = reduce_recursive(nums.begin(), nums.end(), sum, init);
17 std::cout << result << std::endl;
18 return 0;
19}The C++ recursive solution uses iterator pairs for the vector. It applies recursion to reduce the numbers by iterating from the back, with a base case returning the initial value. The function sum is used to increment totals.