SHARE
TWEET

sliding_window_map.rb

a guest Sep 3rd, 2012 104 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.     @verbose = verbose
  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.  
  18.   def getNextKey()
  19.     @key_counts.keys.each{|key|
  20.     puts "checking #{key}..." if @verbose
  21.       return key if has_uses_remaining?(key)
  22.     }
  23.     nil
  24.   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
RAW Paste Data
Want to get better at Ruby?
Learn to code Ruby in 2017
Pastebin PRO Summer Special!
Get 40% OFF on Pastebin PRO accounts!
Top