Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/bitcoin/network/node.rb

Instance Method Summary collapse

Instance Method Details

#random(weights = nil) ⇒ Object



481
482
483
484
485
486
487
488
489
490
491
492
493
# File 'lib/bitcoin/network/node.rb', line 481

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



495
496
497
498
499
500
501
502
503
504
505
506
507
508
# File 'lib/bitcoin/network/node.rb', line 495

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