1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

概要

文系(体育科)卒業の僕が、人並みのアルゴリズムを身につけるためにLeetCodeを初めてみました。
日本だとAtCoderが一般的なようですが、海外エンジニアへの憧れを持つ僕はLeetCodeを選びました。

フロントの言語しかほぼ触ったことがないのでJavaScriptでやっていこうと思います。

問題

2626. Array Reduce Transformation

問題文

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.

問題を整理します。

  • 整数の配列`nums
  • reducer関数fn
  • 初期値`init
  • val = fn(init,nums[0])→ val =fn(val,nums[1]) → val=fn(val,nums[2])
    • 配列の要素が無くなるまで続く
    • 配列がからの時は初期値のinitをreturnする

まずは、JavaScriptのreduce関数について調べてみます。使った記憶ないかも。

縮小関数は配列を要素ごとに走査し、それぞれの段階で、前の段階の結果に現在の配列の値を加えていきます (この結果は、それ以前のすべての段階を合算したものです)。

配列の中身を1つずつ足していって合計を求めるということができるみたいです。
【javascript】reduce - Qiita

まずは、土台をつくります。

  • valに初期値を入れる
  • returnでvalを返します
/**
 * @param {number[]} nums
 * @param {Function} fn
 * @param {number} init
 * @return {number}
 */
var reduce = function(nums, fn, init) {
    let val = init;
    
    // 処理が入る
    
    return val;  
};

整数の配列 nums、リデューサー関数 fn、および初期値 init が与えられた場合、配列の各要素に対して順番に fn 関数を実行し、前の計算からの戻り値を引数として渡して、最終的な結果を返す関数を作成します。

とあるので、ループの中でval = fn(val)とすることで、実行後の値をvalに入れられそうです。
また、例題から、配列の値も順番に使用しているのでfn(val,nums[i])とするのが良さそうです。

/**
 * @param {number[]} nums
 * @param {Function} fn
 * @param {number} init
 * @return {number}
 */
var reduce = function(nums, fn, init) {
    let val = init;
    
    for (let i = 0; i < nums.length; i++) {
        val = fn(val, nums[i])
    }
    
    return val;  
};

実行してみます。

無事にパスしました :congratulations:
CleanShot 2024-07-08 at 22.42.58@2x.jpg

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?