Paizaの問題を解いてたら、「単語数をカウントせよ!」みたいな問題が出てきた。
これ、Setと.sizeを使えばめっちゃスッキリ解けるんだよね。
問題概要
スペース区切りの文字列を改行して出力。ただし、
• 同じ単語は1回だけ出力
• その後、出現した単語の種類の数だけ 1 を出力
入力例
red green blue blue green blue
出力例
red
green
blue
1
1
1
初めのコード
const rl = require('readline').createInterface({input: process.stdin});
rl.on('line', (input) => {
const words = input.split(' ');
const seen = new Set();
words.forEach(word => {
if (!seen.has(word)) {
console.log(word);
seen.add(word);
}
});
for (let i = 0; i < seen.size; i++) {
console.log(1);
}
rl.close();
});
他のコード例(改善?)
const rl = require('readline').createInterface({ input: process.stdin });
rl.on('line', (input) => {
const words = input.split(' ');
const seen = new Set();
const output = [];
words.forEach(word => {
if (!seen.has(word)) {
output.push(word);
seen.add(word);
}
});
console.log(output.join("\n"));
console.log(Array.from(seen).map(() => 1).join("\n"));
rl.close();
});
解説
✅ Set は 重複を自動で排除 してくれる!
✅ .size を使えば ユニークな単語数を取得 できる!
✅ Array.from(seen).map(() => 1).join("\n") で 1 の出力をsizeもループもなしで実装!
まとめ
• Set の特性を活かせば、重複をチェックする手間が減る!
• .size を使えば、要素数のカウントも楽勝!
• map(() => 1) のテクニックで、出力もシンプルに!