scala

/ LRU Cache with max size (not included any concurrency control) // putEntry -- add elements to cache // removeEntry -- remove Elements from cache // it will remove eldest key from cache when it exceeds limit. object Main extends App { import scala.collection.mutable case class LRUCache[K,V](private val MAX_ENTRIES:Int) { private val cache = mutable.LinkedHashMap.empty[K,V] def putEntry(key:K, value:V):Unit = { removeEldest cache += (key -> value) } def getEntry(key:K):Option[V] = { val keyValue = cache.remove(key) if (keyValue != None) { cache.put(key,keyValue.get) } keyValue } def removeEldest { if (!cache.isEmpty && cache.size >= MAX_ENTRIES) { cache -= cache.head._1 } } } //Test Cases val lruCache = LRUCache[Int,Int](5) lruCache.putEntry(1,1) lruCache.putEntry(2,2) lruCache.putEntry(3,3) lruCache.putEntry(4,4) lruCache.putEntry(5,5) // remove eledest (it should remove key 1) lruCache.putEntry(6,6) // key 1 should give None lruCache.getEntry(1) //move to front when we access element lruCache.getEntry(2) lruCache.putEntry(7,7) // it should remove elemnt 3 instead of 2, as 2 moved to front. }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.