项目作者: juyeong

项目描述 :
Ruby weighted random
高级语言: Ruby
项目地址: git://github.com/juyeong/wrandom.git
创建时间: 2016-01-30T05:21:25Z
项目社区:https://github.com/juyeong/wrandom

开源协议:Other

下载


Build Status
Code Climate

wrandom

Ruby weighted random

Installation

  1. gem install wrandom

Usage

  1. # wsample => obj
  2. # wsample(random: rng) => obj
  3. # wsample(n) => new_ary
  4. # wsample(n, random: rng) => new_ary
  5. # wshuffle => new_ary
  6. # wshuffle(random: rng) => new_ary
  7. # wshuffle! => ary
  8. # wshuffle!(random: rng) => ary
  9. arr = [1, 2, 3]
  10. # Choose a weighted random element from the array.
  11. arr.wsample { |v| v * 10 } #=> 3
  12. # Choose n weighted random elements from the array.
  13. arr.wsample(2) { |v| v * 10 } #=> [3, 2]
  14. # Choose n weighted random elements from the array.
  15. arr.wsample(2, random: Random.new) { |v| v * 10 } #=> [3, 2]
  16. # Returns a new array with shuffled by weight.
  17. arr.wshuffle { |v| v * 10 } #=> [3, 2, 1]
  18. arr #=> [1, 2, 3]
  19. # Shuffles elements by weight.
  20. arr.wshuffle! { |v| v * 10 } #=> [3, 2, 1]
  21. arr #=> [3, 2, 1]
  1. # [1,9].sample
  2. Hash[100_000.times.map { [1,9].sample }.group_by(&:to_i).map { |k,v| [k, (v.size.to_f / 1000)]}]
  3. #=> {1=>50.111, 9=>49.889}
  4. # [1,9].wsample { |v| 1 }
  5. Hash[100_000.times.map { [1,9].wsample { |v| 1 } }.group_by(&:to_i).map { |k,v| [k, (v.size.to_f / 1000)]}]
  6. #=> {1=>50.111, 9=>49.889}
  7. # [1,9].wsample { |v| v }
  8. Hash[100_000.times.map { [1,9].wsample { |v| v } }.group_by(&:to_i).map { |k,v| [k, (v.size.to_f / 1000)]}]
  9. #=> {9=>89.887, 1=>10.113}

License

The MIT License (MIT)