title: Help Trump build the wall!

text:
# Question
Title: Help Trump build the wall!
Trump needs the wall constructed and you are going to do it! To most efficiently build his wall I have created a simple, repeatable pattern for you to use:

```
    __   __
   |  |_|  |
___|       |___
-   -   -   -
 - - - - - - -
- - - - - - - -
———————————————

```

Trump will tell you how many wall segments he needs and you will build them to look just like this.

Here is the pattern:

```
    __   __     <-- 4-2-3-2-4          ' _ _ '
   |  |_|  |    <-- 3-1-2-1-1-1-2-1-3  ' | |_| | '
___|       |___ <-- 3-1-7-1-3          '_| |_'
-   -   -   -   <-- 1-3-1-3-1-3-1-1    '- - - - '
 - - - - - - -  <-- 1-1-...-1-1        ' - -...- - '
- - - - - - - - <-- 1-1-...-1-1        '- - ... - -'
——————————————— <-- 15                 Unicode U+2014

```

Input will always be an integer \>0.

Test cases:

```
1
    __   __
   |  |_|  |
___|       |___
-   -   -   -
 - - - - - - -
- - - - - - - -
———————————————

2
    __   __        __   __
   |  |_|  |      |  |_|  |
___|       |______|       |___
-   -   -   -  -   -   -   -
 - - - - - - -  - - - - - - -
- - - - - - - -- - - - - - - -
——————————————————————————————

5
    __   __        __   __        __   __        __   __        __   __
   |  |_|  |      |  |_|  |      |  |_|  |      |  |_|  |      |  |_|  |
___|       |______|       |______|       |______|       |______|       |___
-   -   -   -  -   -   -   -  -   -   -   -  -   -   -   -  -   -   -   -
 - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -
- - - - - - - -- - - - - - - -- - - - - - - -- - - - - - - -- - - - - - - -
———————————————————————————————————————————————————————————————————————————

```

Since you need to do this fast, write the shortest program possible!

If it helps, I wrote the challenge first, title last ;)

# Answer
> 10 votes
# 05AB1E, 38 bytes

```
•4H’*»È%f·ù„áÅ'4•4B3ÝJ"_ -|"‡8ô€ûvy¹×»

```

Try it online!

```
•4H’*»È%f·ù„áÅ'4•     # Push '1724427993555739020619095486300160'
4B                    # Convert to base 4 (turns it into an 8x8 bitmap).
  3ÝJ"_ -|"‡          # Replace digits 0-3 with _, , -, or |.
            8ô        # Split into pieces of 8.
              €û      # Palindromize each piece.
                vy¹×» # For each row, dupe it n times (hori) and print it.

```

***1724427993555739020619095486300160 converted to base-4:***

`11110011111311300003111121112111121212122121212100000000`

***11110011111311300003111121112111121212122121212100000000 with characters replaced:***

`__ | |____| - - - - - -- - - - ________`

***Previous pattern split into 8 pieces:***

```
    __
   |  |_
___|
-   -
 - - - -
- - - -
________

```

***Then you palindromize, and make it as long as needed through repetition.***

# Answer
> 28 votes
# CJam, 52 bytes

```
F,ri*"s@;b6(MBZF,fu"128b6b"_
|-—"f=N/ff=zN*

```

Includes a bunch of unprintable ASCII characters. The hexdump of the first string literal pushed is:

```
01 73 06 40 3B 62 36 28 1E 4D 07 42 5A 14 1B 46 2C 66 75

```

Try it here!

## Explanation

The above hexdump is interpreted as a base-128 number, then converted to base 6, to get this list:

```
[1 1 1 1 0 0 1 1 1 0 0 2
 1 1 1 3 1 1 3 0 3 1 1 3 2
 0 0 0 3 1 1 1 1 1 1 1 3 2
 4 1 1 1 2
 1 4 2
 4 1 2
 5]

```

To this, we apply the mapping `0 → _`, `1 → space`, `2 → \n`, `3 → |`, `4 → -`, `5 → —`. This gets us the string:

```
    __   __
   |  |_|  |
___|       |
-
 -
-
—

```

It consists of the "period" of each line; i.e. we can cycle the fifth line `" -"` to get `" - - - - - - - "`.

Then, we execute this subprogram:

```
N/               Split into lines.
  Ff*            Repeat each line 15 times (to cycle it).
     Ff<         Take the first 15 chars of each line.
        rif*     Repeat these chars input() times.
            N*   Join lines.

```

