Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
ruby LRU cache with constant get/set
#Title of this code #ruby 2.1.2p95 Node = Struct.new(:value,:next,:prev) #double link list implementation to work as a queue class DListQueue def initialize(size) @size = size @head = nil @tail = nil @counter = 0 end def enqueue(node) @counter = @counter+1 if @head == nil and @tail == nil @head = @tail = node else node.next = @head @head.prev = node @head = node end end def dequeue() temp = @tail @tail.prev.next = nil @tail = @tail.prev @counter = @counter -1 return temp end def move_back(node) cur = node cur.prev.next = cur.next cur.next.prev = cur.prev node.next = @head @head.prev = node @head = node end def traversal cur = @head while cur != nil puts cur.value cur = cur.next end end end #lru cache implementatio to work class LRUCache def initialize(size) @size = size @hash = {} @queue = DListQueue.new(size) end def get(cache_id) if @hash[cache_id] update_access_table(@hash[cache_id][1]) return @hash[cache_id][0] else "invalid cache_id" end end def set(cache_id,value) remove_least_accesed if @hash.length > @size-1 if @hash[cache_id] @hash[cache_id][0] = value else node = Node.new(cache_id) @hash[cache_id] = [value,node] @queue.enqueue(node) end end def remove_least_accesed item = @queue.dequeue() @hash.delete(item.value) end def update_access_table(node) @queue.move_back(node) end def hash @hash end def queue @queue end end
run
|
edit
|
history
|
help
0
simple cache
Arithmetic Operations, Function Calls, Recursion and more in Ruby
Ruby
soncita
Hash and Symbols
variables output
regex.rb
Adiel Vasquez
faktorial
variables 1