title: Print every Fool's Mate

text:
# Question
Title: Print every Fool's Mate
In chess, the Fool's Mate is the fastest possible way to reach checkmate. It is reached with Black's second move. In chess notation, one possible sequence of moves that achieves Fool's Mate is `1.f3 e6 2.g4 Qh4#`.

This is not the only possible way to achieve this checkmate (in the same number of moves). There are three things that can be varied while still taking the same number of moves:

1. White can move the f-pawn first or the g-pawn first,
2. White can move the f-pawn to f3 or f4, and
3. Black can move the e-pawn to e6 or e5.

This gives 8 possible games that end in Fool's Mate. Print them all in standard chess notation. They are:

```
1.f3 e5 2.g4 Qh4#
1.f3 e6 2.g4 Qh4#
1.f4 e5 2.g4 Qh4#
1.f4 e6 2.g4 Qh4#
1.g4 e5 2.f3 Qh4#
1.g4 e5 2.f4 Qh4#
1.g4 e6 2.f3 Qh4#
1.g4 e6 2.f4 Qh4#

```

The order in which the games are printed does not matter, so e.g. this is OK:

```
1.g4 e5 2.f4 Qh4#
1.f3 e6 2.g4 Qh4#
1.g4 e6 2.f4 Qh4#
1.f4 e5 2.g4 Qh4#
1.f4 e6 2.g4 Qh4#
1.g4 e5 2.f3 Qh4#
1.g4 e6 2.f3 Qh4#
1.f3 e5 2.g4 Qh4#

```

# Answer
# Bash, 61

This is a pretty good challenge for bash brace expansions

```
printf '1.%s Qh4#
' f{3,4}\ e{5,6}\ 2.g4 g4\ e{5,6}\ 2.f{3,4}

```

Try it online!
> 12 votes

# Answer
# JavaScript (V8), 80 bytes

*-2 bytes by using a full program, as suggested by @dingledooper*
*-2 bytes thanks to @Kevin Cruijssen*

```
for(n=8;n--;)print(`1.${n&2?G='g4':F} e${6-n%2} 2.${n&2?F=`f${n&4||3}`:G} Qh4#`)

```

Try it online!

### How?

We iterate from \\$n=7\\$ to \\$n=0\\$ and use each bit to decide what should be displayed:

```
bit : 2 1 0
      | | |
      | | +--> use 'e5' if set, use 'e6' if clear
      | +----> g-pawn first if set, f-pawn first if clear
      +------> use 'f4' if set, use 'f3' if clear

```
> 6 votes

# Answer
# C (gcc), ~~104~~ ~~99~~ ~~90~~ 89 bytes

```
f(i){for(i=9;--i;printf("1.%c%d e%d 2.%c%d Qh4#\n",102+i/5,4+3/~i,6-i%2,103-i/5,4-i/7));}

```

Try it online!

-3 bytes thanks to Steffan

-1 byte thanks to Arnauld

-9 bytes thanks to AZTECCO

-1 byte thanks to c--
> 5 votes

# Answer
# Vyxal `j`, 36 bytes

```
\f43f+56fẊ‛g4vJ:RJƛ÷`1.Π eΠ 2.Π Qh4#

```

Try it Online!

This was... annoying

```
         Ẋ                           # Cartesian product of...
\f43f+                               # ["f3", "f4"]
      56f                            # and [5, 6]
          ‛g4vJ                      # Append "g4" to each
               :RJ                   # Reverse each and append to the original
                  ƛ                  # Over each...
                   ÷                 # Push each into the stack
                    `1.Π eΠ 2.Π Qh4# # Format into the final output.

```
> 5 votes

# Answer
# Retina 0.8.2, ~~62~~ 60 bytes

```

g4#f3¶f3#g4
#
 e5 2.
.+
1.$& Qh4#
3
$&$%'¶$%`4
5
$&$%'¶$%`6

```

Try it online! Edit: Saved 2 bytes thanks to @DLosc. Explanation:

```

g4#f3¶f3#g4

```

Insert the two pawn orders for White.

```
#
 e5 2.

```

Insert Black's first move in between each pair.

```
.+
1.$& Qh4#

```

Append Black's second move to each pair.

```
3
$&$%'¶$%`4

```

Duplicate each game but with `f3` changed to `f4`.

```
5
$&$%'¶$%`6

```

Duplicate each game but with `e5` changed to `e6`.
> 3 votes

# Answer
# Python 3, 76 bytes

```
print('1.%s%s e%%s 2.%s%s Qh4#\n'*4%(*'g4f3g4f4f4g4f3g4',)*2%(*'55556666',))

```

Try it online!

Can definitely be improved.

### Python 3, 73 bytes

```
for x in 5,6:print(f'1.%c%c e{x} 2.%c%c Qh4#\n'*4%(*'g4f3g4f4f3g4f4g4',))

