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?

Array.from() でループ不要! (A, B) をN回出力するスマートな方法

Posted at

Paizaの問題を解いていたら、 (A, B)N回出力するだけなのに、もっとスッキリ書ける方法があった! forループを使うのもアリだけど、Array.from() を使うと一発で解決できるぞ!

問題:(A, B)N回出力せよ!

📌 入力例

3 5 7  // N A B

📌 出力例

(5, 7), (5, 7), (5, 7)

👉 N(A, B) を出力し、各ペアは カンマ + 半角スペース で区切る。


最初のNGコード: forループでゴリ押し

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

rl.on('line', (input) => {
    const [N, A, B] = input.split(" ").map(Number);
    const nums = [];
    for(let i = 0; i < N; i++){
        nums.push(`(${A}, ${B})`);
    }
    console.log(nums.join(", "));
});

💡 問題点

  • forループで Npush() するのがちょっと冗長
  • 変数 nums を使わずにもっと短く書ける


改善版: Array.from() でループを消す!

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

rl.on('line', (input) => {
    const [N, A, B] = input.split(" ").map(Number);
    console.log(Array.from({ length: N }, () => `(${A}, ${B})`).join(", "));
});

改善ポイント🚀
Array.from() で配列を1行で生成
✅ ループ不要でスッキリ!
✅ 可読性UP! 余計な変数なし


気づきメモ📝

  • Array.from({ length: N }) は長さNの配列を作る

  • マッピング関数 () => \(${A}, ${B})`` で各要素をセット

    ループを書かなくても、スマートに配列を作れる!


まとめ

forループより Array.from() を使うと短く書ける
✔ 繰り返し処理はループ以外の方法も考えよう
✔ 可読性が上がるとバグも減る!

こういう小さな工夫が、"書きやすくて読みやすい" コードにつながるぞ!💡


僕の失敗談と解決話!

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?