Class: Array
- Inherits:
-
Object
- Object
- Array
- Defined in:
- lib/bitcoin/network/node.rb
Instance Method Summary collapse
Instance Method Details
#random(weights = nil) ⇒ Object
356 357 358 359 360 361 362 363 364 365 366 367 368 |
# File 'lib/bitcoin/network/node.rb', line 356 def random(weights=nil) return random(map {|n| yield(n) }) if block_given? return random(map {|n| n.send(weights) }) if weights.is_a? Symbol weights ||= Array.new(length, 1.0) total = weights.inject(0.0) {|t,w| t+w} point = rand * total zip(weights).each do |n,w| return n if w >= point point -= w end end |
#weighted_sample(n, weights = nil) ⇒ Object
370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
# File 'lib/bitcoin/network/node.rb', line 370 def weighted_sample(n, weights = nil) src = dup buf = [] n = src.size if n > src.size while buf.size < n if block_given? item = src.random {|n| yield(n) } else item = src.random(weights) end buf << item; src.delete(item) end buf end |