Skip to content

Instantly share code, notes, and snippets.

@jfinucane
Last active November 15, 2018 15:02
Show Gist options
  • Save jfinucane/72e32a9ad61ced7d3343ebb15e978913 to your computer and use it in GitHub Desktop.
Save jfinucane/72e32a9ad61ced7d3343ebb15e978913 to your computer and use it in GitHub Desktop.
LRU wip
class Node
attr_accessor :prev, :next, :value
end
class ListManager
def initialize(capacity)
@capacity = capacity
@used=0
@head = nil
@last =nil
end
def use_key pos
#puts "#got here use_key #{pos} #{pos.prev},head is #{@head}"
return @pos if pos == @head
if pos == @last
@last = pos.prev
else
pos.next.prev = pos.prev #if pos.next
end
pos.prev.next = pos.next
pos.prev = nil
pos.next = @head
@head.prev=pos
@head = pos
end
def add_key value
if @used < @capacity
n = Node.new
if @head
@head.prev = n
n.next = @head
else
@last = n
end
n.value = value
@head = n
@used += 1
return @head, nil
else
evicted_key = @last.value #testme
pos = use_key @last
return pos, evicted_key
end
end
end
class LRUCache
=begin
:type capacity: Integer
=end
def initialize(capacity)
@dict = {} #returns value, list_index
@node = ListManager.new(capacity)
end
=begin
:type key: Integer
:rtype: Integer
=end
def get(key)
value, pos = @dict[key]
puts "get #{key} gives #{value}"
if pos
@node.use_key pos
return value
else
return -1
end
end
=begin
:type key: Integer
:type value: Integer
:rtype: Void
=end
def put(key, value)
puts "puts #{key}, #{value} #{@dict.keys}"
lookup = @dict[key]
if lookup
ptr = @node.use_key lookup[1]
else
ptr, evicted_key = @node.add_key(key)
#puts "evicted #{evicted_key}, dict #@dict"
@dict.delete(evicted_key) if evicted_key
end
@dict[key] = [value,ptr]
end
end
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache.new(capacity)
# param_1 = obj.get(key)
# obj.put(key, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment