-
-
Save brainwire/38b226044867eb84021f 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
# позволяет получить процентное соотношение для чисел в массиве | |
# percents [1,2,3] => [0.16666666666666666, 0.3333333333333333, 0.5] | |
def percents(numbers) | |
total = numbers.inject(:+).to_f | |
numbers.map {|it| it / total } | |
end | |
# позволяет получить процентное распределение для чисел в массиве | |
# требуется чтобы генерировать рендомное число с заданными вероятностями | |
# distribution [1,2,3] => [0.16666666666666666, 0.5, 1.0] | |
# например, если rand вернет число | |
# - от 0 до 0.16 - это первый элемент | |
# - от 0.16 до 0.5 - это второй элемент | |
# - от 0.5 до 1.0 - это последний элемент | |
def distribution(numbers) | |
percents(numbers).inject([]) do |range, it| | |
range.push it + range.fetch(-1, 0) | |
end | |
end | |
# позволяет разбить число на случайные положительные составляющие с учетом приоритетов | |
# split_number 10, [1,1,98] => [1, 1, 8] | |
# в данном примере будет в среднем два раза из 100 возвращать другие значения | |
def split_number(number, chances) | |
range = distribution chances | |
number.times.group_by do |i| | |
random = rand | |
i < chances.size ? i : range.index {|it| it > random } | |
end.values.map &:size | |
end | |
# Пример разбиения числа на нужное количество случайных положительных составляющих, используя новый метод | |
# split_number_in_chunks(10, 3) == split_number(10, [0.33, 0.33, 0.33]) | |
# def split_number_in_chunks(number, count) | |
# split_number number, Array.new(count, 1.0 / count) | |
# end | |
# Example with pokemon | |
# def gain | |
# split_number 10, [attack_chance, defence_chance, speed_chance] | |
# end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment