title: Build an alphabetised polyglot

text:
# Question
Title: Build an alphabetised polyglot
As TIO can show, every letter of the Latin alphabet is represented when it comes to languages. For every letter there is at least 1 programming language whose name begins with that letter. Your task is to create a polyglot in order to demonstrate that.

Your program should be runnable in between 2 and 26 different languages, each of which starts with a different letter. However, if your program runs in \\$N\\$ languages, the languages used must have the first \\$N\\$ letters of the alphabet as the first letter of their names. So if your program runs in 5 languages, the languages must start with `A`, `B`, `C`, `D` and `E`. (e.g. A Pear Tree, BrainSpace, C++, Dash and Enlist)

Your program should take no input, and output a constant string: the alphabet (case-irrelevant, in order), but with the letter of the language name removed. So the language beginning with `A` should output `BCDEFGHIJKLMNOPQRSTUVWXYZ` (or the equivalent lower case version). Case doesn’t have to be consistent for different languages, but it does between runs in the same language.

Any languages are fair game, so long as no letters are repeated. This rules out using different versions for most languages (e.g. Python 2 vs Python 3), but this is only as a consequence of having unique letters. Seriously and Actually, for example, are considered different versions, but can both be used in the same answer as they start with different characters.

If using languages with custom code pages, then, as is standard, the bytes must match between programs, not characters.

Submissions are scored by number of languages used, with a tie breaker of shortest code.

# Answer
# AsciiDots, Bash, Cardinal, Dash, evil, fish, goruby, Haystack, Implicit, J-uby, ksh, Ly, mksh, Numberwang, OSH, Python 3, QuadR, Ruby, Super Stack!, Taco, Unefunge-98 (Pyfunge), V (Vim), Wumpus, xonsh, yash, Zsh, 1009 bytes

9 shells, 3 Rubies, some 2D (and 1D!) languages and many languages I learned just for this challenge. I really enjoyed this challenge and learned some new languages and features. I enjoyed finding a shorter way than just the raw string in some languages (in some languages generating the string seemed longer) and trying to re-use the `s` variable as many times as possible was fun too. I've also tried to keep the byte-count as low as possible. If I find the time and the inclination, I wonder if I could start adding the letters of the alphabet to the end instead... Crazy talk...

```
' # "194940711909711999999999999940391270919999999999994039127zaeeeawawawawavaeeaaaaamvawvusb"' #165#1#1;.040;"ZYXWVTSRQPONMLKJIHGFEDCBA"8 3*k,q"ABCDEFGIJKLMNOPQRSTUVWXYZ"o¡72"8:é9:é8++:90+1®;65µ
'\&p"A""K"R"M""Z"R&o;';#   x%"ABDEFGHIJKLMNOPQRSTUVWXYZ"x.-$"BCDEFGHIJKLMNOPQRSTUVWXYZ" 0 65 65 if pop dup dup 83 sub if pop outputascii 0 fi pop 1 add dup 91 sub fi "ZYXVUTSRQPONMLKJIHGFEDCBA"#25&o   @"ABCDEFGHIJKLMNOPQRSUVWXYZ"
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'
0//1;
try:echo -n;print(s[0:23]+"YZ");
except:print(s[0:15]+s[16:]);"""/.__id__;begin ~:*;puts s.gsub ?J,"";rescue;begin A;puts s.gsub ?G,"";rescue;puts s.gsub ?R,"";end;end;'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;';/
('Q'⎕R'')⎕A⋄'\} #<esc>ggdG¬AZ:s/#\|V//"""#\'⍵

```

# AsciiDots

The relevant code is:

```
.-$"BCDEFGHIJKLMNOPQRSTUVWXYZ"

```

This needs to be wrapped in `[`...`]` to avoid \[Extended Brainfuck Type I\] from outputting rubbish before the desired string because of the `.`.

Try it online!

# Bash

The relevant code is:

```
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' #

```

This first line sets `$s` to be the full alphabet in uppercase, so `-z $s` is false and skipped over. `$status` is unset, `\e` is treated as an escape, not a `\` and `e`, `$BASHPID` is set, `$_OVM_PATH` is not and `$USER_ID` isn't set so `B` is replaced with the empty string in `$s` (`${s/B/}`) and `echo`ed it out.

Try it online!

# Cardinal

The relevant code is:

```
x%"ABDEFGHIJKLMNOPQRSTUVWXYZ"x

```

The cursors spawn from the `%` and are terminated by the `x`s. This needed to be moved slightly to prevent additional output.

Try it online!

# Dash

The relevant code is:

```
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' #