```

Try it online!

This is 3 bytes shorter, but prints an empty line in the middle.
> 3 votes

# Answer
# Whitespace, ~~380~~ 378 bytes

```
[S S S T    S S S N
_Push_n=8][N
S S N
_Create_Label_LOOP][S S S T N
_Push_1][T  S S T   _Subtract:_n=n-1][S N
S _Duplicate_n][N
T   T   S N
_If_negative_Jump_to_Label_EXIT][S S S T    N
_Push_1][T  N
S T _Print_as_number][S S S T   S T T   T   S N
_Push_46_.][T   N
S S _Print_as_character][S N
S _Duplicate_n][S S S T S S N
_Push_4][T  S T S _Integer_divide][S S S T  T   S S T   T   S N
_Push_102][T    S S S _Add][T   N
S S _Print_as_character][S S S T    S S N
_Push_4][S S S T    T   N
_Push_3][S T    S S T   S N
_Copy_0-based_2nd:_n][S S S T   S N
_Push_2][T  S S S _Add][T   S T S _Integer_divide][T    S S T   _Subtract][T    N
S T _Print_as_number][S S S T   S S S S S N
_Push_32_<space>][T N
S S _Print_as_character][S S S T    T   S S T   S T N
_Push_101_e][T  N
S S _Print_as_character][S N
S _Duplicate_n][S S S T S N
_Push_2][T  S T T   _Modulo][S S S T    T   S N
_Push_6][S N
T   _Swap_top_two][T    S S T   _Subtract][T    N
S T _Print_as_number][S S S T   S S S S S N
_Push_32_<space>][T N
S S _Print_as_character][S S S T    S N
_Push_2][T  N
S T _Print_as_number][S S S T   S T T   T   S N
_Push_46_.][T   N
S S _Print_as_character][S N
S _Duplicate_n][S S S T S S N
_Push_4][T  S T S _Integer_divide][S S S T  T   S S T   T   T   N
_Push_103][S N
T   _Swap_top_two][T    S S T   _Subtract][T    N
S S _Print_as_character][S N
S _Duplicate_n][S S S T T   S N
_Push_6][T  S T S _Integer_divide][S S S T  S S N
_Push_4][S N
T   _Swap_top_two][T    S S T   _Subtract][T    N
S T _Print_as_number][S S S T   S S S S S N
_Push_32_<space>][T N
S S _Print_as_character][S S S T    S T S S S T N
_Push_81_Q][T   N
S S _Print_as_character][S S S T    T   S T S S S N
_Push_108_h][T  N
S S _Print_as_character][S S S T    S S N
_Push_4][T  N
S T _Print_as_number][S S S T   S S S T T   N
_Push_35_#][T   N
S S _Print_as_character][S S S T    S T S N
_Push_10_\n][T  N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

**Try it online** (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

Port of *@jdt*'s C answer, with `3+(i>1)` replaced with `4-3/(n+2)`:

```
Integer n = 8
Start LOOP:
  n = n - 1
  If (n < 0):
    Stop program with an error, by jumping to an undefined label
  Print "1."
  Print n//4+102 as character
  Print 4-3//(n+2) as integer
  Print " e"
  Print 6-n%2 as integer
  Print " 2."
  Print 103-n//4 as character
  Print 6-n//4 as integer
  Print " Qh4#\n"
  Go to next iteration of LOOP

```
> 3 votes

# Answer
# Regenerate `-a`, 42 bytes

```
1.(f[34] e[56] 2.g4|g4 e[56] 2.f[34]) Qh4#

```

Attempt This Online!

### Explanation

The logic is a bit clunkier than I'd like, but Regenerate doesn't have any string-based conditionals (yet).

```
1.(f[34] e[56] 2.g4|g4 e[56] 2.f[34]) Qh4#
1.                                          Match 1.
  (                |                )       Then match one of these two patterns:
   f[34]                                      f3 or f4
         e[56]                                followed by e5 or e6
               2.g4                           followed by 2.g4
                                            or
                    g4                        g4
                       e[56]                  followed by e5 or e6
                             2.f[34]          followed by 2.f3 or 2.f4
                                      Qh4#  Finally, match Qh4#
                                            The -a flag outputs all possible matches

```
> 2 votes

# Answer
# 05AB1E, ~~37~~ 36 bytes

```
56āÌ'fìâ„g4δšDí«ε`"1.ÿ eÿ 2.ÿ Qh4#",

```

Try it online.

If outputting as a list of lines is allowed, the trailing `",` can be removed for -2 bytes: try it online.

**Explanation:**

```
56            # Push 56
  ā           # Push a list in the range [1,length] (without popping): [1,2]
   Ì          # Increase each by 2: [3,4]
    'fì      '# Prepend an "f" to each: ["f3","f4"]
       â      # Get the cartesian product of these two:
              #  [[5,"f3"],[5,"f4"],[6,"f3"],[6,"f4"]]
          δ   # Map over each inner list:
        „g4 š #  Prepend string "g4" to the list
              #   [["g4",5,"f3"],["g4",5,"f4"],["g4",6,"f3"],["g4",6,"f4"]]
D             # Duplicate this list of lists
 í            # Reverse each inner list:
              #  [["f3",5,"g4"],["f4",5,"g4"],["f3",6,"g4"],["f4",6,"g4"]]
  «           # Merge the two lists together
ε             # Foreach over each inner list:
 `            #  Pop and push the items of the list to the stack
  "1.ÿ eÿ 2.ÿ Qh4#"
              #  Push this string, where the `ÿ` are automatically one by one filled
              #  with the items
    ,         #  Pop and print it with trailing newline

```
> 2 votes

# Answer
# C (gcc), 156 131 130 111 105 103 90 bytes

Some bytes lost because of @Steffan.

```
main(i){for(;i++<9;printf("1.%c%d e%d 2.%c%d Qh4#\n",102|i>5,4-3/i,5+i%2,102|i<6,4-i/8));}

```

Explained:

* import modules
* declare main
* declare iterator
* keep looping 8 times
* + print according to the format specifiers
* + - if i is lesser than 5, the first character is f, else g
* + - if i is less than 3, the first number is 3, else 4
* + - if i is odd and is less than six, or is six, then 5, else 6
* + - if i is less than 5, then 'g', else 'f'
* + - if i is less than 5 or is even, then 4, else 3.
* + add a newline
> 1 votes

# Answer
# Charcoal, 37 bytes

```
ＦＥ34⁺g4fιＦ⪪ι²Ｅ56⪫⟦1.⁻ικ eλ 2.κ Qh4#⟧ω

```

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

```
ＦＥ34⁺g4fι

```

Loop over the strings `g4f3` and `g4f4` representing the alternatives for White's pairs of moves.

```
Ｆ⪪ι²

```

Loop over each of White's possible moves from the current pair.

```
Ｅ56⪫⟦1.⁻ικ eλ 2.κ Qh4#⟧ω

```

Map over the characters `5` and `6` and output the following joined together for each line:

* The literal string `1.`
* The other move for White from the current pair
* The literal string  `e`
* The character `5` or `6` from the innermost loop
* The literal string  `2.`
* The move for White from the inner loop
* The literal string  `Qh4#`
> 1 votes

# Answer
# Jelly, 37 bytes

```
“ḲṚẉċ‘ḤD“feg”żⱮ;Ṛ€$“1.““2.“Qh4#”żⱮK€Y

```

A full program that prints the eight games.

**Try it online!**

```
“ḲṚẉċ‘ḤD“feg”żⱮ;Ṛ€$“1.““2.“Qh4#”żⱮK€Y - Main Link: no arguments
“ḲṚẉċ‘                                - code-page indices = [177,182,227,232]
      Ḥ                               - double           -> [354,364,454,464]
       D                              - decimal digits   -> [[3,5,4],[3,6,4],[4,5,4],[4,6,4]]
        “feg”                         - "feg"
             żⱮ                       - map with zip     -> [[['f',3],['e',5],['g',4]],[['f',3],['e',6],['g',4]],[['f',4],['e',5],['g',4]],[['f',4],['e',6],['g',4]]]
                  $                   - last two links as a monad:
                Ṛ€                    -   reverse each   -> [[['g',4],['e',5],['f',3]],[['g',4],['e',6],['f',3]],[['g',4],['e',5],['f',4]],[['g',4],['e',6],['f',4]]]
               ;                      -   concatenate    -> [[['f',3],['e',5],['g',4]],[['f',3],['e',6],['g',4]],[['f',4],['e',5],['g',4]],[['f',4],['e',6],['g',4]],[['g',4],['e',5],['f',3]],[['g',4],['e',6],['f',3]],[['g',4],['e',5],['f',4]],[['g',4],['e',6],['f',4]]]
                   “1.““2.“Qh4#”      - ["1.","","2.","Qh4#"]
                                żⱮ    - map with zip     -> [[["1.",['f',3]],[[],['e',5]],["2.",['g',4]],["Qh4#"]],[["1.",['f',3]],[[],['e',6]],["2.",['g',4]],["Qh4#"]],[["1.",['f',4]],[[],['e',5]],["2.",['g',4]],["Qh4#"]],[["1.",['f',4]],[[],['e',6]],["2.",['g',4]],["Qh4#"]],[["1.",['g',4]],[[],['e',5]],["2.",['f',3]],["Qh4#"]],[["1.",['g',4]],[[],['e',6]],["2.",['f',3]],["Qh4#"]],[["1.",['g',4]],[[],['e',5]],["2.",['f',4]],["Qh4#"]],[["1.",['g',4]],[[],['e',6]],["2.",['f',4]],["Qh4#"]]]
                                  K€  - space-join each  -> [["1.",['f',3],' ',[],['e',5],' ',"2.",['g',4],' ',"Qh4#"],["1.",['f',3],' ',[],['e',6],' ',"2.",['g',4],' ',"Qh4#"],["1.",['f',4],' ',[],['e',5],' ',"2.",['g',4],' ',"Qh4#"],["1.",['f',4],' ',[],['e',6],' ',"2.",['g',4],' ',"Qh4#"],["1.",['g',4],' ',[],['e',5],' ',"2.",['f',3],' ',"Qh4#"],["1.",['g',4],' ',[],['e',6],' ',"2.",['f',3],' ',"Qh4#"],["1.",['g',4],' ',[],['e',5],' ',"2.",['f',4],' ',"Qh4#"],["1.",['g',4],' ',[],['e',6],' ',"2.",['f',4],' ',"Qh4#"]]
                                    Y - newline-join     -> ["1.",['f',3],' ',[],['e',5],' ',"2.",['g',4],' ',"Qh4#",'\n',"1.",['f',3],' ',[],['e',6],' ',"2.",['g',4],' ',"Qh4#",'\n',"1.",['f',4],' ',[],['e',5],' ',"2.",['g',4],' ',"Qh4#",'\n',"1.",['f',4],' ',[],['e',6],' ',"2.",['g',4],' ',"Qh4#",'\n',"1.",['g',4],' ',[],['e',5],' ',"2.",['f',3],' ',"Qh4#",'\n',"1.",['g',4],' ',[],['e',6],' ',"2.",['f',3],' ',"Qh4#",'\n',"1.",['g',4],' ',[],['e',5],' ',"2.",['f',4],' ',"Qh4#",'\n',"1.",['g',4],' ',[],['e',6],' ',"2.",['f',4],' ',"Qh4#"]
                                      - implicit, smashing print

```
> 1 votes

# Answer
# MATLAB, 72 bytes

Somewhat straight-forward, but it's not how the tutorial tells you to do it. Uses this little-known syntax.

```
function a b

```

is equivalent to

```
function('a','b')

```

Which means that two string inputs `'a'` and `'b'` can be entered `a b` instead of `('a','b')`, saving 6 bytes.

---

First make a string template that is equal to a row, but with "wild cards" for the characters that varies. All strings have `1.`,  `e`,  `2.`,  `Qh4#\n`. All other characters are stored in the string in the end.

I tried to find a way to use the pattern with similarities between rows, but string manipulation is verbose in Octave.

```
printf 1.%c%c e%c 2.%c%c Qh4#\n f35g4f36g4f45g4f46g4g45f3g45f4g46f3g46f4

```

Try it online!
> 1 votes

# Answer
# Python 3, 118 bytes

```
for f in 0,1:
 x='f3','f4';y='g4',
 if f:y,x=x,y
 [print(f'1.{w} e{r} 2.{W} Qh4#')for w in x for W in y for r in[5,6]]

```

Try it online!
> 0 votes

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


title: Name the poker hand

text:
# Question
Title: Name the poker hand
# Name the poker hand

Given five cards, output the name of the poker hand, which will be one of:

```
High card
One pair
Two pair
Three of a kind
Straight
Flush
Full house
Four of a kind
Straight flush
Royal Flush

```

If in doubt, refer to the rules at http://en.wikipedia.org/wiki/List\_of\_poker\_hands.

## Input

5 *cards* from either stdin or commandline arguments. A card is a two letter string on the form `RS`, where R is rank and S is suit. The **ranks** are `2` \- `9` (number cards), `T` (ten), `J` (Jack), `Q` (Queen), `K` (King), `A` (Ace). The **suits** are `S`, `D`, `H`, `C` for spades, diamonds, hearts and clubs respectively.

### Example of cards

```
5H - five of hearts
TS - ten of spades
AD - ace of diamonds

```

### Example of input =\> desired output

```
3H 5D JS 3C 7C => One pair
JH 4C 2C JD 2H => Two pair
7H 3S 7S 7D 7C => Four of a kind
8C 3H 8S 8H 3S => Full house

```

## Rules

Shortest code wins

### Edit

Looking great so far! I can't really verify all the answers, since I don't know these languages very well and don't have compilers/interpreters for all of them, but I suspect that not everyone have thought about that **Aces can be both the highest and the lowest cards of a Straight (flush)**.

# Answer
> 3 votes
## GolfScript (209 208 207 206 200 199 197 196 chars)

```
3/zip:^0={10,''*"TJQKA"+?}/]:?15,{?\{=}+,,}%2,-$6,14.),++@$/):|;[!!2*^1=.&,(!+5+]or{/}*'Full house
Two pair
One pair
ThreeKFourKHigh card
Flush
Straight''K'/' of a kind
'*n/~|1$"Royal"if" "+2$+](=

```

I'm exploiting the offered freedom to tweak capitalisation: my Straight Flush and Royal Flush both capitalise Flush in order to reuse the word from the simple flush.

Note: some earlier versions were buggy: they only supported full house when the pair was of lower value than the pair royal. They can be corrected by replacing the space separating `- 0` with a `$`.

Demo

# Answer
> 9 votes
Came up with an answer of my own :)

# Python - 312 301 298

```
R,K,F,S,g=' 23456789TJQKA2345A',' of a Kind','Flush','Straight ',sorted
s,r=''.join(g(raw_input(),key=R.find)).split()
n,m=g(map(r.count,set(r)))[-2:]
print[[F,[0,'High Card','TOwnoe'[n&1::2]+' Pair',['Full House','Three'+K][n&1],'Four'+K][m]],[[S,'Royal '][r[0]=='T']+F,S]][r in R][len(set(s))>1]

```

Creates a 2x2 list where the indices of the two dimensions are boolean checks for flush and straight. In case of both, we check if it's a royal flush or just a straight flush. For not flush and not straight, we check for the other hands: `m` and `n` holds the highest and second highest amount of same-rank cards; the names of the hands are stored in a list with indices according to `m`. Sub-checks within this list's values are done with `n` to seperate one pair from two pair, and three of a kind from house.

Edit: Thanks Nolen Royality for a total of 20 characters saved!

# Answer
> 6 votes
## Ruby 1.9 (~~427~~ ~~359~~ ~~348~~ ~~338~~ ~~296~~ ~~292~~ 289)

**EDIT**: Fixed to work with low aces.

**EDIT**: Incorporated @je-je's fixes / improvements

```
o,p=%w(flush straight)
f=/1{5}|^1+0+1$/
s=[0]*13
puts Hash[*$*.map{|c|s['23456789TJQKA'.index c[0]]+=1;c[1]}.uniq[1]?[f,p,?4,'four'+a=' of a kind',/^[^1]+$/,'full house',?3,'three'+a,/2.*2/,'two pair',?2,'one pair',0,'high card']:[/1{5}$/,'royal '+o,f,p+' '+o,0,o]].find{|r,y|s.join[r]}[1]

```

The basic idea is to build up an array of the quantity of card in each rank, concatenate the digits into a string, and then run regular expressions to see which hand shape fits. We count the number of distinct suits to determine whether to check it against the different flushes (flush, straight flush, royal flush) or to the other shapes (everything else).

Takes the cards as separate command-line args, like so:

```
>ruby poker-hand-golf.rb 3H 5D JS 3C 7C
one pair

```

# Answer
> 4 votes
C, 454 characters

```
#define L for(a=1;a<6;a++)for(b=0;b<13;b++)
#define U u[b+6]
#define R(x,y) if(x)puts(#y);else
b,f,r,h=0,s=0,u[20]={0};main(int a,char**v){L U+=v[a][0]=="23456789TJQKA"[b];f=v[1][1];L{if(v[a][1]!=f)f=0;u[a]+=a==U;if(b>7)h+=U;if(a*13+b<64||!U)r=0;else if(++r==5)s=1;}R(f&&h==25,Royal flush)R(f&&s,Straight flush)R(u[4],Four of a kind)R(u[3]&&u[2],Full house)R(f,Flush)R(s,Straight)R(u[3],Three of a kind)R(u[2]==2,Two pair)R(u[2],One pair)R(h,High card);}

```

Run from command line with cards as arguments, e.g. ./a.out 8C 3H 8S 8H 3S

Expanded version, with comments:

```
#define L for(a=1;a<6;a++)for(b=0;b<13;b++)
#define R(x,y) if(x)puts(#y);else
#define U u[b+6]
b,f,r,h=0,s=0,u[20]={0};
main(int a,char**v){
    // card usage - u[6..]
    L U+=v[a][0]=="23456789TJQKA"[b];
    // NOTE: lets expand the inner body of the loop in the answer so this looks more sane:
    // flush
    f=v[1][1];L if(v[a][1]!=f)f=0;
    // count of usages - u[0..5]
    L u[a]+=a==U;
    // high cards x5
    L if(b>7)h+=U;
    // straights
    L if(a*13+b<64||!U)r=0;else if(++r==5)s=1;
    // display
    R(f&&h==25,Royal flush)
    R(f&&s,Straight flush)
    R(u[4],Four of a kind)
    R(u[3]&&u[2],Full house)
    R(f,Flush)
    R(s,Straight)
    R(u[3],Three of a kind)
    R(u[2]==2,Two pair)
    R(u[2],One pair)
    R(h,High card);
}

```

Edits:

1. Saved 12 chars by combining and reusing loops.
2. Saved 9 chars by inlining string constant.
3. Saved 19 chars by using stringification in macro, nasty..

# Answer
> 3 votes
# K, 294 295

```
d:{F:"Flush";S:"Straight ";P:" Pair";K:" of a kind";$[(f:1=#?,/-1#'c)&("AJKQT")~a@<a:,/j:1#'c:" "\:x;"Royal ",F;f&s:(4#1)~1_-':a@<a:,/(("A23456789TJQKA")!1+!14)@j;S,F;4=p:|/#:'=j;"Four",K;(2;3)~u:a@<a:,/#:'=j;"Full House";f;F;s;S;3=p;"Three",K;(1;2;2)~u;"Two",P;(1;1;1;2)~u;"One",P;"High Card"]}

```

.

```
k)d'("TS JS QS KS AS";"3S 4S 5S 7S 6S";"JC JH KS JD JS";"JC JH 2S JD 2C";"2C 9C TC QC 6C";"8C 5D 9H 6C 7D";"8C 8D 9H 8S 7D";"8C 8D 9H 2S 9D";"8C 8D 4H 2S 9D";"3C 8D 4H 2S 9D")
"Royal Flush"
"Straight Flush"
"Four of a kind"
"Full House"
"Flush"
"Straight "
"Three of a kind"
"Two Pair"
"One Pair"
"High Card"

```

edit: Added 1 char for Ace-low straights

# Answer
> 3 votes
## *Mathematica*, 365

Here is my take on David Carraher's answer.

Shown with white space for some readability.

```
If[
  a = Characters;
  x = Thread;
  r = Range;
  d = Sort[a@StringSplit@# /. x[a@"23456789TJQKA" -> 2~r~14]];
  {t, u} = Sort[Last /@ Tally@#] & /@ x@d;
  c = First /@ d;
  f = u == {5};
  S = "Straight";
  c == r[b = d[[1, 1]], b + 4],
  If[f,
   If[c == 10~r~14, "Royal Flush", S <> " flush"], S],
  If[f, "Flush",
   Switch[t,
    {_, 4},    "Four of a kind",
    {2, 3},    "Full house",
    {__, 3},   "Three of a kind",
    {_, 2, 2}, "Two pair",
    {__, 2},   "One pair",
    _,         "High card"]
  ]
] &

```

One line version:

```
If[a=Characters;x=Thread;r=Range;d=Sort[a@StringSplit@#/.x[a@"23456789TJQKA"->2~r~14]];{t,u}=Sort[Last/@Tally@#]&/@x@d;c=First/@d;f=u=={5};S="Straight";c==r[b=d[[1,1]],b+4],If[f,If[c==10~r~14,"Royal Flush",S<>" flush"],S],If[f,"Flush",Switch[t,{_,4},"Four of a kind",{2,3},"Full house",{__,3},"Three of a kind",{_,2,2},"Two pair",{__,2},"One pair",_,"High card"]]]&

```

# Answer
> 3 votes
### Python 334, 326 322 Characters

```
p,f,l,t,o=" pair"," of a kind"," Flush","Straight","A23456789TJQK"
v,u=zip(*raw_input().split())
s=''.join(sorted(v,key=o.find))
print{5:"High card",7:"One"+p,9:"Two"+p,11:"Three"+f,13:"Full house",17:"Four"+f,23:t,24:l[1:],25:t,42:t+l,44:"Royal"+l}[(sum(map(v.count,v)),24)[len(set(u))<2]+((0,20)[s=="ATJQK"],18)[s in o]]

```

I know that last one liner is getting pretty unreadable, I'll put up a non-golfed version when I'm happy with with my solution.

# Answer
> 2 votes
# Mathematica - 500 494 465 chars

This solution is based on a poker demonstration by Ed Pegg, Jr. In this version, the cards are treated internally as numbers in `Range[2,14]`

```
v[x_] := Block[{d, t, c, f, s},
 d = Sort@ToExpression[Characters[ImportString[x, "Table"][[1]]] /. {"T" -> 10, "J" -> 11, "Q" -> 12, "K" -> 13, "A" -> 14}];t = Sort /@ Map[Length, Split /@ Sort /@ Transpose@d, {2}];c = d[[All, 1]];f = (t[[2]] == {5});s = c == Range[b = d[[1, 1]], b + 4];
If[s,
 If[f, If[c == 10~Range~14, "royal flush", "straight flush"],"straight"],
 If[ f, "flush",
Switch[t[[1]],
 {1, 4}, "four of a kind",
 {2, 3}, "full house",
 {1, 1, 3}, "three of a kind",
 {1, 2, 2}, "two pair",
 {1, 1, 1, 2}, "one pair",
 {1, 1, 1, 1, 1}, "high card"]]]]

```

Sample inputs, outputs:

**Notes:**

f: flush

c: cards (without suit)

s: straight

t: {cards, suites}

d:

# Answer
> 2 votes
### GolfScript, 258 250 characters

```
3/zip~;.&,(!\{"23456789TJQKA"?}%$.(\{.@- 8%}%\;"\1"-!\.1/.&{1$\-,}%1.$?)"Four"" of a kind":k+{.,2="Full house"{.2\?)"Three"k+{.3-,({.3\?)"One pair"{;"Straight":?;2$2$&{(8="Royal"?if" flush"+}{;?{"Flush""High card"if}if}if}if}"Two pair"if}if}if}if])\;

```

The program expects input on STDIN as given above and outputs to STDOUT. You may test the code yourself.

```
> 8C 3H 8S 8H 3S
Full house

> 8C 7H 6S TH 9S
Straight

> AH 3H 4S 2H 6S
High card

```

*Edit:* Incorporated w0lf's suggestions.

# Answer
> 1 votes
# Factor \+ `poker`, 16 bytes

```
string>hand-name

```

Try it online!

---
Tags: code-golf, game
---


# Question
Title: Count the number of compositions of \$n\$ in which the greatest part is odd
A composition of an integer \\$n\\$ is a representation of \\$n\\$ as a sum of positive integers. For example the eight compositions of 4 are as follows:

```
4, 3 + 1, 1 + 3, 2 + 2, 2 + 1 + 1, 1 + 2 + 1, 1 + 1 + 2, 1 + 1 + 1 + 1.

```

The challenge is to output the number of compositions of \\$n\\$ in which the greatest part is odd.

The sequence has generating function

$$ \sum\_{n=1}^\infty \frac{(1-x)^2 x^{2n-1}}{(1-2x+x^{2n-1}) (1-2x+x^{2n})}$$

You only need to do this for n up to 33.

Your code should output the following numbers in order.

```
1 1
2 1
3 2
4 3
5 7
6 14
7 30
8 62
9 129
10 263
11 534
12 1076
13 2160
14 4318
15 8612
16 17145
17 34097
18 67764
19 134638
20 267506
21 531606
22 1056812
23 2101854
24 4182462
25 8327263
26 16588973
27 33066080
28 65945522
29 131588128
30 262702054
31 524699094
32 1048433468
33 2095744336

```

You only need to output the second column, not the first.

The numbers are taken directly from OEIS A103421.

# Answer
> 5 votes
# Python, 58 bytes

```
f=lambda n,m=0:sum(f(k,max(m,n-k))for k in range(n))or m%2

```

Try it online!

An exponential solution that implicitly generates all compositions by deciding at each branch how to split the current value `n` into the first part `n-k` and remaining parts adding to `k`. Tracks the running maximum `m`, and when the initial `n` is exhausted, returns `m%2` to indicate if the maximum part was odd.

---

**60 bytes**

```
f=lambda n,m=1,r=2:n>1and f(n-1,max(r,m),r+1)+f(n-1,m)or m%2

```

Try it online!

An exponential-time solution. Given `n`, it branches through all compositions of `n`, by deciding whether to increment the last summand or append a new summand of 1. Actually, we don't need to keep track of the entire composition, but only:

* `n`, the remaining value left to assign
* `m`, the maximum run length encountered so far
* `r`, the current run length plus one

When we increment the last summand, we bump up the run length and update the maximum to whichever is bigger of the current maximum and the new run length. When we append a new summand of 1, we reset the run length and keep the maximum. If either case, we decrement `n` because we've used up `1` value.

---

**Python 3, 68 bytes**

```
lambda n:sum(~len(max(f"{k:b}".split('0')))%2for k in range(2**~-n))

```

Try it online!

A slow exponential-time solution. Generates all \\$2^{n-1}\\$ compositions by taking all bit strings of length \\$n-1\\$, splitting on zeroes, taking the length-plus-one of each run of ones, and summing these lengths modulo 2.

Actually, since we only care about the longest run, we just take the max run after splitting, take its length, and flip the parity. And, we can just work with binary representations of numbers from \\$0\\$ to \\$2^{n-1}-1\\$ without padding to length \\$n-1\\$ because the omitted leading zeroes correspond to runs of length 1 which we can ignore.

# Answer
> 4 votes
# Python, 92 bytes

```
g=[17*[1,-1]]
r=range(33)
for i in r:g+=[sum(y[~k:])for*y,k in zip(*g,r)],;print(sum(g[-1]))

```

Attempt This Online!

Prints 33 terms.

### How?

First computes g(n,k), the number of compositions of n with all terms \<= k.

This satisfies g(n,k) = g(n-1,k) + ... + g(n-k,k). (Split the set of compositions into k subsets by the size of the first term.) Once we have those we can compute the odd-largest-term ones as f(n,2k+1) = g(n,1) - g(n,2) + ... + g(n,2k+1).

### Python, 114 bytes

```
n,*g=0,
while 1:g+=[sum([p[j]for p in g[~j:]if p[j:]]+g[~j][:j])for j in range(n)]+[1],;print(sum(g[n][::2]));n+=1

```

Attempt This Online!

Prints forever. Not very golfy but reasonably fast (O(n3)). Times out on ato after printing \>800 terms.

# Answer
> 3 votes
# 05AB1E, ~~15~~ 11 bytes

```
Åœ€œ€`Ù€àÉO

```

-4 bytes outputting the \\$n^{th}\\$ value instead of mapping over the ranged list \\$\[1,33\]\\$
Outputs as a list.

Very slow, and will time out for \\$n\geq9\\$ on TIO.

Try it online or (don't) verify all test cases.

**Explanation:**

```
Åœ          #  Get all unique lists of positive integers that sum to the (implicit) input
  €œ        #  Get the permutations of each list
    €`      #  Flatten the list of lists of lists by one level
      Ù     #  Uniquify the list of lists
       €à   #  Only leave the maximum of each list
         É  #  Check for each integer whether it's odd
          O #  Sum all those together
            # (after which the resulting list is output implicitly)

```

---

A faster version that outputs all values in ~3 seconds on TIO - **18 bytes**:
Port of *@Jonathan Allan*'s Jelly answer, so make sure to upvote him as well!

```
ÅœʒθÉ}εÅγygš!.»÷}O

```

Try it online or verify all test cases.

**Explanation:**

```
Åœ            # Same as above: all positive integer lists that sum to the input
  ʒ           # Filter this list of lists by:
   θ          #  Only leave the last/largest integer
    É         #  And check whether it's odd
  }ε          # After the filter: map over the remaining lists:
    Åγ        #  Run-length encode the list, pushing the list of items and list of
              #  lengths separately to the stack
      y       #  Push the current list again
       g      #  Pop and push its length
        š     #  Prepend this to the list of run-length encoded lengths
         !    #  Get the factorial of each
          .»  #  Left-reduce this list by:
            ÷ #   Integer-dividing
   }O         # After the map: sum everything together
              # (after which the result is output implicitly)

```

# Answer
> 3 votes
# x86-64 machine code, 27 bytes

```
31 C9 48 0F AB F9 6A 01 58 99 89 CF 41 F7 D2 8D 34 3F 21 F7 75 F7 29 D0 E2 EF C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes a value in EDI and returns a value in EAX.

The value taken is 0-indexed, so `n-1`, as permitted in the default rules. (For a version taking `n`, insert `dec edi` at the start for +2 bytes.)

In assembly:

```
f:  xor ecx, ecx    # Set ECX to 0.
    bts rcx, rdi    # Set to 1 the bit at position given by the argument.
    push 1; pop rax # Set EAX to 1.
ol: cdq             # Set EDX to 0 by sign-extending EAX.
    mov edi, ecx    # Copy the value of ECX into EDI.
    .byte 0x41      # REX.B prefix; combines with the next instruction
                    #  into "not r10", here effectively a no-op.
il: not edx         # Invert each bit of EDX, changing 0 to -1 or vice versa.
    lea esi, [rdi + rdi]    # Set ESI to 2*EDI.
    and edi, esi    # Bitwise-AND EDI with the doubled value.
    jnz il          # Jump back, to repeat the inner loop, if it's nonzero.
    sub eax, edx    # Subtract EDX from EAX.
                    # This adds 1 from EDX=-1 or is no change for EDX=0.
    loop ol         # Decrease ECX by 1, and jump back if it's nonzero.
    ret             # Return.

```

---

```
1 + 3 + 1  + 4    = 9
● ●—●—● ● ●—●—●—●
 0 1 1 0 0 1 1 1

```

A composition can be visualised as `n` dots, with each two consecutive dots either joined or not joined. Then, it can be represented by `n-1` bits, with each bit being 1 for joining or 0 for not joining. The greatest part is equal to 1 plus the maximum number of consecutive 1s in those bits.

```
Original:       0 1 1 0 0 1 1 1
Doubled:      0 1 1 0 0 1 1 1 0
Bitwise AND:    0 1 0 0 0 1 1 0

```

Take the bitwise AND with the value doubled: this reduces the length of each block of consecutive 1s by 1. Repeat until the result is 0; the number of repetitions is the maximum number of consecutive 1s.

The program loops from \\$2^{n-1}\\$ down to 1, and counts the compositions with the greatest part odd in EAX. \\$2^{n-1}\\$ is actually invalid, but it doesn't matter because it doesn't get counted.

0, which corresponds to the composition \\$1 + \cdots + 1\\$, is skipped because of the way the loop works (but it would have been a false negative anyway, because the inner loop always executes at least once). To correct for this, EAX is initialised to 1 instead of 0.

Because of the use of 32-bit registers for the calculation, when `n=33`, the first iteration uses a value of 0 instead of 232, but this makes no difference to the result.

# Answer
> 2 votes
# JavaScript (ES6), 47 bytes

*-3 bytes thanks to m90*

```
f=(n,m,i=1)=>i>n?!n&m:f(n-i,i<m?m:i)+f(n,m,i+1)

```

Try it online!

(limited to the 25 first terms on TIO)

### Commented

```
f = (         // f is a recursive function taking:
  n,          //   n = input
  m,          //   m = maximum value in the composition
  i = 1       //   i = value to be subtracted from n
) =>          //
i > n ?       // if i is greater than n:
  !n &        //   increment the final result if n = 0
  m           //   and m is odd
:             // else:
  f(          //   do a 1st recursive call where:
    n - i,    //     i is subtracted from n
    i < m ? m //     m is updated to max(m, i)
          : i //     (and i is implicitly reseted to 1)
  ) +         //   end of recursive call
  f(          //   do a 2nd recursive call where:
    n,        //     n is left unchanged
    m,        //     m is left unchanged
    i + 1     //     i is incremented
  )           //   end of recursive call

```

# Answer
> 2 votes
# Jelly,  ~~12~~  11 bytes

-1 by delaying the mod-2 check like Kevin Cruijssen's 05AB1E answer.

```
ŒṗŒ!€ẎQṀ€ḂS

```

A monadic Link that accepts a positive integer and yields the number of compositions with an odd largest part.

**Try it online!** (Slow - \\$9\\$ within \\$1\\$ minute on TIO)

Or, a faster version which can do all \\$33\\$ in under \\$12\\$ seconds on TIO in \\$15\\$ bytes (slightly slower than the \\$16\\$ byte version in the history of edits):

```
ŒṗµL;Œɠ!:/×ḂṪ)S

```

### How?

The slow one:

```
ŒṗŒ!€ẎQṀ€ḂS - Link: positive integer, n   e.g. 5
Œṗ          - integer partitions          [[1,1,1,1,1],[1,1,1,2],[1,1,3],[1,2,2],[1,4],[2,3],[5]]
  Œ!€       - all permutations of each    [[[1,1,1,1,1],[1,1,1,1,1],...],[[1,1,3],[1,3,1],[1,1,3],[1,3,1],[3,1,1],[3,1,1]],...,[[5]]
     Ẏ      - tighten                     [[1,1,1,1,1],[1,1,1,1,1],...,[1,1,3],[1,3,1],[1,1,3],[1,3,1],[3,1,1],[3,1,1],...,[5]]
      Q     - deduplicate                 [[1,1,1,1,1],...,[1,1,3],[1,3,1],[3,1,1],...,[5]]
       Ṁ€   - maximum of each             [1,2,2,2,2,3,3,3,2,2,2,4,4,3,3,5]
         Ḃ  - modulo 2                    [1,0,0,0,0,1,1,1,0,0,0,0,0,1,1,1]
          S - sum                         7

```

The faster version calculates the number of distinct permutations for each partition and sums them up instead:

```
ŒṗµL;Œɠ!:/×ḂṪ)S - Link: positive integer, n
Œṗ              - all partitions
                  (note: each are always in sorted order)
  µ          )  - for each: e.g. part = [2,2,2,4,5,5]
   L            -   length               6
     Œɠ         -   run-lengths         [3,1,2]
    ;           -   concatenate         [6,3,1,2]
       !        -   factorial           [720,6,1,2]
         /      -   reduce by:
        :       -     integer division   60
           Ḃ    -   (part) modulo 2     [0,0,0,0,1,1]
          ×     -   multiply            [0,0,0,0,60,60]
            Ṫ   -   tail                 60
              S - sum

