Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
simple cache
#Title of this code #ruby 2.1.2p95 class SACache def initialize(cache_size) @size = cache_size @cache = Hash.new @access_map = Hash.new end def get cache_id if @cache[cache_id] @access_map[cache_id] = @access_map[cache_id] + 1 # complexity 1 @cache[cache_id] else "invalid cache_id" end end def put cache_id, data remove_least_accessed if @cache.length >= @size @cache[cache_id] = data @access_map[cache_id] = 0 end def remove_least_accessed to_be_removed = nil c = 0 recent = nil @access_map.each do |cid,acc| #here the complexity is log n to find most least accessed cached item if c == 0 recent = acc to_be_removed = cid else if acc < recent recent = acc to_be_removed = cid end end c = c + 1 end @cache.delete(to_be_removed) @access_map.delete(to_be_removed) end def print_cache_structure @cache end def print_access_map_structure @access_map end end awesome_cache = SACache.new(5) awesome_cache.put 'c1',"this sample cache data1" awesome_cache.put 'c2',"this sample cache data2" awesome_cache.put 'c3',"this sample cache data3" awesome_cache.put 'c4',"this sample cache data4" awesome_cache.put 'c5',"this sample cache data5" awesome_cache.put 'c6',"this sample cache data6" awesome_cache.get 'c2' awesome_cache.get 'c2' awesome_cache.get 'c3' awesome_cache.get 'c4' awesome_cache.get 'c6' awesome_cache.get 'c2' awesome_cache.get 'c3' awesome_cache.get 'c3' awesome_cache.get 'c2' awesome_cache.get 'c6' awesome_cache.put 'c9',"this sample cache data9" puts awesome_cache.print_cache_structure puts awesome_cache.print_access_map_structure
run
|
edit
|
history
|
help
0
MY CODE
IS_IP?
Testing out multiple variable returns in a method
Ruby Inheritence
regex.rb
My code
3.4.0 / 3.5.2 / 3.5.1 / 3.6.1 / 3.6.5.#
Calculator
variables output
Division Function without / or * signs