class Array
Public Instance Methods
wsample(*args, &block)
click to toggle source
# File lib/wrandom.rb, line 2 def wsample(*args, &block) count, options = \ if args.size == 0 || args[0].class == Hash [nil, args[0]] else [args[0], args[1]] end arr = wshuffle(options, &block) count ? arr.first(count) : arr.first end
wshuffle(options = {}, &block)
click to toggle source
# File lib/wrandom.rb, line 13 def wshuffle(options = {}, &block) sort_by { |v| w_algorithm(v, options, &block) }.reverse! end
wshuffle!(options = {}, &block)
click to toggle source
# File lib/wrandom.rb, line 17 def wshuffle!(options = {}, &block) sort_by! { |v| w_algorithm(v, options, &block) }.reverse! end
Private Instance Methods
w_algorithm(v, options = {}, &block)
click to toggle source
# File lib/wrandom.rb, line 23 def w_algorithm(v, options = {}, &block) # Pavlos S. Efraimidis, Paul G. Spirakis # Weighted random sampling with a reservoir # Information Processing Letters # Volume 97 Issue 5, 16 March 2006 # Pages 181-185 r = options[:random] ? options[:random].rand : rand rescue rand population = block.call(v) r ** ( 1.0 / population ) end