```

# Answer
> 2 votes
# Regex  (RME / PCRE2 v10.35+), 45 bytes

```
^(?*(x(xx)*))(?(?=\1(x*))x+(?=\3($)?)|x+)+$\4

```

Takes its input in unary, as the length of a string of `x`s. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.)

Attempt This Online! \- PCRE2 v10.40+
Try it on replit.com \- RegexMathEngine

```
^               # tail = input number
(?*
    (x(xx)*)    # \1 = {any odd number, which shall be the maximum
                        partition width}
)
(?(?=
    \1(x*)      # \3 = tail - \1
  )
    # If the above condition (tail ≥ \1) is true:
    x+          # tail -= {any positive number}
    (?=\3($)?)  # Assert tail ≥ \3; if tail == \3, set \4 = 0
|
    # Else:
    x+          # tail -= {any positive number}
)+              # Iterate the above any positive number of times
$               # Assert tail == 0
\4              # Assert that \4 is set, i.e. that the chosen maximum
                # partition width occurred at least once.

```

# Answer
> 2 votes
# Vyxal, 10 bytes

```
ṄvṖÞfUvG∷∑

```

Try it Online!

Port of 05AB1E. Very slow.

```
ṄvṖÞfUvG∷∑   # example input: 3
Ṅ            # integer partitions => [[1, 1, 1], [2, 1], [3]]
 vṖ          # permutations of each => [[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]], [[2, 1], [1, 2]], [[3]]]
   Þf        # flatten by one level => [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [2, 1], [1, 2], [3]]
     U       # uniquify => [[1, 1, 1], [2, 1], [1, 2], [3]]
      vG     # max of each => [1, 2, 2, 3]
        ∷    # modulo each by 2 => [1, 0, 0, 1]
         ∑   # sum => 2

```

# Answer
> 2 votes
# Japt, 14 bytes

No integer partitions in Japt but a port of xnor's Python solution works out at a respectable length. Completes for input `33`, and beyond, in milliseconds.

```
ÆßXVwXnUÃx ªVu

```

Try it

```
ÆßXVwXnUÃx ªVu     :Implicit input of integers U and V, the latter of which defaults to 0
Æ                  :Map each X in the range [0,U)
 ßX                :  Recursive call with arguments X and
   Vw              :    Max of V and
     XnU           :      U-X
        Ã          :End map
         x         :Reduce by addition
           ª       :Logical OR with
            Vu     :V%2

```

# Answer
> 1 votes
# Desmos, 121 bytes

```
f(n)=1+∑_{k=1}^{n^n-1}0^{(n-total(AL))^2+mod(L[A>0].max-1,2)}A.total!/∏_{i=1}^nA![i]
L=[1...n]
A=mod(floor(nk/n^L),n)

