text stringlengths 26 126k |
|---|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
[Question]
[
Inspired by the title of [the *Toggle some bits and get a square* challenge](https://codegolf.stackexchange.com/questions/170281/toggle-some-bits-and-get-a-square).
In that challenge you output how many bits should be toggled, in order for the base-10 representation of the binary to become a square number.
## Challenge:
In this challenge, you'll be given a bit-matrix \$M\$ and an integer \$n\$ as inputs.
Output the edge-size of the largest square you can make by toggling at most \$n\$ bits in the grid. A square is defined as having a border of `1`s, with an irrelevant inner body.
E.g., these all contain valid squares of size 4x4, highlighted below with `X`:
(for the third example, more than one 4x4 square is possible)
```
1111 1111 11111111 010110
1001 1011 11111111 001111
1001 1101 11111111 101011
1111 1111 11111111 111001
011111
XXXX XXXX XXXX1111 010110
X00X X01X X11X1111 00XXXX
X00X X10X X11X1111 10X01X
XXXX XXXX XXXX1111 11X00X
01XXXX
```
**Example:**
So let's say the inputs are \$n=4\$ and \$M=\$
```
010110
001011
101010
111001
011110
```
You could toggle these three bits (highlighted as `T`):
```
010110
001T11
10101T
111001
01111T
```
to get the 4x4 square of the fourth example above. So the output is `4`.
## Challenge rules:
* You can take the input-grid in any reasonable format. Can be a matrix of integers; matrix of booleans; list of strings; list of integers for which their binary representation (with leading 0s) is the binary grid; etc.
* You toggle at most \$n\$ bits, not exactly \$n\$ bits.
* The input-matrix \$M\$ is not guaranteed to be a square, but it is guaranteed to be a (non-empty) rectangle.
* The input-integer \$n\$ is guaranteed to be non-negative (\$n\geq0\$).
## General Rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (e.g. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test Cases:
| Inputs: | Output: |
| --- | --- |
| \$n\$=`4` and \$M\$=
```
010110001011101010111001011110
```
| 4 |
| \$n\$=`8` and \$M\$=
```
0010101010110111001001001
```
| 4 |
| \$n\$=`0` and \$M\$=
```
000000000000
```
| 0 |
| \$n\$=`0` and \$M\$=
```
111111
```
| 2 |
| \$n\$=`1` and \$M\$=
```
101010101
```
| 1 |
| \$n\$=`1000` and \$M\$=
```
100010010010100101100011110110110101010010101001101011
```
| 6 |
[Answer]
# JavaScript (ES6), 139 bytes
Expects `(n)(matrix)`.
```
n=>m=>m.map(W=h=(X,w,k,Y)=>m.map((r,y)=>r.map((v,x)=>k?h(x,w,q=t=0,y):(x-X)%w&&(y-Y)%w||x<X|x>X+w|y<Y|y>Y+w||++q<w*4|(t+=!v)>n?0:W=w+1)))|W
```
[Try it online!](https://tio.run/##VU9Nb4IwGL73V3Qmc@3Apk08LM7iaTvu4kGIemAIyoSiBQWy7rezfmiWJW3f530@3rZf8TWuE5mfmomodumQ8UHwoNSLlPEJrfiBo9Bv/aMf4TuJpN/rRrrm6ne6OS4OqNO@M2841fIMdZMQP7bjMeonkQZKdfNQdUHotaqfR6oPIo2U553n7fNUocbjD1cciAWdrXjrMYyxWg0yPV9ymaKnrH7CRKbx7j0v0mUvEkQxaaplI3OxR5jUpyJv0GgjNmKESVbJtzg5oBryAH4DCIu0gWsofEgIKeEWclj/RUb4VVuEJj1hUKmR@6nNr3Wm3tr@41J@phJbf1KJuipSUlR7lCGBUWn4HzxMAWWUMQqorYCZQgHTFGVaMwCAFyeDu@icBlPrAyb/fwM7xG5gxwIbNWZmdHPc89QNY45k7gJ3j8vdopTeHsh@AQ "JavaScript (Node.js) – Try It Online")
### Commented
```
n => // n = max. number of times we can toggle bits
m => // m[] = binary matrix
m.map(W = // initialize W to a zero'ish value
h = (X, w, k, Y) => // for each entry in m[], using a recursive callback h:
m.map((r, y) => // for each row r[] at index y in m[]:
r.map((v, x) => // for each value v at index x in r[]:
k ? // if this is the first pass:
h( // do a recursive call:
x, // set X = x
w, // pass w unchanged
q = t = 0, // set k = q = t = 0
y // set Y = y
) // end of recursive call
: // else (2nd pass):
(x - X) % w && // do nothing if we're not located on the grid
(y - Y) % w || // of width w
x < X | // or x is too low
x > X + w | // or x is too high
y < Y | // or y is too low
y > Y + w // or y is too high
|| // otherwise:
++q < w * 4 | // increment q
(t += !v) > n // increment t if v = 0
? // if q < w * 4 (not a complete square)
// or t > n (too many bits must be toggled):
0 // do nothing
: // else:
W = w + 1 // success: update W
) // end of map()
) // end of map()
) | W // end of map(); return W
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 30 bytes
```
xZyP:"0&G@qWQB&+gZ++7Mz<m@*vX>
```
It uses convolution \o/
Inputs are `n`, then `M`.
[Try it online!](https://tio.run/##y00syfn/vyKqMsBKyUDN3aEwPNBJTTs9Slvb3LfKJtdBqyzC7v9/E65oAwVDBRAGktZABpxrDWUYQGQMIUpAXGuoerBALAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8L8iqjLASslAzd2hMDzQSU07PUpb29y3yibXQasswu5/rEtURch/E65oAwVDBRAGktZABpxrDWUYQGQMIUpAXGuoerBALJcFyAyoSmt0LUhGGcCsgHJiuQwgOqH2olFgaUOYdkOQekOQAMIWqAuB4gYGBhApTFtgyuAORCgzRHIisnuR/IFsD8zziGAxjAUA "MATL – Try It Online").
### Explanation
```
x % Implicit input: n. Delete
Zy % Implicit input: M. Size as a length-two vector, [R, C]
P % Sort. Gives [S, L], where S = min(R, C) is the smallest dimension of A
: % Range from 1 to the first entry of the vector, that is, A
" % For each k in [1, 2, ... , A]
0 % Push 0
&G % Push the two inputs again: n, then M
@ % Push k
qWQB % Subtract 1, 2 raised to that, add 1, binary: gives [1 0 0 ··· 0 1] of
% length k
&+g % 2D array of pairwise additions. Convert to logical. This gives a binary
% k×k array with a frame of ones: [1 1 ··· 1 1;
% 1 0 ··· 0 1;
% ··· ··· ···
% 1 0 ··· 0 1;
% 1 1 ··· 1 1]
Z+ % 2D convolution with M, maintaining size. This counts the number of ones
% in M along all sliding frames of the above form. The result is a 2D array
+ % Add the above with n, element-wise.
7M % Push the 2D array defining the frame again. Number of nonzeros. This
% gives the frame "length", that is, the number of ones (which is 4*(k-1))
< % Less than?, element-wise. An entry equal to 0 indicates that a frame
% exists such that the number of ones in M along that frame plus n is at
% least the frame length
m % Ismember. This checks if 0 is indeed present in the above result
@* % Multiply the above by k. This will give either 0 or k
vX> % Concatenate stack contents, then maximum. This computes a cumulative
% maximum of the results for all k (each result being either 0 or k)
% End (implicit). Display (implicit)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 133 bytes
```
n=>m=>m.map(W=h=(X,w,Y,t)=>m.every((r,y)=>[...r,0].every((v,x)=>t?x%w&&y%w||x>w|y>w||(t+=1-(m[y+Y]||0)[x+X]):h(x,w,y,~n)?W=w+1:1)))|W
```
[Try it online!](https://tio.run/##VU/LbsIwELz7KywkwFaMZUs9VFSGU3vshQOgNIc0OJAqcahjSKKm/fXUD1BVyevdnZ3Zx0d6TZtMF2ezUPVBjrkYlVhV9tEqPaOtOAm0Iy3ZE4MdKK9S9whp0ts0ppRqwpI7eiWdRc26m7azWT9th6FbtUNvbUAmEnyBqriP9skwMBx30S7ByxPqbPee/Ci83oo24kuOMR62o5afl0JLNM@bOaZapoeXopSbXmWIYWrqjdGFOiJMm3NZGDR5U29qgmle6@c0O6EGihX8AhCW0sAYKgLtrhVMoIDNn2SCnyxFWTBSLqpsFA73endfk/j89VK9S409P6tVU5eSlvUR5UhhVDn8G48PgHHGOQPMe8CdY4BbiHFbcwEAj6EM7sXAdDHzPOD0/w34Jt6Abwu81JG5q7vvrmehGQ8gDwPCnKC7SRm7Lch/AQ "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 134 bytes
```
n=>m=>m.map(W=h=(X,w,k,Y)=>m.map((r,y)=>r.map((v,x)=>k?h(x,w,q=t=0,y):x%w&&(y-Y)%w||x>w|y<Y|y>Y+w||++q<w*4|(t+=!r[x+X])>n?0:W=w+1)))|W
```
[Try it online!](https://tio.run/##VU9Nb8IgGL7zK5iJCmslkHhYnNTTdtzFgzbqoatUO1uqtNo26357x4dmWQK87/P1Al/RLSpjlZ6riSz2ok94L3mQ60Xy6IxW/MjR2q/9kx/iB4mU32qgHLj5jQanxRE12nfhFadanjXDejRC7STEw7rrmqDu2nnYtUHoaeh5l3n9PO1Q5fEntWm89Q4HckFnK157DGPcrXolLtdUCTROyjEmSkT79zQTy1bGiGJSFctKpfKAMCnPWVqhwVZu5QCTpFBvUXxEJeQB/AYQZqKCGyh9SAjJ4Q5yWP5FBvhVW6QmPWm6XHfukza/0ZlyZ/HHNf8UClt/XMiyyATJigNKkMQoN/wP7qeAMsoYBdRWwEyhgGmKMq2ZBoAXJ4OH6Jymp9YHTP7/BnaI3cCOBTZqzMzo5njkqRvGHMncBe4el7tHKb0/kP0C "JavaScript (Node.js) – Try It Online")
Modified from Arnauld's
# [JavaScript (Node.js)](https://nodejs.org), 156 bytes
```
M=>n=>M.map((_,i)=>M.map((N,y)=>N.map((c,x)=>R=M.map((_,j)=>W-=j<i&&N[x+j]+M[y+i][x-~j]+M[y-~j][x]+M[y+j][x+i],W=4*i+!i*!c)&&W<=n?i+1:R),M.push([])),R=0)&&R
```
[Try it online!](https://tio.run/##fZG9boMwFIX3vkUWZMcG2VKGqIqTLRsMLAyWVSEStUYpoNBGZMmr02t@HKNAhcB8@NxzL8d5ekvr7KqrH78oT@f2KNpQ7AuxD4PvtELog2psIaJ3gKiHjDYAsbDCHDDxRb7TnhfJhuSKhPJOtJKN/@jBrLLpv5s32KSJ2Kw1Wen1KsOel@xEcdCEv8eYhkH1W38hqTCmsWCwG7dZWdTl5Rxcyk90RFIyyqm54akokGUgbol11KkMd0o@XEwpjDYYv71aD@WD3DVyWzDbfLQHw@2C4Tjl6wpFbKaI2068d14SLTpYez63afp394JgksAY6r9zzEViS5@RPpXcDXUSsRv@ZAB7jtw5cfMHjJm52j8 "JavaScript (Node.js) – Try It Online")
I don't know what I'm doing...
```
M=>n=> // Unupdated
M.map((_,i)=>
M.map((N,y)=>N&&
N.map((c,x)=>
R=M.map((_,j)=>
W-=j<i&&
N[x+j]+
M[y+i][x-~j]+
M[y-~j][x]+
M[y+j][x+i],
W=4*i)|i|c|n&& // When i=0
// Special consider:
// Here is 1, or
// n>0
W<=n?i+1:R),M.push(0)),R=0)&&R
// So Z[y+i] isn't undefined
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 63 bytes
```
KEVUQVUhQVhS,-lQN-lhQHIgKsm!|*F*V-Rbdd@@Q+Nhd+Hed^Uhb2=eS,Zhb;Z
```
[Try it online!](https://tio.run/##K6gsyfj/39s1LDQwLDQjMCwjWEc3J9BPNycj0MMz3bs4V7FGy00rTDcoKSXFwSFQ2y8jRdsjNSUuNCPJyDY1WCcqI8k66v//6GgDHUMdEAaSsTpAHpwP5BnCeQZgHlgViA9WaQiFBrGxXCYA "Pyth – Try It Online")
Expects array of arrays of booleans and \$n\$ in that order.
### Explanation
```
# implicitly assign Q = eval(input())
KE # assign K = eval(input())
VUQ # for N in range(len(Q)):
VUhQ # for H in range(len(Q[0])):
VhS,-lQN-lhQH # for b in range(1+max(len(Q)-N, len(Q[0])-H)):
m ^Uhb2 # map range(b+1) x range(b+1) to lambda d (look at coordinates in a square of size b+1)
!| # neither of the following are true
*F*V-Rbdd # d[0]*d[1]*(d[0]-b)*(d[1]-b) (coordinates are in the middle of the square)
@@Q+Nhd+Hed # Q[N+d[0]][H+d[1]] (coordinates are already a 1 in Q)
IgKs # if K >= (the sum of this map):
=eS,Zhb # Z = max(Z, b+1)
;Z # after all loops complete, output Z
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
¬ẆZṡLƊ€Ẏ.ị$€JṖḊƊ¦FS>ʋÐḟẈṀ
```
A dyadic Link that accepts the matrix, \$M\$, on the left and the maximal toggle count, \$n\$, on the right and yields the side length of the largest attainable square.
**[Try it online!](https://tio.run/##y0rNyan8///Qmoe72qIe7lzoc6zrUROQ06f3cHe3CpDp9XDntIc7uo51HVrmFmx3qvvwhIc75j/c1fFwZ8P///@jow11DMAQSMdy6USDGQgunKNjiOCCBKBcQwgHptgQWTEWo6ACyFywUbH/LQE "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///Qmoe72qIe7lzoc6zrUROQ06f3cHe3CpDp9XDntIc7uo51HVrmFmx3qvvwhIc75j/c1fFwZ8P/o5Mf7lz8qHHfoW2Htj3cvQWo@tDWhztXhR1e7hAG5ACR5v//BoYGhoYGXAZgmssQRBlwGQKFDAy5gCIgORMuiDQXTBKiEsQ2AKuzACkwQMVcIEPAGMSEaAbThiAuQrMBxCRDiKAhxHSIJRBNUH0GBlDXQVQCAA "Jelly – Try It Online").
### How?
Toggles all bits of \$M\$ and extracts all possible square sub-matrices. Filters out any which have more than \$n\$ ones in their border, and then gets the length of the longest remaining one (or zero).
```
¬ẆZṡLƊ€Ẏ.ị$€JṖḊƊ¦FS>ʋÐḟẈṀ - Link: list of lists of 1s and 0s; M, integer, n
¬ - logical NOT (M) -> toggle all bits of M
Ẇ - get all contiguous sublists of rows of that
€ - for each (sublist, s, of rows):
Ɗ - last three links as a monad - f(s):
Z - transpose (s)
L - length (s)
ṡ - all sublists of (transposed s) of length (length (s))
-> all full height square sub-matrices from s
Ẏ - tighten to a list of all square-submatrices
Ðḟ - filter discard those for which:
ʋ - last four links as a dyad - f(sub-matrix, n)
€ ¦ - sparse application...
Ɗ - ...to indices: last three links as a monad - f(sub-matrix):
J - range of length
Ṗ - pop
Ḋ - dequeue -> [2,3,...,length-1]
$ - ...action: last two links as a monad - f(sub-matrix):
. - 0.5
ị - index into (sub-matrix) -> last and first entries
F - flatten
S - sum
> - is greater than (n)?
Ẉ - length of each (remaining sub-matrix)
Ṁ - maximum (or 0 if empty)
```
---
Note: the second `€` is necessary, even though all of the test cases pass without it (e.g. [this](https://tio.run/##y0rNyan8///Qmoe72qIe7lzoc6zrUROQ06f3cHe3itfDndMe7ug61nVomVuw3anuwxMe7pj/cFfHw50N////j4421DHQMYzl0kFlGMRyxf43AgA) should return `2` not `3`).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 61 bytes
```
NθWS⊞υι≔LυζW⬤υ⬤κ›⁻∨×⁴⊖ζ¹θΣ⭆υ⎇№…λ⁺λζπ✂ξν⁺νζ∨∨⁼πλ⁼π⁺λ⊖ζ⊖ζω≦⊖ζIζ
```
[Try it online!](https://tio.run/##bVDbSgMxEH3PV@RxAhES6FufShURrC62PxDXYRvMTndzsdqfXyfdSkUMGSY5Z86ZYdq9i@3BhWl6oKHkp9K/YoRRLcVx7wNKOMPbHD11oJRsStpD0dJzxSol3xE8InWZQaXl6apbhVDranrX8j6iy2y88VQSPEfY@R4TLLS8xTZij5TxDU6KPSzHyLEtPcx9N26oVjuM5OIXrA@FMrw46hCClk1gx1B7s2iowuBbhE8t6UJSJbXkrnzvxuJCgkHLwNj192PzZx71H3JU85E82WUJv4rmNTQ8eYa1S7mKltO0EMYaa40w5yxsTUZYhoxlrj7EdPMRvgE "Charcoal – Try It Online") Link is to verbose version of code. Takes `n` as the first input and then the binary matrix `M` as a list of newline-terminated strings. Explanation:
```
Nθ
```
Input `n`.
```
WS⊞υι
```
Input `M`.
```
≔Lυζ
```
Start with the height of `M` as the current square size.
```
W⬤υ⬤κ›⁻∨×⁴⊖ζ¹θΣ⭆υ⎇№…λ⁺λζπ✂ξν⁺νζ∨∨⁼πλ⁼π⁺λ⊖ζ⊖ζω
```
For each possible cell of `M`, try to slice a square of the current size out of `M`, count the number of `1`s on its border, and while none of the candidate squares have enough `1`s...
```
≦⊖ζ
```
... decrement the square size.
```
Iζ
```
Output the final square size.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 116 bytes
```
f(a,n)=for(k=l=0,min(#a,#a~),matrix(#a~-k,#a-k,i,j,sum(s=0,k,sum(t=0,k,!(s*t*(k-s)*(k-t)+a[i+s,j+t])))<=n)&&l=k+1);l
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVFBasMwEKTXvkJJIGjjNUjQQ0BxP-KKIgouimTX2Aq0l3ykl1xK39S-prIkywk9aJnZ3dlZSZ_fvRr082t_uXydXFPuf1xDFXZQNW8DNZWtGLa6oxuFG3UGbJUb9Lun59L4jA8ajzieWjr6ThOQC2hFx53bUVOOMEUHhap1MeKxcBIADlUH262tTMFB2Oj9e9eqvrcfVJHykfSD7pyH64msyYuyljZIFACSuq4ZcpyOj4JhZoJnzASP9YmJ2Bu4RPIgpyFZJ241yySW5ifsVfusjL430ddYqPM0gQfNnMtOcUuf5bnyzyt1zRsuPXzZ8Wrfp_vlHlce6fbLqwRXxpiUEF99_vk_)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 40 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
U˜āR.Δ…€üÿD'øý.V€`ε4Fćˆíø}¯˜_OXs@´}à}Dd*
```
Since there isn't a 05AB1E answer yet, I'll just create my own.
Inputs in the order \$n,M\$.
[Try it online](https://tio.run/##yy9OTMpM/f8/9PScI41BeuemPGpY9qhpzeE9h/e7qB/ecXivXhiQm3Buq4nbkfbTbYfXHt5Re2j96Tnx/hHFDoe21B5eUOuSovX/vwVXdLSBjoGOIQjH6kRDWToGQLYhlG0IZhvAxSFqQOpjAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmVCs5JlXUFpSbKWQZ6tkb6@kkJiXouBrq6TjdWi3DpeSf2kJUNZKQcm@MuHQyuL/oafnHGkM0js35VHDskdNaw7vObzfRf3wjsN7D60r1gsDiiSc22ridqT9dNvhtYd31B5af3pOvH9EscOhLbWHF9S6pGj91zm0zf5/dLSJTnS0gY6hDggDyVgdIA/OB/IM4TwDMA@sCsQHqzSEQoPY2FgdhWgLsGFQDVAFyFqRDTWAWwczEGyEAdQImEswabgyQ7hphjDdhmBhJMthPoBKGxgYQFVgcQBcNcIDCJWGyF5A8RCyV1HshIeTIVKIAgEA).
**Explanation:**
```
U # Pop and store the first (implicit) input-integer in variable `X`
˜ # Flatten the second (implicit) input-matrix
ā # Push a list in the range [1,length]
R # Reverse it to [length,1]
.Δ # Pop and find the first value that's truthy for
# (or -1 if none are truthy):
…€üÿD'øý.V€` '# Get a list of all overlapping block of size y×y
# (where `y` is the current integer):
…€üÿ # Push string "€üÿ",
# where `ÿ` is automatically replaced with the current integer
D # Duplicate it
'øý '# Join the two strings on the stack with "ø" delimiter
.V # Evaluate and execute it as 05AB1E code:
€ # Map over each row of the (implicit) input-matrix
üy # Get all overlapping lists of this row of size `y`†
ø # Zip/transpose; swapping rows/columns
€ # Map over each list of lists
üy # Get all overlapping lists of these row of size `y`†
€` # Flatten this list of lists of blocks one level down
ε4Fćˆíø}¯´˜ # Leave just the borders of each y×y block:
ε # Map over each block:
4F # Inner loop 4 times:
ć # Extract head; pop and push remainder-matrix and first row
# separately to the stack
ˆ # Pop and add this first row to the global array
íø # Rotate the matrix once clockwise:
í # Reverse each inner row
ø # Zip/transpose; swapping rows/columns
}¯ # After the loop: push the global array
˜ # Flatten it
_ # ==0 check (0 becomes 1; everything else becomes 0)
O # Sum to get the amount of 0s in this block's borders
X # Push the first input from variable `X`
s@ # Check amountOfZeros <= `X`
´ # Empty the global array for the next iteration
}à # After the map, do an `any` check by popping and pushing the max
}Dd* # After the find first: fix a potential -1 to 0†:
D # Duplicate the integer
d # Pop the copy and do a non-negative check (1 if >=0; 0 if <0)
* # Multiply the two together
# (after which the result is output implicitly)
```
We have to do the `}Dd*` instead of just lowering the `[length,1]` ranged list to `[length,0]`, because `ü0` would give an error.
] |
[Question]
[

Imgur is a free image hosting service. Many people use it. Here is an example of an imgur link: <https://i.stack.imgur.com/II8CA.png>. Write a program that continually outputs random (valid) imgur links. For example, here is some sample output of my progam (not shown because it contains some tricks you will have to figure out yourself):
```
http://i.imgur.com/uFmsA.png
http://i.imgur.com/FlpHS.png
http://i.imgur.com/eAbsZ.png
http://i.imgur.com/lEUsq.png
http://i.imgur.com/RuveH.png
http://i.imgur.com/BoEwB.png
http://i.imgur.com/HVFGQ.png
http://i.imgur.com/PZpMg.png
http://i.imgur.com/DezCY.png
```
Helpful hints:
* When imgur was new, 5-letter links were used.
* When imgur was new, numbers weren't used.
* You can use this to your advantage: only find 5-letter link images with only letters. That is what my program does.
* Also, all images are saved as `.png`.
Requirements:
* Continually output random imgur links
* Links considered sufficiently "random" if 50 are outputted with no repeats
* When visited, links must be an image
* Links must start with `http://i.imgur.com/` and end with `.png`
* Score is amount of characters
I did it in Java (TERRIBLE for golfing) in 452 chars. Not shown here because it contains some tricks you will have to figure out for yourself!)
[Answer]
**HTML (152)**
```
<img src=x
onload=console.log(s);g()
onerror=g=function(){s='http://i.imgur.com/'+Math.random().toString(36).substr(2,6)+'.png';event.target.src=s};g()>
```
This logs all found images on the JavaScript console using `console.log()`. Works in all tested browsers (Firefox, Chrome, IE9, Safari and Opera).
The fun part is that all sorts of funny images are flashing up for the blink of an eye :).
[Try it!](http://jsfiddle.net/zR4AS/show/) (jsFiddle wraps this into a more complete HTML page, but browsers also accept the single element.)
Props to the [amazing random string method](https://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript/8084248#8084248) by [doubletap](https://stackoverflow.com/users/1040319/doubletap)!
**Where can I see the JavaScript console and the logged images?**
* *Firefox:* Press Control-Shift-K (Command-Option-K on the Mac). Unselect the Net, CSS and JS buttons there, only select the Logging button.
* *Opera:* Press Control+Shift+i, select the Console tab.
* *Chrome:* Press Control+Shift+i, select the Console tab. On the bottom, select Logs.
* *Safari:* Basically like Chrome, but make sure first that [Safari's developer tools are activated](http://developer.apple.com/library/safari/#documentation/AppleApplications/Conceptual/Safari_Developer_Guide/1Introduction/Introduction.html#//apple_ref/doc/uid/TP40007874-CH1-SW4). Then press Control+Alt+C (on Windows, not sure on the Mac) instead of Control+Shift+i, select the Console tab. On the bottom, select Logs.
* *IE:* Press F12, select the console tab.
[Answer]
## Perl (93 + 4 = 97)
Using imgur's own [random](https://imgur.com/gallery/random) mechanism to get **their** image URLs, which aren't png URLs most of the time:
```
$ perl -Mojo -E 'say+g("http://imgur.com/gallery/random")->dom->at("[rel=image_src]")->attrs("href")for+1..50'
http://i.imgur.com/7cNoA.jpg
...
```
(You need [Mojolicious](http://mojolicio.us) for this.)
[Answer]
## PHP 5.4, 76 characters
URLs are generated in sequential order using only uppercase letters and never repeat, meeting the letter of the specification.
```
<?for($t=@ZZZZ;$t++;)file($u="http://i.imgur.com/$t.png")[0]>@F&&print"$u
";
```
[Answer]
# Perl (87)
```
perl -pe's/\W//g;$_="http://i.imgur.com/$_.png\n";$_=""if`curl $_`=~/^</'</dev/urandom
```
Finding images with uppercase, lowercase and digits from 0 up to any characters,
some day.
[Answer]
### *Mathematica*, 108
White-space added.
```
While[True,
Import@# /. _Image :> Print@# &[
"http://i.imgur.com/" <> "a" ~CharacterRange~ "z" ~RandomChoice~ 5 <> ".png"
]
]
```
[Answer]
## Python (~~174~~ ~~158~~ 156)
I want shorter module names in Python. Also an easier method of getting random letters. :)
```
import urllib,random
while 1:a='http://i.imgur.com/%s.png'%''.join(chr(random.randint(65,90))for i in'AAAAA');print('File'not in urllib.urlopen(a).read())*a
```
Explanation:
The modulus operator on a string is the formatting command, in this case it replaces '%s' in the string with 5 random uppercase letters
`a` is the website name (type `str`)
`('File'not in urllib.urlopen(a).read())` is True when 'File' (from 'File not found!') is **not** found in the the HTML of the URL. (type `bool`)
`bool` \* `str` = `str` if `bool` = True, so it will only output `a` if 'File' is not found in the HTML code.
[Answer]
# Bash (129, 121) (117, 109)
I've got two versions: an iterative and an endless recursive one (which will slowly eat up all memory).
Both versions check if there actually is a PNG file present (jpg's, gif's and other file types are ignored).
Iterative(old) (129):
```
while true;do u=http://i.imgur.com/$(tr -dc a-zA-Z</dev/urandom|head -c5).png;curl $u -s 2>&1|head -c4|grep PNG$ -q&&echo $u;done
```
Recursive(old) (121):
```
:(){ u=http://i.imgur.com/$(tr -dc a-zA-Z</dev/urandom|head -c5).png;curl $u -s 2>&1|head -c4|grep PNG$ -q&&echo $u;:;};:
```
**Note**:
There might be a compatability issue with grep. My grep manual states that `-s` silents grep's output but it does nothing. However, using `--quiet`, `--silent` or `-q` instead works.
**EDIT:**
Using content headers now after reading <https://codegolf.stackexchange.com/a/10499/7195> :)
Iterative (117):
```
while true;do u=http://i.imgur.com/$(tr -dc a-zA-Z</dev/urandom|head -c5).png;curl $u -sI|grep image -q&&echo $u;done
```
Recursive (109):
```
:(){ u=http://i.imgur.com/$(tr -dc a-zA-Z</dev/urandom|head -c5).png;curl $u -sI|grep image -q&&echo $u;:;};:
```
[Answer]
# Python, 361 355 334 332 322 314 characters
A little obfuscated, nothing too difficult. May result in unusually high density of cat pictures, you have been warned.
```
import json as j,urllib as o,time as t;a=0
while 1:
q="i.imgur";y,p=('data','children');r="njj";h="erqqvg.pbz/";u="uggc://"+h+"e/"+r;c=j.loads(o.urlopen(u.decode('rot13')+".json?sorted=new&after=%s"%a).read())[y]
for s in c[p]:
f=s[y];w=f['url'].strip('?1')
if w.find(q)!=-1:print w
a=c['after'];t.sleep(3)
```
Output:
```
http://i.imgur.com/u3vyMCW.jpg
http://i.imgur.com/zF7rPAf.jpg
http://i.imgur.com/aDTl7OM.jpg
http://i.imgur.com/KONVsYw.jpg
http://i.imgur.com/RVM2pYi.png
http://i.imgur.com/tkMhc9T.jpg
http://i.imgur.com/KxUrZkp.gif
http://i.imgur.com/mnDTovy.jpg
http://i.imgur.com/WpuXbHb.jpg
http://i.imgur.com/qZA3mCR.jpg
http://i.imgur.com/AxMS1Fs.png
http://i.imgur.com/TLSd571.jpg
http://i.imgur.com/VfMhLIQ.jpg
http://i.imgur.com/Wu32582.jpg
http://i.imgur.com/hrmQL2F.jpg
http://i.imgur.com/Clg8N.jpg
http://i.imgur.com/7Wsko.jpg
http://i.imgur.com/Rhb0UNx.jpg
http://i.imgur.com/LAXAf45.gif
http://i.imgur.com/jhOLJ9B.jpg
http://i.imgur.com/FQ9NeAl.jpg
http://i.imgur.com/oqzf6tE.jpg
http://i.imgur.com/rnpXs1A.jpg
http://i.imgur.com/DfUIz6k.jpg
http://i.imgur.com/orfGA5I.jpg
http://i.imgur.com/wBT7JNt.jpg
http://i.imgur.com/RycK1m2.jpg
http://i.imgur.com/7j21FIR.jpg
http://i.imgur.com/z2tVnNC.jpg
http://i.imgur.com/mnsAGuF.jpg
http://i.imgur.com/vIZM1NY.jpg
http://i.imgur.com/JT3XRI4.jpg
http://i.imgur.com/SNpwTmp.jpg
http://i.imgur.com/u9ynLb9.jpg
http://i.imgur.com/DrFWsBP.jpg
http://i.imgur.com/rU6oyup.jpg
http://i.imgur.com/XxBD5nl.jpg
http://i.imgur.com/d09qQzP.jpg
http://i.imgur.com/vvPSbqI.jpg
http://i.imgur.com/1hdfobQ.jpg
http://i.imgur.com/4LLC6Vs.jpg
http://i.imgur.com/RfasxO2.jpg
http://i.imgur.com/BBcpOos.jpg
http://i.imgur.com/zMH8mgG.jpg
http://i.imgur.com/7g8k2Ww.jpg
```
[Answer]
## R, 182 characters
```
library(httr);while(0<1){s=paste("http://i.imgur.com/",paste(sample(c(LETTERS,letters),5),collapse=""),".png",sep="");if(HEAD(s)$headers$'content-type'=='text/html')'' else print(s)}
```
[Answer]
# Python, 153 chars
```
import string as s,random as w,requests as r
while 1:
t='http://i.imgur.com/%s.png'%''.join(w.sample(s.letters,5))
if'not'not in r.get(t).text:print t
```
While this works, it is bloody slow and might take many seconds before returning any output.
Inspired by @beary605's solution - he saved me a bunch of characters as I was planning to check for image by content-type header.
[Answer]
# Ruby (103 chars)
```
require"open-uri";loop{u="http://i.imgur.com/#{rand(1e9).to_s(36)[0,5]}.png";open u rescue next;puts u}
```
[Answer]
# Bash/command-line tools, 72 chars
Borrowing @memowe's [clever technique](https://codegolf.stackexchange.com/a/10503/11259):
```
curl -sL http://imgur.com/gallery/random|grep e_sr|cut -d\" -f4;exec $0
```
This achieves a continuous loop by re-execing itself within the same process space.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 41 bytes
```
ØẠẊs5Ḣ
“http://i.imgur.com/”;¢;“.png”ṄƲÐḶ
```
How?
```
ØẠẊs5Ḣ : Helper Link
ØẠ : Upper and Lowercase Alphabet
Ẋ : Shuffle
s5 : Split Into Lengths of 5
Ḣ : Head; pop from front of list
-----------------------------------------------------------------------------------------
“http://i.imgur.com/”;¢;“.png”ṄƲÐḶ : Main Link
“http://i.imgur.com/” : String Literal
¢ : Previous link as a nilad.
“.png” : String Literal
; ; : Concat
Ṅ : Print with a linefeed
Ʋ : Last four links as a monad
ÐḶ : Loop; Repeat until the results are no longer unique.
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FjftD894uGvBw11dxaYPdyzietQwJ6OkpMBKXz9TLzM3vbRILzk_V_9Rw1zrQ4usgZJ6BXnpQN7DnS3HNh2e8HDHtiXFScnFUMNghgIA)
] |
[Question]
[
Given as input a positive nonzero integer `n` >= 10 and a sequence of digits `0-9` (which may be taken as a string or a list), find the first contiguous subsequence of digits in the sequence that sums to `n` and output the start and end indexes. You may use zero- or one-based indexing. If no such subsequence exists, your program may output any *constant* value.
## Examples
These examples use zero-based indexing.
```
Input: 10 123456789
Output: 0 3
Input: 32 444444444
Output: 0 7
Input: 15 123456789
Output: 0 4
Input: 33 444444444
Output: No solutions
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program wins!
[Answer]
# Excel (ms365), 155 bytes
Assuming list as input and 0-indexed output:
[](https://i.stack.imgur.com/era3A.png)
Formula in `C1`:
```
=LET(x,TOCOL(B:B,1),y,COUNT(x),REDUCE("No solutions",SEQUENCE(y),LAMBDA(a,b,IFERROR(HSTACK(y-b,y-b+MATCH(A1,SCAN(0,DROP(x,y-b),LAMBDA(c,d,c+d)),0)-1),a))))
```
The idea here is to use `SCAN()` to iterate from each element in reversed order in column B and `MATCH()` the value in `A1` against each resulting array. If found, then `HSTACK()` both the current iteration and the position the element is found.
Unfortunately this process is rather verbose in Excel, but fun to attempt this challenge nonetheless.
---
[](https://i.stack.imgur.com/f7aiC.png)
[](https://i.stack.imgur.com/P6Rtn.png)
[](https://i.stack.imgur.com/rycXl.png)
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), 126 bytes
```
i01:}r[l0$>:?v~]}r4[{:}]=?v1+$:@$:@l5-$-)?v20.
/[-2lr@@+@:$@/ ;n+oan:$/-3lr1;?=-2l:+1~/
\}]r1-a0. \[}]r20.
```
[Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaTAxOn1yW2wwJD46P3Z+XX1yNFt7On1dPT92MSskOkAkOkBsNS0kLSk/djIwLlxuL1stMmxyQEArQDokQC8gICAgO24rb2FuOiQvLTNscjE7Pz0tMmw6KzF+LyBcblxcfV1yMS1hMC4gICAgICAgICAgICAgICAgIFxcW31dcjIwLiIsImlucHV0IjoiMTEiLCJzdGFjayI6IjEsIDUsIDYiLCJzdGFja19mb3JtYXQiOiJudW1iZXJzIiwiaW5wdXRfZm9ybWF0IjoibnVtYmVycyJ9)
## Explanation
[](https://i.stack.imgur.com/wBkMA.png)
Takes the array of characters as the initial value of the stack and the target as the input over STDIN. Outputs nothing if no solution exists, and an exclusive range if it does.
`i01` push the target value, the start of the range, and the length to the stack.
`:}r[l0$>:` Push the top "length" elements of the stack to a new stack. Set it's length, that's the amount of elements we want to compare.
`@$:@+@@rl2-]}]r1-a0.` This adds the top of the stack to the accumulator, rotates the stack, then subtract one from the number of remaining rotations necessary.
`~]}` pop 0, the remaining number of rotations, and combine the stack back with the previous. Now the sum of the top N elements of the input are on top of the stack.
`r4[{:}]=` Copy the target sum to the end of the input.
```
=?v
\$:nao+n;
```
If the sum equals the target, output.
`1+$:@$:@15-$-)?v` Add one to the length. If it's greater than the remaining length of the list go down.
`~1+:l2-=?;` Add one to the starting value. If it's greater than the length of the input exit.
`1rl3-[}]r` Set the length back to 1. Shift the rest of the stack over one so it starts at the second position.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ā<ã.Δ¹sŸèOQ
```
Inputs in the order `sequence, n`.
0-based output; will output `-1` if no result can be found; and `[i,i]` if `n` is a single digit that's present in the input-`sequence`.
[Try it online](https://tio.run/##AScA2P9vc2FiaWX//8SBPMOjLs6UwrlzxbjDqE9R//8xMjM0NTY3ODkKMTA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6KGV/4802hxerHduyqF1xUd3HJ55eIV/ROD/Wp3/0dGGRsYmpmbmFpY6hgaxOtEmMKBjbITKNQZyEYpNYmMB).
**Explanation:**
```
ā # Push a list in the range [1, length of the first (implicit) input sequence]
< # Decrease each by to make it a 0-based [1,length)
√£ # Cartesian power of 2 to get all possible pairs of this list
.Δ # Find the first pair that's truthy for:
¬π # Push the first input-sequence again
s # Swap so the current pair is at the top
≈∏ # Pop and push a list in the range of this pair
√ô # Uniquify this list (in case the pair was [a,a])
è # Index each into the first input-sequence
O # Sum these digits together
Q # Check if this sum is equal to the second (implicit) input
# (after which the result is output implicitly)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `g`, 11 bytes
```
ẏ:Ẋ'ƒṡ¹İ∑⁰=
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJnIiwiIiwi4bqPOuG6iifGkuG5ocK5xLDiiJHigbA9IiwiIiwiMTIzNDU2Nzg5XG4xMCJd)
A simple little approach.
## Explained
```
ẏ:Ẋ'ƒṡ¹İ∑⁰=
ẏ: # The range [0, len(input)), twice.
Ẋ # cartesian product of the two lists and sort to get the first
' # get all items of that where
ƒṡ # the list turned into an inclusive range between the two numbers
¹İ # indexed into the sequence of numbers
∑⁰= # summed equals n
# g flag gets the smallest pair
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 75 bytes
```
f=lambda v,l,a=0,b=1:v==(q:=sum(l[a:b]))and(a,b-1)or f(v,l,a+(q>v),b+(q<v))
```
[Try it online!](https://tio.run/##VY7NDoIwEITvPMXGC11dExB/sLG8CPHQKkQSaGupjT491r@De9nk29mZsQ9/MboorZumVvRyUGcJgXqSIiMlch6EYFcuxtvA@lpydUSU@swkqWWOxkHL3uoFu1YBScV9CIiTb0Y/goCa5RlBmq@K9Wa7K/cpErBiFdH6Nx9U/KNj0kbzQA46DW8znoB3D25dp33MdJTCsoKUXgXq@SAtiwdyGAsm0NxPjfVf8UwbGE1/852JXobPKL7j9AQ "Python 3.8 (pre-release) – Try It Online")
Switched to a list of integers instead of a string for -9 bytes
old:
```
f=lambda v,l,a=0,b=1:v==(q:=sum(map(int,l[a:b])))and(a,b-1)or f(v,l,a+(q>v),b+(q<v))
```
[Try it online!](https://tio.run/##VY7NDoIwEITvPMXGC924JCL@YGN5EeOhVYgk0JZSG3l6rH8H9zLJl5nZsZO/GV2U1s1zIzrZq6uEQB1JsSIlch6EYAMX471nvbSs1Z66k@TqjIhSX5kkleVoHDTsHVuyoQpIKuoxIM6@Hv0IAk4sXxGk@brYbHf78pAiASvWEW1@90HFPzonTSwP5KDV8C7jCXg3cevilvjTUQpZBSm9BjjEBOrHpbb@a1hoA6Pp7r41MW/4gl6u@Qk "Python 3.8 (pre-release) – Try It Online")
Takes an integer and a string as input. Returns a tuple with start and end index if a solution is found, and an error if not.
[Answer]
# JavaScript (ES6), 64 bytes
*-1 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)*
Expects `(n)(array)`. Returns either `[start, end]` or *false*.
```
n=>a=>a.some((_,i)=>a.some((v,j)=>j<i||(s-=v)?0:o=[i,j],s=n))&&o
```
[Try it online!](https://tio.run/##fc5NDoIwEAXgvafoirTJCLQFQWP1Bl6AEEMQTAlSY5EVd68NEH@6cGY2L/leMk0xFLp8yHu/7tSlMrUwnTgU9nytbhXGZ5DkkwZobGr2chyxXouBHMOdEpmEJgctOkI8T5lSdVq1ld@qK64xDQnOKDDgEEEMG0gghW1OCAoCFCK@@uWcWR6Bs2@euJz/4SeFLH320lacHuXTV3T6KQU679LjKHI4ihce5@hrZs4QMy8 "JavaScript (Node.js) – Try It Online")
### Commented
```
n => // n = target sum
a => // a[] = array of digits
a.some((_, i) => // for each digit at index i in a[]:
a.some((v, j) => // for each digit v at index j in a[]:
j < i || // if j is less than i
(s -= v) // or subtracting v from s
? // does not result in 0:
0 // do nothing
: // else:
o = [i, j], // set o = [i, j] and exit
s = n // start with s = n
) // end of inner some()
) // end of outer some()
&& o // if successful, return o[]
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ðÊï æÈrõ xgU ¶V
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8MrvIObIcvUgeGdVILZW&input=WzEsMiwzLDQsNSw2LDcsOCw5XQoxMA)
```
ðÊï æÈrõ xgU ¶V :Implicit input of digit array U and integer V
√∞ :0-based indices of elements of U that are truthy under
Ê : Factorial
ï :Cartesian product with itself
√¶ :First element/pair that returns true when
È :Passed through the following function
r : Reduce by
õ : Inclusive range
x : Reduce by addition after
gU : Indexing each into U
¶V : Is equal to V?
```
[Answer]
# R 4.1, ~~78 bytes~~ ~~71 bytes~~ 65 bytes
## v1.2 65 bytes
-5 bytes thanks to [pajonk](https://codegolf.stackexchange.com/questions/256556/find-the-first-run-of-numbers-summing-to-n/256617?noredirect=1#comment577984_256617):
1. -4 for pointing out that `F <- F + 1;k <- m[, F];sum(s[k:k[2]])` can be expressed as `sum(s[(k <- m[, F <- F + 1]):k[2]])`. This also means you can lose the curly braces as the expression is on one line, and you do not need semi-colons.
2. -1 because `while(a!=b)` can actually be expressed as `while(a-b)`. This is safe as negative numbers are also `TRUE` when coerced to `logical`.
(And also -1 byte by pointing out I had miscounted.)
```
\(s,n,m=combn(seq(s),2)){while(sum(s[(k=m[,F<-F+1]):k[2]])-n)0
k}
```
[Attempt This Online!]<https://ato.pxeger.com/run?1=m72waMGSNAUb3aWlJWm6FjcdYzSKdfJ0cm2T83OT8jSKUws1ijV1jDQ1q8szMnNSNYpLczWKozWybXOjddxsdN20DWM1rbKjjWJjNXXzNA24smuhBrkpK4SkFpcoJCcWpxZzpWkYWlnqKBgaaAKZRakFGiZgjo6CsZEmXNIUQ9JYE2LaggUQGgA>)
## v 1.1 71 bytes
```
\(s,n,m=combn(seq(s),2)){while({F=F+1;k<-m[,F];sum(s[k:k[2]])!=n})0
k}
```
-7 bytes thanks to [Giuseppe](https://codegolf.stackexchange.com/questions/256556/find-the-first-run-of-numbers-summing-to-n#comment567896_256617)
Two changes:
1. Not replacing `seq()` with the unary `-` as it's only being used once (I was using it twice before and failed to notice that was no longer the case).
2. Replacing `j` with `F` is yet another ludicrous thing that R allows you to do that I would never have tried in the vein of [these](https://codegolf.stackexchange.com/questions/4024/tips-for-golfing-in-r/162674#162674) coercion tips by @rturnbull (link from Giuseppe - thanks). For non-R uses, `T` and `F` are built-in aliases for TRUE and FALSE. This means you can do this:
```
T == TRUE # TRUE
F == FALSE # TRUE
F == TRUE # FALSE
F <- F+1
F == FALSE # FALSE
F == TRUE # TRUE
```
I have no idea why this is allowed in R but it's saved 5 characters compared with initialising `j`.
## v.1.0 78 bytes
```
\(s,n,`-`=seq,j=0,m=combn(-s,2)){while({j=j+1;k<-m[,j];sum(s[k:k[2]])!=n})0
k}
```
[Attempt this online](https://ato.pxeger.com/run?1=m72waMGSNAUb3aWlJWm6Fjf9YjSKdfJ0EnQTbItTC3WybA10cm2T83OT8jR0i3WMNDWryzMyc1I1qrNss7QNrbNtdHOjdbJirYtLczWKo7OtsqONYmM1FW3zajUNuLJroaa6KiuEpBaXKCQnFqcWc6VpGFpZ6igYGmgCmUWpBRomYI6OgrGRJlzSFC5pBZEz1oQYtmABhAYA)
### How?
This is a function which expects a vector, `s` and a target value `n`, as arguments. Basically it does this:
1. Uses `combn()` to create a `m`, a matrix of all possible length 2 combinations of the indices of `s`. E.g. `combn(1:5,2)` produces:
```
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 1 1 1 2 2 2 3 3 4
[2,] 2 3 4 5 3 4 5 4 5 5
```
2. Loops through the columns of this to subset `s`, using row 1 as the start index and row 2 as the end index.
3. Breaks the loop if the subset adds up to `n`. It exits with an error if there is no solution. I wasn't entirely clear if an error counts as a constant, but [this nice Python answer](https://codegolf.stackexchange.com/questions/256556/find-the-first-run-of-numbers-summing-to-n/256572#256572) behaves in the same way, which I took as a green light.
4. There are a couple of golfing tricks both from [Giuseppe](https://codegolf.stackexchange.com/a/138046/115882). Taking advantage of how `seq(s)` behaves if `s` is a vector and reassigning the unary `-` with ``-` = seq`, means we can do `m = combn(-s, 2)` instead of the positively verbose `m = combn(seq_along(s), 2)`.
The test cases are included in the footer of ATO link. Only my second Code Golf answer ever so very interested in any suggestions / improvements.
[Answer]
# [Perl 5](https://www.perl.org/) List::Util, 82 bytes
```
sub{$s=pop;($i,$j)=($_%@_,int$_/@_),$s-sum(@_[$i..$j])||return($i,$j)for 0..@_*@_}
```
[Try it online!](https://tio.run/##XZFbT4NAEIWf5VdMmmkBs70BvQhZ3XcvfdGn2mxqC4ZKF8JCjGn718WhYGPcl8mZ75zZyW4W5smk2n9hxCtdvh1Q8yzNAgtjhjubWyi7QrJYFSiHQtoMdV@Xe0vIJcaDAe5W9vGYh0WZqzYSpTmMBgMhr4U8VYFB2jIAljAeMRg7rjeZzuY3wG@BtAsrdoauw8D7PS2cXaD7D5ZqG0YtdCjpOt547k6mbg29NmkfiAPsvyxUDJNYF7R8sc6phGprc4EyaB0gasx1lsTFcNiYg0taU8AGDj2MLNHMUXaDs5xeJoJOtz/VJDc@4Iaqoqqo1ma/GU7qc61I/dmBeu/puUXyVXWYcUXPzxsH9HqAIanaeAdm@mGCD@bT4hkW92ZgnKrvNCviVOmq//hQX@S/FHHC6Xd@AA "Perl 5 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 18 bytes
```
KEhfqQs:KhTheT^UK2
```
[Try it online!](https://tio.run/##K6gsyfj/39s1I60wsNjKOyMkIzUkLtTb6P9/QwOuaEMdBSMdBWMdBRMdBVMdBTMdBXMdBQsdBctYAA "Pyth – Try It Online")
Takes n, sequence as separate inputs. Outputs [start, end] or an index error if no sequence exists.
### Explanation
```
# implicitly assign Q = eval(input())
KE # assign K = eval(input())
^ 2 # cartesian product of two copies of
UK # range(len(K))
f # filter this on lambda T
s # sum of
:KhTheT # slice K from first element of product to second element plus 1
qQ # equals Q
h # take the first element (this will give us the indices if they exist or an index error if they don't)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
J·πó2r/·ªã¬≥S= ã∆á·∏¢
```
[Try it online!](https://tio.run/##ATUAyv9qZWxsef//SuG5lzJyL@G7i8KzUz3Ki8aH4bii////WzEsMiwzLDQsNSw2LDcsOCw5Xf8xNQ "Jelly – Try It Online")
Full program, that takes a list of digits and an integer \$n\$, and outputs the 1-indexed indices, or `0` if there's no solution.
## How it works
```
J·πó2r/·ªã¬≥S= ã∆á·∏¢ - Main link. Takes a list of digits D on the left, and n on the right
J - Indices; [1, 2, ..., len(D)]
·πó2 - Cartesian square
ã∆á - Filter the indices on the dyad f([i, j], n):
r/ - Range; [i, i+1, ..., j-1, j]
ị³ - Index into D
S - Sum
= - Does that equal n?
·∏¢ - Take the first pair, or zero if there's no solution
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~90~~ 88 bytes
```
i;j;a;f(*s,n){for(a=i=-1;s[++i]*a;)for(a=n,j=i;a*s[j];)a-=s[j++]-48;*s++=!a*i-1;*s=j-1;}
```
[Try it online!](https://tio.run/##lVJtb5swEP7eX3FFSmUMaCWkayvP@zLtW/9BQJHnHB0ZcRJM1WxR/vrYgWGhXSp1Fi/2Pc/dPXdnHelSmcemKcRKKJEzbkPjH/JNxZQsZBQLOw@CIuNK@M5owpUshOJ2vsqEryJJmyDIotmd4DYI5KXiBblxK1f0OzaFqWGtCsN8OFwArdZQo60XZp6BhEN8HUIypTc5ioHAHcM6xoMXT5PZzcfbu3svhAdvNqxXp5M/4H6LusblEIJy0BPF5yjoKEkIt8TqGXpjbA36u6o4fVH/wMrRvHT/dZru77/Qe0MCxudkkECtAtYmKcwS9@R2LfrtJ7DFL9zk7KTQhw@DkY@sAqjxrc/QuEG4oXh9Azs8E2OYw27A7TkcSoJnwIE9a1uiYTsfAoj9V0G@PeU5EdeqLDealSN4jWu9/claQgi7EMZY7szmZTTAhaVYo5mc04ULHJPwX1IOrI10KWmQ46YMEbbKtnm40y67tFdXXSnzOHMWFC/cthU55swzcrIMwcrUm5Q29SD6DK1hsoSJTQ2N2XS1cld1HzH8ezPazNmo6CNgafF9Ev9D0Fkxb2o4TaVC7AbTow6psH6qDN3Mi2PzW@elerRN9PwH "C (clang) – Try It Online")
*Saved 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
Inputs a pointer to a wide charater string of the sequence and \$n\$.
Returns the first and last position in the array referenced by the input pointer or \$-1\$ if no sum exists.
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 25 \log\_{256}(96) \approx \$ 20.58 bytes
```
LRDZ!gAu1+:z0sAISz1=kAJ0~
```
Takes a list of digits, then a number. Outputs 0 if it doesn't find the subsequence.
#### Explanation
```
LRDZ!gAu1+:z0sAISz1=kAJ0~ # Implicit input
LR # range(len(input))
DZ! # Cartesian product with itself
g k # Filter for items where the following is truthy:
Au # Dump the pair onto the stack
1+ # Add one to the last one (because of how Thunno's range works)
: # Range between the two numbers
sAI # Indexed into
z0 # The first input (this will return a list)
S # The sum of this list
z1= # Equals the second input?
AJ # After the filter, get the first item of the list
0~ # If the list was empty, push 0
```
#### Screenshots
[](https://i.stack.imgur.com/1edRm.png)
[](https://i.stack.imgur.com/u5efj.png)
[Answer]
# [Desmos](https://desmos.com/calculator), 79 bytes
```
L=[1...l.length]
T=[0^{(l[I...E].total-s)^2}(I,E)forE=L,I=L]
f(s,l)=T[T.x>0][1]
```
\$f\$ returns a point `(I,E)` that has the starting index `I` and the ending index `E` as the \$x\$ and \$y\$ coordinates, respectively, and returns the answer one-indexed.
For no solution, \$f\$ returns the point `(undefined,undefined)`.
Note that because of the limitations of Desmos, this will not work for input lists longer than \$100\$ elements.
[Try It On Desmos!](https://www.desmos.com/calculator/3cyneucbqz)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/dmv2bd8yol)
[Answer]
# [C (clang)](http://clang.llvm.org/), 76 bytes
Takes a list of digits and a number as input and returns \$[start, end)\$.
```
i;j;f(*l,s,n){for(i=j=0;n<0|s/~j*n;)n-=n>0?l[j++]:-l[i++];l[1]=j;*l=n?-1:i;}
```
## How it works
```
i;j; // start and end of the sliding window, respectively.
f(*l, s, n) { // input a list of integers, its size and the number.
for( // main loop
i = j = 0; // start with i = 0 and j = 0 (empty window)
n < 0 | // the sum of elements in the window exceeds n, we will remove elements in the next iteration
s / ~j * n;) // j < l and the sum of elements does not match n
n -= // subtract from n:
n > 0 ? // if n > 0 ...
l[j++] // increase the window size.
: // else (n < 0) ...
-l[i++] // decrease the window size.
; // end main loop
l[1] = j; // l doubles as return placeholder. l[1] is the end of the window.
*l = // l[0] is:
n ? // if n != 0 ...
-1 // there was no solution, set it to -1.
: // else (n == 0) ...
i; // we found the solution, set it to the start of the window.
}
```
[Try it online!](https://tio.run/##hVJNb5tAED2bXzGiSgR4acDGie01yaHqoVKkHnvAqHJgScbdLBYLjVXX/elxd/lwoZXSkZZh5s28fTOQuAnfiMfTCemWZpbDiSTCPmR5YWG4DT0qVt5PefVr6whqCzcUt94dj7bjcbx0eYTKUx75cbilDg/FnesvkR5P71AkvEoZrGSZYv7@6dYYpDg@DHMvydOm0CkDRWk8b1BY33NMbeNggLIkF7IEXQNO986Sb6yIYgjhAOZ6/3Gy3i8@qDMzySCemnCkNYuidkomy6@yaTNG96Y/mQaz65v5wiQ6DDprwrfRxfzmehZMJ755VHHNLBSzNi3K9whMJwT8mfJT5T3QdWy/Y0nJ0k4FgKrrjusrPxvWsa4uUNhc423doq5DApyAIOA8VFlGjXpU9f3AQtXmUUBYgcQfLM@gmR6uurhdB4XxGG1odq1NqM52HozpOa0vUMhLItNqZ7WrxNimxmhXqO1mlvlJ7KpyCRcpXHC5FmatTPfZf2hqcbwRp6GIx1oBt43RqI3BDSGY91osDTST9pgwA6u3T4zVqJ59hrV1wj5X5VlZI8xpKLs/yWmmC2FAGPduY1yy/3CTf/nrifyYDDpbe/tuuLzsugcY@0tXVjBm9XZ8rJ8FK6tCqB0bx9NrkvHNozy5X0Tu4vOOY4Llbw "C (clang) – Try It Online")
[Answer]
# [Julia](https://julialang.org), ~~69~~ ~~65~~ 47 bytes
```
~=:;y^x=argmax(k->sum(x[k])==y,(q=keys(x)).~q')
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6Fjf162ytrCvjKmwTi9JzEys0snXtiktzNSqis2M1bW0rdTQKbbNTK4s1KjQ19eoK1TWh2mY6FGfklyvEaRga6ChEG-oY6RjrmOiY6pjpmOtY6FjGanLBFBgbARWY6KBBJAWGpoRMMMZhAheKIwyAmk1joQ6E-Q8A)
Uses 1-based indexing. Prints the range `1:1` if no solution exists.
* -4 bytes thanks to MarcMush: Replace `1:length(x)` with `keys(x)`
* -18 bytes (!!) thanks to MarcMush: Improve range generation
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
NθI⌊ΦEη⟦κ⌕EηΣ✂ηκ⊕μ¹θ⟧⊕↨ι⁰
```
[Try it online!](https://tio.run/##VYqxCsIwFEV3vyLjexDBqFVLN4VCh4rQURxiGujDJLZp4u/HKDh4hwOHc9UgvXpKk1LjxhjO0d61hwmrxcWTC3CSc4CWHNlooSYTcm3lCANn1wdnNbn@511@dIaU/khujVNeW@2C7sEiZwIxc8Ib/rejnDUQZyv8rkpJFEysN9titz@Uafkybw "Charcoal – Try It Online") Link is to verbose version of code. Outputs `None` if there is no solution. Explanation:
```
Nθ First input as a number
η Second input
E Map over digits
κ Current index
η Second input
E Map over digits
η Second input
‚úÇ ¬π Sliced from
κ Outer index to
μ Inner index
‚äï Incremented
Σ Take the sum
‚åï Find index of
θ First input
‚ü¶ ‚üß Make into list
Φ Filtered where
↨ι⁰ Last element
‚äï Is not `-1`
‚åä Take the minimum (first if it exists)
I Cast to string
Implicitly print
```
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 69 bytes
```
[| n s | s length iota 2 [ last2 s subseq Σ n = ] find-combination ]
```
[Try it online!](https://tio.run/##hVDLTgMxDLz3K@YHGtHdlqfgirhwQZyqHtzUaaNmk5B4D6jdr@F/@KXFqCAOCGHLcxiPRxo7spLK@Pz08Hh/jY5kZ2zq1j6S0t5WVH7pOVqu2HOJHJALi7zm4qOc9H30Nm0YIVkKFXqefeBipDCbXFKmLYlP0eg6TNk5tgKqNan7zeQwgdYBs7NPQIMWcyxwjgtc4goDhi9B2yjMf/WPYLb4z6H902EYl0dEVBx1Aset7OCTkLotEahKo3zt1/oNvL@p8hYrOB830@9vaUCsRncKdtdRRhWyezN@AA "Factor – Try It Online")
Returns a 0-based start index and 1-based end index. Returns `f` if there is no solution.
[Answer]
## C99:
```
int main() {
int x = 22;
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}, n = sizeof(a) / sizeof(int);
int i = 0, j = 0, s = 0;
while ((s < x && j < n) || (s > x && i < n))
s += s < x ? a[j++] : -a[i++];
printf("found: %d, i: %d, j: %d", s == x, i, j - 1);
return 0;
}
```
The algorithm actually takes 66 bytes:
```
inti=0,j=0,s=0;while((s<x&&j<n)||(s>x&&i<n))s+=s<x?a[j++]:-a[i++];
```
[Try it!](https://tio.run/##PY7bbsJADETf@YoRVdGu4rQQeuES4EMQD1EuxRHdVNlERQW@PfXutvhl7NHYPnn8kefDA5v81BclUtsV3DwdtwObDp8ZG6VxGUHKGWdskCTr@5ztD@JcZoSEMCe8EF4Jb4R3woKwvBGMBCz/lE2lMo3n/162dbhzP8aSnBLqINZJSHwf@VRCKYtUCCYTiaQwGtcrxNsGj72n/YIri0ge@42dcNZRdMAKcbZn6dYjn/tq5W@lxlXTm2KFx4LAQWonY0@xwVlsxxVj9sfcll3fGsd3G4Zf)
[Answer]
# [Haskell](https://www.haskell.org/), 71 bytes
```
x#y=take 1[[s,e]|i<-[[0..length x-1]],s<-i,e<-i,sum[x!!i|i<-[s..e]]==y]
```
[Try it online!](https://tio.run/##HcrRCsIgFADQX3FbDw5UctVLzC@R@yB0SZm6sWvkoH836uU8He9owRhbq8NhiluQaWtJIHzCLK09KxUxP4tnVWoAQbMMAn/QK9nadeH/SCkEMOaAllzIZttDLqfkNr6jeyh@7/tx5OTXN9PT5XobBz21Lw "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/), 77 bytes
```
x#y=take 1[[s,e]|let m=length x-1,s<-[0..m],e<-[s..m],sum[x!!i|i<-[s..e]]==y]
```
[Try it online!](https://tio.run/##JcjdCsIgFADgV3FbFwpOsh@CyCcRLw50SJna2DFysHe3qLuPzwNNGGNrdVhNgQmZtpYkui1iYclEzI/iWR21pNto90olJ/Er@oleydauC1v4FzpnzOpagpDNvIRcdglmviDcFb/2vRCc/PPN9OF4Oovh0j4 "Haskell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~58~~ 56 bytes
Returns `nil` if no subsequence is found.
-2 bytes thanks to [Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink)
```
->n,a{(b=*0...a.size).product(b).find{a[_1.._2].sum==n}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3LXTt8nQSqzWSbLUM9PT0EvWKM6tSNfUKivJTSpNLNJI09dIy81KqE6PjDfX04o1i9YpLc21t82profp7ChTcog0NdBSiDXWMdIx1THRMdcx0zHUsdCxjY7lAksZGQEkTHTQIlTQ0xaPT0BBdEmakMXYjIW5asABCAwA)
[Answer]
# [Arturo](https://arturo-lang.io), 79 bytes
```
$[n,a][l:-size a 1loop 0..l'x[loop x..l'y[if n=sum slice a x y->return[x,y]]]0]
```
[Try it](http://arturo-lang.io/playground?YqZrIB)
Returns `[start end+1]` or `0` if there's no solution.
[Answer]
# [Scala](https://www.scala-lang.org/), 91 bytes
Golfed version. [Try it online!](https://tio.run/##PY5Ba8MwDIXv/hWiJ5sZQ7rtEnBhsMsOPZWdSihqaqcejtvZymCM/vZMzsp0ENKT3scrPUacL8cP1xNsMST4EUJ8YQTfypec8Xv/lqjT3JTd7NznXvKooe4d2Fmirgc0IZ1C74rxEWmLV1nsRhaYEoUIaKJLA52V8SGSy9JVR4lskEW7h0aZMo3WkjIjW1k7KKVmgJPzMHIoiXkoLfzl2VEOaehUC@8pEFhODFw1c5rGo8uFtVWzfnx6Xi28g8HyGobAeLosjH8DMdhVRrNetCujKSbp5R2l7y9K8f0mxG3@BQ)
```
(a,t)=>a.indices.flatMap(s=>(s until a.length).filter(e=>a.slice(s,e+1).sum==t).map((s,_)))
```
Ungolfed version. [Try it online!](https://tio.run/##VVA9a8MwEN3zK45MEnUFTtvF1EMgS4dOplMwRbZlVUWWU@lcCMW/3b0ocmi16O7eB/cutNLKZRmbT9UivErj4GezAehUD71xXTU10nt5Doy@AvaX@vjisM4ApdcKC6COF1CpryOjMot9DSX5AL1@9KkCCCRBeL4H8hJkbloVEqRcdwGujMmhsZFkldP4kTimj7NgScciM4u6O8i5CNMAZZmWioIZzkbZDv5QOQHzGm@gsJRKhzVWhd44XVOYN2fwluBbWnDT0CgfaLbNdw@PT1sxyBN7FzIcjDbIBY7R4ya47kH8fBdnJ7JG69j/mybb9ZY87Tcvyy8)
```
object Main {
def findSubarrays(arr: Array[Int], target: Int): Seq[(Int, Int)] = {
for {
start <- arr.indices
end <- start until arr.length
if arr.slice(start, end + 1).sum == target
} yield (start, end)
}
def main(args: Array[String]): Unit = {
val numbers = "12345".map(_.asDigit).toArray
val target = 12
println(findSubarrays(numbers, target))
}
}
```
] |
[Question]
[
This was inspired by a function I recently added to my language [Add++](https://github.com/SatansSon/AddPlusPlus). Therefore I will submit an short answer in Add++ but I won't accept it if it wins (it wouldn't be fair)
Don't you hate it when you can multiply numbers but not strings? So you should correct that, right?
You are to write a function or full program that takes two non-empty strings as input and output their multiplied version.
How do you multiply strings? I'll tell you!
To multiply two strings, you take two strings and compare each character. The character with the highest code point is then added to the output. If they are equal, simply add the character to the output.
Strings are not guaranteed to be equal in length. If the lengths are different, the length of the final string is the length of the shortest string. The input will always be lowercase and may contain any character in the printable ASCII range (`0x20 - 0x7E`), excluding uppercase letters.
You may output in any reasonable format, such as string, list etc. Be sensible, integers aren't a sensible way to output in this challenge.
With inputs of `hello,` and `world!`, this is how it works
```
hello,
world!
w > h so "w" is added ("w")
o > e so "o" is added ("wo")
r > l so "r" is added ("wor")
l = l so "l" is added ("worl")
d < o so "o" is added ("worlo")
! < , so "," is added ("worlo,")
```
So the final output for `hello,` and `world!` would be `worlo,`.
# More test cases
(without steps)
```
input1
input2 => output
programming puzzles & code golf!?
not yet graduated, needs a rehaul => prtgyetmirgduuzzlesneedsde rolful
king
object => oing
blended
bold => boln
lab0ur win.
the "super bowl" => the0usuwir.
donald j.
trumfefe! => trumlefj.
```
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins! Luok!
[Answer]
# [Erlang (escript)](http://erlang.org/doc/man/escript.html), 46 bytes
```
t([I|M],[E|S])->[max(I,E)]++t(M,S);t(_,_)->[].
```
[Try it online!](https://tio.run/##Fcq7DoIwFADQ3a@4djBtKHyAJjoxMDAxNg1p4IJN@iDlEpXw71XnczA5E@YS1yHZhfIpE1fN0Wqp6qPTorwrb968kbXQRUG8lZ24Ee9l/yddZW9s4OofbbxOr2QJOXG2pDgn470NMyzbvjtc4QJDHBHm6Kbzg0kWIsEHCX5x3AzhKCEgjisYSPg0m2NCVPkL "Erlang (escript) – Try It Online")
## Explanation
```
t([I|M],[E|S])-> % Extract the head of both operands
[max(I,E)] % Take the max of the heads
++t(M,S); % Recurse with the remaining strings
t(_,_) % If head-extraction fails for either of these operands:
->[]. % Return the empty string
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 2 bytes
```
zY
```
[Try it online!](https://tio.run/##DcqxEYAgDAXQVb6NlTs4h2XORPAEwgEpZPnoq1@0/rjPw91r09Ao57sEVJszSceKU1kQNF3L7kUHXhn4GxsN4Q1FhDsITSJZ@gA "Husk – Try It Online")
zip using maximum.
[Answer]
# [Perl 5](https://www.perl.org/) `-lF`, ~~88~~ 67 bytes
```
@b=<>=~/./g;$#F=$#b=@F>@b?$#b:$#F;say map{($q=shift@b)gt$_?$q:$_}@F
```
[Try it online!](https://tio.run/##DcgxDoMgFADQvacg@od2EOngokWZ2HoGw0@oklBBwJimaY9e6vbyvA62yVkgv/X8W9N66qCUHErkQvYCh0PtMV1UL/JU/n2GlcfZPJLAy5RgHGBtYfwImbNVyLZAdrPQU5o1KeLmdSDodlv8nE/GLTFX94ayK8uVlX8 "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
ø€à
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8I5HTWsOL/j/P1q9oCg/vSgxNzczL12hoLSqKie1WEFNITk/JVUhPT8nTdFeXUdBPS@/RKEytUQBqDKlNLEkNUVHIS81NaVYIVGhKDUjsTRHPRYA "05AB1E – Try It Online")
```
ø€à # full program
ø # list of...
à # maximums of...
€ # each element of...
ø # code points of...
# implicit input...
ø # with each element paired with the corresponding element in second sub-list
# implicit output
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 3 bytes
```
ZvG
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=ZvG&inputs=hello%2C%0Aworld!&header=&footer=)
That is: the maximum function (`G`) `v`ectorised over the inputs `Z`ipped together (`abc` and `def` turn into `[["a", "d"], ["b", "e"], ["c", "f"]]`. Takes a single string (alternatively, a list of characters) and outputs a list of characters.
[Answer]
# [Factor](https://factorcode.org/), ~~16~~ 4 bytes
```
vmax
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQma@QnVqUl5qjkJtYkqFXlgqSLFaw5lLKSM3JyddRUlAqzy/KSVFU@l@Wm1jxv6AoM6/kPwA "Factor – Try It Online")
Element-wise maximum. It's a builtin.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 5 bytes
```
eCSMC
```
[Test suite](https://pythtemp.herokuapp.com/?code=eCSMC&test_suite=1&test_suite_input=%22hello%2C%22%2C+%22world%21%22%0A%22programming+puzzles+%26+code+golf%21%3F%22%2C+%22not+yet+graduated%2C+needs+a+rehaul%22%0A%22king%22%2C+%22object%22%0A%22blended%22%2C+%22bold%22%0A%22lab0ur+win.%22%2C+%27the+%22super+bowl%22%27%0A%22donald+j.%22%2C+%22trumfefe%21%22&debug=0)
[Answer]
# [Thunno](https://github.com/Thunno/Thunno) `J` `B`, \$ 5 \log\_{256}(96) \approx \$ 4.12 bytes
```
ZZeMC
```
(No ATO link since it's not on a new enough version)
#### Explanation
```
ZZeMC # Implicit input. The B flag converts the strings to codepoints.
ZZe # Zip together and loop through:
M # Get the maximum
C # And get chr of that
# Implicit output, with the J flag joining everything together
```
### [Thunno](https://github.com/Thunno/Thunno) `J`, \$ 9 \log\_{256}(96) \approx \$ 7.41 bytes
```
ZZeO.AJMC
```
(No ATO link since it's not on a new enough version)
#### Explanation
Unfortunately the `max` command (`M`) doesn't work with strings, otherwise this would have been a lot simpler.
```
ZZeO.AJMC # Implicit input
ZZe # Zip together and loop through:
O.AJ # Get the ordinals of both characters
M # Get the maximum
C # And get chr of that
# Implicit output, with the J flag joining everything together
```
#### Screenshots
[](https://i.stack.imgur.com/PHQD0.png)
[](https://i.stack.imgur.com/BQC9n.png)
[Answer]
# [Python 3](https://docs.python.org/3/), 26 bytes
```
lambda*a:list(map(max,*a))
```
[Try it online!](https://tio.run/##VY/BbsIwEETv/YrFh5Igq0LiVqniR7is2XUSuvZajq0APx/MpWoOc3pvRpr0KKPG0@p/LqtgcIQH/JZpLl3A1HK3B@z7NeUpls53ZmQRtcaaRbPQzvT9xx9LWYeMIUxxgFSfT@EZPuGqxDCo@N251aIWeHCBJlLFwmQhMtMMCJlHrLJZ/G1TraTuxteyIU44ElODToU2SNAda4Zlil/G7svIYOaaOIPTRcz@v0oaUQhuTQRTcg2ePb9PrS8 "Python 3 – Try It Online")
Similar to another Python 3 answer, only that I use `list` instead of `''.join`, which shaves 3 bytes off.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 51 bytes
```
f(char*s,char*t){(*s=*s>*t|!*s?*s:*t)&&f(s+1,t+1);}
```
[Try it online!](https://tio.run/##ZY/BasMwEETv@Yq1D0ZW5IOvNWk@pPSgSCvZIEtGu6I0br7dUQs9lM5lYJk3y5jBG3McTphZZ0nqx7jfhaSLpFfJX42kq6SXeuw6J@g8Kj6P/fQ4lsiw6iWK/rSfoGr/hkG/vcMF2hlDSKqdwAmt2o@Ug23aftoKk9AV/09sOfms13WJHrZyvwck6MAki@BTcM31tywmhk9kqGlbNKNVEBEtgYaMsy7hz5/HIWkYS50yjOBKhFthCCl6zE8 "C (gcc) – Try It Online")
# [C (gcc)](https://gcc.gnu.org/), 51 bytes
```
f(char*s,char*t){(*s=0u-*s<-*t?*s:*t)&&f(s+1,t+1);}
```
[Try it online!](https://tio.run/##lY3LCoMwFET3fsVtFhJjhLqtFT@kdHFJ4gNiInlQqvjt1ha66Eo6m4FhzowoOiG2raWiR8c8/1jIFsp8fY4F89eChYb5yx6maUt9XvKQl1m1boMJMOJgaJYsCexa3jDg7Q41kF5pbTmpoKXIycM6LU8kq6YYPMUdPyYO2v9MT852DsdxMB1McZ618pCCsFJBZ3V7ar5jxgZ4qgB7W0YMSnIwSkkPCE71GPXPz7q9AA "C (gcc) – Try It Online")
[Answer]
# [Arturo](https://arturo-lang.io), 22 bytes
```
$=>[couple&&|map=>max]
```
[Try it](http://arturo-lang.io/playground?WidqaF)
Takes and outputs a list of characters.
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 3 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
Z€G
```
Output as a list of characters. Add the `J` flag if you want a string.
#### Explanation
```
Z€G # Implicit input
Z # Zip the two inputs together
€ # For each pair:
G # Get the maximum of the pair
# Implicit output
```
#### Screenshot
[](https://i.stack.imgur.com/8G35K.png)
] |
[Question]
[]
|
[Question]
[
>
> **Note:** This is a more limited version of a [challenge from 2014](https://codegolf.stackexchange.com/questions/40150/find-a-representative-submatrix) that only received one answer. That challenge required participants write two programs; this challenge is essentially one half of that. The text here is original, but credit for the idea goes to [Matthew Butterick](https://codegolf.stackexchange.com/users/31003/matthew-butterick), who is no longer active on the site.
>
>
>
Given a matrix of integers \$M\$, find the smallest (by number of elements) submatrix \$N\$ that contains at least one of every element present in \$M\$. (A [submatrix](https://mathworld.wolfram.com/Submatrix.html) is a “matrix formed by taking a block of the entries … from the original matrix.”)
$$
M = \begin{bmatrix}9 & 0 & -4 & 5 & 1 & -4\\
3 & -2 & 5 & 9 & -7 & 1\\
\color{blue}{0} & \color{blue}{-7} & \color{blue}{-2} & \color{blue}{5} & 9 & 5\\
\color{blue}{9} & \color{blue}{9} & \color{blue}{5} & \color{blue}{-4} & 1 & 9\\
\color{blue}{-4} & \color{blue}{1} & \color{blue}{8} & \color{blue}{3} & -4 & -4\end{bmatrix}
$$
In the above example the submatrix \$N\$, shown in blue, has at least one of every element in \$M\$, and there is no smaller submatrix with that property. Note that some elements (i.e. \$8\$) do not exist outside of \$N\$ and some elements in \$N\$ are duplicated (i.e. \$9\$).
## Input
Input will consist of a matrix \$M\$ in any convenient format. It will be at least \$1\times 1\$.
## Output
Output may be either of:
1. The submatrix \$N\$ in any convenient format. If it's returned as a 1-dimensional list its dimensions must also be given.
2. The position of \$N\$ within \$M\$, given either as the row and column positions of two of its corners diagonal from each other, or as the row and column position of one of its corners and its width and height. The answer should indicate which corners are given.
If multiple submatrices are tied for smallest representative submatrix, any one may be returned, or all may be returned.
## Rules
* [Default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/) and [standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) apply. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest solution in bytes wins.
## Test cases
The below test cases each show one possible correct output, but not all possible valid outputs.
```
Input
3 3 -9 0 3
3 3 1 -8 1
0 0 0 8 -8
3 8 8 0 3
0 8 8 0 -9
Output
-8 1
8 -8
0 3
0 -9
```
```
Input
3 6 -8 -1
-8 3 1 -2
-8 -2 -1 -2
Output
6 -8
3 1
-2 -1
```
```
Input
-8 -7 -4 7 -7
-7 -6 7 -7 -7
8 -3 -8 -6 -4
-4 5 -7 7 8
-8 7 8 -4 -3
Output
-3 -8 -6 -4
5 -7 7 8
```
```
Input
-8 7
-2 -4
Output
-8 7
-2 -4
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~275 261 231 229 227 220 218~~ 201 bytes
```
def f(m):
z,o,a,r=m,len,sum,range
for i,k,j,l in product(*(r(o(m[0])),r(o(m)))*2):
s=[q[i:j+1]for q in m[k:l+1]];t,f=a(s,[]),a(z,[])
if{*f}=={*t}and o(t)<o(f):z=s
return z
from itertools import*
```
[Try it online!](https://tio.run/##jZDBcoIwEIbveYq9mdBlBtEq0vIklANTSYtCgiEeiuOzU5Yg6s3Dzu782f/fD5o/@6vVqu/3hQTJaxEz6FBjjiapsSoUtucaTa5@CgZSGyjxiAesoFTQGL0/f1vuccM1r9MgEwLHUQjhhRQFbZKe0jI@vC0zcp/IV6fHuBqE7MOiTHLeYpoJzHlHffCU8uLJa5JcPHvN1R40t@JTcyniLmkZmMKejYKOSaNrKG1hrNZVC2XdaGO9vjGlGqAkZ2kKKwQqfzf0gOYMGcwyLIeniLqTg2mLKqKn@3Y01UNI8Cz7uyxjAqEtmmTxpRaCMYcyDw9MG3fYd4dHhhtPOEt@SBuj9FLy6NkOtR6iqG9dFI2bmzTL4xeuJg7iWbttMr@7TXJAdEfcTv9lTc7XmWDiCMcjz7b@Hw "Python 3 – Try It Online")
* -14 thanks to Neil
* -30, -2, -17 thanks to okie
Input/output as nested lists.
# [Python 3](https://docs.python.org/3/) + [`golfing-shortcuts`](https://github.com/nayakrujul/golfing-shortcuts), ~~228 198 190 186~~ 164 bytes
```
def F(M):
Z=M
for I,K,J,L in Ip(*(r(l(M[0])),r(l(M)))*2):
S=[Q[I:J+1]for Q in M[K:L+1]];T,F=s(S,[]),s(Z,[])
if{*F}=={*T}and l(T)<l(F):Z=S
p(Z)
from s import*
```
* -30, -22 thanks to okie
Makes use of the much cheaper `s.Ip` instead of `itertools.product`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ZẆ$⁺€ẎFQL;LN$Ʋ$ÞṪ
```
A monadic Link that accepts the matrix as a list of lists and yields the/a smallest sub-matrix which contains all of the distinct values.
**[Try it online!](https://tio.run/##y0rNyan8/z/q4a42lUeNux41rXm4q88t0Mfax0/l2CaVw/Me7lz1////6GgFYx0FENa1BNIGIHYslw5cVMEQKGMBosGiBlA1IGwBkoGrtYBihAkGqKK6lrFcsQA "Jelly – Try It Online")**
### How?
```
ZẆ$⁺€ẎFQL;LN$Ʋ$ÞṪ - Link: rectangular matrix, M
$ - last two links as a monad - f(X=M):
Z - transpose
Ẇ - all non-empty contiguous sub-lists (includes X itself (transposed))
€ - for each (such "strip" of columns):
⁺ - repeat the last link - i.e. f(X=strip)
Ẏ - tighten (to a flat list of the sub-matrices)
Þ - sort (these submatrices, S) by:
$ - last two links as a monad - g(S):
F - flatten (S) -> Elements
Ʋ - last four links as a monad - g(Elements):
Q - deduplicate -> distinct elements
L - length -> number of distinct elements
$ - last two links as a monad - h(elements):
L - length -> total number of elements
N - negate -> -1 * total number of elements
; - concatenate -> [number of distinct elements, -1 * total number of elements]
Ṫ - tail
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 51 bytes
```
FLθF⊕ιFL⌊θF⊕λ⊞υE✂θκ⊕ι¹✂νμ⊕λ≔Φυ¬⁻ΣθΣιυ≔EυLΣιθI§υ⌕θ⌊θ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVDdSsMwFMbbPcVhVymcwqYbrng1BoOBk8EuSy9qm61hbWrzI76LN7tQ9JX0aTxpsunAi5B8P_nynbx-FlWuijavj8d3a3bx7PsKdq0Cds_l3lSsiyKPV7JQvOHS8JKJExlMayFFYxtn_sddE7mxumIWYZ0_sW0tCs46hAPCZSrCmJbXJUJzqVNOFN0N5lqLvWRLURuuXOZDa1wDq9m270AJtAvnRrC_N9zbZA-dTx6EjiwbJaRhi1wbNjcrWfIXZ10KWbqif-ejCm_6sdDhuz7SYfxcD7MvnaYpJAgjjCcIUxqFDhkOAFK4wfi65xKMb0kJ9MihswLTQCce9TljOns6oBm6tInLzjJf4Qc) Link is to verbose version of code. Explanation:
```
FLθF⊕ιFL⌊θF⊕λ
```
Loop over all of the possible submatrices.
```
⊞υE✂θκ⊕ι¹✂νμ⊕λ
```
Extract the submatrix to the predefined empty list.
```
≔Φυ¬⁻ΣθΣιυ
```
Filter out those submatrices that are not representative.
```
≔EυLΣιθ
```
Get the sizes of all the submatrices.
```
I§υ⌕θ⌊θ
```
Output the matrix with the smallest size.
Note that Charcoal outputs each element on its own row with rows double-spaced from each other.
[Answer]
# JavaScript (ES10), 160 bytes
```
f=(m,x=s=g=m=>new Set(q=m.flat()).size,y)=>m.map((r,j)=>r.map((_,i)=>1/x?g(m)>g(M=m.slice(y,j+1).map(r=>r.slice(x,i+1)))|(v=q.length)>s||(s=v,o=M):f(m,i,j)))&&o
```
[Try it online!](https://tio.run/##RU7LbsIwELz7K1YcwCuS8CyPVk5P7Y1euCJVaXCCUR5gGwot/Xa6tg9IK2tmdnY8@@ycmVyrg42bdivv90LwOroII0pRi7SR37CWlh9FnRRVZjliYtSPjK4o0jqpswPnOtoT0YF8RorIaHB5LXmNaclXdGkqlUt@jfb9EXqbdv6gXiJFKuKNn8UxqWRT2h2m5nbjRpyjVqzwuaBGij5B7Hbbu5bHk9KS9wrTw0TLbPuuKrm@NjkfYmLbtdWqKTn1PFTK8s6m2TQdTIpWv2X5jhsQKfwygEpaqEGAeRg7oZ23GIKW/IPNuj8ow@LjVH9JjfhC53nbmLaSSdWWnAo68Q/vMAGaeAkwJMAChRHEC3qZE8MsSPHbhZ9gHj5ovGR@PXOX8Yi5@xA0djgek@iwJ3OIpwD0zpnDs4Addf9MfAQFTZmzPbkVGWDhQ@e@y5RsLHDmsqf/ "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
m, // m[] = input matrix
x = // x = current column
s = // s = best score
g = m => // g = helper function taking a sub-matrix m[],
new Set( // turning into a set ...
q = m.flat() // ... a flattened array q[] made from m[]
).size, // and returning its size
y // y = current row
) => //
m.map((r, j) => // for each row r[] at index j in m[]:
r.map((_, i) => // for each cell at index i in r[]:
1 / x ? // if x is defined (2nd pass):
g(m) > // if the number of distinct values in m[]
g( // is greater than those of
M = // the sub-matrix M[]
m.slice( // located between (x, y) and (i, j)
y, j + 1 // built by using slices of the original
).map(r => // matrix
r.slice( //
x, i + 1 //
) //
) //
) | // or
(v = q.length) // the size v of the sub-matrix
> s // is greater than the current best size,
|| // then do nothing
(s = v, o = M) // otherwise, update the solution
: // else (first pass):
f(m, i, j) // do a recursive call with (x, y) = (i, j)
) // end of inner map()
) && o // end of outer map(); return the solution
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes
```
cd;Lcpġ.&s\s\
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/PznF2ie54MhCPbXimOKY//@jo411zHTiLXTiDWN1ooG0sY6hTrwRhB1vBBQG8WL/RwEA "Brachylog – Try It Online")
Really slow.
### Explanation
We first get the set of distinct elements of the matrix. We know that the submatrix contains at least these elements: we thus append an unknown amount of additional elements (Brachylog will try in increasing amounts until it finds a solution), we then permute them (until it finds a solution) and group them in sublists of equal lengths (trying different lengths until it finds a solution). We finally constrain this constructed sublist to actually be a sublist of the input.
Since what we’re doing is basically constructing all possible matrices which contain at least all distinct elements of the original one, and verify afterwards that it is a real submatrix of the input, you can guess why it’s really slow.
```
c Concatenate the matrix into a list
d Remove duplicate values: we get elements that must be in the submatrix
;Lc Append an unknown list L to this list
p Try any permutation
ġ. Try any grouping of elements into sublists of equal lengths; this is the output
&s Take a subset of consecutive rows of the input
\ Transpose
s Take a subset of consecutive columns of this subset
\ Transpose
This must also be the output (i.e. the output is a submatrix of the input)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~34~~ 32 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
˜©āãε`"€üÿø€üÿ".V}€`€`Σ˜g}.Δ˜®åP
```
[Try it online](https://tio.run/##yy9OTMpM/f//9JxDK480Hl58bmuC0qOmNYf3HN5/eAeUoaQXVgtkJoDwucWn56TX6p2bAtSw7vDSgP//o6MtdQx0dE10THUMgVSsTrSxjq4RkGepo2uuYwjkG4AYUCFTIN8SRIN0GOpYArlghoWOMUgEqD/2v65uXr5uTmJVJQA) or [verify all test cases](https://tio.run/##XY/PSoRQFMb3PYW4PlfU2@g1iCHoAWZTBCKMlYQw6DBzDQxc1DO0nJ20CKJVE1HBgLYb8CF6ETvn6hgMl@v5vvPn57npMryMo/ZWnywiKXM2X8SJjK61OJln8kjTIbfqz2ZtN29GVRbVFxzoJ1cyC2dDxzj/z6WZ3CVPz9rtqnr@ua/LZn2xnOq/Dy/1d72pP3qhG@cFyindptyubgqjecSR1/pp0hbH@wsNaNhbqHoft77ve2ACO4QRWBgC8DkwG50HzAULvUmiT43QexRpwgIPrRICOGVwPgDNRwRa4nLF44QWPYyOQKsqAk/XZfaaeTuEQzOMhpjoEHancRemnGqkhEs/x49LDRgdZTqPZa5ITvc89VQsuiA6nEvr4O584CmMrV4TtIwlKZuFd/kf).
**Explanation:**
Step 1: similar as [my 05AB1E answer](https://codegolf.stackexchange.com/a/255234/52210) for the [*Find the box by its corners* challenge](https://codegolf.stackexchange.com/questions/255133/find-the-box-by-its-corners), get all possible blocks from the input-matrix:
```
˜ # Flatten the (implicit) input-matrix
© # Store it in variable `®` (without popping)
ā # Push a list in the range [1,length] (without popping the list)
ã # Create all possible pairs of this list with the cartesian product
ε # Map over each pair:
` # Pop and push them both separated to the stack
"€üÿø€üÿ" # Push this string, where both `ÿ` are filled with the two values
.V # Evaluate and execute it as 05AB1E code:
€ # Map over each row of the (implicit) input-matrix
üA # Convert it into overlapping lists of size A
ø # Zip/transpose; swapping rows/columns
€ # Map over each the list of lists
üB # Convert it into overlapping lists of size B
} # Close the map
€`€` # Flatten two levels down so we have a list of blocks of various sizes
```
Step 2: Find the smallest valid AxB block from this list and output it:
```
Σ # Sort all AxB blocks by:
˜ # Flatten the matrix to a single list
g # Pop and push its length to get the amount of elements in this block
}.Δ # After the sort-by: find the first/smallest block which is truthy for:
˜ # Flatten the current AxB block
® # Push the flattened input-list from variable `®`
å # Check for each value of the input-list if it's in the block-list
P # Check if this is truthy for all of them
# (after which this smallest found block is output implicitly as result)
```
[Answer]
# [J](http://jsoftware.com/), 53 bytes
```
<(0{]#~a:=-.&,&.>)[:(/:#@,@>)@,<<;._3&>~],@{@;&(#\)|:
```
[Try it online!](https://tio.run/##VU7LasMwELzrKyYxyBZIql/xQ7GNoNBTT72mpoSQUHrpoe4pJb/u7kqFtrBazeyMZvW29htXzM3G9Wkqtja9YHRIoZHD0TEW90@PD@uQ5dc5uR3daKzU0k7q4LI7l3jtJ@X1MOztSyWn26z91e9lljyrL7cqIZbzxzJaHBzOp9d3vi/YWjn50@dCb0pEC6/LBSpQmR5EUf1QFDAddcHDWB1NgtqFiub8l5peqL@55Gw4xBSCo2JmydiUNGT8z89CC1MD1FvBuImYKa@vQhyF1oJtO5bIgC4saMMXa7IJtX4D "J – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 193 bytes
```
sub f{($_,$r)=(@_,\"$_[0]");$u=sub{my%h;@h{pop=~/\S+/g}=();keys%h};&$u($_)<&$u($$r)or$$r=@{[/\S+/g]}<@{[$$r=~/\S+/g]}?$\_:$$r,f($_,$r)for s/^\S+\s*//gmr,s/\s+\S+$//gmr,s/\n.*$//r,s/^.*\n//r;$$r}
```
[Try it online!](https://tio.run/##TVLRbtpAEHzufcXKOooN5xwBAg7GCe@VmofkDYOlVjagBNu1QSpynV@ns2cHkKz17OzMjk7aPC4@Hs7n8viLksqWkZKFE9iLSIWWjJaDleX48hhgXO1Pna2/2FZ5lgefOnzt600d2I7/Hp/Kzrb2v8sj/M7c/LElK1CDRbVstKt6DszU5xfxLKMZCJW0uUlWUKnXmIZlT@vNvlClDss@CHlp07seGobru16YAvrYUZ9htsXSGhGNyH0kGgAI09E9uR6qGBgWnweCZ575jHJw7dxHSxAFT4KsxmfkrQrDlRJN0IT3uveCVU3MkLE7BImKLWbJpE2DkCetn4VTcsdEqFPBeNJgbjEcme0wjwWrHniCOXkmb2peMYbsK@bWcBVf02hq8scX/Q21Ek6FNxPtT7bcpbkiGf/NHQpoISO/nZDcZAdQiZE4DZ0Xu/SQWB13UhKBnhGgB0xYEP8@cD8ccg8zmjJMLSW@fezS2G4y4j/UdBA49Ezd7L1LM@r@fHmjlx/di5gzFV2N6sbmi1rwCTPTHChfiv6nN4WBZV9Ti9d8W3Pd8rilJ43r@Q8 "Perl 5 – Try It Online")
] |
[Question]
[
Your task is simple, just remove the odd indices and double the even indices
## Example
the input is `Hello, World!` and we get indices
```
H e l l o , _ W o r l d !
1 2 3 4 5 6 7 8 9 10 11 12 13
```
and remove the odd indices
```
el,Wrd
```
Double!
```
eell,,WWrrdd
```
and you are done
1-Indexing
## Test cases
```
abcdef => bbddff
umbrella => mmrrllaa
looooooooong text => ooooooooooggttxx
abc => bb
xkcd => kkdd
Hello, World! => eell,,WWrrdd
D => <empty>
KK => KK
Hi => ii
odd_length! => dd__eegghh
<empty> => <empty>
```
The input can be list if you want.
[Answer]
# [Coconut](http://coconut-lang.org/), 40 bytes
```
"".join(map(->_*2,input()[1::2]))`print`
```
[Try it online!](https://tio.run/##S85Pzs8rLfn/X0lJLys/M08jN7FAQ9cuXstIJzOvoLREQzPa0MrKKFZTM6GgKDOvJOH///yUlPic1Lz0kgxFAA "Coconut – Try It Online")
I'm just learning Coconut, so there's probably a shorter, better way to do this... Feedback 100% welcomed!
Here's how it works:
```
->_*2 - def lambda that dup's a char
input() - read string from STDIN
[1::2] - make a list of even num chars
map( , ) - map the lambda over char list
"".join( ) - convert list to a string
`print` - apply "print" implicit lambda
```
[Answer]
# [Uiua](https://uiua.org), 8 [bytes](https://www.uiua.org/pad?src=U0JDUyDihpAgK0BcMOKKlwpEZWNvZGUg4oaQIOKHjOKKjy0x4pa9wrEu4o2Y4ouv4oav4oqCwq8x4qe74ouv4qe7LOKHjOKItSjihpjCrzHii68rMjU2KSAtQFwwKzEKJnAg4oqCIjggYml0IGVuY29kaW5nOlx0IiBTQkNTICLih4ziio8tMeKWvcKxLuKNmOKLr-KGr-KKgsKvMeKnu-KLr-Knuyzih4ziiLUo4oaYwq8x4ouvKzI1NikiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIKJnAg4oqCImRlY29kZWQ6XHQiIERlY29kZSAiwqPCsS0xwrjChy7DjMKlwrPCsMKIMcKfwqXCnyzCo8K_KMK1wogxwqUrMjU2KSIg4oqCK0BcMOKHoTEyOSIuLOKItjviiJjCrMKxwq_ijLXiiJril4vijIrijIjigYU94omgPOKJpD7iiaUrLcOXw7fil7_igb_igpnihqfihqXiiKDip7vilrPih6HiiqLih4zima3ii6_ijYnijY_ijZbiipriipviip3ilqHiipTiiYXiip_iioLiio_iiqHihq_ihpnihpjihrvil6vilr3ijJXiiIriipcv4oinXFziiLXiiaHiiLriip7iiqDijaXiipXiipziiKniipPiioPiipnii4XijZjijZzijZrirJonP-KNo-KNpCHijovihqzimoLOt8-Az4TiiJ5-X1tde30oKcKvQCRcIuKGkHwjIg==)
```
▽+.◿2⇡⧻.
```
[Try it!](https://uiua.org/pad?src=ZiDihpAg4pa9Ky7il78y4oeh4qe7LgoKZiAiYWJjZGVmIgpmICJhYmNkZSIKZiAiYWIiCmYgImEiCmYgImFhYWEiCmYgImEgYiI=)
```
▽+.◿2⇡⧻.
. # duplicate
⧻ # length
⇡ # range
◿2 # modulo two
+. # double
▽ # keep
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 9 bytes
```
(UW^a1)X2
```
[Try it online!](https://tio.run/##K8gs@P9fIzQ8LtFQM8Lo////Hqk5Ofk6CuH5RTkpigA "Pip – Try It Online")
### Explanation
```
a ; Command-line argument (string)
^ ; Split into list of characters
UW ; Unweave into two lists of every other character
( 1) ; Get the second of those lists
X2 ; Double each character in it
; Concatenate together and output (implicit)
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 3 bytes
```
ĭ:Ĭ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FkuPrLU6smZJcVJyMVRkwc1kpcSk5JTUNCUupdLcpKLUnJxEIDMnHwby0hVKUitKgGJAdUCyIjs5BUh5ABXm6yiE5xflpCgC-S5A7O0NksgEEvkpKfE5qXnpJRkgOSWIXQA)
```
ĭ:Ĭ
ĭ Uninterleave
: Duplicate
Ĭ Interleave
```
[Answer]
# APL+WIN, ~~15~~ 14 bytes
-1 byte thanks to Adám
Prompts for string
```
2/(~2|⍳⍴m)/m←⍞
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv5G@Rp1RzaPezY96t@Rq6ucCZR71zvsPlOP6n8aVmJSckprGlcZVmptUlJqTkwhk5uTDQF66QklqRQkXWB2QrMhOTgFSHkCF@ToK4flFOSmKQL4LEHt7gyQygUR@Skp8TmpeekmGIgA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 13 bytes
```
{2/⍵/⍨~2|⍳≢⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97X@1kf6j3q1AvKLOqOZR7@ZHnYuA/FqQ5H8FIEjjMuSC0EBJQwMA "APL (Dyalog Unicode) – Try It Online")
pretty self explnatory
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 bytes
```
{⍵/⍨0 2⍴⍨≢⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97X/1o96t@o96VxgoGD3q3QJkPOpcBBSqBcn@VwCCNC5DLgj9qHezoQEA "APL (Dyalog Unicode) – Try It Online")
APL port of @jonah 's j answer
[Answer]
# [naz](https://github.com/sporeball/naz), 40 bytes
```
2x1v1x1f1r3x1v2e1r3x1v2e2o1f0x1x2f0a0x1f
```
It's sure been a while, hasn't it? Works for any null-terminated input string.
[Try it online!](https://sporeball.dev/naz/?code=2x1v1x1f1r3x1v2e1r3x1v2e2o1f0x1x2f0a0x1f&input=Hello%252C%2520World!&n=true)
**Explanation** (with `0x` instructions removed)
```
2x1v # Set variable 1 equal to 0
1x1f # Function 1
1r # Read a byte of input
3x1v2e # Goto function 2 if it equals variable 1
1r # Read another byte of input
3x1v2e # Goto function 2 if it equals variable 1
2o1f # Otherwise, output twice and call function 1
1x2f # Function 2
0a # No-op
1f # Call function 1
```
[Answer]
# [Python 2](https://docs.python.org/2/), 34 bytes
```
f=lambda s:s and s[1:2]*2+f(s[2:])
```
[Try it online!](https://tio.run/##PYzNasMwEITveortKXZrCvHRoJ5yCPgBfAjBSFn9YVkSkkzcp3ellHYvO/vNzoTvrL3rj0NSy1aODNKQgDmEdDsP/f29/5BNuvXDvT2e2lgB54GAcaEDv@UAFCJ7zuXectN@pmBNbk5Av@DUEgjRuAyyKXYLlL4SB@MPFLK@cI4oJdlWHoW1rKJ1jbFIRqz/G6cgiz1X9595pXLed1K6fovIvjywymVBJNdS5zuYfLT4VqkooOumKcbiXioh41jXOJKrqcIY4hFnK5zK@pUp1yyEUlr/AA "Python 2 – Try It Online")
[Answer]
# [Lexurgy](https://www.lexurgy.com/sc), 32 bytes
Docs [here](https://www.meamoria.com/lexurgy/html/sc-tutorial.html).
Due to Lexurgy's input considering strings as "stuff surrounded by whitespace", no whitespace can appear in the input string. Otherwise, Lexurgy will consider `["Hello, world!"]` as `["Hello,", "world!"]`. Whitespace must be replaced with a different character (such as `_`).
```
o:
[] []$1=>* $1 $1
[]=>* /_ $
```
Ungolfed:
```
only-evens:
[] []$1 => * $1 $1 # capture the second character and dup it
[] => * / _ $ # remove last odd character as well
```
[Answer]
# [sed 4.2.2](https://www.gnu.org/software/sed/), 5 bytes
```
n;p;p
```
[Try it online!](https://tio.run/##K05N@f8/z7rAuuD//0SuJK5krpR/@QUlmfl5xf918wA "sed 4.2.2 – Try It Online")
Takes string input one character per line (if allowed).
* `-n option` Don't print by default
* `n;` Skips a line.
* `p;p` Print the line twice.
## [sed 4.2.2](https://www.gnu.org/software/sed/), 15 bytes
```
s/.\(.\)/\1\1/g
```
[Try it online!](https://tio.run/##K05N@f@/WF8vRkMvRlM/xjDGUD/9/3@P1JycfB2F8vyinBSuiuzkFAA "sed 4.2.2 – Try It Online")
Solution taking a single string.
* `s/.\(.\)/` Substitute any char, followed by any other char...
* `\1\1/` With the 2nd char repeated twice...
* `g` Globally
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes
```
#~##&~#&/@#~Drop~;;;;2&
```
[Try it online!](https://tio.run/##NYo/C8IwFMT3foqaQCZFcLWWgh2ELoKDg4q8JukfTBOJTyiI@eqxr@ANd8fvbgDs9ADYS4jNLvLAuQhcrAseSu@eYTtpI@LR9xYvfJWzK2NZ3hT7DjxI1P5V8GymNxFOEmz4JAxqqXTDlgl7D7XXxgB14/6ybYp6RILTlWJ8SEV5mM5umZ6dN2pBoCSrqnnryZ1Sd6Nti928s@Qbfw "Wolfram Language (Mathematica) – Try It Online")
Input a list. Drops odd indices and doubles everything left.
[Answer]
# [munge](https://github.com/tomtheisen/munge), 20 bytes
```
/.(.)?/=>{$1 $1}
```
[Munge it!](https://munge.netlify.app/#eyJtIjoiLy4oLik/Lz0+eyQxICQxfSIsImkiOiJhYmNkZWZcbnVtYnJlbGxhXG5sb29vb29vb29vbmcgdGV4dFxuYWJjXG54a2NkXG5IZWxsbywgV29ybGQhXG5EXG5LS1xuSGlcbm9kZF9sZW5ndGghXG4ifQ==)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 32 bytes
```
->s{s.scan(/.(.)/).map{_1*2}*''}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PVBLToQwGI7b_xSVzcCEYaIrN8zKxSQcgIUaUugDQnmkLQkGOIkbYvRQehr7Q8Yu-j37N-3Hlx7y9_VTxN-DFaenH3K6mMlEpqCtf478KDgHUUP7KXs4Pi7Hw2HZe793gUfzgnFB4gvJc8aEgKHJNVeKotU0WjtKQXW31Upi-Wgx_fc6Ka0dR3Cz9kEw1gVDWteMwdWN60KSdlqxe3S5M8IwTbV26TM6kCQISQLXCklVQcdYpngrbbmdcSrjXMqyBJReZHpVWd97bb39bbOqWj4DQbiFWzMgsEScFuU0W25sqLlxtZ6gAEJj8YLsDS26bXHsKsRRXbUWLwBYYP-xdd3xDw)
[Answer]
# [Perl 5](https://www.perl.org/) + `-p`, 11 bytes
Takes a list of chars (to differentiate from [@Kjetil's answer](https://codegolf.stackexchange.com/a/241295/9365)).
2 bytes saved thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)!
```
$_ x=$|--*2
```
[Try it online!](https://tio.run/##K0gtyjH9/18lXqHCVqVGV1fL6P9/D65UrhwgzOfS4VLgCgfSRUBeCpfiv/yCksz8vOL/ugUA "Perl 5 – Try It Online")
## Explanation
Uses the string repetition operator (`x`) to repeat `$_` `$|--*2` times which, since `$|` can only be `1` or `0`, will alternate between `0` or `2` for each character of input.
[Answer]
# [SimpleTemplate](https://github.com/ismael-miguel/SimpleTemplate) 0.84, 36 bytes
Requires that an array of characters is passed to the `render()` method in PHP. [Argument unpacking](https://www.php.net/manual/en/functions.arguments.php#example-159) can be used for convenience. Each argument is 1 character.
```
{@eachargv}{@if__ is mod2}{@echo_,_}
```
This is a full program.
---
## How it works?
It simply loops all over the arguments passed to the `render()` method.
It checks if the index is odd, and, in case it is, displays the character twice.
---
## About the code...
* `{@eachargv}`
This is a simple loop over the elements in `argv`.
Automatically, the current value is stored in the variable `_` and the index is stored in `__`.
A more readable example is `{@each argv as _ key __}`
* `{@if__ is mod2}`
This checks if the key's [modulo](https://www.php.net/manual/en/language.operators.arithmetic.php) is a truthy value.
If it is a truthy value, it means we are dealing with an odd index (the language is 0-indexed, like PHP).
A readable alternative is `{@if __ is not multiple of 2}`
* `{@echo_,_}`
Simply outputs the character twice.
* Usually, it would be needed to close the loop and the `if`, but it is optional since there isn't any other code to run outside.
---
You can try this on <http://sandbox.onlinephpfunctions.com/code/b006b2ec293bab18cd6db2f1b8a2454da047ea49>
Please pick PHP 7.4.13.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 6 bytes
```
.i=%2t
```
[Test suite](http://pythtemp.herokuapp.com/?code=.i%3D%252t&test_suite=1&test_suite_input=%22abcdef%22%0A%22umbrella%22%0A%22looooooooong+text%22%0A%22abc%22%0A%22xkcd%22%0A%22Hello%2C+World%21%22%0A%22D%22%0A%22KK%22%0A%22Hi%22%0A%22odd_length%21%22%0A%22%22&debug=0). Slightly more interesting one..
**Explanation:**
```
.i=%2t # whole program
# take the implicit input (Q)
t # remove the first letter
%2 # keep the odd indices only
%2t # keep the even indices only
= # assign this to Q (the variable encountered)
.i # then interleave this, with
# newly assigned implicit Q (implicit output)
```
---
### 7 bytes
This one uses a `map` in order to double the characters.
```
s+Rd%2t
```
[Test suite](http://pythtemp.herokuapp.com/?code=s%2BRd%252t&test_suite=1&test_suite_input=%22abcdef%22%0A%22umbrella%22%0A%22looooooooong+text%22%0A%22abc%22%0A%22xkcd%22%0A%22Hello%2C+World%21%22%0A%22D%22%0A%22KK%22%0A%22Hi%22%0A%22odd_length%21%22%0A%22%22&debug=0)
[Answer]
# [PLIS](https://github.com/ConorOBrien-Foxx/PLIS), 13 bytes
```
&R($0@@i@VfB)
```
Defines a function `R` which takes a sequence as its first and only parameter. The language implements strings as infinite sequences of `0`s preceded by the string itself. This program works for all sequences, strings included.
We define a function instead of using command line parameters because it is currently impossible to supply anything besides big integers through command line parameters. This would be 9 bytes if it were possible to supply, say, a string via command line (`$0@@i@VfB`).
```
print(R("umbrella")) #=> mmrrllaa
print(R("Hello, World!")) #=> eell,,WWrrdd
print(R("odd_length!")) #=> dd__eegghh
```
## Explanation
After expanding shortnames, we have the following, equivalent code:
```
&R($0@@A000035@A004526)
&R( ) define a function R
A000035 a(n) = n%2 ( 0 1 0 1 0 1 0 1 ... )
@ indices where true; ( 1 3 5 7 9 11 ... )
using shortnames, this is shorter than the equivalent
A005408; compare CwB <=> @i
@ index by
A004526 non-negative integers repeated ( 0 0 1 1 2 2 ...)
this gives ( 1 1 3 3 5 5 7 7 9 9 ... )
$0@ index input by this sequence
```
[Answer]
# [Dis](https://esolangs.org/wiki/Dis), 4 bytes
```
}}{{
```
[Offline interpreter on dis.web](https://tpaefawzen.github.io/dis.web/#source=%7D%7D%7B%7B&input_enc=utf-8&input=Hello%2C+World%21&output_enc=utf-8)
Easy for this kind of task.
A string of any bytes shall be given from standard input, and outputs to standard output.
## Explained
```
} store odd-indexed byte to accumulator
59048 is stored if EOF
} same for even-indexed byte
{ output the accumulator
halt if accumulator is 59048
{ same
implicitly NOP until cell 59048
loop back to cell 0
```
[Answer]
# [Rust](https://rust-lang.org), 118 bytes
```
fn main(){let y=&mut"".into();std::io::stdin().read_line(y);for(i,c)in(0..).zip(y.chars()){if i%2>0{print!("{c}{c}")}}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY5RCsIwEESvUgPKLtRQBUFS9CpS0gQX2rSkKRJDTuJPED2UtzFSYT4ezDAzj5edJ5fSe3Z6e_zctCn6hgxg6JQr_GnTz44xTsYNgPXkWiFoECLDL8StatpLR0aBx1oPFqiUmJ2Kc-R3GsFzeW3sBIiBdEHr_bkKo811K2BBxiyGMcZl_v8iPXeHhb4)
Half is just stdin...
Else,
---
# [Rust](https://rust-lang.org), ~~108~~ ~~106~~ 94 bytes
```
|c:&str|{let mut s=format!("");for(i,c)in(0..).zip(c.chars()){if i%2>0{s.push(c);s.push(c)}}s}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY1NCsIwFISvEgPKe1BDcSWWehUJoSGB_pGXbExzEjdZ6N6lV_E2VgOu5mOGmbndXSCfn3pkg7QjYOw7z2T7CF7vj-_Lok478m752UPwjFo9uUH6DXCOzcpgK4VrsxYCxdXOoIQy0hEgRquZ3R7OdSQxBzKgsPlTSpSacvOanR2_izHxSgI3Xd9PHDGVOOeiHw)
[Answer]
# [Rattle](https://github.com/DRH001/Rattle), 25 bytes
```
|!I=@[0q][=#%[1=#1g`bb]]@
```
[Try it Online!](https://www.drh001.com/rattle/?flags=&code=%7C!I%3D%40%5B0q%5D%5B%3D%23%25%5B1%3D%231g%60bb%5D%5D%40&inputs=Hello%2C%20World!)
Might not be the most elegant solution...
# Explanation
```
| parse input
! disables implicit output (necessary only for special case of empty input)
I save input as char array in consecutive memory slots, move pointer to next empty slot
=@ set top of stack to value of pointer
[0q] if the pointer is in the zero position (meaning empty input), terminate the program
[ ]@ repeat x number of times where x is the value of the pointer (to iterate over all input characters)
=# set top of stack to current loop iterator
% mod 2
[1 ] if the result is 1...
=#1 set top of stack to current loop iterator for main loop
g` get value from the memory slot according to the top of the stack
bb add char to output buffer twice with no separator
```
[Answer]
# [Rockstar](https://codewithrockstar.com/), 70 bytes
```
listen to S
cut S
O's ""
while S
roll S
let O be+roll S*2 or ""
say O
```
[Try it](https://codewithrockstar.com/online) (Code will need to be pasted in)
Or, if we can output each pair of characters separately:
## 51 bytes
```
listen to S
cut S
while S
roll S
say roll S*2 or ""
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-hP`](https://codegolf.meta.stackexchange.com/a/14339/), ~~5~~ 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
The `¬` can be removed if we can take input as a character array.
```
¬m²ó
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWhQ&code=rG2y8w&input=IkhlbGxvLCBXb3JsZCEi)
[Answer]
# *[Acc!!](https://github.com/dloscutoff/Esolangs/tree/master/Acc!!)*, 46 bytes
```
N
N
Count i while _/32 {
Write _
Write _
N
N
}
```
[Try it online!](https://tio.run/##S0xOTkr6/9@Py4/LOb80r0QhU6E8IzMnVSFe39hIoZorvCizBMiB0yCFtf//e6Tm5OTrKITnF@WkKAIA "Acc!! – Try It Online")
### Explanation
```
# Read two characters
N
N
# Loop while the most recent character code is 32 or greater
Count i while _/32 {
# Write the most recent character twice
Write _
Write _
# Read two more characters
N
N
}
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 11 bytes
```
ii::1+?!;oo
```
[Try it online!](https://tio.run/##S8sszvj/PzPTyspQ217ROj/////8lJT4nNS89JIMRQA "><> – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~6~~ 5 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
{ï¥∞*
```
-1 byte thanks to *@Neil*.
[Try it online.](https://tio.run/##y00syUjPz0n7/7/68PpDSx91zNP6/18pMSk5JTVNiUupNDepKDUnJxHIzMmHgbx0hZLUihKgGFAdkKzITk4BUh5Ahfk6CuH5RTkpikC@CxB7e4MkMoFEfkpKfE5qXnpJhqISAA)
**Explanation:**
```
{ # Foreach over the characters of the (implicit) input-string:
ï # Push the 0-based loop index
¥ # Modulo-2 this index
∞ # Double it
* # Repeat the current character that many times (0 results in an empty string)
# (after which the entire stack joined together is output implicitly)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 74 bytes
```
from functools import*
lambda s:reduce(tuple.__add__,zip(s[1::2],s[1::2]))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1chrTQvuSQ/P6dYITO3IL@oRIsrJzE3KSVRodiqKDWlNDlVo6S0ICdVLz4@MSUlPl6nKrNAozja0MrKKFYHSmtq/v8PAA "Python 3 – Try It Online")
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~76~~ 74 bytes
```
I =INPUT
N I POS(X) LEN(1) (LEN(1) | '') . E @X =E E :S(N)
OUTPUT =I
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/n9NTwdbTLyA0hMsPyAzwD9aI0FTwcfXTMNRU0IDSNQrq6poKegquCg4RCrauCq6cVsEafppcnP6hIUCdQAO4XP1c/v/3SM3JyddRCM8vyklRBAA "SNOBOL4 (CSNOBOL4) – Try It Online")
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 6 bytes
```
2en)^^
```
[Try it online!](https://tio.run/##SyotykktLixN/Z@TV/3fKDVPMy7uf21udHBATHRxxn@P1JycfB2F8PyinBRFrsSk5JTUNK7S3KQioHgiV04@DOSlK5SkVpSAVHBVZCencLlweXtzeWRy5aekxOek5qWXZCgCAA "Burlesque – Try It Online")
```
2en # Take every 2nd
)^^ # Map duplicate char
```
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 21 bytes
```
~:gsub&'\1\1'&/.(.)?/
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZBBCoJAFIZp6ymmgiywwl0E1iYi8AAuKsTxjaM5NjHOgG26SBsJOkKX6TQJNqOzecz3_bwf3vN9CRW-16-991Yyma8-jzUtFZ7YJ_fk2pPlYrqYbZet-w5mNyVLtD-OIhwDSUZnNEbeBmEMkCSWlqrAgjAWaV0UQjTfyAQY1-9KkSSV1EnDOaVSVpXV6-vKDK3yGDTOcwAjDk09d1DABYOhTpAGOk4QCNFL7v7WAN_Xed_v9mUaZpmBHCBk5EplaioaEhJCaZq2F6vrdv4A)
] |
[Question]
[
### Your task
Given a string, output the range of ASCII values.
### Example
Let's say we have the string `Hello`.
We get the ASCII values:
* `H` = 72
* `e` = 101
* `l` = 108
* `l` = 108
* `o` = 111
Now, we get the range (`max - min`):
* 111 - 72 = 39
Our answer is 39.
### Test cases
```
Input Output
Hello, World! 82
aaaaa 0
Code Golf 79
Stack Exchange 88
ASCII 18
```
### Scoring
For scoring, we will get the range of ASCII/Unicode values of your program source code, and add that to the length of your code in bytes.
For example, with the program `abc`, the score would be:
* 3 (the length of the program) + 2 (the ASCII range of the program) = 5
You can use [this TIO link](https://tio.run/##RYyxCoMwFEX3fMXbTKh16SZ0KJ2Ebu3S8dVEDSR54SUF/XobKeh2OefeG5c8Ubisq/WROENakmC4gkP/0QiuBY@zdArO4G0oQdBhUwvOpiw9Rkmsa0hKieHwcwssSc6F2kLLd5OytqFhg1oqgQUO0irhto0JW4xsQ5bV7XnvOmAMo2mrGnAXDxPGPG3M7exFGR2knvhfPjm1rm/6MvSkDYxkEkyGzQ8) to get your score.
### Clarifications
* There will be no non-ASCII characters in the input (but your program source code may contain non-ASCII characters)
* There will be no newline characters in the input (but your program source code may include newlines)
* **Lowest score wins**
[Answer]
# [MATL](https://github.com/lmendo/MATL), score 37 (length 7, range 30)
```
X>GX<ZP
```
[Try it online!](https://tio.run/##y00syfn/P8LOPcImKuD/f3WP1JycfHUA "MATL – Try It Online") Or [verify](https://tio.run/##y00syfmf8D/Czj3CJirgv0tURch/dY/UnJx8HYXw/KKcFEV1LvVEEADSzvkpqQru@TlpQHZwSWJytoJrRXJGYl56KlDAMdjZ0xNIQ41SBwA) all test cases and source code.
```
X> % Implicit input. Maximum
G % Push input again
X< % Minimum
ZP % Distance (of code points). Implicit display
```
[Answer]
# [C (clang)](http://clang.llvm.org/), 79 bytes + 28 = ~~145 138 129 112 111~~ 107
*-7 score thanks to [@Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma)
~~-9~~ -10 score thanks to [@jdt](https://codegolf.stackexchange.com/users/41374/jdt)*
```
A,B;D(*C)??<*C<A?A=*C:*C>B?B=*C:0;*++C?D(C):0;??>C(*C)??<A=B=*C;D(C);*C=B-A;??>
```
[Try it online!](https://tio.run/##jVBNT4QwED3TXzGSbAIFshyNXWiga3STve1hDysHLB9LrNAAuhrDXxdbRA/Egz29eTNvOu9xj4u0LscxcmOytTCzKd1gtoloFGB2g1kY01gjn2DHYXRrMVthSkM2D0eB7hPdIJgFsRfp7ljVPXpOq9p6barMRh/IUAzgPu/6UwIBKMLYm/e5EI0Lx6YV2ZXpTlyq34xZk@Vw14hirg99yp/g9o2f1dH5TEYHttv94F8bpqrXGBzAa9ib/zK1kMwWl4v@MrxUTtf4yBhcwFi68PhSnK79xIU27wlCRtG0YEkVg86DAJYEHEfaUyoX3nH5bimJEkubKIrpakKyVTEWlrkSHXghrLKH2tRj31/4iR4a0DB@8kKkZTd6fVuVbSrPCl6@AA "C (clang) – Try It Online")
## Explanation
`??<` and `??>` are trigraphs for `{` and `}` respectively
```
A,B; // A will track the minimum, B will track the maximum
D(*C){ // D() will traverse C updating the values of A and B
*C<A? // if current character < A
A=*C // update A with it's value
:*C>B? // else if current character > B
B=*C // update B with it's value
:0; // else, do nothing
*++C? // if we're not at the end of the string
D(C) // call D recursively with the next character
:0; // else, do nothing
} // end D()
C(*C){ // C() takes the string, which is also where we'll store the output
A=B=*C; // initialize A and B with the first character in C
D(C); // call D
*C=B-A; // store the range (max - min) in the out argument
} // end C()
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 52 bytes + 92 range = 144
```
od -An -w1 -td1 -v|sort -n|sed -n '1p;$p'|dc -e??r-p
```
[Try it online!](https://tio.run/##nY2xDoIwFAD3fsWTYLrYgZmBEEKUxMHIYBwr7yHEpq9piTj03yv@gjfccsM9dJjSOs2GwJPGEpCF87NdRpD7ICHLr@3lfM8gJkZQtQW1FqAW3PSOgf0CysZAW7MgC1fmTkYcQFFVeeUSsqV0ImP4ADf2BndC/xANI8GRzSj6RQ8vaD/DpO2TRN03XSf@mYkv "Bash – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 13 bytes + 39 = 52
```
a:A^aMXaADMNa
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJhOkFeYU1YYUFETU5hIiwiIiwiIiwiXCJIZWxsbywgV29ybGQhXCIiXQ==)
### Explanation
A straight code-golf solution to the challenge might look like this:
```
A*:a;Ma-Na
a First command-line argument
A* Get ASCII value of each character
: and assign that list of integers back to a
; Statement separator
Na Minimum of a
a- Subtract that from each element in a
M and take the maximum of the resulting list
```
This gets a score of 65. The `a` for getting the command-line argument and `A` for taking ASCII values are both necessary, so to improve the score we'll need to look at the characters with ASCII values less than `A`.
The smallest character is `*`, which we can get rid of by splitting the string into a list of characters with `^` and passing that list to `A` directly:
```
A*:a
->
a:A^a
```
The next-smallest character is `-`, which we can get rid of by using the absolute difference operator `AD` instead. Then we have to rearrange a bit more to avoid needing a space; we'll use the old `MX` and `MN` operators for max and min instead of the newer `M` and `N`.
```
Ma-Na
->
MXaADMNa
```
(We could also keep using `M`, but since it also requires a semicolon to parse correctly, the score is the same if we replace it with `MX` which doesn't need the semicolon.)
[Answer]
# [Alumin](https://github.com/ConorOBrien-Foxx/Alumin), ~~36~~ 19 bytes + ~~22~~ 20 = ~~58~~ 39
```
idiqdhhhwrvsruripkc
```
[Try it online!](https://tio.run/##S8wpzc3M@/8/MyWzMCUjI6O8qKy4qLQosyA7GasgAA "Alumin – Try It Online")
Both the right language for the job~~, and horribly inefficient at it!~~ Turns out, I'm just an inefficient thinker!
## Explanation
```
idiqdhhhwrvsruripkc
explanation | stack
id take input, duplicate | MAX MIN
iq ip while input > 0 | MAX MIN in
d duplicate | MAX MIN in in
hhhw grab top 3 | MAX [ MIN in in ]
r reverse stack | MAX [ in in MIN ]
v get lesser of two | MAX [ in MIN' ]
s ungrab | MAX in MIN'
r reverse stack | MIN' in MAX
u get greater of two | MIN' MAX'
r reverse stack | MAX' MIN'
(this gives us a better score than using `y` to swap 2)
loop finishes | MAX MIN -1
k discard eof | MAX MIN
c subtract | MAX-MIN
```
## Explanation (Old)
```
hqidrlhcwrspkrklhhgwfufsykrlhcwfvfsc
h push 1 (to start loop)
q p input loop
id take input, duplicate
r reverse stack
lhc stack length - 1
wrs reverse that many elements off the stack
this has the effect of pushing two copies of the input
krk pop trailing EOF twice
lhhg stack length / 2
w grab that many elements into a new stack
fuf fold over maximum
sykr place on bottom stack, remove initial 1
lhc stack length - 1
w grab that many elements as before
fvf fold over minimum
sc push and subtract
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), score 56 (length 6, range 50)
```
@range
```
[Try it online!](https://tio.run/##y08uSSxL/f/foSgxLz31f5qCrUJiXrE1V5qGukdqTk6@jkJ4flFOiqK6JkgoEQQgTOf8lFQF9/ycNAg3uCQxOVvBtSI5A2QORMwx2NnTE8KEGK@u@R8A "Octave – Try It Online")
[Answer]
# [Terse](https://gymhgy.github.io/TerseLang/), 7 bytes + 6769 = 6776
```
找没最手样找到
```
[Try it here](https://gymhgy.github.io/TerseLang/?code=wGm9voTAag&in=IuaJvuayoeacgOaJi-agt-aJvuWIsCI)
Could be worse.
```
找 Char codes
没 Maximum, after
最手 Squaring and then square root (identity)
样 Subtract
找到 Minimum
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~9~~ 12 bytes + ~~56~~ ~~49~~ 38 = 50
```
;*;-;o;/;\;`<@@o;/_$;`$$
```
This corresponds to the [Nibbles](http://golfscript.com/nibbles/index.html) program with nibbles:
```
6 a 6 9 6 e 6 a 6 b 6 e 4 d 4 e 6 a 5 3 6 d 7 3
```
Which, paired-up into bytes, gives
```
6a 69 6e 6a 6b 6e 4d 4e 6a 53 6d 73
```
which can be read-out as a string (with the same ASCII values)
```
jinjknMNjSms
```
with ASCII range 115 (`73`) - 77 (`4d`) = 38.
---
**How?**
We start from a straightforward code-golf solution to the question: `-o/\;`<$$o/` (5.5 bytes, 11 nibbles):
```
-o/\;`<$@o/
- # subtract
o # character value of
/ # fold over
\ # reverse of
; # (save)
`< # sorted
@ # input
$ # returning left element each time
# (so the fold returns the first element)
# from
o # character value of
/ # fold over
# (implicit) saved sorted input
# (implicit) returning left element each time
```
The nibbles are slightly re-arranged in the final program, since the 2-nibble 'sort' function ( ``<`) wraps around its argument (here `$`). Thus, the paired-up nibbles from this are:
```
-o /\ ;` @< $o / # program code (in final order)
9e ab 6e 4d 3e a # nibbles
```
We can reduce the range of bytes by inserting 'save' operators (`;`, nibble `6`) to shift high-valued nibbles into the least-significant-nibble position of each byte.
This doesn't affect the output, but we need to override the final implicit variable to account for the saved (but ignored) values. Hence:
```
;- ;o ;/ ;\ ;` @< $o ;/ ;$ # program code (in final order), with final variable changed to ;$
69 6e 6a 6b 6e 4d 3e 6a 63 # nibbles
```
Modifying both folds (so returning right element `@` instead of left element `$`) avoids the lowest byte `3e`, but unfortunately outputs a negated value.
So we multiply (and save: `;*`) the negated value by its own sign (also saved: `;`$`): this corrects the output, introducing a new highest byte of `73`, but the overall score is still reduced.
[](https://i.stack.imgur.com/KOztR.png)
[Answer]
# [Julia](https://julialang.org), 22 bytes + 80 = 102
```
+s=-(-(extrema(s)...))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6Ftu0i211NXQ1UitKilJzEzWKNfX09DQ1IZI3G6OVPFJzcvJ1FMLzi3JSFJV0lBUULIy4lBJBAMyDAwMuJef8lFQF9_ycNISMuSWXUnBJYnK2gmtFckZiXnoqxAwLLiXHYGdPTyVkIxQMLbhi9WrsCooy80py8h51zNCGOATmWgA)
[Answer]
# Java 8, score: 134 (54 bytes)
```
s->s.chars().max().orElse(0)-s.chars().min().orElse(0)
```
[**Try it online**](https://tio.run/##dVLBTuMwEL33KwafbKU1e0IrKlaCqLAcFlYExIFFq8FxGhfXruxpAaF@e7GT0q1WIpEmmTfjN@@NPMMVjmb180ZZjBF@oXHvAwDjSIcGlYarnHYAKF5RMG4KUYwTuB6kEAnJKLgCByebOPoRpWoxRC7kHF9T9GFio@bfxGivYtx@ZTPORIvlk01EW76VNzXMk5jtyIdHFNQG/xJh8qr0gox3vbDGB77CAKQjlRj1sdMv8Hnonf3U1voh3Ptg6wM2ZJif9C19reHC2yb9V4TqOfO26KY6AadVeXnJ1qIbAFC9RdJz6ZckF4mXrOOf0wp2DKxwUu0QITo7AFmUylNO4J8kPkv7ls542Rir5XkKUQaN9am1Z2@J47@G30it9A1n8lBmMpmMMyGGsGvrlqpJJhOuxlCXfR7l3e353@9CxoU1xNkfx8TD0eN48IWh3FDkCWK8Ux90XFrK@pO/vVq@C1a7KbWp1qnqMy6@pq/K65tJ3hXvWYv@iCgYcFZsMZbeHi@YYNtLtt58AA) (also contains code to extract the lambda function from the code-block and calculate its score: `(max_codepoint - min_codepoint) + length`).
Not too much too improve unfortunately.
* We could change the `x` to `\u0078`, but unfortunately the next highest codepoint then becomes `u` which isn't too much lower than `x`, so the +5 in byte-count is higher than the -3 in codepoint, giving a +2 in score instead of decrease: [Try it online](https://tio.run/##dVLBThsxEL3nK6Y@2drE5NQiIirRVaAcSiu2iAOgyvV6sw6OHdmTUITy7el4N4QIiV3J9rwZv/dm5Llaq9G8ftxqp1KCH8r6lwGA9Whio7SBqxx2AGheYbR@BklMCNwMaEmo0Gq4Ag@n2zT6mqRuVUxcyIW6X43HX47pGOLUJcPHYnSQtv4ws51ktuXqryO2Hek62BoW5Gine/egBLYxPCWY/tNmiTb43l0TIl@rCGgSliqZE2@e4PXSC/tunAtDuA3R1Z/YkKn80V6G2sBFcA2dK1T6MfO2ys8MAWdVeXnJNqITAKieE5qFDCuUS@JF5/mrWsFOgBVe6j0iRNcOQDals8opvFnicxq69DbIxjojz2lJMhpVnzn37Zk43hX8UtjK0HAmj2Qmk9Q4E2II@7JuqAYlNeFrFeuyj5O8@X3@51jItHQWObv3TNx9fpgMPmgoFxRZQUz27qNJK4fZP/V3kMsPwhk/w5Zynas@4uJj@qr8eT3Ns@I9a9FfEQUDzoodxujv8YIJtntpm@1/).
* Using a regular for-loop requires both `{}` and a space, so the difference of the max-min codepoints would widen on both ends. And in addition it's longer anyway: [Try it online](https://tio.run/##dVLBjtMwEL33KwafbKU1nBBtNotKtAt7yIIIKw6lQsZxmnQdu7KnXaqq317spFsE0iaS7Xl6897M2GuxE5N19XiSWngPhWjNYQTQGlSuFlLBfQx7ACSVjXCLpWdpwI6jsHgU2Eq4BwPZyU@uD5HXZdPpdFxkb9LaOtpnzjw7dJm86t7LWZcWmbwuwqlIj07h1hkoJl16PKVRcrP9pYPkWXln2wq6UBUt0bVmtVgKho2zTx5ufku1wdaaocLotRMOUHnMhVczo57gOelAPimt7Ri@W6erV2RMRPzCnttKwUer63AuUcjHqNsIs1IBmJf53R05st4AoNx7VB23W@SboIva0Ge3hMyAJIbLC8LR5mFcc@fEnjLG@uYAYokyembwt0C6DtfATWt53WrFb8PiuVOimmv9YR8U/yN8EdhwW1PCX/MoxsMYCGNjuNDiTXmFPLRkKuGqfIg9f/h2@/Md436jW6TkhyFs8XaZjl5oLxKS6MDSS/VO@a3GWH/odnD/p9P08mC0MitsArNnDRFlL5uV@eevN3GOdPBIhhSWEKAkOWMk/AOeEEbOT/F4@gM).
**Explanation:**
```
s-> // Method with String parameter and integer return-type
s.chars() // Convert the String to an IntStream of codepoint integers
.max() // Get the maximum of these codepoints
.orElse(0) // Convert the OptionalInt to an int
// (`.orElse(0)` is 1 byte shorter than `.getAsInt()`)
- // And subtract
s.chars().min().orElse(0)
// The same to get the minimum codepoint
```
[Answer]
# [Excel](https://www.microsoft.com/en-us/microsoft-365/excel), score = ~~103~~ 94 (length 46, range 48)
-9 score thanks to [Engineer Toast](https://codegolf.stackexchange.com/users/38183/engineer-toast)
```
=LET(A,CODE(RIGHT(A1,ROW(A:A))),MAX(A)-MIN(A))
```
[](https://i.stack.imgur.com/SzCp3.png)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~12 bytes + 86 = 98~~ 13 bytes + 56 = 69
h/t @isaacg
```
+/1_-':@/1<:\
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs9LWN4zXVbdy0De0sYrh4srPSbHS1deo0bdW09d0iLHi4gqx0lDySM3JyVcIzy/KSVFU4lJQUFBKBAIIyzk/JVXBPT8nDcINLklMzlZwrUjOSMxLT4WIOQY7e3pCmEhmx1hBhFBcEKOkycWVph7CBQBShCQG)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes + 32 = 35
```
Sds
```
### Explanation
```
Sds
S % Sort implicit input
d % Difference between adjacent elements
s % Sum the values
```
[Try it online!](https://tio.run/##y00syfn/Pzil@P9/dY/UnJx8HYXw/KKcFEV1AA "MATL – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) + 149 = 154
I think this is about as good as it's going to get in Jelly due to the distance between `O` (unavoidable as it's the only way to get the ordinals of the input string) and the large ordinals of Unicode characters representing the bytes for mapping and getting maximums and minimums, index into a list etc.
```
OÞOIS
```
A monadic Link that accepts a list of characters and yields the range size as an integer.
**[Try it online!](https://tio.run/##y0rNyan8/9//8Dx/z@D///@rewAF8nUUwvOLclIU1QE "Jelly – Try It Online")**
### How?
```
OÞOIS - Link: list of characters (ordinal)
Þ - sort by: (222)
O - ordinal value (79)
O - ordinal values (79)
I - forward differences (73)
S - sum (83)
----
222
- 73
====
149
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes + [63](https://tio.run/##RYy9CsIwGEX3PMW3NcHaxS2iUAShIDjUxfGz6U8gfyQZWl8@pgjtdjnn3uuWOFlzSklqZ32EsATi4QIK9UcgKA4aZ6oYHEFLkwOxuw0clAyRanTUelFCYIwMu585eGrpnKnMNH9XIQppKt@joIxghgOVjKh105s1Oi9NpEXd3poGPJqx50UJuIlHb8Y4rUxt7GUjKgid9f/yQbGU6vZ7tef7@6m7Hw) = 74
```
ASz>o;FYOmc
```
[Try it online!](https://tio.run/##yygtzv7/3zG4yi7f2i3SPzf5////Hqk5Ofk6CuH5RTkpigA "Husk – Try It Online")
```
ASz>o;FYOmc
m # map over input
c # getting character values
O # and sort into ascending order;
z # now, zip together
> # getting differences
S # the sorted list itself
# and
o; # the single-element list of
F # fold over the sorted list
Y # getting pairwise maxima
A # finally, get the average
# of the resulting single-element list.
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 42 bytes + 80 = 122
```
s=>Math.max(...b=Buffer(s))-Math.min(...b)
```
[Try it online!](https://tio.run/##Xc/BbsIwDAbgO0/hRRwSAWHbhW5SkQChwWGnHnYlhKQthBiSDDFNffauHSBV8dH@7F/ei4vw0pWnMLK4U7VOa59OP0Uo@FFcKed8m86/tVaOesZGt0Fp/weslmg9GsUN5nSTSXTqHfq/FlLQPGAWXGlzyrhRNg9FBdufoDwMGnJuCe0iVjWtdncA52rDer3ubU3JShmDQ/hCZ3ZPBBiD8RiS15iJtgg86saeY7VoXoUPNJp01OQtZlkQ8gDLqyyEzRW5ZyYxm2WL9TrOfEnqPw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 8 bytes + 70 = 78
```
ia0I-s>l
```
[Try it online!](https://tio.run/##y6n8/z8z0cBTt9gu5///4JLE5GwF14rkjMS89FQA "Ly – Try It Online")
I found a shorter program, but the character range of the code was big enough that it had a higher total score.
```
ia - read STDIN onto stack as codepoints, sort the stack
0I - copy the bottom of the stack to the top
- - subtract to get the range
s>l - save result, switch to clean stack, load result
```
[Answer]
# [Raku](https://www.raku.org/), 25 bytes
ASCII range: 88
Length: 25
Total score: 113
```
[-] @_.ords.minmax[*-1,0]
```
[Try it online!](https://tio.run/##K0gtyjH7X1yapJCmUP0/WjdWwSFeL78opVgvNzMvN7EiWkvXUMcg9n@ttUJBUWZeCVCZukdqTk6@jkJ4flFOiqL6fwA "Perl 6 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), score 70 (16 bytes, range 54)
```
[:+/2-/\a.I.]\:]
```
[Try it online!](https://tio.run/##y/r/P03B1koh2kpb30hXPyZRz1MvNsYq9n9qcka@QpqCukdqTk6@jkJ4flFOiqL6fwA "J – Try It Online")
* `]` `\:` `]`: Pass the input (using the identity function [`]`](https://www.jsoftware.com/help/dictionary/d500.htm)) on both sides of [`\:`](https://www.jsoftware.com/help/dictionary/d431.htm) to sort it in descending order.
* `a.` `I.`: For each character of the sorted input, find its index in the ["alphabet"](https://www.jsoftware.com/help/dictionary/dadot.htm); at least on TIO's setup, this contains all of [ISO-8859-1](https://en.wikipedia.org/wiki/ISO-8859-1) in order, which includes ASCII. Thus, this produces the ASCII values of the characters, while keeping the highest used character lower than the straightforward method of `3` [`u:`](https://www.jsoftware.com/help/dictionary/duco.htm) would.
([`I.`](https://www.jsoftware.com/help/dictionary/dicapdot.htm) would also take the following index if a character is not found, but that never happens; it was chosen over [`i.`](https://www.jsoftware.com/help/dictionary/didot.htm) to reduce the highest used character.)
* `2-/\`: For each length-2 subarray (from the `2` and [`\`](https://www.jsoftware.com/help/dictionary/d430.htm)), subtract the second value from the first ([`-`](https://www.jsoftware.com/help/dictionary/d120.htm) [`/`](https://www.jsoftware.com/help/dictionary/d420.htm)).
* `[:` `+/`: Take the sum ([`+`](https://www.jsoftware.com/help/dictionary/d100.htm) [`/`](https://www.jsoftware.com/help/dictionary/d420.htm)) of the values, using [`[:`](https://www.jsoftware.com/help/dictionary/d502.htm) to do so monadically.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal) -v, 35 bytes, score 61
```
castminusordceilceil[q]ordminmin[q]
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z85sbgkNzOvtDi/KCU5NTMHhKMLY4E8oCgQAdnEKdItywEA "Charcoal – Try It Online") Abusing Charcoal's verbose parser again. In order for it to recognise `q` as a variable name I can't follow it with a letter, so the next nearest suitable characters are the list delimiters. I've also used `ceil` instead of `max` to avoid using an `x`; this costs 2 bytes but overall saves 1 from my score. Normally the program would be written like this:
```
Print(Cast(Minus(Ordinal(Maximum(q)), Ordinal(Minimum(q)))));
```
The best I could do in succinct Charcoal was a score of 10135:
```
⭆ψ⁻℅⌈θ℅⌊θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaFTqKPhm5pUWa/gXpWTmJeZo@CZWZOaW5moUamrqKMAFM/NggkBg/f//o7Vt5zseNe5@1NL6qKfj3A4w3XVux3/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The limiting factors here are the Greek letter `θ` needed for the two occurrences of the input variable (the only other input method uses `S` which has a ridiculously high Unicode code point of 65531) and the `⭆` used to stringify the result (again, `I` would have had far too high a code point).
```
ψ Predefined string null character
⭆ Map over characters and join
θ Input string
⌈ Maximium
℅ Ordinal
⁻ Minus
θ Input string
⌊ Minimum
℅ Ordinal
Implicitly print
```
If using bytes from Charcoal's code page was allowed, its score would "only" be 210:
```
SαI⁻℅⌈α℅⌊α
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0JLikKDMvXSNR05orAMgq0XBOLC7R8M3MKy3W8C9KycxLzNHwTazIzC3NBSrS1FGAC2bmwQSBwPr//8NTDy883Hlo7aFmqcMLDzVLHl74X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The limiting factors here are that `⌊` (`Minimum`) is byte index 25 while `α` (variable `a`) is byte index 225, although I did reduce my score by 14 by taking the input into `α` rather than the default input of `θ` (variable `q`, byte index 241).
```
S Input as a string
α Store in variable `a`
α Input string
⌈ Maximum
℅ Ordinal
⁻ Subtract
α Input string
⌊ Minimum
℅ Ordinal
I Cast to string
Implicitly print
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes + 34 = 42
```
+F.+CDCM
```
[Try it online!](https://tio.run/##K6gsyfj/X9tNT9vZxdn3/38lGFMJAA "Pyth – Try It Online")
* `CM`: Map to ASCII value
* `CD`: Sort (equivalent to `S`)
* `.+`: Deltas (Differences between consecutive elements, all nonegative because of sort)
* `+F`: Sum (equivalent to `s`)
Using `.+` is golfier than `h` and `e`, and also stays within the established ASCII value range.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 12 bytes + 52 = 64
```
)**J>]\/<].-
```
[Try it online!](https://tio.run/##SyotykktLixN/V/9X1NLy8suNkbfJlZP939teM5/j9ScnHwuZGEA "Burlesque – Try It Online")
```
)** # Map to char code
J # Duplicate
>] # Maximum
\/ # Swap
<] # Minimum
.- # Difference
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 98 score (18 bytes)
ASCII range: 80
Length: 18
```
s=>s.Max()-s.Min()
```
[Try it online!](https://tio.run/##ZY7LCsIwEEX3/Yoxq4Q@EJdqC1J8FCoIFVyHJG2DJZEmlYL47bUPoYizGc6Zy3CZ8ZmR3aFRbGtsLVXhgVQ2ghzCzoSRCc60xcTvt1SYdBvnKozF6CSqSiPygx7cdF3xxazpMDPGmgs46iqfVWYpu8O@ZSVVhZj9LouTZMAv/1cZj08tOYyJqXzf/dFY8nIAbrW0IpVK4NG5aI1chIIL5anILV4t/dEHqVCFLYmbTznSv313Hw "C# (Visual C# Interactive Compiler) – Try It Online")
* -27 score thanks to Kevin Cruijssen for the tip to use C# Interactive
---
# [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 125 score (36 bytes)
ASCII range: 89
Length: 36
Total score: 125
```
s=>s.Max()-s.Min()
```
If we're going traditional through the compiler then we have to include an extra 18 bytes for `using System.Linq;`
[Try it online!](https://tio.run/##jc1LCoMwEIDhfU8xdZWAegGrUKQPoULBhesQow1NE@rEYimePY3FvZ3NwPD9DMeII3cDSt1B9UYrHvFF6mcCXDFEuMIH0DIrObyMbKBkUhPqj4s9Dprv0PY@D0Fqm0ELKThMM4xLNhIa@T0nLtksSW40GiXiupdW@F@CtCQ4C6VMQOkfKoTa9KrZrmo2z6rKTSPgZFS7KivL@B0OI78x3YlVvq/yovipCSb3BQ "C# (Visual C# Compiler) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes + 67 = score 73
```
C:G$g-
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiQzpHJGctIiwiIiwiXCJIZWxsbywgV29ybGQhXCJcblwiQzpHJGctXCJcblwiYVwiIl0=)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes + 85 = 116
```
ToCharacterCode@s//Max@#-Min@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n1icnJkZlJiXnhpdHB9cUpSZlx6rYGX7PyTfOSOxKDG5JLXIOT8l1aFYX983scJBWdc3M89BWQ1Zn5JHak5Ovo5CeH5RToqiUqy@fgDQmBIuZCWJIIBdCmS8gnt@Thp26eCSxORsBdeK5AwQH7sax2BnT0@41H8A)
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `GB`, 2 + 24 = 26
```
G_
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPUdfJmZvb3Rlcj0maW5wdXQ9SGVsbG8mZmxhZ3M9R0I=)
Port of lyxal's Vyxal answer.
#### Explanation
```
G_ # Implicit input
# Convert to codepoints
G # Maximum codepoint
_ # Subtract each input codepoint
# Find the maximum
# Implicit output
```
[Answer]
# [Sequences](https://github.com/nayakrujul/sequences), score = 73 + 4.12 = 77.12
(Sequences uses the 96 printable ASCII characters as its codepage, so the byte count of this program is \$5\log\_{256}(96) \approx 4.12\$)
```
`vMm-
```
### Explanation
```
`vMm- # Implicit input as a string
`v # Get the ASCII values of the input string in a list
M # Get the maximum value of that list
m # Get the minimum value of that list
- # And subtract to find the range
# (implicit output)
```
[Answer]
# [Python](https://www.python.org), 39 + 80 = 119
```
print(ord(max(s:=input()))-ord(min(s)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dY8xTgMxEEV7n2JwE1vZTUGFVtoCRQhSb5HarG1i4R1btoOSs6RJA1yDa-Q2zO6SdEz3x-9__zl9xWPZBTx_W2iBc_65L7Z-uCxiclhESFoM6iBy0zqM-yKklPW0dCgyiT_8h5yrXJKLQjI2e3nXh2QaXoE3KKysgC9JXCOtlFDDNYsUvbc3GJYg_iUl_eGGGFKBfMyM2ZDAOzTgcFxQEe2wYUAztabLvBpetWom7FZ0BMyH8pQ533G-3L8Y70MF25C8vmNqHLYO2sBz8JZ1RfXv8HTodwrfDHvs1pvNbP0F)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 26 bytes + 80 = 106
-2 bytes thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)
```
->s{y=s.bytes;y.max-y.min}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuha7dO2Kqytti_WSKktSi60r9XITK3SBZGZeLUTBlgIFt2glj9ScnHwdhfD8opwURaVYiNSCBRAaAA)
[Answer]
# [Haskell](https://www.haskell.org), 27 bytes + 84 = score 111
```
_?s=(maximum$s)-(minimum$s)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FN7dzEzDzbgqLMvBIFFQUNe00FA4VoQwNDHQUoYaGjYG4EZBgaxi4tLUnTtdgdb19sq5GbWJGZW5qrUqypq5GbmQdlQ1QsgFJQGgA)
] |
[Question]
[
# Challenge
The goal is to output `Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo`.
[Context](https://en.wikipedia.org/wiki/Buffalo_buffalo_Buffalo_buffalo_buffalo_buffalo_Buffalo_buffalo). (Maybe another interesting challenge could be printing all of the [other examples](https://en.wikipedia.org/wiki/List_of_linguistic_example_sentences#Lexical_ambiguity)? This would probably use similar logic but involve either a function or just a for loop.)
# Rule(s)
1. You cannot output anything other than the string with correct casing and spacing. Trailing new lines are allowed, trailing spaces are not.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes win!
[Answer]
# [Ohm v2](https://github.com/nickbclifford/Ohm), 20 bytes
```
‥bB.¢`b}®:_”cåχíð”↔ù
```
[Try it online!](https://tio.run/##y8/INfr//1HD0iQnvUOLEpJqD62zin/UMDf58NLz7YfXHt4AZD9qm3J45///AA "Ohm v2 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 39 bytes
```
print('uffalo '.join('BbBbbbBb ')[:-2])
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ700LS0xJ19BXS8rPzNPQ90pySkpCYgV1DWjrXSNYjX//wcA "Python 3 – Try It Online")
## Potentially invalid, 35 bytes
```
print('uffalo '.join('BbBbbbBb\b'))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ700LS0xJ19BXS8rPzNPQ90pySkpCYhjktQ1Nf//BwA "Python 3 – Try It Online")
[Answer]
# [brainfuck](https://esolangs.org/wiki/Brainfuck), 370 bytes
```
>++++++++[>++++++++<-]<++++++++[>++++<-]>>++.--------[>++>++<<-]>+.>--------------..[>+>+>+<<<-]>-----.>++++++.+++.<<<<<.>>>>+.<<.>>>>..<<-.>---.+++.<<<<<.>++++++++[>>++++++++<<-]>>++.<.>>>>..<<.>---.+++.<<<<<.>>>>+.<<.>>>>..<<-.>---.+++.<<<<<.>>>>+.<<.>>>>..<<-.>---.+++.<<<<<.>>>>+.<<.>>>>..<<-.>---.+++.<<<<<.>>>.<.>>>>..<<.>---.+++.<<<<<.>>>>+.<<.>>>>..<<-.>---.+++.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v/fThsKouEsG91YG1RRoIgdkKGnCwUgUSCyAYlr69npogA9PaA0CNqA5SFiUMP1QNgGBPTsgADEBjP0gAxdsEHIKhCOQLgN5hSEPgxthA2mjgoy3fD/PwA)
Not exactly the most optimized answer and could probably be golfed much further. Makes lots of use of copying cells, as well as repeadedly performing the same print function near the end.
Original un-minified version (sadly uncommented) [can be found here](https://gist.github.com/TheThunderGuyS/1fc08e8de4354b912f476b20c2074a16).
[Answer]
# T-SQL, ~~45 51~~ 47 bytes
```
PRINT REPLACE('B0 B0 b0 B0',0,'uffalo buffalo')
```
`PRINT` is shorter than `SELECT`. Using a numeral in the `REPLACE` eliminates a set of quotes and saves 2 bytes.
**EDIT**: Fixed trailing space, at the cost of 6 bytes. Saved 4 by replacing a longer phrase, thanks @Giuseppe
[Answer]
# [PHP](https://php.net/), ~~47~~ 45 bytes
```
while($x<8)echo~_[!$x],BbBbbbBb[$x++],uffalo;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwMWVmpyRr6CupG79vzwjMydVQ6XCxkITJFgXH62oUhGr45TklJQExNEqFdrasTqlaWmJOfnW/xH6AA "PHP – Try It Online")
*-2 bytes thx to @manatwork!*
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), ~~27~~ 25 bytes
-2 bytes thanks to ngn!
```
" "/"BbBbbbBb",\:"uffalo"
```
[Try it online!](https://tio.run/##y9bNS8/7/19JQUlfySnJKSkJiJV0YqyUStPSEnPylf7/BwA "K (ngn/k) – Try It Online")
# [J](http://jsoftware.com/), 30 bytes
```
echo}:,/'BbBbbbBb',"{'uffalo '
```
[Try it online!](https://tio.run/##y/r/PzU5I7/WSkdf3SnJKSkJiNV1lKrVS9PSEnPyFdT//wcA "J – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 49 bytes
```
v->"B b B b b b B b".replaceAll("b|B","$0uffalo")
```
[Try it online!](https://tio.run/##ZY09C8IwEIb3/oojOLRSg7sfoIObk@AiDtfaSOo1CcmlIOpvr6m6ORwvL8/Dey32OGsvt0F3znqGNnUZWZNU0dSsrZHTRfYHA/sGuxHVhCHAHrWBRwbgYkW6hsDIKXqrL9Allh/Ya3M9nQH9NRQfFWD3e7E8Jq/8KmtQsBr62VpsoYLxqm8K6RtHWDcbolxUz60oxWQelUKyohgWn8XDPXDTSRtZurTGuZLoHN1zE4mKYpRe2Wt4Aw "Java (JDK) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 41 38 bytes
-3 bytes thanks to @mazzy
```
'BbBbbbBb'-replace'.',' $0uffalo'|% *m
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X90pySkpCYjVdYtSC3ISk1PV9dR11BVUDErT0hJz8tVrVBW0cv//BwA "PowerShell – Try It Online")
[Answer]
# [QBasic](https://en.wikipedia.org/wiki/QBasic), 43 bytes
```
u$="uffalo buffalo
?"B"u$" B"u$" b"u$" B"u$
```
Abuses a couple tricks with the autoformatter (besides the standard `?` for `PRINT` shortcut): the missing double quote is added at the end of line 1, and semicolons are inferred in the print statement whenever a literal string is next to a variable. After expansion, the code becomes
```
b$ = "uffalo buffalo"
PRINT "B"; b$; " B"; b$; " b"; b$; " B"; b$
```
The semicolon trick, plus the fact that string variables need the `$` sigil, meant that approaches using more variables to build the string ended up longer.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 49 bytes
```
v->"B b B b b b B b".replaceAll("\\w","$0uffalo")
```
[Try it online!](https://tio.run/##ZY09C8IwEIb3/oojOLSiwd0P0MHNSXBRh2ttJPWahORSEfG311TdHI6Xl@fhvQY7nDaXW69bZz1Dk7qMrEmqaCrW1sjxPPuDgX2N7YAqwhBgh9rAMwNwsSRdQWDkFJ3VF2gTy/fstbkez4D@GoqPCrD9vVgckjf5KitQsOy76UpsoIThym8K6WtHWNVrolycTncxEaNZVArJiqKffxb3j8B1K21k6dIak8mVROfokZtIVBSD9spe/Rs "Java (JDK) – Try It Online")
## Credits
* -14 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
* -1 byte thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)
[Answer]
# x86-16 machine code, IBM PC DOS, ~~35~~ ~~33~~ 32 bytes
```
00000000: b820 09b1 e7ba 1801 cd21 d0e9 7409 7303 . .......!..t.s.
00000010: 3044 19cd 29eb f1c3 4275 6666 616c 6f24 0D..)...Buffalo$
```
Listing:
```
B8 0920 MOV AX, 0920H ; AH = 9 DOS string function, AL = ' '
B1 E7 MOV CL, 11100111b ; magic buffalo number 11100111
BA 0118 MOV DX, OFFSET BUF ; 'Buffalo' pointer for display
STAMPEDE:
CD 21 INT 21H ; write our *uffalo to screen
D0 E9 SHR CL, 1 ; LSB of magic buffalo number into CF
74 09 JZ BYE_BUFFALO ; loop until CL is 0
73 03 JNC HI_BUFFALO ; if LSB bit is a 0, don't change case
30 44 19 XOR [SI+BUF-100H], AL ; swap case on first letter
HI_BUFFALO:
CD 29 INT 29H ; if not last of the buffalo, display a space
EB F1 JMP STAMPEDE ; keep 'em coming
BYE_BUFFALO:
C3 RET ; return to DOS
BUF:
DB 'Buffalo$' ; the real Buffalo
```
[Try it online!](http://twt86.co/?c=uCAJsee6GwGL2lDNIVjQ6XQIcwIwB80p6/DDQnVmZmFsbyQ=)
**Explanation:**
Uses the byte `0xe7` (`1110 0111` binary) to determine if the case should be swapped. Each `[Bb]uffalo` corresponds to the next least significant bit of the byte where a `1` means to change the case and a `0` means don't change.
The case of the first character can be alternated by doing an `xor 0x20` on the ASCII value. Now `0x20` just happens to be the ASCII value for a space character, so we can put that in `al` and use for both the `xor` and to write the space character.
[](https://i.stack.imgur.com/5pmNr.png)
**Props:**
* -1 byte thx to @peter ferrie!
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~190~~ 179 bytes
```
+++[>+++[>++++[>++>+++>+++>+++>+++>+++>+++>+++>+[<]>>>-]>->->+>->->-[<]<-]<-]>>>+++.>->.>+++.>+++.>--.>.>+++.>----.[<]>>[.>]<[<]>.>>[.>]<[<]+++[>>[.>]<[<]>-]>.>>[.>]<[-]<[<]>>[.>]
```
[Try it online!](https://tio.run/##dY5RCoAwDEMPVNITlFxk7EMFQQQ/BM9fuw6dP7IuvCRjdD6n7VivZXcXkcJHUhv832KVJCoRR1IRmaFNNPFII9MO3UH5Ypj8oiirNdLBucBo8CnRo3TuNw "brainfuck – Try It Online")
The ASCII codes are initialised using a similar method to my [Buffalo answer](https://codegolf.stackexchange.com/a/218330/92901), though here both `b` and the second `f` get their own cells. Printing the output requires fewer instructions in brainfuck compared with Buffalo because of a key difference in the way that loops are handled: brainfuck uses the currently active cell to decide whether a loop ends, whereas Buffalo refers back to the cell that was originally active when the loop was entered. Consequently, we can print runs of letters in successive cells with a simple `[.>]` loop in brainfuck, a construction that isn't possible in Buffalo.
[Answer]
# [Red](http://www.red-lang.org), 57 bytes
```
prin collect[foreach b"BbBbbbBb"[keep rejoin[b"uffalo"]]]
```
[Try it online!](https://tio.run/##DcPRCcAgDAXAVSSjOEJ/Qz6MPqmtGAnt/GkPztHiQGOJ7WOlanOiPtzNUeqZlLJm1T/xDezkuGwsVnp7L9NIRCI@ "Red – Try It Online")
## Alternative:
## [Red](http://www.red-lang.org), 60 bytes
```
parse s:"B b B b b b B b"[any["b"insert"uffallo"|" "]]prin s
```
[Try it online!](https://tio.run/##K0pN@R@UmhId@78gsag4VaHYSslJIUkBhJMgtFJ0Yl5ltFKSUmZecWpRiVJpWlpiTk6@Uo2SglJsbEFRZp5C8f//AA "Red – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Æ▼.#t!♦ΩÿN+╪\7êI
```
[Run and debug it](https://staxlang.xyz/#p=921f2e23742104ea984e2bd85c378849&i=)
Uses mixed base conversion and some zipping.
Made with a lot of @recursive's help.
[Answer]
# [C++11](https://gcc.gnu.org/), 126 bytes
```
#include<random>
#include<cstdio>
int main(){std::knuth_b g(7);for(char i{},s[]=" buffalo";i-8;++i)s[1]^=*s&g(),printf(s+!i);}
```
[Try it online!](https://tio.run/##Pcy7DoIwFADQna@omJjWwuCkocKPEDTl1sKN0DZ9TIRvr0yuZzjgXD0B5HxGA0tSn6eXRtm1K/4AISq0XYEmklWioWw7pGm@JsX5PZKJ3pnQ1lOYpSe47VXoh7YkY9JaLrYUWD8E58hCfxte7TVcJsoq549P08BPyMSe8w8 "C++ (gcc) – Try It Online")
Not a serious contender for shortest program — but I was inspired by the (original, now-deleted) requirement not to use a random number generator. ;)
[Answer]
# [Python 3](https://docs.python.org/3/), 117 bytes
```
o=['buffalo']
for x in ['B' if int(i) else 'b' for i in bin(69)[:1:-1]]:
o.insert(0,x+o[-1][1:])
print(' '.join(o))
```
[Try it online!](https://tio.run/##FYxBCsMgEEX3nmJ2o7QNlUKhQja5xuCigtIpwQnGQHp6q7vH5/23/epH8qM1mQnDkdJ7FfQqSYETOAPhgsCpY9VsIK57BAwIQ@AhBM76@TLkrLtZ750CkInzHkvV9@t5EeozWeeN2sqoIOD0lf4SY1r7Aw "Python 3 – Try It Online")
69 is the reverse of the binary representation of the capitalization pattern.
[Answer]
# [Perl 5](https://www.perl.org/), 37 bytes
```
say"@{[map{(21%$_?b:B).uffalo}1..8]}"
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVLJoTo6N7GgWsPIUFUl3j7JyklTrzQtLTEnv9ZQT88itlbp//9/@QUlmfl5xf91fU31DAwNAA "Perl 5 – Try It Online")
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 17
Obligatory bubblegum answer generated with `zopfli --deflate --i1000 -c buffalo.txt | xxd`
```
00000000: 732a 4d4b 4bcc c957 4882 d2e8 fc24 fcf2 s*MKK..WH....$..
00000010: 00 .
```
[Try it online!](https://tio.run/##SypNSspJTS/N/f/fAAqsFMyNjRIVTFJMkhRMkpKTFZItTc0VTCwsjBRSjFItFNKSjUyARJqRgkKxlq@3t55euIceEKjo6XFBTDAEmmFgoEAc0Pv/HwA "Bubblegum – Try It Online")
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), ~~33~~ 30 bytes
```
put "BbBbbbBb".comb X~"uffalo"
```
[Try it online!](https://tio.run/##K0gtyjH7/7@gtERBySnJKSkJiJX0kvNzkxQi6pRK09ISc/KV/v8HAA "Perl 6 – Try It Online")
[Answer]
# [Rattle](https://github.com/DRH001/Rattle), ~~51~~ ~~46~~ 42 bytes
Rattle just hit release today - this is my first golf with the released version! If you're interested in learning a fun and easy new language, I would highly recommend checking it out!
```
B&b&uffalo& |I=[b0[2b^b1]b2b3b1b2[3q]b3+]4
```
[Try it online!](https://tio.run/##7T1te9s2kt/1KxDqEou2JIty0qRqHCdNk2fzPHttnyS7@0FRWkqEJG4oUuFLHPd8@eu9GbyQAAhSUpxcb3vrNrJFAANgZjBvGIDbq3ydxGe/d8ngeEAWSRDGqwkp8uXgAT7pOI7TeZpSP6cBSWLyel2QJ8WKeGdk9GBy98Hk7D4Zj8ajTuexXwCkdEJ@8OOQRp3HH2iahUk8Id5wNDzrdP62DRgUqO4NRuPB6AEZjyejEXn26jXrBn7wV56QIJl0CPywj4DOocNlES9yAHeLVCXVx8Z/R4lfViIAA4aTbPw8XPhRdEWyPEmhRkz8NPWvSBiTDd0k6RU8Csgm@UBJvqZkm4RxTlNsjl9j@jEnH/yooFUnNMooQIOZbGicZxckSaHgak7JP4ssJ3GSa6UPBwNyuQ4Xa7LAzhc58TMTBukxyGFOikyMcbWM/NWFK9CCn@@LcPGObNNklfqbTEHP8/C33@58X/z22/WtF9PVyUtvnt0@m47mo/nb0Wx1@x786eGf3888wHWYsQZYnwyIH8FsY0DSBxpdTTRY2avMe@Vl45/PVKBeBXRcAmXDuETQaxpFCblM0ihgD6@n3vn72a1BdvIom64e3v40HZ1v389Wg@zR7NO5tyWLNV28yxDfGQUMLIEw2yJHUNs03FCyzvNtNjk9Bb6kqyRaDgFri3f042Ltxys6XCSb0/cFzZDm2em9@99490/DbJCv4SMuNnOaDvwBgySGM3o/m25nI2AwCr1CtclhXXwzvn82Pg0324iRDqDnKbD9YOMv1mEsegFS54eCHZ@NTjMGdwCtB4LOpAf8RCfkeoso@fGn18DjCFwU98mcLnxkGuRWjroVBYba@mkGK@1yTYHPfWB2aI2cSTfb/Mplo/z@zvxOsVz6UXKHAOesRovx4ix7tPLY7@n87vzebDy/B//dBaqPPxtjY@/B@MHd06TIYXSDOe/yc39XXD@nOS5UziWc1JyZKEig6@XoO@C85UxjvGXJd7AqJQCJwKukkCu0YALDDwKUhrAel1hvObKJHePjOoPeRifAY9DTw@NP2BvKh@sX44e154QMHhGyhA6TNPQj0kuiYMKBDAQUVhWazD49XCF84gphwD6eA2RGcy4MOPk3KISAAhRmtkSRh5xxDRImXK25dFr7H1DIXJHro4yzAiw7nP6lH2P7KA@BCzm4rC9F0h2UWz6sUmAtH0ZMeiCuLsMoMuTsgqmKStCieGXcCMwIjJtfbUGEgmYArQOKhmTrpIgCGGt9JCATFkkM3E5jhLj202CABAnETC/DfI2jE0gA/KVcBOcoTJMYhT7iIQQpm@Hoq7qumBZ5w3rFH/rRx8U3IW/ubBOQzMmbO@M3aqc4kSua3Rn3CQW03NUhwhOGjBVIUjJ1oKLTJ1DV4cD417sz1h0s42cTpAsqJPgXJwBx4QNiYAGlwA@gN0mPDldD8iZ2kX/eFwgF9drGT0Fc9pz@kQsQAKHIs6B7cM4xDknIz5hR@BIIUMQRzTKG1iAp5hHjiM2wnPhbwDkvCPrVKoigKSx3WF1IdPgNtJpfkRR5Coid4/ciw8@XYw9JBWKHpCGYCEvGcSAMsFdz4LDu2LwcJwf54DjX2HoA64B/70gTABcU/AR0yZmnhzRwFaW3ipI5rBmUbep3qf8z9WFKt8CT6hMujJ7kz@JAfZwn25@Wr1CWqU/RcvBXVH0kzAT1UZQk26dJUT7uKs8BZKr1vyjSFLTH02SzAbZ6EQf0ownLGNqCV83Man8Ns9xW72myvTInQYMnuCS1xxSWGDxeqQ/B@ngO1oc2YWCA/HuQwfqkRc3xThLYhr8DCdm7cPs6UZ/QOHgugJvjC2NZYhuK6KKGq/oAnlvKbZBVNGtttiEFxrfpBgMaOScDTy3QhgGlUy4sLHPAwumsf@P/Z6SL@hxtA1yyUbgBkQ7rGwTSENfxUtBQmyx03oRWoYWUGT73wdCtygwC1itwmleTb8IP1ODquFsuL/2RWInlQ2nXy@9iTWNPoxk5JtKIrSRAWVWusmpUylpSHsqVBI9@TIQlKNaHNlG5ZrSHyvoyZs8@FHkFxa9T4Y@ohJHdchwESXyEmj4OQN7TNE1Ao3DKXtp48@joqDIhrlGofieJ7JV/jYfsR3798TsyzdG@REMJJlVwV4ZpNe7woG7juGLuGGByUYlTrr43/kfkNHRMmJuVzZjDhIbutsjWvCWzLvvS9IBnoIj60ly4luy7DFO0fKQG7VeeBNeN@TpNitWaP@65Q/JiKXRwiIaNcw0ams0H7RS0UJgVlUkzKuROiT6oIfkJQVyGGe2jGmewlbWwtI2M@Z7CJveF6Sq6xtqsaEPBlQ64SQHanWsw7BhV/gZVex7i4HrhkBKPNWF10wKAXIYL6qJxmW3pAi3LhY/jG@EjDikDjCPdQiQkKj4ODDnE88S3HDR35Oo8wpmLWcXnzDgeArzIX9CeQ5y@4/DqXAbKGtk2CvOe8x0UCic6RNHAK8HqM1gxXPaAFBJHQuWXpaIGFknA146La/j8HIwKpXptNQu6KxUq2w@WYUvLem9a3fKLmJlZ3ZtZsaRMxTp4JhJ61UBcrTSleZHGdeQgCZHTEIFVWx0y9MqqQK9Hb94cGf3Wpl99qebx5o3Tlxjte24NQKeOVl2GcdHHOUL8AjN96zHp10WXYsAMv0zxbMG6ZT4ELMXSbShbjlW5m6dXVcdNkxEkuqPQA7FHwbNvw54Gu/Ie6KLn@NCBQ07QXu4hGLeOGDlUJguznjt1fEdnJ7Sct/mksSUC7pgF3tDfbkG99lgtt2HuWNG6niIaq5yGnOG1raXqi1wM5qhrWKpjSOnQbe7KjigbkrZ@lkmGUi2nrJI23mQyE4XoOyOZUwxZMASU9V1l6uXDaThTTB/8WlvVOmo1DHCxy6RQzpY84M21CQ4@RIU0siWYIwZFSpjeqN6P@OOEeFbyVG31QUuLAkrAoVMMPDboPm/m1qoLA8TWRHTl6v10TenWJ7x2iWDZsF924hqaoovKThZy22SolDJJyEuRzrLihHSzS3/LvoPBAjo1CmMQM5EvPTfWWqNel6GskAZvT8Cq5tQ18dstGbJ80taes2SabJjuJeFmm4BFu6Xp8peFsGRB@AlD@DVWEYYoN3yVgp6rre0KH2CSReBGW2zphwS5v8SywmX1IWdTCwSFk23wT2pcJpWQpfJtZgtauL2qL6b5SEz/hNyzaDDOX87PIoyKaA1QBQ3JD2HAwhzAHxizgD9B5n8MMWgWc4PowqnL7XlK/XfqLBROY2FHrjuA1zBwD1wG1iDXeH3xGzhMt09pvtDMHkVBKhOCAtU5uIX60WopOM7wn@DlqLUVucp0sUYAu43RkWEXYy0vce2rAZhtkmXhPKLg8aC0cEbe@OzuvW/uP/j206@P77y9GDpdcgfXcEoz5hj4YI6CtGSWCRqkPDhXCemY4lpMoCY4BKU/wTH8lkXfLphHIYs4okv9r7to3HPz2SMeTiKNYt/VsR0nMFuU9lBLnaRrKkTRqdS82EbnG9E/FrSZmgLOdOChhmGNTvRGCjC1dt0K5VZhr8THMRLArQsD5QNpra5zMcuDYl@WgJEWGSrVMcoqzeT3mb@8qLRe6QO8ZT4AlCto57Xhs1K9b3WDunK4SydZx7jNIy/7vNivzwtrn@OdnY7rvcqusZdbhhNQM6FwiEPLEPWhLqPEzxGgzox1xquaoBComrm7rSxz6Kb/4uthEFv1T/X6OAzBcFPBZTOLOlOA/GoHYjpNZrPH9maiT9fSIXgJiHc0WxmKJl2@15Wx5jy6IcNgOtc0eBmGEOJAd/sZUI8bojhe/sXdy3vQbBHDCgM4fbYxI8hvsKcU0T@EC5RA/6XBdk6ciR8Eff3hwJlkxTxHTWeUHDsTscN0ZZScOpMg/BAG1Hh@6UzYrvI/cFPZKHvpTOSORJ90Eekj9gOWIO59it0vHn8JwhWP4bAtqJ53DlPvk/E539zok7NztgRcMmBb0XMaJZeMVAHN/TACSs9BQ4NARUMVNz4YwEwfUAYTx4iXMc6VMwF9ajx86EwEx/2QXMZG4aOy8G9bo@hn6IPmP/NSo2wLzdLY7OmWM0FlaTxdOBO@v2Y8n@IcwLL6a5KYXc@cCag6S8FtIGsSFFFiPP8PgAXWtvE0xRmIcCnT5Ub5uTOplvCz9wXITKPGLxI9wd8xbPgifsXlhrVyjhNCIsvgs1HeR6QBsKdgmz0xx@IDf2Ok90UclrF7s4Mnos5PYLH7vEKX734m5RPM8cAkkSVLF4HhLFiMLdGXr7MBRGLpx7b@XiH@IrrIn4PLwOLQRoW5JO3r5OfKHDQqfS@m/SQOXoKNZq8UikovANerWul7Z/K@CHNhZRuFL8RaeIHBG6NsCYz0kS6KnDbQJABpgGk/1bZQzYPAn/9WzHAWYVCFFfvigjHlgIt@ImX3ieMKWaxVnuKXmVspTtPb5OQz84zQBw3jLMQ8AfL3/wThgdvgfNMSnLYVyIoL3h5UW8hL8pDtlBcwNXRRYxhZwaDxjrssoM7MWyVzKEmxtp7hhJ2z@AhAG5BwSIdsg98HOi7YDq2IJWOek3BVoC4WHC2PWAAeJRrPN@I2NUXfH2Wm8LXK7pidaJCsxB8jkm44tm/I7dwbrG/@7dgtbNkbbNyr@3rbg9rObH1brDQTVS3syOFMQCIRHbWaFaMVoT2DdpZiPNR32cr@tPXTGBF4zlwRHhaw4GhqTHzm1l31fZpNm7qeyXj@zLFYuQGt8Fvzgr5u17Jb6fKNGgLfLdEQjlsMiZgNuvZ9Tr4Shttk2xsogXbJNGLHlOcoQSXGPPyha/FE6pvQGjfVwp5tSKwH/KroqAZ1pu4QaKvxC8Fs@ePwoFpzYK2jQbYR18IYX22VmXxvLHsL@7ZtvzfHuuz9WcWZJW54s9Xo7r@cOk14aWzVGGr8jHDj1wg52klhw8jO5awLGjHQANQG2aV0lAYWUvatNHHb10hNlFn8YSHBXCOizh@jBwwkb1g4FrHQFUJUrE5rkLoRXJPMrUlaK4VaZ2ntzphyucEBViZN84bBe/Av7FvFtowQqLaGZUtFpIzwVE3FzBwQ3jEJMTJbuTMAJiHvC1pQfa5N@T9oP1YWfa@KYElulNuCWII2O1n7mHxBY2l2Bo5rxi2F769AW25Qbks4Yieo7v/3eWp/WMZvMD7C0jqK@WCpWnScbhgqwJrQIAuZ65/JTR/yG00TFtGu6rNIQtmCBwqEjg7oItxgtm@aoAMQuG1wZGxCABJ5WUqWKCZoophhao764CtQkTfYUbZ2ASm1PV1E1AnG7R3duNzk0gTyVBNog0RiUgAqYLTWleaF3misNUI67NHoTGvEI5GWZhXh2WiAEEiH85HueRhJnNCTqGiKeiM7RIZA1W1p0rHkW@gWFcM88OBaGhhRsioL5wIyPKtD73sj1z1gNKfe6Pi4Nz/xBmJCML7j2rOOwJBYAruxI4KiI8wzFn8bDoU2NGPn3pbp0ZQqANAnA7YuZwop@Ty/KDFrqLNnpGht2HK0EIlUiG1N/8e5VHFKLpG67EGfn4fhCW8f/DT05b4Wxz631rqYOR6TtyzNPq1YSIjHv1QHaxxlEcmdhbL9xe72twwAFoqrjfrkH02tRvUma8s4zZ1HK/RjBHriua4Fr34gESpyDcsEvDJgkhGWhQ6UQwmplHG0sBA3qyZa1yraGU5wp6uQ6/y8eXlohqgiMvQqSJ5qcjJQLmYov7KBMuGiTEYW4my5Z9M236p2CevrTHuwe9oDNu0aZXnEX0ydf@GDO5U8LJ7yqJQ6fMwCHatzHgnW75OyiVFdJMqI@gmmbrY38PXE@Jth6fRcjNfAkn096Q21FB8bfk8FfjUtKTZaJGdhxePzErGiODwMt2qrfdHb0uaLYvj4czF8vAeGj1UOVrDMYtwCxSLhV5hrONC@kq0IhnRO/YDI83oyxqruqHcZOI0i@CfHF56famon1r1c@u1Q2ABj2@6@5ZHdZLhVUxpy6xZKZ5rit6hec5tXry8TUBS7vpvhsUbrfMRZXZY/LlHUhpq9ARm8eQPUGBZUhaddVomJp4rtyt1BFUl4jjnTDjIXWxsObPUYU7AMh6wp3aPRXsAkJQEIJv/tt2aCkijT1GM9IcE8pGEY2rr/XE@B2DGIxoE0Z0eYA7J7@Ao1cCO3nR4B1NiPIljzy9Fk1ECSwb4k@fbbm9Nk1EKSwaEkgQHV6VBtjFtlh3G831jgKlqrfkSGhLs7xFNxQxprsosZvFldSpkSyMYYTW2bRfhnnWKsUkHcdrayH0vQicXrqHJOCcohgnBvU0VQkfFDNVAWxrQ8t8JTKTsiFnaLoFrG9ECOMjwsHy5AvYr8SoGYZz89Jz2@bwo6mB0Dxnb89gr1ggF2LMhtOxbaYHHYTjLUdyBwnnwTXp2pcqI5q2kbyZdWvthbC7W66zzGppGGn8DgpoxI@9AWDz4UJwShiAyIzqAMw2kR88MZR5ncDi8bhIJefKZJrGhcoALFjA1zQaIhJTP1emxf@63LT0iF2IOPe@4faIrZ2@GyukjjkNOldTS2Hac9ALIlGdK@Gb5rf7lpe1o789g0mI6SzVp1r0aXzc1MCyS32@2q@kSTCJhMwE71yzQrbvDPU7wKImfRWyWzoNOYjKbGMeraQ3SpsHBdJ7DwPiniPIy4fRwl7GS6GEqtvtiSa8toZ8mY1j3gvbLc2yru0LhaTl7D4S9B1zpu/lzIkZKgXN/siAeZ@xkX5lleLJeKEgSxjyE2kTqD4fMEz1HCbG1Kag/@r@9Pu7ZzDH@qZXGzDduDWcOygbuz9r/ECvoXwaPViG1@wNPAeAqoaiSUeWNWE4HdMsDOJ7NiZungGWPN3iVv@0oddvsWv9UHLSF2IpmZhcuQHwCv2U52Y9h2lUa7/raq/IZbNSxnIfY2yL@sUbAr100zbuRGNt65grvYexzuMptIeIc0tuw6wzpUN4yFNa2eM5IJ@L866ik@e2f6amnXYeft5dVpj19xm1/sY@qWtKedr8JBfvqjBvlJGWTtCEVtmI//qGE@VoYpT1u4rnEWvzr98yVHCNJUOD8139RtSh77HN2eSo9FNVx05dOYwajurXlt6V77kgPFgLWOTWHqy3OvdMuucl5Y7VNxG2pj75Y7hSk1sp66xq0GWhcsb8jmpOw2BVrRhUkIFWO0V@XJCO6XWxoHd04Gxm0LDWmjpY9okKK5tiRwE@0MDVApgPYZ9onzJnbc2vrSiVVJ@BsmDOr0v6ERdn5DADdRIn9OPHyOnvpzYuJAVfh/CwmtyvRfSI/eGBHt2ezNTf@tf7@Y/v2DV7Q@/BvC@loq/rm8XKBZzxupI@ww50H777yJLKrWrwB15rKgQKZuT9wmZ@5h2R@7shM14OPWhLXmdt6o0yZF2hqO9k@HhPpyu8OWS4jHZjn@ywxtfNSU0xEHygZnoNxZbmY/7IaxR1TFHtHYEQ1ppiDdbF/hnTwN@Q67E0Yar7tCsDaS1HssszF2p7K091TfBdTPOlsXFa9SncO0b1Drt7WqN06K3K@KhVjH5iHqg9YzW8FJSkZ9Ec2LE1JuD@/KJm5boyOyI9PKksrWcthbmdTOrW7SPkwLk1mzwiz1yqXM91HV0@bqWQc/y7pyk5tfqlxdgIMKeUKWUbg9TfH@SbyzcR7Gp2uQ9j12avwdvpHgEu9lZZkXQKWMun08UpBs8J4deWu0N/4GWrJrwNlj3Pnrk4VPMz8l2Tpc5vJu5erYu8obKr21DAR2baBgFnj4mXkMDIolUesm@Qs78hUW65rvpZgRCmn16k0uipKaXLsbQEUk8T2ZiifuA1iyYx6UXXIU0XiVr1XOt2WvAYxf@L2jWXWrusD2PMnzZGPJiCb@2NamfN0DMF4Ss8JADmggBEp51kQmL/L9fxiaN9SrjIzy0ZA8izLeiut6tW8pruDrUSaVTNU9u9lUjo/2OVgcJ9vTg9EMsKKYHV64EgQTnnbUxxvc2N1SfbIfH9kuwt7roiNdAHfKdxEwMhh3/0L3T5RrbXhCUnntn3a7i9peq83sQesFfvo1PNV1ek9wrZXw9Ei7HJFuzrCzNNqVpMpwasupQfzxW5QterLtrlJN5E/LXg1I9dGP1TNy4r0GeHnYmGtQdSqKjrROhWvuMF@sibl1hkXGHc8NaW8Vuu23djIo6gWdvEfXduhUKbbv/WkjHtXP@Fqz5nZN1TRm@PLQ/WkNlaM2PI7@jUcNj1ZX3H4RXAlYlzT/L3DZMOV2nMrrCo37d0Q@fhGDqRXild0dRVhg/n1lcIu8vKtFhFoHjSO8elTYXyeD49PbffLy5bPnTM1QP43w5VEBRcT5eCx043883eDVpeIPvGGAH8VcJFGxiU/T5LJPfAAIMvMUvGHsptjUXmXRoK5qGqfZ1OmKYXNkdBpvbJMXjpmaoCHdsQ5DuQWyunNX/2hOjrVcb2Skglpdolv4s/PVFQYS27MahHOmXaR0iDfR0PEBrpCpScvblPc/EaA7rrb0U@0OKBXV7Dwcu7tOvuCF3zGKooQZFPisuhfXlpTJbD2WtUHx9RHsRT0sDQRvq8QX77BTpaQ8lFYlPSnQxgLchQIuALLYYDHOKPNA8GkJLaahPHKEUEU2CRdxLW4KtNQ9FbOZzC6zGOd7vCLlJu@U2XWvphrK9Zy@OOUop1@eDTVFh5FS1siqpT/EZyViiOI61YbzAkp1ETxxHGI7r9rZEY9uHRUGxY2RtQzKrK0cvGl3G3l9qSXNO8sbtjIbWuqbJKr/rd@/1nBuQLxHQ1@oeNNYEqMnx3RTGze2HhP5AvcLGzOv7BMDOXjNQpe/CQzf8siCHhcVLsQ1c3sFI@oBTJEZnu@IPygLGnGiN/tfPERhBiQaT1LUN9k6dWGvXMRXV2JNOW@NI2zI4h17d@/ffXD2zd37NZVTHYZkF/7Vx7B30Ngi9lTE1/3nJApe24PsyoXumrNZfZu1u9eHS8x93iHR4EXXXu1wwEmtnUexDhnbIeOzjrFFsu4zhn36rp3lO/Bo2teikzUHtx7i1nm2djOvPMCrHpcuQ2L42j/9DDCZojklom3l8V/mhTDLCd82FLNT7njaRrz5NsPb1mfiRKxyNA6fi9tqMEDHXijK43WIKszlZTVsUla8JBRkrL9B640rq9xI@ZXne02Lu1x13ZXcnWDX9GBrdcxsWPxFk0qMkQUK8d2GumzsdJQXc3Tw7q2n/P1FjuO8@V17C@qL8@l8NB3P38692Xw8P8P3nk7P3s/mZyezu7@z924q7eWf0wmaHx3@nkL5EDT87/8D)
Try to out-golf me! You'll probably want to consult the [documentation](https://github.com/DRH001/Rattle)
## Explanation
```
B&b&uffalo& creates an array of hard-coded strings: ["B","b","uffalo"," "]
| syntax for taking input
I stores this data in first memory slots
= sets top of stack to 0
[ ... ]4 loops 4 times
b0 adds item in slot 0 to buffer
[2 ... ] executes statements inside if top of stack is equal to 2
b^ deletes last item from buffer
b1 adds item in slot 1 to buffer
b2b3b1b2 adds item in slot 2, 3, 1, 2 to buffer
[3 ... ] executes statement inside if top of stack is equal to 3
q ends program - buffer is implicitly printed
b3 adds item in slot 3 to buffer
+ adds 1 to top of stack
```
[Answer]
# [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate), 27 bytes
```
B((uffalo) b$2 B$2 b$2) b$1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72qKDU9NS-1KLEkdcGCpaUlaboWu500NErT0hJz8jUVklSMFJyAGEiDOIYQFVCFMA0A)
Pretty simple: golf repeated substrings using capture groups.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 18 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
9G*âx{ûbB§╕«Γ╢ô };
```
[Try it online.](https://tio.run/##ASgA1/9tYXRoZ29sZv//OUcqw6J4e8O7YkLCp@KVlcKrzpPilaLDtCB9O///)
`âx{ûbB§╕«Γ╢ô` could alternatively be `à{ENR**╦\i╛δ` for the same byte-count: [try it online](https://tio.run/##y00syUjPz0n7/9/SXevwgmpXvyAtrUdTl8VkPpo6@9wWhVrr//8B).
**Explanation:**
```
9G* # Push 9*18=162
â # Convert it to a binary list
# (which is unfortunately in reversed order due to a bug)
x # Reverse it to the correct order
{ # Loop over each of these bits as integers:
ûbB # Push string "bB"
§ # (0-based) index the current bit into it
╕«Γ # Push compressed string "uffa"
╢ô # Push compressed string "lo"
# Push a space character " "
}; # After the loop: discard the final space
# (after which the entire stack is joined and output implicitly)
à # Convert it to a binary string (in correct order..)
{ # Loop over each of these bits as characters:
ENR** # Push 15*25*29=10875
╦ # Get the dictionary word at this index: "buffalo"
\ # Swap so the current bit is at the top of the stack
i # Convert it from a character to an integer
╛ # If it's truthy:
δ # Titlecase the string
```
[Answer]
# [Scratch](https://scratch.mit.edu), 8 blocks
[](https://i.stack.imgur.com/VmnFx.png)
[Try it on scratch!](https://scratch.mit.edu/projects/754657063/)
I tried to refrain from doing anything too illegal like setting the costume as `Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo` or setting a variable as that.
Here is the scratchblocks code (102 bytes):
```
when gf clicked
for each[i v]in(8){set[B v]to(join(B)(join(letter(i)of[BbBbbbBb])[uffalo ])
}::control
```
Usually when people submit scratch, they submit Tosh (<https://tosh.blob.codes/>), which is Scratch but text-based or an image of the blocks compiled on scratchblocks (<https://scratchblocks.github.io>). I would’ve done both, but the `for each [i v] in (8)` block is old and removed and I can’t figure out how to do it on Tosh.
[Answer]
# [sed](https://www.gnu.org/software/sed/), ~~35~~ 33 bytes
*-2 bytes thanks to [user41805](https://codegolf.stackexchange.com/users/41805/user41805)*
```
s/^/BbBbbbBb/
s/./ &uffalo/g
s///
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlwYKlpSVpuhY3lYr14_SdkpySkoBYn6tYX09fQa00LS0xJ18_HczVh6iEaliwkAvCAAA)
34B solution:
*-1 byte thanks to [user41805](https://codegolf.stackexchange.com/users/41805/user41805)*
```
s/^/B b B b b b B b/
s/\>/uffalo/g
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlwYKlpSVpuhY3lYr14_SdFJIUQDgJQutzFevH2OmXpqUl5uTrp0NUQjUsWMgFYQAA)
35B solution: *(The regex matches empty string at first and then is reused for the second `s` command)*
```
s/b*/B b B b b b B b/i
s//&uffalo/g
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlwYKlpSVpuhY3lYv1k7T0nRSSFEA4CULrZ3IV6-urlaalJebk66dDlEJ1LFjIBWEAAA)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 48 bytes
```
##<>#&//"B"~Print~#["uffalo"~#~b~#~" B",b=" b"]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE7875@WFh1cUpSZl@6Vn5lnZVUMZsf@V1a2sVNW09dXclKqCwAKldQpRyuVpqUl5uQr1SnXJQGxkoKTkk6SrZJCklKs2v//AA "Wolfram Language (Mathematica) – Try It Online")
Port of TiKevin83's [TI-BASIC solution](https://codegolf.stackexchange.com/a/218303/81203).
[Answer]
# [Clojure](https://clojure.org), 60 bytes
```
(clojure.string/join " " (map #(str % "uffalo") "BbBbbbBb"))
```
[Answer]
## C#, 131 bytes
```
using System.Linq;using System;class A{static void Main(){Console.Write($"{String.Join("uffalo ", "BbBbbbBb".ToArray())}uffalo");}}
```
[Try it online!](https://dotnetfiddle.net/B4jteX)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 22 bytes
```
jdm+d"uffalo""BbBbbbBb
```
[Try it online!](https://tio.run/##K6gsyfj/PyslVztFqTQtLTEnX0nJKckpKQmI//8HAA "Pyth – Try It Online")
[Answer]
# [jq](https://stedolan.github.io/jq/), 35 characters
```
"BbBbbbBb "/""|join("uffalo ")[:-2]
```
Sample run:
```
bash-5.0$ jq -nr '"BbBbbbBb "/""|join("uffalo ")[:-2]'
Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo
```
[Try it online!](https://tio.run/##TU@7CgIxEOz9iiE2CgbB0tJOCy0sxSJ3t2okt3uXbBTBbze@ECymmve5L0NEauVC0BPB2uiuVrJ2WVFL2zpubPBMkE69MFRwJMVqu1njKxsMMVqiJceTH/tOSho9H0FcB0nUwDMayVUg9FmU0gRJcJOMRJ/qSPAJLNDofHhbU@dqGhezqBZV9QLM1Jj7WTyPTD4cXBCY8W5uZ/tSHt95qVjLOQTr@bWs/L95Ag "jq – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 23 22 bytes
Save a byte thanks to @Scott!
```
V"BbBbbbBb"p+N"uffalo
```
[Try it online!](https://tio.run/##K6gsyfj/381PySnJKSkJiJUKtP2UStPSEnPyFf7/BwA "Pyth – Try It Online")
---
I wanted to be smart and encode the state of the upper- and lowercase letters as bits, but that ended up taking a byte more. Here's the code and explanation anyway!
### 24 bytes
```
FNj162 2p+?N\B\b"uffalo
```
```
FN # loop with N
j162 2 # convert 162 into binary as list of bits
p # print without newlines
+ # concatinate strings
?N\B\b # ternary operator, checks if the bit is falsey (0)
"ufallo # note the trailing space
```
] |
[Question]
[
# Challenge:
Read input (within visible ASCII range) and output with a few modifications:
1. In each set of 10 characters of the input randomly (50/50):
* replace one character\* (with a random\*\* one within visible ASCII range) (ex. `lumberjack` becomes `lumbeZjack`)
* or remove one character (ex. `lumberjack` becomes `lmberjack`)
\* If the set is of less than 10 characters, you don't have to modify it, but you can.
\*\* The character can be the same as the one input, as long as it's still random.
# Example:
Input: `Go home cat! You're drunk!`
Output: `Go hom cat! YouLre drunk!`
(just a example, since output could be random, don't use as a test case)
# Rules:
* [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), least characters wins!
[Answer]
# Pyth, ~~27~~ 25 bytes
```
VczTpXNOT?<JOr\ \ÞKC127JK
```
[Test suite available here.](http://pyth.herokuapp.com/?code=VczTpXNOT%3F%3CJOr%5C+%5C%C3%9EKC127JK&input=Go+home+cat%21+You%27re+drunk%21&test_suite=1&test_suite_input=lumberjack%0AGo+home+cat%21+You%27re+drunk%21%0APerhaps+I+should+not+use+test+cases+from+the+question%2C+as+the+output+can+be+different+from+those+examples+and+still+be+correct%21&debug=0)
Thanks to [Maltysen](https://codegolf.stackexchange.com/questions/103355/this-cat-has-bugs-really/103376#comment251583_103376) for shaving off 2 bytes.
# Explanation
```
VczTpXNOT?<JOr\ \ÞKC127JK z autoinitalizes to input, T autoinitializes to 10
czT chop input into strings of length 10, returned as list of strings
V for each string N in this list:
Or\ \Þ randomly pick a char between ' ' (32) and 'Þ' (222)
J and assign it to variable J
KC127 assign the DEL char to variable K
?<J K if J < K:
XNOT J replace a random character in N with J
?<J K else:
XNOT K replace a random character in N with K
p print this string with no trailing newline
```
As is often the case, I feel that this is a bit of a naive method and may be improved upon. Usually I find something obvious while typing up the explanation but nothing jumped out at me this time.
[Answer]
## [\*><>](https://esolangs.org/wiki/Starfish), ~~44~~ ~~46~~ ~~52~~ 50 bytes
```
rl5(?voooo/!|Ou+1Ox:@=?~o~oooo!
ol5(?v" ":/
o;!?l<
```
[Try it here!](https://starfish.000webhostapp.com/?script=E4GwrAFA-Abg9guB6AhAHwPIFcDUBGDADwC4ABAXigD84bEUAoOcaGAIgAI3ikmBuFFBAAeIA)
This uses any ascii character near/above space for the random characters. This always edits the 6th character, unless it's the end of a string and that string's length isn't a multiple of 10. This has a 50% chance to remove the 7th character instead of editing the 6th.
### Input
>
> The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a
> technical standard for floating-point computation established in 1985
> by the Institute of Electrical and Electronics Engineers (IEEE). The
> standard addressed many problems found in the diverse floating point
> implementations that made them difficult to use reliably and portably.
> Many hardware floating point units now use the IEEE 754 standard.
>
>
>
### Output
>
> The IEE Standardfor Float$ng-Point Aithmetic (EEE 754) i a technicl
> standar! for floa!ing-point!computati#n establised in 1985by the
> Insitute of !lectrical#and Electrnics Engi!eers (IEE%). The st!ndard
> add!essed man! problems#found in !he divers! floating oint
> impl!mentation" that mad# them dif!icult to ue reliabl# and port!bly.
> Many!hardware foating po#nt units %ow use th! IEEE 754"standard.
>
>
>
Edit: ~~This answer probably isn't always in the visible ascii range, editing...~~ Fixed.
Edit2: ~~Didn't see there needs to be a 50/50 chance to remove a character, editing again...~~ I believe everything is in order now :).
[Answer]
# [Perl 6](https://perl6.org), ~~78~~ 67 bytes
```
{[~] map {~S/.**{(^.chars).pick}<(./{(' '..'~').pick x Bool.pick}/},.comb(10)}
```
```
{[~] .comb(10)».&{~S/.**{10.rand}<(./{(' '..'~').pick x 2.rand}/}}
```
[Try it](https://tio.run/nexus/perl6#@19anKpQZqaXbM2VW6mglpyfkqpgq1AdXReroJecn5ukYWigeWi3nlp1XbC@npZWtaGBXlFiXkqtjYaefrWGuoK6np56nbqmXkFmcrZChYIRRFa/tparOLFSAWzc@72L3PMVMvJzUxWSE0sUFSLzS9WLUhVSikrzshXf712skJZfpBBnaPD/PwA "Perl 6 – TIO Nexus")
## Explanation:
```
{
[~] # reduce with string concatenation operator
.comb(10)\ # take input and break it into chunks of up-to 10 chars
».\ # on each of them call the following
&{
~ # Stringify the following
S/ # substituted
. # any char
** # repeated
{ 10.rand } # a random number of times
<( # ignore all of that
. # the char to be removed/replaced
/{
( ' ' .. '~' ).pick # choose a character
x # string repeated
2.rand # zero or one times
}/
}
}
```
[Answer]
# Pyth - 21 bytes
```
smO,XdOTOr;\~.DdOTcQT
```
[Try it online here](http://pyth.herokuapp.com/?code=smO%2CXdOTOr%3B%5C%7E.DdOTcQT&input=%22Go%20home%20cat%21%20You%27re%20drunk%21%22&debug=0).
[Answer]
# [Python 3](https://docs.python.org/3/), 75 bytes
The 75-byte applies the transformation to the first character of each group, and only picks from 2 random characters, such as in [the Jelly answer](https://codegolf.stackexchange.com/a/103394/60919) (which OP allowed):
```
from random import*
f=lambda s:s and choice(['','a','b'])+s[1:10]+f(s[10:])
```
[**Try it online!**](https://tio.run/nexus/python3#DYm7DoQgEAD7@4o9G0AttCW5@j6A0lCsPCK5gzUbLPx6pJjMJNMiUwbG4rtSPonr@IqfP@bdIxhtoC9wByUX5CbELLCzC6sms616XewUZa9FW9VOTqXKKIcvwUE5gMM6w02X4ACer/J7D0q1Bw)
This is a recursive function which, every iteration, prepends either nothing, `'a'`, or `'b'`, and then calls itself with the first 10 characters sliced off. The final iteration short circuits at `s and` (an empty string is falsy), avoiding infinite recursion.
The result of all the separate calls are then concatenated, and returned to the context which called the function.
# 120 bytes
Of course, that feels a bit like cheating, so here's one which is completely random:
```
from random import*;r=randint
def f(S):a=S[:10];R=r(0,len(a)-1);print(end=a[:R]+chr(r(32,126))*r(0,1)+a[R+1:]);f(S[10:])
```
[**Try it online!**](https://tio.run/nexus/python3#JYyxDoMgFEX3fgV16XtKE7FJBwhzdxyJAxGIphXMiw79eovpdE9uzr1HpLwwcsmXmJc101Yr0mcxp@3iQ2QRepRO91aKdlBGE7T8ExI4vAtUKxUPQvLaWWmGZpwICB4dF90TsT5lgY2zphFyQFXOrGgLHf9hhOqV2ZSXwEa3cfbN@40C87Sn97VCPH4)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes
```
₀ẇ⟑ẏ℅kP¤"℅℅Ȧ₴
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigoDhuofin5Hhuo/ihIVrUMKkXCLihIXihIXIpuKCtCIsIiIsIlwiR28gaG9tZSBjYXQhIFlvdSdyZSBkcnVuayFcIiJd)
```
₀ẇ # Chunks of length 10...
⟑ # Over each...
Ȧ # Replace at ...
ẏ℅ # random index in the input
℅ # A random item of...
℅ # A random item of...
kP # Printable ascii
¤" # Or the empty string
₴ #
```
[Answer]
**Clojure, ~~135~~ 139 bytes**
Edit: Forgot to use `partition-all` instead of `partition`.
```
(fn[i](apply str(flatten(map #(let[r rand-int [b e](split-at(r 9)%)][b(if(<(rand)0.5)""(char(+(r 25)97)))(rest e)])(partition-all 10 i)))))
```
Ungolfed:
```
(def f (fn[i]
(->> i
(partition-all 10)
(map #(let [[begin end] (split-at (rand-int 9) %)]
[begin (if (< 0.5 (rand)) "" (char (+(rand-int 25)97))) (rest end)]))
flatten
(apply str))))
```
Man those function names are long... Anyway, it splits input into partitions of 10 characters, splits them at random point into two halves, randomly injects an empty string or a random character between them and discards the first character of the 2nd half.
[Answer]
## Mathematica 133 Bytes (129 characters)
```
StringReplacePart[#,Table[If[(r=RandomInteger)[]<1,"",FromCharacterCode@r@128],c=⌊StringLength@#/10⌋],Array[{g=10#-9+r@9,g}&,c]]&
```
76 characters to write the names of 8 functions :/
Using the `⌊..⌋` instead of `Floor[]` saves 5 characters, 1 byte.
[Answer]
# Python 3, 129 bytes
```
def f(s):f=id(s)%9+1;print(''.join(j[0:f-1]+chr(33+id(s)%94)*(id(s)//10%2)+j[f:]for j in [s[i:i+10]for i in range(0,len(s),10)]))
```
In order to save some bytes, instead of importing Python's random module, I just did some modulo operations on the id of the string, which should be different every time. For example the program will decide whether or not to remove a char or replace one based on whether or not `id(string)//10` is even (I integer divide by 10 as the last digit will always be even).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15 14~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) 13 characters
```
2X
s⁵µ¢1¦ṫ¢µ€
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=MlgKc-KBtcK1wqIxwqbhuavCosK14oKs&input=&args=TG9yZW0gSXBzdW0uIFNlZCB1dCBwZXJzcGljaWF0aXMsIHVuZGUgb21uaXMgaXN0ZSBuYXR1cyBlcnJvciBzaXQgdm9sdXB0YXRlbSBhY2N1c2FudGl1bSBkb2xvcmVtcXVlIGxhdWRhbnRpdW0sIHRvdGFtIHJlbSBhcGVyaWFtIGVhcXVlIGlwc2EsIHF1YWUgYWIgaWxsbyBpbnZlbnRvcmUgdmVyaXRhdGlzIGV0IHF1YXNpIGFyY2hpdGVjdG8gYmVhdGFlIHZpdGFlIGRpY3RhIHN1bnQsIGV4cGxpY2Fiby4gTmVtbyBlbmltIGlwc2FtIHZvbHVwdGF0ZW0sIHF1aWEgdm9sdXB0YXMgc2l0LCBhc3Blcm5hdHVyIGF1dCBvZGl0IGF1dCBmdWdpdCwgc2VkIHF1aWEgY29uc2VxdXVudHVyIG1hZ25pIGRvbG9yZXMgZW9zLCBxdWkgcmF0aW9uZSB2b2x1cHRhdGVtIHNlcXVpIG5lc2NpdW50LCBuZXF1ZSBwb3JybyBxdWlzcXVhbSBlc3QsIHF1aSBkb2xvcmVtIGlwc3VtLCBxdWlhIGRvbG9yIHNpdCBhbWV0IGNvbnNlY3RldHVyIGFkaXBpc2NpW25nXSB2ZWxpdCwgc2VkIHF1aWEgbm9uIG51bXF1YW0gW2RvXSBlaXVzIG1vZGkgdGVtcG9yYSBpbmNpW2RpXWR1bnQsIHV0IGxhYm9yZSBldCBkb2xvcmUgbWFnbmFtIGFsaXF1YW0gcXVhZXJhdCB2b2x1cHRhdGVtLiBVdCBlbmltIGFkIG1pbmltYSB2ZW5pYW0sIHF1aXMgbm9zdHJ1bSBleGVyY2l0YXRpb25lbSB1bGxhbSBjb3Jwb3JpcyBzdXNjaXBpdCBsYWJvcmlvc2FtLCBuaXNpIHV0IGFsaXF1aWQgZXggZWEgY29tbW9kaSBjb25zZXF1YXR1cj8gUXVpcyBhdXRlbSB2ZWwgZXVtIGl1cmUgcmVwcmVoZW5kZXJpdCwgcXVpIGluIGVhIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlLCBxdWFtIG5paGlsIG1vbGVzdGlhZSBjb25zZXF1YXR1ciwgdmVsIGlsbHVtLCBxdWkgZG9sb3JlbSBldW0gZnVnaWF0LCBxdW8gdm9sdXB0YXMgbnVsbGEgcGFyaWF0dXIu)**
Replaces or removes the first of every ten characters including that of the last 1-9 if there is such a chunk. Chooses from the, admittedly small, subset of characters: `1`; `2`.
### How?
```
2X - Link 1, flip a coin: no arguments
X - random choice from
2 - 2 (treated as the integers [1,2])
s⁵µ¢1¦ṫ¢µ€ - Main link: string of printable ASCII
s⁵ - split (s) into chunks of size ten (⁵)
µ µ - monadic chain separation
€ - for each chunk
¢ - last link as a nilad
1¦ - apply to index 1 (replace 1st of the 10 char chunk with the chosen integer)
¢ - last link as a nilad
ṫ - tail - if it was 1 this has no effect (50%)
- if it was 2 this discards the replaced character (50%)
- implicit print
```
---
To choose from all of printable ASCII rather than just `1` and `2` (still replacing or removing the 1st character of each chunk) in 21 bytes:
```
s⁵µ32r126¤ỌX¤1¦ṫ2X¤µ€
```
---
For a [fully random version](http://jelly.tryitonline.net/#code=OTVSKzMx4buMWDsKCnPigbXCteG5meKBtVjCpMKp4bmWMljCpMS_4bmZwq5DwqTCteKCrA&input=&args=TG9yZW0gSXBzdW0uIFNlZCB1dCBwZXJzcGljaWF0aXMsIHVuZGUgb21uaXMgaXN0ZSBuYXR1cyBlcnJvciBzaXQgdm9sdXB0YXRlbSBhY2N1c2FudGl1bSBkb2xvcmVtcXVlIGxhdWRhbnRpdW0sIHRvdGFtIHJlbSBhcGVyaWFtIGVhcXVlIGlwc2EsIHF1YWUgYWIgaWxsbyBpbnZlbnRvcmUgdmVyaXRhdGlzIGV0IHF1YXNpIGFyY2hpdGVjdG8gYmVhdGFlIHZpdGFlIGRpY3RhIHN1bnQsIGV4cGxpY2Fiby4gTmVtbyBlbmltIGlwc2FtIHZvbHVwdGF0ZW0sIHF1aWEgdm9sdXB0YXMgc2l0LCBhc3Blcm5hdHVyIGF1dCBvZGl0IGF1dCBmdWdpdCwgc2VkIHF1aWEgY29uc2VxdXVudHVyIG1hZ25pIGRvbG9yZXMgZW9zLCBxdWkgcmF0aW9uZSB2b2x1cHRhdGVtIHNlcXVpIG5lc2NpdW50LCBuZXF1ZSBwb3JybyBxdWlzcXVhbSBlc3QsIHF1aSBkb2xvcmVtIGlwc3VtLCBxdWlhIGRvbG9yIHNpdCBhbWV0IGNvbnNlY3RldHVyIGFkaXBpc2NpW25nXSB2ZWxpdCwgc2VkIHF1aWEgbm9uIG51bXF1YW0gW2RvXSBlaXVzIG1vZGkgdGVtcG9yYSBpbmNpW2RpXWR1bnQsIHV0IGxhYm9yZSBldCBkb2xvcmUgbWFnbmFtIGFsaXF1YW0gcXVhZXJhdCB2b2x1cHRhdGVtLiBVdCBlbmltIGFkIG1pbmltYSB2ZW5pYW0sIHF1aXMgbm9zdHJ1bSBleGVyY2l0YXRpb25lbSB1bGxhbSBjb3Jwb3JpcyBzdXNjaXBpdCBsYWJvcmlvc2FtLCBuaXNpIHV0IGFsaXF1aWQgZXggZWEgY29tbW9kaSBjb25zZXF1YXR1cj8gUXVpcyBhdXRlbSB2ZWwgZXVtIGl1cmUgcmVwcmVoZW5kZXJpdCwgcXVpIGluIGVhIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlLCBxdWFtIG5paGlsIG1vbGVzdGlhZSBjb25zZXF1YXR1ciwgdmVsIGlsbHVtLCBxdWkgZG9sb3JlbSBldW0gZnVnaWF0LCBxdW8gdm9sdXB0YXMgbnVsbGEgcGFyaWF0dXIu) (50/50 remove/replace, uniform random printable ASCII, and a uniformly random character location within each chunk) I have 30 bytes (probably non-optimal):
```
95R+31ỌX;
s⁵µṙ⁵X¤©Ṗ2X¤Ŀṙ®C¤µ€
```
This rotates each chunk left by a random amount, pops the last character off and then calls a random one of the first two links, one of which is empty and the other which concatenates with a random printable ASCII character; it then rotates the chunk right again.
[Answer]
# Python3, ~~188~~ ~~186~~ ~~184~~ 114 characters
```
from random import*
s=input()
for c in[s[i:i+10]for i in range(0,len(s),10)]:print(end=choice(["","x","y"])+c[1:])
```
~~Seems too long. Could probably be shortened a lot with a lambda.~~
Apparently the OP has allowed choosing the random character from a list of two characters and the index of the character to be replaced can be a constant. After the modifications, my answer would've looked exactly the same as [@FlipTacks](https://codegolf.stackexchange.com/a/105194/41754) Python submission, so this is the form I'm staying with.
[@FlipTack](https://codegolf.stackexchange.com/users/60919/fliptack) saved 5 bytes!
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-pl`, 52 bytes
```
gsub(/.{10}/){_1[rand 0..9]=[*" "..?~,""].sample
_1}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnm0km5BjlLsgqWlJWm6FjdN0otLkzT09aoNDWr1NavjDaOLEvNSFAz09CxjbaO1lBSU9PTs63SUlGL1ihNzC3JSueINayF6oUYs2OWer5CRn5uqkJxYoqgQmV-qXpSqkFJUmpetCFEBAA)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 46 bytes
```
Fi(a<>t){IRR2YiRARR#iRCPAEL{YiRARR#ix}b:bAEy}b
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJGaShhPD50KXtJUlIyWWlSQVJSI2lSQ1BBRUx7WWlSQVJSI2l4fWI6YkFFeX1iIiwiIiwiIiwiXCJHbyBob21lIGNhdCEgWW91J3JlIGRydW5rIVwiIl0=)
How?
```
Fi(a<>t){IRR2YiRARR#iRCPAEL{YiRARR#ix}b:bAEy}b
Fi { } - For each in
t - Var for 10
a<>t - Split input into 10 pieces
I - If truthy
RR2 - 0 or 1
Y - Yank (equivalent to (y:a)):
RA - Replace item in at index
i - First input
RR#i - Random int from 0 to length of input
RCPA - Random Printable ASCII character
EL{ } - Else
Y - Yank:
RA - Replace item in at index
i - First input
RR#i - Random int from 0 to length of input
x - Empty string
b: - Assign b to
bAEy - Append y to b
b - Output b
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
TôεžQΩæΩ9ÝΩǝ?
```
Also (potentially) modifies the last part if it's less than 10 characters.
[Try it online](https://tio.run/##AUQAu/9vc2FiaWX//1TDtM61xb5RzqnDps6pOcOdzqnHnT///0dvIGhvbWUgY2F0ISBZb3UncmUgZHJ1bmsh/y0tbm8tbGF6eQ) or [see 10 example outputs at once](https://tio.run/##AUsAtP9vc2FiaWX/VEb/VMO0zrXFvlHOqcOmzqk5w53OqcedP/99XMK2P/9HbyBob21lIGNhdCEgWW91J3JlIGRydW5rIf8tLW5vLWxhenk).
**Explanation:**
```
Tô # Split the (implicit) input-string into parts of size 10
# (where the trailing part is potentially smaller)
ε # Foreach over the parts:
žQ # Push the printable ASCII string constant
Ω # Pop and push a random character from it
æ # Get the powerset of this character, resulting in a pair of an empty
# string "" and the character
Ω # Pop and push a random item from this pair
9Ý # Push list [0,1,2,3,4,5,6,7,8,9]
Ω # Pop and push a random digit from this list
ǝ # Replace the character at that (0-based) index with the chosen ASCII
# character or the empty string
# (if the index is ≥ the length, it does nothing)
? # Pop and print the modified part
```
] |
[Question]
[
### Your task
Given a string of lowercase letters, output the "alphabet checksum" of that string, as a letter.
### Example
Let's say we have the string *"helloworld"*. With `a = 0`, `b = 1`, `c = 2` ... `z = 25`, we can replace all of the letters with numbers:
```
h e l l o w o r l d
7 4 11 11 14 22 14 17 11 3
```
Now, we can sum these:
```
7+4+11+11+14+22+14+17+11+3 = 114
```
If we mod this by 26, we get:
```
114 % 26 = 10
```
Now, using the same numbering system as before, get the 10th letter, `k`. This is our answer.
### Test cases
```
Input Output
helloworld k
abcdef p
codegolf h
stackexchange e
aaaaa a
```
**This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.**
[Answer]
# [Zsh](https://www.zsh.org/), 41 bytes
```
a=(+##${(s..)^1}+7)
<<<${(#)$((a%26+97))}
```
[Try it online!](https://tio.run/##dY1LCsIwGIT3PYWQCvkJFHRhEeJVhLyjjY021dZIzx6TA@RbzQNmYrBJY8CJXTBBqP3h0HVwPWykh4ZSmgMELcZsfzyRcw@wJWgavbPKOb/4yclsGBdS6SyEl8p4V2SYmRjUKiwbjcr@tahp/r5v/umGuzVaBhZX8eHjowxUySWvUh6r5DJWSX8 "Zsh – Try It Online")
`(s..)`plit, `^` RC-style expand as `+##${1[1]}+7 +##${1[2]}+7 ...`. Then `(#)` evaluate the expression as character codes.
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$10\log\_{256}(96)\approx\$ 8.231 bytes
```
ica%26S+7C
```
Using [Arnauld's](https://codegolf.stackexchange.com/users/58563/arnauld) logic. Accepts a list of characters
[Try it online!](https://fig.fly.dev/#WyJpY2ElMjZTKzdDIiwiW3MsdCxhLGMsayxlLHgsYyxoLGEsbixnLGVdIl0=)
```
ica%26S+7C
C # str -> char code, vectorises
+7 # add 7 to each item
S # sum
%26 # sum % 26
ca # lowercase alphabet
i # index intro ca using result
```
# Alternate \$13\log\_{256}(96)\approx\$ 10.701 bytes
```
ica%26SM'lxca
```
[Try it online!](https://fig.fly.dev/#WyJpY2ElMjZTTSdseGNhIiwiW3MsdCxhLGMsayxlLHgsYyxoLGEsbixnLGVdIl0=)
```
ica%26SM'lxca
ca # lowercase alphabet
x # input
M'l # map find over x where we look for each char in ca, returns index
S # sum
%26 # sum % 26
ica # index into ca using the result
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 46
```
t;f(char*s){for(t=0;*s;)t+=*s++-97;t=t%26+97;}
```
[Try it online!](https://tio.run/##ZU/LTsMwEDwnX7EERXLiFFUcQMikX1Bx4wQVStfOQ6QOsjdQqcq3BzsuqlD3sJode2dmcdUgzjOJmmFbmdxmp3owjMq1yK3IiJe55Xz19CiopPT@gTs0zbedxn6UCp4tSanqu3YT/@O6wVNxpwkOVaeBeVSZBgvwNpA7/J3BKQZXgSFlCSur7NsOSvcSJa3q@@FnML1MCjdWe3RWC8RBqmbow2Cpwk91dCq6UeGnL49eXrfbxWISFydLBu14CIzPRfjRyaOIF8JdDywwLsZawCVXYHdwU4IXFudFzv0h0VnWLdXsaicTcfRlnFnNktTCagMpvuukuFYv/vJlIeC0dKNoNNrFiaf5Fw "C (gcc) – Try It Online")
[Answer]
# ARM Thumb machine code, 18 bytes
```
61 20 04 c9 61 3a 10 44 fb d5 1a 38 fd d2 7b 30
70 47
```
Assembler source:
```
.syntax unified
.arch armv7-a
.thumb
.globl alpha_checksum
.thumb_func
// Input: r1: null terminated UTF-32LE string
// Output: r0
// Clobbers: r0-r2
alpha_checksum:
// Initial accumulator. Start at 'a' to cancel the checksum
// loop adding '\0' - 'a' when the null terminator is reached.
movs r0, #'a'
.Lloop:
// Load character, increment pointer
ldmia r1!, {r2}
// Subtract 'a' to convert to a number, set flags
// In the case of the null terminator, this will result in
// -'a', which ends the loop condition below.
subs r2, #'a'
// Add to the checksum, without setting the flags
add r0, r2
// Loop if the subs didn't return negative,
// which happens only with the null terminator.
bpl .Lloop
.Lend:
// Calculate (checksum % 26) - 26 using a naive subtraction loop
.Lmodulo:
// Subtract 26
subs r0, #26
// Loop while it was >= 26
bhs .Lmodulo
// Add 26 to correct the modulo, and 'a' to convert to ASCII.
adds r0, #'a' + 26
// Return
bx lr
```
This can be called from C using a dummy parameter to place `ptr` in `r1`.
`ptr` is expected to be a pointer to a null terminated UTF-32LE string.
```
char32_t alpha_checksum(int dummy, const char32_t *ptr);
```
[Answer]
# [Clojure](https://clojure.org/), 65 bytes
```
(defn a[s](char(+(mod(apply + (map #(- % 97)(map int s)))26)97)))
```
[Try it online!](https://tio.run/##dY4xDsIwDEV3TmEFVbJVsTCAOAswGCdtgTSOkiLg9CEwE29@78v@4vX2SK4UtG4IwMd8Rpk4YY@zWuQY/Rt6wJkjrHEDHRz29NuuYYFMRNsdVURUMKbKBjCdnIIBZDCT816fmrw1RKs/Ab5I/duQotaN6ls6Lyx396ptw@ha979TXfkA "Clojure – Try It Online")
Ungolfed:
```
(defn alpha-checksum [s]
(char (+ (mod (apply + (map #(- % 97) (map int s))) 26) 97)))
```
[Answer]
# [Wren](https://github.com/munificent/wren), 47 bytes
```
Fn.new{|s|(s.bytes.reduce{|x,y|x+7+y}+7)%26+97}
```
[Try it online!](https://tio.run/##FYuxCsMgGIT3PoUECorBoUNDh06FzoWMpYPR3yTUaFHbRGKe3cZb7uPjbnZg8o87pK75bpiBeU0@Yc@6GMAzB/IrYE1LHdNCGxo32pDj6UwvzZaVdQh7NBr0rAbQ2s7WaVnVFe@EBLWDsBJ6qwv6wMUbFjFw00PZlFQvgtYDQm30ASb2caMJuA179Uw5O932/8MWqZjgWmNPCDls@Q8 "Wren – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes
```
§βΣES⌕βι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMOxxDMvJbVCI0lHIbg0V8M3sUDDM6@gtCS4BCidrqGpo@CWmZcCks7UBAHr//@LSxKTs1MrkjMS89JT/@uW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
E Map over characters
ι Current character
⌕ Find index in
β Predefined variable lowercase alphabet
Σ Take the sum
§ Cyclically indexed into
β Predefined variable lowercase alphabet
Implicitly print
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 25 bytes
```
0T1>`l`L
+T`l__L`zlL_`^..
```
[Try it online!](https://tio.run/##FcFBCoAgEADA@/4jCAKpD3Tt4tFz7qarRouCBUWfN5qpfO2ZWtcv2EYzzSioYTAo1mp8RVtclWotsUi5SxUPtDnPAVzxHIsEOC9yBz8uUY4M9PsA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
0T1>`l`L
```
Uppercase all letters after the first.
```
+T`l__L`zlL_`^..
```
While there are at least two letters, repeatedly rotate the first letter backwards and the second letter forwards in the alphabet, however the first letter rotates back from `a` to `z` while the second letter drops off when it passes `Z`, allowing subsequent letters to be processed.
The `l` and `L` in the patters expand to the lowercase and uppercase alphabet respectively. The `_` in the source pattern is just a placeholder to allow the use of `l` and `L` in the destination pattern, while in the destination pattern it indicates that the character is to be deleted.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 20 bytes
```
C(($+(7+A*a))%26+97)
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJDKCgkKyg3K0EqYSkpJTI2Kzk3KSIsIiIsIiIsImhlbGxvd29ybGQiXQ==)
Probably could be shorter, I feel like there are just way too many parentheses.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 15 bytes
```
'a'+26|·+´-⟜'a'
```
[Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=Q2hlY2tzdW0g4oaQICdhJysyNnzCtyvCtC3in5wnYScKQ2hlY2tzdW0gImhlbGxvd29ybGQi)
```
'a'+26|·+´-⟜'a'
-⟜'a' # subtract 'a' from each letter of input
+´ # sum
· # (no-op to preserve train syntax)
26| # modulo 26
'a'+ # add 'a'
```
[Answer]
# [Gema](http://gema.sourceforge.net/), 77 characters
```
?=@set{s;@add{${s;};@add{@char-int{?};7}}}
\Z=@int-char{@add{@mod{$s;26};97}}
```
(Yepp. Arithmetic operations are a pain in Gema.)
Sample run:
```
bash-5.1$ echo -n helloworld | gema '?=@set{s;@add{${s;};@add{@char-int{?};7}}};\Z=@int-char{@add{@mod{$s;26};97}}'
k
```
[Try it online!](https://tio.run/##S0/NTfz/397WoTi1pLrY2iExJaVaBciohTAdkjMSi3Qz80qq7WutzWtra7liomwdgHxdkEQ1RE1uPlBPsbWRWa21JVDN//8ZqTk5@eX5RTkpAA "Gema – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), 72 bytes
```
([...s])=>String.fromCharCode(s.map(c=>t+=c.charCodeAt()+7,t=0)|t%26+97)
```
[Try it online!](https://tio.run/##Zc6xDoIwEIDh3adoSEzaoMU4iA4lMTyCo3GoR1uQQknboIPvXiGgA954@XL/PXjPHdiq89v@GCQL@EopdTfCsou3VauotKbJS25zUwjsaMM7DCzzMQMK8/rsMYnTjWc78vbr/SE@pSSAaZ3RgmqjsMRRKbQ2T2N1ESGECEFJgurVAvE7FEKOAP1Qt0QwFJXRM5tQuUTOc6jFa/iwVSKakPjLjfOtzZd4@AA "JavaScript (V8) – Try It Online")
[Answer]
# PowerShell, 54 bytes
```
$s.tochararray()|%{$r+=([char]$_)-97};[char]($r%26+97)
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvUqxgq6AEYuaX5xflpCgBRfRK8pMzEosSi4oSKzU0a1SrVYq0bTWiQWKxKvGaupbmtdYQnoZKkaqRmbalueb//wA "PowerShell – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 16 bytes
```
zPK$+(A*a-97)%26
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJ6UEskKyhBKmEtOTcpJTI2IiwiIiwiIiwiaGVsbG93b3JsZCJd)
[Answer]
## x86‑64 assembly machine code, 30 B
### input
* unsigned length of string in 64‑bit register `rdi`
* address of string buffer in 64‑bit register `rsi`
### code listing
```
1 alphabet_checksum:
2 0000 6A61 push 'a' ; push(97)
3 0002 58 pop rax ; pop(rax)
4 0003 F7E7 mul edi ; edx○eax ≔ eax × edi
5
6 0005 F7D8 neg eax ; eax ≔ −eax; CF ≔ eax ≠ 0
7 0007 7310 jnc .adjust ; if ¬CF then goto adjust
8 .sum:
9 0009 0FB64C3EFF movzx ecx, byte [rsi+rdi-1] ; ecx ≔ (rsi + rdi − 1)↑
10 000E 01C8 add eax, ecx ; eax ≔ eax + ecx
11 0010 FFCF dec edi ; edi ≔ edi − 1; ZF ≔ edi = 0
12 0012 75F5 jnz .sum ; if ¬ZF then goto sum
13
14 0014 6A1A push 26 ; push(26)
15 0016 5F pop rdi ; pop(rdi)
16 0017 F7F7 div edi ; edx ≔ edx○eax mod edi
17 .adjust:
18 0019 92 xchg eax, edx ; eax ≔ edx
19 001A 83C061 add eax, 'a' ; eax ≔ eax + 97
20 001D C3 ret
```
### output
* alphabet checksum as ASCII character in 64‑bit register `rax`
### limitations
* length of string must be ≤ 44,278,013, else the `mul` spills into `edx`, yet the algorithm relies on `edx` being `0` in the case of a zero-length string
[Answer]
# [Haskell](https://www.haskell.org/), 43 bytes
```
f s=['a'..]!!mod(sum[fromEnum c-97|c<-s])26
```
[Try it online!](https://tio.run/##Vcy9DoIwFAXgvU9x6QImlsFBYyKjo09AGK79oYT@EArRRH32Kigaz3Ryc@6nMbTSmBgVhKJMMc3zKkmsF1kYbal6b49utMDZfnfnBxaq1WYbLTYOCrDYnSDr@sYNkINaQUn1y/IX3xtB10DxzIVUU@NeyNqbuYcBeSuvXKOr5TybQitCboz8AJjSkrcBSzqyUJ@DJn8egCSz9/0AJOwRnw "Haskell – Try It Online")
### Same-length alternative:
```
f s=['a'..]!!mod(sum$do c<-s;1<$['b'..c])26
```
[Try it online!](https://tio.run/##VcxNDoIwEAXg/ZxiaEiQREh04UY4gicgLIa2UEJLCcVoYjx7BRSNb/UyP58i10mtva/R5UVEUZqWQWCs2LmrCYVFniXufMjCIqrmHS/j48kbanvM0dBwwd0wtv2EKdYxFkzNlr3ZUQu2R0YVF7JeGrdCNlav3U3EO3nnivpGrmdLWAnwSOAH4JIO3gZuGWCjPgMFfx6ihNX7fiBB8vQv "Haskell – Try It Online")
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang) (v2), 36 bytes
```
;=sP;=i@O;Ws;=i+~-97iAs=s]sA+97%i 26
```
[Try it online!](https://knight-lang.netlify.app/#WyI7PXNQOz1pQE87V3M7PWkrfi05N2lBcz1zXXNBKzk3JWkgMjYiLCJoZWxsb3dvcmxkIiwiMi4wIl0=)
I feel like you can golf better but i tried for awhile and gave up
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), ~~26~~ 24 bytes
* -2 bytes thanks to @Eminga. I didn't want to change the input mode to stack though so I didn't use all the golfing potential. Also I wanted to exit properly and not just error.
```
0i:0(?v+7+2d*%!
o+"a"~<;
```
[Animated Version](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiMGk6MCg/dis3KzJkKiUhXG5vK1wiYVwifjw7IiwiaW5wdXQiOiJoZWxsb3dvcmxkIiwic3RhY2siOiIiLCJtb2RlIjoibnVtYmVycyJ9)
## Explanation:
```
0
```
Push 0, the starting value
```
i:0(?v
```
Check if the input is negative, if so go down.
```
+7+2d*%
```
Add 7+the input to the accumulator, then mod 26
```
!
```
Skip the 0 the second time, since the accumulator is already set
```
~"a"+o;
```
(Reversed in the program)
Print "a" + the accumulator.
[Answer]
# [Uiua](https://uiua.org), 11 [bytes](https://www.uiua.org/pad?src=U0JDUyDihpAgK0BcMOKKlwpEZWNvZGUg4oaQIOKHjOKKjy0x4pa9wrEu4o2Y4ouv4oav4oqCwq8x4qe74ouv4qe7LOKHjOKItSjihpjCrzHii68rMjU2KSAtQFwwKzEKJnAg4oqCIjggYml0IGVuY29kaW5nOlx0IiBTQkNTICLih4ziio8tMeKWvcKxLuKNmOKLr-KGr-KKgsKvMeKnu-KLr-Knuyzih4ziiLUo4oaYwq8x4ouvKzI1NikiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIKJnAg4oqCImRlY29kZWQ6XHQiIERlY29kZSAiwqPCsS0xwrjChy7DjMKlwrPCsMKIMcKfwqXCnyzCo8K_KMK1wogxwqUrMjU2KSIg4oqCK0BcMOKHoTEyOSIuLOKItjviiJjCrMKxwq_ijLXiiJril4vijIrijIjigYU94omgPOKJpD7iiaUrLcOXw7fil7_igb_igpnihqfihqXiiKDip7vilrPih6HiiqLih4zima3ii6_ijYnijY_ijZbiipriipviip3ilqHiipTiiYXiip_iioLiio_iiqHihq_ihpnihpjihrvil6vilr3ijJXiiIriipcv4oinXFziiLXiiaHiiLriip7iiqDijaXiipXiipziiKniipPiioPiipnii4XijZjijZzijZrirJonP-KNo-KNpCHijovihqzimoLOt8-Az4TiiJ5-X1tde30oKcKvQCRcIuKGkHwjIg==)
```
+@a◿26/+-@a
```
[Try it!](https://uiua.org/pad?src=ZiDihpAgK0Bh4pe_MjYvKy1AYQoKZiAiaGVsbG93b3JsZCIKZiAiYWJjZGVmIgpmICJjb2RlZ29sZiIKZiAic3RhY2tleGNoYW5nZSIKZiAiYWFhYWEi)
```
+@a◿26/+-@a
-@a # convert string to code points
/+ # sum
◿26 # modulo 26
+@a # add the letter a
```
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~76~~ 73 bytes
-3 thanks to @[ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
I think this is as much golf as you can get without using a completely different method. Other people ~~will probably prove me wrong the moment I hit "Post."~~ have in fact proven me wrong.
```
#import<ios>
int f(char*s){int t=0;for(;*s;t+=*s++-97);putchar(t%26+97);}
```
[Try it online!](https://tio.run/##jY5BCoMwEEXX9RTBUoiKULpoqdHeJZ0kKo1JSEZaEM9ujT1And2f/3h8cK5sAZbl2A/Oeqx7Gx5Jb5AoCh33ecimmLA5M2U9ZXlgWDR5KIryfsuYGzFiFE@XaxEf82oyoEchSXShl3z4CQfeG5qRKTkomnZSa/u2Xos0Y8khoKgqsCOSuiZbkEbotdhg/gQh1Q4QrJCt1XvQgBxe8rOON63csyHeH24myxc "C++ (gcc) – Try It Online")
### Ungolfed
We used `#import<ios>` so we can `putchar()`.
```
int f(char* s) {
int t = 0; // Running total
for(;*s != 0;t += *s++ - 97); // Loop through string until we get to null byte, add to running total
putchar(t % 26 + 97); // Add 97 to final result and print
}
```
[Answer]
# [Arturo](https://arturo-lang.io), 29 bytes
```
$[a][+97(sum map a=>[+7])%26]
```
[Try it](http://arturo-lang.io/playground?2aJrIX)
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 91 bytes
```
++[++[->+>+<<]>>[--<<+>>]<],[[-[->+<]>]>>>>>>>,]+[<<<<<<<<<<<<<<<<<<<<<<<<<<+<[-----.[>]]>]
```
[Try it online!](https://tio.run/##dYtLCoAwDAUP9BpPEHKRkEUtVUuhCz/g7WN07/BWb5h5z20sV@nugMZIIGA2ESVihoixJVV6TdwhPpJB@Rdw1MGkYtG4H2cuvd5ly2OtDw "brainfuck – Try It Online")
```
++[++[->+>+<<]>>[--<<+>>]<] Init memory with 1,2,3,...,127
,[[-[->+<]>]>>>>>>>,] Reading each byte, move right that many steps
+[<<<<<<<<<<<<<<<<<<<<<<<<<<+< Go left 26 and check if empty
[-----.[>]]>] If not empty, give shift, output and halt
```
[Answer]
# Dyalog APL v18, 28 bytes\*
```
{a[1+26|+/1-⍨(a←¯1∘⎕C⎕A)⍳⍵]}
```
Assuming that indices start from one (`⎕IO←1`).
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
\*: APL can be written in its own legacy charset (defined by `⎕AV`) instead of Unicode; therefore an APL program that only uses ASCII characters and APL symbols can be scored as 1 char = 1 byte.
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 6 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
Ä⁻S⁺ÄL
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMyU4NCVFMiU4MSVCQlMlRTIlODElQkElQzMlODRMJmZvb3Rlcj0maW5wdXQ9aGVsbG93b3JsZCZmbGFncz0=)
#### Explanation
```
Ä⁻S⁺ÄL # Implicit input
Ä # 1-based index in alphabet
⁻ # Decrement to make 0-indexed
S # Sum the resulting list
⁺ # Increment for 1-indexing
Ä # 1-based convert to letter
L # Lowercase it
# Implicit output
```
] |
[Question]
[
# Background
The [Copeland–Erdős constant](https://en.wikipedia.org/wiki/Copeland%E2%80%93Erd%C5%91s_constant) is the concatenation of "0." with the base 10 representations of the prime numbers in order. Its value is
```
0.23571113171923293137414...
```
See also [OEIS A033308](https://oeis.org/A033308).
Copeland and Erdős proved that this is a [normal number](https://en.wikipedia.org/wiki/Normal_number). This implies that every natural number can be found at some point in the decimal expansion of the Copeland-Erdős constant.
# The challenge
Given a positive integer, express it in base 10 (without leading zeros) and output the index of its first appearance within the sequence of decimal digits of the Copeland–Erdős constant.
Any reasonable input and output format is allowed, but input and output should be in base 10. In particular, the input can be read as a string; and in that case it can be assumed not to contain leading zeros.
Output may be 0-based or 1-based, starting from the first decimal of the constant.
The actual results may be limited by data type, memory or computing power, and thus the program may fail for some test cases. But:
* It should work in theory (i.e. not taking those limitations into account) for any input.
* It should work in practice for at least the first four cases, and for each of them the result should be produced in less than a minute.
# Test cases
Output is here given as 1-based.
```
13 --> 7 # Any prime is of course easy to find
997 --> 44 # ... and seems to always appear at a position less than itself
999 --> 1013 # Of course some numbers do appear later than themselves
314 --> 219 # Approximations to pi are also present
31416 --> 67858 # ... although one may have to go deep to find them
33308 --> 16304 # Number of the referred OEIS sequence: check
36398 --> 39386 # My PPCG ID. Hey, the result is a permutation of the input!
1234567 --> 11047265 # This one may take a while to find
```
[Answer]
# Python 2, 64 bytes
```
f=lambda n,k=2,m=1,s='':-~s.find(`n`)or f(n,k+1,m*k*k,s+m%k*`k`)
```
Returns the 1-based index. Test it on [Ideone](http://ideone.com/hDwIIu).
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 14 bytes
Uses **0-indexed output**. Prime functions in osabie are *very* inefficient. Code:
```
[NØJD¹å#]¹.Oð¢
```
Explanation:
```
[ ] # Infinite loop...
N # Get the iteration value
Ø # Get the nth prime
J # Join the stack
D # Duplicate this value
¹å# # If the input is in this string, break out of the loop
¹.O # Overlap function (due to a bug, I couldn't use the index command)
ð¢ # Count spaces and implicitly print
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=W07DmEpEwrnDpSNdwrkuT8OwwqI&input=OTk5).
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ÆRDFṡL}i
Ḥçßç?
çD
```
Returns the 1-based index. [Try it online!](http://jelly.tryitonline.net/#code=w4ZSREbhuaFMfWkK4bikw6fDn8OnPwrDp0Q&input=&args=MQ) or [verify most test cases](http://jelly.tryitonline.net/#code=w4ZSREbhuaFMfWkK4bikw6fDn8OnPwrDp0QKxbzDh-KCrEc&input=&args=MTMsIDk5NywgOTk5LCAzMTQsIDMxNDE2LCAzMzMwOCwgMzYzOTg).
I've verified the last test case locally; it took 8 minutes and 48 seconds.
### How it works
```
çD Main link. Argument: n (integer)
D Decimal; yield A, the array of base 10 digits of n.
ç Call the second helper link with arguments n and A.
Ḥçßç? Second helper link. Left argument: n. Right argument: A.
Ḥ Unhalve; yield 2n.
? If...
ç the first helper link called with 2n and A returns a non-zero integer:
ç Return that integer.
Else:
ß Recursively call the second helper link with arguments 2n and A.
ÆRDFṡL}i First helper link. Left argument: k. Right argument: A.
ÆR Prime range; yield the array of all primes up to k.
DF Convert each prime to base 10 and flatten the resulting nested array.
L} Yield l, the length of A.
ṡ Split the flattened array into overlapping slices of length l.
i Find the 1-based index of A in the result (0 if not found).
```
## Alternate version, 11 bytes (non-competing)
```
ÆRVw³
ḤÇßÇ?
```
The `w` atom did not exist when this challenge was posted. [Try it online!](http://jelly.tryitonline.net/#code=w4ZSVnfCswrhuKTDh8Ofw4c_&input=&args=OTk5)
### How it works
```
ḤÇßÇ? Main link. Argument: n (integer)
Ḥ Unhalve; yield 2n.
? If...
Ç the helper link called with argument 2n returns a non-zero integer:
Ç Return that integer.
Else:
ß Recursively call the main link with argument 2n.
ÆRVw³ Helper link. Argument: k (integer)
ÆR Prime range; yield the array of all primes up to k.
V Eval; concatenate all primes, forming a single integer.
³ Yield the first command-line argument (original value of n).
w Windowed index of; find the 1-based index of the digits of the result to
the right in the digits of the result to the left (0 if not found).
```
[Answer]
## Actually, 19 bytes
```
╗1`r♂Pεj╜@íu`;)╓i@ƒ
```
Takes a string as input and outputs the 1-based index of the substring
[Try it online!](http://actually.tryitonline.net/#code=4pWXMWBy4pmCUM61auKVnEDDrXVgOynilZNpQMaS&input=IjEzIg)
Explanation:
```
╗1`r♂Pεj╜@íu`;)╓i@ƒ
╗ push input to register 0
`r♂Pεj╜@íu`;) push this function twice, moving one copy to the bottom of the stack:
r♂Pεj concatenate primes from 0 to n-1 (inclusive)
╜@íu 1-based index of input, 0 if not found
1 ╓ find first value of n (starting from n = 0) where the function returns a truthy value
i@ flatten the list and move the other copy of the function on top
ƒ call the function again to get the 1-based index
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
€ṁdİpd
```
[Try it online!](https://tio.run/##yygtzv7//1HTmoc7G1OObChI@f//v7GhCQA "Husk – Try It Online")
Prime number infinite list babyyyyy
[Answer]
# Julia, 55 bytes
```
\(n,s="$n",r=searchindex(n|>primes|>join,s))=r>0?r:3n\s
```
Returns the 1-based index. Completes all test cases in under a second. [Try it online!](http://julia.tryitonline.net/#code=XChuLHM9IiRuIixyPXNlYXJjaGluZGV4KG58PnByaW1lc3w-am9pbixzKSk9cj4wP3I6M25ccwoKZm9yIG4gaW4gKDEzLCA5OTcsIDk5OSwgMzE0LCAzMTQxNiwgMzMzMDgsIDM2Mzk4LCAxMjM0NTY3KQogICAgQHByaW50ZigiJTh1IC0tPiAlOXVcbiIsIG4sIFwobikpCmVuZA&input=)
[Answer]
# Pyth, 17 bytes
```
fhJxs`MfP_YSTz2J
```
Leading space is important.
[Test suite.](http://pyth.herokuapp.com/?code=+fhJxs%60MfP_YSTz2J&test_suite=1&test_suite_input=13%0A997%0A314&debug=0)
[Answer]
# [J](http://jsoftware.com), 37 bytes
```
(0{":@[I.@E.[:;<@":@p:@i.@]) ::($:+:)
```
Input is given as a base 10 integer and the output uses zero-based indexing.
## Usage
```
f =: (0{":@[I.@E.[:;<@":@p:@i.@]) ::($:+:)
f 1
4
f 13
6
f 31416
67857
```
## Explanation
This first call treats the verb as a monad, however subsequent calls which may occur recursively treat it as a dyad.
```
0{":@[I.@E.[:;<@":@p:@i.@] Input: n on LHS, k on RHS
] Get k
i.@ Get the range [0, 1, ..., k-1]
p:@ Get the kth prime of each
":@ Convert each to a string
<@ Box each string
[:; Unbox each and concatenate to get a string of primes
[ Get n
":@ Convert n to a string
I.@E. Find the indices where the string n appears in
the string of primes
0{ Take the first result and return it - This will cause an error
if there are no matches
(...) ::($:+:) Input: n on RHS, k on LHS
(...) Execute the above on n and k
::( ) If there is an error, execute this instead
+: Double k
$: Call recursively on n and 2k
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-rprime`, 48 bytes
0-based.
```
->n{s=""
Prime.find{s<<_1.to_s=~/#{n}/}
$`.size}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7CI326WlJWm6FjcNdO3yqottlZS4AkBSemmZeSnVxTY28YZ6JfnxxbZ1-srVebX6tVwqCXrFmVWptRB9qwoU3KKNDU0MzWIhAgsWQGgA)
[Answer]
# [Raku](https://raku.org/), 45 bytes
```
{{$~={$_ x.is-prime}(++$)}...*~~/$_/;$/.from}
```
[Try it online!](https://tio.run/##DcpLCoAgFAXQrVziEX3oSRSFlG1FGiQESWGTQnTr1uDMzrW5Y0j2RW6gkvcUlSeNh/e7udxut1DUNZWBmasYBWkxkWDjThvSvb7I/qwWeAPSIYM5Hea2g5TjT6Jr@yV9 "Perl 6 – Try It Online")
Really had to dig deep to bring the byte count way down here. The code generates a warning, but oh well!
The first bracketed expression generates strings consisting of the concatenation of successive primes. `++$` increments an anonymous state variable, and that number is passed to an anonymous function `{ $_ x .is-prime }`, which replicates the stringified number once if it's prime, and zero times (ie, to an empty string) if it isn't. That string is appended to another anonymous state variable that keeps the concatenation of all primes seen so far with `$ ~=`. The sequence looks like `2, 23, 23, 235, 235, 2357, 2357, 2357, 2357, 235711, ...`, with a repeated element whenever there isn't a prime. Very inefficient!
The sequence terminates when the ending condition `* ~~ /$_/` is met; that is, when the concatenated string of primes matches the input number interpolated into a regex. That has the side effect of storing the resulting Match object into `$/`. Then the function just returns `$/.from`, the starting position of the match in the string of primes.
[Answer]
## PowerShell v2+, 90 bytes
```
for($a="0.";!($b=$a.IndexOf($args)+1)){for(;'1'*++$i-match'^(?!(..+)\1+$)..'){$a+=$i}}$b-2
```
Combines the logic of my [Find the number in the Champernowne constant](https://codegolf.stackexchange.com/a/66884/42963) answer, coupled with the prime generation method of my [Print the nth prime that contains n](https://codegolf.stackexchange.com/a/80446/42963) answer, then subtracts `2` to output the index appropriately (i.e., not counting the `0.` at the start).
Takes input as a string. Finds the `999` one in about seven seconds on my machine, but the `33308` one in quite a bit longer (*edit - I gave up after 90 minutes*). Should theoretically work for any value up to index `[Int32]::Maxvalue` aka `2147483647`, as that's the maximum length of .NET strings. Will likely run into memory issues long before that happens, however.
] |
[Question]
[
## Introduction
[OEIS sequence A127421](https://oeis.org/A127421 "OEIS sequence A127421") is the sequence of numbers whose decimal expansion is a concatenation of 2 consecutive increasing non-negative numbers. Put simply, every number in the sequence is formed by putting together *n* with *n+1* for some non-negative, integer value of *n*. The first several terms are:
>
> 1, 12, 23, 34, 45, 56, 67, 78, 89, 910, 1011, 1112, 1213, 1314, 1415,
> 1516, 1617, 1718, 1819, 1920, 2021, 2122, 2223, 2324, 2425, 2526,
> 2627, 2728, 2829, 2930, 3031, 3132, 3233, 3334, 3435, 3536, 3637,
> 3738, 3839, 3940, 4041, 4142, 4243, 4344, 4445, 4546, …
>
>
>
## Challenge
Given a single positive integer *n*, print the first *n* entries of OEIS sequence A127421 in increasing order.
* Input and output can be in [any acceptable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Strings or numbers are fine for output.
* Leading zeroes are **not** permitted.
* Either a full program or function is permitted.
* For the purposes of this challenge, *n* will be positive and under 100.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed by default.
* This question is code golf, so lowest byte-count wins.
* Here is some sample input and output:
```
1 => 1
2 => 1, 12
3 => 1, 12, 23
10 => 1, 12, 23, 34, 45, 56, 67, 78, 89, 910
```
If you have any questions, don't hesitate to ask. Good luck.
*P.S this is my first challenge, so hopefully this all makes sense.*
*EDIT: Removed output restriction to allow numbers or strings.*
[Answer]
# Twig, 72 bytes
Twig is very verbose, causing some issues when trying to reduce the length.
```
{%macro f(a)%}{%for i in 1..a%}{{o~i}}
{%set o=i%}{%endfor%}{%endmacro%}
```
This requires that "strict variables" is disabled (default).
---
## How to use?
Simply import the macro and call it:
```
{% import "fn.twig" as fn %}
{{ fn.f(<number>) }}
```
You can test it on <https://twigfiddle.com/lah1a5>
[Answer]
# [Haskell](https://www.haskell.org/), 35 bytes
```
f n="1":map(show.(-1+)<>show)[2..n]
```
[Try it online! 1](https://tio.run/##FcbBCgIhEAbgV/nZkxJJdgzdS117gugwsG4rrTOiAz2@1eGDb6P@Tvs@cqnSFDdScndhyQsMTJgt7FjBcfLTpVA1fZOPM0d/sGH@3z7OzvFzFMqMiNoyKxzWn5ZoQQwBr6RXYU2sffjTFw "Haskell – Try It Online")
## Explanation / Ungolfed
The operator `(<>)` is the addition of Semigroups, in case of the Semigroup `a -> b` (where `b` needs to be a Semigroup) it is defined as:
```
(f <> g) = \x-> f x <> g x
```
And in case of the Semigroup `String` it is the same as concatenation, so the code becomes:
```
f n = "1" : map (\x-> show (x-1) ++ show x) [2..n]
```
---
1 (imports `(<>)` since it's not part of the Prelude in GHC 8.2.2)
[Answer]
## TI-Basic, 22 bytes
```
:seq(A,A,1,Ans
:Ans+(Ans-1)10^(1+int(log(Ans
```
[Answer]
# Bash, 56 bytes
```
echo 1;for i in $(seq $(($1-1)));do echo $i$((i+1));done
```
A pretty naive approach.
[Answer]
# [Lua](https://www.lua.org), 62 bytes
```
loadstring't={1}for i=2,(...)do t[#t+1]=(i-1)..i end return t'
```
[Try it online!](https://tio.run/##DcJBCgIxDADArwQ9bIJrsN77EvFQt60ESgMxiwfx7dFhxl6i5xha6stN5nPx/EnfrgaSrysyM1UFvx39lO4Z5ZyIWaDNCtZ8twm@hCi/Tbyhl8dovOnciiNAx3QhgBUO/0QRPw "Lua – Try It Online")
---
### Explanation
This is an anonymous function.
```
t={1} -- initializes the return table, with the number 1 already in it
for i = 2, (...) do -- loop from 2 to the number of the input
-- (this is actual code, ... gets the arguments of the program/function
t[#t+1] = (i-1)..i -- append to the table i-1 concatenated with i
end
return t -- returns the table
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~34~~ 33 bytes
```
->n{$><<i||=p(1);p(i+=1)<n&&redo}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsXOxiazpsa2QMNQ07pAI1Pb1lDTJk9NrSg1Jb/2f1q0oUHsfwA "Ruby – Try It Online")
Pseudocode:
```
loop
if i is undefined
set i to 1
print 1
print newline
end if
print i
increment i by 1
print i
print newline
if i >= n
break and return
end if
end loop
```
[Answer]
# [Swift 4](https://developer.apple.com/swift/), 43 bytes
```
print(1);(1..<n).map{print("\($0)\($0+1)")}
```
[Try it online!](https://tio.run/##Ky7PTCsx@Z@TWqKQp2Cr4JlXolGUmpjik5mXqqGpqKn4v6AoEyhmqGmtYainZ5OnqZebWFANEVSK0VAx0AQR2oaaSpq1//8bAwA "Swift 4 – Try It Online")
`n` is the input of the program
[Answer]
# [Noether](https://github.com/beta-decay/Noether), 15 bytes
```
I(iWi1+W+WP?!i)
```
[Try it online!](https://tio.run/##y8tPLclILfr/31MjMzzTUDtcOzw@wF4xU/P/f0MDAA "Noether – Try It Online")
## Explanation
```
I( ) - Loop until the top of the stack equals the input
iW - Push i and convert it to a string
i1+W - Add one to i and convert to string
+ - Concatenate two strings
WP - Convert string to a number and print it
? - Print a newline
!i - Increment i
```
[Answer]
**VBA (Excel), 31 bytes**
using immediate window and Cell `[A1]` as input
`for x=1to[a1]:?int(x-1 &x):next`
[Answer]
# [Python 2](https://docs.python.org/2/), 42 bytes
I know there are plenty of shorter answers already.
```
a=0
exec"print`a`[:a]+`a+1`;a+=1;"*input()
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9HWgCu1IjVZqaAoM68kITEh2ioxVjshUdswwTpR29bQWkkrM6@gtERD8/9/QwMA "Python 2 – Try It Online")
[Answer]
# [Pepe](https://github.com/Soaku/Pepe), 68 bytes
```
RrEEEEEREeErREEREEEEEREErEEEEEeEErEEEereEEreeErEEEEEeeEReerREEREeRee
```
[Try it online!](https://soaku.github.io/Pepe/#--iR@F-jFS6!oMIS2/@FD/)
Previous code has errors when giving input 0, so this is fixed!
Explanation:
```
# Preparation
RrEEEEE # Stack r: [0, 1]
REeE # Stack R: [input]
# Loop
rREE # create label input (r flag: skip until REe)
REEEEE # increment input (loop preparation)
REE # create label input
rEEEEEeEE # join all
rEEEe # move r pointer to last
reEE # output as int
reeE # output newline "\n"
rEEEEEeeE # increment all
Ree # repeat if input != last content of stack
rREE # create label input + 1 (r flag: skip until REe)
REe # stop skipping commands
Ree # if not 0, go to loop
```
[Answer]
# [Microscript II](https://github.com/SuperJedi224/Microscript-II), 16 bytes
```
1vsN-s{lPps1+v}*
```
Output is newline-separated.
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 11 bytes
```
IFLL?nLPN|;
```
[Try it online!](https://tio.run/##S8/PScsszvj/39PNx8c@zyfAr8b6/39DAwMA "Gol><> – Try It Online")
Explanation:
```
IFLL?nLPN|;
I //Take a number as input
F //Loop as many times as the input specified
LL // Push the loop counter twice to the stack (same as L:)
?n // Check wether the count is zero, if not print the counter as the first digit
LP // Push the loop counter and add 1
N // Output the next digits of the number with nl
|; //Exit code
```
[Answer]
# [Dart](https://www.dartlang.org/), ~~46~~ 45 bytes
```
f(n)=>List.generate(n,(e)=>e<1?1:'$e${e+1}');
```
- -1 byte by replacing `e==0` by `e<1`
[Try it online!](https://tio.run/##S0ksKvn/P00jT9PWziezuEQvPTUvtSixJFUjT0cjFSiYamNob2ilrpKqUp2qbVirrmn9vyw/M0UhNzEzT0OzmouzoCgzr0QjTcNQU9MajaegAOcbofGN0fiGBiCB2v8A "Dart – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), ~~43~~ 41 bytes
```
{(1..it).mapIndexed{i,v->"$i$v".toInt()}}
```
[Try it online!](https://tio.run/##NY3BCoMwEETvfsUSPOxCDS29iab0KHjrFwRMZamuElNpEb89DQXnNsxj3msKA0t8vgVGy4LW90sJd@/tt3oEz9Ibgi2DlNUOkDZsJBAUBlpeQpWKgTpueNGaA@nRzo107uO6jU9rYVTO@ap0mBKItO/xeBKoAb2zXcvikOBWgjorOsi/cU7@gAsKUbbH6w8 "Kotlin – Try It Online")
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), 29 bytes
```
;=n+0P;=i 0W>n iO+0++""i=i+1i
```
[Try it online!](https://knight-lang.netlify.app/#WyI7PW4rMFA7PWkgMFc+biBpTyswKytcIlwiaT1pKzFpIiwiMTAiLCIyLjAiXQ==)
[Answer]
# [Gema](http://gema.sourceforge.net/), 42 characters
```
*=@repeat{*;${n;}@set{n;@add{${n;};1}}$n }
```
Sample run:
```
bash-5.1$ gema '*=@repeat{*;${n;}@set{n;@add{${n;};1}}$n }' <<< 5
1 12 23 34 45
```
[Try it online!](https://tio.run/##S0/NTfz/X8vWoSi1IDWxpFrLWqU6z7rWoTi1BEg7JKakVIMFrA1ra1XyFGr//zc0BQA "Gema – Try It Online")
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 12 bytes
```
Rrp[:u`u' o]
```
[Try it online!](https://tio.run/##y6n8/z@oqCDaqjShVF0hP/b/f1NTAA "Ly – Try It Online")
This is pretty brute force, but short enough to warrant a post I think...
```
R - generate an inclusive rangefrom "0" to the STDIN number
rp - reverse the stack, delete the "0"
[ ] - for each number on the stack...
:u - duplicate number, print it
`u - increment the number, print it
' o - print a space
```
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 26 bytes
```
a=$1{for(;a;a--)$a=a a+1}1
```
[Try it online!](https://tio.run/##SyzP/v8/0VbFsDotv0jDOtE6UVdXUyXRNlEhUduw1vD/f2MTAA "AWK – Try It Online")
Turns out that a version in AWK is pretty short too, so here's that one...
```
a=$1 - stash the number we want
{ } - code always runs if STDIN>0
for(;a;a--) - loop for N, N-1, N-2, ... 1
$a=a a+1 - set positional var to N appended w/ N+1
1 - print all the positional vars we just set
```
This really just abuses the fact that AWK will reset the positional variable count if you set them to a value. And it uses a "truthy" condition with no associated code block to print them all.
[Answer]
# [Go](https://go.dev), 122 bytes, using string operations
```
import(."strconv";."fmt")
func f(n int)(o[]int){for i:=0;i<n;i++{k,_:=Atoi(Sprintf("%d%d",i,i+1))
o=append(o,k)}
return o}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY49CsJAEIX7nGJZEGZJlEQbMaawsxQsRSQk2TDEzCzrxsLgSWyCYOeFvI1GBbF6fPD-LteSu7tJsyotC1GnSLfG6eH0ccLasHUwkgdnM6ajjEdS104qTzeUCQ0kkJwC3mx7bTVbgbMkjHFOMfp-WwW7WbJwjLA29mXRIAf5IJcBBuhHSnmcpMYUlAMHlTp7tnCNJcHn74Ple6e_BEq03qrv2BNo6LM_Gv_R5I-i8IXfvq776BM)
# [Go](https://go.dev), 125 bytes, using formula
```
import."math"
func f(n int)(o[]int){for i:=0;i<n;i++{o=append(o,i*int(Pow10(1+int(Floor(Log10(float64(i)+1)))))+i+1)}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VU9BasNADLz7FYtPsretvUkIpamvPfXge0hgSbyOqC2ZZU0Pxi_pxRTyiDwlv8naTqERCGmGGUb6-S15uDT68KXLQtQaKcC6YeteQlO78Nw68_x67f-4WrtTGJiWDsIACSQXAW934-wMW4FvWbrBd9qglB1numkKOgI_YewlkPO3SkHJcf-omC18cukZU7F26xVgJFU0lkS_9IEtXGupvx9BSSIoVukelJDCTP6KS6DJ5CnyrebjxkcgEl2QWx9WERjwon9o8YCWD0ilHt5Th2GeNw)
Uses the formula \$a(n) = n\cdot10^{1 + \lfloor\log\_{10}(n+1))\rfloor} + n + 1\$ for \$n \ge 0\$.
[Answer]
# SAS
Input is passed by:
```
%let n=123;
```
# 4GL - 38
```
data;
do i=1to &n;x=cats(i-1,i)+0;put x;end;
run;
```
The `data;` and `run;` are obligatory for every 4GL data step, so the code effectively doing the job is in line 2.
# Macrolanguage - 44
```
%macro
m(n,x);%do i=1%to&n;%put&x&i;%let x=&i;%end;
%mend;
```
The `%macro` and `%mend;` are obligatory for every Macroprogram, so the code effectively doing the job is in line 2.
To run macro execute:
```
%m(&n)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 29 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 3.625 bytes
```
ʀzṅ⌊
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiyoB64bmF4oyKIiwiIiwiMTAiXQ==)
## Explained
```
ɾzṅ
ɾ # range [1, input]
z # overlapping pairs (equivalent to 2l)
ṅ # concatenate each pair into a single string
```
] |
[Question]
[
In this challenge you will take as input a non-empty list of binary values (these can be booleans or integers on the range 0-1), you should output all the ways to partition the list into non-empty sections such that no two adjacent equal values in the initial list are separated into different sections.
For example if the input is `[1,1,0,0,1]` then `[1,1],[0,0,1]` is a valid partition but `[1,1,0],[0,1]` is not since the adjacent `0`s are divided.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes.
## Test cases
```
[1,0] ->
[ [[1,0]]
, [[1],[0]]
]
[1,1,1,1] ->
[ [[1,1,1,1]]
]
[1,1,0,0,1] ->
[ [[1,1,0,0,1]]
, [[1,1],[0,0,1]]
, [[1,1,0,0],[1]]
, [[1,1],[0,0],[1]]
]
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 22 bytes
```
{(&'+1,!2-1_=':x)_\:x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rWUFPXNtRRNNI1jLdVt6rQjI+xqqjl4uJKczBUMACTYAhlGQChIQBVpwuO)
`1_=':x` For pairs of adjacent values: are they equal?
`2-` 2 minus that. Gives 2s for the lines between sections and 1s in sections.
`!` odometer. Returns a matrix with all binary patterns bounded by the vector.
`+1,` prepend a 1 and transpose to have the binary patterns with leading 1s in the rows.
`&'` Get indices of 1s for each row.
`(...)_\:x` For each of those integer vectors, split the input at those indices.
[Answer]
# [Factor](https://factorcode.org) + `math.combinatorics math.unicode`, 81 bytes
```
[ dup 2 clump [ Σ 1 = ] arg-where 1 v+n all-subsets [ split-indices ] with map ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PU4xTsQwEOzvFdOjWAcVAiHRIRokhKiiFD5nL1mR2MZe34EQD0E0kRC8gHfQ329wznDaYnZ2dmfn_Wutjbgw7d7u765vrs7wQMHSgC645Nl2GLX0Klk2riVEekxkDUVFTxJ0LOqGZos_Yty4YqvzgE1E9AOLzD6HU_hAIs8-sBWcLxYvOMYSr3ss9d8vc2X2mWRdne5ua7TJ4wRmSKNHjZ-PrF6ggQ5dte0pUOabIws9DFVMq0gS89o-QsW25fl5gy1Ln6N6NMX4u4ZSKgs5uXeRIIEvizRNBX8B)
* `dup 2 clump [ Σ 1 = ] arg-where 1 v+n` get the indices of rising and falling edges
* `all-subsets` take all the subsets of that
* `[ split-indices ] with map` split the input according to each of these
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ITŒP‘œṖ€
```
A monadic Link that accepts a list of ones and zeros and yields a list of the valid partitions.
**[Try it online!](https://tio.run/##y0rNyan8/98z5OikgEcNM45Ofrhz2qOmNf8Ptx@d9HDnDCAz8v//aEMdQx0DIDREggaxAA "Jelly – Try It Online")**
### How?
```
ITŒP‘œṖ€ - Link: list, B e.g. [0, 0, 1, 1, 0, 1]
I - deltas (of B) [ 0, 1, 0,-1, 1]
T - truthy indices [ 2, 4, 5]
ŒP - powerset [[],[2],[4],[5],[2,4],[2,5],[4,5],[2,4,5]]
‘ - increment [[],[3],[5],[6],[3,5],[3,6],[5,6],[3,5,6]]
€ - for each:
œṖ - partition (B) at [[[0,0,1,1,0,1]],[[0,0],[1,1,0,1]],[[0,0,1,1],[0,1]],[[0,0,1,1,0],[1]],[[0,0],[1,1],[0,1]],[[0,0],[1,1,0],[1]],[[0,0,1,1],[0],[1]],[[0,0],[1,1],[0],[1]]]
```
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 40 bytes
```
f(a++b:c:d)|b/=c=(a++[b]):f(c:d)
f a=[a]
```
[Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NI1FbO8kq2SpFsyZJ3zbZFsSPTorVtErTAAlypSkk2kYnxv7PTczMU7BVSFOINtQx1DEAQsPY/wA "Curry (PAKCS) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
ĠøṖvvf
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQQSIsIiIsIsSgw7jhuZZ2dmYiLCIiLCJbMSwwXVxuWzEsMSwxLDFdXG5bMSwxLDAsMCwxXSJd)
Port of @UnrelatedString's Brachylog answer.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 (or 4?) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
γ.œ€€˜
```
[Try it online](https://tio.run/##yy9OTMpM/f//3Ga9o5MfNa0BotNz/v@PNtQx1DEAQsNYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c5v1jk5@1LQGiE7P@a/zPzraUMcgVgdIgiGUZQCEhrGxAA).
If we can use strings as I/O, this could be 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) instead by replacing `€€˜` with `J`:
[Try it online](https://tio.run/##yy9OTMpM/f//3Ga9o5O9/v83NDQwMAQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c5v1jk72@q/zP9rQQMcQCICEgYFhLAA).
**Explanation:**
```
γ # Split the (implicit) input-list into groups of equal adjacent values
.œ # Get all partitions of these groups
€ # For each partition:
€ # For each part of groups within a partition:
˜ # Flatten the part of groups to a single list
# (or alternatively:)
J # Join each list/part of groups within each partition together
# (after which the result is output implicitly)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
ḅ~ccᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/w93tNYlJ4NY/6OjDXUMYnWAJBhCWQZAaBgbCwA "Brachylog – Try It Online")
Takes a list through the input variable and [generates](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) a list of lists of lists through the output variable.
```
ḅ Partition into runs of consecutive equal elements.
~c Take an arbitrary partition of the list of runs,
cᵐ and concatenate each slice.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 20 bytes
```
Ė!|ḅa₀cPl;?b₍↰;Pgᵗ↔c
```
A predicate that takes a list of 0's and 1's as input and outputs each possible partition [one after another](https://codegolf.meta.stackexchange.com/a/9134/16766).
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh7s6H3Ut/X9kmmLNwx2tiY@aGpIDcqztkx419QIVWAekP9w6/VHblOT//6MNdQx1DIDQMBYA "Brachylog – Try It Online")
### Explanation
This seems way too long.
```
Ė!|ḅa₀cPl;?b₍↰;Pgᵗ↔c
Ė! Either the input is an empty list (in which case return empty list)
| Or, take the input and...
ḅ Partition into blocks of equal elements
a₀ Get a prefix of that list of blocks
c Flatten it
P Call that list P
l Take its length
;?b₍ The original input with that many elements removed from the front
↰ Recurse (returns a list of lists)
;P Pair with P
gᵗ wrapped in a list
↔ Reverse the order of the pair
c Flatten once
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 65 bytes
```
Q+[E|F]:-append(A,[B,C|D],Q),B\=C,append(A,[B],E),[C|D]+F.
Q+[Q].
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P1A72rXGLdZKN7GgIDUvRcNRJ9pJx7nGJVYnUFPHKcbWWQdJIlbHVVMnGiSr7abHBdQaGKv330pXIS2/KDEnRyPaUMdQxwAIDWO1g3QUyosyS1Jz8jSCNDX1/gMA "Prolog (SWI) – Try It Online")
Similar to @alephalpha's Curry answer. Outputs as a list of choicepoints.
[Answer]
# [J](http://jsoftware.com/), 27 bytes
```
<;.1~1,.[:(#:[:i.*/)2-2=/\]
```
[Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/baz1DOsMdfSirTSUraKtMvW09DWNdI1s9WNi/2tycaUmZ@QrpCkYKhggmGAI5@oY6hgAoeF/AA "J – Try It Online")
*-1 bytes thanks to the "2 minus" trick stolen from ovs's answer*
Say we have, eg, `1,1,0,0,1` -- then we have 2 "change points" and 4 possible combos. This is *essentially* just the problem of listing:
```
0 0
0 1
1 0
1 1
```
except we want that that list to be embedded in the `X`s of this list:
```
0 X 0 X
```
The key insight is that this is 0..3 converted using the *mixed base* number `1 2 1 2`. After that we just cut the original input using our 4 lists, with a 1 prepended to each.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Ir0Œpk€
```
[Try it online!](https://tio.run/##y0rNyan8/9@zyODopILsR01r/h9uPzrp4c4ZQObDnYsi//@PNtQx1DEAQkMkaBALAA "Jelly – Try It Online")
Inspired by [Jonathan Allan's solution](https://codegolf.stackexchange.com/a/252314/85334).
```
I Get the forward differences of the list.
k Partition the list after each truthy position
€ of each element of
Œp the Cartesian product of
r0 the ranges from each difference to 0 inclusive.
```
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ŒgŒṖẎ€€
```
[Try it online!](https://tio.run/##y0rNyan8///opPSjkx7unPZwV9@jpjVA9P9wO0hgBpD5cOeiyP//DXUMdQyA0BAJGgAA "Jelly – Try It Online")
Port of my Brachylog solution.
```
Œg Partition into runs of consecutive equal elements.
ŒṖ Generate every partition of the runs,
Ẏ€€ and concatenate the runs in each slice.
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 28 bytes
```
(.),(?!\1)
$1#
+%1`#
;$'¶$`,
```
[Try it online!](https://tio.run/##K0otycxL/H9oG9ehbYe2/dfQ09TRsFeMMdTkUjFU5tJWNUxQ5rJWUT@0TSVB5/9/Qx0DLkMdMATTBkBoCAA "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs semicolon-delimited lists. Explanation:
```
(.),(?!\1)
$1#
```
Find all acceptable cutting points.
```
+
```
Loop until each cutting point has been processed.
```
%
```
Loop over each partially cut list.
```
1`
```
Only process the first remaining cutting point on each pass.
```
#
;$'¶$`,
```
Create two lists, one cut at that point, one not cut at that point.
[Answer]
# [Perl 5](https://www.perl.org/), 80 bytes
```
sub{@p=pop=~/0+|1+/g;$s="@p";map$s=~s, ,$r=$_%2?$&:'';$_/=2;$r,ger,0..2**@p/2-1}
```
[Try it online!](https://tio.run/##VY9RT8IwFIWf3a84aQpjUFiZ4YWmshefTXhVQjTZyFS22s5Eg/DX5@02QPvQfPeec09vTWbfF83@GzzXjft8OaRGm8roUywnP/NJvFPcaZYapvbPhvDkBAS3mm8HyYoPl2Go@DbWieJW7DIr5GyWjMepiZPp/NioIK8sfHqduRqjAMAjEM5lSAR916KgG9TZiItOJ@z1Dv35q0tJ3U736CMo40xS4tojxCaIDn6YdhnxojQizb5MpNN2L9UrSHdVDY0hz1tTdBE4uV1t9WtVlD63Hb@qNPZfpUanGluUdQ42mC4cKHKJlgCa93wrfUF2KtxTyURw07@F7OMcjBVY9cawBLtfrx/Wrct/4mL21HlVcGx@AQ "Perl 5 – Try It Online")
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang) (v2), 125 bytes
```
;=lL=p+=a@P;W=l-lT|?Gp lT Gp-lT1=a+a,l;=n^2LaW+1=n-nT;=x!=b+=o@p;=kLa;W+=k-kT1&%/n^2k 2;=o+o,GbF=d+~x=x[Ga kT=bSbFd@;D+o,bO''
```
[Try it online!](https://knight-lang.netlify.app/v2#WyI7PWxMPXArPWFAUDtXPWwtbFR8P0dwIGxUIEdwLWxUMT1hK2EsbDs9bl4yTGFXKzE9bi1uVDs9eCE9Yis9b0BwOz1rTGE7Vys9ay1rVDEmJS9uXjJrIDI7PW8rbyxHYkY9ZCt+eD14W0dhIGtUPWJTYkZkQDtEK28sYk8nJyIsIjExMDAxIl0=)
Input as a binary string. Outputs each partition on a separate line.
This probably is not even the golfiest strategy lol, but whatever. The general strategy is to construct a list `a` that contains the possible indexes that can be cut at (the easy part), then enumerate over all possible combinations of cuts using `a` (the annoying as f\*\*\* part).
[Answer]
# [Haskell](https://www.haskell.org/), 94 bytes
```
import Data.List
f l=nub[w|w<-subsequences[id=<<x|x<-tails=<<(inits.group)l,x>[]],(w>>=id)==l]
```
[Try it online!](https://tio.run/##jYqxDoIwFEV3vuKFOEACBPeWyZHNselQpOiLpUD7Ghj490p0cjHmDDcn9zyUf2pjYsRxnhzBRZGqWvSUDGC4DZ1Y95WVPnReL0Hbm/YCe87Ytm@sJIXGH5KhRfLV3U1hzk2xNULKIlubhmOfc25kHBVa4NBPCcwOLcEJBnEuanl4oCu51kKafp9vfgf1wT/JZ2V8AQ "Haskell – Try It Online")
Corrected as x specifications.
Thanks to @Wheat Wizard for saving some bytes using *id=<<x* instead of concat.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 45 bytes
```
⊞υ⟦A⟧FυF…ι¹F²F⁺¹⌕A⪫κω⁺Iλ¬λ⊞υ⁺⟦…κμ✂κμ⟧ΦιξEυ⭆¹ι
```
[Try it online!](https://tio.run/##RU7LCsIwELz3K3LcQATjtScpCApKoceQQ4jVBtekpImPr49Jrbh7GGZ3Z2b1oLx2ClNq4zRAZETs7RgDUEnr6uI8gUjJjM1bY98MbgTDCKfLdLNgi3ECzsjO2PMWEQ7OWLgx8qSMzLtGTQEws5MrWIr8MucD8Q/Iunu@7NDo/ktkccbQ@xL@ytq6ar2xAY5qLA5dyOxaSP7BlH1KQnDG2To3lzKtHvgB "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ⟦A⟧
```
Start with the original list, which is always a valid partition.
```
Fυ
```
Loop over the partitions found so far.
```
F…ι¹
```
Loop over the lists in the current partition, but stop after the first. (This is a sneaky way of getting the first list into a variable.)
```
F²
```
Loop over the possible first bits of a cutting point.
```
F⁺¹⌕A⪫κω⁺Iλ¬λ
```
Loop over all of the possible cutting points that start with that bit. The cutting point is in between the bits, thus the extra `1` added to the positions. (`Incremented` works on empty lists in the newer version of Charcoal on ATO which would save a byte.)
```
⊞υ⁺⟦…κμ✂κμ⟧Φιξ
```
Cut the first list of the partition at that point and push the resulting partition to the list of partitions where it will be reevaluated for cutting.
```
Eυ⭆¹ι
```
Pretty-print all of the found partitions.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 10 bytes
```
mmrk9d./r8
```
[Try it online!](https://tio.run/##K6gsyfj/Pze3KNsyRU@/yOL/f3VDQwMDQ3UA "Pyth – Try It Online")
### Explanation
```
r8 length encode the implicitly evaluated input
./ get all partitions
mmrk9d map length decoding to each partition element
```
[Answer]
# [Python](https://www.python.org), 230 bytes
```
from itertools import*
import re
def f(M):L=re.split(r'((.)\2*)',''.join(map(str,M)))[1::3];l=len(L);I=[*range(1,l)];return[[M]]+[[[int(c)for c in''.join(L[i:j])]for i,j in pairwise([0,*P,l])]for s in I for P in combinations(I,s)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NZBBTsQwDEX3c4rsapdQTWGDWvUAlVpp9iGLUlJwlSaRkxHiLGxmA6fgIlyAc9BqqLzwl5_lb_vjK7ynV-8ul89zmm4ffn4n9ougZDh5b6OgJXhO-eGaBZvDs5nEBD1WXcOmiMFSAs4ACny8yzGTWVbMnhwsQ4CYWPaIqMqqute1baxx0GHdNirnwb0YKKVFXbNJZ3ZK9VrfKKXIJRhx8ixGQW4f2CmqZo16q5OcVyLCQPxG0YA6yvwk7T-NG2vFJk-bHP3yRG5I5F2EVkbU12u_Vb5tGXg1lBOoUpbyuEapcW_ZH_MH)
Python 3.10+ required for `pairwise`.
for `[1,1,0,0,1]` returns:
```
[[[1, 1, 0, 0, 1]],
[[1, 1], [0, 0, 1]],
[[1, 1, 0, 0], [1]],
[[1, 1], [0, 0], [1]]]
```
ungolfed:
```
from itertools import *
import re
def f(M):
# produce ['11', '00', '1'] by splitting on regex which checks 2 consecutive duplicates
L = re.split(r'((.)\2*)',''.join(map(str,M)))[1::3]
l = len(L)
indexes = [*range(1,l)]
return [[M]]+[
# wrap list for each consequtive pair of index combos and convert back from string
[[int(c) for c in ''.join(L[i:j])]
for i,j in pairwise([0,*partition_indexes,l])]
for partition_size in indexes
for partition_indexes in combinations(indexes,partition_size)
]
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 4 bytes
```
ĉJᵐj
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FsuPdHo93Doha0lxUnIxVGzB7mhDHYNYLiAJhlCWARAaxkKUAAA)
A port of [@Unrelated String's Brachylog answer](https://codegolf.stackexchange.com/a/252326/9288).
```
ĉ Partition into runs of consecutive equal elements.
J Take an arbitrary partition of the list of runs,
ᵐj and concatenate each slice.
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 71 bytes
```
f=([x,...y],z='')=>x?f(y,z+x)|f(y,[z,x]):/^,|1,1|0,0/.test(z)||print(z)
```
[Try it online!](https://tio.run/##FcZBCoAgEADAex/RpU3dWxTWQ6IgIqEOESVisn83nNOca1jf7Tlu34Q2Z2flFFEp9c2YrBBghzg6@WGqI3DJlDDO0OkFmZDYoNHK76@XCZjv57jKcl85KYiMIQH5Bw "JavaScript (V8) – Try It Online")
Seems they look same
# [JavaScript (V8)](https://v8.dev/), 72 bytes
```
f=([x,...y],z='')=>x?f(y,z+x)|f(y,z+[,x]):/^,|1,1|0,0/.test(z)||print(z)
```
[Try it online!](https://tio.run/##JcZBCoAgEADAex/Rpc3cWxTWQ6JAIsEOESVhsn83ojnNZm97Lac/QnU3OTsjx4hKqWfCZIQA08fByQdTGYH/jBgnaOsZmZBYo65VWK8gEzAfp9@/5a5wUhBpTQLyCw "JavaScript (V8) – Try It Online")
] |
[Question]
[
Given a positive integer n, randomly output n non negative integers that sum to one hundred. n will be at most 200. The output should be present as a list of integers (not sorted).
Your random sample should be uniformly sampled from all lists of n non negative integers that sum to one hundred.
Your code should run in a reasonable amount of time (e.g. should terminate on TIO) for n less than a 200 . This is just to prevent brute force solutions.
# Examples
If n=1 the code should always output 100
If n=2 the code should output 100,0 or 99,1 or 98,2 or 97,3 ... or 2,98 or 1,99 or 0,100 with equal probability. There are 101 different possible outputs in this case.
If n>100 then some of the values in the output will necessarily be 0.
[Answer]
# [R](https://www.r-project.org), 64 bytes
```
\(n,m=rle(c(1,sample(!c(1:99,!1:n-1)),1)))c(m$l[!m$v],!1:n)[1:n]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jU9BasMwELzrFTINRgsK2IVC4yLoP9IghKLYTiTFSOuSUvqSXtxDH5U_9BGVrR56aw_aXWZnZkfvH2G60qjcYI3sPZrWhCixUyjVfi_xLOuqEp8jHtb318cn5rkTwRqmWc2zihVpbjYbXtSNX9cAPD3QzK3stnCr592ygG0qux-fLzQRpRe3d4TcUHNZfGgYfUP-SMKyEmad7ow-0ZlAlbVpMNQa32IXqQrJrm87pOWCx9H9AhuS-CyqYbAvKXqyrfhh9Br7s2cXeD2Kf6Z4yPfYEYTIEC3L-diCJOIbAMl_nqbcvwE)
Implementation of 'sticks-and-stones' as suggested by xnor.
**Ungolfed**
```
function(n){
w=rep(0:1,times=c(n-1,100)) # n-1 zeros, followed by 100 ones
x=sample(w) # randomly shuffle it
y=c(0,x,0) # and add zeros at the start & the end
m=rle(y) # get the lengths of runs of 1s and 0s
o=m$lengths[m$values==1] # lengths of the runs of ones
p=m$lengths[m$values==0]-1 # lengths of the runs of zeros, minus 1
q=sum(p) # so q is the number of zero-length runs of 1s
z=rep(0,q) # repeat zero that many times
return(c(o,z)) # and return the concatenation of the runlengths of 1s and the zero-length runs
}
```
**Golfing tricks**
`rep(0:1,times=c(n-1,100))` -> `!c(1:99,!1:n-1)`
`c(m$lengths[m$values==1],rep(0,sum(m$lengths[m$values==0]-1)))` -> `c(m$l[!m$v],!1:n)[1:n]`
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 46 bytes
```
@(n)diff([0,sort(randperm(n+99,n-1)),n+100])-1
```
[Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjTzMlMy1NI9pApzi/qESjKDEvpSC1KFcjT9vSUidP11BTUydP29DAIFZT1/B/moaRgYHmfwA "Octave – Try It Online")
Based on [@xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s comment. But instead of shuffling a list of zeros and ones, here I generate a random permutation of `1:n+99`, and see the first `n-1` terms as the positions of zeros.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 16 bytes
```
lMc.S+*100N*tQdd
```
[Try it online!](https://tio.run/##K6gsyfj/P8c3WS9YW8vQwMBPqyQwJeX/f2MDAA "Pyth – Try It Online")
Based on xnor's comment.
* `*100N`: 100 `"` characters
* `*tQd`: n-1 space characters
* `.S+`: Concatenate, shuffle
* `c ... d`: Split on spaces
* `lM`: Map to lengths of remaining pieces
[Answer]
# [J](http://jsoftware.com/), 27 bytes
```
0+/;.1@,1 0({~#?#)@#~100,<:
```
[Try it online!](https://tio.run/##y/pvqWhlGGumaGWprq7g56Sn4JKfp16ikJZZoVCUmJeSn6tQnJqaoselpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DbT1rfUMHXQMFQw0quuU7ZU1HZTrDA0MdGys/mtypSZn5CukKZjCGEYGMBZQyX8A "J – Try It Online")
Sticks and stones method thanks to [xnor's idea from the comments](https://codegolf.stackexchange.com/questions/247970/sample-integers-that-sum-to-one-hundred#comment554669_247970).
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~125~~ ~~120~~ 115 bytes
* *-5 bytes thanks to @ceilingcat*
```
i=99,j,a[];main(n){scanf("%d",&n);n+=i;for(srand(&n);a[rand()%n]++||i--;);for(;i<n;)j=a[++i]?j+1:!printf("%d ",j);}
```
An implementation of xnor's suggestion in C.
[Try it online!](https://tio.run/##HYxBCsIwEAC/ooVKwiYH8VTX4ENCDktKyoa6SiJ4sH7diLkNwzDRxpVkaY3dNJlsyAe8EYsS/a6RJKlhnAdzEI0CjjHdi6qFZFZ/Rb6jHiUAbBtbi7onyBdBnR15AA7XDMfz/lFYnv23G0zW@Gnt9I1ppaU2@/oB "C (clang) – Try It Online")
[Answer]
# [Desmos](https://desmos.com/calculator), 77 bytes
```
l=[2...n]
L=join(0,[1...99+n].shuffle[l[l0+n>1]].sort,100+n)
f(n)=L[2...]-L-1
```
Uses xnor's Stars and Bars idea.
[Try It On Desmos!](https://www.desmos.com/calculator/yftw79pgpc?nographpaper)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/npcsficqdl?nographpaper)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
т∍ú¦.r#€g
```
Inspired by [*@isaacg*'s Pyth answer](https://codegolf.stackexchange.com/a/248041/52210), using [*@xnor*'s approach](https://codegolf.stackexchange.com/questions/247970/sample-integers-that-sum-to-one-hundred#comment554669_247970).
[Try it online](https://tio.run/##yy9OTMpM/f//YtOjjt7Duw4t0ytSftS0Jv3/f1MA) or [verify a few random outputs at once](https://tio.run/##yy9OTMpM/X@xyUevyOLQ4otNFUd3HFqmV2R0aPGh1dVlSp55BaUlVgpK9pU6XEr@pSUwngtQy6OO3sO7QIqVHzWtSf@vc2ib/X8A).
**Explanation:**
```
∍ # Extend the (implicit) input
т # to length 100
# (resulting in a string - e.g. n=50 becomes "505050...50")
ú # Pad this string with the (implicit) input amount of leading spaces
# (it's important to note that `∍` results in a string instead of integer,
# otherwise this would have resulted in "50" with 505050...50 amount of
# leading spaces instead)
¦ # Remove the first space, so there are input-1 amount of spaces
.r # Randomly shuffle the characters in this string
# # Split it on spaces
€g # Get the length of each inner string
# (after which the result is output implicitly)
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 82 bytes
```
n->Vec(Ser(concat([Set(numtoperm(m=n+99,random(m!))[1..n-1]),m+1]))*(y=1-x)-1/y,n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN4PydO3CUpM1glOLNJLz85ITSzSig1NLNPJKc0vyC1KLcjVybfO0LS11ihLzUvKBPEVNzWhDPb08XcNYTZ1cbSCpqaVRaWuoW6Gpa6hfqZOnCTVZuTi1BKRJIz21pDwxJ6ckMzdV05qroCgzr0QjTcPIwEATqnTBAggNAA)
Based on [@xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s comment:
>
> It doesn't look like anyone has done this yet, but a slick approach is to make a list of 100 ones and n-1 zeros, shuffle it, and list off the lengths of the n runs of ones separated by zeroes. – [xnor](https://codegolf.stackexchange.com/users/20260/xnor)
>
>
>
PARI/GP doesn't have a built-in for shuffling, but we can generate a random permutation of `[1..n+100-1]` using `numtoperm` and `random`, and see the first `n-1` terms as the positions of zeros.
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 94 bytes
```
n->b=binomial;r=random(b(n+99,k=100));[while(r>=s=b(n-l+k-1,k),r-=s;i++;k--)+i|l<-[1..n],!i=0]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY1BDoIwEEX3nkLjpk07BFxp6nARgqbEgpOWQkoNG2_ihsQYz-RtlODqLf7Lf493rwOdm3561mt83WIN-8_JQ15hRb5rSTsVMGh_6VpWMS8OB2kxS1POVTFeyRkWchzwN4ETFjJpuQyAgyIhlAXggu7uCEWWJL6UG8K0_Fe2g4nzMWtMHLVzkVrD1aoP5COr2W5uLOo0LfwC)
The number of possible outputs is `binomial(n+100-1,100)`. Here I first generate a random number `r` in the range `[0..binomial(n+100-1,100)-1]`, and then find the `r`th result. So this is guaranteed to be uniform.
[Answer]
# [Python 3](https://docs.python.org/3/), 88 bytes
```
lambda n:[*map(len,bytes(sample([0]*100+[9]*~-n,n+99)).split(b' '))]
from random import*
```
[Try it online!](https://tio.run/##DcWxDsIgEADQWb@iW@9oNagTJn4JZYAUIgkcF2Dp0l9H3/L46N9CrxE@20g2u91O9NYiW4bkaXVH9w2azZw8aGnEQ8pFKyPOG620KIV4b5xiBzdfZkRzDbXkqVra/8XMpXYxuEbqEOApJeL4AQ "Python 3 – Try It Online")
Also uses the "sticks and stones" method.
This creates a list of 100 0s and n−1 9s, then `sample` gives n+99 elements (which is all of them) in a random order. The result is then converted to `bytes` in order to use `split`; 9 was chosen because it corresponds to the tab character (which is placed in the `bytes` literal for the argument to `split`). Finally, use `map` to take the `len`gth of each piece, and `[*…]` makes it into a list.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 28 bytes [SBCS](https://github.com/abrudz/SBCS)
```
-↑∘{+/¨⍵⊂⍨1@1~⍵}{100≥?⍨⍵+99}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=033UNvFRx4xqbf1DKx71bn3U1fSod4Whg2EdkFNbbWhg8KhzqT1QCMjVtrSsBQA&f=03jUtUjnUe/SR11N2vqaaQqmAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
A train which takes a single integer. Uses the sticks and stones method, since it translates quite well to APL.
-6 from ovs.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 43 bytes
```
.+
*
_$
100*@¶
+@v`(.)(.*¶)
$2$1
¶
S`_
%`@
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4srXoXL0MBAy@HQNi5th7IEDT1NDT2tQ9s0uVSMVAy5gKJcwQnxXKoJDv//GxoAAA "Retina – Try It Online") Explanation:
```
.+
*
```
Convert to unary (using `_`).
```
_$
100*@¶
```
Decrement the input, append 100 `@`s, and create a work area for the shuffle.
```
+@v`(.)(.*¶)
$2$1
```
Repeatedly select a character randomly from the first line and move it to the start of the second line. (The `+` indicates to repeat, the `@` selects randomly, and the `v` allows the matches to overlap, which doesn't matter here since we're only replacing one at a time.)
```
¶
```
Delete the input area.
```
S`_
```
Split the working area on `_`s. Since there were `n-1` of them, there are now `n` lines.
```
%`@
```
Count the number of `@`s on each line.
[Answer]
# Wolfram Language (Mathematica), 41 bytes
Edit: I have made my code much simpler and shorter.
```
Values[Counts[RandomInteger[{1,#},100]]]&
```
RandomInteger creates a random number between 1 and the given input integer, with uniform probability. This is done 100 times, and Counts tallies up the number of appearances of each number.
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PywxpzS1ONo5vzSvpDg6KDEvJT/XM68kNT21KLraUEe5VsfQwCA2Nlbtf0BRZl6JQ0hiUk5qdFp0ZqxOdaaOIVC2NvY/AA "Wolfram Language (Mathematica) – Try It Online")
Old code from my previous submission is below.
```
Length/@Select[Flatten[Split[RandomChoice[Join[Riffle[Table[1,{#}]&/@#,0]]&/@Flatten[Permutations/@IntegerPartitions[100+#,{#}]-1,1]]],1],Length[#]>1&]&
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 99 bytes
```
f=(n,a=[100])=>--n?f(n,a.flatMap(v=>(s||s++)<p&&(s+=v)>p?[d=s-p|0,v-d]:v,p=Math.random(s=0)*101)):a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVXNbttGEL7lwKeYQ2ruSiRFKjVSy6aMIAkCF3ETxLkpArQhVzJdapfhLpkUFp8klxzah2qfJrPLH0lpDdSAKHp-vp2Z79vR1z-FTPm3b39Veu3_8neyjonwWLyIwnBJ47nvi8u1sQTrnOlrVpA6nhO126nxmF4UJydEjeOazovLRRorv9iFXu2ny1ntFfE107dByUQqt0TFIR1FYUTpjLVH_fOInjtOIoXS8P7d1bPXNxADnop_aF84kedMPeeJ55x6ThR6zmQytc9T-8RAZxmsZfmSJbdEQDyHewfAwMmcB7nckBVa4fG9aFZ4UOvSUHJV5Vqh574xVkQAknMNGZrCc_y66KrBd2zRoh4nYyBOxGIeO250ib7VAg9tDcGdzARxPXBpA0sggz3nYqNvG7pqQbI1kCMPxHEMAk5OOuSg5GmVcEJUtfWgpqZdfIUx1B6E1IbjRPpqoW9zMRS2xMrIf1h3O5M_hqitpAGeKz7AHI3zQzV9-nMCr6QeGkSIxo7weNSI47SfdjzYFPrffLzjiQ5-53-ovhLa9WuSDAmJ3H6Uhpyot2QDSYags7NzPGqMLM1Nv0iR79M-axS3vqOMyCT4NiHsGO3CJ3Hr2WsjkZWw0ugqrVle8YNat0b9ZvQ1TDqRHChry5npsgX5gTCWH1LGckvaxMxln690-oIjPNhroz6VmvyAVe-RasQh-A82YM6lMBrBdI86lNWTZxkwIoFLcA2DEeSZ0i7MYNUSihENVCL7VHHrUiDXwL8UOAieor-dmuH08T2xvY6s5AIt35Y8yVQmBXlCm59sQW1Y19JDgUrjbmBlCimvM6bRfnhTTREPqUZJnI7gn-FK6Dx4LnPcTbIkVnouF65n33oVi2rLyyyZgS4r7nXGSrENn4FroNzemG2ELPnbSiS6sgXNYM3wQgyapgHOoWAlt4Wae2sma8QYUVtxoIo8Q7JwY1nZ-zANbax19vuKoAIy2i-tvmOs06jv15s3vwV4huIkt3CauMSlC9zHhzunYMpEm6R_bQ1r_H87Yw_Za8UCo0zMfQ9PjUTcD-bm4x5bGVb7LZIvh2vwIMWbVlvDXjiamKk0s3Wc0aMK3CAIXJvR4BM_7S9G_yP1HQ)
A recursive approach that starts with the array `[100]`, and 'splits' it randomly `n` times.
eg. `[27, 51, 22]` -> `[27, 11, 40, 22]`
The hardest (and most costly) part is making sure `[0, 100]` is a possible output.
There is an extremely slim chance (at most approx. 1 in 253, [source](https://stackoverflow.com/a/52095861/14117133)) of the function producing invalid output, when `Math.random()` returns exactly `0`.
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 42 bytes
```
100\(:a+,{;9.?rand}${a<}%1+{.1?.@@)>n\.}do
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPlvaABEBjEaVonaOtXWlnr2RYl5KbUq1Yk2taqG2tV6hvZ6Dg6adnkxerUp@f//AwA "GolfScript – Try It Online")
For some reason I just *had* to use GolfScript for this. No idea why though, I've never used this language before. Anyways, this is yet another implementation of xnor's idea.
```
100 # push 100 onto the stack
\(:a # store n-1 in variable a
+, # create array of ints from 0 to (100 + n-1) - 1
{;9.?rand}$ # shuffle array, method taken from GS tips page
{a<}% # map items to 0 if they are >=a and to 1 if they are <1
1+ # append 1 to list.
# This is done so that ? always finds a 1 later
{
.1? # find position of first 1 in array
.@@ # move a copy of that position to the back of the stack
)> # discard all elements with an index < (position - 1)
n\ # push a newline onto the stack, flip array back to the top
# The implicit output concats all stack values together :(
.}do # repeat until array is empty
```
The program expects n to be at to top of the stack. TIO's input field does ...unexpected things, so the header field is used to provide input instead.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `W`, 13 bytes
```
‹(₁ʀ℅)₁Ws₍h¯f
```
choose cut positions and sort them, append 100 at the end, calculate the difference
=>`first number, differences...`
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwi4oC5KOKCgcqA4oSFKeKCgVdz4oKNaMKvZiIsIiIsIjUiXQ==)
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 22 bytes
```
'dspn,[r0l?:lf-spr,]pl
```
[Try it online!](https://tio.run/##y6n8/189pbggTye6yCDH3ionTbe4oEgntiDn/38LAA "Ly – Try It Online")
This meets the requirements in that all possible combinations of numbers that sum to 100 could be returned, but I don't think all of them have an equal chance. But someone with better understanding of statistics would have to weigh in to be sure... If that's a disqualification, I'll remove the answer. But from what I can tell, the approach is different from the other algorithms used so it might be interesting?
At a high level, the code loops `N-1` times where `N` is the count requested on STDIN. Each time through the loop it generates a random number in `0-X` where `X` starts at 100 and is decremented by the number added to the list each time. Once the loop is exhausted, it finds the number requires to get the sum to 100 and uses that as the last entry.
```
'dsp - Load "100", save to backup cell and pop from stack
n, - Read list size "N" requested from STDIN, decrement
[r r,]p - Loop once for "N-1" times
0l? - Load backup cell, generate random number in "0-X"
: - Duplicate random pick
lf- - Sub random pick from previous "left to sum" number
sp - Save new "left to sum" to backup cell and pop from stack
l - Load "left to sum" from backup cell
- Stack prints as numbers by default on exit
```
[Answer]
# Python 3.9, 233 226 224 211 Bytes
```
import random
from functools import*
r,p=range,cache(lambda n,s:s<1 if n<1 else sum(p(n-1,k)for k in r(s+1)))
def f(n,s):
k=random.choices(r(s+1),[p(n-1,k)for k in r(s+1)])[0]
return[]if n<1 else[s-k]+f(n-1,k)
```
[TIO link](https://tio.run/##dY0xTsQwEEV7n2LKGdaLHGjQavcKXCCKUHBsYiWescZOwelDpFDQUP3iv6dXvtss/PpWdN9TLqINdORJsokqGeLGvomsFc7zyagtj4P4CnbV7cOPfg74LhwI1zF/TiOwrbd67yBF4GPCWgPULWNBvnZ2oSgKCyQGxXrpiMhMIULEw6ObgeVx9p/9LMmHiidm@3/8gXo3GNDQNuV@@FPt63UZLvFX24smbhjxxTnbOUe0/wA). Slightly longer as the cache decorator is only available in Python 3.9.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 49 bytes
```
s10 100rn1bx100.*FL{jg_x/0x/ia}{g1-.Js1}w!q0;;)++
```
[Try it online!](https://tio.run/##SyotykktLixN/V9dkPq/2NBAwdDAoCjPMKkCSOtpuflUZ6XHV@gbVOhnJtZWpxvq6nkVG9aWKxYaWFtramv/zyypDc/5b6BgzGUIJoxAhDHQEC5DBUMA "Burlesque – Try It Online")
Inputs are random seed and count.
```
s1 # Save count
0 100rn # Random numbers 0..100 (seeded by second input)
1bx100.*FL # 100 1s
{
j # Reorder stack
g_ # Get head of random number
x/0x/ia # Insert a 0 at that position
}{
g1-.Js1 # Decrement count and check
}w! # While
q0;; # Split on 0s
)++ # Sum each block
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes
```
≔E⊖N⁰θ≔E×χχ¹η⊞υ⁰W⁺θη⊞υ⎇‽ι⁺⊟υ⊟η⊟θIυ
```
[Try it online!](https://tio.run/##TYzLCsIwEEX3/YosZ6BCs@5KdONCKdIfiO1gAnk1D8Wvj4kouLjMDOfcWaQIixO6lH2M6m7hLDwcaQlkyCZa4WR9TpdsbhQAsWdDzYZj96fPylAEPvSMN8prZDWmHCXk1hi7p1SaGEw6R9gaRvbDMwUrwguuwq7OgKrtjzY5D7kddUr8Lhu2x0HZBAcRUxVwLIUPZffQbw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses @xnor's method.
```
≔E⊖N⁰θ
```
Create a list of `n-1` `0`s.
```
≔E×χχ¹η
```
Create a list of `100` `1`s.
```
⊞υ⁰
```
Start the output list with one `0` for now.
```
W⁺θη
```
Repeat until all of the `0`s and `1`s have been popped.
```
⊞υ⎇‽ι⁺⊟υ⊟η⊟θ
```
Select one of them at random. If it's a `1`, then increment the latest number in the output list, otherwise push one of the `0`s to the output list, all while removing the `1` or `0` from its list as appropriate.
```
Iυ
```
Output all of the integers.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 94 bytes
```
f=(n,s=100,g=Math.random,i=g()*-~s|0)=>--n?g()*s**n<(i+1)**n-i**n?[...f(n,i),s-i]:f(n+1,s):[s]
```
[Try it online!](https://tio.run/##JY1NCoMwEEb3nsJlYjJBl1VTT9ATiGDwr2NtIo6UUkqP3jTSWcy8Dx7zzeZhqNtw3cG6fvB@1MxK0lmayklfzH5Vm7G9u0vUE@MJfOidcn0GsNWRKUlsyVBkPABgWFWtlBrDE@SSAJs8sMgk8bymxo9uY9g/dVbE4ZShpoiFCMijzllyy6AWN7HxkLiaHdpWtDzyX7fuGAQPQLvpbkD4GvTpPz8 "JavaScript (Node.js) – Try It Online")
Probable ret[0]==s-i is `((i+1)**n-i**n)/s**n`
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
î ÅiLî¬ ö¬¸mÊ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=7iDFaUzurCD2rLhtyg&input=OA)
] |
[Question]
[
*This is the cops' thread of a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. The robbers' thread can be found [here](https://codegolf.stackexchange.com/questions/251451/polyglot-quiz-robbers-thread)*
In this challenge as a cop you will choose two programming languages **A** and **B**, as well as a non-empty string **S**. You are then going to write 4 programs:
1. A program which outputs exactly **S** when run in both **A** and **B**.
2. A program which outputs **S** in **A** but not in **B**.
3. A program which outputs **S** in **B** but not in **A**.
4. A program which doesn't output **S** in either **A** or **B**.
You will then reveal all 4 programs (including which number each program is) and **S**, but keep the languages hidden.
Robbers will try to figure out a pair of languages such that they print the correct results for the 4 programs, and cops will try to make posts that are hard to figure out while remaining as short as possible.
**Warning: There is a slight difference in the rules from "normal" [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'")**
Cops' posts here can have 4 different states:
1. Vulnerable
2. Cracked
3. Safe
4. Revealed
All cops' posts start as *vulnerable*. If a robber finds and posts a solution to a *vulnerable* post they will receive 1 point and the post will become *cracked*. If a post lasts 10 days in *vulnerable* without being solved it automatically becomes *safe*. A cop with a *safe* post may choose to reveal **A** and **B** and their *safe* post will become *revealed*. A robber can still solve a *safe* post, if they do they receive a point and the post becomes *revealed*.
Only *revealed* posts are eligible for scoring. Robbers are only permitted to solve *vulnerable* and *safe* posts.
## Scoring
Cops will be scored on the sum size of all four programs as measured in bytes, with the goal being to have an answer with as low a score as possible. Answers that are not *revealed* effectively have infinite score by this measure until they become *revealed*.
## Languages and Output
In the interest of fairness, we are going to require that languages are free and reasonably cross platform. Both languages you choose must be freely available on Linux and FreeBSD (the two largest foss operating systems). This includes languages which are free and open source.
Your selected languages must predate this challenge.
Since this challenge requires that **A** and **B** produce different outputs for the same program, there is no requirement for what "counts" as a different language, the fact that they produce different outputs is enough.
Programs do not have to compile, run without error or "work" in the cases where they do not need to output **S**. As long as **S** is not the output it is valid.
Programs here should be complete programs not functions, expressions or snippets.
Running a program is assumed to be done with no input. All four programs must be deterministic, within an environment. It is fine for example if as a part of an error the program outputs the name of the file or your host name, this is not considered non-determinism since it is determined by the environment running the program. However if it is included in the output please indicate what the file is named etc.
[Answer]
# A = [HQ9+](https://esolangs.org/wiki/HQ9%2B), B = [Python 3](https://docs.python.org/3/), 291 bytes, [Cracked](https://codegolf.stackexchange.com/a/251464/107310)
**S** is `Hello, world!`
1. Both **A** and **B** work
```
#console.log("Hello, world!")/*
print("hello, world!".capitalize())
#*/
```
2. **A** only
```
console.log("Hello, world!")/*
print("hello, world!")
*/
```
3. **B** only
```
#console.log("Hello, world!")/*
print("Hello, world!")
#*/
```
4. Neither work
```
console.log(String.fromCharCode(49-1)+"ello, world!")/*
print(String.fromCharCode(49-1)+"ello, world!")
*/
```
GG
[Answer]
# [A] and [B], 64 Bytes, [Cracked](https://codegolf.stackexchange.com/a/251462/92689) by @Steffan
S = "Cop"
Both *A* and *B* works
```
main=print"Cop"
```
Works only *A*
```
main=print
"Cop"
```
Works only *B*
```
main=
print"Cop"
```
None works
```
main=print
"Cop"
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) and [yup](https://github.com/ConorOBrien-Foxx/yup/wiki), 8 bytes, [Cracked by *@FryAmTheEggman*](https://codegolf.stackexchange.com/a/251649/52210)
\$S\$: `0`
1. Works in \$A\$=05AB1E and \$B\$=yup:
```
0#?
```
2. Works in just \$A\$=05AB1E:
```
0?
```
3. Works in just \$B\$=yup:
```
0#
```
4. Works in neither \$A\$=05AB1E nor \$B\$=yup:
```
0
```
---
**Explanation now that it's cracked:**
```
0#? # 05AB1E: Push 0; pop and split on spaces (no-op that just pops); print
# without newline, which implicitly uses the last value that was on the now
# empty stack, which is the 0
# yup: Push 0; pop and print it without newline; no-op character '?'
0? # 05AB1E: Push 0; pop and print it without newline
# yup: Push 0; no-op character '?', so don't print anything
0# # 05AB1E: Push 0; no-op pop; implicitly output 0 with trailing newline
# yup: Push 0; pop and print it without newline
0 # 05AB1E: Push 0; implicitly output 0 with trailing newline
# yup: Push 0; don't print anything
```
[Answer]
# Hexagony and Labyrinth, 44 bytes, [Cracked](https://codegolf.stackexchange.com/a/251469/78410) by Aiden Chow
**S** = `1234`
1. Works in both A and B
```
"123_1234!@
```
2. Works in A, but not in B
```
123+1
234!@
```
3. Works in B, but not A
```
1234@
;!;!;
```
4. Does not work in A or B
```
;!;!;
1234@
```
[Answer]
# ??? and ???, 69 bytes, vulnerable
S = `A`
1. Both A and B work:
```
:-%~! v
put(97)
.% >`a
```
2. Works in A, but not B:
```
:-%~v!
put(a)
.% >97
```
3. Works in B, but not A:
```
:-%~!<
put a.
.%^97C
```
4. Works in neither A or B:
```
put(97)
```
[Answer]
# [Glypho](https://web.archive.org/web/20060621185740/http://www4.ncsu.edu/%7Ebcthomp2/glypho.txt) and [Somme](https://github.com/ConorOBrien-Foxx/Somme), 747 bytes, revealed
## Explanation
For this approach, I thought it would make sense to choose two languages which cared very little about the actual content of their source codes, and instead cared about some properties the code has.
Glypho is a language who cares about the distinct permutations formed by chunks of 4 bytes. It has 15 commands, and is a stack-based language. For example, the string `UU{u` corresponds to the `push` command, since it is equivalent to `aabc` (in terms of uniqueness).
Somme is a language which is usually a fairly innocuous stack-based language, but once multiple lines are involved, the columns are summed and converted into a corresponding command. (Addition is performed by treating space, 32, as 0, `!` as 1, etc., then taking the result mod 95.)
Hence, the programs consist almost entirely of red herrings.
Recall that
**S** = `owo!owo!owo!owo!owo!owo!owo!owo!`
a string chosen because I thought it was funny.
## Both **[Glypho](https://tio.run/##VY9NSwNBDIbv8yv6theV0g74cXE7mVI8eQjTcRlQbPekHixpDxKKP37N7AoiuQQenrxv3j/Pxw/p@7b9/mJWARGEbVQlb/O2UW0KChvzUqQE1QAHVzk8vANc0qRsAwIt5ot5ZZEi/bqoTEqR0XUYXHh1KOZqGl2iIVfU/XeV/3IHV@G9t7UkPaXKa64IGxONRLHRYK6VVussBUGDji5bZw@Xc04mWyse/wUHBHKzdTfZrJ7v3s6bl7bL@fB0Gy8PXbh@nax2/LC7n9oJTK9ulqfH/cW@738A)** and **[Somme](https://tio.run/##VY9BSwNBDIXv8yv62otKaQfUXtxOphRPHsJ0XAYU273obQlFShB//JrZFURyCXx8eS@f0vfvw9C23xdmFRBB2EZV8iEfGtWmoLAxL0VKUA1wcJXDwzvAJU3KNiDQarlaVhYp0q@LyqQUmVyH0YVXh2KupsklGnNF3X9X@S93dBXee1tL0nOqvOaKsDHRSBQbDeZaabXOUhA06OSydfZwOedksrXi6V9wQCC32HWz/fZl8/G1f227nPvn@3jdd@H2bbY98uPxYW4nML@5W5@fTlenYfgB)** work:
```
UU{uOOwo!??!oOoOowwoSRSR<ww<W!WOOOw0oWoW>ww>!
!
owwo!0!0
!!
QwQwOwOw!?!?.,.,owwo@?@?<ww<W!W!OwOwoWWo>ww>!
!owwo!!0w
!W
QwwQOwOw!???oOoOoow
@?@?<ww<W!W!OwwOoWoW>ww>!
!owww!000
!WQwqQOwwO!?!?ooO!owow@??@<w><W!!WOww0ooW!>w>w!
!owOo!00!
SSSQQwqOwoO!??!oO!O>!>?
#A` C=Z6fyC[U`SSmT5@)m`>3] =^OE^;"owO!"*4/qK_(_
```
This corresponds to the [Glypho (shorthand) program](https://tio.run/##S8@pLMjI1y3OyC8qyUjMS/n/39BQOwUIow1TwHQKEIApbSAw1NVOyU@Bymjn54P4QJ6uthaYBPFjo1MRIPb/fwA) (`[eeeeeeeeeee]` is a loop that never runs):
```
11+d+d+[1d+d+d+dddd+d+dd++++1-+dod1d+d+d++oo1-+d1d+-+*1d+-+o1-+][eeeeeeeeeee]
11+ stack: 2
d+d+ stack: 8 (loop counter)
[ 1-+] loop 8 times
1d+d+d+ stack: LC, 8
dddd stack: LC, 8, 8, 8, 8, 8
+d+dd++++ stack: LC, 8, 112
1-+ stack: LC, 8, 111
do output and keep 'o'
d1d+d+d++ stack: LC, 8, 111, 119
oo output 'wo'
1-+ stack: LC, 7
d1d+-+* stack: LC, 35
1d+-+ stack: LC, 33
o output '!'
1-+ stack: LC-1
```
In Somme, this corresponds to the following program after the columns are summed:
```
F1+7*1-::8+\3B*m,m,m,m,m,m,m,m,0;!fw'@9AH `
F stack: 15
1+ stack: 16
7*1- stack: 111
:: stack: 111, 111, 111
8+\ stack: 111, 119, 111
3B* stack: 111, 119, 111, 33
m, map output (,) over stack
m,m,m,m,m,m,m, ...eight times in total
0; exit with exit code 0
!fw'@9AH ` (never executed)
```
## Only **[Glypho](https://tio.run/##Pc0xDgIxDETRPqew444GFy62WOEj5ABRaiiQDNWI0wcrLGuXo6d/f35ej5izdxvO@are0FCiRBAFIoqSxhjWVdF25h0CcRHPEd2s/5xrA1pJllARBUqkw/7O0wk85XJb35yZ3XNcvQxSUPbSKaUbCmj2OJ24C5YDjt7hRG6nU4rDIXsOSK2CGkBUu9j1PdbN@QU)** works:
```
[[4]?!?!?00?OwOw
o
oo owoo
0 0o]]4[00wO<!!<w#w#?##?owow[44[?!?!?0?0OwwO
oooo 0wo
w0 0]44[00wO<!?<w##w?#?#owow[8[8?!!!??0wOwOw
oo
o o woow0 0 ]44]0ww0<!!!w###??#wowow[ww[?!?!?00wOwOw
##>o o woow00 o]44]0www<!??ww#""#w"owwo"4*4/q]]]]]]
```
This corresponds to the following [Glypho (shorthand) program](https://tio.run/##HYlBCoBADAPfsteGPeQ96kEI2INsRb34@lqWITBkjvO7PPrjcb@@D2VSkGALCWH6yg6rSQrOD4hpVoCIVnVrI/MH):
```
1d+dd+*[11+d+d+dd+\1-+*1-+dddo1d+d+d++oo1d+d*d*d+1+o!1-+]!n
1d+dd+* stack: 8
[ 1-+] loop 8 times
11+d+d+dd+ stack: LC, 8, 16
\1-+*1-+dd stack: LC, 8, 111, 111, 111
do output and keep 'o'
1d+d+d++ stack: LC, 8, 111, 111, 119
oo output 'wo'
1d+d*d*d+1+ stack: LC, 8, 111, 33
o output '!'
! discard 111
1-+ stack: LC-1
!n discard; no-op
```
And also to the (gibberish) [Somme program](https://tio.run/##Pc0xDgMxCETR3qcA06UJBcUWq3AEH8BymXKFohRzfAc5TqAcPf13XNdzzt5tOOerekNDiRJBFIgoShpjWFdFO5lPCMRFPEd0s/51rg1oJVlCRRQokQ77OU8n8JTLHf1wZnbPcfUySEHZS6eUbiig2eN04i5YDti97UQef6cU2yF7DkitghpAVLvZ/TXWzfkB):
```
u>B-t$?@+@@v)IUnX'PFK;~{k**bj2Q1J02is?F}zRC/)mmU-U-w
```
This errors out immediately because `u` is not a command that exists.
## Only **[Somme](https://tio.run/##K87PzU39/z8zTaGgKDOvREMpv9xfSVOhJCM1z0pBOYxLASbuX56vpMmVmpfCpZxqYK1V52qXklTo6FtVq@1elGhbaRWQmcqVlFpSnpqap5CamJyhkF9aUlBaopCcmJOjo5CSb4UwShFoAQjkRcc4mOVUWykYgM0tSi1ITSxRKCnPTE7liojWSjcycFDKDteoNvHRLQrOVinXM6nVrNOy9ga6FwA)** works:
```
if print("owO") then: #V
print("Owo")
end
#e0;*~E>dbqAMz}+Gra=y:Pie
between each output call, do:
print("!") n[\@6l{: 0
end
repeat twice
X[*g20@"kW({4L-rSk$w.4})~*;Ke
```
This corresponds to the following Somme program:
```
F1+7*1-::8+\3B*r`,{`FF+2+*0;
F1+7*1-::8+\3B* same as previous
r reverse stack
`,{` push this string
FF+2+ push 32
* execute that string 32 times
(once for each character)
0; exit with exit code 0
```
And to the (gibberish) [Glypho (shorthand) program](https://tio.run/##S8@pLMjI1y3OyC8qyUjMS/n/PxUMtFLhQFcRiFMNgTA6D8SPjYXJ/P8PAA):
```
eeeeee*eeeeeeeeee-!ee-e1e1e[neeee]]eeeeeeee
```
This errors out immediately due to `e` (execute) having no parameters.
## Neither **[A]** nor **[B]** work:
Didn't need to spend too much time here, since the answer was probably fine without it.
```
print("owo!"*8)
#&7("owo!"-1)
```
Thanks for reading!
[Answer]
# [Python](https://www.python.org/) and [PARI/GP](https://pari.math.u-bordeaux.fr/), 48 bytes, [Cracked](https://codegolf.stackexchange.com/a/251466/9288) by @Steffan
An easy one.
**S** is `Cop`
1. Both **A** and **B** work
```
print("Cop")
```
2. **A** only
```
print('Cop')
```
3. **B** only
```
print('Cop)'
```
4. Neither work
```
print("Cop)"
```
[Answer]
# ??? and ???, 54 bytes
String: `8356830650`
Works in A and B (hex):
```
00000000: 300b 3366 b87e 0b00 247e e239 2a83 2a3b 0.3f.~..$~.9*.*;
00000010: 0fd6 30 ..0
```
Works in A (hex):
```
00000000: a4ac b3bb 762b 3a74 d6 ....v+:t.
```
Works in B (hex):
```
00000000: 300b 01f9 3033 1f0b 3131 5ee2 8891 5ebb 0...03..11^...^.
00000010: 2d88 7661 8976 0bce 0000 0b2b -.va.v.....+
```
Works in neither:
```
We're no strangers to love
You know the rules and so do I (do I)
A full commitment's what I'm thinking of
You wouldn't get this from any other guy
I just wanna tell you how I'm feeling
Gotta make you understand
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
We've known each other for so long
Your heart's been aching, but you're too shy to say it (say it)
Inside, we both know what's been going on (going on)
We know the game and we're gonna play it
And if you ask me how I'm feeling
Don't tell me you're too blind to see
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
(Ooh, give you up)
(Ooh, give you up)
(Ooh) Never gonna give, never gonna give (give you up)
(Ooh) Never gonna give, never gonna give (give you up)
We've known each other for so long
Your heart's been aching, but you're too shy to say it (to say it)
Inside, we both know what's been going on (going on)
We know the game and we're gonna play it
I just wanna tell you how I'm feeling
Gotta make you understand
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
```
Or the empty program.
[Answer]
# [A] and [B], 46 bytes, Cracked by @mousetail
**S** is `0`
1. Both **A** and **B**, 14 bytes
```
print('0')
out
```
2. **A** but not **B**, 15 bytes
```
print('0')
out#
```
3. **B** but not **A**, 17 bytes
```
print('0',)
out #
```
4. Neither **B** nor **A**, 0 bytes
Yeah, I'm not wasting any bytes here `:-)`
[Answer]
# ??? and ???, 300 bytes
S = `A\n` (as in, `A` with a trailing newline)
1. Works in *A* and *B*
```
puts A
n = A[ exit ]
n = 8
m = n - 1
p = m - n
n = 3 * 10
p /= 2
t = p * p
```
2. Works in *A* but not *B*
```
puts 'A'
n = A[ exit ]
n = 8
m = n - 1
p = m - n
n = 3 * 10
p /= 2
t = p * p
```
3. Works in *B* but not *A*.
```
puts A
n = A[exit]
n = 8
m = n - 1
p = m - n
n = 3 * 10
p /= 2
t = p * p
```
4. Works in neither *A* nor *B*
```
n = A[ exit ]
puts A
n = 8
m = n - 1
p = m - n
n = 3 * 10
p /= 2
t = p * p
```
[Answer]
# [A] and [B], ACTUALLY 3 BYTES!!!, [Cracked](https://codegolf.stackexchange.com/questions/251451/polyglot-quiz-robbers-thread/251487#251487)
**S** is `0`
* Both, 0 bytes:
* Only **A**, 1 byte:
```
!
```
* Only **B**, 1 byte:
```
r
```
* Neither, 1 byte:
```
"
```
[Answer]
# [Lightlang](https://esolangs.org/wiki/Lightlang) and [PDAsephone](https://esolangs.org/wiki/PDAsephone), 141 bytes, revealed
## Explanation
My thought process for this approach was to choose two obscure esolangs with interpreters not on TIO. Since there are no interpreters online available, I recommend you download [`lightlang.py`](https://github.com/bangyen/esolangs/blob/master/register-based/lightlang.py) and [`PDASephone.java`](https://esolangs.org/wiki/Talk:PDAsephone).
My strategy with this one was further devious. If you were hurriedly scanning through esolangs, and found this language, the program will not complete immediately. The `_` command in Lightlang sleeps for one second, meaning the program takes about 13 seconds to complete.
Lightlang is a curious language which only has 1 bit of memory, whose implementation clocks in at 35 sloc. My solutions use the "interesting" parts of the language, bouncing, jumping, and conditional skipping, to produce varied output. The program otherwise is just a garden path through toggling a bit on and off and printing it occasionally.
PDAsephone is a language with a PDA (push-down automaton) datatype. Unfortunately, I didn't want to spend bytes (or mental energy) getting a non-trivial PDA functional in the language, especially when the other language is so simple that it would be hard to replicate any meaningfully complex behavior implemented in PDAsephone. Hence, I use it just for its stack-based capabilities, and most of the work done is to make it play nice with Lightlang.
**S** = `0110100`
Both **Lightlang** and **PDAsephone** work:
```
__@;"1_&^"0^!^!.$$:.__/!^#&!^&$$:."0:v..^:..___
```
Only **Lightlang** works:
```
[*)`!$]^|>,=+!+/#(]+|!!-+)$'%)}|^!]>*].==`^{;"|
```
Only **PDAsephone** works:
```
'**"0-'})'"1=/:+?.`/:~'{++:.>.'+*/(:./:-./::'..
```
Neither **Lightlang** nor **PDAsephone** work: (the empty program)
Thanks for reading!
[Answer]
# ??? and ???, 43 bytes, safe
output: `2147483647`
| | |
| --- | --- |
| both | `-print /*"\r"%S #*/|2**31-1` |
| only A | `-print %S` |
| only B | `2**31-1` |
| neither | |
hint:
none of the languages are esoteric or recreational, both are practical and one of them is even quite popular, the other one is free open source but not available on any service like TIO, it's a script for a domain-specific tool
[Answer]
# ??? and ???, 406 bytes, [cracked by Conor O'Brian](https://codegolf.stackexchange.com/a/251507/91213)
S=`2`
Both A and B:
```
# print("22222222222") //
!\print("22222222222")# 2
\\ ("11111111111")<<n
;;;;;;;;;;;;;;;;;;;;;;;;;
```
## A but not B:
```
# print("11111111110") //
!\print("11111111110")# 2
\\ ("11111111110")<<n
;;;;;;;;;;;;;;;;;;;;;;;;;
```
## B but not A:
```
print("22222222222") //
!\print("22222222222")# 2
\\ ("11111111111")<<n
;;;;;;;;;;;;;;;;;;;;;;;;;
```
## Neither A nor B:
```
# print("11111111111") //
!\print("11111111111")# 1
\\\ ("11111111111")>>n
;;;;;;;;;;;;;;;;;;;;;;;;;
```
[Answer]
# Pyth and V, 11 bytes, [Cracked](https://codegolf.stackexchange.com/questions/251451/polyglot-quiz-robbers-thread/251500#251500) by @Steffan
S = `3`
Both:
```
l"aa3
```
Only A:
```
3
```
Only B:
```
dl3P1é3
```
None: (empty)
] |
[Question]
[
If the agent is at the origin it always moves right when you choose it.
The goal is to get one agent to 10.
The cost is the sum of the square of the total number of moves (left or right) taken by each individual agent until the first agent gets to 10. You want to minimise the expected cost
Once you have fixed a strategy you should run your code ten thousand times (each time up to the point where the first agent gets to 10) and report the average cost.
# Input and output
There is no input to this challenge. Your code need only output the mean cost over ~~10000~~ 100,000 runs as specified. However please do include an explanation of your strategy for choosing which agent to move when.
In short, the cost of moving a particular agent effectively increases each time you move it. This is a result of the scoring system. As another example, if you move agent 1 twice for your first two moves and it ends up back at the origin, it is now cheaper to move any other agent.
If two answers have the same strategy then the first answer wins. If two different strategies give similar mean costs then they should be rerun with ~~100,000~~ a million (or even more) iterations to see which is better.
A very simple strategy gives a mean cost of 6369. So the first hurdle is to do better than that.
# Winners
This question was first brilliantly solved optimally by Anders Kaseorg.
[Answer]
# [Ruby](https://www.ruby-lang.org/), modified minimum product, average cost ~4950
```
f=->a,b{(0..3).min_by{|q|(9-a[q])**3*b[q]}}
```
[Try it online!](https://tio.run/##RY7NCoQgHMTvPcVeFtSt/1qdIuxFRBalgg5JZeGG@uxuH4edgeF3mIFZNrXH6ZHTQ7AOY2fAbKPz2ieScZpeFon6c@xZ1shUOUQBSgzjoD9qd372qMoknwUmpCTqgBAiBbN2E/SDbp1lPT92opbcCobOfKFF6hYVmBRZjgnSz@IiDFKZWp0NltcSRvltqpCo@5v1ltgQ3vdpGn8 "Ruby – Try It Online")
Always select the agent that minimizes `(9-position)^3*(number of moves)`:
* On the first round, every agent makes a move.
* By using `9-a` instead of `10-a`, any agent in position 9 will try to move on the next iteration.
* Position seems to be more important than the cost projection, so after trying out different values, I found out that the third power is the best way to represent it.
The easiest strategy (round-robin) has a cost of about 7000.
If I let it run in a continuous loop, after a while the average stabilizes around 4950.
[Answer]
# Rust, cost = 4928.296960314256
Computed exactly (modulo floating point imprecision) with a non-random algorithm, but also measured as \$4923.8 ± 2.6\$ (\$1σ\$ confidence) with \$10^7\$ random runs of the actual game as a check.
### Strategy
Consider the following equivalent but wetter version of the game. There’s a tower of cells \$(p, m)\$ with eleven columns \$0 ≤ p ≤ 10\$ and infinitely many rows \$m ≥ 0\$ going downwards. We’ll call the first ten columns \$p = 0, \dotsc, 9\$ “live” and the last column \$p = 10\$ “dead”. Each live cell has a plugged drain in the floor, connected by equal-width pipes to its diagonal neighbors below. We start with \$1\$ liter of water in \$(0, 0)\$, with \$4\$ grains of sand floating in the water. Our goal is to control the plugs until one of the grains ends up in the dead column, while minimizing the expected sum of the squared row numbers of the grains at that time.
The reason to formulate the game like this is that our strategy does not need to look at the grains. Instead, we’re going to open the plugs in some fixed order, letting the grains float where they may, until 100% of the water flows into the dead column in the limit as all of the plugs are open. (We’re very good at opening plugs.)
I’ll explain in a moment how to decide which order we’ll use, but to motivate that, I first need to explain how to evaluate our expected score. Define “time \$t\$” to be the time when \$t\$ liters of water have flowed into the dead column. Then, because the grains of sand flow equivalently to water molecules, the distribution of time quadruples \$(t\_1, \dotsc, t\_4)\$ when the four grains enter the dead column is just the uniform distribution over \$[0, 1]^4\$. Therefore, the time \$t\_\min = \min \{t\_1, \dotsc, t\_4\}\$ when the score should be evaluated has a [beta distribution](https://en.wikipedia.org/wiki/Beta_distribution) \$t\_\min \sim \mathrm{Beta}(1, 4)\$, whose [PDF](https://en.wikipedia.org/wiki/Probability_density_function) is \$4(1 - t)^3\$.
Let \$q\_{(p, m)}(t)\$ be the amount of water in cell \$(p, m)\$ at time \$t\$; let \$c\_{(p, m)}(t) = m^2q\_{(p, m)}(t)\$ be its weighted cost, and \$c\_{\textrm{live}}(t)\$ (resp. \$c\_{\textrm{dead}}(t)\$) the sum over all live (resp. dead) cells. Then we can write our expected score as
\begin{split}
&\int\_0^1 4(1 - t)^3 \left(3\frac{c\_{\textrm{live}}(t)}{1 - t} + c'\_{\textrm{dead}}(t)\right)\,dt \\
&= \int\_0^1 12(1 - t)^2 c\_{\textrm{live}}(t)\,dt + \int\_0^1 4(1 - t)^3 c'\_{\textrm{dead}}(t)\,dt \\
&= \Bigl[-4(1 - t)^3 c\_{\textrm{live}}(t)\Bigr]\_0^1 - \int\_0^1 -4(1 - t)^3 c'\_{\textrm{live}}(t)\,dt + \int\_0^1 4(1 - t)^3 c'\_{\textrm{dead}}(t)\,dt \\
&= \int\_0^1 4(1 - t)^3 (c'\_{\textrm{live}}(t) + c'\_{\textrm{dead}}(t))\,dt.
\end{split}
Therefore, we see that our goal at each step is to minimize the total growth rate of the weighted cost of *all* cells (\$c'\_{\textrm{live}}(t) + c'\_{\textrm{dead}}(t)\$), relative to the rate of flow into the dead column (i.e. growth of \$t\$ itself). \$4(1 - t)^3\$ is decreasing, so we prefer to have smaller ratios earlier. This makes our strategy obvious: at each step, we’ll open the plug that minimizes this ratio, wait until all water has flowed out of that cell, and leave it open while proceeding to the following cells.
Since \$c'\_{\textrm{live}}(t) + c'\_{\textrm{dead}}(t)\$ is piecewise constant, the integral evaluates to an (infinite) sum, one that converges much more quickly than the Monte Carlo simulation. That’s how I determined the precise answer above.
### Code
Build and run with `cargo run --release`.
**`Cargo.toml`**
```
[package]
name = "wandering"
version = "0.1.0"
edition = "2021"
[dependencies]
rand = "0.8.5"
```
**`src/main.rs`**
```
use rand::prelude::*;
use rand::rngs::StdRng;
use std::collections::HashMap;
#[derive(Default, Debug)]
struct Rate {
dead: f64,
cost: f64,
live: HashMap<(u32, u32), f64>,
}
fn add(map: &mut HashMap<(u32, u32), f64>, state: (u32, u32), value: f64) {
if value != 0.0 {
*map.entry(state).or_insert(0.0) += value;
}
}
struct SortingHat {
distribution: HashMap<(u32, u32), f64>,
moves_frontier: [u32; 10],
rates: HashMap<(u32, u32), Rate>,
orders: HashMap<(u32, u32), usize>,
}
impl Default for SortingHat {
fn default() -> SortingHat {
let mut distribution = HashMap::new();
distribution.insert((0, 0), 1.0);
SortingHat {
distribution,
moves_frontier: [0_u32, 1, 2, 3, 4, 5, 6, 7, 8, 9],
rates: HashMap::new(),
orders: HashMap::new(),
}
}
}
impl SortingHat {
fn get_order(&mut self, query_position: u32, query_moves: u32) -> usize {
if let Some(&order) = self.orders.get(&(query_position, query_moves)) {
return order;
}
loop {
let (_, position, moves) = (0_u32..10)
.zip(&self.moves_frontier)
.filter(|&(position, &moves)| {
position + 1 == 10 || self.moves_frontier[position as usize + 1] > moves + 1
})
.map(|(position, &moves)| {
let mut cost = 0.0;
let mut dead = 0.0;
for new_position in [position.abs_diff(1), position + 1] {
cost += moves as f64 + 1. / 2.;
if new_position == 10 {
dead += 1. / 2.;
} else if let Some(new_rate) = self.rates.get(&(new_position, moves + 1)) {
dead += new_rate.dead / 2.;
cost += new_rate.cost / 2.;
}
}
(cost / dead, position, moves)
})
.min_by(|a, b| a.partial_cmp(&b).unwrap())
.unwrap();
self.orders.insert((position, moves), self.orders.len());
let mut rate = Rate::default();
for new_position in [position.abs_diff(1), position + 1] {
rate.cost += moves as f64 + 1. / 2.;
if new_position == 10 {
rate.dead += 1. / 2.;
} else if let Some(new_rate) = self.rates.get(&(new_position, moves + 1)) {
rate.dead += new_rate.dead / 2.;
rate.cost += new_rate.cost / 2.;
for (&newer_state, live_rate) in &new_rate.live {
add(&mut rate.live, newer_state, live_rate / 2.);
}
} else {
add(&mut rate.live, (new_position, moves + 1), 1. / 2.);
}
}
if let Some(mass) = self.distribution.remove(&(position, moves)) {
for (&new_state, live_rate) in &rate.live {
add(&mut self.distribution, new_state, live_rate * mass);
}
}
for old_rate in self.rates.values_mut() {
if let Some(live_rate) = old_rate.live.remove(&(position, moves)) {
old_rate.dead += rate.dead * live_rate;
old_rate.cost += rate.cost * live_rate;
for (&new_state, new_live_rate) in &rate.live {
*old_rate.live.entry(new_state).or_insert(0.0) += new_live_rate * live_rate;
}
}
}
self.rates.remove(&(position + 1, moves + 1));
self.rates.insert((position, moves), rate);
self.moves_frontier[position as usize] += 2;
if (position, moves) == (query_position, query_moves) {
return self.orders.len() - 1;
}
}
}
fn strategy(&mut self, positions: &[u32; 4], num_moves: &[u32; 4]) -> usize {
(0..4)
.min_by_key(|&agent| self.get_order(positions[agent], num_moves[agent]))
.unwrap()
}
}
fn test(mut rng: impl Rng, mut strategy: impl FnMut(&[u32; 4], &[u32; 4]) -> usize, runs: u32) {
let mut count = 0;
let mut mean = 0.0;
let mut m2 = 0.0;
let mut mean_stdev = f64::NAN;
for _ in 0..runs {
let mut positions = [0; 4];
let mut num_moves = [0; 4];
loop {
let agent = strategy(&positions, &num_moves);
if positions[agent] == 0 || rng.gen() {
positions[agent] += 1;
} else {
positions[agent] -= 1;
}
num_moves[agent] += 1;
if positions[agent] == 10 {
break;
}
}
let sample: f64 = num_moves.into_iter().map(|m| (m as f64).powi(2)).sum();
count += 1;
let delta = sample - mean;
mean += delta / count as f64;
m2 += delta * delta * (1. - 1. / count as f64);
mean_stdev = (m2 / (count as f64 * (count - 1) as f64)).sqrt();
if count % 100 == 0 {
eprint!("\r\x1b[K{count}: {mean} ± {mean_stdev}");
}
}
eprint!("\r\x1b[K");
println!("{count}: {mean} ± {mean_stdev}");
}
fn main() {
let rng = StdRng::seed_from_u64(0);
let mut sorting_hat = SortingHat::default();
test(
rng,
|positions, num_moves| sorting_hat.strategy(positions, num_moves),
10000000,
)
}
```
[Answer]
# [Python 3 (PyPy)](http://pypy.org/), 4957.6 +/- 2.6 (10M trials)
```
def expco(positions, num_moves,depth=0) -> float:
if depth==0:
return min((10**2 - positions[i] ** 2)
* (5 * 10**2 - positions[i] ** 2 + 6 * num_moves[i] - 2)/3 for i in range(4))
return (10 not in positions)and min(
expco([abs(p-(i==j)) for j,p in enumerate(positions)],
[m+(i==j) for j,m in enumerate(num_moves)],depth-1)/2 +
expco([p+(i==j) for j,p in enumerate(positions)],
[m+(i==j) for j,m in enumerate(num_moves)],depth-1)/2 +
num_moves[i]*2+1 for i in range(4))
def strategy(positions, num_moves, depth=1) -> int:
return min(range(4), key = lambda i:
expco([abs(p-(i==j)) for j,p in enumerate(positions)],
[m+(i==j) for j,m in enumerate(num_moves)],depth)/2 +
expco([p+(i==j) for j,p in enumerate(positions)],
[m+(i==j) for j,m in enumerate(num_moves)],depth)/2 +
num_moves[i]*2+1)
```
[Try it online!](https://tio.run/##xVTNjpswEL7zFKM9GQIJsNseItGn6C2KIic4iXfjn4LZJlrlofoKfbF0jMGEbLbqqeuDBZ6Zb2a@@Wx9MnslHxN90qfLpWRbYEe9UUSrmhuuZB2DbMRKqFdWxyXTZl@kISTfYHtQ1MwDwMW34CxF6g7sqphpKgmCS0KyNIpySMCDLvgSogjy0LvbFQH5gtuH3jCBr2j39djzBEFmj7BVFXDgEioqd4w8hQ65KwILAKmMtXvQkMqyra4vwfW9oOua6ITwongOwxb3OdY2kmFeVlHDBm7CZTxqABZi4iK7QDEO9JVjYMtYkoUzbOumBD0G@V/Zr3mN8kl2j1QrkNpYuN3pvkY6KWStSLjsJHKlhh4shhd2ggIOVKxLCnz@mYP4zDH8dQhhEFy40KoyIKjZB903klgqEbTzMKw2pB9KDFUjr6bgWN2oRpoYBKMS9xxZT2NIp24LWpebYVuUcLjNvlsMXaR4HeHJ23zJd2w/9/zA4HvVsPmIJLpj0qD/v2gJZTqKHd6FFmUJkwIy@wi9MxTYJ7BDzTq@ppu94htGFlkMSbYcww7MX8GOPD5IkaXj3uxaV4y@@NOaCo00YLuNIEf7ulm2j5btQQ2Bd2@nNU5fsoOhFsAhJe0ovdX@WH/nNXMAgzX3NpsaX9kMAbLer0tsMVa1KdkrprFSm9Y/KkMweAbEVRT1Hxgddi@srvCOk@3DWz/J6WolqWCr1RneLOYZfv9yXw79/IAJgxvNZmmKWszDyx8 "Python 3 (PyPy) – Try It Online")
This is a simple brute force search on top of @Anders Kaseorg's formula (and code).
The score given was obtained with search depth 1, i.e. for each agent compute the expected cost if we can switch agents once immediately after the first move and take the best.
Apologies for the messy code.
[Answer]
# Python 3, cost ≈ 5034.3 ± 2.7
\$1σ\$ confidence, evaluated with \$10^7\$ runs.
```
def strategy(positions, num_moves):
return min(
range(4),
key=lambda i: (10**2 - positions[i] ** 2)
* (5 * 10**2 - positions[i] ** 2 + 6 * num_moves[i] - 2),
)
```
[Try it online!](https://tio.run/##fVJBbuMwDLz7FURPsmsndrbbQ4H8orcgMNSYSYRGkivJbYwij9ov7MeylBUrcXe7PAgSORxySLW922v1o2j7tj@fG9yCdYY73PWs1VY4oZXNQXWylvodbfqUAJlB1xkFUig2vAcfVztkD2kePa/YLw9cvjQcxBOwqsyyBRQQeVdiDVkGizRmZMB@0vEtEu7hkeKxHe8viCDUTM9Ctto4kNztk8ud2mq0TBIvzaF1bNSXg@nUKGijO@VykMgVnQtYQplDOQtHMkC22oAAoS5Cb5K9xVYpdVVSt/AQY7Hdf8Q@9uKA8Gw6vHJ54ztUjvD/38Yk5TqtIXkN90uoQGz/DixJHuDB4mU6s81eiw2yVZVDUa2ntNdh39BOEN@UqMqpJG8vBvlr9FouW1JPKjvJjn7nfshHP@QbjRE@LGlavsGD454gMBXDBmPUPzw@oOaB4BpdxJgvTX@vIoJqxF0Ke47augbfqYz/WDP7Zhyj5Dmw0FE2Xig7TcP0WiOUY9u7z3GBs7pWXGJdn@DTc57g969wC@ynOyqYfPmhVektPf8B "Python 3 (PyPy) – Try It Online") (\$10^5\$ runs)
### How it works
If we were to pick one agent at position \$p\$ that’s previously moved \$m\$ times, and use it for the rest of the game, the expected additional cost would be exactly
$$f(p, m) = \frac13(10^2 - p^2)(5⋅10^2 - p^2 + 6m - 2).$$
(You can verify that
$$m^2 + f(p, m) = (m + 1)^2 + \frac12(f(\lvert p - 1\rvert, m + 1) + f(p + 1, m + 1))$$
and \$f(10, m) = 0\$.)
At each step, we pick the agent that minimizes this quantity. (We don’t restrict ourselves to using it for the rest of the game.)
[Answer]
# 5050? ± 26.64
```
def strategy(positions, num_moves):
E = [100, 99, 96, 91, 84, 75, 64, 51, 36, 19]
_, n = min(((E[p] + m) ** 2 - m ** 2, i) for p, m, i in zip(positions, num_moves, range(4)))
return n
```
[Try it online!](https://tio.run/##fVPbctowEH33V5zJk@waYhOSls7wmD/oG8N4VBCgKbpUltPQDB/VX@iP0ZUFCk7TakaypD17ds@ubA9@Z/TdyB7s4XRaiw1a77gX2wOzppVeGt2W0J1qlHkSbf45Ax4xx6KuqhKzGc0HmnWJT9MSH@9LPND3ns53dF/PloRviIBclNSMsceFXeIDVI6iwAQjqH5TQubYGAdbQtEBUuOntO8mUcJxvRVsmuc50TvhO6ehT1JZ4zwU97vsvCfg2qgsC8K8aD27qCOOTkc5wMp02lNcwTWtE8qVtFXjuGQ9JKTWJxVDXzmHkbIMlamWKDBNtpT2O7YfO7kX@OI68coVBt8K7Qn//14MXBJi0TtTjeeoITd/G@YkD2LfinN1xqudkSvBFtS0Ub0c0qZo17QDxD9C1NVQUhhfneDf0m3LlSX1pLJT7LkoJn2Rn0ORrzQmeN@kYfi12HseCCLTqO9gsoZDwEfUbSR4tU6SLYQuwGoiqC@4c@DA0bR@LZ7CA6aHNW6/O8/I@RYsZlRcNuQdHyQ1w0nt2ebm5dLAcdNorkTTHPESOI/4/SvuIvvxhgJmb14o/WI08tMf "Python 3 (PyPy) – Try It Online")
Use minimal \$\left(E(P\_i)+M\_i\right)^2-M\_i^2\$, where \$E(X)\$ is a pre-calculated array $$\left[E(0),\dots,E(9)\right]=\left[100, 99, 96, 91, 84, 75, 64, 51, 36, 19\right]$$
generated by following codes
```
syms E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 EA
solve([E0-E1-1, E1-(E0+E2)/2-1, E2-(E1+E3)/2-1, E3-(E2+E4)/2-1, E4-(E3+E5)/2-1, E5-(E4+E6)/2-1, E6-(E5+E7)/2-1, E7-(E6+E8)/2-1, E8-(E7+E9)/2-1, E9-(E8+EA)/2-1, EA])
```
[Try it online!](https://tio.run/##Ncq7CsJAEEbh3qeYMmEMZu@bMsX/FGIRYxAxskIk4NOvgzDd@eCU@TPtS30/77SW6Ubb93Ut62OuEhuhJxiCJTiCJwRCJCRCJgyE8bCVdV@aM/oOpjNHubsGPcO2J/u3FRuGUzuxZXi1FztGUAexZ0R1FAdGUidxZGR1FifGoB7EmTGqx0tb6w8 "Octave – Try It Online")
The driver code is used from other posts.
[Answer]
# Python 3, cost ≈ 4928.4 ± 1
I believe this is essentially optimal. Thank you to @usul for the inspiration.
```
import functools
f = lambda p, m: (1. / 3) * (100 - p * p) * (500 - p * p + 6 * m - 2)
@functools.lru_cache(None)
def gittins_value(p, m, l):
if m >= 400:
return f(p, m)
if p == 0:
v_next = gittins_value(p + 1, m + 1, l)
else:
v_next = 0.5 * gittins_value(p - 1, m + 1, l)
if p != 9:
v_next += 0.5 * gittins_value(p + 1, m + 1, l)
return min((2 * m + 1) + v_next, l)
@functools.lru_cache(None)
def gittins_index(p, m):
low = 2 * m + 1
high = f(p, m)
while True:
mid = 0.5 * (low + high)
v = gittins_value(p, m, mid)
if v < mid:
high = mid
else:
low = mid
if abs(high - low) <= 1e-6:
break
return 0.5 * (low + high)
def strategy(p, m):
indices = [gittins_index(p_i, m_i) for p_i, m_i in zip(p, m)]
return indices.index(min(indices))
```
[Answer]
# R / Rcpp: 5006 ± 7.31, or 4932 ± 3.63
Score computed by taking the average of 20 million simulated games. Bounds are a 95% bootstrap confidence interval with 10,000 iterations.
Thanks to Anders Kaseorg for pointing out a typo in my code that caused the solution to accidentally be optimal. Reader, may all your future bugs behave thusly. The following description explains the 5006 solution with a note for how to get the 4932 solution.
## Strategy:
Let's consider a simplified version of the environment in order to construct a risk heuristic. We'd like to be able to treat `n` consecutive movements of an agent as independent, but that won't be true if the agent ever reaches position 0 or 10 during those movements.
Suppose instead that each of the number lines is infinite in both directions, and that the probability of moving right is always 0.5 (even at position 0). In this simplified case, if we move a single agent `n` consecutive times, we may treat the resulting `k` number of movements to the right as binomially distributed.
At each step, let `n = 10 - x`, where `x` is the agent's position on the number line. Since the agent's movements are independent in the simplified environment, we can calculate the probability that the agent has moved backwards given `k` moves to the right as
$$Prob = 1 - \sum\_{k=\lceil \frac{n}{2} \rceil}^n \dbinom n k \cdot 0.5^k \cdot (1-0.5)^{n-k}$$
Note: If you incorrectly move the one-minus inside the sum, the solution becomes near optimal for reasons that are unclear.
Let the cost function be the increase in cost accrued by moving the agent `n` times:
$$ Cost = (x + n)^2 - (x)^2 $$
Then define the risk of moving an agent as
$$ Risk = Prob \cdot Cost $$
and at each step move the agent with the lowest risk.
## Intuition:
The idea is to calculate the risk that over the minimum number of steps an agent would need to reach the goal, the agent ends up moving backwards instead of forwards, i.e. We try to maximize the chance that the chosen agent will move closer to the goal. Minimizing this risk heuristic appears to perform fairly well even though the method does not take into account the effect of the order of the movements, nor the effect of reaching the zero position.
```
#include <Rcpp.h>
using namespace Rcpp;
//* Initialize Environment
// [[Rcpp::export]]
NumericMatrix initEnv() {
return(NumericMatrix (4, 2));
}
//* Update Environment
// [[Rcpp::export]]
NumericMatrix updateEnv(NumericMatrix x, int a) {
//Update move counter
x(a, 1) = x(a, 1) + 1;
//Update position
if(x(a, 0) == 0){
x(a, 0) = 1;
} else {
RNGScope scope;
NumericVector r = Rcpp::runif(1, 0.0, 1.0);
if(r[0] <= 0.5){
x(a, 0) = x(a, 0) - 1;
} else {
x(a, 0) = x(a, 0) + 1;
}
}
//Return
return(x);
}
//* Calculate Loss
// [[Rcpp::export]]
double envCost(NumericMatrix x) {
double lambda = 0;
for(int i = 0; i < 4; i++){
lambda = lambda + pow(x(i, 1), 2);
}
return(lambda);
}
//* Calculate Risk
// [[Rcpp::export]]
double agentRisk(NumericMatrix x, int a) {
//Parameters
int pos = x(a, 0);
int n = 10 - pos;
//Calculate risk correctly
double prob = 0;
double cost = pow(x(a, 1) + n, 2) - pow(x(a, 1), 2);
for(int k = ceil(n / 2); k <= n; k++){
prob = prob + (Rf_choose(n, k) * pow(0.5, k) * pow(0.5, n - k));
}
prob = 1 - prob;
//Calculate risk with typo
//double prob = 0;
//double cost = pow(x(a, 1) + n, 2) - pow(x(a, 1), 2);
//for(int k = ceil(n / 2); k <= n; k++){
// prob = prob + (1 - Rf_choose(n, k) * pow(0.5, k) * pow(0.5, n - k));
//}
//Return
return(prob * cost);
}
//* Simulate Game
// [[Rcpp::export]]
List simGame() {
//Generate environment
NumericMatrix en = initEnv();
//Complete game
bool done = false;
while(!done){
//Parameters
int a = 0;
double lambda = agentRisk(en, 0);
//Calculate risks and choose action
for(int i = 1; i < 4; i++){
double lambda_new = agentRisk(en, i);
if(lambda_new < lambda){
a = i;
lambda = lambda_new;
}
}
//Update game
en = updateEnv(en, a);
//Check victory conditions
for(int i = 0; i < 4; i++){
if(en(i, 0) >= 10){
done = true;
break;
}
}
}
//Return
return(
List::create(
Named("state") = en,
Named("cost") = envCost(en)
)
);
}
```
[Answer]
# Rust, cost = ~5032 (1M iterations)
```
const depth: usize = 1200;
const iterations: usize = 1_000_000;
lazy_static! {
static ref EXPECTED_SCORES: [[usize; 10]; depth] = {
let mut expected_scores = [[1_000_000usize; 10]; depth];
for i in (0..depth-1).rev() {
for j in 0..10 {
if j == 0 {
expected_scores[i][j] = expected_scores[i + 1][j + 1].saturating_add(2 * i + 1);
} else if j == 9 {
expected_scores[i][j] =
(expected_scores[i + 1][j - 1] / 2).saturating_add(2 * i + 1);
} else {
expected_scores[i][j] = (expected_scores[i + 1][j + 1]/ 2)
.saturating_add(expected_scores[i + 1][j - 1] / 2)
.saturating_add(2 * i + 1);
}
}
}
expected_scores
};
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
struct Agent {
position: u8,
actions: u32,
}
fn strategy(agents: [Agent; 4]) -> usize {
return (0..4)
.min_by_key(|i| EXPECTED_SCORES[(agents[*i].actions as usize).min(depth - 1)][agents[*i].position as usize])
.unwrap();
}
```
Basically pre-computes a table of expected scores then uses that.
[Playground link](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=31b9f5b089615a963e41b679395e1d1a) Need to reduce iterations if you don't want it to time out.
[Answer]
# [Python 3 (PyPy)](http://pypy.org/), 5027.1 ± 8.3
```
def strategy(positions, num_moves) -> int:
return min(
range(4),
key=lambda i: (10 - positions[i] + 2*num_moves[i]) * (10 - positions[i]),
)
```
[Try it online!](https://tio.run/##fVPBbtswDL37K4ieZM9O7aynAOkn7LRbEBhqzCRCI8mV5K5GkY/aL@zHMkpylHrrxoMhkY@PfKTcj@6o1deqH/vxculwD9YZ7vAwsl5b4YRWtgQ1yFbqV7Q5VI8glFtlQGbQDUaBFIqFe/BxdUD2kJfJ84zj@sTlU8dBrIA1NVSQuDdiC19gWaQK5Mih@AQ2MeYXIXttHEjujtl0pqKdllnm@3doHbuKKMEMKnb9TSuMbe/0oFwJErmi7xLWUJdQL@InC5C9NiBI6CQnkKySotQWpW7qLbX7kGJJyCexH0dxQvhuBrxxeeMHVI7w/x/9LOU2mZBMQ1xDA2L/d2BN8gBPFqcpLXZHLXbINk0JVbOd097W8IF2hvhHiaaeS/L2ZJA/J6/lsif1pHKQ7K0olmHIb37IHzQmeFjSvHyHJ8c9QWSqwgZT1F88PqLuI8EtukwxX9o/MCJorripsOdorevwlcr4B7awL8YxSr4HFjsqrgfKzvM4vd7QL8H2d@/XBS7aVnGJbXuGd895hl8/4ymyn@@oYPbHS23qYPnlNw "Python 3 (PyPy) – Try It Online")
Copies the function/testing template from [Anders Keorg's answer](https://codegolf.stackexchange.com/a/250837).
Chooses the agent with the minimal best-case cost \$(10-\mathit{position}+\mathit{moves})^2-\mathit{moves}^2=(10-\mathit{position}+2\mathit{moves})(10-\mathit{position})\$.
[Answer]
# C++: ~4953 (100 million iterations)
```
#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int rand(int a, int b) { return uniform_int_distribution<int>(a, b)(rng);}
int main() {
const int NRIT = 100'000'000;
auto go = [&] {
int l[4] = { 10,10,10,10 }, t[4] = {}, sol = 0;
auto cost = [&](int nr) {return l[nr] * (4 * t[nr] * l[nr] + 6); };
while (1) {
pair<int, int> best = { INT_MAX, -1 };
for (int i = 0; i < 4; ++i)
best = min(best, { cost(i), i });
int opt = best.second;
sol += 2 * t[opt]++ + 1;
if (l[opt] == 10)
--l[opt];
else {
if (rand(0,1))
--l[opt];
else
++l[opt];
}
if (!l[opt])
return sol;
}
};
long long total = 0;
for (int i = 0; i < NRIT; ++i)
total += go();
cout << (double)(total) / NRIT;
}
```
I misread the question at first and thought it had a 1/2 chance to move backwards or stay still. This chooses the agent with the least expected cost to finish, according to my calculations and the (wrong) assumption it can't go backwards.
\$ \text{cost} = (10-p)(4 \cdot (10-p) \cdot m+6)\$
I want to add 10 000 iterations is definitely not enough, I could cherrypick 10k iterations to get 4790, which is far from the real average. Standardised testing also encounters the issue of different number generators, which can actually make a small difference (it did from my testing).
[Answer]
# Python: ~4973
**TL;DR** By Gittins theory, there is an optimal solution of the following form, but it has some complicated replacement for `approx_grades` and this is a heuristic.
```
import random,numpy
def approx_grade(x,n):
if x <= 0:
return 2*n+1 + approx_grade(1, n+1)
else:
return 2**(10-x) * (9 - x) + (2**(11-x) -2)*(2*n + 1)
def sim(num_players):
xs = [0]*num_players
ns = [0]*num_players
grades = [approx_grade(0,0)]*num_players
while True:
i = numpy.argmin(grades) # STRATEGY HERE
ns[i] += 1
if xs[i] == 0:
xs[i] = 1
elif random.random() <= 0.5:
xs[i] += 1
if xs[i] == 10:
return sum([n*n for n in ns])
else:
xs[i] -= 1
grades[i] = approx_grade(xs[i], ns[i])
T = 100000
scores = [sim(4) for t in range(T)]
print(numpy.mean(scores))
```
This is a special case of the Gittins index theorem, and there is a very nice exposition of essentially this game in the 2003 paper *On Playing Golf with Two Balls*[1]
[1] <https://epubs.siam.org/doi/abs/10.1137/S0895480102408341>
Notice we can rephrase the cost as: when we move an agent that has taken n steps so far, we pay 2n+1 immediately, and the total cost at the end is the sum of all payments made along the way. Note 2n+1 = (n+1)^2 - n^2.
The key point is that for any given agent i and state of the agent (i.e. location x[i] and number of steps so far n[i]), there is an **index** or "grade" we can give the agent that perfectly captures how desirable it is to choose that agent next. The optimal strategy is to pick the agent with the best grade. **One agent's grade does not depend on the others' states!**
The grade is the following number. Imagine we had a fifth agent with the ability to magically teleport to the end for a cost g. And imagine we are playing the game with only agent i and the magic agent. If g is very small, we will just choose the magic agent. But if g is large, we will take a risk and play agent i, see what happens, and then decide whether to use the magic agent or play agent i again.
There is some magic number g(x[i],n[i]) where we are indifferent between the magic agent and i. That number is the grade.
---
Now, in theory the grade is polynomial-time computable, but it's pretty complex. So I used the following approximation: suppose the optimal strategy in the magic game is to keep trying agent i as long as they move right, but as soon as they move left, pay g to stop. Then the index for step 9 would satisfy
$$ g(9,n) = 2n + 1 + \frac{1}{2}g(9,n) . $$
The left side is if we pay g(9,n) for the magic agent to halt immediately, and the right side is if we pay 2n+1 to advance agent i: with probability half we terminate and pay nothing, and with probability half we go left, at which point we pay g(9,n) to stop.
This solves to g(9,n) = 4n+2.
Similarly, at location 8, we should be indifferent between paying g(8,n) to stop, or paying 2n+1 to get a half chance to go left -- when we pay g(8,n) to stop -- and a half chance to go right -- when we repeat the game at step 9.
$$ g(8,n) = 2n+1 + \frac{1}{2} g(8,n) + \frac{1}{2}\left(2(n+1)+1 + \frac{1}{2}g(8,n)\right) . $$
If we repeat this logic, we get an approximation to the grade which is
$$ g(x,n) = 2^{10-x}(9-x) + (2^{11-x}-2)(2n+1) . $$
After dealing with the special case of x=0, I get this code. Apparently it's still pretty suboptimal as another answer gets ~4927.
---
Note: I used multiprocessing to run 8 million total reps in 36min on a laptop, and got an average of just under 4973. I also reimplemented in C++ with probably hundreds of millions of reps and it seemed to converge to about 4974.5. But the quality of the RNG and precision arithmetic matters! C's built in rand() gave basically nonsense.
[Answer]
# R / Rcpp: 4937 ± 4.22
Average of 15 million simulated games. Bounds are a 95% bootstrap confidence interval with 15,000 iterations.
As a supplement to the wonderful Gittins index answers, I wanted to show an empirical method that produces the same result. This solution predicts which robot to move using a neural net that's been trained by a genetic algorithm.
## Strategy:
In order to optimally move our robots across the number lines, we need to determine a function that maps each robot's state information to a value that represents our decision to move it. This is called an action-value function. For simplicity, let's choose to always move the robot with the highest action-value.
At this point we could use the Gittins index as our action-value, but let's empirically estimate an action-value function instead.
### Estimating the Action-Value Function
I decided to use a neural net (NN) to approximate the action-value function. The NN is fully connected with two hidden layers, each having ten neurons. Weights are initialized using the He method, and biases are initialized uniformly on \$[-1,1]\$. The activation functions are all rectified linear units (ReLU), except the activation function for the output, which is a ReLU clamped to \$[0, 1]\$.
Neural nets often have better performance when the inputs are symmetrically distributed and on the interval \$[-1, 1]\$, but in this problem the input state information of a robot is its current position on the interval \$[0 .. 9]\$ and the number of times it has been moved on the interval \$[0 .. \infty)\$.
I transformed the position of the robot to the \$[-1, 1]\$ interval by shifting and scaling.
To transform the total number of moves I first simulated 10 million games in which I always moved the same robot. This gave a distribution for the total number of moves, which I used to estimate an upper bound. The distribution of the total number of moves is heavily right skewed, so I applied a log transform to reduce skew, and then normalized the result using the log of my estimated upper bound in order to arrive at the \$[-1, 1]\$ interval for total number of moves. Note: Because the total number of moves can be zero, I added one to the total number of moves before taking the log.
### Training the Neural Net
In reinforcement learning there are a number of well-established methods for training neural nets that predict action-values, but I have decided to completely ignore them because I've been having a lot of fun with genetic algorithms recently. There's no fun like gradient-free fun.
The genetic algorithm that I used updated NN weights and biases, but not the NN architecture itself. The initial population was 225 chromosomes, and fitness for each chromosome was calculated by evaluating its corresponding action-value function over 7500 games.
It is often desirable for neural net weights and biases to be relatively small and for the model's learned representation to be distributed across the neurons. To achieve this, I added batch normalization to the hidden layers of the neural nets. Regularizing the models in this way greatly improved performance and helped to ensure that the mutation function continued to be effective late in training by keeping the weights and biases close to the mutation function's generating distributions.
The batch normalization's \$\gamma\$ and \$\beta\$ parameters were also updated by the genetic algorithm.
## Learned Action-Values:
This graph shows the final neural net's predicted action-values for robots in the most commonly traversed subset of the state space. Note: Because these estimated action-values are not with reference to any rewards, they only have meaning with respect to each other. I have arbitrarily scaled them to be between zero and one.
[](https://i.stack.imgur.com/pGKVv.jpg)
## Code:
**R Code to Generate Policy**
```
# Parameters
iters <- 100
popNum <- 225
layers <- c(10, 10)
neval <- 7500
mutRate <- 0.001
# Evolve
population <- generatePopulation(popNum, layers, neval)
out <- rep(NA, iters)
for(i in 1:iters){
# Evaluate population fitness
fitness = evaluatePopulation(population, neval)
out[i] = mean(fitness)
# Keep track of best policy so far
minFit = fitness[length(fitness)]
if(min(fitness) <= minFit){
minFit = min(fitness)
minPolicy = population[[which.min(fitness)]]
}
# Selection
cutoff = quantile(fitness, 0.5)
population = population[fitness <= cutoff]
# Crossover
offspringNum = (popNum - length(population))
offspring = lapply(1:offspringNum, function(i){
inds = sample(1:length(population), 2, FALSE)
crossover(population[[ inds[1] ]], population[[ inds[2] ]])
})
population = c(population, offspring)
# Mutate
population = lapply(1:length(population), function(i){
mutate(population[[i]], rate = mutRate)
})
# Elitism
eliteInds = c(round(0.99 * popNum):popNum)
population[eliteInds] = lapply(eliteInds, function(i){minPolicy})
}
```
**R Code Helper Functions**
```
#' Evaluate Population
#' @export
evaluatePopulation <- function(population, neval){
sapply(population, function(x){
return(mean(evaluatePolicy(x, neval)))
})
}
#' Generate Random Population
#' @export
generatePopulation <- function(size, layers, neval, maxCost = Inf){
# Population
population = list()
# Increase yield
while(TRUE){
# Generate seed population
out = lapply(1:size, function(i){
generateChromosome(layers)
})
# Calculate fitness
fitness = evaluatePopulation(out, neval)
fitness[fitness > maxCost] = NA
inds = order(fitness)
out = out[inds]
fitness = fitness[inds]
# Seed population
population = c(population, out[!is.na(fitness)])
# Report
if(length(population) >= size){
population = population[1:size]
break
} else {
message(paste0("Found: ", length(population)))
}
}
# Return
return(population)
}
```
**Rcpp Code for Genetic Algorithm**
```
#include <Rcpp.h>
using namespace Rcpp;
//* Initialize Environment
// [[Rcpp::export]]
NumericMatrix initEnv() {
return(NumericMatrix (4, 2));
}
//* Update Environment
// [[Rcpp::export]]
NumericMatrix updateEnv(
NumericMatrix env,
int a
) {
//Increase movement count
env(a, 1) += 1;
//Move robot
if(env(a, 0) == 0){
env(a, 0) = 1;
} else {
NumericVector r = Rcpp::runif(1, 0.0, 1.0);
if(r[0] >= 0.5){
env(a, 0) += 1;
} else {
env(a, 0) -= 1;
}
}
//Return
return(env);
}
//* Calculate Total Cost
// [[Rcpp::export]]
double envCost(NumericMatrix env) {
double lambda = 0;
for(int i = 0; i < env.nrow(); i++){
lambda += pow(env(i, 1), 2);
}
return(lambda);
}
//* Generate Chromosome
// [[Rcpp::export]]
List generateChromosome(
IntegerVector layers
) {
//Create container for the NN matrices
List chrom;
//Create weight and bias matrices for each layer
for(int i = 0; i < layers.length() + 1; i++){
//Determine matrix dimensions
int inputNum;
int outputNum;
if(i == 0){
inputNum = 2;
outputNum = layers[i];
} else if(i == layers.length()){
inputNum = layers[i - 1];
outputNum = 1;
} else {
inputNum = layers[i - 1];
outputNum = layers[i];
}
//Initialize weights and biases
NumericVector wtList = Rcpp::rnorm(outputNum * inputNum, 0.0, sqrt(0.5 * inputNum));
NumericVector biList = Rcpp::runif(outputNum, -1.0, 1.0);
NumericMatrix wt (outputNum, inputNum, wtList.begin());
NumericMatrix bi (outputNum, 1, biList.begin());
//Record
List chLayer = List::create(
Named("wt") = wt,
Named("bi") = bi
);
chrom.push_back(chLayer);
}
//Initialize batch normalization matrix
NumericMatrix batch (layers.length(), 2);
NumericVector batchVals = Rcpp::rnorm(batch.size(), 0.0, 1.0);
for(int i = 0; i < batch.size(); i++){
batch[i] = batchVals[i];
}
//Return
List out = List::create(
Named("layers") = layers,
Named("chrom") = chrom,
Named("batch") = batch
);
return(out);
}
//* Crossover
// [[Rcpp::export]]
List crossover(
List x,
List y,
double rate = -1,
double scale = -1
) {
//Set parameters
NumericVector probs = Rcpp::runif(2, 0.0, 1.0);
if(rate >= 0){
probs[0] = rate;
}
if(scale >= 0){
probs[1] = scale;
}
//Crossover the NN
List out = clone(x);
//Access the components
List chrom = out["chrom"];
List xChrom = x["chrom"];
List yChrom = y["chrom"];
//Crossover weights and biases
for(int i = 0; i < chrom.length(); i++){
//Reference the layer
List chLayer = chrom[i];
List xLayer = xChrom[i];
List yLayer = yChrom[i];
//Access the matrices
NumericMatrix wt = chLayer["wt"];
NumericMatrix bi = chLayer["bi"];
NumericMatrix xWt = xLayer["wt"];
NumericMatrix xBi = xLayer["bi"];
NumericMatrix yWt = yLayer["wt"];
NumericMatrix yBi = yLayer["bi"];
//Crossover
LogicalVector doCross_wt = (Rcpp::runif(wt.size(), 0.0, 1.0) < probs[0]);
LogicalVector doCross_bi = (Rcpp::runif(bi.size(), 0.0, 1.0) < probs[0]);
for(int j = 0; j < wt.size(); j++){
if(doCross_wt[j]){
wt[j] = probs[1] * (xWt[j] - yWt[j]) + xWt[j];
}
}
for(int j = 0; j < bi.size(); j++){
if(doCross_bi[j]){
bi[j] = probs[1] * (xBi[j] - yBi[j]) + xBi[j];
}
}
}
//Crossover gamma and beta
NumericMatrix batch = out["batch"];
NumericMatrix xBatch = x["batch"];
NumericMatrix yBatch = y["batch"];
LogicalVector doCross_yb = (Rcpp::runif(batch.size(), 0.0, 1.0) < probs[0]);
for(int i = 0; i < batch.size(); i++){
if(doCross_yb[i]){
batch[i] = probs[1] * (xBatch[i] - yBatch[i]) + xBatch[i];
}
}
//Return
return(out);
}
//* Mutate
// [[Rcpp::export]]
List mutate(
List x,
double rate = -1
) {
//Set parameters
NumericVector probs = Rcpp::runif(1, 0.0, 1.0);
if(rate >= 0){
probs[0] = rate;
}
//Access components
List out = clone(x);
List chrom = out["chrom"];
//Mutate weights and biases
for(int i = 0; i < chrom.length(); i++){
//Access the weights and biases
List chLayer = chrom[i];
NumericMatrix wt = chLayer["wt"];
NumericMatrix bi = chLayer["bi"];
//Mutate
int numInputs = wt.ncol();
LogicalVector doMut_wt = (Rcpp::runif(wt.size(), 0.0, 1.0) <= probs[0]);
LogicalVector doMut_bi = (Rcpp::runif(bi.size(), 0.0, 1.0) <= probs[0]);
for(int j = 0; j < wt.size(); j++){
if(doMut_wt[j]){
wt[j] = Rcpp::rnorm(1, 0.0, sqrt(0.5 * numInputs))[0];
}
}
for(int j = 0; j < bi.size(); j++){
if(doMut_bi[j]){
bi[j] = Rcpp::runif(1, -1.0, 1.0)[0];
}
}
}
//Mutate gamma and beta
NumericMatrix batch = out["batch"];
LogicalVector doMut_yb = (Rcpp::runif(batch.size(), 0.0, 1.0) <= probs[0]);
for(int i = 0; i < batch.size(); i++){
if(doMut_yb[i]){
batch[i] = Rcpp::rnorm(1, 0.0, 1.0)[0];
}
}
//Return
return(out);
}
//* Neural Net Prediction
//*
//* Environment:
//* env[0] = Position
//* env[1] = Total moves
//*
// [[Rcpp::export]]
NumericVector predictNN(
NumericVector env,
List chromosome
) {
//Initialize the output
NumericVector pred (1);
//Process environment
//Normalizing to be in [-1, 1]
NumericVector vIn (2);
vIn[0] = (env[0] / 5 - 1);
vIn[1] = 2 * (log(env[1] + 1) / log(2000)) - 1;
//Compute NN outputs
List chrom = chromosome["chrom"];
NumericMatrix batch = chromosome["batch"];
for(int i = 0; i < chrom.length(); i++){
//Access the layer
List chLayer = chrom[i];
NumericMatrix wt = chLayer["wt"];
NumericMatrix bi = chLayer["bi"];
//Calculate activation
NumericVector vOut (wt.nrow());
for(int j = 0; j < wt.nrow(); j++){
NumericVector wtVec = wt(j, _);
NumericVector biVec = bi(j, _);
NumericVector act = {sum(wtVec * vIn) + biVec};
vOut[j] = act[0];
}
//Apply batch normalization
if(vOut.size() > 1){
vOut = (vOut - mean(vOut)) / sd(vOut);
vOut = batch(i, 0) * vOut + batch(i, 1);
}
//Apply ReLU
for(int j = 0; j < vOut.length(); j++){
NumericVector relu = {0.0, vOut[j]};
vOut[j] = max(relu);
}
//Copy
vIn = clone(vOut);
}
//Record
pred[0] = vIn[0];
//Return
return(Rcpp::clamp(0.0, pred, 1.0));
}
//* NN Prediction to Action
// [[Rcpp::export]]
int predToResponse(NumericVector pred){
//Calculate response
double maxPred = max(pred);
IntegerVector response;
for(int i = 0; i < 4; i++){
if(pred[i] >= maxPred){
response.push_back(i);
}
}
int action = Rcpp::sample(response, 1)[0];
//Return
return(action);
}
//* Evaluate Chromosome
// [[Rcpp::export]]
NumericVector evaluatePolicy(
List chromosome,
int iters
) {
//Initialize parameters
NumericVector out (iters);
NumericVector pred (4);
//Run episodes
for(int i = 0; i < iters; i++){
//Episode parameters
NumericMatrix env = initEnv();
//Complete episode
bool done = false;
while(!done){
//Update state
for(int j = 0; j < 4; j++){
NumericVector state = env(j, _);
pred[j] = predictNN(state, chromosome)[0];
}
int a = predToResponse(pred);
env = updateEnv(env, a);
//Check victory condition
for(int j = 0; j < 4; j++){
if(env(j, 0) >= 10){
out[i] = envCost(env);
done = true;
break;
}
}
}
}
//Return
return(out);
}
```
] |
[Question]
[
This is not the same as [m-ss-ng-lette-s](https://codegolf.stackexchange.com/questions/164809/m-ss-ng-lette-s)
**Challenge:**
Given a string with masked characters, generate all possible words, inclusive of non-meaningfull words.
**Rules:**
* The sequence of the characters in the string does not change.
* The masked character (\*) will be one of an English alphabets [a-z].
* There are no line breaks, space, numbers, special characters or punctuations.
* The output can be a list of non-meaningfull words too.
* Any characters in a string can be masked. Not necessarily alternating characters.
* For memory constraint, lets keep the maximum length of input as 10.
**Example 1:**
Input:
```
*o*
```
Output:
```
aoa
aob
aoc
...
...
...
boa
bob
boc
...
...
...
zoa
zob
zoc
...
...
...
zoz
```
**Example 2:**
Input:
```
*e*c*m*
```
Output:
```
aeacama
aeacamb
...
...
...
welcome
...
...
zezczmz
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!
[Answer]
# [Haskell](https://www.haskell.org/), 31 bytes
```
mapM q
q '*'=['a'..'z']
q c=[c]
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPzexwFehkKtQQV1L3TZaPVFdT0@9Sj0WKJBsG50cC5TPzLMtKMrMK1FQUUhTUNJK1UrWytVS@v8vOS0nMb34v25yQQEA "Haskell – Try It Online")
[Answer]
# [Zsh](https://www.zsh.org/), 25 bytes
```
eval echo ${1//\*/{a..z}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY7U8sScxRSkzPyFVSqDfX1Y7T0qxP19KpqayHyUGXLo5W08rWUYqFcAA)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
```
->s{(?a..?z*10).grep /^#{s.tr'*',?.}$/}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664WsM@UU/PvkrLWFMvvSi1QEE/Trm6WK@kSF1LXcder1ZFv/Z/gUJatLpWvpZ67H8A "Ruby – Try It Online")
The range is set to terminate after 10 `z`s, to fit the constraint. Realistically this takes forever to run unless a smaller number is used.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 5 bytes
```
×kaVΠ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwiw5drYVbOoCIsIiIsIltcIipcIixcInlcIixcInhcIixcIipcIixcImxcIl0iXQ==) Input as char lists.
```
V # Replace
× # Asterisks
ka # With the lowercase alphabet
Π # Take cartesian product
```
[Answer]
# [Perl 5](https://www.perl.org/) + `-n -M5.10.0`, 37 bytes
1 byte saved thanks to [@Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus)!
```
$"=",";s/\*/{@{[a..z]}}/g;say<"$_\n">
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJFwiPVwiLFwiO3MvXFwqL3tAe1thLi56XX19L2c7c2F5PFwiJF9cXG5cIj4iLCJhcmdzIjoiLW5cbi1NNS4xMC4wIiwiaW5wdXQiOiIqbXkifQ==)
## Explanation
Turns the input into a `glob` (`<"$_\n">`) which is then evaluated as a list and printed (`say`) with newline separators.
**Note:** This does struggle to produce all the output for multiple `*`s when running on my phone!
[Answer]
# Python 3, ~~88~~ 86 bytes
```
def A(x):p=x.find("*");~p and[A(x[:p]+chr(i+97)+x[p+1:])for i in range(26)]or print(x)
```
Removed 2 bytes thanks to [@Adam](https://codegolf.stackexchange.com/users/113573/adam)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `j`, ~~14~~ 13 bytes
```
×Oka↔ƛ?×\%V$%
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwiw5dPa2HihpTGmz/Dl1xcJVYkJSIsIiIsIipvKiJd)
[Could be 8 bytes by using `%` instead of `*`](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwiXFwlT2th4oaUdiUiLCIiLCIlbyUiXQ==)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 9 bytes
```
×Ẇ⌈yvkaYΠ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwiw5fhuobijIh5dmthWc6gIiwiIiwiKnl4KmwiXQ==)
Based on emanresu A's answer, but shaves off another byte.
[Answer]
# [R](https://www.r-project.org), 65 bytes
```
f=\(s)`if`(grepl("[*]",s[1]),f(sapply(letters,sub,pa="[*]",s)),s)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWNx3TbGM0ijUTMtMSNNKLUgtyNJSitWKVdIqjDWM1ddI0ihMLCnIqNXJSS0pSi4p1ikuTdAoSbaFqNDWBGGLQ3jQNJa18LSVNrpzUvPSSDI00DXWtVK1krVwtdU2oGpilAA)
Basically the same recursive idea as in [Cong Chen's answer](https://codegolf.stackexchange.com/a/250540/55372).
[Answer]
# [Julia](https://julialang.org), 61 bytes
```
!s=join.(Iterators.product((x>'*' ? x : 'a':'z' for x=s)...))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FjdtFYtts_Iz8_Q0PEtSixJL8ouK9QqK8lNKk0s0NCrs1LXUFewVKhSsFNQT1a3Uq9QV0vKLFCpsizX19PQ0NaGGuOek5qWXZGgoKmnlaylpKtTYKRQUZeaV5ORxKSrla-UrIYsg1KZqJWvlAtXX2EHlIMbB3AYA)
(This returns a matrix of all possible words, rather than a list/vector.)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 30 bytes
```
/\*/{%`$
25*$(¶$`
,Y0`*`l`\*.*
```
[Try it online!](https://tio.run/##K0otycxLNPz/Xz9GS79aNUGFy8hUS0Xj0DaVBC6dSIMErYSchBgtPa3//7XytQA "Retina – Try It Online") Explanation:
```
/\*/{
```
Repeat while there are still any `*`s to process.
```
%`$
25*$(¶$`
```
Add 25 copies of each line.
```
,Y0`*`l`\*.*
```
Cyclically transliterate the first `*` on each line to the lowercase alphabet. The `,` tells Retina to process all matches and the `0` tells Retina to process the first character of each match.
[Answer]
# [lin](https://github.com/molarmanful/lin), 49 bytes
```
"\*".?g.+_.+_"%s"?s.#t ?i len $a.~ `/\".t.~ sf"`'
```
[Try it here!](https://replit.com/@molarmanful/try-lin) Returns an iterator of strings.
For testing purposes:
```
"*e*c*m*" ; \outln `' `_
"\*".?g.+_.+_"%s"?s.#t ?i len $a.~ `/\".t.~ sf"`'
```
## Explanation
Prettified code:
```
"\*".?g.+_.+_ "%s"?s.#t ?i len $a.~ `/\ (.t.~ sf ) `'
```
Not very short, but surprisingly straightforward.
* `"\*".?g` regex `/\*/g`
* `.+_.+_ "%s"?s.#t` replace `*` with `%s` and store as *t*
* `?i len` get number of `*`s as *n*
* `$a.~ `/\` create length-*n* "digit" sequences from alphabet
* `(.t.~ sf ) `'` use *t* to `sprintf` each sequence
[Answer]
# sh + coreutils + [hashcat](https://hashcat.net/hashcat/), 31 bytes
```
sed s/*/?l/g|xargs hashcat -a 3
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'*A:.»â€S
```
Input as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f9fXcvRSu/Q7sOLHjWtCf7/P1pJS0lHKR@ItZRiAQ) or [verify both test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXwf3UtRyu9Q7sPL3rUtCb4v5fO/2glrXwtJR0FJa1UrWStXC2lWAA).
**Explanation:**
```
'*A: '# Replace all "*" in the (implicit) input-list with the lowercase alphabet
.» # Left-reduce the list of strings by:
â # Taking the cartesian product
€S # Then convert each inner list to a flattened list of characters
# (after which the result is output implicitly)
```
Minor note: `'*` could be `W` in the legacy version of 05AB1E if the input is guaranteed to always contain a `"*"`, but unfortunately the `€S` should be `€˜J` in that case, not saving any bytes.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
⊞υSFυ¿№ι*Fβ⊞υ⭆ι⎇⁻μ⌕ι*λκ⟦ι
```
[Try it online!](https://tio.run/##Pc1BCsIwEIXhvacYupoJ8QRdCoKLQkF34iLW1A7GSUkygqePVtH1@z/eMLk0RBdq7TVPqBZ2MmvZl8RyRaJ2NcYEqAQ8Am6iSkG20JiGCD7TmeBHv6pz85IcfBKXntixaMa7hS3L5W8tBAs3Wg58yB76tyx45BO1tZpo6voRXg "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υS
```
Start with the input string.
```
Fυ
```
Check each string.
```
¿№ι*
```
If it contains a `*`, then:
```
Fβ
```
Loop over the lowercase alphabet.
```
⊞υ⭆ι⎇⁻μ⌕ι*λκ
```
Replace the first `*` in the string with the current letter and push it to the search list.
```
⟦ι
```
Otherwise output the string on its own line.
23 bytes using the newer version of Charcoal on ATO:
```
⊞υωFS≡ι*≔ΣEυEβ⁺κμυ≧⁺ιυυ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY6xDoIwEIZ3nuLS6UrKbnBydDAhMhqHUoE2ViBcK4PxKRxdGDTxAXwZ30YauOG_S-77_7vnR2nZq1bacXx7VyWr3yPzpNELGPg6qtoecNt03uWuN02NnAMNxikNaDjcIiWpBBazFDZEpm4w9xfcyS4EhFYIyKwnPAu48KkE-Cn2VFbSW5cGZPbtTa0dBlSAmaF7lE0nHU7ziwpFy4PfA0uulglgiQkatzE7Lrs_ "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation:
```
⊞υω
```
Start with the empty string.
```
FS
```
Loop over the characters of the input string.
```
≡ι*
```
If the current character is a `*`, then...
```
≔ΣEυEβ⁺κμυ
```
... append each lowercase letter to each of the strings so far and join the resulting lists, otherwise...
```
≧⁺ιυ
```
... append the current character to each of the strings so far.
```
υ
```
Output the final list of strings.
[Answer]
# [R](https://www.r-project.org), 91 bytes
```
\(a,j=Vectorize(\(x,y)sub('*',y,x,,,T),'y'))`if`(grepl('*',a,,,T),sapply(j(a,letters),f),a)
```
Recursive solution.
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3o2M0EnWybMNSk0vyizKrUjViNCp0KjWLS5M01LXUdSp1KnR0dEI0ddQr1TU1EzLTEjTSi1ILcsCSiRCp4sSCgpxKjSygQTmpJSWpRcWaOmmaOomaUCtUc1Lz0ksyNNKAmvK1gMZwIQmkaiVr5YIEIYoXLIDQAA)
[Answer]
# [Factor](https://factorcode.org) + `spelling`, ~~60~~ 56 bytes
```
[ 1 group { "*"} ${ ALPHABET } replace [ ] product-map ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TYyxCsIwFEX3fsWjOBUquBWdKogKIoK6WDqE-KzBZxLTZCr9Epcu-gN-Tf_GlDg43Qv3nPt8Xxi3ynT96bhfb5dTuKGRSFAZ5bSQFdQaiYZCwqJhVEOND4eS418ba6POjlsQyguetIMxi6I4UUn8cvaSZn1WwCT8QgNxErcwaiDf7Fb5fHGAFgxqYhyhgBJ-f-mdaSiD_-GMyI_aCGk9goxfw9J1Ib8)
```
! "*o*"
1 group ! { "*" "o" "*" }
{ "*"} ${ ALPHABET } replace ! { "abcdefghijklmnopqrstuvwxyz" "o" "abcdefghijklmnopqrstuvwxyz" }
[ ] product-map ! { "aoa" "boa" ... "zoz" }
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes
```
ẹ{"*"∧!Ạ∋|}ᵐc
```
[Try it online!](https://tio.run/##ATQAy/9icmFjaHlsb2cy/@KGsOKCgeG2oP/hurl7Iioi4oinIeG6oOKIi3x94bWQY///IipvIv9a "Brachylog – Try It Online")
This is a generator predicate that will unify its output with each possible combination. The TIO example uses `ᶠ - findall` to generate all answers, but in a Prolog REPL you could just press `;` repeatedly to get each answer.
### Explanation
```
ẹ Split the string into a list of characters
{ }ᵐ Map for each char:
"*" If the char is "*"
∧! Cut (i.e. discard the "else" possibility)
Ạ∋ The output is an element of the alphabet
| Else don’t modify the char
c Concatenate back to a string
```
The cut `!` is necessary, otherwise the predicate would also generate answers with the asterisk unchanged.
[Answer]
## JavaScript, 111 bytes
I feel like it's way too long and I'm missing something big.
```
s=>(r=s=>s[1]?.at?[...'abcdefghijklmnopqrstuvwxyz'].flatMap(c=>r(s.slice(1)).map(p=>s[0]+c+p)):s)(s.split('*'))
```
[Answer]
# Also **Python 3, 86 Bytes**:
```
def f(x):
for i in range(26):y=x.replace('*',chr(i+97),1);f(y)if'*'in y else print(y)
```
[Answer]
# [Julia](https://julialang.org), 61 bytes
```
!s=foldl((x,y)->[x.*y...],[x<'a' ? 'a'.+(0:25)' : x for x=s])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FjdtFYtt0_JzUnI0NCp0KjV17aIr9LQq9fT0YnWiK2zUE9UV7BWApJ62hoGVkammuoKVQoVCWn6RQoVtcawm1BDjnNS89JIMDUUlrXwtJc0au4KizLySnDwuhHiqVrJWLrIcRCvMHQA)
] |
[Question]
[
A completely even number is a positive even integer whose divisors (not including 1) are all even.
Some completely even numbers are:
* 2 (divisors: 2, 1)
* 4 (divisors: 4, 2, 1)
* 16 (divisors: 16, 8, 4, 2, 1)
* 128 (divisors: 128, 64, 32, 16, 8, 4, 2, 1).
Some *non*-completely even numbers are:
* 10 (divisors: 10, 5, 2, 1)
* 12 (divisors: 12, 6, 4, 3, 2, 1)
* 14 (divisors: 14, 7, 2, 1)
* 18 (divisors: 18, 9, 6, 3, 2, 1)
* 1, being odd, is not completely even.
0 is not completely even (it's divisible by all positive integers, including odd numbers) but you **do not** need to handle this.
Your challenge is to take a positive integer as input and output a truthy value if it is completely even and a falsy value if it is not. These outputs do not need to be consistent.
If your solution doesn't return a falsy value for 0, it's encouraged to show what changes would be necessary to make it do so. Especially encouraged is to **show how your solution differs from checking if the input is a power of 2**; in some languages it may be shorter, and in some longer.
Input may be taken via any allowed method, and output may be given via any allowed method.
The shortest code in bytes wins!
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
qB
```
[Try it online!](https://tio.run/##y00syfn/v9Dp/39DAA "MATL – Try It Online")
### How it works
This takes advantage of MATL's convenient interpretation of truthy and falsy. `q` decrements the input and `B` gets the binary representation of the result. This yields a non-empty array of **1**'s (truthy) for even powers of two, an array that is either empty of contains a **0** (falsy) otherwise.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
Óg
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8OT0//8NAQ "05AB1E – Try It Online")
In 05AB1E only `1` is truthy. Input-`1`-and-input-`0`-verified.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
^’>
```
[Try it online!](https://tio.run/##y0rNyan8/z/uUcNMu/8GRYYGBgYKh9sPT0hTiFR4uGP7o4Y5Cj6ZxSXFCok5OQrJ@bkFOaklqTmVCqllqXkKeaW5SalFxQpJqSXlqUC@gUJiXooCyAy9/wA "Jelly – Try It Online")
### How it works
```
^’> Main link. Argument: n
’ Decrement; yield n-1.
^ Compute the bitwise XOR of n and n-1.
This will conserve the highest set bit of n only if n is a power of two.
If n is even, n-1 will be positive and the result will be different from n.
> Test if the result is larger than n.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 16 bytes
```
lambda n:n^n-1>n
```
Returns *True* or *False*.
[Try it online!](https://tio.run/##K6gsycjPM/5fUJSZV6KhlZaZU5JapPE/JzE3KSVRIc8qLy5P19Au77@OQlFiXnqqhqGBgYGmpuZ/AA "Python 3 – Try It Online")
### How it works
* If **n = 0**, then **n ‚äï (n - 1) = 0 ‚äï -1 = -1 < 0 = n**, so the function returns *False*.
* If **n = 1**, then **n ‚äï (n - 1) = 1 ‚äï 0 = 1 = n**, so the function returns *False*.
* If **2k < n < 2k+1**, then **2k ‚â§ n - 1 < 2k+1**, so **n** and **n - 1** have the **2k** bit in common,
**n ‚äï (n - 1) < 2k < n**, and the function returns *False*.
* Finally, if **n = 2k** with **k > 0**, then **n = 2k** and **n - 1 = 2k - 1** have no bits in common, so
**n ‚äï (n - 1) = n + (n - 1) > n + 0 = n** and the function returns *True*.
[Answer]
# Regex (ECMAScript or better), 17 bytes
`^((x+)(?=\2$))+x$` - Completely even
Takes its input in unary, as a string of `x` characters whose length represents the number.
**[Try it online!](https://tio.run/##Tc89b8IwFIXhv0IjBPeSJiQIdcA1TB1YGNqxtJIVLs5tjWPZBlI@fnsKQ6XOz5GO3i91UKHy7GIWHG/I7xr7TT@dl5aOvVfSL60DOMn5eNR9ArQpwkKuJ33EtO13o/EJ89i8Rc9WA@bBcEXw9JhNEUWQhTjWbAjASE9qY9gSID5IuzcGz1qaPDjDEYbZEAVvAazUuSGrY43zyeXCYaVWwNIpH2hpI@j34gPxD@g/2Hm5KGd3xlj75pgs7UEZ3vS8sppmvSQ1Ytt4EPwsSXCa4u0waZPckyMVgTHfqVjV4BHPYTBwt6QI94pSuH0M0d8m4nrtimxaFsUv "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript
[Try it online!](https://tio.run/##TY5Na8JAEIb/igRhZ4hZEunJ7eqpBy8e2mNtcUnGOCXdpLOrBtTfnsZCwdsLz/v15U4ulMJdzHxb0RBsbsS@Uv3Sd/AWhX2txZ13wydAnyKs7HY@RUz76bDToeGSoJhlBaIR@jmyECghVzXsSaEuRx1p7SPJ3o3WC/vuGBedtCWFoEOs2N9Qtx7UX2LW2OWlto0OXcMRVKbQ8B7A21o35Ot4wOX8euWwcRtg2zkJ93ao3/MPxH9Aj8Avi1WxuGOMB2nPydqfXMPVRJyvaTFJ0sbsWwHDz5YMpymOg0mfaKFuPA@M@tvF8gCCeHk43h6jPgtHAggrtfVqoRSmjCbYwtxuOOTZU5Hnvw "JavaScript (Node.js) – Try It Online") - ECMAScript 2018**
[Try it online!](https://tio.run/##bVLbbtswDH3vV3BGh0i5qE6xp6lGsQ0bMGDthvYxzQDFlhOlMu1JcuOm6LdnlONdCtQvNMmjQ50jbtWDmm2L@4OpmtoF2FIuTC3GEv6vtMHYV2tOr3VHnZOmXVmTQ26V93ClDMITDDUfVKDwUJsCKuqw2@AMrkG5tV8sOYSNq3cePne5boKp6eQJwBdjNZQZ6l3/yxKR14UW1E@4/NiWpXa6uNGq0A5WPexlkf05OaQl53KY66dB7jaRnzGfrUiDKr4Z1IzzNxm21nJTMi/0r1ZZz5Kz8XiccP70EnpkYCy8SvBEDOEvAxGcEcOKcPfST7LRHY5iDPL5WHv@oULQDsFlwx@prZo4wHNJbqzq2mqFsM9KYtQSbnOFSNINNm2ADKLaocZuH33QlTDIJQw6e5jYKH@tu0DX7C0GGAyxdHfiOIKQEIPEob9YgqV2RAnfWBNYMqNHIHwATKnzFQOtgRONcl5TwuwiXfIp4PzVprAa12FzcQ6XEJHwnsJ8SYz5RrnFshv09BnOlxI@OKcevSiNtaybjrpRbwpAWbuoja6RYSoBLzKcU5hMSOCVCvmGHKqIzYnqmLF@c5EW/BORHzdG7Jxq2DAir5vH7@WNwrWmSekUOY9KS2AVjceCvItvu@eDyTU5tnMmaBYflct9Flwb3@dfuyEPQ8mStz4hS7h8jt9J3KrDT8a6CWeX2d35KeeT7vQQV@WQzt7N0/Q3 "Java (JDK) – Try It Online") - Java
Remarkably, there are *three* completely different 17 byte solutions for Powers of 2, which blew my mind even when I thought there were two. For this challenge, only one is 17 bytes, but for plain Powers of 2 they all are.
---
`^(?!(x(xx)+)\1*$)` - **17 bytes** - Powers of 2
`^(?!(x(xx)+)\1*$)x` - **18 bytes** - Powers of 2, correct at zero
`^(?!(x(xx)+)\1*$)xx` - **19 bytes** - Completely even
| Regex engine | Powers of 2 | Completely even |
| --- | --- | --- |
| ECMAScript | [Try it online!](https://tio.run/##Tc/LbsIwEIXhV4GogpmkCUmFusA1rLpgw6Jd9iJZZHCmNY5lG0i5PHsKi0pdf0c6@r/UXoW1Zxfz4Lgmv23tN/30Xlo6DF5IP3cO4Cjnk7T/hMUQOug6zPC9Su@wTydHLGL7Gj1bDVgEw2uCx/t8iiiCLMWhYUMARnpStWFLgDiUdmcMnrQ0RXCGI4zzMQreAFipC0NWxwbnD@czh5VaAUunfKCljaDfyg/EP6D/YOfVoprdGGPj20OytHtluB54ZTXNBklmxKb1IPhJkuAsw@th0iWFJ0cqAmOxVXHdgEc8hdHIXZMi3Coq4XYxRH@diMulr/JpVZa/ "JavaScript (SpiderMonkey) – Try It Online") | [Try it online!](https://tio.run/##Tc/LbsIwEIXhV4GoghnShKRCXeAaVl2wYdEue5EsGJxpjWPZBlwuz57ColLX35GO/i@1V2Hl2cUiOF6T37b2m346Ly0dei@kn5MDOMrZeNR9wrwPCVLCHN/r0R2m1I3GRyxj@xo9Ww1YBsMrgsf7YoIogqzEoWFDAEZ6UmvDlgCxL@3OGDxpacrgDEcYFkMUvAGwUpeGrI4Nzh7OZw5LtQSWTvlACxtBv1UfiH9A/8HO6nk9vTHGxreHbGH3yvC655XVNO1luRGb1oPgJ0mC8xyvh1nKSk@OVATGcqviqgGPeAqDgbsmRbhV1MLtYoj@OhGXS1cVk7qqfgE "JavaScript (SpiderMonkey) – Try It Online") |
| Python | [Try it online!](https://tio.run/##NY7BTsMwEETv@YrF6mG3TaIscEqw@iEhSBW4rZFZR2ujpl@f1kXcRvP0RjNf8znKy@p/5qgZ0jXV6urvFGUAtWqMWT9w/4QLLgvt6J23G1rv7ch9w9MA3nbVMSoE8FLsNuUvL30FwYY2zcFnNI2hCvwRghMM9PbcQxh5smHspgqKLEXWg5wceslYANV/iSfaMd33yoC6NrmDfp5RazCL2cqDFOR7mLUo9CgsD/9v4m9uL@qzw5QVhWjl5pW77gY "Python 3 – Try It Online") | [Try it online!](https://tio.run/##NY7BTsMwEETv@YrF6mG3TSIbOCVY/ZAQpArc1siso7VR3a9P6yJuo3l6o1mu@Rz5ZfU/S5QM6Zpace13ijyCWFFKrR@4f8KCpdCO3s12Q6Ws934yQ2fmEbzVzTEKBPBc/T7lL89DA8GGPi3BZ1Sdogb8EYJjDPT2PECYzGzDpOcGqsxVlgOfHHrOWAG1f8nMtDN036sD4vrkDvJ5RmlBFbXlB6nID7BIVehRWDP@v4m/ub@Izw5TFmSiVXevRusb "Python 3 – Try It Online") |
| Ruby | [Try it online!](https://tio.run/##PY5BiwIxDIXv/oo4LNgqE1rZW7eI4F73IHsbtSjWsVDi0KnYvfjXZ1tRDwnk5X0vCdfD3xBAw9q2NnVI9gar5e8Sg90fFTgtFNzOzlvwurWxHwG4E/imllutqw1VKi98IxDr@VaBpWN2ZAX7zrvIJvWEPxH0ltp4Zvxrnpkm8xl7I6dLAAJHUESMF@OYFByxGN9j9j2yWJWqKXHQdwiqCG5c/uyusX/klb9lnoOjCPQ6UXopY75/VsYMO7YYs8RS4jO@kdMPPgyy/pRC/AM "Ruby – Try It Online") | [Try it online!](https://tio.run/##PY5BiwIxDIXv/oo4LNgqE1rZW7eI4F73IHsbtSjWsVDi0KnYvfjXZ1tRDwnk5X0vCdfD3xBAw9q2NnVI9gar5e8Sg90fFTgtFNzOzlvwurWxHwG4E/imllutqw1VKi98IxDr@VaBpWN2ZAX7zrvIJvWEPxH0ltp4Zvxrnpkm8xl7I6dLAAJHUESMF@OYFByxGN9j9j2yWJWqKXHQdwiqCG5c/uyusX/klb9lnoOjCPQ6UXopY75/VsYMO7YYs8RS4jO@kdMPntIwiPpTCvEP "Ruby – Try It Online") |
This is what I came up to solve a level of [Regex Golf](https://alf.nu/RegexGolf) on 2014-02-21, and was also independently discovered by several others, including earlier than 2013-12-20. It's the one most similar to the well-known [primality test](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime/177196#177196), which is probably why most people came up with this one instead of the others.
It asserts that \$n\$ has no odd divisors of \$3\$ or greater yielding a positive quotient. It has a false positive for zero, since although zero can be divided by any odd number, the quotient is zero, not positive. This can be fixed at the cost of an extra byte: `^(?!(x(xx)+|)\1*$)` or `^(?!(x(xx)+)\1*$)x`.
Since the entire test is inside a (negative) lookahead, it can be adapted to answer this challenge by adding `xx` at the end, which enforces that only \$n≥2\$ can match.
---
`^(?!(x*)(\1\1)+$)` - **17 bytes** - Powers of 2
`^(?!(x*)(\1\1)+$)xx` - **19 bytes** - Completely even
| Regex engine | Powers of 2 | Completely even |
| --- | --- | --- |
| ECMAScript | [Try it online!](https://tio.run/##Tc/LbsIwEIXhVwlRBTNJE5IKdYFrWHXBhkW7LK1kweBMaxzLNpdyefYUFpVYf0c6@r/VToWlZxeL4HhFftPaH/rtvLS0T95Ivx4cwFFOhln3BdMeHDKERb2oMX/ALhsesYzte/RsNWAZDC8Jnh@LEaIIshL7hg0BGOlJrQxbAsSetFtj8KSlKYMzHGFQDFDwGsBKXRqyOjY4eTqfOczVHFg65QPNbAT9UX0i/gPdg53U03p8Y4yNb/fpzO6U4VXildU0TtLciHXrQfCLJMF5jtfD9JCWnhypCIzlRsVlAx7xFPp9d02KcKuohdvGEP11Ii6XripGdVX9AQ "JavaScript (SpiderMonkey) – Try It Online") | [Try it online!](https://tio.run/##TY5PT8IwGMa/ChKTvq9jzWo8rRZOHrhw0KNoaLaX8ZrazbbAEuCzz2Fiwu1Jfs@/L3uwsQrcpdy3NQ3RFDqYV2pe@g7eUmDfyGCPm@ETFnfQPyCs1Vphdo99P2xkdFwRqFmuEHWgnz0HAhHI1o49CZTVqBMtfaKwtaP1xL7bp7ILbUUxyphq9heUrQfxl5g5Mz81xsnYOU4gcoGatwDeNNKRb9IO54/nM8eVXQGbzoZ4bYfmvfhA/Ad0C/xcLVR5xZh2oT1Ol/5gHdeTYH1D5WSaOb1tA2h@NqQ5y3AcnPZTGagbzwOj/Lap2kFAPN0cb/dJHgMnAogLsfaiFAIzRh2N0pcLDkX@pIriFw "JavaScript (Node.js) – Try It Online") |
| Python | [Try it online!](https://tio.run/##NY7BTsMwEETv@YrF4rDbJpFdbglWPyQNUgUuXWTW0doV7deHuojbaJ7eaJZbOSd5Wfl7SVog33Krof3KSUZQr8aY9Q33T3jdEB7cwdH2mdZ7O7mhc/MI7G1zSgoRWKrd5/LBMjQQfezzErmg6Qw1wCeIQTDS626AOLnZx8nODVRZqqxH@QzIUrACav@Sm2nr6L5XBzT0ORz1/YzagrmajTxIRTzAolWhR@Hd@P8mXUr/o1wC5qIoRKvtds7aXw "Python 3 – Try It Online") | [Try it online!](https://tio.run/##NY7BTsMwEETv@YrF4rDbJpFdbgkWH5IGqQKXLjLraG1E@vWhLuI2mqc3muVaLkmeNv5akhbI19xqaD9zkhHUqzFme8WXB1x3hEd3dLR/pHXdbv3khs7NI7C3zTkpRGCpfp/LO8vQQPSxz0vkgqYz1ACfIQbBSM@HAeLkZh8nOzdQZamynuQjIEvBCqj9S26mvaPbXh3Q0Odw0rcLagtmNTu5k4p4gEWrQvfCu/H/Tfou/Y9yCZiLohBttjs4a38B "Python 3 – Try It Online") |
| Ruby | [Try it online!](https://tio.run/##PY5Bi8IwEIXv/oqxLJgoHZJes2ER9LqHxVurQWmsgTCWNGL34l/vJrJ6mIF58743E26n3ymAhh/b2bFHsnfYrHdrDPbYKnBaKLhfnLfgdWfjMANwZ/B1KfdaFw0VKi18LRDLaq/AUpscScGh9y6yRbng/wh6S128MP5ZJaZOfMLeyPkagMARZBHj1TgmBUfMxveYfM8sVozFkjjoBwSVBTfPf/a3ODzz8t8yzcFRBHqdyD2XMdvvjTHTgX3N2bjkrJGN5KsPPk2irKQQfw "Ruby – Try It Online") | [Try it online!](https://tio.run/##PY5BawIxEIXv/RXjIpgoOyR7jUEEvXoove3aUDGugTAu2YjppX99m0jrYQbmzfveTLifvqcAGt5tb9OAZB@w235sMdivswKnhYLH1XkLXvc2jm8A7gK@reVR66qjSuWFbwVi3RwVWDpnR1ZwHLyLbFEv@B@C3lIfr4yvm8y0mc/YC7ncAhA4giJivBnHpOCIxfgas@@ZxapULYmD/oGgiuBm5c/hHsdnXvlb5jk4ikD/J0ovZcz@sDNm@mSbGUtLzjrZSb6a85SmSdSNFOIX "Ruby – Try It Online") |
This was discovered by Grimmy in 2019-02-05, [without fanfare](https://chat.stackexchange.com/transcript/message/48931239#48931239). I on the other hand was amazed, as this has no such flaw as the other negative assertion – it does not match zero.
It asserts that \$n\$ has no divisors yielding an odd quotient of \$3\$ or greater. As a negative assertion, it does not consume the power of 2 that it matches, and thus is great for use in larger regexes where it doesn't need to be wrapped in a lookahead to allow other tests to be done on the same value of \$tail\$.
The downside is that in standard regex engines, it's significantly slower than `^(?!(x(xx)+|)\1*$)`. In my regex engine though, they're both [statically optimized](https://github.com/Davidebyzero/RegexMathEngine/blob/master/matcher-optimization.h#L148) into a bitwise power of 2 test unless optimizations are disabled.
---
`^((x+)(?=\2$))*x$` - **17 bytes** - Powers of 2
`^((x+)(?=\2$))+x$` - **17 bytes** - Completely even
| Regex engine | Powers of 2 | Completely even |
| --- | --- | --- |
| ECMAScript | [Try it online!](https://tio.run/##Tc89b8IwFIXhv0IjBPeSJiQIdcA1TB1YGNqxtJIVLs5tjWPZBlI@fnsKQ6XOz5GO3i91UKHy7GIWHG/I7xr7TT@dl5aOvVfSL60DOMn5eNR9ArQpwkKuJ33EUdvvRuMT5rF5i56tBsyD4Yrg6TGbIoogC3Gs2RCAkZ7UxrAlQHyQdm8MnrU0eXCGIwyzIQreAlipc0NWxxrnk8uFw0qtgKVTPtDSRtDvxQfiH9B/sPNyUc7ujLH2zTFZ2oMyvOl5ZTXNeklqxLbxIPhZkuA0xdth0ia5J0cqAmO@U7GqwSOew2DgbkkR7hWlcPsYor9NxPXaFdm0LIpf "JavaScript (SpiderMonkey) – Try It Online") | [Try it online!](https://tio.run/##Tc89b8IwFIXhv0IjBPeSJiQIdcA1TB1YGNqxtJIVLs5tjWPZBlI@fnsKQ6XOz5GO3i91UKHy7GIWHG/I7xr7TT@dl5aOvVfSL60DOMn5eNR9ArQpwkKuJ33EtO13o/EJ89i8Rc9WA@bBcEXw9JhNEUWQhTjWbAjASE9qY9gSID5IuzcGz1qaPDjDEYbZEAVvAazUuSGrY43zyeXCYaVWwNIpH2hpI@j34gPxD@g/2Hm5KGd3xlj75pgs7UEZ3vS8sppmvSQ1Ytt4EPwsSXCa4u0waZPckyMVgTHfqVjV4BHPYTBwt6QI94pSuH0M0d8m4nrtimxaFsUv "JavaScript (SpiderMonkey) – Try It Online") |
| Python | [Try it online!](https://tio.run/##NY7BbsIwEETv@YqVxWEXkshOb0ktPiQECbWmGLnraG1E@PqAqXobzdMbzfzIl8gfq/@do2RIj1SLq68p8gBiRSm1HhGXHeHeHroN0XbZrK92NH1jpgG81dU5CgTwXOw25W/PfQXBhjbNwWdUjaIK/BmCYwz02fUQRjPZMOqpgiJzkeXEPw49ZyyA6r9kJtoZeu2VAXFtcif5uqDUoBa15TcpyPcwS1HoXVgz/L@Jt9zexWeHKQsy0aqbzmj9BA "Python 3 – Try It Online") | [Try it online!](https://tio.run/##NY7NasMwEITvfopF5LBb/yC5N7uiD@I4EFqlUVFXZqUQ5@mdKKG3YT6@YZZbPkd@3/zfEiVDuqVGXPObIo8gVpRS2wFxrQk/7b7fEdXrbnu0kxlaM4/gra5OUSCA52J3KX97HioINnRpCT6jahVV4E8QHGOgj36AMJnZhknPFRSZiyxH/nHoOWMB1LySmak29NgrA@K65I7ydUZpQK3qjZ@kID/AIkWhZ2HN@P8mXnJ3FZ8dpizIRJtue6P1HQ "Python 3 – Try It Online") |
| Ruby | [Try it online!](https://tio.run/##PY5BC8IwDIXv/oo4BFtlodu1FhH06kG8TS2KdRZKHF3FefGvz1bUQwJ5ed9L/P307D0o2JjadA2SecBysV2gN8ezBKuEhMfVOgNO1Sa0AwB7AVflxV6pbEeZjAtXCcS83EswdI6OqGDbOBvYOB/zL4LOUB2ujM/KyFSRj9gfudw8EFiCJGK4acsKwRGT8T9G3yeLZV02IQ7qBV4mwQ7Tn809tJ@89HcRZ28pAP1OpJ5K69V6qXV/YKybcjZXu3LE@aQb9b3Iy0KINw "Ruby – Try It Online") | [Try it online!](https://tio.run/##PY5BC8IwDIXv/oo4BFtlodu1FhH06kG8TS2KdRZKHF3FefGvz1bUQwJ5ed9L/P307D0o2JjadA2SecBysV2gN8ezBKuEhMfVOgNO1Sa0AwB7AVflxV6pbEeZjAtXCcS83EswdI6OqGDbOBvYOB/zL4LOUB2ujM/KyFSRj9gfudw8EFiCJGK4acsKwRGT8T9G3yeLZV02IQ7qBV4mwQ7Tn809tJ@89HcRZ28pAP1OpJ5K69V6qXV/YKybcjZXu3LE@bQb9b3Iy0KINw "Ruby – Try It Online") |
I discovered this one in 2014-02-21, after being mentally primed by solving teukon's Dominoes 2 puzzle (which is now included in [Regex Golf](https://alf.nu/RegexGolf)); teukon independently came up with it later that same day. It was the very first problem in unary that we solved by repeatedly decreasing \$tail\$ in a loop while retaining an invariant property at every step, and is probably the simplest function that is best golfed by being solved that way.
It repeatedly divides \$tail\$ by \$2\$ (asserting each time that there is no remainder) as many times as possible, and then asserts that the end result is \$1\$. This one is useful in larger regexes when it is desirable to consume the identified power of 2.
It is the most suitable for solving this challenge, “Is it a completely even number?”, as the only change necessary is upping the minimum iteration count of the loop from `0` to `1` by changing the `*` quantifier to a `+`, at a cost of 0 bytes. This enforces that \$n\$ must be evenly divided by \$2\$ at least once before yielding an end result of \$1\$.
[Answer]
# [Python 2](https://docs.python.org/2/), 18 bytes
```
lambda x:~-x&x<1<x
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCqk63Qq3CxtCm4n9BUWZeiUKaRmZeQWmJhqbmf0MA "Python 2 – Try It Online")
-3 thanks to [Rod](https://codegolf.stackexchange.com/users/47120/rod).
[Answer]
## JavaScript (ES6), 14 bytes
```
f=
n=>n>1>(n&n-1)
```
```
<input type=number min=0 oninput=o.textContent=f(this.value)><pre id=o>
```
Python doesn't have the monopoly on chained comparisons!
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
Returns `log‚ÇÇ(x)` if True `0` otherwise
```
£İ2
```
### Explanation
```
£ Is it an element of the increasing sequence
İ2 powers of two (starting at 2)
```
[Try it online!](https://tio.run/##yygtzv7//9DiIxuM/v//b2hkAQA "Husk – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 6 bytes
```
õ!² øU
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=9SGyIPhV&input=MQ==)
---
## Explanation
Generate an array of integers (`õ`) from `1` to input `U`. Raise 2 to the power of each (`!²`). Check if the array includes (`ø`) `U`.
[Answer]
# [Python 2](https://docs.python.org/2/), 33 bytes
```
lambda n:bin(n).count('1')==1-n%2
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKikzTyNPUy85vzSvREPdUF3T1tZQN08VqCq/SCFTITNPoSgxLz1Vw9RA06qgKDOvRCFTJ00jU/M/AA "Python 2 – Try It Online")
## Recusive approach, ~~38~~ 36 bytes
-2 bytes thanks to Leaky Nun
```
f=lambda n:n>1if n<3else f(~n%2*n/2)
```
[Try it online!](https://tio.run/##BcFBCoAgEAXQq8wm0Agqo41UdzFyasC@Ym7adHV7L73lijC18hrcvR@OYLGNwoRl8uHxxOpDY1r0RleOmYQElB1Or@ZB25QFhaRjJbr@ "Python 2 – Try It Online")
[Answer]
# [Implicit](//git.io/sS), ~~7~~ ~~2~~ 3 bytes
```
½?ö
```
[Try it online!](https://tio.run/##K87MLchJLS5JTM7@///QXvvD2/7/NwQA) Explanation:
```
implicit float input
¬Ω calculate log2(input)
? if truthy
ö push 1 if top-of-stack is whole, 0 if non-whole
implicit int output
```
`½` pushes log2(input). If the input is `0` or `1` it will push `0.000000`. 0 is a whole number so performing `ö` on 0 will yield 1, giving the incorrect result for the input 1. `?` only performs the next command if the top of stack is truthy. So if the input was 1 or 0, it will skip the `ö` and print 0 as it's supposed to. Otherwise it will push 1 if `log2(input)` is whole and 0 if it's not.
[Answer]
# Regex ([Tcl ARE](https://www.tcl-lang.org/man/tcl/TclCmd/re_syntax.htm)), ~~24~~ 22 bytes
`^((x((xx)*))\2*$)\3` - **19 bytes** - Powers of 2 - [Try it online!](https://tio.run/##bVHbisIwEH33K46hD1YotC7sS7f7I5qFWscajGNJ4loo/fbutG5Flh3yMJk5l3ASKjt4CnDY@tveByR8ra6XS8kHP/b7sjp7W/oTTdfv0plyb@XSDV@rVSunjddxvNuso3j3NvQ6xywXnOEaruSaEDlk2FLbOHTzxhLX4SQrjQSbXuvFyDTIctxPxpIgawoePhwMw2osCyRZj24BqRFrrdg01gREFipRYm6OQrOztBXWJ9KZM/M4xdYaPlA7QpD@yysKjGYTPkPEokLW03PyqpDp/mlwvLpfzIPURYyPQvpRzXDlwK/vGWsyd1RLPkhE1VQSsESmniFSQ2WAmLFW@i99llhGRlbNTTJTqs8faaY5pol8HtNd3kxQEateakiT9zT9AQ "Tcl – Try It Online")
`^(x$|(x((xx)*))\2*$)\3` - **22 bytes** - Completely even - [Try it online!](https://tio.run/##bVHLboMwELznKyaWDxAJCVKpF0p/JHElQjbEqmOQ7TRIlG@nCylRVHVP6915rMahMqOnAIedvx58QGKbqrlcSnv0U38oq09vSn@m@flVOl0eDD/68SPq5HfURVHXxZs43m83Mt6/jIPKsSgGp20NV9qaIB0y7KhrHfplY8jW4cwrhQTbQanVxNTIctzO2hAjawoePhy1hVFYF0iyAf0KXBPWGLZpjQ6QBiIRbK5PTDOLtGHWO9KFs/Bsip3R9kjdBEH6L68oMJnN@AzSsgoZT4/Js0KmhofBqXG/mDuplxZvBfeTmraVg32@Z6rZ3FHN@SBhVV1xxhyZeIRILZUBbGaVUH/pi8Raal61V85MiCG/p5nmmCf8f5ZufDNBSCsGrjFNXtP0Bw "Tcl – Try It Online")
Tcl ARE has both positive and negative lookaheads, but neither backreferences nor captures can be done inside one. So seemingly, it would be impossible to match powers of 2 instead of non-powers, because all of the ECMAScript regexes use backreferences inside a lookahead. This challenge states "output a truthy value if it is completely even and a falsy value if it is not", so an inverted-logic regex, such as `^(x*)(\1\1)+$|^x$`, would not satisfy the rules.
But as it so happens, in Tcl ARE it seems that any group anchored on both sides (`^` at the beginning and `$` at the end, either inside or outside the group as long as it's adjacent to the parentheses) in all its alternatives will be treated as atomic (preventing the engine from doing the equivalent of backtracking into that expression if the pattern fails to match at a later point). This does not appear to be documented, but it can be exploited to emulate a negative match. The equivalent in engines that support atomic groups would be:
`^(?>(x((xx)*))\1*$)\2` - **21 bytes** - Powers of 2 - [Try it online!](https://tio.run/##XVBda8IwFH33V4QQaK6m2ha3IbHzZRsIYw/b3qwLtUttWU1DGqEg/vbuVva0h1zu1znn5tjKDuuNrSxhjqSELiiZE@v0UTltm7zQPFjMpxulqrzxqmhPtm60y3gGMntfdIEgAb4Sm@qoxwXjtfEdV@pl@/qsFAgSA1IisZzUplad9pzawun5IS9@vMOgmvpUeyoIXSar5er@IVndUZCTsnWc1WkkWZOWyN7xj8@n7RtIuJC65KzZdd412mAGYbxPU5oZCrjcnQ84wbaIRBjDiNe9bdpvzWlIBa5LxBft2fgRu04QtEMCjNFeTgi5KZu/mpl1eptjNpsBShN@c@iU@6LizAkUG@3SuedBHwhmAIBcxhNr0EXVjndJgl@JJRlrwoy8osz1n60c5PDFN4@857zvYQqQxVMGWTIMUZjEUfQL "PHP – Try It Online")
`^(?>(x\B((xx)*))\1*$)\2` - **23 bytes** - Completely even - [Try it online!](https://tio.run/##XVBdS8MwFH3frwgh0Nyt3doylZHVgaggiA/q2zpDV9O1mKUhzaAw9tvr7fDJh1zu1znn5tjaDuuNrS1hjmSELiiZE@vUQTpldVEqHizm042UdaG9LNujbbRyOc9B5O@LLghJgK/CpjyoccF4ZXzHpXx@eX2SEkKSAFIisZg0ppGd8pza0qn5vih/vMMgdXNsPA0JXaar5er2Ll3dUBCTqnWcNVksmM4qZO/4x@fjyxsIOJOm4kxvO@@0MphBlOyyjOaGAi53pz1OsB3GYZTAiFe91e234jSiIa4LxJftyfgRu04RtEUCjPFOTAi5Kpu/mpl1dp1jNpsBShN@dehY@LLmzIUoNtqlCs@DPgiZAQByHk9sQJV1O94lCH4lEWSsCTPigjKXf7ZyEMMX39zzPn/gvO9hCpAnUwZ5OgxxlCZx/As "PHP – Try It Online")
These in turn are based on the [17 byte ECMAScript regex](https://codegolf.stackexchange.com/a/222496/17216) `^(?!(x(xx)+)\1*$)`. The logic of the Tcl ARE version is to assert that the largest odd factor of \$n\$ is \$1\$. The "completely even" version additionally asserts than \$n\ne 1\$.
Even more strangely than the atomic grouping behavior, Tcl ARE apparently records the positions where word-boundary-match operators (`\m`, `\M`, `\y`, `\Y`) were used inside a capture group, and repeats them if that group is repeated via a backreference. So `^((x\Y((xx)*))\2*$)\3` (**21 bytes**) not only doesn't match \$1\$, but doesn't match \$2\$ either: [Try it online!](https://tio.run/##bVHLasMwELznKybChzhgsFPoxXX/oyQqOM7GEVU2RlIag/G3u2unDqF0D2K1Ow8xCpUdPAU4bP117wMSvlSX87nkgx/7fVl9eVv6E03X79KZcm/l0g2fq1W7@5CjjddxvNuso3j3MvQ6xywYnOEaruSaEDlk2FLbOHTzxhLX4SQrjQSbXuvFyDTIctxOxpIgawoePhwMw2osCyRZj24BqRFrrdg01gREFipRYm6OQrOztBXWO9KZM/M4xdYaPlA7QpD@yysKjGYTPkPEokLW02PyrJDp/mFwvLhfzJ3URYy3QvpRzXDlwM/vGWsyd1RLPkhE1VQSsUSmHiFSQ2WAmLFW@i99llhGRlbNVTJTqs/vaaY5pol8H9NN3kxQEateakiT1zT9AQ "Tcl – Try It Online") – and as a result, the 22 byte method has to be used instead.
Explanation for Powers of 2 (**19 bytes**):
```
^
( # Group an expression that is anchored to start at its
# beginning and to end at its end, thus telling the Tcl ARE
# regex engine to treat it as atomic, not backtracking into
# it if a subsequent match fails.
( # \2 = sum of the following, which will be the largest odd
# number that results in a match for what follows:
x # 1; tail -= 1
((xx)*) # \3 = any even number, including zero, trying the largest
# values first; tail -= \3
)
\2*$ # Assert that \2 divides tail; anchor to end of string
)
\3 # Now that the above match is locked in and won't backtrack,
# assert that \3 == 0, as no other value can match when
# tail == 0 (at the end of the string), thus asserting that
# \2 == 1, i.e. that the largest odd factor of N is 1.
```
For Completely even (**22 bytes**), an alternative of `x$` is inserted as the first choice. If \$n=1\$ and this alternative matches, it effectively acts like a boolean short-circuit operator – the powers of 2 test won't be done, and `\3` will not be set.
An alternative method to match powers of 2 is `^((x+?)((\2\2)*$))\3` (**20 bytes**): [Try it online!](https://tio.run/##bVHbboJAEH33K44bHqANCeCjpf0Q3SaII266jmR3rSaEb6cDFmOaztPszLlMzobaDp4CHDb@svMBKZ/r8@lU8d6P/a6qv7yt/JGm53flTLWz8uiGzzi@vX4kcbwttkXyEiXJdjX0eo1ZLzjDDVzFDSFyyLGhW@vQzRtL3ISjrDRSFL3Wi5FpkK9xPRpLgmwoePiwNwyrsSyR5j26BaRGrLVi01oTEFmoVIm5OQjNztJWWO/IZs7M4wwba3hPtxGC7F9eWWI0m/A5IhYVsp4ek2eFXPcPg8PZ/WLupC5ivJXSj2qGawd@vmesydxRI/kgFVVTS8ISmXqESC1VAWLGWum/9FliGRlZtRfJTKl@fU8zW2OayO8xXeVmgopY9VJDlq6KHw "Tcl – Try It Online") - this uses the same atomic grouping trick, but the logic is to assert that the smallest quotient from dividing \$n\$ by any odd number is \$n\$ (thus it's implied that the only odd divisor of \$n\$ is \$1\$). For "completely even" numbers this becomes `^(x$|(x+?)((\2\2)*$))\3` (**23 bytes**): [Try it online!](https://tio.run/##bVHLboMwELznKyaWD9AKCciR0n5I4kqEuMSqs0G20yBRvp0upERR1T2td@exGofajl4HOGz9Ze8DEjrX59OpooOf@n1Vf3pb@aOen1@VM9Xe8qMf36NOfkfd81scRbt8l8dPMo53m3FQBRbJ4Aw1cBU1GtIhw1Z3rUO/bKymJhx5pZAgH5RaTUyDrMD1aKxmZKODhw8HQ7AK6xJJNqBfgWvCWss2rTUB0kIkgs3NB9PsIm2Z9Yp04Sw8SrG1hg66myBI/@WVJSazGZ9BEqto6/V98qiQqeFu8HF2v5gbqZeEl5L7Sc1Q7UCP90w1mzvdcD5IWNXUHDJHJu4h6lZXAWxGSqi/9EViLQ2v2gtnJsRQ3NJMC8wT/kDSV75ZQ0gSA9eYJpv8Bw "Tcl – Try It Online") But this method is much slower than the primary one shown in this answer, and Tcl cannot even match \$n=64\$ within 60 seconds.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Æf=2Ȧ
```
[Try it online!](https://tio.run/##y0rNyan8//9wW5qt0Yll////NwQA "Jelly – Try It Online")
Does ***NOT*** fail for `1`!
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~18~~ 16 bytes
```
i->i>1&(i&~-i)<1
```
[Try it online!](https://tio.run/##TY0xD4IwEIV3fsVNhBppwmYCMjiYODgxGocKlRyWtqFXEmLwr2MxDL7x3fe@68QoUmOl7prXgr01A0EXOk7YS77Lo//OEyr@9LomNHo9RrUSzsFVoIZ3BCGOBGEN5w0qLppkK4c9nIxRUugSLBxhwbTEMosTjD8psiJbgmudW/9QYb5ZRoMN9EGeVDSgbm93EEPr2PZrTTU5kj03nrgNCCmdWC6sVVNyYCz/cXM0L18 "Java (OpenJDK 8) – Try It Online")
[Answer]
# MATL, 4 bytes
Saved a byte thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)!
```
Yf2=
```
**[Try it here.](https://matl.suever.net/?code=Yf2%3D&inputs=2&version=20.4.1)**
Returns `1` (or an array of several `1`s) for truthy and `0` or (the empty string) for falsy.
# How?
```
Yf2= % Full program.
Yf % Prime factors.
2= % All equal 2?
% Output implicitly.
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 5 bytes
```
q]2{P
```
**[Verify all the test cases.](https://pyth.herokuapp.com/?code=q%5D2%7BP&test_suite=1&test_suite_input=1%0A2%0A4%0A16%0A128%0A10%0A12&debug=0)**
Alternative:
```
q2s{P
```
# Explanation
```
q]2{P ~ Full program with implicit input (Q) at the end.
P ~ Prime factors.
{ ~ Deduplicated.
q ~ Equals?
]2 ~ The literal [2].
~ Output (implicitly).
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~37~~ ~~33~~ ~~27~~ 18 bytes
Thanks to @MD XF for the idea
```
f(n){n=(n^n-1)>n;}
```
[Try it online!](https://tio.run/##HcjNCkBAEADg@zzFptRMOFBcBk8ipdVopwzJTZ59/XzHzxeL9zEKGl3WoY1WlNQb31EZ1ikYElzgXrIdqF3J2lZ1w5pl9PcniENBJXL7EewUTNJ5sCRXYrghPg "C (gcc) – Try It Online")
[Answer]
# JavaScript, ~~14~~ 11 bytes
-3 thanks to Deadcode
```
f=
n=>!(n&n-2)
// test numbers 0-16
const tests = [f(0), false, true, false, true, false, false, false, true, false, false, false, false, false, false, false, true]
const results = tests.map((res, n) => res === f(n))
document.write(
results.every(res => res)
? "All tests passed üòä"
: [
"Tests failed üò¶",
...results.map((res, n) => !res && `f(${n}): expected ${tests[n]}`).filter(Boolean),
].join("<br />")
)
```
```
body{font-size:3rem;font-family:monospace}
```
Explanation - this uses [this trick](https://stackoverflow.com/a/1053594/1903116) for checking if `n` is a power of 2, but uses `n&n-2` instead of `n&n-1` to make 1 return false
[Answer]
# Regex (Java / Perl / PCRE / .NET), 12 bytes
`^(\1\1|^x)*x$` - **13 bytes** - Powers of 2
`(\1\1|^x)+x$` - **12 bytes** - Completely even
| Regex engine | Powers of 2 | Completely even |
| --- | --- | --- |
| Java | [Try it online!](https://tio.run/##bVJdb9swDHzvr@CMDZHSRHXWt6nGsA0bMGDthvYxTQHFlhOlMu1JcuO062/PKMf7KBC/0CRPR92JG/Wgppvifm@qpnYBNpQLU4uxhP8rbTD2aM3ple6oc9K0S2tyyK3yHi6VQXiCoeaDChQealNARR12E5zBFSi38vMFh7B29dbD5y7XTTA1nTwB@GKshjJDve1/WSLyutCC@gmXH9uy1E4X11oV2sGyh70ssj8nh7TkXA5z/STI7TryM@azJWlQxTeDmnH@KsPWWm5K5oX@2SrrWXI2Ho8Tzp9eQg8MjIWjBE/EEP4yEMEZMSwJdy/9aTa6xVGMQT4fas8/VAjaIbhs@CO1VRMHeC7JjWVdW60QHrOSGLWEm1whknSDTRsgg6h2qLGbnQ@6Ega5hEFnDxNr5a90F@iavcUAgyGW7k4cBxASYpA49OcLsNSOKOEbawJLpvQIhA@AKXW@YqA1cKJRzmtKmJ2nCz4BnB1tCqtxFdYXb@E9RCS8ozBbEGO@Vm6@6AY9fYazhYQPzqmdF6WxlnWTUTfqTQEoaxe10TUyTCXgRYYzCqenJPBShXxNDlXE5kR1yFi/uUgL/onIDxsjtk41bBiR183ue3mtcKVpUjpBzqPSElhF47Eg7@LbPvLB5Joc2zoTNIuPyuVjFlwb3@dfuyEPQ8mSNz4hS7h8jt9J3Kr9Hbud3c5@3XV83L3exzXZp9Pz8zRNfwM "Java (JDK) – Try It Online") | [Try it online!](https://tio.run/##bVLbbtswDH3PV3DGhki5qE6fhqnGsA0bMGDdhvYxzQDFlhO1Mu1JcuO067dnlONdCsQvNMmjQ50j3qp7Nb8t7g6mamoX4JZyYWoxkfB/pQ3Gnqw5vdEddUZNu7Ymh9wq7@FSGYRHGGo@qEDhvjYFVNRh18EZ3IByG79ccQhbV@88fOxy3QRT08kRwCdjNZQZ6l3/yxKR14UW1E@4fN@WpXa6uNKq0A7WPex5kf05OaQl53KY62dB7raRnzGfrUmDKr4Y1IzzFxm21nJTMi/0z1ZZz5KzyWSScP74HHpkYCycJHgkhvCXgQjOiGFNuDvpp9n4BscxBvl0rD19VyFoh@Cy4Y/UVk0c4LkkN9Z1bbVCeMhKYtQSrnOFSNINNm2ADKLaocau9z7oShjkEgadPUxslf@qu0DX7C0GGAyxdHfiOIKQEIPEob9cgaV2RAnfWBNYMqdHIHwATKnzGQOtgRONcl5TwuwyXfEZ4OJkU1iNm7C9OIe3EJHwhsJiRYz5Vrnlqhv09BkuVhLeOaf2XpTGWtbNxt24NwWgrF3URtfIMJWAFxkuKEynJPBShXxLDlXE5kR1zFi/uUgL/oHIjxsjdk41bBiR183@W3mlcKNpUjpDzqPSElhF47Eg7@LbPvDB5Joc2zkTNIuPyuVDFlwb3@dfuyEPQ8mSVz4hS7h8it8obtWB3SxuFr9@dHzavTzELTmk89fnafob "Java (JDK) – Try It Online") |
| Perl | [Try it online!](https://tio.run/##RY7NasMwEIRfZQlLrG1sLKX0UlmpA@m1p97qRCQhBoGauJILLqr66q7iBnpZdmZ/5utOzj6M71@ATkKwl@PeApYySVVt1q/rVYT24hh6xWW1khTAtElR6Jw59zBrzjMZobbKd9b0LCuy3H8efJ9OdF6IXNDp47r09O/y5NMjapLXXz4l7l1tqyWF2r6JrUqVb@Ut19wkmkpN49QtFhRMC4xlQwYDpCUiUD9QoispoJ/PJ7iJLYEL@ceKRsYYtX5@2Wg97lgjGvG9G@huwHHkhbhfcs5/AQ "Perl 5 – Try It Online") | [Try it online!](https://tio.run/##RY5fS8MwFMW/ymVc1lza0mQgiGlmB/PVJ9/sDHOsEMi2mlSoxPjVa1YHvlzuOffP@fVHZ@@m0xegkxDs5bC3gJVMUtXbzctmHaG7OIZecVmvJQUwXVIUemfOAyza80JGaKzyvTUDy8qs8J/vfkgnuihFIej4cV16/Hd58ukBNcnrL58S966x9YpCY1/FTqXKd/KWa24STa3mcerynILpgLFszGCEtEQE6gcqdBUF9MvlDDezJXAh/1jRyBij1k/PW60n1opWfL@NlI84Tby8X3H@Cw "Perl 5 – Try It Online") |
| PCRE | [Try it online!](https://tio.run/##XVBda8IwFH33V4QQaKKptuo2JBZftoEw9rDtzWqoXWrDYhrSCAW3397dyp72kMv9OufcHFe7fr1xtUPEowzhGUZT5Lw6Sa@cKUpFo9l0vJGyLkyQZXN22iif05yJ/G3WRhxF8CpoypMaFmxQNrRUyufty5OUjKOUASUQi5G2WrYqUOxKr6bHovwKHoI0@qwD5ggv56vl6v5hvrrDTIyqxlOis0QQk1XA3tL3j8ftKxPsinRFidm1wRtlIWNxus8ynFvMYLm9HGECbZ7wOGUDXnXONJ@K4hhzWBeAL5uLDQN2PQfQDgggJnsxQuimbP9qYtfZbQ7ZZMJAGtGbQ@cilDUlnoPYYJcqAo26iBPLGEPX4UTNVFk3w10CwVdSgYYaESt@QObnn62Uif5A8zRPvw8dG3ek75M4XSySJPkF "PHP – Try It Online") | [Try it online!](https://tio.run/##XVDLasMwELznK4QQWGrkxDbpIygml7YQKD20vcWpcFw5FlVkIStgSPPt7jr01IOWfc3MalzjhtXaNQ4Rj3KE5xjNkPPqIL1ypqwUjeazm7WUTWmCrNqj00b5ghZMFG/zLuIogldDUx7UuGCDsqGjUj5vXp6kZBylDCiBWEy01bJTgWJXeTXbl9V38BCk0UcdMEd4kS0Xy7v7bHmLmZjUradE54kgJq@BvaPvH4@bVybYGemaErPtgjfKQsbidJfnuLCYwXJ32sME2jzhccpGvOqdab8UxTHmsC4AX7UnG0bsKgPQFgggJjsxQeiqbP9qYlf5dQ7ZdMpAGtGrQ8cyVA0lnoPYaJcqA436iBPLGEPn8UTNVNW0410CwVdSgcYaESsuIHP5ZytlYqBFWqQ/nz2b9mQYkvghS5Jf "PHP – Try It Online") |
| .NET | [Try it online!](https://tio.run/##RY9Ra4MwFIX/SpALJnUpcX1rCBT23F9gLYi7nYH0RmKKUpvf7nRj7PE7HD7O6f2IYejQuQWCqQJ@4VQfj4QjP@XLlV/KS/m6TmI3wZKf3rIPf@@tw89MaHgapW8@YNN2HByzxMBS/4hihsaAk0PvbMxkpu2NQ7Nv/YOidJG9b4XCQFOpOq0CDmQqS7H@STSQdPjH5cZFIebNEfbnJrYdDjyf8h2Q@I2fYh6DjSg7P8S0zir1PzNJfn3jLCEDSiktSh4OSqlv "PowerShell – Try It Online") | [Try it online!](https://tio.run/##RY/RaoQwFER/JcgFk9oscZ/KhsBCn/sFroVg79ZA9kZiFmVtvt1qS@njGYbDzBAmjGOP3q8QTRPxE@f2dCKc@Llc@aW@1F/vs6hmWMvzc/EaboPz@FEIDQ@j9DVEtF3PwTNHDBwN9yQWsAa8HAfvUiEL7a4c7KELd0rSJ3bcC5UB26g2bwIOZBpHqf1JNJD0@Mf1zlUllt0RD282dT2OvJzLJyDxGz/EMkWXUPZhTHmbVet/ZpLCdsY7QgaUc16VfDkq9Q0 "PowerShell – Try It Online") |
Subtracts increasing powers of 2 from \$tail\$, starting with \$1\$. As such, the sum of the subtracted powers will be \$2^a-1\$ where \$a\$ is the number of iterations so far. Once the loop has matched as many iterations as it can, asserts that the remaining \$tail=1\$.
Unlike the ECMAScript regexes, this needs to do no backtracking, thus is orders of magnitude faster in standard regex engines.
As with the 17 byte ECMAScript regex, it is quite suitable for solving this challenge, as the only change necessary is upping the minimum iteration count of the loop from `0` to `1` by changing the `*` quantifier to a `+`, at a cost of 0 bytes. But an added bonus here is that the first iteration of the loop can only match at the beginning of the string, so we can remove the first `^` anchor to save 1 byte. This does make the regex much slower in most regex engines though.
# Regex (Java / Perl / PCRE / Python[`regex`](https://github.com/mrabarnett/mrab-regex) / Ruby / .NET), 22 bytes
`^((?=(\3\3|^x))(\2))*x$` - **23 bytes** - Powers of 2
`((?=(\3\3|^x))(\2))+x$` - **22 bytes** - Completely even
| Regex engine | Powers of 2 | Completely even |
| --- | --- | --- |
| Python `import regex` | [Try it online!](https://tio.run/##NY5BasMwEEX3PsUguphJbSPFi4Ad0YPYDoRWSVSUsRmp1IHe3Y1cuhvm8R5/fqTbxM3q7/MkCeIjluKubik/48QdiBWl1HpCfLM4NEPzc1qIcNgT7ZaX9cl601Zm7MBbXVwmgQCec6aO6cNzW0CwoY5z8AlVpagAf4HgGAMd9y2E3ow29HosIMucZTnz1aHnhBlQ@XeZkV4NPXs5sE2sozvL@w2lBLWoHW8wU9/CLNmi7WFN9z9o@kr1t/jkMCZBJlp1ZQ5a618 "Python 3 – Try It Online") | [Try it online!](https://tio.run/##NY7RSsQwEEXf@xVD8GHGbUuy9ak1@CFthUWzu5E4KZOIXfDf66bi2zCHc7jLLV8jd5v/XKJkSLdUi7u4tf5IkQcQK0qpDfHF4tRN3c/rSoTTkeiwPmx3NJq@MfMA3urqHAUCeC6VNuV3z30FwYY2LcFnVI2iCvwZgmMM9HzsIYxmtmHUcwVF5iLLiS8OPWcsgOq/y8x0MHTvlcC@sE3uJG9XlBrUqh55h4X6HhYpFu0Pa4b/QfErt9/is8OUBZlo082T0foX "Python 3 – Try It Online") |
| Ruby | [Try it online!](https://tio.run/##PY5Bi8IwEIXv/oqxCCZCh7QePMQggl49yN5aDYqxBsJY0ohdWPzr3UR2PczAvHnfm/GP8/fgQcHeNKZvkcwTNuuvNXpzukiwSkh43qwz4FRjQjcCsFdwVV4clMpqymRcuEog5uVBgqFLdEQFu9bZwKb5lP8h6Aw14cb4soxMFfmIfZDr3QOBJUgihru2rBAcMRk/Y/S9s1jWZzPioF7gZRLsOP3ZPkL3zkt/F3H2lgLQ/4nUU2m93W20Ho6MrRSr5/X859hzzuqS81k/GQaRFwshxC8 "Ruby – Try It Online") | [Try it online!](https://tio.run/##PY5Bi8IwEIXv/oqxCCa7dEjrRciGRdCrB9lb6wbFWANhLGnECuJfr4nsepiBefO@N@Mv@9vgQcHGNKZvkcwVloufBXqzO0iwSki4nqwz4FRjQjcCsEdwVV5slcpqymRcuEog5uVWgqFDdEQFu9bZwKb5lP8h6Aw14cT4VxmZKvIReyPHswcCS5BEDGdtWSE4YjK@x@h7ZbGszz6Ig3qAl0mw4/RnewndKy/9XcTZWwpA/ydST6X1ar3UemDsW7F6Vs/uvz3nrC45/@wnwyDyeSnEEw "Ruby – Try It Online") |
This is a direct port of the 13 byte / 12 byte regex. Ruby, and Python's `regex` module, do not support nested backreferences, so they must be emulated via forward-declared backreferences. (Python's `re` module doesn't even support the latter.) The 13 byte version of this is faster than the 17 byte regexes, but golf-wise, they win.
Although this results in a fast regex that's compatible with six different engines, the [recursive solutions](https://codegolf.stackexchange.com/a/259835/17216) provide the best golf for Python's `regex` module and Ruby.
### \$\large\textit{Full programs}\$
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 18 bytes
```
.+
$*
(\1\1|^.)+.$
```
[Try it online!](https://tio.run/##Dcg5CoAwAEXB/p0jQjQQ/FlcTuAlgmhhYWMhlt49OuXcx3Nee23sslXvMB22qOhdfeu8qbVHBCKJzMDIxIz@FAooooQyGj4 "Retina 0.8.2 – Try It Online")
Takes its input in decimal. Uses the Java/Perl/PCRE/.NET pure regex.
# [Perl 5](https://www.perl.org/), 24 bytes
```
say 1x<>~~/(\1\1|^.)+.$/
```
[Try it online!](https://tio.run/##RU7NasMwGHuVb8YQm/w0GesOjROyS0YPu@ywS9sNE5zF4NjGDrSjS497gD3iHmRpaBm7CAkJSVY4tZy0gT13Wup3D4E4WOFkL/TA1Wrle@6Gng9NF@RgrNCkjlC5RjSHfSeVIKykx6Yzvc0rVXir5ECCOIjw25yQLfENV9xVit3SY6U22a6YMd2N0BpHsLyqHEtWXNyZhSE9ev4BNWA5jtAo4wWp6f86u6xXD8@PLwVao78jN8K0hFK4viFYFawu56B1Ug@AVYTg5@sbUD7N7XhzYOXptCDbbJt9viY0TPBiGqc0vr/7NXaQRvspflomaZaeAQ "Perl 5 – Try It Online")
[Answer]
# Regex (PCRE1), 11 bytes
`^(x(?1)?x|x)$` - **13 bytes** - Powers of 2
`^(x(?1)?x)$` - **11 bytes** - Completely even
| Regex engine | Powers of 2 | Completely even |
| --- | --- | --- |
| PCRE1 | [Try it online!](https://tio.run/##hVPbbtpAEH3nKya0CetgIrtIVWXjRGlK1QeaVIhIrQi1XLOGVc3aWq8LSeDXS2d37cS5SLX8sJczZ86cmY3zvLeI4/0bxuO0nFMY5LGgJ8vTVryMBIT5dAYBjNsf1@vfv/rlj9vb75Pl@/WS7H@SDTlzrbPNdmO93VvPAW0bjvMgzLuu33okL@ScZYq9eSQYXzw9Yxme0mj1EnfaYlxCjksZUiEyQeKMFxK02uMVLYpoQa17zON5MQJgMIDqVC31OeXz1AdBZSk4uP5OU64ixokF9y3AL59itpRykls9dxY4PpSI6b8LJWRqpwIWuNBgzWnU4UVeSh@Uh3AsqA9NdSgnl8JEC1qUqTRrVUeSFFTakJUS0y7k0txkf2gsMzHtz0wqZA00eRhnq5yllOQ2fLsYD8NPV5Pz0Qi2Znc9@fzBhiOT0CzqDI5lqFgC5EBQq/Yh0Z4mBKtBtA1tRaSlCYhQiQ6Hw7kHh8UNx@42OE2eijjBAKLE3ymntDkLKlPGKTFdYdw2Plk@Ytzacy0Kw7iDNUYyY0SDTuIQvSWWZQN3bcizAq/NTcL4nHR6nSqx@rirDELMQdDsi@dxdXj2Ci90Nb4LKMTD5I9cpmkqHadrs5tyt@vOfJyoFRZOChs6m44ShqUUeDkLGvEPRrCAq5kZBNz1odtlzYpNV9Us1J2lGxoTQW24vB6NbMAcDLum/2ocbOg3Sq6bWbGcBuDAdluTog96Iobj8dU4vLz6ej65@PJcQE1xZwE6oyolnRveMf3xX0BNG3FU1Yti/qtUVfoBijk6@o@YJ3xtD4Zq6NpPeXevO9aw2yB2LT2ynhlFQSkqsR4ee/XqWru903Ndx/kbJ2m0KPa9VFn/Dw "C++ (gcc) – Try It Online") | [Try it online!](https://tio.run/##hVNtb5swEP6eX3HN1sY0pIJFmiYIrbqu0z5k7RSl0qY0Q4wYYo0YZMySvuSvLzvb0NIXaYgP9r0899xz57goBmkc794wHmfVgsKoiAU9Wh534mUkICxmcwhg0v24Xv/@Nax@3Nx8ny7fr5dk95NsyIlrnWystzvrubtrw2ERhEXf9TuP0KVcsFxht02C8fSpjeVopdHqZdxxh3EJBR5lSIXIBYlzXkrQXA9XtCyjlFp3WMfzYgyA0QhqqzpqO@WLzAdBZSU4uP5WQ64ixokFdx3Ar5hhtYxyUlgDdx44PlQYM3wXSsjVTSWkeNDBGtOwQ0dRSR@UgnAoqA9tdkinkMJkC1pWmTRn1UeSlFTakFcSy6ZyaTz5HxrLXMyGc1MKUQMNHsb5qmAZJYUN384m5@Gny@npeAz35nY1/fzBhgNT0ByaCo5loFgCZE9Qq9Eh0ZomBLvBaBu6CkhTExAhE50O@wsP9strjtNtYZo6NXCCCUSRv1VKaXFSKjPGKTFTYdw2Olk@xriN5poUpnEHe4xkzogOOopD1JZYlg3ctaHIS3QbT8L4gvQGvbqw@rirBMKYvaA9F8/jynjyCi70dXwfkIiHxR@xzNBUOU7X5jbjbt@d@7hRK2yclDb0Nj1FDFsp0TkPWvkPQrCAq50ZBdz1od9n7Y7NVNUuNJOlGxoTQW24uBqPbcAaDKem/3odbBi2Wm6GWaMcB@DA/X0DijrojTifTC4n4cXl19Pp2ZfnBBqIWwtQGdUp6V3znpmP/yLUjBFXVb0o5r8KVZcfIZmDg/@QeYLX9eBcLV33Ke72dcVacpuIbUevrGdWUVCKTKyHx16/us525wxc13H@xkkWpeVukCnp/wE "C++ (gcc) – Try It Online") |
I'm not sure when this recursive regex was originally discovered. It was likely an accidental discovery, when someone tried to match palindromes and found that due to PCRE1's atomic subroutine calls, words consisting of only one distinct letter would only match when their length was a power of 2.
Explaining why this works is complicated, but I do intend to do it sometime.
This regex is absolutely phenomenal at being ported to this challenge; it loses 2 bytes in doing so.
# Regex (Perl / PCRE), 15 bytes
`^x(x(?1)?+x|x|)$` - **16 bytes** - Powers of 2
`^x(x(?1)?+x|x)$` - **15 bytes** - Completely even
This is a port of the PCRE1 regex to engines that may have non-atomic subroutine calls.
| Regex engine | Powers of 2 | Completely even |
| --- | --- | --- |
| Perl | [Try it online!](https://tio.run/##RY5fa8IwFMW/ykWCzaUtTYS9LI2t4F598m1zwQ0LgUxrUiEjxq9eYyfs5XLPuX/Orz9Y8zL@/AKxAoI5fe8NkEokKev1artaRuhOlhInmaiXAgPoLikMvdXHAWYfx5mI0BrpeqMHmpVZ4S5fbkgnqih5wfFwfiw1/y5LPr4SheLxy6XEvW1NvcDQmne@k6mynXjm6qckupbTOHV5jkF3QGnmM/CQlhBB3qAitsJA3Hw@wU1sCZyLP1aiRYxRqbfNWqnx01NPG45N7q/@imQcWbngjN0B "Perl 5 – Try It Online") | [Try it online!](https://tio.run/##RY5fa8IwFMW/ykWCzaUtTYS9mMZWcK8@7W1zwQ0Lgag16SAji1@9i1Xw5XLPuX/Orz9Y8zIef4FYAcGcv/cGSCWSlPVm/bZeRejOlhInmahXAgPoLikMvdWnAWYfp5mI0BrpeqMHmpVZ4X6@3JBOVFHyguPhcltqni5LPi6JQnH75VLi3ramXmBozTvfyVTZTjxy9UMSXctpnLo8x6A7oDTzGXhIS4ggr1ARW2Egbj6f4Ca2BM7FnZVoEWNU6nW7UWr89NTThmOT@z@PZBxZueCM/QM "Perl 5 – Try It Online") |
| PCRE1 | [Try it online!](https://tio.run/##hVNdb9owFH3nV9yytThNqMiQpikhrbqOaQ@snRCVNlEWseAEa8GxHDNoC3997NombfohLcqDP@4959xzrxMh2lmS7N4wnuTLGYWeSCQ9mZ82kvlUQizGE4hg2Py4Wv3@1V3@uL39Ppq/X83J7uearMmZ75y5681647zdOc9jmh4ciygWrh82HvFLNWOFJqgfScazp2eswFM6XbyMO20wrkDgUsVUykKSpOClAiP4eEHLcppR5x55giDBAOj1YH@ql@ac8lkegqRqKTn44dZALqaMEwfuG4CfGCNbTjkRTtufRJ0QlhjTfRcrKPROJ2S4MMEG06rDC7FUIWgb4VjSEOrqUI5Q0mZLWi5zZde6jjQtqfKgWCqkzdTc3hR/aKIKOe5OLBWiRgY8ToqFYDklwoNvF8N@/OlqdD4YwMburkefP3hwZAntomLoOBaKpUAOJHUqH1LjaUqwGoz2oKmBjDQJU1Ri0uFwFsBhecOxuzVMy7MHTjGBaPF32iljTkZVzjgltiuMe9YnJ8QYv/LciMI03sEap6pgxASdJDF6SxzHA@57IIoSr@1NyviMtNqtPbH@uK8NwpiDqN6XIOD68OwVXHBNvAsoJEDyRyzbNE3H6cruxtx3/UmIE7XAwknpQWvd0sKwlBIvJ1Et/8EIFnE9M72I@yG4LqtXbLuqZ6HqLF3ThEjqweX1YOABcjDsmvn34@BBt1Zy1cw9ymkEHdhsKlD0wUxEfzi8GsaXV1/PRxdfnguoIO4cQGd0paR1w1u2P@GLUNtGHFX9olj4KtSevodijo7@I@YJXjOAvh665lPc7euO1ey2EduGGdnAjqKkFJU4D499/@oa212n7fudzt8kzadZuWvn2vp/ "C++ (gcc) – Try It Online") | [Try it online!](https://tio.run/##hVNdb9owFH3nV9yytThNqMiQpikhrbqOaQ@snRCVNlEWseAEa8GxHDNoC3997NombfohLcqDP84999xzrxMh2lmS7N4wnuTLGYWeSCQ9mZ82kvlUQizGE4hg2Py4Wv3@1V3@uL39Ppq/X83J7uearMmZ75y5683aebtznkOaHhyLKBauHzYe6Us1Y4Xmrx9JxrOnZ6zAUzpdvMSdNhhXIHCpYiplIUlS8FKB0Xu8oGU5zahzj3mCIEEA9HqwP9VLc075LA9BUrWUHPxwaygXU8aJA/cNwE@MMVtOORFO259EnRCWiOm@ixUUeqcDMlwYsOG06vBCLFUI2kU4ljSEujqUI5S00ZKWy1zZta4jTUuqPCiWCtNmam5vij80UYUcdyc2FbJGhjxOioVgOSXCg28Xw3786Wp0PhjAxu6uR58/eHBkE9pFlaHjWCqWAjmQ1Kl8SI2nKcFqEO1BUxMZaRKmqMSEw@EsgMPyhmN3a5w2z544xQCixd9pp4w5GVU545TYrjDuWZ@cEDF@5bkRhWG8gzVOVcGIAZ0kMXpLHMcD7nsgihKv7U3K@Iy02q19Yv1xXxuEmIOo3pcg4Prw7BVecA3eBRQSYPJHLts0nY7Tld2Nue/6kxAnaoGFk9KD1rqlhWEpJV5Oolr8gxEs4npmehH3Q3BdVq/YdlXPQtVZuqYJkdSDy@vBwAPMwbBr5t@PgwfdWslVM/cspxF0YLOpSNEHMxH94fBqGF9efT0fXXx5LqCiuHMAndGVktYNb9n@hC@gto04qvpFsfBVqn36Hoo5OvqPmCd8zQD6euiaT3m3rztWs9sitg0zsoEdRUkpKnEeHvv@1TW2u07b9zudv0maT7Ny18619f8A "C++ (gcc) – Try It Online") |
| PCRE2 | [Try it online!](https://tio.run/##XVBda8IwFH33V4QQaO5stS1uQ2LpyzYQxh62vVkXapfasJqGNEJB/e3uVva0h1zu1znn5tjGXle5bSxhjmSEzimZEevUXjpl27JSPJjP7nIpm7L1suoOVrfKFbwAUbzP@yAkAb4am3KvxgXjlfE9l/Jl/fosJYQkAaREYjHRRsteeU5t5dRsV1Y/3mGQrT5oT0NCF@lysXx4TJf3FMSk7hxnOosFa7Ma2Xv@8fm0fgMBJ6JrztpN712rDGYQJdsso4WhgMv9cYcTbIdxGCUw4tVg2@5bcRrRENcF4qvuaPyIXaUI2iABxngrJoTclM1fzcwqu80xm04BpQm/OXQofdVw5kIUG@1SpefBEITMAAA5jSdqUFXTjXcJgl9JBBlrwoy4oMzln60cxPVr4APPE8inw3k4A7te4yhN4vgX "PHP – Try It Online") | [Try it online!](https://tio.run/##XVBdS8MwFH3frwgh0FzXbm2ZyshKX1QYiA/q2zpDV9M12KUhzaAw/e31dvjkQy7365xzc2xjx01uG0uYIxmhS0oWxDp1lE7ZtqwUD5aLm1zKpmy9rLqT1a1yBS9AFK/LPghJgK/GpjyqacF4ZXzPpXzaPj9KCSFJACmRWMy00bJXnlNbObU4lNWXdxhkq0/a05DQVbpere/u0/UtBTGrO8eZzmLB2qxG9p6/vT9sX0DAheias3bXe9cqgxlEyT7LaGEo4HJ/PuAE22EcRglMeDXYtvtUnEY0xHWB@Ko7Gz9hNymCdkiAMd6LGSFXZfNXM7PJrnPM5nNAacKvDp1KXzWcuRDFJrtU6XkwBCEzAEAu04kaVNV0012C4FcSQaaaMCN@UObnn60cxPgx8IHnCeTz4XsANo5xlCZx/As "PHP – Try It Online") |
# Regex (PCRE / Ruby), 16 bytes
`^x(x\g<1>?+x|x|)$` - **17 bytes** - Powers of 2
`^x(x\g<1>?+x|x)$` - **16 bytes** - Completely even
This is a port of the PCRE1 recursive regex to Ruby's subroutine call syntax.
| Regex engine | Powers of 2 | Completely even |
| --- | --- | --- |
| PCRE1 | [Try it online!](https://tio.run/##hVNdb9owFH3nV9yytTglVGRI05QQqq7rtAfWTohKmyiLWHCCteBYjjNoC3997NombfohLcqDP@4959xzr2MhOmkc794wHmflnEJfxJKeLAaNeDGTEInJFEIYNT@uVr9/9coft7ffx4v3qwXZ/VyT9U3a9wan7fVmvXHe7pznQU0XjkUYibYXNB4JCjVnuWaoH0nG06dnLMdTOlu@jBs0GFcgcKkiKmUuSZzzQoFRfLykRTFLqXOPPL4fYwD0@7A/1UtzTvk8C0BSVUoOXrA1kMsZ48SB@wbgJybIllFOhNPxpmE3gBJjeu8iBbne6YQUFybYYFp1eCFKFYD2EY4lDaCuDuUIJW22pEWZKbvWdSRJQZULeamQNlULe5P/obHK5aQ3tVSIGhrwKM6XgmWUCBe@nY8uok9X47PhEDZ2dz3@/MGFI0toFxVD17FQLAFyIKlT@ZAYTxOC1WC0C00NZKRJmKESkw6Hcx8OixuO3a1hWp49cIIJRIu/004Zc1KqMsYpsV1h3LU@OQHGeJXnRhSm8S7WOFM5IyboJI7QW@I4LnDPBZEXeG1vEsbnpNVp7Yn1xz1tEMYchPW@@D7Xh6ev4ELbxLcBhfhI/ohlm6bpOF3Z3YR7bW8a4EQtsXBSuNBat7QwLKXAy2lYy38wgoVcz0w/5F4A7TarV2y7qmeh6ixd05hI6sLl9XDoAnIw7Jr59@PgQq9WctXMPcoghC5sNhUo@mAm4mI0uhpFl1dfz8bnX54LqCDuHEBndKWkdcNbtj/Bi1DbRhxV/aJY8CrUnr6PYo6O/iPmCV7Thws9dM2nuNvXHavZbSO2DTOyvh1FSSkqcR4e@/7VNba7bsfzut2/cZLN0mLXybT1/wA "C++ (gcc) – Try It Online") | [Try it online!](https://tio.run/##hVNdb9owFH3nV9yytTglVGRI05QQqq7rtAfWTohKmyiLWHCCteBYjjNoC3997NombfohLcqDP@4959xzr2MhOmkc794wHmflnEJfxJKeLAaNeDGTEInJFEIYNT@uVr9/9coft7ffx4v3qwXZ/VyT9U3a9wan7fVm7bzdOc9jmi4cizASbS9oPOIXas5yTVA/koynT89Yjqd0tnwZN2gwrkDgUkVUylySOOeFAiP4eEmLYpZS5x55fD/GAOj3YX@ql@ac8nkWgKSqlBy8YGsglzPGiQP3DcBPTJAto5wIp@NNw24AJcb03kUKcr3TCSkuTLDBtOrwQpQqAG0jHEsaQF0dyhFK2mxJizJTdq3rSJKCKhfyUiFtqhb2Jv9DY5XLSW9qqRA1NOBRnC8FyygRLnw7H11En67GZ8MhbOzuevz5gwtHltAuKoauY6FYAuRAUqfyITGeJgSrwWgXmhrISJMwQyUmHQ7nPhwWNxy7W8O0PHvgBBOIFn@nnTLmpFRljFNiu8K4a31yAozxKs@NKEzjXaxxpnJGTNBJHKG3xHFc4J4LIi/w2t4kjM9Jq9PaE@uPe9ogjDkI633xfa4PT1/BhbaJbwMK8ZH8Ecs2TdNxurK7Cffa3jTAiVpi4aRwobVuaWFYSoGX07CW/2AEC7memX7IvQDabVav2HZVz0LVWbqmMZHUhcvr4dAF5GDYNfPvx8GFXq3kqpl7lEEIXdhsKlD0wUzExWh0NYour76ejc@/PBdQQdw5gM7oSknrhrdsf4IXobaNOKr6RbHgVag9fR/FHB39R8wTvKYPF3romk9xt687VrPbRmwbZmR9O4qSUlTiPDz2/atrbHfdjud1u3/jJJulxa6Taev/AQ "C++ (gcc) – Try It Online") |
| PCRE2 | [Try it online!](https://tio.run/##XVBdS8MwFH3frwgh0MSlW1umMrK6FxUG4oP6ts7Q1XQNZmlIMyi4/fZ6O3zyIZf7dc65Oa5xw2rtGoeIRznCc4xmyHl1kF45U1aKRvPZzVrKpjRBVu3RaaN8QQsmird5F3EUwauhKQ9qXLBB2dBRKZ83L09SMo5SBpRALCbaatmpQLGrvJrty@o7eAjS6KMOmCO8yJaL5d19trzFTEzq1lOi80QQk9fA3tH3j8fNKxPsB@maErPtgjfKQsbidJfnuLCYwXJ32sME2jzhccpGvOqdab8UxTHmsC4AX7UnG0bsKgPQFgggJjsxQeiqbP9qYlf5dQ7ZdMpAGtGrQ8cyVA0lnoPYaJcqA436iBPLGEM/44maqappx7sEgq@kAo01IlZcQObyz1bKxPDZ0744rNKH9bQ/92dGhiGJszRJfgE "PHP – Try It Online") | [Try it online!](https://tio.run/##XVBdS8MwFH3frwgh0MSlW1umMrK6FxUG4oP6ts7Q1XQNZmlIMyjM/fZ6O3zyIZf7dc65Oa5xw2rtGoeIRznCc4xmyHl1kF45U1aKRvPZzVrKpjRBVu3RaaN8QQsmird5F3EUwauhKQ9qXLBB2dBRKZ83L09SMo5SBpRALCbaatmpQLGrvJrty@o7eAjS6KMOmCO8yJaL5d19trzFTEzq1lOi80QQk9fA3tH3j8fNKxPsjHRNidl2wRtlIWNxustzXFjMYLk77WECbZ7wOGUjXvXOtF@K4hhzWBeAr9qTDSN2lQFoCwQQk52YIHRVtn81sav8OodsOmUgjejVoWMZqoYSz0FstEuVgUZ9xIlljKHzeKJmqmra8S6B4CupQGONiBUXkLn8s5UyMXz2tC8Oq/RhPe1/ekaGIYmzNEl@AQ "PHP – Try It Online") |
| **Ruby** | **[Try it online!](https://tio.run/##PY5BawIxEIXv/RXTpWBi2SHZa4wi2GsPxdtqg2JcA2FcshFTEP/6NpHWwwzMm/e9mXDZ/4wBNHzZzqYeyV5htVwvMdjdQYHTQsH15LwFrzsbhxcAdwTf1nKrdbWhSuWFbwVi3WwVWDpkR1Zw6L2LbFJP@B@C3lIXT4zPmsy0mc/YEzmeAxA4giJiPBvHpOCIxfgcs@@RxapUTYmDvkNQRXCv5c/@EodHXvlb5jk4ikD/J0ovZczH58qY8TuxtOlmcr54T7d042/jKGrZCPEL "Ruby – Try It Online")** | **[Try it online!](https://tio.run/##PY5BawIxEIXv/opxKZi07JDsNaZFsNceirfVBsW4BsK4ZCOmUPzrayLWwwzMm/e9mXDe/Y4BNHzbzqYeyV5guVgtMNjtXoHTQsHl6LwFrzsbhwmAO4Bva7nRulpTpfLCtwKxbjYKLO2zIys49N5FNqtn/IGgt9TFI@PzJjNt5jP2RA6nAASOoIgYT8YxKThiMT7H7LtnsSpVr8RBXyGoIrhp@bM/x@GeV/6WeQ6OItD/idJLGfP5tTRm/Eksrbu5fP94S3@Jv4yjqGUjxA0 "Ruby – Try It Online")** |
# Regex (Perl / PCRE2 / Boost / Python[`regex`](https://github.com/mrabarnett/mrab-regex)), 15 bytes
`^x(x((?1))\2|)$` - Powers of 2
`^x(x((?1)?)\2)$` - Completely even
| Regex engine | Powers of 2 | Completely even |
| --- | --- | --- |
| Perl | [Try it online!](https://tio.run/##RY5fa8IwFMW/ykWCzcWWJoW9LI1WcK8@@TZdcMNCINMu6aAjxq/eXTthL5d7zv1zft3Ju6fx8weYVxDd5ePogJWKpK436916maC9eM6CFqpeKoxgW1IYO2/PPcz255lK0DgdOmd7nhVZHr7fQ08nJi9kLvH0dV9a/buCfHxmBtX9V6DEo29cXWFs3Ks8aKrioB659iGZrfU0pm6xwGhb4DwbMhiAlhBB36BkvsTIwnw@wU1sBC7VHyuzKqVkzMt2Y8z4NvCB85VE3FdXZOMoikoK8Qs "Perl 5 – Try It Online") | [Try it online!](https://tio.run/##RY7NasMwEIRfZQlLrCU2lgy9RFbsQHrtqbcmFWmJQaAkjuSCi1Bf3VXcQC/LzuzPfP3J2afp/A3oJAR7/TxawFImqerd9nW7idBdHUOvuKw3kgKYLikKvTOXARb7y0JGaK3yvTUDy4os918ffkgnOi9ELuh0uy81/y5PPq1Rk7z/8inx6FpbVxRa@yYOKlV@kI9c85BoajWPU7daUTAdMJaNGYyQlohA/UCJrqSAfrmc4Wa2BC7kHysaGWPU@vllp/X0PrKRsUZQQ/uKcJp4UQnOfwE "Perl 5 – Try It Online") |
| PCRE2 | [Try it online!](https://tio.run/##XVBdS8MwFH3frwgh0FyXbm2ZysjKXlQYiA/q2zpDV9M12KUhzWAw/e31dvjkQy7365xzc1zjhtXaNY4wT3JC55TMiPP6oLx2bVlpHs1nN2ulmrINquqOzrTaF7wAWbzO@0iQCF@NTXXQ44IN2oaeK/W0eX5UCgRJASmRWE6MNarXgVNXeT3bl9VX8BhUa44mUEHoIlsulnf32fKWgpzUnefM5IlkbV4je8/f3h82LyDhQkzNWbvtg2@1xQzidJfntLAUcLk/7XGCbZGIOIURr8@u7T41pzEVuC4RX3UnG0bsKkPQFgkwJjs5IeSqbP9qZlf5dY7ZdAooTfjVoWMZqoYzL1BstEuXgUfnSDALAOQynmhAV0033iUJfiWVZKwJs/IHZX7@2cpBDh9nfuZ8nQIU2TewYUjiLE2SXw "PHP – Try It Online") | [Try it online!](https://tio.run/##XVDNa4MwFL/3rwhBMG@NrUq3UVLxsg0KY4dtt9oF62KVpTHEFITSv909y0475PG@fh95trHjJreNJYEjGaFLShbEOnWUTlldVoqFy8VdLmVTai@r7mRbrVzBChDF@7IPOQnx1diURzUtGK@M75mUL9vXZymBkwSQEonFrDWt7JVn1FZOLQ5l9eMdBqnbU@spJ3SVrlfrh8d0fU9BzOrOsaDNYhHorEb2nn18Pm3fQMCFtDUL9K73TiuDGUTJPstoYSjgcn8@4ATbPOZRAhNeDVZ334rRiHJcF4ivurPxE3aTImiHBBjjvZgRclM2f3VgNtltjtl8DihN2O1Cp9JXDQscR7HpXKr0LBxCHhgAIJfJYguqarrJlyD4lUSQqSaBEVeUuf47KwMxfg1sYCxPIIcCfY1jHKVJHP8C "PHP – Try It Online") |
| **Boost** | **[Try it online!](https://tio.run/##dVNtb5swEP6eX3HLpsYu0EIq7QOEVpq0PzDtw6Y0RdRxwFpiLGOUl61/vdnZNIxmxB/A9/bcPXdnplRQMHb8KCRbN0sOs@eqqs2t5gXf3ZRK3Y/OTXzHuDKikrdLkRcSVYJlQq4qvcmtuo1iZa4hU/MFpPBt/GW7/fV81/zc7398Lz9vS3J82pEdIQ8RpY/TP/TTkZ67jH24VmmmvCjplSAwneb55n4kpIFNLiSh8HsEeNQcTWsuiaJBtEjDBBr0uZtmBior2YDCXmqzjGP0FbJApWpM4uJZJWsDjmMcO/6gOYIlJ12N/FgJ2zJ/i0DKQCzsIQ19OPAOvOBmLSQnTmBC@m0empxqtccGyhDbk5tKEOdwwzKsi1Dqg4x8UFWN5tayEnJJJsGEJh2AjNBqfT6kfU5xLK3yYQAXPOfvQUQhxuT/sNy4rm06ybetNJeRFy0S2PBNzQ2pfZjsJrYw7EiNRtviLr5rhUil7fUslVECnif6jO0xen@mcb1YAel3Pqt5rllJSI8XvbJZA7Hw3Qh8nA6lA1gnvAMFpG6pkMmjxMbhmKJk0L2dU9UYmM1A/O/zMrosMbcU5N32dE8ErrjW9ALh4QLPirGfcQxfta70OBnG4RRWFsnB@BbAZk3sRnZ4qOnjje3/rdrhZ0wcxgXi7a39am4aLQGX4eUYBtE0DF/Zap0X9TFYuwyZG@lf "C++ (gcc) – Try It Online")** | **[Try it online!](https://tio.run/##dVNtb5swEP6eX3HLpsYu0EIq7QOEVpq0PzDtw6Y0RdRxwFpiLGOUl61/vdnZNIxmxB/A9/bcPXdnplRQMHb8KCRbN0sOs@eqqs2t5gXf3ZRK3Y/OTXzHuDKikrdLkRcSVYJlQq4qvcmtuo1iZa4hU/MFpPBt/GW7/fV81/zc7398Lz9vS3J82pEdIQ8R/UMfp/TTkZ67jH24VmmmvCjplSAwneb55n4kpIFNLiSh8HsEeNQcTWsuiaJBtEjDBBr0uZtmBior2YDCXmqzjGP0FbJApWpM4uJZJWsDjmMcO/6gOYIlJ12N/FgJ2zJ/i0DKQCzsIQ19OPAOvOBmLSQnTmBC@m0empxqtccGyhDbk5tKEOdwwzKsi1Dqg4x8UFWN5tayEnJJJsGEJh2AjNBqfT6kfU5xLK3yYQAXPOfvQUQhxuT/sNy4rm06ybetNJeRFy0S2PBNzQ2pfZjsJrYw7EiNRtviLr5rhUil7fUslVECnif6jO0xen@mcb1YAel3Pqt5rllJSI8XvbJZA7Hw3Qh8nA6lA1gnvAMFpG6pkMmjxMbhmKJk0L2dU9UYmM1A/O/zMrosMbcU5N32dE8ErrjW9ALh4QLPirGfcQxfta70OBnG4RRWFsnB@BbAZk3sRnZ4qOnjje3/rdrhZ0wcxgXi7a39am4aLQGX4eUYBtE0DF/Zap0X9TFYuwyZG@lf "C++ (gcc) – Try It Online")** |
| **Python `import regex`** | **[Try it online!](https://tio.run/##NY7BasMwEETv/opF5LDb2kZyb3ZFPsR1ICRKoqKuzEqlDvTfncilt2Eeb5j5nm@R31b/NUfJkO6pFnd1S/2ZIg8gVpRS62HBBXFviD66X9qtz240fWOmAbzV1SUKBPBc9Dbls@e@gmBDm@bgM6pGUQX@AsExBnrvegijmWwY9VRBkbnIcuSrQ88ZC6D6L5mJXg0998rAdq1N7iinG0oNalEvvMFCfQ@zFIu2wprh/1D8zu2P@OwwZUEmWnVjOq0f "Python 3 – Try It Online")** | **[Try it online!](https://tio.run/##NY7BasMwEETv/opF5LDb2kZyb3ZFPsR1ICRKoqKuzEqhztc7kUtvwzzeMPMj3yJ/rP5njpIhPVIt7uqW@jtFHkCsKKXWw4IL4t7Qnr462q2vbjR9Y6YBvNXVJQoE8Fz0NuWz576CYEOb5uAzqkZRBf4CwTEG@ux6CKOZbBj1VEGRuchy5KtDzxkLoPovmYneDb32ysB2rU3uKKcbSg1qUW@8wUJ9D7MUi7bCmuH/ULzn9ld8dpiyIBOtujGd1k8 "Python 3 – Try It Online")** |
I discovered this recursive regex on 2022-07-18 while working on
[Sum of Powers of 2](https://codegolf.stackexchange.com/questions/179174/sum-of-powers-of-2/250059#250059). It relies on subroutine calls being atomic.
```
^ # tail = N = input number
x # tail -= 1
( # Define subroutine (?1)
x # match += 1; tail -= 1
((?1)) # \2 = match made by recursive call; match += \2; tail -= \2
\2 # match += \2; tail -= \2
| # or
# Match nothing, causing a cascading pop to the top level of
# recursion, ending the match.
)
$ # Assert that we've reached the end of the string.
```
This is similar to `^(\1\1|^x)*x$`, in that the `(?1)` subroutine call will always return \$2^a-1\$ where \$a\$ is the depth of recursion it reached. This is why an extra \$1\$ is subtracted at the beginning (it could just as easily be done at the end, but that would be slightly slower due to backtracking).
It is very easily ported to solving this challenge; the first iteration at which it has a choice of whether to match nothing just has to be pushed down one level, at a cost of 0 bytes.
# Regex (PCRE2 / Ruby), 16 bytes
`^x(x(\g<1>)\2|)$` - Powers of 2
`^x(x(\g<1>?)\2)$` - Completely even
| Regex engine | Powers of 2 | Completely even |
| --- | --- | --- |
| PCRE2 | [Try it online!](https://tio.run/##XVBdS8MwFH3frwgh0FyXbm2ZykjrXlQYiA/q2zpDV9O12KUhzWAw99vr7fDJh1zu1znn5tjaDunK1pYwRzJC55TMiHV6r5y2bVFqHsxnNyul6qL1quwOtmm1y3kOMn@b94EgAb4Km2qvxwXjtfE9V@p5/fKkFAgSA1IisZw0plG99pza0unZrii/vcOg2ubQeCoIXSTLxfLuPlneUpCTqnOcNVkkWZtVyN7z94/H9StIOJOm4qzd9N612mAGYbzNMpobCrjcH3c4wbaIRBjDiNcn23ZfmtOQClyXiC@7o/EjNk0QtEECjNFWTgi5Kpu/mpk0u84xm04BpQm/OnQofFlz5gSKjXbpwvPgFAhmAICcxxMb0GXdjXdJgl@JJRlrwoy8oMzln60c5PB54iee79P4AfLkB9gwRGESR9Ev "PHP – Try It Online") | [Try it online!](https://tio.run/##XVDNS8MwFL/vrwgh0MSlW1umMtK6iwoD8aDe1hm6mq7BLA1pBoXh315fhycPebyv30eea92Yb1zrEPGoQHiJ0QI5r47SK2eqWtFoubjZSNlWJsi6OzltlC9pyUT5tuwjjiJ4DTTlUU0LNigbeirl8/blSUrGUcqAEojFTFstexUodrVXi0NVfwcPQRp90gFzhFfZerW@u8/Wt5iJWdN5SnSRCGKKBth7@v7xuH1lgl2Qbigxuz54oyxkLE73RYFLixks9@cDTKDNEx6nbMKrwZnuS1EcYw7rAvB1d7ZhwuYZgHZAADHZixlCV2X7VxObF9c5ZPM5A2lErxc6VaFuKfEcxKZzqSrQaIg4sYwxdJksaqbqtpt8CQRfSQWaakSs@AGZn39npUyMnwMdaHnM04cNK8HYOCZxlibJLw "PHP – Try It Online") |
| **Ruby** | **[Try it online!](https://tio.run/##PY5Bi8IwEIXv@ytmi2Cy0CHpNWZB0KsH2VvrBqWxBsJY0ogVZP96TcT1MAPz5n1vJlwOtymAhq3t7Ngj2Suslj9LDHbfKnBaKLienLfgdWfj8AHgjuDrUu60LhoqVFr4WiCW1U6BpTY5koJD711k83LOXwh6S108Mb6oElMnPmFv5HgOQOAIsojxbByTgiNm43tMvmcWK8biizjoPwgqC@4z/9lf4vDMy3/LNAdHEej/RO65jFlvVsZMvyMbWdMt5DdvqjufTZMoZSXEAw "Ruby – Try It Online")** | **[Try it online!](https://tio.run/##PY5Bi8IwEIXv/oqxCCZCh6TXmBVBrx5kb60bdjHWQBhLGrFe/OvdRNTDDMyb972ZcP27jwE07G1rhw7J3mCz/l5jsL9HBU4LBbez8xa8bm3sJwDuBL4u5UHroqFCpYWvBWJZHRRYOiZHUrDvvItsXs75C0FvqY1nxpdVYurEJ@yDnC4BCBxBFjFejGNScMRs/IzJ98xixVAsiIN@QFBZcNP8Z3eN/TMv/y3THBxFoPeJ3HMZs91tjBl/Bjawpl3KrxVvKj4bR1HKSoh/ "Ruby – Try It Online")** |
This is a port of the non-atomic recursive regex to Ruby's subroutine call syntax.
[Answer]
# [Thunno](https://github.com/Thunno/Thunno) `-`, \$ 4 \log\_{256}(96) \approx \$ 3.29 bytes
```
bdiP
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSrlLsgqWlJWm6FkuSUjIDIEyoyIJFxkYQFgA)
or [verify all test cases](https://ato.pxeger.com/run?1=m72sJKM0Ly9_weJ0Q92lpSVpuhZLklIyAyDMBVBqsaGBAYQJAA)
Port of [Dennis's MATL answer.](https://codegolf.stackexchange.com/a/142577/114446)
## [Thunno](https://github.com/Thunno/Thunno) `DD`, \$ 5 \log\_{256}(96) \approx \$ 4.12 bytes
```
1-A^<
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_WbSSi4tS7IKlpSVpuhZLDXUd42wgbKjQgkXGRhAWAA)
or [verify all test cases](https://ato.pxeger.com/run?1=m72sJKM0Ly9_UXTs4nQXl6WlJWm6FksNdR3jbCDsBVBqsaGBAYQJAA)
Port of [Dennis's Jelly answer.](https://codegolf.stackexchange.com/a/142578/114446)
**Note**: a plain "power of two" answer would be 5 chars: [`b1c1=`](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhZLkwyTDW0hbKgQTAoA) (is the count of 1s in the binary representation equal to 1?)
#### Explanation
```
bdiP # Implicit input
# - flag decrements
b # Convert to a binary string
di # Get the list of digits
# This is a non-empty list of ones
# if the input is a power of two
P # Push the product of this list
# Implicit output
```
```
1-A^< # Implicit input
1- # Subtract one
A^ # Xor with input
# The highest set bit will only be conserved
# if the input is a power of two
< # Is more than input?
# Implicit output
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `g`, 4 bytes
```
K·∏£v‚ÇÇ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBZyIsIiIsIkvhuKN24oKCIiwiIiwiMlxuNFxuMTZcbjEyOFxuMTBcbjEyXG4xNFxuMThcbjEiXQ==)
Can probably be golfed but it’s painful to do this on mobile.
Outputs `1` for truthy, `0` or the empty list for falsy.
```
K # divisors of input
·∏£ # without the first element
v # vectorize the following over it
‚ÇÇ # is even?
# (after which the `g` flag takes the minimum of the stack)
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 40 bytes
```
param($i)(($i-band(-$i))-eq$i)-and$i-ne0
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVTUwNI6CYl5qVo6AJ5mrqphUBKF8gHCuelGvz//9/QyAIA "PowerShell – Try It Online")
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `M`, 2 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
⁻ḃ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faGm0kq9S7IKlpSVpuhbLHjXufrijeUlxUnIxVGjBImMjCAsA)
Port of [Dennis's MATL answer](/a/142577/114446): decrement, convert to binary, take minimum.
---
A plain "power of two" answer would be **4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md):**
```
2BS·∏Ö
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWy4ycgh_uaF1SnJRcDBVasMjYCMICAA)
Convert to a binary list, sum equals one?
[Answer]
# [Neim](https://github.com/okx-code/Neim), 3 bytes
```
ùêÖ·õÉùê©
```
Doesn't work on TIO.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ÆEL’¬
```
[Try it online!](https://tio.run/##y0rNyan8//9wm6vPo4aZh9b8///fBAA "Jelly – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 25 bytes
```
.+
$*
+`^(11+)\1$
$1
^11$
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYtLOyFOw9BQWzPGUIVLxZArztBQ5f9/QzMA "Retina – Try It Online")
[Answer]
# [Actually](https://github.com/Mego/Seriously), 5 bytes
```
;R♂╙c
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/9866NHMpkdTZyb//28BAA "Actually – Try It Online")
Explanation:
```
;R♂╙c
; duplicate n
R range(1, n+1)
♂╙ powers of 2
c contains n
```
[Answer]
# [Haskell](https://www.haskell.org/), 24 bytes
```
f n=elem n$map(2^)[1..n]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY1JzVXIU8lN7FAwyhOM9pQTy8v9n9uYmaegq1CSj4XJ1DCV0EjpkJB106hoLQkuKTIJ09BRaE4I79coUJbW0nXTklbG8TTSFOo0NRUiDbQ0zM0MIj9DwA "Haskell – Try It Online")
[Answer]
# [Actually](https://github.com/Mego/Seriously), 4 bytes
```
yN2=
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/7/Sz8j2/39DAA "Actually – Try It Online")
] |
[Question]
[
Write a program or function that takes in a non-negative integer N from stdin or as a function argument. It must print or return a string of a hollow ASCII-art square whose sides are each made with N copies of the number N.
### Specifically:
If N is `0`, no copies of N are used, so there should be no output (or only a single trailing newline).
If N is `1`, the output is:
```
1
```
If N is `2`:
```
22
22
```
If N is `3`:
```
333
3 3
333
```
If N is `4`:
```
4444
4 4
4 4
4444
```
If N is `5`:
```
55555
5 5
5 5
5 5
55555
```
The pattern continues for `6` through `9`.
If N is `10`, the output is:
```
10101010101010101010
10 10
10 10
10 10
10 10
10 10
10 10
10 10
10 10
10101010101010101010
```
**Notice that this is not actually square.** It is 10 rows tall but 20 columns wide because `10` is two characters long. This is intended. The point is that each side of the "square" contains N copies of N. **So all inputs beyond `9` will technically be ASCII rectangles.**
For example, if N is `23`, the output is:
```
2323232323232323232323232323232323232323232323
23 23
23 23
23 23
23 23
23 23
23 23
23 23
23 23
23 23
23 23
23 23
23 23
23 23
23 23
23 23
23 23
23 23
23 23
23 23
23 23
23 23
2323232323232323232323232323232323232323232323
```
Here are Pastebins of the required outputs for [`99`](http://pastebin.com/raw/Qcas2Qmu), [`100`](http://pastebin.com/raw/1wc2FNmL), [`111`](http://pastebin.com/raw/DGZcHSiS), and [`123`](http://pastebin.com/raw/ajYdGhmw) (they may look wrong in a browser but in a text editor they'll look correct). The output for `1000` is to large for Pastebin but it would have 1000 rows and 4000 columns. **Numbers with 4 or more digits must work just like smaller numbers.**
### Details:
* N must be written in the usual decimal number representation, with no `+` sign or other non-digits.
* The hollow area must only be filled with spaces.
* No lines should have leading or trailing spaces.
* A single newline after the squares' last line is optionally allowed.
* Languages written after this challenge was made are welcome, they just [aren't eligible to win](http://meta.codegolf.stackexchange.com/a/4870/26997).
* **The shortest code in bytes wins!**
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 20 bytes
```
ẋṅ,⇩(L⁰‹*$S↲₴,)ċ[ẋṅ,
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuovhuYUs4oepKEzigbDigLkqJFPihrLigrQsKcSLW+G6i+G5hSwiLCIiLCIxMCJd)
## How?
```
ẋṅ,⇩(L⁰‹*$S↲₴,)ċ[ẋṅ,
ẋ # Repeat the (implicit) input the (implicit) input number of times (returns a list)
ṅ # Join by nothing
, # Print with trailing newline
⇩( # Loop (implicit) input minus 2 times:
L # Get the length of the (implicit) input
⁰‹ # Push the input minus 1
* # Multiply the length by that
$ # Swap to make (implicit) input at top
S # Convert the input to a string
↲ # Pad the stringified input with leading spaces until its length is len(input) * (input - 1) calculated earlier
₴ # Print this without a trailing newline
, # Print the (implicit) input with trailing newline
) # Close loop
ċ[ # If the (implicit) input is not one:
ẋ # Repeat the (implicit) input the (implicit) input amount of times
ṅ # Join by nothing to make it a string
, # Print with trailing newline
```
[Answer]
## Pyth, 27 bytes
```
jsMmm?sqM*,dk,0tQ`Q*\ l`QQQ
```
[Test suite](https://pyth.herokuapp.com/?code=jsMmm%3FsqM%2a%2Cdk%2C0tQ%60Q%2a%5C+l%60QQQ&input=12&test_suite=1&test_suite_input=0%0A1%0A10&debug=1).
[Answer]
# Python 2, 70 characters
```
def p(i):
k=`i`;j=i-2;h=k*i;print h+'\n'+(k+' '*j*len(k)+k+'\n')*j+h
```
[Answer]
# PHP 112 ~~114~~ ~~120~~ bytes
```
<?php $z=$j=$argv[1];while($j){$i=(--$j&&$i)?$z.str_pad('',strlen($z)*($z-2)).$z:str_repeat($z,$z);echo"$i\n";}
```
Command line usage: `php scriptname.php [n]`
[ideone demo](https://ideone.com/lbsfjv)
This golf uses `str_repeat` for the first and last row and `str_pad` for the rows in between.
[Answer]
## Ruby, 79 bytes
```
->n{s=n.to_s
puts s*n
$><<(s+" "*s.size*(a=n-2)+s+$/)*a if n>2
$><<s*n if n>1}
```
Some cases print a trailing line after the last line and some do not, but the question does not disallow this.
[Answer]
# Dyalog APL, 41 bytes
```
{1≥⍵:⍵⍴⍵⋄(' '≠⍕⍵/⍵)/⍕⍵⍪⍨⍵⍪⍵,⍵,⍨''⍴⍨2/⍵-2}
```
[Answer]
# Python 2, 73 characters
```
def l(i):s=`i`;n='\n';l=i-2;b=s*i+n;print b+(s+' '*l*len(s)+s+n)*l+b*(i>1)
```
[Answer]
# Python 3.5, 101 135 bytes:
(*+34 since apparently an input of 1 should just output 1 and an input of 0 should output nothing*)
```
def y(g):g=str(g);i=len(g);[print(g*(int(g))+('\n'+g+' '*((int(g)*i)-(i*2))+g)*(int(g)-2)+'\n'+g*int(g))if int(g)>1 else print(g*int(g))]
```
Prints out all the correct values for any integer input, whether in string form or not.
**Sample Inputs and Outputs:**
```
Input: y(10)
Output:
10101010101010101010
10 10
10 10
10 10
10 10
10 10
10 10
10 10
10 10
10101010101010101010
Input: y(1)
Output:
1
Input: y(2)
Output:
22
22
Input: y(4)
Output:
4444
4 4
4 4
4444
```
However, for triple digit numbers, it was just too big to fit on my monitor, so I hope that comes out correct if someone else tries it. I suspect it should since all 1 and 2 digit numbers come out correctly.
[Answer]
## Python 3, 75 characters
```
def q(n):s=str(n);m=n-2;print(s*n,*[s+" "*len(s)*m+s]*m,s*n*(n>1),sep="\n")
```
[Answer]
# PHP, 86 Bytes
```
for(;$i<$a=$argn;)echo str_pad($a>1?$a:"",($a-1)*strlen($a),$i++&&$i<$a?" ":$a)."$a
";
```
[Try it online!](https://tio.run/nexus/php#HYtLCoAgFEXnriIeD8m0oKCJVi4lHv0hVKz9mzQ791zOYMMZGFI83Nj1Ju0@lgavAWn8pRHbcvrieeMcaC2RptYiaQCVuW5FlZ97c3kIhZeUnP@xhQJ0dg0gMTApfQ "PHP – TIO Nexus")
[Answer]
# JS to ES6 compatibilized, ~~136~~ 76 B
```
function x(a){var c='';function Q(){for(var b=0;b<a;++b)c+=a}Q();c+='\n';
for(b=2;b<a;++b){c+=a;for(let A=2;A<a;++a)c+=' ';c+=a+'\n'}Q()}
```
Works way smaller:
```
x=(a,c)=>{Q=(í,k)=>{for(;í<a;++í)c+=k}Q(0,a);c+='\n';Q(2,a+Q(2,' ')+a+'\n')}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 78 bytes
```
N=input()
n=int(N)
m=n-2
b=N*n+"\n"
print(b+(N+" "*len(N)*m+N+"\n")*m+b*(n>1))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/3882M6@gtERDkysPyCrR8NPkyrXN0zXiSrL108rTVorJU@IqKALJJGlr@GkrKShp5aTmAZVp5Wr7gaVBrCQtjTw7Q03N//9NAQ "Python 3 – Try It Online")
I went back and forth over multiple approaches to this (even using `exec()` at one point, then ditching it because it was unnecessary), but I figured out that this is the shortest Python 3 approach.
[Answer]
**Python 2,96 bytes**
```
s=raw_input()
n=int(s)
for i in range(n):
if 0<i<n-1:print s+' '*(n-2)*len(s)+s
else:print s*n
```
**Python 3,94 bytes**
```
s=input()
n=int(s)
for i in range(n):
if 0<i<n-1:print(s+' '*(n-2)*len(s)+s)
else:print(s*n)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
×,<GgIÍ*ú«,}≠i×,
```
[Try it online](https://tio.run/##yy9OTMpM/f//8HQdG/d0z8O9Wod3HVqtU/uoc0EmUOz/f0MDAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VQ@amrRc/l/eLqOjXt65eFercO7Dq3WqX3UuSATKPa/9tA2e82Y/9EGOoY6RjrGOiY6pjqWOoYGOkbGsQA).
**Explanation:**
```
× # Repeat the (implicit) input the (implicit) input amount of times as string
, # Pop and print this string with trailing newline
<G # Loop the (implicit) input-2 amount of times:
g # Get the length of the (implicit) input
IÍ # Push the input-2
* # Multiply it by the length
ú # Pad the (implicit) input with that many leading spaces
« # Append it to the (implicit) input
, # Pop and print it with trailing newline
} # Close the loop
≠i # If the (implicit) input is NOT 1:
× # Repeat the (implicit) input the (implicit) input amount of times as string
, # Pop and print this string with trailing newline
```
I don't think I've ever used the fact that input can be implicitly as many times in a single program as this one. xD
[Answer]
# [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate), 42 bytes
```
(($~1){$~1})((
$2 {#2}{$2-2}$2){$2-2}
$1!)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72qKDU9NS-1KLEkdcGCpaUlaboWN7U0NFTqDDWrgUStpoYGl4qRQrWyUW21ipGuUa2KkSaEwaViqKgJ0QHVuCxaychYKRbKAwA)
For clarity, space is replaced with `_` and newline is replaced with `¶`:
```
( # Capture the first line as $1, for reuse as the last line.
($~1){$~1} # Repeat N in decimal, N times. Capture N in $2 for golf,
# which allows referring to it as "$2" instead of "$~1" and
# its length as "#2" instead of "#~1".
)
(
(
¶
$2 # Output N in decimal for the left edge.
_{#2}{$2-2} # Output length(N)*(N-2) spaces
$2 # Output N in decimal for the right edge.
){$2-2} # Repeat the above N-2 times. This will cause a non-match
# if N == 1, preventing this entire block from matching,
# which will also prevent the top line from being repeated
# as the bottom line below.
¶
$1 # Repeat the top line as the bottom line.
!
# If N == 1, the above alternative won't be able to match;
# do nothing here, to prevent it from triggering a top-level
# non-match.
)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~34~~ ~~30~~ 29 bytes
Code:
```
F¹}JDU,¹!#¹DÍF¹gFð}}¹J¹ÍF=}X,
```
[Try it online!](http://05ab1e.tryitonline.net/#code=RsK5fUpEVSzCuSEjwrlEw41GwrlnRsOwfX3CuUrCucONRj19WCw&input=MTA)
I didn't have some kind of fancy string multiplication function, but here is the submission *with* the function. It's something I added after the challenge and is therefore non-competing:
**26 bytes:**
Code:
```
D×DU,¹¹Í¹g*ð×¹J¹ÍF=}¹1›iX,
```
Uses **CP-1252** encoding.
[Answer]
# Mathematica,116 bytes
```
Switch[#,0,"",1,1,_,#5<>#4[#<>#4[" ",StringLength@#*#3]<>#<>"\n",#3]<>#5&[##,#~#4~#2<>"\n"]&[ToString@#,#,#-2,Table]]&
```
Somewhat long, but oh well.
[Answer]
# Oracle SQL 11.2, ~~106~~ ~~105~~ 115 bytes
```
SELECT RPAD(:1,(:1-1)*LENGTH(:1),DECODE(LEVEL,1,:1||'',:1,:1||'',' '))||:1 FROM DUAL WHERE:1>0 CONNECT BY:1>=LEVEL;
```
10 bytes added to manage 0
[Answer]
# SmileBASIC, 89 bytes
```
INPUT N$N=VAL(N$)Q=N>1FOR I=1TO N?N$*!!N*G;" "*LEN(N$*(N-Q*2))*G;N$*(Q*G+N*!G)G=I<N-1NEXT
```
[Answer]
# Common Lisp, SBCL, 151 bytes
```
(defun c(x)(if(< x 10)1(1+(c(/ x 10)))))(lambda(a)(format t"~:[~v{~a~:*~}~&~v@{~v<~a~;~a~>~4@*~&~}~*~v@{~a~:*~}~;1~]"(= a 1)a`(,a)(- a 2)(*(c a)a)a a))
```
function for counting digits adjusted to CL from Joshua's answer [here](https://stackoverflow.com/questions/19530112/how-to-count-number-of-digits)
### Ungolfed
```
(defun c(x)
(if(< x 10) 1
(1+ (c(/ x 10))))) ;counting digits
(lambda(a)
(format t"~:[~v{~a~:*~}~&~v@{~v<~a~;~a~>~4@*~&~}~*~v@{~a~:*~}~;1~]"(= a 1)a`(,a)(- a 2)(*(c a)a)a a))
;~[~] checks whether agument is equal 1 (if it is equal 1 then print out only "1") - without it we would print out 1\Newline 1
;first loop: ~v{~a~:*~} - printing first line of N
;second loop: uses justification "~<~>" to output enough spaces between N's on sides
;third loop: -printing last line of N
```
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~61~~ 58 bytes
```
;_LA|x=!A!~x=1|?A\Y=A+space$((x-2)*a)+A[x|Z=Z+A]?Z[x-2|?Y]
```
Explanation
```
; Read A$ from the cmd line
_LA| Take the length of A$ and assign to a
x=!A! Cast A$ to int, assign to x
~x=1|?A If x == 1, quit printing just the 1
\Y=A Else, setup Y$ as the middle of the square; it starts as the literal input
+space$( Followed by X spaces
(x-2)*a) where X is the length of the string x the value, minus start and end
+A Followed by the input again
[x| This FOR loop creates the top row
Z=Z+A] By concatenating the input x times to itself and assigning it to Z$
?Z Print the top row
[x-2|?Y] Print the right amount of middle rows
And the bottom row (Z$) is implicitly printed at EOF.
```
[Answer]
# Lua, 101 bytes
```
p,n=print,io.read()d,s=#n,n:rep(n)p(s)for i=3,n do p(n..(" "):rep(d*(n-2))..n)end p(n+0>1 and s or"")
```
Alternate 102 bytes:
```
l,n="\n",io.read()d,s=#n,n:rep(n)print(s..l..(n..(" "):rep(d*(n-2))..n..l):rep(n-2)..(n+0>1 and s or""))
```
101 Readable:
```
p,n=print,io.read()
d,s=#n,n:rep(n)
p(s)
for i=3,n do
p(n..(" "):rep(d*(n-2))..n)
end
p(n+0>1 and s or"")
```
Lua naturally has a small trick here by being able to convert a number as a string (e.g. "123") into a string or a number as needed based on context. It's not 100% intelligent though as you can see in my "ternary" statement at the end for handling the 0 and 1 cases- I had to use n+0 to coax it into a number before comparing it to 1.
[Answer]
# Perl 5, 67+2=69 bytes
Requires the flags `-lp`.
```
$@=($,=$"=$_)-2;$,x=$,;s/./ /g;$"=$".$_ x$@.$".$/;$_=$,.$/.$"x$@.$,
```
Has all the length of a mainstream language, and the unreadability of a more esoteric language!
[Answer]
# [WC](https://wasp-compiled.firebaseapp.com/), 146 bytes
```
;>_0|;>_0|$-;>_0|;>=_0|[<]$'[>]$--[>]$--[>];>_0|$''_0|!$?#@3|//#;>(?[>]$-!!_0|;>@5|$''[<<<<]!!$?!$[>>>>>>];<?[>]##@3|/#)?##@10|[>>>>>]*$#?[>>>>]!$
```
[Try it online!](https://wasp-compiled.firebaseapp.com/?;%3E_0|;%3E_0|$-;%3E_0|;%3E=_0|[%3C]$%27[%3E]$--[%3E]$--[%3E];%3E_0|$%27%27_0|!$?#@3|//#;>(?[>]$-!!_0|;>@5|$''[<<<<]!!$?!$[>>>>>>];<?[>]##@3|/#)?##@10|[>>>>>]*$#?[>>>>]!$&16)
Ungolfed/commented:
```
;>_0|;>_0| var n, var c
$- decrement c
;>_0|;>=_0| var i, var len = length(X)
[<] move to i
$'[>] multply i by len
$--[>]$--[>] i -= len (x2)
;>_0|$''_0| var full = X repeated X times
!$ print full
? reset index
#@3| if n == 0
// terminate
# end if
;>( new function
?[>] set index to 1
$-!!_0| decrement c and print it
;>@5| var spaces
$''[<<<<] repeat i times
!!$ print spaces
? reset index
!$ print n
[>>>>>>] move to spaces
;< delete spaces var
?[>] set index to 1
##@3| if c != 0
/ restart context (this function)
# end if
) end function
? reset index
##@10| if n != 2 (10th global)
[>>>>>] set index to 5
*$ call the function
# end if
?[>>>>] set index to 4
!$ print full
```
[Answer]
# APL(NARS), 69 chars, 138 bytes
```
{⍵≤1:⍕⍳⍵⋄f←{⊂∊⍺/⊂⍕⍵}⋄y←((⍴⊃x←f⍨⍵)-2×⍴r←⍕⍵)f' '⋄⊃x,((⊂∊r,y,r)/⍨⍵-2),x}
```
test:
```
g←{⍵≤1:⍕⍳⍵⋄f←{⊂∊⍺/⊂⍕⍵}⋄y←((⍴⊃x←f⍨⍵)-2×⍴r←⍕⍵)f' '⋄⊃x,((⊂∊r,y,r)/⍨⍵-2),x}
⎕fmt g¨0 1 2 3 11
┌5──────────────────────────────────────────┐
│┌0┐ ┌1┐ ┌2─┐ ┌3──┐ ┌22────────────────────┐│
││ │ │1│ 222│ 3333│ 11111111111111111111111││
│└¯┘ └─┘ │22│ │3 3│ 111 11││
│ └──┘ │333│ │11 11││
│ └───┘ │11 11││
│ │11 11││
│ │11 11││
│ │11 11││
│ │11 11││
│ │11 11││
│ │11 11││
│ │1111111111111111111111││
│ └──────────────────────┘2
└∊──────────────────────────────────────────┘
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 29 bytes
```
*zKszVSJ-K2p+z*J*lzdz)I>K1*zK
```
[Try it online!](https://tio.run/##K6gsyfj/X6vKu7gqLNhL19uoQLtKy0srpyqlStPTztsQKPP/v6EBAA "Pyth – Try It Online")
Properly handles "1" case, even if it cost me 3 more characters to do so. Still new to Pyth, and there's some interesting stuff happening with that Pyth answer that uses all the joins.
```
*zKsz #input auto-assigned to z as string, assign K to int(z), and print z*K
VSJ-K2 #set J to K-2, for N in range J
p+z*J*lzdz #print with no newline: z + (" " * len(z)) * (K - 2), print z
)I>K1*zK #close for loop and print z*K if K greater than 1
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 146 bytes
```
a=>{string b=a.ToString(),s="";for(int i=0,j,k;++i<=a;s+="\n")for(j=0;++j<=a;)if(i>1&i<a&j>1&j<a)for(k=0;k++<b.Length;)s+=" ";else s+=b;return s;}
```
[Try it online!](https://tio.run/##NU5Na4QwED3XXzF4WBK04rbHGKEUCoXtpVvopZfojttRm0AmLhTxt9u4Zecy876G1/J96zyuE5M9w/GXA/4oaEfDDE8wJxxMoBZeJttWZEMOHHx01tCBXo2u538MjTbFhztegZA56zRVnfMiZoB0mff5oLKMKm0UZzr9sqnc5F6Xke43WlInqN7vqDK7Pu6@MlfLEC1DllVNcUB7Dt9Kbg8gVTgyQrwb5TFM3gKrZVW3xhdHJ3gzZIWck7tnZ9mNWHx6Cig6EfEFfYiVX214fBA3/R3N6UAWhYyjkmVZ9@Uf "C# (.NET Core) – Try It Online")
Ungolfed:
```
a => {
string b = a.ToString(), s = ""; // initialize b (saves 4 bytes) and s (return variable)
for(int i = 0, j, k; ++i <= a; s += "\n") // for each row of the square
for(j = 0; ++j <= a;) // for each column of the square
if(i > 1 & i < a & j > 1 & j < a) // if not an edge of the square
for(k = 0; k++ < b.Length;) // for each digit in a
s += " "; // add a space
else // if an edge of the square
s += b; // add the input num
return s; // output the full string
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 22 bytes
```
_hUçU)z3
NgV gV gV gV
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=Cl9oVedVKXozCk5nViBnViBnViBnVg==&input=NQotUQ==)
More competitive than I expected, though I wouldn't be surprised if Charcoal or something has a really short answer that just hasn't been found yet.
Explanation:
```
:Empty line preserves the input as U
_hUçU)z3 :Declare a function V taking an argument Z:
_h ) : Set the first line of Z to
U : U as a string
Uç : Repeated U times
z3 : Rotate Z 90 degrees counterclockwise
NgV gV gV gV :Main program
N : Start with an arbitrary array (in this case [U])
gV gV gV gV : Apply V 4 times
```
It's necessary to rotate counterclockwise in `V` because a single-line array always ends up left-aligned when rotated, making clockwise rotations take an extra `gV`. The 1 extra byte for `z3` instead of `z` was better.
[Answer]
# Japt `-R`, 18 bytes
```
îU
U+ÕÅ+UÔÅ Õ·hJUw
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=7lUKVSvVxStV1MUg1bdoSlV3&input=MwoKLVI=)
[Answer]
# Batch, 264 bytes
```
@echo off&setlocal enabledelayedexpansion&set o=&set m=
for /l %%i in (1,1,%1)do set o=!o!%1&if %%i gtr 2 set m=!m!%1
if %1 gtr 0 echo %o%&if %1 gtr 2 (for /l %%i in (0,1,9)do set m=!m:%%i= !
set/an=%1-2
for /l %%i in (1,1,!n!)do echo %1!m!%1)
if %1 gtr 1 echo %o%
```
Only works for numbers up to 2029 because of the length limitations of `echo`.
] |
[Question]
[
They say that `hate` is a strong word. I wanted to find out why, so I had a good look at the word.
I noticed that every consonant had a vowel after it. That made it look quite strong to me, so I decided that that's what makes a word strong.
I want to find more strong words, so I'll need a program for it!
# Finding strong words
Strong words are words where every consonant (letters in the set `BCDFGHJKLMNPQRSTVWXZ`) is followed by a vowel (letters in the set `AEIOUY`). That's it. Nothing else matters.
If the word starts with a vowel, you don't have to worry about any of the letters before the first consonant. If the word has no consonants in it at all, it's automatically a strong word!
Some examples of strong words are `agate`, `hate` and `you`. `agate` is still a strong word because although it starts with a vowel, every consonant is still followed by a vowel. `you` is a strong word because it has no consonants.
There is no restriction on length for strong words.
# The challenge
Write a program or function that takes a non-empty string as input, and outputs a truthy value if it is a strong word or a falsy value if it is not.
# Clarifications
* You may decide to take the input in either lowercase or uppercase. Specify which in your answer.
* Words will not contain punctuation of any kind. They will only contain plain letters in the set `ABCDEFGHIJKLMNOPQRSTUVWXYZ`.
* Instead of truthy and falsy values, you may choose two distinct and consistent values to return for true and false. If you do this, specify the values you have picked in your answer.
+ You may alternatively output a falsy value for a strong word and a truthy one for a non-strong word.
# Test cases
```
Input -> Output
hate -> true
love -> true
popularize -> true
academy -> true
you -> true
mouse -> true
acorn -> false
nut -> false
ah -> false
strong -> false
false -> false
parakeet -> false
```
# Scoring
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the answer with the least bytes wins!
[Answer]
# JavaScript (ES6), ~~36~~ ~~28~~ 27 bytes
*Saved 1 byte by inverting the result, as suggested by LarsW*
Takes input in lowercase. Returns `false` for a strong word and `true` for a non-strong word.
```
s=>/[^aeiouy]{2}/.test(s+0)
```
### How?
We append a `0` (non-vowel) at the end of the input string and look for two consecutive non-vowel characters. This allows us to cover both cases that make a word *not* strong:
* it contains two consecutive consonants
* *or* it ends with a consonant
### Test cases
```
let f =
s=>/[^aeiouy]{2}/.test(s+0)
;[
"hate", "love", "popularize", "academy", "you", "mouse", "a", "euouae",
"acorn", "nut", "ah", "strong", "false", "parakeet"
]
.forEach(s => console.log(s + ' --> ' + f(s)))
```
[Answer]
# [Python 2](https://docs.python.org/2/), 48 bytes
```
lambda s:'se, F'in`[v in'aeiouy'for v in s+'b']`
```
An unnamed function taking a (lowercase) string, `s`, and returning `False` if strong or `True` if not.
**[Try it online!](https://tio.run/##JY7BCsIwEETP@hVLoKzFetCjoEd/QgVXm9pgmw3JplB/Pib1Mm9m2IVxs/RsD6k73dJA47MlCEcMuoELGvu4TmAskjYcZ@zYQ8kQtvjE@yOVQnSQ0m1UT6JVowaeChy7OJA33xLoRa0e5@xmjllHjuHfs7eZNkpJfZYgnu07m46G5caRp4/WourjeuW8sQKq2h8C7M5QBQUVbMqGBrqFNdkWcHlGyPtQfNRYp/QD "Python 2 – Try It Online")** (inverts the results to match the OP)
### How?
Non-strong words have either a consonant followed by a consonant or end in a consonant.
The code adds a consonant to the end (`s+'b'`) to make the required test be just for two consonants in a row.
It finds out if each letter in the altered word is a vowel with the list comprehension `[v in'aeiouy'for v in s+'b']`.
It now needs to check for two `False` results in a row (signalling a non-strong word), it does so by getting a string representation (using ``...``) of this list and looking for the existence of `'se, F'`. This is the shortest string found in `'False, False'` but none of: `'True, True'`; `'False, True'`; or `'True, False'`.
As an example consider `'nut'`, the list comprehension evaluates each letter, `v`, of `'nutb'` for existence in `'aeiouy'` yielding the list `[False, True, False, False]`, the string representation of this list is `'[False, True, False, False]'` which contains `'e, F'` here: `'[False, True, Fals>>e, F<<alse]'` hence the function returns `True` meaning that nut is **not** a strong word.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
e€ØY;Ạ11ẇ
```
A monadic link taking a list of characters and returning:
* `0` if strong
* `1` if not
**[Try it online!](https://tio.run/##y0rNyan8/z/1UdOawzMirU8sMzR8uKv9////5flFKQA "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##y0rNyan8/z/1UdOawzMirR/uWmBo@HBX@//D7Q93dz9qmJOWmFOcCqRLikqB1Fyuh7u3HN1zuB2oXMX9//@MxJJUrpz8slSugvyC0pzEosyqVK7E5MSU1NxKrsr8Uq7c/NJikEh@UR5XXmkJV2IGV3FJUX5eOhfYYK6CxKLE7NTUEgA "Jelly – Try It Online").
### How?
```
e€ØY;Ạ11ẇ - Link: list of characters, s e.g. "hate" or "you" or "not"
ØY - consonant yield "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz"
e€ - exists in? for €ach letter [1,0,1,0] [0,0,0] [1,0,1]
Ạ - all truthy? (1 for any valid input) 1 1 1
; - concatenate [1,0,1,0,1] [0,0,0,1] [1,0,1,1]
11 - literal eleven
ẇ - sublist exists? 0 0 1
- N.B.: left of ẇ implicitly makes digits so it looks for the sublist [1,1]
```
Note: The reason for using `Ạ` is just to save a byte over using `1` (since we then want to use `11` straight away).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
### Code
```
žPS¡¦õÊP
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//6L6A4EMLDy07vPVwV8D//4npiSWpAA "05AB1E – Try It Online")
### Explanation
```
žPS¡ # Split the string on consonants (bcdfghjklmnpqrstvwxz)
¦ # Remove the first element of the array to handle cases when the
string starts with a consonant
õÊP # Check if the empty string is not in the array
```
### Example
```
# "popularize"
žPS¡ # ['', 'o', 'u', 'a', 'i', 'e']
¦ # ['o', 'u', 'a', 'i', 'e']
õÊ # [1, 1, 1, 1, 1]
P # 1
```
[Answer]
# [R](https://www.r-project.org/), 43 bytes
```
function(s)grep("[^aeiouy]{2}",paste(s,""))
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jWDO9KLVAQyk6LjE1M7@0MrbaqFZJpyCxuCRVo1hHSUlT83@ahlJiemJJqpImF5BZmV8KYSTl52dDWBlwSaBZqXlKmv8B "R – Try It Online")
A port of Arnauld's JavaScript answer; returns 1 for weak words and `integer(0)` for strong ones; it appends a (space) to the end of the string.
This is actually vectorized; with a vector of strings, it returns the indices (1-based) of the weak words.
[Answer]
# Dyalog APL, 20 bytes
```
⎕←∧/2∨/0,⍨⍞∊'aeiouy'
```
[Try it online!](https://tio.run/##ATwAw/9hcGwtZHlhbG9nLWNsYXNzaWP//@KOleKGkOKIpy8y4oioLzAs4o2o4o2e4oiKJ2FlaW91eSf//2hhdGU)
[Answer]
# [Haskell](https://www.haskell.org/), ~~61~~ 54 bytes
```
f=and.(zipWith(||)=<<tail).(map(`elem`"aeiouy")).(++"z")
```
[Try it online!](https://tio.run/##JYpBDoMgEEXX7SnIrCA2nkCP0HUXTRMndSxEYAiCica7U2w3/7//8jUuM1lbytSjH1u5m/AwScvjUH3XJTRWtdJhkANZcgMgGc4bqGqbBnZQxaHxohcjXy/1dxcyRONTOynxBI2J4AaW17MCh2wxmv0c@MaR3FZp41zTcV7@nqOv7XM6l66xpMj@U2FC@/sEjDgTJXiVLw "Haskell – Try It Online")
I had to add a `z` at the end of the string to handle the case of a trailing consonant.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
ΛΣX_2m€¨γaıu
```
[Try it online!](https://tio.run/##ASMA3P9odXNr///Om86jWF8ybeKCrMKozrNhxLF1////ImFnYXRlIg "Husk – Try It Online")
Thanks to [H.PWiz](https://codegolf.stackexchange.com/users/71256/) for help with -4. ~~Returns inconsistent but appropriately truthy or falsy values.~~
Thanks to [Leo](https://codegolf.stackexchange.com/users/62393/leo) for -1, now returns consistent truthy/falsy value.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~93~~ 81 bytes
```
s->{int w=0,p=w,l;for(char c:s)w|=p&(p=l="aeiouy".indexOf(c)>>31);return w+p>=0;}
```
[Try it online!](https://tio.run/##LY6xTsMwFEX3fIWVAdmQWkVspI4ESGyIoWPV4eE4xaljW/ZzQ1Ty7cFBvePVubqnhwtsnFe2b8@LHrwLSPrc8YTa8C5ZidpZfl8XhTQQI/kAbcm1IDkRAbUk7zdoJ78hHI7Vq3NGgW1IJ5a4aa7aIhnFtvJirEzduUBXkMjnyMZf4e@oF0aUoLRLU8m1bdXPZ0cla5qnR1YHhSlYMj74Rmzrecki67dPXyZ/3xQuTrdkyGZ0j0Hb0@FIIJwiu4mu2U8R1cBdQu4zgsbSjoP3ZqKlhwBnpbDk6N6y20sIMFHGWP0/n4t5@QM "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 25 bytes
```
->w{w+?t!~/[^aeiouy]{2}/}
```
[Try it online!](https://tio.run/##LYpBDoIwFESvUklIF4JEE5fiQZqafLUIEfhN2y9UwKvXFN3MvJcZQ1cfqlPIy2Eatme3@RTiAqpB8nI6LMUSBK/BKZ4x3uJrbY2aWjDNezW4wV11PqJHitUh2f@Epo/Qk1u9jmmdwf4RqYL2d9Rg4KmU43LXgZ7mcdbkLEvS/dGyvGSpTVIxZpUYpVzCFw "Ruby – Try It Online")
Everybody else is doing it, so why can't Ruby?
[Answer]
# [Pyth](https://pyth.readthedocs.io), 18 bytes
```
:+Q1."2}M>åYà
```
**[Verify all the test cases.](https://pyth.herokuapp.com/?code=%3A%2BQ1.%222%7D%04M%C2%83%3E%C2%85%C3%A5Y%13%C3%A0%C2%9B&test_suite=1&test_suite_input=%22hate%22%0A%22love%22%0A%22popularize%22%0A%22academy%22%0A%22you%22%0A%22mouse%22%0A%22acorn%22%0A%22nut%22%0A%22ah%22%0A%22strong%22%0A%22false%22%0A%22parakeet%22&debug=0)**
"Borrowed" the regex from [the JS answer](https://codegolf.stackexchange.com/a/142279/59487). This returns `False` for strong words, `True` otherwise
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~18~~ ~~11~~ 10 bytes
```
,Ḷs₂{¬∈Ẉ}ᵐ
```
[Try it online!](https://tio.run/##LY07DsIwEESvsnJB5YrrIIpN4nyE4438iRQ@TQoUOg5CQQNCKbmJc5EQmzQ7b2Z2tYnGtOwkFdv5NF2fU99vOIOMhAFFFkQrFMgqtxwSTcyPt/NSVwaM1aSKEFz86z5z/3mb5fj0fUzD4MchpvMOWIlWMA5MUhu1ocZJ1NUxOkwxE3UXsCMXpCZn1oq0CqCcjb4Mc/27UI7yv9igxoMQlsH@Bw "Brachylog – Try It Online")
Neat and simple (except maybe for the 2 extra initial bytes to handle the final consonant case, like "parakeet").
Is falsey for strong words and truthy for non-strong words.
```
,Ḷ % append a newline (non-vowel) at the end of input,
% to catch final consonants
s₂ % the result has some substring of length 2
{¬∈Ẉ}ᵐ % where neither of its elements belong to
% the set of alternate vowels (with "y")
```
[Answer]
# Perl 5, 31 bytes (30 + 1)
```
$_=''if/[^aeiouy](?![aeiouy])/
```
+1 byte for `-p` command line flag. Prints the word if it's a strong word, or the empty string if it is not.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
e€ØY;1a2\¬Ȧ
```
[Try it online!](https://tio.run/##y0rNyan8/z/1UdOawzMirQ0TjWIOrTmx7P///4nJ@UV5AA "Jelly – Try It Online")
```
e€ØY;1a2\¬Ȧ Main link
€ For each letter
e Is it an element of
ØY The consonants (excluding Yy)?
;1 Append 1 (true) (consonant) to make sure last letter isn't consonant
2\ For all (overlapping) slices of length 2 (the <link><nilad>\ functionality)
a Logical AND of the two values; is it a consonant pair?
¬ Logical NOT vectorizing; for each (overlapping) pair, is it not a consonant pair?
Ȧ Any and all; make sure all pairs are not consonant pairs
```
Yes I know I've been beaten a lot by Jonathan Allan but I wanted to share my approach anyway :P
-4 bytes by stealing a little bit of Jonathan Allan's answer (instead of appending a consonant to check for last-letter edge case, just append 1)
-1 byte thanks to miles
[Answer]
# Awk, 39 bytes
```
/([^aeiouy]{2}|[^aeiouy]$)/{print "n"}
```
prints `n` for non-strongword, nothing (or, just a newline) for strongword
following the pack and searching for two consecutive non-vowels on lowercase input
testing
```
$ awk -f strongwork.awk
hate
love
popularize
academy
you
mouse
acorn
n
nut
n
ah
n
strong
n
false
n
parakeet
n
```
[Answer]
# [Kotlin](https://kotlinlang.org), 49 bytes
```
{Regex(".*[^aeiouy]([^aeiouy].*|$)").matches(it)}
```
**True and false are swapped**
## Beautified
```
{
Regex(".*[^aeiouy]([^aeiouy].*|$)").matches(it)
}
```
## Test
```
var s:(String)->Boolean =
{Regex(".*[^aeiouy]([^aeiouy].*|$)").matches(it)}
data class TestData(val input: String, val output: Boolean)
fun main(args: Array<String>) {
val items = listOf(
TestData("hate", true),
TestData("love", true),
TestData("popularize", true),
TestData("academy", true),
TestData("you", true),
TestData("mouse", true),
TestData("acorn", false),
TestData("nut", false),
TestData("ah", false),
TestData("strong", false),
TestData("false", false),
TestData("parakeet", false)
)
items
.filter { s(it.input) == it.output }
.forEach { throw AssertionError(it.toString()) }
println("Test Passed")
}
```
[TryItOnline](https://tio.run/##jZLBTsMwDIbvfQqr4pBMow8w0UlD7AwCbggka0vbaGlSOc6gjD17SVsYAmkqviR2vt@2lH/n2Gjb7ZHAL8QDk7alvFxeO2cUWsi7w70q1ZtIs9nTCyrtQvssTrds9nEhU5nVyJtKeaFZHrstMsLGoPfwqDzfxFTs0YC2TeAFjDPm0Jdc4KH2NU4mSREs1KitQCr9AlZE2F6NkqWEQwIxhmasag85GO35thBD/TtOU9MKWaVzYApKzs8wxu0nmcY1wSDp90kSN7hVdTuFtS5MIbUL/h/jHNkIFWj8ecoGnmSwmkQ8k7PlJDa8TlINEu6U@lls4KID@mP43V/CrNCGFcEBepdlg5ck5HlEs9FFcPwjcLTGTRUVXJF7hZX3ilg7uyZy1DdhNxpLSBnFg7qJORsr0n5RuIseVttUJsfuEw)
Based on [@Arnauld's](https://codegolf.stackexchange.com/users/58563/arnauld) [Answer](https://codegolf.stackexchange.com/questions/142278/is-it-a-strong-word/142279#142279)
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~23~~ 18 bytes
```
$
$
1`[^aeiouy]{2}
```
[Try it online!](https://tio.run/##HclBCsIwEAXQ/T9HhW71Eh5ClH50akPTTJjOCEE8exS375l4KuyH8Tz1AQOO0@VGSRrt@j59el/ogqwvQdUamZZ2Ae98yNbQNLBp/EWtoISDC3Y3LU/MzL@pNK4i/gU "Retina – Try It Online") Outputs 0 for strong, 1 if not. Add 1 byte to support mixed case. Edit: Saved 5 bytes thanks to @ovs.
[Answer]
# Java 8, ~~53~~ 42 bytes
```
s->s.matches(".*[^aeiouy]([^aeiouy].*|$)")
```
-11 bytes by using the same regex as in [*@jrtapsell*'s Kotlin answer](https://codegolf.stackexchange.com/a/142332/52210) instead.
[Try it here.](https://tio.run/##jZDBbsIwDIbvPIVV7dAgkReotjcYF44IJBMMDaRxlTiVuq3P3oXBdtsyKZYS/Z/9//EFB1xxT/5yvM7GYYzwita/LwCsFwonNATr2xPgwOwIPZh6I8H6M0TVZGHKlU8UFGtgDR6eYY6rl6g7FNNSrCu93O6RLKdxV//c9PLjSVVqbu79fTq43P8YM7A9QpeTPLy2O0B1j7EZo1CnOYnusyTO116bumpRqFJfkX6HHA9lqOc@OQz2rYyiwSN1Y5EbORWZjlP801E1N6GQh4MvOvkk5Z@1RSRKYH8uYid08R9Lx4BXou9g02KaPwE) (`false` if strong; `true` if not)
**Explanation:**
```
s-> // Method with String parameter and boolean return-type
s.matches( // Checks if the String matches the following regex:
".* // One or more characters
[^aeiouy] // Followed by a consonant
([^aeiouy].* // Followed by another consonant (+ any more characters)
|$)") // Or the end of the String
// End of method (implicit / single-line return statement)
```
So it basically checks if we can find two adjacent consonants, or if the String ends with a consonant.
---
Old answer (**53 bytes**):
```
s->s.matches("[aeiouy]*([a-z&&[^aeiouy]][aeiouy]+)*")
```
[Try it here.](https://tio.run/##jZBBboMwEEX3OcWIRYQTwQVQe4NmkyWi0sQ4wYnxII@NRCrOTp2GLFtX8izs//T/91xxxIIGZa/tbZEGmeEDtf3aAGjrlTujVHB4XAFOREahBZkfvdP2AiyqKMxx4mGPXks4gIU3WLh457JHLzvFeVaj0hSmZpfXWNy32/pzfWheyl7sMrFUT6shnEy0Wh1H0i30sdQaWzeA4tnoOLFXfUnBl0OUvLG5LWWedehVJn7a/Q4ZGtPQQEMw6PQ9jaLEVvVTkpsoJJmeAv@ZKKqHkOhDziaTbPDpn3VJhL0je0liZzT8j6Wjw5tSr2LzZl6@AQ) (`true` if strong; `false` if not)
Uses regex to see if the input-String matches the 'strong'-regex. Note that `String#matches` in Java automatically adds `^...$` to check if the String entirely matches the given regex.
**Explanation":**
```
s-> // Method with String parameter and boolean return-type
s.matches( // Checks if the String matches the following regex:
"[aeiouy]* // 0 or more vowels
([a-z&&[^aeiouy]] // { A consonant,
[aeiouy]+) // plus one or more vowels }
*") // Repeated 0 or more times
// End of method (implicit / single-line return statement)
```
---
A search instead of matches (like a lot of other answers use) is actually longer in Java:
**70 bytes**:
```
s->java.util.regex.Pattern.compile("[^aeiouy]{2}").matcher(s+0).find()
```
[Try it here.](https://tio.run/##jZBBasMwEEX3OcXglUWJKN2a9gYNhSxDChN54iiRNUYahbrBZ3eVJl22KkgLMY//3@iIZ1zyQP7YnmbjMEZ4ResvCwDrhcIeDcHq@gTYMTtCD6ZeS7C@g6iaPJjyzScKijWwAg/PMMflyzFH6yTW6UAdfeg3lBzoteF@sI7qavOOZDmN28vTVCndo5gDhTo@PCq9t76t1dzcsoe0czn7XnFm20KfLe8emy2guimuxyjUa06ihzwS5@tcWFcHFKrUt@7vkONzGRp4SA6D/SyjaLClfixyI6ci03OKfzaq5joo@HDwxSafpLzZoYhECey7IrZHF//x6RjwRPQjNi2m@Qs) (`false` if strong; `true` if not)
[Answer]
# [Python 2](https://docs.python.org/2/), 58 bytes
*-30 bytes by realizing it can be as simple as [Arnauld's JS answer](https://codegolf.stackexchange.com/a/142279/68615).*
```
lambda s:re.search('[^aeiouy]([^aeiouy]|$)',s)<1
import re
```
[Try it online!](https://tio.run/##PY7BCsIwEETv/Yo9CGlBBD0W@yW1wtpubbDNhs1GqPjvkVTxMvOGmcP4VSd2pzQ2lzTjchsQQi10CITST6Vpr0iW49qVf3rvKrMP1flY2MWzKAglpaABGmjNhEpmD2bm5@aefZxR7GtL2ONAy5px5Zht4Rh@FYvL4KJuecoaVNjdM404f4ceBR9EarqiGFnAgnWwHajBi3UKY2mr9AE "Python 2 – Try It Online")
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~19~~ 18 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
æ"[^ŗy]”ŗ(ŗ|$)”øβ=
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JUU2JTIyJTVCJTVFJXUwMTU3eSU1RCV1MjAxRCV1MDM5ODFnJTI1JXUwMTdFSiV1MjAxOCVGOCV1MDNCMiUzRA__,inputs=cG9wdWxhcml6ZQ__)
Explanation:
```
æ push "aeiou"
"[^ŗy]” push "[^ŗy]" with ŗ replaced with pop
ŗ(ŗ|$)” push `ŗ(ŗ|$)` with ŗ replaced with pop
øβ replace in the input that regex with nothing
= check for equality with the original input
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
žP¹SåJ1«11å
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6L6AQzuDDy/1Mjy02tDw8NL//xPTE0tSAQ "05AB1E – Try It Online")
Uses Jonathan's algorithm, returns `0` for true and `1` for false.
[Answer]
# [Swift 3.1](https://www.swift.org), 85 bytes
```
import Foundation
{($0+"0").range(of:"[^aeiouy]{2}",options:.regularExpression)==nil}
```
**[Try it here!](http://swift.sandbox.bluemix.net/#/repl/59b513d36bb1b17773ce606b)**
This borrows [Arnauld's regex](https://codegolf.stackexchange.com/a/142279/59487).
[Answer]
# Lua, 41 bytes
```
return#(io.read()..0):match"[^aeiouy]+"<2
```
Reads from standard input
# Lua (loadstring'ed), 37 bytes
```
return#((...)..0):match"[^aeiouy]+"<2
```
Reads from function parameter(s)
---
Input is lowercase
Sees if there is a string of length 2 or more, consisting only of not vowels (consonants) or if the string ends with a non-vowel
Returns true/false
[Answer]
## C++, ~~195~~ 194 bytes
-1 bytes thanks to Zacharý
Uppercase, return true if input is a strong word, false otherwise ( C++ have simple int to bool implicit cast rules, 0 => false, true otherwise )
```
#include<string>
#define C(p)(v.find(e[p])==size_t(-1))
std::string v="AEIOUY";int s(std::string e){for(int i=0;i<e.size()-1;++i)if(e[i]>64&&e[i]<91&&C(i)&&C(i+1))return 0;return!C(e.size()-1);}
```
**Code to test :**
```
auto t = {
"HATE",
"LOVE",
"POPULARIZE",
"ACADEMY",
"YOU",
"MOUSE",
"ACORN",
"NUT",
"AH",
"STRONG",
"FALSE",
"PARAKEET"
};
for (auto&a : t) {
std::cout << (s(a) ? "true" : "false") << '\n';
}
```
[Answer]
# C, 107 Bytes
```
i,v,w,r,t;a(char*s){w=0;for(r=1;*s;s++){v=1;for(i=6;v&&i;)v=*s^" aeiouy"[i--];r=w&&v?0:r;w=v;}return r&~v;}
```
Returns 1 for *strong* word and 0 for *weak* word. Tested with the words given in the main post.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 59 bytes
```
f(char*s){return*s?strcspn(s,"aeiouy")+!s[1]<2?f(s+1):0:1;}
```
[Try it online!](https://tio.run/##PVDBbsMgDD3DVzCmSpBkU7Nj060/UO22U5cDIqRBSyDCMCmr8u0ZKdlOfrafn58tn65SLkvLZCdcBvzmlA/OZHAC7ySMhkFBhdI2TJTnD3Ap6@PLqWWQl/ywP5TVvDxqI/vQKHIE32j73L1hbTwZhDaMkxtG0hrwZF1AsoThUpPXtYVoJ7yixYp6@72h0Y6hF07/bLmQolHDlJLJhgQGG@CfYJ1J0AS/1Tq6hniGNddUakX/NzEKJ76UStz3j/MZo7nCqLWOsNW9jv72VTSq64roPL8fgkYXey2ju3IPZNd8xp13SkHiR2LkPGrMGKUnRgE8L78 "C (gcc) – Try It Online")
[Answer]
# **PHP, 69 bytes**
```
preg_match("/([^AEIOUY][^AEIOUY]+|[^AEIOUY]$)/",$_SERVER['argv'][1]);
```
Returns **1** is the word is not strong.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 57 bytes
```
q{"aeiouy"#W=}%_,:B{_A={_A_)\B(<{=!X&:X;}{0:X;;;}?}&}fA;X
```
[Try it online!](https://tio.run/##S85KzP3/v7BaKTE1M7@0Ukk53LZWNV7Hyqk63tEWiOM1Y5w0bKptFSPUrCKsa6sNgKS1da19rVptmqN1xP//ufmlxakA "CJam – Try It Online")
---
Reads input, converts to 1s for consonants, 0s for vowels. For every consonant, AND predefined variable X (predefined to 1) with next character's value. Output X
[Answer]
# [Zsh](https://www.zsh.org/), 21 bytes
```
>$1x<*[^aeiouy](#c2)*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=JckxCsIwFIDhvad4YIe24FAnh6AHEYVn-9IW07yQvEjrVVwC4uTsYbyNYqcfvv_-uIU-fXQgYSdAk5Btqe0MnzPNHmooehQCw1cCxy4a9EMgwAZbGmeYOcLI8S_sLdgogD0E8Ww70Gh-x6HHC5GUxTOKXm_fu7yeVHU4IQ0c52OxajZltbyXUirfZ36EqlwkpaVf)
Same method everyone else is using. Outputs via exit code: 1 for strong, 0 for not strong. Requires the `extendedglob` option.
] |
[Question]
[
Given n, k, and p, find the probability that a weighted coin with probability p of heads will flip heads at least k times in a row in n flips, correct to 3 decimal digits after decimal point (changed from 8 because I don't know how to estimate the accuracy of double computation for this (was using arbitrary precision floating points before)).
Edits:
Examples:
```
n, k, p -> Output
10, 3, 0.5 -> 0.5078125
100, 6, 0.6 -> 0.87262307
100, 9, 0.2 -> 0.00003779
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~40~~ ~~39~~ ~~18~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
**Brute-force approach:**
```
0Lα1ݲãʒγOà³@}èPO
```
Byte-count more than halved by porting [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/249352/52210), which uses a similar approach as [@DominicVanEssen's top R answer](https://codegolf.stackexchange.com/a/249333/52210), so make sure to upvote them as well!
Inputs in the order \$p,n,k\$.
Very slow, so use small \$n\$ in order to run it on TIO.
[Try it online.](https://tio.run/##yy9OTMpM/f/fwOfcRsPDcw9tOrz41KRzm/0PLzi02aH28IoAf6CcnimXoQGXMQA)
**Original mathematical ~~40~~ 39 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach:**
```
÷L®s©>m²®¹*-D>®/$-*I+s®<cI®¹*m$-®<m)øPO
```
Inputs in the order \$k,n,p\$.
[Try it online.](https://tio.run/##yy9OTMpM/f//8HafQ@uKD620yz206dC6Qzu1dF3sDq3TV9HV8tQuPrTOJtkTLJqrogvk5Goe3hHg//@/GZehgQGXgZ4ZAA)
**General explanation of the larger original program:**
Even though the challenge description was just a single sentence, it lead me on a chase down the rabbit hole. After quite a long search, I came across this MathExchange answer: [Probability for the length of the longest run in *n* Bernoulli trials](https://math.stackexchange.com/questions/59738/probability-for-the-length-of-the-longest-run-in-n-bernoulli-trials), for which [the accepted answer](https://math.stackexchange.com/a/59749/368863) contains the generalized formula for this challenge, originally solved by *de Moivre* in 1738:
$$\mathbb{P}(\ell\_n \geq k)=\sum\_{j=1}^{\lfloor n/k\rfloor} (-1)^{j+1}\left(p+\left({n-jk+1\over j}\right)(1-p)\right){n-jk\choose j-1}p^{jk}(1-p)^{j-1}$$
Where \$\mathbb{P}(\ell\_n \geq k)\$ is the probability that a consecutive run of the same unfair coin result with a length \$\ell\_n\$ is at least \$k\$ flips. \$p\$, \$k\$, and \$n\$ are as given by the challenge description, with \$p\$ being a decimal probability (e.g. 0.70 for 70%), and \$k\$ and \$n\$ being integers.
**Code explanation:**
```
0L # Push pair [1,0]
α # Get the absolute difference with the first (implicit) input p:
# [1-p,p]
1Ý # Push pair [0,1]
²ã # Get the second input n'th cartesian product
# (creating all n-sized lists with 0s/1s)
ʒ # Filter this list by:
γ # Group the 0s/1s into consecutive adjacent items
O # Sum each group
à # Pop and push the maximum
³@ # Check if this largest group of 1s is >= the third input k
}è # After the filter: (0-based) index each 0/1 into pair [1-p,p]
P # Take the product of each inner list
O # Take the sum of all values
# (after which the result is output implicitly)
```
```
÷ # Integer divide the first two (implicit) inputs: n//k
L # Pop and push a list in the range [1,n//k] (its values are j)
® # Push -1
s # Swap so the list is at the top
© # Store it in variable `®` (without popping)
> # Increase each j in the list by 1
m # Pop both, and calculate -1**(j+1) for each
® # Push the list `®` containing j again
¹* # Multiply each j by the first input k
² - # Subtract each from the second input n
D # Duplicate this n-jk list, since we need it again later
> # Increase each by 1
®/ # Divide each by j
$ # Push 1 and the third input p
- # Subtract: 1-p
* # Multiply this to each (n-jk+1)/j
I+ # And add the third input p to each
s # Swap so the n-jk list is at the top again
® # Push list `®` containing j again
< # Decrease each j by 1
c # Calculate the binomial coefficients of n-jk and j-1
I # Push the third input p again
® # Push list `®` containing j again
¹* # Multiply each j by the first input k again
m # Pop both, and calculate p**(jk)
$ # Push 1 and the third input p again
- # Subtract again: 1-p
® # Push list `®` containing j again
< # Decrease each j by 1 again
m # Calculate (1-p)**(j-1)
) # Wrap these five lists on the stack into a list of lists
ø # Zip/transpose; swapping rows/columns
P # Get the product of each inner list
O # And finally sum everything together
# (which is output implicitly as result)
```
[Answer]
# [Python](https://www.python.org), 66 bytes (-1 @xnor)
```
f=lambda n,k,p:n>=k and(1-p*(n>k))*(1-f(n+~k,k,p))*p**k+f(n-1,k,p)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY9BDoIwEEX3nKJh1ZZiQCNRElh4AC9giEGggRSmTS0LY_AibtjonbyNFWH35mcy78_zrW6mljCOr95wf_c58KTNu0uZI2CCqRjSRKAcShz6imJIBSHUMsfgPcRvw86KUuHZxA-nYL40cC07xHsojJTtFTWdktqgVvfnIi_qyrGmhfFRQkUwJw6X-m9GDaBTGLANC1bbjFkMWGQ5mnlveZ3FDlK6AYO5e7cNJn8cDe5cYnnrCw)
Adapted from my [answer to a similar challenge](https://codegolf.stackexchange.com/a/248518/107561). Note that I add memoization in the footer. This in theory doesn't change the result but it greatly accelerates the recursion.
### How?
Uses the recurrence
\$f(n,k,p)=f(n-1,k,p)+p^k(1-p)(1-f(n-k-1,k,p))\$
(valid for *n*>*k*) which is obtained by accounting for words that have k consecutive heads somewhere in the first n-1 tosses, words that end in a tail followed by k heads and the overlap of these two groups.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ø.ṗṣ1ZṫɗƇ_⁵AP€S
```
A full program accepting `n`, `k`, and `p` that prints the result.
**[Try it online!](https://tio.run/##AS4A0f9qZWxsef//w5gu4bmX4bmjMVrhuavJl8aHX@KBtUFQ4oKsU////zEw/zP/MC42 "Jelly – Try It Online")** (`n=100` is too big for such an inefficient program.)
### How?
Creates all \$2^{n}\$ possible outcomes, filters them to those containing a run of at least \$k\$ heads and then sums the probability of each occurrence.
The probability of a given occurrence is the product of `p`'s and `(1-p)`s identified by heads and tails respectively. For example the chance of `[tails, tails, heads, heads, heads]` is the product of `[(1-p), (1-p), p, p, p]` i.e. \$p^3(1-p)^{2}\$.
```
Ø.ṗṣ1ZṫɗƇ_⁵AP€S - Main Link: integer n, integer k (p is accessed later)
Ø. - [0,1]
ṗ - ([0,1]) Cartesian power (n)
-> all length-n tosses with 0 as heads and 1 as tails
Ƈ - filter keep those for which:
ɗ - last three links as a dyad - f(Outcome, k):
ṣ1 - split at 1s -> runs of heads
Z - transpose
ṫ - tail from index k -> empty (falsey) if longest run < k
⁵ - third program argument, p
_ - subtract -> valid outcomes with heads: -p; tails: 1-p
A - absolute values -> valid outcomes with heads: p; tails 1-p
P€ - product of each -> valid outcome probabilities
S - sum -> total probability of any valid outcome
```
---
If we could take the probability of tails (\$1-p\$) instead of heads (\$p\$) 14 byes taking `1-p`, `n`, `k`:
```
C©Ƭṗṣ®ZṫɗƇ⁵P€S
```
[Try it online!](https://tio.run/##AS4A0f9qZWxsef//Q8KpxqzhuZfhuaPCrlrhuavJl8aH4oG1UOKCrFP///8uNP8xMP8z)
[Answer]
# [R](https://www.r-project.org/), ~~129~~ ~~122~~ 116 bytes
*Edit: -2 bytes thanks to pajonk (which led to -4 more...)*
```
function(n,k,p)sum(apply(which(array(T,rep(2,n)),T)-1,1,function(v,r=rle(v))prod(p*v+(1-p)*!v)*(max(r$l[!r$v])>=k)))
```
[Try it online!](https://tio.run/##lY9NboMwEIX3nGKiZjEDThQQpt3QU2RXtcgiIFsQ2xoSKKenQKWqaumimyfN3/ve8NQUulKXrjC2UAW7IZ/quy1vxlm0ohGeuvsVlfftiIM2pUbFrEY8C648JsISiTMdYhGLr7tecM5thT2RZ3dBH/YRxgdP4a6nEK/qHXnfvux437/Sc94Q0fQApVa2rMDVkMAaCYwFBXMkGMxNg7PtOI/q1vhu2VJQK8NQunkth9MxkcHPX@Z8iThKCoLv9nLTPvvbWb7JaNFsrU5p9vS4wcqE/M1K/89Ko0/iImsrTjZp6UKbPgA "R – Try It Online")
Exact solution: calculates the probability of every possible outcome of `n` coin flips, and sums those that contain at least `k` heads-in-a-row.
**How?**
```
function(n,k,p){
a=expand.grid(rep(list(1:0),n)) # a is a matrix of all possible outcomes of n flips
# with heads represented as 0, tails as 1
pvals=apply(a,1,function(v)prod(p*v+(1-p)*!v))
# pvals are the probabilities of each outcome
# by multiplying the probability of each single flip
itsarun=apply(a,1,function(v)max(rle(v)$l[!rle(v)$v])>=k)
# itsarun is TRUE if the longest run of 0s in each row is >=k
# (rle(v)$l = length of each run, rle(v)$v = value of each run)
return(sum(pvals*itsarun)) # return the sum of all the pvals for successful outcomes
}
```
---
# [R](https://www.r-project.org/), 98 bytes
```
function(n,k,p){while((T=T+1)<1e19)F=F+(max((r=rle(sample(1:0,n,T,c(1-p,p))))$l[!r$v])>=k);F/1e19}
```
[Try it online with a low-accuracy version](https://tio.run/##dY5BDoIwEEX3nGKMLtpQEYhFo9YlJ2BnlDQVQgO0pKhojGfHwsoYncVMJvP/f2P6Mi0yfm5TqVKeGt2xPr8qcZFaIUVK0uBnV8gqQyhhiRvgXZBRHLPYRTW/I2SYsbeW140dwcYniiREoGDeWKetWXWYmNntiPesxNt4Yd2vfgqi4EpkoHMIYcSDVMDB4qGTlwK0qh72lFeyaQcVh5xLA0JbGQPfC6nz/TcKSUg8ih3nM57@jI/@J9MTdYcejZu/jNarH6yI0IHVvwE "R – Try It Online")
Brute-force approach: performs `1e19` series of `n` flips, and counts the number of times we get `k` heads-in-a-row. With this number of repetitions, the answer has a very high chance of being accurate to 8 decimal places, but there is a low-but-finite chance that this won't be the case...
We need to do them one-after-the-other in a `while` loop (rather than the more idiomatic vectorized [R](https://www.r-project.org/) approach of building a matrix and checking the rows) since the number of iterations needed to obtain 8 decimal places of accuracy is too big to be contained in an [R](https://www.r-project.org/) matrix.
The test link substitutes `1e5` in place of `1e19`, for a lower-accuracy output without timing-out. Feel free to run the high-accuracy version on your own computer if you have the time to wait.
---
# [R](https://www.r-project.org/), 83 bytes
```
function(n,k,p,m=cbind(rbind(1-p,diag(k)*p),!k:0))Reduce(`%*%`,rep(list(m),n))[k+1]
```
[Try it online!](https://tio.run/##lc7BToQwEAbgO08xZrNJu4wbaChuTHgJr0bZWoo0ZadNYbPx6RHwYhQPXv6k08n/TZxc3RnVDLWlWtXR36qpvZIerSdG6DDgpdJvlhoW18zvAzZWvTPHD4HjnXvMOH8yzVUbdt4f9meMJrDeDiO7cCTOn12av0w70J0ibcC3IGAVwRIomEW42bEDT/3H/NX2NgzLloJW2Qjaz2sVZEchk5@nMoECj5Inyfd6uVlf/t0sX2W6ZLm@sqI8PWxYJcrfVvF/q0i/xCXWUS42tWLRpk8 "R – Try It Online")
Port of [dancxviii's Markov method](https://codegolf.stackexchange.com/a/249365/95126) - upvote that one - but sadly still longer than [pajonk's R answer](https://codegolf.stackexchange.com/a/249376/95126)...
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `ḋ`, 23 bytes
```
2$ÞẊ'2€vLG›¹>;⁰⌐⁰"$İvΠ∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCIyJMOe4bqKJzLigqx2TEfigLrCuT474oGw4oyQ4oGwXCIkxLB2zqDiiJEiLCIiLCIxMFxuM1xuMC42Il0=)
Port of Jelly. Really slow.
Previous answer (much faster):
# [Vyxal](https://github.com/Vyxal/Vyxal) `ḋ`, 41 bytes
```
ḭɾ:£›u$e¹¥□h*-:›¥/⁰⌐*⁰+$¥‹ƈ?¥?*e⁰⌐¥‹eWƒ*∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCLhuK3JvjrCo+KAunUkZcK5wqXilqFoKi064oC6wqUv4oGw4oyQKuKBsCskwqXigLnGiD/CpT8qZeKBsOKMkMKl4oC5ZVfGkiriiJEiLCIiLCI2XG4xMDBcbjAuNiJd)
Port of 05AB1E.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 53 bytes
```
k->p->g(n)=if(n>=k,p^k*(1-p*(n>k))*(1-g(n---k))+g(n))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN02zde0KdO3SNfI0bTPTNPLsbLN1CuKytTQMdQu0gNxsTU0QGyivq6sL5GiDVGpCNG8pKMrMK9FI0zDW1DDQM9XUMDSASS1YAKEB)
A port of [loopy walt's Python answer](https://codegolf.stackexchange.com/a/249360/9288). Takes input in the the form `(k)(p)(n)`
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 56 bytes
```
f(n,k,p)=Pol((1-y=p*x)/(t=1-x)/(t/y^k+x-y)+O(x^n*x))\x^n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWNy3SNPJ0snUKNG0D8nM0NAx1K20LtCo09TVKbA11wbR-ZVy2doVupaa2v0ZFXB5QUjMGSEP1hyQWFORUaiQq6NopFBRl5pUAmUogjpJCcmJOjkaajkKipqaOQnS0oYGOgrGOgoGeaSyQa2gA5JqBuGZwriWIaxQbqwkxG-ZGAA)
The generation function of the sequence (for given \$p, k\$) is \$\frac{p^k\ x^k\ (1-p\ x)}{(1-x)(1-x+(1-p)\ p^k\ x^{k+1})}\$.
---
This generation function can be derived from loopy walt's recurrence formula:
\$f(n,k,p)=f(n-1,k,p)+p^k(1-p)(1-f(n-k-1,k,p))\$.
This recurrence formula is valid when \$n>k\$. In addition,
when \$n=k\$, we have \$f(n,k,p)=p^k\$ when \$n=k\$, and \$f(n,k,p)=0\$ when \$n<k\$.
Let \$F(k,p)\$ be the generation function (for given \$p, k\$), we have
\$\begin{align}
F(k,p) &= \sum\_{n=0}^{\infty}f(n,k,p)\ x^n \\
&= p^k\ x^k+\sum\_{n=k+1}^{\infty}f(n,k,p)\ x^n \\
&= p^k\ x^k+\sum\_{n=k+1}^{\infty}(f(n-1,k,p)+p^k(1-p)(1-f(n-k-1,k,p)))\ x^n \\
&= p^k\ x^k+\sum\_{n=k+1}^{\infty}f(n-1,k,p)\ x^n+p^k(1-p)\sum\_{n=k+1}^{\infty}(x^n-f(n-k-1,k,p)x^n) \\
&= p^k\ x^k+x\sum\_{n=0}^{\infty}f(n,k,p)\ x^n+p^k(1-p)\sum\_{n=0}^{\infty}(x^{n+k+1}-f(n,k,p)x^{n+k+1}) \\
&= p^k\ x^k+x\ F(k,p)+p^k(1-p)(\frac{x^{k+1}}{1-x}-x^{k+1}F(k,p))
\end{align}\$.
Solving this equation, we have \$F(k,p)=\frac{p^k\ x^k(1-p\ x)}{(1-x)(1-x+(1-p)\ p^k\ x^{k+1})}\$.
[Answer]
# JavaScript (ES7), 106 bytes
Quickly computes the probability, using the formula [found by Kevin Cruijssen](https://codegolf.stackexchange.com/a/249334/58563).
```
(n,k,p,q=1-p)=>(g=s=>(x=n-(y=j*k))<0?0:s*(p-~x/j*q)*(h=k=>--k?h(k)*(x-k+1)/k:p**y*q**~-j++)(j)+g(-s))(j=1)
```
[Try it online!](https://tio.run/##bcnLDoIwEIXhvU/BcmbagVYjicTBZzFe0JZAscbAxlevdWni5uQ/@dzxdYynxz08eRjPl3SVBIP2OuhJLAeUFjqJeWcZGBZx5BH35mCaSBD4PVeOJiS4iZeW2R9u4POd2SuLlW8C0UIT0ZudUggOVQccMZdYTKdxiGN/KfuxgysU1uhiowtTbhFXv2ZNtvpr9X/bfW2NmD4 "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES12), 58 bytes
Using [loopy walt's recursive formula](https://codegolf.stackexchange.com/a/249360/58563) is much shorter and much slower. This version uses a cache to speed it up (-7 bytes without the cache).
Expects `(k)(p)(n)`.
```
k=>p=>g=n=>g[n]||=n>=k&&p**k*(1-p*(n>k))*(1-g(--n-k))+g(n)
// \_____/
// cache
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGiNNulpSVpuhY3rbJt7Qps7dJt84BEdF5sTY1tnp1ttppagZZWtpaGoW6BlkaeXbamJoidrqGrm6cL5Gina-RpQk0ISs7PK87PSdXLyU_XSNMw1tQw0DPV1DA00NTkQpUyA0mZgaQw5SxBckZQOYjJCxZAaAA)
[Answer]
# PARI-GP, 75 bytes
[Port of below solution](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN73TNPJ0snUKNG01chNLijIrNLK1tYECiTpJOhqJuoa2tkmaWgXaGok2RppaGkk22UDSULdAEyiinWRrm62drakZl6cZna1jGAsxcl9BUWZeiUaahqEBDOgYmhroGOhZmJtqakIUwewHAA) (can run n ~ 1000000000, k ~ 150)
```
f(n,k,p)=(matrix(k++,k,a,b,(a-1==b)*p+(a<2)*(b<k)*(1-p)+(a+b==k+k))^n)[k,1]
```
# Python (Numpy), 104 bytes
Noone has the markov method yet:
The states are the number of consecutive heads starting at state 0, with the final state as state k. State i (i < k) goes to state i+1 with probability p and state 0 with probability 1-p. State k always goes to state k. The matrix is:
\$
\begin{bmatrix}
1 - p & 1 - p & 1 - p & \dots & 1 - p & 0 \\
p & 0 & 0 & \dots & 0 & 0 \\
0 & p & 0 & \dots & 0 & 0 \\
\dots & \dots & \dots & \dots & \dots & \dots \\
\dots & \dots & \dots & \dots & \dots & \dots \\
0 & 0 & 0 & \dots & p & 1 \\
\end{bmatrix}
\$
Taking this matrix to the nth power and multiplying it by the vector \$\left[1, 0, 0, \dots, 0 \right]^T \$ gives the answer.
This [solution](https://ato.pxeger.com/run?1=RY1NCsIwEIXX5hRZJvaHBARFyN47lCBd9Ce0kwwxRetV3HSjd-ptTLXQ4Q3fvPcW8_rgGFpnp_lSewfUDoAjNYDOB7onW5b3xpZ9s1XEUkWliEO6eB0EwQiRH99DqLPT3IJ6Vt7dGOsSmcblnNTOU0ONpb60TcU6fiY7KIQujFYyw8WYRP4sEig6HaUkQW9sYFAGbx5XdPfKM0gtX3qh-f_ftGLlFw) is not an clean mathematical sum but it is much more computationally efficient then the sum.
```
m=zeros((k+1,k+1))
for i in range(k):
m[0][i]=1-p
m[i+1][i]=p
m[k][k]=1
print(matrix_power(m,n)[k][0])
```
[Answer]
# Desmos, 80 bytes
```
P(p,k,n)=∑_{j=1}^{n/k}-(-1)^j(p+(n-jk+1)(1-p)/j)nCr(n-jk,j-1)p^{jk}(1-p)^{j-1}
```
[Try it on Desmos](https://www.desmos.com/calculator/on5h94g72s) or [prettified](https://www.desmos.com/calculator/pgfnarlcg3).
Thanks to Kevin Cruijssen for finding this formula.
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 133 bytes
```
[| n k p | n k /i [1,b] [| j | -1 j 1 + ^ n j k * - :> z z 1 + j
/ 1 p - * p + z j 1 - nCk p j k * ^ * 1 p - j 1 - ^ * * * ] map Σ ]
```
[Try it online!](https://tio.run/##PY/BTsMwDIbvfYr/vNGuZWISQ@LCAXHhgjhVnZSFdKTtnJCkBxh7Gt6HVypOMyErdv7vty25FTIYN72@PD0/btErR2rAYKQYPI4ivM@paEeSQRtKrJDmuNckeFDLC3KCDuryH0lL86bg1ceoSDK2ToXwaZ2mgLssO@GEqsQaZXGD8yxKbFht/tUtq2tW56n@BqGHRaorjbq62jdg3jHLKy4Vltix3XHDAjm29/jiiLjLVlwtwwXnJdPYnoMe4s40sOOXepIXdYyG77H4/UEz1Wi182HNjI@xxqvZ80HIvpj@AA "Factor – Try It Online")
Translation of the formula given in Kevin Cruijssen's [05AB1E answer](https://codegolf.stackexchange.com/a/249334/97916).
[Answer]
# [R](https://www.r-project.org/), 70 bytes
```
`[`=function(k,n,p)`if`(n<k,0,(1-p*(n>k))*(1-k[n-k-1,p])*p^k+k[n-1,p])
```
[Try it online!](https://tio.run/##lY/BisIwEIbvfYqBvSTtVNqSRA/WFxFtQ9fQEJmEqohPX5suC6Ldw16G@ecf/m9mGF3Tn/T3pbHU6Gbw93ps921tbtRdrSfmkDDw1pqW0dZhgazMQ8po5zhPp97tKXd5ieHA03B0WdSzGr@g6zV1J/AGKpghYAk0TBC422sPns6PyTJnGy5xS4PRdoDOT2s1FKtKJu/XsQorXEmeJK/xcjFe/Z0sjzKLVc2qEGqzXmBJVJ8s8X@WyH6Iscyjcukz8Uv7cBSK6IxP "R – Try It Online")
Port of [@loopy walt's Python answer](https://codegolf.stackexchange.com/a/249360/55372).
For different approaches in [R](https://www.r-project.org/) see [@Dominic van Essen's answer](https://codegolf.stackexchange.com/a/249333/55372).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
NθNηNζIΣEΦEX²θ⍘ι²№ι×1η×XζΣιX⁻¹ζ⁻θΣι
```
[Try it online!](https://tio.run/##XYzLCsIwEEX3@YrQ1QRGaSuuurNQcFEp1B@IpdhA01cShf58nBAQcVZzztw73SC3bpaj99dpcfbm9KPfYBUF@@Xhj3fiZlOThVIaC63TUMsFKjVauoa1md@05chXgfwiTd9ayj9BIc8FqXJ21Ca6K90bSLIE@SDCJYrY35GH3yr4aGo1OQMZ8p1UhPUbilN4n6XsxNLj2R9e4wc "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Brute force approach.
```
NθNηNζ
```
Input `n`, `k` and `p`.
```
EX²θ⍘ι²
```
Get all of the binary numbers up to `2ⁿ`.
```
Φ...№ι×1η
```
Keep only those with `k` consecutive heads, I mean `1`s.
```
E...×XζΣιX⁻¹ζ⁻θΣι
```
Compute their probabilities, which is `pⁱ(1-p)ⁿ⁻ⁱ`, where `i` is the number of `1`s in each relevant row.
```
IΣ...
```
Output the grand total.
A 40-byte port of @dancxviii's approach is much more efficient:
```
Nθ≔E⊕N¬ιηFN«≔⊟ηζ≔⁺⟦×Ση⁻¹θ⟧×ηθη⊞η⁺ζ⊟η»I⊟η
```
[Try it online!](https://tio.run/##XY09D4IwEIZn@is6XhM0sLA4GScGCIluxqFitU1ogX44YPzttRRDjNPdPe/HtZzqtqed96UanK2dvDINI9mhvTHioaCiA5Sq1UwyZdkNfm2EpLjuLYh54SFz7zX@c@AXSr5VTT8AD84pOFfWOQPnk5DMwNHJqFdCBZineCTkkuJF5PFc3iSNM3wmMT2FGZtJkN6o0UJZOFBjYcXeZ9sCFSjPMr95dh8 "Charcoal – Try It Online") Link is to verbose version of code. Takes inputs in the order `p`, `k`, `n`. Expects `k>1` (+1 byte to support `k=1`). Explanation:
```
Nθ
```
Input `p`.
```
≔E⊕N¬ιη
```
Create an array of `1` `1` and `k` `0`s.
```
FN«
```
Repeat `n` times.
```
≔⊟ηζ
```
Remove the last entry of the array.
```
≔⁺⟦×Ση⁻¹θ⟧×ηθη
```
Multiply the array by `p`, then prefix the sum of the array multiplied by `1-p`.
```
⊞η⁺ζ⊟η
```
Add the previous last entry to the current last entry.
```
»I⊟η
```
Output the last entry in the array.
I had been planning on working out how to solve the problem using dynamic programming but I'm pretty sure it would have resulted in the same algorithm.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~30~~ ~~19~~ 17 bytes
```
ṁoΠm≠²fö≥⁰▲mΣgπḋ2
```
[Try it online!](https://tio.run/##ATIAzf9odXNr///huYFvzqBt4omgwrJmw7biiaXigbDilrJtzqNnz4DhuIsy////MS8y/zX/Ng "Husk – Try It Online")
Port of [my R answer](https://codegolf.stackexchange.com/a/249333/95126).
Input is arg1=p, arg2=k, arg3=n.
```
πḋ2 # cartesian arg-3-th power of binary digits of 2
# so: all possible combinations of n heads/tails;
fö # now consider only those with runs: filter by
▲ # the maximum of
mΣg # the sums of each group of identical elements
≥⁰ # is greater than or equal to arg-2;
# now convert the 1s & 0s to probabilities:
mo -² # subtract the probability of heads from each
a # and get the absolute values
# so 1s become (1-p) and 0s become p;
ṁo # finally map across each group & sum the result
Π # product of the probabilities
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 59 bytes
```
kpIf[#>=k,(1-Boole[#>k]p)(1-#0[#-k-1])p^k+#0[#-1],0]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P/v9pIUFQOyZFq1sZ5uto2Go65Sfn5MK5GXHFmgCucoG0cq62bqGsZoFcdnaYJ5hrI5BrNr/gKLMvBIFB4W0aOPYaAM909hoQ4PY/wA "Wolfram Language (Mathematica) – Try It Online")
Port of Python. Takes `f(k)(p)(n)`.
[Answer]
# [J](http://jsoftware.com/), 49 bytes
```
1 :'0{_1{[:+/ .*^:(u-1)~(1,~]#0:),.~(*=@i.),~1-['
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRWs1A2q4w2ro6209RX0tOKsNEp1DTXrNAx16mKVDaw0dfTqNLRsHTL1NHXqDHWj1f9rcqUmZ@QrGOiZKmgYGiikaSoYw0TMQCJgITOYkBFcyPI/AA "J – Try It Online")
Almost identical to dancxviii's Markov chain approach.
] |
[Question]
[
[Related](https://codegolf.stackexchange.com/questions/246025/average-ignorant-sets-of-integers).
Given a list of 3 or more positive integers, remove every number X for which there is another number Y in the list and the average of X and Y is also in the list. In other words, if X, Y, and the average of X and Y are all in the input, neither X nor Y should appear in the output.
Note: Pairs of numbers are not successively removed from the list, rather all at once. This avoids ambiguity. A pair of numbers whose average is in the list will be removed even if one or both of the numbers are already part of another such pair.
The average of two numbers is their sum divided by two.
Examples:
```
input => output
explanation
[1, 2, 3] => [2]
1 and 3 are removed because their average (2) is in the list.
[1, 2, 3, 4] => []
1 and 3 are removed because their average (2) is in the list,
2 and 4 are removed because their average (3) is in the list.
[1, 3, 4, 5] => [4]
1 and 5 are removed because their average (3) is in the list,
3 and 5 are removed because their average (4) is in the list.
[1, 5, 10, 20, 40] => [1, 5, 10, 20, 40]
No numbers are removed; No pair of numbers also has their average in the list.
[1, 5, 6, 10] => [1, 5, 6, 10]
[1, 2, 3, 4, 10, 52, 100, 200] => [10, 52, 200]
[1, 2, 3, 5, 8, 13, 21, 34] => []
```
You may assume numbers are given in ascending order with no duplicates.
[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") Shortest code wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 7 bytes
```
+HfḊʋÐḟ
```
[Try it online!](https://tio.run/##y0rNyan8/1/bI@3hjq5T3YcnPNwx///hdm/NyP//ow11FIx0FIxjdRRgTB0FEygPxNRRMIXyTHUUDA2ASoDYxAAhZgYSRtUOUWhqBKLBOlDlgZosgFJAlhHIEpNYAA "Jelly – Try It Online")
```
Ðḟ Remove elements for which
+ that element plus each element of the list
H halved
Ḋ has more than one element
f ʋ after being filtered to only elements of the original list.
```
[Answer]
# [J](http://jsoftware.com/), 27 22 15 14 bytes
```
-.&,~:/~*+:-/]
```
[Try it online!](https://tio.run/##XY5BCsIwFET3PcWg0FqbpEmaiKQUioIrceG@K2kRNx5AyNXrb9IKdfFJ8v7MZF7jRmQDGocMDBKOhguc79fLyEXKvCv9vnC87MY8uZ0ELT9t7et261PW9cIHAXdtUfqkfzzfGKBQwcAm8a3RBKZRRZBl4G5BMBHuFINlUJJB0xiZz6I/vFIfps1KGEjUKAmrySV/e81QUUaMs3o6Q@5sMHPRWH5ddTHTF0fy0U0Tq8z4BQ "J – Try It Online")
Consider `1 3 4 5`.
* `+:-/]` We note that if `c = (a + b)/2`, then `2c - a = b`. So we can double the input,
and create a subtraction table between that doubled input and the original input:
```
1 _1 _2 _3
5 3 2 1
7 5 4 3
9 7 6 5
```
Now any element in that table not on the diagonal is the `a` or `b` giving rise to
a `c` in the original list, and thus invalid.
* `~:/~*` So zero out the diagonal:
```
0 _1 _2 _3
5 0 2 1
7 5 0 3
9 7 6 0
```
* `-.&,` Flatten, and then remove all the table elements from the original list:
```
4
```
[Answer]
# [R](https://www.r-project.org), ~~48~~ 46 bytes
```
\(v)v[!v%in%combn(v,2)[,combn(v,2,mean)%in%v]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY39WI0yjTLohXLVDPzVJPzc5PyNMp0jDSjdeBsndzUxDxNkHRZbCxU15c0jWQNQx0FIx0FY01NZQVbO4Voo1guJFEdBROYBFwcJKijYAoTN4FLmOooGBoA9QGxiQFMGl0cWbUZSAJVIVgI3QkQ_aZGIBpsEEITVBwohKYJaJYFUD2QZQRyM8IbEL8vWAChAQ)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 17 bytes
```
{x^/x+(x-\:x)^'0}
```
[Try it online!](https://ngn.codeberg.page/k#eJx1kd1uwyAMhe95CkeREsiPDDSZJrZMfY+mVLnJM3jK0mevoWnSrJuEMJzPHIwZ3UQeqZRU946Uz/UsxOim6Qdx6NDZYnDMvpXXM7oTnS80R24+08EPPnDGOyal6WpMc98baQvVU61ylf5mZW/Taod2pFbRcmF0zExXIuZD17v8fim6lb2aRpQl+GoaogvnMkr+OcdVFl8en2tcnsa9ktcuJVXUoQBbbPJD4B5uogzC0tlVpZKVE33QObZ7/PMLwICFwyNCE1ccoY2rFowGq6HRy/aNhS070NbyHJI2vYV3MAew7NQ8JbPlsTICRWVFokXViN0Fq/3dNBgmYdwA8bGKRg==)
Dang, [Jonah's solution](https://codegolf.stackexchange.com/a/248996/78410) translates very well to K.
```
{x^/x+(x-\:x)^'0}
(x-\:x) self difference table
^'0 remove zeros from each row
x+ add i-th item of x to i-th row of matrix above
x^/ seeded reduce: remove all numbers that appear
in the matrix from x
```
---
# [K (ngn/k)](https://codeberg.org/ngn/k), 22 bytes
```
{((*>^/^\+\2#,x-)')_x}
```
[Try it online!](https://ngn.codeberg.page/k#eJx1kF0OwiAMgN85RZclG8wtBRzGEGe8h4jhZWfATO8uxZ85jQmhpV/7NWG0E+fN3qN3K6fLNnaiFud4Y2y003RFDANa3QTLY3cRXt7QHuOJGoirXRl88MQTXjDO1dBhWXunuG6Ey+Lym807X2hBOpGVTxYPlRpWiHUYnK0fS9G+2a80o6rAXylFS3NVLP7M/f0XUKBh/YrQ5yxFMDkzoCRoCb18PjepMHcTNTrd1DTXDWxBrUEnU//RbBiyVrNCsrZnC/fb/PCRq6BzB9ykakw=)
I think this idea is not touched well yet (or at least not explained well in other answers).
The idea here is: given an element E of list X, E is to be removed from the result if:
* there exists two other elements E2 and E3 of X such that E2 = (E + E3)/2
* ⇔ E, E2, E3 forms an arithmetic progression
* ⇔ E2 = E + k, E3 = E + 2k for some nonzero k
* ⇔ X-E (elementwise) contains k and 2k for some nonzero k
```
{((*>^/^\+\2#,x-)')_x}
{(( )')_x} apply to each element E and keep those that gives 0
x- L = X-E
+\2#, (L, 2L)
^/^\ set intersection of L and 2L
*> first of grade down (index of max)
all k's (including zero) are found in increasing order;
index of max is nonzero iff there exist some nonzero k's
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ʒ+;Ãg
```
Byte-count halved thanks to *@Steffan* by porting [*@UnrelatedString*'s Jelly answer](https://codegolf.stackexchange.com/a/249019/52210).
[Try it online](https://tio.run/##yy9OTMpM/f//1CRt68PN6f//RxvqKBjpKBjrKJjoKBga6CiYGoFoIMPIwCAWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLoZX/T006tM6lSNv6cHP6/1qd/9HRhjpGOsaxOhBaxwTMAtI6pmCWqY6hgY6RgY6JAZRrBhRAqAbJmhoCSZAihLipjoWOobGOEdAkk9hYAA).
**Explanation:**
```
ʒ # Filter the (implicit) input-list by:
+ # Add the current value to each in the (implicit) input-list
; # Halve each
à # Only keep those values from the (implicit) input-list
g # Pop and push the length to get the amount of remaining values
# (only 1 is truthy in 05AB1E)
# (after which the filtered result is output implicitly)
```
[Answer]
# [Haskell](https://www.haskell.org), 39 bytes
```
f a=[x|x<-a,[1]==[1|z<-a,elem(2*z-x)a]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN9XTFBJtoytqKmx0E3WiDWNtbaMNa6pAnNSc1FwNI60q3QrNxNhYqPLO3MTMPAVbhZR8LgWFgqLMvBIFFYU0hWhDHWMdEx3TWHRRUx0zHUMDDGEFIx0FYx0FEx0FQwMdBVMjEA1kGBngVGqqo2ABVAVkGQHFjE2gDoL5AwA)
ovs and Wheat Wizard each saved a byte. Thanks!
[Answer]
# JavaScript (ES6), 50 bytes
```
a=>a.filter(x=>!a.some(y=>x-y&&a.includes(y*2-x)))
```
[Try it online!](https://tio.run/##fY5BDsIgEEX3ngI3DRhKWizGDVzEuJi01NQgmFINnB5Bt7WLyUzyXv78O7zB9/P0XGrrBp1GmUAqYONkFj3jINUemHcPjaNUoY5VBWyyvXkN2uN44HUghKTeWe@MZsbd8IgvLUWcouOVkN06oahbh4VQJNahoKhtckCervmrnIq1@foXI3jZ37xNPUees5kvXgqW4ukD "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input
a.filter(x => // for each value x in a[]:
!a.some(y => // test whether there is a value y in a[]:
x - y && // which is not equal to x
a.includes( // and is the average of x and
y * 2 - x // another value 2y - x that exists in a[]
) //
) // end of some()
) // end of filter()
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 20 bytes
```
{x^/a*~=#a:-x-\:2*x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6quiNNP1KqzVU600q3QjbEy0qqo5eJKUzBUMFIwhtEKJmAWkFYwBbNMFQwNFIwMFEwMoFwzoABCNUjW1AhIghQhxE0VLBQMjRWMgCaZAABf3xgV)
Switched to @Jonah's approach.
-1 byte thanks to @ovs!
## Explanation
Input is *x*.
* `a:-x-\:2*x` subtraction table of 2*x* - *x* stored as `a`
* `a*~=#` multiply *a* by inverse of eye of *a* (i.e. zero out *a*'s diagonals)
* `x^/` remove table elements from *x*
[Answer]
# [Scala](http://www.scala-lang.org/), 52 bytes
```
s=>s.filter(i=>s.forall(j=>i==j|s.forall(_*2!=i+j)))
```
[Try it online!](https://tio.run/##dZHBTsMwDIbvewpv2qEBD21di9BEKnHggDhMGuKEEMq2FKUKXWmyCQn27MVJuzLKuESO/8@/LdushBbVZpnJlYXHXOxkKV6lWGppQH5Yma8N3BQFfPZ6AGuZQjqDB/n@dJfbZ@DJUVwZnpiLVGkry0D5eFMKrYOMJ4rz7KtNvJyFfa7OM8ZYBbATmjqJt8K15M4woFYAgYsmGOIUY4Y@HzKGHe1/BaNG60gktIZRR4txMsZwjNG4AX6luuwlSUec/54YwxnEIb3Ohwq85FPu@7cgxiucTDGkUaOaZowY5i5AG6RT@AKVF1uLtLqCTifXDK5H7R49sdlaImilac06k31TXZQqtzqvNw2gUggOOP@xbFQAM5jfwwyG3gdGCQxretAQUht5BN8uFvPFKR76HIYH@7rYT9XbV98 "Scala – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~12~~ 10 bytes
```
f(εn¹Mo½+¹
```
[Try it online!](https://tio.run/##yygtzv7/P03j3Na8Qzt98w/t1T608////9GGOkY6xjomOoYGOqZGQNJAx8jAIBYA "Husk – Try It Online")
```
f( ) # filter the input to keep only elements that satisfy:
½+ # half the sum
Mo ¹ # with each other element of the input
ε # has only 1 element
n¹ # shared with any elements of the input
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~9~~ 7 bytes
```
'?+½?↔₃
```
[Try it Online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCInPyvCvT/ihpTigoMiLCIiLCJbMSwgMiwgMywgNCwgMTAsIDUyLCAxMDAsIDIwMF0iXQ==) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJhUGoiLCJ2aMabwqMiLCInwqUrwr3CpeKGlOKCgyIsIjs7wqhad0o7Osabw7figbxg4p2M4pyFYGk7wqhaJMO3JF9cImAgPT4gYGpcXCBKcCIsIlsxLCAyLCAzXSwgWzJdXG5bMSwgMiwgMywgNF0sIFtdXG5bMSwgMywgNCwgNV0sIFs0XVxuWzEsIDUsIDEwLCAyMCwgNDBdLCBbMSwgNSwgMTAsIDIwLCA0MF1cblsxLCA1LCA2LCAxMF0sIFsxLCA1LCA2LCAxMF1cblsxLCAyLCAzLCA0LCAxMCwgNTIsIDEwMCwgMjAwXSwgWzEwLCA1MiwgMjAwXVxuWzEsIDIsIDMsIDUsIDgsIDEzLCAyMSwgMzRdLCBbXSJd).
*-2 bytes by porting Unrelated String's Jelly answer*
## How?
```
'?+½?↔₃
' # Filter for:
?+ # Add the input (vectorizes)
½ # Halve each
?↔ # Remove elements that are not in the input
₃ # Is the length equal to 1?
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
```
->l{l-l.permutation(2).map{|a,b|a*2-b}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOkc3R68gtSi3tCSxJDM/T8NIUy83saC6JlEnqSZRy0g3qbb2f4FCWnS0oY6RjnFsLBeUo2Cko2Cso2Cio2BooKNgagSigQwjAwOgmv8A "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/)
## 58 bytes with unordered sets
*Thanx to [Jitse](https://codegolf.stackexchange.com/users/87681/jitse)!*
```
lambda l:{*l}-{a for a in l for b in{*l}-{a}if(a+b)/2in l}
```
[Try it online!](https://tio.run/##VY3RCsIgFIav6ynOpZbR5jRi0JMsL5SQBHNjeBPDZzfPMmIX4nfO9/@c6R2fY@iyvd2z1y/z0OD75eDTadFgxxk0uAB@RVOwquQs0UdDzxxtyqgjJoehZcAZdIrBDxmIOiEykHWSDNqmRMoTzX93wfW2/g1Kjv/a2PpSuhZViOMRoVS/302zC5FYEinNHw "Python 3 – Try It Online")
## ~~62~~ 61 bytes with ordered lists
```
lambda l:[a for a in l if{(a+b)/2in l for b in{*l}-{a}}=={0}]
```
[Try it online!](https://tio.run/##VY3NCsMgEITP7VPsUVtLjfmhBHwS60Ep0oBNQvBSxGe3bppSclh2Zr4ddn6H5zTW2cl79uZlHwZ8rwy4aQEDwwgeBheJOVt6FatFYguJJ58u0aQkZeRJZ8wDNpSqGAgGtWbwkwyazaFk0G6uZVDxclKm4f@sw3hf/x62Avfa2PNSuhVUlMAnjdb98TAvwxiII4HS/AE "Python 3 – Try It Online")
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 7 bytes (14 nibbles)
```
|$~<<`&*2@+@_
```
```
|$~<<`&*2@+@_
| # filter
$ # input list
~ # keeping only elements that are falsy for
<< # discard first element of
`& # common elements of
*2@ # twice the input list
# and
+@_ # sum of this element and the input list
```
[](https://i.stack.imgur.com/D5Mig.png)
---
Works on the basis that if the average of X and Y is Z, then X+Y=2\*Z. So we just remove all Xs whenever there's a Y that when added to it gives twice one of the other elements of the input.
Step-by-step for input of `[1, 2, 3, 4, 10, 52, 100, 200]`:
```
|$ # for each element x in input=[1, 2, 3, 4, 10, 52, 100, 200]
~ # keep it if the following function returns an empty list (falsy):
`& # find elements in common between:
*2@ # double the input: [2, 4, 6, 8, 20, 104, 200, 400]
# and:
+@_ # input + x:
# so, when x=1 => [2, 3, 4, 5, 11, 53, 101, 201]
# common elements = [2, 4]
# when x=10 => [11, 12, 13, 14, 20, 62, 110, 210]
# common elements = [20]
<< # and remove the first element:
# so, when x=1 => [4] => so won't keep it
# when x=10 => [] => so we'll keep it
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒcSe¥ƇḤFḟ@
```
A monadic Link that accepts a list of positive integers and yields the filtered list.
**[Try it online!](https://tio.run/##y0rNyan8///opOTg1ENLj7U/3LHE7eGO@Q7///@PNtRRMNJRMNZRMNFRMDTQUTA1AtFAhpGBQSwA "Jelly – Try It Online")**
### How?
```
ŒcSe¥ƇḤFḟ@ - Link: list L
Œc - ordered pairs (L)
Ḥ - double (L) (vectorises)
Ƈ - filter the pairs keeping those for which:
¥ - last two links as a dyad - f(pair, doubled L)
S - sum (pair)
e - exists in (doubled L)?
F - flatten (this list of pairs whose sum is in the doubled L)
@ - with swapped arguments:
ḟ - filter discard (take L and remove the pair elements)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~12~~ 10 bytes
```
-Qs-L-LydQ
```
[Try it online!](https://tio.run/##K6gsyfj/XzewWNdH16cyJfD//2hDHQVjHQUTHQXTWAA "Pyth – Try It Online") or [Verify all test cases](https://tio.run/##K6gsyfiv/F83sFjXR9enMiUwUMHW9f//aEMdBSMdBeNYLhhLR8EEwgGxdBRMIRxTHQVDA6ACIDYxgAuZgURRtEKUmRqBaLB6FGmgFgugDJBlBLLAJBYA "Pyth – Try It Online")
```
-Qs-L-LydQ
L (Q) # Left map over the implicit input with variable `d`:
L Q # Left map over the input with variable `k`:
- yd # d*2 - k
- # Remove d from the resulting list
s # Flatten
-Q # Remove elements of the resulting list from the input
```
### 12-byte solutions
```
fqFf}-yYTQQQ
```
```
-Qsf}.OT-QT*
```
[Answer]
# [Factor](https://factorcode.org) + `math.unicode`, ~~57~~ ~~51~~ 50 bytes
```
[| s | s [ s n+v 2 v/n s ∩ length 1 > ] reject ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XU-7bsJAEOz9FdNHEPvACAUpbURDE6VCFCezJkb22dydLfHq-QcaN0TKJ9Gm5CvYixvbK-1jZnd2tdefWEY21_X98fU5X3y8IZP2e1iqJMrXhEKTtftCJ8rC0K4kFZFBrPfNWEVOa7AhRVqmyUHaJFfmv4k0j2RqMPO8owe2IwIIjHDuoHELOxS2cIjAh_Ax9jvkxNH9LUyFgqMT9LshpghGEHzBnTvfShsPpnexPMHA-ZJdvVQ8XL0qrv8uv0hJbfiLAO9YQdOWX8WqUd4yWWDY1HXd5Cc)
[Answer]
# [Desmos](https://desmos.com/calculator), ~~80~~ 76 bytes
```
f(l)=l[[[(.5k-l)^2.minfork=l[m]+l[(L-m)^2>0]].minform=L]>0]
L=[1...l.length]
```
This is probably a terrible way of doing it, but whatever. Also, the "words" `minfork` and `minform` that appear in the code are very much intentional, though you will quickly see what they actually parse as in the graph links :P.
[Try It On Desmos!](https://www.desmos.com/calculator/xhboevghmj)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/hflewhjjth)
[Answer]
# [T-SQL] 111 bytes
```
DELETE FROM T WHERE EXISTS(Select*From T Y Join T Z ON T.ID NOT IN(Y.ID,Z.ID)And Y.ID<>Z.ID And T.N+Y.N=2*Z.ID)
```
Formatted:
```
DELETE FROM T
WHERE EXISTS(
Select *
From T as Y
Join T as Z
ON T.ID NOT IN(Y.ID, Z.ID)
And Y.ID <> Z.ID
And T.N+Y.N = 2*Z.ID)
```
I *could* save one more byte by using the excremental SQL-89 joins, but my soul is worth more than one byte.
[Answer]
# [Arturo](https://arturo-lang.io), 41 bytes
```
$[a][a--map permutate.by:2a'p[-p\0*2p\1]]
```
[Try it](http://arturo-lang.io/playground?I0bU8I)
Port of G B's [Ruby answer](https://codegolf.stackexchange.com/a/249099/97916).
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 14\log\_{256}(96)\approx \$ 11.52 bytes
```
gz0+2/z0sAqS2<
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhbr0qsMtI30qwyKHQuDjWwgglC5BWuiDXUUjHUUTHQUTGMhYgA)
#### Explanation
```
g # Filter:
z0+ # Add input
2/ # Halve each
z0 # Push input again
sAq # Each is in the input?
S2< # Sum is less than 2?
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 16 bytes
```
ĐĐ2*⇹ɐ-ĐŁřĐɐ≠*Ƒ\
```
[Try it online!](https://tio.run/##AS0A0v9weXT//8SQxJAyKuKHucmQLcSQxYHFmcSQyZDiiaAqxpFc//9bMSwyLDMsNF0 "Pyt – Try It Online")
Port of [Jonah's J answer](https://codegolf.stackexchange.com/a/248996/116013)
[Answer]
# [Julia 1.0](http://julialang.org/), 32 bytes
```
!l=l[l.|>i->sum(i.+l.∈[2l])<2]
```
[Try it online!](https://tio.run/##ZY5RCsIwDED/d4rsr8M6XN3EDze8gCcY@wisQiVWaaf44QE8pxeZrXEwsFCavLykOd3IYPEYx5Rqail/NmbZ@NtZmHxB@fv1ahV12U514/HiwICx4DT2ZKz2IksgHJQaatB3JHHQA@ZXdF4Lk3H16owdyAqEuoEUGe7Re@2GkEMdWhNt@7EtJCgJ6y6KreqSCUgomTGKuYSKUcmsklCsgh1uueLKH53ETaRzh8H8O@6rVHy/Ayb/RyOY@WHGNqghUnG/adsP "Julia 1.0 – Try It Online")
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 68 bytes
```
($a=$args)|?{$_-notin($a|%{$a-ne($c=$_)|%{$_,$c*(($_+$c)/2-in$a)}})}
```
[Try it online!](https://tio.run/##lU/RSsMwFH3vV1zGVRJNcKub@FIsFH3wRXF7Eyk1Zm6yNbPJVGj77TVJtyLbHmagNPece07OWalvWeiZXCy4UIVscBqVDcEswqx417S6KTHluTLz3ILVSYkZzyVBEWFK3ZgyFGeEYHqOgl6EfJ5jRuua1k0dBDEJwB4GMYnJgEHI4JK6KaR0n2Ew9OQu5wgGI88Nd8kRg0Hf6u037PuVPXBfceX4P8vtfDhSazUK3d97boQb0M0Hhdb22mrsLXQdumoUKrhTxW0mZvzh9UMKA6XXo5HaMED5s7KgfIMIMG2ZQur1wljgFKcQuz2PPz@Ok7U2atn6vMStkTvjtRBSa3@PgGwdKhirwmzfrSBR@ZcszETxe61y4IlaruyqpsDlp5V1WY4Wdgl6ExsTkkzLnmviQh/t0pk8tbE3Nf7bwtvUQd38Ag "PowerShell Core – Try It Online")
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 26 bytes
```
Js12CB:U_f{avg1j~[}g1jFL\\
```
[Try it online!](https://tio.run/##SyotykktLixN/V@tZGunZG2tG1uUqFmS8t@r2NDI2ckqND6tOrEs3TCrLroWSLr5xMT8rw3P@R9tqKNgpKNgHKtga6cQbRTLBRPQUTCBiMUqgMVAAjoKphAxE4g6Ux0FQwOgciA2MYDIYIjCFJqBRJHVQASQ7YPoMzUC0WADYOqhoiABJPVAMyyASoEsI5D7YM4FAA "Burlesque – Try It Online")
Takes input as block of doubles
```
J # Duplicate
s1 # Store as 1
2CB # Combinations of length 2
:U_ # Filter for unique (guaranteed safe by no dups)
f{avg1j~[} # Filter for average contained in original list (1)
g1 # Get 1
j # Reorder stack
FL # Flatten
\\ # Remove elements contained in (1) also in averages
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
IΦθ¬⊙θ∧⁻κμ№⊗θ⁺ιλ
```
[Try it online!](https://tio.run/##LYvBCoMwEER/ZY8rbCGm9tSTWLy1eBcPqQoN3SYYk4Jfv0ZwLvN4w4wfE0ZvWKQL1kVszBqxtRzngAvBy0es3XZg7SZ8WpdW/BL8CoLGp3x4@PTmecIlm47zagm4OHMX6fuSQBNcCSqCUhHc9NEZtFLDIJc/7w "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input list
Φ Filtered where
θ Input list
¬⊙ No elements satisfy
⁻κμ Indices differ
∧ Logical And
θ Input list
⊗ Doubled
№ Does not contain
⁺ιλ Sum of current elements
I Cast to string
Implicitly print
```
[Answer]
# [Haskell](https://www.haskell.org), 67 bytes
```
f a=[z|z<-a,not$elem z[x|x<-a,y<-a,x/=y,even$x+y,div(x+y)2`elem`a]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN53TFBJto6tqqmx0E3Xy8ktUUnNScxWqoitqKkAilSCiQt-2Uie1LDVPpUK7Uicls0wDSGsaJYCUJiTGxkKMgpoIMxkA)
[Answer]
# [Zsh](https://www.zsh.org/), 75 bytes
```
for x;for y;((s=x+y,s%2||x==y))||a+=(${=${(M)@:#$[s/2]}:+$x $y})
<<<${@:|a}
```
[Try it online!](https://tio.run/##bZDBbsIwEETv/oqpcNUEkAoBpAqIxKGH9tBjTxVSXLIBqyRGsQNJCd@e2gGKVPXitXbXM/P8rTdN4vlek6gc5cyd1czzdFj2qr6@D@q6DMPK9@ta9EKPH0N@9N78xbTDP/RjsDxNe7wEr04@m8/n/LiY1uLU@IwlGCLA@FJH13rp2IpJe5tgOEAwwHhwW3GtSWBPN7n1J3jCcITAPh8zRqU0jHXwrEhnDwYHlX/1IbIYZkPISWiV4bCpsFLFNsYnodCUFFs4xLXaJjJbT9l/1GloyW7sdX3HFx/eq8/T5e8/OGbf2b9QToh4GkFqULmzASiGtXYpuruc9lIVuou92BYElYCnNos1JMTKRmj3RC7NJiUjV2cJLVVmtd@1WziLZ9qQiJ1AtItazKi/C@3kL55MUKkCGdkYRkGLPbUe1yiQhnJhrEPzAw "Zsh – Try It Online")
Not as compact as I was expecting...
```
for x;for y # for $x, $y in the Cartesian product of the list with itself
((s=x+y,s%2||x==y)) || # test if the sum is odd or x == y. If not,
a+=(${=${(M)@:#$[s/2]}:+$x $y})
# ${(M)@:#$[s/2]} # substitute the average if found in $@
# ${ :+$x $y} # if non-empty, substitute "$x $y"
# a+=(${= }) # split on spaces and add it to $a
<<<${@:|a} # set difference
```
[Answer]
# [Python](https://www.python.org) + NumPy, 50 bytes
```
lambda a:a[((a+[[a]]).T==a+a[:,1>0]).sum((0,1))<2]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY5BCsIwEEX3PcUsExxLkrZSivUU7mIWI1Is2DTEFuxZ3BRE8Urexth24-q9_z8Dc3-5oTu3dnxU5eHZd9U6_6gLNccTARWkGaOV1mQMj_dlSSvSBcqdCPHaN4wJlJxvlVku33XjWt-B7Rs3AF3BuqhqPdwAagtaosLE4ExMJwvEbLIMpUAlMBVThAxhgyCXpBAShPRXhEn9GESJvzmc5GEJpkKXpKaIwPnadqxi1sXkPQ3sxjmf_x3HmV8)
Straightforward masking with a few tricks to shorten the required indexing operations without having to explicitly import numpy.
#### How?
Construct 3d table of *z,y,x* each running through the input list *a*. Each cell is True if *2z=y+x* and False otherwise. Fixing *x=a* count solutions *z,y*. If *a* is not part of an averaging pair there is only solution *z=a,y=a*, otherwise there are more. Use boolean indexing to filter *a* accordingly.
`(a+[[a]]).T` is a shorter surrogate for `2*a[:,None,None]` and `a[:,1>0]` is shorter than the more natural `a[:,None]`.
] |
[Question]
[
Say I have a ragged list, like:
```
[
[1, 2],
[3,
[4, 5]
]
]
```
And I want to iterate over each item and delete it one-by-one. However, I don't know the structure of the list.
So, I have to iterate over the list, with the following algorithm:
* Look at the first item of the list.
* If it's a list, concatenate it to the start of the rest of the list.
* Else, delete it.
For example, with the above example `[[1, 2], [3, [4, 5]]]`:
* `[1, 2]` is a list. Concatenate it - `[1, 2, [3, [4, 5]]]`
* `1` is a number. Delete it - `[2, [3, [4, 5]]]`
* `2` is a number. Delete it - `[[3, [4, 5]]]`
* `[3, [4, 5]]` is a list. Concatenate it - `[3, [4, 5]]`
* `3` is a number. Delete it - `[[4, 5]]`
* `[4, 5]` is a list. Concatenate it - `[4, 5]`
* `4` is a number. Delete it - `[5]`
* `5` is a number. Delete it - `[]`
There are no more items left, so our work is done.
Your challenge is to compute the sizes of the lists resulting from applying this. For example, with the above, the list starts with length 2. It then goes to lengths 3, 2, 1, 2, 1, 2, 1, 0.
Standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply - that is, you may take a list \$l\$ and generate all terms, or take a list \$l\$ and a number \$n\$ and calculate the nth or first n terms. Your results may or may not contain the length of the initial list at the start, and the 0 at the end, and you may take \$n\$ 0-indexed or 1-indexed.
Since only the shape of \$l\$ matters, you may take it filled with any consistent value instead of arbitrary integers.
\$l\$ may contain empty lists. In this case, it's concatenated as normal and the length decreases by 1.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
## Testcases
These include the leading length but not the trailing 0. [Reference implementation](https://tio.run/##VY7BCgIxDETv/Yo5bnER19WL4JeUIsJm2UKopY3Ifn1Ne9JDSHjJzCTtsr3iXOtCK4JQfizEJDRwsTcDplhwh/MGny0wgYvSjo/PlCgug87t2CoOK2RPTetO3iIUcCjSBKpTm85xaH26qSWIC/2tO84k7xx7iDEphyjD72fOTSPOfoSbtS4jrt57a2v9Ag)
```
[[1, 2], [3, [4, 5]]] -> [2, 3, 2, 1, 2, 1, 2, 1]
[[6, 3, [1, 3, 4]], 4, [2, 3, 9, [5, 6]]] -> [3, 5, 4, 3, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1]
[3, 4, 5] -> [3, 2, 1]
[[[[[[[[1]]]]]]]] -> [1, 1, 1, 1, 1, 1, 1, 1]
[] -> []
[1, [], 1] -> [3, 2, 1]
[[],[[[]]],[]] -> [3, 2, 2, 2, 1]
```
[Answer]
# [R](https://www.r-project.org), ~~62~~ 61 bytes
*Edit: -1 byte thanks to pajonk*
```
f=\(l)if(h<-length(l))c(h,f(c(if(is.list(g<-el(l)))g,l[-1])))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWN23TbGM0cjQz0zQybHRzUvPSSzKAXM1kjQydNI1kDaB4ZrFeTmZxiUa6jW5qDkhOM10nJ1rXMBbIghqSkmMLVgImDHWMNHXALGMIZaJjClTKVVxSBNTNlQYikNVDFSMJaEKFUDVB7II5HAA)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~27~~ 25 bytes
Anonymous prefix lambda.
```
{×⎕←≢⍵:∇((0≠≡⊃⍵)/⊃⍵),1↓⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/rw9Ed9Ux@1TXjUuehR71arRx3tGhoGjzoXPOpc@KirGSikqQ@ldQwftU0GMmr/pwHVazzq7QNLrHnUu@XQeuNHbROBBgUHOQPJEA/PYM1qqLm9W3XUFR61TQIS3S0KQEGvYH8/iDHq0dGGOgpGsToK0cZAbKKjYBobG6vOBZIw01EAiRmCKZNYoBqgdLQRmGsJZJnqKJjBFBuDJU2hOiHAMBYKwIIQEmhYNNAgw1h1AA "APL (Dyalog Unicode) – Try It Online")
`{`…`}` "dfn"; argument is `⍵`:
 `≢⍵` tally the argument
 `⎕←` print that
‚ÄÉ`√ó`‚ÄÉsignum of that
‚ÄÉ`:`‚ÄÉif 1 (i.e. there's content):
  `1↓⍵` drop the first element of the argument
  `(`…`),` prepend:
   `⊃⍵` the first element of the argument
   `(`…`)/` replicated by (i.e. if the following holds true):
    `⊃⍵` the first element of the argument
    `0≠≡` is its depth different from zero? (i.e. a list)
  `∇` recurse
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes
```
def f(x,*r):print-~len(r);x>{}<f(*x+r);f(*r)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVBLCsIwEN33FENXMzVZpD80ikvvIdqgILWECCmiF3HTjXgaD-BtnPQjOEPyZvLeG5I8Xk3rDuc67brnxRk5_4h9ZcCgF4kl3dhj7eT9VNVoaenX19vKYOJn3DBaGj3v4NlgsiUdgbOtNqGOoPK7qnFaQQT9pFhKGUcsRFQCUhKAGa9cQEEcA1MKCIeqh5xYxDymfbvgqhBQ_tRZzxaTdwgl6D8HdgQejDxUTZ5wi7CHZIbGR00f8gU)
Prints to STDOUT; terminates with an error.
# [Whython](https://github.com/pxeger/whython), 37 bytes
-7 bytes thanks to @ovs
```
def f(x,*r):print(len(r)+1);f(*x+r?r)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVBLCsIwEN33FENBmGnTRfpD48Kd9xBNqCC1hIjtWdx0I97Gvbdx0rSCM0zm8948kjxe92ZwzbUdx-fNmWz9WZ20AYO9SCypzp5bhxfdoqVU0tZg0qd2Z2kmvz15j8mBVATODsr4OgLdH3XnlIwgKMRZlsUUMRNRCshJABYcpYCK2AJSC_BDOaWSmMQ45lO74aoSUP_YxYRWy24wKejfAzonFkYWlcuOv4U_vTNC86uWr_gC)
Despite being Whython, this still also terminates with an error.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~ 55 53 ~~ 52 bytes
*Saved 2 bytes thanks to [@pfg](https://codegolf.stackexchange.com/users/77796/pfg)*
*Saved 1 more byte thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh) and [@pfg](https://codegolf.stackexchange.com/users/77796/pfg)*
```
f=a=>[n=a.length,...n?f(a.shift().concat?.(a)??a):a]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZBLDsIgEIb3noIlJDgJfUVNkIMQFqSW1qSBRfE0brrQQ3kFT-HQ1o0yCc_5_p8Z7g8fLt08P2_R7Q-vykkrz9pLC2Pn-zhwAPDKUQvTcHWRMmiDb21UQC1TyrKTNZv2jZkpjB2MoaeOai04KQwnusRRcVIbYxjb_VINJwkQy1IZFCCri-V4xF3NSZNVlgtZ5zzXEGaLfyJzhQVofFzk_FIXOKfidLJbO_7-2gc)
### Commented
```
f = a => // f is a recursive function taking the input list a[]
[ // build the output:
n = a.length, // append the length of a[] and save it in n
...n ? // if a[] is not empty:
f( // do a recursive call:
a.shift() // extract the leading entry and attempt to
.concat?.(a) // concatenate it with the remaining entries
??a // if it fails, just append a[] (the leading entry
// was not an array)
) // end of recursive call
: // else:
a // stop the recursion and return a[] (which is empty)
] // end of output
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ΔDg,ćDi\ëì
```
A byte is saved by taking the input filled with `1`s instead of positive integers.
Outputs the lengths on separated newlines to STDOUT, including a trailing 0.
[Try it online](https://tio.run/##yy9OTMpM/f//3BSXdJ0j7S6ZMYdXH17z/390tKGOYawOkAQzYmMB) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX2nLpeRfWgLh6fw/N8UlXedIu0tKZszh1YfX/K@tPbTN/n90dLShjmGsDpAEM2JjdRTAQmAuSADORFIAkQKphACQMBgAhSDyQAqqAGg21FQgKxrMBhEA).
**Explanation:**
```
Δ # Loop until the result no longer changes (e.g. until the list is empty):
D # Duplicate the current list
g # Pop and push the length
, # Pop and output this length with trailing newline to STDOUT
ć # Extract head; pop and push remainder-list and first item separately
D # Duplicate this extracted head
i # If it's a 1:
\ # Discard it from the stack
ë # Else (it's a list instead)
ì # Prepend-merge it to the remainder-list
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 24 bytes
```
#'{$[t~*t:*x;!0;t],1_x}\
```
[Try it online!](https://ngn.codeberg.page/k#eJxdT+1ugzAM/J+ncLVJgyoUEhK0EmkvkkUroqFFZWUr2UQ1tc8+89WxOtg4d76zUqQPTz+P2l2XLl22ahEpZyh7ay+vhLgUmfP1lBYA0KpNfVDepsjKSrXqrE6+uRCnPQZcebESIH1fcYiBA7tlZLoRL1GxYkgJXwnlcbytlYQEBTFIEDDVTiJmFr0cZSBV/AfQMRh6/j89jW+gw17WvYf5c63XsZiLaIBHgoRk79xHk4ZhXm/trq6KVeOy/GDbfJ8dd3aV1+/h55dtXFkfm5CL5yTiYensKXPlt63OwdZW1tkgC6qycYRozShwQ0HHmIKCNMZA8AKaU0AIK5tXg4qkZzoh/oRBMerG+TV2kkIyuSAke37eDHbibgFaxz0qb9Jp4xDMjNHTrBfefzg90NjgXZsOu7czFN3Qh2oz5/g0QX4BSgWRIw==)
Output includes the length of the initial list and a 0 at the end.
* `{...}\` set up a scan-converge, seeded with the (implicit) input and run until two successive iterations return the same result
+ `$[t~*t:*x;!0;t]` using `$[c;t;f] cond`, check if the first item is a list or an atom. if it is an atom, return an empty list (`!0`); if it is a list, return the first element of that list
+ `,1_x` append the remainder of the list (dropping the first item)
* `#'` return the number of items in each iteration
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ö┬☻╪<æ·ë97╞φº♠B
```
[Run and debug it](https://staxlang.xyz/#p=99c202d83c91fa893937c6eda70642&i=%5B%5B1,+2%5D,+%5B3,+%5B4,+5%5D%5D%5D%0A%5B%5B6,+3,+%5B1,+3,+4%5D%5D,+4,+%5B2,+3,+9,+%5B5,+6%5D%5D%5D&m=2)
# [Stax](https://github.com/tomtheisen/stax), 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü╜←Φ■Yxbo╟ⁿ▀í▼ε~
```
[Run and debug it](https://staxlang.xyz/#p=81bd1be8fe5978626fc7fcdfa11fee7e&i=%5B%5B1,+2%5D,+%5B3,+%5B4,+5%5D%5D%5D%0A%5B%5B6,+3,+%5B1,+3,+4%5D%5D,+4,+%5B2,+3,+9,+%5B5,+6%5D%5D%5D&m=2)
a generator.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes
```
Print[i+=Length@#-1]#0/@#&[i=1;#]&
```
[Try it online!](https://tio.run/##JYwxC8IwEIX3/o1ABz3Rq2mhSCCLm4PgWDqE0NoMjSDZjvSvx6cO9917d@9udWmZVpeCd2U25f4OMQ1hb25TfKbFqgOP6nS0qh6C4Ysa6zLb3dUvr@3hXdykEmFqMsmZRFObcyaMOoJlQMNrkgayJ2mp@wewQBbiW0xo/LvDHwARoMrlAw "Wolfram Language (Mathematica) – Try It Online")
Prints the lengths. Includes a trailing `0`.
```
Print[i+=Length@#-1]#0/@#&[i=1;#]&
[i=1;#] initialize i=1 before run
#0/@# in depth-first, prefix order:
i+=Length@#-1 add length-1 to i (atoms have length 0)
Print[ ] print i
```
[Answer]
# JavaScript (ES2019), ~~51~~ ~~48~~ 47 bytes
```
i=0;f=(v=[])=>[i+=v.length-!!i,...v.flatMap(f)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWN_UzbQ2s02w1ymyjYzVt7aIztW3L9HJS89JLMnQVFTN19PT0yvTSchJLfBMLNNI0YyHabjGqJ-fnFZcolCrYKpTmpaSmZealpnCBxPJzUvVy8tM10jSio0t1FEpjdRRANIQdCyI0NYlQiEsVVAHMMAQXn06YDixmQgBIGxhgqsBuXDQun4B8ASRBjosGGQcJL1hwAwA)
Input requires `undefined` as leaves. Output includes initial size and trailing `0`.
I assume the output must be a flat array instead of allowing nested array. If nested array is acceptable then there is this 40-byte solution:
```
i=0;f=(v=[])=>[i+=v.length-!!i,v.map(f)]
```
## Algorithm
Instead of implementing the specified process and constructing the intermediate arrays, this submission uses an analytical solution to calculate the output.
Notice that, with the process in the question, each item of the root array is completely deleted before moving on to the next item. Using the original example `[[1,2],[3,[4,5]]`, the `[1,2]` subarray is fully deleted before `[3,[4,5]]` is touched. This means that while processing `[1,2]`, the sizes of the intermediate arrays at each step is the same as those while processing `[1,2]` as a root, but plus 1 because we have to count `[3,[4,5]]`
```
[[1, 2], [3, [4, 5]]]
[1, 2, [3, [4, 5]]] (size: 3) | [1,2] (size: 2)
[2, [3, [4, 5]]] (size: 2) | [2] (size: 1)
[[3, [4, 5]]] (size: 1) | [] (size: 0)
```
Take another example from the test cases
```
[[6, 3, [1, 3, 4]], 4, [2, 3, 9, [5, 6]]]
[6, 3, [1, 3, 4], 4, [2, 3, 9, [5, 6]]] (size: 5) | [6, 3, [1, 3, 4]] (size: 3)
[3, [1, 3, 4], 4, [2, 3, 9, [5, 6]]] (size: 4) | [3, [1, 3, 4]] (size: 2)
[[1, 3, 4], 4, [2, 3, 9, [5, 6]]] (size: 3) | [[1, 3, 4]] (size: 1)
[1, 3, 4, 4, [2, 3, 9, [5, 6]]] (size: 5) | [1, 3, 4] (size: 3)
[3, 4, 4, [2, 3, 9, [5, 6]]] (size: 4) | [3, 4] (size: 2)
[4, 4, [2, 3, 9, [5, 6]]] (size: 3) | [4] (size: 1)
[4, [2, 3, 9, [5, 6]]] (size: 2) | [] (size: 0)
```
The size difference is 2 here because there are 2 items after the item being processed (`[6, 3, [1, 3, 4]]`).
This shows that this problem can be solved with a recursive algorithm
```
f([1, 2]) = [2, 1, 0]
f([3, [4, 5]]) = [2, 1, 2, 1, 0]
[2, 1, 0][2, 1, 2, 1, 0]
+ [2, 1, 0]
--------------------------------
f([[1, 2], [3, [4, 5]]]) = [2, 3, 2, 1, 2, 1, 2, 1, 0]
```
More precisely, the output of processing an array consists of:
* The initial length of the array, then
* For each item, the result of processing that item, plus adding the number of items after it to each element.
### Naive, readable implementation
```
function f(value) {
if (value !== undefined) {
return [
value.length,
...value.flatMap((item, index) => f(item).map((n) => n + value.length - index - 1))
]
}
return [0]
}
```
## Golfing
First, of course, is to apply basic golfing techniques
```
// 70 bytes
f=v=>v?[v.length,...v.flatMap((u,j)=>f(u).map($=>$+v.length-j-1))]:[0]
```
Then, since leaves are `undefined`, we can actually use default argument to treat leaves as `[]` and merge the two branches
```
// 69 bytes
f=(v=[])=>[v.length,...v.flatMap((u,j)=>f(u).map($=>$+v.length-j-1))]
```
Then, instead of mapping a second time to add the "base" value `v.length-j-1`, we can make `f` accept a second argument for a value to add to everything.
```
// 67 bytes
f=(v=[],i=0)=>[v.length+i,...v.flatMap((u,j)=>f(u,v.length+i-j-1))]
```
Next, we can pull `i` up to the global scope and mutate it instead of passing it around and using a lengthy expression to calculate the base
```
// 53 bytes
i=0;f=(v=[])=>[i+=v.length,...v.flatMap(u=>f(u,i--))]
```
Finally, we can move the `i--` decrement into `f` so that, instead of decrementing at each `flatMap` iteration, we just decrement `i` at the start of `f`.
```
// 45 bytes
i=1;f=(v=[])=>[i+=v.length-1,...v.flatMap(f)]
```
**BUT**, this breaks because the global variable `i` is changed after calling `f`, which is [forbiddened](https://codegolf.meta.stackexchange.com/a/4940/6972). Specifically, `i` is decremented by 1 for each root call to `f`. Before the change, `i` is decremented by 1 by one per child while looping in `flatMap`, but now `i` is decremented by 1 per call (i.e. per node), and the root is the only node that is not a child.
To counter this, we need to change the increment to "number of children" (instead of "number of children - 1") but only for the root node. This is doable by noticing that `i` is at its initial value only at the start of a root `f` call and after processing the last leaf. So we can initialize `i` to 0 and when we increment `i`, we increment by "number of children" if `i` is 0 but by "number of children - 1" otherwise.
```
// 47 bytes
i=0;f=(v=[])=>[i+=v.length-!!i,...v.flatMap(f)]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), (16) 21 bytes
```
Wθ«⟦ILθ⟧≔⁺∨&⁰§θ⁰υΦθλθ
```
[Try it online!](https://tio.run/##HYxLC8IwEITP7a/Y4wYi1FdBPFVBEAR7DzmENrSBEMmjVhB/e9x2YWd2voHtRhW6l7I5z6OxGtAz@JZFG4xLKK4qJnxoN6SRCibZuSyaGM3gsLVTxGfAi0mzibpxPVYcmnR3vf6g51AxxmGivRmbdFiQXZCnJ7@chRA1hz0HsV3tICUJxd0aT3QdOdSSJm/e9g8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Wθ«
```
Repeat until the input list is empty.
```
⟦ILθ⟧
```
Output its length on its own line.
```
≔⁺∨&⁰§θ⁰υΦθλθ
```
Add the tail of the list to the first element.
* This would be three bytes shorter if the list was to be iteratively deleted from the end rather than the start.
* This would be four bytes shorter if Charcoal's vectorising `Add` worked properly, but unfortunately it only vectorises to depth 1. (Other operators, such as `BitwiseAnd`, do vectorise correctly, so I'm assuming this is an oversight. Edit: Ironically, `Times` also doesn't vectorise correctly, so I needed to replace it with `BitwiseAnd` to fix a bug.)
* Alternatively, this could be two bytes shorter if the input integers were all zero. (Not applicable when vectorising `Add` works properly.)
* This could be one byte shorter by outputting the last length instead of the first.
16 bytes using the newer version of Charcoal on ATO:
```
Wθ«≔⁺§θ⁰Φθλθ⟦ILθ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjfDyzMyc1IVNAo1Faq5OB2LizPT8zQCckqLNRxLPPNSUis0CnUUDDR1FNwyc0pSi0C8HE0gt1DTmoszoCgzr0Qj2jmxuETDJzUvvSQDaI5mLFCqdklxUnIx1JLl0Uq6ZTlKsTe1o6OjzXQUjHUUog3BlElsLJAAco3AXEsgy1RHwSwWCCBaAQ "Charcoal – Attempt This Online") Link is to verbose version of code. Outputs the last length instead of the first.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
OḢ;$Ḋ⁼¡µƬẈṖ
```
A monadic Link that accepts a ragged list of integers and yields the lengths as a list, including both the initial length and a trailing `0`.
**[Try it online!](https://tio.run/##y0rNyan8/9//4Y5F1ioPd3Q9atxzaOGhrcfWPNzV8XDntP///0dHm@koGOsoRBuCKZPYWCAB5BqBuZZAlqmOgllsbCwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9//4Y5F1ioPd3Q9atxzaOGhrcfWPNzV8XDntP86h9uPTnq4c8ajpjVZjxr36dppRv7/Hx0dbaijYBSroxBtDMQmOgqmsbGxXDrR0WY6CiARQzBlEgtUAZSMNgJzLYEsUx0FM4hSY7CUKVgXBBjGQgFQCISBhkQDDTAEKwHZBSRBJgJJrlgA "Jelly – Try It Online").
### How?
```
OḢ;$Ḋ⁼¡µƬẈṖ - Link: ragged list of positive integers, L
Ƭ - collect input, X (initially L), while distinct, applying:
µ - this monadic chain - f(X):
O - ordinal value (vectorises) -- only here to get us a copy of X
so that we don't mutate it with ·∏¢
$ - last two links as a monad - f(Y=that):
·∏¢ - head Y (alters Y, yields the first element or 0 when given [])
; - concatenate that with (the altered Y)
¬° - if...
⁼ - ...condition: that equals X? (head of X was an integer)
Ḋ - ...then: dequeue
Ẉ - length of each
·πñ - pop the last length (removes the trailing 1, the length of 0)
```
---
Also 11 with no `Ḣ` and, therefore, no `O`: `1ị;ḊḊ⁼¡µƬẈṖ`
[Answer]
# JavaScript (ES5), ~~ 84 ~~ 80 bytes
*Saved 4 bytes thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)*
```
function(a){for(r=[];m=a.shift(r.push(a.length));)a=m[0]?m.concat(a):a;return r}
```
[Try it online!](https://tio.run/##jVJPT4MwFL/vUzx3WNqkNmODRSXEkwc96MFj00NF2DCsJW1ZYpZ9dnyUbcGpiS/QPt77/WlpP9ROudxWjb/e3XSlsSQ32nkQlW5az8C0HmcJpgQxAQwBQkQMFpKBWOIbM0iklIDpggFWcIzGowTJzsxVgPQCOMUSReIz8RazhMHqqIaVJLTHySAbXxiNLZahnZwkfqxgiEgeA4bV/PKMWQE2LkT9dwD9YSMZuqA@E3KEWYyQksI@wIcfbgsHGZCubHXuK6OJovv@OGwmZLrNFHebqvTE8qZ1G6J4Xei131CaUpVtxVzebzkK5coj8U6ltvCt1WAPXW9BSThOmgbDqiRPry/P3Hlb6XVVfhI0p3CVZXBRF5zz4QYwmEsa2LMZ/Jc@UCmlYY@mLnht1mT6YK2xU9Zv@XTBcGWHyTfQYwnaHLug3syuYKDqGnzhvINGOVe8T2nafQE "JavaScript (V8) – Try It Online")
Formatted and renamed:
```
function(array){
result = [];
while(
result.push(array.length),
current = array.shift()
) {
if(current !== +current) { // if current is not a number
array = current.concat(array);
}
}
return result;
}
```
[Answer]
# Rust, ~~19~~ ~~194~~ ~~185~~ 174 bytes
Even defining a type for a ragged list is bytes intensive in rust. Still shorter than C :)
```
enum K{N,Y(Vec<K>)}fn f(k:&K,n:usize)->Vec<usize>{if let K::Y(b)=k{[n+b.len()].into_iter().chain((1..).zip(b).map(|(i,z)|f(z,b.len()+n-i)).flatten()).collect()}else{vec![n]}}
```
Sequences will have a extra 0 at the end. [Verify all test cases](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c8474744bc710deb37a6d0546f7a477b)
-9 bytes by using `Vec` instead of array slices
-11 bytes by replacing `enumerate` with `zip` and `match` with `if let`
[Answer]
# BQN, 26 bytes
```
{(‚â†‚àæ¬∑ùïä=‚àò‚äë‚ó∂‚ü®‚ü©‚Äø‚äë‚àæ1‚ä∏‚Üì)‚çü(√ó‚â†)ùï©}
```
[Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge/CdlaniiaDiirjiiL4o8J2Vij3iiJjiipHil7bin6jin6nigL/iipHiiL4x4oq44oaTKeKNnyjDl+KJoCnwnZWpfQoKKOKAolNob3cgRuKImOKAokpzKcKo4p+oCiJbWzEsIDJdLCBbMywgWzQsIDVdXV0iCiJbWzYsIDMsIFsxLCAzLCA0XV0sIDQsIFsyLCAzLCA5LCBbNSwgNl1dXSIKIlszLCA0LCA1XSIKIltbW1tbW1tbMV1dXV1dXV1dIgoiW10iCiJbMSwgW10sIDFdIgoiW1tdLFtbW11dXSxbXV0iCuKfqQpA)
-1 byte thanks to @DLosc!
## Explanation
* `≠∾·...` append input length to...
* `(...)‚çü(√ó‚â†)ùï©` if input is nonempty...
* `...∾1⊸↓` append tail to...
* `=∘⊑◶⟨⟩‿⊑` head if head is rank 1 (i.e. list), otherwise empty list
* `ùïä` recurse
[Answer]
# [Factor](https://factorcode.org/), 57 bytes
```
[ [ dup length . unclip [ prepend ] when* ] until-empty ]
```
[Try it online!](https://tio.run/##lZFNb8IwDIbv/RXvrpOKBC0XkLhOu@yCOFUcqmDWiuCGNNWGqv72zsDSrwvCr2InVvzYSo6pcoVtd9vPr48VTmSZNEq6VMSKShhLzl2Nzdn12Rn9OpuWyAusg6AOIFaLjqLmHv3@pqm9IdzIhQUiWfNuNSPMwz8Q/WmI/cdEWCLu/A0UD8Ae6mHPrIOOJxrK9@81KZ5P5DHPu48w/ej1/Q2a10ZvgjZBgkNloIm/XYYZKlY6N5KVXzXEB@zxkxG/S6zY5Tqks3FX7KWStSRVcTZFSaBUZe0f "Factor – Try It Online")
Input consists of ragged sequences of `f` — Factor's canonical false value — as this saves about 20 bytes over integers.
* `[ ... ] until-empty` Call `[ ... ]` on the input until it's empty.
* `dup length .` Print the current length of the input non-destructively.
* `unclip` Remove the first element from the sequence and place it on top of the data stack.
* `[ prepend ] when*` `when*` is like `when` except it drops its input value if it's false, but retains its input if it's true (which is any non-false value in Factor). So, prepend it to the input if it's a sequence, or drop it if it's `f`.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt#L140), 15 (non-competing†) [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
{‚îú_nn¬°¬ø\;+ho}‚ñ≤;
```
† The program above doesn't compile due to a bug in MathGolf with (do-)while loops using blocks above 8 characters. `{...}` is supposed to be a block for when `...` contains more than 8 characters, but instead the `{` behaves as a for-each.
We can remove the `{}` and trailing `;` so the do-while works on all preceding characters, so we can verify the test cases. Unfortunately, all test cases will then output an additional trailing empty list `[]`.
Both programs also fail with an error for input `[]`.
Outputs each length to STDOUT, without leading length and with trailing 0.
`‚îú_nn¬°¬ø\;+ho‚ñ≤`: [Try it online](https://tio.run/##LUq7DYNAFOtZJW4eHCdFGcVYiIZQEGgySpQqTVbIAkiMwiLHy4FlWf49uudwn8c@pe31aadp/a5Lc7sM8/b@pUQaSoEVGFBLKsgIT@YSJASwdHsFa8S8e@9P/x0wnSjoNFCw/ypkntZFOe4).
**Explanation:**
```
{ }‚ñ≤ # Do-while true with pop:
‚îú # Extract and push the left item of the list
# (this is where the `[]` test case errors)
_ # Duplicate it
n # If it's a list: join it with newline delimiter to a string
# If it's an integer: push a newline "\n" character
n¬° # Check that this string is NOT equal to "\n"
¬ø # If it's indeed not "\n" (thus it's a list)
\ # Swap the top two values
¬ø # Else (it's an integer):
; # Discard it from the stack
+ # If it's a list: merge the top two lists together
# If it's an integer: add it to each inner-most value
h # Push the length (without popping the list)
o # Output it with trailing newline (without popping)
‚ñ≤ # Once the length is 0, the do-while stops
; # After the do-while: discard the empty list (since MathGolf
# implicitly outputs the entire stack at the end of a program)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 266 bytes
```
#define S *w++=*r++
#define B b+=*r==91?1:-(*r==93)
f(r,b,w)char*r,*w;{w=++r;if(*++r==93)r++,r+=*r?*r==44:-1;else{if(*r!=44)for(b=1;b;B)S;r++;}for(;*r;)S;*w=0;}i;main(b,v,r)char**v,*r;{for(v++;*(*v+2);printf("%d ",i),f(*v))for(b=0,r=*v,i=1;*++r;B)(!b&&*r==44)&&i++;}
```
[Try it online!](https://tio.run/##PY7LbsIwEEX3fEWgauTHRMKUDYwsJH6BJfICh7i1VNJqWtmLiG93x6HtZh5X986Zvnvt@1KerkOI49CcGpW1toq0Xvxpx8ZXxdqdOZh9J@bxRS6CIPCQZf92IUWgMk7Zak0Yg1DcZxcfAqrxQ41tt/vO4PD@NUzVREtWZPgg4a1Bj0d5Qg7gvUqoCHlX2a7xHvF2iaPwkIAeQJWADVN1Jo4ooZLeSPykOH4HsXq@NiuIEpiS5C9iDWQ5FplV/2OcWPq2fTwm2zZWdCnlfDZgYC7Guf9xbs65Hw "C (gcc) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 82 bytes
```
0
[]
+`..(],?|(((\[)|(?<-4>])|,)+)])(.*)$
$&¶[$2$5
.(.((\[)|(?<-3>])|,)*].)*.?
$#1
```
[Try it online!](https://tio.run/##RY5LCsJADIb3OcWAo2TaGJy2UxDEHiQNVNCFGxfisufyAF5sTKeCgTz/LyHP2@v@uOQtTuO1hgM4yAcQhXpiRqVhRsRRwozDad@dNcwU6qABuQoe/O7zFt/4BIz859qVq5RDxQP4TcxZJJJrlJy05h25pKoAIj25ZRJL6tQIE6Up7dGqRK5f0bZIqWytFvVnsLwMyxGxA7EgSkaYRha@ "Retina 0.8.2 – Try It Online") Outputs both leading and trailing counts and takes `0` as the consistent value (since `[]` is disallowed), but link is to test suite that replaces all non-negative integers with zero and deletes spaces for convenience. Explanation:
```
0
[]
```
Replace `0`s with empty lists.
```
+`
```
Repeat until the last line is an empty list.
```
..(],?|(((\[)|(?<-4>])|,)+)])(.*)$
```
On the last line, match a list containing either an empty list as its first or only element, or otherwise the contents of the list at the first element.
```
$&¶[$2$5
```
Keep the original list to count its elements later and create a new list obtained by prepending the contents (if any) to the rest of the list.
```
.(.((\[)|(?<-3>])|,)*].)*.?
$#1
```
Count the number of elements of each list.
[Answer]
## Brev, 85 bytes
```
(fn(descend(x)(cons(length x)(desc(if(pair?(car x))(append(car x)(cdr x))(cdr x))))))
```
Example:
```
((fn (descend (x)
(cons
(length x)
(desc
(if (pair? (car x))
(append (car x) (cdr x))
(cdr x))))))
'((1 2) (3 (4 5))))
```
`fn` makes a function with an argument `x`. `descend` checks if it's null, if it is, return it. Otherwise, `cons` its `length` onto a recursive call of `descend`, where the `car` of `x` has been spliced if it's a `pair?` or dropped if it's an atom. For the test example, it returns `(2 3 2 1 2 1 2 1)`
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
```
#l=+|hQYt
```
[Try it online!](https://tio.run/##K6gsyfj/XznHVrsmIzCy5P//6GgDHQWDWB0FEA1hx8YCAA "Pyth – Try It Online")
Accepts a ragged list filled with 0s.
Excludes the length of the initial list, and includes the 0 for the final list.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 32 bytes
```
saj{g_Jto'B~[{j_+}qvvIEsaj}qL[w!
```
[Try it online!](https://tio.run/##VU3LCoJQEN33FZObFuHiPhTCcFG0KNy3kJACCUQoM20xTL9@O/lAPJcZLuc1t@ZV5nXV5I49P/aiyL88c1dfC75np/djtfumXGRrqdr2eAAtVZJ@lq4F9snWl3PpmBVpITbElgIRIT8m1mRIkxpHFswhKHgNWXhsb9kQBxSOIUMBhHH/o3aqQQWiuDBYh9YeSgZ0oqLZg63n8VHYYOYdggZkWSZed9oP "Burlesque – Try It Online")
```
saj # Get initial length
{
g_ # Pop head from list
J # Dup
to'B~[ # Is Block
{j_+} # Prepend elements
qvv # Drop
IE # If (isBlock) else
saj # Length
}
qL[w! # While non-empty
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 22 bytes
```
{⍴⍴⍵:∊(⍴,∇¨+⍴-⍳∘⍴)⍵⋄0}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/@lHvFjDaavWoo0sDyNR51NF@aIU2kKX7qHfzo44ZQJYmUP5Rd4tB7f@0R20TgKr6HnU1P@pdA5Q6tN74UdvER31Tg4OcgWSIh2ewJpD2Cvb3@5@mHh1tqKNgFKujEG0MxCY6CqaxsbHqXCAJMx0FkJghmDKJBaoBSkcbgbmWQJapjoIZTLExWNIUqhMCDGOhACwIIYGGRQMNMoQqjNUBqgOq0AES6gA "APL (Dyalog Classic) – Try It Online")
I assume the output must be a flat array instead of allowing nested array. If nested array is acceptable then `‚àä` is not needed for -1 byte
Uses the same algorithm as my [other submission](https://codegolf.stackexchange.com/a/251282/6972), but pretty much ungolfed because tacit APL is that good
```
{⍴⍴⍵:∊(⍴⍵),(∇¨⍵)+(⍴⍵)-(⍳⍴⍵)⋄0} With trains expanded
⍴⍴⍵: If argument is array
(∇¨⍵) recursive call with each element
+(⍴⍵)-(⍳⍴⍵) add (length of argument - index)
note that APL arrays are 1-based by default
(⍴⍵), prepend length of argument
‚àä flatten
⋄0 Else return 0
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth) (arbitrary values), 15 bytes
```
lM.u+.x[.*hN[)t
```
[Test suite](https://pythtemp.herokuapp.com/?code=lM.u%2B.x%5B.%2ahN%5B%29t&test_suite=1&test_suite_input=%5B%5B1%2C+2%5D%2C+%5B3%2C+%5B4%2C+5%5D%5D%5D%0A%5B%5B6%2C+3%2C+%5B1%2C+3%2C+4%5D%5D%2C+4%2C+%5B2%2C+3%2C+9%2C+%5B5%2C+6%5D%5D%5D%0A%5B3%2C+4%2C+5%5D%0A%5B%5B%5B%5B%5B%5B%5B%5B1%5D%5D%5D%5D%5D%5D%5D%5D%0A%5B%5D%0A%5B1%2C+%5B%5D%2C+1%5D%0A%5B%5B%5D%2C%5B%5B%5B%5D%5D%5D%2C%5B%5D%5D&debug=0)
Takes a ragged list of arbitrary values (even accepts floats). Includes length of original list and final 0.
##### Explanation:
```
lM.u+.x[.*hN[)t | Full code
lM.u+.x[.*hN[)tNQ | with implicit variables
------------------+----------------------------------------------------------------------------------------------------------------
.u Q | Collect N, starting with the input, with each succussive N defined by the following until a result is repeated:
+ tN | Prepend to the tail of N:
[.*hN | N if N is a list
.x [) | or the empty list if N is not a list
lM | Convert each element to its length
```
] |
[Question]
[
A *run ascending list* is a list such that runs of consecutive equal elements are strictly increasing in length. For example `[1,1,2,2,1,1,1]` can be split into three runs `[[1,1],[2,2],[1,1,1]]` with lengths `[2,2,3]`, since two runs are the same length this is **not** a run ascending list. Similarly `[2,2,1,3,3,3]` is not run ascending since the second run (`[1]`) is shorter than the first (`[2,2]`). `[4,4,0,0,0,0,3,3,3,3,3]` is run ascending since the three runs strictly increase in length.
An interesting challenge is to figure out for a particular set of symbols whether they can be arranged into a run ascending list. Of course the values of the individual symbols don't matter. It just matters how many of each there are.
In this challenge you will be given a list of \$n\$ positive integers, \$x\_i\$, as input. Your task is to determine if a run ascending list can be made from the numbers \$1\$ to \$n\$ with each number \$k\$ appearing *exactly* \$x\_k\$ times.
For example if the input is `[4,4,7]` it means you must determine if a run ascending list can be made with four 1s, four 2s and seven 3s. The answer is yes:
```
[1, 3,3, 1,1,1, 2,2,2,2, 3,3,3,3,3]
```
If the input is `[9,9,1]` it means you must try to find a run ascending list made of nine 1s, nine 2s and one 3. This cannot be done. It must start with the single `3` since that run can only be 1 long. Then the 1s and 2s must alternate to the end, since each run must larger than the previous, there must be more of whichever number goes last.
## Rules
You should take as input a non-empty list of positive integers. You should output one of two distinct values. One if a run ascending list can be made the other if it cannot.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the goal is to minimize the size of your source code as measured in bytes.
## Testcases
Inputs that cannot make a run ascending list
```
[2,2]
[40,40]
[40,40,1]
[4,4,3]
[3,3,20]
[3,3,3,3]
```
Inputs that can make a run ascending list
```
[1]
[10]
[6,7]
[7,6]
[4,4,2]
[4,4,7]
[4,4,8]
```
[Answer]
# [Python 3](https://docs.python.org/3/), 106 bytes
```
def f(a,n=-1,x=0):a[n]-=x;return~-any(a)^any(f(1*a,i,j+1)for i,k in enumerate(a)for j in range(x,k)if i-n)
```
[Try it online!](https://tio.run/##NY3BboMwDIbvfQofk81IhKAydeLYXnfZDTEp25w2pQ3IChtc9uosYezi79fn3/Iwh0vv9bJ8kgUrDPo6UzjVuTyYxrdZPT0zhZH9T2b8LIx8S7BCPRh0eH1U0vYMDjtwHsiPd2ITKPaSvibJxp9JTNhJZ8FlXi7fF3cjeOWRDjuAwHMCxO4ANdCXuYkYxyCkXP3Azof4MsrV0PRBQ4Djy@nI3PPf8TuT6ZamwKLdNWWOZf5PVClhiTpSo8Yi34JeVVqrpPZYxVnhfusXG6uNT@0v "Python 3 – Try It Online")
Brute force search. Recursively subtracts a strictly increasing value from every index in the input, as long as it is not equal to the prviously picked index. This continues until all values in the input are zero or the options to continue are exhausted.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
āsÅΓœεÅγü›P}à
```
Brute-force approach, so extremely slow.
[Try it online](https://tio.run/##yy9OTMpM/f//SGPx4dZzk49OPrcVSG8@vOdRw66A2sML/v@PNtIxigUA) or [verify some of the smaller test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/I43Fh1vPTT46@dxWIL358J5HDbsCag8v@K/zPzraSMcoVifaWMcYSBrqQHhAEsw3htAK0YYgQYgCsDCIbwJmm4AVGukYQjWYAOViAQ).
**Explanation:**
```
ā # Push a list in the range [1, (implicit) input-length]
s # Swap so the input-list is at the top
ÅΓ # Run-length decode using the two lists
œ # Get all permutations of this list
ε # Map over each permutation:
Åγ # Run-length encode the list, pushing the values and counts as two
# separated lists to the stack
ü›P # Check if this counts-list is strictly increasing:
ü # For each overlapping pair of the counts-list:
› # Check if the first is larger than the second
P # Product to check if all of them are truthy
# (or if the list is empty after the overlapping pairs builtin,
# which means the counts-list only contains a single value)
}à # After the map: max to check if any of them is truthy
# (which is output implicitly as result)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes
```
{igᵗj₍}ᶠcpḅlᵐ<₁
```
[Try it online!](https://tio.run/##ATAAz/9icmFjaHlsb2cy//97aWfhtZdq4oKNfeG2oGNw4biFbOG1kDzigoH//1s0LDQsMl0 "Brachylog – Try It Online")
Times out on most of the test cases. I believe the algorithm is something like \$O(S!)\$, where \$S\$ is the sum of the input list.
### Explanation
```
{igᵗj₍}ᶠcpḅlᵐ<₁
{ }ᶠ Find all ways to satisfy this predicate:
i [E, I] pair where E is an element of the input and I is its index
gᵗ Turn that into [E, [I]]
j₍ Concatenate [I] to itself E times
Result: a list of lists like [[0, 0, 0, 0], [1, 1, 1, 1], [2, 2]]
c Concatenate those lists into one big list
p Consider some permutation of that list
ḅ Break it into blocks (i.e. runs of the same value)
lᵐ Take the length of each block
<₁ Assert that the list of lengths is strictly increasing
```
[Answer]
# JavaScript (ES6), 84 bytes
Returns \$0\$ or \$1\$.
```
f=(a,i=0,p,g)=>a.some((v,j)=>v&&(g=_=>p!=j&v>i&&f(a,v,j,a[j]-=v)|g(a[j]+=v--))())|!g
```
[Try it online!](https://tio.run/##dY7LDoIwEEX3/gWb0sYp4RVwU5Z@gTskpkGoNEgJYBMT/h1r3GhsdzPnzONKrvlcT9240EFdm21rGebQsRBGEIQVPJjVvcFYgzSdRggLdmHF6DGJdNEh1JpxI4GXsqJMk1Xgd7lnmlJCMCGrJ7ZaDbPqm6BXAvvlkffzs/LJ7hu3uIwhrsgfTUNIQxeHyGYghcTCE0ggDh0i@az8KP88lKfpsdxsaW2fI9v1DHILzSFzRI8dPHfwg@HbCw "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
a, // a[] = input array
i = 0, // i = previous run length
p, // p = previous index
g // g = variable used to store a local
// helper function and as a flag
) => //
a.some((v, j) => // for each value v at position j in a[]:
v && ( // abort if v = 0
g = _ => // g is a helper function which ignores its argument
p != j & // if the index is not equal to the previous one
v > i && // and v is greater than the previous run length:
f( // do a recursive call to f:
a, // pass a[]
v, // update i to v
j, // update p to j
a[j] -= v // subtract v from a[j]
) | // end of recursive call
g( // do a recursive call to g:
a[j] += v-- // restore a[j] and decrement v
) // end of recursive call
)() // initial call to g
) | // end of some()
!g // success if some() is truthy or g = 0,
// which means that a[] is now filled with 0's
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes
```
żZødṖƛĠvL2lvƒ>A;G
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLFvFrDuGThuZbGm8SgdkwybHbGkj5BO0ciLCIiLCJbMSwyXSJd)
Port of 05AB1E. ~~`vw` and `f` are only needed due to [a bug](https://github.com/Vyxal/Vyxal/issues/995), and `ƒ∴` is needed instead of `G` due to [another bug](https://github.com/Vyxal/Vyxal/issues/997).~~ Bugs fixed.
[Could be 13 bytes](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLFvMO44biK4bmWxpvDuMSWwqhwPkE7RyIsIiIsIlsxLDJdIl0=), but, well, this challenge is what inspired me to create all those new builtins, so, I guess it doesn't count.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 32 bytes
```
{+.bxj.*}wiFLr@{gw)-]qU_qsom&}ay
```
[Try it online!](https://tio.run/##SyotykktLixN/V@U@L9aWy@pIktPq7Y8082nyKE6vVxTN7YwNL6wOD9XrTax8v//aBMdEx2jWAA "Burlesque – Try It Online")
Drastically inefficient brute force
```
{ # Generate initial list, e.g. for [2,2] builds {1 1 2 2}
+. # Increment (indexed from zero)
bx # Box
j.* # Product
}wi # Zip with indices and map
FL # Flatten (strictly builds {{{1}{1}}{{2}{2}}})
r@ # All possible permutations (even repeated ones)
{
gw # Group like with length (count)
)-] # Get length (count)
qU_ # Quoted Unique
qso # Quoted sorted
m& # Make and (is sorted and unique)
}ay # Any
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 59 bytes
```
⊞υ⟦±¹θ⁰⟧FυF…⊟ι⌈§ι¹FLθF∧⁻λ§ι⁰›§§ι¹λκ⊞υ⟦λE§ι¹⁻ν∧⁼ξλ⊕κ⊕κ⟧⬤υ⌈⊟ι
```
[Try it online!](https://tio.run/##ZY/NCsIwEITvPkWOG4hgQfDgqQcRQaV4LT2Edm2D6damifTtY2JV/AmEsGHmm52ykabspPY@c0MDTrD8iLW0CAkXrBdsUfD17NwZBo6zx3uSVCNk3RVUkBzkqFrXQmp3VOEISrCE86d0j1TbBvrXnFIFB0VuAC3Yh2PBA2lrMOSaN@mLKJgO9xLJ70V1TL/@6iY@BX4I2/RO6gHGyb6j0mCLZLGCiPr7il0zo8hCqnXMeLWb2oaz9j7Pl2IpVkXh5zd9Bw "Charcoal – Try It Online") Link is to verbose version of code. Outputs nothing if a run ascending list can be made, `-` if not. Explanation: Inspired by @Jitse's Python answer.
```
⊞υ⟦±¹θ⁰⟧Fυ
```
Start a search with a previous run of `0` `-1`s and the original input still to process.
```
F…⊟ι⌈§ι¹
```
Loop over potential next run lengths.
```
FLθ
```
Loop over potential next run values.
```
F∧⁻λ§ι⁰›§§ι¹λκ
```
If this is a new run and there are enough of the value remaining, then...
```
⊞υ⟦λE§ι¹⁻ν∧⁼ξλ⊕κ⊕κ⟧
```
... add a new search entry of the run and updated array of counts.
```
⬤υ⌈⊟ι
```
See whether an array of all zeros was achieved.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
¬ΛȯV≤mLgP`ṘN
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f@hNedmn1gf9qhzSa5PekDCw50z/P4b6hjpGNqmJeYUpyqA2EZIbGPbkqJSCNMEzPz/PzoarCFWB0wbQWljKG0SGwsA "Husk – Try It Online")
Brute force approach, times out for even moderate inputs. TIO link includes a set of very short true & false inputs.
```
¬ΛȯV≤mLgP`ṘN
N # for each integer 1..N
`Ṙ # replicate it the number of times in the input array;
P # now get all permutations of this list
Λȯ # and output zero if none of these satisfy:
V # there is at least one pair of adjacent elemnts
≤ # for which the left is smaller or equal to the right,
mL # for the lengths of each
g # group of equal elements;
# (at this point truthy (nonzero) means a run-ascending list cannot be made,
# falsy (zero) means a run-ascending list can be made)
¬ # so NOT the result to get a consistent output
# 1=can be made, 0=cannot be made
```
(Omit the final `¬` for falsy & truthy-but-non-consistent output)
] |
[Question]
[
## The Task
The task is easy: given an Alpha-2 country code, output the Alpha-3 equivalent. The input may be in any case you choose, and the output in any consistent case of your choosing. Here are the codes:
```
[["AF", "AFG"], ["AX", "ALA"], ["AL", "ALB"], ["DZ", "DZA"], ["AS", "ASM"], ["AD", "AND"], ["AO", "AGO"], ["AI", "AIA"], ["AQ", "ATA"], ["AG", "ATG"], ["AR", "ARG"], ["AM", "ARM"], ["AW", "ABW"], ["AU", "AUS"], ["AT", "AUT"], ["AZ", "AZE"], ["BS", "BHS"], ["BH", "BHR"], ["BD", "BGD"], ["BB", "BRB"], ["BY", "BLR"], ["BE", "BEL"], ["BZ", "BLZ"], ["BJ", "BEN"], ["BM", "BMU"], ["BT", "BTN"], ["BO", "BOL"], ["BA", "BIH"], ["BW", "BWA"], ["BV", "BVT"], ["BR", "BRA"], ["VG", "VGB"], ["IO", "IOT"], ["BN", "BRN"], ["BG", "BGR"], ["BF", "BFA"], ["BI", "BDI"], ["KH", "KHM"], ["CM", "CMR"], ["CA", "CAN"], ["CV", "CPV"], ["KY", "CYM"], ["CF", "CAF"], ["TD", "TCD"], ["CL", "CHL"], ["CN", "CHN"], ["HK", "HKG"], ["MO", "MAC"], ["CX", "CXR"], ["CC", "CCK"], ["CO", "COL"], ["KM", "COM"], ["CG", "COG"], ["CD", "COD"], ["CK", "COK"], ["CR", "CRI"], ["CI", "CIV"], ["HR", "HRV"], ["CU", "CUB"], ["CY", "CYP"], ["CZ", "CZE"], ["DK", "DNK"], ["DJ", "DJI"], ["DM", "DMA"], ["DO", "DOM"], ["EC", "ECU"], ["EG", "EGY"], ["SV", "SLV"], ["GQ", "GNQ"], ["ER", "ERI"], ["EE", "EST"], ["ET", "ETH"], ["FK", "FLK"], ["FO", "FRO"], ["FJ", "FJI"], ["FI", "FIN"], ["FR", "FRA"], ["GF", "GUF"], ["PF", "PYF"], ["TF", "ATF"], ["GA", "GAB"], ["GM", "GMB"], ["GE", "GEO"], ["DE", "DEU"], ["GH", "GHA"], ["GI", "GIB"], ["GR", "GRC"], ["GL", "GRL"], ["GD", "GRD"], ["GP", "GLP"], ["GU", "GUM"], ["GT", "GTM"], ["GG", "GGY"], ["GN", "GIN"], ["GW", "GNB"], ["GY", "GUY"], ["HT", "HTI"], ["HM", "HMD"], ["VA", "VAT"], ["HN", "HND"], ["HU", "HUN"], ["IS", "ISL"], ["IN", "IND"], ["ID", "IDN"], ["IR", "IRN"], ["IQ", "IRQ"], ["IE", "IRL"], ["IM", "IMN"], ["IL", "ISR"], ["IT", "ITA"], ["JM", "JAM"], ["JP", "JPN"], ["JE", "JEY"], ["JO", "JOR"], ["KZ", "KAZ"], ["KE", "KEN"], ["KI", "KIR"], ["KP", "PRK"], ["KR", "KOR"], ["KW", "KWT"], ["KG", "KGZ"], ["LA", "LAO"], ["LV", "LVA"], ["LB", "LBN"], ["LS", "LSO"], ["LR", "LBR"], ["LY", "LBY"], ["LI", "LIE"], ["LT", "LTU"], ["LU", "LUX"], ["MK", "MKD"], ["MG", "MDG"], ["MW", "MWI"], ["MY", "MYS"], ["MV", "MDV"], ["ML", "MLI"], ["MT", "MLT"], ["MH", "MHL"], ["MQ", "MTQ"], ["MR", "MRT"], ["MU", "MUS"], ["YT", "MYT"], ["MX", "MEX"], ["FM", "FSM"], ["MD", "MDA"], ["MC", "MCO"], ["MN", "MNG"], ["ME", "MNE"], ["MS", "MSR"], ["MA", "MAR"], ["MZ", "MOZ"], ["MM", "MMR"], ["NA", "NAM"], ["NR", "NRU"], ["NP", "NPL"], ["NL", "NLD"], ["AN", "ANT"], ["NC", "NCL"], ["NZ", "NZL"], ["NI", "NIC"], ["NE", "NER"], ["NG", "NGA"], ["NU", "NIU"], ["NF", "NFK"], ["MP", "MNP"], ["NO", "NOR"], ["OM", "OMN"], ["PK", "PAK"], ["PW", "PLW"], ["PS", "PSE"], ["PA", "PAN"], ["PG", "PNG"], ["PY", "PRY"], ["PE", "PER"], ["PH", "PHL"], ["PN", "PCN"], ["PL", "POL"], ["PT", "PRT"], ["PR", "PRI"], ["QA", "QAT"], ["RE", "REU"], ["RO", "ROU"], ["RU", "RUS"], ["RW", "RWA"], ["BL", "BLM"], ["SH", "SHN"], ["KN", "KNA"], ["LC", "LCA"], ["MF", "MAF"], ["PM", "SPM"], ["VC", "VCT"], ["WS", "WSM"], ["SM", "SMR"], ["ST", "STP"], ["SA", "SAU"], ["SN", "SEN"], ["RS", "SRB"], ["SC", "SYC"], ["SL", "SLE"], ["SG", "SGP"], ["SK", "SVK"], ["SI", "SVN"], ["SB", "SLB"], ["SO", "SOM"], ["ZA", "ZAF"], ["GS", "SGS"], ["SS", "SSD"], ["ES", "ESP"], ["LK", "LKA"], ["SD", "SDN"], ["SR", "SUR"], ["SJ", "SJM"], ["SZ", "SWZ"], ["SE", "SWE"], ["CH", "CHE"], ["SY", "SYR"], ["TW", "TWN"], ["TJ", "TJK"], ["TZ", "TZA"], ["TH", "THA"], ["TL", "TLS"], ["TG", "TGO"], ["TK", "TKL"], ["TO", "TON"], ["TT", "TTO"], ["TN", "TUN"], ["TR", "TUR"], ["TM", "TKM"], ["TC", "TCA"], ["TV", "TUV"], ["UG", "UGA"], ["UA", "UKR"], ["AE", "ARE"], ["GB", "GBR"], ["US", "USA"], ["UM", "UMI"], ["UY", "URY"], ["UZ", "UZB"], ["VU", "VUT"], ["VE", "VEN"], ["VN", "VNM"], ["VI", "VIR"], ["WF", "WLF"], ["EH", "ESH"], ["YE", "YEM"], ["ZM", "ZMB"], ["ZW", "ZWE"]]
```
## Test Cases
```
US -> USA
GT -> GTM
VA -> VAT
IN -> IND
KP -> PRK
```
## Scoring
Because my soft drive can only store a kilobyte, and because this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins.
This is the reverse of [this challenge](https://codegolf.stackexchange.com/q/246777/107299).
[Answer]
# JavaScript (ES6), ~~582~~ 554 bytes
```
s=>("CCAPMSSS"[x="KYKMTFKPYTPMRSGSAXAQBYBJBAMOEEGWIEILSIUA".search([a,b]=s)/2]||a)+("YOTRYPRGLTLEIASNRSVK"[x]+"MMFKTMBSAARNHCTBLRNR"[x]||(c="E8bOUX3b11R1O1nadL2DIRG1ntTRlSdIeSo10M1L1RK2C2D2RL1U2i4L22N23N3RynL2ao1c3IEr2l1r11T39U9U5S15UlyNw1PN1MvEReM2uDP1l2Rw13c2O2KLSkuN2u1O1uN25I11rB10T1T1N1B1R4M6TnrGt4BrTg2GMuS1bl1E10Mr1gL1RRd2MUrL3hN1T3l10N1Ko1aoEV1ohRhL2I2BpMRPE14U4In3M3F11B7U1E1Ys9IPH24NIl1s1r21BR1rOuY1B2rBi1lnC1MM3u21G1DD3V1IN18N8NDT1rNL21Y7a1RN24N1ZMR8o4T2a10ON1".replace(/\d+/g,n=>"A".repeat(n))[parseInt(s,36)%774],c>{}?c.toUpperCase()+b:b+c))
```
[Try it online!](https://tio.run/##NVfbchs3En3XV7BYtWWypJWNoRzbScmpuWKGA4AjADPUUNEDRdGWd1mkipSSTcX5g1TlZR93/yPfkx/IJzg86PaLVEfTODh9utGA/rX8cXlY7T89Pv1zu7tff/lw@eVw@X40TNO40c654c1/Lod1X2tf1E3vG22ddPF1fJX0yTSJ9SzP5bzKK@WqNh6eH9bL/ephdLM8u7u9PIxfRrefPy/Hp6NhP/O2b6xUXuVV7Ix1XX3kvj0dal3UXicujq0pU58oayy@fP48Wl0O87d3s/Z6cieEFTOxXd6rKKusFNsnbzfuvlq7nXilhRK2jtIoi6wSbfTpQkWRiSZmYn/eqmi5E6tJle@jjdgL4Sfv2nftaydet5ufzU@iMUL/mNu1jp6zRmwi@5OYrKJZVCv372cTPR@3Pf56XQmxT8QrL7wwIhH2Qn/jt3v5dJHs/cdI6mcn7jYiP4rZi49HOfY@0u1eTR7McceNeGVEvRPLXd6J3YN9UFEVJY/aNrm4aC@q7URPCiGSN@2RoT@8q5oyujDVRhzEPhKJFfvZcy@SaJ98EpttKrSePEdCiiybdKIy4q15azIv9kZFon@zFNYcl4uFtm93Fz5ailczI4bn@/XjZrlaj17@cH/68uPZ9vL9MA5/XS@fRtvx@OZxuT@sq@3T6HA2@Wb8jzdvLm7PVu9/@fX71fnTrn18XO/T5WE9Gp/efXt3uhqPv3x3c3IzjIvh2fGHHN6eHcE1gIoJqACSALLFEWQL/uLwxWkCGYDJCMwA5IxABVDxmisAz0AGwJtaAMtAB8DUc4BkTqAFaB0BH4AnAG3xIg8ggbakpLCkDMASgNBEktAkAbCUXNIDKA7LAXJFYBG@LAhMwxdDAEIT3RKAnMTzF3iQzJggBqhKAsgnmZMHSQfQUQqJDXLoSwd3OknaKrBVMw4zIYz3kSEfVo0yJgVTw/gkqwKo4UFdkqMpVKea1qTQlsbElkJO2nS0BoakPa8pQlgRgIeJPiUTU3RIWlKmqQmA2Mr6CMqaaqqRgo5TCkOLpdesIAVIawIIS9m3OgidsQIZALGlWQCsoA6ACWBiaintFB6kFeVT4ktpCaRopLQle1PKtCGAaqfcSBmoM0PUGUqfTYk6g7ZMk9cZVGcsNEc@eUpNkUN1LvsAHOx1ihRInAVprigM2nJWnaP5ckfVztFVuafeKSCnUCSnwKaFpWNWQFvB2gqkXVRUhcKGMBIqUUbZUhkbgKbnmoYR4AlINIWMyR2JTKVmAG0yp00zgCynTCVaTJa8DxTIitdAgbRUeqkCoALLLAAqo2wAFFVBtkEoOSrhgfQM4KhkR6UJ@1Cmch4c5U37QEBhJQhKT@6UyKfUtGmHTLuYvC7BVvIUK6GgbIm6wkCpHKmuEFZxWIUUqozDkGnFR7O6CoAKXOUBMAEUVJrDVKCms1BBaMUDcoqwaUxpT@HOtKE1U7BNc0puij6YzoigRvfWMc2qGmE1z6oaJakrDgNbY6mRaqiuvxLAxHpOhtTwupbEpmCViqn0Cq2sOhKqMEdVQvsoWKUch9nwhahVHwCpVpCjKjpmCmkrT42kYLxqr2lsoON1TV5ryNEZDxQI1XOqqQa17mng6y6E0THTsFcrDvMBUHIaDat5cGkUS3sqloZqbTkMcjRfOX0g6PkLppjOSWiBYhV8HeosKCB3NOaBTskQjd7RhlPIAyAPNHzT3Ac6DtOSAWqqZ1QFjX00D2@DMMMdYqDaWDLRoMCmoeQMPDCKb2cTrmpKwUCbSTkM@5gFA9THVHRoDYSanDdFFYyk5EwbwnhTzBBTUFfpJiRHx9mgRw232AwpzLj9GxS4iWlNg5o2iu76BoY0jtxp4hDGa6CgYRObPrQydVUDoQ0LbVDghgvcIO0mZQIY0vAt0/hAQIY0NgBqlytsesXDwYLa8rCzyMfOGMADyx1ikYL9er2r8HKg@jjIcXw31pBTGz4/qIJKuV2KUHoe0bDKNUTQIaxLSc4c7sy531wI46ZwyMd5Mt4hBReTUIdNHc8DCwLHjx8HatdTtZ0K1xQZ7@C1k8yGYuHZH0AVALG5JKxhNrjj@DpcQMGC85FhU0lWuQActWXuwqVH@yjso2oyxOEwOZ6wDvVxLWeKS89N2QN0r5vTKXF5AJRCWoZHCefTh0yJwKNYfk7UHmx@Ssl5sHl@6noQeL7aPNzxilLwcMfzU9dDta@pqzw88DOmRkm85zBUwfPF4m0ALEcHAsrHp@GRxZt2IYxGWotNWz6ALextayKI8/BwpkwlSiJ59rawt3W8Bvu0mpq8hSEtn58WabcLKmOHvu74fd2BuuPe6ZBCZ7gt0QcdXyxzdO9cUbXzMtSU3i49CPqcmwIKFvymWKAKCxTr5Pbk/MNuny@P/4CObgbLzePDMjqj35PB7Xhw@X7wy8lgsFk/Dfbrw@By8GFEQePvjn9e7baH3WZ9vtl9HH1deww7o9jLrzzfD1789cfvf/7vv8efLwbfDl78@f/fXoxPfh1/@Rs "JavaScript (Node.js) – Try It Online")
### How?
The most common letter that needs to be added to an alpha-2 code to get the alpha-3 code is `A`. Therefore, it's the best suited padding character for our main lookup string, which is expanded by replacing all integers with the corresponding number of `A`'s.
[Try it online!](https://tio.run/##dVDNbptAGLznKRAnW2kdz7e4sWWlUgnURWYXa4GornpZwwrcrhZrgaR5epcccsxppNH8af6oZ9VX7nwZPtuu1ter0YPXew@eH69PWfmTnQCJDFbVKUWJ3MEOhTR5nei8w5IjhdzTI0UkU5R0DlIiQUww@WpTUh0qlsSODBxQsE25KVc5VqV5FS84CPDnWGpOY3SAIfkCVlFG@zT/Owoap9oJVgngQiwLFBAIIQP@pbBuNwShKxra8THHySCexjg00xxZEy9dyloxNRosBfYdVBc/oWtlm1JC4YXLQ4ygDBLLOPsOhPfllHDsN8nhBwUiMejhCKGEy8YjQnLhGcY@gnM2EnaIIvaERGAt1iIq4ERKON4rSDHZ8YvLdRcUpLDMBPztzdur@t9F2VrX07n9wumLUZWe3f2ub@@aT/bhq//Nf2O1GmZ2Pt/eVJ3tO6MXpmtm79aF0bYZWu/W872qVU5Vg3a9/4F6vr1e/wM "JavaScript (Node.js) – Try It Online")
The lookup function is a single modulo on the input parsed in base-36:
```
parseInt(s, 36) % 774
```
If we get a character in upper case, it means that it must be added at the end of the alpha-2 code.
```
"AF" ~> "G" ~> "AF**G**"
```
If we get a character in lower case, it means that it must be added in the middle of the alpha-2 code:
```
"AO" ~> "g" ~> "A**G**O"
```
Similarly to [my answer to the other challenge](https://codegolf.stackexchange.com/a/246784/58563), the 20 codes that do not follow the above rules are hard-coded separately, just the other way around.
[Answer]
# [Perl 5](https://www.perl.org/) `-MLocale::Country -pl`, ~~48~~ 40 bytes
```
$_=country_code2code($_,,'alpha-3')||ant
```
[Try it online!](https://tio.run/##JZOxat0wGEb38xyBtJAsLV0CHSRZlmXpl3Ul2Y69hEsaaCHkhjQdCnn23qZ0OcPh8G3f88PL45fz@eLu6/3p19Pry@@7@9O3h0//8OHi7urq8vj4/P14/fny49vb8en1fFYdyqJ6lEN5VEQJKqEm1AFVUBXVUDNqRd2idrRCa3SHtuge7dAD2qNHdEQLOqEndEFXdEMv6BW9oXeMwhhMh@kxDjNgPCZgIkYwCTNhCmbGLJhbzIbZ6SzdSBfohG6i27EGa7EOO2ALtmIbvacf6QO90E/0BadwGtfhLK7HOdyA87iIE1zCZdwB915WXMPNuBW3MQQGYUgMhaExzPgOb/ERL/iEn/AHfMFXfGO0jMI4MWaCJTjCQPAEISTCuyyElbARdqIiaqIhemIgFmIlNuJMXIgbohCDdIhFesQhAxKQiAiSkAnJyAEpSEUaMiMLsiK3yPvCTlIkQ7KknuRInhRJEymTCmkm7UxCVmRL7smOPJADOZLffSIXciU38kreOCiKpUyUSpkpK1VRNdVQO6qlOupA9dSRGqiRKtREnaiFWqmNulA36k4ztI7W0xxtoI20QIs0oSXaRCu0RltoK21nVsyOWZgr88a8sygWw2JZHItnSSwza89a2SxbY1fswr7@OT2//jg9/TxfSzzdHx8fbm7M/3ecr58f/wI "Perl 5 – Try It Online")
For some reason, the AN->ANT mapping isn't in Perl's list so I had to hardcode it.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~435~~ ~~426~~ 422 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.•4₆₆ÿ¸˜E¡´³*ιœýOóÖq₅;YpÂ-|ož®Ωg4∊₅“=à–ô9αA$ΔL,žÆE6óµQ£‚Ç\ΣN¬ÓóÑC∞\†ìвö—'‰ßÍ™¶HFü"í4·nÛZ0ø₅k{'¦Δ"¢h¦h)U–̱4ƒ¿¢
œ\a^»ãfzλ»Ï˜≠7>2e5Nl”SGed.iÉVó¸£₃l&C§ÚΣ6½+¢ å(₃L¦Ûā:vÊιOL†aëƵ₁fǝfVEtþΣ{õ-o¡ø4•u2ôD•46‰εcĆ2Zâæ¥ÙÚMт'•₂в£εN>.b«}˜ø.•1…¤θ30ËиʒÕf%γžBpéт(ĆVáä∞Kî%àôλ#KbɵC‘jÊα-zª+UΛGÙÀ"zFûÌιô#fиαL¸Λ¾o₄Ò{žwým«‚È3÷«εΩ)ØN÷U•u2ôD•Gò7¬ýà®vQ<ÑU•12в£ε€SN>.bý}˜áø.•Úù»ÔáÝâ|¹мœ4å)Çø{:вoÒaÿšмk*øW—Ã*‹Σc̉Δú¤š3rSwsJܲùη₅ĀPŽEf~:•u23S40∍£)˜DIk>è
```
[Try it online](https://tio.run/##TZF9T5JRGMb/71M0zRRNp0C6rNxK0UpCHdOWc21okqaFZekm1R4fDdF0TaBmgMWLUoa5eJOHENzui8e22M7wK5wvQof8p@1sZ@e@t3Ndv@uyzVpGJ8fL5SYuhfRcdoiDY1KKfgMFKUmJepZR3cj1IYGPz7j89ur9GciNr2xqng7Y3iM9d66JKZf81xHgkhvJKyx24wLzGC@peTgMrUhQaoDCXPJiZYSFTbQPt/hrs5M7P49wKYD9UhyHXPLUcuknvmCDL4fo8FY3jqrwQ0/pp/ANN0MRGlP2WoowTxWFJigyoRmsqK1TTH/iomMKnVPdI5YHlEXYusCy4n5f9PPVQFuHdvyyaZpL2@ae8YdNk1gdEo4UYUhemr7YSV/hZeFWyjVQ6Dx268TUSBH4Covtc1hjmT6jsGhB9CTF5UXr723rkOEF8ixsR6rRRkEoehHbSy2SXZX4WgUCS40VHNphhBChXXyC9@6pLNBCXJZLcQqzlKmjaZSir4t@KJXMW7gUoR2m6JrxrqT8ceGDtYYl1PzNGeydynUFxxCC2BFh9eKgBgEkWba6dxSrlOrk0tZjYTLWuEDfGwaZr0fISVUL3chinWWQrLaWFBYzksJ8lLdxeRkuu5qfR@4JRSt9OHVIU5Sl2J4GWyakB/9j6UG8TVSVQ4AO5gauYbOybNGeIXB531zBQK6CETwDgRcZEbtHvLcRekWZ0pHq1mNXgxUo9vZS3AaXBcdqsHQ0VQ/lnqgcS/VcyrDwGNYryXnwi3bUoO65eX72DvwUR4alRfEFqV/NGaxv2v/505n1zdy5QWFN0d91e6oD38rl3v6/) or [verify all test cases](https://tio.run/##TZNtbxRVFMff@ymaRYTyFGhXiKgk3dnd2e3OTKed2a2taFKUCoIWRSGhaJYFS0GIoa0G26LtLlSxSOzD0l1LS3JPFxObTJavMF@kzv7uG5Pm3/bec/4P59wZuTh06uzpnZ1DYbEcD0tj0Y@8ULXt2ZSaV6tqZV9Qb0zKRo@syE9fhKXv3h64IKWDV0cam@pp8PiTeDh@OzoNi7PvylxYnJTVt4KlrteDKetAY1PGUkdlRVV7VSUsTsvNk0HFUU9kMuK6Z4Tjv5wMi3PypLksz8Li1J6w@Jf8KnfDG2X1LJOW5zH5M67WPpeZwcNSizTOje5RC8FUTJXPqIUz7fmW2h21FH85oV6o8muNyZNDH6p1qQxfCdaj3z9sz4a35o6d6Dj9pnM@LD7wzNMfHzortwqRo1pkqHT9/BuG@k2mg8pRtbFfldvk0d7o1FILMrN17fgluR3Ue6zI4pAsvqyGpWvD/zwYLqS@ks2gMirVgyNqXmrxaGxfd8hqsjW@o1GEoPrR1ljHoJRlQT2Sn2XaflWKopXDUqm5rCpB1Tlx6JRa/GZ7VmqtmR8JiwvqYVDrPCzfN2v/TsiPw7uDlcZm4oI8flXauzVWkHl5GA0rJ093y5ysBuu7cqfklqoaYfH@p5HJpYNX1B/788GMGckVY1fSsi53grqs7hpu1oIlS9WCGbU5EpZuyMRoY/OybHymFlv7GO@UNbUYVIPH7XLfkbX8/7KYsnwsWtWGzKmnl3rfkXutyyMdOkJYeuK1YshGK8a8DiLTUo/GPhX9/0DKV1W9@bwxGZdH7XJTaqPHm8sjMjEkLxrzzefn9kmtP1q5XN8XFutB5SO505rclPytHjbmO7/0Ll/sllm1LPVgLVr8VtFtbKSGvz2Ov04vfjgcv6sq7duzyey5E/L7jtRibeHYRFtMNtT6zvuxrnTsQFus6z3QamFykL89MAn2gFmwFzTBPtAG@8E86IPwJOBJZEDYEglwAEyBurIbhC0BQwLdRBcIf6IAolvAQ1bXOCAnCRIlcJtD14DTgMeAIYe6QaWPK4PsBjyZXAttmA0mYxggJznNhpahe6k3cGWgm9F/Mw1Da5ExSWWSpEl4knCm4E/B6eHQZM4peFJMKcVM0jCk6UrDk0YxTaVJIlfnAk1Sm2iZ8CRBk8mY9Jq6lwmYJDJdEP8muibeTOZjsguTXBluM/AX0MroGdKbZftZTrIwZ9HKki6Lkyy9WdSzsHVz0o2Hbmq69eSZYY6TnN4vNTk4c7jK4dPCicUkLd6bhROLSgvnFgwWihZubb13GGzYbCpteGwc2tTbTM8mhQ2nDcOAvuXNpElhk9pmvzZzsPFv48fGp00um3qHEwdOh3QOul30OvA41Dv4d2Bz8OzgwWHvtu5lbj0wu6RzyeWi7qLl0uuS1IXNJZ2Loou6Sy4XV7109VHZB38fun36C6XegyEHg6Wz65ep3wkn/XjwOPHg92D26OrTt1R6mlN/HaTwyO6xWQ8Pg/qd6y4wpTeu69mCh3@Pr8Zjhh4pDNx6TMAnhU@NT43PrY8HHw8@nD66Ps59PPvw@yTyce7zcvJ05XHYpb8@nOdxmKc@j3oexQLzLFBZgLlA3n5mmMLPALeD9A72xz74Dw).
**Explanation:**
Step 1a: Create I/O pairs of all alpha-2 codes for which a single trailing letter has to be added for the alpha-3 conversion:
```
.•4₆₆ÿ¸˜E¡´³*ιœýOóÖq₅;YpÂ-|ož®Ωg4∊₅“=à–ô9αA$ΔL,žÆE6óµQ£‚Ç\ΣN¬ÓóÑC∞\†ìвö—'‰ßÍ™¶HFü"í4·nÛZ0ø₅k{'¦Δ"¢h¦h)U–̱4ƒ¿¢
œ\a^»ãfzλ»Ï˜≠7>2e5Nl”SGed.iÉVó¸£₃l&C§ÚΣ6½+¢ å(₃L¦Ûā:vÊιOL†aëƵ₁fǝfVEtþΣ{õ-o¡ø4•
"# Push compressed string "dzaibwbrbfdmfrghitlvmdngrwknlclktzthtcugusalvgcugagmgiuzzmgrnihmhninmknlssazczlipsslchzwzaafarhkmnetcrdjerfjhtmwmlprumccnftjbebocoismhnpncnzphtkaskhdogugtnablwssosjvnyebtcafihuidirimjpkelbompashsdtwtovegelalsmctgttcystsgesbhbgcmcxjokimsmammnenopesmsygbviaumymurutlbviovakwmranqavcvubmecdeltnrrerosacihrluegggjekg"
u # Uppercase it
2ô # Split it into parts of size 2
D # Duplicate this list of pairs
•46‰εcĆ2Zâæ¥ÙÚMт'•
'# Push compressed integer 5045888909142307005039435397419896531
₂в # Convert it to base-26 as list: [21,8,2,6,7,1,4,1,9,0,3,10,12,17,6,4,0,16,5,9,8,2,0,1,3,1]
£ # Split the duplicated pairs into parts of that size
ε # Map over each list of string-pairs:
N> # Push the 1-based map-index
.b # Convert it to an uppercase alphabetic letter (1=A,2=B,...,26=Z)
« # Append it to each string-pair in the current list
}˜ # After the map: flatten
ø # Create pairs of the two lists
```
[Try just this step, to see all I/O pairs of step 1a.](https://tio.run/##FZBtK0NxGMbf@xRa8mxpHROixPBiJomipYYNkZGHFx7qOJhNJLaUGeacTPIQtsNZs63ua5sXq3/zFf5fZP7qrruuF9f1uy7vqmtq3l0um7msSlzxiUOWjGLERneUoHg9S@aDSA8hjosVrhx0jC9Dadr25jP0yh5nJe4/EiqXI52IcjmIRBt7765iIXtjPgOfzYo46cOkcTmMQyfTHPSMoPA66@H@GyeXo3gufeCTy6EaLr/hFid8X6XPgT58m/Ai0dcSriaaYYiMha0airGQidQ5is3Vjf6nHdO7VDinLKkV@aDTNUkpaJ5NlhL/tBjhgWhrl8Xd4ljk8vVIv3vGPI/AmCAyBJCyt1jdQw8IM81K6QZSK3FfK1Q7xXCV223fwBFLDtkFogtPBZ0ru56fa8@YbQ0Zpm1Bb/LSHQxJzLZuQaL3fz6rqMD06ZzPMgEVMbrHJcKDv4qopnJFKX2QxnRHl3mKnnaKERjl8h8)
Step 1b: Create I/O pairs of all alpha-2 codes for which a single middle letter has to be added for the alpha-3 conversion:
```
.•1…¤θ30ËиʒÕf%γžBpéт(ĆVáä∞Kî%àôλ#KbɵC‘jÊα-zª+UΛGÙÀ"zFûÌιô#fиαL¸Λ¾o₄Ò{žwým«‚È3÷«εΩ)ØN÷U•
# Push compressed string "cfjmkzpkmfawlrlytdpnbimgmvmxsnaobdbsclcngnnutmbzsvfkgpmtpwsbwfaddkgqmemppgcgcdckkrmzplcvambbbnfoglgdiqpyptaeuyfmehagmqatgfgysrtntrtvskszsepfsc"
u2ôD # Same as above (uppercase; split into pairs; duplicate)
•Gò7¬ýà®vQ<ÑU• # Push compressed integer 5023299766197034891137684120
12в # Convert it to base-12 as list: [5,3,2,3,2,0,2,3,2,0,1,8,0,6,6,1,0,11,2,2,7,1,2,0,2,0]
£ # Split the duplicated pairs into parts of that size
ε # Map over each list of string-pairs:
€S # Convert each string to a list
N>.b # Same as above: get the uppercase letter based on the index
ý # Join the inner list-pairs with this letter as delimiter
}˜áø # Same as above, but `á` removes empty strings from the list
```
[Try just this step, to see all I/O pairs of step 1b.](https://tio.run/##AdMALP9vc2FiaWX//y7igKIx4oCmwqTOuDMww4vQuMqSw5VmJc6zxb5CcMOp0YIoxIZWw6HDpOKInkvDriXDoMO0zrsjS2LDicK1Q@KAmGrDis6xLXrCqitVzptHw5nDgCJ6RsO7w4zOucO0I2bQuM6xTMK4zpvCvm/igoTDknvFvnfDvW3Cq@KAmsOIM8O3wqvOtc6pKcOYTsO3VeKAonUyw7RE4oCiR8OyN8Ksw73DoMKudlE8w5FV4oCiMTLQssKjzrXigqxTTj4uYsO9fcucw6HDuP//)
Step 1c: Create I/O pairs for all remaining alpha-2 to alpha-3 conversions (as a flattened list):
```
.•Úù»ÔáÝâ|¹мœ4å)Çø{:вoÒaÿšмk*øW—Ã*‹Σc̉Δú¤š3rSwsJܲùη₅ĀPŽEf~:•
# Push compressed string "aqataaxalababihbjbenbyblreeestgssgsgwgnbieirlilisrkmcomkpprkkycymmomacpmspmrssrbsisvntfatfuaukrytmyt"
u # Uppercase it
23S # Push [2,3]
40∍ # Extend it to size 40: [2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3]
£ # Split the string into parts of that size
```
[Try just this step, to see the flattened list of all the I/O pairs of step 1c.](https://tio.run/##AX8AgP9vc2FiaWX//y7igKLDmsO5wrvDlMOhw53DonzCudC8xZM0w6Upw4fDuHs60LJvw5Jhw7/FodC8ayrDuFfigJTDgyrigLnOo2PDjOKAsM6Uw7rCpMWhM3JTd3NKw5zCssO5zrfigoXEgFDFvUVmfjrigKJ1MjNTNDDiiI3Co///)
Step 2: Combine the results of the previous steps, and use them for the input to output conversion:
```
) # Wrap the entire stack into a list
˜ # Flatten
D # Duplicate this list
Ik # Get the index of the input-string
> # Increase this index by 1
è # And use it to index into the list
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress strings not part of the dictionary?*, *How to compress large integers?*, and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compressions work.
[Answer]
# [R](https://www.r-project.org/), 74 bytes
```
function(c)`if`(c=="AN","ANT",countrycode::countrycode(c,"iso2c","iso3c"))
```
[Try it rdrr.io!](https://rdrr.io/snippets/embed/?code=f%3D%0Afunction(c)%60if%60(c%3D%3D%22AN%22%2C%22ANT%22%2Ccountrycode%3A%3Acountrycode(c%2C%22iso2c%22%2C%22iso3c%22))%0A%0Asapply(c(%22AF%22%2C%22AX%22%2C%22AL%22%2C%22DZ%22%2C%22AS%22%2C%22AD%22%2C%22AO%22%2C%22AI%22%2C%22AQ%22%2C%22AG%22%2C%22AR%22%2C%22AM%22%2C%22AW%22%2C%22AU%22%2C%22AT%22%2C%22AZ%22%2C%22BS%22%2C%22BH%22%2C%22BD%22%2C%22BB%22%2C%22BY%22%2C%22BE%22%2C%22BZ%22%2C%22BJ%22%2C%22BM%22%2C%22BT%22%2C%22BO%22%2C%22BA%22%2C%22BW%22%2C%22BV%22%2C%22BR%22%2C%22VG%22%2C%22IO%22%2C%22BN%22%2C%22BG%22%2C%22BF%22%2C%22BI%22%2C%22KH%22%2C%22CM%22%2C%22CA%22%2C%22CV%22%2C%22KY%22%2C%22CF%22%2C%22TD%22%2C%22CL%22%2C%22CN%22%2C%22HK%22%2C%22MO%22%2C%22CX%22%2C%22CC%22%2C%22CO%22%2C%22KM%22%2C%22CG%22%2C%22CD%22%2C%22CK%22%2C%22CR%22%2C%22CI%22%2C%22HR%22%2C%22CU%22%2C%22CY%22%2C%22CZ%22%2C%22DK%22%2C%22DJ%22%2C%22DM%22%2C%22DO%22%2C%22EC%22%2C%22EG%22%2C%22SV%22%2C%22GQ%22%2C%22ER%22%2C%22EE%22%2C%22ET%22%2C%22FK%22%2C%22FO%22%2C%22FJ%22%2C%22FI%22%2C%22FR%22%2C%22GF%22%2C%22PF%22%2C%22TF%22%2C%22GA%22%2C%22GM%22%2C%22GE%22%2C%22DE%22%2C%22GH%22%2C%22GI%22%2C%22GR%22%2C%22GL%22%2C%22GD%22%2C%22GP%22%2C%22GU%22%2C%22GT%22%2C%22GG%22%2C%22GN%22%2C%22GW%22%2C%22GY%22%2C%22HT%22%2C%22HM%22%2C%22VA%22%2C%22HN%22%2C%22HU%22%2C%22IS%22%2C%22IN%22%2C%22ID%22%2C%22IR%22%2C%22IQ%22%2C%22IE%22%2C%22IM%22%2C%22IL%22%2C%22IT%22%2C%22JM%22%2C%22JP%22%2C%22JE%22%2C%22JO%22%2C%22KZ%22%2C%22KE%22%2C%22KI%22%2C%22KP%22%2C%22KR%22%2C%22KW%22%2C%22KG%22%2C%22LA%22%2C%22LV%22%2C%22LB%22%2C%22LS%22%2C%22LR%22%2C%22LY%22%2C%22LI%22%2C%22LT%22%2C%22LU%22%2C%22MK%22%2C%22MG%22%2C%22MW%22%2C%22MY%22%2C%22MV%22%2C%22ML%22%2C%22MT%22%2C%22MH%22%2C%22MQ%22%2C%22MR%22%2C%22MU%22%2C%22YT%22%2C%22MX%22%2C%22FM%22%2C%22MD%22%2C%22MC%22%2C%22MN%22%2C%22ME%22%2C%22MS%22%2C%22MA%22%2C%22MZ%22%2C%22MM%22%2C%22NA%22%2C%22NR%22%2C%22NP%22%2C%22NL%22%2C%22AN%22%2C%22NC%22%2C%22NZ%22%2C%22NI%22%2C%22NE%22%2C%22NG%22%2C%22NU%22%2C%22NF%22%2C%22MP%22%2C%22NO%22%2C%22OM%22%2C%22PK%22%2C%22PW%22%2C%22PS%22%2C%22PA%22%2C%22PG%22%2C%22PY%22%2C%22PE%22%2C%22PH%22%2C%22PN%22%2C%22PL%22%2C%22PT%22%2C%22PR%22%2C%22QA%22%2C%22RE%22%2C%22RO%22%2C%22RU%22%2C%22RW%22%2C%22BL%22%2C%22SH%22%2C%22KN%22%2C%22LC%22%2C%22MF%22%2C%22PM%22%2C%22VC%22%2C%22WS%22%2C%22SM%22%2C%22ST%22%2C%22SA%22%2C%22SN%22%2C%22RS%22%2C%22SC%22%2C%22SL%22%2C%22SG%22%2C%22SK%22%2C%22SI%22%2C%22SB%22%2C%22SO%22%2C%22ZA%22%2C%22GS%22%2C%22SS%22%2C%22ES%22%2C%22LK%22%2C%22SD%22%2C%22SR%22%2C%22SJ%22%2C%22SZ%22%2C%22SE%22%2C%22CH%22%2C%22SY%22%2C%22TW%22%2C%22TJ%22%2C%22TZ%22%2C%22TH%22%2C%22TL%22%2C%22TG%22%2C%22TK%22%2C%22TO%22%2C%22TT%22%2C%22TN%22%2C%22TR%22%2C%22TM%22%2C%22TC%22%2C%22TV%22%2C%22UG%22%2C%22UA%22%2C%22AE%22%2C%22GB%22%2C%22US%22%2C%22UM%22%2C%22UY%22%2C%22UZ%22%2C%22VU%22%2C%22VE%22%2C%22VN%22%2C%22VI%22%2C%22WF%22%2C%22EH%22%2C%22YE%22%2C%22ZM%22%2C%22ZW%22)%2Cf))
[Answer]
# Python 1779 bytes
```
a=' AF AFG AX ALA AL ALB DZ DZA AS ASM AD AND AO AGO AI AIA AQ ATA AG ATG AR ARG AM ARM AW ABW AU AUS AT AUT AZ AZE BS BHS BH BHR BD BGD BB BRB BY BLR BE BEL BZ BLZ BJ BEN BM BMU BT BTN BO BOL BA BIH BW BWA BV BVT BR BRA VG VGB IO IOT BN BRN BG BGR BF BFA BI BDI KH KHM CM CMR CA CAN CV CPV KY CYM CF CAF TD TCD CL CHL CN CHN HK HKG MO MAC CX CXR CC CCK CO COL KM COM CG COG CD COD CK COK CR CRI CI CIV HR HRV CU CUB CY CYP CZ CZE DK DNK DJ DJI DM DMA DO DOM EC ECU EG EGY SV SLV GQ GNQ ER ERI EE EST ET ETH FK FLK FO FRO FJ FJI FI FIN FR FRA GF GUF PF PYF TF ATF GA GAB GM GMB GE GEO DE DEU GH GHA GI GIB GR GRC GL GRL GD GRD GP GLP GU GUM GT GTM GG GGY GN GIN GW GNB GY GUY HT HTI HM HMD VA VAT HN HND HU HUN IS ISL IN IND ID IDN IR IRN IQ IRQ IE IRL IM IMN IL ISR IT ITA JM JAM JP JPN JE JEY JO JOR KZ KAZ KE KEN KI KIR KP PRK KR KOR KW KWT KG KGZ LA LAO LV LVA LB LBN LS LSO LR LBR LY LBY LI LIE LT LTU LU LUX MK MKD MG MDG MW MWI MY MYS MV MDV ML MLI MT MLT MH MHL MQ MTQ MR MRT MU MUS YT MYT MX MEX FM FSM MD MDA MC MCO MN MNG ME MNE MS MSR MA MAR MZ MOZ MM MMR NA NAM NR NRU NP NPL NL NLD AN ANT NC NCL NZ NZL NI NIC NE NER NG NGA NU NIU NF NFK MP MNP NO NOR OM OMN PK PAK PW PLW PS PSE PA PAN PG PNG PY PRY PE PER PH PHL PN PCN PL POL PT PRT PR PRI QA QAT RE REU RO ROU RU RUS RW RWA BL BLM SH SHN KN KNA LC LCA MF MAF PM SPM VC VCT WS WSM SM SMR ST STP SA SAU SN SEN RS SRB SC SYC SL SLE SG SGP SK SVK SI SVN SB SLB SO SOM ZA ZAF GS SGS SS SSD ES ESP LK LKA SD SDN SR SUR SJ SJM SZ SWZ SE SWE CH CHE SY SYR TW TWN TJ TJK TZ TZA TH THA TL TLS TG TGO TK TKL TO TON TT TTO TN TUN TR TUR TM TKM TC TCA TV TUV UG UGA UA UKR AE ARE GB GBR US USA UM UMI UY URY UZ UZB VU VUT VE VEN VN VNM VI VIR WF WLF EH ESH YE YEM ZM ZMB ZW ZWE'
z=lambda b:a[a.find(" "+b)+4:a.find(" "+b)+7]
```
Not sure what to do with the mass of data.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 420 bytes
```
«⟑``‟Ḃȯ†√¦∑iRṫΠʁǓ₴5]p#4Ṅl}3ẋ¶T+⟑V]ḭr≤ṁǔ
A»cP⌐kẋṠ†⟇Ǔ≈ɽ⟩›ṪwSʀ₇⌊Ǔ∇•Xwð⇩I‡ṅfβ℅₍ṗµ∆€¾aǍ⟑Ȧ2⋏$λ⁺]/|f₁Pa⟨,₁,h¨ṁ₌ε⟑‹İ⟨Nṫw%yĖ⁼*>₈˹ȯU÷s¬)∨ʀ0ŀƈ½)(m-Ẋ ǓḂ⟩[0e•₂↲S⟇Ġj⟨^ɖg[⌐₁⋏żo:ẎRʁ⌐ð%⇧↓Y*?* †8„S|⁽l3√⁺⟑«⇧2ẇ:»⟑⟇βE'ċ¬$≠∪₀↳↲æMf»₄τẇkA¨£vJfZ«ƛ¤‛H∧λŻJ@±*dCẋ°4£Mgċ ≥ƒX¢ǎd≤ǔ₈b¢&Ẋ≈•ġ.ẎAl>₅j¨∵½↳Ŀa>€¼₌Rǔb*JA⌐Ḃ∵Ḣ3\⌈|ẋ;Π1₆›Ẇ∧≬₆ETh□ʀ≬¨«⇧2ẇ:»½ǒ÷₇Π≤¶:ɽq∇¨»12τẇkAZƛ÷$f$vj;fZ«↲↵˝≥꘍≠}ĊKṫ⟑ɖhṪ⁺|oI3⌈%‟ṙK/i⁺!ṅȮiȧS'₌βP⅛‛ṙ∧6ƈ;7↔⋎¡↵G]ḟɾḋ†*↑o«⇧23f20ẋfẇWf:⁰ḟ›i
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCq+KfkWBg4oCf4biCyK/igKDiiJrCpuKIkWlS4bmrzqDKgceT4oK0NV1wIzThuYRsfTPhuovCtlQr4p+RVl3huK1y4omk4bmBx5RcbkHCu2NQ4oyQa+G6i+G5oOKAoOKfh8eT4omIyb3in6nigLrhuap3U8qA4oKH4oyKx5PiiIfigKJYd8Ow4oepSeKAoeG5hWbOsuKEheKCjeG5l8K14oiG4oKswr5hx43in5HIpjLii48kzrvigbpdL3xm4oKBUGHin6gs4oKBLGjCqOG5geKCjM614p+R4oC5xLDin6hO4bmrdyV5xJbigbwqPuKCiMSWwrnIr1XDt3PCrCniiKjKgDDFgMaIwr0pKG0t4bqKIMeT4biC4p+pWzBl4oCi4oKC4oayU+Kfh8SgauKfqF7Jlmdb4oyQ4oKB4ouPxbxvOuG6jlLKgeKMkMOwJeKHp+KGk1kqPyog4oCgOOKAnlN84oG9bDPiiJrigbrin5HCq+KHpzLhuoc6wrvin5Hin4fOskUnxIvCrCTiiaDiiKrigoDihrPihrLDpk1mwrvigoTPhOG6h2tBwqjCo3ZKZlrCq8abwqTigJtI4oinzrvFu0pAwrEqZEPhuovCsDTCo01nxIsg4omlxpJYwqLHjmTiiaTHlOKCiGLCoibhuoriiYjigKLEoS7huo5BbD7igoVqwqjiiLXCveKGs8S/YT7igqzCvOKCjFLHlGIqSkHijJDhuILiiLXhuKIzXFzijIh84bqLO86gMeKChuKAuuG6huKIp+KJrOKChkVUaOKWocqA4omswqjCq+KHpzLhuoc6wrvCvceSw7figofOoOKJpMK2Osm9ceKIh8KowrsxMs+E4bqHa0FaxpvDtyRmJHZqO2ZawqvihrLihrXElsKv4oml6piN4omgfcSKS+G5q+KfkcmWaOG5quKBunxvSTPijIgl4oCf4bmZSy9p4oG6IeG5hciuacinUyfigozOslDihZvigJvhuZniiKc2xog7N+KGlOKLjsKh4oa1R13huJ/JvuG4i+KAoCrihpFvwqvih6cyM2YyMOG6i2bhuodXZjrigbDhuJ/igLppIiwiIiwiS1AiXQ==) or [Verify all test cases (takes a while, but doesn't time out)](https://vyxal.pythonanywhere.com/#WyJqVCIsIsab4oaSIiwiwqvin5FgYOKAn+G4gsiv4oCg4oiawqbiiJFpUuG5q86gyoHHk+KCtDVdcCM04bmEbH0z4bqLwrZUK+KfkVZd4bitcuKJpOG5gceUXG5BwrtjUOKMkGvhuovhuaDigKDin4fHk+KJiMm94p+p4oC64bmqd1PKgOKCh+KMiseT4oiH4oCiWHfDsOKHqUnigKHhuYVmzrLihIXigo3huZfCteKIhuKCrMK+YceN4p+RyKYy4ouPJM674oG6XS98ZuKCgVBh4p+oLOKCgSxowqjhuYHigozOteKfkeKAucSw4p+oTuG5q3clecSW4oG8Kj7igojElsK5yK9Vw7dzwqwp4oioyoAwxYDGiMK9KShtLeG6iiDHk+G4guKfqVswZeKAouKCguKGslPin4fEoGrin6heyZZnW+KMkOKCgeKLj8W8bzrhuo5SyoHijJDDsCXih6fihpNZKj8qIOKAoDjigJ5TfOKBvWwz4oia4oG64p+Rwqvih6cy4bqHOsK74p+R4p+HzrJFJ8SLwqwk4omg4oiq4oKA4oaz4oayw6ZNZsK74oKEz4ThuodrQcKowqN2SmZawqvGm8Kk4oCbSOKIp867xbtKQMKxKmRD4bqLwrA0wqNNZ8SLIOKJpcaSWMKix45k4omkx5TigohiwqIm4bqK4omI4oCixKEu4bqOQWw+4oKFasKo4oi1wr3ihrPEv2E+4oKswrzigoxSx5RiKkpB4oyQ4biC4oi14biiM1xc4oyIfOG6izvOoDHigobigLrhuobiiKfiiazigoZFVGjilqHKgOKJrMKowqvih6cy4bqHOsK7wr3HksO34oKHzqDiiaTCtjrJvXHiiIfCqMK7MTLPhOG6h2tBWsabw7ckZiR2ajtmWsKr4oay4oa1xJbCr+KJpeqYjeKJoH3Eikvhuavin5HJlmjhuarigbp8b0kz4oyIJeKAn+G5mUsvaeKBuiHhuYXIrmnIp1Mn4oKMzrJQ4oWb4oCb4bmZ4oinNsaIOzfihpTii47CoeKGtUdd4bifyb7huIvigKAq4oaRb8Kr4oenMjNmMjDhuotm4bqHV2Y64oaQ4bif4oC6aSIsIjtaxptgID0+IGBqIiwiW1wiQUZcIiwgXCJBWFwiLCBcIkFMXCIsIFwiRFpcIiwgXCJBU1wiLCBcIkFEXCIsIFwiQU9cIiwgXCJBSVwiLCBcIkFRXCIsIFwiQUdcIiwgXCJBUlwiLCBcIkFNXCIsIFwiQVdcIiwgXCJBVVwiLCBcIkFUXCIsIFwiQVpcIiwgXCJCU1wiLCBcIkJIXCIsIFwiQkRcIiwgXCJCQlwiLCBcIkJZXCIsIFwiQkVcIiwgXCJCWlwiLCBcIkJKXCIsIFwiQk1cIiwgXCJCVFwiLCBcIkJPXCIsIFwiQkFcIiwgXCJCV1wiLCBcIkJWXCIsIFwiQlJcIiwgXCJWR1wiLCBcIklPXCIsIFwiQk5cIiwgXCJCR1wiLCBcIkJGXCIsIFwiQklcIiwgXCJLSFwiLCBcIkNNXCIsIFwiQ0FcIiwgXCJDVlwiLCBcIktZXCIsIFwiQ0ZcIiwgXCJURFwiLCBcIkNMXCIsIFwiQ05cIiwgXCJIS1wiLCBcIk1PXCIsIFwiQ1hcIiwgXCJDQ1wiLCBcIkNPXCIsIFwiS01cIiwgXCJDR1wiLCBcIkNEXCIsIFwiQ0tcIiwgXCJDUlwiLCBcIkNJXCIsIFwiSFJcIiwgXCJDVVwiLCBcIkNZXCIsIFwiQ1pcIiwgXCJES1wiLCBcIkRKXCIsIFwiRE1cIiwgXCJET1wiLCBcIkVDXCIsIFwiRUdcIiwgXCJTVlwiLCBcIkdRXCIsIFwiRVJcIiwgXCJFRVwiLCBcIkVUXCIsIFwiRktcIiwgXCJGT1wiLCBcIkZKXCIsIFwiRklcIiwgXCJGUlwiLCBcIkdGXCIsIFwiUEZcIiwgXCJURlwiLCBcIkdBXCIsIFwiR01cIiwgXCJHRVwiLCBcIkRFXCIsIFwiR0hcIiwgXCJHSVwiLCBcIkdSXCIsIFwiR0xcIiwgXCJHRFwiLCBcIkdQXCIsIFwiR1VcIiwgXCJHVFwiLCBcIkdHXCIsIFwiR05cIiwgXCJHV1wiLCBcIkdZXCIsIFwiSFRcIiwgXCJITVwiLCBcIlZBXCIsIFwiSE5cIiwgXCJIVVwiLCBcIklTXCIsIFwiSU5cIiwgXCJJRFwiLCBcIklSXCIsIFwiSVFcIiwgXCJJRVwiLCBcIklNXCIsIFwiSUxcIiwgXCJJVFwiLCBcIkpNXCIsIFwiSlBcIiwgXCJKRVwiLCBcIkpPXCIsIFwiS1pcIiwgXCJLRVwiLCBcIktJXCIsIFwiS1BcIiwgXCJLUlwiLCBcIktXXCIsIFwiS0dcIiwgXCJMQVwiLCBcIkxWXCIsIFwiTEJcIiwgXCJMU1wiLCBcIkxSXCIsIFwiTFlcIiwgXCJMSVwiLCBcIkxUXCIsIFwiTFVcIiwgXCJNS1wiLCBcIk1HXCIsIFwiTVdcIiwgXCJNWVwiLCBcIk1WXCIsIFwiTUxcIiwgXCJNVFwiLCBcIk1IXCIsIFwiTVFcIiwgXCJNUlwiLCBcIk1VXCIsIFwiWVRcIiwgXCJNWFwiLCBcIkZNXCIsIFwiTURcIiwgXCJNQ1wiLCBcIk1OXCIsIFwiTUVcIiwgXCJNU1wiLCBcIk1BXCIsIFwiTVpcIiwgXCJNTVwiLCBcIk5BXCIsIFwiTlJcIiwgXCJOUFwiLCBcIk5MXCIsIFwiQU5cIiwgXCJOQ1wiLCBcIk5aXCIsIFwiTklcIiwgXCJORVwiLCBcIk5HXCIsIFwiTlVcIiwgXCJORlwiLCBcIk1QXCIsIFwiTk9cIiwgXCJPTVwiLCBcIlBLXCIsIFwiUFdcIiwgXCJQU1wiLCBcIlBBXCIsIFwiUEdcIiwgXCJQWVwiLCBcIlBFXCIsIFwiUEhcIiwgXCJQTlwiLCBcIlBMXCIsIFwiUFRcIiwgXCJQUlwiLCBcIlFBXCIsIFwiUkVcIiwgXCJST1wiLCBcIlJVXCIsIFwiUldcIiwgXCJCTFwiLCBcIlNIXCIsIFwiS05cIiwgXCJMQ1wiLCBcIk1GXCIsIFwiUE1cIiwgXCJWQ1wiLCBcIldTXCIsIFwiU01cIiwgXCJTVFwiLCBcIlNBXCIsIFwiU05cIiwgXCJSU1wiLCBcIlNDXCIsIFwiU0xcIiwgXCJTR1wiLCBcIlNLXCIsIFwiU0lcIiwgXCJTQlwiLCBcIlNPXCIsIFwiWkFcIiwgXCJHU1wiLCBcIlNTXCIsIFwiRVNcIiwgXCJMS1wiLCBcIlNEXCIsIFwiU1JcIiwgXCJTSlwiLCBcIlNaXCIsIFwiU0VcIiwgXCJDSFwiLCBcIlNZXCIsIFwiVFdcIiwgXCJUSlwiLCBcIlRaXCIsIFwiVEhcIiwgXCJUTFwiLCBcIlRHXCIsIFwiVEtcIiwgXCJUT1wiLCBcIlRUXCIsIFwiVE5cIiwgXCJUUlwiLCBcIlRNXCIsIFwiVENcIiwgXCJUVlwiLCBcIlVHXCIsIFwiVUFcIiwgXCJBRVwiLCBcIkdCXCIsIFwiVVNcIiwgXCJVTVwiLCBcIlVZXCIsIFwiVVpcIiwgXCJWVVwiLCBcIlZFXCIsIFwiVk5cIiwgXCJWSVwiLCBcIldGXCIsIFwiRUhcIiwgXCJZRVwiLCBcIlpNXCIsIFwiWldcIl0iXQ==)
Messy port of 05AB1E.
## How?
```
«⟑``‟Ḃȯ†√¦∑iRṫΠʁǓ₴5]p#4Ṅl}3ẋ¶T+⟑V]ḭr≤ṁǔ
A»cP⌐kẋṠ†⟇Ǔ≈ɽ⟩›ṪwSʀ₇⌊Ǔ∇•Xwð⇩I‡ṅfβ℅₍ṗµ∆€¾aǍ⟑Ȧ2⋏$λ⁺]/|f₁Pa⟨,₁,h¨ṁ₌ε⟑‹İ⟨Nṫw%yĖ⁼*>₈˹ȯU÷s¬)∨ʀ0ŀƈ½)(m-Ẋ ǓḂ⟩[0e•₂↲S⟇Ġj⟨^ɖg[⌐₁⋏żo:ẎRʁ⌐ð%⇧↓Y*?* †8„S|⁽l3√⁺⟑«
# Push compressed string "dzaibwbrbfdmfrghitlvmdngrwknlclktzthtcugusalvgcugagmgiuzzmgrnihmhninmknlssazczlipsslchzwzaafarhkmnetcrdjerfjhtmwmlprumccnftjbebocoismhnpncnzphtkaskhdogugtnablwssosjvnyebtcafihuidirimjpkelbompashsdtwtovegelalsmctgttcystsgesbhbgcmcxjokimsmammnenopesmsygbviaumymurutlbviovakwmranqavcvubmecdeltnrrerosacihrluegggjekg"
⇧ # Uppercase
2ẇ # Split into chunks of two
: # Duplicate
»⟑⟇βE'ċ¬$≠∪₀↳↲æMf» # Push compressed integer 5045888909142307005039435397419896531
₄τ # Convert to base-26 as a list: [21,8,2,6,7,1,4,1,9,0,3,10,12,17,6,4,0,16,5,9,8,2,0,1,3,1]
ẇ # Split the string into chunks of that size: [["DZ", "AI", ..., "US"], ["AL", "VG", ..., "ZM"], ["GR", "NI"], ..., ["KG"]]
kA # Push the uppercase alphabet
¨£vJ # Zip the list with the alphabet, and for each, append the corresponding letter to each:
# [["DZA", "AIA", ..., "USA"], ["ALB", "VGB", ..., "ZMB"], ["GRC", "NIC"], ..., ["KGZ"]]
f # Flatten
Z # Zip the ["DZ", "AI", "BW", ...] list with this
«ƛ¤‛H∧λŻJ@±*dCẋ°4£Mgċ ≥ƒX¢ǎd≤ǔ₈b¢&Ẋ≈•ġ.ẎAl>₅j¨∵½↳Ŀa>€¼₌Rǔb*JA⌐Ḃ∵Ḣ3\⌈|ẋ;Π1₆›Ẇ∧≬₆ETh□ʀ≬¨«
# Push compressed string "cfjmkzpkmfawlrlytdpnbimgmvmxsnaobdbsclcngnnutmbzsvfkgpmtpwsbwfaddkgqmemppgcgcdckkrmzplcvambbbnfoglgdiqpyptaeuyfmehagmqatgfgysrtntrtvskszsepfsc"
⇧2ẇ # Uppercase and split into chunks of two
: # Duplicate
»½ǒ÷₇Π≤¶:ɽq∇¨» # Push compressed integer 5023299766197034891137684120
12τ # Convert to base 12 as a list: [5,3,2,3,2,0,2,3,2,0,1,8,0,6,6,1,0,11,2,2,7,1,2,0,2,0]
ẇ # Split the list into chunks of that size: [["CF", "JM", "KZ", "PK", "MF"], ["AW", "LR", "LY"], ..., ["PF", "SC"], []]
kAZ # Zip with the uppercase alphabet
ƛ÷$f$vj; # Map, and for each, insert the letter between each string: [["CAF", "JAM", "KAZ", "PAK", "MAF"], ..., ["PYF", "SYC"], []]
fZ # Flatten and zip the ["CF", "JM", ..., "SC"] list with this
«↲↵˝≥꘍≠}ĊKṫ⟑ɖhṪ⁺|oI3⌈%‟ṙK/i⁺!ṅȮiȧS'₌βP⅛‛ṙ∧6ƈ;7↔⋎¡↵G]ḟɾḋ†*↑o«
# Push compressed string "aqataaxalababihbjbenbyblreeestgssgsgwgnbieirlilisrkmcomkpprkkycymmomacpmspmrssrbsisvntfatfuaukrytmyt"
⇧ # Uppercase
23f # Push list [2, 3]
20ẋf # Repeat it twenty times: [2, 3, 2, 3, 2, 3, ..., 2, 3]
ẇ # Split the string into chunks of that size: ["AQ", "ATA", "AX", ..., "YT", "MYT"]
W # Wrap the stack into a list
f # Flatten
: # Duplicate
⁰ḟ # Find the index of the input in it
› # Increment
i # Index into the list
```
[Answer]
# C - 1324 Bytes
```
char*c="AFAFGAXALAALALBDZDZAASASMADANDAOAGOAIAIAAQATAAGATGARARGAMARMAWABWAUAUSATAUTAZAZEBSBHSBHBHRBDBGDBBBRBBYBLRBEBELBZBLZBJBENBMBMUBTBTNBOBOLBABIHBWBWABVBVTBRBRAVGVGBIOIOTBNBRNBGBGRBFBFABIBDIKHKHMCMCMRCACANCVCPVKYCYMCFCAFTDTCDCLCHLCNCHNHKHKGMOMACCXCXRCCCCKCOCOLKMCOMCGCOGCDCODCKCOKCRCRICICIVHRHRVCUCUBCYCYPCZCZEDKDNKDJDJIDMDMADODOMECECUEGEGYSVSLVGQGNQERERIEEESTETETHFKFLKFOFROFJFJIFIFINFRFRAGFGUFPFPYFTFATFGAGABGMGMBGEGEODEDEUGHGHAGIGIBGRGRCGLGRLGDGRDGPGLPGUGUMGTGTMGGGGYGNGINGWGNBGYGUYHTHTIHMHMDVAVATHNHNDHUHUNISISLININDIDIDNIRIRNIQIRQIEIRLIMIMNILISRITITAJMJAMJPJPNJEJEYJOJORKZKAZKEKENKIKIRKPPRKKRKORKWKWTKGKGZLALAOLVLVALBLBNLSLSOLRLBRLYLBYLILIELTLTULULUXMKMKDMGMDGMWMWIMYMYSMVMDVMLMLIMTMLTMHMHLMQMTQMRMRTMUMUSYTMYTMXMEXFMFSMMDMDAMCMCOMNMNGMEMNEMSMSRMAMARMZMOZMMMMRNANAMNRNRUNPNPLNLNLDANANTNCNCLNZNZLNINICNENERNGNGANUNIUNFNFKMPMNPNONOROMOMNPKPAKPWPLWPSPSEPAPANPGPNGPYPRYPEPERPHPHLPNPCNPLPOLPTPRTPRPRIQAQATREREUROROURURUSRWRWABLBLMSHSHNKNKNALCLCAMFMAFPMSPMVCVCTWSWSMSMSMRSTSTPSASAUSNSENRSSRBSCSYCSLSLESGSGPSKSVKSISVNSBSLBSOSOMZAZAFGSSGSSSSSDESESPLKLKASDSDNSRSURSJSJMSZSWZSESWECHCHESYSYRTWTWNTJTJKTZTZATHTHATLTLSTGTGOTKTKLTOTONTTTTOTNTUNTRTURTMTKMTCTCATVTUVUGUGAUAUKRAEAREGBGBRUSUSAUMUMIUYURYUZUZBVUVUTVEVENVNVNMVIVIRWFWLFEHESHYEYEMZMZMBZWZWE";f(char* i){for(;*c;c+=5)!strncmp(c, i,2)&&printf("%c%c%c",*(c+2),*(c+3),*(c+4));}
```
**Ungolfed**
```
char*c = "AFAFGAXALAALALBDZDZAASASMADANDAOAGOAIAIAAQATAAGATGARARGAMARMAWABWAUAUSATAUTAZAZEBSBHSBHBHRBDBGDBBBRBBYBLRBEBELBZBLZBJBENBMBMUBTBTNBOBOLBABIHBWBWABVBVTBRBRAVGVGBIOIOTBNBRNBGBGRBFBFABIBDIKHKHMCMCMRCACANCVCPVKYCYMCFCAFTDTCDCLCHLCNCHNHKHKGMOMACCXCXRCCCCKCOCOLKMCOMCGCOGCDCODCKCOKCRCRICICIVHRHRVCUCUBCYCYPCZCZEDKDNKDJDJIDMDMADODOMECECUEGEGYSVSLVGQGNQERERIEEESTETETHFKFLKFOFROFJFJIFIFINFRFRAGFGUFPFPYFTFATFGAGABGMGMBGEGEODEDEUGHGHAGIGIBGRGRCGLGRLGDGRDGPGLPGUGUMGTGTMGGGGYGNGINGWGNBGYGUYHTHTIHMHMDVAVATHNHNDHUHUNISISLININDIDIDNIRIRNIQIRQIEIRLIMIMNILISRITITAJMJAMJPJPNJEJEYJOJORKZKAZKEKENKIKIRKPPRKKRKORKWKWTKGKGZLALAOLVLVALBLBNLSLSOLRLBRLYLBYLILIELTLTULULUXMKMKDMGMDGMWMWIMYMYSMVMDVMLMLIMTMLTMHMHLMQMTQMRMRTMUMUSYTMYTMXMEXFMFSMMDMDAMCMCOMNMNGMEMNEMSMSRMAMARMZMOZMMMMRNANAMNRNRUNPNPLNLNLDANANTNCNCLNZNZLNINICNENERNGNGANUNIUNFNFKMPMNPNONOROMOMNPKPAKPWPLWPSPSEPAPANPGPNGPYPRYPEPERPHPHLPNPCNPLPOLPTPRTPRPRIQAQATREREUROROURURUSRWRWABLBLMSHSHNKNKNALCLCAMFMAFPMSPMVCVCTWSWSMSMSMRSTSTPSASAUSNSENRSSRBSCSYCSLSLESGSGPSKSVKSISVNSBSLBSOSOMZAZAFGSSGSSSSSDESESPLKLKASDSDNSRSURSJSJMSZSWZSESWECHCHESYSYRTWTWNTJTJKTZTZATHTHATLTLSTGTGOTKTKLTOTONTTTTOTNTUNTRTURTMTKMTCTCATVTUVUGUGAUAUKRAEAREGBGBRUSUSAUMUMIUYURYUZUZBVUVUTVEVENVNVNMVIVIRWFWLFEHESHYEYEMZMZMBZWZWE";
f(char* i)
{
for(; *c; c += 5)
!strncmp(c, i, 2) && printf("%c%c%c", *(c + 2), *(c + 3), *(c + 4));
}
```
**Explanation**
A function that receives a character string with an Alpha-2 code and converts it to Alpha-3 using a "raw" list which contains the Alpha-2 codes followed by their Alpha-3 counterpart every five(5) characters; the function looks for the given code within the list and if it is found its counterpart is displayed.
Tested on GCC, generates some warnings if not compiled with std=c89.
## C99 - 1296 Bytes (By @ceilingcat)
```
f(int*i){for(char*c="AFAFGAXALAALALBDZDZAASASMADANDAOAGOAIAIAAQATAAGATGARARGAMARMAWABWAUAUSATAUTAZAZEBSBHSBHBHRBDBGDBBBRBBYBLRBEBELBZBLZBJBENBMBMUBTBTNBOBOLBABIHBWBWABVBVTBRBRAVGVGBIOIOTBNBRNBGBGRBFBFABIBDIKHKHMCMCMRCACANCVCPVKYCYMCFCAFTDTCDCLCHLCNCHNHKHKGMOMACCXCXRCCCCKCOCOLKMCOMCGCOGCDCODCKCOKCRCRICICIVHRHRVCUCUBCYCYPCZCZEDKDNKDJDJIDMDMADODOMECECUEGEGYSVSLVGQGNQERERIEEESTETETHFKFLKFOFROFJFJIFIFINFRFRAGFGUFPFPYFTFATFGAGABGMGMBGEGEODEDEUGHGHAGIGIBGRGRCGLGRLGDGRDGPGLPGUGUMGTGTMGGGGYGNGINGWGNBGYGUYHTHTIHMHMDVAVATHNHNDHUHUNISISLININDIDIDNIRIRNIQIRQIEIRLIMIMNILISRITITAJMJAMJPJPNJEJEYJOJORKZKAZKEKENKIKIRKPPRKKRKORKWKWTKGKGZLALAOLVLVALBLBNLSLSOLRLBRLYLBYLILIELTLTULULUXMKMKDMGMDGMWMWIMYMYSMVMDVMLMLIMTMLTMHMHLMQMTQMRMRTMUMUSYTMYTMXMEXFMFSMMDMDAMCMCOMNMNGMEMNEMSMSRMAMARMZMOZMMMMRNANAMNRNRUNPNPLNLNLDANANTNCNCLNZNZLNINICNENERNGNGANUNIUNFNFKMPMNPNONOROMOMNPKPAKPWPLWPSPSEPAPANPGPNGPYPRYPEPERPHPHLPNPCNPLPOLPTPRTPRPRIQAQATREREUROROURURUSRWRWABLBLMSHSHNKNKNALCLCAMFMAFPMSPMVCVCTWSWSMSMSMRSTSTPSASAUSNSENRSSRBSCSYCSLSLESGSGPSKSVKSISVNSBSLBSOSOMZAZAFGSSGSSSSSDESESPLKLKASDSDNSRSURSJSJMSZSWZSESWECHCHESYSYRTWTWNTJTJKTZTZATHTHATLTLSTGTGOTKTKLTOTONTTTTOTNTUNTRTURTMTKMTCTCATVTUVUGUGAUAUKRAEAREGBGBRUSUSAUMUMIUYURYUZUZBVUVUTVEVENVNVNMVIVIRWFWLFEHESHYEYEMZMZMBZWZWE";*c;c+=5)write(!strncmp(c,i,2),c+2,3);}
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 111 bytes
```
Switch[#,"HM","HMD","AN","ANT","PS","PSE",_,Association[#@"CountryCode"->#@"UNCode"&/@EntityList@"Country"]@#]&
```
Don't [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7g8syQ5I1pZR8nDVwlEuABJRz8wEQIkA4LBhKuSTryOY3FxfnImUGt@XrSyg5JzfmleSVGlc35KqpKuHVAg1A/MVtN3cM0rySyp9MksLoErU4p1UI5V@x9QlJlXEp2m71Ct5OKqBLUVbB/YptBgpdrY/wA "Wolfram Language (Mathematica) – Try It Online")
[Try in the Wolfram Cloud!](https://www.wolframcloud.com/obj/4ec45ac9-dd2f-4a24-8c75-de1e61660872)
---
Explanation:
`Switch[#,"HM","HMD","AN","ANT","PS","PSE",` If our input is equal to one of the three countries not in the Mathematica database, return the correct code.
`_,` Otherwise
`Association[#@"CountryCode"->#@"UNCode"&/@EntityList@"Country"]` Create an association between the two-letter and three-letter codes of each country
`@#]` and find the value matching the input.
[Answer]
# C, 216+554+1=771 bytes
```
#include<stdio.h>
#define G d=getc(f);w=d&31|64
FILE*f;char c,d,r[4],y,w;char*z(a,b){for(f=fopen("f","r");;){G;c=d/4&56;y=w;G;c|=d>>5&7;*r=a;r[1]=r[2]=b;r[c>26?1:2]=c&31|64;if(!c)fgets(r,4,f);if(a==y&b==w)return r;}}
```
It requires this file with the name "f" in the same directory, shown here as a hex dump. You can use `cut -c 11-58 "data.txt" | xxd -r -p > f` to recreate the file. It should have 554 bytes.
```
00000000 01 e6 01 18 41 4c 41 01 4c 04 3a 21 b3 a1 c4 81 |....ALA.L.:!....|
00000010 ef 01 29 01 11 41 54 41 c1 87 01 f2 c1 4d 81 57 |..)..ATA.....M.W|
00000020 41 75 c1 b4 01 ba a2 13 42 48 82 e4 c2 42 02 19 |Au......BH...B..|
00000030 42 4c 52 22 85 a2 9a 02 0a 42 45 4e 42 ad 22 d4 |BLR".....BENB.".|
00000040 22 8f 02 01 42 49 48 02 37 42 96 02 32 16 47 49 |"...BIH.7B..2.GI|
00000050 8f c2 4e 42 47 02 26 82 89 2b a8 43 4d 23 c1 c3 |..NBG.&..+.CM#..|
00000060 16 0b 19 43 59 4d 83 26 94 64 a3 0c a3 0e 08 eb |...CYM.&.d......|
00000070 0d 0f 4d 41 43 43 58 23 63 23 8f 0b 0d 43 4f 4d |..MACCX#c#...COM|
00000080 a3 e7 a3 e4 a3 eb 23 32 43 c9 48 d2 03 55 43 19 |......#2C.H..UC.|
00000090 03 ba a4 cb 24 2a 04 2d 24 af 45 a3 65 27 b3 96 |....$*.-$.E.e'..|
000000a0 a7 d1 25 32 05 05 45 53 54 25 14 a6 8b c6 4f 26 |..%2..EST%....O&|
000000b0 2a 26 c9 06 32 c7 a6 f0 26 14 06 41 54 46 07 41 |*&..2...&..ATF.A|
000000c0 07 4d 27 e5 44 a5 07 28 07 49 07 72 c7 4c c7 44 |.M'.D..(.I.r.L.D|
000000d0 a7 90 27 b5 27 b4 67 27 a7 2e 07 17 47 4e 42 c7 |..'.'.g'....GNB.|
000000e0 b9 28 34 08 8d 56 81 08 8e 28 d5 29 93 09 8e 29 |.(4..V...(.)...)|
000000f0 c4 29 d2 c9 51 09 05 49 52 4c 29 cd 09 0c 49 53 |.)..Q..IRL)...IS|
00000100 52 09 34 8a 2d 2a d0 6a 25 4a 4f 8b 3a 2b c5 4b |R.4.-*.j%JO.:+.K|
00000110 49 0b 10 50 52 4b ab f2 4b 97 6b 47 2c e1 0c 36 |I..PRK..K.kG,..6|
00000120 2c c2 2c f3 8c 52 8c 59 0c a9 4c b4 6c 15 0d 8b |,.,..R.Y..L.l...|
00000130 8d 87 2d 37 4d 79 8d 96 2d 2c ad 94 2d 88 cd 91 |..-7My..-,..-...|
00000140 4d 92 4d 75 19 14 4d 59 54 8d b8 c6 6d 0d 24 2d |M.Mu..MYT...m.$-|
00000150 e3 0d ee ad c5 4d 53 4d 41 ad fa 4d 4d 2e a1 4e |.....MSMA..MM..N|
00000160 b2 2e 90 0e 8c 41 8e 2e 83 2e 9a 0e 69 4e 45 0e |.....A......iNE.|
00000170 27 ae 35 2e 66 ad d0 4e 4f 2f cd 90 2b b0 97 10 |'.5.f..NO/..+...|
00000180 b3 30 c1 b0 c7 d0 59 50 45 30 88 90 6e b0 ec d0 |.0....YPE0..n...|
00000190 54 30 32 51 81 52 a5 52 af 52 75 12 37 22 ac 33 |T02Q.R.R.Ru.7".3|
000001a0 c8 0b 2e 0c 23 8d 26 10 0d 53 50 4d 56 83 37 b3 |....#.&..SPMV.7.|
000001b0 53 4d 53 14 53 a1 93 ae 12 13 53 52 42 f3 23 13 |SMS.S.....SRB.#.|
000001c0 ac 53 07 d3 cb 13 09 53 56 4e b3 82 33 af 1a c1 |.S.....SVN..3...|
000001d0 07 13 53 47 53 13 93 45 13 0c 2b 33 c4 d3 b2 33 |..SGS..E..+3...3|
000001e0 aa d3 fa d3 e5 03 a8 53 59 34 d7 34 6a 14 3a 14 |.......SY4.4j.:.|
000001f0 28 54 6c 34 e7 34 8b 34 cf 34 f4 d4 ae d4 b2 b4 |(Tl4.4.4.4......|
00000200 6d 14 23 d4 b6 15 27 15 01 55 4b 52 c1 45 47 42 |m.#...'..UKR.EGB|
00000210 15 33 35 2d d5 59 15 5a 56 95 36 c5 36 ae 56 49 |.35-.Y.ZV.6.6.VI|
00000220 b7 86 c5 68 39 a5 1a 4d 1a b7 |...h9..M..|
0000022a
```
The function takes the Alpha-2 code as two separate characters, which must be capitalized, and returns the capitalized Alpha-3 code. I don't know of an online compiler that allows you to include binary files like this, so no link, unfortunately.
#### Explanation:
Since we're only dealing with capital letters, we can use only the lower five bits to store a character. The basic strategy is to store the Alpha-2 codes in the file, and use the bits we save to describe how to create the Alpha-3 code; then, the program will search for the Alpha-2 code and follow the instructions.
The instruction format is simple. We have six instruction bits. The lower five bits store a 5-bit letter code which can be converted to ASCII with `&31|64`. If the high bit is zero, the letter is added to the end of the code. If it's one, the letter is inserted in the middle. If the instruction bits are all zero, the file stores the complete Alpha-3 code in the next 3 bytes of the file (these are visible in the hex dump).
Of the 247 conversions, 156 append a character to the end, 71 insert a character in the middle, 4 prepend a character to the beginning, and 16 conversions are replacements, which are anything not included in the other categories. Inserts and appends only use two bytes in the file, while the others use five; (156+71)\*2+(4+16)\*5=554 bytes.
Ungolfed version:
```
#include <stdio.h>
FILE* f;
char c,d,r[4],y,w;
char* z(a,b){
for(f=fopen("f","r");;){
// get first character
d=getc(f); w=d&31|64;
c=d/4&56;
y=w;
// get second character
d=getc(f); w=d&31|64;
c|=d>>5&7; // c now holds the instruction
// prepare return string for inserts/appends
r[0]=a;
r[1]=r[2]=b;
r[c>26?1:2]=c&31|64; // insert or append
if(!c) // replace
fgets(r,4,f);
if(a==y&b==w)
return r;
}
}
```
] |
[Question]
[
Write the shortest code you can that produces an infinite output.
That's all. You code will only be disqualified if it stops producing output at some point. As always in code golf, the shortest code wins.
Here's a list of answers that I think are really clever, so they can get credit:
* [The comma is both code and data](https://codegolf.stackexchange.com/a/37210/8611)
* [Infinite errors (that counts)](https://codegolf.stackexchange.com/a/26418/8611)
* [Infinite warnings (that also counts)](https://codegolf.stackexchange.com/a/20902/8611)
* [What's Marbelous?](https://codegolf.stackexchange.com/a/37209/8611)
## Leaderboard
```
var QUESTION_ID=13152,OVERRIDE_USER=8611;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&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(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.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(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;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="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <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><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><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
## [Spice](https://github.com/Slord6/Spice), 26 bytes
Spice module that recursively calls itself. Quite quickly hits a stack overflow.
Given the code is saved to a module named 'x':
```
;return@OUT a;LOD .\x a a;
```
## Un-golfed explanation
```
;a;return@ - define variables: "a" and the required "return"
OUT a; - output a, implicitly "[0]"
LOD .\x a a; - call this module, passing a, storing result in a
```
[Answer]
## [Roj](https://github.com/RojerGS/Roj), 19 bytes
```
while(1)do out""end
```
This produces output because of the `[out]:` buffer.
[Answer]
# T-SQL, 15 bytes
```
a:PRINT 0GOTO a
```
6 years and 10 pages of answers, and no SQL versions yet.
Notes:
* `PRINT` is 1 byte less than a `SELECT`.
* A label with a goto is 1 byte shorter than the shortest `WHILE` statement: `WHILE 1=1PRINT 1` (you can't just do `WHILE 1` in SQL)
* Depending on the version of SQL Management Studio, the "messages" pane (which displays the result of `PRINT` statements), might not immediately refresh; this is a client-side UI issue only.
[Answer]
# Go, 59 characters
```
package main
import "fmt"
func main(){for{fmt.Print(0)}}
```
[Answer]
# [International Phonetic Esoteric Language](https://esolangs.org/wiki/International_Phonetic_Esoteric_Language), 6 bytes
```
10ɑeoɒ
```
Will print `0` with newlines forever.
Explanation:
```
10ɑeoɒ
10 (push the bounds for the loop: from 0 to 1)
ɑ (pop the bounds and start the loop)
e (push the current index)
o (print)
ɒ (check if index < start. 0 < 1, so loop)
```
[Answer]
# Ruby, ~~11~~ 9 characters
```
loop{p:p}
```
Old answer:
```
p 0 while 1
```
[Answer]
# [Rockstar](https://codewithrockstar.com/), 13 bytes
```
while 1 say 1
```
[Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in)
[Answer]
## ARM Thumb, Linux syscalls only, 12 bytes
Raw machine code:
```
2704 2001 4669 2201 df00 e7f9
```
Assembly:
```
.text
.globl _start
.thumb
.thumb_func
_start:
movs r7, #4 @ write syscall
movs r0, #1 @ STDOUT_FILENO
mov r1, sp @ sp is a valid pointer. May not be legible, but...
movs r2, #1 @ one byte is fine
svc #0 @ syscall: write(STDOUT_FILENO, sp, 1)
b _start @ loop forever
```
## ARM Thumb, with libc, 6 bytes
Raw machine code (`f7ff fffe` is an unlinked libc call):
```
f7ff fffe e7fc
```
Assembly:
```
.text
.globl main
.thumb
.thumb_func
@ Note that putchar returns the char it put, so we do this:
@ for (;;) putchar(argc);
main:
bl putchar @ putchar(argc)
b main @ Loop forever
```
Fun fact: These programs do the exact same thing, printing argc % 256 in binary infinitely, since `sp[0]` at `_start` is also `argc`.
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 1 byte
```
'
```
[Try it online!](https://tio.run/##S0pNK81LT/3/X/3/fwA "Befunge-93 – Try It Online")
```
' # full program
' # invalid command, NOP but raises warning
```
[Answer]
# [Duocentehexaquinquagesimal](https://esolangs.org/wiki/Duocentehexaquinquagesimal), 2 bytes
```
L½
```
[Try it online!](https://tio.run/##S0oszvifnFhiYxPzqGGRXbx1cWqKgm6mgrphsXWcNVDIWl0hXsHILq80x7qkqDQPqDRVQbdY11Ah3jo1OSNfQTdPQR2oLOnQMuPDW5yP7stQsrPR1tXTiY5VetSw0Evdzg6isEY/v6BEP784MSkzFUopxNslWYOFk4oSM/PSSpOzESyFpP8@h/b@Bxr9HwA)
[Answer]
# Pushy, 3 bytes
```
3[_
```
Explanation:
```
3 \ pushes 3 to the stack
[ \ starts an infinite loop
_ \ prints out the contents of the stack
```
[Answer]
# [Mascarpone](https://github.com/catseye/Mascarpone), 6.875 bytes
```
['@.:!]v*:!
```
[Try It Online!](https://tio.run/##y00sTk4sKsjPS/3/P1rdQc9KMbZMy0rx/38A)
### Explanation:
```
[ ] // push a string that will define an operation
'@. // push the symbol '@ and output it (popping it in the process)
:! // duplicate the top of the stack and execute it
v* // push a function/operation that does the above
:! // duplicate the operation, and execute it.
```
The operation duplicates and executes itself tail-recursively, generating the infinite output.
5 bits are sufficient for the characters used by this program, thus the total size is 55 bits, or 6.875 bytes
[Answer]
# [INTERCAL](http://www.catb.org/%7Eesr/intercal/), 26 bytes
```
DOCOMEFROM#1(1)DOREADOUT#0
```
[Try it online!](https://tio.run/##y8wrSS1KTsz5/9/F39nf19UtyN9X2VDDUNPFP8jV0cU/NETZ4P9/AA "INTERCAL – Try It Online")
This works for both C-INTERCAL and CLC-INTERCAL.
[Answer]
# [RETURN](https://esolangs.org/wiki/RETURN), 62 bytes
```
(())(()()()()()()()()()()()()()()()()())((()()()()()()()()()))
```
[Try it online!](https://tio.run/##K0otKS3K@/9fQ0NTE4gJQaAaLIKa//8DAA)
## Explanation:
```
(()) Add 1
(()()()()()()()()()()()()()()()()()) While nonzero repeat what's in the next group of brackets
(
(()()()()()()()()()) Put character
)
```
[Answer]
# [KonamiCode](https://esolangs.org/wiki/KonamiCode), 15 bytes
`v(^)L(^)<<<B(^)`
Explanation:
```
v(^) [Writes 1 to memory address 1.]
L(^) [A loop marker]
<<< [Output the current memory address as a number]
B(^) [A reverse-jump instruction, ending the loop.]
```
*Note:* We can't use 0 for the first instruction becuase the comparison buffer is set to 0 by default. This means that the reverse-jump's condition will be fulfilled and the loop will immediately exit. However, we could also replace this instruction with S(^) and have the program run the same way.
[Answer]
# [APOL](https://esolangs.org/wiki/APOL), 8 bytes
`w(T p(0))`
I'm not sure if this could reasonably be made smaller.
[Answer]
# [Headass](https://esolangs.org/wiki/Headass), 2 bytes
```
PE
```
[Try it here!](https://replit.com/@thejonymyster/HA23) copy and paste this: `srun("PE")`
Prints an infinite stream of 0s and newlines.
```
P Print the value of the current register (initialized at 0) + a newline
E Go to code block determined by value at current register,
Block 0 = return to start.
```
# [Headascii](https://esolangs.org/wiki/Headass#Headascii), 2 bytes
```
!E
```
[Try it here!](https://replit.com/@thejonymyster/HA23) copy and paste this: `erun("!E")`
Similar to the last one, but instead of printing 0s and newlines, it just prints newlines.
```
! Print the value of the string register (initially empty) + a newline
E Go to code block determined by value at current register,
Block 0 = return to start.
```
[Answer]
# Python 3, ~~18~~ 15 bytes
*Thanks to [DLosc](https://codegolf.stackexchange.com/users/16766/dlosc) for -3 bytes!*
```
while 1:print()
```
[Answer]
# [Appleseed](https://github.com/dloscutoff/appleseed), 26 bytes
```
(def start!(q(_(print!(0to
```
[Try it online!](https://tio.run/##SywoyEktTk1N@f9fIyU1TaG4JLGoRFGjUCNeo6AoMw/INCjJ//8fAA "Appleseed – Try It Online")
### Explanation
```
(def start! ; Define the start! event handler as
(q ; A function
(_ ; That takes any number of arguments
(print! ; And outputs
(0to ; The infinite list of all nonnegative integers
```
[Answer]
# [rusty\_deque](https://github.com/bigyihsuan/rusty_deque/), 17 bytes
```
1~{dup~ow~}~loop~
```
Forever print `1`s to the screen.
[Answer]
# [BitCycle](https://github.com/dloscutoff/esolangs/tree/master/BitCycle), 10 bytes
```
!
~<
1A^
```
Outputs an infinite bit stream of alternating 1s and 0s, or, with the `-u` or `-U` flags, an infinite sequence of 1s.
[Try it online!](https://tio.run/##S8osSa5Mzkn9/19BkUuhzobL0DHu/38A "BitCycle – Try It Online") or [with an online visualizer](https://dloscutoff.github.io/Esolangs/BitCycle/?p=cbrczwr1An)
[Answer]
# [Common Lisp](http://www.sbcl.org/), 15 bytes
```
(loop(princ'x))
```
[Try it online!](https://tio.run/##S87JLC74/18jJz@/QKOgKDMvWb1CU/P/fwA "Common Lisp – Try It Online")
[Answer]
# [A0A0](https://esolangs.org/wiki/A0A0), 43 39 bytes
```
A0A0
A0C3G1G1A0
A0O0A0
A0A1G-3G-3A0
G-3
```
Prints 0 forever. This uses a classic infinite loop which was created by the inventor of the language. Considering the only important thing about this code is that it runs infinitely, I'll use this post as an explanation of this looping construct, since it's the basis for all loops.
Loops are generally not really difficult in programming languages, even those which only have goto instructions and not proper looping constructs. A0A0 has goto instructions, so what's the problem? A0A0 is a self-modifying language which deletes the instruciton after it executes it. So if we were to use a goto to form a loop, we would simply end up at nothing and the program halts. This is not what we want.
Thankfully, the language contains instructions to modify its own code. There are two instructions that do this. `A#` and `C#` where # is a placeholder for an integer. `A#` appends the current line of instructions (excluding itself) to the line # positions below. `C#` clears the line # positions below this line. Since all integers are allowed, negative numbers can be used to go to lines above and 0 can be used to stay on the same line.
Let's take a look at the basis of the loop.
```
A0 A0
A0 C3 G1 G1 A0
A0 instructions here A0
A0 A1 G-3 G-3 A0
G-3
```
The first thing we do when entering the loop is go past four `A0` instructions which append their own lines to themselves. Remember that it excludes itself, so this first `A0` is not copied. This would be an issue on subsequent iterations, which is why at the very end of the loop, there is also an `A0`. This means that this A0 at the end is copied, which preserves the ability to copy the loop infinite amount of times.
You'll notice that the last line does not have any kind of append instruction. This is necessary, because we must at some point go back up and we can't go up if we have an `A#`. But if we never place a `G-3` there again, we eventually will end up there and, again get stuck since there's no instruction there. This is what line 4 is for. It contains the following:
```
A1 G-3 G-3
```
It places two `G-3` in line lower - at line 5. This preserves the ability for us to keep jumping back up forever. However, this line contains an A0 at the end. And during exeuciton, it may contain many more instructions we don't want. If we execute anything that is not `G-3`, we go to line 6 and left the loop. This is where line 2 comes into play. It contains a `C3` instruction, which clears the line three lines lower. This is line 5. Because the instructions are aligned properly, this means that the line is cleared the moment we would hit an instruction that is not `G-3`. And since at the same point there will be another `A1 G-3 G-3` on line 4, this now empty line will get two `G-3` instructions again, just in time.
You may observe that, since there are also `G-3` instructions on line 4, we may sometimes jump up to line 1 instead of line 2. And this is where line 1 comes into play. It only contains `A0 A0`. This will repeat itself infinitely on that line and acts as an infinite no-op. After executing a single instruction, the program counter automatically moves to the next line and we're back on line 2 again.
And all of this code gives us freedom on line 3. We can put whatever instructions we want in there, as long as these instructions don't modify the loop. We can even have multiple lines in the middle, as long as you change the `G-3` to the appropriate amount.
Edit: Optimized by 4 bytes. It turns out that there is no minimum requirement of 3 instructions for the loop, allowing us to drop 2 instructions, totalling 4 bytes.
[Answer]
# [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate) `-a`, 1 byte
```
*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72qKDU9NS-1KLEkdVm0km6iUuyCpaUlaboWC7UgNJS7AEoDAA)
Prints newlines forever :P it's finding and printing every possible match for at least 0 nothings, delimited with newlines. Surprised this isn't a syntax error.
[Answer]
# [BitCycle](https://github.com/dloscutoff/Esolangs/tree/master/BitCycle), 6 bytes
```
!~<
1^
```
Inspired by [emanresu A's suggested golf](https://codegolf.stackexchange.com/questions/13152/shortest-code-to-produce-infinite-output#comment555299_247161) to [des54321's answer](https://codegolf.stackexchange.com/a/247161/16766). Similarly to that answer, this outputs alternating 0s and 1s.
[Try it here!](https://dloscutoff.github.io/Esolangs/BitCycle/?p=bzwr1n)
### Explanation
The initial `1` bit is directed north into the dupneg (`~`). A negated copy (`0`) is sent west to the sink (`!`) and is output. A non-negated copy is sent east, whereupon it is immediately directed west again back into the dupneg. Now the original copy is sent north and leaves the playfield, while the negated copy is sent south, redirected north again, and the cycle continues forever (with the bit changing parity each time).
[Answer]
# [Fuzzy Octo Guacamole](https://github.com/RikerW/Fuzzy-Octo-Guacamole), 3 bytes
```
(1)
```
Infinitely outputs 1.
Due to weird implicit output and recursive loops (it executes the code inside the loop using recursion), 1 is outputted by the implicit output.
[Answer]
# Quetzalcoatl, 14 chars
```
while 1: ::' '
```
This is for an older version of Quetzalcoatl.
[Answer]
# [Intcode](https://esolangs.com/wiki/Intcode), 9 bytes
```
4,0,5,0,1
```
Outputs "4" an infinite number of times.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 4 bytes
```
W1P1
```
Prints the number `1` with a trailing newline over and over. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZLwg0DDCFMqAhMBgA)
This is a simple loop; in pseudocode,
```
while 1:
print 1
```
Almost any expression can be printed instead of `1`. For example, `W1Pr` prints random floats between 0 and 1 forever.
A more interesting option, also 4 bytes:
```
P*,u
```
This constructs an infinite range starting at 0 (`,u`) and then prints each element of it (`P*`). The result is an infinite loop that outputs the natural numbers one at a time. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZLArR0SiFMqAhMBgA)
[Answer]
# [Trilangle](https://github.com/bbrk24/Trilangle/), unbounded memory, 3 bytes
```
'1!
```
Push a 1 to the stack, print it, repeat.
## Trilangle, 4 bytes
```
'1,!
```
Push a 1 to the stack, print it, pop it off, repeat.
## Trilangle `-w`, 1 + 2 = 3 bytes
```
,
```
When run with the `-w` flag or in [the online interpreter](https://bbrk24.github.io/Trilangle/), popping from an empty stack prints a warning.
] |
[Question]
[
## Problem
John bought 5 apples. You are given the weights of every group of four apples, and must then find the weights of the apples themselves.
For example, if all apples without the first one weigh 798 g, without the second - 794 g, without the third - 813 g, without the fourth - 806 g, and without the fifth - 789 g, the weights are 202, 206, 187, 194, and 211.
## Rules
1. The solution of the problem by enumeration is allowed
2. Consider the number of points as follows: the number of bytes in your code. The lower the number of points, the better.
Have fun!
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 3 (or 5) [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
Σ¼,
```
No idea why MathGolf has a single-byte `a//4` builtin, but it's pretty useful here. ;)
[Try it online.](https://tio.run/##y00syUjPz0n7///c4kN7dP7/jza3tNAxtzTRsTAw1rEwNNMxt7CMBQA)
With strict input of space-delimited values it would be 5 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) instead:
```
ê_Σ¼,
```
[Try it online.](https://tio.run/##y00syUjPz0n7///wqvhziw/t0fn/39zSQsHc0kTBwsBYwcLQTMHcwhIA)
**Explanation:**
```
# Optional for stricter space-delimited input:
ê # Push the inputs as integer-array
_ # Duplicate it
Σ # Sum the values together
¼ # Integer-divide it by 4
, # Subtract each value in the list from this sum//4
# (after which the entire stack is output implicitly)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~9~~ ~~7~~ ~~6~~ 5 bytes
```
∑4ḭ$-
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiJE04bitJC0iLCIiLCJbNzk4LDc5NCw4MDMsODE2LDc4OV0iXQ==)
## Explanation
```
∑4ḭ$-
# (implicit input)
∑ # Sum
4ḭ # Divide the sum by four
$- # Swap and subtract
```
*-2 bytes thanks to a stone arachnid*
*-1 byte thanks to ovs*
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/index.html), ~~8~~ 6 bytes
*Edit: -2 bytes thanks to ovs*
```
-+´÷⟜4
```
[Try it at BQN online REPL](https://mlochbaum.github.io/BQN/try.html#code=QXBwbGVzIOKGkCAtK8K0w7fin5w0CkFwcGxlcyA3OTjigL83OTTigL84MTPigL84MDbigL83ODkK)
```
÷⟜4 # divide each of the input values by 4
+´ # and then fold the 'plus' function across them
- # using the negative of the input as a list of starting values
# (so effectively we start the fold using each negative input value
# in parallel as a starting value)
```
[Answer]
# [Python](https://www.python.org), 32 bytes
```
lambda a:[sum(a)/4-x for x in a]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3FXISc5NSEhUSraKLS3M1EjX1TXQrFNLyixQqFDLzFBJjoepUCooy80o0tNI0os0tLXQUzC1NdBQsDIyBhKEZkGthGaupCVG7YAGEBgA)
[Answer]
# [Haskell](https://www.haskell.org), 18 bytes
```
map=<<(-).(/4).sum
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ0W0km5yQYFS7OI025ilpSVpuhabchMLbG1sNHQ19TT0TTT1iktzIRI39XMTM_MUbBVS8rkUFAqKMvNKFFQU0hSizS0tdBTMLU10FCwMjIGEoRmQa2EZC9G2YAGEBgA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
aWx÷4
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LW0&code=YVd49zQ&input=Wzc5OCw3OTQsODEzLDgwNiw3ODld)
[Answer]
# [λ-2d](https://l-2d.glitch.me/), 456 squares
the program can be imported in [the playground](https://l-2d.glitch.me/) with the following JSON file
```
{"41,13":"entry","41,18":"entry","41,23":"entry","41,28":"entry","41,32":"entry","42,13":"end_s","42,18":"end_s","42,23":"end_s","42,28":"end_s","42,32":"end_s","43,13":"end_e","43,18":"end_e","43,23":"end_e","43,28":"end_e","43,32":"end_e","39,15":"wire_nw","39,20":"wire_nw","39,25":"wire_nw","39,30":"wire_nw","39,34":"wire_nw","38,15":"wire_ne","38,20":"wire_ne","38,25":"wire_ne","38,30":"wire_ne","38,34":"wire_ne","44,13":"frame_tl","44,18":"frame_tl","44,23":"frame_tl","44,28":"frame_tl","44,32":"frame_tl","45,13":"wire_we","45,18":"wire_we","45,23":"wire_we","45,28":"wire_we","45,32":"wire_we","46,13":"wire_we","46,18":"wire_we","46,23":"wire_we","46,28":"wire_we","46,32":"wire_we","47,13":"wire_we","47,18":"wire_we","47,23":"wire_we","47,28":"wire_we","47,32":"wire_we","47,15":"wire_we","47,20":"wire_we","47,25":"wire_we","47,30":"wire_we","47,34":"wire_we","46,15":"wire_we","46,20":"wire_we","46,25":"wire_we","46,30":"wire_we","46,34":"wire_we","45,15":"wire_we","45,20":"wire_we","45,25":"wire_we","45,30":"wire_we","45,34":"wire_we","48,13":"wire_sw","48,18":"wire_sw","48,23":"wire_sw","48,28":"wire_sw","48,32":"wire_sw","48,15":"wire_nw","48,20":"wire_nw","48,25":"wire_nw","48,30":"wire_nw","48,34":"wire_nw","44,15":"wire_ne","44,20":"wire_ne","44,25":"wire_ne","44,30":"wire_ne","44,34":"wire_ne","44,14":"wire_ns","44,19":"wire_ns","44,24":"wire_ns","44,29":"wire_ns","44,33":"wire_ns","48,14":"wire_ns","48,19":"wire_ns","48,24":"wire_ns","48,29":"wire_ns","48,33":"wire_ns","42,14":"wire_nw","42,19":"wire_nw","42,24":"wire_nw","42,29":"wire_nw","42,33":"wire_nw","41,14":"wire_we","41,19":"wire_we","41,24":"wire_we","41,29":"wire_we","41,33":"wire_we","40,14":"wire_we","40,19":"wire_we","40,24":"wire_we","40,29":"wire_we","40,33":"wire_we","38,14":"wire_sw","38,19":"wire_sw","38,24":"wire_sw","38,29":"wire_sw","38,33":"wire_sw","39,14":"func_call","39,19":"func_call","39,24":"func_call","39,29":"func_call","39,33":"func_call","39,13":"joint_nsw","39,18":"joint_nsw","39,23":"joint_nsw","39,28":"joint_nsw","38,13":"wire_we","38,18":"wire_we","38,23":"wire_we","38,28":"wire_we","37,13":"wire_se","37,18":"wire_se","37,23":"wire_se","37,28":"wire_se","37,14":"wire_nswe","37,19":"wire_nswe","37,24":"wire_nswe","37,29":"wire_nswe","37,17":"wire_nw","37,22":"wire_nw","37,27":"wire_nw","37,32":"wire_nw","36,17":"wire_se","36,22":"wire_se","36,27":"wire_se","36,32":"wire_se","37,15":"wire_ns","37,20":"wire_ns","37,25":"wire_ns","37,30":"wire_ns","36,15":"wire_nw","36,20":"wire_nw","36,25":"wire_nw","36,30":"wire_nw","36,34":"wire_nw","35,15":"wire_ne","35,20":"wire_ne","35,25":"wire_ne","35,30":"wire_ne","35,34":"wire_ne","35,14":"wire_sw","35,19":"wire_sw","35,24":"wire_sw","35,29":"wire_sw","35,33":"wire_sw","36,14":"func_call","36,19":"func_call","36,24":"func_call","36,29":"func_call","36,33":"func_call","36,13":"joint_nsw","36,18":"joint_nsw","36,23":"joint_nsw","36,28":"joint_nsw","35,13":"wire_we","35,18":"wire_we","35,23":"wire_we","35,28":"wire_we","34,13":"wire_se","34,18":"wire_se","34,23":"wire_se","34,28":"wire_se","34,14":"wire_nswe","34,19":"wire_nswe","34,24":"wire_nswe","34,29":"wire_nswe","34,17":"wire_nw","34,22":"wire_nw","34,27":"wire_nw","34,32":"wire_nw","33,17":"wire_se","33,22":"wire_se","33,27":"wire_se","33,32":"wire_se","34,15":"wire_ns","34,20":"wire_ns","34,25":"wire_ns","34,30":"wire_ns","33,15":"wire_nw","33,20":"wire_nw","33,25":"wire_nw","33,30":"wire_nw","33,34":"wire_nw","32,15":"wire_ne","32,20":"wire_ne","32,25":"wire_ne","32,30":"wire_ne","32,34":"wire_ne","32,14":"wire_sw","32,19":"wire_sw","32,24":"wire_sw","32,29":"wire_sw","32,33":"wire_sw","33,14":"func_call","33,19":"func_call","33,24":"func_call","33,29":"func_call","33,33":"func_call","33,13":"joint_nsw","33,18":"joint_nsw","33,23":"joint_nsw","33,28":"joint_nsw","32,13":"wire_we","32,18":"wire_we","32,23":"wire_we","32,28":"wire_we","31,13":"wire_se","31,18":"wire_se","31,23":"wire_se","31,28":"wire_se","31,14":"wire_nswe","31,19":"wire_nswe","31,24":"wire_nswe","31,29":"wire_nswe","31,17":"wire_nw","31,22":"wire_nw","31,27":"wire_nw","31,32":"wire_nw","30,17":"wire_se","30,22":"wire_se","30,27":"wire_se","30,32":"wire_se","31,15":"wire_ns","31,20":"wire_ns","31,25":"wire_ns","31,30":"wire_ns","30,15":"wire_nw","30,20":"wire_nw","30,25":"wire_nw","30,30":"wire_nw","30,34":"wire_nw","29,15":"wire_ne","29,20":"wire_ne","29,25":"wire_ne","29,30":"wire_ne","29,34":"wire_ne","29,14":"wire_sw","29,19":"wire_sw","29,24":"wire_sw","29,29":"wire_sw","29,33":"wire_sw","30,14":"func_call","30,19":"func_call","30,24":"func_call","30,29":"func_call","30,33":"func_call","30,13":"joint_nsw","30,18":"joint_nsw","30,23":"joint_nsw","30,28":"joint_nsw","29,13":"wire_we","29,18":"wire_we","29,23":"wire_we","29,28":"wire_we","28,13":"wire_se","28,18":"wire_se","28,23":"wire_se","28,28":"wire_se","28,14":"wire_nswe","28,19":"wire_nswe","28,24":"wire_nswe","28,29":"wire_nswe","28,17":"wire_nw","28,22":"wire_nw","28,27":"wire_nw","28,32":"wire_nw","27,17":"wire_se","27,22":"wire_se","27,27":"wire_se","27,32":"wire_se","28,15":"wire_ns","28,20":"wire_ns","28,25":"wire_ns","28,30":"wire_ns","27,14":"func_call","27,19":"func_call","27,24":"func_call","27,29":"func_call","27,33":"func_call","27,13":"joint_nsw","27,18":"joint_nsw","27,23":"joint_nsw","27,28":"joint_nsw","26,13":"wire_se","26,18":"wire_se","26,23":"wire_se","26,28":"wire_se","26,14":"wire_ns","26,19":"wire_ns","26,24":"wire_ns","26,29":"wire_ns","26,15":"wire_ns","26,20":"wire_ns","26,25":"wire_ns","26,30":"wire_ns","26,16":"wire_ne","26,21":"wire_ne","26,26":"wire_ne","26,31":"wire_ne","27,16":"wire_we","27,21":"wire_we","27,26":"wire_we","27,31":"wire_we","29,16":"wire_we","29,21":"wire_we","29,26":"wire_we","29,31":"wire_we","30,16":"wire_we","30,21":"wire_we","30,26":"wire_we","30,31":"wire_we","32,16":"wire_we","32,21":"wire_we","32,26":"wire_we","32,31":"wire_we","33,16":"wire_we","33,21":"wire_we","33,26":"wire_we","33,31":"wire_we","35,16":"wire_we","35,21":"wire_we","35,26":"wire_we","35,31":"wire_we","36,16":"wire_we","36,21":"wire_we","36,26":"wire_we","36,31":"wire_we","39,16":"wire_sw","39,21":"wire_sw","39,26":"wire_sw","39,31":"wire_sw","39,17":"wire_ns","39,22":"wire_ns","39,27":"wire_ns","39,32":"wire_ns","38,16":"wire_we","38,21":"wire_we","38,26":"wire_we","38,31":"wire_we","28,16":"wire_nswe","28,21":"wire_nswe","28,26":"wire_nswe","28,31":"wire_nswe","31,16":"wire_nswe","31,21":"wire_nswe","31,26":"wire_nswe","31,31":"wire_nswe","34,16":"wire_nswe","34,21":"wire_nswe","34,26":"wire_nswe","34,31":"wire_nswe","37,16":"wire_nswe","37,21":"wire_nswe","37,26":"wire_nswe","37,31":"wire_nswe","28,33":"wire_we","31,33":"wire_we","34,33":"wire_we","37,33":"wire_we","39,12":"num_7","40,12":"num_8","41,12":"num_9","36,11":"num_8","37,11":"num_0","38,11":"num_6","33,12":"num_8","34,12":"num_1","35,12":"num_3","30,11":"num_7","31,11":"num_9","32,11":"num_4","28,12":"num_9","29,12":"num_8","27,12":"num_7","30,12":"wire_ns","36,12":"wire_ns","27,15":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"27,20":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"27,25":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"27,30":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"27,34":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"53,12":"func_def","55,12":"func_def","57,12":"func_def","59,12":"func_def","61,12":"func_def","54,12":"end_s","58,12":"end_s","56,12":"end_s","60,12":"end_s","62,12":"end_s","63,12":"end_e","54,11":"label","55,11":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"53,11":"wire_se","54,13":"joint_nse","55,16":"op_plus","57,16":"op_plus","59,16":"op_plus","61,16":"op_plus","55,15":"func_call","57,15":"func_call","59,15":"func_call","61,15":"func_call","56,13":"wire_nswe","58,13":"wire_nswe","61,13":"wire_we","60,13":"wire_nswe","62,13":"wire_nswe","59,13":"wire_we","57,13":"wire_we","55,13":"wire_we","55,14":"wire_sw","54,14":"wire_ne","56,15":"wire_nw","58,15":"wire_nw","60,15":"wire_nw","57,14":"wire_sw","59,14":"wire_sw","60,14":"func_call","61,14":"wire_sw","56,14":"func_call","58,14":"func_call","62,14":"func_call","62,15":"wire_nw","63,14":"wire_sw","63,15":"wire_ns","63,16":"func_call","63,17":"op_div","64,16":"wire_nw","64,15":"func_call","64,14":"num_4","65,15":"wire_sw","65,16":"func_call","65,17":"op_minus","66,16":"wire_nw","66,14":"func_call","67,14":"wire_nw","66,13":"wire_sw","67,12":"wire_sw","66,15":"wire_ns","67,13":"wire_ns","63,13":"wire_we","64,13":"wire_we","65,13":"wire_we","64,12":"wire_we","65,12":"wire_we","66,12":"wire_we"}
```
[](https://i.stack.imgur.com/aClTn.png)
the function in itself is the right structure, the left one being 5 calls to the function with the 5 arguments in differents orders
---
## js equivalent
```
a=798
b=794
c=813
d=806
e=789
f=v=>w>=>x=>y=>z=>((v+w+x+y+z)/4)-v
f(a)(b)(c)(d)(e)
f(b)(c)(d)(e)(a)
f(c)(d)(e)(a)(b)
f(d)(e)(a)(b)(c)
f(e)(a)(b)(c)(d)
```
---
Language explanation can be found in [the playground](https://l-2d.glitch.me/) by loading the *cheatsheet* example, or in the [release blog post](https://www.media.mit.edu/projects/2d-an-exploration-of-drawing-as-programming-language-featuring-ideas-from-lambda-calculus/overview/)
[Answer]
# Excel, 15 bytes
```
=SUM(A1#)/4-A1#
```
Input is in cell A1 as an array. For instance, `={798;794;813;806;789}`
[](https://i.stack.imgur.com/b7PhL.png) [](https://i.stack.imgur.com/ODCEq.png)
---
# Excel, 19 bytes
```
=SUM(A1:A5)/4-A1:A5
```
Input is in the cells `A1:A5`. Doesn't rely on array input. Output is wherever the formula is. It's not a very interesting solution.
[](https://i.stack.imgur.com/3arY0.png)
[Answer]
# TI-Basic, 7 bytes
```
sum(Ans)/4-Ans
```
Takes input in `Ans`. Output is stored in `Ans` and displayed.
[Answer]
# [Desmos](https://desmos.com/calculator), 16 bytes
```
f(l)=l.total/4-l
```
[Try It On Desmos!](https://www.desmos.com/calculator/iscwqjxvd9)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/kzetwyayfs)
[Answer]
# [LOLCODE](http://lolcode.org/), 216 bytes
```
HOW IZ I f YR a
I HAS A s ITZ 0
IM IN YR l UPPIN YR i TIL BOTH SAEM i 5
s R SUM OF s a'Z SRS i
IM OUTTA YR l
IM IN YR l UPPIN YR i TIL BOTH SAEM i 5
VISIBLE DIFF OF QUOSHUNT OF s 4 a'Z SRS i
IM OUTTA YR l
IF U SAY SO
```
[Try it online!](https://tio.run/##jZA9D4IwFEX3/oq7uRkQVBxLhPQFsUpbFTbiR0JCwsD/DxaqA4OJ23vn5Z7k3bZr793jOQhO8JfBIOQVVIHwQlmgZgTBFTh6kK7gMcpBx/HUwpxObmyg6YBYagHFk9zua9ajgDI5ZGqj9aKCKhSaMS6N1nwy/C27kKL4kGBPaToaz0YqYY7a2cPf/hTGWkooOXwfqadHOGKTZaRZ/cFj3JtO2100o/6HhjO6mmjkBTMaOOpvZjR0hmjHbJ22XFct8oyXLNPiFpfJ8AY "LOLCODE – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~9~~ 7 bytes
```
$+a/4-a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSbkGFUuyCpaUlaboWy1W0E_VNdBMhPKjgzmilaHNLC2tzSxNrCwNjawtDM2tzC8tYuC4A)
*-2 bytes thanks to DLosc*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4? 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
With a strict interpretation of Rule 1 (can't take as a program argument due to the "single line" part) - a full program that reads from STDIN and writes to STDOUT:
```
ɠḲVµS÷4_
```
[Try it online!](https://tio.run/##y0rNyan8///kgoc7NoUd2hp8eLtJ/P//5pYWCuaWJgoWhsYKFgZmCuYWlgA)
...or with site default IO instead - a monadic Link that accepts a list of five numbers and yields a list of five numbers:
```
S÷4_
```
**[Try it online!](https://tio.run/##y0rNyan8/z/48HaT@P///0ebW1roKJhbmugoWBgaAwkDMyDXwjIWAA "Jelly – Try It Online")**
### How?
```
ɠḲVµS÷4_ - Main Link: no arguments
ɠ - read a line from STDIN
Ḳ - split that at spaces
V - evaluate that as Jelly code -> list of the five four-apple-weights, W
µ - start a new monadic chain - f(W)
S - sum W
4 - four
÷ - divide -> sum(W)/4
_ - subtract W (vectorises) -> [sum(W)/4-w1, sum(W)/4-w2, sum(W)/4-w3, sum(W)/4-w4, sum(W)/4-w5]
- implicit print
```
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 23 bytes
```
[ dup Σ 4 / swap n-v ]
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjkJtYkqFXmpeZnJ@SCuZARMpSQWqLFQqKUktKKguKMvNKFKy5uKoVzC0tgNhEwcLAWMHC0EzB3MJSoVbhf7RCSmmBwrnFCiYK@grF5YkFCnm6ZQqx/5MTc3IU9P4DAA "Factor – Try It Online")
## Explanation
```
! { 798 794 803 816 789 }
dup ! { 798 794 803 816 789 } { 798 794 803 816 789 }
Σ ! { 798 794 803 816 789 } 4000
4 ! { 798 794 803 816 789 } 4000 4
/ ! { 798 794 803 816 789 } 1000
swap ! 1000 { 798 794 803 816 789 }
n-v ! { 202 206 197 184 211 }
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 22 bytes
```
->a{a.map{a.sum/4-_1}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhbbdO0SqxP1chMLgGRxaa6-iW68YW0tRHJfgUJadLS5pYWOgrmliY6ChYExkDA0A3ItLGNjIYoWLIDQAA)
[Answer]
# [Julia 1.0](http://julialang.org/), 14 bytes
```
!l=sum(l/4).-l
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/XzHHtrg0VyNH30RTTzfnv0NxRn65gmK0uaWFjoK5pYmOgoWhMZAwMANyLSxj/wMA "Julia 1.0 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 4 bytes
```
O4÷α
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f3@Tw9nMb//@PNre00DG3NNGxMDDWsTA00zG3sIwFAA "05AB1E – Try It Online")
*-5 bytes thanks to Kevin Cruijssen*
[Answer]
# [R](https://www.r-project.org/), 14 bytes
```
\(x)sum(x)/4-x
```
[Try it online!](https://tio.run/##K/r/P600L7kkMz9Po0KzuDQXSOqb6Fb8/19ho5usYW5poaNgbmmio2BhaAwkDMyAXAtLTQA "R – Try It Online")
Uses the new lambda, `\`, introduced in R 4.1.
[Answer]
# [J](https://www.jsoftware.com), 7 bytes
```
-~4%~+/
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8GCpaUlaboWa9IUbK0UdOtMVOu09SFCe1OTM_IVaqwU0hTMLS2A2ETBwsBYwcLQTMHcwhKiBqYdAA)
[Answer]
# [jq](https://stedolan.github.io/jq/), ~~20~~ 9 bytes
```
add/4-.[]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70oq3DBgqWlJWm6FisTU1L0TXT1omMhfKjwgp3R5pYWOgrmliY6ChaGxkDCwAzItbCEqgMA)
*-11 bytes thanks to @ovs*
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 9 bytes
```
J++4./j?-
```
[Try it online!](https://tio.run/##SyotykktLixN/V@Q@t9LW9tETz/LXvf//2pzSwsFc0sTBQtDYwULAzMFcwvLWgUA "Burlesque – Try It Online")
```
J # Duplicate
++ # Sum
4./ # Divide by 4
j # Swap
?- # Subtract from each
```
[Answer]
# [Halfwit](https://github.com/chunkybanana/halfwit/), 5 bytes
```
kJ>+<k+N+N
```
[Try it online.](https://dso.surge.sh/#@WyJoYWxmd2l0IixudWxsLCJrSj4rPGsrTitOIiwiIiwiW1s3OThuLDc5NG4sODAzbiw4MTZuLDc4OW5dXSIsIiJd)
Inputs as a list of BigInts.
**Explanation:**
```
kJ # Sum the (implicit) input-list
>+< # Push compressed BigInt 4n
k+ # Integer-divide the sum by this 4
N+N # Subtract the values in the (implicit) input-list from this value:
N # Negate the value
+ # Add it to each value in the (implicit) input-list
N # Negate each value in the list
# (after which the result is output implicitly)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~61~~ 58 bytes
```
n,i;f(int*a){for(i=10;i--;)i>4?n+=a[i%5]:(a[i]=n/4-a[i]);}
```
[Try it online!](https://tio.run/##JYxBCsIwEEX3OUUoFBI7wRYbmxijByldhEpkFkYp7kLOHqe4mTfw/3@req5rrQnQRYHpewgyx/cm0A@9Q6WcxNt4T50PM7Z6uQji4tNxVPsjXamvgEnIzGjMw6wXnydrYLIjmOEEpj/DZGxxLIog6e5uaiL3vHeEK9eEriPDZ6MkiqZ9AG/g72eFlfoD "C (gcc) – Try It Online")
*-3 bytes thanks to ceilingcat*
[Answer]
# x86 32-bit machine code, 32 bytes
```
00000000: 87ca 31c0 6a05 5903 448a fce2 fac1 e802 ..1.j.Y.D.......
00000010: 6a05 5950 2b44 8afc 8944 8afc 58e2 f4c3 j.YP+D...D..X...
```
## Assembly
```
section .text
global func
func: ;void func(int *ecx);
; int *edx=ecx; int eax=0;
xchg ecx, edx
xor eax,eax
; for(ecx=5;ecx>0;ecx--)eax+=edx[ecx-1]
push 0x5
pop ecx
add:
add eax, [edx + 4*ecx-4]
loop add
; eax = eax / 4
shr eax, 2
; for(ecx=5;ecx>0;ecx--)edx[ecx-1]=eax-edx[ecx-1];
push 0x5
pop ecx
sub:
push eax
sub eax, [edx + 4*ecx-4]
mov [edx + 4*ecx-4], eax
pop eax
loop sub
; return
ret
```
Takes a pointer to an array of 5 integers in ECX (fastcall convention), and modifies the array in place with the results.
[Try it online!](https://tio.run/##fVPbjpswEH3GXzGK1AoITrK5NBdCHqpu1ZdqPyAbRcaYhBXYCMyW1Wq/PR2b1SZp0yIx@MycMzP2mJjVxxNnGtbr@4fvsIGhLsohG7C6ONWC60xJGGjRauIcchWzHNJGcmLMyjFP@KyyxDrdTGrwBW@9kDghdChpI/R0SLA2GmGs5ccDoDcADCNUlQkF@BIjTFXlYjSahWg3I2Mp9TDaj5C/NfBuR5yyqY8wame4UqVJRxyWJCtrbT7YIh36MDU90SlKcoVMDNsySIHI2iFMiVMfuy5g/L8mPupHyKVnGN7sp27i1XvAbM7gf3RWqOc/nUGnscnMwjaPGWx7ldBNJYmD3xPOjZC/RljrJh5wgpMTlQQ7pP2eaV1lcaPFfu@6Kas1Z3nueR/j870QSMEy6XqvxDEzy2TZ6D2rqu1sh8f1Ol8ugvlyGixGk2Bx9yWYL5ZvAfiWhvEC8ynujkdeAJkddiEKXr64lhCc0@E5j8w9ea@MXovw1I0sW8/CrN/3ygp7SN3ep@RR9gJL22Y7ZL4Ru2uJ1xRoKvJ0Mr64uUBVh7hKxECRA@fXLhRcntIlGahUtMwE0GIyJip@4qp8AfoAcSZZhaun7n@40pzXyCJGlTRFCfQb0J/m6ov8ir75PCaCH7GWgN6j9H3/64sWwFUj9QpRzzJ@YdMc1tfJb2h/iNZUOwvbNrkhIlfbP/0G "Try It Online")
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 4 bytes (8 nibbles)
```
+/+$4*~
```
```
+ # sum of
$ # the input
/ # divided by
4 # 4
+ # added to
# (implicitly) each element of input
* # multiplied by
~ # -1
```
[Answer]
# [J](https://www.jsoftware.com), 7 bytes
```
-~4%~+/
```
Nothing new here.
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxXLfORLVOWx_Cu2muyZWanJGvkKZgbmkBxCYKFgbGChaGZgrmFpYYUoZAKQOwFET7ggUQGgA)
```
-~4%~+/
+/ NB. sum
4%~ NB. divide result by 4
-~ NB. subtract result by input, vectorized
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 7 bytes
```
I⁻÷Σθ⁴θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczr7RYwzOvxCWzLDMlVSO4NFejUFNHwQSICzU1Na3//4@ONre00FEwtzTRUbAwNAYSBmZAroVlbOx/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input list
Σ Take the sum
÷ Integer divided by
⁴ Literal integer `4`
⁻ Vectorised subtract
θ Input list
I Cast to string
Implicitly print
```
9 bytes for a version that works with two or more apples, not just five:
```
I⁻÷Σθ⊖Lθθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczr7RYwzOvxCWzLDMlVSO4NFejUFNHwSU1uSg1NzWvJDVFwyc1L70kAyisCZQAkdb//0dHm1ta6CiYW5roKFgYGgMJAzMg18IyNva/blkOAA "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~34~~ 32 bytes
```
a=>a.map(e=>eval(a.join`+`)/4-e)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGiNNulpSVpuhY3FRJt7RL1chMLNFJt7VLLEnM0EvWy8jPzErQTNPVNdFM1oeo0k_PzivNzUvVy8tM10jSizS0tdBTMLU10FCwMjIGEoRmQa2EZqwnVsGABhAYA)
-2 bytes thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)
[Answer]
# [Red](http://www.red-lang.org), 28 bytes
```
func[v][v -((sum v)/ 4)* -1]
```
[Try it online!](https://tio.run/##BcFLCoAgAAXAq7x2GUhJktox2oqL8AMRWph6fZvJ3vXDO20Q9h5qsroZ3UDH8asRjczgZAJlpr/5SgUB8bw9mrflyQO0UBJCcchlhWQbhFSm/w "Red – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), 60 bytes
```
b,c;f(*a){for(b=c=0;b<5;c+=a[b++]);for(;b--;a[b]=c/4-a[b]);}
```
[Try it online!](https://tio.run/##HY7NDoIwEITP8BQbEpPWFvkRBLL2SQyHtoA2QTSCJ8Kz49bLZHYmu/vZ2I56uu@7kRYHdtR8HV4fZpRVKZpriVYofTNCtBx9gSaOkYJW2aSIveG47U/tJsbXMHDTAks/L7eyVbBWTS2hagoJdXYmSS801s2GkCQwP17fsQPTA@RpLkmozeqKxG/oqYM8y05hMDB/kSM5AvAfHLE5YnNC8PeHkoFFhw4i@X/tCCnc9h8 "C (clang) – Try It Online") Takes an array of 5 integers and modifies the array in-place.
] |
[Question]
[]
|
[Question]
[]
|
[Question]
[]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.