[Question]
  [
This challenge is really simple (and a precursor to a more difficult one!).
Given an array of resource accesses (simply denoted by nonnegative integers) and a parameter `n`, return the number of cache misses it would have assuming our cache has capacity `n` and uses a first-in-first-out (FIFO) ejection scheme when it is full.
Example:
```
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]
```
So in this example there were 9 misses. Maybe a code example helps explain it better. 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
```
Some further testcases (which contains a hint towards the next challenge - notice anything curious?):
```
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
```
Shortest code in bytes wins.
  
[Answer]
# JavaScript (ES6), 55 bytes
### Method #1: the cache overwrites the input
Takes input in currying syntax `(cache_size)(list)`.
```
n=>a=>a.map(x=>a[a.indexOf(x,k>n&&k-n)<k||k++]=x,k=0)|k
```
[Try it online!](https://tio.run/##lc5LCsIwEAbgvafIqiQ0bZO2CwXTK3iA0kXoQ2pqUqxIFr17HFpEiQo6zOJnYL6Zk7zJqb704zXSpmldJ5wWhYSOz3LEFkIp4143rT102FJV6CBQkSZ7Nc8qDCsBM8HIrFxt9GSGNh7MEXeYEVxWhKBfK0kQ27wTnKKUooyinKJn/gwDsfWIFAhGkd9fHwOCe0QGRLZc5svymvNHWIcvHwGx84j8f4Izdwc "JavaScript (Node.js) – Try It Online")
### How?
We overwrite the input array **a[ ]** with the cache, using a separate pointer **k** initialized to **0**.
We use `a.indexOf(x, k > n && k - n) < k` to test whether **x** is in the cache.
The cache can't grow faster than the original array is walked through, so each value is guaranteed to be found, either within or beyond the cache window (i.e. `indexOf()` will never return **-1**).
A value is in the cache if it is found at an index between **max(0, k - n)** and **k - 1** (both bounds included), in which case we do **a[true] = x**. This only affects a property of the underlying object behind **a[ ]** but does not alter the *array* **a[ ]**. Otherwise, we do **a[k++] = x**.
### Example
Below are the different steps for the input `[1, 1, 2, 3, 3, 2, 1, 4]` with a cache size of **2**:
* bold borders: **map()** pointer
* brackets: cache pointer **k**
* orange: current cache window
* yellow: expired cache values
[![method #1](https://i.stack.imgur.com/ZbCTW.png)](https://i.stack.imgur.com/ZbCTW.png)
---
# JavaScript (ES6), 57 bytes
### Method #2: the cache is appended at the end of the input
Takes input in currying syntax `(cache_size)(list)`.
```
n=>a=>a.map(x=>n*~a.indexOf(~x,-n)||a.push(~x)&k++,k=0)|k
```
[Try it online!](https://tio.run/##lc5LDoIwEAbgvaeYlWmllBZY6KJcwQMYFw0P5WFLRA0LwtVrAzGaqolOZvG3yXwzlbzJLj2X7cVXOstNIYwSibRNT7JFvUjUapS0VFnebws09sRXeBgkba/d0T7xsvY8UguGh9qkWnW6yWmjD6hADKPdHmP4tYIA2OKd4ARCAhGBmMAzf4YtsXaI0BKMgNtfD7MEd4jIEtG0mU/Dc44fYf58ucgSG4eI/yc4M3c "JavaScript (Node.js) – Try It Online")
### How?
Because the input array **a[ ]** is guaranteed to contain non-negative integers, we can safely append the cache at the end of **a[ ]** by using the one-complement **~x** of each value **x**.
We use `n * ~a.indexOf(~x, -n)` to test whether **~x** is found among the last **n** values. Whenever this test fails, we append **~x** to **a[ ]** and increment the number of misses **k**.
### Example
Below are the different steps for the same example as above, using this method. Because cache values are simply appended at the end of the array, there is no explicit cache pointer.
[![method #2](https://i.stack.imgur.com/lfMR0.png)](https://i.stack.imgur.com/lfMR0.png)
[Answer]
# [Haskell](https://www.haskell.org/), 50 bytes
```
f n=length.foldl(\r x->[x|all(/=x)$take n r]++r)[]
```
[Try it online!](https://tio.run/##jYxBDoIwEEX3nOIvWLShqAjbwgk8QWlME0EIQyGVBQvvXhFiMK5MZvH@nzfTmEdXEXlfw0qq7H1qDvVAN2Klwxznan4aInaUMw8n01WwcDqKHFfas4LLOuhNayHRm/FyBSuZFcTjHKNr7YQQtiAeAFBgJwGluXgnbCkROAukApnAzruzFGrxfmcXFl2l62GyrjbOPrCVXw@zP31A@xc "Haskell – Try It Online")
Based on [Lynn's method](https://codegolf.stackexchange.com/a/166677/20260) of storing the whole cache history and taking its length. [Unary output](https://codegolf.meta.stackexchange.com/q/5343/20260) would be a bit shorter:
**[Haskell](https://www.haskell.org/), 47 bytes**
```
n?l=1<$foldl(\r x->[x|all(/=x)$take n r]++r)[]l
```
[Try it online!](https://tio.run/##jYxNDoIwEIX3nuItWLRhiCIsLZ7AE5TGNBEjYaiksmDh3WuFGIwrk1m8n2/ezT66hjkEd2SVH5LrnS8sao8pq/T0tMxiqyaZjLZr4OBNmnqpDYfetg4KvR1OZ4haOGKZVRh860YkiHNyA0BD7AjaSHo7LC4n7AkFoSSsemVioCP3eysQcV3Mj/lcLbr8iCX8Giz/5AETXg "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 58 bytes
```
lambda n,a:len(reduce(lambda c,i:[i][i in c[:n]:]+c,a,[]))
```
[Try it online!](https://tio.run/##TchBDoIwEEbhq8yywL9QZNXEk4yzqKXESWBsSFl4@moMCeze@/KnvN7W1@n@qHNYnmMgQ/BzMremcYvJ7RqhnlVYSY0iexMvXUQAS9PUvKoVmlyrlrfifjKA@AK6gnrQDXTu4b@HyBc "Python 2 – Try It Online")
Thanks to ovs for 3 bytes, and xnor for 3 more.
[Answer]
# [R](https://www.r-project.org/), ~~69~~ ~~64~~ 62 bytes
```
function(n,A,K={}){for(i in A)K=c(i[!i%in%K[0:n]],K);sum(K|1)}
```
[Try it online!](https://tio.run/##lc3NCsIwDAfwe58iIoMGMmjXHvyasHMfYexUKPRgB9Od5p691k4R5kEMOfwJ@SVDdHAqoxuDvfk@8EANmXqacXL9wD34AA2a2nLfbnzhQ2FacQhdRwaP1/HCzV3iHJnjgixHhN@1hfIM4iUkQUWgCDTBJ6/uZLFLokpCEKz7@20WMgmVhMp3Zd5dsn6HZfj8l8U@Cf2XkIIxFh8 "R – Try It Online")
Thanks to JayCe for suggesting some improvements, and DigEmAll for another couple!
[Answer]
## Haskell, ~~61~~ 58 bytes
```
n!a|let(a:b)#c|elem a c=b#c|1<2=1+b#take n(a:c);_#_=0=a#[]
```
[Try it online!](https://tio.run/##jYxNCsIwEIX3nuJJXCQYoWm7UuMNPEEsZVoCliahaJe9e4wtUnElzOL9fPPu9OytczGGLU3OjpyOjWDtZJ31ILS6SUadc632DRuptwgJacWpZrXONDFTRU9dgIan4VqD33iQJA4XDI8ujNghLYsNAAOeSZhKyLfD4pRELlFIlBKrXpkUmMT93gok3BTzo5qrRZcfsYRfg@WfPFDFFw "Haskell – Try It 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
```
Edit: -3 bytes thanks to @Lynn.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ 16 bytes
```
)svDyå_i¼y¸ìI£]¾
```
[Try it online!](https://tio.run/##MzBNTDJM/f9fs7jMpfLw0vjMQ3sqD@04vMbz0OLYQ/v@/4821lEw0lEw1FEw0FGAsE1gDIigSSyXMQA "05AB1E – Try It Online")
**Explanation**
```
)                   # 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
```
[Answer]
# [Kotlin](https://kotlinlang.org), ~~82~~ 69 bytes
```
{a,n->a.fold(List(0){0}){c,v->if(v!in c.takeLast(n))c+v else c}.size}
```
Takes input as an `IntArray`, **not** the typical `List<Int>` (which shouldn't be a problem.) This uses the approach of "build a cache history and count its length".
[Try it online!](https://tio.run/##TY7NCsIwEITvfYr1totpqT8nwYJHoeAzhJrA0riVJga09NljVET3st/swMz2Q3AsKWoHF/be@B3gUcJhHPVdQSaCsnlt2KdJKykbXdnBnbFlH7CmqZ5p6lQsG7YYFyzQVUH3ptXZFqJuGcE4b6CbK88PMyd7E7hoFiSYCshzHVmCE/z0o8vBJ4u1gpWCtYKNgn/evuXvQlUYvg8jZZ@omNMT "Kotlin – Try It Online")
## Explanation
```
{ 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
}
```
### Creating an empty list
Kotlin does not have collection literals, but it does have some functions to create new collections.
The proper way to create an empty `List<Int>` is simply:
```
List<Int>()
```
but it is shorter if we abuse the size and initializer args to do this:
```
List(0){0}
List(0)       // List of size 0
       { 0 }  // with generator returning 0
```
Because the generator lambda returns 0, Kotlin infers the type of this list as `List<Int>`, and the size of 0 means this list is empty.
[Answer]
# [Perl 6](https://perl6.org), 48 bytes
```
{my@c;$_∈@c.tail($^n)||push @c,$_ for @^o;+@c}
```
[Test it](https://tio.run/##jZBNTsMwEIX3PsVbBJwQ9yc0qkTdVj4Eu5BWkWMgUpJGcYqo2rLuXbgFR@EiwXH/kNiwsZ6fv5nxm0rV@bhda4W3cV9yQooNbuUqVZi122IjJHeW34eDkP0myXLXWZTeblet9SuEZM4Sz6saYrHivpD71tSKRukGM@RZqXS/SKoJtgQoJjp70VUi1cDcAGdazg3l4in14VFGrRuBRhQfoDFFJKZJXScbixnKi@9wA0MitiztzemplXqvlGxUekGNP@DmcOF3gxj8r89zO9Z5lwoGk8Eje0K6FTyav3NS5UkJ3wbhxOazmXpzuE7JIGwfU3huYmSqtPRs0Eyj215HHkHvL8nJvg0ZoiFDwHDPMGL4rUN7vTpxN/uBGCOyckgMFI3sY2DBow7P4miGp7rw/3Aw/AE "Perl 6 – Try It Online")
```
{  # 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)
}
```
[Answer]
# Java 8, 96 bytes
A curried lambda taking a cache size (`int`) and access list (mutable `java.util.List<Integer>`) and returning an `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;}
```
[Try It Online](https://tio.run/##lVE9T8MwEJ2TX3ELyCGulQBT84FYkJBADIxVB5M6xSVxIp9DKVV@e7HdliIGJKJEd3537@XeecXf@aTrhVot3nb98NLICqqGI8Ijlwq2YXAA0XBjQy0Vb2BlWWwwsmH1oCojO8XuDkl@r4xYCk3/bDrVHiSaI6ekcMxKqKEIdzgp@aTcSmVgXSS0tZ/M6k4Th@gpj9q4ILLgTKqF@HiqiY6ifH0uc7xJppinN@k0jZMLzlAYso7jM6Q6yrQwg1bQZuMuDLLwt8f3Ti6gtfbJs9FSLWdz4HqJkdtGYH9szyg/BUIBSqxhj2wTClcUrikkY2b7DkZmc8euKoH4TfhZcpLBdqQ@WP4lhdRKeK1LL/cTvP5vY@qx/Vyn3Bf9lHaV4Hcp7WxJZkO@98YaoZbm1SFxAenee/C8QSNa1g2G9XYzplGkZrzvmw3xrJmcR4ezM3q65Vut@cZfdUl@ocg4ugo5bsmJ2MeNN4b2HcPdFw)
## Ungolfed
This uses the first (up to) `s` slots in the input list for the 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;
    }
```
## Acknowledgments
* bugfix thanks to *nimi*
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~16 15 18 14~~ 13 bytes
Saved 1 byte thanks to [isaacg](https://codegolf.stackexchange.com/users/20080/isaacg).
```
luaW-H>QGGHEY
```
[Test suite!](https://pyth.herokuapp.com/?code=luaW-H%3EQGGHEY&input=4%0A%5B0%2C+1%2C+2%2C+3%2C+0%2C+1%2C+2%2C+3%2C+4%2C+0%2C+0%2C+1%2C+2%2C+3%5D&test_suite=1&test_suite_input=4%0A%5B0%2C+1%2C+2%2C+3%2C+0%2C+1%2C+2%2C+3%2C+4%2C+0%2C+0%2C+1%2C+2%2C+3%5D%0A%0A0%0A%5B%5D%0A%0A0%0A%5B1%2C+2%2C+3%2C+4%2C+1%2C+2%2C+3%2C+4%5D%0A%0A2%0A%5B0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%5D%0A%0A3%0A%5B3%2C+2%2C+1%2C+0%2C+3%2C+2%2C+4%2C+3%2C+2%2C+1%2C+0%2C+4%5D%0A%0A4%0A%5B3%2C+2%2C+1%2C+0%2C+3%2C+2%2C+4%2C+3%2C+2%2C+1%2C+0%2C+4%5D%0A&debug=0&input_size=3)
This challenge is very well suited to Pyth's `u` structure.
### How it works
```
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.
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~60~~ 59 bytes
```
Tr[k={};n=#;k~Take~UpTo@n~FreeQ~#&&k~PrependTo~#&/@#2;1^k]&
```
[Try it online!](https://tio.run/##jYu9CsMgAIR3n0IQQguWJtZNUpw6p2CnkIK0hgaJCeIm@urWuDRjh4P7@W6W7qNm6aaXTGN7SML2uvWBmRYxHYXUKj5WsXATb1ape0RVpWNn1arMWyw5njkirHnqoUpHBjo7Gdej03XkHA159AB4iqGvMWwwJBheMNx7WuKvCQGDDfbFZGATKXNdDqR89iUtKP0TBSCkLw "Wolfram Language (Mathematica) – Try It Online")
### Using pattern-matching, 60 bytes
```
Length[#2//.{p___,a_,q___,a_,r___}/;Tr[1^{q}]<#:>{p,a,q,r}]&
```
I really like this one better, but it's 1 byte longer...
[Try it online!](https://tio.run/##jYu9CsIwFIX3PEUgUBSupo2ZrJY@gIODW4ghSGs7tLQh2yXPHtsg2NHhcn7udwbru2awvn/Z2F538daMb98pJjg/4mSMAWtg/qpbNPDy4VTxxDnoCztXOIGFGVzQWdyX5O760St2qNq6ZjrjNRKCEijmQAugAugJ6NbLFH9NCEBWGJNZgPVEeudpINJmW8qEyj9RQkL8AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Japt, 16 bytes
```
;£A¯V øX ªAiXÃAl
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=O6NBr1Yg+FggqkFpWMNBbA==&input=WzAsMSwyLDMsMCwxLDIsMyw0LDAsMCwxLDIsM10KNA==)
---
## Explanation
```
                     :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
```
[Answer]
# [K4](https://kx.com/download/), ~~42~~ 40 bytes
**Solution:**
```
{*1+/1_{r,,(y;x#z,y)r:~z in y:*|y}[x]\y}
```
**Examples:**
```
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
```
**Explanation:**
For the inner function, y is the cache, z is the request and x is the cache size.
```
{*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
```
**Notes:**
There is probably a nicer way to do all of this, but this is the first way that came to mind.
The function can be ran like this for **36 bytes**:
```
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
```
Alternative - using a global variable to store state (not very K-like), **42 bytes**:
```
{m::0;(){$[z in y;y;[m+:1;x#z,y]]}[x]\y;m}
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 172 bytes
```
(([{}]<>)<{({}(()))}{}>)<>([]){{}<>((({})<{({}()<<>(({})<({}<>({}<>))>)<>>)}{}>)<<>(({})([{}]<>{<>(){[()](<{}>)}{}<><({}()<<>({}<>)>)>}{})){(<{}{}>)}{}>)<>([])}{}<>({}[]<>)
```
[Try it online!](https://tio.run/##PY6xCsMwDET3foXGu6HQNh6Nf8R4SIZCaejQVejbXSkoxSD76e5kbd/19bk@9/U9J9DVRm2sCjWApKk5NvRBVfMHXEmdNTgQhxSFDHvLXOo5Vh2pHRyoIVsE6n/SEffjbVLDkqZzActfeqw4Z7ks8pC73CTuIieVHw "Brain-Flak – Try It 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)
<>({}[]<>)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
Ṗɼṛ;ɼe®Uḣ⁴¤C$¡€ṛLɼ
```
[Try it online!](https://tio.run/##y0rNyan8///hzmkn9zzcOdv65J7UQ@tCH@5Y/Khxy6ElziqHFj5qWgOU8Dm55////9HGOgpGOgqGOgoGOgoQtgmMARE0if1vAgA "Jelly – Try It Online")
Takes the list as the first argument and cache capacity as second argument.
```
Ṗɼṛ;ɼ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
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~43~~ 40 bytes
```
->s,a,*r{a.count{|*x|r!=r=(r|x).pop(s)}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf165YJ1FHq6g6US85vzSvpLpGq6KmSNG2yFajqKZCU68gv0CjWLO29n9BaUmxQlq0iY5CtIGOgqGOgpGOgrGOAjLbBMxFiMTGckF1ASVB2AgsZQBWbARWjyxoglBvQqT6/wA "Ruby – Try It Online")
Thanks histocrat for shaving 3 bytes.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~112 110~~ 108 bytes
```
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;}
```
[Try it online!](https://tio.run/##xZNNboMwEIX3OYUbCcnGg8SPo1ZxrRyEskggtF5AKkJVTMTZqcFEeJGqLBJVLMZjz7x5n2xS7z1N@z7HDShoiSxrV/HLEKRQtIVD3CRQCJ/npwp/F8fifKzxAVrhBdAQLj3FFaVkOEk/Kn3iKr2/21JauM3uELeC0tZpEuGqrc8bUfCu1@qo2MsSE3RZITSkkk@Ls2yPetqUpaevsp7TbF/v/ThBAl06vtKbn5XezvE6x04GKF7D2E@Geu0XYalLfY4kejVSHFEqzdS5GZxMNxptmYzNnaWdEOFkb6UuyfGgPpWCUSRkNDLbNpZfbMuBsRxACBEwmOKdCeiThGnaYojgBkQ4QzzbEKGB8MH6HoUQLkcIbyBEM0IQ2gyRYYj0BQTa/xAZXLOHXUi0nCa6QcN@o2H/QsOW07A/aJhNs7m@L/N7XCMbX9q4fhTRZjnRxiLq@h8 "C (gcc) – Try It Online")
Slightly less golfed
```
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;
}
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 156 bytes
```
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;}
```
[Try it online!](https://tio.run/##VVFhb4IwEP3Or7i5kLS2LuL8VusfYY0hRfTIKAvgQsb47exaUWdJuOt7vfce1K5O1k5TK52sJMpSFayXB46uWx7UQAVs2hvldKXXqqgbhlRx1yshkNsUjV4lM94ScyBkT5VYSXs@eKokoAwjJW9/NbNpabT2R7nCgr20fLCpE8IETFVCKBfrXo1jrys1Tq/o7OclP8Ku7XKs3877yAerMnTMN1lzshLsOWtgSf13ajgMEdDybIs/R9CQdTWywCZke2dtfaG3Dhqwgs2DwUebZ12WhpMiMSoK@FdDTMEWBYtzCelCBiM@s/TZwJB01woQdlcbBf6nzdH8CrpontIhCNjcEv43knFOJvPIzI/RXSY4eCm6j@eEhus4/3A0XDCf8SrCb1GbY3dpHAWNxml6p2czJdM61O19t/0D "C (gcc) – Try It Online")
Description:
```
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
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 44 bytes
```
n=>a=>a.map(y=t=>y[t]+n>p||(y[t]=++p),p=0)|p
```
[Try it online!](https://tio.run/##ldBRC8IgEAfw9z7FPSrappuDenBfZOxB1hbFUmkSDPbdzTaisIIm9/Dn4H53eFY3NTTXk3VbbQ6t76TXslShkouyaJROlmPlaqJLO03oESUhFlMrGZ6sb4weTN8mvTmiDjGMqhpj@PelKbDNJ8EpZBRyCoLCK3@HA7GLiCwQjEJcPw8LBI@IPBD5vJnPw0sWz7A03y4KxD4ixHqCx59RrDcKfwc "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
Ṗœ|Ṛḣ⁴$Ṛʋ\-;⁸e"ċ0
```
[Try it online!](https://tio.run/##y0rNyan8///hzmlHJ9c83Dnr4Y7Fjxq3qABZp7pjdK0fNe5IVTrSbfD///9oYx0FIx0FQx0FAx0FCNsExoAImsT@NwEA "Jelly – Try It Online")
Full program.
Argument 1: stack (Python 3 `list` of `int`egers)  
Argument 2: `n` (Python 3 `int`eger)
[Answer]
# [Rust](https://www.rust-lang.org/), 129 bytes
```
|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()}
```
[Try it online!](https://tio.run/##RY5BCsIwFETX9hS/XciPfkOrrgz1IqWIhAQDSSpJ6ibN2WtduRkG3vCYMMe0ag/uaTwyyNXOqgQa@nWxt/3wGCkuRkO8t3kD6OYEkn7pWI8fJevh1Ik4UsuEngJ4MB4sN0kFZNnoWnI5@bTJI3qWJQ/KTR@F21zy9xxfePBMuGPfiVJcUTaqbLlV25eyimr3DsanGptcGtK4HzqCM8GF4Erw7yNBy5ioyvoF "Rust – Try It 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()
    }
}
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ç═╛¢s▲▬╓í±°☻÷hi
```
[Run and debug it](https://staxlang.xyz/#p=80cdbe9b731e16d6a1f1f802f66869&i=0,+[]%0A0,+[1,+2,+3,+4,+1,+2,+3,+4]%0A2,+[0,+0,+0,+0,+0,+0,+0]%0A3,+[3,+2,+1,+0,+3,+2,+4,+3,+2,+1,+0,+4]%0A4,+[3,+2,+1,+0,+3,+2,+4,+3,+2,+1,+0,+4]&a=1&m=2)
]