```

As per Bash, this first sets `$s` to be the full alphabet in uppercase. so `-z $s` is false. `$status` is empty, `\e` is an escape sequence and doesn't match `e`, but `$-` is empty in Dash so that conditional is met and we `echo` out `ABC` followed by `$s` with the prefix `ABCD` removed (`${s#ABCD}`).

Try it online!

# evil

The relevant code is:

```
zaeeeawawawawavaeeaaaaamvawvusb

```

Try it online!

# fish

The relevant code is:

```
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' #

```

In fish, variables aren't assigned via the `s=...` syntax so `$s` is empty meaning the first conditional is hit, the required string is `echo`ed out and then `exit` is called.

Try it online!

# goruby \+ `--disable=gems`

This isn't available on TIO, but is distributed with the official Ruby source and can be compiled (after the normal `autoconf` and `./configure` steps) with `make goruby`. Tested on version `ruby 2.8.0dev (2020-08-24T10:24:07Z master 1eb1add68a) [x86_64-linux]`. The relevant code is:

```
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0
0//.../.__id__;begin ~:*&?,;puts s.gsub ?J,"";rescue;begin A;puts s.gsub ?G,"";rescue;puts s.gsub ?R,"";end;end

```

# Haystack

The relevant code is:

```
"ABCDEFGIJKLMNOPQRSTUVWXYZ"o

```

which `o`utputs the required string.

Try it online!

# Implicit

The relevant code is:

```
¡72"8:é9:é8++:90+1®;65µ

```

This pushes the range of `1`..`72` and joins the last 8 items on the stack to a string, duplicates the top the stack, increments all codepoints by 9, duplicates the stack again, increments all codepoints in the string by 8, pushes `90` to the stack and concatenates all, reverses the stack, pop off the top 65 elements then prints the stack.

Try it online!

# J-uby

The relevant code is:

```
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0
0//.../.__id__;begin ~:*&?,;puts s.gsub ?J,"";rescue;begin A;puts s.gsub ?G,"";rescue;puts s.gsub ?R,"";end;end

```

This shares the declaration of `s` with the shells and other Ruby implementations and and `.gsub`s `J` from the string before `puts`ing it as long as `~:*&?,` doesn't cause an error.

Try it online!

# ksh

The relevant code is:

```
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' #

```

`$s` is set as the other shells and `$status` is empty, `\e` doesn't match `e`, `$-` is not empty, but `$BASHPID` is so `$s` is `echo`ed removing `K` (`${s/K/}`).

Try it online!

# Ly

The relevant code is:

```
&p"A""K"R"M""Z"R&o;

```

which first clears the stack then pushes the `R`anges from `A`-`K` and `M`-`Z`, before `&o`utputting the stack contents and terminating (`;`).

Try it online!

# mksh

The relevant code is:

```
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' #

```

As per the previous shells, the first line sets `$s` to be the full alphabet in uppercase, so `-z $s` is false and skipped over. `$status` is unset, `\e` is treated as an escape, not a `\` and `e`, `$BASHPID` is set, `$_OVM_PATH` is not and `$USER_ID` is set so `M` is replaced with the empty string in `$s` (`${s/M/}`) and echoed it out. Tested on version `58-1`.

# Numberwang

The relevant code is the big number as Numberwang is just a transliteration of brainfuck:

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

```

There's a minor amount of work to balance `4`s and `7`s throughout the rest of the code, alongside making sure things appear in the right order, but nothing major. Might be able to save some bytes by moving stuff around here...

Try it online!

# OSH

Oh look, another shell! As per the others the relevant code is:

```
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' #

```

The main difference here is that `$_OVM_PATH` is set in OSH, but not in Bash, so the correct string is `echo`ed using `tr` to remove the `O`.

Try it online!

# Python 3

The relevant code is:

```
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0
0//1;
try:echo -n;print(s[0:23]+"YZ");
except:print(s[0:15]+s[16:]);"""..."""

```

This shares the declaration of `s` with the shells and Rubies and is also shared with xonsh. The code in the `try` will fail in Python (`echo -n`), but works in xonsh so the code in the `except` is called, printing slices of `s`.

Try it online!

# QuadR

The relevant code is:

```
('Q'⎕R'')⎕A⋄'...'⍵

```

In QuadR, when the final line contains  all the preceding lines are patterns to match and the final line is a transformation function. This particular transformation function just takes the alphabet `⎕A` and `⎕R`eplaces `'Q'` with `''`, the rest of the function after the statement separator () is just to close off all the other strings/comments/regex literals and comment out the end of the function.

Try it online!

# Ruby

The relevant code is shared with J-uby and goruby:

```
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0
0//.../.__id__;begin ~:*&?,;puts s.gsub ?J,"";rescue;begin A;puts s.gsub ?G,"";rescue;puts s.gsub ?R,"";end;end

```

Like the other Rubies, `s` is shared from the shells but in Ruby here, both the other clauses `~:*&?,` and `A` will raise exceptions so the final statement is executed which replaces `R` in `s` with the empty string.

Try it online!

# Super Stack!

The relevant code is:

```
0 65 65 if pop dup dup 83 sub if pop outputascii 0 fi pop 1 add dup 91 sub fi

```

This pushes `0` and `65` (twice) to the stack, then `if` (which is "while top of stack is truthy" - non-zero), `pop`s the top element, `dup`licates the new top element twice, pushes `83` and `sub`tracts it from the next stack item down. Then `if` top of stack is truthy (e.g. it's not 83 - `S`), `pop` it, `outputascii`, push `0` and terminate with `fi` (since top of stack is now `0`). Finally, `pop`, push `1`, `add` the two top elements together (increment), `dup`licate, push `91` and `sub`tract, terminate the loop, which will happen if the last output char was `90` (`Z`).

Try it online!

# TacO

The relevant code is:

```
@"ABCDEFGHIJKLMNOPQRSUVWXYZ"

```

Try it online!

# Unefunge-98 (PyFunge)

The relevant code is:

```
"ZYXWVTSRQPONMLKJIHGFEDCBA"8 3*k,q

```

There are a few commands before this that are executed and push things to the stack, but basically this just pushes the required chars in reverse, then pushes `8` and `3` and multiplies them. The `k` command repeats the next command TOS (`24`) `+ 1` times, outputting the required string and `q`uits.

Try it online!

# V (vim) \+ `-v`

The relevant code is:

```
<esc>ggdG¬AZ:s/V//"...

```

Which first leaves insert mode (`<esc>`), goes to the first line of text (`gg`), deletes to the last line (`dG`), inserts the letters from `A` to `Z` (`¬AZ`), then finally replaces `V` with the empty string (`:s/V//`). The rest of the line is commented out (`"`).

Try it online!

# Wumpus

The relevant code is:

```
...#220#1#1;.
..."ZYXVUTSRQPONMLKJIHGFEDCBA"#25&o @

```

The `#220#1#1` pushes `220`, `1`, `1` to the stack, then `;` pops off the last item then calls `.` which jumps the IP to line 1, char 220 and executes. We need to just because TacO mandates only one `@` in the code.

Try it online!

# xonsh

The relevant code is:

```
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0
0//1;
try:echo -n;print(s[0:23]+"YZ");
except:print(s[0:15]+s[16:]);"""..."""

```

xonsh is a Python based shell so the code is shared with Python 3 and uses the same `s` var as the shells and Rubies. I've used a technique I've used in many polyglots with Ruby to get this code in. `0//1` is integer division and the `echo -n` works fine since xonsh is a shell so the execution of printing the required substring portion of `s` with the literal string `YZ` concatenated, then the rest of the program is a `"""` string.

# yash

The relevant code is:

```
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' #

```

Like the other shells, but in yash, the sequence `\e` is not an escape sequence and so is just the string `\e` which matches `e` so `$s` is printed substituting `Y` for the empty string (`${s/Y/}`).

Try it online!

# Zsh \+ `--continueonerror`

The relevant code is:

```
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";0#'...'
[ -z $s ]&&echo ABCDEGHIJKLMNOPQRSTUVWXYZ&&exit;echo `[ $status = 1 ]&&echo \${s/Z/}&&exit;[ \e =~ e ]&&echo \${s/Y/}&&exit;\[ -z \$- \]&&echo ABC\${s#ABCD}&&exit;[ -z \$BASHPID ]&&echo \${s/K/}&&exit;[ -z $_OVM_PATH ]||echo $s|tr -d O;[ -z $_OVM_PATH ]||exit;[[ -n $USER_ID ]]&&echo \${s/M/}||echo \${s/B/}`;'...' #

```

Zsh is less tolerant of errors in a script than the other shells and so necessitates the `--continueonerror` flag. In Zsh `$status` is also set (in fish too) when a command fails, so if `$status` is `1`, then `$s` is `echo`ed out, substituting `Z` for the empty string (`${s/Z/}`).

Try it online!

---

Validation suite.
> 30 votes

# Answer
# Arcyou, Braille, COW, Deadfish~, Emoji, Forked, Gaot++, Hyper-Dimensional Brainfuck, 3389 Bytes

```
"BCDEFGHIJKLMNOPQRSTUVWXYZ";11+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+@1+@1+@1+@1+@1+1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@&------------------------.+.+.+.+.+.+.++.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiciciciicicicicicicicicicicicicicicicicicicicicicich⠆⠄⡒⡆⡘⠀⢕⢍⢅⠽⠵⠭⠥⠝⠕⠍⠅⢼⢴⢬⢤⢜⢔⢌⢄⠼⠴⠬⠤⠜⠌ABCDFGHIJKLMNOPQRSTUVWXYZ➡MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MoO Moo MoO MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet bleeeeet

```

Try it online in Arcyou, Braille, COW, Deadfish~, Emoji, Forked, Gaot++, and Hyper-Dimensional Brainfuck.

I'll explain each part below:

### Arcyou

```
"BCDEFGHIJKLMNOPQRSTUVWXYZ";

```

Implicitly prints the string, and ignores everything afterwards with a comment `;`.

### Braille

```
⠆⠄⡒⡆⡘⠀⢕⢍⢅⠽⠵⠭⠥⠝⠕⠍⠅⢼⢴⢬⢤⢜⢔⢌⢄⠼⠴⠬⠤⠜⠌

```

All non braille symbols are ignored, so this is an easy choice.

### COW

```
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MoO Moo MoO MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo MoO Moo

```

All non-moo tokens are ignored, making this easy as well. We also use a moo-exit (`Moo`) so that if we accidentally have a moo token in the future we don't run it.

### Deadfish~

```
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiciciciicicicicicicicicicicicicicicicicicicicicicich

```

Uses `i` to increment, `o` to output, and `h` to halt meaning we don't interpret future tokens.

### Emoji

```
ABCDFGHIJKLMNOPQRSTUVWXYZ➡

```

All non-emoji tokens are ignored, making this another easy choice.

### Forked

```
11+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+@1+@1+@1+@1+@1+1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@&

```

This language has a lot of tokens, but halts on `&` meaning we can put in it early. The `"BCDEFGHIJKLMNOPQRSTUVWXYZ";` in front from Arcyou acts as a no-op.

### Gaot++

```
baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeet bleeeeet

```

All non-sheep tokens are ignored, making this another easy choice. I hope the cows and the sheep can get along.

### Hyper-Dimensional Brainfuck

```
11+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+@1+@1+@1+@1+@1+1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@1+@&------------------------.+.+.+.+.+.+.++.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.

```

Basically brainfuck with some extra command we can ignore. Notice we use part of the Forked solution as a starter.
> 18 votes

# Answer
# Aheui (esotope), Brainfuck, Canvas, 127 bytes

```
밤밦뚜
나타뺘우차빠빠빠
떠벓벓벅멓더희뎌
>+[+[<]>>+<+]>.+>>++++[<++++++>-]<[<+.>-]
ABDEFGHIJKLMNOPQRSTUVWXYZ

```

Try it online in Aheui, Brainfuck, and Canvas!

Just a trivial solution of three languages which ignore each other's code entirely.

* Aheui ignores all non-Korean(Hangul) characters.
* Brainfuck ignores all characters that are not Brainfuck instructions `+-.,<>[]`.
* Canvas treats all ASCII characters as string literals and prints the last line.
> 5 votes

# Answer
# axo, Befunge-93, Canvas, Deadfish~, 104 bytes

```
"%A","EDC",,,"F">::,"Z"-|
{>B">[[("Z"-#%\{i}}dddci@
cici^icici +1<{c^i}{ci+1<}
ABDEFGHIJKLMNOPQRSTUVWXYZ

```

Try axo online! Try Befunge-93 online! Try Canvas online! Try Deadfish~ online!

## Explanations

### axo

```
"%
 >B">[[("Z"-#%\
    ^      +1<

```

It activates stringmode, pushes the B, then starts printing and incrementing that B until it's a Z.

### Befunge-93

```
"%A","EDC",,,"F">::,"Z"-|
                        @
                ^     +1<

```

Print ACDE, push an F, print and increment it until it's a Z.

### Canvas

Canvas prints the last line.

### Deadfish~

```
{{i}}dddciciciicicic{ci}{ci}

```
> 4 votes

# Answer
# AlphaBeta, brainfuck, Cauliflower, Dreaderef, emotifuck, 413 bytes

```
ebbbkiigZUaCILQ++++++++[>++++++++<-]>+.+<+++++[<+++++>-]<-[->>+.<<]deref16 4deref?7bool?9?7 13chro?add1 21 16deref100-1"abcefghijklmnopqrstuvwxyz"\;(print abdefghijklmnopqrstuvwxyz)

```

Try AlphaBeta, brainfuck, Cauliflower, Dreadref, emotifuck online!

---

### AlphaBeta

The relevant part is

```
e                ;add 100 to register 1
 bbb             ;subtract 3 from register 1 (=97)
    k            ;add 100 to register 2
     ii          ;add 20 to register 2
       g         ;add 1 to register 2 (=121)
        ZU       ;add 10 to position register
                 ;loop: prints 'bcd...xyz'
          a      ;add 1 to register 1
           C     ;set value of register to register 1
            I    ;set value of memory to register 3
             L   ;print value in memory as char
              Q  ;if reg1 <= reg2, jump to stored position (10)

```

There are no comments in *AlphaBeta*, which means most uppercase letters need to be avoided, as they break stuff and errors are printed to *stdout*.

### brainfuck

```
++++++++[>++++++++<-]>+  ;calculate 65
.+                       ;print A and increment
<+++++[<+++++>-]<-       ;push 24

[->>  <<]                ;24 times:
    +.                   ; increment and print

```

Since brainfuck ignores any other characters, this doesn't cause any further issues.

### Cauliflower

I haven't found any good documentation on this language, so this was mostly trial and error:

```
\;                                  ;escaped comment?
  (print abdefghijklmnopqrstuvwxyz) ;print string

```

### Dreaderef

The relevant part is

```
deref16 4deref?7bool?9?7 13chro?add1 21 16deref100-1"abcefghijklmnopqrstuvwxyz"\;

```

This is adapted from the Hello World in the documentation. The `;` comments out the rest of the line.

### emotifuck

```

```

is equivalent to the brainfuck program

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

```
> 3 votes

# Answer
# AWK, Bash, 68 bytes

```
echo ACDEFGHIJKLMNOPQRSTUVWXYZ
END{print"BCDEFGHIJKLMNOPQRSTUVWXYZ"}

```

Try it online (AWK)!

Try it online (Bash)!
> 2 votes

---
Tags: string, kolmogorov-complexity, polyglot, rosetta-stone
---


title: Find the longest uninterrupted arc

text:
# Question
Title: Find the longest uninterrupted arc
The challenge here is to find the longest uninterruped arc around a unit circle with a random amount of points distributed in random positions around it. Here is a diagram to assist my explanation:

The red line indicates the largest arc between any two points that is not interrupted by any other points. The challenge is to find the two points on either end of the red line. The green line is simply the straight line distance.

A clarification about what interrupted means: When drawing an arc around the edge of the circle (the red line), this arc should not be intersected by any other point.

Here is a template for the function in C#:

```
int[] FindPair(double[][] points)
{
     return new[]{ 0, 1}; //Find the indices of the two points
}

```

The function should return two integers, the indices of the two points on either end of the green line.

Assumptions:

* The Length of the points array is arbitrary but more than two. In the example we have:
points\[40\]\[\]
* Each element of the points array contains the x, y position of the point, for example:
points\[i\] = {x, y}
* You can assume that the distance of any given point to the origin at the centre of the circle is always 1.

Notes:

* The answer with the smallest Big O algorithm complexity wins. In case of a tie, shorter code wins.
* Bonus points for the solution to have the ability to work in more dimensions than two.
* I do have a solution, but it is very computationally expensive and only produces the correct answer around 99% of the time.
* I am not sure if the problem has a name in mathematics, or a generally accepted solution. If anyone knows of a better name for this problem so that I can have a better title, that would be helpful.

**Test case 1**:

```
Points: {
  { -0.71997 , -0.69400 },
  { 0.88564 , 0.46437 },
  { 0.78145 , -0.62397 },
  { 0.98409 , -0.17765 },
  { 0.88220 , 0.47087 },
  { 0.69938 , 0.71475 },
  { -0.89036 , -0.45526 },
  { -0.70588 , -0.70833 },
  { 0.70507 , 0.70914 },
  { -0.34971 , 0.93686 }
}

Solution:
{6, 9}

```

**Test case 2:**

```
Points: {
  { -0.71038 , 0.70382 },
  { 0.04882 , 0.99881 },
  { -0.53250 , -0.84643 },
  { -0.86814 , -0.49632 },
  { 0.97588 , -0.21829 },
  { 0.73581 , -0.67719 },
  { 0.88413 , -0.46724 },
  { -0.28739 , -0.95781 },
  { -0.68325 , 0.73019 },
  { 0.91879 , 0.39475 },
  { 0.65335 , 0.75706 },
  { -0.21009 , -0.97768 },
  { -0.94542 , -0.32585 },
  { 0.83207 , -0.55467 },
  { 0.99482 , 0.10170 },
  { 0.86228 , 0.50643 },
  { 0.98017 , 0.19817 },
  { 0.67520 , 0.73763 },
  { -0.03982 , -0.99921 },
  { -0.57624 , -0.81728 }
}

Solution: {0, 12}

```

**Invalid example:**
This is invalid, because when drawing an arc around the edge of the circle (the red line) between the two points connected by the green line, this arc is intersected by another point.

# Answer
# JavaScript (Node.js), O(n), ~~234~~ ~~229~~ ~~228~~ 211 bytes

```
a=>(b=a.map(s=>Math.atan2(...s)/Math.PI+2),k=[],b.map(t=>d=![k[u=t*a.length|1]=t<k[u]?k[u]:t,k[--u]=t>k[u]?k[u]:t]),k.filter(t=>t).map((v,i,s)=>d=d<(t=s[i+1]||s[0]+2)-v?(T=t)-(V=v):d),[T,V].map(x=>b.indexOf(x)))

```

Try it online!

Assuming:

* atan2 is O(1)
* x.map, x.filter are O(n) function calls
* x.indexOf is O(n)

---

```
a=>(
  n=a.length,
  b=a.map(([t,u])=>Math.atan2(t,u)/Math.PI+2),    // [1, 3)
  k=[...Array(n*4)],
  b.map(t=>d=![k[u=t*n|1]=t<k[u]?k[u]:t,k[--u]=t>k[u]?k[u]:t]),
  // interval = 2/n, just enough
  k.filter(t=>t).map(
    (v,i,s)=>d=d<(t=s[i+1]||s[0]+2)-v?(T=t)-(V=v):d
  ),  // furthest
  [b.indexOf(T),b.indexOf(V)]
)

```
> 5 votes

# Answer
# Python 3, O(n\*log(n)), 167 bytes

```
import math
def f(p):p=[math.atan2(*x)for x in p];q=sorted(p);d=[b-a for a,b in zip(q,q[1:])]+[math.pi*2-q[-1]+q[0]];i=d.index(max(d));return map(p.index,(q*2)[i:i+2])

```

Try it online!

The sorting step takes O(n\*log(n)) time, all other steps take linear time.

---

## Ungolfed

```
import math
def f(p):
  p=[math.atan2(x, y)for x, y in p]   # convert coords to angle (radians)
  q=sorted(p)                         # sort by angle
  d=[b-a for a,b in zip(q,q[1:])]     # calculate the difference between two adjacent points
  d+=[math.pi*2-q[-1]+q[0]]           # difference between first and last point
  i=d.index(max(d))                   # where is the maximum delta?
  return map(p.index,(q*2)[i:i+2])    # where were these two points in the original list?

```
> 7 votes

# Answer
# APL (Dyalog Unicode), O(n), 92 bytes

```
L←12○⎕
x←(n←⍴L)⍴⊂⍬
L{x[⌊n×.5+⍺÷○2],←⊂⊂⍺⍵}¨⍳n
1∘⊃¨{2↑⍵⌽⍨⊃⍸(⌊/=⊢)2-/{⍵,⍵+○2}⊃¨⍵}⊃,/{⍵[⍋⊃¨⍵]}¨x

```

Try it online!

Takes input as a vector of complex numbers and outputs a single array of the two indices. This uses bucket sort to achieve linear complexity.

Requires `⎕IO←0`

## Details

```
L←12○⎕   ⍝ Take input to L and convert all points to their phases  -- O(n)
n←⍴L     ⍝ Set n to be the length of L
x←n⍴⊂⍬   ⍝ Create an array consisting of `n` empty buckets         -- O(n)
L{...}¨⍳n  ⍝ For each ⍺=element of of L, ⍵=corresponding index:    -- ×n:
  ⍺⍵         ⍝ Create an entry consisting of the two-element array ⍺ ⍵    -- O(1)
  x[...],←⊂⊂ ⍝ Append it to the correct bucket in x                       -- O(1)
  ⌊n×.5+⍺÷○2 ⍝ Map phases in [-pi, pi) to bucket indices in 0..n-1        -- O(1)
x          ⍝ Now, x is a vector of buckets,
           ⍝ each of which contains a vector of entries (phase, index)
{⍵[⍋⊃¨⍵]}¨ ⍝ Sort each bucket by phase (buckets contain 1 element on average, so this is O(1) average case per bucket)
⊃,/        ⍝ Join so we have a single sorted vector of all entries (phase, index)
{...}      ⍝ Computationally less-worrisome part now that we have the phases sorted
           ⍝ Most following lines are O(n), rest are O(1)
  ⊃¨         ⍝ Extract the phase of of each entry
  {⍵,⍵+○2}   ⍝ Add 2pi to each phase, and append (deals with wrapping around)
  2-/        ⍝ Compute the difference of each consecutive pair of phases
               ⍝ (always negative since the phases are increasing)
  ⊃⍸(⌊/=⊢)   ⍝ Find the index i of the minimum difference (most negative --- furthest)
  ⍵⌽⍨        ⍝ Rotate the original vector of (phase, index) by i
  2↑         ⍝ Take the first 2 entries
  1∘⊃¨       ⍝ Get the indices of these two entries

```
> 3 votes

# Answer
# JavaScript (Node.js), O(n log n)?, ~~130~~ ~~129~~ 125 bytes

```
a=>a.map((r,i)=>[Math.atan2(...r)+6,i]).sort().map(([r,s],i,a,[p,q]=a[++i]||a[a=0])=>[p-r+!a*2*Math.PI-8,[s,q]]).sort()[0][1]

```

Try it online!

If the sorting is treated as O(n log n), then the whole algorithm is O(n log n); however it sorts by ASCII, so I'm not quite sure if the complexity remain
> 0 votes

# Answer
# Wolfram Language (Mathematica), 92 bytes

```
s~Position~#-1&/@Last@(S=SortBy)[Partition[S[s=#,ArcTan@@#&],2,1,-1],EuclideanDistance@@#&]&

```

Try it online!
> 0 votes

---
Tags: code-golf, math, arithmetic, geometry, fastest-algorithm
---


title: How many days in a month?

text:
# Question
Title: How many days in a month?
Given a textual representation (case-insensitive full name or 3 character abbreviation) of a month return the number of days in the month.

For example, `december`, `DEC`, and `dec` should all return 31.

February can have either 28 or 29 days.

Assume the input is a month in one of the correct forms.

# Answer
> 4 votes
# Pyke, 9 bytes

```
l4C9@~%R@

```

Try it here!

```
l4        -   input.title()
    @     -  v.index(^)
  C9      -   ['PADDING', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
        @ - v[^]
     ~%R  -  ['Padding', 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

```

### Or 15 bytes if all input formats are required

```
l43<C9 3L<@~%R@

```

Try it here!

```
l43<            -   input.title()[:3]
          @     -  v.index(^)
    C9 3L<      -   ['PAD', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
              @ - v[^]
           ~%R  -  ['Padding', 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

```

# Answer
> 36 votes
# JavaScript (ES6),  ~~48 47 44 43~~  42 bytes

```
m=>31^'311'[parseInt(m[1]+m[2],34)*3%49%8]

```

### Demo

```
let f =

m=>31^'311'[parseInt(m[1]+m[2],34)*3%49%8]

;(
  'JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC,' +
  'JANUARY,FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER'
).split`,`
.forEach(m => console.log(m, '->', f(m)))
```

### How?

These operations lead to a lookup table of 8 entries, which would not be very interesting if the values were randomly distributed. But any result greater than **2** is mapped to **31** days. Therefore, only the first 3 entries need to be stored explicitly.

```
Month | [1:2] | Base 34 -> dec. | * 3  | % 49 | % 8 | Days
------+-------+-----------------+------+------+-----+-----
  JAN |    AN |             363 | 1089 |   11 |   3 |  31
  FEB |    EB |             487 | 1461 |   40 |   0 |  28
  MAR |    AR |             367 | 1101 |   23 |   7 |  31
  APR |    PR |             877 | 2631 |   34 |   2 |  30
  MAY |    AY |              10 |   30 |   30 |   6 |  31
  JUN |    UN |            1043 | 3129 |   42 |   2 |  30
  JUL |    UL |            1041 | 3123 |   36 |   4 |  31
  AUG |    UG |            1036 | 3108 |   21 |   5 |  31
  SEP |    EP |             501 | 1503 |   33 |   1 |  30
  OCT |    CT |             437 | 1311 |   37 |   5 |  31
  NOV |    OV |             847 | 2541 |   42 |   2 |  30
  DEC |    EC |             488 | 1464 |   43 |   3 |  31

```

# Answer
> 18 votes
# Javascript (ES6), ~~36~~ 33 bytes

-3 bytes thanks to @JustinMariner and @Neil

```
m=>31-new Date(m+31).getDate()%31

```

Sorry @Arnauld, abusing JavaScript weirdness is shorter than your fancy base conversions.

### How it works

For some reason, JavaScript allows entering dates outside of the specified month. The code counts how many days outside the month the date is to determine how many days there are in the month. Examples:
`"FEB31"``Thu Mar 02 2000``31 - 2 % 31``29`
`"October31"``Tue Oct 31 2000``31 - 31 % 31``31`

### Test cases

```
f=m=>31-new Date(m+31).getDate()%31
;(
 "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC,"+
 "January,February,Mars,April,May,June,July,August,September,October,November,December"
).split`,`.forEach(s=>console.log(s,"->",f(s)))
```

# Answer
> 12 votes
# Python 2, ~~46~~ ~~45~~ 38 bytes

*-1 byte thanks to @totallyhuman*

```
lambda m:29-int(m[1:3],35)%238%36%-5/2

```

Try it online!

# Answer
> 6 votes
# Proton, 50 bytes

```
k=>31-((e=k.lower()[1to3])in"eprunov")-3*(e=="eb")

```

Try it online!

-14 bytes thanks to Jonathan Frech

Thirty days hath September, April, June, and November. All the rest had peanut butter. All except my grandmother; she had a little red trike, but I stole it. muahahahahaha

(I've been waiting to tell that joke (source: my math professor) for ages on this site :D :D :D)

# Answer
> 6 votes
# Bash, 21 bytes

```
cal $1|xargs|tail -c3

```

Try it online!

Takes input as command-line argument and outputs with a trailing newline. The day count for February depends on that of the current year

Requires the **util-linux 2.29** version of `cal`, which is the one available on TIO. Also is locale-dependent, so LC\_TIME must be changed on non-English systems (thanks @Dennis for clarification).

Idea of piping through `xargs` to trim `cal`'s output is from this SO answer.

# Answer
> 6 votes
# APL (Dyalog), ~~32~~ 27 bytes (SBCS)

-2 thanks to ngn

Tacit prefix function. Assumes `⎕IO` (**I**ndex **O**rigin) `0`, which is default on many systems.

```
32-1⌈∘⊃'.p|un|no|feb'⎕S 1⍠1

```

Try it online!

`1⌈∘⊃` and use the maximum of one and the first element of that (0 if none) to pick from

`32-` thirty-two minus

`1⌈∘` the maximum of one and

the first element (0 if none) of

`'.p|un|no|f'⎕S` the PCRE **Search* for any-char,"p" or "un" or "no" or "f"

`1` returning the length of the matches

`⍠1` and done case insensitively

* **Ap**r, S**ep**, J**un**, and **No**v will give 32−2=30
* **Feb** will give 32−3=29 (allowed by OP)
* anything else will give 32−1=31

# Answer
> 4 votes
# C# (.NET Core), 52+13=65 38+24=62 bytes

```
m=>D.DaysInMonth(1,D.Parse(1+m).Month)

```

Try it online!

+24 for `using D=System.DateTime;`

### Acknowledgements

-3 bytes thanks to Grzegorz Puławski.

# Answer
> 3 votes
# Python 3, 60 bytes

```
x=input().lower()[1:3];print(31-(x in"eprunov")-3*(x=="eb"))

```

Try it online!

Porting my Proton solution

-10 bytes thanks to totallyhuman

# Answer
> 3 votes
## Shell/GNU Date, ~~39~~, 26 bytes

```
date -d1$1+1month-1day +%d

```

Where `$1` is the name of the month.

Try it online!

*edit: Thanks Dennis for saving many bytes!*

# Answer
> 2 votes
# AWK, ~~45~~ 44 bytes

```
L=tolower($1){$0=L~/v|p|un/?30:L~/f/?28:31}1

```

Try it online!

# Answer
> 2 votes
# Haskell, ~~65~~ ~~63~~ 62 bytes

```
f.map((`mod`32).fromEnum)
f(_:b:c:_)|c<3=28|c>13,b>3=30
f _=31

```

Try it online!

Pattern matching approach. The first line is to handle the case-insensitivity. Then we return `28` if the third letter is smaller than C (number 3), `30` if the second letter is larger than C and the third one larger than M, or `31` otherwise.

*Edit: -1 byte thanks to Leo*

---

### Alternative (~~65~~ 64 bytes)

```
f s|let i#n=n<mod(fromEnum$s!!i)32=sum$29:[2|2#2]++[-1|2#13,1#3]

```

Try it online!

# Answer
> 2 votes
# Perl 5, 47 + 1 (`-p`) = 48 bytes

```
$_=substr$_,1,2;$_=31-("eprunov"=~/$_/i)-3*/b/i

```

Try it online!

# Answer
> 2 votes
# Mediawiki Template, 19 bytes

```
{{#time:t|{{{1}}}}}

```

# Answer
> 2 votes
# q/kdb+, 36 bytes

**Solution:**

```
28 30 31@2^1&(*)"ebeprunov"ss(_)1_3#

```

**Examples:**

```
q)28 30 31@2^1&(*)"ebeprunov"ss(_)1_3#"January"
31
q)28 30 31@2^1&(*)"ebeprunov"ss(_)1_3#"FEB"
28
q)28 30 31@2^1&(*)"ebeprunov"ss(_)1_3#"jun"
30

```

**Explanation:**

There are a million ways to skin a cat. I think is slightly different to the others. Take the 2nd and 3rd letters of the input, lowercase them, then look them up in the string `"ebeprunov"`. If they are at location 0, then this is February, if they are at a location \>0 they are a 30-dayer, if they are not in the string, they are a 31-dayer.

```
28 30 31@2^1&first"ebeprunov"ss lower 1_3# / ungolfed solution
                                        3# / take first 3 items from list, January => Jan
                                      1_   / drop the first item from the list, Jan => an
                                lower      / lower-case, an => an
                  "ebeprunov"ss            / string-search in "ebeprunov", an => ,0N (enlisted null)
             first                         / take the first, ,0N => 0N
           1&                              / take max (&) with 1, 0N => 0N
         2^                                / fill nulls with 2, 0N => 2
        @                                  / index into
28 30 31                                   / list 28,30,31

```

# Answer
> 1 votes
# MATL, 22 bytes

```
14L22Y2c3:Z)Z{kj3:)km)

```

**Try it online!**

### Explanation

```
14L    % Push numeric array of month lengths: [31 28 ... 31]
22Y2   % Push cell array of strings with month names: {'January', ..., 'December'}
c      % Convert to 2D char array, right-padding with spaces
3:Z)   % Keep first 3 columns
Z{     % Split into cell array of strings, one each row
k      % Convert to lower case
j      % Input string
3:)    % Keep first 3 characcters
k      % Convert to lower case
m      % Ismember: gives a logical index with one match
)      % Use that as index into array of month lengths. Implicit display

```

# Answer
> 1 votes
# Retina, ~~32~~ ~~31~~ 28 bytes

```
i`f
28
i`p|v|un
30
\D

^$
31

```

Try it online! Edit: Saved 1 byte thanks to @RobertBenson. Saved 3 bytes thanks to @ovs.

# Answer
> 1 votes
# Python 3 \- ~~93~~ ~~86~~ ~~84~~ 82 bytes

Variants of answer (showing the progression of time, and bytes for each, with TIO links):

Original Answer (93 bytes)

-7 bytes thanks to Jonathan Frech. (86 bytes)

-2 more bytes thanks to my own further testing of the `monthrange` results, with the second value always being the higher value. (84 bytes) 1

-2 more by using `import calendar as c` and referencing it with `c.monthrange`. (82 bytes, **current revision**)

---

```
lambda x:c.monthrange(1,time.strptime(x[:3],'%b')[1])[1];import time,calendar as c

```

---

Obviously not as nice as HyperNeutrino's answer which doesn't use built-ins, but this still works.

---

*Footnotes*

1: Test cases via TIO.run showing the proof for how I'm handling those `monthrange` values, for a varying number of month test cases.

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~46~~ 30 bytes

```
#~NextDate~"Month"~DayCount~#&

```

Try it online!

Will give either `28` or `29` for February depending on whether the current year is a leap year.

# How it works

All date commands in Mathematica will interpret input such `April`, `APR`, `ApRiL`, and so on as the first day of the corresponding month in the current year. (As a bonus, input such as `"February 2016"` or `{2016,2}` also works as expected.)

`#~NextDate~"Month"` gives the first day of the month after that, and `DayCount` gives the number of days between its two arguments. The number of days between April 1st and May 1st is 30, the number of days in April.

# Answer
> 1 votes
# Java 8, 47 bytes

```
m->31-new java.util.Date(m+"31 1").getDate()%31

```

Try it online!

Ended up using the same idea as Herman Lauenstein's JS answer, where setting the date to the 31st pushed into the next month. Java does require a year, so that has been set to `1`.

# Answer
> 1 votes
# PHP, ~~38~~ ~~33+1~~ 32+1 bytes

*Saved 5 bytes thanks to Titus*

```
<?=date(t,strtotime("$argn 1"));

```

Run as pipe with `-nF`

Try it online!

# Answer
> 1 votes
# Excel VBA, ~~47~~ 43 Bytes

Anonymous VBE immediate window function that takes input, as month name, abbreviation, or number, from range `[A1]` and outputs the length of that month in the year 2001 to the VBE immediate window function.

```
?31-Day(DateValue("1 "&[A1]&" 1")+30)Mod 31

```

### Old Version

```
d=DateValue(["1 "&A1&" 1"]):?DateAdd("m",1,d)-d

```

# Answer
> 0 votes
# QBIC, ~~49~~ 35 bytes

```
?31-(instr(@aprjunsepnov feb`,;)%3)

```

Significantly shorter with some trickery.

## Explanation

```
?                          PRINT
31-(                       31 minus
  instr(                   the position of
                      ,;   our input string
    @aprjunsepnov feb`  )  in the string cntaining all non-31 months
    %3)                    modulo 3 (this yields a 1 for each month except feb=2)

```

# Answer
> 0 votes
# Java (OpenJDK 8), 126 bytes

```
s->{for(java.time.Month m:java.time.Month.values())if(m.name().startsWith(s.toUpperCase()))System.out.print(m.length(false));}

```

Try it online!

# Answer
> 0 votes
## Perl 5, 24 bytes

**23 bytes code + 1 for `-p`.**

```
$_=31-/p|un|no/i-/f/i*3

```

Try it online!

# Answer
> 0 votes
# Ruby, 45 bytes

```
->m{((Date.parse(m)>>1)-1).day}
require'date'

```

Try it online!

Ruby's `Date.parse` accepts a month name on its own. What would normally be a right-shift (`>>`) actually adds to the month of the `Date` object. Subtraction affects the day of the month, which will wrap backwards to the last day of the previous month.

# Answer
> 0 votes
# Kotlin, 92 bytes

```
val d={m:String->arrayOf(0,31,30,30,31,30,31,28,31,0,30)[(m[1].toInt()+m[2].toInt())%32%11]}

```

Try it online!

# Answer
> 0 votes
# JavaScript (V8), 100 bytes

```
(z,v=n=e=b=r=y=u=c=0,t=s=a=l=1,f=p=29,m=j=g=o=30,d=31)=>eval([z[0],z[1],z[2]].join`+`.toLowerCase())

```

Try it online!

# Answer
> 0 votes
# Japt, 12 bytes

Uses Herman's method.

```
´H-ÐU+H f uH

```

Try it (includes all test cases, footer resets the `H` constant for the next case)

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


title: De-interleave log lines

text:
# Question
Title: De-interleave log lines
You've inherited a server that runs several apps which all output to the same log.

Your task is to de-interleave the lines of the log file by source. Fortunately, each line begins with a tag that indicates which app it is from.

## Logs

Each line will look something like this:

```
[app_name] Something horrible happened!

```
* App tags are always between square brackets and will contain only alphanumeric characters and underscores.
* All lines will have an app tag at the beginning. There will not be preceding whitespace or any other characters.
* There will always be at least one space after the app tag
* App tags are nonempty
* There may be other square brackets later on any given line.
* There may or may not be a message after the tag
* The log may be empty
* There is no limit to how many unique app tags will be present in the file.

## Example

An entire log might look like this:

```
[weather] Current temp: 83F
[barkeep] Fish enters bar
[barkeep] Fish orders beer
[stockmarket] PI +3.14
[barkeep] Fish leaves bar
[weather] 40% chance of rain detected

```

Which should output three different logs:

```
[weather] Current temp: 83F
[weather] 40% chance of rain detected

```

```
[barkeep] Fish enters bar
[barkeep] Fish orders beer
[barkeep] Fish leaves bar

```

```
[stockmarket] PI +3.14

```

You are not given the names of the app tags ahead of time. You must determine them only by analyzing the log file.

## Rules and Scoring

* This is , so shortest code wins.
* Standard rules and loopholes apply
* Use any convenient IO format, provided that each input line is represented as a string, not a pre-parsed tag + message. Non-exhaustive list of allowed outputs:
    + Several files named after each tag
    + Several lists of strings
    + One concatenated list of strings containing lines grouped by tag with or without a separator (the separator must not begin with a tag)
    + Same as above, but to stdout or a file.
* The order in which separated logs are output is irrelevant, however the log lines within each group must preserve the order they were found in the original file

# Answer
# Bash, ~~4~~ 11 bytes

Added 7 bytes to fix a bug kindly pointed out by Shaggy.

```
sort -sk1,1

```

Try it online!

Performs a stable sort (the `s` command line argument) based on the first field (`k1,1`) separated by whitespace.
> 9 votes

# Answer
# , ~~50~~ 46 bytes

```
function(r)split(r,substr(r,1,regexpr("]",r)))

```

Try it online!

Outputs as a `list` with each element `name`d with the `[tag]`. Each list element maintains order within its tag. Returns an empty named list `named list()` for empty input.

-2 bytes each thanks to Robin Ryder and Dominic van Essen!
> 7 votes

# Answer
# Pyth, 3 bytes

```
ohc

```

Try it online!

The input format is a list of strings:

```
["[weather] Current temp: 83F","[barkeep] Fish enters bar","[barkeep] Fish orders beer","[stockmarket] PI +3.14","[barkeep] Fish leaves bar","[weather] 40% chance of rain detected"]

```

How the code works:

* `o`: Order by
* `h`: The first element of
* `c`: Each string split on spaces
> 5 votes

# Answer
# Python, 44 bytes

```
lambda a:sorted(a,key=lambda l:l.split()[0])

```

**Try it online!**

Loose I/O allows us to take, and result in, a list of lines. Since we do not have to separate the groups, the problem is reduced to performing a stable sort of the lines on the prefix of each line up to the first space, `split()` will split at some other white-space characters too but none can be present in the application tag portion.
> 4 votes

# Answer
# Scala, 26 bytes

```
_.sortBy(_.split("]")(0))

```

Returns a `List[String]` with no separator in between, but it is sorted by the tag.

Try it in Scastie

---

# Returns a `Map[String,List[String]]`, 26 bytes

```
_ groupBy(_.split("]")(0))

```

Takes a list of strings and returns a `Map[List[String]]` where the keys are the tags and the values are the logs associated with that tag.

Try it in Scastie

---

# Previous solution, 66 bytes

```
_ groupBy{case s"[$t]$r"=>t}map(_._2 mkString "\n")mkString "\n"*2

```

Try it in Scastie (for whatever reason, `s` doesn't work in TIO)

Each app's logs are separated by 2 newlines (I might be able to save 2 bytes if it just had to be the one newline character). The input is a list of strings, and the output is one big string.
> 3 votes

# Answer
# APL (Dyalog Extended), 10 bytes (SBCS)

Anonymous tacit prefix function. Takes a list of character lists as argument. Returns a matrix of character lists, with one log in each row.

```
⊢⊢⌸⍨≠⊃⍤⊆¨⊢

```

Try it online!

on the argument,

use the non-spaces to…

`⊆¨` partition each list into a list of lists (removes spaces, keeps runs of non-spaces),

`⊃⍤` then keep the first \[of each\] (i.e. the tags),

`⊢⌸⍨` use those as keys to group…

the argument
> 3 votes

# Answer
# vim, ~~13~~ 11 bytes

```
:sor/\w\+/r

```

bugfix and byte save thanks to @Dingus!

Try it online!
> 3 votes

# Answer
# Retina 0.8.2, ~~14~~ 13 bytes

```
O$`(\w+).*
$1

```

Try it online! Explanation: Since no output group separator is required, the lines are simply sorted by app tag, which is achieved by capturing the match on `\w+` and specifying `$1` as the sort key. Sort in Retina is stable, so that lines with the same prefix will retain their order. Edit: Saved 1 byte thanks to @FryAmTheEggman for pointing out an easier way to match the app tag. Note that although the match doesn't include the leading `[`, all of the lines start with `[`, so that doesn't affect the result of the sort.
> 2 votes

# Answer
# AWK, ~~62~~ 58 bytes

Saved 4 bytes thanks to Dominic van Essen!!!

```
{a[$1][i++]=$0}END{for(k in a)for(j in a[k])print a[k][j]}

```

Try it online!

Stores all lines in a 2D associative array `a`. The first key is the first field (separated by whitespace). So all lines that begin with the same field are stored together. The second key is an increasing integer index. The most verbose part is the `END` action which prints the contents of `a` grouped by first field in order of appearance.
> 2 votes

# Answer
# 05AB1E, 3 bytes

```
Σ#¬

```

**Input and Output** is a list of logs.

Explanation:

```
Σ#¬
Σ          Sort by:
 #         Split (each log) by spaces
  ¬        Head (which is the tagname)

```

This also keeps the order of the logs, as required.

Try it online!
> 2 votes

# Answer
# Python 3, <sup>~~148~~</sup>127 bytes

```
a={}
try:
 while 1:
  b=input();c=b.split("]")[0]
  if 1-(c in a):a[c]=[]
  a[c]+=[b]
except:[print(e)for k in a for e in a[k]]

```

Try it online!
> 1 votes

# Answer
# Japt, 4 bytes

Takes input as an array of lines, outputs a 2D-array.

```
ü_¸g

```

Try it
> 1 votes

# Answer
# Io, 73 bytes

```
method(i,i map(split first)unique map(I,i select(split first==I))flatten)

```

Try it online!
> 1 votes

# Answer
# C# (.NET Core), 181 162 160 bytes

```
input.GroupBy(l=>l.Split()[0]).ToList().ForEach((g)=>{using(var sw = new StreamWriter(g.Key.Trim('[').Trim(']')+".log")){foreach(var v in g)sw.WriteLine(v);}});

```

Try it online!

# C# (Visual C# Interactive Compiler), 179 bytes

```
i=>i.GroupBy((l)=>{return l.Split(' ')[0];}).ToList().ForEach((g)=>{using(var sw = new StreamWriter(g.Key.Trim(new char[]{'[',']'})+".log")){foreach(var v in g)sw.WriteLine(v);}})

```

Try it online!

I'm not sure the first solution is code gulf compliant, so the second solution uses a lambda expression.
> 1 votes

# Answer
# Perl 6, 16 bytes

```
*.sort:{~m/\w+/}

```

Try it online!

Sorts by the first string of alphanumeric characters, which should be the app name
> 1 votes

# Answer
# V (vim), 5 bytes

```
úr/?]

```

Note: The `?` above is in-place of the unprintable byte \\$\text{\x}81\\$ (the "No Break Here" control character).

**Try it online!**

Note that this works with a lack of spaces (even one directly after the first `]` bracket), with the presence of `[]` brackets in the log message, and with the presence of an untagged application, Try it online!

### How?

```
úr/?]
ú     - sort by:
 r    -   with flag=r: use match (default behaviour is to use what's after the match)
  /   -     with the pattern:
   ?  -       (byte 83) a shortcut for .\{-}
                                       .     - match any character
                                        \{-} - 0 or more times matching as few times as possible
    ] -       match a literal ']' character

```
> 1 votes

# Answer
# AutoHotkey, 74 bytes

```
Loop,Read,f
{
s:=A_LoopReadLine
FileAppend,%s%`n,% StrSplit(s,"]","[")[1]
}

```

Reads from a file named `f` and outputs into multiple files based on the tag.
> 1 votes

# Answer
# SimpleTemplate 0.84, 109 bytes

Yeah, it's pretty long, but does the job!

```
{@callexplode intoL EOL,argv.0}{@eachL}{@if_ matches"@^(\[.*\])@"M}{@setS.[M.1]S.[M.1],_,EOL}{@/}{@/}{@echoS}

```

This code generates an array with `<old content>, line, <end of line>`.

`{@echoS}` automatically flattens the array and displays it.

---

**Ungolfed:**

Yes, it's a mess, but here's a cleaner version:

```
{@call explode into lines EOL, argv.0}
{@set storage null}
{@each lines as line}
    {@if line matches "@^(\[.*\])@" match}
        {@set storage.[match.1] storage.[match.1], line, EOL}
    {@/}
{@/}
{@echo storage}

```

The function `explode` is a standard PHP function, but accessible from my language.

---

You can try this on: http://sandbox.onlinephpfunctions.com/code/9c66f8bacc6315ae56e7c193170e430f9cf9d902
> 1 votes

# Answer
# Haskell, 37 bytes

```
import Data.List
f=sortOn(head.words)

```

Try it online!
> 1 votes

# Answer
# Rust, 40 bytes

```
|a|a.sort_by_key(|x|x.split("]").next())

```

Takes a mutable reference to a slice of strings and sorts it.

Try it on the rust playground
> 1 votes

# Answer
# Perl 5 -M5.10.0 -Msort=stable, 53 bytes

```
say sort{(split('\]',$a))[0]cmp(split('\]',$b))[0]}<>

```

Try it online!
> 0 votes

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


title: Legendre's (Unsolved) Conjecture

text:
# Question
Title: Legendre's (Unsolved) Conjecture
Legendre's Conjecture is an unproven statement regarding the distribution of prime numbers; it asserts there is at least one prime number in the interval \\$(n^2,(n+1)^2)\\$ for all natural \\$n\\$.

# The Challenge

Make a program which only halts if Legendre's conjecture is false. Equivalently, the program will halt if there exists \\$n\\$ which disproves the conjecture.

# Rules

* This is so the shortest program in bytes wins.
* No input shall be taken by the program.
* The program only needs to halt or not halt in theory; memory and time constraints shall be ignored.
* One may use methods other than checking every \\$n\\$ if they can prove their program will still only halt if Legendre's conjecture is false.

# Answer
> 12 votes
# JavaScript (Node.js),  ~~49~~  47 bytes

A full program that stops only if there's some \\$n\ge2\\$ such that all \\$x\in\[(n-1)^2..n^2\]\\$ are composite.

```
for(x=n=2n;x-n*n;d?0:x=n*n++)for(d=x++;x%d--;);

```

Try it online!

### Commented

```
for(                  // outer loop:
  x = n = 2n;         //   start with x = n = 2
  x - n * n;          //   stop if x = n²
  d ? 0 : x = n * n++ //   if d = 0, set x = n² and increment n
)                     //
  for(                //   inner loop:
    d = x++;          //     start with d = x and increment x
    x % d--;          //     stop if d divides x; decrement d
  );                  //     if we end up with d = 0, then x is prime

```

# Answer
> 8 votes
# Raku, 34 bytes

```
1...{is-prime none $_²..($_+1)²}

```

Try it online!

Counts upwards until it finds a number where none of the given range are prime.

# Answer
> 8 votes
# 05AB1E, ~~17~~ 11 bytes

```
∞.∆DnÅNs>n@

```

Try it online!

*-6 bytes thanks to @ovs*

## Explained

```
∞.∆DnÅNs>n@
∞                   Push an infinite list
 .∆                 Find the first item in that list that:
   D
       s>n              (n+1)^2 is
          @             larger or equal than
    nÅN                 the next prime from n^2

```

# Answer
> 7 votes
# Jelly, 9 bytes

```
²+æR$Ṇµ2#

```

Try it online!

-1 byte thanks to caird coinheringaahing
-1 byte thanks to Jonathan Allan

# Answer
> 7 votes
# , ~~60~~ ~~55~~ 54 bytes

*Edit: -1 byte thanks to Robin Ryder*

```
while(sd(sapply(lapply(T^2:(T=T+1)^2,`%%`,2:T),all)))T

```

Try it online!, or, since it's rather boring to run a program that (probably) never halts and produces no output, try a slightly longer version (exchanging `n=sum(` for `any(`) that prints n and the number of primes in the interval (n-1)^2..n^2 for each n\>2.

Commented original version:

```
while(                                  # keep looping as long as...
    any(                                # there is at least one true result among...
        sapply(T^2:(T=T+1)^2,           # the loop from T^2 up to (T+1)^2
                                        # (& use this opportunity to increment T)...
            function(x)all(x%%(2:T))    # tested for primality by checking that all
                                        # modulo divisions from 2..T have a non-zero result
        )
    )
){}

```

# Answer
> 7 votes
# Jelly, 7 bytes

```
‘ɼ²ÆCµƬ

```

A niladic Link which, if the conjecture is False, will yield a list of counts of primes between \\$2\\$ and \\$k^2\\$ where \\$k\\$ is the zero-based index of the element (although the zero-indexed element will be `None` rather than `0`). The final value in the list will be the count of primes between \\$2\\$ and \\$n^2\\$ (the next term would be the count between \\$2\\$ and \\$(n+1)^2\\$, and would be equal to that).

Note: Since this uses one of Jelly's prime related built-ins, this is subject to the underlying implementation's (sympy's) primality check, and `help(sympy.ntheory.isprime)` states *...\[If\] the number is larger than 2^64, a strong BPSW test is performed. While this is a probable prime test and we believe counterexamples exist, there are no known counterexamples)*.

**Try it online!**

### How?

Collects the counts of primes between \\$2\\$ and \\$(k+1)^2\\$ starting with \\$k=0\\$ until repetition would be present by appending the result. This implies there are no new primes between \\$(k+1)^2\\$ and \\$(k+2)^2\\$ (i.e. \\$n^2\\$ and \\$(n+1)^2\\$). The final result, if any, will have a leading `None` \- the initial input to the function that performs the counting.

```
‘ɼ²ÆCµƬ - Link: no arguments
      Ƭ - collect up (the initial input (None) and each result) until repetition:
     µ  -   apply the monadic chain - i.e. f(x=previousResult):
 ɼ      -     recall (k) from the register (initially 0), apply, store back, and yield:
‘       -     increment -> k+1
  ²     -     square -> (k+1)²
   ÆC   -     count primes from 2 to (k+1)² inclusive

```

# Answer
> 5 votes
# Retina 0.8.2, ~~67~~ 62 bytes

```

_¶¶_
{`(_+)¶_*(¶_+)
_$1$2$2$1$1_
¶(_+)¶(?!_*(?!(__+)\2+$)\1)

```

Don't try it online! Instead, try a Retina 1 version which takes as input the number of iterations. Explanation:

```

_¶¶_

```

The working area contains `n+1`,  and `(n+1)²`, where `n` starts at `0` but is immediately incremented (saving 5 bytes over my previous answer which started with `n=1`).

```
{`

```

Repeat until Legendre's conjecture is false.

```
(_+)¶_*(¶_+)
_$1$2$2$1$1_

```

Increment `n`; the old `(n+1)²` becomes the new  and the new `(n+1)²` is calculated.

```
¶(_+)¶(?!_*(?!(__+)\2+$)\1)

```

If none of the numbers between  and `(n+1)²` are prime, then delete  and `(n+1)²`, which causes the loop to terminate, as neither stage can now match.

# Answer
> 5 votes
# C (gcc), ~~194~~ ~~180~~ 169 bytes

```
#include<gmp.h>
main(){mpz_t n,l,h;for(mpz_init_set_ui(n,1),mpz_init(l),mpz_init(h);mpz_mul(l,n,n),mpz_add_ui(n,n,1),mpz_mul(h,n,n),mpz_nextprime(l,l),mpz_cmp(l,h)<1;);}

```

Try it online!

-14 bytes thanks to ceilingcat!

-11 bytes again thanks to ceilingcat!

To test, here's one that outputs the prime in each range:

# C (gcc), 352 bytes

```
 #include<stdio.h>
#include<gmp.h>
#define m(X) mpz_##X
main(){m(t) n,l,h;m(init_set_ui)(n,1);m(init)(l);m(init)(h);for(;;){m(mul)(l,n,n);m(add_ui)(n,n,1);m(mul)(h,n,n);
 printf("In (");
 m(out_str)(stdout,10,l);
 printf(", ");
 m(out_str)(stdout,10,h);
 printf("): ");
m(nextprime)(l,l);if(m(cmp)(l,h)>0)return;
 m(out_str)(stdout,10,l);
 puts("");
}}

```

Try it online!

Note: This is probably very optimizable. When certain users inevitably improve the solution, I'll update. ;)

# Answer
> 4 votes
# 05AB1E, 11 bytes

First attempt:

```
[N>nÅMNn‹#]

```

Fixed (after @ovs notes):

```
[NÌnÅMN>n‹#

```

## Explanation:

```
[NÌnÅMN>n‹#
[                     Infinite Loop
 N                    Current loop index (starts from 0 to Infinity)
  Ì                   add 2 ( we want to start from N=1 instead of N=0)
   n                  Squaring - (N+1)**2
    ÅM                Find the previous prime. Highest prime less than (N+1)**2
      N>               Push Current loop index + 1
        n              Squaring - N**2
         ‹             Does  Highest prime less than (N+1)**2 < N**2  ?
          #            If true, break the loop

```

Try it online!

# Answer
> 4 votes
# Python 2, 45 bytes

```
i=k=P=1
while~i*~i-k:P*=k;k+=1;i+=i*i<k>0<P%k

```

Try it online!

Here's a demonstration of the code halting if we modify it to claim that all of `range(36,49)` is non-prime.

We use the Wilson's Theorem prime generator. We count up potential primes `k`, and the condition `P%k>0` is met exactly for primes. Except, we use `P*=k` instead of `P*=k*k` which makes `k=4` also be called prime, but that doesn't matter here.

Here's how we halt if there's not prime between two consecutive squares. The value `i` tries to track the smallest number so that the square `i*i` is at least the current potential prime `k`. Every time we hit a prime `k`, we update `i` by checking if `i*i<k`, and if so, increment `i`. This makes it so that `k<=i*i` afterwards. But, if there is no prime between `i**2` and `(i+1)**2`, then `i` won't update in that interval, and `k` will reach all the way to `(i+1)**2`. The `while` loop conditions checks for this (writing `~i*~i` for `(i+1)**2`) and terminates the loop if it happens.

---

**73 bytes**

```
n=2
while any(all(k%i for i in range(2,k))for k in range(n*n,~n*~n)):n+=1

```

Try it online!

A more direct approach of checking that each interval between squares contains a prime, based on the solution of Manish Kundu

# Answer
> 3 votes
# MATL, ~~11~~ 10 bytes

```
`@U_Yq@QU<

```

Try it online!

-1 byte thanks to Luis Mendo. Otherwise, pretty straightforward.

```
`  % Start a loop
@  % Push loop index (n)
U  % square
_Yq % Get next prime
@QU % Loop index plus one, squared
<   % Continue loop if the prime is smaller than this.

```

# Answer
> 3 votes
# Io, 124 bytes

```
method(x :=1;loop(s :=0;for(i,x*x,x*(x+2)+1,if(Range 1 to(i)asList select(o,i%o<1)size<3,s :=1;break));if(s<1,break);x=x+1))

```

Try it online!

# Answer
> 3 votes
# Python 3, ~~107~~ ~~99~~ ~~88~~ ~~86~~ ~~90~~ ~~86~~ 79 bytes

```
n=2
while n:n+=0<sum(min(i%j for j in range(2,i))for i in range(n*n,~n*~n))or-n

```

Try it online!

Initially, n=2. Then it checks if any of the 2n numbers between n^2 and (n+1)^2 are prime or not. If yes, then n is incremented, otherwise n is set to 0 and the loop terminates.

*-7 bytes thanks to Jo King*

# Answer
> 3 votes
# \>\<\>, 51 bytes

```
/;?)*:&+1}::&<
\~:*>2:}}:}=?^:}}:}$%?2~1+l3+1.15a&4

```

Try it online!

Try it online! (2) shows the program terminating if starting above last prime in first range.

**Explanation**

```
/;?)*:&+1}::&<
\~:*

```

Prime branch, checks if first found prime is below \\$(n+1)^2\\$ and then increments \\$n\\$ and jumps up to the next range, otherwise terminates

```
    >2:}}:}=?^

```

Ends trial division if we have found a prime

```
              :}}:}$%?2~1+l3+1.

```

Branch-free trial division

```
/
\                             .15a&4

```

Initial values, starts at 10 trying to find primes below \\$4^2\\$

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

```
_²ôZÑ dj}f1

```

Test it (May cause your browser to explode!)

```
_               :Function taking an integer Z as argument
 ²              :  Z squared
   ZÑ           :  Z times 2
  ô             :  Range [Z²,Z²+Z*2]
      d         :  Any
       j        :    Prime
        }       :End function
         f1     :Return the first Z≥1 that returns false

```

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

```
For[n=1,NextPrime[n++^2]<n^2,]

```

Try it online!

Special thankks to @att for saving 9 bytes

# Answer
> 2 votes
# Scala, <sup>~~98~~ ~~93~~ ~~91~~</sup> 87 bytes

*-7 bytes thanks to Dominic Van Essen*

```
Stream.iterate(2:BigInt)(_+1)find(n=>n*n to n*n+2*n forall(x=>n to(2,-1)exists(x%_<1)))

```

Without `BigInt`, it could be made a few bytes shorter, but then it would overflow.

It first creates an infinite list starting at 2, then tries to find an `n` in that list such that every number `x` in the range `n^2` to `(n+1)^2` is composite.

Try it in Scastie

# Answer
> 2 votes
# C (gcc), ~~88~~ 84 bytes

Saved 4 bytes thanks to ceilingcat!!!

```
q;h;i;j;f(n){for(h=n=1;h;++n)for(h=0,i=n*n;q=j=++i<~n*~n;h|=q)for(;++j<i;)q=q&&i%j;}

```

Try it online!

Will run forever on an infinite machine (with new infinity-bit `int` types!) so long as there's always a prime number in the interval \\$(n^2,(n+1)^2)\\$.

Here's the same code modified to print the primes as they are found:

# C (gcc), 161 bytes

```
q;h;i;j;f(n){for(h=n=1;h;++n)for(h=0,i=n*n;q=j=++i<~n*~n;h|=q){for(;++j<i;)q=q&&i%j;if(q)printf("Found prime %d in the interval (%d, %d)\n",j,n*n,(n+1)*(n+1));}}

```

Try it online!

# Answer
> 2 votes
# Brachylog, 12 bytes

```
+₁;?≜^₂ᵐ⟧₂ṗⁿ

```

Try it online!

### How it works

Brachylog will try to find a value `N` that fulfills the following program:

```
+₁;?≜^₂ᵐ⟧₂ṗⁿ
+₁            N+1
  ;?          [N+1, N]
    ≜         Try possible numbers, e.g. [5, 4]
     ^₂ᵐ      Map square [25, 16]
        ⟧₂    Range from min to max
          ṗⁿ  Succeeds if there is no prime in this range

```

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


title: Integers in cosine

text:
# Question
Title: Integers in cosine
## Integers in cosine

From trigonometry we know that

\\$\sin(a) =-\cos(a + \frac{(4\*m + 1)\pi}{2})\\$

where \\$a\\$ is an angle and \\$m\in\mathbb{Z}\\$ (integer).

### The task

For an input of a positive integer \\$n\\$ calculate the value of the integer \\$k\\$ with \\$n\\$ digits that minimizes the difference between \\$\sin(a)\\$ and \\$-\cos(a + k)\\$. Or in a simpler way, generate the sequence A308879.

### First few values

1 digit : 8
2 digits: 33
3 digits: 699
4 digits: 9929
5 digits: 51819
6 digits: 573204

### Output

You can create a function or print the result on the standard output. Your program needs to be able to calculate at least the 6 cases in the section above.

### Scoring

This is , shortest code in bytes wins.

### Reference

https://www.iquilezles.org/blog/?p=4760

# Answer
> 11 votes
# Wolfram Language (Mathematica), 25 bytes

This uses a trick: Mathematica doesn't expand `Sin[51819]` into a proper number even when `Max` is called on a list of such things, and because of how `Last` works, it doesn't care that `Sin[51819]` is not a list and simply returns `51819`.

```
Last@Max@Sin@Range[10^#]&

```

Try it online!

# Answer
> 9 votes
# Ruby, 37 bytes

```
->n{(1..10**n).max_by{|k|Math.sin k}}

```

Try it online!

Minimising the difference between \\$\sin(a)\\$ and \\$-\cos(a+k)\\$ amounts to minimising \\$|k-(4m+1)\pi/2|\\$ for some \\$m\\$, or equivalently maximising \\$\sin(k)\\$.

Iterating over `(1..10**n)` works at least for \\$n\le6\\$, as required. More generally, according to the OEIS (reference courtesy of @Λ̸̸'s 05AB1E answer):

> It is not guaranteed that each term in the sequence produces a better approximation than the previous one, although numerical evidence suggests so.

Iterating over `(10**~-n...10**n)` is guaranteed to work for any \\$n\\$, at a cost of 7 extra bytes.

# Answer
> 6 votes
# 05AB1E, 7 bytes

Port of Dingus's answer. (It's A308879. From that page, it says that the sequence is also "the n-digit integer m that maximizes sin(m)"...)

```
°LΣÅ½}θ

```

Try it online!

## Explanation

```
°       10 ** n
 L      1 range
  Σ     Sort by:
   Å½}  Sine
      θ Maximum under that mapping

```

# Answer
> 5 votes
# ~~30~~ 27 bytes

Following the same thread as @Dingus' Ruby answer, as indicated in the entry to A308879, i.e. looking at the maximum value of \\$\sin(k)\\$ over \\$1,\ldots,10^n\\$:

```
which.max(sin(1:10^scan()))

```

Try it online!

# Answer
> 4 votes
# Java 8, 91 bytes

```
n->{double r=0,m=0,s,k=Math.pow(10,n);for(;k-->1;)if((s=Math.sin(k))>m){m=s;r=k;}return r;}

```

Port of *@Dingus*' Ruby answer, so make sure to upvote him!

Try it online. (It's barely able to reach up to \\$n=9\\$ on TIO before it times out.)

**Explanation:**

```
n->{                           // Method with integer parameter and double return-type
  double r=0,                  //  Result-double, starting at 0
         m=0,                  //  Maximum `m`, starting at 0
         s,                    //  Integer `s` for the Sine calculation, uninitialized
  k=Math.pow(10,n);for(;k-->1; //  Loop `k` in the range (10^input, 1]:
    if((s=Math.sin(k))         //   Set `s` to the Sine of `k`
       >m){                    //   If this `s` is larger than the current maximum `m`:
      m=s;                     //    Replace the maximum with this `s`
      r=k;}                    //    And replace the result with `k`
  return r;}                   //  Return the result after the loop

```

# Answer
> 3 votes
# JavaScript (Node.js), ~~64~~ 63 bytes

```
n=>[...Array(t=10**n)].map(_=>[9-Math.sin(--t),t]).sort()[0][1]

```

Try it online!

# Answer
> 3 votes
# Japt `-h`, 10 bytes

```
ApU õ ñ!sM

```

Try it

# Answer
> 3 votes
# APL (Dyalog Extended), 9 bytes

```
⊃⍒1○⍳10*⎕

```

-7 bytes from ngn and Adám.

Try it online!

# APL (Dyalog Extended), ~~20~~ 16 bytes

```
{i[⊃⍒1○i←⍳10*⍵]}

```

-4 bytes from Bubbler.

Try it online!

Implements Dingus's algorithm.

## Explanation

```
{i[⊃⍒1○i←⍳10*⍵]}
{              } function body
 i     i←⍳10*⍵   assign to i the range of 1 to 10^n
     1○          find the sine of each value in i
     ⊃⍒          Grade(sort) by descending value, select index of first(maximum) value
 i[           ]  return k in i where sin k is maximum

```

# Answer
> 2 votes
# Fortran (GFortran), <sup>~~53~~</sup> 51 bytes

```
read*,n
print*,maxloc([(sin(1d0*k),k=1,10**n)])
end

```

Try it online!

Port of my own Ruby answer. Because why not?

# Answer
> 2 votes
# Python 3, 51 bytes

```
import math
lambda n:max(range(10**n),key=math.sin)

```

Try it online!

Uses Dingus's observation about maximizing sine.

---
Tags: code-golf, math, integer, trigonometry
---


# Question
Title: Remove partial matching duplicate lines and retain longest line
Write the shortest possible program to remove all partial matched duplicates from a list and only retain the longest lines. Sort order does not matter.

For following inputs, the intent is to search for the string `reminder` followed by a number and retain the longest unique `reminder + number` lines.

# Some rules

* `reminder` is a hard-coded word, case-sensitive.
* All lines contain exactly one match.
* There is always a space between `reminder` and the number.
* Only positive, whole numbers are used in the matches (not necessarily a contiguous set).
* Lines with same length for the same reminder are possible. It does not matter what line is chosen.
* Sort order of output does not matter.

# Inputs

```
A short reminder 1
This is the longest reminder 1 available
This is the longest reminder 2 available, different length
A short reminder 2
A short reminder 3
This is the longest reminder 3 available, another different length
Another short reminder 3
A reminder -1 but really a short reminder 42
This is the longest reminder but really a short reminder 42.

```

# Expected output

```
This is the longest reminder 1 available
This is the longest reminder 2 available, different length
This is the longest reminder 3 available, another different length
This is the longest reminder but really a short reminder 42.

```

Shortest code wins

---

Background: this stackoverflow question

# Answer
> 1 votes
# 05AB1E, 17 bytes

```
é.¡#I¡εнžm(Ã}þ}€θ

```

05AB1E doesn't have any regex, so figuring out the best approach with test case containing negative numbers or multiples spaces between the string and the number (i.e. `reminder 42`) was a bit tricky, but still pretty happy with how short it turned out.

First input is a list of string lines, and the second input is the hard-coded string to match.

Try it online.

**Explanation:**

```
é             # Sort the (implicit) input-list of lines by length (shortest to longest)
 .¡           # Group the lines by:
   #          #  Split the string on spaces
    I¡        #  Split that list on the second input-word
      ε       #  Map each inner list of strings to:
       н      #   Only leave the first part of the list
        žm    #   Push builtin 9876543210
          (   #   Negate it to -9876543210
           Ã  #   Only keep those characters from the string
      }þ      #  After the map, only leave strings consisting of just digits;
              #  so this will remove empty strings and negative numbers from the list
  }€          # After the group by: map over each group:
    θ         #  And only leave the last (thus longest) line
              # (after which the resulting list of lines is output implicitly)

```

See this for a step-by-step on how the input is transformed into the output.

# Answer
> 3 votes
# JavaScript (ES6),  ~~85 82~~  79 bytes

```
a=>a.sort((a,b)=>-!b[a.length]).filter(s=>a[k=/reminder \d+/.exec(s)]^(a[k]=1))

```

Try it online!

### How?

We first sort all strings from longest to shortest.

```
a.sort((a, b) =>
  -!b[a.length]  // 0 if 'b' is longer than 'a', -1 otherwise
)

```

We then filter the strings, keeping only the first occurrence of each `reminder N` key. The underlying object of the input array `a[]` is re-used to keep track of the keys that were already encountered.

```
.filter(s =>
  a[k = /reminder \d+/.exec(s)]
  ^
  (a[k] = 1)
)

```

# Answer
> 3 votes
# Japt, 20 bytes

Takes input as an array of strings. Output is sorted by the matched number, in lexicographical order.

```
ü_f`ã„ %d+` gÃ®ñÊÌ

```

Try it (Header splits input string on newlines)

```
ü_f`... %d+` gÃ®ñÊÌ     :Implicit input of array
ü                       :Group and sort by
 _                      :Passing each through the following function
  f                     :  Match
   `... %d+`            :    Compressed string "reminder %d+", which translates to the RegEx /reminder \d+/g
             g          :  Get first match ('Cause matching returns an array)
              Ã         :End grouping
               ®        :Map
                ñ       :  Sort by
                 Ê      :    Length
                  Ì     :  Get last element

```

# Answer
> 3 votes
# Python 3.8, ~~134~~ 132 bytes

```
import re
def f(l,d={}):
 for s in l:
  if len(d.get(n:=re.sub('.*reminder (\\d+).*','\\1',s))or'')<len(s):d[n]=s
 return d.values()

```

Try it online!

Tried recursive lambda approach but it's longer:

# Python 3.8, 148 bytes

```
f=lambda l,d={}:l and(len(d.get(n:=re.sub('.*reminder (\\d+).*','\\1',s:=l.pop()))or'')<len(s)and d.update([(n,s)])or f(l,d))or d.values()
import re

```

Try it online!

# Answer
> 2 votes
# Raku, 48 bytes

```
*.sort(-*.comb).unique(:as({~m/reminder\s\d+/}))

```

Try it online!

Sorts by longest first, then gets the unique elements by the reminder number.

# Answer
> 2 votes
# Retina 0.8.2, 68 bytes

```
O#$`
$.&
O#$`.*reminder (\d+).*
$1
.*(reminder \d+)(.*¶(.*\1\b))+
$3

```

Try it online! Explanation:

```
O#$`
$.&

```

Sort (in ascending order) numerically by length.

```
O#$`.*reminder (\d+).*
$1

```

Sort numerically by matched number, keeping lines with the same number sorted in length order.

```
.*(reminder \d+)(.*¶(.*\1\b))+
$3

```

Keep only the last line of consecutive lines with the same matched number.

# Answer
> 2 votes
# V (vim), 39 bytes

```
ÎÄÒ0J
ú!
ò/reminder ä
y2e0dw+VGç0¾/d

```

Try it online!

```
Î                 # on every line (:%norm)
 Ä                # (M-D)uplicate the line
  Ò0              # (M-R)eplace all characters with '0'
    J             # (J)oin with the original line
                  # This turns each line into "0000000000 reminder 1"
ú!                # Reverse (M-z)ort (cursor ends up on first line)
ò                 # (M-r)ecursively (until error)
 /reminder ä      # goto /reminder \d/ (longest reminder X, here we find X)
y2e               # (y)ank (e)nd of (2) words: reminder \d+>
   0dw            # goto beginning and (d)elete (w)ord (the 0s)
      +           # goto start of next line
       VG         # highlight until end
         ç^R0¾/d  # in this highlighted region delete lines matching:
                  # (^R)egister 0 - contains the reminder (y)anked earlier
^O                # Jump back to prev cursor position and repeat until error

```

# Answer
> 1 votes
# Jelly, 28 bytes

No (direct) regex support in Jelly (it's only indirectly available by executing Python code).

```
ðœṣ“Ç§ƥ»;⁶¤Ḋe€ÞṪf)ØDĠị⁸LÞṪ$€

```

A monadic Link accepting a list of lists of characters which yields a list of lists of characters.

**Try it online!** (footer just splits at newlines, calls the Link and joins back by newlines.)

### How?

```
ðœṣ“Ç§ƥ»;⁶¤Ḋe€ÞṪf)ØDĠị⁸LÞṪ$€ - Link: list of lists of characters, X
                  ØD         - digit characters
ð                )           - dyadic chain for each (line in X) - i.e. f(line, digit characters)
 œṣ                          -   split at substrings equal to:
          ¤                  -     nilad followed by link(s) as a nilad:
   “Ç§ƥ»                     -       compressed string "reminder"
         ⁶                   -       space character
        ;                    -       concatenate -> "reminder "
           Ḋ                 -   dequeue (leaving only strings to the right of a "match ")
              Þ              -   sort (these "parts") by
             €               -   for each (character, c, in part):
            e                -     (c) exists in (digit characters)?
               Ṫ             -   tail - giving us the single part starting with positive digit
                                        characters - N.B. a '0...' is always less, if present
                f            -   filter-keep (digit characters) - thus "42..." becomes "42"
                    Ġ        - group indices by value
                     ị       - index into:
                      ⁸      -   X - giving us a list of lists of lines with equal "number"
                           € - for each:
                          $  -   last two links as a monad:
                        Þ    -     sort by:
                       L     -       length
                         Ṫ   -     tail

```

# Answer
> 1 votes
# Perl 5 \+ `-M5.10.0`, 59 bytes

Uses the same approach as @Arbauld's answer, sorts the input by length then discards any sentences that contain a previously seen match.

```
say grep/reminder \d+/&&!${$&}++,sort{$b=~y///c-length$a}<>

```

Try it online!

# Answer
> 1 votes
# Ruby, 53 bytes

```
->a{a.sort_by{|s|-s.size}.uniq{|s|s[/reminder \d+/]}}

```

Try it online!

# Answer
> 1 votes
# Python 3, 100 bytes

```
lambda a:{max((j for j in a if'reminder '+i in j),key=len)for i in' '.join(a).split()if i.isdigit()}

```

Try it online!

Test cases borrowed from Noodle9.

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


title: Interviewer's Room

text:
# Question
Title: Interviewer's Room
> You are *James* and **four** of your friends (*Bjarne*, *Eich*, *Rossum*, *Ada*) are called for an interview. There are **n** interviewers, and they can *each serve one* person at a time, **alphabetically**. Each round of interview takes **20** min.

Let's take **n = 2**,

> So, the first round started with *Ada* and *Bjarne*, takes 20 min (they're handled simultaneously). Then, interviewers call persons for next round, who are *Eich* and ***James***, they took another 20 min.

Hence, finally you're out after 40 min.

---

# Challenge

Given an array as input like `["yourName", [an, Array, Of, Friends], numberOfInterviewers]`, your task is to output the time it'll take for you to complete the interview, in minutes.

Feel free to take three arguments as input, instead of the array.

### Sample I/O:

(`In = Out` format)

```
[ "James", ["Bjarne", "Eich"   , "Rossum", "Ada"  ], 2  ]   =   40
[ "Stark", ["Steve" , "Tchalla", "Banner", "Scott"], 3  ]   =   20
[ "spam" , ["bar"   , "eggs"   , "foo"   , "lorem"], 1  ]   =   100
[ "Oggy" , ["Jack"  , "DeeDee" , "Marky" , "Bob"  ], 10 ]   =   20

```

This is a , so fewest bytes will win!

# Answer
> 8 votes
# Python 2, ~~40~~ 39 bytes

*-1 byte thanks to @JonathanAllan!*

```
lambda s,l,n:~sum(x<s for x in l)/n*-20

```

Try it online!

# Answer
> 7 votes
# JavaScript (ES6),  ~~44~~  40 bytes

```
(s,a,n)=>-~(a.map(S=>k+=s>S,k=0),k/n)*20

```

Try it online!

# Answer
> 5 votes
# , ~~50~~ ~~49~~ ~~33~~ 32 bytes

*Edit: -1 byte thanks to Robin Ryder*

```
function(y,f,n)sum(f<y,n)%/%n*20

```

Try it online!

# Answer
> 4 votes
# Raku, 23 bytes

```
(*Xgt*).sum div*×20+20

```

Try it online!

Gets the number of other people before us in the queue, integer divides that by `n`, adds 1 and multiplies by 20.

# Answer
> 4 votes
# Jelly, 11 bytes

```
ṭṢi³N:⁵×-20

```

A full program accepting arguments `name`, `friends`, and `n` which prints the result.

**Try it online!**

### How?

```
ṭṢi³N:⁵×-20 - Main Link: name, friends
ṭ           - tack (friends to name)
 Ṣ          - sort
   ³        - 1st program arg = name
  i         - (1-based) index of (name in sort result)
    N       - negate
      ⁵     - 3rd program arg = n
     :      - integer division
        -20 - minus twenty
       ×    - multiply
            - implicit print

```

# Answer
> 3 votes
# Ruby, 46 40 39 38 31 bytes

```
->a,b,c{~b.count{|i|i<a}/c*-20}

```

-5 -1 byte from petStorm.

-1 byte from Rahul Verma.

-7 bytes from Dingus.

Try it online!

# Ruby, 83 bytes

```
->a,b,c{(b.push(a).sort.each_slice(c).map{|x|x.include?(a)}.find_index(true)+1)*20}

```

Try it online!

# Answer
> 3 votes
# Python 3, ~~53~~ ~~45~~ ~~44~~ 43 bytes

```
lambda a,b,c:~sorted([a]+b).index(a)//c*-20

```

Try it online!

Adds your name to list of friends, sorts the list and calculates the answer from the index of your name in the sorted list.

*Special thanks to Jonathan Allan for -1 byte*

# Answer
> 3 votes
# Rust, ~~56~~ 55 bytes

```
|s,l:&[&str],n|20+l.iter().filter(|x|*x<s).count()/n*20

```

Try it online!

*Special thanks to user and madlaina*

This is my first ever code golf so I hope I have the format correct!

# Answer
> 2 votes
# Io,  ~~48~~  45 bytes

```
method(s,a,n,((a select(<s)size+1)/n)ceil*20)

```

Try it online!

## Explanation

```
method(s,a,n,((      // Take 3 arguments.
    a select(<s)     // Take all items in the array a that is smaller than s
       size + 1)     // Take the size of that, and add 1
    /n)              // Divide it by n
ceil * 20)           // Take the ceiling of that, multiply by 20

```

# Answer
> 2 votes
# , 19 bytes

```
20*1+(<.@%~0 i.~/:)

```

Try it online!

### How it works

```
 20*1+(<.@%~0 i.~/:)
                  /:  ascending indices for sorting
             0 i.~    find your name
           %~         divided by interviewers
        <.@           and floored
  20*1+               +1 then *20

```

# Answer
> 2 votes
# 05AB1E , 16 bytes

```
R`©¸«{®QsôOƶ20*O

```

Explentation:

```
R`©¸«{®QsôOƶ20*O
R                    Reverse input
 `                   Push input to stack seperatly
  ©                  Store your name in register C
   ¸                 Listify
    «                Merge lists (add your name to the list of names)
     {               Sort
      ®              Push your name
       Q             For each element; is it equal to your name?
        s            Swap (n on top)
         ô           Split list of names into n chunks
          O          Sum each element
           ƶ         Lift a, multiplying each element by its index
            20*      Multiply by 20
               O     Sum for the result

```

Try it online!

# Answer
> 2 votes
# APL (Dyalog Unicode), 11 bytes

```
20×⌈⎕÷⍨⊃⍋⍋⎕

```

Try it online!

Full program that takes the names and the value of n from stdin.

### How it works

```
20×⌈⎕÷⍨⊃⍋⍋⎕
          ⎕  ⍝ Take first input (names)
        ⍋⍋   ⍝ Rank the names alphabetically; A E C B D → 1 5 3 2 4
       ⊃     ⍝ Extract the first number
   ⌈⎕÷⍨      ⍝ Take second input (n), divide above by n, and ceiling it
20×          ⍝ Multiply 20

```

# Answer
> 1 votes
# Scala, ~~29~~ 23 bytes

*Saved 1 byte thanks to Rahul Verma*

```
y=>_.count(_<y)/_*20+20

```

Try it online!

Accepts `(y)(a, n)`. `y` is a `String` representing your name, `a` is a `List[String]` with your ~~competitors'~~ "friends'" names, and `n` is an `Int` representing the number of interviewers. The function is pretty straightfoward - it just finds how many friends will go before you (plus 1 because you're going to go too), divides that by `n` (rounding up), and multiplies by 20 to get the total time.

# Answer
> 1 votes
# Charcoal, 13 bytes

```
Ｉ×²⁰⊕÷ΣＥη‹ιθζ

```

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

```
        η       Second input (array of friends)
       Ｅ        Map over array
          ι     Current friend
         ‹      Alphabetically precedes
           θ    First input (your name)
      Σ         Take the sum
     ÷          Integer divided by
            ζ   Number of simultaneous interviews
    ⊕           Incremented
 ×              Multiplied by
  ²⁰            Literal `20`
Ｉ               Cast to string
                Implicitly print

```

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

```
l;f(p,n)char**p;{for(l=0;p[++l]&&strcmp(*p,p[l])>0;);n=20+--l/n*20;}

```

Try it online!

# Answer
> 1 votes
# Java (JDK), 54 bytes

```
(m,l,q)->l.filter(x->x.compareTo(m)<0).count()/q*20+20

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 10 bytes

```
ª{¹kI÷>20*

```

Try it online or verify all test cases.

**Explanation:**

```
ª           # Add the first (implicit) input-string to the (implicit) input-list
 {          # Sort the list alphabetically
  ¹k        # Get the 0-based index of the first input in the sorted list
    I÷      # Integer-divide it by the input-integer
      >     # Increase it by 1
       20*  # And multiply it by 20
            # (after which the result is output implicitly)

```

# Answer
> 0 votes
# Wolfram Language (Mathematica), 35 bytes

```
20⌈{#}~Union~#2~Position~#/#3⌉&

```

Try it online! Pure function. Takes the three arguments in order and returns `{{x}}`, where `x` is the desired number of minutes.

# Answer
> 0 votes
# MathGolf, 9 bytes

```
èsl=j/üI*

```

Inputs in the order and format `"myName" numberOfInterviewers "an","Array","Of","Friends"`.
Assumes the names only contains letters. Will delete and fix it if they can contain digits as well.

Try it online.

**Explanation:**

```
è         # Push all inputs as single string array
          #  i.e. "Oggy" 10 "Jack","DeeDee","Marky","Bob"
          #   → ['Oggy','10','Jack','DeeDee','Marky','Bob']
 s        # Sort this array alphabetically
          #  → ['10','Bob','DeeDee','Jack','Marky','Oggy']
  l       # Push the first input as string
          #  → ['10','Bob','DeeDee','Jack','Marky','Oggy'] and 'Oggy'
   =      # Get its 0-based index in the array
          #  → 5
    j     # Push the second input as float
          #  → 5 and 10.0
     /    # Divide the index by this float
          #  → 0.5
      ü   # Ceil it to an integer
          #  → 1
       I* # Multiply it by 20
          #  → 20
          # (after which the entire stack joined together is output implicitly as result)

```

---
Tags: code-golf, sorting
---