Created
October 26, 2012 15:08
-
-
Save numa08/3959321 to your computer and use it in GitHub Desktop.
重み付き乱択アルゴリズム ref: http://qiita.com/items/6d20c2571dac55e4de4c
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
#! ruby | |
class DUP | |
def initialize(name, age) | |
@name = name | |
@age = age | |
end | |
attr_accessor :name,:age | |
end | |
def make_random_picker(dup) | |
dup.sort{|a,b| a.age <=> b.age} | |
age_sum = 0 | |
dup.each do |d| | |
age_sum += d.age | |
end | |
dup.each do |d| | |
d.age /= age_sum | |
end | |
r = rand() | |
sum = 0 | |
dup.each do |d| | |
sum += d.age | |
return d if r < sum | |
end | |
return dup[dup.length - 1] | |
end | |
20.times do | |
p make_random_picker([DUP.new("digiko", 10.0), | |
DUP.new("usada", 14.0), | |
DUP.new("puchiko", 5.0), | |
DUP.new("piyoko", 7.0), | |
DUP.new("rinna", 10.0), | |
DUP.new("mike", 10.0)]).name | |
end |
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
274 "usada" | |
179 "digiko" | |
171 "rinna" | |
171 "mike" | |
130 "piyoko" | |
75 "puchiko" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment