[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)
]


[Question]
      [
Here's an array representing a standard deck of cards, including two Jokers.
```
[
  "AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "JS", "QS", "KS",
  "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "JD", "QD", "KD",
  "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "10H", "JH", "QH", "KH",
  "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "10C", "JC", "QC", "KC",
  "J", "J"
]
```
It's composed in this manner:
* There are four suits; hearts, spades, diamonds, and clubs (H, S, D, C).
* Each suit has one card for the numbers 2 to 10, plus 4 'picture' cards, Ace, Jack, Queen, and King (A, J, Q, K).
* For each combination of suit and value, there should be one item in the array, which is a string, and is made up of the value followed by the suit (Whitespace between these is permitted).
* On top of that, there are two Joker cards ('J').
* Write in any language you please.
* Golf it up! Try to produce this output in the smallest number of bytes.
* It does not matter what order the output is in.

[Answer]
# JavaScript (ES6), ~~62~~ 60 bytes
```
f=n=>n>51?'JJ':[('JQKA'[k=n>>2]||k-2)+'CDHS'[n&3],...f(-~n)]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i7PztTQXt3LS90qWkPdK9DbUT062zbPzs4otqYmW9dIU1vd2cUjWD06T804VkdPTy9NQ7cuTzP2f3J@XnF@TqpeTn66RpqGpuZ/AA "JavaScript (Node.js) ‚Äì Try It Online")
[Answer]
## [Bash](https://www.gnu.org/software/bash/) ~~43~~ 34 bytes
```
d=({A,J,Q,K,{2..10}}{H,S,D,C} J J)
```
[Try it online!](https://tio.run/##S0oszvj/P8VWo9pRx0snUMdbp9pIT8/QoLa22kMnWMdFx7lWwUvBS/N/anJGvoJKdUq0Q2ztfwA "Bash ‚Äì Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~200~~ 197 bytes
```
+[[<+>->++<]>]+<++++<<+++[->+++>+++++>+>+<<<<]>+.<<.>>.--<<<[->>+++<<]>>+>[<<.>.-.+>.<<.<<[>>>+.>.<<.<+<-]>[-<+>>>+<<]>>.>.<<.>+++++++++.>.<<.>+.>.<<.>++++++.>.,++++[-<-------->]>[[-<+>]>]<<[<]>>>]
```
[Try it online!](https://tio.run/##VU5bCsMwDDuQZp/A6CLGH2thUAr9GOz8mZxsHxXEQQ9kb@/ncb0@@zkGMgM0AlEsBIToma2hX09KDCXgEU66maginPHSz2zHzcHOyKVUXwRhxTRtIld@Gau@8ec3XeSBeUvYD1TPLNK12tFVrDG@ "brainfuck ‚Äì Try It Online")
Uses one negative cell (+1 bytes to fix), wrapping cells (lots o' bytes to fix) and 0 on EOF (+2 bytes to remove dependancy).
Outputs
```
J J 10H 2H 3H 4H 5H 6H 7H 8H 9H AH JH KH QH 10S 2S 3S 4S 5S 6S 7S 8S 9S AS JS KS QS 10D 2D 3D 4D 5D 6D 7D 8D 9D AD JD KD QD 10C 2C 3C 4C 5C 6C 7C 8C 9C AC JC KC QC
```
### Explanation:
```
+[[<+>->++<]>]  Sets the tape to powers of 2
          TAPE: 1 2 4 8 16 32 64 128 0 0'
+<++++<<+++[->+++>+++++>+>+<<<<]   Uses the 64 and the 128 to generate the suit letters
          TAPE: 1 2 4 8 16 32 0' 73 83 68 67
                                 I  S  D  C
>+.<<.>>.--<<     Prints the Jokers
<[->>+++<<]>>+>   Uses the 16 to create 49
          TAPE: 1 2 4 8 0 32 49 72' 83 68 67
                                 H   S  D  C
[  Loop over the suits
   <<.>.-.+>.<<.<<      Print the 10 card with a leading space
          TAPE: 1 2 4 8' 0 32 49 Suit
   [>>>+.>.<<.<+<-]  Use the 8 to print the other 8 number cards
          TAPE: 1 2 4 0' 8 32 57 Suit
   >[-<+>>>+<<]      Move the 8 back into place while also adding it to the 57
          TAPE: 1 2 4 8 0' 32 65 Suit
   >>.>.<<.         Print the Ace
   >+++++++++.>.<<. Print the Jack
   >+.>.<<.         Print the King
   >++++++.>.<<.    Print the Queen
          TAPE: 1 2 4 8 0 32 81' Suit
   >>,    Clear the current suit
   ++++[-<-------->]    Subtract 32 to get back to 49 (reusing the space is longer than just subtracting 32)
          TAPE: 1 2 4 8 0 32 49 0' MoreSuits?
   >[[-<+>]>]<<[<]>>>   Shift all the remaining suits over one
          TAPE: 1 2 4 8 0 32 49 Suit?'
] End on the character of the next suit and repeat
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~28~~ ~~27~~ ~~25~~ ~~24~~ 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2T≈∏.‚Ä¢-≈∏‚Ä¢S¬´.‚Ä¢√¥√¨‚Ä¢√¢J‚ÄûjjS¬´u
```
[Try it online.](https://tio.run/##yy9OTMpM/f/fKOToDr1HDYt0j@4AksGHVoM4h7ccXgOiFnk9apiXlQUULf3/HwA)
-1 byte thanks to *@Emigna* removing the `S` after `"HSDC"`, because `√¢` does this implicitly.
**Explanation:**
```
2T≈∏           # Push list in the range [2,10]: [2,3,4,5,6,7,8,9,10]
   .‚Ä¢-≈∏‚Ä¢      # Push compressed string "ajqk"
        S     # Convert it to a list of characters: ["a","j","q","k"]
         ¬´    # Merge the two lists together: [2,3,4,5,6,7,8,9,10,"a","j","q","k"]
.‚Ä¢√¥√¨‚Ä¢         # Push compressed string "cdhs"
√¢             # Cartesian product of each (pair each character of both lists):
              #  [[2,"a"],[2,"d"],[2,"h"],...,["k","d"],["k","h"],["k","s"]]
J             # Join each pair together to a single string:
              #  ["2a","2d","2h",...,"kd","kh","ks"]
‚ÄûjjS          # Push string "jj", and convert it to a list of characters: ["j","j"]
    ¬´         # Merge both lists together:
              #  ["2a","2d","2h",...,"kd","kh","ks","j","j"]
     u        # Convert everything to uppercase:
              #  ["2A","2D","2H",...,"KD","KH","KS","J","J"]
              # (and output the result implicitly)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.‚Ä¢-≈∏‚Ä¢` is `"ajqk"` and `.‚Ä¢√¥√¨‚Ä¢` is `"cdhs"`.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~550~~ 504 bytes
```
++++++++++[>+++>+++++>+++++++<<<-]>++>->[>+>+>+>+<<<<-]>----->++++.<<<<.>>>>.<<<<.>>>>>--->+++++++++++++<<<<<.-.+>>>>.<<<<<.>.-.+>>>>+.<<<<<.>.-.+>>>>++++.-----<<<<<.>.-.+>>>>>.<<<<<<.>>++++++++[-<+.>>>>.<<<<<.>.>>>>+.<<<<<.>.>>>>++++.-----<<<<<.>.>>>>>.<<<<<<.>>]>.>>.<<<<<.>>>>.>.<<<<<.>>>>+.>.<<<<<.>>>>++++++.>.<<<<<.>>>.>>+.<<<<<.>>>>.>.<<<<<.>>>>------.>.<<<<<.>>>>-.>.<<<<<.>>>.>>++++.<<<<<.>>>>.>.<<<<<.>>>>+.>.<<<<<.>>>>++++++.>.<<<<<.>>>.>>>.<<<<<<.>>>>.>>.<<<<<<.>>>>------.>>.<<<<<<.>>>>-.>>.
```
[Try it online!](https://tio.run/##nVBBCoAwDHtQaV9Q@hHxoIIgggfB98@2urlOT0aQJWkT57gPyzYf05oSFHSiL/Gj3BIzY69EUNS9Hr5ENPgcmUKieE6SzQJ2DwnKoE5mDi/Bcr2iMe5VaynfjQwUUmPkd14T1puSV8ypCUTmqCWq6tpdL8Uotbv5J/6rrm4hzy1iexSNp3QC "brainfuck ‚Äì Try It Online")
[Old answer, also online!](https://tio.run/##vVBbCsMwDDuQsU9gdJHSj7VQKIV9DHr@zHGehrGfwRQIlmSsONvrcT6Pe79Soo4FdsFLVElVeTUChrnlaBE5w/skKwLDqNDMDnWPhXpj7uzZrCTBWSETs3ImFJljSFzR0ujXuDouSF/i2p/8bcFqfMybPE@cOMYL4p5RzDylNw "brainfuck ‚Äì Try It Online")
[Answer]
# Java 10, ~~153~~ ~~151~~ ~~125~~ ~~77~~ 75 bytes
```
v->("AJQK2345678910".replaceAll("1?.","$0H,$0S,$0D,$0C,")+"J,J").split(",")
```
-28 bytes thanks to *@OlivierGr√©goire*.
-50 bytes thanks to *@mazzy*.
[Try it online.](https://tio.run/##PY9PS8NAEMXv/RTD0sOupkvqfwkqQQ8SaUEKXsTDuo2ycbJZdieBIv3scUqDMO8wM495v2nMYBbN9md0begiQcO97smhPilmFk1KsDLO/84AnKc6fhlbw/rQAmwoOv/9/gFWvnVuC4MqeL5ncSUy5CyswcMdjMPiXoqyen05O7@4vLq@uV3mQsc6IJ8rEaVYPmiRiXn@nM3zDeuJ9ZgJdSqqrBJKp4COJFvUWBwDQv@JHDDlDAeAlknlP5VRE@YuUd3qricdeEXoZRmj2SVN3dEsvbbS94hKTS/sxz8)
**Explanation:**
```
v->                      // Method with empty unused parameter and String-array return-type
  "AJQK2345678910"
   .replaceAll("1?.",    //  Replace every loose character (or "10" as single char)
     "$0H,$0S,$0D,$0C,") //  with "cH,cS,cD,cC,", where c is the character
   +"J,J")               //  Append "J,J"
  .split(",")            //  And split everything by commas
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 29 bytes
*1 byte saved thanks to Probie by using `1+‚ç≥9` instead of `1‚Üì‚ç≥10`*
```
'JJ',,'HCDS'‚àò.,‚ç®'AKJQ',‚çï¬®1+‚ç≥9
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/@v8ahvql/wo941mo96@9SBHOdIdfXixJwSdfVH3S1AfrCrXqizr4u6elJ@hUJ@noJumm1@HlCya3FqXmJSTmqwo0@IOtejjva0/@peXuo6Ouoezi7B6o86ZujpPOpdoe7o7RWoDmRNPbTCUPtR72bL/0C1/9MA "APL (Dyalog Unicode) ‚Äì Try It Online")
This is a full program. In the TIO link, I have enabled boxing so that the individual elements of the array can be distinguished.
Here is the boxed output.
```
‚îå‚îÄ‚î¨‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚îÄ‚î¨‚îÄ‚îÄ‚îÄ‚îê
‚îÇJ‚îÇJ‚îÇAH‚îÇAC‚îÇAD‚îÇAS‚îÇKH‚îÇKC‚îÇKD‚îÇKS‚îÇJH‚îÇJC‚îÇJD‚îÇJS‚îÇQH‚îÇQC‚îÇQD‚îÇQS‚îÇ2H‚îÇ2C‚îÇ2D‚îÇ2S‚îÇ3H‚îÇ3C‚îÇ3D‚îÇ3S‚îÇ4H‚îÇ4C‚îÇ4D‚îÇ4S‚îÇ5H‚îÇ5C‚îÇ5D‚îÇ5S‚îÇ6H‚îÇ6C‚îÇ6D‚îÇ6S‚îÇ7H‚îÇ7C‚îÇ7D‚îÇ7S‚îÇ8H‚îÇ8C‚îÇ8D‚îÇ8S‚îÇ9H‚îÇ9C‚îÇ9D‚îÇ9S‚îÇ10H‚îÇ10C‚îÇ10D‚îÇ10S‚îÇ
‚îî‚îÄ‚î¥‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚îÄ‚î¥‚îÄ‚îÄ‚îÄ‚îò
```
`'JJ',` 2 jokers concatenated to
`,` the raveled form of
`‚àò.,‚ç®` the matrix created by concatenating every combination of
* `'HCDS'` this string against
* `'AKJQ',` this string with
	+ `‚çï¬®` the stringified forms of each of

		- `1+‚ç≥9` the numbers 2..10 (1 plus the range 1..9)
[Answer]
# [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 75 bytes
```
j4d*1-2k:d%4+1g:'0-!#v_>,d/1g,' ,!#v_3
CHSDA234567890JQK@;1'< ^,;,k2"J J" <
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/P8skRctQ1yjbKkXVRNsw3UrdQFdRuSzeTidF3zBdR11BB8Qz5nL2CHZxNDI2MTUzt7A08Ar0drA2VLdRiNOx1sk2UvJS8FJSsPn/HwA "Befunge-98 (FBBI) ‚Äì Try It Online")
## Program structure
[![enter image description here](https://i.stack.imgur.com/y4N8r.png)](https://i.stack.imgur.com/y4N8r.png)
At first, the stack is filled with `0`'s, and `j` does not jump over the initialisation. The initialisation pushes `4 * 13 = 52`, which is the program counter. In the following iterations the trailing `3` causes the pointer to jump over this part.
```
1-2k:d%4+1g,d/1g,' ,!#v_  Main loop
1-                        decrement counter
  2k:                     duplicate counter three times
     d%                   counter mod 13 ...
       4+                 ... + 4 is the position of the card in the Data section
         1g,              get the card from row 1 and print it
            d/            counter / 13 is the position of the suit in the Data section
              1g,         get the suit from row 1 and print it
                 ' ,      print a space as seperator
                    !     negate the counter (0 for non-zero, 1 for 0)
                       _  If the counter is 0, move West ...
                     #v   ... and move to the termination
                          otherwise, continue with the next iteration
```
Code that prints 10:
```
'0-!#v_>    Checks if Card is '0'
'0-         subtract the '0' from the card
   !        negate (1 for '0', 0 for all other cards)
      _     If card was '0', move West
    #v        and go South to print '10'
            Else continue to go East
  ;1'< ^,;  Prints '10'
     <      Go West
   1'       Push '1'
  ;         Jump to ...
         ;  ... the next semicolon
        ,   Print '1'
       ^    Go back to the main loop
            The '0' will be printed by the main loop
```
Termination:
```
@; ... ;,k2"J J" <
                 <  Go West
           "J J"    Push "J J"
        ,k2         Print it
       ;            Jump to ...
 ;                  ... the next semicolon
@                   terminate the program
```
[Answer]
# [R](https://www.r-project.org/), 65 bytes
```
c(outer(c('A',2:10,J<-'J','Q','K'),c('S','D','H','C'),paste),J,J)
```
[Try it online!](https://tio.run/##K/r/P1kjv7QktUgjWUPdUV3HyMrQQMfLRlfdS11HPRCIvdU1dYBSwUCmCxB7ALEzUKggsbgkVVPHS8dL8/9/AA "R ‚Äì Try It Online")
-2 Bytes thanks to @Giuseppe and @JayCe suggestions
[Answer]
# Powershell, ~~63~~ ~~61~~ ~~59~~ 56 bytes
-3 bytes: thanks [ConnorLSW](https://codegolf.stackexchange.com/users/59735/connorlsw)
```
2..10+'AJQK'[0..3]|%{"$_`H";"$_`S";"$_`D";"$_`C"};,'J'*2
```
[Answer]
## [Perl 5](https://www.perl.org/), 41 bytes
```
sub{J,J,map<"$_"{S,D,H,C}>,A,2..10,J,Q,K}
```
[Try it online!](https://tio.run/##K0gtyjH9r5Jm@7@4NKnaS8dLJzexwEZJJV6pOljHRcdDx7nWTsdRx0hPz9AAKBmo413735qrtDhVwSWxJNHKyqU0tyC1yJqroCgzr0QBwlOIVknTtdPQjLX@DwA "Perl 5 ‚Äì Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~67~~ 64 bytes
```
print(*[a+b for a in['10',*'A23456789JQK']for b in'CHSD'],*'JJ')
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQys6UTtJIS2/SCFRITMvWt3QQF1HS93RyNjE1MzcwtIr0Fs9FiSbBJRVd/YIdlGPBcp7ealr/v8PAA "Python 3 ‚Äì Try It Online")
---
# [Python 2](https://docs.python.org/2/), ~~78~~ ~~76~~ ~~74~~ 68 bytes
```
print['1'*(a<'1')+a+b for a in'A234567890JQK'for b in'CHSD']+['J']*2
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM68kWt1QXUsj0QZIaWonaicppOUXKSQqZOapOxoZm5iamVtYGngFequDhJNAws4ewS7qsdrR6l7qsVpAUwA "Python 2 ‚Äì Try It Online")
Alt:
# [Python 2](https://docs.python.org/2/), 68 bytes
```
print[a+b for a in['10']+list('A23456789JQK')for b in'CHSD']+['J']*2
print['1'[a>'0':]+a+b for a in'A234567890JQK'for b in'CHSD']+['J']*2
```
---
saved
* -3 bytes, thanks to ovs
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 30 bytes
```
"JJ",/("AKQJ",$2+!9),'/:"SHDC"
```
[Try it online!](https://tio.run/##y9bNS8/7/1/Jy0tJR19DydE7EMhQMdJWtNTUUde3Ugr2cHFW@v8fAA "K (ngn/k) ‚Äì Try It Online")
`!9` is the list `0 1 ... 8`
`2+!9` is the list `2 3 ... 10`
`$` to string
`,` concatenate
`,'/:` concatenate each with each right, i.e. Cartesian product; normally it's `,/:\:` or `,\:/:` but on the right we have only scalars (`"SHDC"`), so we can use `'` instead of `\:`
`"JJ",/` join (concat reduce) the list on the right using `"JJ"` as initial value for the reduction
[Answer]
# MS-SQL, 137 bytes
```
SELECT v.value+s.value
FROM STRING_SPLIT('A-2-3-4-5-6-7-8-9-10-J-Q-K','-')v,STRING_SPLIT('H-S-D-C--','-')s
WHERE s.value>''OR v.value='J'
```
An array of values in SQL is returned as separate query rows. Uses the `STRING_SPLIT` function [introduced in SQL 2016](https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql).
It includes the jokers by adding two "blank string" suits to take advantage of the existing "J" for Jack, then filtering out rows we don't want. Shorter than using `UNION ALL` statements to add the jokers.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 61 bytes
```
->{[*0..52,52].map{|x|['JAKQ'[w=x%13]||w-2,'SDHC'[x/13]]*''}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1646WstAT8/USMfUKFYvN7GguqaiJlrdy9E7UD263LZC1dA4tqamXNdIRz3YxcNZPbpCHygSq6WuXlv7v0AhLTr2PwA "Ruby ‚Äì Try It Online")
[Answer]
# C# .NET, 114 bytes
```
o=>(new System.Text.RegularExpressions.Regex("1?.").Replace("AJQK2345678910","$0H,$0S,$0D,$0C,")+"J,J").Split(',')
```
Port of [my Java answer (credit to *@mazzy*)](https://codegolf.stackexchange.com/a/166628/52210).
[Try it online.](https://tio.run/##RY9PSwMxEMXv@ymGUGhCY9iq9Q@1FamKrPRQV/BQeohxWiIxWTZZXZF@9nWKLB7eYWbe4/3GxCMTauyM0zHC8icDiEkna6D8jgk/1H3jzVV4fUeTJJ1q63frzRy2sy7M5tzjV298xjapJ9w1Ttd3bVVjjDb4eFhhy9n4WjFBQ@W0Qc5uitXj8cnp5Oz84nKcM8kG@YMc5CXplrSQTIxYIQvKlJWziQ/lUHQA0@yf8DPYN1hq63nPBVocPoCeaUEAwaF6qW2i0jUb/TlVEShFrRK23DfOCWrbMDGl8D7bd78)
---
Interesting alternative of [**119 bytes** by *@Corak*](https://codegolf.stackexchange.com/questions/166623/generate-a-deck-of-cards?page=2&tab=votes#comment402916_166635).
```
using System.Linq;o=>new[]{"J","J"}.Concat(from s in"SDCH"from n in"A234567890JQK"select(n=='0'?"10":n+"")+s).ToArray()
```
[Try it online.](https://tio.run/##RY5LS8QwFIX3/RWXu5mE1lDfj9qRYUSkOgsZwUXpIsZUIp0bTFJlGPrba0YpLu7icM53@ZQ/UNbpsfeG3mG99UFvxKOhzyJRnfQeVrsEwAcZjJrqu57UtX390CpksXKRrJs5tFCOtpyT/q6bHVaYxRvE0pKSgbXObsCDIVzfLu/xN9I@Lo6OT07Pzi8u8@rpAb3u4ldGZTnLZzd4mOMVpYg89Vw824Vzcsv4CFAk/1Zf1rzBShpikwtIvreGSTg6eNtp8eJM0AxrTP@WorKRiqIZtIz6ruM8xQZ5EeEhGcYf)
If an `System.Collections.Generic.IEnumerable<string>` instead of `string[]` is an acceptable output, the trailing `.ToArray()` can be dropped so it becomes **109 bytes**.
**Explanation:**
```
using System.Linq;       // Required import for the `from .. in ..` and `select` parts
o=>                      // Method with empty unused parameter and string-array return-type
  new[]{"J","J"}         //  Return a string-array containing two times "J"
   .Concat(              //  And add:
     from s in"SDCH"     //   Loop over the suits
       from n in"A234567890JQK"
                         //    Inner loop over the cards
         select(n=='0'?  //     If the current card item is '0'
                 "10"    //      Use 10 instead
                :        //     Else:
                 n+"")   //      Simply use the card item as is
                      +s)//     And append the suit
   .ToArray()            //  Convert the IEnumerable to an array
```
[Answer]
## PHP, ~~108~~ ~~99~~ 97 Bytes
[Try it online!](https://tio.run/##Dcu7CgIxFEXRfr4ihBQJnML3gygiWkisxHIYhqDRCOpcrikU8dtjitXtTZFyXqwoklC8rB1cYy8dB3@Kul7D4YA9BhhihDEmmGKGOfq9xr9UMt@yeGb/aR@Br0ErRnjTvTsHLYWE3KkkjsW22KgkjbG/qqoy8e2ZWi69sfkP)
[Try it online! (Edit 1)](https://tio.run/##K8go@P/fxr4go0BBpcg22kvHK9Y6Lb8oNTE5QyPaUcdLJ1DHW8dIx1jHRMdUx0zHXMdCx1LH0CA2sVilRLMaqCWxqCixMj43tSg9VUOlSCfaQ0@lRCcYRLiACGcgEatpXfu/oCgzryS@CKhG0/o/AA)
**Code**
```
<?php $r=[J,J];foreach([A,J,Q,K,2,3,4,5,6,7,8,9,10]as$t)
$r=array_merge($r,[H.$t,S.$t,D.$t,C.$t]);
```
Tried to use purely php funcions, but bytecount was lower with a loop :(
**Output (using `print_r`)**
```
Array
(
[0] => J
[1] => J
[2] => HA
[3] => SA
[4] => DA
[5] => CA
[6] => HJ
[7] => SJ
[8] => DJ
[9] => CJ
[10] => HQ
[11] => SQ
[12] => DQ
[13] => CQ
[14] => HK
[15] => SK
[16] => DK
[17] => CK
[18] => H2
[19] => S2
[20] => D2
[21] => C2
[22] => H3
[23] => S3
[24] => D3
[25] => C3
[26] => H4
[27] => S4
[28] => D4
[29] => C4
[30] => H5
[31] => S5
[32] => D5
[33] => C5
[34] => H6
[35] => S6
[36] => D6
[37] => C6
[38] => H7
[39] => S7
[40] => D7
[41] => C7
[42] => H8
[43] => S8
[44] => D8
[45] => C8
[46] => H9
[47] => S9
[48] => D9
[49] => C9
[50] => H10
[51] => S10
[52] => D10
[53] => C10
)
```
**Edit**
Thanks to @JoKing by suggesting change `explode(" ","H$t S$t D$t C$t")` for `[H.$t,S.$t,D.$t,C.$t]`
[Answer]
# [SMBF](https://esolangs.org/wiki/Self-modifying_Brainfuck), 169 bytes
`‚êÄ` represents a literal NUL byte `\x00`.
```
<[.<]‚êÄJ J HA HK HQ HJ H01 H9 H8 H7 H6 H5 H4 H3 H2 SA SK SQ SJ S01 S9 S8 S7 S6 S5 S4 S3 S2 DA DK DQ DJ D01 D9 D8 D7 D6 D5 D4 D3 D2 CA CK CQ CJ C01 C9 C8 C7 C6 C5 C4 C3 C2
```
This is the naive solution.
Because this program contains a NUL byte, there's no easy way to use TIO. Run this in the [Python interpreter](https://ideone.com/L2byRe) using
```
data = bytearray(b'<[.<]\x00J J HA HK HQ HJ H01 H9 H8 H7 H6 H5 H4 H3 H2 SA SK SQ SJ S01 S9 S8 S7 S6 S5 S4 S3 S2 DA DK DQ DJ D01 D9 D8 D7 D6 D5 D4 D3 D2 CA CK CQ CJ C01 C9 C8 C7 C6 C5 C4 C3 C2')
```
[Answer]
# Japt, ~~32~~ ~~30~~ 26 bytes
```
'J¬≤¬¨c"JQKA"¬¨c9√µ√Ñ)√Ø+"CHSD"q
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.6&code=J0qyrGMiSlFLQSKsYzn1xCnvIkNIU0QicSltcQ==&input=LVE=)
```
'J¬≤¬¨c"JQKA"¬¨c9√µ√Ñ)√Ø+"CHSD"q
'J                             :Literal "J"
  ¬≤                            :Repeat twice
   ¬¨                           :Split
    c                          :Concatenate
     "JQKA"¬¨                   :  Split "JQKA"
            c                  :  Concatenate
             9√µ                :    Range [1,9]
               √Ñ               :    Add 1 to each
                )              :  End concatenation
                 √Ø             :  Cartesian Product
                   "CHSD"q     :    Split "CHSD"
                  +            :  Join each pair to a string
```
[Answer]
## Batch, 118 bytes
```
@for %%s in (C D H S)do @(for /l %%r in (2,1,10)do @echo %%r%%s)&for %%r in (J Q K A)do @echo %%r%%s
@echo J
@echo J
```
[Answer]
# [J](http://jsoftware.com/), 41 bytes
```
'J';^:2,'HCDS',&.>/~(":&.>2+i.9),;/'AJQK'
```
[Try it online!](https://tio.run/##y/r/PzU5I1/dS906zspIR93D2SVYXUdNz06/TkPJCkgbaWfqWWrqWOurO3oFeqv//w8A "J ‚Äì Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~67~~ 66 bytes
```
c(paste(rep(c('A',2:10,J<-'J','Q','K'),4),c('S','D','H','C')),J,J)
```
[Try it online!](https://tio.run/##K/pfYfs/WaMgsbgkVaMotUAjWUPdUV3HyMrQQMfLRlfdS11HPRCIvdU1dUw0dYCywUCeCxB7ALGzuqamjpeOl@b/3MSSoswKjYpoQytTo1gdQ2NNropoU2MrU5PY/wA "R ‚Äì Try It Online")
Only one more byte than [digEmAll's golfier solution](https://codegolf.stackexchange.com/a/166648/80010). Inspired by[Giuseppe's solution](https://codegolf.stackexchange.com/a/158100/80010) to [this related challenge](https://codegolf.stackexchange.com/q/158060/80010) - the same Giuseppe who golfed one byte off by answer!
I'm posting separately since it's a slightly different approach taking advantage of the fact that 4 is not a divisor of 13 and that the output does not need to be in any particular order.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~126~~ ~~137~~ 133 bytes
```
#define S(X)"A"X,"2"X,"3"X,"4"X,"5"X,"6"X,"7"X,"8"X,"9"X,"10"X,"J"X,"Q"X,"K"X,
#define c (char*[54]){S("S")S("D")S("H")S("C")"J","J"}
```
[Try it online!](https://tio.run/##Rc5NS8NAEAbge37Fy5bCblpt1cQP0gpVD6InyaXQ9hA2iR1IN7JJBSn97XEmErw87MzOvIy9@LS2G5Gz1TEvsGjanOrL/WM3youSXIFUr41aqfVUXQs3QiTEwq1wJ9wLD8LVXHwTPoR3JhjiLLTdZz7cxNHOnFKtUmXYl97X3mdleFsSzh25FoeMnP6uKTc4BYC0KOFHWXtowhLzBIQF4ijBZEKGv4Avz3OlVuMGagq7oZ2RndkMDR2oynz1w6WcgjBccYhN/uunoR5Sto5HlpD@ON86Tvyr@0xftEfv@Irg3P0C "C (gcc) ‚Äì Try It Online")
+11 bytes to be more complete thanks to Jakob.
-4 bytes thanks to Zachary
Mostly abusing of preprocessor to compress the suits. Could probably be out-golfed, but is pretty efficient all things considered.
[Answer]
# Javascript (ES6) 77 74 72 bytes
This is a complete program.
```
`J,J,${[..."A23456789JQK",10].map(c=>[..."SDHC"].map(s=>c+s))}`.split`,`
```
[Answer]
# C (gcc, clang), 138 bytes
```
#define p(c)putchar(c)
int main(){for(char*q,*r="CDHS";*r;r++)for(q="A234567890JQK";*q;q++)(48==*q)&&p(49),p(*q),p(*r),p(32);puts("J J");}
```
Approach is to encode the sequences in character arrays.
**Sample Output**
```
AC AD AH AS 2C 2D 2H 2S 3C 3D 3H 3S 4C 4D 4H 4S 5C 5D 5H 5S 6C 6D 6H 6S 7C 7D 7H 7S 8C 8D 8H 8S 9C 9D 9H 9S 10C 10D 10H 10S JC JD JH JS QC QD QH QS KC KD KH KS J J
```
[Try it online!](https://tio.run/##S9ZNT07@/185JTUtMy9VoUAjWbOgtCQ5I7EIyOLKzCtRyE3MzNPQrE7LB4oAhbUKdbSKbJWcXTyClay1iqyLtLU1QXKFtkqORsYmpmbmFpYGXoHeQMlC60KgpIaJha2tVqGmmlqBhomlpk6BBpADIotApLGRpjXQwmINJS8FLyVN69r//wE)
[Answer]
# Oracle SQL, 164 bytes
Not a golfing language but...
```
SELECT CASE WHEN LEVEL>52THEN'J'ELSE DECODE(MOD(LEVEL,13),1,'A',11,'J',12,'Q',0,'K',MOD(LEVEL,13))||SUBSTR('HDSC',CEIL(LEVEL/13),1)END FROM DUAL CONNECT BY LEVEL<55
```
[Try it online - SQL Fiddle](http://sqlfiddle.com/#!4/ae2cc8/456)
[Answer]
# [Lua](https://www.lua.org), ~~156~~ ~~127~~ ~~138~~ 129 bytes
```
loadstring'r={"J","J"}for x=1,52 do p=x%4+1r[#r+1]=({"A",2,3,4,5,6,7,8,9,10,"J","Q","K"})[x%13+1]..("SDHC"):sub(p,p)end return r'
```
[Try it online!](https://tio.run/##HY3JCsIwFAB/JTwpTeijmC5ukIPoQfQkHouHdBOhJCFNoVD67TF4mNsMM0zS98IPWrajs1/1ia1Y4A4YWHttySw4lhlpNTFijoqE22pjE/4WdIEzYIY5FljiDvd4wCPyLf7rZ@ABK6vmiOdBT1MKr@vtAuw0TjU1aFinWmI7N1lFbOxNmDvqZD10aaNVIx3tKUNAAoz5Hw "Lua ‚Äì Try It Online")
Based on Jo King's code.
As he suggested in the comments, my original answer wasn't valid (I'm still learning how code golf works üò¨), and linked a better and valid answer. Then I made it smaller.
---
### Original solution (156 bytes):
```
r={}s="SDHC"c={"J","Q","K"}t=table.insert for x in s:gmatch"."do for y=1,13 do t(r,(y==1 and"A"or y>10 and c[y-10]or y)..x)end end for _=1,2 do t(r, "J")end
```
```
r={} -- initializes the result table
s="SDHC" -- initializes the suits' string, it's better to be a string because we're just looping through it
c={"J","Q","K"} -- initializes some of the special cards
t=table.insert -- stores the table.insert call inside the 't' variable
for x in s:gmatch"."do -- loops through the suits, calling each one 'x'
  for y=1,13 do -- 'y' is the current card
    t(r,(y==1 and"A"or y>10 and c[y-10]or y)..x) -- adds the card accompanied by the suit to the result ('r') table
      -- y==1 and"A"or y>10 and c[y-10]or y  means if we're at the first card, it's an "A", else if we're past the 10th card, it's a special card, else, it's the number itself
  end
end
for _=1,2 do t(r, "J")end -- loop 2 times, adding a "J" to the result table
```
I just want to say that I'm new to this Code Golf stuff, so if I'm doing something wrong, feel free to tell me.
I know this answer isn't one of the smallest, I just wanted to challenge myself.
If you have suggestions for reducing my code you can say too. :)
[Answer]
# [Perl¬†6](https://github.com/nxadm/rakudo-pkg), ~~¬†43¬†~~ 42 bytes
```
{|(|(2..10),|<A J Q K>X~ <S D H C>),|<J J>}
```
[Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszcWVW6mglpyfkqpg@7@6RqNGw0hPz9BAU6fGxlHBSyFQwdsuok7BJljBRcFDwdkOJO6l4GVX@784sVIBpE1D8z8A "Perl 6 ‚Äì Try It Online")
```
{|(|(^9+2),|<A J Q K>X~ <S D H C>),|<J J>}
```
[Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszcWVW6mglpyfkqpg@7@6RqNGI85S20hTp8bGUcFLIVDB2y6iTsEmWMFFwUPB2Q4k7qXgZVf7vzixUgGkS0PzPwA "Perl 6 ‚Äì Try It Online") from [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)
## Expanded:
```
{  # bare block lambda
    |(  # flatten into outer list
        |(  # flatten into left-side list for X~
          ^9 + 2
          # 0+2 ..^ 9+2
          #   2 ..^ 11
          #   2 ..  10
        ),
        |   # flatten into left-side list for X~
          < A J Q K >
      X~    # cross using &infix:¬´ ~ ¬ª (string concatenation)
        <S D H C>
    ),
    |< J J > # flatten two `J`s into outer list
}
```
[Answer]
# QBasic 4.5, ~~114~~ ~~142~~ 127 bytes
```
dim r$(54)
FOR i=1TO 52
m=i MOD 13
r$(i)=MID$("JQKA2345678910",1+m,1-(m=12))+MID$("CDHS",(i-1)\13+1,1)
NEXT
r$(53)="J
r$(54)="J
```
Release Notes:
* V1.0 Initial deploy
* V1.1 Misread the challenge requirements, so switched to a more expensive array `r$`. All the rest of the code is pretty much the same.
* V1.2 Suggestions from @TaylorScott lead to a complete rewrite saving 15 bytes!
**Sample output**
If we add this snippet to our code, we can see what is put into `r$`:
```
for i = 1 to ubound(r$)
?r$(i)
next
QC
KC
AC
2C
3C
4C
5C
6C
7C
8C
9C
10C
JC
QD
KD
AD
[... snip ...]
6S
7S
8S
9S
10S
JS
J
J
```
**But how?** Well, let me tell you:
```
dim r$(54)          ' create a 54-slot array for our results
FOR i=1TO 52        ' Loop through the numbers 1-52 in var i
m=i MOD 13          ' Take i mod 13 to select a value (saved as m)
                    ' , and (not saved) i intdiv 13 to get a suit
r$(i)=              ' assigns to slot i in the result array
  MID$("JQKA2345678910"  ' a substring from the string with all the values
  ,1+m                   ' from position 1-13 (13 % 13 = 0, but QBasic strings are 1-based.
                         ' Hence the + 1)
  ,1-(m=12))             ' taking 1 char by default, and 2 for the Ten
                         ' Note that m=12 evaluates to 0 for 0-11, and to -1 for 12
  + MID$("CDHS",(i-1)\13+1,1)  ' and take 1 char from the suits-string
NEXT
r$(53)="J           ' Then append 2 jokers
r$(54)="J           ' These strings are auto-closed by the QBasic compiler.
```
[Answer]
# Pyth, ~~26~~ 25 bytes
```
+ B\JsM*+tSTc"JQKA"1"CDHS
```
Saved a byte thanks to hakr14.
[Try it here](http://pyth.herokuapp.com/?code=%2B+B%5CJsM%2a%2BtSTc%22JQKA%221%22CDHS&debug=0)
### Explanation
```
+ B\JsM*+tSTc"JQKA"1"CDHS
         tST                Get the range from 2 to 10...
        +   c"JQKA"1        ... plus the list ['J', 'Q', 'K', 'A'].
       *            "CDHS   Take the Cartesian product with the suits.
     sM                     Stick the ranks and suits together.
+ B\J                       Add the jokers.
```
]


[Question]
      [
`your shift key is broken. wheNever you type two lines, the cApitaL`
`LetteRs in them get swappeD. you must write a program to fiX THIS!`
## Description
The input is two strings, `s1` and `s2`, equal in length. They will each contain only printable ASCII and be at least one character in length. You may input these as two strings, an array of two strings, or a single string with `s1` and `s2` separated by either a tab or newline.
The output is the following:
* For each character `c` in `s1`:
	+ If the character is not a letter, output it unchanged.
	+ Otherwise, if `c` is a letter:

		- Find the matching character (the one at the same index) in `s2`.

			* If it is a capital letter, output `c` capitalized.
			* If it is a lowercase letter, output `c` in lowercase.
			* Otherwise, output `c` unchanged.
* Then do the same thing, except with `s1` and `s2` switched.
Essentially, all letters in `s1` for which the matching character in `s2` is capital should be capitalized, and all letters in `s1` with a lowercase letter at the same index in `s2` should become lowercase (and vice versa).
## Test cases
Input:
```
ABCDEfghijKlMnOpqrstuvwxyz
aaaaaaaaaaaaaaaa----------
```
Output:
```
abcdefghijklmnopqrstuvwxyz
AAAAAaaaaaAaAaAa----------
```
---
Input:
```
PRogrammiNG puzZLes & CODe golf
SdlkhkfaladlKsdlalksdg7ldklDgsl
```
Output:
```
Programming Puzzles & Code Golf
SDlkhkfalADlksdLAlksdg7LDkldgsl
```
---
Input:
```
AAAbbb111
Cc2Dd3Ee4
```
Output:
```
AaABbb111
CC2dd3Ee4
```

[Answer]
# CJam, 25 bytes
```
{z{_el_eu&\__:^32&f^?}%z}
```
This is an anonymous function that pops an array of strings from the stack and leaves one in return.
In supported browsers, you can verify all test cases at once in the [CJam interpreter](http://cjam.aditsu.net/#code=qN%2F2%2F%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20Read%20input%20and%20split%20into%20arrays%20of%20two%20strings.%0A%0A%7Bz%7B_el_eu%26%5C__%3A%5E32%26f%5E%3F%7D%25z%7D%0A%0A%25%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20Map%20the%20block%20over%20all%20string%20arrays.%0A%3A%2BN*%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20Separate%20the%20strings%20by%20linefeeds.&input=ABCDEfghijKlMnOpqrstuvwxyz%0Aaaaaaaaaaaaaaaaa----------%0APRogrammiNG%20puzZLes%20%26%20CODe%20golf%0ASdlkhkfaladlKsdlalksdg7ldklDgsl%0AAAAbbb111%0ACc2Dd3Ee4).
### Test cases
**Code**
```
qN/2/                     e# Read input and split into arrays of two strings.
{z{_el_eu&\__:^32&f^?}%z}
%                         e# Map the block over all string arrays.
:+N*                      e# Separate the strings by linefeeds.
```
**Input**
```
ABCDEfghijKlMnOpqrstuvwxyz
aaaaaaaaaaaaaaaa----------
PRogrammiNG puzZLes & CODe golf
SdlkhkfaladlKsdlalksdg7ldklDgsl
AAAbbb111
Cc2Dd3Ee4
```
**Output**
```
abcdefghijklmnopqrstuvwxyz
AAAAAaaaaaAaAaAa----------
Programming Puzzles & Code Golf
SDlkhkfalADlksdLAlksdg7LDkldgsl
AaABbb111
CC2dd3Ee4
```
### How it works
```
z                       e# Zip to transform the array of strings into an array
                        e# of character pairs.
 {                  }%  e# For each character pair:
  _el                   e#   Push a copy and convert to lowercase.
     _eu                e#   Push a copy and convert to uppercase.
        &               e#   Intersect. The result will be an empty string if
                        e#   and only if both characters are letters.
         \              e#   Swap the character pair on top of the stack.
          __            e#   Push two copies.
            :^          e#   XOR both characters.
              32&       e#   Logical AND with 32. This pushes 32 for letters of
                        e#   different cases and 0 for letters of the same case.
                 f^     e#   XOR each character with the result.
                   ?    e#   Select the original copy for non-empty intersection
                        e#   and the modified one otherwise.
                      z e# Zip to turn the characters pairs back into two strings.
```
[Answer]
# C, 126 bytes
This is my first attempt at a code golf, ever. Let me know if I did anything wrong.
I'm using bitwise operations to perform the switching
Golfed:
```
main(u,a,s,t)char**a,*s,*t;{for(s=a[1],t=a[2];*t;s++,t++)isalpha(*s)*isalpha(*t)?u=(*t^*s)&32,*t^=u,*s^=u:0;*s=10;puts(a[1]);}
```
Ungolfed:
```
main(u,a,s,t) char**a,*s,*t; {       // K&R style arguments
    for(s=a[1],t=a[2];*t;s++,t++)    // initialize loop.
        isalpha(*s) * isalpha(*t) ? // ensure both characters are letters (if)
            u = (*t^*s) & 0x20,      // check if characters have swapped case
            *t^=u,                   // if so, xor the bit which represents case
            *s^=u                    // for both characters in the string.
        :0;                          // end ternary statement (endif)
    *s=10;                           // replace null terminator in first string
    puts(a[1]);                      // with newline. This allows both output to
}                                    // be printed out all at once
```
edit: replaced && with \*
[Answer]
# Pyth, ~~19~~ 18 bytes
```
LCmrW&@dG@drG1d2Cb
```
This defines a function **y** that accepts and return a list of strings.
Verify all test cases at once in the [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=LCmrW%26%40dG%40drG1d2Cb%0A%0Ajb%2BFmydc.z2&input=ABCDEfghijKlMnOpqrstuvwxyz%0Aaaaaaaaaaaaaaaaa----------%0APRogrammiNG+puzZLes+%26+CODe+golf%0ASdlkhkfaladlKsdlalksdg7ldklDgsl%0AAAAbbb111%0ACc2Dd3Ee4&debug=0).
*Thanks to @Jakube for golfing off 1 byte.*
### How it works
```
                   " (implicit) Initialize G to 'abcdefghijklmnopqrstuvwxyz'.
L                  " Define y(b):
                Cb "   Zip to turn the two strings into an array of char pairs.
  m                "   Map (implicit variable d):
      @dG          "     Intersect d with G.
         @drG1     "     Intersect d with G.upper().
    W&             "     If both are non-empty:
   r          d2   "       Apply swapcase() to d.
 C                 "   Zip to turn the character pairs back into two strings.
```
[Answer]
# SQL (PostGreSQL), 427 Bytes
Despite it's huge size, this ended up being quite a bit smaller than I expected. I wasn't quite sure I was going to be able to do it to be honest. I suspect there is a lot that still can be done:)
```
CREATE FUNCTION F(TEXT,TEXT)RETURNS TABLE(S TEXT) AS'SELECT unnest(array[string_agg(CASE WHEN T~''[A-Z]''THEN upper(S)WHEN T~''[a-z]''THEN lower(S)ELSE S END,''''),string_agg(CASE WHEN S~''[A-Z]''THEN upper(T)WHEN S~''[a-z]''THEN lower(T)ELSE T END,'''')])FROM(SELECT ROW_NUMBER()OVER()N,S FROM regexp_split_to_table($1,'''')X(S))A JOIN(SELECT ROW_NUMBER()OVER()M,T FROM regexp_split_to_table($2,'''')Y(T))B ON N=M'LANGUAGE SQL
```
Formatted and commented
```
-- Declare the function spec
CREATE FUNCTION F(TEXT,TEXT)RETURNS TABLE(S TEXT) AS
'SELECT unnest(   -- turns array into a table
    array[        -- build array of the column results
    string_agg( -- Aggregate the result into a string
        CASE
        WHEN T~''[A-Z]''THEN upper(S) -- uppercase it if corresponding char is uppercase
        WHEN T~''[a-z]''THEN lower(S) -- lowercase it if corresponding char is lowercase
        ELSE S END
        ,''''),
    string_agg( -- Same as the previous but swap strings
        CASE
        WHEN S~''[A-Z]''THEN upper(T)
        WHEN S~''[a-z]''THEN lower(T)
        ELSE T END
        ,'''')
    ])
FROM
    -- split the first string
   (SELECT ROW_NUMBER()OVER()N,S FROM regexp_split_to_table($1,'''')X(S))A
    JOIN
    -- split the second string
   (SELECT ROW_NUMBER()OVER()M,T FROM regexp_split_to_table($2,'''')Y(T))B
   ON N=M
'
LANGUAGE SQL
```
Test run
```
SELECT F(A,B) AS Result
FROM (VALUES
    ('AAAbbb111', 'Cc2Dd3Ee4'),
    ('ABCDEfghijKlMnOpqrstuvwxyz', 'aaaaaaaaaaaaaaaa----------'),
    ('PRogrammiNG puzZLes & CODe golf', 'SdlkhkfaladlKsdlalksdg7ldklDgsl')
    )A(A,B)
Result
-----------------------------
AaABbb111
CC2dd3Ee4
abcdefghijklmnopqrstuvwxyz
AAAAAaaaaaAaAaAa----------
Programming Puzzles & Code Golf
SDlkhkfalADlksdLAlksdg7LDkldgsl
```
[Answer]
# Julia, 140 bytes
```
f(s,t)=(C(x,y)=(i=0;z="";for c=x i+=1;z*=string(isalpha(c)?isupper(y[i])?uppercase(c):islower(t[i])?lowercase(c):c:c)end;z);(C(s,t),C(t,s)))
```
This creates a function that accepts two strings and returns a tuple of strings. Nothing particularly clever is going on here; we simply define an inner function that directly implements the algorithm in the spec and call it twice.
Ungolfed:
```
function f(s, t)
    C(x, y) = begin
        i = 0
        z = ""
        for c in x
            i += 1
            if isalpha(c)
                if isupper(y[i])
                    z *= string(uppercase(c))
                elseif islower(y[i])
                    z *= string(lowercase(c))
                else
                    z *= string(c)
                end
            else
                z *= string(c)
            end
        end
        return z
    end
    return (C(s, t), C(t, s))
end
```
[Answer]
# JavaScript ES6, ~~128~~ 108 bytes
```
s=(a,b,t)=>[...a].map((l,i)=>/[^a-z]/.exec(b[i])?l.toUpperCase():l.toLowerCase()).join``+(t?'':`
`+s(b,a,1))
```
JavaScript's `toUpperCase()` and `toLowerCase()` take up a lot of bytes but `String.fromCharCode()` is even longer
[Answer]
## Mathematica, ~~173~~ ~~169~~ 155 bytes
```
f=0>1;t=!f;c=Characters;u=ToUpperCase;StringJoin/@MapThread[#@#2&,{Reverse[{LetterQ@#,#==(u@#)}&/@c@#/.{{f,_}->(#&),{t,t}->u,{t,f}->ToLowerCase}&/@#],c/@#},2]&
```
This is a function taking an array of two strings, e.g. `{"Foo","bAR"}` and outputting an array of two strings. Un-spatially-compressing it, rewriting the scheme `f@x` as `f[x]` wherever it appears, expanding the notation abbreviations (`f=0>1` a.k.a. `False`,`t=!f` a.k.a. `True`, `c=Characters`, and `u=ToUpperCaseQ`), and un-replacing UpperCaseQ[#] with `#==u@#` (this character equals its uppercased version), it is:
```
StringJoin /@ MapThread[#[#2] &, {
    Reverse[
        { LetterQ[#], UpperCaseQ[#] } & /@ Characters[#] /.
        { {False, _} -> (# &), {True, True} -> ToUpperCase,
          {True, False} -> ToLowerCase } & /@ #
    ],
    Characters /@ #
}, 2] &
```
Interfacing: the trailing `&` makes this a function. Its argument is inserted as the "#" at both instances of `/@ #`. For instance `f=0>1; ... & [{"AAAbbb111", "Cc2Dd3Ee4"}]` produces the output `{AaABbb111,CC2dd3Ee4}`.
Processing: Told in usual outside in order:
* The output of the `MapThread[...]` is a list of two lists of characters. StringJoin is applied to each of these two lists of characters to produce a list of two strings, the output.
* `MapThread[#[#2]&, ... , 2]` acts on an array of two 2-by-n element lists. The first list is a 2-by-n array of functions. The second list is a 2-by-n array of characters, `Characters /@ #`, the lists of characters in the two input strings. It works at depth 2, i.e., on the functions and individual characters.
* `Reverse[...]` swaps the two sublists of functions so that MapThread will apply the second string's functions to the first string and vice versa.
* `{ ... } &` is an anonymous function that is applied to each of the two input strings.
* `{LetterQ[#], UpperCaseQ[#]} & /@ Characters[#]` splits a string into a list of characters, then replaces each character with two element lists. In these two element lists, the first element is `True` if the character is a letter and `False` otherwise, similarly, the second element indicates whether the character is upper case. `UpperCaseQ[]` cannot return true if it does not receive a letter.
* `/. {{False, _} -> (# &), {True, True} -> ToUpperCase, {True, False} -> ToLowerCase}` replaces these two element lists with functions. (Expansion of the abbreviations `t` and `f` occurs before any matching is attempted.) If a two element list has `False` as its first element, it is replaced with the function `(# &)`, the identity function. (The parentheses are necessary, otherwise the arrow binds more tightly than the ampersand.) Otherwise the two element list starts with `True`, the character was a letter, and we output the functions `ToUpperCase` and `ToLowerCase` corresponding to its case. (Checking for this last `False` is unnecessary, in fact `{_,_}->ToLowerCase` would work, catching anything that hadn't been replaced yet, but this would be no shorter and more obscure.)
The only challenge was figuring out a succinct way to zip a two dimensional array of functions to an array of arguments.
Edit: Thanks to @Martin Büttner for catching "helpful" cut/paste linebreak backslashes, the `1>0` and `1<0` abbreviations, and also for the guidance to count length in bytes not characters (whatever those are :-) )
Edit2: Further thanks to @Martin Büttner for pointing out that polluting the global namespace is acceptable golf, reminding me of one character function application, and suggesting replacing the two uppercase functions with an abbreviation for one and using the one to emulate the other (saving four characters). (I think he's done this before. :-) )
[Answer]
# Python 3, 131 bytes
```
def j(s,g):p=lambda s,g:''.join(i.upper()if j.istitle()else i.lower()if j.islower()else i for i,j in zip(s,g));return p(s,g),p(g,s)
```
Function returns strings in a tuple
[Answer]
# Erlang, 157 bytes
```
f(A,B)->S=string,G=fun(A,B)->[if Q>64andalso Q<91->S:to_upper(P);Q>96andalso Q<123->S:to_lower(P);true->P end||{P,Q}<-lists:zip(A,B)]end,G(A,B)++"\n"++G(B,A).
```
Zips the two strings (actually, lists) into a two-character-tuple list and maps each character to the appropriate case using a list comprehension.
[Answer]
# Python 2, 101 bytes
```
lambda*I:["".join([a.upper(),a.lower(),a][~-b.isalpha()or"Z"<b]for a,b in zip(*X))for X in I,I[::-1]]
```
An anonymous function which takes two strings and returns the output strings in a list. I've marked this as Python 2 because Python 3 doesn't allow `I,I[::-1]` to sit alone at the end like that.
[Answer]
# Python, 126 bytes
```
t="".join;s="low","upp";y=lambda a,b:eval("a"+".%ser()"%s[b.isupper()]*b.isalpha());f=lambda a,b:(t(map(y,a,b)),t(map(y,b,a)))
```
Function `f` returns strings in a tuple
[Answer]
# C, 181 bytes
```
char*x,*y;main(int a,char**_){a?x=_[2],y=_[1],main(0,0),putchar(10),x=_[1],y=_[2],main(0,0):(*x?putchar(!isupper(*x)?!islower(*x)?*y:tolower(*y):toupper(*y)),x++,y++,main(0,0):0);}
```
Had trouble shortening standard library names in a worthwhile way, (#define'ing them takes 11 characters of overhead). Uses main recursion and global variables x and y as arguments.
main(<non-zero>,argv) = call main(0,{argv[1],argv[2]}) then print newline then call main(0,{argv[2],argv[1]})
main(0,{x,y}) = if x is end of string return 0, else print correct case of first character of x and call main(0,{x+1,y+1}).
Run with the two strings as arguments.
[Answer]
# C - ~~164~~ 153 Bytes - GCC
```
#define r z[_][w]
main(_,z,w)char**z;{while(--_)for(w=0;r;r+=r<25?97:r<91&&r>64?z[!(_-1)+1][w]-=32,_-1?z[_-1][w]-=97:0,32:0,w++);puts(z[1]),puts(z[2]);}
```
gcc prog.c
./a.out AfdgF a2dfsd
Will update if I can get wc -c down. Works very well actually
[Answer]
# F#, 211 chars
```
let n x y=List.fold2(fun a i j->a@match j with|c when c>='A'&&c<='Z'->[Char.ToUpper i]|c when c>='a'&&c<='z'->[Char.ToLower i]|_->[i])[](x|>Seq.toList)(y|>Seq.toList)|>String.Concat
let m a b =n a b+"\n"+n b a
```
could be better ...
[Answer]
## Matlab, 140
```
function [s,t]=f(s,t)
c=s>96&s<123;C=s>64&s<91;d=t>96&t<123;D=t>64&t<91;s(c&D)=s(c&D)-32;s(C&d)=s(C&d)+32;t(d&C)=t(d&C)-32;t(D&c)=t(D&c)+32;
```
Ungolfed:
```
function [s,t] = f(s,t)
c = s>96 & s<123;         % letters that are lowercase in 1st string
C = s>64 & s<91;          % letters that are uppercase in 1st string
d = t>96 & t<123;         % letters that are lowercase in 2nd string
D = t>64 & t<91;          % letters that are uppercase in 2nd string
s(c&D) = s(c&D) - 32;     % make uppercase in 1st string
s(C&d) = s(C&d) + 32;     % make lowercase in 1st string
t(d&C) = t(d&C) - 32;     % make uppercase in 2nd string
t(D&c) = t(D&c) + 32;     % make lowercase in 2nd string
```
Example:
```
>> [s,t]=f('PRogrammiNG puzZLes & CODe golf','SdlkhkfaladlKsdlalksdg7ldklDgsl')
s =
Programming Puzzles & Code Golf
t =
SDlkhkfalADlksdLAlksdg7LDkldgsl
```
[Answer]
# C, 164 bytes
Pretty much implementing the algorithm as described in the problem. Takes 2 strings as input parameters.
```
char*a,*b;main(c,v)char**v;{for(a=v[1],b=v[2];*a&&*b;++a,++b)isupper(*a)&&islower(*b)?*a+=32,*b-=32:isupper(*b)&&islower(*a)?*b+=32,*a-=32:0;puts(v[1]);puts(v[2]);}
```
Ungolfed:
```
char *a, *b; /* Helpers */
main(c, v)
char **v;
{
    /* While strings not terminated... */
    for (a = v[1], b = v[2]; *a && *b; ++a, ++b)
        isupper(*a) && islower(*b)
            ? *a += 32, *b -= 32 /* Make first string lowercase, second uppercase */
            : isupper(*b) && islower(*a)
                ? *b += 32, *a -= 32; /* Make second string lowercase, first uppercase */
    puts(v[1]); /* print out first string */
    puts(v[2]); /* print out second string */
}
```
[Answer]
## Ruby, 102
```
$><<gets.chars.zip(gets.chars).map{|i|/[a-z][A-Z]|[A-Z][a-z]/=~i*''?(i.map &:swapcase):i}.transpose*''
```
Takes the original strings, pairs off letters in arrays. If they are either lower/cap or cap/lower, then swapcase on both. Then transpose the arrays back into our ordered array.
This requires a trailing newline in input.
[Answer]
# Perl 5.10+, 101 99 bytes
```
perl -p00e '/\n/;s/([a-z])(?=.{$-[0]}([a-z]))/$x=($1^$2)&" ";$s{$-[2]}=$2^$x;$1^$x/egis;s|.|$s{$-[0]}//$&|eg'
```
96 bytes + 3 bytes for the command line flags `p00`. Takes a single newline-delimited string as input:
```
$ echo -e "AAAbbb111\nCc2Dd3Ee4" | perl -p00e '...'
```
Or you can enter input on STDIN:
```
$ perl -p00e '...'
AAAbbb111 <Enter>
Cc2Dd3Ee4 <Ctrl+D>
```
## Broken down:
```
perl -p00e'  # Slurp everything into $_, print $_ automatically at the end
    /\n/;    # Match first newline, setting $-[0] to length(s1)
    s/
        ([a-z])  # Match a single letter in s1
        (?=
            .{$-[0]}  # Match n chars where n is length(s1) (until corresponding char in s2)
            ([a-z])   # Corresponding letter in s2
        )
    /
        $x=($1^$2)&" ";   # Check whether bit 6 is the same for both chars.
                          # (Only difference between a lowercase and uppercase ASCII letter
                          # is bit 6; ASCII space is 100000 in binary)
        $s{$-[2]}=$2^$x;  # Swap case of corresponding char in s2 and store in %s,
                          # with position as the key
        $1^$x             # Swap case of current char
    /egis;
    s|.|$s{$-[0]}//$&|eg  # Do a second pass through $_. If there's a value stored in %s
                          # corresponding to this position, use it
'
```
[Answer]
# First attempt in scala, 138 chars
```
def f(s:String,t:String)={val g=(a:Char,o:Char)=>if(o.isUpper)a.toUpper else a.toLower;s.zip(t).map(c=>(g.tupled(c),g(c._2, c._1))).unzip}
```
f is a function that take the two input strings and do the job, with a local function, used two times, for changing case of strings.
The same code, with indentation and just a litte more readable names :
```
def f_ungolfed(first : String, second : String) = {
  val aux = (c1: Char, c2: Char) => if (c2.isUpper) c1.toUpper else c1.toLower
    first.zip(second).map(
         c => (aux.tupled(c), aux.tupled(c.swap))
    ).unzip
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
=Œu=/ị"Ɱż"Œs$
```
A monadic Link accepting and returning lists of two "strings" (lists of characters in Jelly).
**[Try it online!](https://tio.run/##ATUAyv9qZWxsef//PcWSdT0v4buLIuKxrsW8IsWScyT/4bu0w4dZ//9Db2RlR29sZgp4eFBQQ0d4eA "Jelly – Try It Online")**
[Answer]
# [Python 2](https://docs.python.org/2/), 97 bytes
```
lambda a,b:''.join([x,chr(ord(x)&95|ord(y)&32)][(x+y).isalpha()]for x,y in zip(a+'\n'+b,b+' '+a))
```
[Try it online!](https://tio.run/##XZDBT8IwFMbP@lf0RNtskjA0RhIPY1t2QGTBmBiBQ0vXraysswPpFv/3SZ148J2@933v/Q5f1RxyVXodf1x3kuwpI4C4dALhcKdEiVbG3eYaKc2QwYOHuy@rGjwYe3izQsZp8FDURFY5QXjDlQbGbYAoQSsqRBy4LqFDXepAAB2CcWcvznh7sULQnwZhxLNc7GZyXi6qD10fjp8n07TQBZD8m5u/gdgFCCZLlWmy34vnGFTH9v0prcEABIswBZmS3CJemCzyghNJmJzVTBJZ1Cy7l6yQYVbLnuP7PqV0NBrZj2DrhWwcpbd9FiiWxmfYT2ZMkgSxZ0yfSXVKtfVfkyRa9t5cvKWh9fqw59vd/9XTLbNrxOMc4s3k@qrSojwAchH0Ijg694Rd22D3DQ "Python 2 – Try It Online")
[Answer]
# [Tcl](http://tcl.tk/), 194 bytes
```
proc C a\ b {proc L x\ y {expr [[set S string] is u $y]?"[$S tou $x]":"[$S is lo $y]"?"[$S tol $x]":"$x"}
lmap x [split $a ""] y [split $b ""] {append s [L $x $y]
append t [L $y $x]}
list $s $t}
```
[Try it online!](https://tio.run/##XZBBT4NAEIXv@yteNsSbh6qJiReD0HgoWmNvUg5LFygywMouCm347bjQ1oNz@@blvckbs6NxVE29gwexRYzjDAG6LXock041CEOdGGygTZNXWYRco4XTR488dDYwtYUu4g8zWY3qSeQXlc6q0/GBUSkUOoRaUW7gCHAe2TsXjmc@CqWSSkIjDKx5SmPnlZlX/RRpw3JtPRqOGcY5@FSAuU@ev0yzff65opdqrb4abdrvn64/MPFvrv@GMf72XmeNKMv89RmqPXwEicYVvLWfIKsp5WwjqdgXqSAhaaUlCSq0zO5JFuRnmhhzXTeO48ViwbzdjS9vl8kdG@xLW2O7eFNfJ4621TD@Ag "Tcl – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~109~~ 91 bytes
```
import Data.Char
(!)=zipWith f
f c|isUpper c=toUpper|isAlpha c=toLower|1<3=id
a#b=[b!a,a!b]
```
Thanks to @Laikoni for 16 bytes!
[Try it online!](https://tio.run/##XYxBS8NAEIXv@RWTFKSFKsQKXppDTIqHplYsIrQUmc0m2TWTZN3dWg3973FpwYPvMo9veJ9AUxdEwyAb1WkLKVq8SQRqb@xPol6qN2kFlF4J@UmaV6UKDXlku3NzJCYl8Eyy7uhIOJ9Fkns4YtGO@ThFn@2HBmULETSoVu8wvhx1sBurs3biwQ6C@CFJF2Ul5MeSVu1afWpjD1/H758@GAX4L9d/CTyYQvD80lUam0Y@PTptv80KA1eQrNMCqo5KZ9hwqkVdIiGnpeGEVBte3ROvKa0MXTRxHDPGwjB0gyS/TflsUdy51374BQ "Haskell – Try It Online")
]


[Question]
      [
Your task is to decipher a non-empty string consisting of printable ASCII characters in the range **[32..126]**.
Reading the string character per character:
* each time you encounter a letter in lowercase, associate it with the next letter in uppercase, starting with **'A'**
* each time you encounter a letter in uppercase, replace it with the letter in lowercase it's associated with
* other characters do not require any special processing and are just left unchanged
## Example
For the input string `"endlAsEBAEE"`:
* Associate `e` to `A`, `n` to `B`, `d` to `C` and `l` to `D`
* Replace `A` with `e`
* Associate `s` to `E`
* Replace `EBAEE` with `sness`
The final output is `"endlessness"`.
## Clarifications and rules
* The input string is guaranteed to contain each lowercase letter at most once. All further instances will be replaced with the corresponding capital letter.
* The input string is guaranteed to be valid. (You will not encounter a capital letter that is not yet associated with a lowercase letter.)
* Once a capital letter has been associated to a lowercase letter, it may or may not be used later in the string. For instance, `C` and `D` are not used in the above example.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins!
## Test cases
**Inputs:**
```
abcd
honk! ABCD!
abrAcAdABCA
endlAsEBAEE
helCo wDrCd!
dermatoglyphics
progBamFinD AuzJles & cCdL DCKf
sphinx of black quKrtz, jOdge my vGw. K NODLM IPGZE HGF SOWBA GYVP QCV JKRX TGU.
petBr AiABD AEckBd a ABFG of AEFGlBH ABAABDs. hJw mIny AEFGLBH ABAABDM HEH ABCBD AEABD AEFG?
```
**Answers:**
```
abcd
honk! honk!
abracadabra
endlessness
hello world!
dermatoglyphics
programming puzzles & code golf
sphinx of black quartz, judge my vow. a quick brown fox jumps over the lazy dog.
peter piper picked a peck of pickled peppers. how many pickled peppers did peter piper pick?
```

[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes
```
fØaØA,y
```
[Try it online!](https://tio.run/##PY0/UoNAHEZ7TvHZWGW4gvPbZVkCROK/aOwIC4FkgQiJSEobr5BDWKaz5CR6ESRxxu775s28t4q1bvs@6Q5hd6BR239/HbuPn/fPed@Hi0gZ4aKiiBQxTkZcKE21YCSEkcaal2isiqsLY1OVSxbmdlZYoN3e1XGNS0Rc@bC4lxj1Js2KN5QJFjqM1njZedV2P8IqUMsYeYtX2ZjwcB1Y/gTjqXwWcKSNu@CREeR8NsUNn8H1bp9wLx9MYxNvWQXKiA1BEa2ZQghitjw1SNhSM2f4NPDaROo2yMdFeyb@P5nAEafNz5I/lS2vfgE "Jelly – Try It Online")
### How it works
```
fØaØA,y  Main link. Argument: s (string)
 Øa      Yield the lowercase alphabet.
f        Filter; keep only characters that appear in the lowercase alphabet.
          Call the result r.
   ØA    Yield the uppercase alphabet (u).
     ,   Pair; yield [u, r].
      y  Translate s, using the substitutions in [u, r].
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
Code:
```
AÃAus‡
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f/f8XCzY2nxo4aF//8XFOWnOyXmumXmuSg4llZ55aQWK6gpJDun@Ci4OHunAQA "05AB1E – Try It Online")
[Answer]
# JavaScript (ES6), 62 bytes
```
s=>s.replace(/[A-Z]/g,c=>s.match(/[a-z]/g)[parseInt(c,36)-10])
```
Each capital letter is converted to its base 36 value, less 10.
We then match on the lowercase letter that's at that index.
```
let f=
s=>s.replace(/[A-Z]/g,c=>s.match(/[a-z]/g)[parseInt(c,36)-10])
console.log(f('abcd'))
console.log(f('abrAcAdABCA'))
console.log(f('endlAsEBAEE'))
console.log(f('helCo wDrCd!'))
console.log(f('progBamFinD AuzJles & cCdL DCKf'))
console.log(f('sphinx of black quKrtz, jOdge my vGw. K NODLM IPGZE HGF SOWBA GYVP QCV JKRX TGU.'))
console.log(f('petBr AiABD AEckBd a ABFG of AEFGlBH ABAABDs. hJw mIny AEFGLBH ABAABDM HEH ABCBD AEABD AEFG?'))
```
[Answer]
# Pyth, 36 bytes
```
JKr1GVQI&}NG!}NH=XHNhK=tK)p?}NJ@_HNN
```
[Try it here](https://pyth.herokuapp.com/?code=JKr1GVQI%26%7DNG%21%7DNH%3DXHNhK%3DtK%29p%3F%7DNJ%40_HNN&input=%22sphinx%20of%20black%20quKrtz%2C%20jOdge%20my%20vGw.%20K%20NODLM%20IPGZE%20HGF%20SOWBA%20GYVP%20QCV%20JKRX%20TGU.%22&debug=0)
### Explanation
```
JKr1GVQI&}NG!}NH=XHNhK=tK)p?}NJ@_HNN
JKr1G                                  Let J and K be the uppercase alphabet.
     VQ                                For each character in the input...
       I&}NG!}NH         )             ... if the character is lowercase and not
                                       yet in H, ...
                =XHNhK                 ... add the letter and the next uppercase
                                       letter to H...
                      =tK              ... and move to the next uppercase letter.
                          p?}NJ@_HNN   Print either the next character or the
                                       letter it represents.
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ñ·í=Üò°f1èb
```
[Run and debug it](https://staxlang.xyz/#p=a5faa13d9a95f866318a62&i=abcd%0AabrAcAdABCA%0AendlAsEBAEE%0AhelCo+wDrCd%21%0AprogBamFinD+AuzJles+%26+cCdL+DCKf%0Asphinx+of+black+quKrtz,+jOdge+my+vGw.+K+NODLM+IPGZE+HGF+SOWBA+GYVP+QCV+JKRX+TGU.%0ApetBr+AiABD+AEckBd+a+ABFG+of+AEFGlBH+ABAABDs.+hJw+mIny+AEFGLBH+ABAABDM+HEH+ABCBD+AEABD+AEFG%3F&a=1&m=2)
[Answer]
# [R](https://www.r-project.org/), 79 bytes
```
function(x){s=utf8ToInt(x)
s[j]=s[s>96&s<123][s[j<-s>64&s<91]-64]
intToUtf8(s)}
```
[Try it online!](https://tio.run/##PZBbb4JAEIXf@RWnPigkamLbmJqIzS4CKlptq/ZifUAuiuJi2aV4ib/dgk36NPPNmTknmfjiqxc/YY4IIibvlRNXE@E/jKMuExlKfLaeq3zGW416kTdrt3fzWTZqVnirfp8NGrV5pX4/lwImxtEkO5S5cr6kUexyqHBkqWAvHLdQzmtMHOISqpEcPeaGhOuU6HqOKy/UIqTtWHNvct7F0ZLaWyNgbZDk2As9jiIcze2jrVl@vsJ3q4DtEflYhLazwXdixeJYxnroLj1sD/gx0yosPA3b/QG6I/NTR8c08Dp8owTmx3SEZ22KnvXyjrE5qV5jPUFjkIDQLFZ3NtSFDUINM48humGGtJMxyXRexaqXYttlh6vS/1cG6Oh5r11N/qwM8zH3P4lVwEE8LqBxJNzzk/BcUCQ/iuUUAcP1c8pJAhxbyL6cKuXSFysp0vnyCw "R – Try It Online")
[Answer]
## [Perl 5](https://www.perl.org/) with `-p`, 27 bytes
```
eval"y/A-Z/".y/a-z//cdr."/"
```
[Try it online!](https://tio.run/##PZDLTsMwFET3@YpLFqzamA1rdO04bpuUFCgFykNyY7cJdR44fZAifp2QFondjI50RppKW3PZtnonjdsQ7M@J6zVE9g@EJMp6LnHbVi4S5ciFxQQVUoaOLpTBmlPk3Em1YSXsfcvUmVPZckVlHmSFD7g9jIyu4RwSpiLwWbh06irNik8ol7AwMlnDxza0m0MP3mO10pA3sBN7D0K4jv1oDMOJmHMYiADu4geKIJ5mE7hhMxiFt48wFfeeU@kNtYAZ0m6QJ2uqQALSQBw3kAfC0EHXseO1B@loD/mwaE4k@idjGPBjZifJnyoQVz9ltcnKom77VUCe37pPXurXr4veN/kF "Perl 5 – Try It Online")
-2 bytes thanks to [@breadbox](https://codegolf.stackexchange.com/users/4201/breadbox)!
[Answer]
# [Z80Golf](https://github.com/lynn/z80golf), 37 bytes
```
00000000: 2505 cd03 8030 0176 fe7b 300c fe61 3011  %....0.v.{0..a0.
00000010: fe5b 3004 fe41 3003 ff18 e7d6 414f 0a18  .[0..A0.....AO..
00000020: f777 2318 f3                             .w#..
```
[Try it online!](https://tio.run/##fYzNjoJAEITvPkUlxmunhwGGeNnMqKBmN/sAnhCY1Yi6WY1GfXi2wZ@jdarqqv6uCf/sa980/NAQQcQRipI1EtYMViaGr8wSmrkQFytxSgEDEjGd6MZEOVPvTlDC8FXU7UNxYbsXmvcqQWXKGKEKPTiXCFrIr@WWRPabnoygZRhjEGhZeY13onOfqGl@q6P7g11bN4adFBtXIod1aYa9l0Oa1W4q2Up/IKzmZ2xnu0vXfL6aL0wnrR91kDsqzT7@AQ "Z80Golf – Try It Online")
z80 does pretty good at this! Here is a disassembly:
```
  dec h         ; HL = cipher write pointer
  dec b         ; BC = cipher read pointer
                ; meaning of 'A'..'Z' is written to $ff00~$ff19
next:
  call $8003    ; getchar
  jr nc, ok     ; not EOF?
  halt
ok:
  cp '{'
  jr nc, other  ; a ≥ '{'
  cp 'a'
  jr nc, lower  ; 'a' ≤ a ≤ 'z'
  cp '['
  jr nc, other  ; '[' ≤ a ≤ '`'
  cp 'A'
  jr nc, upper  ; 'A' ≤ a ≤ 'Z'
other:
  rst $38
  jr next
upper:
  sub 'A'
  ld c, a
  ld a, (bc)
  jr other
lower:
  ld (hl), a
  inc hl
  jr other
```
We point both HL and BC at the `$ff00` range with `dec`, and use `rst $38` as a short alternative to `call $8000`, but otherwise there isn't much trickery going on.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 25 bytes
```
~["T`L`"|""L$`[a-z]
$&-$&
```
[Try it online!](https://tio.run/##PY3bTsJAFEXf5yu2TSU@SBO/wJyZTqe0RVARL8Sk006BSinYcpHG@OsVMPFt76xkrSrb5KW@aS@vVNz@TKxRHMXWt2VFdjzR3ead2Z2u3WlbnaSG6aSilAxxQSwrTUG15CQlm2eFWGHvVsJcsHW1mnG99PLSBW2boMhqdJAKE8EV4ZTV63lefmE1RVLodIHPbVhtmmt8DMwsw/KAndo7CHE3cKM@ekP1JuErD4@DZ05Qr@Mh7sUYQfjwgpF6ctg62/AKlBM/BmW64AYaxD11apD0VMH946cjrx3Mgz2WvfJwJtE/6cOXpy3Okj@Vp25/AQ "Retina – Try It Online") Explanation:
```
[a-z]
```
Match lowercase letters.
```
$`
$&-$&
```
Replace each letter with a degenerate range of itself. (This prevents the later transliteration from treating it as a character class; backslash can't be used because some lower case letters have a special meaning after a backslash.)
```
["T`L`"|""L
```
List the degenerate ranges, but without line separators, and with a preceding `T`L``.
```
~
```
Evaluate the resulting transliteration program on the original input.
[Answer]
# [Python 2](https://docs.python.org/2/), 78 bytes
```
lambda s:''.join('@'<c<'['and filter(str.islower,s)[ord(c)-65]or c for c in s)
```
[Try it online!](https://tio.run/##PZBJU4NAEIXP@iueF4dUIQer9JBK1Bm2rCZucYk5EAYCCQw4Q8TkzyNglZfu99Xr7lfV@aGIMnFZhf3PKvHSNfeguoQY2ywWGrkjPb9HlsQTHGGcFIHUVCGNWCVZGUhddZaZ5Jrfubi@WmUSPsK2xgKqUzVaNbreX/uc6Ki7pD7llJm0wUDwhCqbUdtuMAoSM0NpSZOfNZzLbMO81ImFBbo/jpJA4Ry@ySewzHHYjKg8isUPshDrxPN3@NqPZXHUsZ3xTYD0gG@3NDDG/cyaTDGcux82Bq6Dp9kro3DfF3M8mAuMxo9veHZfjDY2KJgEjSmrY21/xzg8UOa4TQy1HTdhg5pp7SsD0ahEOhSH1pn8O1MM7Eab7ZG/U457S1bd05NcxqKA0kn/huihVr@q@gU "Python 2 – Try It Online")
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 109 bytes
```
s->{var r=s.replaceAll("[^a-z]","");for(char i=64;i++<64+r.length();)s=s.replace(i,r.charAt(i-65));return s;}
```
[Try it online!](https://tio.run/##ZVFNc9owEL3zKzY@dOwCOqUc6pCObGyTACUtbfqRSWeELRuBLLuSDIUMv53KOAVmetCsdt/b3bfzlmRNustkdWB5WUgNS5OjSjOO3rqt/2ppJWLNClGDMSdKwYQw8dICKKs5ZzEoTbQJ64IlkBvInmnJRPb0DERmyoGaChC@jrlp0E4TbiGF/kF1b1/WRILsKyRpyUlMMee29fSLdHfPVseyHDctpB0vDIn1e9cua7dvetdtiTgVmV7Yjuuoc7PNOhLVZKxt1u29cxxXUl1JAcrdH9yjnpNITZVW0H@VCWCReZxYnX/ZohCrK8CeP7g6F8lc4hgnporPRSoSjlXg4SC4aKfcL2AzkH5y0Z9QmRNdZHxbLliszkApi8wjecjEAHC1u@dUwRuI/WQMA3@UnonKNIo/UKQwNxev4Hc1knrXgeU0ySjkW1hHGwQj@DgdjCdw9xD9DGAYhTCbfvMwRD8eH@CT/wj3o8/f4Uv0FV1IoNqTgBn2jIQgXnkJEHN/GNXLcBBG3BuaHBtcIVjcbyC/E9sjMj4hExgG9d8/DmlGhdEH67hk3zhQO1q7XhvwvrHBObkw2ypNc1RUGpXGKM2FnSJSlnxr10zjaDOqVb/94S8 "Java (JDK 10) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 105 bytes
```
C;f(char*Z){for(char*z=--Z,c,*s;c=*++z;putchar(c))for(C=64,s=Z;*z>64&91>*z&&C^*z;c=*s)C+=*++s>96&*s<123;}
```
[Try it online!](https://tio.run/##ZZBtb5swFIU/N7/iFmlRoCRSu6pSxdLKEELbpGv31m0RmuTYhrCAzWzSNFT57ZmdkEjrPmAu5xyfx4Z0U0I2m8BLOmSGpTOxXxMhd3Pd73YnLnEd5ZG@c3JSe@WiMk6H2LZJBf2Lc1f1J55TX12cty9Pr5y63Q5@ObXZoOzgxGxTV5cXbUd9OD177603VcNxty9mv5Yy41XSsSDpxNY7FVt2zPt9iC3Lndj6WHrZR2Ir5tfGMrGYx9xyme2tWwXOeMd@bR1VHQtPCbXc1hHAbrS9rTwTfH4MyA8Gx427U7brPoSnEhFEdQodKiQmmJrXPsQ4zZEKfRSGTcgoTCmunwOO5YGA5UAG9MBjea4lIXN6AFImC1yJNF@Vs4yoJvlWbcKlFKmPi2HGB4AW9Z1mQhtIQMcwCEZJs9mkJC6KjKdQLuq6SQnKIBV5si9Tupq/gEhgmmMyhz@LkaxqF34/0JRBsYLnaNmDEXx8GIzv4fYxmoRwEw3hy8N3H0H08@kRPgVPcDf6/AO@Rt96Df3/WryrXexrha7FWs@0O5ViySERL9ovSgXimUmoZgxyXK@AirR3uDurfAkoQ76@e0jmPtUlyB9GBoXCYZT7N/obaV/1YHa3hOKWr7bO@ODcw01o5mBbsqsaRtf7H8cqTS@zcruSOTOIkuljaoQRcq2UrNS@QQiNwBrxxgGamfnfqmtzjfXmLw "C (gcc) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ØAi
Çị¥¹Ç?€
```
[Try it online!](https://tio.run/##ASkA1v9qZWxsef//w5hBaQrDh@G7i8KlwrnDhz/igqz///9hYnJBY0FkQUJDQQ "Jelly – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 7 bytes
Fork of [Dennis' brilliant Jelly answer](https://codegolf.stackexchange.com/a/166573/48934)
```
XQr1G@G
```
[All testcases.](https://pyth.herokuapp.com/?code=XQr1G%40G&test_suite=1&test_suite_input=%22abcd%22%0A%22abrAcAdABCA%22%0A%22endlAsEBAEE%22%0A%22helCo+wDrCd%21%22%0A%22progBamFinD+AuzJles+%26+cCdL+DCKf%22%0A%22sphinx+of+black+quKrtz%2C+jOdge+my+vGw.+K+NODLM+IPGZE+HGF+SOWBA+GYVP+QCV+JKRX+TGU.%22%0A%22petBr+AiABD+AEckBd+a+ABFG+of+AEFGlBH+ABAABDs.+hJw+mIny+AEFGLBH+ABAABDM+HEH+ABCBD+AEABD+AEFG%3F%22&debug=0)
]