-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLFU.cs
More file actions
79 lines (61 loc) · 2.34 KB
/
LFU.cs
File metadata and controls
79 lines (61 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System.Collections.Generic;
namespace AlgorithmsAndDataStructures.DataStructures.Cache;
public class Lfu
{
private const int DefaultFrequency = 1;
private readonly int capacity;
private readonly Dictionary<int, CacheDoubleLinkedList> frequencies;
private readonly Dictionary<CacheEntry, int> nodeFrequencies;
private readonly Dictionary<int, CacheEntry> values;
private int entriesCount;
private int minFrequency;
public Lfu(int capacity)
{
values = new Dictionary<int, CacheEntry>();
frequencies = new Dictionary<int, CacheDoubleLinkedList>();
nodeFrequencies = new Dictionary<CacheEntry, int>();
minFrequency = int.MaxValue;
this.capacity = capacity;
entriesCount = 0;
}
public void Add(int key, string value)
{
if (values.ContainsKey(key))
{
values[key].UpdateValue(value);
PromoteEntry(values[key]);
return;
}
if (entriesCount == capacity)
{
var evictedEntry = frequencies[minFrequency].RemoveTail();
values.Remove(evictedEntry.Key);
if (frequencies[minFrequency].IsEmpty) frequencies.Remove(minFrequency);
entriesCount--;
}
if (!frequencies.ContainsKey(DefaultFrequency)) frequencies[DefaultFrequency] = new CacheDoubleLinkedList();
var newEntry = new CacheEntry(key, value);
frequencies[DefaultFrequency].InsertToHead(newEntry);
values[key] = newEntry;
nodeFrequencies[newEntry] = DefaultFrequency;
minFrequency = DefaultFrequency;
entriesCount++;
}
public string Get(int key)
{
if (!values.ContainsKey(key)) return null;
var entry = values[key];
PromoteEntry(entry);
return entry.Value;
}
private void PromoteEntry(CacheEntry cacheEntry)
{
var currentFrequency = nodeFrequencies[cacheEntry];
frequencies[currentFrequency].Remove(cacheEntry);
if (frequencies[currentFrequency].IsEmpty) frequencies.Remove(currentFrequency);
var newFrequency = ++currentFrequency;
if (!frequencies.ContainsKey(newFrequency)) frequencies[newFrequency] = new CacheDoubleLinkedList();
frequencies[newFrequency].InsertToHead(cacheEntry);
nodeFrequencies[cacheEntry] = newFrequency;
}
}