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(N).fill() .join(" ")で一発! 簡単な問題ほど シンプルな解法を考えるクセ が大事!

Posted at

今回解いた問題は、
「整数 N を受け取り、N 回 paiza を半角スペース区切りで出力せよ」
while でN回ループを書いたら、なぜかN-1回しか回らないバグ に遭遇した。
原因は count = 1 で始めたせい。ループは count < N だから、1からN-1までの N-1回しか回らない ってオチだった。

NGコード(N-1回しか出力されない)

let count = 1;  
while (count < N) {  
    process.stdout.write("paiza ");  
    count++;  
}  
process.stdout.write("paiza");  

OKコード(ちゃんとN回出力)

let count = 0;  
while (count < N) {  
    process.stdout.write(count === N - 1 ? "paiza" : "paiza ");  
    count++;  
}  
console.log("");  

または、count <= N
さらに、Array(N).fill().join() を使うと超スマートかも。

console.log(Array(N).fill("paiza").join(" "));  

こっちなら while ループなしで N回出力完了!

Array(N) で N 個の空の要素を持つ配列を作成
.fill("paiza") で全部 paiza にする
.join(" ") で半角スペース区切りで結合

僕の失敗談と解決話!

0
0
3

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?