Array Reduce Transformation Without Built-In Method

Easy
23
53.5% Acceptance

In this lab, you will be implementing a custom reduce function for integer arrays, without using the built-in Array.reduce method. The custom reduce function takes an integer array nums, a reducer function fn, and an initial value init as arguments and returns the reduced array value.

The reduced array is created by applying the following operation: val = fn(init, nums[0]), val = fn(val, nums[1]), val = fn(val, nums[2]), until every element in the array has been processed. The final value of val is returned.

If the length of the array is 0, the function should return the init value.

Example

Consider the following examples to get a better understanding of the reduce function:

Example 1:

Input:

nums = [1, 2, 3, 4] fn = function sum(accum, curr) { return accum + curr; } init = 0

Output: 10

Explanation:

  1. Initially, the value is init=0.
  2. (0) + nums[0] = 1
  3. (1) + nums[1] = 3
  4. (3) + nums[2] = 6
  5. (6) + nums[3] = 10
  6. The final answer is 10.

Example 2:

Input:

nums = [1, 2, 3, 4] fn = function sum(accum, curr) { return accum + curr * curr; } init = 100

Output: 130

Explanation:

  1. Initially, the value is init=100.
  2. (100) + nums[0]^2 = 101
  3. (101) + nums[1]^2 = 105
  4. (105) + nums[2]^2 = 114
  5. (114) + nums[3]^2 = 130
  6. The final answer is 130.

Example 3:

Input:

nums = [] fn = function sum(accum, curr) { return 0; } init = 25

Output: 25

Explanation: For empty arrays, the answer is always init.

Constraints

  • 0 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
  • 0 <= init <= 1000

Now that you've understood the problem statement, go ahead and complete the lab by writing the appropriate code and completing the challenges. Good luck!