A set-associative LRU cache

A k-way set-associative cache lets a block live in any of the k lines of its set, and throws out the least recently used block when the set is full.

What to build

A program that simulates the cache on a list of addresses and prints hits and misses.

Requirements

  • The cache has lines lines in total, split into lines ÷ ways sets of ways lines each. Block number is address ÷ block size (rounded down), and the set is block mod number of sets. All sets start empty.
  • A hit moves the block to the most recently used place. A miss puts the block there, first removing the least recently used block if the set is full.
  • Print a string with H or M for each address, then hits and the number of hits.

Input

A line with lines, ways and block size. A line with n, then a line with n addresses.

Output

Two lines.

Constraints

ways divides lines; 1 ≤ n ≤ 200; addresses are from 0 to 65535.

Example

Input:

4 2 4
5
0 16 0 32 16

Output:

MMHMM
hits 1

Why it works

LRU bets on temporal locality: the block used longest ago is the least likely to be used soon. Keeping each set in order of use makes the victim simply the first element.

Examples

Example 1 · Input
4 2 4
5
0 16 0 32 16
Expected output
MMHMM
hits 1
Example 2 · Input
4 1 4
5
0 16 0 16 0
Expected output
MMMMM
hits 0

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Keep one list per set, ordered from least recently used (front) to most recently used (back).

Hint 2

The set of a block b is b % sets, where sets = lines // ways.

Hint 3

On a hit, move the block to the back. On a miss, if the set already has `ways` blocks remove the first, then append the block.

Solution

Show one correct solution (try it yourself first)
lines, ways, block = map(int, input().split())
n = int(input())
addresses = list(map(int, input().split()))
sets = lines // ways
cache = [[] for _ in range(sets)]
out = ""
for a in addresses:
    b = a // block
    s = cache[b % sets]
    if b in s:
        s.remove(b)
        s.append(b)
        out += "H"
    else:
        if len(s) == ways:
            s.pop(0)
        s.append(b)
        out += "M"
print(out)
print("hits", out.count("H"))

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Cache memory →