Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
simple cache
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
#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
[
+
]
Show input
Absolute running time: 0.13 sec, cpu time: 0.03 sec, memory peak: 7 Mb, absolute service time: 0.14 sec
edit mode
|
history
|
discussion