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?

Setとsizeで単語数を取得!

Posted at

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) のテクニックで、出力もシンプルに!


僕の失敗談と解決談!

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?