```

What can I say, Desmos just isn't that great at problems involving counting partitions, especially ones where order matters.

Also, this is very inefficient. It can't even calculate \\$n=10\\$ in a reasonable amount of time, let alone \\$n=33\\$. This is because it tests \\$n^n-1\\$ different partitions; as you can imagine, that is not efficient at all.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 1 votes
# Python3, 425 bytes:

```
import math as M,itertools as I
R=range
Y=lambda x:x[0]if 1==len(x)else x[0]*Y(x[1:])
def f(n,s,c):
 if n==0:yield c;return
 for i in{*R(1,s+1)}-{*c}:
  for x in R(1,n//i+1):
   if i*x<=n:yield from f(n-i*x,s,c+[i]*x)
def F(n):
 t=[]
 for i in R(1,n+1):
  if i%2:t+=[tuple(sorted(j))for k in R(1,n//i+1)for j in f(n-i*k,i,[i]*k)]
 return sum(M.factorial(len(j))/Y([M.factorial(len([*b]))for _,b in I.groupby(j)])for j in{*t})

```

Try it online!

Prints all 33 results in ~10 seconds.

# Answer
> 1 votes
# PARI/GP, 52 bytes

-13 bytes thanks to @xnor.

```
n->sum(i=0,2*n,(-1)^i*(1-x)/(1-2*x+x^i))%x^(n+1)\x^n

```

Attempt This Online!

Using the generating function.

# Answer
> 1 votes
# Wolfram Language (Mathematica), 42 bytes

```
Mod[Max@## 2^#,2]+#0[#-i,##2,i]~Sum~{i,#}&

```

Try it online!

Slow recursive solution.

# Answer
> 1 votes
# Haskell + hgl, (slow) 16 bytes

```
cn od<xMl<<pt<e1

```

**Alternative 1**

```
cn(od<xMl)<pt<e1

```

**Alternative 2**

```
l<pST(od<xMl)<e1

```

## Explanation

* `e1`: Create a list from \\$1\\$ to \\$n\\$.
* `pt`: Get all partitions of the list.
* `xMl<`: Get the length of the largest part in each partition.
* `cn od`: Count the number of odd results.

## Reflection

I've not spent much focus on arithmetic in hgl, so I am pretty pleased with this. The use of `xMl` here is brutally efficient. That being said there are some things I think could be improved.

* There's no function which takes mod 2. You can do `fmu 2`, but that's really long. Small modulos should have builtins. This wouldn't make this answer shorter, but I noticed this.
* There should be a function for finding integer partitions. `l<<pt<e1` is *way* too long, and this will likely come up again. With a function for integer partitions, `ipt`, this whole thing could be `cn od<mx<<ipt` which would save 3 bytes.

# Answer
> 1 votes
# APL (Dyalog Extended), 31 bytes

```
{2+.|⌈/¨∪((∨\⍢⌽⍵=+\)¨⊆⍥∊⊢)⍳⍴⍨⍵}

```

Try it online!

```
    ⍳⍴⍨ all permutations of 1..n
      (∨\⍢⌽⍵=+\)¨ mask contiguous subsets which compose to n
        ⊆⍥∊ partition compositions
    ∪ uniques
    ⌈/¨ greatest of each
    2+.| count odds

```

Same length in BQN: `{+´2|0⌈´¨⍷⥊(∨`⌾⌽=+`)⊸/¨1+↕⥊˜}`

# Answer
> 0 votes
# Charcoal, 25 bytes

```
ＩＥφＬΦＥＸφφ↨λφ∧⌊λ∧⁼⊕ιΣλ﹪⌈λ²

```

Don't try it online, or indeed offline, because it needs unreasonable amounts of time and memory. Instead, here's a link that computes 6 values instead:

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

```
  φ                         Predefined variable `1000`
 Ｅ                          Map over implicit range
       φ                    Predefined variable `1000`
      Ｘ                     Raised to power
        φ                   Predefined variable `1000`
     Ｅ                      Map over implicit range
          λ                 Current value
         ↨                  Converted to base
           φ                Predefined variable `1000`
    Φ                       Filtered where
              λ             List of base `1000` digits
             ⌊              Minimum
            ∧               Logical And
                  ι         Outer value
                 ⊕          Incremented
                ⁼           Equals
                    λ       List of base `1000` digits
                   Σ        Summed
               ∧            Logical And
                       λ    List of base `1000` digits
                      ⌈     Maximum
                     ﹪      Modulo
                        ²   Literal integer `2`
   Ｌ                        Take the length
Ｉ                           Cast to string
                            Implicitly print

```

36 bytes for a slightly faster version:

```
⊞υ⟦⁰⟧ＦυＦ⁻φΣι⊞υ⁺ι⟦⊕κ⟧ＩＥφＬΦυ∧⁼⊕ιΣλ﹪⌈λ²

```

Don't try it online, because it still tries to compute 1,000 values. Instead, here's a link that computes 10 values instead:

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

```
⊞υ⟦⁰⟧

```

Start with a sum of `0`.

```
Ｆυ

```

Loop over all of the sums so far.

```
Ｆ⁻φΣι

```

Find integers to add to this sum without exceeding 1,000.

```
⊞υ⁺ι⟦⊕κ⟧

```

Add the new sum to the list of sums.

```
ＩＥφＬΦυ∧⁼⊕ιΣλ﹪⌈λ²

```

Count how many sums with odd maxima sum to each integer up to 1,000.

42 bytes for a slightly faster still version:

```
Ｆφ⊞υＥφ⎇κ⎇›κι⁰Σ⁺…§υ±κκＥ…⮌υκ§μκ¬ιＩＥΦυκΣΦι﹪μ²

```

Don't try it online, because it still tries to compute 999 values. Instead, here's a link that computes 9 values instead:

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

```
Ｆφ

```

Loop 1,000 times.

```
⊞υＥφ⎇κ⎇›κι⁰Σ⁺…§υ±κκＥ…⮌υκ§μκ¬ι

```

Calculate the matrix `f(n, m)` of the number of sums of compositions of `n` whose maximum is `m`. The "first" row for `n=0` is simply `1, 0...` and subsequent rows are calculated by moving up `m` cells and left `m` cells and summing the passed-over cells.

```
ＩＥΦυκΣΦι﹪μ²

```

For each `n>0`, sum those `f(n, m)` where `m` is odd.

Example: The first few rows of `f` look like this:

```
1   0   ...
-----------
0   1   0   ...
--------------+
0   1   1   0 | ...
----------+   |
0   1   2 | 1 | 0 | ...
------+   |   |   |
0   1 | 4 | 2 | 1 | 0 | ...
--+   |   |   |   |   |
0 | 1 | 7 | 5 | 2 | 1 | 0 | ...

```

These are calculated as `1 = 1 + 0`, `7 = 4 + 2 + 1 + 0`, `5 = 2 + 1 + 0 + 1 + 1 + 0`, `2 = 1 + .... + 1 + 0`, `1 = ... + 1`.

This final version can be adapted to calculate exactly 33 values, but that takes 44 bytes: Try it online! Link is to verbose version of code.

# Answer
> 0 votes
# Pyth, 14 bytes

```
sm&%ed2l{.pd./

```

Try it online!

## Explanation

```
sm&%ed2l{.pd./Q
s                  # sum(
 m                 #   map(
                   #     lambda d:
   %ed2            #       (d[-1] % 2)
  &                #         and  # short-circuiting
       l{.pd       #       len(unique(permutations(d)),
            ./Q    #     partitions(input)  # partitions are sorted
                   #   )
                   # )

```

# Answer
> 0 votes
# Haskell, (slow) 49 bytes

```
0!u=mod u 2
x!u=sum[(x-i)!max u i|i<-[1..x]]

```

```
(!0)

```

Try it online!

---
Tags: code-golf, math, sequence, integer-partitions
---


title: Can you connect the dots?

text:
# Question
Title: Can you connect the dots?
This challenge is based off of Flow Free. An online version can be found here: http://www.moh97.us/

You will be given a puzzle, and you must return `1` if the puzzle is solvable, or `0` if it is not.

To solve a puzzle, the player must create a path to connect each pair of numbers using every empty square exactly once.

You are passed in the dimensions of the square, and then the x,y,c (where c is a number representing the color) of each dot. For example:

If `5,5` `0,0,0` `3,0,1` `1,1,2` `1,2,2` `4,2,1` `4,4,0` was passed to you, it would represent:

```
0..1.
.2...
.2..1
....0

```

And should return 1.

---

Here are some more test problems:

`5,2` `2,0,1` `0,1,2` `4,1,2` represents:

```
..1..
2...2

```

and is not solvable because there is only 1 `1`.

`4,2` `0,0,0` `3,0,0` `0,1,0` `3,1,0` represents:

```
0..0
0..0

```

and is not solvable because it includes more than 2 `0`s.

`8,6` `0,0,1` `7,5,1` represents:

```
1.......
........
........
........
........
.......1

```

and is not solvable (as you can't use every square).

`2,5` `0,0,1` `2,0,6` `4,0,6` `0,1,4` `3,1,4` `4,1,1` represents:

```
1.6.6
4..41

```

and is not solvable because you cannot connect the 1s.

`6,3` `1,0,4` `5,0,1` `0,1,4` `1,1,3` `5,1,3` `0,2,2` `3,2,2` `5,2,1` represents:

```
.4...1
43...3
2..2.1

```

and is not solvable because you cannot connect the 1s (or the 3s), as the two paths must necessarily cross.

`5,2` `0,0,1` `3,0,1` `0,1,3` `4,1,1` represents:

```
1..1.
3...3

```

and is not solvable because you cannot use all of the squares in building a path.

`2,2` `0,0,0` `1,1,0` represents:

```
1.
.1

```

and is not solvable because you can't use all of the squares here either

Here are some more tests:

`5,5` `0,3,0` `0,4,1` `1,2,2` `1,3,1` `2,0,0` `3,0,4` `3,1,2` `3,3,5` `3,4,4` `4,4,5` should return 1

`13,13` `1,1,0` `9,1,1` `10,1,2` `11,1,3` `1,2,4` `2,2,5` `5,2,6` `7,2,7` `3,3,0` `5,4,6` `6,4,1` `9,6,3` `4,7,8` `5,8,9` `12,8,8` `11,9,10` `2,10,4` `4,10,2` `9,10,5` `11,10,7` `1,11,9` `12,12,10` should return 1

`7,7` `0,0,0` `0,1,1` `1,1,2` `2,1,3` `4,2,4` `0,3,1` `5,3,3` `0,4,4` `2,4,5` `5,4,2` `0,5,0` `1,5,5` `3,5,6` `3,7,6` should return 0

---

This is a code golf, and the standard rules apply.

# Answer
> 3 votes
## Haskell

```
import Data.List.Split
import qualified Data.Sequence as Q
import Data.List
import Control.Monad

data A a = S a | E a | P a | X deriving Eq

sc = foldr1 (Q.><)
sp b x y p = Q.update y (Q.update x p $ b `Q.index` y) b
dt b c | S c `elem` sc b = E c
       | otherwise = S c
ad b [x, y, c] = sp b x y (dt b c)

ep b [x, y, c] = do
  let nps = filter ob [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]
      ns = map gp nps
  [b | E c `elem` ns] ++ do
    (x', y') <- filter ((== X) . gp) nps
    ep (sp b x' y' (P c)) [x', y', c]
  where ob (u, v) = 0 <= u && u < length (b `Q.index` 0) && 0 <= v && v < length b
        gp (u, v) = b `Q.index` v `Q.index` u

rd i = let [c, r] : ps = (map read . splitOn ",") <$> words i :: [[Int]]
           e = Q.replicate r $ Q.replicate c X
           cs = map last ps
           ss = nubBy (\[_,_,c1] [_,_,c2] -> c1 == c2) ps
           b = foldl ad e ps
           bs = foldM ep b ss
       in if even (length cs) && length ss == length cs `div` 2 &&
             (all (\[j,k] -> j==k) . chunksOf 2 . sort $ cs) &&
             any (null . Q.elemIndicesL X . sc) bs
           then 1
           else 0

main = rd <$> getContents >>= print

```

### Key

* sc: Seq concat
* sp: set position
* dt: dot type (ie, start or end of line)
* ad: add dot
* ep: extend path
* rd: run dots (primary pure algorithm)

# Answer
> 0 votes
# Python3, 538 bytes:

```
R=range
def f(x,y,v):
 d={}
 for j in R(x):
  for k in R(y):d[r]=d.get(r:=v.get((j,k),-1),[])+[(j,k)]
 if any(i!=-1 and len(d[i])!=2 for i in d):return 0
 D=eval(str(d));del D[(M:=max(d))][0]
 q=[(M,D,d[M][0],0)]
 while q:
  M,D,(j,k),C=q.pop(0)
  if(j,k)in D[M]:
   Y=eval(str(D));del Y[M]
   if(M:=max(Y))!=-1:q+=[(M,Y,Y[M][0],0)];del Y[M][0]
   if{-1:[]}==Y:return 1
   continue
  for J,K in[(-1,0),(1,0),(0,1),(0,-1)]:
   if(T:=(j+J,k+K))in D[-1]:Y=eval(str(D));Y[-1].remove(T);q+=[(M,Y,T,C+1)]
   elif T in D[M]and C:q+=[(M,D,T,C+1)]

```

Try it online!

---
Tags: code-golf, puzzle-solver
---


title: Carryless factors

text:
# Question
Title: Carryless factors
Carryless multiplication is an operation similar to binary long multiplication, but with XOR instead of addition:

```
  1011    11
×  101     5
 -----
  1011
    0
1011
------
100111    39

```

In this challenge, you'll be given a positive integer `>= 2`, and must return a list of all positive integers which are carryless factors of that number, meaning that they can be carryless-multiplied by another number to get the input. For example, for 39, 5 and 11 would be two of those.

Rules:

* You may choose whether or not to include 1 and/or the input itself
* You may output the factors in any order, and may include duplicates
* You may choose how to represent the numbers (binary strings are allowed)

Test cases:

```
2       (1) (2)
4       (1) 2 (4)
5       (1) 3 (5)
6       (1) 2 3 (6)
25      (1) (25)
39      (1) 3 5 11 29 (39)
42      (1) 2 7 14 21 (42)
100     (1) 2 4 25 50 (100)
574     (1) 2 3 5 6 7 9 10 11 14 15 18 22 27 29 30 39 45 49 54 58 78 83 90 98 105 166 210 245 287 490 (574)
5040    (1) 2 3 4 6 7 8 9 12 13 14 16 18 21 23 24 26 28 35 36 42 46 48 52 56 63 70 72 84 92 101 104 112 126 140 144 168 184 202 208 233 252 280 315 336 368 404 466 504 560 630 808 932 1008 1260 1616 1864 2520 3728 (5040)
848640  (1) 2 3 4 5 6 7 8 9 10 12 14 15 16 17 18 20 21 24 27 28 30 32 34 36 40 42 45 48 51 54 56 60 63 64 65 68 72 80 84 85 90 96 102 108 112 119 120 126 128 130 136 144 153 160 168 170 180 192 195 204 216 224 238 240 252 255 256 260 272 288 306 320 325 336 340 360 384 390 408 427 432 448 476 480 504 510 520 544 576 612 640 650 672 680 720 765 768 780 816 854 864 896 952 960 975 1008 1020 1040 1088 1105 1152 1224 1280 1300 1344 1360 1440 1530 1560 1632 1708 1728 1792 1904 1920 1950 2016 2040 2080 2176 2210 2304 2448 2600 2688 2720 2880 3060 3120 3264 3315 3416 3456 3808 3840 3900 4032 4080 4160 4352 4420 4896 5200 5376 5440 5760 6120 6240 6528 6630 6832 6912 7616 7800 8064 8160 8320 8840 9792 10400 10880 11520 12240 12480 13056 13260 13664 15232 15600 16128 16320 16640 17680 19584 20800 21760 24480 24960 26520 27328 30464 31200 32640 35360 39168 41600 48960 49920 53040 54656 62400 65280 70720 83200 97920 106080 109312 124800 141440 195840 212160 249600 282880 424320 (848640)

```

This is , shortest answer in bytes (per language) wins!

# Answer
# JavaScript (V8), 69 bytes

*-4 by using a single loop as in @jdt's C port*
*-1 thanks to another suggestion from @jdt*

Prints all carryless factors, excluding 1 and the input itself.

```
n=>{for(p=n*n;--p;g(p/n|0,q=p%n)^n||print(q))g=p=>p&&p%2*q^g(p>>1)*2}

```

Try it online!

Or **68 bytes** for a much slower version relying on arithmetic underflow:

```
n=>{for(p=n*n;--p;g(p/n,q=p%n)^n||print(q))g=p=>p&&(p&1)*q^g(p/2)*2}

```

Try it online!

### Commented

```
n => {            // n = input
  for(            // loop:
    p = n * n;    //   start with p = n²
    --p;          //   decrement p until p = 0
    g(            //   invoke g with:
      p / n | 0,  //     floor(p / n)
      q = p % n   //     q = p mod n
    )             //   end of call
    ^ n           //   XOR the result with n
    || print(q)   //   print q if the result of g is equal to n
  )               //
    g = p =>      //   g is a recursive function taking p:
      p &&        //     stop if p = 0
      p % 2 * q ^ //     XOR the result with q if the LSB of p is set
      g(p >> 1)   //     recursive call with p right-shifted by 1
      * 2         //     double the result to account for the shift
}                 //

```
> 7 votes

# Answer
# Jelly,  ~~12~~  11 bytes

```
B€æcþ`Ḃċ€BT

```

A monadic Link that accepts an integer and yields a list of integers.

**Try it online!** Or see the test-suite (reduced set as code is slow).

### How?

```
B€æcþ`Ḃċ€BT - Link: integer, n
 €          - for each i in [1,n]:
B           -   convert to binary
     `      - use as both arguments of:
    þ       -   table with:
  æc        -     convolution
      Ḃ     - modulo 2 (vectorises)
         B  - convert n to binary
        €   - for each row in the table:
       ċ    -   count occurrences (of n in binary)
          T - truthy indices

```
> 6 votes

# Answer
# PARI/GP, 55 bytes

```
n->[eval(lift(d))|d<-divisors(Mod(Pol(binary(n)),x=2))]

```

Attempt This Online!

This is just factoring in the polynomial ring \\$\mathbb{F}\_2\[x\]\\$.

---

## PARI/GP, 56 bytes

```
n->[d|d<-[1..n],!(g(n)%g(d))]
g(n)=Mod(Pol(binary(n)),2)

```

Attempt This Online!
> 4 votes

# Answer
# Wolfram Language (Mathematica), ~~54~~ 53 bytes

```
BitXor@@(#~NumberExpand~2#2)&~Array~{#,#}~Position~#&

```

Try it online!

Returns all pairs that xor-multiply to the input.

Loosely based on alephalpha's answer to the multiplication question. `NumberExpand` was introduced in 2016 with version 11.0.
> 4 votes

# Answer
# C (gcc), ~~89~~ 86 bytes

```
i;r(k,p){k=k?k%2*p^r(k/2,p*2):0;}f(n){for(i=n*n;--i;)r(i/n,i%n)^n||printf("%d ",i%n);}

```

Try it online!

Port of Arnauld's answer

-2 bytes thanks to AZTECCO

-2 bytes thanks to Arnauld
> 3 votes

# Answer
# 05AB1E, 18 bytes

```
LʒULε0sbv·yX*^}Q}à

```

Try it online or verify (almost) all test cases (the largest two test cases are omitted because they'll time out).

**Explanation:**

```
L              # Push a list in the range [1, (implicit) input]
 ʒ             # Filter it by:
  U            #  Pop and put the current integer in variable `X`
  L            #  Push a list in the range [1, (implicit) input] again
   ε           #  Map it to:
    0          #   Push a 0
     s         #   Swap so the current map-integer is at the top
      b        #   Convert it to a binary string
       v       #   Loop over each bit `y` of this string:
        ·      #    Double the current integer
         y     #    Push bit `y`
          X*   #    Multiply it by integer `X`
            ^  #    Bitwise-XOR the two integers together
       }Q      #   After the loop: check if it's equal to the (implicit) input
   }à          #  After the map: max to check if any was turthy
               # (after which the filtered list is output implicitly as result)

```
> 3 votes

# Answer
# Java 8, ~~120~~ ~~119~~ 117 bytes

```
n->{for(int x=n,y,r,i;x>0;)for(y=x--;--y>0;System.out.print(r==n?x+" "+y+" ":""))for(r=i=0;i<32;)r^=(y>>i&1)*x<<i++;}

```

-2 bytes thanks to *@ceilingcat*.

Outputs the results space-delimited to STDOUT in pairs, excluding `1`/`n` (to save a byte). May contain duplicates if a pair of the same integer XOR-multiplies into the input (e.g. `n=4`).
Limited to `n=2147483647`, but could be raised to `n=9223372036854775807` by changing `int`/`32` to `long`/`64` (although already times out for test case `n=848640` anyway, tbh..)

Try it online.

**Explanation:**

```
n->{                         // Method with integer parameter and no return-type
  for(int x=n,y,r,i;         //  Temp-integers
      x>0;)                  //  Loop `x` in the range [n,0):
    for(y=x--;--y>0          //   Inner loop `y` in the range [x,0):
        ;                    //     After every iteration:
         System.out.print(   //      Print:
          r==n?              //       If `r` is equal to input `n`:
           x+" "+y+" "       //        Print `x` and `y` with space delimiters
          :                  //       Else:
           ""))              //        Print nothing instead
      for(r=i=0;             //    Reset `r` and `i` both to 0
          i<32;)             //    Inner loop `i` in the range [0,32):
        r^=                  //     Bitwise-XOR `r` by:
           (y>>i             //      Bitwise right-shift `y` by `i` positions
                &1)          //      Modulo-2 that (using Bitwise-AND by 1, so we won't
                             //                     need parenthesis)
                   *x        //      Multiply that by `x`
                     <<i     //      Bitwise left-shift that by `i` positions
                        ++;} //      And increase `i` by 1 afterwards with `i++`

```
> 3 votes

# Answer
# Ruby, ~~70~~ 68 bytes

```
->n{(k=0..n).select{|b|k.any?{|a|r=0
k.map{|x|r^=a*(b&2**x)}
r==n}}}

```

Try it online!

* Saved 2 thanks to @G B reminding me that *f=* doesn't need to be counted.

Very inefficient lambda function.

Uses the range (0..input) three times: check each number up to input, try carryless multiply it for each and bitmask 2nd operand by 2^ each.
> 3 votes

# Answer
# Vyxal, 18 bytes

```
'£?ƛ0$b(dn¥*꘍)?=;a

```

Try it Online!

Port of 05AB1E.
> 2 votes

# Answer
# Charcoal, 48 bytes

```
ＮθＦθ«≔θηＦ⮌×⊕ιＸ²…·⁰⁻Ｌ↨θ²Ｌ↨⊕ι²≔⌊⟦η⁻｜ηκ＆ηκ⟧η¿¬η⟦Ｉ⊕ι

```

Try it online! Link is to verbose version of code. Outputs includes `1` and `n` as divisors. Explanation:

```
Ｎθ

```

Input `n`.

```
Ｆθ«

```

Loop up to `n`. (The loop variable is incremented whenever it is used effectively looping the trial factor from `1` to `n` inclusive.)

```
≔θη

```

Start with `n`.

```
Ｆ⮌×⊕ιＸ²…·⁰⁻Ｌ↨θ²Ｌ↨⊕ι²

```

Take all possible shifts of the trial factor up to and including the same length as `n`, highest first.

```
≔⌊⟦η⁻｜ηκ＆ηκ⟧η

```

Perform trial division by updating the running total with the XOR of the running total with the current shifted trial factor if this reduces it.

```
¿¬η⟦Ｉ⊕ι

```

If there was no remainder then output the trial factor.
> 1 votes

# Answer
# Python 2, 78 bytes

```
N=k=input()
while k:
 k-=1;i=n=N
 while i:i-=1;n=min(k<<i^n,n)
 if n<1:print k

```

Try it online!

Prints the factors backwards, excluding the input itself.

The idea is to test divisibility using a carryless analogue of long-division to compute the remainder and see if it's zero.

The number `k` is a factor of `n` if we can xor some collection of leftward bit-shifts of `k` onto `n` to get zero. It suffices to use the greedy strategy of making `n` as small as possible at each step, which is achieved by clearing the leftmost bit of `n` (without introducing larger-valued bits) by taking the bit-shift of `k` whose leftmost bit aligns with that of `n`.

The code achieves this by taking the bit-shifts `k<<i` for some large `i` counting down to `0`, and checking if xor-ing this value onto `n` makes `n` smaller.

An alternative approach to repeatedly try to clear the rightmost bit of `n` while shifting `k` leftward.

**Python 2, 79 bytes**

```
N=k=input()
while k:
 n=N;c=k=k-1;exec"n^=c*(n&c&-c>0);c*=2;"*N
 if n<1:print k

```

Try it online!
> 1 votes

---
Tags: code-golf, math, integer, binary, factoring
---


title: Find the nth Mersenne Prime

text:
# Question
Title: Find the nth Mersenne Prime
> A number is a Mersenne Prime if it is both prime and can be written in the form 2m-1, where m is a positive integer.

**For example:**

* 7 is a Mersenne Prime because it is 23-1
* 11 is not a Mersenne Prime because it cannot be written as 2m-1
* 15 is not a Mersenne Prime because it is not prime

**The first few Mersenne primes:**

* 3
* 7
* 31
* 127
* 8191

**Your task:**

* Take a user input (it will be a positive integer) - let's call it n
* Find the nth Mersenne prime and output it in the format shown below

**Example output:**

With an input of `4`, the output should be `127`. (But this is so any form of output is allowed)

---

I'll add my attempt at this as an answer, but I'm sure that it can be golfed down a bit.

As this is , all languages are accepted, and the shortest answer wins!

# Answer
> 4 votes
# Vyxal `G`, 7 bytes

```
Þ∞E‹~æẎ

```

Try it Online!

7 bytes flagless (change  to `i`) if 0-indexing is allowed.

## But how?

```
Þ∞E‹~æẎ
Þ∞      # all positive integers
  E‹    # as the power of 2 minus 1 (basically, all numbers that are of the form 2^m -  1)
    ~æ  # with only primes kept
      Ẏ # take the first (input) items
# The -G flag outputs the biggest of the final list

```

# Answer
> 5 votes
# JavaScript (ES6), 50 bytes

Returns the \\$n\\$-th Mersenne prime, 1-indexed.

```
n=>{for(k=1;n;n-=d<2)for(d=k-=~k;k%--d;);return k}

```

Try it online!

# `eval()` version, 48 bytes

*Suggested by @Steffan*

```
n=>eval(`for(k=1;n;n-=d<2)for(d=k-=~k;k%--d;)k`)

```

Try it online!

### How?

Numbers of the form \\$2^n-1,\\:n\>1\\$ can be computed recursively with:

$$\begin{cases} a(0)=3\\a(n)=2\times a(n-1)+1\end{cases}$$

Hence the golfed recurrence formula: `k-=~k`.

### Commented

```
n => {         // n = input
  for(         // outer loop:
    k = 1;     //   start with k = 1
    n;         //   stop when n = 0
               //   after each inner loop,
    n -= d < 2 //   decrement n if d = 1 (i.e. k is prime)
  )            //
    for(       //   inner loop:
      d =      //     update k to the next number of the form 2**N - 1
      k -= ~k; //     and initialize the divisor d to the same value
      k % --d; //     decrement d until it divides k
    );         //
  return k     // k is the n-th Mersenne prime: return it
}              //

```

# Answer
> 4 votes
# Factor \+ `math.primes.lucas-lehmer`, 48 bytes

```
[ 1 lfrom [ lucas-lehmer ] lfilter lnth 2^ 1 - ]

```

Try it online!

0-indexed.

* `1 lfrom` A lazy list of the natural numbers
* `[ ... ] lfilter` Select the ones that...
* `lucas-lehmer` ...are Mersenne numbers
* `lnth` Take the nth one
* `2^ 1 -` Turn a Mersenne number into a Mersenne prime

# Answer
> 4 votes
# Python 2, 56 bytes

```
f=lambda k,n=1,p=1:k and f(k-(p%n>n&n+1),n+1,p*n*n)or~-n

```

Try it online!

Uses the Wilson's Theorem prime generator, which could be implemented like this to find the `k`'th prime:

```
f=lambda k,n=1,p=1:k and f(k-p%n,n+1,p*n*n)or~-n

```

Try it online!

But, modifies it to count only numbers of the form \\$2^a-1\\$ which are tested for as `n&n+1==0`. This is combined with the primality check as `p%n>n&n+1`.

Because this method recurses through all potential primes whether or not they have form \\$2^a-1\\$, it already exceeds the default maximum recursion depth for inputs of 5 and above.

**Python 2, 65 bytes**

```
f=lambda k,n=3:k and f(k-all(n%d for d in range(2,n)),n-~n)or n/2

```

Try it online!

Recurses through numbers of the \\$2^a-1\\$ by repeatedly applying `n->2*n+1`, using trial division to test for primality.

# Answer
> 3 votes
# Python, 57 bytes

```
a=1
while 1:a-=~a;0in(a%d for d in range(2,a))or print(a)

```

Attempt This Online!

`a-=~a` taken from Arnauld's JS answer

# Answer
> 3 votes
# C (gcc), ~~63~~ 51 bytes

```
d;k;f(n){for(k=1;n;n-=d<2)for(d=k-=~k;k%--d;);n=k;}

```

Try it online!

*A port of Arnauld's JavaScript answer.*
*Saved a whopping 13 bytes thanks to Steffan!!!*

Inputs positive integer \\$n\\$.
Returns the 1-based \\$n^{\text{th}}\\$ Mersenne prime.

# Answer
> 3 votes
# Prolog (SWI), 85 bytes

```
Y+X:-X mod Y<1->Y<X;Y+1+X.
Q-N-R:-2+Q,Q- \Q-N-R;N>1,Q- \Q-(N-1)-R;R is Q.
W-R:-3-W-R.

```

Try it online!

-4 bytes thanks to Jo King

# Answer
> 3 votes
# Jelly, 7 bytes

```
&‘<Ẓø#Ṫ

```

Try it online!

```
     #     Count up the first n matches
      Ṫ    then take the last
    ø      starting from 0:
&          Is the candidate bitwise AND
 ‘         itself + 1
  <        less than
   Ẓ       whether or not it's prime?

```

# Answer
> 2 votes
# Python 3, ~~116 99 88~~ 85 bytes

```
def f(n,i=1,j=0):
 while j!=n:i+=1;m=2**i-1;j+=all(m%k for k in range(2,m))
 print(m)

```

Try it online!

* (-24 thanks to Jo King)
* (-4 thanks to pxeger)

# Python+, 78 73 bytes

```
n=int(§())
i=1
j=0
€j!=n
 i+=1;m=2**i-1;j+=all(m%k£k:range(2,m))
$(m)

```
* (-1 thanks to pxeger)
* (-4 thanks to Jo King)

# Answer
> 2 votes
# Wolfram Language (Mathematica), 28 bytes

```
2^MersennePrimeExponent@#-1&

```

Try it online!

# Answer
> 2 votes
# Husk, 7 bytes

```
!fṗm←İ2

```

Try it online!

```
!fṗm←İ2
   m    # map over
     İ2 # powers of 2
    ←   # decrementing each one
 f      # then filter to keep only
  ṗ     # primes
!       # and get the input-th one.

```

# Answer
> 2 votes
# Brachylog, 14 bytes

```
;2{;X≜^-₁ṗ}ᶠ⁽t

```

Try it online!

Worth noting it started with `∧{≜;2↔^-₁ṗ}ᶠ↖?t`.

```
;2{       }ᶠ⁽     Find the first n possible outputs given 2 from:
   ;X             pair the 2 with an unbound variable,
     ≜            label the variable to an integer,
      ^           raise the 2 to that power,
       -₁         subtract 1,
         ṗ        and fail if not prime.
             t    Yield only the last of the results.

```

# Answer
> 2 votes
# 05AB1E, 5 bytes

```
∞o<ʒp

```

Outputs the infinite sequence.

Try it online.

Outputting the 1-based \\$n^{th}\\$ value like the example in the challenge description, would be **8 bytes** in the legacy version of 05AB1E instead:

```
µNbSPNp*

```

Try it online.

**Explanation:**

```
∞      # Push an infinite list of positive integers: [1,2,3,...]
 o     # Take 2 to the power each: [2,4,8,...
  <    # Decrease each by 1: [1,3,7,...]
   ʒ   # Filter this list by:
    p  #  Only keep the prime numbers
       # (after which the result is output implicitly)

µ      # Continue looping while `¾` is not equal to the (implicit) input-integer:
       # (counter variable `¾` is 0 by default)
 N     #  Push the loop-index
  b    #  Convert it to a binary string
   S   #  Convert it to a list of digits
    P  #  Check if all bits are 1 by taking the product
 N     #  Push the loop-index again
  p    #  Check whether it's a prime number
     * #  Check if both are truthy
       #  (if they are: implicitly increase `¾` by 1)
       # (after which the last index `N` is output implicitly as result)

```

# Answer
> 1 votes
# Retina, 38 bytes

```
\d+
_
$
_$`
"$+"}/^(__+)\1+$/+`$
_$`
_

```

Try it online! No test suite due to the program's use of history. Explanation:

```
\d+
_

```

On the first pass through the loop, replace the input with `1` in unary.

```
$
_$`

```

Double and increment the value.

```
/^(__+)\1+$/+`

```

While the value is composite...

```
$
_$`

```

... double and increment the value.

```
"$+"}

```

Repeat the above `n` times.

```
_

```

Convert to decimal.

# Answer
> 1 votes
# Charcoal, 26 bytes

```
Ｎθ≔¹ηＷθ«≔⊕⊗ηη≧⁻﹪±Π…¹ηηθ»Ｉη

```

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

```
Ｎθ

```

Input `n`.

```
≔¹η

```

Start with `1`.

```
Ｗθ«

```

Repeat until `n=0`.

```
≔⊕⊗ηη

```

Double and increment the value.

```
≧⁻﹪±Π…¹ηηθ

```

If the value is prime then decrement `n`. For decremented powers of 2, `(n-1)!%-n` is either `0` for composite or `-1` for prime. (In fact, `(n-1)!²%n` is `0` for any positive non-prime and `1` for any prime.)

```
»Ｉη

```

Output the final value.

# Answer
> 1 votes
# Ruby, 52 bytes

```
->n{r=1;1until(2...r+=r+1).all?{|x|r%x>0}&&1>n-=1;r}

```

Try it online!

# Answer
> 1 votes
# Japt, 14 bytes

```
Èõ!²mÉ øX*j}iU

```

Try it

# Answer
> 0 votes
# Fig, \\$8\log\_{256}(96)\approx\\$ 6.585 bytes

```
F@p{^2mC

```

Try it online!

Outputs an infinite list of Mersenne primes.

```
F@p{^2mC
      mC # Infinite list of counting numbers
    ^2   # 2^x
   {     # Decrement
F@       # Filter for...
  p      # Primality

```

---
Tags: code-golf, sequence, primes
---


title: Split along groups

text:
# Question
Title: Split along groups
You are going to be given a string containing some alphabetic characters along with `[` and `]`. Your task is to split into sections that are enclosed in a "group" created by `[...]` and those that are not. e.g.

```
"absbn[mesl]meslo[eyyis]me"
->
"absbn"
"mesl"
"meslo"
"eyyis"
"me"

```

Super simple right? Well hold your horses. What happens when multiple brackets conflict? like `co[[x]t` or `m[[e]]it`? We don't have any guarantee that the brackets are matched or not nested.

The rule we are going to use is that when multiple possible groups could be made we will always choose the smallest ones. Any `[`s left without a match are just regular characters and appear in the output.

So in `co[[x]t` we could do `co` `[x` `t`, but we could also do `co[` `x` `t`. Since the group here is either `[x` or `x` we choose the smaller one and the result is `co[` `x` `t`. In the second case `me[[e]]it` there are 4 ways to make groups here, but unambiguously `me[` `e` `]it` results in the smallest group.

Your task will be to take a non-empty string of characters `a` through `z` plus two brackets of your choice (`[]`, `{}`, `()` and `<>`) and to split it as described above, providing a list of strings as output.

In cases where a group is on the boundary of the string, e.g. `aaa[b]` or `[ems]ee` you may choose to include or omit an empty string `""` on that boundary. The test cases always include them.

This is . Answers will be scored in bytes with the goal being to minimize the size of your source code.

## Test cases

```
go[cat]me -> "go" "cat" "me"
absbn[mesl]meslo[eyyis]me -> "absbn" "mesl" "meslo" "eyyis" "me"
co[[x]t -> "co[" "x" "t"
me[[e]]t -> "me[" "e" "]t"
mon[g]]u -> "mon" "g" "]u"
msy]mesl -> "msy]mesl"
eoa[m -> "eoa[m"
a[b[ -> "a[b["
mesi]mmp[mo -> "mesi]mmp[mo"
meu[ems[mela[] -> "meu[ems[mela" "" ""
w[[[] -> "w[[" "" ""
[foo]foobar[bar] -> "" "foo" "foobar" "bar" ""
[][] -> "" "" "" "" ""

```

# Answer
> 7 votes
# Retina 0.8.2, 9 bytes

```
S`<(\w*)>

```

Try it online! Link includes test suite that switches between `[]` and `<>` and separates the output lines for each case with `-` for convenience. Explanation: Simply splits on a minimal group, capturing the contents.

The question now requires empty chunks, but the previous 10-byte version only required an extra `_` prefix to disable them:

```
_S`<(\w*)>

```

Try it online! Link includes test suite that switches between `[]` and `<>` and separates the output lines for each case with `-` for convenience. Explanation: Splits on a minimal group, capturing the contents even if it is empty, but skipping empty chunks.

# Answer
> 4 votes
# sed, 92 21  20 bytes

```
s/<\(\w*\)>/\
\1\
/g

```

Try it online!

Thanks to DLosc for pointing out the specs had changed, greatly simplifying my answer, and for a -3 bytes golf

-1 thanks to "emanresu A" for pointing out I could use `<>` as my bracket chars

Prints each group on its own line.

* Finds all matches of the form `[<string of chars without brackets>]`.
* Replaces them with `\n<string of chars without brackets>\n`

# Answer
> 4 votes
# , ~~68~~ ~~63~~ 62 bytes

*Edit: -1 byte thanks to pajonk*

```
function(x,`[`=gsub)"@"["",scan(t="<(\\w*)>"[" @\\1 ",x],,"")]

```

Try it online!

Would be 55 bytes if it wasn't for the annoying behaviour of 's `strsplit` function, which outputs an extra empty string if the split pattern occurs at the start of the string-to-be-split.

We first search for bracket-pairs (using `<` and `>` as brackets) that contain only letters between them, and swap these brackets for spaces. Then, we use `scan` to split the resulting string (because of the annoying `strsplit` behaviour). `Scan` has it's own problem, though, which is that it treats consecutive whitespace as a single delimiter, and so would miss any empty groups: so, we add a spurious `@` character to each group, and then remove it with `gsub` when we're done splitting.

# Answer
> 3 votes
# Python3, 158 bytes:

```
import re
def f(l):
 t=''
 while l:
  if(j:=re.findall('^\[\w+\]|^\[\]',l)):yield t;yield j[0][1:-1];l=l[len(j[0]):];t=''
  else:t+=l[0];l=l[1:]
 if t:yield t

```

Try it online!

# Answer
> 3 votes
# Javascript, ~~113~~ ~~103~~ 39 bytes

```
s=>s.replace(/<(\w*)>/g,'0$10').split(0)

```

Uses `<>` as the brackets.

First time code golfing, yay! I'm pretty sure there's some regex magic which will beat this, but this was the best I could come up with.

EDIT: First version didn't properly handle strings starting or ending with groups, e.g. `<a>b<c>`

EDIT2: Shaved off 10 bytes thanks to emanresu A

EDIT3: Figured out the regex magic

# Answer
> 3 votes
# Pip `-p`, 11 bytes

```
a^`<(\w*)>`

```

Uses `<>` for brackets. Attempt This Online!

Verify all test cases

### Explanation

Same idea as Neil's Retina answer: the smallest possible group is always one that does not include any brackets.

```
a            ; Command-line input
 ^           ; Split
  `       `  ; on this regex:
   <         ;   Opening bracket
    (   )    ;   Group the following part so it is included in the list of results:
     \w*     ;     0 or more word characters (here, letters)
         >   ;   Closing bracket

```

# Answer
> 2 votes
# Python, 83 bytes

```
lambda s:[t for i,t in enumerate(re.split(r"\[([^][]*)\]",s))if(i&1)or t]
import re
```

Attempt This Online!

This uses `re.split` which returns a list containing both the stuff between matches and those parts of matches that are in grouping parentheses.

This is then filtered to remove empty strings but only between groups; empty groups are retained.

# Answer
> 1 votes
# JavaScript, 21 bytes

```
s=>s.split(/<(\w*)>/)

```

Try it online!

# Answer
> 1 votes
# Perl 5, 57 bytes

```
s/<(\w*)>/ $1 /g;s/^ (.*) $/$1/;print for split/ +/,$_,-1

```

Try it online!

# Answer
> 0 votes
# Raku, 28 bytes

```
~«*.split(/\[<(\w*)>\]/,:v)

```

No TIO link, because the version of Raku/Perl 6 found there appears to have a regex bug. All of the test cases work fine on my local system though.

* `*.split(/.../, :v)` splits the input parameter on the given regex. The `:v` adverb causes the delimiters to be included in the returned list as well, as Match objects.
* converts everything in the split return list to strings. The nondelimiter groups are already strings, but the delimiter Match objects need to be converted.
* `\[` and `\]` match the literal square bracket delimiters.
* `<(` and `)>` cause the delimiter Match objects to only reference the enclosed text; that is, the square brackets are excluded.
* `\w*` is a sequence of letters.

All of the allowed delimiter pairs are Raku regex metacharacters, so there's no avoiding having to escape them.

---
Tags: code-golf, string, parsing
---


title: Say "Hello" to the world in ASCII art

text:
# Question
Title: Say "Hello" to the world in ASCII art
**Challenge:** Produce the following output using as few chars as possible:

```
 _   _      _ _                             _     _ _
| | | | ___| | | ___    __      _____  _ __| | __| | |
| |_| |/ _ \ | |/ _ \   \ \ /\ / / _ \| '__| |/ _` | |
|  _  |  __/ | | (_) |   \ V  V / (_) | |  | | (_| |_|
|_| |_|\___|_|_|\___( )   \_/\_/ \___/|_|  |_|\__,_(_)
                    |/

```

**Rules and restrictions:**

* You may not use FIGLet or any similar tools. (Otherwise, `figlet Hello, world!` would be a trivial and pretty much unbeatable solution.)
* Your program must consist entirely of printable ASCII characters — specifically, code points 9 (TAB), 10 (LF) and 32 – 126. (If your language / OS requires CRLF line breaks, you may use those instead of plain LFs.) Yes, this regrettably disqualifies any language that requires non-ASCII characters (or non-textual data) as part of its syntax.
* The output must look exactly like the example above. You may, however, include extra whitespace around the output if you want. You may assume 8-character tab spacing (or your chosen platform's native default setting, if it has a consistent one).

Ps. To set the par, I came up with a 199-char Perl solution. I won't post it yet, though, in case someone comes up with it independently. (Also, it's kind of cheesy.) Of course, this shouldn't discourage you from posting your own solution, even if it's longer.

---

**Update:** Now that han has beaten it by one char, here's my cheesy 199-char Perl solution:

```
use Compress'Zlib;say uncompress unpack u,'M>-I]BT$*`S$,`^]YQ=R:0,&_Z<DP?8@?WVQJ]E2J"%E$$@)R(/(/MCJ*\U!OM`Z#=5`4Y>6M=L\L%DMP&DB0V.4GQL&OOGB$4:%`4TT4!R8O-Z(^BTZWNV?>F86K:9+""-35*-LNC:T^D:_$#%^`";"DD0'

```

It's very similar to D C's solution (and all the other zlib/gzip-based solutions in various languages), except that I used uuencoding instead of base64 for the compressed text and a few other minor golfing tricks.

---

**Update 2**: I think it's time to officially accept a winner. The first place goes to konsolenfreddy's PHP code, since, however you count the chars, it *is* the shortest submitted so far. In fact, combining it with the optimized DEFLATE stream from my 199-char Perl code yields an even shorter 176-char solution:

```
<?=gzinflate(base64_decode("fYtBCgMxDAPvecXcmkDBv+nJMH2IH99savZUqghZRBICciDyD7Y6ivNQbwOg3VQFOXlrXbPLBZLcBpIkNjlJ8bBr754hFGhQFNNFAcmLzeiPotOt7tn3plq2mSwgjU1SjbLo2tPpGvxAxfgA"));

```

However, I do think that han deserves a special honorary mention for getting so close without using any pre-written decompression tools. Congratulations to both of you, and a happy new year to everyone!

# Answer
# Stax, 137 bytes

```
"9&BO]h>&)>3ieuCoKVKVnuOoT'E-^Z(1.3u[);h1[RTOGqTZkoQx?KMy&9ctG&*y~HxR9%GYn.rYMdMcOOq^wXc@%zy*P[*Q"90|E|B"0+1"{%",``_|\/()V'"@]}R.1 |t54/m

```

Run and debug it

It works like this.

1. Start with a big string literal.
2. Convert to integer by decoding as a base-90 number.
3. Convert that number to binary.
4. Runs of `0`s followed by a `1` are translated into non-space characters.
5. All remaining `1`s are replaced with spaces.
6. The resulting string is split into 54-character lines.
> 2 votes

# Answer
# Perl 5.10 - 195 198 202 203 characters

Here's an entry that does not require any libraries beyond basic regexp matching. The encoded string is 131 characters, and the code to decode and print it takes up 64 characters (assuming no newline at the end of the source). The idea is to represent common 3-character strings by lower case letters.

```
s!!xfefxxf\t\t\tf efyx
no| cnocfxefxceyxm|xmn
nm|wtnwtgt/uvy \\| 'ym|w`o|
pepyy/o| _ogrr/ _opn (ml
l lbyly|by( )fiihyjm lb,y_
\t\tf |/!;s!\w!substr'(_)\___   \_/|_| |  V \ / _',-95+ord$&,3!eg;say

```

The encoder is a lot longer and unfortunately not very readable right now. The basic idea is to use dynamic programming to find the shortest encoding for each line, given a fixed set of string substitutions. The string of substitutions on the last line was built by trial and error, and it is possible that another string of substitutions might lead to a shorter program than above.

One trick here is that some substitutions are shorter than 3 characters long: due to the way perl `substr` works, `x` is replaced by ' `_`' and `y` by '`_`'. The latter is necessary because `\w` in the regex matches '`_`', which is then replaced by '`(_)`'.
> 17 votes

# Answer
## Brainfuck - 862 characters:

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

```
> 14 votes

# Answer
## Python (2.x), 194 characters

```
print'eNo9T8ENxCAMe5cp/DsqVco2fSH5BsnwZ4ccEIhxbAIgAK9KvDRwGBEjsSfJA6r2N7EISbmrpbLNKFRYOABaC6FAEYkPW/Ztm1t7Z1S3ydtHuV4ooolEV6vPyJ2XH8kGE7d9DAVMhFUte6h7xv5rxg8sf0Qc'.decode('base64').decode('zip')

```
> 9 votes

# Answer
This answer is longer than just printing the string; however, just for the fun of it, here it is:

## Python, 485 characters ☺

```
import sys

data= ',C6UBKq.)U^\\ 8[hHl7gfLFyX6,;p\'SlYpN@K-`Kbs#fSU+4o~^_h\\dJDy{o9p?<GnLTgG{?ZM>bJE+"[kHm7EavoGcS#AQ^\\>e_'
table= " _|\\/(\n)V'`,"
key= (0,(1,((((7,5),(6,(8,(11,(9,10))))),(4,3)),2)))

number= 0
for char in data:
    number= number*95 + ord(char) - 32

mask= 1<<655
decoder= key
while mask:
    index= mask & number and 1
    try:
        decoder= decoder[index]
    except TypeError:
        sys.stdout.write(table[decoder])
        decoder= key[index]
    mask>>= 1

```

Since I have one of the shortest ASCII representations of the compressed original text, I must have the longest scrollbar in my code! It's a win! :)
> 4 votes

# Answer
## Javascript, ~~273~~ ~~265~~ 264 characters

```
" _2_22_ _2222222226_26_ _10 0 3_0 | 3_2 32233_6_ 30 30 |10_0/ _ 4 0/ _ 424 4 /4 / / _ 4| '30/ _` 01|6_6|63/ 0 (_) |24 V6V / (_) 060 (_0_|1|_0_|43_|_543_( )24_/4_/ 43_/56543,_(_)12222226|/".replace(/\d/g,function(a){return'| |,\n,   ,__,\\,|_|,  '.split(',')[a]})

```

:(
> 4 votes

# Answer
## PHP, ~~194~~ 189 characters

```
php -r'=gzinflate(base64_decode("dU/BDcQgDPszhX+lUqVs0xeSb5AMf3ZI+7qDACa2EwABeNXR4M/goxqJPUm+oLinEishKTdbKtuMQsTCC6C1EApUInHIvOlP+9zbO6PaTZ6+ynZDEZ1INFuNRu5z+ZVsMHHax1DAibCqZRdVZ/z6esYX"));'

```

It's basically the same as the Python and Perl answer, slightly shorter
> 3 votes

# Answer
> In other languages: **C** (original version), 209 chars; **Perl**, 200 chars.

## J, ~~167~~ 160 chars (47 + 113)

Another no-builtin-compression submission. Uses a pretty straightforward variable-length encoding, encoding each character as a series of 1 bits and separating characters by 0 bits. The compressed string is a mere 113 characters.

```
('a _|\/',CR,'()V`,'''){~#;.2,(6$2)#:40-~3&u:'8H1(((((H:f[4ZS4ZP2(RPMAMANf[>CZD[F;I[OVFF;TgfS5aGd[7T9JW4[eG[+Of7ddg?d[.AfT]WUASE=S>bSdgI]cS[RWBYSE?gSeG_X(()WG('

```
> 3 votes

# Answer
## Python (2.7.x), 218 characters

```
import base64,zlib;
print zlib.decompress(base64.b64decode("eNo9T8ENxCAMe5cp/DsqVco2fSH5BsnwZ4ccEIhxbAIgAK9KvDRwGBEjsSfJA6r2N7EISbmrpbLNKFRYOABaC6FAEYkPW/Ztm1t7Z1S3ydtHuV4ooolEV6vPyJ2XH8kGE7d9DAVMhFUte6h7xv5rxg8sf0Qc"))

```

Pretty straightforward... not terribly pleased with this attempt.
> 2 votes

# Answer
## Bash, ~~199~~ ~~196~~ 193 characters

```
base64 -d<<<H4sIAAAAAAAAAz1PQQ6AIAw7S+IfelMTk/3GE0l9CI+3HRPYoHQtAxCAMzduGliMiL0NzElygSz+LiYhLWc1VekzDFU6FoCyIxRIYuBgyd7f5+5eGdnv5OWjbA8UUcRAVbORfBN0v5MFTlw2MhQwEVaV7KYu2tv88IgPjUlb7QoBAAA=|zcat

```

Close enough...

EDIT: Down to 193!
> 2 votes

# Answer
## bash, 196 192

```
base64 -d<<<H4sIAO4SqFMCA3VPQQ7AIAi7+4re5pIl/GYnk+4hPH4U0dOmILUUUBCAPEOBn8Wlao65SW6QudWJSYSUM5sqlQlZJAY2QPiAhSEJx8GSPVWm0TppOa3z1DWqboRZEY7K5pzmMw49kgU6TtXRwiDCpCrZxejTvn7u1l5z59MGKQEAAA|zcat

```
> 2 votes

# Answer
## Perl, 230 characters

```
use Compress::Zlib;
use MIME::Base64;
print uncompress(decode_base64('eNo9T8ENxCAMe5cp/DsqVco2fSH5BsnwZ4ccEIhxbAIgAK9KvDRwGBEjsSfJA6r2N7EISbmrpbLNKFRYOABaC6FAEYkPW/Ztm1t7Z1S3ydtHuV4ooolEV6vPyJ2XH8kGE7d9DAVMhFUte6h7xv5rxg8sf0Qc'));

```

This is basically the same as my Python answer. I'd like to see the 199-character version.. sounds like magic.
> 1 votes

# Answer
# Perl, ~~294~~ 290 bytes.

The compressed string alone, is ~~151~~ 130 bytes.

This isn't short, but it was really fun to write.

@t=split//,"_|\\/\n()V',`";$b.=substr unpack("B8",chr(-48+ord)),2,6 for split//,'Ph?`@Ooooo1l410````0066600?03l0001PP06600HHB1Q064L4D<8h8^::<DLL4@J0032>1D<90h<>00hHI@6QhYllLX3@`hHI@1Q04P@1Q04@002080R001I^80a074001Q07208P0B0X34ooo`ST';$b=~s/(1)|(0.{4})/$1?" ":$t[ord pack"B8","000$2"]/eg;print$b

@t=split//," _|x"x4 ."\\/\n()V',`";$b.=substr unpack("B8",chr(-48+ord)),2,6 for split//,'4100A0000000001017:8R5HR5@1@05E15R5R;:9Ra4`8\\A<0<30a`<C4C2=URa7PRbP@PG4R<g@P<3D=C4cM288S=RK:HV`EVK1G<d0`LL74`EaV2K1Mg=db0000002ab';$b=~s/1(1.{4})|(..)/$t[ord pack"B8","000".($2?"000$2":$1)]/eg;print$b
</code></pre>
> 1 votes

# Answer
# Perl, 346 bytes

The compressed string alone, is 111 bytes.

```
@t = split//, " _|\\/\n()V',`";
$k=[0,[1,[2,[[3,4],[[5,6],[7,[[8,9],[10,11]]]]]]]];

$b .= substr unpack("B8", chr(-48+ord)), 2, 6 for split//,'@P900000PBlc<b[<bX:0ZXUIUIVlcFKZLI^Y`LLMhjjW<oJcMGncNHS5MIW]l`ho3lMNgc<IW]V]i[=KUF]KUG[hL^l^^EMeSFiGmNggP001^Pl';

$d = $k;
$o.=$d=~/^\d/?$t[$s=$d,$d=$$k[$_],$s]:($d=$$d[$_],"")for split//,$b;
print $o

```

Trying to understand what the python with `key= (0,(1,((((7,5),(6,(8,(11,(9,10))))),(4,3)),2)))` was doing, I ended up making a very similar looking perl version.
> 1 votes

# Answer
## PHP 590

obviously, i'm not trying to win, just got interested on trying another compression scheme, altough it can't even beat the simpler 302 plain text PHP solution of just copy-pasting

it works as a bitmap on 10 channels

"golfed"

```
<? $l=['_'=>['l8kqo,ei','9uo6,2fko0','52m0w,5r1c','540lc,5maq','lifeo,19i7ai'],'|'=>[0,'1h39j4,105','1h2k8w,q9x','14l2jk,wlx','1h39j4,wlc','1s,0'],'/'=>[2=>'b9c0,n3kao','pa8,18y68','0,mihog','w,0'],'\\'=>[2=>'pc5,a0zy8','2,0','b9c1,am2kg'],'('=>[3=>'e8,b8lc','1s,4'],')'=>[3=>'3k,2t4w','g,1'],'V'=>[3=>'0,18y680'],'`'=>[2=>'0,g'],"'"=>[2=>'0,6bk'],','=>[4=>'0,g'],];$p=@str_pad;$b=@base_convert;$i=-1;while($i++<5){$h=' ';foreach($l as$c=>$r)if(@$r[$i]){$a=explode(',',$r[$i]);$d=str_split($p($b($a[0],36,2),27,0,0).$p($b($a[1],36,2),27,0,0));foreach($d as$j=>$v)$v&&$h[$j]=$c;}echo"$h\n";}

```

readable

```
<?php
$l = ['_'=>['l8kqo,ei','9uo6,2fko0','52m0w,5r1c','540lc,5maq','lifeo,19i7ai'],
      '|'=>[0,'1h39j4,105','1h2k8w,q9x','14l2jk,wlx','1h39j4,wlc','1s,0'],
      '/'=>[2=>'b9c0,n3kao','pa8,18y68','0,mihog','w,0'],
     '\\'=>[2=>'pc5,a0zy8','2,0','b9c1,am2kg'],
      '('=>[3=>'e8,b8lc','1s,4'],
      ')'=>[3=>'3k,2t4w','g,1'],
      'V'=>[3=>'0,18y680'],
      '`'=>[2=>'0,g'],
      "'"=>[2=>'0,6bk'],
      ','=>[4=>'0,g'],
      ];
$p=@str_pad;
$b=@base_convert;
$i=-1;
while($i++<5){
    $h = str_repeat(' ',54);
    foreach($l as $c=>$r)
        if(@$r[$i]){
        $a = explode(',',$r[$i]);
        $d = str_split($p($b($a[0],36,2),27,0,0).$p($b($a[1],36,2),27,0,0));
        foreach($d as$j=>$v)
            if ($v)
                $h[$j]=$c;
        }
    echo "$h\n";
}

```
> 1 votes

# Answer
# Pylongolf2, 300 bytes

```
" _   _      _ _                             _     _ _
| | | | ___| | | ___    __      _____  _ __| | __| | |
| |_| |/ _ \ | |/ _ \   \ \ /\ / / _ \| '__| |/ _` | |
|  _  |  __/ | | (_) |   \ V  V / (_) | |  | | (_| |_|
|_| |_|\___|_|_|\___( )   \_/\_/ \___/|_|  |_|\__,_(_)
                    |/"~

```

I couldn't find any classy encoding methods, so I'm *probably* not competing.
> 1 votes

# Answer
## Golf-Basic 84, 325

```
:"                     "_Str1t` _   _      _ _ "d`Str1d`Str1t`_     _ _"t`| | | | ___| | | ___    __      _____  _ __| | __| | |"t`| |_| |/ _ \ | |/ _ \   \ \ /\ / / _ \| '__| |/ _` | |"t`|  _  |  __/ | | (_) |   \ V  V / (_) | |  | | (_| |_|"t`|_| |_|\___|_|_|\___( )   \_/\_/ \___/|_|  |_|\__,_(_)"t`                    |/"

```

Assuming a calculator could print backticks, backslashes, single pipes, and underscores.
> 0 votes

# Answer
## HTML + JS (223 unicode characters)

Just for fun:

```

```

NB: you have to save it in a "UTF-8 with BOM" HTML file.
> 0 votes

# Answer
# PowerShell, 220 byes = script:9 + archive:211

```
tar xOf t

```

Try it online!

The Powershell script to create the archive `t` (see TIO):

```
(
" _   _      _ _                             _     _ _",
"| | | | ___| | | ___    __      _____  _ __| | __| | |",
"| |_| |/ _ \ | |/ _ \   \ \ /\ / / _ \| '__| |/ _` | |",
"|  _  |  __/ | | (_) |   \ V  V / (_) | |  | | (_| |_|",
"|_| |_|\___|_|_|\___( )   \_/\_/ \___/|_|  |_|\__,_(_)",
"                    |/"
) | Set-Content f -Force
tar zcfo t f
Get-ChildItem t # output info about archive size

```
> 0 votes

# Answer
# Fig, \\$274\log\_{256}(96)\approx\\$ 225.535 bytes

```
Dr_tem[82]\r-reIX3vb/pBNI9@xbV1?^csytMxrA)YVtY.5yfDryr#(K{bAe,YSkOIU9\|tet&RZF_n+!\;TlNE'T3OB{GGqqvpiP 61;Y#nh0^=vOX6@vxmixkmqp<&y<%;b?=|FG&!6*XI*<glXG,bt|0Kv`/lO;OEx7[`$vT4ljhkSGVaE'</\z{uF8L2E2yXU%r\Ws9F;cF4FXZVD}TL?qdxQ;slDX~lyO# K_+lFV52P-Io9a.7JuDaWJ/sAo,lCChg=5 P9^=[B

```

Try it online!

Boring text compression answer. Doesn't compress very well due to the compressor being much more optimized for words and spaces before words than characters. Fun fact: when designing Fig, I was considering making the compressor use RLE in the character case, but decided to do capitalization instead :(
> 0 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity, printable-ascii, hello-world
---