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?

「長テーブルのうなぎ屋」を解くために:part5

Posted at

今回は paiza の「「長テーブルのうなぎ屋」を解くために:part5」の問題に挑戦!


問題概要

  • 今回は 複数グループ(m組)が座る場合の座席番号を確認する問題。

  • テーブルは 円卓 で、座席番号 n と 1 が隣り合っている。

  • 各グループについて、

    • グループ人数 a_i
    • 着席開始番号 b_i
      が与えられるので、座る席の番号を順に出力する。

※実際に座るわけではなく、「座席番号の確認のみ」。



入力例:

5 2  // n m
3 4  // a_1 b_1
1 3

出力例:

4 5 1
3






✅ OK例:

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

rl.on('line', (input) => lines.push(input));

rl.on('close', () => {
    // 座席数 n, グループ数 m を取得
    const [n, m] = lines[0].split(' ').map(Number);
    
    // 各グループの情報を取得
    const groups = lines.slice(1).map(line => line.split(' ').map(Number));
    
    // 各グループごとに座席番号を出力
    for (let i = 0; i < m; i++) {
        const [a, b] = groups[i];  // 人数aと開始番号b
        
        const seats = [];
        for (let j = b; j < a + b; j++) {
            if (j <= n) {
                seats.push(j);       // n以内ならそのまま
            } else {
                seats.push(j - n);   // nを超えたら1から再開
            }
        }
        
        console.log(seats.join(' '));
    }
});






🗒️ まとめ

  • 円卓(ループ構造)
    → 最後(n)の次は1番に戻る。
  • 複数グループ対応
    → 配列をループして各グループごとに処理する。
  • 座席番号の計算
    j - n で「1に戻る」動作を表現。

  • map + forEachでも書ける
    → より短く書くと以下のように可能:
const [n, m] = lines[0].split(' ').map(Number);
lines.slice(1).map(l => l.split(' ').map(Number))
     .forEach(([a, b]) => 
         console.log([...Array(a)].map((_, i) => (b + i - 1) % n + 1).join(' '))
     );
  • mod(%)を使うとスマートに円卓を扱える
    (b + i - 1) % n + 1 で1始まりに調整。







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

0
0
0

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?