2626. Array Reduce Transformation

2626. Array Reduce Transformation

更新於 發佈於 閱讀時間約 4 分鐘

(略),array 是用來將陣列的值進行累加,我們來看看怎麼怎麼達成吧:

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.

 

Example 1:

Input: 
nums = [1,2,3,4]
fn = function sum(accum, curr) { return accum + curr; }
init = 0
Output: 10
Explanation:
initially, the value is init=0.
(0) + nums[0] = 1
(1) + nums[1] = 3
(3) + nums[2] = 6
(6) + nums[3] = 10
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:
initially, the value is init=100.
(100) + nums[0] * nums[0] = 101
(101) + nums[1] * nums[1] = 105
(105) + nums[2] * nums[2] = 114
(114) + nums[3] * nums[3] = 130
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.

 

解題思路

我們首先先建立一個函式,並包含題目要求的三個元素:數組 nums、一個 reducer 函數 fn 和一個初始值 init

const reduce = function(nums, fn, init) 

因為會需要迭代,所以我們要先宣告一個最終返回的值

let current = init

接著依照 nums 陣列的長度執行每一次 fn 函式的迴圈,並變更值

 for (let i = 0; i < nums.length; i++) {
current = fn(current, nums[i]);
}

最後再回傳 current 值就完成了


const reduce = function(nums, fn, init) {
let current = init
for (let i = 0; i < nums.length; i++) {
current = fn(current, nums[i]);;
}
return current
};




avatar-img
高的沙龍
0會員
5內容數
留言
avatar-img
留言分享你的想法!
高的沙龍 的其他內容
今天要來嘗試的是,如何不用好用的Array.map 方法,來實現 Array.map 的功能。 What is Array.map map() 方法會建立一個新的陣列,其內容為原陣列的每一個元素經由回呼函式運算後所回傳的結果之集合。 簡單來說就是把陣列內的每一個值,個別跑函式,把新的值回傳出成
今天要來嘗試的是,如何不用好用的Array.map 方法,來實現 Array.map 的功能。 What is Array.map map() 方法會建立一個新的陣列,其內容為原陣列的每一個元素經由回呼函式運算後所回傳的結果之集合。 簡單來說就是把陣列內的每一個值,個別跑函式,把新的值回傳出成