(The new version does this in a slightly different way that I actually can't wrap my head around myself very well, because it uses `ff=`.)

# Answer
> 13 votes
# JavaScript (ES6), ~~116~~ 115 bytes

```
n=>"__   __    n|  |_|  |   n|       |___n -  n- n -n—".split`n`.map(l=>l.repeat(15).slice(-15).repeat(n)).join`
`

```

*Saved a byte thanks to @Neil!*

## Explanation

Pretty much the same as @Mauris' CJam method, but without the character mapping.

The wall parts are in the format:

```
__   __
|  |_|  |
|       |___
 -
-
 -
—

```

because if you repeat each line 15 times you get:

```
...    __   __    __   __    __   __
... |  |_|  |   |  |_|  |   |  |_|  |
... |       |___|       |___|       |___
 -   -   -   -   -   -   -   -   -   -
          - - - - - - - - - - - - - - -
           - - - - - - - - - - - - - - -
                         ———————————————

```

and after slicing to just the last 15 characters you get:

```
    __   __
   |  |_|  |
___|       |___
-   -   -   -
 - - - - - - -
- - - - - - - -
———————————————

```

### Ungolfed

```
n=>

  // array of wall line parts
  "__   __    n|  |_|  |   n|       |___n -  n- n -n—".split`n`

  .map(l=>       // for each wall line
    l.repeat(15) // repeat the line 15 times to create a complete wall line
    .slice(-15)  // each wall piece is only 15 characters long
    .repeat(n)   // repeat the wall n times
  )
  .join`
`                // output the resulting wall

```

## Test

```
var solution = n=>"__   __    n|  |_|  |   n|       |___n -  n- n -n—".split`n`.map(l=>l.repeat(15).slice(-15).repeat(n)).join`
`
```

```
<input type="number" oninput="result.textContent=solution(+this.value)" />
<pre id="result"></pre>
```

# Answer
> 5 votes
# Jolf, 135 bytes

~~Considerable golfing can be done.~~ Turn off pretty print and clear the output for a better result. Try it here!. Also, use this to test an arbitrary number with more ease.

```
oHpAt++++++++++++*"    __   __    "jH*"   |  |_|  |   "jH*"___|       |___"jH*j"-   -   -   -  "H*+*" -"7' jH*"- - - - - - - -"jH*M35j'—

```

I will add an explanation later.

# Answer
> 5 votes
## Haskell, ~~116~~ ~~118~~ 108 bytes

```
h n=take(n*15).cycle
f n=unlines$h n.h 1<$>lines"    __   __\n   |  |_|  |\n___|       |\n-   \n -\n- \n—"

```

Usage example:

```
*Main> putStr $ f 3
    __   __        __   __        __   __
   |  |_|  |      |  |_|  |      |  |_|  |
___|       |______|       |______|       |___
-   -   -   -  -   -   -   -  -   -   -   -
 - - - - - - -  - - - - - - -  - - - - - - -
- - - - - - - -- - - - - - - -- - - - - - - -
—————————————————————————————————————————————

```

This uses the same strategy as other answers here: each line of the wall is one cycle of the pattern, e.g. "- " (dash + space) for the second last line. Repeat each pattern, take 15 chars to get one wall segment, repeat again and take `15*n` chars for `n` segments.

Edit: @Mauris found 10 bytes. Thanks!

# Answer
> 4 votes
# Bash + Linux utilities (~~247~~ ~~186~~ 180 bytes)

```
read x
for i in {1..7}
do
tail -n +7 $0|gzip -dc|sed -nr "$i s/(.*)/$(printf '\\1%.0s' $(seq 1 $x))/p"
done
exit
ˈ ELzVSPPPȏǑ
\@\Dk>ĄÚ ܋ɀÜ@r²uٞ5L! ͠

```

Since unprintable characters have been generously used in the construction of the above script, here's a hexdump:

```
00000000  72 65 61 64 20 78 0a 66  6f 72 20 69 20 69 6e 20  |read x.for i in |
00000010  7b 31 2e 2e 37 7d 0a 64  6f 0a 74 61 69 6c 20 2d  |{1..7}.do.tail -|
00000020  6e 20 2b 37 20 24 30 7c  67 7a 69 70 20 2d 64 63  |n +7 $0|gzip -dc|
00000030  7c 73 65 64 20 2d 6e 72  20 22 24 69 20 73 2f 28  ||sed -nr "$i s/(|
00000040  2e 2a 29 2f 24 28 70 72  69 6e 74 66 20 27 5c 5c  |.*)/$(printf '\\|
00000050  31 25 2e 30 73 27 20 24  28 73 65 71 20 31 20 24  |1%.0s' $(seq 1 $|
00000060  78 29 29 2f 70 22 0a 64  6f 6e 65 0a 65 78 69 74  |x))/p".done.exit|
00000070  0a 1f 8b 08 00 45 4c 7a  56 02 03 53 50 50 50 88  |.....ELzV..SPPP.|
00000080  8f 87 11 0a 5c 40 5c 03  44 f1 35 60 5a 81 2b 3e  |....\@\.D.5`Z.+>|
00000090  1e c4 04 83 1a 20 9b 4b  17 c8 40 c2 5c 40 02 19  |..... .K..@.\@..|
000000a0  72 a1 72 75 b9 1e 35 4c  21 1e 01 00 f3 30 f0 f9  |r.ru..5L!....0..|
000000b0  8d 00 00 00                                       |....|
000000b4

```

# Answer
> 4 votes
# PowerShell, ~~103~~ 100 characters (105 bytes on disk, 102 w/o BOM)

Pretty much the same as @user81655 method.

```
Param($c)'    __   __n   |  |_|  |n___|       |n-   n -n- n—'-split'n'|%{($_*15).Substring(0,15)*$c}

```

### Ungolfed version

```
# Assign input to variable,
Param($c)

# Split array of wall parts and send them down the pipeline
'    __   __n   |  |_|  |n___|       |n-   n -n- n—' -split 'n' |
    ForEach-Object { # For each piece of wall
        ($_*15) # Repeat the line 15 times to create a complete wall line
        .Substring(0,15) # Each wall piece is only 15 characters long
        *$c # Repeat the wall n times
    }

```

### Usage example

```
PS> .\TrumpWall.ps1 3
    __   __        __   __        __   __
   |  |_|  |      |  |_|  |      |  |_|  |
___|       |______|       |______|       |___
-   -   -   -  -   -   -   -  -   -   -   -
 - - - - - - -  - - - - - - -  - - - - - - -
- - - - - - - -- - - - - - - -- - - - - - - -
—————————————————————————————————————————————

```

# Answer
> 3 votes
# PHP 5.4, ( ~~182~~ 175 characters )

```
foreach(['    __   __    ','   |  |_|  |   ','___|       |___','-   -   -   -  ', ' - - - - - - - ','- - - - - - - -','———————————————'] as$d)echo str_repeat($d,$argv[1])."\n";

```

Ungolfed Version

```
$s=['    __   __    ',
    '   |  |_|  |   ',
    '___|       |___',
    '-   -   -   -  ',
    ' - - - - - - - ',
    '- - - - - - - -',
    '———————————————'
];
foreach($s as $d) {
    echo str_repeat($d,$argv[1])."\n";
}

```

\[ 7 characters saved by follow Blackhole suggestion. \]

Another version with less bytes but more characters

# PHP 5.4, ( 176 characters, 178 bytes )

```
foreach(['    __   __    ','   |  |_|  |   ','___|       |___','-   -   -   -  ',' - - - - - - - ','- - - - - - - -',str_repeat('—',15)] as$d)echo str_repeat($d,$argv[1])."\n";

```

Just replace 15 instances of m-dash with one dash with str\_repeat function

# Answer
> 3 votes
# C, 148 bytes

```
#define q 16843009
i;p[]={-1,q*17,q*68,q*16,-8388417,8577152,3936000};
f(n){for(i=n*105;i--;i%(15*n)||puts(""))putchar(" -|_"[p[i/15/n]>>i%15*2&3]);}

```

Score excludes the unnecessary newline before `f(n)` which is included for clarity.

the magic numbers in `p` encode the characters for the wall in base 4, which are reconstructed from the string `" -|_"` *0,1,2,3 respectively*

`16843009` in hex is `0x1010101`. this is used for the lines with `-` in them.

Because `_` is encoded by `3`, the bottom line can be encoded simply as `-1`, which is the number with all the bits set to `1`.

# Answer
> 2 votes
## Python 3, 132 122 120 bytes

```
def f(n):[print((s*15*n)[:15*n])for s in['    __   __    ','   |  |_|  |   ','___|       |___','-   ', ' -', '- ', '—']]

```

Ungolfed:

```
def f(n):
    [print((s*15*n)[:15*n])for s in['    __   __    ',
                                    '   |  |_|  |   ',
                                    '___|       |___',
                                    '-   ',
                                    ' -',
                                    '- ',
                                    '—']]

```

# Answer
> 2 votes
# PHP5.5, ~~182~~ ~~172 bytes~~ 168 bytes

based on @kuldeep.kamboj's answer, which is actually 212 bytes the moment I write this but 182 characters. I wish the wall was a bit higher, then I could do some more optimisation ;-)

this one is 168 bytes, thanks to @JörgHülsermann

```
$r='str_repeat';$d=$r(' -',7);$x='   ';foreach(["$x __   __ $x","$x|  |_|  |$x","___|$x$x |___","-$x-$x-$x-  ","$d ","-$d",$r('—',15)] as$z){echo$r($z,$argv[1])."
";}

```

This one is 172 bytes

```
$r='str_repeat';$d=$r(' -',7);$x=$r(' ',3);foreach(["$x __   __ $x","$x|  |_|  |$x","___|$x$x |___","-$x-$x-$x-  ","$d ","-$d",$r('—',15)] as$z){echo$r($z,$argv[1])."
";}

```

This one is 182 bytes :-)

```
$r='str_repeat';$d=$r(' -',7);$x=$r(' ',4);foreach([$x.'__   __'.$x,'   |  |_|  |   ','___|       |___','-   -   -   -  ',$d.' ','-'.$d,$r('—',15)] as$z){echo $r($z,$argv[1]).'
';}

```

ungolfed version

```
$r='str_repeat';
$d=$r(' -',7);
$x=$r(' ',3);
$s=["$x __   __ $x",
    "$x|  |_|  |$x",
    "___|$x$x |___",
    "-$x-$x-$x-  ",
    "$d ",
    "-$d",
    $r('—',15)
];
foreach($s as $z) {
  echo$r($z,$argv[1])."
";
}

```

# Answer
> 2 votes
# Python 2, (161 characters, 191 bytes)

```
x=input();a=['    __   __    ','   |  |_|  |   ','___|       |___','-   -   -   -  ',' - - - - - - - ','- - - - - - - -','———————————————']
for i in a:print i*x

```

# Answer
> 2 votes
# Vitsy, 121 bytes

How I do this is by accessing each line one at a time input times, giving me stacks with the contents of each line. Then, I output a line at a time. If anyone wants me to give a more in-depth explanation, just ask (I'm currently opening presents, so...).

```
V0v7\[v1+v&V\[vDvm]a]y\[?Z]
"    __   __    "
"   |  |_|  |   "
"___|       |___"
4\["-   "]Xr
6mXr" "
8\["- "]X
"—"e\D
```

Try it online!

# Answer
> 2 votes
# Vim, 90 keys

Assuming the input is in a buffer by itself the following will do the job (newline only for readability)

```
"aDi    __   __    ^M   |  |_|  |   ^M___|       |___^M^[
4i-   ^[xo-^[Y7P8JY2PxA ^[GVr^K-M^Vgg$d@aP

```

where `^M` is a `return`, `^[` is `escape`, `^K` is `ctrl+k` and `^V` is `ctrl+v`.

This can very likely be golfed down quite a bit, as there might be much better ways of generating the pattern.

# Answer
> 2 votes
# SOGL V0.12, 32 bytes

```
→↔\ιδ»►℮⁰}▒║ΙOģΠp~⁵‘ ¾“ζ'¹*+'¹n*

```

Try it Here!

Explanation:

```
...‘ ¾“ζ'¹*+'¹n*
...‘              push a string of the top 6 lines of 1 wall piece (no newlines)
     ¾“           push 8212
       ζ          convert to char from unicode codepoint
        '¹*       repeat 15 times
           +      add that to the previous compressed string
            '¹n   split into lines with length 15
               *  repeat horizontally input times

```

# Answer
> 0 votes
# Java 11, ~~236~~ ~~235~~ ~~231~~ 229 bytes

```
n->{String w[]={"","","","","","",""},t="- ".repeat(7);for(;n-->0;w[0]+="x __x__x ",w[1]+="x|  |_|  |x",w[2]+="___|xx |___",w[3]+="-x-x-x-  ",w[4]+=" "+t,w[5]+=t+"-")w[6]+="_".repeat(15);return"".join("\n",w).replace("x","   ");}

```

Try it online.
NOTE: Java 11 isn't on TIO yet, so `String.repeat(int)` has been emulated with `repeat(String,int)` (for the same byte-count).

**Explanation:**

```
n->{                                // Method with integer parameter and String return-type
  String w[]={"","","","","","",""},//  Start with seven empty rows
         t="- ".repeat(7);          //  Temp String to reduce bytes
  for(;n-->0;                       //  Loop `n` amount of times:
    w[0]+="x __x__x ",              //   Append to the first row
    w[1]+="x|  |_|  |x",            //   Append to the second row
    w[2]+="___|xx |___",            //   Append to the third row
    w[3]+="-x-x-x-  ",              //   Append to the fourth row
    w[4]+=" "+t,                    //   Append to the fifth row
    w[5]+=t+"-")                    //   Append to the sixth row
    w[6]+="_".repeat(15);           //   Append to the seventh row
  return"".join("\n",w)             //  Join all rows by new-lines
          .replace("x","   ");}     //  Then replace all "x" with three spaces,
                                    //  and return the result

```

# Answer
> 0 votes
# Powershell + file, 92 bytes

save powershell to `get-trumpwall.ps1` (40 bytes)

```
param($c);gc f|%{-join($_*15)[0..14]*$c}

```

save data file with name `f` and data contains Unicode symbol and Linux LF only (52 bytes):

```
    __   __
   |  |_|  |
___|       |
-
 -
-
—

```

hex dump:

```
0000000000: 20 20 20 20 5F 5F 20 20 │ 20 5F 5F 0A 20 20 20 7C      __   __◙   |
0000000010: 20 20 7C 5F 7C 20 20 7C │ 0A 5F 5F 5F 7C 20 20 20    |_|  |◙___|
0000000020: 20 20 20 20 7C 0A 2D 20 │ 20 20 0A 20 2D 0A 2D 20      |◙-   ◙ -◙-
0000000030: 0A E2 80 94             │                          ◙—››

```

## Usage example

```
PS> .\get-trumpwall.ps1 5
    __   __        __   __        __   __        __   __        __   __
   |  |_|  |      |  |_|  |      |  |_|  |      |  |_|  |      |  |_|  |
___|       |______|       |______|       |______|       |______|       |___
-   -   -   -  -   -   -   -  -   -   -   -  -   -   -   -  -   -   -   -
 - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -  - - - - - - -
- - - - - - - -- - - - - - - -- - - - - - - -- - - - - - - -- - - - - - - -
———————————————————————————————————————————————————————————————————————————

```

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


title: Which Card is it?

text:
# Question
Title: Which Card is it?
# Introduction

Long ago, when I used to code card games with usual playing cards, I used to specify a number for each card and call a function with some number to get a card. This somewhat inspired me to make this challenge.

So for the people unaware of the playing cards, a deck of cards consist of 52 cards (13 in each of the four suits, i.e, Hearts, Diamonds, Spades, Clubs). In each suit, there are 13 cards - firstly the cards numbered from 2-10, then the Jack(J), Queen(Q), King(K) and the Ace(A). This is the order

# Challenge

The challenge is to take an integer between 1-52 as input and display the card at that position. But, your output must be in words. Also, order must be maintained, i.e, first 13 cards will be of Hearts, then Diamonds, then Spades and finally Clubs.

For example, if someone chooses the number `30`.The card would then belong to the third suit, i.e, the Spades. Also, it would be the fourth card in the suit, which means the number 5. Hence your output in words must be: `five of spades` and it should **always follow this format**, i.e, first the card, followed by an `of` and the name of the suit at the end, with required spaces in between.

# Input And Output

**The input will be** **an integer** between 1-52 (both inclusive). Note that here counting starts from 1. **You may choose to start from 0**. However, **you must maintain the order** of the cards which is mentioned above. Your output should be the card at that position written in words. You do not need to handle invalid inputs. Also, your output may be in lower-case or in upper-case.

Given below is the list of all the possible inputs and their outputs:

```
1 -> two of hearts
2 -> three of hearts
3 -> four of hearts
4 -> five of hearts
5 -> six of hearts
6 -> seven of hearts
7 -> eight of hearts
8 -> nine of hearts
9 -> ten of hearts
10 -> jack of hearts
11 -> queen of hearts
12 -> king of hearts
13 -> ace of hearts
14 -> two of diamonds
15 -> three of diamonds
16 -> four of diamonds
17 -> five of diamonds
18 -> six of diamonds
19 -> seven of diamonds
20 -> eight of diamonds
21 -> nine of diamonds
22 -> ten of diamonds
23 -> jack of diamonds
24 -> queen of diamonds
25 -> king of diamonds
26 -> ace of diamonds
27 -> two of spades
28 -> three of spades
29 -> four of spades
30 -> five of spades
31 -> six of spades
32 -> seven of spades
33 -> eight of spades
34 -> nine of spades
35 -> ten of spades
36 -> jack of spades
37 -> queen of spades
38 -> king of spades
39 -> ace of spades
40 -> two of clubs
41 -> three of clubs
42 -> four of clubs
43 -> five of clubs
44 -> six of clubs
45 -> seven of clubs
46 -> eight of clubs
47 -> nine of clubs
48 -> ten of clubs
49 -> jack of clubs
50 -> queen of clubs
51 -> king of clubs
52 -> ace of clubs

```

# Scoring

This is , so the shortest code wins.

# Answer
# Python 3,  ~~115~~  90 bytes

```
from unicodedata import*
lambda n:name(chr(n%13+n%13//11+[6,0,4,2][-n//13]*8+127137))[13:]

```

An unnamed function returning the string in uppercase.

**Try it online!**

### How?

Unicode characters have names. The names of some of these are like "PLAYING CARD TWO OF SPADES", hence we can get the characters of the Unicode character representing the required card and strip off the first 13 characters to get our output.

The Unicode characters of interest are within a block like so:

```
            0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
U+1F0Ax     x   As  2s  3s  4s  5s  6s  7s  8s  9s  Ts  Js  x   Qs  Ks  x
U+1F0Bx     x   Ah  2h  3h  4h  5h  6h  7h  8h  9h  Th  Jh  x   Qh  Kh  x
U+1F0Cx     x   Ad  2d  3d  4d  5d  6d  7d  8d  9d  Td  Jd  x   Qd  Kd  x
U+1F0Dx     x   Ac  2c  3c  4c  5c  6c  7c  8c  9c  Tc  Jc  x   Qc  Kc  x

```

Where the `x` are not characters we are after (the four in the `C` column are "knights"; three in `F` are "jokers"; one in `0` is generic; the rest are reserved characters).

As such we can add *some* value to 0x1F0A1 = 127137 (As) to find the card we want.

The value to add is only complicated by three things:

1. We need to reorder the suits (from s,h,d,c to h,d,s,c)
2. We need to reorder the ranks from (A,2,...,K to 2,...,K,A)
3. We need to avoid the columns without cards of interest.

Using the one-indexing option allows the use of negative integer division to index into an array of row-wise offsets for the suit re-ordering with `[6,0,4,2][-n//13]*8+` (effectively `[48,0,32,16][-n//13]`), we can then also place the aces into the correct locations with `n%13+` and then avoid the knights in column `C` with `n%13//11+` (effectively `(n%13>10)+`).
> 32 votes

# Answer
# Perl6/Rakudo 70 bytes

Index 0

Using `perl6 -pe`, and with no dictionary compression:

```
chr(''.ords[$_/13]+($_+1)%13*1.091).uniname.substr(13)

```

It just looks up the card in Unicode (starting from the Ace), asks for the name and uses that. This is a similar route (though I didn't know it at the time!) to Jonathan Aitken's Python answer \- only I index from all 4 aces rather than 4 offsets from the Ace of Spades, and I multiply by 1.091 to make the index round away from the Knight entry in Unicode.

See all the output (for input values 0 to 51) https://glot.io/snippets/ez5v2gkx83

Edited to cope with Knights in the Unicode deck, because Unicode.

Perl6 ♥ Unicode
> 14 votes

# Answer
# 05AB1E, 54 bytes

0-indexed

```
“»€Å‹¡Šdesž…“#“‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿—ÉŸÄ‹ŒÁà“#âí" of "ýsè

```

Try it online!

**Explanation**

```
“»€Å‹¡Šdesž…“#                                          # push list of suits
              “‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿—ÉŸÄ‹ŒÁà“#             # push list of ranks
                                           â            # cartesian product
                                            í           # reverse each
                                             " of "ý    # join on " of "
                                                    sè  # index into cardlist with input

```
> 10 votes

# Answer
# Emojicode, 202 bytes

```
itwo.three.four.five.six.seven.eight.nine.ten.jack.queen.king.ace.i 13 of hearts.diamonds.spades.clubs.➗i 13

```

0 indexed. Try it online!

**Explanation**:

```
		start of the closure block
  i		 closure takes an integer argument i
  		 print:
    		  concatenate these strings:
      ....i 13  [a]
       of
      ....➗i 13  [b]

[a]:
		tell Emojicode to dereference without checking
		 get the nth element of the following array
  		  create an array using the following string and separator
    ...
    .
   i 13	n, i mod 13

[b]
....➗i 13
same but with ⌊i÷13⌋
```
> 7 votes

# Answer
# Python 2, 167 148 bytes

```
n=input();print 'two three four five six seven eight nine ten jack queen king ace'.split()[n%13]+' of '+['hearts','diamonds','spades','clubs'][n/13]

```

Zero-indexed.

Try It Online!

EDIT: Bubbler made a great point using the split method (and providing a shorter answer). On the second block using split() yields the same byte count.
> 6 votes

# Answer
# , 154 bytes

```
paste(el(strsplit("Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Jack,Queen,King,Ace",",")),"of",rep(c("Hearts","Diamonds","Spades","Clubs"),e=13))[scan()]

```

Try it online!

Takes input (1-indexed) from STDIN and with `source(...,echo=T)` will print the result to console.

It's not pretty, BUT it comes in 2 bytes shorter than the best solution I could using `outer` (presented below), so let this be a reminder to examine another approach!

```
paste(                          # concatenate together, separating by spaces,
                                # and recycling each arg to match the length of the longest
el(strsplit("Two,...",",")),    # split on commas and take the first element
"of",                           #
 rep(c("Hearts",...),           # replicate the suits (shorter as a vector than using strsplit
               e=13)            # each 13 times
                    )[scan()]   # and take the input'th index.

```

# , 156 bytes

```
outer(el(strsplit("Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Jack,Queen,King,Ace",",")),c("Hearts","Diamonds","Spades","Clubs"),paste,sep=" of ")[scan()]

```

Try it online!

Essentially the same as above; however, `outer` will do the recycling properly, but having to set `sep=" of "` for the `paste` made this just a hair longer.
> 6 votes

# Answer
## Excel, 156 bytes

```
=TRIM(MID("two  threefour five six  seveneightnine ten  jack queenking ace",1+MOD(A1,13)*5,5))&" of "&CHOOSE(1+(A1/13),"hearts","diamonds","spades","clubs")

```

Cards from 0-51. Unfortunately, Excel does not feature a function to convert `1` to `"one"`...

Using `TRIM` and `MID` is shorter than using `CHOOSE` for the face values, but longer than using `CHOOSE` for the Suit.
> 6 votes

# Answer
# Java 8, 141 bytes

```
n->"two;three;four;five;six;seven;eight;nine;ten;jack;queen;king;ace".split(";")[n%13]+" of "+"hearts;diamonds;spades;clubs".split(";")[n/13]

```

Input is 0-indexed.

**Explanation:**

Try it online.

```
n->         // Method with integer parameter and String return-type
  "two;three;four;five;six;seven;eight;nine;ten;jack;queen;king;ace".split(";")[n%13]
            //  Take `n` modulo-13 as 0-indexed card value
   +" of "  //  append " of "
   +"hearts;diamonds;spades;clubs".split(";")[n/13]
            //  append `n` integer-divided by 13 as 0-indexed suit

```
> 5 votes

# Answer
# Husk, 52 bytes

```
;↔!Πmw¶¨×‼sÿẋδẎ₆ṡ⁷Ḃ6‰fωθ»&⌈θƒV₆x⁵▼Ëġ`nıEṅ'jĊk⁸"eïkÄc

```

Try it online!

I'm always happy to show off Husk's string compression system :D

### Explanation

The majority of the program (from `¨` onwards) is obviously a compressed string. When uncompressed it turns into:

```
hearts diamonds spades clubs
of
two three four five six seven eight nine ten jack queen king ace

```

The program then is:

```
;↔!Πmw¶¨…
       ¨…    The previous string
      ¶      Split on lines
    mw       Split each line into words
             - we now have a list of lists of words
   Π         Cartesian product of the three lists
             - with this we obtain all possible combinations of suits and values
               with "of" between the two (e.g. ["spades","of","king"])
  !          Pick the combination at the index corresponding to the input
 ↔           Reverse it, so words are in the correct order
;            Wrap it in a list. Result: [["king","of","spades"]]

```

There are a couple of things left to explain:

* We build the cards with suits before values because of how the cartesian product `Π` works: if we did it the other way around, the list of cards would be ordered by value (i.e. two of hearts, two of diamonds, two of spades, two of clubs, three of hearts...). As a consequence, we have to reverse our result.
* The result of the program is a two-dimensional matrix of strings. This is automatically printed by Husk as a single string built by joining rows of the matrix with newlines and cells with spaces. The reason we build this matrix instead of using the more straightforward `w` (join a list of words with spaces) is that if using `w` the type inferencer guesses another interpretation for the program, producing a different result.
> 4 votes

# Answer
# Kotlin, ~~154~~ ~~152~~ 140 bytes

```
i->"two,three,four,five,six,seven,eight,nine,ten,jack,queen,king,ace".split(',')[i%13]+" of ${"heart,diamond,spade,club".split(',')[i/13]}s"

```

Try it online!

Updated to use just lambda expression.
> 4 votes

# Answer
# Stax, 58 57 56 bytes

```
î↑à■?R╢8«E▄¡╔ÿ•L╫<<⌠ï∞∟⌡♪Ös1"TàLα╥▀¢¡◄└%≈δñM;;}'░o=⌡»╬í√

```

Run and debug it

Here's the commented ungolfed representation of the same program. It uses stax's compressed literals heavily. The input is 0-indexed. It's Emigna's 05AB1E algorithm.

```
`SsUI'S~pTU5T@T^Ez+`j   suits
`fV:l7eTkQtL*L2!CZb6u[&YNO4>cNHn;9(`j   ranks
|*  cross-product
@   index with input
r   reverse pair
`%+(`*  join with " of "

```

Run this one
> 3 votes

# Answer
# JavaScript ES6, ~~124~~ 118 Bytes, 0-index

```
F= x=>(h=btoa`O
?NÞ{ñhº¿Å÷¿J,IëÞñ"6)Þý7§üô.yéÿ*)àüÿÿÿæ«·÷bjj'wû)i×¿r[`.split`/`)[x%13]+` of ${h[x/13|16]}s`

console.log (F(51))
```

Base64 version

```
eD0+KGg9YnRvYWBPCj9OGt578Wi6v8WK979KLH9J696f8SKCG382Kd79N6f8lpyT9C556f8qKeD8Bx7///+F5qu392Jqaid3+ylp179yW5tgLnNwbGl0YC9gKVt4JTEzXStgIG9mICR7aFt4LzEzfDE2XX1zYA==

```
> 3 votes

# Answer
# Octave, ~~155~~ ~~153~~ ~~151~~ 150 bytes

```
@(x)[strsplit(' of ,s,heart,diamond,spade,club,ace,two,three,four,five,six,seven,eight,nine,ten,jack,queen,king',','){[mod(x,13)+7,1,ceil(2+x/13),2]}]

```

Try it online!

This creates a string starting with `' of '` and `'s'`, then all the suits followed by all the ranks. This string is split at commas into separate strings. The suits are before the ranks, because since that saves a byte when creating the indices. After this, we index it using square brackets with the following indices:

```
{[mod(x,13)+7,1,ceil(2+x/13),2]}

```

which is the rank, followed by the first element `' of '`, followed by the suit, followed by `'s'`.

Having the `'s'` as part of the suits (`hearts,diamonds,spades,clubs`) instead of a separate string is the exact same length but less fun.

Splitting on the default separator  would save 4 bytes in the `strsplit`-call, but the spaces around `' of '` would be removed and would have to be added manually, costing more bytes.
> 2 votes

# Answer
## mIRCScript, 157 bytes

```
c echo $token(ace two three four five six seven eight nine ten jack queen king,$calc(1+$1% 13),32) of $token(clubs spades diamonds hearts,$calc(-$1// 13),32)

```

Load as an alias, then use: `/c N`. mIRC is 1-indexed, so floor division (//) on the negative value of the input produces -1 to -4 as required.
> 2 votes

# Answer
# PowerShell, 207 192 182 174 165 163 161 157 bytes

# 0-Indexed

```
$args|%{(-split'two three four five six seven eight nine ten jack queen king ace')[$_%13]+' of '+('hearts','diamonds','spades','clubs')[$_/13-replace'\..*']}

```

Try it online!

*4 bytes saved thanks to AdmBorkBork in the comments*
> 2 votes

# Answer
# , 154 147 144 142 Bytes

-7 Bytes thanks to DJMcMayhem

```
13i1heart
2diamond
3spade
4club
ÚGxCtwo
three
four
five
six
seven
eight
nine
ten
jack
queen
king
aceH$A of 012j$d4ñ13jPñÍ «/
{ÀjYHVGpAs

```

Try it online!

Hexdump:

```
00000000: 3133 6931 6865 6172 740a 3264 6961 6d6f  13i1heart.2diamo
00000010: 6e64 0a33 7370 6164 650a 3463 6c75 620a  nd.3spade.4club.
00000020: 1bda 1647 7843 7477 6f0a 7468 7265 650a  ...GxCtwo.three.
00000030: 666f 7572 0a66 6976 650a 7369 780a 7365  four.five.six.se
00000040: 7665 6e0a 6569 6768 740a 6e69 6e65 0a74  ven.eight.nine.t
00000050: 656e 0a6a 6163 6b0a 7175 6565 6e0a 6b69  en.jack.queen.ki
00000060: 6e67 0a61 6365 1b16 4824 4120 6f66 201b  ng.ace..H$A of .
00000070: 3016 3132 6a24 6434 f131 336a 50f1 cd20  0.12j$d4.13jP..
00000080: ab2f 200a 7bc0 6a59 4856 4770 4173       ./ .{.jYHVGpAs

```
> 2 votes

# Answer
# C#, 219 207 202 197 bytes (0 indexed)

```
static string O(int i){string[]s={"two","three","four","five","six","seven","eight","nine","ten","jack","queen","king","ace","hearts","diamonds","spades","clubs"};return s[i%13]+" of "+s[i/14+13];}

```

thanks to input from @Ciaran\_McCarthy and @raznagul

Takes an input of int I, subtracts 1 to match 0 indexing of the string array and outputs the number based on I mod 13 and the suit based on i/14+13.

works pretty well for my second code golf, just wondering if i could get it shorter using LINQ or something else.
> 2 votes

# Answer
# C (gcc), 148 bytes

```
f(n){printf("%.5s of %.7ss","two\0 threefour\0five\0six\0 seveneightnine\0ten\0 jack\0queenking\0ace"+n%13*5,"heart\0 diamondspade\0 club"+n/13*7);}

```

Try it online!

0-based.
> 2 votes

# Answer
# Haskell, 132 bytes

```
(!!)[v++" of "++s|s<-words"hearts diamonds spades clubs",v<-words"two three four five six seven eight nine ten jack queen king ace"]

```

Try it online!

An anonymous function, using list comprehension to build all the combinations of suit and value, and indexing into the resulting list with the input.
> 2 votes

# Answer
# F#, 174 168 bytes

Removed some extra whitespace as noted by Manish Kundu. Thanks!

```
let c x=["two";"three";"four";"five";"six";"seven";"eight";"nine";"ten";"jack";"queen";"king";"ace"].[(x-1)%13]+" of "+["hearts";"diamonds";"spades";"clubs"].[(x-1)/13]

```

Try it online!

I'll be honest - I'm new at code golf, so I don't know if it's more appropriate to answer with a pure function like this (with parameters, but no I/O) or with a working code block with user I/O.
> 2 votes

# Answer
# dc, ~~161~~ ~~160~~ ~~158~~ 142 bytes

```
[TWO][THREE][FOUR][FIVE][SIX][SEVEN][EIGHT][NINE][TEN][JACK][QUEEN][KING][ACE][HEART][DIAMOND][SPADE][CLUB][z2-:rz1<A]dsAxD~;rP[ OF ]PD+;rP83P

```

Try it online!

Over a year later, I was looking for something in my old golfs and found 16 bytes of inefficiency in the previous code:

```
[ACE][KING][QUEEN][JACK][TEN][NINE][EIGHT][SEVEN][SIX][FIVE][FOUR][THREE][TWO]0[d1+si:rlidD>A]dsAxr[CLUB]3:s[SPADE]2:s[DIAMOND]1:s[HEART]0:sD~;rP[ OF ]P;sP83P

```

Try that chunkier version online!

Top of stack used as input. 0-indexed.

In the old version, the array of ranks (`r`) was created using an iterator to run through the strings on the stack (`0[d1+si:rlidD>A]dsAxr`), but with only four items, it's shorter to manually assign the suits (`3:s`, etc.). The new version simply uses one array for all of it and also doesn't check against a fixed stack size. `[z2-:rz1<A]dsAx` replaces the above stack-crawler, popping everything into `r` at the position `(stack depth)-2`; it stops when there's one value left.

After all that setup is done, we divide by 13 leaving remainder & quotient on stack (`D~`). In the old version, we used these values to pick from the two arrays. In the new version, without a separate array of suits, we add 14 (`E+`) to the suit value, since our suits are after our ranks in array `r`. Print the strings, and print `OF` in the middle (`;rP[ OF ]PE+;rP`).

(First two golfs: -1 byte by outputting uppercase; this allows me to remove the 4 `s`es from the end of the suits, and instead print it via its ASCII value with the 3-byte `83P` at the end. -2 bytes because I repeatedly misread the challenge as requiring 1-indexing. Now 0-indexed.)
> 2 votes

# Answer
# CJam, 114 bytes

```
riDmd"two three four five six seven eight nine ten jack queen king ace"S/=" of "@"hearts diamonds spades clubs"S/=

```

Try it online!

Zero-indexed. Will probably be beaten by languages with dictionary compression, but oh well...
> 1 votes

# Answer
# Julia 0.6, 156 bytes

```
f(n)=print(split(" of ,hearts,diamonds,spades,clubs,two,three,four,five,six,seven,eight,nine,ten,jack,queen,king,ace",',')[[(n-1)%13+6,1,div(n-1,13)+2]]...)

```

Try it online!

-2 bytes thanks to @Stewie Griffin
> 1 votes

# Answer
# Jelly, 61 bytes

```
d13Uị"“¢¶/CŻ)Gụ+Ḷ}ċ<ʂḤaỴ£k7Ỵ€^ḥæ]¿9Ụ“¡¢|hḂṗƬßĖ,$ðĿȧ»Ḳ€¤j“ of

```

0-indexing. Try it online!
> 1 votes

# Answer
# Haskell, 144 bytes

```
f n=words"two three four five six seven eight nine ten jack queen king ace"!!(n`mod`13)++" of "++words"hearts diamonds spades clubs"!!(n`div`13)

```

Try it online!

This hits all kinds of Haskell's pain points.
> 1 votes

# Answer
# SOGL V0.12, 53 bytes

```
ķζ≡◄Τū┌p9P7šH□≡⅝'╗ΦqΖ▒ƨM.‘θ.wo"C█}y1+►ΚqΚ‘θJ¼ o.'⁰/wp

```

Try it Here!
> 1 votes

# Answer
## Javascript ~~149~~ ~~143~~ 140 bytes

```
a=_=>"two three four five six seven eight nine ten jack queen king ace".split` `[_%13]+' of '+["hearts","diamonds","spades","clubs"][_/13|0]

```

*-3 bits thanks to @rick hitchcock*

```
a=_=>"two three four five six seven eight nine ten jack queen king ace".split` `[_%13]+' of '+["hearts","diamonds","spades","clubs"][_/13|0]
console.log(a(14))
console.log(a(34))
console.log(a(51))
console.log(a(8))
console.log(a(24))
```
> 1 votes

# Answer
# Jelly, ~~58~~ 55 bytes

```
“ıĿ⁽⁷lg3e/“ẏ“£Ṣ¢÷yḊ⁾⁶ƭ⁼ẎẇḄṡ¿Onṃ⁶ḂḂfṠȮ⁻ẉÑ%»Ḳ€p/⁸ịṚj“ of

```

Try it online!
> 1 votes

# Answer
# Perl 5 `-p`, 119 bytes

0-based

```
$_=(TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,TEN,JACK,QUEEN,KING,ACE)[$_%13].' OF '.(HEART,DIAMOND,SPADE,CLUB)[$_/13].S

```

Try it online!
> 1 votes

# Answer
# Japt, ~~91~~ 86 bytes

0-indexed.

I used a tool written by @Shaggy to generate the compressed lists.

```
`{`twodÈ(‚fÆfivÀ£xç P ightdÍÂdÈˆjackdquÁÈkˆg»`qd gU}  {`Ê#tsk¹aÚˆäiÂ£kclubs`qk gUzD

```

Try it online!

## Explanation:

The first compressed string contains the card values delimited by `d`. The second compressed string contains the card ranks delimited by `k`.

These chars were picked using Shaggy's tool, which generates a string delimited by a char that is optimally compressed using shoco (the compression that Japt uses). This allows us to create a list of card values and ranks.

We use backticks ``` to decompress these strings, then we split the string using `q`, followed by the char to split on.

Once we have the lists, we map through the card values, then we get the index of the input. It is important to note that Japt wraps its indexes, so we don't have to modulo by 13.

At each item, we loop through the card ranks. We get the index by dividing the input by 13.

Once we have both items, we concatenate them with `" of "`, which produces the final string.
> 1 votes

# Answer
# Ruby, 124 bytes

```
->n{%w{two three four five six seven eight nine ten jack queen king ace}[n%13]+" of #{%w{heart diamond spade club}[n/13]}s"}

```

Try it online!

Zero indexed. Very straightforward.
> 1 votes

# Answer
# Pip `-s`, 114 bytes

<sup>Yay I tied CJam!</sup>

```
[("two three four five six seven eight nine ten jack queen king ace"^sa)"of"("heart diamond spade club"^sa/13).'s]

```

Uses 0-indexing. Try it online! Or, verify all inputs!
> 1 votes

# Answer
# Kotlin, 138 bytes

```
"two|three|four|five|six|seven|eight|nine|ten|jack|queen|king|ace".split("|")[i%13]+" of "+"hearts|diamonds|spades|clubs".split("|")[i/13]

```

## Beautified

```
"two|three|four|five|six|seven|eight|nine|ten|jack|queen|king|ace".split("|")[i%13]+" of "+"hearts|diamonds|spades|clubs".split("|")[i/13]

```

## Test

```
fun i(i:Int) =
"two|three|four|five|six|seven|eight|nine|ten|jack|queen|king|ace".split("|")[i%13]+" of "+"hearts|diamonds|spades|clubs".split("|")[i/13]
fun main(args: Array<String>) {
    for (i in (1..52)) {
        println(i(i))
    }
}

```

## TIO

TryItOnline
> 1 votes

# Answer
# QBasic, ~~190~~ 178 bytes

```
a$="ace  two  threefour five six  seveneightnine ten  jack queenking
b$="hearts  diamondsspades  clubs
INPUT i
?RTRIM$(MID$(a$,(i MOD 13)*5+1,5))+" of "+MID$(b$,((i-1)\13)*8+1,8)

```

As usual, @DLosc saved me some bytes. I should listen to my own advice more often.

Encoding all the text is expensive here...

**Explanation** of previous version, same principles still apply.

```
                ' String containing 13 card values - each position is 5 chars long
a$="ace  two  threefour five six  seveneightnine ten  jack queenking
b$(1)="hearts   ' Four card suits. Now it might look like these string lits
b$(2)="diamonds ' are not terminated, but that's because they aren't
b$(3)="spades   ' QBasic 4.5 auto-adds the quotes on a line break
b$(4)="clubs    ' (kinda like it also auto-expands ? to PRINT)
INPUT i         ' Take the base-1 index, and
?               ' PRINT
RTRIM$(         ' a string with all the spaces removed from the right end
MID$(a$,        ' of a substring of our card values
(i MOD 13)*5+1  ' starting at pos 0 (for the ace) through 12, * 5 (0, 5, 10 ... 60)
                ' + 1 (QBasic has 1-based strings)
,5))            ' and running for 5 characters
+" of "+        ' followed by " of " and
b$((i-1)\13+1)  ' the suit, taken from the array after int-divide op i

```
> 1 votes

# Answer
# Excel VBA, 138 bytes

An anonymous function that takes input from `[A1]` and outputs to `STDOUT`. `0` indexed.

```
?Split("Two Three Four Five Six Seven Eight Nine Ten Jack Queen King Ace")([A1]Mod 13)" of "Split("Hearts Diamonds Spades Clubs")([A1/13])

```
> 1 votes

# Answer
# Red, 176 bytes

```
func[n][i: 0
foreach s["hearts""diamonds""spades""clubs"][foreach c split{two three four five six seven eight nine ten jack queen king ace}" "[if n = i: i + 1[print[c"of"s]]]]]

```

Try it online!

As always, the facts that the indexing is 1-based in Red and the math expressions are always long because of the obligatory spaces, are the reasons not to use modulo in my solution.
> 0 votes

# Answer
# Charcoal, 78 bytes

```
§⪪”↶⌈=≔≡Ss←⊟✂sδ‴/﹪]7v1θ/✂eS'⌊D↔⎚Ｂ^#ïＧ⎚¦Ｊ←↥§”¶Ｉθ of §⪪”↶↧#σïＰ/Ｍ≡#↗÷⌕ρTM”¶÷Ｉθ¹³s

```

Try it online! Link is to verbose version of code. 0-indexed. Explanation:

```
  ”...”         Compressed string "two\nthree...king\ace"
 ⪪     ¶        Split on newlines
§       Ｉθ      Cyclically index on input cast to integer
                Implicitly print
 of             Literal string " of "
                Implicitly print
  ”...”         Compressed string "heart\ndiamond\nspade\nclub"
 ⪪     ¶        Split on newlines
         Ｉθ     Cast input to integer
        ÷  ¹³   Integer divide by 13
§               Index into list
                Implicitly print
s               Literal string "s"
                Implicitly print

```

Note: Without the limitation on suit ordering it can be done in 72 bytes:

```
Ｆ⪪”↶±″ς#₂g⎇¹αＦ+9r@c？×πλ¿BRu≦Zθx⊗Ｚj⊗✳Ｒ⦄ηs⊖▶fB‽⁺Ｐ4!⁶E~p↥Ｆºχβ｜»J↧H¦”¶§⪪ιyＩθ

```

Try it online! Link is to verbose version of code. Explanation:

```
  ”...”         Compressed string "twoy...yace\n of \nheartsy...yclubs"
 ⪪     ¶        Split on newlines
Ｆ               Loop over each element
         ⪪ιy    Split on literal string "y"
        §   Ｉθ  Cyclically index on input cast to integer
                Implicitly print

```
> 0 votes

# Answer
# Python 3, 157 bytes

```
lambda n:'two,three,four,five,six,seven,eight,nine,ten,jack,queen,king,ace'.split(',')[(n-1)%13]+' of '+['hearts','diamonds','spades','clubs'][int((n-1)/13)]

```

Try it online!
> 0 votes

# Answer
## Javascript 137 bytes

```
i=>"two,three,four,five,six,seven,eight,nine,ten,jack,queen,king,ace".split`,`[i%13]+` of ${["heart","diamond","spade","club"][0|i/13]}s`

```

```
f=

i=>"two,three,four,five,six,seven,eight,nine,ten,jack,queen,king,ace".split`,`[i%13]+` of ${["heart","diamond","spade","club"][0|i/13]}s`

console.log(f(38))
```
> 0 votes

# Answer
# ///, 460 bytes

```
/*/\/\///52/M!*51/L!*50/K!*49/J!*48/I!*47/H!*46/G!*45/F!*44/E!*43/D!*42/C!*41/B!*40/A!*39/M@*38/L@*37/K@*36/J@*35/I@*34/H@*33/G@*32/F@*31/E@*30/D@*29/C@*28/B@*27/A@*26/M#*25/L#*24/K#*23/J#*22/I#*21/H#*20/G#*19/F#*18/E#*17/D#*16/C#*15/B#*14/A#*13/M$*12/L$*11/K$*10/J$*9/I$*8/H$*7/G$*6/F$*5/E$*4/D$*3/C$*2/B$*1/A$*M/ace.*L/king.*K/queen.*J/jack.*I/ten.*H/nine.*G/eight.*F/seven.*E/six.*D/five.*C/four.*B/three.*A/two.*./ of *!/clubs*@/spades*#/diamonds*$/hearts/

```

Try it online!

The index of the card you want gets placed after the last `/`. I've left all indices in the TIO-link as a test suite. Also, because I've placed that test-suite in the Footer part of TIO, it adds a linebreak at the top.
> 0 votes

# Answer
# PHP 209 Bytes

No way this is the shortest, just a fun challenge.

```
<?php
 $a=$_GET['q'];$s=$a<53?'clubs':0;$s=$a<40?'spades':$s;$s=$a<27?'diamonds':$s;$s=$a<14?'hearts':$s;$v=$a%13;$v=$v==1?'ace':$v;$v=$v==11?'jack':$v;$v=$v==12?'queen':$v;$v=$v===0?'king':$v;echo "$v of $s";

```

Ungolfed

```
<?php
    $a=$_GET['q'];//input
    $s= $a<53?'clubs':0;//Ordered descending to overwrite extra positives, (prevent two checks per number like
    $s= $a<40?'spades':$s;//                                                                           a>=x>=b
    $s= $a<27?'diamonds':$s;
    $s= $a<14?'hearts':$s;

    $v=$a%13;
    $v = $v==1?'ace': $v;
    $v = $v==11?'jack': $v;
    $v = $v==12?'queen': $v;
    $v = $v===0?'king': $v;

    echo "$v of $s";

```
> 0 votes

# Answer
# Python 3, 143 bytes

```
s='hearts diamonds spades clubs two three four five six seven eight nine ten jack queen king ace'.split()
lambda n:f'{s[n%13+4]} of {s[n//13]}'

```
> 0 votes

# Answer
# PHP, ~~148~~ ~~137~~ 133 bytes

```
<?=[two,three,four,five,six,seven,eight,nine,ten,jack,queen,king,ace][($a=$argv[1])%13]." of ".[hearts,diamonds,spades,clubs][$a/13];

```

Try it online!

Zero based.
> 0 votes

# Answer
# T-SQL, 173 bytes

```
SELECT TRIM(SUBSTRING('two  threefour five six  seveneightnine ten  jack queenking ace'
 ,i%13*5+1,5))+' of '+TRIM(SUBSTRING('hearts  diamondsspades  clubs',i/13*8+1,8))FROM t

```

0-based input is taken via pre-existing table **t** with int field **i**, per our IO standards.

Saw the trick using string position and `TRIM` in Chronocidal's Excel answer, I'm using it to "look up" both the card value and the suit.

`TRIM()` is new to SQL 2017, prior to that add 2 characters for `RTRIM()` instead.
> 0 votes

# Answer
## Pyth, 104 bytes<sup>SBCS</sup>

```
jd[@c." X$¾k¼q}V©>##!Tâò°Ùisö÷¼ÞÊ?.Q \\v,X*nã¬ËÇè"d%Q13"OF"@cr." uô¶)BMÙ¼)|Ó¹MÃ"1d/Q13

```

Try it online!

**NOTE:** This code make use of unprintable characters which are not copy/paste-able from this post. The link provided leads to the correct version of the program, which *is* copy/paste-able.

0-indexed.

Python 3 translation:
```
Q=eval(input())
print(" ".join(["TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE TEN JACK QUEEN KING ACE".split()[Q%13],"OF","hearts diamonds spades clubs".upper().split()[Q//13]]))

```

A few oddities here and there due to Pyth's string compression deciding to just not work sometimes, but I managed to work around them.
> 0 votes

# Answer
# Yabasic, 186 bytes

An anonymous function that takes input, `n` and outputs to STDOUT. `0` indexed.

```
input""n
dim s$(13),t$(4)
k=Split("Two Three Four Five Six Seven Eight Nine Ten Jack Queen King Ace",s$())
k=Split("Hearts Diamonds Spades Clubs",t$())
?s$(Mod(n,13)+1)+" of "+t$(n/13+1)

```

Try it online!
> 0 votes

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


title: Find the 10-adic cube root of 3

text:
# Question
Title: Find the 10-adic cube root of 3
I like to think of a 10-adic number as a number that goes infinitely to the left, or an integer modulo a very very large power of 10.

Things carry infinitely to the left and vanish. To see what I mean, note that `...6667 * 3 = 1` in the 10-adic land, since the "2" that carries to the left goes to infinity.

Addition and multiplication make sense for 10-adic numbers, since the last `n` digits of the sum/product only depend on the last `n` digits of the summands/multiplicands.

---

Given `n`, you need to print the last `n` digits of the 10-adic cube root of 3, i.e. `x` satisfiying `x*x*x = 3`.

It ends:

```
...878683312291648481630318492665160423850087895134587

```

---

**Your code must terminate for `n=1000` before submission.**

Let's say that if the number you need to print begins with zero, then you don't need to print the leading zeroes, since it isn't actually the point to print extra zeroes.

---

This is . Shortest answer in bytes wins.

# Answer
> 28 votes
# Python 2, 33 bytes

```
lambda k:pow(3,10**k*2/3+1,10**k)

```

Try it online!

The `pow` function efficiently computes the modular exponent `3**(10**k*2/3+1)%10**k`.

We're asked to find a solution to `r**3 = 3 (mod 10**k)`. We want to find an exponent `e` for which the map `x -> x**e` is inverse to cubing `x -> x**3` working mod `10**k`, just as the decryption and encryption exponents in RSA cancel to produce the original value. This means that `(x**3)**e = x (mod 10**k)` for all `x`. (We'll assume throughout that `gcd(x,10) = 1`.) Then, we can recover `r` by inverting the cubing to get `r = 3**e (mod 10**k)`.

Expanding out `(r**3)**e = r (mod 10**k)`, we get

```
r**(3*e-1) = 1 (mod 10**k)

```

We're looking for an exponent `3*e-1` that guarantees that multiplying that many copies gives us `1`.

Multiplication modulo `10**k` forms a group for invertible numbers, that is those with `gcd(x,10) = 1`. By Lagrange's Theorem, `x**c = 1` where `c` is the count of elements in the group. For the group modulo `N`, that count is the Euler totient value `φ(N)`, the number of values from `1` to `N` that are relatively prime to `N`. So, we have `r**φ(10**k) = 1 (mod 10**k)`. Therefore, its suffices for `3*e-1` to be a multiple of `φ(10**k)`.

We compute

```
φ(10**k) = φ(5**k) φ(2**k)= 4 * 5**(k-1) * 2**(k-1) = 4 * 10**(k-1)`

```

So, we want `3*e-1` to be a multiple of `4 * 10**(k-1)`

```
3*e - 1 = r * 4 * 10**(k-1)
e = (4r * 10**(k-1) + 1)/3

```

Many choices are possible for `r`, but `r=5` gives the short expression

```
e = (2 * 10**k + 1)/3

```

with `e` a whole number. A little golfing using floor-division shortens `e` to `10**k*2/3+1`, and expressing `r = 3**e (mod 10**k)` gives the desired result `r`.

# Answer
> 20 votes
# Python 2 (PyPy), ~~55~~ 50 bytes

-5 bytes thanks to @H.P. Wiz!

```
n=p=1;exec"p*=10;n+=3*(3-n**3)%p;"*input();print n

```

Try it online!

Calculates (non-bruteforcing) digit by digit, so it's faster than brute force.

Version without exec

### Explanation

(Thanks @Leaky Nun and @user202729 for figuring this out)

First, observe that \\$n^3\\$ is an involution modulo 10 (i.e. if the function is called \\$f\\$, then \\$f(f(n)) = n\\$). This can be confirmed using an exhaustive search.

We can use mathematical induction to find the next digit.
Let \\$d\_n\\$ be the \\$n\\$th digit of the number (from the right).

$$ \begin{align\*} d\_1^3 &\equiv 3 &&\pmod{10} \\ d\_1 &\equiv 3^3 &&\pmod{10} \\ &\equiv 27 &&\pmod{10} \\ &\equiv 7 &&\pmod{10} \\ \end{align\*} $$

Now, assume we know the number up to the \\$k\\$th digit, \\$x\\$

$$ \begin{align\*} x^3 &\equiv 3 &&\pmod{10} \\ (d\_{k+1} \cdot 10^k + x)^3 &\equiv 3 &&\pmod{10} \\ m \cdot 10^{2k} + 3 \cdot d\_{k+1} x^2 \cdot 10^k + x^3 &\equiv 3 &&\pmod{10^{k+1}} \\;\textrm{(for some } m \textrm{)} \\ 3 \cdot d\_{k+1} x^2 \cdot 10^k + x^3 &\equiv 3 &&\pmod{10^{k+1}} \\ \end{align\*} $$

We know that:

$$ \begin{align\*} x &\equiv 7 &&\pmod{10} \\ x^2 &\equiv 49 &&\pmod{10} \\ &\equiv 9 &&\pmod{10} \\ x^2 \cdot 10^k &\equiv 9 \cdot 10^k &&\pmod{10^{k+1}} \\ 3 \cdot x^2 \cdot 10^k &\equiv 27 \cdot 10^k &&\pmod{10^{k+1}} \\ &\equiv 7 \cdot 10^k &&\pmod{10^{k+1}} \\ \end{align\*} $$

Substituting this in:

$$ \begin{align\*} 3 \cdot d\_{k+1} x^2 \cdot 10^k + x^3 &\equiv 3 &&\pmod{10^{k+1}} \\ 7 \cdot d\_{k+1} \cdot 10k + x^3 &\equiv 3 &&\pmod{10^{k+1}} \\ d\_{k+1} &\equiv \frac{3 - x3}{7 \cdot 10^k} &&\pmod{10} \\ \therefore d\_{k+1} &\equiv \frac{3 \cdot \left(3 - x^3\right)}{10^k} &&\pmod{10} \\; (7^{-1} \equiv 3 \pmod{10}) \end{align\*} $$

# Answer
> 7 votes
# Wolfram Language (Mathematica), 21 bytes

```
PowerMod[3,1/3,10^#]&

```

Try it online!

# Answer
> 5 votes
# 05AB1E, ~~17~~ 13 bytes

```
7IGD3mN°÷7*θì

```

Port of *@ASCII-only*'s Python 2 (PyPy) answer.
-4 bytes AND bug-fixed for outputs with leading zeros thanks to *@Emigna*, by replacing `T%N°*+` with `θì`.

Try it online.

**Explanation:**

```
7               # Start result-string `r` at '7'
IG              # Loop `N` in the range [1, input)
  D3m           #  `r` to the power 3
       ÷        #  Integer-divided with
     N°         #  10 to the power `N`
        7*      #  Multiplied by 7
          θì    #  Then take the last digit of this, and prepend it to the result `r`
                # Implicitly output result `r` after the loop

```

# Answer
> 4 votes
# Java (JDK 10), 106 bytes

```
n->n.valueOf(3).modPow(n.valueOf(2).multiply(n=n.TEN.pow(n.intValue())).divide(n.valueOf(3)).add(n.ONE),n)

```

Try it online!

## Credits

# Answer
> 4 votes
# Java 8, ~~158~~ ~~156~~ ~~141~~ ~~136~~ 135 bytes

```
n->{var t=n.valueOf(3);var r=n.ONE;for(int i=0;i++<n.intValue();)r=r.add(t.subtract(r.pow(3)).multiply(t).mod(n.TEN.pow(i)));return r;}

```

Port of *@ASCII-only*'s Python 2 (PyPy) answer.
-2 bytes thanks to *@Neil*.
-20 bytes thanks to *@ASCII-only*.

NOTE: There is already a much shorter Java answer by *@OlivierGrégoire* using an algorithmic approach utilizing `modPow`.

Try it online.

**Explanation:**

```
n->{                            // Method with BigInteger as both parameter and return-type
  var t=n.valueOf(3);           //  Temp BigInteger with value 3
  var r=n.ONE;                  //  Result-BigInteger, starting at 1
  for(int i=0;i++<n.intValue();)//  Loop `i` in the range [1, n]
    r=r.add(                    //   Add to the result-BigDecimal:
       t.subtract(r.pow(3))     //    `t` subtracted with `r` to the power 3
       .multiply(t)             //    Multiplied by 3
       .mod(n.TEN.pow(i)));     //    Modulo by 10 to the power `i`
  return r;}                    //  Return the result-BigInteger

```

# Answer
> 3 votes
# Haskell, 37 bytes

1 byte saved thanks to ASCII-only!

```
(10!1!!)
n!x=x:(n*10)!mod(9-3*x^3+x)n

```

Try it online!

I use a similar approach to ASCII-only, but I avoid using division

# Answer
> 2 votes
# dc, 15

```
3?Ar^d2*3/1+r|p

```

Uses modular exponentiation, like @xnor's answer.

Try it online!

TIO calculates input=1000 in 21s.

# Answer
> 2 votes
# Pyth, 12

```
.^3h/y^TQ3^T

```

Try it online!

Again, using modular exponentiation, like @xnor's answer.

# Answer
> 1 votes
# Pyth, 23 bytes

Of course, this uses ASCII-only's approach.

```
K7em=+K*%*7/^K3J^TdTJtU

```

Try it here!

# Answer
> 1 votes
# Charcoal, ~~26~~ 22 bytes

```
≔⁷ηＦＮ≧⁺﹪×³⁻³Ｘη³Ｘχ⊕ιηＩη

```

Try it online! Link is to verbose version of code. Explanation:

```
≔⁷η

```

Initialise the result to 7. (Doesn't have to be 7, but 0 doesn't work.)

```
ＦＮ

```

Loop over the number of required digits.

```
        η       Current result.
       Ｘ ³     Take the cube.
     ⁻³         Subtract from 3.
   ×³           Multiply by 3.
            ⊕ι  Increment the loop index.
          Ｘχ    Get that power of 10.
  ﹪             Modulo
≧⁺            η Add to the result.

```

Now uses @H.P.Wiz's approach to save 4 bytes.

```
Ｉη

```

Print the result.

Here's a 28-byte brute-force version that takes cube roots of arbitrary values:

```
ＦＮ⊞υ⊟Φχ¬﹪⁻ＸＩ⁺κ⭆⮌υμ³ＩηＸχ⊕ι↓Ｉυ

```

Try it online! Link is to verbose version of code. First input is number of digits, second is value to root.

# Answer
> 1 votes
# , 33 bytes

```
f=:3 :'((10x^y)|]+3*3-^&3)^:y 1x'

```

TIO

port of @ASCII-only's answer but using fixed modulo 10^n throughout

# Answer
> 0 votes
# Jelly, ~~23~~ ~~18~~ 17 bytes

```
*3:×7DṪ×+⁸
R⁵*çƒ7

```

Try it online!

I know `ƒ` will be useful.

---
Tags: code-golf, number-theory
---


title: Hand patterns in a card game

text:
# Question
Title: Hand patterns in a card game
A deck of cards is the Cartesian product of `S` suits and `R` ranks. Many, though not all, card games use `S=4` and `R∊{6,8,13}`. A hand of `H` cards is dealt from the deck. Its *distribution*, a.k.a. "hand pattern", is an array that describes how many cards you got from each suit, ignoring suit order (so, it's like a multi-set). Given a distribution `D` satisfying `len(D)=S`, `1≤sum(D)=H≤S×R`, `0≤D[i]≤R`, `D[i]≥D[i+1]`, find the probability of it occurring.

Input: an integer `R` and an array `D`.

Output: the probability with at least 5 digits after the decimal mark; trailing zeroes may be skipped; scientific notation is ok.

Loopholes forbidden. Shortest wins.

Tests:

```
R    D               probability
13   4 4 3 2     ->  0.2155117564516334148528314355068773
13   5 3 3 2     ->  0.1551684646451760586940386335649517
13   9 3 1 0     ->  0.0001004716813294328274372174524508
13   13 0 0 0    ->  0.0000000000062990780897964308603403
8    3 2 2 1     ->  0.4007096203759162602321667950144035
8    4 2 1 1     ->  0.1431105787056843786543452839337155
8    2 2 1 0     ->  0.3737486095661846496106785317018910
8    3 1 1 0     ->  0.2135706340378197997775305895439377
15   4 4 3 2 1   ->  0.1428926269185580521441708109954798
10   3 0 0       ->  0.0886699507389162561576354679802956
10   2 1 0       ->  0.6650246305418719211822660098522167
10   1 1 1       ->  0.2463054187192118226600985221674877

```

See also Bridge hand patterns in Wikipedia.

EDIT: dropped unnecessary restriction `H≤R`

EDIT: added constraint `H≥1`

# Answer
> 9 votes
# APL (Dyalog Unicode), 30 chars

```
×/!⍨,z,1÷((z←!∘≢⊢)⌸⊢),×∘≢!⍨1⊥⊢

```

Try it online!

Using @orlp’s formula.

# Answer
> 8 votes
# Python 3, 134 bytes

```
b=lambda n,k:k<1or n*b(n-1,k-1)/k
f=lambda R,D,i=1,s=1,t=0:D and b(R,D[0])*i/s*f(R,D[1:],i+1,(D[0]in D[1:])*s+1,t+D[0])or 1/b(~-i*R,t)

```

Formula is the product of `binom(R, d)` for each element `d` in `D`, times `factorial(len(D))`, divided by the product of `factorial(len(S))` for each `S` in the groupings of `D` (e.g. `[4, 4, 3, 2]` has groupings `[[4, 4], [3], [2]]`), finally divided by `binom(len(D) * R, sum(D))`.

Or in math notation, assuming **m** contains the multiplicities of the **n** unique elements in **D**:

$$ \frac{|D|!}{m\_1!\cdot m\_2!\cdots m\_n!} \binom{|D|\cdot R}{\sum D}^{-1} \prod\_{d\in D}\binom{R}{d} $$

# Answer
> 7 votes
# , ~~90~~ ~~85~~ 83 bytes

```
function(R,D,l=sum(D|1),K=choose)prod(K(R,D),1:l,1/gamma(1+table(D)))/K(R*l,sum(D))

```

Try it online!

I observed the same thing as orlp, but I picked a nice language that has combinatorics builtins.

Explanation:

```
function(R,D,             # next are optional arguments
 l=sum(D|1),              # alias for length of D, aka S
 K=choose)                # alias for choose
  prod(                   # take the product of:
    K(R,D),               # "choose" is vectorized over R and D
    1:l,                  # S!
    1/gamma(1+            # gamma(n+1) = n! for integer n
     table(D))            # multiplicities of unique elements of D
  ) /                     # divide by
  K(R`*`l, sum(D))          # R`*`S choose H
                          # return last computation (which is all the computation)

```

# Answer
> 6 votes
# Jelly,  ~~22~~  20 bytes

-2 bytes using a new quick, `ʋ`, and a new monadic atom

```
ĠẈ!;L×c⁸S¤ʋ
L!;c@÷çP

```

A dyadic link, taking the dealt-distribution, D, on the left and the number-of-ranks, R, on the right, which returns the probability of occurrence.

**Try it online!** or see the test-suite

### How?

```
ĠẈ!;L×c⁸S¤ʋ - Link 1, denomParts: list, distribution (D); number, ranks (R)
                                                                 e.g. [3,3,3,2,2]; 8
Ġ           - group indices of D by their values                      [[4,5],[1,2,3]]
 Ẉ          - length of each group                                    [2,3]
  !         - factorial (vectorises)                                  [2,6]
          ʋ - last four links as a dyad
            - ... i.e. totalWaysToDeal = f(list, distribution (D); number, ranks (R)):
    L       - length of D                                             5
     ×      - multiply by R = total number of cards                   40
         ¤  - nilad followed by link(s) as a nilad:
       ⁸    -   chain's left argument, D                              [3,3,3,2,2]
        S   -   sum = total cards dealt                               13
      c     - binomial                                        40C13 = 12033222880
   ;        - concatenate                                             [2,6,12033222880]

L!;c@÷çP - Main link: list, distribution (D); number, ranks (R)
         -                                                  e.g. [3,3,3,2,2]; 8
L        - length of D = number of suits                         5
 !       - factorial                                             120
   c@    - R binomial (vectorised across) D     (8C3=56;8C2=28)  [56,56,56,28,28]
  ;      - concatenate                                           [120,56,56,56,28,28]
      ç  - call the last link (1) as a dyad = denomParts(D,R)    [2,6,12033222880]
     ÷   - divide (vectorises)                                   [120/2,56/6,56/12033222880,56,28,28]
       P - product                                               0.11441900924883391

```

# Answer
> 5 votes
# 05AB1E, 21 bytes

```
cP¹g!*¹γ€g!P¹gI*¹Oc*/

```

Try it online!

**Explanation**

```
 P                      # product of
c                       # bin(input1,input2)
     *                  # multiplied by
    !                   # fac of
  ¹g                    # length of input1
                    /   # divided by
           P            # product of
          !             # fac of each
        €g              # length of each
      ¹γ                # chunk of consecutive equal elements of input1
                   *    # multiplied by
                  c     # bin of
            ¹g          # length of input1
              I*        # times input2
                ¹O      # and sum of input1

```

# Answer
> 3 votes
# Pyth, 32 bytes

```
cc*.!lQ*F.cLvzQ*F.!hMr8Q.c*vzlQs

```

**Try it here!** or **Verify all the test cases!**

### How this works?

```
cc*.!lQ*F.cLvzQ*F.!hMr8Q.c*vzlQs ~ Full program. D = list, R = number.

   .!                            ~ The factorial of...
     lQ                            ~ The length of D.
  *                              ~ Multiplied by...
       *F                          ~ The product of the elements of...
         .c                          ~ The nCr between...
           L  Q                        ~ Each element of D, and...
            vz                         ~ R.
 c                               ~ Divided by...
               *F                  ~ The product of the elements of...
                 .!                  ~ The factorial of each...
                   hM                  ~ Heads. Count of adjacent elements in...
                     r8Q                 ~ The run length encoding of D.
c                                ~ Divided by...
                        .c         ~ The nCr between...
                          *          ~ The product of...
                           vz          ~ R, and...
                             lQ        ~ The length of D.
                               s   ~ And the sum of D.
                                 ~ Output implicitly.

```

# Answer
> 3 votes
# APL (Dyalog), 42 bytes

```
{×/(!≢⍵),(⍵!⍺),÷((+/⍵)!⍺×≢⍵),!≢¨⍵⊂⍨1,2≠/⍵}

```

Try it online!

Still golfing.

# Answer
> 2 votes
## Clojure, 153 bytes

```
#(apply +(for[_(range 1e06):when(=(remove #{0}%)(reverse(sort(vals(frequencies(take(apply + %)(shuffle(for[i(range %2)j(range(count %))]j))))))))]1e-06))

```

Just a brute-force simulation, to get more precision increase the iteration count and the "1 / N" value at the end accordingly. First argument is the counts and 2nd argument is the number of cards in the deck per suite.

# Answer
> 2 votes
# J, 57 bytes

```
](#@]%~[:+/[-:"1[:\:~@(#/.~)"1+/@[{."1])i.@!@(*+/)A.(##\)

```

Try it online!

This runs in *O(golf)* and will choke on many of the test cases (though works theoretically), which would be fine if it were golfier. But I'm stuck on trimming it down, especially with avoiding those repeated `"1`. If anyone wants to help, here's the parsed version...

The right side of the main fork is all possible deals of the *deck*, and the left side of the main fork is just the original right arg, ie, the suit mask we're matching against.

Inside, from each "shuffled" deck, we take the first *hand* elements, then group them using key `/.` and sort the result, and check if that matches the suit mask in question. We add add up the total number that do match, and divide that into the length of all possible decks.

```
┌─┬─────────────────────────────────────────────────────────────────────────────────────────────────┬─────────────────────────────────────┐
│]│┌───────┬─────┬─────────────────────────────────────────────────────────────────────────────────┐│┌──────────────────────┬──┬─────────┐│
│ ││┌─┬─┬─┐│┌─┬─┐│┌──┬─────┬──────────────────────────────────────────────────────────────────────┐│││┌────────┬─┬─────────┐│A.│┌─┬─────┐││
│ │││#│@│]│││%│~│││[:│┌─┬─┐│┌─┬────────┬─────────────────────────────────────────────────────────┐│││││┌──┬─┬─┐│@│┌─┬─────┐││  ││#│┌─┬─┐│││
│ ││└─┴─┴─┘│└─┴─┘││  ││+│/│││[│┌──┬─┬─┐│┌──┬───────────────────────────┬────────────────────────┐│││││││i.│@│!││ ││*│┌─┬─┐│││  ││ ││#│\││││
│ ││       │     ││  │└─┴─┘││ ││-:│"│1│││[:│┌─────────────────────┬─┬─┐│┌───────────┬────────┬─┐│││││││└──┴─┴─┘│ ││ ││+│/││││  ││ │└─┴─┘│││
│ ││       │     ││  │     ││ │└──┴─┴─┘││  ││┌──────┬─┬──────────┐│"│1│││┌─────┬─┬─┐│┌──┬─┬─┐│]││││││││        │ ││ │└─┴─┘│││  │└─┴─────┘││
│ ││       │     ││  │     ││ │        ││  │││┌──┬─┐│@│┌──────┬─┐││ │ ││││┌─┬─┐│@│[│││{.│"│1││ ││││││││        │ │└─┴─────┘││  │         ││
│ ││       │     ││  │     ││ │        ││  ││││\:│~││ ││┌─┬──┐│~│││ │ │││││+│/││ │ ││└──┴─┴─┘│ │││││││└────────┴─┴─────────┘│  │         ││
│ ││       │     ││  │     ││ │        ││  │││└──┴─┘│ │││#│/.││ │││ │ ││││└─┴─┘│ │ ││        │ ││││││└──────────────────────┴──┴─────────┘│
│ ││       │     ││  │     ││ │        ││  │││      │ ││└─┴──┘│ │││ │ │││└─────┴─┴─┘│        │ ││││││                                     │
│ ││       │     ││  │     ││ │        ││  │││      │ │└──────┴─┘││ │ ││└───────────┴────────┴─┘│││││                                     │
│ ││       │     ││  │     ││ │        ││  ││└──────┴─┴──────────┘│ │ ││                        │││││                                     │
│ ││       │     ││  │     ││ │        ││  │└─────────────────────┴─┴─┘│                        │││││                                     │
│ ││       │     ││  │     ││ │        │└──┴───────────────────────────┴────────────────────────┘││││                                     │
│ ││       │     ││  │     │└─┴────────┴─────────────────────────────────────────────────────────┘│││                                     │
│ ││       │     │└──┴─────┴──────────────────────────────────────────────────────────────────────┘││                                     │
│ │└───────┴─────┴─────────────────────────────────────────────────────────────────────────────────┘│                                     │
└─┴─────────────────────────────────────────────────────────────────────────────────────────────────┴─────────────────────────────────────┘

```

---
Tags: code-golf, combinatorics, probability-theory, card-games
---


title: Pair and sort from two integer lists

text:
# Question
Title: Pair and sort from two integer lists
You are given two arbitrary integer lists, e.g. `[-10, 99, -6, 43]`, `[100, 32, 44]`. You are to pick one integer from each list and sum them up, then sort the best pairs ordered by the absolute distance to 100 in ascending order. Paired up integers from each list shall not be repeated in the output.

For instance, we have

| Pair | Calculation | Absolute distance from 100 |
| --- | --- | --- |
| (-10, 100) | 100 - (-10 + 100) | = 10 |
| (-10, 32) | 100 - (-10 + 32 ) | = 78 |
| (-10, 44) | 100 - (-10 + 44 ) | = 66 |
| (99, 100) | 100 - (99 + 100 ) | = 99 |
| (99, 32 ) | 100 - (99 + 32 ) | = 31 |
| (99, 44 ) | 100 - (99 + 44 ) | = 43 |
| (-6, 100) | 100 - (-6 + 100 ) | = 6 |
| (-6, 32 ) | 100 - (-6 + 32 ) | = 74 |
| (-6, 44 ) | 100 - (-6 + 44 ) | = 62 |
| (43, 100) | 100 - (43 + 100 ) | = 43 |
| (43, 32 ) | 100 - (43 + 32 ) | = 25 |
| (43, 44 ) | 100 - (43 + 44 ) | = 13 |

After pairing with the first item `-10`, it is tempted to pick the pair `(-10, 100)` as the best pair as it has the least distance to 100. But further checking down the list, `(-6, 100)` in fact has a lesser distance to 100, hence it should be the best pair picked. After picking the pair, they are removed from their lists, leaving us

| Pair | Calculation | Absolute distance from 100 |
| --- | --- | --- |
| (-10, 32) | 100 - (-10 + 32) | = 78 |
| (-10, 44) | 100 - (-10 + 44) | = 66 |
| (99, 32 ) | 100 - (99 + 32 ) | = 31 |
| (99, 44 ) | 100 - (99 + 44 ) | = 43 |
| (43, 32 ) | 100 - (43 + 32 ) | = 25 |
| (43, 44 ) | 100 - (43 + 44 ) | = 13 |

Then next pair to pick will be `(43, 44)`. Notice that the distance to 100 is 13 for this pair, which is higher than the pair `(-10, 100)`, but only because `100` has been paired with `-6` and hence the pair `(-10, 100)` is gone. Moving on, we have these remaining

| Pair | Calculation | Absolute distance from 100 |
| --- | --- | --- |
| (-10, 32) : | 100 - (-10 + 32) | = 78 |
| (99, 32 ) : | 100 - (99 + 32 ) | = 31 |

And finally `(99, 32)` is picked. Hence the output `(-6, 100), (43, 44), (99, 32)`. Ignore the rest that have nothing to pair up.

*Note: when there is a tie, just pick any pair, without worrying the consequence to the remaining candidates.*

The challenge here is to complete the task with the least number of comparisons operating on the inputs. i.e. if all comparison result has to come from a function `comp(a, b)`, then the least number of call to this function wins. Looping control etc. are not included. Three way comparison is essentially 2 operations. General purpose code only and no special purpose optimisation is required. Favour code that can verify the number of comparison calls, however, when using build in functions, please explain their complexity for us to examine.

# Answer
## Python O(mn log mn)

The best pairs can be found computing the distances of all the possible pairs, and iteratively choosing the best pair among those remaining after filtering out the already chosen items.

A simple implementation is shown in the following code:

```
def find_nearest_pairs_to_100(l, m):
    pair_list = sorted([((i, j), abs(100 - i - j)) for i in l for j in m], key=lambda x: x[1])
    chosen_pairs = []
    while pair_list:
        best_pair = pair_list[0][0]
        chosen_pairs.append(best_pair)
        pair_list = [(p, s) for (p, s) in pair_list if p[0] != best_pair[0] and p[1] != best_pair[1]]
    return chosen_pairs

```

The `find_nearest_pairs_to_100` function takes the two lists in input and returns an ordered list with the chosen pairs.

The `sorted` function in Python is based on Timsort algorithm, that requires O(n log n) comparisons in the worst case (where n is the length of the list).

In this case the length of the list is the cardinality of the Cartesian product of the two input lists, i.e. mn (with n \> m). Therefore, the total cost of this implementation is of O(mn log mn) comparisons, excluding the other comparison operations needed for filtering.

Including comparisons for filtering, at each iteration, in the worst case, all the items of the list are checked against the elements of the chosen pair; the length the `pair_list` is mn at the first iteration, (n-1)(m-1) at the second, (n-2)(m-2) at the third, and n-m+1 at the last step. So the total number of comparisons for filtering is O(n^3).

If you like golfing, it is a golfed version (163 bytes) of the previous one (a little bit different):

```
f=lambda l,m:l and m and[[k]+f(l.remove(k[0])or l,m.remove(k[1])or m)for k in sorted([[[[i,j]],abs(100-i-j)]for i in l for j in m],key=lambda x:x[1])[0][0]][0]or[]

```
> 3 votes

---
Tags: number, code-challenge, sequence, arithmetic, sorting
---


title: Convert xxd output to shellcode

text:
# Question
Title: Convert xxd output to shellcode
Taking some output from xxd and turning it into usable shellcode by hand is no fun, so your job is to automate the process.

**Rules**

Your submission can be a function, lambda, script, or any reasonable equivalent of those. You may print the result, or if your submission is a function/lambda then you may also return it.

You program must take three arguments, the first being a string containing the output of xxd, ran with no arguments other than a filename, like this: `xxd some_file`. Here's an example of what the the first argument will look like:

```
00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088  1..F1.1.....[1..
00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c  C..[..C....K..S.
00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58  ......./bin/shNX
00000030: 5858 5859 5959 59                        XXXYYYY

```

Your need to take that middle section containing the bytes (the first 8 columns after the `:`) and turn it into shellcode by removing any whitespace, then putting a `\x` before each byte.

Here's what the output should be for the input above (ignoring any other arguments):

`\x31\xc0\xb0\x46\x31\xdb\x31\xc9\xcd\x80\xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x4e\x58\x58\x58\x58\x59\x59\x59\x59`

You can assume the first argument will always be a valid xxd output, ran with no arguments other than the filename.

Your output should also be a string where the backslashes are literal backslashes, not used as escape characters. So when I say "\x65", I'm not talking about the byte 0x65, or even the letter "A". In code, it would be the string "\x65".

The second argument specifies where in the xxd output the shellcode should start, and the third specifies where it should end. If the third argument is `-1`, it will end at the end of xxd output. The second and third argument will also always be non negative, except for when the third is `-1`

Here are some test cases:

Argument 1:

```
00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088  1..F1.1.....[1..
00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c  C..[..C....K..S.
00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58  ......./bin/shNX
00000030: 5858 5859 5959 59                        XXXYYYY

```

Argument 2: `7`, Argument 3: `e` (these are both strings representing hexadecimal numbers)

Output: `\xc9\xcd\x80\xeb\x16\x5b\x31\xc0`

Argument 1:

```
00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088  1..F1.1.....[1..
00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c  C..[..C....K..S.
00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58  ......./bin/shNX
00000030: 5858 5859 5959 59                        XXXYYYY

```

Argument 2: `0`, Argument 3: `2e`

Output: `\x31\xc0\xb0\x46\x31\xdb\x31\xc9\xcd\x80\xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x4e`

Argument 1:

```
00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088  1..F1.1.....[1..
00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c  C..[..C....K..S.
00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58  ......./bin/shNX
00000030: 5858 5859 5959 59                        XXXYYYY

```

Argument 2: `a`, Argument 3: `-1`

Output: `\xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x4e\x58\x58\x58\x58\x59\x59\x59\x59`

The code with the least bytes wins. The winner will be announced in seven days, on August 15, 2016 (but submissions after then are still appreciated).

**Update**

Congrats to @Adnan to winning the challenge!

# Answer
> 5 votes
# 05AB1E, ~~39~~ 38 bytes

Input in the form:

```
arg2
arg3
arg1

```

Code:

```
²\|vy9F¦}40£ðK}J2ô„\xì²H>²®Qi²}£¹HF¦}J

```

Explanation:

```
²\                                       # Get the first two inputs and discard them.
  |                                      # Take the rest of the input as an array.
   vy         }                          # For each line...
     9F¦}                                #   Ten times, remove the first character.
         40£                             #   Only remain the substring [0:40].
            ðK                           #   Remove spaces.
               J                         # Join the string.
                2ô                       # Split into pieces of 2.
                  „\xì                   # Prepend a "\x" at each string.
                      ²H                 # Convert the second line from hex to int.
                        >                # Increment by one.
                         ²               # Push the second input again.
                          ®Qi }          # If equal to -1...
                             ²           #   Push the second input again.
                               £         # Take the substring [0:(² + 1)].
                                ¹H       # Convert the first input from hex to int.
                                  F¦}    # Remove that many characters at the beginning.
                                     J   # Join the array and implicitly output.

```

Uses the **CP-1252** encoding. Try it online!.

# Answer
> 12 votes
# Bash + coreutils + xxd, ~~73~~ ~~71~~ 69 bytes

```
printf \\x%s `xxd -r|xxd -p -s0x$1 -l$[(e=1+0x$2)?e-0x$1:-1]|fold -2`

```

Expects the hexdump on STDIN and start/end as command-line arguments.

This prints some warnings to STDERR, which is allowed by default.

# Answer
> 5 votes
# Ruby: ~~90~~ ~~89~~ ~~87~~ ~~79~~ 63 bytes

-2 bytes thanks to @addison
-8 bytes thanks to @PiersMainwaring

```
->s,x,y{'\x'+s.scan(/(?<=.{9})\w\w(?=.* )/)[x.hex..y.hex]*'\x'}

```

See the tests on repl.it: https://repl.it/Cknc/5

# Answer
> 5 votes
## JavaScript, 84 bytes

```
(s,f,t,u)=>s.replace(/.*:|  .*\n?| /g,'').replace(/../g,'\\x$&').slice(f*4,++t*4||u)

```

Explanation: Removes all the unwanted parts of the dump, prepends `\x` to each hex pair, then extracts the desired portion of the result. `||u` is used to convert the zero obtained by incrementing the `-1` parameter into `undefined` which is a magic value that causes `slice` to slice to the end of the string. 101 bytes if `f` and `t` are strings of hex digits:

```
(s,f,t,u)=>s.replace(/.*:|  .*\n?| /g,``).replace(/../g,`\\x$&`).slice(`0x${f}`*4,t<0?u:`0x${t}`*4+4)

```

# Answer
> 4 votes
# Jelly, ~~48~~ 44 bytes

```
ØhiÐ€ɠ’ḅ¥®L’¤Ạ?⁴‘
ṣ⁷ṫ€⁵ḣ€40Fḟ⁶s©2ḣ¢ṫ¢[“\x”]p

```

This expects the hexdump as sole command-line argument, and the end and start points on STDIN, in that order, separated by a linefeed.

Try it online!

# Answer
> 3 votes
## PowerShell v2+, ~~175~~ ~~157~~ ~~142~~ ~~133~~ 129 bytes

```
param($a,$b,$c)'\x'+(($z=$a-split"`n"|%{$_[10..48]-ne32-join''-split'(..)'-ne''})["0x$b"..(("0x$c",$z.count)[$c-eq-1])]-join'\x')

```

Takes input `$a`, `$b`, `$c`, with `$a` as either a literal newline-separated string, or with the PowerShell ``n` character separating the lines. We set helper string `$z` as the heavily processed `$a` as follows --

First we `-split` on newlines, then, for each line `|%{...}`, we slice the middle section `[10..48]`, use the `-ne32` to remove spaces, `-join` it back together into one long string, `-split` it on every two characters (keeping the two characters), and `-ne''` to remove the empty elements. This results in an array of two-element strings, like `('31','c0','b0'...)`.

We then slice into that array based on `$b` cast with the hexadecimal operator up to the value of `$c`. We need to use a pseudo-ternary here that accounts for whether `$c` is `-1` or not. If it is, we choose the `.count` (i.e., the end element) of `$z`. Otherwise, we just prepend the `0x` hexadecimal operator with `$c` in a string. Note that this is zero-indexed.

That array slice has its elements `-join`ed together with a literal `\x` to form one string. That's prepended with another literal `\x` and the result is left on the pipeline. Printing is implicit.

### Example

```
PS C:\Tools\Scripts\golfing> .\xxd-output.ps1 "00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088  1..F1.1.....[1..
00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c  C..[..C....K..S.
00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58  ......./bin/shNX
00000030: 5858 5859 5959 59                        XXXYYYY" a -1
\xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x4e\x58\x58\x58\x58\x59\x59\x59\x59

```

# Answer
> 3 votes
# Jelly, ~~39~~ ~~38~~ 37 bytes

```
ØhiⱮɠ’ḅ¥ȷ9Ṃ?⁴‘
Ỵṫ€⁵ḣ€40Fḟ⁶s2ṭ€⁾\xḣ¢ṫ¢

```

Try it online!

Now beats 05AB1E! (despite the lack of "convert from hexadecimal" builtin)

Same input format as Dennis' solution.

Use , which is a new feature (short for `Ð€`). Without it, this would take 38 bytes.

# Answer
> 1 votes
## Perl, 114 bytes

```
($_,$a,$b)=@ARGV;s/^.*:|\S*$|\s//gm;@_=(m/../g);for(@_){s/^/\\x/}$"='';say substr"@_",4*$a,$b!=-1?4*($a+$b):2<<20;

```

Arguments given on the command line as a quoted string followed by two numbers. The numbers are taken in decimal (I know hex was used in the examples but it wasn't specified in the post)

Technically only works on inputs with up to 2^21 bytes since perl's substring method is silly

# Answer
> 1 votes
## Python, 140 bytes

```
lambda O,a,b:''.join(sum([['\\x'+x[:2],('','\\x')[len(x)>2]+x[2:]]for x in O.split()if len(x)<5],[])[int(a,16):(int(b,16)+1,None)[b=='-1']])

```

https://repl.it/ClB3

Splits the original string and dumps the elements if they're less than five characters, prepends `\x`, and slices by the second and third arguments.

162 byte version if we need to handle other types of output not specified by the question:

```
import re
J=''.join
def f(x,a,b):r=J(J(re.findall(':(.*?)  ',x)).split());print J(['\\x'+i+j for i,j in zip(r,r[1:])][::2][int(a,16):(int(b,16)+1,None)[b=='-1']])

```

# Answer
> 0 votes
# Python 2 and 3 - ~~164 162 150 146 134~~ 150 bytes

Now accepts hex strings for second and third arguments.

```
j=''.join
def f(a,b,c):s=j(x[10:49].replace(' ','')for x in a.split('\n'));print(j('\\x'+s[i:i+2]for i in range(int(b,16)*2,1+2*int(c,16)%len(s),2))

```

# Answer
> 0 votes
Python 3.5, 125 bytes

```
import re
lambda s,b,e:re.sub(r'(\w\w)',r'\\x\1',re.sub(r'^.*?:|  .*$|\s','',s,0,8)[2*int(b,16):[2*int(e,16)+2,None][e<'0']])

```

Ungolfed:

```
def f(s,b,e):
    b = 2*int(b,16)
    e = [2*int(e,16)+2,None][e<'0']
    x = re.sub(r'''(?v)   # verbose (not in golfed version)
            ^.*?:     # match begining of line to the ':'
           |  .*$     # or match '  ' to end of line
           |\s        # or match whitespace
           ''',
           '',        # replacement
           s,
           0,         # replace all matches
           re.M       # multiline mode
           )
    y = re.sub(r'(\w\w)', # match pairs of 'word' characters
           r'\\x\1',  # insert \x
            x[b:e])
    return y

```

---
Tags: code-golf, hexadecimal
---


title: Count the timespans

text:
# Question
Title: Count the timespans
Inspired by a real-life scenario, which I have asked for an answer to here: https://superuser.com/questions/1312212/writing-a-formula-to-count-how-many-times-each-date-appears-in-a-set-of-date-ran

Given an array of timespans (or startdate-enddate pairs), output a count of how many timespans cover each day, for all days in the total range.

For example:

```
  #      Start      End
  1    2001-01-01 2001-01-01
  2    2001-01-01 2001-01-03
  3    2001-01-01 2001-01-02
  4    2001-01-03 2001-01-03
  5    2001-01-05 2001-01-05

```

Given the above data, the results should be as follows:

```
2001-01-01: 3 (Records 1,2,3)
2001-01-02: 2 (Records 2,3)
2001-01-03: 2 (Records 2,4)
2001-01-04: 0
2001-01-05: 1 (Record 5)

```

You only need to output the counts for each day (in order, sorted oldest-newest); not which records they appear in.

You can assume that each timespan only contains dates, not times; and so whole days are always represented.

## I/O

**Input** can be any format that represents a set of timespans - so either a set of pairs of times, or a collection of (builtin) objects containing start- and end-dates. The date-times are limited to between 1901 and 2099, as is normal for PPCG challenges.

You can assume the input is pre-sorted however you like (specify in your answer). Input dates are inclusive (so the range includes the whole of the start and end dates).

You can also assume that, of the two dates in any given range, the first will be older or equal to the second (i.e. you won't have a negative date range).

**Output** is an array containing the count for each day, from the oldest to the newest in the input when sorted by Start Date.

So, the output for the above example would be `{3,2,2,0,1}`

It is possible that some days are not included in any time range, in which case `0` is output for that date.

## Winning Criteria

This is code-golf, so lowest bytes wins. Usual exclusions apply

## Pseudo-algorithm example

```
For each time range in input
    If start is older than current oldest, update current oldest
    If end is newer than current newest, update current newest
End For
For each day in range oldest..newest
   For each time range
       If timerange contains day
            add 1 to count for day
End For
Output count array

```

Other algorithms to get to the same result are fine.

# Answer
# APL (Dyalog Unicode), 32 bytesSBCS

Full program. Prompts stdin for a list of pairs of International Date Numbers (like what Excel and MATLAB use). Both list and pairs may be given in any order, e.g. (End,Start). Prints list of counts to stdout.

`¯1+⊢∘≢⌸(R,⊢)∊(R←⌊/,⌊/+∘⍳⌈/-⌊/)¨⎕`Try it online!

If this is invalid, a list of (Y M D) pairs can be converted for an additional 21 bytes, totalling 53:

`¯1+⊢∘≢⌸(R,⊢)∊(R⌊/,⌊/+∘⍳⌈/-⌊/)¨{2⎕NQ#'DateToIDN'⍵}¨¨⎕`Try it online!

---

prompt console for evaluated input

`(` apply the following tacit function to each pair

`⌊/` the minimum (lit. min-reduction), i.e. the start date

`⌈/-` the maximum (i.e. end date) minus that

`⌊/+∘⍳` the start date plus the range 1-through-that

`⌊/,` the start date prepended to that

`R←` assign this function to `R` (for **R**ange)

**ϵ**nlist (flatten) the list of ranges into a single list

`(``)` apply the following tacit function to that:

`R,⊢` the result of applying `R` (i.e. the date range) followed by the argument
(this ensures that each date in the range is represented at least once, and that the dates appear in sorted order)

for each pair of unique (date, its indices of occurrence in the input), do:

`⊢∘≢` ignore the actual date in favour of the tally of indices

`¯1+` add -1 to those tallies (because we prepended one of each date in the range)
> 3 votes

# Answer
# JavaScript (ES6), 85 bytes

Takes input as a list of `Date` pairs. Expects the list to be sorted by starting date. Returns an array of integers.

```
f=(a,d=+a[0][0])=>[a.map(([a,b])=>n+=!(r|=d<b,d<a|d>b),r=n=0)|n,...r?f(a,d+864e5):[]]

```

Try it online!

or **84 bytes** if we can take JS timestamps as input (as suggested by @Shaggy)
> 9 votes

# Answer
# JavaScript, ~~75~~ 73 bytes

Takes input as a sorted array of arrays of date primitive pairs, outputs an object where the keys are the primitives of each date and the values the counts of those dates in the ranges.

```
a=>a.map(g=([x,y])=>y<a[0][0]||g([x,y-864e5],o[y]=~~o[y]+(x<=y)),o={})&&o

```

Try it

---

I was working on this 60 byte version until it was confirmed that dates that don't appear in any of the ranges *must* be included so hastily updated it to the solution above.

```
a=>a.map(g=([x,y])=>x>y||g([x+864e5,y],o[x]=-~o[x]),o={})&&o

```

Try it online (or with human readable dates in the output)
> 7 votes

# Answer
# Octave, 63 bytes

```
@(x)histc(t=[cellfun(@(c)c(1):c(2),x,'un',0){:}],min(t):max(t))

```

Try it online!

Now that was ugly!

### Explanation:

Takes the input as a cell array of `datenum` elements (i.e. a string `"2001-01-01"` converted to a numeric value, looking like this:

```
{[d("2001-01-01") d("2001-01-01")]
[d("2001-01-01") d("2001-01-03")]
[d("2001-01-01") d("2001-01-02")]
[d("2001-01-03") d("2001-01-03")]
[d("2001-01-05") d("2001-01-05")]};

```

where `d()` is the function `datenum`. We then use `cellfun` to create cells with the ranges from the first column to the second for each of those rows. We concatenate these ranges horizontally, so that we have a long horizontal vector with all the dates.

We then create a histogram using `histc` of these values, with bins given by the range between the lowest and the highest date.
> 6 votes

# Answer
# , 75 bytes

```
function(x,u=min(x):max(x))rowSums(outer(u,x[,1],">=")&outer(u,x[,2],"<="))

```

Try it online!

Input is a matrix whose first column is Start and second column is End. Assumes Start\<=End but does not require Start dates to be sorted.
> 5 votes

# Answer
# Python 2, ~~114~~ ~~87~~ 93 bytes

-27 bytes thanks to Jonathan Allan
+6 bytes thanks to sundar

Takes input as list of pairs of datetime objects.
Assumes that first pair starts with the lowest date.

```
def F(I):
 d=I[0][0]
 while d<=max(sum(I,[])):print sum(a<=d<=b for a,b in I);d+=type(d-d)(1)

```

Try it online!
> 4 votes

# Answer
# Groovy, 142 bytes

```
{a={Date.parse('yyyy-mm-dd',it)};b=it.collect{a(it[0])..a(it[1])};b.collect{c->b.collect{it}.flatten().unique().collect{it in c?1:0}.sum()}}

```

##

Formatted out:

```
 {                                   // Begin Closure
    a={Date.parse('yyyy-mm-dd',it)}; // Create closure for parsing dates, store in a().
    b=it.collect{                    // For each input date pair...
        a(it[0])..a(it[1])           // Parse and create date-range.
    };
    b.collect{                       // For each date range...
        c->
        b.collect{                   // For each individual date for that range...
           it
        }.flatten().unique().collect{ // Collect unique dates.
            it in c?1:0
        }.sum()                      // Occurrence count.
    }
}

```
> 4 votes

# Answer
# Red, 174 bytes

```
func[b][m: copy #()foreach[s e]b[c: s
until[m/(c): either none = v: m/(c)[1][v + 1]e < c: c + 1]]c: first sort b
until[print[either none = v: m/(c)[0][v]](last b)< c: c + 1]]

```

Quite long and literal implementation.

Try it online!

## Readable:

```
f: func [ b ] [
    m: copy #()
    foreach [ s e ] b [
        c: s
        until [
            m/(c): either none = v: m/(c) [ 1 ] [ v + 1 ]
            e < c: c + 1
        ]
    ]
    c: first sort b
    until[
        print [ either none = v: m/(c) [ 0 ] [ v ] ]
        ( last b ) < c: c + 1
    ]
]

```
> 4 votes

# Answer
# , ~~65~~ 63 bytes

```
function(x)hist(unlist(Map(`:`,x[,1],x[,2])),min(x-1):max(x))$c

```

Try it online!

This is a collaboration between JayCe and myself, porting Stewie Griffin's answer over to R.

To quote JayCe:

> Input is a matrix whose first column is Start and second column is End. Assumes Start\<=End but does not require Start dates to be sorted.

Possibly, `$c` is unnecessary but it's not quite in the spirit of the challenge so I've included it.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 62 bytes

```
Lookup[d=DayRange;Counts[Join@@d@@@#],#[[1,1]]~d~#[[-1,1]],0]&

```

Try it online!

+35 bytes because OP specified that `0` must be included in the output.

### If omitting an entry in a dictionary were allowed, 27 bytes

```
Counts[Join@@DayRange@@@#]&

```

Try it online!

The built-in `DayRange` accepts two `DateObject`s (or a string equivalent) and outputs a list of `Dates` between those dates (inclusive).
> 3 votes

# Answer
# Powershell, ~~122~~ ~~121~~ ~~118~~ 113 bytes

```
filter d{0..($_[-1]-($s=$_[0])).Days|%{$s.AddDays($_)}}$c=@{};$args|d|%{++$c.$_};,($c.Keys.Date|sort)|d|%{+$c.$_}

```

save it as `count-timespan.ps1`. Test script:

```
.\count-timespan.ps1 `
    @([datetime]"2001-01-01", [datetime]"2001-01-01")`
    @([datetime]"2001-01-01", [datetime]"2001-01-03")`
    @([datetime]"2001-01-01", [datetime]"2001-01-02")`
    @([datetime]"2001-01-03", [datetime]"2001-01-03")`
    @([datetime]"2001-01-05", [datetime]"2001-01-05")

```

## Explanation

```
filter d{                           # define a function with a pipe argument (it's expected that argument is an array of dates)
    0..($_[-1]-($s=$_[0])).Days|%{  # for each integer from 0 to the Days
                                    # where Days is a number of days between last and first elements of the range
                                    # (let $s stores a start of the range)
        $s.AddDays($_)              # output to the pipe a date = first date + number of the current iteration
    }                               # filter returns all dates for each range
}                                   # dates started from first element and ended to last element
$c=@{}                              # define hashtable @{key=date; value=count}
$args|d|%{++$c.$_}                  # count each date in a array of arrays of a date
,($c.Keys.Date|sort)|d|%{+$c.$_}    # call the filter via pipe with the array of sorted dates from hashtable keys

# Trace:
# call d @(2001-01-01, 2001-01-01) @(2001-01-01, 2001-01-03) @(2001-01-01, 2001-01-02) @(2001-01-03, 2001-01-03) @(2001-01-05, 2001-01-05)
# [pipe]=@(2001-01-01, 2001-01-01, 2001-01-02, 2001-01-03, 2001-01-01, 2001-01-02, 2001-01-03, 2001-01-05)
# $c=@{2001-01-03=2; 2001-01-01=3; 2001-01-05=1; 2001-01-02=2}
# call d @(2001-01-01, 2001-01-02, 2001-01-03, 2001-01-05)
# [pipe]=@(2001-01-01, 2001-01-02, 2001-01-03, 2001-01-04, 2001-01-05)
# [output]=@(3, 2, 2, 0, 1)

```
> 3 votes

# Answer
# J, 43 bytes

```
(],.[:+/@,"2="{~)&:((>./(]+i.@>:@-)<./)"1),

```

the input is a list of pairs of integers, where each integer is the offset from any arbitrary common 0-day.

## ungolfed

```
(] ,. [: +/@,"2 ="{~)&:((>./ (] + i.@>:@-) <./)"1) ,

```

## explanation

structure is:

```
(A)&:(B) C

```
* C creates a hook that gives the main verb `A&:B` the input on the left and the input flattened on the right
* B aka `((>./ (] + i.@>:@-) <./)"1)` takes the min and max of a list and returns the resulting range, and acts with rank 1. hence it gives the total range on the right, and the individual ranges on the left.
* A then uses `=` with rank `"0 _` (ie, rank of `{`) to count how many times each input appears in any of the ranges. finally it zips every year with those counts.

Try it online!
> 3 votes

# Answer
# JavaScript (Node.js), 80 bytes

```
(a,u=[])=>a.map(g=([p,q])=>p>q||g([p,q-864e5],u[z=(q-a[0][0])/864e5]=-~u[z]))&&u

```

Try it online!

`undefined` means zero; First element should start earliest

`(a,u=[])=>a.map(g=([p,q])=>p>q||g([p,q-1],u[z=(q-a[0][0])/864e5]=-~u[z]))&&u` is shorter if you only see elements and use more stack
> 2 votes

# Answer
# Julia 0.6, 77 bytes

```
M->[println(sum(d∈M[r,1]:M[r,2]for r∈1:size(M,1)))for d∈M[1]:max(M...)]

```

Try it online!

Inspired by @DeadPossum's Python solution.

Takes input as a matrix, where each row has two dates: the starting and ending dates of an input range. Assumes the input has the earliest date first, and that each row has the starting date first, but assumes no sorting beyond that between different rows.

---

Older solution:

# Julia 0.6, 124 bytes

```
R->(t=Dict();[[d∈keys(t)?t[d]+=1:t[d]=1 for d∈g]for g∈R];[d∈keys(t)?t[d]:0 for d∈min(keys(t)...):max(keys(t)...)])

```

Try it online!

Accepts input as an array of date ranges. Does not assume any sorting among the different ranges in the array.
> 1 votes

# Answer
# Ruby, 70 bytes

```
->s{f,=s.min;(p s.count{|a,b|(f-a)*(f-b)<=0};f+=86400)until f>s[0][1]}

```

Try it online!

### Input:

Array of pairs of dates, sorted by ending date descending.
> 1 votes

# Answer
# R (70)

```
function(x)(function(.)tabulate(.-min(.)+1))(unlist(Map(seq,x$S,x$E,"d")))

```

Presumes a data frame `x` with two columns (`Start` and `End` or possibly `S` and `E`) with dates (class `Date`).

Try it online
> 1 votes

---
Tags: code-golf, date
---