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?

数値の出現率 Map() vs 配列

Posted at

paizaの「数字の出現回数カウント」の問題を解いた!出現回数をカウントする問題は前に解いたことあったけど、地味なミスを連発した(´;ω;`) あと、正解は一つじゃないんだと改めてわかったことを記録するよ!


🎯 問題概要:0〜9の出現回数を数えるだけ

入力例:

5  // N
1 2 3 3 6  

出力例:

0 1 1 2 0 0 1 0 0 0

N個の整数(0〜9)が与えられるので、それぞれの出現回数をカウントし、
0から9の順で1行に出力するだけ。


❌NG例

const nums = lines[1].split(' ');
const count = new Map();

for (let i = 1; i <= 9; i++) {
    count.set(i, 0); // ❌ 0入れ忘れた
}

nums.forEach(a => {
    count.set(a, count.get(a) + 1); // ❌ aが文字列なのでNaNになる
});

count.forEach(v => console.log(v)); // ❌ 出力が改行されてしまう

ミス:

  • 0 を初期化し忘れる
  • .split(' ') で得た値が文字列 → .map(Number) を忘れると事故る
  • 出力が 10行 に分かれる(joinが必要)


✅ OK例:Mapをちゃんと使うならこう

const nums = lines[1].split(' ').map(Number);
const count = new Map();

for (let i = 0; i <= 9; i++) {
    count.set(i, 0);
}

nums.forEach(a => {
    count.set(a, count.get(a) + 1);
});

const result = [];
count.forEach(value => result.push(value));
console.log(result.join(' '));


✨配列でスマートに!

const nums = lines[1].split(' ').map(Number);
const counts = Array(10).fill(0);

for (const n of nums) {
    counts[n]++;
}

console.log(counts.join(' '));

解説:

  • Array(10).fill(0):0〜9に対応する配列を初期化
  • counts[n]++:そのままインデックスで加算
  • console.log(counts.join(' ')):出力は1行で整形済み


なぜ配列がいいのか?

  • キーが固定(0〜9)ならMapより配列が高速&簡潔
  • 書く量も読む量も少なくなる=タイパがいい


🧠 まとめ:Mapに頼りすぎない!

Mapももちろん便利だけど、キーが固定なら配列で十分。


覚えておきたい構文:

  • Array(10).fill(0)
  • .map(Number)(文字列→数値)
  • .join(' ')(出力整形)



僕の失敗談(´;ω;`)と解決話🚀

0
0
1

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?