Skip to content

Commit

Permalink
Speed up Network#next by building the weighted array on-the-fly
Browse files Browse the repository at this point in the history
  • Loading branch information
sstephenson committed Apr 12, 2009
1 parent 17d3864 commit 517f96e
Showing 1 changed file with 3 additions and 12 deletions.
15 changes: 3 additions & 12 deletions lib/minihal/network.rb
@@ -1,6 +1,7 @@
module Minihal
class Network
def initialize
@values = []
@weights = Hash.new
end

Expand All @@ -9,26 +10,16 @@ def [](value)
end

def increment(value)
@values << value
if @weights[value]
@weights[value] += 1
else
@weights[value] = 1
end
end

def values
@weights.values
end

def next
values = to_a
values[rand(values.length)]
end

def to_a
@weights.inject([]) do |values, (value, weight)|
values += [value] * weight
end
@values[rand(@values.length)]
end
end
end

0 comments on commit 517f96e

Please sign in to comment.