rejection_sampling.sf 1021 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/ruby
  2. #
  3. ## Rejection sampling algorithm
  4. ## https://en.wikipedia.org/wiki/Rejection_sampling
  5. #
  6. func accept_reject(table) {
  7. var accepted = nil
  8. var max_fitness = table.map{|h| h{:weight} }.max
  9. var prob = max_fitness.rand
  10. loop {
  11. var item = table.rand
  12. if (prob < item{:weight}) {
  13. accepted = item
  14. break
  15. }
  16. }
  17. accepted
  18. }
  19. var table = [
  20. Hash(value => "Sidef", weight => 1.0.rand(0.5)),
  21. Hash(value => "Ruby", weight => 0.5.rand),
  22. Hash(value => "Perl", weight => 0.5.rand),
  23. Hash(value => "Python", weight => 0.5.rand),
  24. Hash(value => "Julia", weight => 0.5.rand),
  25. ]
  26. var picked = accept_reject(table)
  27. say "Picked #{picked{:value}} with a probability of #{picked{:weight}.round(-2)}%"
  28. var freq = 100.of { accept_reject(table){:value} }.freq
  29. var max = freq.max_by { |_,v| v }
  30. if (max.key == "Sidef") {
  31. say "In average, Sidef is the winner!"
  32. }
  33. else {
  34. say "In average, #{max.key} is the winner -- that's sad..."
  35. }