0
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?

More than 1 year has passed since last update.

今回挑戦したのは、A と B、2つの配列を比べて、同じ「位置」にある値が一致している個数をカウントする問題。初めは勘違いしてミスったけど正解できた!



問題概要

  • 整数N、配列A、配列Bが与えられる。
  • A[i] === B[i] となる「i」の数を数える!

入力例:

5
1 2 3 4 5
1 20 30 4 5

出力例:

3

https://paiza.jp/works/mondai/conditions_branch/conditions_branch__complex_step3




❌NGコード例

const rl = require('readline').createInterface({input:process.stdin});
const lines = [];

rl.on('line',(input) => {
    lines.push(input);
});


rl.on('close',()=>{
    const N = Number(lines[0]);
    const arrA = lines[1].split(' ').map(Number);
    const arrB = lines[2].split(' ').map(Number);
    
    
    let count = 0;
    
    arrA.forEach(a => {
        arrB.forEach(b => {
            if(a === b){
                count++;
            }
        })
    })
    
    console.log(count);
    
    
});

🌀 問題点

  • インデックス完全無視の全探索!
  • つまり「同じ位置の比較」ではなく「全ての組み合わせ」を比べている!
  • 出力が“やけに多い”と感じた時点で気づくべきだった……



✅OKコード例:forループ

let count = 0;
for (let i = 0; i < N; i++) {
    if (arrA[i] === arrB[i]) count++;
}
console.log(count);

✅ ポイント

  • 同じインデックス i で A と B を正確に比較!
  • 正攻法ですっきりシンプル!




💡他の書き方:

✅ filter

const count = arrA.filter((val, i) => val === arrB[i]).length;

console.log(count);

🔍 filter は「条件を満たす要素だけを残す」→ その長さが一致した回数。

  • valarrA[i] の 値(その要素自体)
  • i → その インデックス(位置番号)



✅ reduce

const count = arrA.reduce((acc, val, i) => acc + (val === arrB[i] ? 1 : 0), 0);

console.log(count);

reduce は累積変数 acc を使って、条件を満たす回数を数える方法。



✅ 再利用できる関数化

function countMatchingIndices(a, b) {
    return a.filter((val, i) => val === b[i]).length;
}

console.log(countMatchingIndices(arrA, arrB));
const countMatch = (a, b) => a.filter((v, i) => v === b[i]).length;
console.log(countMatch(arrA, arrB));




気づきメモ

  • forEachで2重ループして「A[i] === B[i]」ではなく「Aの全要素とBの全要素を比較」していた

  • filter:特定条件を満たす要素だけを抽出。配列の長さで件数を数えられる

  • reduce:累積計算が得意。「条件を満たすなら+1」の考え方は汎用性高い!

  • forEach の使いどころ注意:インデックス制御が必要な時はforループの方が安心!



まとめ

しかり問題文を読むのが大事だった。あと、いろいろな書き方したけど、個人的には、結局forループが一番わかりやすくていいなと思った(^▽^)/




僕の失敗談(´;ω;`)と解決法🐈

0
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
0
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?