Skip to content

Instantly share code, notes, and snippets.

@goldengrape
Last active November 16, 2019 08:14
Show Gist options
  • Save goldengrape/6ff99ac3c861812cd6f4f9375da734a7 to your computer and use it in GitHub Desktop.
Save goldengrape/6ff99ac3c861812cd6f4f9375da734a7 to your computer and use it in GitHub Desktop.
按概率随机选取, 使用Hash table, 键=>相对概率, sonic-pi测试通过
# base from https://stackoverflow.com/a/19265735/9191373
def picker(options)
current, max = 0, options.values.inject(:+)
random_value = rrand(0,max)
options.each do |key,val|
current += val
return key if random_value <= current
end
end
opti = {:C4=>1, :D4=>2, :E4=>3 }
9.times do
play picker(opti)
sleep 0.25
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment