문제

Given an integer array nums, a reducer function fn, and an initial value init, return the final result obtained by executing the fn function on each element of the array, sequentially, passing in the return value from the calculation on the preceding element.

This result is achieved through the following operations: 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 ultimate value of val is then returned.

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

Please solve it without using the built-in Array.reduce method.

 

예제

초기값과 숫자들, 그리고 함수가 주어지면 Array.reduce처럼 누적값과 숫자가 함수 내에서 연산된 뒤 반환된 값을 누적값으로 업데이트한다.

위 예제의 경우 먼저 fn 함수에 의해 초기값과 num[0]이 더해져 나온 값인 1이 누적값으로 업데이트되고,

그 누적값과 num[1]이 더해져 나온 값인 3이 누적값으로 업데이트되는 방식으로 nums 배열을 모두 순회할 때까지 진행된다.

 

위 예제도 예제 1과 같은 방식이지만, fn 함수 내부 연산이 curr의 제곱값을 더하는 점에서 다르다.

 

nums가 빈 배열일 경우, 정답은 항상 초기값이다.

 

 

코드

/**
 * @param {number[]} nums
 * @param {Function} fn
 * @param {number} init
 * @return {number}
 */
var reduce = function(nums, fn, init) {
    let value = init;
    for (let num of nums) {
        value = fn(value, num);
    }
    
    return value;
};

 

먼저 누적값을 담을 변수 value을 선언하고 초기값인 init으로 초기화한다.

이후 nums 배열을 순회하면서 value값과 num을 fn 함수에 넣고 반환된 값으로 value를 업데이트해준다.

마지막으로 value를 반환해주면 문제에서 요구했던 함수를 구현할 수 있다!

'Algorithm' 카테고리의 다른 글

[LeetCode] 2634. Filter Elements from Array  (0) 2024.01.22
[LeetCode] 2629. Function Composition  (0) 2024.01.21
[LeetCode] 2621. Sleep  (0) 2024.01.19
[LeetCode] 2620. Counter  (0) 2024.01.19
[LeetCode] 2619. Array Prototype Last  (0) 2024.01.15

+ Recent posts