View difference between Paste ID: iiAjfC3V and Wh86ZnkZ
SHOW: | | - or go back to the newest paste.
1
# By Pseudon Mousie
2
class SlidingWindowMap
3
  
4
  # Create a hash, with the keys as keys
5
  # The values will be the timestamps when the key was used.
6
  def initialize(keys, max_count, period_ms, verbose=false)
7-
	def initialize(keys, max_count, period_ms, verbose=false)
7+
8
    @key_counts = Hash.new
9
    keys.each{|key|
10
      @key_counts[key] = []
11
    }
12
    @max_count = max_count
13
    # store period in floating point seconds to match Time objects
14
    @period_f_sec = period_ms / 1000.0
15
    puts "keycounts:#{@key_counts.inspect}..." if @verbose
16
  end
17-
	end
17+
18
  def getNextKey()
19-
	def getNextKey()
19+
    @key_counts.keys.each{|key|
20-
		@key_counts.keys.each{|key|
20+
21
      return key if has_uses_remaining?(key)
22-
			return key if has_uses_remaining?(key)
22+
23
    nil 
24
  end
25-
	end
25+
26
  # Calling this function counts as a "use"
27
  # unless there are no uses available.
28
  def has_uses_remaining?(key)
29
    times_used = @key_counts[key]
30
    # Clear out expired uses
31
    while !(times_used.empty?) && (times_used.first < Time.now)
32
      times_used.shift
33
    end
34
    if times_used.length < @max_count
35
      times_used.push(Time.now + @period_f_sec) 
36
      return true
37
    else
38
      return false
39
    end
40
  end
41
end