title: Output with the same length always

text:
# Question
Title: Output with the same length always
With challenges like Output with the same length as the code and Create output twice the length of the code, I thought of a separate, but similar challenge.

The task is to produce an output. It can either be a string, a list of characters, or whatever is the default output format of your program. However, your output must always be the same length, regardless of the input. And more importantly, **the output should be different for different inputs**.

## Input

A single integer \\$n\\$, the ranges of which is determined by the choice of language. If your language has variable length integers, the range is \\$-2^{31} \leq n \< 2^{31}\\$.

## Output

A string or a list of characters, or a print to STDOUT or STDERR. You may only use one of these methods. The output should be of the same length regardless of the input, but it is up to you to define which length that is. **The output may not contain the digit characters `0-9`, or the minus sign `-`**. **The output should be deterministic**.

You should be able to prove that **for every output there is only one possible input**, either by a formal proof, an argument, or a brute-force search.

This is a code golf question, so shave off any extraneous bytes. All languages are welcome, the more the better!

# Answer
# JavaScript (ES8), 33 bytes

Expects the input in the range of safe JS integers: \\$-2^{53}\le n \< 2^{53}\\$.

Returns a string of 76 characters.

```
n=>btoa(n.toString(2)).padEnd(76)

```

Try it online!

## How?

### Step 1

The input is first converted to binary. This preserves the leading minus sign for negative numbers.

Examples:

* `123``"1111011"`
* `-77``"-1001101"`

### Step 2

The resulting string is encoded in base-64.

It means that each block of 1 to 3 characters will be turned into a new block of 4 characters. This conversion is safe because none of the resulting blocks contain the forbidden symbols (digits or minus sign).

**3-character blocks**

```
"-10" -> "LTEw" | "011" -> "MDEx"
"-11" -> "LTEx" | "100" -> "MTAw"
"000" -> "MDAw" | "101" -> "MTAx"
"001" -> "MDAx" | "110" -> "MTEw"
"010" -> "MDEw" | "111" -> "MTEx"

```

A single final block of 1 or 2 characters has to be encoded if the length of the binary string is not a multiple of 3:

**1-character blocks**

```
"0"   -> "MA==" | "1"   -> "MQ=="

```

**2-character blocks**

```
"-1"  -> "LTE=" | "10"  -> "MTA="
"00"  -> "MDA=" | "11"  -> "MTE="
"01"  -> "MDE=" |

```

### Step 3

The final output is padded with trailing spaces.
> 16 votes

# Answer
# Python 3, ~~49~~ 39 bytes

```
lambda i:[chr(ord(x)*2)for x in"%9x"%i]

```

Try it online!

*-10 bytes thanks to negative seven*

Converts the integer to hexadecimal, and prepends spaces up to 9 characters total. Then, doubles the ASCII code of each character in the string (some extend outside of ASCII into Unicode, but Python handles it fine), outputting a list of characters.

This works because every digit, including `-`, is mapped to a different ASCII character. No integers between `-2147483648` and `2147483648` are equal, so converting them to hexadecimal and prepending spaces would not make them equal. Then, mapping them to different codepoints does not lead to collisions, so there are still no two values in the range which lead to equal outputs.

# Python 3, ~~59~~ ~~56~~ 47 bytes

```
lambda i:[*map(lambda x:chr(ord(x)*2),"%9x"%i)]

```

Try it online!

*-3 bytes thanks to Jitse*

*-9 bytes thanks to negative seven*

Same algorithm, but using `map` instead of a `for` loop.
> 11 votes

# Answer
# 05AB1E, ~~11~~ 5 bytes

```
тjÇ·ç

```

-6 bytes porting *@Stephen*'s approach, so make sure to upvote him!

Outputs a list of up to 100 characters, with \\$100-(\text{input length})\\$ amount of `@` (double the space codepoint), and all `-0123456789` mapped to `Z`bdfhjlnpr` (double the ASCII codepoints).

Try it online.

**Explanation:**

```
 j     # Prepend spaces in front of the (implicit) input-integer to make it of length:
т      # 100
  Ç    # Convert each character to its unicode value
   ·   # Double each
    ç  # And convert it back to a character
       # (after which the resulting list is output implicitly)

```

---

**Original 11 bytes answer:**

```
Ä¶×AIdè«žIj

```

Try it online (limited to `1000` instead of `2147483648`).

**Explanation:**

The output length is always 2,147,483,648 characters long. It will output \\$2147483648-|n|-1\\$ amount of spaces, appended with \\$|n|\\$ amount of newlines, appended with either an 'a' if \\$n\lt0\\$ or 'b' if \\$n\geq0\\$.

```
Ä            # Get the absolute value of the (implicit) input-integer
 ¶×          # And have a string with that many newline characters
   A         # Push the lowercase alphabet
    Id       # Check if the input is non-negative (>=0) (1 if truthy; 0 if falsey)
      è      # Use that to index into the alphabet (so "a" for <0 and "b" for >=0)
       «     # Append that to the newline-string we created earlier
          j  # And prepend spaces to make the string of a length:
        žI   # 2147483648 (this has been replaced with `₄`/1000 in the TIO)
             # (after which the result is output implicitly)

```
> 9 votes

# Answer
# brainfuck, ~~48~~ ~~29~~ ~~28~~ ~~16~~ 13 bytes

This program requires cells, where \\$ c\_n \in \mathbb{N} \\$, but if you want consistent results, make sure that \\$ c\_n \< 256 \\$

Output will obviously be unique no matter what number will you enter (\\$ -\infty \lt n \lt \infty \\$). If the integer is shorter, the program will pad out the output to match exactly \\$ \infty \\$ bytes, so the length is always the same.

This answer is a bit loopholing the challenge, as it didn't state that output has to be finite.

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

```

Try it online!

---

Original, 28 byte answer:

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

```

This one will pad the output to be exactly \\$ 2^8 - 1 \\$ bytes. The number conversion mechanism works the same here. This program assumes the same as the program above.
> 8 votes

# Answer
# Python 3, 39 bytes

```
lambda n:f"{n:33b}".translate("abc"*99)

```

Try it online!

Turns the given number into a binary string representation (padded with spaces), then maps the characters `(space)-01` to `caab` with the `str.translate` function.
> 5 votes

# Answer
# Ruby, 27 bytes

```
->n{('%34b'%n).tr'01','ah'}

```

Try it online!

`('%34b'%n)` Converts an integer into its binary representation, using `..1` to indicate a negative number (this is meant to represent an infinitely-long prefix of 1s), and left-pads this out to 34 characters using spaces. Then we replace the `0`s with 'a' and the `1`s with 'h' to create the Maniacal Base 2 Representation: strings like "haaahahahaaha" prepended with spaces and sometimes `..`. Since every step here is invertible this is 1:1.

Edit: Let the record show that @manatwork posted this identical solution first. Oops. I should've refreshed.
> 5 votes

# Answer
# Jelly, 4 bytes

```
œ?ØẠ

```

A monadic Link accepting an integer which yields a list of 52 characters.

The input range may be up to somewhat more than \\$-2^{223} \leq n \lt 2^{223}\\$ since \\$52!\>2^{224}\\$.

**Try it online!**

### How?

```
œ?ØẠ - Link: integer, n
  ØẠ - alphabet (Jelly's longest built-in character list containing no digits
     -           or hyphen) = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
œ?   - permutation at index (n) if all 52! permutations were written out
     - in lexicographical order.
     - This indexing is modular so when n = -x we fetch the (52!-x)th entry.

```

So...

```
-2147483648 zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONIGCDAMLJKFEHB
-2147483647 zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONIGCDAMLJKFHBE
-2147483646 zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONIGCDAMLJKFHEB
-2147483645 zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONIGCDAMLJKHBEF
    ...
         -4 zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDACB
         -3 zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDBAC
         -2 zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDBCA
         -1 zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCAB
          0 zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA
          1 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
          2 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxzy
          3 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwyxz
          4 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwyzx
    ...
 2147483644 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmrtxwznoqpsvyu
 2147483645 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmrtxwznoqpsyuv
 2147483646 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmrtxwznoqpsyvu
 2147483647 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmrtxwznoqpusvy

```
> 5 votes

# Answer
# C (gcc), 38 bytes

```
f(a,i){for(i=32;i--;putchar(a>>i&1));}

```

Try it online!

This expands each bit of the input integer into a byte that is either 0 or 1 (which are both unprintable characters, but there is no rule against that). So the output is always 32 bytes, and guaranteed to be unique.
> 5 votes

# Answer
## Haskell, 31 bytes

```
map(\d->[d..]!!10).show.(+2^60)

```

Try it online!

Adds `2^60` to the input so that the resulting number has the same amount of digits for the whole input range. Turn into a string and shift each character 10 places to the right in the ASCII order (`0` -\> `:` ... `9` -\> `C`).
> 4 votes

# Answer
# Jelly, 6 bytes

```
Ø%+ṃØA

```

Try it online!

Since Jelly has arbitrary length integers, this monadic link takes an integer in the range \\$±2^{31}\\$ and returns a length 7 alphabetic string. It works by adding \\$2^{32}\\$ and then base decompressing into the capital letters.
> 4 votes

# Answer
# C# (Visual C# Interactive Compiler), 35 bytes

```
x=>$"{x,11}".Select(n=>(char)(n+n))

```

Try it online!
> 4 votes

# Answer
# Perl 5 `-MDigest::MD5=md5_hex -p`, 23 bytes

```
$_=md5_hex$_;y/0-9/k-t/

```

Try it online!

Previously:

### Perl 5 `-p`, 29 bytes

```
$_=sprintf'%064b',$_;y/01/ab/

```

Try it online!

Converts the number to its 64 bit binary representation, then transliterates `0` and `1` to `a` and `b`, respectively.
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), 52 bytes

```
x=>(new char[32]).Select(y=>(char)(x%2+65+(x/=2)*0))

```

Try it online!

Different approach to a c# solution, takes advantage of the fact that c# modulus is negative for negative numbers. I suppose you could shave off a byte or two if you allow non-display characters ('\0', and so on) by updating the `+65...` to not offset the character value to something human readable.
> 3 votes

# Answer
# T-SQL, ~~73 70~~ 61 bytes

```
SELECT TRANSLATE(STR(n,11),'-0123456789','ABCDEFGHIJK')FROM t

```

I'm just directly replacing the digits (and `-`) with letters, after `STR` pads the integer to 11 characters. No conversion to hex or binary is necessary.

`TRANSLATE` was introduced in SQL 2017.

Input is via a pre-existing table \\$t\\$ with INT column \\$n\\$, per our IO rules. Range of the `INT` datatype in SQL is \\$-2^{31} \leq n \< 2^{31}\\$.

**EDIT**: Saved 3 bytes by replacing manual padding with a conversion to CHAR(11), which is a fixed-width character format that automatically pads with spaces.

**EDIT 2**: Saved *9 bytes* by using `STR()` function instead of `CAST`. `STR` converts a number to a text string padded to the specified length.
> 2 votes

# Answer
# APL (Dyalog Unicode), 28 bytes

```
{11↑' Z'[⍵≤0],⎕A[⍎¨'¯'~⍨⍕⍵]}

```

Try it online!

Simple Dfn, taking an integer argument. Uses `⎕IO←0`.

TIO links to a test case from `-2^10` to `2^10`. The `0~⍨` part removes the duplicate `0` from the arguments.

### How:

```
{11↑' Z'[⍵≤0],⎕A[⍎¨'¯'~⍨⍕⍵]} ⍝ Dfn
              ⎕A[         ]  ⍝ Index the Uppercase Alphabet with
                        ⍕⍵   ⍝ String representation of the argument
                   '¯'~⍨     ⍝ Without the character ¯
                 ⍎¨          ⍝ Executing each digit back into integers
             ,               ⍝ Prepend
    ' Z'[   ]                ⍝ A character from the string ' Z' indexed by
         ⍵≤0                 ⍝ Argument ≤ 0. Returns 1 if true, else 0.
                             ⍝ This will prepend a whitespace to positive numbers, and a Z otherwise.
 11↑                         ⍝ Take the first 11 characters, padding with whitespace.

