LoginSignup
6
5

More than 5 years have passed since last update.

整数 n を なるべく等しい整数になるように m 等分する

Posted at

すごいどうでもいいのでわざわざ文章にするまでも無かったのですが、せっかくなので投稿します。

整数 n を なるべく等しい整数になるように m 等分するコードを書きました。

# 整数 n を なるべく等しい整数になるように m 等分する
# 返り値は整数の Array とする
def divide_equally(n, m)
  result = Array.new(m, n/m)
  rest = n%m

  if rest == 0
    # 端数が出ない場合
    return result
  else
    rest.times do |i|
      result[i] += 1
    end
    return result
  end
end

p divide_equally(10,2) # => [5, 5]
p divide_equally(10,3) # => [4, 3, 3]
p divide_equally(10,10) # => [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
p divide_equally(0,10) # => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

やっぱりどうでも良すぎた感がある。なんで投稿したんだ。

6
5
5

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
6
5