Last active
December 16, 2015 11:29
-
-
Save JunichiIto/5427712 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 重み付け抽選クラス(Lottery)の仕様。 | |
# | |
# new(size) | |
# インスタンスを作成する。 | |
# [PARAM] size: 最大の当選者数 | |
# | |
# add(member, weight) | |
# 応募者を追加する。 | |
# [PARAM] member: 応募者 | |
# [PARAM] weight: 1以上の整数で指定する当選確率の重み。大きいほど当選しやすい。 | |
# | |
# winners -> Array | |
# 当選者の配列を返す。当選者はweightを考慮しつつ、ランダムに選択される。 | |
# | |
# [詳細] | |
# - winnersは繰り返し呼べる。呼び出しのたびに結果が変わる。 | |
# - winnersの中身は重複してはいけない | |
# - 応募者数(member)が商品の数(size)よりもすくなければ、全員が当選者(winners)となる。 | |
# また、このときwinnersの数と追加されたmemberの数は等しくなる(size以下のwinnersになる)。 | |
# - newの引数(size)が0であれば、winnersは空の配列([])が返る。 | |
# - addされたmemberが0であれば、winnersは空の配列([])が返る。 | |
# | |
# [考慮不要] | |
# - newの引数に0以上の整数以外が渡された場合 | |
# - addの第1引数(member)に同じ値(==で比較するとtrue)が2回以上渡された場合 | |
# - addの第2引数(weight)に1以上の整数以外が渡された場合 | |
# Lotteryクラスの実行例 | |
lottery = Lottery.new(3) # 当選者は最大3人 | |
# 応募者を追加(1以上の整数で重みを付ける) | |
lottery.add('John', 1) # 確率 1/20 | |
lottery.add('Tom', 2) # 2/20 | |
lottery.add('Bill', 5) # 5/20 | |
lottery.add('Woz', 2) # 2/20 | |
lottery.add('Ken', 10) # 10/20 | |
# 当選者を発表する | |
# (KenはJohnより10倍当選しやすいが、Johnが当選する確率も0ではない) | |
lottery.winners | |
=> ["Ken", "Bill", "John"] | |
lottery.winners | |
=> ["Bill", "Ken", "Tom"] | |
lottery.winners | |
=> ["Ken", "Tom", "John"] | |
lottery.winners | |
=> ["Ken", "Woz", "John"] | |
lottery.winners | |
=> ["Ken", "Bill", "Woz"] | |
lottery.winners | |
=> ["Bill", "Tom", "Ken"] | |
lottery.winners | |
=> ["Bill", "Ken", "Woz"] | |
lottery.winners | |
=> ["Bill", "Ken", "John"] | |
lottery.winners | |
=> ["Tom", "Ken", "John"] | |
lottery.winners | |
=> ["Woz", "John", "Tom"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment