Numero di errori cache FIFO


35

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à ne 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.


15
Stavo guardando l'ultima affermazione notice anything curious?da un po 'di tempo ... e ho appena notato, aumentare la capacità della cache non riduce necessariamente il numero di errori ?!
JungHwan Min

@JungHwanMin Correct! In effetti, quanto peggio può arrivare è illimitato.
orlp,

Possiamo emettere il numero in unario?
dylnan,

9
Conosciuta come l'anomalia di Bélády e FIFO è il classico esempio. L'anomalia è illimitata .
virtualirfan,

@dylnan No, scusa.
orlp,

Risposte:


11

JavaScript (ES6), 55 byte

Metodo n. 1: la cache sovrascrive l'input

Accetta input nella sintassi del curry (cache_size)(list).

n=>a=>a.map(x=>a[a.indexOf(x,k>n&&k-n)<k||k++]=x,k=0)|k

Provalo online!

Come?

Sovrascriviamo l'array di input a [] con la cache, usando un puntatore separato k inizializzato su 0 .

Usiamo a.indexOf(x, k > n && k - n) < kper verificare se x è nella cache.

La cache non può crescere più velocemente di quanto l'array originale venga attraversato, quindi si garantisce che ogni valore venga trovato, all'interno o oltre la finestra della cache (ovvero indexOf()non restituirà mai -1 ).

Un valore è nella cache se viene trovato in un indice tra max (0, k - n) e k - 1 (inclusi entrambi i limiti), nel qual caso facciamo un [vero] = x . Ciò influisce solo su una proprietà dell'oggetto sottostante dietro a [] ma non altera l' array a [] . Altrimenti, facciamo un [k ++] = x .

Esempio

Di seguito sono riportati i diversi passaggi per l'input [1, 1, 2, 3, 3, 2, 1, 4]con una dimensione della cache di 2 :

  • bordi in grassetto: puntatore map ()
  • parentesi: puntatore cache k
  • arancione: finestra cache corrente
  • giallo: valori cache scaduti

metodo n. 1


JavaScript (ES6), 57 byte

Metodo n. 2: la cache viene aggiunta alla fine dell'input

Accetta input nella sintassi del curry (cache_size)(list).

n=>a=>a.map(x=>n*~a.indexOf(~x,-n)||a.push(~x)&k++,k=0)|k

Provalo online!

Come?

Poiché è garantito che l'array di input a [] contenga numeri interi non negativi, possiamo tranquillamente aggiungere la cache alla fine di un [] utilizzando il complemento a uno ~ x di ciascun valore x .

Usiamo n * ~a.indexOf(~x, -n)per verificare se ~ x si trova tra gli ultimi n valori. Ogni volta che questo test fallisce, aggiungiamo ~ x a [] e incrementiamo il numero di miss k .

Esempio

Di seguito sono riportati i diversi passaggi per lo stesso esempio sopra riportato, utilizzando questo metodo. Poiché i valori della cache vengono semplicemente aggiunti alla fine dell'array, non esiste un puntatore di cache esplicito.

metodo n. 2



9

Python 2 , 58 byte

lambda n,a:len(reduce(lambda c,i:[i][i in c[:n]:]+c,a,[]))

Provalo online!

Grazie a ovs per 3 byte e xnor per altri 3.


Dovresti essere in grado di salvare i byte inserendo un set dopo c+=, poiché per qualche motivo viene convertito in un elenco per te.
xnor

(ah, sì, c+={i}-set(c[-n:])funziona, in senso positivo n. Ma Nimi ha sottolineato che c[-n:]è sbagliato n == 0, quindi non posso usarlo +=, e quindi quel trucco - peccato.)
Lynn,

1
@Lynn Ah, capisco. reducesalva ancora byte: lambda n,a:len(reduce(lambda c,i:[i][i in c[:n]:]+c,a,[])).
xnor

7

R , 69 64 62 byte

function(n,A,K={}){for(i in A)K=c(i[!i%in%K[0:n]],K);sum(K|1)}

Provalo online!

Grazie a JayCe per aver suggerito alcuni miglioramenti e DigEmAll per un'altra coppia!


Immagino che +davanti a Fsia per f(0,{})restituire 0?
JayCe,

@JayCe sì, un classico golf in tandem con Fun valore di ritorno pre-inizializzato.
Giuseppe,

1
un piccolo miglioramento . Inoltre, se viene accettato un output unario, probabilmente è possibile salvare alcuni byte.
JayCe,

@JayCe ha trovato altri byte!
Giuseppe,

1
@JDL sì, peccato per l' qidea ma comunque una bella idea! L'uso NAè meno buono dell'uso {}poiché mi interessa davvero la lunghezza qui (e non sto effettivamente estraendo elementi dalla cache).
Giuseppe,

5

Haskell, 61 58 byte

n!a|let(a:b)#c|elem a c=b#c|1<2=1+b#take n(a:c);_#_=0=a#[]

Provalo online!

n!a|      =a#[]     -- take input 'n' and a list 'a'
                    -- and call # with the initial list and an empty cache
 let                -- bind function '#':
  (a:b)#c           -- if there's at least one element 'a' left in the list
     |elem a c=b#c  --  and it's in the cache, go on with the same cache
                    --  and the remainder of the list
     |1<2=          -- else (i.e. cache miss)
          1+        --  add one to the recursive call of
       b#           --  the remainder of the list and 
       take n(a:c)  --  the first n elements of 'a' prepended to the cach
 _#_=0              -- if there's no element in the list, return 0

Modifica: -3 byte grazie a @Lynn.


5

05AB1E , 17 16 byte

)svDyå_i¼y¸ìI£]¾

Provalo online!

Spiegazione

)                   # wrap the stack in a list
 sv                 # for each item y in input list
   D                # duplicate current list
    yå_i            # if y is not contained in the current list
        ¼           # increment counter
         y¸ì        # prepend y to the current list
            I£      # keep the first input elements
              ]¾    # end loop and push counter

@nimi: grazie! Risolto durante il salvataggio di un byte :)
Emigna il

5

Kotlin , 82 69 byte

{a,n->a.fold(List(0){0}){c,v->if(v!in c.takeLast(n))c+v else c}.size}

Prende l'input come un IntArray, non il tipico List<Int>(che non dovrebbe essere un problema.) Questo utilizza l'approccio di "costruire una cronologia della cache e contarne la lunghezza".

Provalo online!

Spiegazione

{ a, n ->                         // lambda where a is accesses and n is cache size
    a.fold(List(0){0}) { c, v ->  // fold on empty list
        if(v !in c.takeLast(n))   // if resource is not in last n cache inserts
            c + v                 // insert to cache list
        else
            c                     // return cache as is
    }.size                        // length of cache list is number of inserts
}

Creazione di un elenco vuoto

Kotlin non ha letterali da collezione, ma ha alcune funzioni per creare nuove collezioni.

Il modo corretto di creare un vuoto List<Int>è semplicemente:

List<Int>()

ma è più breve se abusiamo delle dimensioni e l'inizializzatore sostiene di farlo:

List(0){0}
List(0)       // List of size 0
       { 0 }  // with generator returning 0

Poiché il generatore lambda restituisce 0, Kotlin indica il tipo di questo elenco List<Int>e la dimensione 0 indica che questo elenco è vuoto.


4

Perl 6 , 48 byte

{my@c;$_@c.tail($^n)||push @c,$_ for @^o;+@c}

Provalo

{  # bare block with placeholder params $n,@o

  my @c; # cache


      $_  @c.tail($^n) # is the current value in the last bit of the cache
    ||
      push @c, $_       # if not add it to the cache

  for                   # do this for all of

    @^o;                # the input array


  +@c                   # numify the cache (the count)
}

4

Java 8, 96 byte

Una lambda al curry che prende una dimensione della cache ( int) e un elenco di accesso (mutabile java.util.List<Integer>) e restituisce un int.

s->a->{int w=0,m=0,i;for(int r:a)m+=(i=a.indexOf(r))<w&i<s?0:s<1?1:1+0*a.set(w++%s,r);return m;}

Provalo online

Ungolfed

Questo utilizza i primi (fino a) sslot nell'elenco di input per la cache.

s ->
    a -> {
        int
            w = 0,
            m = 0,
            i
        ;
        for (int r : a)
            m +=
                (i = a.indexOf(r)) < w & i < s ?
                    0
                    s < 1 ?
                        1
                        : 1 + 0*a.set(w++ % s, r)
            ;
        return m;
    }

Ringraziamenti

  • bugfix grazie a nimi

4

Pyth ,  16 15 18 14  13 byte

Salvato 1 byte grazie a isaacg .

luaW-H>QGGHEY

Suite di test!

Questa sfida si adatta molto bene alla ustruttura di Pyth .

Come funziona

luaW-H>QGGHEY     Full program. Q = the cache length, E = the list.
 u         E      Reduce E with G = current value and H = corresponding element
            Y     With starting value Y, which is preinitialised to [] (empty list).
   W              Conditional application. If...
    -H            ... Filtering H on absence of...
      >QG         ... The last Q elements of G... 
                  ... Yields a truthy value (that is, H is not in G[-Q:]), then...
  a      GH       ... Append H to G.
                  ... Otherwise, return G unchanged (do not append H at all).
l                  Get the length of the result.

aW-H>QGGHbatte ?}H<GQG+HGdi 1
isaacg

@isaacg Grazie! Inizialmente l'ho avuto +G*]H!}H>QG, ma quando ho giocato a golf non ci avevo davvero pensato W... Bello!
Mr. Xcoder,

Che cosa fa esattamente u?
dylnan,

@dylnan uè un operatore con riduzione del valore iniziale. Proprio come Jelly'sƒ
Mr. Xcoder,


2

Japt, 16 byte

;£A¯V øX ªAiXÃAl

Provalo


Spiegazione

                     :Implicit input of array U and integer V
 £                   :Map over each X in U
; A                  :  Initially the empty array
   ¯V                :  Slice to the Vth element
      øX             :  Contains X?
         ª           :  Logical OR
          AiX        :  Prepend X to A
             Ã       :End map
              Al     :Length of A

1

K4 , 42 40 byte

Soluzione:

{*1+/1_{r,,(y;x#z,y)r:~z in y:*|y}[x]\y}

Esempi:

q)k)f:{*1+/1_{r,,(y;x#z,y)r:~z in y:*|y}[x]\y}
q)f[0;1 2 3 4 1 2 3 4]
8
q)f[2;0 0 0 0 0 0 0]
1
q)f[3;3 2 1 0 3 2 4 3 2 1 0 4]
9
q)f[4;3 2 1 0 3 2 4 3 2 1 0 4]
10

Spiegazione:

Per la funzione interna, y è la cache, z è la richiesta e x è la dimensione della cache.

{*1+/1_{r,,(y;x#z,y)r:~z in y:*|y}[x]\y} / the solution
{                                      } / lambda taking 2 args
       {                         }       / lambda taking 3 args
                                  [x]\y  / iterate over lambda with each y
                              *|y        / last (reverse, first) y
                            y:           / assign to y
                       z in              / is z in y?
                      ~                  / not 
                    r:                   / assign result to r (true=1,false=0)
           ( ;     )                     / 2-element list
                z,y                      / join request to cache
              x#                         / take x from cache (limit size)
            y                            / (else) return cache unchanged
          ,                              / enlist this result
        r,                               / join with r
     1_                                  / drop the first result
  1+/                                    / sum up (starting from 1)
 *                                       / take the first result

Gli appunti:

C'è probabilmente un modo migliore per fare tutto questo, ma questo è il primo modo che mi è venuto in mente.

La funzione può essere eseguita in questo modo per 36 byte :

q)k)*1+/1_{r,,(y;x#z,y)r:~z in y:*|y}[4]\3 2 1 0 3 2 4 3 2 1 0 4
10

Alternativa: utilizzare una variabile globale per memorizzare lo stato (non molto simile a K), 42 byte :

{m::0;(){$[z in y;y;[m+:1;x#z,y]]}[x]\y;m}

1

Brain-Flak , 172 byte

(([{}]<>)<{({}(()))}{}>)<>([]){{}<>((({})<{({}()<<>(({})<({}<>({}<>))>)<>>)}{}>)<<>(({})([{}]<>{<>(){[()](<{}>)}{}<><({}()<<>({}<>)>)>}{})){(<{}{}>)}{}>)<>([])}{}<>({}[]<>)

Provalo online!

# Initialize cache with n -1s (represented as 1s)
(([{}]<>)<{({}(()))}{}>)<>

# For each number in input
([]){{}

    # Keep n on third stack
    <>((({})<

        # For last n cache entries, compute difference between entry and new value
        {({}()<<>(({})<({}<>({}<>))>)<>>)}{}

    >)<

        # Get negation of current entry and...
        <>(({})([{}]<>

            {

                # Count cache hits (total will be 1 or 0)
                <>(){[()](<{}>)}{}

                # while moving entries back to right stack
                <><({}()<<>({}<>)>)>

            }{}

        ))

        # If cache hit, don't add to cache
        {(<{}{}>)}{}

    >)

<>([])}{}

# Compute cache history length minus cache size (to account for the initial -1s)
<>({}[]<>)

1

Gelatina , 18 byte

Ṗɼṛ;ɼe®Uḣ⁴¤C$¡€ṛLɼ

Provalo online!

Prende l'elenco come primo argomento e la capacità della cache come secondo argomento.

Ṗɼṛ;ɼe®Uḣ⁴¤C$¡€ṛLɼ
 ɼ                 Apply to the register:
Ṗ                  Pop. This initializes the register to the empty list.
  ṛ                Right argument. Yields the list of addresses.
              €    For each element in the list
             ¡     If{
     e                 the element is in
          ¤            nilad{
      ®                      the register
       U                     reversed
        ḣ                    first...
         ⁴                   (cache depth) number of elements
                             }
           C           Complement. 1 <-> 0. Easier to type this than "not".
            $          Combines everything up to `e` into a monad
                      }
                    Then{
    ɼ                    Apply to the register and store the result
   ;                     Append the element
                        }
                ṛ   Right argument:
                  ɼ Apply to the register:
                 L  Length

1

Rubino , 43 40 byte

->s,a,*r{a.count{|*x|r!=r=(r|x).pop(s)}}

Provalo online!

Grazie istocrate per la rasatura di 3 byte.


1
Bella risposta! È possibile salvare un paio di byte inizializzando r come parte dell'elenco degli argomenti: ->s,a,*rche fornisce anche la funzione bonus che il chiamante può adescare la cache passando argomenti aggiuntivi :)
histocrat

Oh, e allo stesso modo gettare xin una matrice:.count{|*x|
istocratico

1

C (gcc) , 112 110 108 byte

f(x,y,z)int*y;{int*i=y+z,b[x],m=0;for(wmemset(b,z=-1,x);i-y;y++)wmemchr(b,*y,x)?:++m*x?b[z=++z%x]=*y:0;x=m;}

Provalo online!

Leggermente meno golfato

f(x,y,z)int*y;{
 int*i=y+z,b[x],m=0;
 for(wmemset(b,z=-1,x);i-y;y++)
  wmemchr(b,*y,x)?:
   ++m*
   x?
    b[z=++z%x]=*y
   :
    0;
 x=m;
}

0

C (gcc) , 156 byte

s,n,m,i,j;f(x,_)int*_;{int c[x];n=m=0;for(i=0;i<x;++i)c[i]=-1;for(i=s=0;_[i]>=0;++i,s=0){for(j=0;j<x;++j)s|=(c[j]==_[i]);if(!s){c[n++]=_[i];m++;n%=x;}}x=m;}

Provalo online!

Descrizione:

s,n,m,i,j;                       // Variable declaration
f(x,_)int*_;{                    // F takes X (the cache size) and _ (-1-terminated data)
    int c[x];                    // declare the cache
    n=m=0;                       // next queue insert pos = 0, misses = 0
    for(i=0;i<x;++i)c[i]=-1;     // initialize the cache to -1 (invalid data)
    for(i=s=0;_[i]>=0;++i,s=0){  // for each datum in _ (resetting s to 0 each time)
        for(j=0;j<x;++j)         // for each datum in cache
            s|=(c[j]==_[i]);     // set s if item found
        if(!s){                  // if no item found
            c[n++]=_[i];         // add it to the cache at position n
            m++;                 // add a mis
            n%=x;                // move to next n position (with n++)
        }} x=m;}                 // 'return' m by assigning to first argument

Suggerisci wmemset(c,-1,x)invece di n=m=0;for(i=0;i<x;++i)c[i]=-1, n=m=i=s=0invece di i=s=0, for(j=x;j--;)invece di for(j=0;j<x;++j)e s||(c[n++]=_[i],m++,n%=x);invece diif(!s){c[n++]=_[i];m++;n%=x;}
ceilingcat il



0

Ruggine , 129 byte

|l:&[_],s|if s>0{let(mut c,mut m)=(vec![-1;s],0);for n in l.iter(){if!c.contains(n){c.remove(0);c.push(*n);m+=1;}}m}else{l.len()}

Provalo online!

Ungolfed

|l: &[isize], s: usize| {
    if s > 0 {
        let mut c = vec![-1; s];
        let mut m = 0;
        for n in l.iter() {
            if !c.contains(n) {
                c.remove(0);
                c.push(*n);
                m += 1;
            }
        }
        m
    } else {
        l.len()
    }
}

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.