```
> 2 votes

# Answer
# Japt, 6 bytes

I *think* this is right. Inspired by Stephen's Python solution so please `+1` him.

```
¤ùI cÑ

```

Try it

```
¤ùI cÑ     :Implicit input of integer
¤          :Convert to binary string
 ù         :Left pad with spaces
  I        :  To length 64
    c      :Map codepoints
     Ñ     :  Multiply by 2

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~44~~ 33 bytes

```
Echo@Table[Or[i>#+13!,],{i,14!}]&

```

Try it with a smaller domain

-2 thanks to Greg Martin

Prints `>>` , followed by the 523069747202-character string representation of a list of \\$13!+n\\$ `Null`s padded by `True`s to a length of \\$14!\\$, and a newline. Works on the domain \\$\[-13!,14!-13!)\\$, which is a superset of \\$\[-2^{31},2^{31})\\$.

Given the size of the output, I've included a test case with a smaller domain of \\$\[-2^4,2^4)\\$ instead
> 2 votes

# Answer
# Malbolge, 2708 bytes

This answer is super cheaty, because it always produces the same amount of input, which is equal to \\$ \infty \\$.

```
bP&A@?>=<;:9876543210/.-,+*)('&%$T"!~}|;]yxwvutslUSRQ.yx+i)J9edFb4`_^]\yxwRQ)(TSRQ]m!G0KJIyxFvDa%_@?"=<5:98765.-2+*/.-,+*)('&%$#"!~}|utyrqvutsrqjonmPkjihgfedc\DDYAA\>>Y;;V886L5322G//D,,G))>&&A##!7~5:{y7xvuu,10/.-,+*)('&%$#"yb}|{zyxwvutmVqSohmOOjihafeHcEa`YAA\[ZYRW:U7SLKP3NMLK-I,GFED&%%@?>=6;|9y70/4u210/o-n+k)"!gg$#"!x}`{zyxZvYtsrqSoRmlkjLhKfedcEaD_^]\>Z=XWVU7S6QPON0LKDI,GFEDCBA#?"=};438y6543s1r/o-&%*k('&%e#d!~}|^z]xwvuWsVqponPlOjihgIeHcba`B^A\[ZY;W:UTSR4PI2MLKJ,,AFE(&B;:?"~<}{zz165v3s+*/pn,mk)jh&ge#db~a_{^\xwvoXsrqpRnmfkjMKg`_GG\aDB^A?[><X;9U86R53ONM0KJC,+FEDC&A@?!!6||3876w4-tr*/.-&+*)('&%$e"!~}|utyxwvutWlkponmlOjchg`edGba`_XW\?ZYRQVOT7RQPINML/JIHAFEDC&A@?>!<;{98yw5.-ss*/pn,+lj(!~ff{"ca}`^z][wZXtWUqTRnQOkNLhgfIdcFaZ_^A\[Z<XW:U8SRQPOHML/JIHG*ED=%%:?>=~;:{876w43210/(-,+*)('h%$d"ca}|_z\rqYYnsVTpoRPledLLafIGcbE`BXW??TY<:V97S64P31M0.J-+G*(DCB%@?"=<;|98765.3210p.-n+$)i'h%${"!~}|{zyxwvuXVlkpSQmlOjLbafIGcbE`BXW??TY<:V97S64P31M0.J-+G*(D'%A@?"=<}:98y6543,1r/.o,+*)j'&%eez!~a|^tsx[YutWUqjinQOkjMhJ`_dGEaDB^A?[><X;9U86R53O20LKJ-HG*ED'BA@?>7~;:{y7x5.3210q.-n+*)jh&%$#"c~}`{z]rwvutWrkpohmPkjihafI^cba`_^A\[>YXW:UTS5QP3NM0KJ-HGF?D'BA:?>=~;:z8765v32s0/.-nl$#(ig%fd"ca}|_]yrqvYWsVTpSQmPNjMKgJHdGEa`_B]\?ZY<WVUTMR5PO20LK.IHA))>CB%#?87}}49zx6wu3tr0qo-nl*ki'hf$ec!~}`{^yxwvotsrUponQlkMihKIe^]EEZ_B@\?=Y<:V97S64P31M0.J-+GFE(C&A@?8=<;:{876w43s10qo-&%kk"'hf$ec!b`|_]y\ZvYWsVTpSQmlkNiLgf_dcba`C^]\?ZY;WV97SLK33HM0.J-+G*(D'%A$">!};|z8yw543t1r/(-,+*)(i&%fd"!~}|_t]xwvutslqTonmPkjLhKIeHFbEC_^A?[TSX;9UT7R4JIN1/K.,H+)E(&B%#?"~<}{987x/4ussr)p-,m*)ihh}$#d!awv{^\x[YuXVrUSonQlNdchKIeHFbaD_AWV[><X;988MRQ4O1GFK.,++@ED'B$:9>!};:9zy0wuut1*/p-,mk#"hh}$#"cb}v{^\\[vunWrqTonmOkjMLgf_HcbE`_A]@>ZY<:VONS64P31M0.J-+G*(D'%A$">!}||3876wv321*/p-,mk#"'hf$ec!b`|{^y[qpuXVUUjonQOkdchKIeHFbEC_B@\?=Y<:VUT76QPONG0KJ-HGFED'%A:9!!6;:9zy654321*q.-n+*j(ig%fd"ca}`^]]rwvYtVlkpSQmPNMMbgfIdF\[`_^A@[ZYXWVUNS6443NMLKJIHG@)DC&A@?!=<}|98765432+r/.-,+k#('&%e{dy~}|uzsx[vuXsrqpoRPledLLafedGF[`C^]\?ZY;W:8T7544INM0.JCBG*(''<A@#!=65:{yxx/43tr0)(-nlkk"'&ge#zy~a_^^sxwZXtmlqTRQQfkjMKg`_dcbEZ_B]\?=SRW:8T75Q42N1/KJ-+G@?D'%A$">!};|z87x5u-,1rp.-n+k#"'hfeez!~}`_t]xwvYtsUTTinmPNjcbgJHdGEa`_BW\?ZY<WVUTS64PIH00EJIH+*?(&&;@#!!~5:{87xv.-2sq/.om+$#(ig%$e"bxw|_]y\ZvuXsUkjoRPOOdihKfH^]bEC_^A\>TS;;PUTS65JO2MLK.,BA))>CBA$9>!}}|3z765v32r0/p-m%$)jh&ge#"c~`vuz][ZZotsVqSihmPNMMbgfIdF\[`CA@@UZY<W9ONS6433HML/J,BAF)'&&;@?"=}549zx6wutt+0/.on%l)('h%$d"ca}`^z][wvYtVlkpSQmPNjiLJf_^cFDCCX]\?=YRQV9766KPO20LEDI,*))>CB%#?87<}{9zx6wu3tr0/.o&m*)('&%fA/cQ>_^;]87%54"32pRA-yejih:s_GGFDDC^{i[T<XQ9b8r_5]O20Li-zB*SdQPO%##]nml43V1TvS@cs0/_'JJH#jhg%BTd!xw_{t99J6$tV21SBR@?kjcbtJ%^F"DD21]@[xfw;)9Nqq5Jmm~LKWVyx@E't&%:]][~YkF8hgv.tssOMp:&ml6Fi&D1T"y?,O<^s\7vX#Wr2}|Rzl+j<bK`r$F"4ZCk|\?-=RQ

```

Try it online!
> 2 votes

# Answer
# Perl 6, 12 bytes

```
*~|('@'x 11)

```

Try it online!

Anonymous Whatever lambda that takes a number and string ORs it with 11 `@`s. This maps the digits to `pqrstuvwxy` and the dash to `m`, then pads the string out to 11 characters with `@`s
> 2 votes

# Answer
# Perl 5 (-p), 9 bytes

```
$_^=A x$=

```

Try it online!

Bitwxise-xor of the input with the string `AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`.
> 2 votes

# Answer
# PHP, ~~64~~ 54 bytes

-10 bytes by using `strtr` function instead of manual character replacement.

```
<?=str_pad(strtr($argn,'-0123456789',ADEFGHIJKLM),20);

```

Try it online!

Largest int value possible in PHP as of now is `9223372036854775807` which is 19 digits long, considering the minus sign in negative numbers, it will be 20. The code above replaces minus sign (`-`) with the `A` character and every digit from `0` to `9` with a character from `D` to `M` and then pads the string in the right with space character to always make it 20 characters long. For example, the output for input of `-9876543210` is `"AMLKJIHGFED "`.

The output is unique for each integer input and you can get back to the input by removing all spaces, replacing `A` with `-` and replacing `D` to `M` with `0` to `9`.

---

# PHP, 44 bytes

```
<?=str_pad(base64_encode(decbin($argn)),88);

