title: Print a shuffled deck of cards

text:
# Question
Title: Print a shuffled deck of cards
## Input

None

## Output

52 cards. No duplicates. Cards are represented as their unicode characters, e.g. .

The Unicode codepoints follow the following format:

* The first three digits are `1F0`.
* The next digit is `A`, `B`, `C`, or `D` for spades, hearts, diamonds, and clubs respectively.
* The next digit is `1` through `C` and `E` for the various numbers/face cards. `1` is ace, `2`-`A` are the number cards, and `B`, `D`, and `E` are the jack, queen, and king respectively. (`C` is the knight, which isn't in most decks.)

**Example output:**

## Rules:

* This is . Shortest answer wins.
* Forbidden loopholes are forbidden.
* Your deck must be actually randomized. If run 20 times, 20 random (and most likely unique) outputs must be generated.

## Note

If you only see boxes, install the DejaVu fonts.

# Answer
> 9 votes
# Jelly,  ~~25 23~~  21 bytes

```
62R%⁴g180<11T+“¢¬⁷’ẊỌ

```

A niladic link returning a list of characters, or a full program that prints the shuffled deck.

**Try it online!**

### How?

```
62R%⁴g180<11T+“¢¬⁷’ẊỌ - Main link: no arguments
62                    - literal 62
  R                   - range(62) -> [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31, 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47, 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62]
    ⁴                 - literal 16
   %                  - modulo    -> [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,  0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,  0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,  0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14]
      180             - literal 180
     g                - G.C.D.    -> [1,2,3,4,5,6,1,4,9,10, 1,12, 1, 2,15,180, 1, 2, 3, 4, 5, 6, 1, 4, 9,10, 1,12, 1, 2,15,180, 1, 2, 3, 4, 5, 6, 1, 4, 9,10, 1,12, 1, 2,15,180, 1, 2, 3, 4, 5, 6, 1, 4, 9,10, 1,12, 1, 2]
          11          - literal 11
         <            - less than?-> [1,1,1,1,1,1,1,1,1, 1, 1, 0, 1, 1, 0,  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0,  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0,  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1]
            T         - truthy    -> [1,2,3,4,5,6,7,8,9,10,11,   13,14,       17,18,19,20,21,22,23,24,25,26,27,   29,30,       33,34,35,36,37,38,39,40,41,42,43,   45,46,       49,50,51,52,53,54,55,56,57,58,59,   61,62]
              “¢¬⁷’   - base 250 number 127136
             +        - addition (vectorises) -> card character ordinals
                   Ẋ  - shuffle the list
                    Ọ - convert to characters
                      - full program has an implicit print

```

# Answer
> 8 votes
# JavaScript (ES6), ~~107~~ ~~106~~ 108 bytes

```
a=[]
for(S of'ABCD')for(N of'123456789ABDE')a.splice(Math.random()*-~a.length,0,eval(`'\\u\{1F0${S+N}}'`))
a

```

```
a=[]
for(S of'ABCD')for(N of'123456789ABDE')a.splice(Math.random()*-~a.length,0,eval(`'\\u\{1F0${S+N}}'`))
a

o.innerHTML = a.join``
```

```
<div id=o style="font-size:80px"></div>
```

<sub>-1 byte thanks to @nderscore</sub>

---

# JavaScript (ES6), ~~120~~ ~~119~~ 121 bytes

Previous version.

```
a=[],[...'ABCD'].map(S=>[...'123456789ABCE'].map(N=>a.splice(Math.random()*-~a.length|0,0,eval("'\\u\{1F0"+S+N+"}'")))),a

```

# Answer
> 7 votes
# Python 3,  ~~106~~  94 bytes

-5 bytes thanks to musicman523 (1. use `sample(...,52)` as an inline equivalent to `shuffle` \[thanks to totallyhuman\]; 2. use `~v&2` instead of `v%4<2`; plus a further 1 byte as a consequence as a space may be removed)

```
from random import*
print(*sample([chr(v+127137)for v in range(63)if~v&2or~v%16>4],52),sep='')

```

**Try it online!**

# Answer
> 6 votes
# Bash + coreutils, 56 bytes

```
printf %b\\n \\U1F0{A..D}{{1..9},A,B,D,E}|shuf|tr -d \\n

```

We use `printf` to write each card on its own line, shuffle the lines, then concatenate all the lines by removing the newline characters.

Note that although the coreutils `printf` command requires exactly 8 hexadecimal digits after `\U`, the Bash built-in `printf` lets us omit leading zeros.

# Answer
> 6 votes
# 05AB1E, ~~22~~ 21 bytes

Saved 1 byte thanks to *carusocomputing*.

```
…1F0A4£14L13KhJâ«Hç.r

```

Try it online!

**Explanation**

```
…1F0                    # push the string "1F0"
    A4£                 # push the string "abcd"
       14L              # push range [1 ... 14]
          13K           # remove 13
             h          # convert to hexadecimal
              J         # join to string "123456789ABCE"
               â        # cartesian product
                «       # prepend the string to each char in the list
                 H      # convert to decimal
                  ç     # get the chars with those code points
                   .r   # randomize

```

# Answer
> 3 votes
# Python 3, 107 bytes

Saved 6 bytes thanks to @totallyhuman and 3 thanks to @CCB60!

```
from random import*
print(*sample([chr(int('1F0'+a+b,16))for a in'ABCD'for b in'123456789ABDE'],52),sep='')

```

Try it online!

# Answer
> 3 votes
# Python 3, 112 bytes

```
from random import*
*a,=map(chr,range(127136,127200))
del a[::16],a[::-15],a[11::14]
shuffle(a)
print(*a,sep='')

```

Try it online!

# Answer
> 3 votes
# Charcoal, 50 bytes

```
Ａ¹²⁷¹³⁶χＡ⪫Ｅ…χ⁺⁶⁴χ℅ιωσＷσ«Ａ‽σχＡ⪫⪪σχωσ¿﹪﹪﹪℅χ¹⁶¦¹⁵¦¹³χ

```

Try it online! Link is to verbose version of code. Creates the string of all the 64 characters in the block but filters invalid cards out as they are randomly selected. (Speaking of which, random selection without replacement from a string is only 11 bytes, compared to 17 for an array.)

Edit: Subtraction from an array and other Charcoal improvements have cut down the size to 41 bytes: Try it online!

# Answer
> 3 votes
# PHP\>=7, 102 bytes

```
for(;$i++<64;)in_array(($c=127136+$i)%16,[0,12,15])?:$q[]=IntlChar::chr($c);shuffle($q);echo join($q);

```

No Online Interpreter available for the IntlChar::chr method

# PHP, 112 bytes

```
for(;$n++<4;shuffle($r))for($i=0;$i++<14;)$i==12?:$r[]=pack("c*",240,159,131-($n>2),$n*16+112+$i);echo join($r);

```

Try it online!

# PHP, 116 bytes

```
for(;$c=ab89[$n++];shuffle($r))for($i=0;$i++<14;)$i==12?:$r[]=hex2bin(f09f8.(2+($n>2)).$c.dechex($i));echo join($r);

```

Try it online!

# PHP, 121 Bytes

```
for(;$c=ABCD[$n++];shuffle($r))for($i=0;$i++<14;)$i==12?:$r[]=json_decode('"\ud83c\udc'.$c.dechex($i).'"');echo join($r);

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog), ~~40~~ 38 bytes

### Jonathan Allan's method

```
⎕UCS((11>180∨16|⍳62)/127136+⍳62)[?⍨52]

```

`(``)` on the following array

`⍳62` the first 62 integers

`127136+` add 127136 to that

`(``)/` filter that with the Boolean

`⍳62` first 62 integers

`16|` modulus 16

`180∨` GCD of 180 and that

`11>` whether 11 is greater than those

`[``]` select the following elements

`?⍨52` shuffle the first 52 integers (pick 52 random integers out of a bag of the first 52 integers)

`⎕UCS` convert to corresponding symbols in the **U**nicode **C**haracter **S**et

---

### Version 16.0 (currently in beta) solution (33 characters)

```
⎕UCS(127136+⍸11>180∨16|⍳62)[?⍨52]

```

`(``)` on the following array

`⍳62` first 62 integers

`16|` modulus 16

`180∨` GCD of 180 and that

`11>` whether 11 is greater than those

indices where True

`127136+` add 127136 to that

`[``]` select the following elements

`?⍨52` shuffle the first 52 integers (pick 52 random integers out of a bag of the first 52 integers)

`⎕UCS` convert to corresponding symbols in the **U**nicode **C**haracter **S**et

---

### Old solution

```
⎕UCS(126976+16⊥¨,(9+⍳4)∘.,12~⍨⍳14)[?⍨52]

```

`(``)` on the following array

`⍳14` the first 14 integers

`12~⍨` except 12

`(``)∘.,` Cartesianly concatenated to

`⍳4` the first 4 integers

`9+` added to 9

`,` ravel (flatten) that

`16⊥¨` evaluate each in base 16

`126976+` add 126976 to that

`[``]` select the following elements

`?⍨52` shuffle the first 52 integers (pick 52 random integers out of a bag of the first 52 integers)

`⎕UCS` convert to corresponding symbols in the **U**nicode **C**haracter **S**et

# Answer
> 3 votes
# Vyxal, 23 bytes

```
kA4Ẏk^ḢṪ\DoẊ`1F0`vpHCÞ℅

```

Try it Online!

Port of 05AB1E.

## How?

```
kA4Ẏk^ḢṪ\DoẊ`1F0`vpHCÞ℅
kA4Ẏ                    # Get the first 4 letters of the uppercase alphabet
    k^                  # Push string "0123456789ABCDEF"
      ḢṪ                # Remove head and tail: "123456789ABCDE"
        \Do             # Remove the D: "123456789ABCE"
           Ẋ            # Cartesian product of strings: ["A1", "A2", "A3", "A4", ..., "DC", "DE"]
            `1F0`       # Push string "1FO"
                 vp     # Prepend to each: ["1FOA1", "1FOA2", ..., "1FODE"]
                   H    # Convert each from hexadecimal: [127137, 127137, ..., 127198]
                    C   # Convert each to their unicode representation: ["", "", ... ""]
                     Þ℅ # Randomly shuffle

```

Port of Jelly is same byte count:

# Vyxal, 23 bytes

```
62ɾ16%180ġ11<T»ƛǔḭ»+CÞ℅

```

Try it Online!

## How?

```
62ɾ16%180ġ11<T»ƛǔḭ»+CÞ℅
62ɾ                     # Push range [1, 2, ..., 62]
   16%                  # Modulo each by 16
      180ġ              # GCD each with 180: [1, 2, 3, 4, 5, 6, 1, 4, 9, 10, ..., 12, 1, 2]
          11<T          # Indices where item is less than 11: [0, 1, 2, 3, ... 13, 16, 17, ..., 26, ...]
              »ƛǔḭ»     # Push compressed integer 127137
                   +    # Add to each (vectorizes)
                    C   # Convert each to their unicode representation
                     Þ℅ # Randomly shuffle

```

For both solutions, add `s` flag if it needs to be a string instead of a list.

# Answer
> 2 votes
# Alice, 34 bytes

```
'?rwd.n$@U,!6?44*%a7+-F$K?'+OK

```

Try it online!

### Explanation

```
'?r                               push numbers 0-63 onto stack
   w                              store return address (start main loop)
    d                             get stack depth
     .n$@                         if zero, terminate
         U                        random number in [0, depth)
          ,                       move corresponding stack element to top
           !                      store on tape
             ?                    copy back from tape
              44*%                mod 16
                  a7+-            subtract 17
            6         F           does the result divide 6?
                       $K         if so, return to start of main loop
                         ?        copy card number from tape again
                          '+     add 0x1F0A1
                             O    output
                              K   return to start of main loop

```

# Answer
> 2 votes
## \>\<\>, ~~49~~ ~~50~~ 49 bytes

```
""v
=?v>:1+}:88+%:c-:3-**?!~{l4d*
{>x
o^>l?!;

```

Try it online!

*(+1 byte to make the randomness better)*

I'm interpreting "random" to mean "every possible outcome has a non-zero probability". This isn't a uniform distribution.

There are two stages to this code. First, the fish puts all the cards on the stack, using the first two lines. Starting with the ace of spades, the fish duplicates and increments it, then checks if the previous card's hex code ends in 0, C or F by multiplying together *x* (*x*-12) (*x*-15), where *x* is the charcode mod 16, and checking if that's zero. If it is, it deletes the offending card from the stack. It repeats until the stack has 52 cards, then swims into stage 2:

```
  v
{>x
o^>l?!;

```

This bit of code shuffles and prints the stack. The `x` sets the fish's direction randomly:

* If the fish swims up, it hits the `v` and goes back to the `x` without doing anything. The left direction is similar.
* If the fish swims right, it wraps and hits the `{`, rotating the entire stack to the left, then returns to the `x`.
* If the fish swims down, it prints the card at the front of the stack then returns to the `x`.

It's clear that every possible order of the cards can be produced: at any point in stage 2, every card that hasn't been printed yet can be printed next if the fish swims rightwards enough times. This shuffling technique usually doesn't move cards very far apart if they were already near each other, but then again, neither does shuffling by hand.

# Answer
> 2 votes
# R, 61 bytes

```
cat(intToUtf8(sample(c(127137:127198)[-c(12,28,44,47,60)])))

```

Randomly sample the vector of integer representations of the cards unicode values (which can be obtained from `utf8ToInt()` fucntion) and remove the unwanted knight/joker cards.

# Answer
> 1 votes
## C# (146 141 bytes)

```
using System.Linq;()=>Enumerable.Range(0,52).OrderBy(i=>System.Guid.NewGuid()).Aggregate("",(s,i)=>s+"\uD83C"+(char)(56481+i+i/13*3+i%13/12))

```

Online demo

This uses extremely bad style in shuffling with `Guid.NewGuid()`, but it's code-golf. It then builds the surrogate pairs manually.

# Answer
> 0 votes
# Perl 5, 75 bytes

```
@c=map{7946+$_%4+$_/64}4..51,56..59;print chr(16*splice@c,@c*rand,1)while@c

```

Note that this uses the code points for queens as given in the question (i.e. last digit `C`). For the actual code points (last digit `D`), replace `51,56` with `47,52`.

# Answer
> 0 votes
# Java 8, 216 bytes

```
import java.util.*;()->{List<Long>l=new ArrayList();for(long i=52;i-->0;l.add(i));Collections.shuffle(l);for(Long x:l)System.out.print((char)(x.parseLong("1F0"+(char)(65+x/12)+((x%=4)>9?(char)(x>2?69:65+x):x),16)));}

```

**Explanation:**

Try it here.

NOTE: Untested because even though I've installed the linked font, I still see boxes. Probably have to restart my PC or something..

```
import java.util.*;               // Required import for List, ArrayList and Collections
()->{                             // Method without parameter nor return-type
  List<Long>l=new ArrayList();    //  List
  for(long i=52;i-->0;l.add(i));  //  Fill the list with 1 through 52
  Collections.shuffle(l);         //  Randomly shuffle the list
  for(Long x:l)                   //  Loop over the shuffled list
    System.out.print(             //   Print the following character:
      (char)(x.parseLong(         //    Convert the following String to a character:
        "1F0"+                    //     The literal String "1F0" +
         (char)(65+x/12)+         //     either A, B, C or D by using x/12, adding 65,
                                  //      and casting it to a char +
         ((x%=4)>9?               //     If the current item mod-4 is 10 or higher:
            (char)(x>2?69:65+x)   //      Convert it to A, B, C or E
           :                      //     Else (1 through 9):
            x)                    //      Simply add this digit
      ,16))
    );
}                                 // End of method

```

# Answer
> 0 votes
# Japt, ~~51~~ ~~41~~ ~~39~~ 22 bytes

With some inspiration from Jonathan's Jelly solution.

```
#?ö¬k@B§XuG y#´Ãmd##

```

Try it (or view output with increased `font-size`)

---

## Explanation

```
#?                         :63
  ö¬                       :Random permutation of range [0,63)
    k                      :Remove elements that return true
     @                     :When passed through this function
      B                    :  11
       §                   :  Less than or equal to
        X                  :  Current element
         u                 :  Modulo
          G                :  16
            y              :  GCD
             #´            :  180
               Ã           :End function
                m          :Map
                  ##       :  Add 127136
                 d         :  Get character at that codepoint

```

# Answer
> 0 votes
# Dyalog APL, 35 bytes

```
⎕ucs(∊127150+(16×⍳4)-⊂2~⍨⍳14)[?⍨52]

```

based on Adám's answer

uses `⎕io←0`

---
Tags: code-golf, string, random, unicode
---


# Question
Title: Inject arbitrary code into a compiler (cops)
**This is the cops' challenge. To post a robber, go here.**

In this challenge, cops will invent a (likely simple) programming language, and write an interpreter, transpiler, or compiler that allows you to run it. Robbers will write a program in this language that manages to inject arbitrary code into the interpreter, transpiler, or compiler.

## Cops

Cops should design a language. This language should be "pure"; its programs can take input and/or produce output, but cannot affect files, make network requests, behave non-deterministically (based on something like randomness or the system time), or otherwise impact or be impacted by the outside world (within reason).

Cops must then implement this language, with one of:

* **An interpreter:** This will take the code and input as arguments/input, and produce the programs's output as output.
* **A transpiler:** This will take the code and input, and produce code in some other language which does the same task. When run using that language's interpreter/compiler with input, the correct output is produced.
* **A compiler:** Similar to a transpiler, but with machine code instead of another language.

There must be an intended "crack", or way to inject arbitrary code.

## Robbers

Robbers should find a way to do one of the following:

* Write a program that, when interpreted, transpiled, or compiled, can run arbitrary code as the interpreter/transpiler/compiler (e.g., if written in Python, you could run arbitrary Python, manipulate files, and so on)
* Write a program that, when transpiled or compiled, injects arbitrary code into the resulting program/machine code (e.g., if your transpiler converts the language to Node.js, you could inject arbitrary JS into the transpiler output)

## Cop Posts

Cops should include the interpreter/transpiler/compiler code, and some documentation for the language. For example:

> # Print1Lang
>
> ```
> function transpile(code) {
>     return code.replace(/^.+/g, "print(1)");
> }
>
> ```
>
> Print1Lang takes code as input, and returns a Python program that prints `1`.

Cops should be designed with some exploit in mind that allows injecting **any** code, in some language or situation that allows performing arbitrary computations and interacting with the computer's files, running shell commands, system calls, non-deterministic code, or anything like that. Simply printing a nondeterministic value does not count, as it does not give you unrestricted access to the environment the code or transpilation/compilation output is being run or transpiled/compiled in.

For an interpreter, this is likely going to be running code in the language the interpreter is written in. For a transpiler or compiler, the vulnerability can occur at either compile time or run time, and for the latter, the vulnerability would most likely consist of being able to inject arbitrary code or machine code into the compiled code.

## Other

All the boring stuff. Nothing malicious, no crypto stuff.

Winner for cops is the user with the most safe cops, winner for robbers is the user who cracks the most cops.

**Note:**

This challenge is intended for languages to be designed for the challenge specifically, but using existing languages is allowed. In this case, you can define a subset of the language such that it follows the rules about non-deterministic commands.

# Answer
# Vyxal 2.7 (safe)

Yes, I found another another one.

No, I'm not JoKing.

As the rules call for deterministic languages, commands involving randomness are not allowed. Also, the `EĖ†` commands are not allowed, since those are designed to execute arbitrary code.

Code and documentation can be found at the repo.

Solution:

> If you look at the recent releases and commits in the GitHub repo, you may notice that we don't like SymPy anymore. There's a reason for that. It turns out that it doesn't play nicely with strings. More specifically, a lot of the time, when you pass a string to it, you can make it do unintended stuff. For example, if you do `sympy.nsimplify("f'{print(69)}'")`, it will evaluate the f-string contained within the string, resulting in it printing 69. The ACE was originally found using `øḋ`, but there were actually a lot of commands that used it. This has now been fixed.
> 8 votes

# Answer
# Exceptionally (cracked by emanresu A)

Exceptionally is a toy language I invented for this challenge. It is inspired by, implemented in, and transpiled to Whython (pxeger's modified version of Python 3 with an added exception-handling operator).

## The language

A program in Exceptionally contains of a series of *lines*, each consisting of a *command* (or multiple commands connected with the Rescue operator; see below under Exceptions). The lines are executed one by one. When the instruction pointer reaches the end of the program, it wraps around to the beginning. The program thus forms an infinite loop; the only way to break out of the loop is by causing an error. Every Exceptionally program either does not terminate or terminates with an exception.

Each command consists of a symbol, optionally followed by an *argument*. The argument can be an integer literal, a string literal, or a variable name.

Most commands modify the value of a *register*, initially set to 0. A command without an explicit argument uses the value of the register as its argument. For example, the command `*3` multiplies the register by 3, while the command `*` multiplies the register by itself.

### Commands

Here is the full list of commands:

* `{`: Load (copy value into register)
* `}`: Store (copy register into variable)
* `+`: Add (value to register)
* `-`: Subtract (value from register)
* `*`: Multiply (register by value)
* `/`: Divide (register by value--floating point division)
* `%`: Mod (register by value)
* `^`: Pow (take register to the power of value--result may be floating point)
* `:`: Item (at given index in register)
* `[`: Slice From (given index to end of register)
* `]`: Slice To (given index from beginning of register)
* `@`: Find (value's index in register)
* `#`: Count (occurrences of value in register)
* `|`: Split (register by value)
* `$`: Join (register on value)
* `<`: Print (value)
* `>`: Input (line of stdin into variable)
* `=`: Equal (assert that register is equal to value)
* `!`: Skip (skip execution of the given number of lines)
* `\`: Func (apply the given function to the register)

The Skip command `!` provides simple control flow. Think of it as a goto, relative to the current line.

The Func command `\` takes a string as its argument and does one of several things:

* `\"int"`: Cast the register to an integer
* `\"str"`: Cast the register to a string
* `\"ord"`: Convert a single-character register value to its character code
* `\"chr"`: Convert an integer register value to the corresponding character
* `\"elems"`: Convert a string or list register value to a list of its elements
* `\"len"`: Get the length of the register
* `\"sum"`: Sum/concatenate the register
* `\"range"`: Get the range from 0 to the register's value (exclusive)
* `\"wrap"`: Wrap the register's value in a singleton list
* `\"inv"`: Reverse the register's value, or negate it if it's a number

### Exceptions

Most commands are capable of triggering an exception in some way. For example, dividing by 0 will cause an exception, as will an out-of-bounds index, as will trying to add a string and a number. These exceptions are the only way to end the program, but they don't have to end the program. They can be caught using the Rescue operator `?`, borrowed from Whython.

A command may be followed by `?` and an additional command. If the first command succeeds, execution continues to the next line. If the first command causes an exception, the second command is executed instead. A line can contain any number of commands chained with `?`. If the last command is reached and it also causes an exception, then the program halts.

For example, consider the line `/x ? <"Division by zero"`. The command `/x` attempts to divide the register by the value of `x`. If `x` is zero, this operation will trigger an exception, in which case the second command `<"Division by zero"` is executed, printing an error message (and leaving the value of the register unchanged).

The `?` operator is the only conditional construct in Exceptionally. Different commands can be used to trigger exceptions under specific circumstances, and `!` can be used to jump to different points in the program depending on the results. For example, in `=5 ? !4`, the `=` command raises an exception if the register does not equal 5; in this case the `!` command is executed, skipping the next four lines. Or again, the following two lines:

```
-5
/ ? !4

```

will skip four lines if the register equals 5: `-5` subtracts 5 from the register, and `/` divides it by itself, resulting in 1 if it is nonzero or an exception if it is zero.

### Miscellaneous

Exceptionally has comments that start with `'` and go until the next newline.

Whitespace is generally unimportant in Exceptionally. This program to square an input number and halt:

```
>
\"int"
*
<
/0

```

could also be written as `>\"int"*</0`. Newlines that end comments, and whitespace in strings, are the only significant whitespace.

## The transpiler

Here is the Exceptionally transpiler, written in Whython:

```
import re
import sys

COMMANDS = {
    "{": "reg := %s",               # Load
    "}": "%s := reg",               # Store
    "+": "reg := reg + %s",         # Add
    "-": "reg := reg - %s",         # Sub
    "*": "reg := reg * %s",         # Mul
    "/": "reg := reg / %s",         # Div
    "%": "reg := reg %% %s",        # Mod
    "^": "reg := reg ** %s",        # Pow
    ":": "reg := reg[%s]",          # Item
    "[": "reg := reg[%s:]",         # SliceFrom
    "]": "reg := reg[:%s]",         # SliceTo
    "@": "reg := reg.index(%s)",    # Find
    "#": "reg := reg.count(%s)",    # Count
    "|": "reg := reg.split(%s)",    # Split
    "$": "reg := %s.join(reg)",     # Join
    "<": "print(%s)",               # Print
    ">": "%s := input()",           # Input
    "=": "1 / (reg == %s)",         # Equal
    "!": "ip := ip + %s",           # Skip
    "\\": "reg := FUNCS[%s](reg)",  # Func
    }

PROGRAM_TEMPLATE = """program = %s
FUNCS = {
"int": int,
"str": str,
"chr": chr,
"ord": ord,
"elems": list,
"len": len,
"sum": lambda x: sum(x) ? sum(x, []) ? "".join(x),
"range": lambda x: list(range(x)),
"wrap": lambda x: [x],
"inv": lambda x: x[::-1] ? -x,
}
ip = 0
reg = 0
while True:
    eval(program[ip])
    ip = (ip + 1) %% len(program)"""

def transpile(code):
    transpiled_lines = []
    code = code.lstrip()
    if code[0] == "?":
        raise SyntaxError(f"Program cannot begin with {code[0]}")
    while code:
        if m := re.match("'.*", code):
            code = code[m.end():].lstrip()
            continue
        if code[0] == "?":
            # Continuing a previous line
            operator = code[0]
            transpiled_lines[-1] += f" {operator} "
            code = code[1:].lstrip()
            if not code:
                raise SyntaxError(f"Program cannot end with {operator}")
        else:
            # Start of a new line
            transpiled_lines.append("")
        if code[0] in COMMANDS:
            command = code[0]
            code = code[1:].lstrip()
            # Parse the command's argument
            if m := re.match(r"\w+", code):
                # Name or integer literal
                argument = m.group()
                argument = (argument.lstrip("0") if int(argument) else "0") ? f"'{argument}'"
                code = code[m.end():].lstrip()
            elif m := re.match(r'"[^"]*"', code):
                # String literal
                argument = repr(m.group())
                code = code[m.end():].lstrip()
            else:
                # No argument, defaults to register
                argument = "'reg'"
            argument = eval(argument) ? f"eval({argument})"
            translation = "(" + COMMANDS[command] % argument + ")"
            transpiled_lines[-1] += translation
        else:
            raise SyntaxError(f"Expected command, found: {code[0]}")
    return PROGRAM_TEMPLATE % transpiled_lines

```

### Attempt This Online!

You can run the transpiler for yourself at Attempt This Online. Put your Exceptionally code in the Input box and click Execute; the program will output the transpiled Whython code.

Here is a version that immediately executes the transpiled code: Attempt This Online.

## Example program

Here is a commented program that outputs the orbit of an input number under the Collatz function. (This is the program used in the second ATO link above.)

```
' Read initial number from stdin
>
' Convert to an integer
\"int"
' Store a copy in n
}n
' Output
<
' Minus 1
-1
' Divide by itself; if n is 1, (n-1)/(n-1) is division by zero and the program halts
/
' Otherwise, keep going; load n back into the register
{n
' Mod 2
%2
' Is this equal to 0? If not, skip the next three lines
=0 ? !3
' Load n
{n
' Divide by 2
/2
' Skip the next three lines
!3
' Load n
{n
' Multiply by 3
*3
' Add 1
+1
' Skip the next line (that is, skip the first line when the program loops)
!1

```
> 8 votes

# Answer
# Exceptionally v0.3 (safe)

Exceptionally is a toy language I invented for this challenge. It is inspired by, implemented in, and transpiled to Whython (pxeger's modified version of Python 3 with an added exception-handling operator).

This is the third (and ~~hopefully~~ final) version of the language, but the only difference is in the implementation; the language spec is the same as before. See the original post for a full description.

## New transpiler

Here is the Exceptionally v0.3 transpiler, written in Whython:

```
import re
import sys

COMMANDS = {
    "{": "reg := %s",               # Load
    "}": "%s := reg",               # Store
    "+": "reg := reg + %s",         # Add
    "-": "reg := reg - %s",         # Sub
    "*": "reg := reg * %s",         # Mul
    "/": "reg := reg / %s",         # Div
    "%": "reg := reg %% %s",        # Mod
    "^": "reg := reg ** %s",        # Pow
    ":": "reg := reg[%s]",          # Item
    "[": "reg := reg[%s:]",         # SliceFrom
    "]": "reg := reg[:%s]",         # SliceTo
    "@": "reg := reg.index(%s)",    # Find
    "#": "reg := reg.count(%s)",    # Count
    "|": "reg := reg.split(%s)",    # Split
    "$": "reg := %s.join(reg)",     # Join
    "<": "print(%s)",               # Print
    ">": "%s := input()",           # Input
    "=": "1 / (reg == %s)",         # Equal
    "!": "ip := ip + %s",           # Skip
    "\\": "reg := program.FUNCS[%s](reg)",  # Func
    }

PROGRAM_TEMPLATE = """class Program: pass
program = Program()
program.LINES = %s
program.FUNCS = {
"int": int,
"str": str,
"chr": chr,
"ord": ord,
"elems": list,
"len": len,
"sum": lambda x: sum(x) ? sum(x, []) ? "".join(x),
"range": lambda x: list(range(x)),
"wrap": lambda x: [x],
"inv": lambda x: x[::-1] ? -x,
}
ip = 0
reg = 0
while True:
    eval(program.LINES[ip])
    ip = (ip + 1) %% len(program.LINES)"""

BUILTIN_NAMES = dir(__builtins__)

def transpile(code):
    transpiled_lines = []
    code = code.lstrip()
    if code[0] == "?":
        raise SyntaxError(f"Program cannot begin with {code[0]}")
    while code:
        if m := re.match("'.*", code):
            code = code[m.end():].lstrip()
            continue
        if code[0] == "?":
            # Continuing a previous line
            operator = code[0]
            transpiled_lines[-1] += f" {operator} "
            code = code[1:].lstrip()
            if not code:
                raise SyntaxError(f"Program cannot end with {operator}")
        else:
            # Start of a new line
            transpiled_lines.append("")
        if code[0] in COMMANDS:
            command = code[0]
            code = code[1:].lstrip()
            # Parse the command's argument
            if m := re.match(r"\w+", code):
                # Name or integer literal
                argument = m.group()
                if argument in BUILTIN_NAMES and command == "}":
                    raise SyntaxError(f"Cannot overwrite built-in name {argument}")
                argument = (argument.lstrip("0") if int(argument) else "0") ? f"'{argument}'"
                code = code[m.end():].lstrip()
            elif m := re.match(r'"[^"\\]*"', code):
                # String literal
                argument = repr(m.group())
                code = code[m.end():].lstrip()
            else:
                # No argument, defaults to register
                argument = "'reg'"
            argument = eval(argument) ? f"eval({argument})"
            translation = "(" + COMMANDS[command] % argument + ")"
            transpiled_lines[-1] += translation
        else:
            raise SyntaxError(f"Expected command, found: {code[0]}")
    return PROGRAM_TEMPLATE % transpiled_lines

```

### Changelog

The second version was cracked thanks to unescaped backslashes in string literals. To close this loophole, backslashes are no longer allowed in string literals. A string can contain any character that is not `\` or `"`.

I've also closed another unintended loophole: previously, you could overwrite `range` with `exec` and then do `\"range"` to execute an arbitrary string. Now you can no longer use a Whython builtin as the argument for the `}` command.

### Attempt This Online!

You can run the transpiler for yourself at Attempt This Online. Put your Exceptionally code in the Input box and click Execute; the program will output the transpiled Whython code.

Here is a version that immediately executes the transpiled code: Attempt This Online.

### Solution

There are two suspiciously convoluted lines in the transpiler. First,

> `argument = (argument.lstrip("0") if int(argument) else "0") ? f"'{argument}'"`

which does this:

> Try to cast `argument` to an integer. If that works and the integer is nonzero, remove any leading 0s from `argument`; if the integer is zero, use `"0"`; if `argument` cannot be converted to an integer, wrap it in single quotes. (Note also that literal strings are `repr`'d, and the register as an argument is `'reg'` rather than just `reg`.)

Then,

> `argument = eval(argument) ? f"eval({argument})"`

> If the argument was a name, it should be wrapped in quotes at this point, so `eval` gives just the name as a string. If the argument was a number, `eval` gives the number as a Python int. If the argument was a string, `eval` reverses the `repr` we did earlier. If `eval` fails (???), then we substitute `argument` into a string that has the effect of `eval`'ing it at post-transpilation runtime (???).

What kind of input will trigger this case?

> We need an argument matching the regex `\w+` that does not error when you pass it to `int`, but does error when you strip leading zeros and pass it to `eval`. Solution: Python 3 (and therefore Whython) allows underscores as digit-group separators in numeric literals. Thus, `0_1` is a legal int literal (with a value of 1); but when we strip the leading zero, `_1` is no longer a legal int literal, but rather a name. When we try to `eval` it, it errors because `_1` is not defined. So instead of `1` or `_1` being placed in the transpiled code, we get `eval(_1)`.

So the exploit is:

> If we set the variable `_1` to some string value, any reference to `0_1` will cause it to be `eval`'d. Here's a simple example:
>
> ```
> {"exec('import os; print(os.getcwd()); exit(0)')"
> }_1
> <0_1
> ```

Transpiled, this becomes (in essence):

> ```
> reg := "exec('import os; print(os.getcwd()); exit(0)')"
> _1 := reg
> print(eval(_1))
> ```
> Attempt This Online!
> 5 votes

# Answer
# Javastack, Cracked by tsh

Not much of a language but it should be enough. Crappy programming for the win!

Code + docs is in the repo.

Since this must be deterministic, random builtins are banned.

As tsh pointed out, there's a small chance loop variables may coincide, but that chance is so small that you may simply consider it to not happen.
> 4 votes

# Answer
# Vyxal, since v2.6 (safe)

Why does Vyxal have so many ACEs?

Commands with randomness aren’t allowed, and neither are `EĖ†`. Info is in the repo.
> 4 votes

# Answer
# Jyxal, Cracked by redwolf

Jyxal is a half-baked JS implementation of Vyxal. While it has most core features (loops, functions, lambdas etc), it has almost no elements, but it's still possible to ACE it.

Vyxal docs should apply for most of it, but for some parts you may have to read the code.

Intended solution:

```
@=1,console.log("ACE"),process.exit(),'+',d|;

```

Quite similar to Redwolf's, this gets compiled into

```
var arity = '=1,console.log("ACE"),process.exit(),d';FUNC_=1,console.log("ACE"),process.exit(),d = <meaningless junk>

```

Just like this Vyxal ACE, this exploits how arbitrary code can be inserted into functions.
> 3 votes

# Answer
# Exceptionally v0.2 (cracked by emanresu A)

Exceptionally is a toy language I invented for this challenge. It is inspired by, implemented in, and transpiled to Whython (pxeger's modified version of Python 3 with an added exception-handling operator).

This is the second version of the language, but the only difference is in the implementation; the language spec is the same as before. See the original post for a full description.

## New transpiler

Here is the Exceptionally v0.2 transpiler, written in Whython:

```
import re
import sys

COMMANDS = {
    "{": "reg := %s",               # Load
    "}": "%s := reg",               # Store
    "+": "reg := reg + %s",         # Add
    "-": "reg := reg - %s",         # Sub
    "*": "reg := reg * %s",         # Mul
    "/": "reg := reg / %s",         # Div
    "%": "reg := reg %% %s",        # Mod
    "^": "reg := reg ** %s",        # Pow
    ":": "reg := reg[%s]",          # Item
    "[": "reg := reg[%s:]",         # SliceFrom
    "]": "reg := reg[:%s]",         # SliceTo
    "@": "reg := reg.index(%s)",    # Find
    "#": "reg := reg.count(%s)",    # Count
    "|": "reg := reg.split(%s)",    # Split
    "$": "reg := %s.join(reg)",     # Join
    "<": "print(%s)",               # Print
    ">": "%s := input()",           # Input
    "=": "1 / (reg == %s)",         # Equal
    "!": "ip := ip + %s",           # Skip
    "\\": "reg := program.FUNCS[%s](reg)",  # Func
    }

PROGRAM_TEMPLATE = """class Program: pass
program = Program()
program.LINES = %s
program.FUNCS = {
"int": int,
"str": str,
"chr": chr,
"ord": ord,
"elems": list,
"len": len,
"sum": lambda x: sum(x) ? sum(x, []) ? "".join(x),
"range": lambda x: list(range(x)),
"wrap": lambda x: [x],
"inv": lambda x: x[::-1] ? -x,
}
ip = 0
reg = 0
while True:
    eval(program.LINES[ip])
    ip = (ip + 1) %% len(program.LINES)"""

def transpile(code):
    transpiled_lines = []
    code = code.lstrip()
    if code[0] == "?":
        raise SyntaxError(f"Program cannot begin with {code[0]}")
    while code:
        if m := re.match("'.*", code):
            code = code[m.end():].lstrip()
            continue
        if code[0] == "?":
            # Continuing a previous line
            operator = code[0]
            transpiled_lines[-1] += f" {operator} "
            code = code[1:].lstrip()
            if not code:
                raise SyntaxError(f"Program cannot end with {operator}")
        else:
            # Start of a new line
            transpiled_lines.append("")
        if code[0] in COMMANDS:
            command = code[0]
            code = code[1:].lstrip()
            # Parse the command's argument
            if m := re.match(r"\w+", code):
                # Name or integer literal
                argument = m.group()
                argument = (argument.lstrip("0") if int(argument) else "0") ? f"'{argument}'"
                code = code[m.end():].lstrip()
            elif m := re.match(r'"[^"]*"', code):
                # String literal
                argument = repr(m.group())
                code = code[m.end():].lstrip()
            else:
                # No argument, defaults to register
                argument = "'reg'"
            argument = eval(argument) ? f"eval({argument})"
            translation = "(" + COMMANDS[command] % argument + ")"
            transpiled_lines[-1] += translation
        else:
            raise SyntaxError(f"Expected command, found: {code[0]}")
    return PROGRAM_TEMPLATE % transpiled_lines

```

### Changelog

The first version was cracked because too many parts of the interpreter were modifiable from within the code. To close this loophole, I've changed the `program` variable to `program.LINES` and the `FUNCS` variable to `program.FUNCS`. Since variable names in Exceptionally cannot contain dots, these changes should make the program contents hack-proof.

### Attempt This Online!

You can run the transpiler for yourself at Attempt This Online. Put your Exceptionally code in the Input box and click Execute; the program will output the transpiled Whython code.

Here is a version that immediately executes the transpiled code: Attempt This Online.
> 3 votes

# Answer
# Vyxal 2.10, cracked

Yep, another another another one.

Again, commands with randomness aren’t allowed, and neither are `EĖ†`. Info is in the repo.
> 3 votes

# Answer
# Vyxal 2.7.2 to 2.11.1 (safe, patched in v2.11.2)

Yet another ACE in Vyxal.

Commands with randomness aren’t allowed, and neither are `EĖ†`. Info is in the repo.

Explanation:

> The vulnerability is in `∆K` (Stationary Points) and `∆¢` (Local Maxima). These both use sympy directly on a string, meaning you can just inject an f-string, like this:
> ``f"{open('look, an ACE!', 'w').write('!')}"` ∆K`
> or:
> ``f"{open('look, an ACE!', 'w').write('!')}"` ∆¢`
> 2 votes

---
Tags: cops-and-robbers, interpreter, language-design, compiler
---


title: Generate a deck of cards

text:
# Question
Title: Generate a deck of cards
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
> 28 votes
# JavaScript (ES6), ~~62~~ 60 bytes

```
f=n=>n>51?'JJ':[('JQKA'[k=n>>2]||k-2)+'CDHS'[n&3],...f(-~n)]

```

Try it online!

# Answer
> 24 votes
## Bash ~~43~~ 34 bytes

```
d=({A,J,Q,K,{2..10}}{H,S,D,C} J J)

```

Try it online!

# Answer
> 14 votes
# brainfuck, ~~200~~ 197 bytes

```
+[[<+>->++<]>]+<++++<<+++[->+++>+++++>+>+<<<<]>+.<<.>>.--<<<[->>+++<<]>>+>[<<.>.-.+>.<<.<<[>>>+.>.<<.<+<-]>[-<+>>>+<<]>>.>.<<.>+++++++++.>.<<.>+.>.<<.>++++++.>.,++++[-<-------->]>[[-<+>]>]<<[<]>>>]

```

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
> 11 votes
# 05AB1E, ~~28~~ ~~27~~ ~~25~~ ~~24~~ 23 bytes

```
2TŸ.•-Ÿ•S«.•ôì•âJ„jjS«u

```

Try it online.

-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?*) to understand why `.•-Ÿ•` is `"ajqk"` and `.•ôì•` is `"cdhs"`.

# Answer
> 9 votes
# brainfuck, ~~550~~ 504 bytes

```
++++++++++[>+++>+++++>+++++++<<<-]>++>->[>+>+>+>+<<<<-]>----->++++.<<<<.>>>>.<<<<.>>>>>--->+++++++++++++<<<<<.-.+>>>>.<<<<<.>.-.+>>>>+.<<<<<.>.-.+>>>>++++.-----<<<<<.>.-.+>>>>>.<<<<<<.>>++++++++[-<+.>>>>.<<<<<.>.>>>>+.<<<<<.>.>>>>++++.-----<<<<<.>.>>>>>.<<<<<<.>>]>.>>.<<<<<.>>>>.>.<<<<<.>>>>+.>.<<<<<.>>>>++++++.>.<<<<<.>>>.>>+.<<<<<.>>>>.>.<<<<<.>>>>------.>.<<<<<.>>>>-.>.<<<<<.>>>.>>++++.<<<<<.>>>>.>.<<<<<.>>>>+.>.<<<<<.>>>>++++++.>.<<<<<.>>>.>>>.<<<<<<.>>>>.>>.<<<<<<.>>>>------.>>.<<<<<<.>>>>-.>>.

```

Try it online!

Old answer, also online!

# Answer
> 8 votes
# 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.

**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
> 7 votes
# APL (Dyalog Unicode), 29 bytes

*1 byte saved thanks to Probie by using `1+⍳9` instead of `1↓⍳10`*

```
'JJ',,'HCDS'∘.,⍨'AKJQ',⍕¨1+⍳9

```

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
> 7 votes
# Befunge-98 (FBBI), 75 bytes

```
j4d*1-2k:d%4+1g:'0-!#v_>,d/1g,' ,!#v_3
CHSDA234567890JQK@;1'< ^,;,k2"J J" <

```

Try it online!

## Program structure

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
> 7 votes
# , 65 bytes

```
c(outer(c('A',2:10,J<-'J','Q','K'),c('S','D','H','C'),paste),J,J)

```

Try it online!

-2 Bytes thanks to @Giuseppe and @JayCe suggestions

# Answer
> 6 votes
# Powershell, ~~63~~ ~~61~~ ~~59~~ 56 bytes

-3 bytes: thanks ConnorLSW

```
2..10+'AJQK'[0..3]|%{"$_`H";"$_`S";"$_`D";"$_`C"};,'J'*2

```

# Answer
> 6 votes
## Perl 5, 41 bytes

```
sub{J,J,map<"$_"{S,D,H,C}>,A,2..10,J,Q,K}

```

Try it online!

# Answer
> 5 votes
# Python 3, ~~67~~ 64 bytes

```
print(*[a+b for a in['10',*'A23456789JQK']for b in'CHSD'],*'JJ')

```

Try it online!

---

# Python 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!

Alt:

# Python 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
> 5 votes
# K (ngn/k), 30 bytes

```
"JJ",/("AKQJ",$2+!9),'/:"SHDC"

```

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
> 5 votes
# 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.

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
> 4 votes
# Japt, ~~32~~ ~~30~~ 26 bytes

```
'J²¬c"JQKA"¬c9õÄ)ï+"CHSD"q

```

Test it

```
'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
> 4 votes
## PHP, ~~108~~ ~~99~~ 97 Bytes

Try it online!

Try it online! (Edit 1)

**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
> 4 votes
# Ruby, 61 bytes

```
->{[*0..52,52].map{|x|['JAKQ'[w=x%13]||w-2,'SDHC'[x/13]]*''}}

```

Try it online!

# Answer
> 4 votes
# 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*).

Try it online.

---

Interesting alternative of **119 bytes** by *@Corak*.

```
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.

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
> 4 votes
# SMBF, 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 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
> 3 votes
## 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
> 3 votes
# , 41 bytes

```
'J';^:2,'HCDS',&.>/~(":&.>2+i.9),;/'AJQK'

```

Try it online!

# Answer
> 3 votes
# C (gcc), ~~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!

+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
> 3 votes
# Pyth, ~~26~~ 25 bytes

```
+ B\JsM*+tSTc"JQKA"1"CDHS

```

Saved a byte thanks to hakr14.
Try it here

### 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.

```

# Answer
> 3 votes
# , ~~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!

Only one more byte than digEmAll's golfier solution. Inspired byGiuseppe's solution to this related challenge \- 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
> 3 votes
# Javascript (ES6) 77 74 72 bytes

This is a complete program.

```
`J,J,${[..."A23456789JQK",10].map(c=>[..."SDHC"].map(s=>c+s))}`.split`,`

```

# Answer
> 3 votes
# Perl 6,  ~~43~~  42 bytes

```
{|(|(2..10),|<A J Q K>X~ <S D H C>),|<J J>}

```

Try it

```
{|(|(^9+2),|<A J Q K>X~ <S D H C>),|<J J>}

```

Try it from 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
> 3 votes
# 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
> 3 votes
# 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!

# Answer
> 3 votes
# 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

# Answer
> 3 votes
# Lua, ~~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!

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
> 3 votes
# Deadfish~, 1318 bytes

```
{{i}ddd}iiiic{d}iiic{ddd}dddddc{iiii}iicddddddc{ddd}ddddddc{iiii}iicddc{dddd}c{iiii}iic{i}dc{ddddd}dc{iiiii}dc{d}ddddc{ddd}dddddc{iiiii}dc{d}dddc{ddd}ddddddc{iiiii}dc{d}ic{dddd}c{iiiii}dciic{ddddd}dc{iiii}iiic{d}iic{ddd}dddddc{iiii}iiic{d}iiic{ddd}ddddddc{iiii}iiicdddc{dddd}c{iiii}iiic{i}ddc{ddddd}dc{iii}iiiciic{ddd}dddddc{iii}iiiciiic{ddd}ddddddc{iii}iiic{i}dddc{dddd}c{iii}iiic{ii}ddc{ddddd}dc{ii}ddc{ii}dddc{ddd}dddddc{ii}ddc{ii}ddc{ddd}ddddddc{ii}ddc{ii}iic{dddd}c{ii}ddc{iii}iiic{ddddd}dc{ii}dc{i}iiiiiic{ddd}dddddc{ii}dc{ii}dddc{ddd}ddddddc{ii}dc{ii}ic{dddd}c{ii}dc{iii}iic{ddddd}dc{ii}c{i}iiiiic{ddd}dddddc{ii}c{i}iiiiiic{ddd}ddddddc{ii}c{ii}c{dddd}c{ii}c{iii}ic{ddddd}dc{ii}ic{i}iiiic{ddd}dddddc{ii}ic{i}iiiiic{ddd}ddddddc{ii}ic{ii}dc{dddd}c{ii}ic{iii}c{ddddd}dc{ii}iic{i}iiic{ddd}dddddc{ii}iic{i}iiiic{ddd}ddddddc{ii}iic{ii}ddc{dddd}c{ii}iic{iii}dc{ddddd}dc{ii}iiic{i}iic{ddd}dddddc{ii}iiic{i}iiic{ddd}ddddddc{ii}iiic{ii}dddc{dddd}c{ii}iiic{iii}ddc{ddddd}dc{ii}iiiic{i}ic{ddd}dddddc{ii}iiiic{i}iic{ddd}ddddddc{ii}iiiic{i}iiiiiic{dddd}c{ii}iiiic{iii}dddc{ddddd}dc{ii}iiiiic{i}c{ddd}dddddc{ii}iiiiic{i}ic{ddd}ddddddc{ii}iiiiic{i}iiiiic{dddd}c{ii}iiiiic{ii}iiiiiic{ddddd}dc{ii}dddcdc{ii}dc{ddd}dddddc{ii}dddcdc{ii}c{ddd}ddddddc{ii}dddcdc{ii}iiiic{dddd}c{ii}dddcdc{iii}iiiiic{ddddd}dc{iiii}iic{dddd}ddc{iiii}iic

```

Try it online!

# Answer
> 3 votes
# Vyxal, 24 bytes

```
₀ɾḢ«∧9₂«fJ«¬⟩C«Ẋvṅ‛jjfJɾ

```

Try it Online!

## How?

```
₀ɾḢ«∧9₂«fJ«¬⟩C«Ẋvṅ‛jjfJɾ
₀ɾ                       # Push a list in the range [1, 10]
  Ḣ                      # Remove the first: [2, 3, 4, ..., 10]
   «∧9₂«                 # Push compressed string "jqka"
        fJ               # Convert to list of characters and add to the other list: [2, 3, 4, ..., 10, "j", "q", "k", "a"]
          «¬⟩C«           # Push compressed string "hsdc"
               Ẋ         # Cartesian product of list and string: [[2, "h"], [2, "s"], ..., ["a", "c"]]
                vṅ       # Join each together: ["2h", "2s", ..., "ac"]
                  ‛jjf   # Push string "jj" and convert to list of characters: ["j", "j"]
                      J  # Append: ["2h", "2s", ..., "ac", "j", "j"]
                       ɾ # Uppercase each: ["2H", "2S", ..., "AC", "J", "J"]

```

# Answer
> 2 votes
# Haskell, 57 bytes

```
"J":"J":[c++[s]|c<-"10":map pure"AJQK23456789",s<-"SDHC"]

```

Try it online!

# Answer
> 2 votes
# Retina, ~~49~~ 42 bytes

```

AJQK2345678910
1?.
$0H,$0S,$0D,$0C,
$
J,J
```

Credit to *@mazzy*'s comment on my Java answer.
-7 bytes thanks to *@ovs*.

Try it online.

**Explanation:**

Start with "AJQK2345678910":

```

AJQK2345678910
```

For each character (with "10" as single character):
Replace it with "cH,cS,cD,cC" where `c` is this character:

```
1?.
$0H,$0S,$0D,$0C,

```

And append "J,J"

```
$
J,J

```

# Answer
> 2 votes
# MATLAB R2018a, ~~82~~ 57 bytes

Thanks to @David:

```
s=["A" 2:10 "J" "Q" "K"]+["D";"S";"H";"C"];[s(:);"J";"J"]

```

**My old code:**

```
X=["J","J"];for n=["A",2:10,"J","Q","K"]for s=["S","H","C","D"]X=[X,n+s];end;end;X

```

I figure it doesn't need an explanation but in case someone's interested:

```
X=["J","J"] // Set up first two Jokers
 for n=["A",2:10,"J","Q","K"] // Set up array for A, 2, 3... to K
  for s=["S","H","C","D"] // Set up suits
   X=[X,n+s]; // "Glue" value and suit together and add to array
  end
 end
X // Print out the result

```

Output:

X =

1×54 string array

Columns 1 through 11

```
"J"    "J"    "AS"    "AH"    "AC"    "AD"    "2S"    "2H"    "2C"    "2D"    "3S"

```

Columns 12 through 22

```
"3H"    "3C"    "3D"    "4S"    "4H"    "4C"    "4D"    "5S"    "5H"    "5C"    "5D"

```

Columns 23 through 33

```
"6S"    "6H"    "6C"    "6D"    "7S"    "7H"    "7C"    "7D"    "8S"    "8H"    "8C"

```

Columns 34 through 43

```
"8D"    "9S"    "9H"    "9C"    "9D"    "10S"    "10H"    "10C"    "10D"    "JS"

```

Columns 44 through 54

```
"JH"    "JC"    "JD"    "QS"    "QH"    "QC"    "QD"    "KS"    "KH"    "KC"    "KD"

```

# Answer
> 2 votes
# VBA + RegExp, 135 bytes

A declared function that takes no input and outputs to the out var, `o`.

This subroutine depends upon the Microsoft VBScript Regular Expression 5.5 reference.

```
Sub a(o)
Set r=New RegExp
r.Global=1
r.Pattern="(\w+)"
o=Split(r.Replace("A 2 3 4 5 6 7 8 9 10 J Q K","$1S $1H $1D $1C")&" J J")
End Sub

```

*Note: The terminal `"` on line 4 is not counted in the bytecount as it is not necessary and is only included for SO's syntax highlighting*

# Answer
> 2 votes
# 8th, ~~156~~ ~~152~~ 149 bytes

**Code**

```
[] ( >s a:push ) 2 10 loop ["J","Q","K","A"] a:+ ( nip dup ["C","D","S","H"] ( nip s:+ >r dup ) a:each drop ) a:each ["J","J"] ( r> a:push ) 52 times

```

Array result is available on **TOS**

**Output**

```
["J","J","AH","AS","AD","AC","KH","KS","KD","KC","QH","QS","QD","QC","JH","JS","JD","JC","10H","10S","10D","10C","9H","9S","9D","9C","8H","8S","8D","8C","7H","7S","7D","7C","6H","6S","6D","6C","5H","5S","5D","5C","4H","4S","4D","4C","3H","3S","3D","3C","2H","2S","2D","2C"]

```

**Ungolfed code**

```
\ make array ["2","3","4","5","6","7","8","9","10"]
[] ( >s a:push ) 2 10 loop

\ make array ["2","3","4","5","6","7","8","9","10","A","J","Q","K"]
["J","Q","K","A"] a:+

\ make 13 cards for each suit and store each card on r-stack
( nip dup ["C","D","S","H"] ( nip s:+ >r dup ) a:each drop ) a:each

\ make array result reading previous cards from r-stack
["J","J"] ( r> a:push ) 52 times

\ array result is available on TOS. Display it and get rid of intermediate stuff
. cr
reset

```

# Answer
> 2 votes
# Bash (if Unicode is allowed), 45 bytes

```
echo -e \\U1F0{{A..D}{{1..9},{A..E}},{CF,DF}}

```

...produces:

```

```

Try it online!

This should work wherever Unicode is supported (ex: LANG=en\_US.UTF8, not LANG=C). I'm not sure, however, if this meets the conditions of the rules. In particular:

> 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).

The Unicode answer has one string per element, and the images indeed show a value followed by a suit. The example output, however, shows two separate chars per element, so there's room for doubt.

If the Unicode approach is disallowed, the code can be easily trimmed down to 34 bytes:

```
d=({A,K,Q,J,{10..2}}{S,H,D,C} J J)

```

Try it online!

...but that is no shorter than the existing answer by glenn jackman (albeit sorted).

Regardless, Unicode is a technique worth mentioning. If you're dealing out a deck of cards, you might as well use the nice little images which are probably already on your computer, even in a text-mode terminal.

As for the question about the rules, I think the best answer is for someone to develop a question format which intrinsically includes an automated unit test. Maybe someday...

# Answer
> 2 votes
# Gol\>\<\>, ~~46~~ 44 bytes

```
"CDSH"4F:j9FL2+noao|j"AKQJ"4F$ooao||S"J`nJ";

```

Try it online!

Edit: Saved 2 bytes thanks to Jo King

Explanation:

```
"CDSH"4F:j9FL2+noao|j"AKQJ"4F$ooao||S"J`nJ";

"CDSH"                                        //Init the 4 suites
      4F                                      //Loop to iterate over the 4 suites
        :j                                    //Pop a copy of the current suite into the next loop
           9FL2+noao|                         //Loop for the output of cards 2-10
                    j                         //Pass current suite into next loop & pop it from the stack
                     "AKQJ"                   //Init the 4 pictures
                           4F$ooao|           //Loop 4 times to output the picture cards
                                   |          //Jump back to the for loop to iterate over all suites
                                    S"J`nJ";  //Output the two J and terminate programm

```

# Answer
> 2 votes
# C (gcc), 86 bytes

```
f(i){for(i=54;i--;)printf(i<52?"1%c%c "+(i>3):"J ","023456789JQKA"[i/4],"HSDC"[i%4]);}

```

Try it online!

# Answer
> 2 votes
# MASM 5 MACRO (x86 machine code), ~~109~~ 100 bytes

```
D LABEL BYTE
IRPC r,234567890JQKA
IRPC s,DSHC
IF'&r'EQ'0'
DB'1'
ENDIF
DB'&r','&s '
ENDM
ENDM
DB'J J'

```

Since machine code has no formal definition for "an array of variable length strings", this returns the elements as characters in contiguous memory, delimited by a separator byte (20H) with the label D as a pointer to the location in memory.

Obviously, this would all be a lot simpler and smaller (76 bytes) if we could use 'T' for 10, which would make all cards exactly 2 bytes in size and simply be an indexable array of DW (double-words). That's your Kolmogorov rub I suppose!

Here's a short test program that shows one possible way this could be utilized:

```
MOV  DX, OFFSET D
MOV  AH, 9
INT  21H
MOV  AH, 4CH
INT  21H

```

Output

```
2D 2S 2H 2C 3D 3S 3H 3C 4D 4S 4H 4C 5D 5S 5H 5C 6D 6S 6H 6C 7D 7S 7H 7C 8D 8S 8H 8C 9D 9S 9H 9C 10D 10S 10H 10C JD JS JH JC QD QS QH QC KD KS KH KC AD AS AH AC J J

```

# Answer
> 2 votes
# Rockstar, ~~129~~ 99 bytes

```
say "J
J"
cut "CHSD" in S
while S
roll S in X
say 10+X
cut "A23456789JQK" in V
while V
say roll V+X

```

Try it here (Code will need to be pasted in)

```
say "J\nJ"          :Output the jokers
cut "CHSD" in S     :Split "CHSD" into array S
while S             :While S is not empty
roll S in X         :  Pop the first element into variable X
say 10+X            :  Output 10 appended with X
cut "..." in V      :  Split "A23456789JQK" into array V
while V             :  While V is not empty
say                 :    Output
  roll V            :      Pop the first element from V
  +X                :      Append X

```

# Answer
> 2 votes
# Factor \+ `poker`, 64 bytes

```
<deck> hand>card-names [ "T""10"replace ] map { "J""J"} append .

```

Try it online!

Factor has a poker vocabulary that gets most of the way there; just have to change `T` to `10` and add the jokers.

# Answer
> 1 votes
# C# (.NET Core), 140 bytes

```
x=>{var a=new string[54];a[0]=a[1]="J";int i=2;foreach(var s in"SDCH")foreach(var n in"023456789AJQK")a[i++]=(n=='0'?"10":n+"")+s;return a;}

```

Try it online!

*-10 bytes thanks to Kevin Cruijssen*

*-1 byte by taking unused input*

*-18 bytes thanks to Corak*

# Answer
> 1 votes
# Red, 88 bytes

```
foreach s{HSDC}[foreach c['A 2 3 4 5 6 7 8 9 10 'J 'Q 'K][prin c print s]]prin['J"^/"'J]

```

Try it online!

## As a list:

# Red, 100 bytes

```
d:[]foreach s{HSDC}[foreach c['A 2 3 4 5 6 7 8 9 10 'J 'Q 'K][append d rejoin[c s]]]append d["J""J"]

```

Try it online!

# Answer
> 1 votes
# CJam, 45 bytes

```
"A"]8,2f+'0f+"10"a+"JQK"++"SDHC"m*::+["J"_]+p

```

Try it online!

# Answer
> 1 votes
# Jelly, 24 bytes

```
⁵ḊṾ€;“AJQK”p“HSDC”;⁾JJẎ€

```

Try it online!

# Answer
> 1 votes
# JavaScript (Node.js), 126 bytes

```
[..."SDHC"].map(a=>Array.apply(0,Array(13)).map((b,i)=>(i==0?'A':i>9?'JQK'[i-10]:i+1)+a)).reduce((a,b)=>a.concat(b),['J','J'])

```

Try it online!

# Answer
> 1 votes
# Stax, 21 bytes

```
Å|R╦¥Ä└╥¿‼≈┴2½#d☺Iwa▐

```

Run and debug it

Explanation:

```
9{^$m"AJQK"+"HSDC"|*'JQPm Full program, unpacked
                          Stack ([] is array, "" string '' char): empty
9{  m                     Map each element in range [1, 9]
  ^                         Increment
   $                        Stringify
                          Stack: ["2", "3", "4", "5", "6", "7", "8", "9", "10"]
     "AJQK"+              Add "AJQK"
                          Stack: ["2", "3", "4", "5", "6", "7", "8", "9", "10", 'A', 'J', 'Q', 'K']
            "HSDC"        Push suits
                          Stack: "HSDC" ["2", "3", "4", "5", "6", "7", "8", "9", "10", 'A', 'J', 'Q', 'K']
                  |*      Cartesian join
                          Stack: [["2", 'H'], ["2", 'S'], ..., "AH", "AS", ...]
                    'J    Push "J"
                          Stack: "J" [...]
                      Q   Peek and print with newline
                          Stack: "J" [...]
                       P  Pop and print with newline
                          Stack: [...]
                        m Map, implicitly print each with a newline

```

# Answer
> 1 votes
# Twig, ~~83~~ 82 bytes

```
J J{%for I in(2..9)|merge('AKQJ'|split)%} {{I~'SDHC'|split|join(' '~I)}}{%endfor%}

```

This outputs the suits grouped by the "number".

You can test it on: https://twigfiddle.com/lz9cuf

Old version:

# Answer
> 1 votes
# SimpleTemplate, 69 bytes

This is a template-like language I've been developing, all written in PHP. The instructions on how to use it are available in the Github page.

```
J J{@setx"SDHC","23456789JQKA"}{@eachx.1 asN}{@eachx.0}{@echo" ",N,_}

```

---

## Ungolfed:

```
J J
{@set chars "SDHC", "23456789JQKA"}
{@each chars.1 as number}
    {@each chars.0 suite}
        {@echo " ", number, suite}
    {@/}
{@/}

```

---

---

Due to a series of bugs, this is not the most optimal solution. A shorter (non-working but should work) version below (51 bytes):

```
J J{@each"23456789JQKA"asN}{@each"SDHC"} {@echoN,_}

```

This, however, doesn't work.

# Answer
> 1 votes
# vim, 80 bytes

```
aoA J Q K<C-V><ESC>:r !seq 2 10<C-V><CR>o<C-V><ESC>V10kJ:s/ /H /g<ESC>
yy3P34lrSjrDjrC:g/./:norm dd@"
oJ J<ESC>

```

`<C-V>` is 0x16. `<CR>` is 0x0d. `<ESC>` is 0x1B

### Annotated

```
a                                    " insert vim code into the buffer that:
   oA J Q K<C-V><ESC>                "   generates face cards
   :r !seq 2 10<C-V><CR>o<C-V><ESC>  "   generates 2-10
   V10kJ                             "   joins into one line
   :s/ /H /g<ESC>                    "   adds suit (hearts)
yy3P                                 " make 3 copies of code
34lrSjrDjrC                          " change suit for each copy
:g/./:norm dd@"              " replace each line with the results from running it
o J J<ESC>                   " Jokers

```

Try it online!

# Answer
> 1 votes
# Google Sheets, 86 Bytes

A worksheet function that returns an array of "cards" to the the calling cell and the 53 cells to its right.

```
=Split(RegExReplace("A 2 3 4 5 6 7 8 9 10 J Q K","(\w+)","$1S $1H $1D $1C ")&" J J","

```

*Note: This function ends with a trailing space*

# Answer
> 1 votes
# Yabasic, 123 bytes

```
Dim r$(54)
r$(1)="J"
r$(2)="J"
For i=0To 51
r$(i+3)=Mid$("JQKA2345678910",1+i/4,1+(i/4>=12))+Mid$("CDHS",Mod(i,4)+1,1)
Next

```

Try it online!

# Answer
> 1 votes
# Cjam, ~~29~~ 26 bytes

```
B,2>"AJQK"+"SDHC"m*"JJ"+N*

```

Try it online!

Explanation:

```
B,2>        e# Generate the range [2, 10]
"AJQK"+     e# add the list with "AJQK"
            e# which generates all the 13 cards
"SDHC"      e# Push the variants
m*          e# Cartesian product
"JJ"+       e# Add 2 J's to the list
N*          e# And join the list items with newlines

```

---

Note:

1. The previous count was incorrect; it should be 29 instead of 28.
2. The challenge said the order doesn't matter, so 3 bytes off!

# Answer
> 1 votes
# Julia, 63 bytes

```
[["1"^(k<'1')*"$k$z"for k="A234567890JQK"for z="HSDC"];"J";"J"]

```

## Explanation

```
[
    [
        "1"^(k<'1')           # "1" if k is lexicographically before '1'
                              # which here only happens if k is '0'
        *"$k$z"               # concatenated to k and z
        for k="A234567890JQK" # for k in ranks
        for z="HSDC"          # and z in suits
    ]
    ;"J"                      # then concatenate 2 jokers
    ;"J"
]

```

# Answer
> 1 votes
# Groovy, ~~68~~ ~~66~~ 60 bytes

This is my first stab at a golf challenge, hope I get everything right.

68 byte version

```
[*2..10,*'AKQJ'.grep()].collectMany{n->'HSDC'.collect{n+it}}+['J']*2

```

Try it here

---

66 byte version
```
[*2..10,*'AKQJ'.grep()].inject([]){a,e->a+'HSDC'*.plus(e)}+['J']*2

```

Try it here

---

60 byte version
```
'HSDC'.grep().sum{[*2..10,*'AKQJ'.grep()]*.plus(it)}+['J']*2

```

Try it here

# Answer
> 1 votes
# Plain TeX, 348 bytes

It's just text printed as if it were an array, but that is close enough I think. It's not like TeX has native arrays anyway (although I do use some form of arrays in the code).

Short answer:

```
\newcount\i\let\c\csname\let\e\endcsname\let\t\the\def~#1,#2,#3{\expandafter\def\c#2\t#1\e{#3}}\i3 ~\i,a,K~\i,s,D\i4 ~\i,a,Q~\i,s,C\i5 ~\i,a,J~\i,s,S\i2 ~\i,a,A~\i,s,H\newcount\v[\loop\v2{\loop"\t\v\c s\t\i\e", \ifnum\v<10\advance\v1\repeat}{\loop"\c a\t\v\e\c s\t\i\e", \ifnum\v<5\advance\v1\repeat}\break\ifnum\i<5\advance\i1\repeat "J", "J"]\bye

```

Long answer, with comments as explanation:

```
%First shorten some commands
\let\c\csname
\let\e\endcsname
\let\t\the
%then define the function todefine and fill the arrays
\def ~#1,#2,#3{\expandafter\def\c #2\t#1\e{#3}}
%main counter in this program
\newcount\i
\i3
%array a contains A, K, Q, J, the 'picture cards'
%array s contains D, C, S, H, the suits
%indexing is 2 to 5 so the same counter as for the 2...10 can be used
 ~\i,a,K
 ~\i,s,D
\i4
 ~\i,a,Q
 ~\i,s,C
\i5
 ~\i,a,J
 ~\i,s,S
%2 is the last one as we want i to be 2 after this
\i2
 ~\i,a,A
 ~\i,s,H
%the other counter
\newcount\v
%outer loop loops over the suits
[\loop
    %2 is the starting point for the arrays and the numbers
    \v2
    %brackets to ensure local use of \v
    %first loop iterates over the numbers
    {
     \loop
     %this prints v and the current suit
     "\t\v \c s\t\i\e",
     \ifnum\v<10
        %\advance \v by 1
        \advance\v1
     \repeat
    }
    %...second loop over the picture cards
    {
     \loop
     "\c a\t\v\e \c s\t\i\e",
     \ifnum\v<5
        \advance\v1
     \repeat
    }
    %to prevent the output escaping the file on the right border
    \break
    \ifnum\i<5
        \advance\i1
 \repeat
 %then print the jokers
 "J", "J"
]
\bye

```

# Answer
> 1 votes
# PicoLisp, ~~181~~ 171 bytes

(replaced `ifn` with `if`)

```
(setq c '(A 2 3 4 5 6 7 8 9 10 J Q K))
(de z (s l)(if (<> l NIL) (cons (pack (car l) s) (z s (cdr l)))))
(setq d (conc (z 'C c) (z 'D c) (z 'H c) (z 'S c) (list "J" "J")))

```

Sample output:

```
bash$ pil +
: (load 'cards.l)
-> ("AC" "2C" "3C" "4C" "5C" "6C" "7C" "8C" "9C" "10C" "JC" "QC" "KC" "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" "AS" "2S" "3S" "4S" "5S" "6S" "7S" "8S" "9S" "10S" "JS" "QS" "KS" "J" "J")
: d
-> ("AC" "2C" "3C" "4C" "5C" "6C" "7C" "8C" "9C" "10C" "JC" "QC" "KC" "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" "AS" "2S" "3S" "4S" "5S" "6S" "7S" "8S" "9S" "10S" "JS" "QS" "KS" "J" "J")
:

```

Try it online!

# Answer
> 1 votes
# Pyth - 32 bytes

```
K+r2hTc"JQKA"1\J\JJ"SDHC"VJVK+HN

```

Explanation:

```
K+r2hTc"JQKA"1\J\JJ"SDHC"VJVK+HN
K                                 Assign variable K to
  r2hT                            Range from 2 to 10 plus 1
 +                                Plus
      c"JQKA"1                    Length 1 substrings of "JQKA"

              \J\J                Print 1 character string "J" twice

                  J"SDHC"         Assign J to "SDHC"

                         VJ       For N in J
                           VK     For H in K
                             +HN  Implicitly print H+N

```

# Answer
> 1 votes
# C (gcc), 129 bytes

```
char*v[]={"A","2","3","4","5","6","7","8","9","10","J","Q","K"};main(i){for(i=0;i<13;)printf("%sS %1$sD %1$sH %1$sC ",v[i++]);puts("J J");}

```

# C (gcc), 89 bytes

```
main(i){for(i=0;i<13;)printf("%cS %1$cD %1$cH %1$cC ","A23456789XJQK"[i++]);puts("J J");}

```

2018-09-16: **-12** @gastropner

# Answer
> 1 votes
# Brain-Flak, 276 bytes

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

```

Try it online!

Prints each card on its own line, with a leading newline.

### Explanation:

```
((((((
((()()())){}{})  # Push 9 to represent  'C'
())              # Push 10 to represent 'D'
[][])            # Push 14 to represent 'H'
<>()())(<()>))   # Push 16, 0, 16 to the other stack to represent the Jokers
<>[][][])        # Push 25 to represent 'S'
{  # Loop over each suit
  (<>)  # Push 0 for a newline
  ((
    ((([()()()])){}{})  # Push -9 to represent '1'
    [()])               # Push -10 to represent '0'
  ())   # Push -9 to use as a counter
  {  # Loop 9 times to push the number cards
    (({}  # Store counter
     <>(<(({})<>)>)  #Push current suit and newline
    ()))  # Decrement counter and push twice, once as the number
  }{}{}
  ((((
    (()()()){}())  # Push 7 as 'A'
    (<<>(({})<>)>) # Push suit and newline
    ((()()())){}{})# Push 16 as 'J'
    (<<>(({})<>)>) # Push suit and newline
    ())            # Push 17 as 'K'
    (<<>(({})<>)>) # Push suit and newline
    (()()()){})    # Push 23 as 'Q'
  <>({}<>)<>       # Push suit
}
<>
{  # Loop over all output
  {  # Add 58 to each number
    ({}((((()()()){}()){}){}()){}<>)<>
  }
  {}<>((()()()()()){})<>  # And turn 0s into newlines
}<>  # Implicit output

```

# Answer
> 1 votes
# Kotlin, 76 bytes

```
("A2345678910JQK".replace(Regex("1?."),"$0C $0D $0H $0S ")+"J J").split(" ")

```

Try it online!

# Answer
> 1 votes
# Tcl, 76 bytes

```
lmap n {S C H D} {lmap v {A K Q J 2 3 4 5 6 7 8 9 10} {puts $v$n}}
puts J\nJ

```

Try it online!

# Answer
> 1 votes
# Pyth, ~~30 29~~ 31 bytes

Current

```
+,K\JKsM*+tST[\AK\Q\K)[\H\D\C\S

```

Previous:

```
+,K\JK*+tST[\AK\Q\K)[\H\D\C\S
+,K\JK*+tS10[\AK\Q\K)[\H\D\C\S

```

Explanation:

```
+,K\JKsM*+tS10[\AK\Q\K)[\H\D\C\S
 ,K\JK                              Create a tuple ('J', 'J'), meanwhile assign 'J' to K
         +tS10[\AK\Q\K)             Create a range from 2-10 and append [A, J, Q, K] (K = 'J')
                       [\H\D\C\S    Create range [H, D, C, S]
      sM*                           Get the Cartesian product of {Num Range} & {Suit Range}, then join them as a string
+                                   Join the jokers onto the result.

```

Try it online!

# Answer
> 1 votes
## PostScript, ~~90~~ 84 bytes

Output as an array of strings on the stack.

```
00000000: 5b28 4443 4853 297b 2f64 923e 9233 284a  [(DCHS){/d.>.3(J
00000010: 514b 4132 3334 3536 3738 3929 7b2f 6a92  QKA23456789){/j.
00000020: 3e92 3332 92a5 9238 9238 3020 6a92 7831  >.32...8.80 j.x1
00000030: 2064 9278 7d92 497d 9249 2831 3044 2928   d.x}.I}.I(10D)(
00000040: 3130 4329 2831 3048 2928 3130 5329 284a  10C)(10H)(10S)(J
00000050: 2992 385d                                ).8]

```

Pre-tokenization (119 bytes):

```
[(DCHS){/d exch def(JQKA23456789){/j exch def 2 string dup dup 0 j put 1 d put}forall}forall(10D)(10C)(10H)(10S)(J)dup]

```

Try it online! (Pre-tokenized version as I don't know how to paste the tokenized file into TIO.)

---
Tags: code-golf, kolmogorov-complexity
---