Advertisement
Guest User

sliding_window_map.rb

a guest
Sep 3rd, 2012
16
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.10 KB | None | 0 0
  1. # By Pseudon Mousie
  2.  
  3. class SlidingWindowMap
  4.  
  5.   # Create a hash, with the keys as keys
  6.   # The values will be the timestamps when the key was used.
  7.     def initialize(keys, max_count, period_ms, verbose=false)
  8.     @verbose = verbose
  9.     @key_counts = Hash.new
  10.     keys.each{|key|
  11.       @key_counts[key] = []
  12.     }
  13.     @max_count = max_count
  14.     # store period in floating point seconds to match Time objects
  15.     @period_f_sec = period_ms / 1000.0
  16.     puts "keycounts:#{@key_counts.inspect}..." if @verbose
  17.     end
  18.  
  19.     def getNextKey()
  20.         @key_counts.keys.each{|key|
  21.     puts "checking #{key}..." if @verbose
  22.             return key if has_uses_remaining?(key)
  23.     }
  24.     nil
  25.     end
  26.  
  27.   # Calling this function counts as a "use"
  28.   # unless there are no uses available.
  29.   def has_uses_remaining?(key)
  30.     times_used = @key_counts[key]
  31.     # Clear out expired uses
  32.     while !(times_used.empty?) && (times_used.first < Time.now)
  33.       times_used.shift
  34.     end
  35.     if times_used.length < @max_count
  36.       times_used.push(Time.now + @period_f_sec)
  37.       return true
  38.     else
  39.       return false
  40.     end
  41.   end
  42. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement