-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray-reduce-transformation.html
62 lines (51 loc) · 1.99 KB
/
array-reduce-transformation.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<p>Given an integer array <code>nums</code>, a reducer function <code>fn</code>, and an initial value <code>init</code>, return a <strong>reduced</strong> array.</p>
<p>A <strong>reduced</strong> array is created by applying the following operation: <code>val = fn(init, nums[0])</code>, <code>val = fn(val, nums[1])</code>, <code>val = fn(val, nums[2])</code>, <code>...</code> until every element in the array has been processed. The final value of <code>val</code> is returned.</p>
<p>If the length of the array is 0, it should return <code>init</code>.</p>
<p>Please solve it without using the built-in <code>Array.reduce</code> method.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong>
nums = [1,2,3,4]
fn = function sum(accum, curr) { return accum + curr; }
init = 0
<strong>Output:</strong> 10
<strong>Explanation:</strong>
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.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong>
nums = [1,2,3,4]
fn = function sum(accum, curr) { return accum + curr * curr; }
init = 100
<strong>Output:</strong> 130
<strong>Explanation:</strong>
initially, the value is init=100.
(100) + nums[0]^2 = 101
(101) + nums[1]^2 = 105
(105) + nums[2]^2 = 114
(114) + nums[3]^2 = 130
The final answer is 130.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong>
nums = []
fn = function sum(accum, curr) { return 0; }
init = 25
<strong>Output:</strong> 25
<strong>Explanation:</strong> For empty arrays, the answer is always init.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= nums.length <= 1000</code></li>
<li><code>0 <= nums[i] <= 1000</code></li>
<li><code>0 <= init <= 1000</code></li>
</ul>