Skip to content

Instantly share code, notes, and snippets.

@VegaFromLyra
Created May 31, 2015 22:33
Show Gist options
  • Save VegaFromLyra/f9b5ac7d3bf56f18f6b8 to your computer and use it in GitHub Desktop.
Save VegaFromLyra/f9b5ac7d3bf56f18f6b8 to your computer and use it in GitHub Desktop.
LRUCache
using System;
using System.Collections.Generic;
namespace LRUCache
{
public class Program
{
public static void Main(string[] args)
{
int totalNumberOfGames = 4;
Storage<int> gamesWon = new Storage<int>(totalNumberOfGames);
gamesWon.Put("Spurs", 5);
gamesWon.Put("Warriors", 2);
gamesWon.Put("Clippers", 3);
gamesWon.Put("Hawks", 4);
gamesWon.Get("Spurs");
gamesWon.Put("Raptors", 3);
gamesWon.Put("Raptors", 4);
Console.WriteLine("Spurs won " + gamesWon.Get("Spurs") + " games this season!");
Console.WriteLine("Raptors won " + gamesWon.Get("Raptors") + " games this season!");
var gamesWonByWarriors = gamesWon.Get("Warriors");
Console.WriteLine("Warriors record found? {0}", gamesWonByWarriors != 0);
}
}
public class Storage<T> {
LinkedList<Data<T>> orderedListOfData;
Dictionary<string, LinkedListNode<Data<T>>> map;
public Storage(int capacity) {
Capacity = capacity;
orderedListOfData = new LinkedList<Data<T>>();
map = new Dictionary<string, LinkedListNode<Data<T>>>();
}
public int Capacity { get; private set; }
public void Put(string key, T payload) {
if (map.ContainsKey(key)) {
var listNode = getNode(key);
listNode.Value.Payload = payload;
} else {
if (map.Count == Capacity) {
removeLeastRecentlyUsed();
}
var data = new Data<T>(key, payload);
var newNode = new LinkedListNode<Data<T>>(data);
orderedListOfData.AddFirst(newNode);
map.Add(key, newNode);
}
}
public T Get(string key) {
var listNode = getNode(key);
if (listNode != null) {
return listNode.Value.Payload;
}
return default(T);
}
LinkedListNode<Data<T>> getNode(string key) {
if (!map.ContainsKey(key)) {
return null;
}
var listNode = map[key];
orderedListOfData.Remove(listNode);
orderedListOfData.AddFirst(listNode);
return listNode;
}
void removeLeastRecentlyUsed() {
var dataToRemove = orderedListOfData.Last.Value;
map.Remove(dataToRemove.Key);
orderedListOfData.RemoveLast();
}
}
public class Data<T> {
public Data(string key, T payload) {
Key = key;
Payload = payload;
}
public string Key { get; private set; }
public T Payload { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment