src/vsphere_cpi/lib/cloud/vsphere/resources/util.rb
# Returns a random item from the given list distributed based on the
# provided weight.
#
# @param [Array] list array of tuples containing the item and weight.
# @return [Object] random item based on provided weight.
Returns a random item from the given list distributed based on the
provided weight.
Returns a random item from the given list distributed based on the provided weight .
def weighted_random(list)
          return nil if list.empty?
          weight_sum = list.inject(0) { |sum, x| sum + x[1] }
          index = rand(weight_sum)
          offset = 0
          list.each do |el, weight|
            offset += weight
            return el if index < offset
          end
          raise ArgumentError, "index: #{index} sum: #{weight_sum}"
        end
def weighted_random ( list ) return nil if list . empty? weight_sum = list . inject ( 0 ) { | sum , x | sum + x [ 1 ] } index = rand ( weight_sum ) offset = 0 list . each do | el , weight | offset += weight return el if index < offset end raise ArgumentError , "index: #{index} sum: #{weight_sum}" end
Returns a random item from the given list distributed based on the
provided weight.
Returns a random item from the given list distributed based on the provided weight .
# Should never happen
random item based on provided weight.
random item based on provided weight .
Object
list
list array of tuples containing the item and weight.
list array of tuples containing the item and weight .