1
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の「みかん仕分け」問題に挑戦。Cランク問題はもう余裕!


問題概要

  • Nの倍数の箱がある(10gごと、みたいな)

  • 各みかんは「一番近い」箱へ仕分け

  • ちょうど中間なら大きい方に入れる

  • 0gはNG。最小はNgの箱から!


入力例:

10 3
24
35
3

出力例:

20
40
10




❌ NG例:

const box = Math.floor(mikan[i] / N) * N;

これだと ちょうど中間の35g→30gの箱に入っちゃう!
問題の仕様では 大きい方(40g) に入れなきゃダメ。



✅ OK例

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

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


rl.on('close', () => {
    const [N, M] = lines[0].split(' ').map(Number);
    const mikan = lines.slice(1).map(Number);
    
    for(let i = 0; i < M; i++){
        const box = Math.round(mikan[i] / N) * N;
        console.log(box !== 0 ? box : N);
    }
});

✅ このコードのポイント

const box = Math.round(mikan[i] / N) * N;

✔ mikan[i] / N

これは「何番目の箱が近いか」を小数で出す。

例:24g ÷ 10 = 2.4 → 2番目と3番目の中間

✔ Math.round(…)

四捨五入して近い箱の番号を整数にする。

例:2.4 → 2、3.5 → 4(ちょうど中間は大きい方になる)

✔ * N

何番目の箱かわかったら、箱の重さに戻す。

例:2番目の箱 → 2 × 10 = 20g

🧯 三項演算子で 0g 対策

box !== 0 ? box : N

box が 0g のときだけ、N(10gなど)に変更。

1g、3g などは 0g に四捨五入されてしまうから、それをNgに補正。




🗒️ メモ&まとめ

  • Math.round = 四捨五入 一番近い箱を選べる(中間は大きい方もOK)
  • 三項演算子で、ゼロ回避 →0g を Ng に置き換え




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

1
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
1
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?