Tuesday, June 23, 2015

[Coding Quiz] LRU cache (last recently used)

/*
Amazon interview SDET June 2015

Limited size cache

create a limited size cache (Java LRUMap).

    when set, if there is an existing item with the same key. it overwrite the old value.
    when set, if it already reaches its size limit, it remove the oldest item.
    when get, if it does not hit, should return -1, should NOT throw exception.

http://stackoverflow.com/questions/9916189/hashtable-with-limited-size

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.1_r1/android/util/LruCache.java

http://crunchify.com/how-to-create-a-simple-in-memory-cache-in-java-lightweight-cache/
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CT.Hash
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }

    interface ILimitedHashTable<K, V>
    {
        void Set(K k, V v);
        V Get(K k);
    }

    class LimitedHashTable<K, V> : ILimitedHashTable<K, V>
    {
        Dictionary<K, V> dict = new Dictionary<K, V>();

        Queue<K> queue = new Queue<K>();

        const int MAXSIZE = 100;

        public void Set(K k, V v)
        {
            if (dict.ContainsKey(k))
            {
                dict[k] = v;
                return;
            }

            if (dict.Count() >= MAXSIZE)
            {
                dict.Remove(queue.Dequeue());
            }

            dict.Add(k, v);
            queue.Enqueue(k);

        }

        public V Get(K k)
        {
            if (!dict.ContainsKey(k))
                return default(V);

            return dict[k];
        }
    }
}

No comments:

Post a Comment