Questa sfida è davvero semplice (e un precursore di una più difficile!).
Dato un array di accessi alle risorse (semplicemente indicato da numeri interi non negativi) e un parametro n
, restituisce il numero di errori della cache che avrebbe supponendo che la nostra cache abbia capacità n
e utilizza uno schema di espulsione first-in-first-out (FIFO) quando è pieno .
Esempio:
4, [0, 1, 2, 3, 0, 1, 2, 3, 4, 0, 0, 1, 2, 3]
0 = not in cache (miss), insert, cache is now [0]
1 = not in cache (miss), insert, cache is now [0, 1]
2 = not in cache (miss), insert, cache is now [0, 1, 2]
3 = not in cache (miss), insert, cache is now [0, 1, 2, 3]
0 = in cache (hit), cache unchanged
1 = in cache (hit), cache unchanged
2 = in cache (hit), cache unchanged
3 = in cache (hit), cache unchanged
4 = not in cache (miss), insert and eject oldest, cache is now [1, 2, 3, 4]
0 = not in cache (miss), insert and eject oldest, cache is now [2, 3, 4, 0]
0 = in cache (hit), cache unchanged
1 = not in cache (miss), insert and eject oldest, cache is now [3, 4, 0, 1]
2 = not in cache (miss), insert and eject oldest, cache is now [4, 0, 1, 2]
3 = not in cache (miss), insert and eject oldest, cache is now [0, 1, 2, 3]
Quindi in questo esempio c'erano 9 mancati. Forse un esempio di codice aiuta a spiegarlo meglio. In Python:
def num_misses(n, arr):
misses = 0
cache = []
for access in arr:
if access not in cache:
misses += 1
cache.append(access)
if len(cache) > n:
cache.pop(0)
return misses
Alcuni ulteriori test (che contengono un suggerimento per la prossima sfida - noti qualcosa di curioso?):
0, [] -> 0
0, [1, 2, 3, 4, 1, 2, 3, 4] -> 8
2, [0, 0, 0, 0, 0, 0, 0] -> 1
3, [3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4] -> 9
4, [3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4] -> 10
Vince il codice più breve in byte.
notice anything curious?
da un po 'di tempo ... e ho appena notato, aumentare la capacità della cache non riduce necessariamente il numero di errori ?!