LoginSignup
0
0

52枚のトランプを5人に配るとき、11枚、11枚、10枚、10枚、10枚と配りたい。

Posted at

やりたいこと

52枚のトランプを5人に配るとき、11枚、11枚、10枚、10枚、10枚と配りたい。

問題

52を3で割って配ると、1人あたり17枚になり、合計が51枚になってしまう。

irb(main):001> total = 52
=> 52
irb(main):002> total / 5
=> 17

考えたこと

・1から52までの数を配列に入れて、5人に順番に渡していく。
・人数分の配列を作り、そこに順番に入れていく。

やってみる

each_sliceメソッドを使うと指定した数で区切れることがわかった。
配列を用意して、区切った配列を入れていく。

numbers = (1..52).to_a

n = 52 / 5

array = []
numbers.each_slice(n) do |x|
  # 均等に配る
  array << x
end

5人に10枚ずつ配ったが、2枚余ってしまった。
余った51と52を1人目と2人目に配りたい。

[ruby]$ ruby tmp_cart.rb
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
[31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
[41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
[51, 52]

each_with_indexメソッドを使って、最後の配列から各要素を取り出して、順番に渡していく。(余った枚数を配る)

array[-1].each_with_index do |x, i|
  array[i] << x
end

array.pop

52枚のトランプを5人に配るとき、11枚、11枚、10枚、10枚、10枚と配ることができた。

[ruby]$ ruby tmp_cart.rb
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 51],
 [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 52],
 [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
 [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
 [41, 42, 43, 44, 45, 46, 47, 48, 49, 50]]
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