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?

paizaの、多重ループとFIZZBUZZ(条件分岐)を組み合わせた「スーパー鳩時計」の問題に挑戦!


問題概要

「時刻の ‘時’ と ‘分’ を足して、その合計が3の倍数なら ‘FIZZ’、5の倍数なら ‘BUZZ’、両方なら ‘FIZZBUZZ’ と鳴かせよ」という問題。0も3と5の倍数とする。


  • 24時間の「時」を0から23までループ
  • 60分の「分」を0から59までループ
  • それぞれの時と分を足した値を判定
  • 3の倍数かつ5の倍数 → FIZZBUZZ
  • 3の倍数だけ → FIZZ
  • 5の倍数だけ → BUZZ
  • どれでもなければ無音(空行)



✅ OK例:

for (let i = 0; i < 24; i++) {  // 時(0〜23)をループ
    for (let j = 0; j < 60; j++) {  // 分(0〜59)をループ
        
        const time = i + j;  // 現在の時 + 分の合計を求める

        // time が 3 と 5 の両方の倍数のとき → FIZZBUZZ
        if (time % 3 === 0 && time % 5 === 0) {
            console.log("FIZZBUZZ");
        } 
        // time が 3 の倍数のとき → FIZZ
        else if (time % 3 === 0) {
            console.log("FIZZ");
        }
        // time が 5 の倍数のとき → BUZZ
        else if (time % 5 === 0) {
            console.log("BUZZ");
        }
        // それ以外のときは何も鳴かない(空行を出力)
        else {
            console.log("");
        }
    }
}



✅ OK例2:出力を一括でまとめて表示

// 出力をためておく配列
const output = [];

for (let i = 0; i < 24; i++) {      // 時(0〜23)
    for (let j = 0; j < 60; j++) {  // 分(0〜59)

        const time = i + j;      // 現在の時 + 分の合計を計算

        // 3と5両方の倍数=15の倍数 → FIZZBUZZ
        if (time % 15 === 0) {
            output.push("FIZZBUZZ");  
        } 

        else if (time % 3 === 0) {
            output.push("FIZZ");      // 3の倍数 → FIZZ
        } 
        
        else if (time % 5 === 0) {
            output.push("BUZZ");      // 5の倍数 → BUZZ
        } 

        else {
            output.push("");      // どれでもない場合は空文字
        }
    }
}

// 最後に一括で出力
console.log(output.join('\n'));
  • 配列にためて最後に一度だけ出力した方が効率的。
  • 後でまとめて加工したりソートしたりしやすい
  • 3と5の倍数 = 15の倍数



🗒️ メモ&まとめ

  • FizzBuzz問題は判定順が命!最も厳しい条件から順に書くべし
  • console.logで毎回出力するより、一旦配列にためて最後にまとめて出すのも効率的!
  • 3と5の倍数=15の倍数(最小公倍数)を使って少し短縮できる




僕の失敗談(´;ω;`)と解決法🐈

0
0
2

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?