```

Try it online!

This is same idea as **Arnauld's answer**. Converts the input to binary, and then converts it to base-64. Also pads it to 88 characters (largest length is for `-9223372036854775807` which is 88 characters) with space character at right to always get same length in the output.
> 1 votes

# Answer
# Stax, 6 bytes

```
11){Hm

```

Run and debug it

**Procedure:**

1. Left pad input to 11 characters.
2. Double each non-space ascii character.
> 1 votes

# Answer
# Zsh, 43 bytes

```
for c (${(s::)${(l:30::0:)1}})echo \\x$[#c]

```

---

```
               ${(l:30:0:)1}                 # left-pad with zeroes to 30 characters
        ${(s::)             }                # split characterwise
 for c (                     )               # for each character
                                      $[#c]  # get character code (in decimal)
                              echo \\x$[#c]  # interpret as hex code, print (with newline)

```

Try it online!

This solution gets around the `long long` limits of Zsh's integers by working with only characters. I only padded it to 30 characters for readability, but replacing `30` with `99` will allow this method to work on all numbers from `-1E99+1` to `1E100-1`.

The effect of interpreting the decimal codes as hexadecimal are as follows:

```
0 => 48 => H    1 => 49 => I    2 => 50 => P    3 => 51 => Q
4 => 52 => R    5 => 53 => S    6 => 54 => T    7 => 55 => U
8 => 56 => V    9 => 57 => W    - => 45 => E

```

# Zsh, 46 bytes

```
integer -i2 -Z66 x=$1
<<<${${x//[02-]/a}//1/b}

```

Try it online!

Declares x as a binary number, zero-padded to a width of 66. Then maps `0``a` and `1``b`. We also map `2` and `-` to a, since those characters are printed in `[[-]][base]#[num]` notation. To see what `$x` looks like before replacement, and Zsh's limits in parsing integer types, check the Debug output in the TIO link.
> 1 votes

# Answer
# Retina 0.8.2, 21 bytes

```
T`p`l
$
10$*o
!`.{11}

```

Try it online! Always outputs 11 characters from the range `n`..`z`. Explanation:

```
T`p`l

```

Translate the printable ASCII characters to the lowercase letters. This maps `-` to `n` and `0`..`9` to `q`..`z`. (It's really fortunate that the digits are the 16th to the 25th printable ASCII characters!)

```
$
10$*o

```

Append 10 `o`s. Since the input will have between 1 and 11 characters, there are now between 11 and 21 characters.

```
!`.{11}

```

Extract the first 11 characters. Since there are fewer than 22 characters, this will only match once.
> 1 votes

# Answer
# Charcoal, 9 bytes

```
◧⍘﹪ＮＸχχαχ

```

Try it online! Link is to verbose version of code. Always outputs 10 spaces and uppercase letters. Explanation:

```
   Ｎ        Input as a number
  ﹪         Modulo
     χ      10
    Ｘ       To power
      χ     10
 ⍘     α    Convert to base 26 using uppercase letters
◧       χ   Left pad to length 10

```
> 1 votes

# Answer
# brainfuck, ~~20~~ 19 bytes

*-1 byte thanks to Krzysztof Szewczyk*

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

```

Try it online!

Outputs the number with each digit and dash mapped to 255 minus their ordinal value, padded out to 255 characters with NUL bytes.
> 1 votes

# Answer
# , 37 bytes

```
set.seed(scan())
cat(sample(LETTERS))

```

Try it online!

Looks like the output is random, but it isn't! The input is used as the seed of the Pseudo-Random Number Generator, and we then get one of the \\$26!=4\cdot 10^{26}\\$ permutations of the alphabet. The output is always of length 51 (26 letters + 25 spaces).

There is still the issue of insuring that all the outputs are different. We end up with \\$2^{32}\approx 4\cdot 10^9\\$ permutations (out of \\$4\cdot 10^{26}\\$). If we pretend that the permutations are distributed uniformly at random, then the probability that all the permutations are different can be computed following the same calculations as for the Birthday problem. The probability that 2 specific outputs are identical is \\$10^{-17}\\$, so a first order approximation of the probability that all \\$2^{32}\\$ outputs are distinct is

\\$1-\exp(-2^{64}/26!)\approx0.99999998\\$

which is close enough to 1 for me.
> 1 votes

# Answer
# , ~~40~~ 37 bytes

```
cat(gsub("S","",intToBits(scan())>0))

```

Try it online!

An alternative to Robin Ryder's answer; this is certainly deterministic.

This converts the input to a `raw` vector of 32 bytes, each byte being a hex number `00` or `01` representing the bits of the integer. We then coerce to a `logical` by comparing to `0`, so `00` is mapped to `FALSE` and `01` to `TRUE`. Then we need to remove a single letter from each `FALSE` to guarantee equal-length output, arbitrarily selected to be `S`. Result is printed (with space) for a length of 169.
> 1 votes

# Answer
# Java (JDK), 42 bytes

```
n->"".format("%8x",n).chars().map(i->i|64)

```

Try it online!

First, this creates the hexadecimal representation of the input, left-padded with spaces which provides the same length constraint (8 characters-long), removes the minus sign, and keeps each intermediate output unique.

This gives a string with 17 different possible characters: `0123456789abcdef` and space.

Then each character is streamed and mapped by adding 64 to its codepoint if it's a digit or a space. Effectively, this results in the following mapping: `0123456789abcdef<space>` to `pqrstuvwxyabcdef`` which has 17 different characters, so no two numbers will result in the same output.
> 1 votes

# Answer
# Bash, 30 bytes

```
echo $1|md5sum|tr '0-9-' 'A-K'

```

Try it online!

To prove that output is unique, I just googled for MD5 collisions, and found no results within the integers between \\$-2^{31}\\$ and \\$2^{31}\\$. To avoid having forbidden characters in the output, just translate the characters in question to be upper case letters. Output is always the same length by definition, and guaranteed to not contain any forbidden characters.
> 1 votes

---
Tags: code-golf, string, integer, hashing
---


title: Output Distinct Factor Cuboids

text:
# Question
Title: Output Distinct Factor Cuboids
# Output Distinct Factor Cuboids

Today's task is very simple: given a positive integer, output a representative of each cuboid formable by its factors.

## Explanations

A cuboid's volume is the product of its three side lengths. For example, a cuboid of volume 4 whose side lengths are integers can have sides `[1, 1, 4]`, `[1, 2, 2]`, `[1, 4, 1]`, `[2, 1, 2]`, `[2, 2, 1]`, or `[4, 1, 1]`. However, some of these represent the same cuboid: e.g. `[1, 1, 4]` and `[4, 1, 1]` are the same cuboid rotated. There are only two distinct cuboids with volume 4 and integer sides: `[1, 1, 4]` and `[1, 2, 2]`. The output can be any representation of the first cuboid, and any representation of the second cuboid.

## Input

Your program must take a single positive integer \\$1 \le n \le 2^{31}−1\\$.

## Output

You will need to output all possible cuboids in a list or any other acceptable way. E.g.

```
Input  Output
  1    [[1, 1, 1]]
  2    [[1, 1, 2]]
  3    [[1, 1, 3]]
  4    [[1, 1, 4], [1, 2, 2]]
  8    [[1, 1, 8], [1, 2, 4], [2, 2, 2]]
 12    [[1, 1, 12], [1, 2, 6], [1, 3, 4], [2, 2, 3]]
 13    [[1, 1, 13]]
 15    [[1, 1, 15], [1, 3, 5]]
 18    [[1, 1, 18], [1, 2, 9], [1, 3, 6], [2, 3, 3]]
 23    [[1, 1, 23]]
 27    [[1, 1, 27], [1, 3, 9], [3, 3, 3]]
 32    [[1, 1, 32], [1, 2, 16], [1, 4, 8], [2, 2, 8], [2, 4, 4]]
 36    [[1, 1, 36], [1, 2, 18], [1, 3, 12],[1, 4, 9], [1, 6, 6], [2, 2, 9], [2, 3, 6], [3, 3, 4]]

```

Sub-lists don't need to be sorted, just as long as they are unique.

## Scoring

This is code golf, so shortest answer in bytes wins. Standard loopholes are forbidden.

*Here is a test case generator*

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=192852;
var OVERRIDE_USER=8478;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```

```
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```

# Answer
> 4 votes
# Jelly, 7 bytes

```
œċ3P⁼¥Ƈ

```

A monadic Link accepting a positive integer which yields a list of 3-lists of positive integers.

**Try it online!**

### How?

```
œċ3P⁼¥Ƈ - Link: positive integer, N
  3     - literal three
œċ      - all combinations (of [1..N]) of length (3) with replacement
           i.e. [[1,1,1],[1,1,2],...,[1,1,N],[1,2,2],[1,2,3],...,[1,2,N],...,[N,N,N]]
      Ƈ - filter keep those for which:
     ¥  -   last two links as a dyad:
   P    -     product
    ⁼   -     equals (N)?

```

# Answer
> 5 votes
# JavaScript (V8),  ~~61~~  60 bytes

Prints the cuboids to STDOUT.

```
n=>{for(z=n;y=z;z--)for(;(x=n/y/z)<=y;y--)x%1||print(x,y,z)}

```

Try it online!

### Commented

```
n => {                // n = input
  for(                // outer loop:
    z = n;            //   start with z = n
    y = z;            //   set y to z; stop if we've reached 0
    z--               //   decrement z after each iteration
  )                   //
    for(              //   inner loop:
      ;               //     no initialization code
      (x = n / y / z) //     set x to n / y / z
      <= y;           //     stop if x > y
      y--             //     decrement y after each iteration
    )                 //
      x % 1 ||        //     unless x is not an integer,
      print(x, y, z)  //     print the cuboid (x, y, z)
}                     //

```

# Answer
> 5 votes
# Haskell, 52 bytes

```
f n=[[a,b,c]|a<-[1..n],b<-[1..a],c<-[1..b],a*b*c==n]

```

Try it online!

Tuples are in descending order. "3" seems to be a small-enough number that writing out the 3 loops was shorter than anything general I could come up with.

# Answer
> 5 votes
# Python 3.8 (pre-release),  ~~83~~  80 bytes

```
lambda n:[[i,j,k]for i in(r:=range(n+1))for j in r[i:]for k in r[j:]if i*j*k==n]

```

**Try it online!**

---

...beating a two-loop version by three bytes:

```
lambda n:[[i,j,n//i//j]for i in(r:=range(1,n+1))for j in r if(i<=j<=n/i/j)>n%(i*j)]

```

# Answer
> 4 votes
# Jelly, 11 bytes

```
ÆDṗ3Ṣ€QP=¥Ƈ

```

Try it online!

A monadic link taking an integer as its argument and returning a list of lists of integers.

## Explanation

```
ÆD          | Divisors
  ṗ3        | Cartesian power of 3
    Ṣ€      | Sort each list
      Q     | Unique
         ¥Ƈ | Keep only where the following is true (as a dyad, using the original argument as right argument)
       P    | - Product
        =   | - Is equal (to original argument)

```

# Answer
> 2 votes
# Haskell, ~~67 60~~ 59 bytes

For a given \\$n\\$, this produces all 3-tuples of with entries in \\$\\{1,2,\ldots,n\\}\\$ and filters out the valid ones. To guarantee uniqueness we require that the tuples are sorted.

```
f n=[x|x@[a,b,c]<-mapM id$[1..n]<$":-)",a*b*c==n,a<=b,b<=c]

```

Try it online!

# Answer
> 2 votes
# Retina, 59 bytes

```
.+
*
2+%L$`(?<=(_+))(?=(\1)*$)
$` _$#2*
A`_(_+) \1\b
_+
$.&

```

Try it online! Link includes test suite. Explanation:

```
.+
*

```

Convert to unary.

```
2+%L$`(?<=(_+))(?=(\1)*$)
$` _$#2*

```

Repeating twice, divide the last number on each line into all of its possible pairs of factors. The lookbehind is greedy and atomic, so once it's matched the prefix of the last number it won't backtrack. This generates all possible permutations of three factors.

```
A`_(_+) \1\b

```

Delete lines where the factors are not in ascending order.

```
_+
$.&

```

Convert to decimal.

# Answer
> 2 votes
# C (clang), 89 bytes

```
a,b,x;f(n){for(a=n;a;a--)for(b=a;b&&(x=n/a/b)<=b;b--)x*b*a-n||printf("%d,%d,%d ",x,b,a);}

```

Try it online!

Port of @Arnauld

Saved 1 thanks to @Jonathan Frech better output format

# Answer
> 2 votes
# Pyth, 11 bytes

```
fqQ*FT.CSQ3

```

Try it online!

```
        SQ  #              range(1, Q+1)          # Q = input
      .C  3 # combinations(             , 3)
f           # filter(lambda T: vvv, ^^^)
 qQ         # Q ==
   *FT      #      fold(__operator_mul, T) ( = product of all elements)

```

# Answer
> 2 votes
# 05AB1E, 8 bytes

```
Ò3.ŒP€{ê

```

```
Ò               # prime factors of the input
 3.Œ            # all 3-element partitions
    P           # take the product of each inner list
     €{         # sort each inner list
       ê        # sort and uniquify the outer list

```

Try it online!

# Answer
> 1 votes
# Icon, 87 bytes

```
procedure f(n)
k:=[]
a:=1to n&b:=1to a&c:=1to b&a*b*c=n&k|||:=[[a,b,c]]&\z
return k
end

```

Try it online!

Close to Python :)

---
Tags: code-golf, math, number, permutations, factoring
---


title: Collapse the antistring

text:
# Question
Title: Collapse the antistring
In this challenge you will be given an alphabetic string as input. We will define the "anti-string" of a given input to be the string with the case of all the letters inverted. For example

```
AaBbbUy -> aAbBBuY

```

You should write a program that takes a string as input and searches for the longest contiguous substring whose anti-string is also a contiguous substring. The two substrings should not overlap.

As an example if you were given the string

```
f**AbbA**cGf**aBBa**gF
```

The bolded portions would be the longest string anti-string pair.

Your program should, once it has found the pair, collapse them into a single character each. It should do this by removing all but the first character of each substring. For example the string above

```
f**AbbA**cGf**aBBa**gF
```

would become

```
f**A**cGf**a**gF
```

Your program should then repeat the process until the longest string anti-string pair is a single character or shorter.

For example working with the same string the new longest pair after the collapse is

```
fAc**Gf**a**gF**
```

So we collapse the string again

```
fAc**G**a**g**
```

Now the string cannot be collapsed further so we should output it.

In the case of a tie between candidate pairs (example `AvaVA`) you may make either reduction (`AaA` or `AvV`, but not `Aa`).

This is so answers will be scored in bytes with fewer bytes being better.

## Test Cases

```
fAbbAcGfaBBagF  ->  fAcGag
AvaVA ->  AaA / AvV
QQQQQQQ -> QQQQQQQ
fAbbAcQQQQaBBacqqqqA -> fAbcQBcq
gaq -> gaq
fAbbAcGfaBBagFaBBa -> fcGaBBag

```

## Motivations

While this problem may seem arbitrary it is actually a problem I encountered while making code to process fundamental polygons. This process can be used to reduce a fundamental polygon to a smaller **n**-gon. After I tried it I thought it would make a nice little golf.

# Answer
# Perl, ~~64~~ 61 bytes

Includes `+1` for `p`

```
perl -pE 's/(.\K.{$%})(.*)(?=(.))(??{$1^$"x$%.$"})/$2$3/ while$%=--pos' <<< fAbbAcGfaBBagFaBBa

```
> 8 votes

# Answer
# JavaScript (ES6), 200 bytes

Uses arrays of characters for I/O.

```
f=a=>(m=M=C=>a.map((_,i)=>a.map((_,j)=>C(i,j-i+1))))(I=>M((i,j)=>a.slice(i,i+j).some((n,k)=>n[c='charCodeAt']()^(a[I+k]||'')[c]()^32)|I+j>i|j<m||(x=[i,I],m=j)))&&m-->1?f(a,x.map(p=>a.splice(p+1,m))):a

```

Try it online!
> 6 votes

# Answer
# C (gcc), ~~240~~ ~~238~~ ~~227~~ ~~225~~ ~~222~~ 216 bytes

* Saved two bytes; removed a stray variable definition.
* Saved ~~eleven~~ thirteen bytes; golfed `b|=S[p+m]!=S[q+m]+32-(S[q+m]>90)*64` to `b|=abs(S[p+m]-S[q+m])-32` to `b|=32-S[p+m]+S[q+m]&63`.
* Saved three bytes; golfed `for(...;...;p++)S[p+1]=S[p+L];` to `for(...;...;S[++p]=S[p+L]);`.
* Saved six bytes thanks to ceilingcat.

```
p,P,q,Q,l,L,b,m;f(char*S){for(p=0;S[p];p++)for(l=0;S[l+++p];)for(q=0;b=S[q+~-l];!b&p+l<=q&l>L?L=l,P=p,Q=q:0,q++)for(b=0,m=l;m--;)b|=32-S[p+m]+S[q+m]&63;for(;b-2;)for(p=b++?-~Q-L:P;S[p];S[++p]=S[L+p]);~-L?L=0,f(S):0;}

```

Try it online!
> 3 votes

# Answer
# Python 3, 189 181 bytes

Credit to Jonathan Frech for making it pure one-liner.

```
f=lambda s,x=set():any(u in s[j+i:]and(x.add(s[:j+1]+s[j+i:].replace(u,u[0],1))or 1)for i in range(len(s),1,-1)for j in range(len(s))for u in[s[j:j+i].swapcase()])and f(x.pop())or s

```

Try it online!

My own version, now obsolete (189 bytes):

```
x=set()
def f(s):
 while any(u in s[j+i:]and(x.add(s[:j+1]+s[j+i:].replace(u,u[0],1))or 1)for i in range(len(s),1,-1)for j in range(len(s))for u in[s[j:j+i].swapcase()]):s=x.pop()
 return s

```

Try it online!

`any()` to break out nested loops early, and `set()` for mutable global object usable in the comprehension. The rest is just the straightforward implementation of the requirements using `str.swapcase`.

# Python 2, 160 bytes

```
def f(s):
 for i in range(len(s),1,-1):
	for j in range(len(s)):
	 u=s[j:j+i].swapcase()
	 if u in s[j+i:]:return f(s[:j+1]+s[j+i:].replace(u,u[0],1))
 return s

```

Try it online!

Turns out that regular nested for loop with early breaking through `return` is way shorter than the "clever" trick with `any`.
> 3 votes

# Answer
# Retina, 119 bytes

```
.+
$&¶$&
T`Ll`lL`.*¶
/(.).*¶.*\1/^&0A`
¶&Lv$`(?<=(.)*)((.)(.)*).*¶(?>((?<-1>.)*.)(?<-4>.)*)(.*)\2
$5$6$3$'
N$`
$.&
}0G`

```

Try it online! Link includes test cases. Explanation:

```
.+
$&¶$&
T`Ll`lL`.*¶

```

Duplicate the input and flip the case of the first copy.

```
/(.).*¶.*\1/^&0A`

```

If there are no anti-strings at all then delete the flipped duplicate.

```
¶&Lv$`(?<=(.)*)((.)(.)*).*¶(?>((?<-1>.)*.)(?<-4>.)*)(.*)\2
$5$6$3$'

```

List all the possible collapsed anti-strings.

```
N$`
$.&
}0G`

```

Sort them in order of length, take the shortest (i.e. longest anti-string), and repeat until all the anti-strings have been collapsed.
> 3 votes

# Answer
# Python 2, 180 bytes

```
def f(s):
 L=len(s)
 for x,y in[(i,i+j)for j in range(L,1,-1)for i in range(L-j)]:
	t=s[x:y];T=t.swapcase()
	if T in s[y:]:return f(s.replace(t,t[0],1).replace(T,T[0],1))
 return s

```

Try it online!
> 0 votes

# Answer
# Stax, 30 bytes

```
î☼fúΩ§☺æ╒ºê@Ñ▀'╫Iqa{d]∟Sa5♦⌂─╚

```

Run and debug it

The corresponding ascii representation of the same program is this.

```
c%Dc:e{%orF..*:{_{32|^mY++_h.$1yh++R

```

It uses a regex approach. It repeatedly regex string replacement. It builds these from each contiguous substring of the current value. For instance for the input `fAbbAcGfaBBagF`, one of the substrings is `AbbA`, in which case the regex `AbbA(.*)aBBa` will be replaced with `A$1a`.

```
c                                       get number of characters
 %D                                     repeat rest of program that many times
   c:e                                  get all substrings
      {%or                              order substrings longest to shortest
          F                             for each substring, execute the rest
           ..*:{                        build the string "(.*)"
                _{32|^m                 current substring with case inverted
                       Y                save the inverted case in register y
                        ++              concatenate search regex together
                                            e.g. "aBc(.*)AbC"
                          _h            first character of substring
                            .$1         "$1"
                               yh       first character of inverted case
                                 ++     concatenate replacement regex together
                                            e.g. "a$1A"
                                   R    do regex replacement

```
> 0 votes

# Answer
# Wolfram Language (Mathematica), 148 bytes

```
#//.s_:>MinimalBy[StringReplaceList[s,a:(p_~~__)~~x___~~b:(q_~~__)/;(32==##&@@Abs[(t=ToCharacterCode)@a-t@b]):>p<>x<>q]/.{}->{s},StringLength][[1]]&

```

Try it online!
> 0 votes

# Answer
# Japt `-h`, 33 bytes

```
à ñÊÅÔ£=rX+"(.*)"+Xc^H ÈÎ+Y+XÎc^H

```

Try it

```
à ñÊÅÔ£=rX+"(.*)"+Xc^H ÈÎ+Y+XÎc^H     :Implicit input of string U
à                                     :Combinations
  ñ                                   :Sort by
   Ê                                  :  Length
    Å                                 :Remove first element (the empty string)
     Ô                                :Reverse
      £                               :Map each X
       =                              :  Reassign to U
        r                             :  Global replacement
         X+"(.*)"+                    :  Append "(.*)" to X and then append
                  Xc                  :    Charcodes of X
                    ^H                :    XORed with 32
                      È               :  Pass each match X, with captured group Y, through the following function
                       Î+Y+           :    Append Y to the first character of X and then append
                           XÎc^H      :      The charcode of the first character of X XORed with 32

```
> 0 votes

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


title: Inquiry answerer

text:
# Question
Title: Inquiry answerer
* Original: https://james-iry.blogspot.co.at/2009/05/brief-incomplete-and-mostly-wrong.html

> Alain Colmerauer designed the logic programming language Prolog. His goal was to create a programming language that is as intelligent as a two-year-old child. In order to prove that he had succeeded in his goal, he presented a Prolog program that answers "No" resourcefully for all inquiries.
> Ask me anything!
> ?-
* (Of course he didn't.) Your task is to create a program that is more intelligent than Alain Colmerauer's program. This does not have to be in Prolog.

## Specifics

* If input ends with `?` and has at least one `,`, return text from the last `,` until before the last `?`.
* Else, if input ends with `?` return `No`.
* Else, return `Yes`.

## Rules

* No standard loopholes.
* Input/output will be taken via our standard input/output methods.
* Your program has to take at least 1 inquiry.
* You should output the processed inquiry.
* The `Yes` and `No`'s are case-sensitive in the examples.
* You are guaranteed that if the input includes a `?`, the input will only have one `?` and it will always be the last character.
* The input will always be a phrase/sentence. This phrase/sentence will never only contain the characters `,` and `?`, e.g. `,`, `?`, and `,?` are not valid inputs. (Although submissions might implement it anyway, since the phrase/sentence is an empty string in these cases.)
* In addition, the input will never end with `,?`.
* If there is whitespace immediately after the last `,` or immediately before the `?`, they should be included in the output.

## Examples

```
Hmm. -> Yes
Alright, -> Yes
Ask me anything! -> Yes
Ask me a question, please! -> Yes
Are you okay? -> No
No? -> No
Hey,does this program work? -> does this program work

Quotes in the following test cases should not be outputted.
They are used as a delimiter here.

Okay, so this does work ? -> " so this does work "
Please, add, a, test, case, containing, multiple, commas? -> " commas"

```

## Scoring

This is , so shortest answer in bytes wins.

# Answer
> 6 votes
# 05AB1E, ~~20~~ 19 bytes

```
'?åi',¡”€–”0ǝθ¨ë”…Ü

```

-1 byte thanks to *@Grimy*.

Try it online or verify all test cases.

**Explanation:**

```
'?åi          '# If the (implicit) input contains a "?":
    ',¡       '#  Split the (implicit) input on ","
       ”€–”    #  Push dictionary string "Not"
           0ǝ  #  Insert it at the first position (index 0) in the list
       θ       #  Then get the last item of the list
        ¨      #  And remove the last character
               #  (either the "?" of the original input; or the "t" in "Not")
      ë        # Else:
       ”…Ü     #  Push dictionary string "Yes"
               # (after which the top of the stack is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `”€–”` is `"Not"` and `”…Ü` is `"Yes"`.

# Answer
> 8 votes
# Python 3, 62 bytes

```
lambda s:['Yes',*s[:-1].split(','),'No'][~(','in s)*('?'in s)]

```

Try it online!

The expression `~(','in s)*('?'in s)` evaluates to `0` (i.e. `'Yes'`) if the string does not contain a `'?'`, else `-1` (i.e. `'No'`) if the string does not contain a `','`, and otherwise `-2` (i.e. the last comma-separated section of the string excluding the last character).

# Answer
> 5 votes
# JavaScript (ES6),  ~~53~~  52 bytes

```
s=>(m=s.match(/(,?)([^,]*)\?/))?m[1]?m[2]:'No':'Yes'

```

Try it online!

### Commented

```
s =>                  // s = input string
  ( m = s.match(      // m is the result of matching in s:
  //     +------------>    an optional comma
  //     |     +------>    followed by a string containing no comma
  //     |     |   +-->    followed by a question mark
  //   <--><-----><>
      /(,?)([^,]*)\?/
  )) ?                // if m is not null:
    m[1] ?            //   if the comma exists:
      m[2]            //     output the string following it
    :                 //   else:
      'No'            //     output 'No'
  :                   // else:
    'Yes'             //   output 'Yes'

```

# Answer
> 4 votes
# Charcoal, ~~23~~ 22 bytes

```
¿№θ?¿№θ,⁻⊟⪪θ,¦?¦No¦Yes

```

Try it online! Link is to verbose version of code. Edit: Saved 1 byte thanks to @KevinCruijssen. Explanation:

```
¿№θ?

```

Does the string contain any `?`s?

```
¿№θ,

```

Does it contain any `,`s?

```
⊟⪪θ,

```

Split the string on `,`s and take the last.

```
⁻...?

```

Delete the `?` and output the result.

```
No

```

If there are no `,`s then output `No`.

```
Yes

```

If there are no `?`s then output `Yes`.

# Answer
> 4 votes
# Perl 5 \+ `-plF/,|\?/`, 25 bytes

```
$_=/\?$/?/,/?pop@F:No:Yes

```

Try it online!

# Answer
> 3 votes
# Pyth, 25 bytes

```
?qeQ\??}\,QPecQ\,"No""Yes

```

Try it online!

```
?q                          # if       ==
  eQ\?                      #    Q[-1]    "?":
      ?}                    #   if     in
        \,Q                 #      ","    Q:
             cQ\,           #     return split(Q, ",")
            e               #                         [-1] (last element)
           P                #                             [:-1] (remove the trailing ?)
                 "No"       #   else: return "No"
                     "Yes"  # else: return "Yes" (last " implicit)

```

# Answer
> 3 votes
# Retina, ~~32~~ 28 bytes

```
^'?K`Yes
.+,(.*)\?
$1
'?K`No

```

-4 bytes with tips from *@Neil*.

Try it online.

**Explanation:**

```
   K`       # Replace any (implicit) input, which does
^           # NOT
 '?        '# contain a "?"
     Yes    # with "Yes"

.+          # Match 1 or more characters
  ,         # followed by a comma
    .*      # followed by zero or more characters,
   (  )     # (captured in capture group 1)
       \?   # followed by a (trailing) "?"
$1          # And replace it with just the match of capture group 1,
            # (so everything between the last comma and trailing question mark)

  K`        # Replace any remaining string, which does
'?         '# contain a "?"
    No      # with "No"

            # (after which the result is output implicitly)

```

# Answer
> 3 votes
# Zsh, 51 bytes

```
<<<${${${1#*\?}:+Yes}:-${${${${1##*,}%$1}:-No}%\?}}

```

Try it online!

A byte can be saved if `ends with,?` and similar are invalid.

# Answer
> 3 votes
# Stax, 16 bytes

```
ëw‼◘╔╤▬n→ª▒¡Γ╟ï¿

```

Run and debug it

# Answer
> 2 votes
# IBM/Lotus Notes Formula, 79 bytes

```
@If(@Ends(i;"?");@If(@Contains(i;",");@Left(@RightBack(i;",");"?");"No");"Yes")

```

No TIO for Formula so...

# Answer
> 2 votes
# Python 3, ~~98~~ 87 bytes

*-9 bytes thanks to ElPedro*

```
x=input();o="Yes"
if"?"==x[-1]:o=x[(x.rfind(",")+1):-1]if x.count(",")else"No"
print(o)

```

Try it online!

This has been solidly beaten by other answers, but I'm trying out golfing in Python a bit more. Advice is appreciated!

# Answer
> 1 votes
# Gema, 34 characters

```
*,*\?=@subst{\*,=;$2}
*\?=No
*=Yes

```

Sample run:

```
bash-5.0$ echo -n 'Hey,does this program work?' | gema '*,*\?=@subst{\*,=;$2};*\?=No;*=Yes'
does this program work

```

Try it online! / Try all test cases online!

# Answer
> 1 votes
# PHP, 58 bytes

```
<?=$argn[-1]=='?'?substr(strrchr($argn,','),1,-1)?:No:Yes;

```

Try it online!

# Answer
> 1 votes
# Red, 78 bytes

```
func[s][r:"Yes"parse s[to","copy t to"?"(r: last split t",")| to"?"(r:"No")]r]

```

Try it online!

# Answer
> 1 votes
# Perl 6, 40 bytes

```
{m/[\,(.*?)]*\?$/??$0.tail||"No"!!"Yes"}

```

Try it online!

# Answer
> 1 votes
# Python 2, ~~66~~ ~~63~~ 62 bytes

```
lambda i:("Yes",("No",i[i.rfind(",")+1:-1])[","in i])["?"in i]

```

Try it online!

-3 after spotting the updated clarification "the input will only have one ? and it will always be the last character."

-1 with thanks to @ChasBrown

Basically a port of my Lotus Notes answer. Curiously, the clarification noted above does not help the Notes answer because `@Ends` is 4 bytes cheaper than `@Contains`. Now if only there was an `@In` function...

# Answer
> 1 votes
# Japt, 23 bytes

```
ø'? ?Uq, hoinu¹Ìk'?:`Y

```

Try it

# Answer
> 1 votes
# C++ (gcc), ~~120~~ 118 bytes

Function-like macro:

```
#include<string>
#define f(s)({int i{},j{};for(;s[i];)j=s[++i]-44?j:i;s[--i]-63?"Yes":j?std::string(s-~j,i+~j):"No";})

```

Try it online!

-2 bytes thanks to @ceilingcat

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 72 bytes

```
x=>x.Last()!=63?"Yes":x.Contains(',')?x.Split(',').Last().Trim('?'):"No"

```

Saved 2 bytes thanks to @someone

Try it online!

# Answer
> 1 votes
# Jelly, 20 bytes

```
Ṗṣ”,Ṫ⁾NoḊ?Ɗ“Yes”i?”?

```

Try it online!

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


title: Decimal “XOR” operator

text:
# Question
Title: Decimal “XOR” operator
Many programming language provide operators for manipulating the binary (base-2) digits of integers. Here is one way to generalize these operators to other bases:

Let *x* and *y* be single-digit numbers in base *B*. Define the unary operator `~` and binary operators `&`, `|`, and `^` such that:

* ~x = (B - 1) - x
* x & y = min(x, y)
* x | y = max(x, y)
* x ^ y = (x & ~y) | (y & ~x)

Note that if B=2, we get the familiar bitwise NOT, AND, OR, and XOR operators.

For B=10, we get the “decimal XOR” table:

```
^ │ 0 1 2 3 4 5 6 7 8 9
──┼────────────────────
0 │ 0 1 2 3 4 5 6 7 8 9
1 │ 1 1 2 3 4 5 6 7 8 8
2 │ 2 2 2 3 4 5 6 7 7 7
3 │ 3 3 3 3 4 5 6 6 6 6
4 │ 4 4 4 4 4 5 5 5 5 5
5 │ 5 5 5 5 5 4 4 4 4 4
6 │ 6 6 6 6 5 4 3 3 3 3
7 │ 7 7 7 6 5 4 3 2 2 2
8 │ 8 8 7 6 5 4 3 2 1 1
9 │ 9 8 7 6 5 4 3 2 1 0

```

For multi-digit numbers, apply the single-digit operator digit-by-digit. For example, 12345 ^ 24680 = 24655, because:

* 1 ^ 2 = 2
* 2 ^ 4 = 4
* 3 ^ 6 = 6
* 4 ^ 8 = 5
* 5 ^ 0 = 5

If the operands are different lengths, then pad the shorter one with leading zeros.

# The challenge

Write, in as few bytes as possible, a program or function that takes as input two integers (which may be assumed to be between 0 and 999 999 999, inclusive) and outputs the “decimal XOR” of the two numbers as defined above.

# Test cases

* 12345, 24680 → 24655
* 12345, 6789 → 16654
* 2019, 5779 → 5770
* 0, 999999999 → 999999999
* 0, 0 → 0

# Answer
# Jelly, 14 bytes

```
DUz0«9_ṚƊṀƊ€UḌ

```

Try it online!

Grid of all single digit pairs

A monadic link taking a list of two integers as its argument and returning an integer.

## Explanation

```
D               | Decimal digits
 U              | Reverse order of each set of digits
  z0            | Transpose with 0 as filler
          Ɗ€    | For each pair of digits, do the following as a monad:
    «   Ɗ       | - Minimum of the two digits and the following as a monad (vectorises):
     9_         |   - 9 minus the digits
       Ṛ        |   - Reverse the order
         Ṁ      | - Maximum
            U   | Reverse the order of the answer to restore the orignal order of digits
             Ḍ  | Convert back from decimal digits to integer

```

If a digit matrix is acceptable input/output:

# Jelly, 12 bytes

```
Uz0«9_ṚƊṀƊ€U

```

Try it online!
> 3 votes

# Answer
# Pyth, 31 bytes

```
LhS,hb-9ebjkmeS,ydy_d_.t_MjRTQ0

```

Try it online!

```
LhS,hb-9eb             # Helper function, computes the (x & ~y) part
L                      # y = lambda b:
  S                    #               sorted(                )
   ,                   #                       [    ,        ]
    hb                 #                        b[0]
      -9eb             #                              9-b[-1]
 h                     #                                       [0] # sorted(...)[0] = minimum

jkmeS,ydy_d_.t_MjRTQ0  # Main program (example input Q: [123, 45])
                jRTQ   # convert each input to a list of digits -> [[1,2,3],[4,5]]
              _M       # reverse each -> [[3,2,1],[5,4]]
            .t      0  # transpose, padding right with 0 -> [[3,5],[2,4],[1,0]]
           _           # reverse -> [[1,0],[2,4],[3,5]]
  m                    # map that over lambda d:
    S,                 #   sorted([    ,           ])
      yd               #           y(d)
        y_d            #                 y(d[::-1])         # reversed
   e                   #                             [-1]   # sorted(...)[-1] = maximum
jk                     # ''.join( ^^^ )

```
> 2 votes

# Answer
# Python 2, 71 bytes

```
f=lambda n,m,T=10:n+m and max(min(n%T,~m%T),min(m%T,~n%T))+f(n/T,m/T)*T

```

Try it online!
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), 75 bytes

```
a=>b=>a.Select((x,y)=>Math.Max(9-x<(y=y<b.Count?b[y]:0)?9-x:y,9-y<x?9-y:x))

```

Saved 6 bytes thanks to @someone

Try it online!
> 1 votes

# Answer
# Forth (gforth), 111 bytes

```
: m 10 /mod rot ;
: t 9 swap - min ;
: f 2dup + 0> if m m recurse 10 * -rot 2dup swap t -rot t max + 1 then * ;

```

Try it online!

### Code Explanation

```
: m          \ start a new word definition
  10 /mod    \ get quotient and remainder of dividing by 10
  rot        \ move item in 3rd stack position to top of stack
;            \ end word definition

\ word implementing "not" followed by "and"
: t          \ start a new word definition
  9 swap -   \ subtract top stack element from 9
  min        \ get the minimum of the top two stack elements
;            \ end word definition

: f          \ start a new word definition
  2dup +     \ duplicate top two stack elements and add them together
  0> if      \ if greater than 0
    m m      \ divide both by 10, move remainders behind quotients
    recurse  \ call self recursively
    10 *     \ multiply result by 10 (decimal left shift of 1)
    -rot     \ get remainders from original division
    2dup     \ duplicate both remainders
    swap t   \ swap order and call t (b & !a)
    -rot t   \ move result back and call t on other pair (a & !b)
    max + 1  \ get the max of the two results and add to total. put 1 on top of stack
  then       \ end if block
  *          \ multiply top two stack results (cheaper way of getting rid of extra 0)
;            \ end word definition

```
> 1 votes

# Answer
# PHP, ~~111~~ 109 bytes

```
for(;''<($a=$argv[1][-++$i]).$b=$argv[2][-$i];)$s=min($a<5?9-$a:$a,max($a<5?$a:9-$a,$a<5?$b:9-$b)).$s;echo$s;

```

Try it online!

Tests: Try it online!

If we call the digits we want to XOR, `$a` and `$b`, I found that:

* When `$a` is less than 5, `XOR = min(9-$a, max($a, $b))`
* When `$a` is equal to or more than 5, `XOR = min($a, max(9-$a, 9-$b))`

So I implemented this logic plus a hack to handle numbers with different lengths. I take each digit form the end of both input numbers (with negative indexes like `input[-1]`, `input[-2]`, ...) and compute the XOR and put the result in reversed order in a string to be printed at the end. Since I take digits from the end of numbers, XOR results should be put together in reversed order. When one of the inputs is longer than the other one, the negative index on shorter input results in an empty string which is equal to 0.
> 0 votes

# Answer
# Retina, ~~85~~ 59 bytes

```
^'0P`.+
N$`.
$.%`
¶

/../_(`^
$"
T`d`Rd`.¶.
%N`.
^N`..
L`^.

```

Try it online! Takes input as separate lines, but link is to test suite that reformats comma-separated input. Explanation:

```
^'0P`.+

```

Left-pad with zeros both lines to the same length.

```
N$`.
$.%`
¶

```

Sort each digit by its column index, then delete the newline. This has the effect of pairing the digits together in much the same way as a transpose would.

```
/../_(`

```

Apply separately to each pair of digits, joining the results together.

```
^
$"

```

Duplicate the pair.

```
T`d`Rd`.¶.

```

Reverse the second digit of the first pair and the first digit of the second, so we now have `x ~y` on one line and `~x y` on the other.

```
%N`.

```

Sort the digits of each line in order, so that the first digit is now `x & ~y` or `~x & y` as appropriate.

```
^N`..

```

Reverse sort the lines.

```
L`^.

```

And extract the first digit, which is the desired result.
> 0 votes

---
Tags: code-golf, math, number
---


title: Is it an Ordered Word?

text:
# Question
Title: Is it an Ordered Word?
*(inspired by this post over on Puzzling. CAUTION: SPOILERS FOR THAT PUZZLE ARE BELOW.)*

The standard telephone keypad correlates letters to numbers as follows:

```
1 ->
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
0 ->

```

A given input word is defined to be an Ordered Word if, when translated to keypad presses using the above, the resulting number is either non-decreasing or non-increasing. In other words, the resultant number cannot both increase *and* decrease.

For example, the word `CAT` translates to `228`, which is non-decreasing, and thus an Ordered Word. However, the word `DOG` is `364`, which both increases and decreases, and thus is not an Ordered Word.

## The challenge

Given a word, output whether or not it's Ordered.

## Input

* A word (not necessarily a dictionary word) consisting of ASCII alphabet (`[A-Z]` or `[a-z]`) letters only, in any suitable format.
* Your choice if the input is all uppercase or all lowercase, but it must be consistent.
* The word will be at least 3 characters in length.

## Output

A consistent truthy/falsey value for whether the input word is Ordered (truthy) or not Ordered (falsey).

## Rules

* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

## Examples

Here are some Ordered Words (i.e., truthy), and there are more on the linked Puzzling puzzle.

```
CAT
TAC
AAA
DEMONS
SKID
LKJONMSRQP
ABCDEFGHIJKLMNOPQRSTUVWXYZ

```

Here are some non-Ordered Words (i.e., falsey)

```
DOG
GOD
ROSE
COFFEE
JKLMNOGHI

```

# Answer
> 14 votes
# Python 2, ~~164~~ ~~148~~ ~~132~~ 77 bytes

*-16 bytes thanks to Rod's suggestion elsewhere. A frickin' -55 bytes thanks to Arnold Palmer.*

```
n=[min(int((ord(i)-58)/3.13),9)for i in input()]
print sorted(n)in[n,n[::-1]]

```

Try it online!

Input must be uppercase. Outputs `True` or `False` based on its orderedness.

---

## Explanation

The first line maps each letter to a number.

```
                               for i in input()   # iterate over the input string
            ord(i)                                # take the ASCII ordinal
                  -58                             # subtract 58
           (         )/3.13                       # divide by 3.13
       int(                )                      # chop off the fractional part
   min(                     ,9)                   # choose the minimum between the number and 9
n=[                                            ]  # assign the resulting list to n

```

This works based on:

```
          | A   B   C  | D   E   F  | G   H   I  | J   K   L  | M   N   O  | P   Q   R   S  | T   U   V  | W   X   Y   Z
----------+------------+------------+------------+------------+------------+----------------+------------+-----------------
ord(x)    | 65  66  67 | 68  69  70 | 71  72  73 | 74  75  76 | 77  78  79 | 80  81  82  83 | 84  85  86 | 87  88  89  90
----------+------------+------------+------------+------------+------------+----------------+------------+-----------------
x - 58    | 7   8   9  | 10  11  12 | 13  14  15 | 16  17  18 | 19  20  21 | 22  23  24  25 | 26  27  28 | 29  30  31  32
----------+------------+------------+------------+------------+------------+----------------+------------+-----------------
x ÷ 3.13* | 2.2 2.6 2.9| 3.2 3.5 3.8| 4.2 4.5 4.8| 5.1 5.4 5.8| 6.1 6.4 6.7| 7.0 7.3 7.7 7.9| 8.3 8.6 8.9| 9.3 9.6 9.9 10.2
----------+------------+------------+------------+------------+------------+----------------+------------+-----------------
int(x)    | 2   2   2  | 3   3   3  | 4   4   4  | 5   5   5  | 6   6   6  | 7   7   7   7  | 8   8   8  | 9   9   9   10
----------+------------+------------+------------+------------+------------+----------------+------------+-----------------
min(x, 9) | 2   2   2  | 3   3   3  | 4   4   4  | 5   5   5  | 6   6   6  | 7   7   7   7  | 8   8   8  | 9   9   9   9

```

<sub>\*Values are rounded. :P</sub>

The second line outputs if the list of numbers is in ascending or descending order.

```
print                                             # print whether...
      sorted(n)                                   # n sorted...
               in[n,n[::-1]]                      # is equivalent to n or n reversed

```

# Answer
> 8 votes
## JavaScript (ES6),  ~~83 ... 71~~  70 bytes

Returns a boolean.

```
x=>[...x].every(c=>v&=~(k=x,x=parseInt(c,35)*.32|0||10,x<k?2:x>k),v=3)

```

### Test cases

```
let f =

x=>[...x].every(c=>v&=~(k=x,x=parseInt(c,35)*.32|0||10,x<k?2:x>k),v=3)

test = a => a.forEach(s => console.log(f(s) + " for '" + s + "'"))

console.log('[Truthy]')
test(["AAA", "CAT", "TAC", "DEMONS", "SKID", "LKJONMSRQP", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"])

console.log('[Falsy]')
test(["DOG", "GOD", "ROSE", "COFFEE", "JKLMNOGHI"])
```

---

### How?

**Letter conversion**

We use `parseInt(c, 35)` to convert each letter of the input string to some number in \[*10* .. *34*\]. Because it's base-35, *"Z"* is converted to `NaN` instead.

The expression `* .32 | 0` maps this number into the interval \[*3* .. *10*\], leading to 8 correct groups of letters for *"A"* to *"Y"*. We need `|| 10` to get the correct value for *"Z"*.

```
           | A  B  C| D  E  F| G  H  I| J  K  L| M  N  O| P  Q  R  S| T  U  V| W  X  Y   Z
-----------+--------+--------+--------+--------+--------+-----------+--------+------------
parseInt   |10 11 12|13 14 15|16 17 18|19 20 21|22 23 24|25 26 27 28|29 30 31|32 33 34 NaN
-----------+--------+--------+--------+--------+--------+-----------+--------+------------
*.32|0||10 | 3  3  3| 4  4  4| 5  5  5| 6  6  6| 7  7  7| 8  8  8  8| 9  9  9|10 10 10  10

```

**Order test**

We keep track of the signs of differences between consecutive numbers into the bitmask ***v***, initially set to 3 (0b11):

* bit #0: cleared when *new\_value \> previous\_value*
* bit #1: cleared when *new\_value \< previous\_value*

The previous value is stored in the same variable ***x*** as the input. This ensures that the first iteration -- where no *previous value* actually exists -- will not clear any bit, because a string containing only letters is neither greater nor less than any number:

```
('CAT' > 5) === false
('CAT' < 5) === false

```

A word is ordered unless both signs are encountered, which leads to ***v = 0*** and makes `every()` fail.

# Answer
> 6 votes
# Jelly, ~~28, 27, 25, 23, 22, 21, 19,~~ 18 bytes

```
_>
O‘ç82ç88:3IṠḟ0E

```

Try it online!

This was a lot of fun to write!

Explanation:

```
                # Define a helper link, decrement a if a > b
_               # Subtract
 >              # Boolean greater than
                # Main link:
O               # The ordinals (ASCII points) of the input
 ‘              # Minus one
  ç82           # Decrement if greater than 82
     ç88        # Decrement if greater than 88
        :3      # Divide each number by 3
          I     # Consecutive differences
           Ṡ    # Sign (-1 if < 0, 0 if == 0, and 1 if > 0)
            ḟ0  # Remove all 0's
              E # All elements are equal?

```

Thanks to @ErikTheOutgolfer, @leakynun and @BusinessCat for all saving bytes. :)

# Answer
> 3 votes
# 05AB1E, 36 bytes

```
v.•1нJ©½è`ÇHø¹á₂N¸°…ÈáÀ•#Dʒyå}k}¥0‹Ë

```

Try it online!

# Answer
> 3 votes
# MATL, ~~26~~ 25 bytes

```
1Y21K250B-Y{c&m8\dZSu|s2<

```

Input is in upper-case letters. Output is `1` or `0`.

**Try it online!**

### Explanation

```
1Y2      % Push 'ABC...XYZ'
1        % Push 1
K        % Push 4
250B     % Push 250 in binary, that is, [1 1 1 1 1 0 1 0]
-        % Subtract (from 4, element-wise): gives [3 3 3 3 3 4 1 4]
Y{       % Convert to cell array, splitting into chunks of those lengths
c        % Convert to char matrix. Gives a 4-column matrix. Chunks of length 3
         % are right-padded with a space
&m       % Implicit input. Push (linear) index of membership in char matrix
8\       % Modulo 8. Converts linear index into 0-based row index
d        % Consecutive differences
ZS       % Sign
u        % Unique
|        % Absolute value
s        % Sum
2<       % Less than 2? Implicit display

```

# Answer
> 3 votes
## Husk, ~~22 21 19~~ 18 bytes

```
±S€Ẋ▲`Ṫo±≤"DGJMPTW

```

Returns `1` for truthy inputs, `0` for falsy ones. Inputs must be in uppercase. Passes all test cases. Try it online!

## Explanation

```
±S€Ẋ▲`Ṫo±≤"DGJMPTW  Implicit input x, e.g. "CAT"
     `Ṫo±≤"DGJMPTW  This part transforms x into a "canonical form" corresponding to the numpad digits
     `Ṫ             Table with flipped arguments
       o±≤          on sign of less-than-or-equal
                    (In Husk, ≤ returns extra information we don't want, so we take sign of the result to get 0 or 1.)
          "DGJMPTW  of this string and x.
                    This gives, for each char in x, a bit array of comparisons with the chars in the string:
                    y = [[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[1,1,1,1,1,1,0]]
   Ẋ▲               Maxima of adjacent pairs: [[0,0,0,0,0,0,0],[1,1,1,1,1,1,0]]
 S€                 1-based index in y as sublist: 2
±                   Sign: 1

```

# Answer
> 3 votes
# Python 2, 60 bytes

```
a=[3681/ord(c)for c in input()]
print sorted(a)in[a,a[::-1]]

```

Try it online!

Accepts input in lowercase.

### How it works

⌊3681/*x*⌋ decreases from

* 38 to 37 at *x* ≈ 96.8684210526, before `a`;
* 37 to 36 at *x* ≈ 99.4864864865, between `c` and `d`;
* 36 to 35 at *x* ≈ 102.25, between `f` and `g`;
* 35 to 34 at *x* ≈ 105.171428571, between `i` and `j`;
* 34 to 33 at *x* ≈ 108.264705882, between `l` and `m`;
* 33 to 32 at *x* ≈ 111.545454545, between `o` and `p`;
* 32 to 31 at *x* ≈ 115.03125, between `s` and `t`;
* 31 to 30 at *x* ≈ 118.741935484, between `v` and `w`;
* 30 to 29 at *x* ≈ 122.7, after `z`.

# Answer
> 2 votes
# JavaScript (ES6), ~~107~~ ~~97~~ ~~95~~ ~~92~~ ~~88~~ 85 bytes

Works with mixed-case strings. Returns `1` for truthy or `0` for falsey.

```
s=>(s=(a=[...s].map(c=>(parseInt(c,36)-3)/3.13%10|0||9))+"")==a.sort()|s==a.reverse()

```
* 10 bytes saved thanks to Rod.

---

## Try It

```
o.innerText=(f=
s=>(s=(a=[...s].map(c=>(parseInt(c,36)-3)/3.13%10|0||9))+"")==a.sort()|s==a.reverse()
)(i.value="Cat")
oninput=_=>o.innerText=f(i.value)
```

```
<input id=i><pre id=o>
```

# Answer
> 2 votes
## C++, ~~375~~ ~~199~~ ~~195~~ 194 bytes

Thanks to Shaggy's JavaScript answer :
-5 bytes thanks to Zacharý

```
#include<string>
int o(std::string a){std::string m="22233344455566677778889999";for(auto&b:a)b=m[b-65];int j=1,i=0,d=0;for(;j<a.size();++j){if(a[j]>a[j-1])++i;if(a[j]<a[j-1])++d;}return!(i*d);}

```

# Answer
> 1 votes
# 05AB1E, 30 bytes

```
A3 8×Ƶ0+S£¹δåā>‚øε`*}.«+¥0K0‹Ë

```

Try it online!

-1 thanks to Magic Octopus Urn.

# Answer
> 1 votes
# Gaia, ~~29~~ ~~27~~ ~~25~~ 17 bytes

```
ċ⟨):“QX’>¦Σ⁻3/⟩¦o

```

Try it online!

### Explanation

```
ċ                  Turn the input into a list of code points
 ⟨            ⟩¦   Map this block to each code point:
  )                 Increment it
   :                Copy it
    “QX’            Push [81 88]
        >¦          Check if the code point is greater than each of [81 88]
          Σ         Sum the results
           ⁻        Subtract from the code point
            3/      Integer divide the result by 3
                o  Check if the resulting list is in sorted order (increasing or decreasing)

```

# Answer
> 1 votes
# 05AB1E, ~~21~~ 17 bytes

### Code

```
A•22ā₂•Sās×J‡Ô¥dË

```

Uses the **05AB1E** encoding.

Try it online! or Verify all test cases!

### Explanation

```
A                   # Push the lowercase alphabet
 •22ā₂•             # Push the number 33333434
       S            # Split into an array
        ā           # Get the range of indices [1 .. length]
         s×         # Swap and string multiply
           J        # Join that array
            ‡       # Transliterate

```

This now essentially maps the following letters to the following numbers:

```
abcdefghijklmnopqrstuvwxyz
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
11122233344455566667778888

```

```
             Ô      # Remove consecutive duplicates
              ¥     # Compute the delta's of the list
               d    # Check if the number is greater or equal to 0
                Ë   # Check if all elements are the same

```

# Answer
> 1 votes
# Pyth, 23 bytes

One of my first non-trivial Pyth answer! Saved 6 bytes thanks to @LeakyNun. The initial solution is below.

```
/{_BKmhS,9/a58Cd3.13zSK

```

Test Suite.

# Pyth, 29 bytes

```
KmhS+9]/-Cd58 3.13w|qKSKqK_SK

```

Test Suite.

---

# Explanation

```
/{_BKmhS,9/a58Cd3.13zSKQ - The Q means evaluated input and is implicit at the end

 {                      - Deduplicate
  _                     - Reverse
   B                    - Bifurcate, Create a two-element list, [B, A(B)]
    K                   - Variable with auto-assignement to:
     m              z    - Map over the input:
      hS                  - Minimum (first element of sorted list)
        ,                 - Create a two-element list, [A, B] with these elements:
         9                  - The numeric literal 9
          /                 - The integer division of:
           a58Cd              - The absolute difference between 58 and ord(current_element)
                3.13          - The numeric literal 3.13
                    SK   - K sorted
/                     Q  - Count the occurrences of the input in [K, K[::-1]]

```

# Answer
> 1 votes
# Retina, 65 bytes

```
T`_ADGJMPTW`d
}T`L`_L
(.)\1*
$1$*1<
(1+)<(?!\1)
$1>
1

^(<*|>*)>$

```

Try it online! Link includes test cases. Explanation:

```
T`_ADGJMPTW`d

```

Change the first letter on each key to a digit. (This is off by 1 but that doesn't matter for an ascending/descending check. On the other hand, zeros would make my life more difficult, so I left one filler character in.)

```
}T`L`_L

```

Shuffle all the remaining letters up 1 and repeat until they've all been converted to digits.

```
(.)\1*
$1$*1<

```

Convert the digits into unary, but only once per run of identical digits. The unary values are seprated with a `<`...

```
(1+)<(?!\1)
$1>

```

... but if the LHS turns out to be greater than the RHS, correct the `<` to `>`.

```
1

```

Delete the `1`s which are no longer necessary.

```
^(<*|>*)>$

```

Check that the word is ordered. (The trailing `>` comes from the last digit which always compares greater than the empty space following it.)

# Answer
> 1 votes
# 05AB1E, 13 bytes

```
ÇÍžq÷8
7:Ô¥dË

```

Whenever I see a numpad question, I have to make a pi-based answer.

Try it online or verify all test cases

```
Ç                    # ASCII code of each letter in the input
 Í                   # add 2
  žq÷                # divide by pi
     8 7:            # replace 8 with 7
         Ô           # remove duplicates
          ¥          # deltas
           d         # each >= 0 ?
            Ë        # are all elements equal?

```

# Answer
> 0 votes
# Jelly, 32 bytes

```
“¢Ç⁺H’D0ẋj1œṗØA⁸=€×"€9Ḋ¤Fḟ0Iḟ0ṠE

```

Try it online!

# Answer
> 0 votes
# Python 3, ~~143~~ ~~147~~ ~~148~~ ~~149~~ 130 bytes

```
def g(s,f=lambda c:min(int((ord(c)-58)/3.13),9)):x=[f(a)-f(b)for a,b in zip(s,s[1:])];return any(t<0for t in x)*any(t>0for t in x)

```

Best I can do for now. Crude function turns the letter into the number based off of ascii code. There are definitely some improvements to be made. 0 is truthy, 1 is falsey (sorry). Saved 10 bytes thanks to Rod, another 3 thanks to Mr. Xcoder.

Try it online!

# Answer
> 0 votes
# Python 2, ~~111~~ 103 bytes

*-8 bytes thanks to @Arnold Palmer:no `lower()` needed*

* Takes uppercase letters as input.

```
lambda x:sorted(f(x))in[f(x),f(x)[::-1]]
f=lambda x:['22233344455566677778889999'[ord(i)-65]for i in x]

```

Try it online!

# Answer
> 0 votes
# C# (.NET Core), 133 bytes

```
using System.Linq;q=>{var u=q.Select(c=>(int)((c-58)/3.13));var z=u.Zip(u.Skip(1),(a,b)=>a-b);return!(z.Any(d=>d<0)&z.Any(d=>d>0));};

```

Try it online!

I feel like there's some room to save, but C# is not a concise language so maybe not. Ungolfed:

```
bool Ordered(string word){

    IEnumerable<int> keys = word.Select(character => (int)((character - 58)/3.13));
    // convert characters to keypad number

    IEnumerable<int> differences = keys.Zip(keys.Skip(1), (a, b)=> a-b);
    // difference between consecutive elements

    return !(differences.Any(diff => diff<0) & differences.Any(diff => diff>0));
    // false if both positive and negative differences exist
}

```

In particular I think there's a shorter way to express the final check for validity, possibly a way to inline it with the `Zip`. Finding a way to express the `Zip` without needing temporary storage for the `Skip` would also save something, but I doubt there's something more concise for that.

# Answer
> 0 votes
# CJam, ~~37~~ ~~31~~ ~~30~~ 27 bytes

```
q{_"SVZY"#g-i3/}%_$_W%](e=g

```

Try it Online

Of course the ugly version ends up being shorter...

```
q{        e# For each character in string...
_"SVZY"#g e# Get index of that character in "SVZY". Signum that. (returns 1 or 0 if inside string, -1 if not.)
-i3/      e# Subtract value from character (i.e 'Z' becomes 'Y', 'F' becomes 'G'). Convert to int. Integer divide by 3. (this is just how the math works out for proper mapping of characters to phone digits.)
}%
_$_W%]    e# Put mapped string, sorted version, and reverse sorted version in array.
(         e# Pop mapped string from array onto stack.
e=        e# Count occurences of mapped string in array.
g         e# Signum.

```

# Answer
> 0 votes
# TI-Basic, ~~92~~ 66 bytes

```
ΔList(int(seq(inString("BC DEF GHI JKL MNO PQRSTUV WXYZ",sub(Ans,I,1))/4,I,1,length(Ans
0≤min(Ansmax(Ans

```

Converts each character in the string to an integer from 0 to 7, and takes the difference between each consecutive element; then checks whether the minimum and maximum differences have the same sign (or either is 0).

# Answer
> 0 votes
# PHP 7, ~~98+1 95+1~~ 84+1 bytes

a golfed port of Arnauld´s answer.

```
for(;$c=ord($argn[$i]);$v|=$i++?$p>$k?2:$p<$k:0,$p=$k)$k=($c-58)*.32%10?:9;echo$v<3;

```

accepts uppercase; empty output for falsy, `1` for truthy.

Run as pipe with `-nR` or try it online.

original post:

```
for(;$c=$argn[$i++];$p?$a[]=$p<=>$k:0,$p=$k)$k=(ord($c)-58)/3.13-($c>Y)|0;echo min($a)*max($a)>=0;

```

# Answer
> 0 votes
# C (gcc), ~~183 169 153~~ 117 bytes

```
#define a(b)(int)fmin(*(b c)/3.2,27)
d(char*c){int r=1,p=1;for(;1<strlen(c);)r&=a()<=a(1+),p&=a()>=a(++);return r|p;}

```

Try it online!

Old solution:

```
#define a(b)(int)((int)(b*.32-17.6)*.9)
d(char*c){int l=~-strlen(c),i=0,r=1,p=1;for(;i<l;++i)r&=a(c[i])<=a(c[i+1]),p&=a(c[l-i])<=a(c[l-i-1]);return r+p;}

```

Saved 8 bytes thanks to ThePirateBay.

Old old solution:

```
d(char*c){char*a="22233344455566677778889999";int l=strlen(c)-1,i=0,r=1,p=1;for(;i<l;++i){if(a[c[i]-65]>a[c[i+1]-65])r=0;if(a[c[l-i]-65]>a[c[l-i-1]-65])p=0;}return r+p;}

```

Old old old solution:

```
d(char*c){char*a="22233344455566677778889999";int l=strlen(c);int i,r=1,p=1;for(;i<l-1;++i)if(a[c[i]-65]>a[c[i+1]-65])r=0;for(i=l-1;i>0;--i)if(a[c[i]-65]>a[c[i-1]-65])p=0;return r+p;}

```

# Answer
> 0 votes
# Zsh, ~~73 69~~ 57 bytes

***-12 bytes** by using @anders-kaseorg's `3681/code` conversion.*

```
for c (${(s::)1})((y=3681/#c,A|=y<p,D|=p&&p<y,p=y,!D|!A))

```

~~Try it online! Try it online!~~ Try it online!

A few things we abuse:

* `((statement,statement,...))` is a sequence of *arithmetic* expressions which returns truthy if the last statement is non-zero.
* The return value of a loop is the return value of the last statement in a loop.
* Arithmetic operator precedences were pretty nice to us, as ~~only one pair of~~ **no** parentheses were used. One byte could be saved if `!` bound less tightly than `&`.
* Unset parameters expand to `0` in arithmetic expansions.
* ~~The function we use to map to the keypad number is `CODE / 3.2 - 18` (with a special case for `Z`), but~~ since we only need the *change* between codes, we don't do the linear adjustment.

```
for c (${(s::)1})           # split into characters
    (( y = #c-90 ? 0^(#c/3.2) : 27,   # this sets y to the keypad number + 18
       A |= y < p,          # set the A flag if we detect it is not ascending
       D |= p && p < y,     # ditto descending, don't compare on first iteration
       p = y,               # save the current character
       !D | !A              # return false if D and A are both set
    ))

```

2 bytes can be saved if the truthy/falsey values can be swapped.

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


title: Bertrand's Primes

text:
# Question
Title: Bertrand's Primes
Bertrand's Postulate states that for every integer **n ≥ 1** there is at least one prime **p** such that **n \< p ≤ 2n**. In order to verify this theorem for **n \< 4000** we do not have to check 4000 cases: The *Landau trick* says it is sufficient to check that

```
2, 3, 5, 7, 13, 23, 43, 83, 163, 317, 631, 1259, 2503, 5003

```

are all prime. Because each of these numbers is less than twice its predecessor each interval **{y : n \< y ≤ 2n}** contains at least one of those prime numbers.

This sequence of numbers are the Bertrand Primes (OEIS A006992) and they are defined as follows:

```
a(1) = 2
a(n) = largest prime below 2a(n-1)

```

### Challenge

Implement this sequence. You may write

* a function or program that given some **n** returns **a(n)** (0 or 1 indexed),
* a function or program that given some **n** returns the first **n** (or **n-1** or **n+1**) entries of this sequence,
* an infinite list or stream or generator or similar equivalent in your langauge.

# Answer
> 8 votes
# Octave, 32 bytes

```
k=2
do k=primes(k+k)(end)until 0

```

Keeps printing the values indefinitely (each value is preceded by `k =`).

Try it online!

---

# Octave, 42 bytes

```
k=2
for i=2:input('')k=primes(k+k)(end)end

```

Takes **n** as input and outputs the **n** first values (each value is preceded by `k =`).

Try it online!

---

# Octave, 51 bytes

```
k=2;for i=2:input('')k=primes(k+k)(end);end
disp(k)

```

Similar to Luis Mendo's MATL answer. Takes **n** as input and outputs **a(n)** (1-indexed).

Try it online!

---

# Octave, 60 bytes

```
k=2;for i=2:input('')k*=2;while~isprime(--k)
end
end
disp(k)

```

Takes **n** as input and outputs **a(n)** (1-indexed).

Try it online!

# Answer
> 7 votes
# , 11 bytes

```
_4&(p:+:)2:

```

Try it online!

0-indexed.

```
_4&(p:+:)2:  Input: integer n
         2:  Constant 2
_4&(    )    Repeat n times
      +:       Double
_4  p:         Find the largest prime less than the double

```

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

Saved one byte thanks to Martin Ender.

0-indexed.

```
Nest[-NextPrime[-2#]&,2,#]&

```

Try it online!

# Answer
> 6 votes
# 05AB1E, ~~14~~ ~~7~~ 6 bytes

```
$F·.ØØ

```

Try it online!

---

1-indexed answer (unless 0 is supposed to output 1), explanation:

```
$       # Push 1 and input (n)...
 F      # n-times do...
  ·     # Double the current prime (first iteration is 1*2=2).
   .ØØ  # Find prime slightly less than double the current prime.

```

---

It's 1-indexed because all iterations have a 'dummy' iteration with `n=1`.

# Answer
> 6 votes
# Haskell, 50 bytes

```
f p|sum(gcd p<$>[1..p-1])<p=p:f(2*p)|1>0=f$p-1
f 2

```

Try it online!

Outputs an infinite list.

---

# Haskell, 40 bytes?

```
f p|mod(2^p-2)p<1=p:f(2*p)|1>0=f$p-1
f 2

```

Try it online!

This works if Bertrand's primes don't contain any Fermat pseudoprimes for 2.

# Answer
> 5 votes
# MATL, 9 bytes

```
1i:"EZq0)

```

Inputs **n**, outputs **a**(**n**), 1-indexed.

Try it online!

### Explanation

```
1       % Push 1
i       % Push input n
:"      % Do the following that many times
  E     %   Multiply by 2
  Zq    %   Primes up to that
  0)    %   Get last entry
        % End (implicit). Display (implicit)

```

# Answer
> 5 votes
# Jelly, 6 bytes

```
2ḤÆp$¡

```

Try it online!

0-indexed.

## Explanation

```
2ḤÆp$¡  Main link. Input: n
2       Constant 2
    $¡  Repeat n times
 Ḥ        Double
  Æp      Find the largest prime less than the double

```

# Answer
> 5 votes
# Stax, 10 bytes

```
ü☼┌τ,æ▒ìn(

```

Run test cases

This problem has exposed a bug in stax's implementation of `:p`, which is an instruction that gets the greatest prime less than its input. If it worked correctly, there would be a 5 6 byte solution. But alas, it does not, and there is not. As the language's creator, I will fix it, but it seems kind of cheap to fix and use it after the problem was posted.

Anyway, here is the corresponding ascii representation of the program above.

```
ODH{|p}{vgs

```

It's a relatively straight-forward implementation of the problem statement. The only thing possibly interesting about it is the use of the `gs` generator form. Generators are a family of constructions that combine an initial condition, a transform, and a filter, to produce one or more satisfying values. In this case, it's used in place of the broken `:p` instruction.

```
O               Push integer 1 underneath the input number.
 D              Pop the input and repeat the rest of the program that many times.
  H             Double number.
   {|p}         Predicate block: is prime?
       {vgs     Decrement until the predicate is satisfied.
                Output is implicitly printed.

```

*Edit:* here's the 6 byte solution, but it requires a bug-fix that was only applied after this challenge was posted.

# Answer
> 4 votes
# Python 2, 63 bytes

```
r=m=k=P=2
while k:
 P*=k;k+=1
 if k>m:print r;m=r*2
 if P%k:r=k

```

Try it online!

Prints forever.

Uses the Wilson's Theorem prime generator even though generating primes forward is clunky for this problem. Tracks the current largest prime seen `r` and the doubling boundary `m`.

Two bytes are saved doing `P*=k` rather than `P*=k*k` as usual, as the only effect is to claim that 4 is prime, and the sequence of doubling misses it.

# Answer
> 4 votes
# Japt, ~~16~~ ~~14~~ ~~13~~ 12 bytes

Two solutions for the price of one, both 1-indexed.

---

## Nth Term

Finally, a challenge I can write a working solution for using `F.g()`.

```
_ôZ fj Ì}g°U

```

Try it

```
                 :Implicit input of integer U
_       }g       :Starting with the array [0,1] take the last element (Z),
                 :pass it through the following function
                 :and push the returned value to the array
 ôZ              :  Range [Z,Z+Z]
    fj           :  Filter primes
       Ì         :  Get the last item
          °U     :Repeat that process U+1 times and return the last element in the array

```

---

## First N Terms

```
ÆV=ôV fj Ìª2

```

Try it

```
                 :Implicit input of integer U
                 :Also makes use of variable V, which defaults to 0
Æ                :Create range [0,U) and pass each through a function
  ôV             :  Range [V,V+V]
     fj          :  Filter primes
        Ì        :  Get the last item
         ª2      :  Logical OR with 2, because the above will return undefined on the first iteration
 V=              :  Assign the result of the above to V

```

# Answer
> 4 votes
## CJam (15 bytes)

```
2{2*{mp},W=}qi*

```

Online demo. Note that this is 0-indexed.

---

A more efficient approach would be to search backwards, but this requires one character more because it can't use implicit `,` (range):

```
2{2*,W%{mp}=}qi*

```

# Answer
> 3 votes
# Python 2, 64 bytes

```
n=2
while 1:
 if all(n%i for i in range(2,n)):print n;n*=2
 n-=1

```

Try it online! Prints the sequence indefinitely

# Answer
> 3 votes
# Pari/GP, 34 bytes

```
a(n)=if(n<2,2,precprime(2*a(n-1)))

```

Try it online!

# Answer
> 3 votes
# Haskell, 58 bytes

```
a 1=2
a n=last[p|p<-[2..2*a(n-1)],all((>0).mod p)[2..p-1]]

```

Try it online!

# Answer
> 2 votes
# Python 2, 68 bytes

Prints the sequence indefinitely (you have to click "Run" the second time to stop the execution).

```
k=2
while 1:
 print k;k+=k
 while any(k%u<1for u in range(2,k)):k-=1

```

Try it online!

### Python 3, 90 bytes

Returns the nth term.

```
f=lambda n,i=1,p=1:n*[0]and p%i*[i]+f(n-1,i+1,p*i*i)
a=lambda n:n and f(2*a(n-1))[-1]or 1

```

Try it online!

# Answer
> 2 votes
# C (gcc), ~~97~~ ~~87~~ ~~86~~ ~~80~~ 79 bytes

* Saved ten bytes by inlining a non-primality checking function `P` into the main loop.
* Saved a byte by moving the `printf` call.
* Saved six bytes by returning the `i`-th sequence entry (0-indexed) instead of outputting a never-ending stream.
* Saved a byte thanks to ceilingcat.

```
f(p,r,i,m,e){for(r=2;p--;)for(e=0,i=r+r;e=m=!e;r=i--)for(;i-++m;e=e&&i%m);p=r;}

```

Try it online!

# Answer
> 1 votes
# Attache, 38 bytes

```
{If[_,Last[Series[Prime,2*$[_-1]]],2]}

```

Try it online!

0-based; returns the `n`th Bertrand prime.

There is currently no builtin to find the previous/next primes, so I use the `Series` builtin to calculate all primes up to `2*$[_-1]`. This last expression uses implicit recursion (bound to `$`) to easily define the recurrence relation. The if condition is used to determine a base condition.

# Answer
> 1 votes
# Perl 6, 35 bytes

```
2,{(2*$_,*-1...&is-prime).tail}...*

```

Try it online!

This expression is an infinite list of Bertrand primes.

# Answer
> 1 votes
# Retina, 39 bytes

```
.K`_
"$+"{`_
__
+`^(?=(..+)\1+$).

*\`_

```

Try it online! Explanation:

```
.K`_

```

Start with 1.

```
"$+"{`

```

Repeat the loop using the input as the loop count.

```
_
__

```

Double the value.

```
+`^(?=(..+)\1+$).

```

Find the highest prime less than the value.

```
*\`_

```

Print it out.

# Answer
> 0 votes
# Ruby, 51 + 7 (-rprime) = 58 bytes

```
->n{x=2
n.times{x=(x..2*x).select(&:prime?)[-1]}
x}

```

Try it online!

A lamba accepting `n` and returning the `nth` Bertrand prime, 0-indexed. There's not much here, but let me ungolf it anyway:

```
->n{
  x=2                       # With a starting value of 2
  n.times{                  # Repeat n times:
    x=(x..2*x)              # Take the range from x to its double
      .select(&:prime?)[-1] # Filter to only primes, and take the last
  }
  x                         # Return
}

```

# Ruby, 48 + 7 = 55 bytes

```
x=2
loop{puts x
x*=2
loop{(x-=1).prime?&&break}}

```

Try it online!

For fun, here's an infinite-loop solution. It prints as it goes, and requires an interrupt. Depending on exactly when you interrupt, you may or may not see the output. Ungolfed:

```
x=2
loop{
  puts x
  x*=2
  loop{
    (x-=1).prime? && break
  }
}

```

# Answer
> 0 votes
# APL (Dyalog Extended), 12 bytes

Takes input from user as N, returns Nth element of the sequence (0-indexed).

```
{¯4⍭2×⍵}⍣⎕⊢2

```

Try it online!

Explanation:

```
{¯4⍭2×⍵}⍣⎕⊢2 ⍝ Full program
          ⎕   ⍝ Get input from user - call it 'N'
         ⍣ ⊢2 ⍝ Repeat the left function N times, beginning with 2
    2×⍵       ⍝ Double the function input
 ¯4⍭          ⍝ Find the largest prime less than above

```

# Answer
> 0 votes
# , 87 bytes

# Given `n` outputs `a(n)`

```
j=scan();n=2;while(j-1){for(i in (n+1):(2*n)){n=ifelse(any(i%%2:(i-1)<1),n,i)};j=j-1};n

```

Try it online!

I'm still working on "Given n output a(1), a(2)... a(n)". I thought I could just modify this code slightly, but it seems more difficult than that.

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