text
stringlengths 180
608k
|
---|
[Question]
[
## Creating a Crossed Square
You are to take input of an integer of one or more and output a square made of any printable character of your choice with a diagonal cross through the centre.
The general idea is for the output to be a hollow square that has a diagonal cross through it.:
```
Input: 7
Output:
*******
*# #*
* # # *
* # *
* # # *
*# #*
*******
```
In the above example the '\*'s represent the outer box and the '#'s represent the diagonal cross.
Note that the above example uses two different characters so that it is easier to see what the output looks like, your program should use one character only.
**Input**
An integer of 1 or more, it is guaranteed to be odd.
**Output**
A square that is made up of a character of your choice with a cross through the middle.
* The cross must be diagonal
* The square may be output via the function or written to output
* Trailing newlines are okay
* Can output as a graphic, diagram or image if you wish too
**Examples**
```
Input: 1
Output:
*
Input: 3
Output:
***
***
***
Input: 5
Output:
*****
** **
* * *
** **
*****
Input: 7
Output:
*******
** **
* * * *
* * *
* * * *
** **
*******
```
**Specs**
* Functions or full programs are allowed
* You can get input by your preferred means
* Standard loopholes are disallowed
* Programs must work without any additional statements i.e. `using`s in `C#`, they must be included in the entry
* You can output from a function or print the result
This is code golf so the shortest solution wins.
[Answer]
# VBA Excel, 168 bytes
**Instruction:**
I find Excel with the help of VBA is an effective and a sufficient tool for this challenge. Set the worksheet of Excel like following
[](https://i.stack.imgur.com/agEBY.png)
Yes, we use the small, classic square-shaped pixels like the old times by using the cells in a worksheet as the pixels. *Ha-ha...*
Here I use cell A1 as the input and I change its font color to red. Why red? Because red is three-letter-color so it fits for golfing. Write and run the following code in the Immediate Window:
```
N=[A1]:Range("A1",Cells(N,N)).Interior.Color=vbRed:Range("B2",Cells(N-1,N-1)).Clear:For i=1To N:Cells(i,i).Interior.Color=vbRed:Cells(i,N+1-i).Interior.Color=vbRed:Next
```
Ungolfed the code:
```
Sub A()
N = [A1]
Range("A1", Cells(N, N)).Interior.Color = vbRed
Range("B2", Cells(N - 1, N - 1)).Clear
For i = 1 To N
Cells(i, i).Interior.Color = vbRed
Cells(i, N + 1 - i).Interior.Color = vbRed
Next
End Sub
```
**Step-by-step Explanation:**
```
N = [A1]: Range("A1", Cells(N, N)).Interior.Color = vbRed
```
[](https://i.stack.imgur.com/Lso5N.png)
```
Range("B2", Cells(N - 1, N - 1)).Clear
```
[](https://i.stack.imgur.com/PKpZi.png)
Looping through the diagonal of range cells: `Cells(i, i).Interior.Color = vbRed`
[](https://i.stack.imgur.com/MXTAZ.png)
Final step and output: `Cells(i, N + 1 - i).Interior.Color = vbRed`
[](https://i.stack.imgur.com/IoHQ2.png)
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~20~~ ~~19~~ 17 bytes
```
2-:XdtP!+~TTYa1YG
```
You can try it experimentally in [MATL online](https://matl.io/?code=2-%3AXdtP%21%2B%7ETTYa1YG&inputs=11&version=19.0.0). You may need to refresh the page if it doesn't work.
Sample run:
[](https://i.stack.imgur.com/ltyje.png)
## ASCII version: 19 bytes
```
2-:XdtP!+~TTYa~42*c
```
[Try it online!](http://matl.tryitonline.net/#code=Mi06WGR0UCErflRUWWF-NDIqYw&input=MTE)
[Answer]
## JavaScript (ES6), 96 bytes
```
f=
n=>[...Array(n--)].map((_,i,a)=>a.map((_,j)=>i&&j&&n-i&&n-j&&i-j&&n-i-j?' ':'*').join``).join`
`
;
```
```
<input type=number min=1 step=2 oninput= o.textContent=f(this.value)><pre id=o>
```
[Answer]
## Python 2, 65 bytes
```
i=n=2**input()/2
while i:print bin((n>i>1or~-n)|n|i|n/i)[2:];i/=2
```
Uses [Jonathan Allan's idea](https://codegolf.stackexchange.com/a/91080/20260) of outputting binary numbers like:
```
11111
11011
10101
11011
11111
```
The rows are created with bit arithmetic and displayed in binary. Each part it or'ed into the rest. The part are are produced by powers of 2 `n` (fixed) and `i` (falling) via
1. Left side `1`
2. Right side `n`
3. Diagonals `i` and `n/i`
4. Top and bottom by `n-1` when `i==1` or `i==n`.
Actually, (1) and (4) are combined by producing `1` when `1<i<n` and `n-1` otherwise.
[Answer]
# Python, ~~114 110 96~~ 90 bytes
Totally changed:
```
lambda n:[bin(sum(2**p for p in[range(n),{0,n-1,r,n-1-r}][0<r<n-1]))[2:]for r in range(n)]
```
Returns a list of strings, characters using `1` and `0`.
-6 bytes thanks to TheBikingViking
Test it at [**ideone**](http://ideone.com/7vCZzO)
---
Previous Python 2 @110
```
def f(n):g=range(n);n-=1;print'\n'.join(''.join((c in(r,n-r,0,n)or r in(0,n))and'#'or' 'for c in g)for r in g)
```
Test it on [**ideone**](http://ideone.com/3CO1cW)
[Answer]
# Java 7, ~~131~~ ~~130~~ ~~128~~ ~~125~~ ~~124~~ 122 bytes
```
String c(int n){String r="";for(int i=n,j;n-->0;r+="\n")for(j=0;j<n;r+=i*j<1|n-i<2|n-j<2|i==j|i==n-++j?"*":" ");return r;}
```
3 bytes saved thanks to *@LeakyNun*;
1 byte saved thanks to [*@OliverGrégoire* in my answer for the *Draw a hollow square of # with given width*](https://codegolf.stackexchange.com/a/98871/52210) challenge;
2 bytes saved thanks to *@cliffroot*.
**Ungolfed & test code:**
[Try it here.](https://ideone.com/VCUnRP)
```
class M{
static String c(int n){
String r = "";
for(int i = n, j; n-- > 0; r += "\n"){
for(j = 0; j < n;
r += i < 1 // Responsible for the first horizontal line
| j < 1 // Responsible for the first vertical line
| n-i < 2 // Responsible for the last horizontal line
| n-j < 2 // Responsible for the last vertical line
| i == j // Responsible for the top-left to bottom-right diagonal line
| i == n-++j // Responsible for the top-right to bottom-left diagonal line (and increasing j)
? "*"
: " ");
}
return r;
}
public static void main(String[] a){
System.out.println(c(1));
System.out.println(c(3));
System.out.println(c(5));
System.out.println(c(7));
}
}
```
**Output:**
```
*
***
***
***
*****
** **
* * *
** **
*****
*******
** **
* * * *
* * *
* * * *
** **
*******
```
[Answer]
# Matlab, ~~68 66 64~~ 58 bytes
Since graphical output is allowed too:
```
k=input('');[x,y]=ndgrid(abs(-k:k));spy(~(max(x,y)<k&x-y))
```
Which outputs e.g.
[](https://i.stack.imgur.com/e9KcY.png)
The ascii only versions would be:
This is using the indexing `0,1,2,3,...`
```
k=input('');[x,y]=ndgrid(abs(-k:k));[(max(x,y)==k|~(x-y))*42,'']
```
Alternatively with the indexing `1,3,7,...`:
```
n=input('');k=1:n;m=eye(n);m([k,end-k+1])=1;[(m|flip(m'))*42,'']
```
[Answer]
# C#, ~~112~~ 101 bytes
Thanks to TheLethalCoder for reminding me that these anonymous lambda statement-nor-expression things are allowed in C#.
```
n=>{var r="";for(int y=n--,x;y-->0;r+="*\n")for(x=0;x<n;r+=y%n*x<1|y==x|y==n-x++?"*":" ");return r;};
```
Who said C# isn't a fun golfing language?
[Answer]
# Logo, 155 bytes
## Graphical solution, implemented as a function
I retooled my answer for [Alphabet Triangle](https://codegolf.stackexchange.com/a/87610/56253) and changed the angles around a bit. As before, `r` draws a line of characters. This time, the `b` function draws a box by drawing one straight edge and one diagonal, rotating, and repeating four times. This causes the diagonals to be drawn twice (on top of each other), but it was less code than handling it separately. This answer also properly handles even numbers. I had to add special handling for an input of `1` to prevent it from going forward.
I implemented it as a function, `b` which takes the size as an argument:
```
pu
to r:n:b:l repeat:n[rt:b label "A lt:b if repcount>1[fd:l]] end
to b:s
repeat 4[rt 90
r:s 90-heading 20 rt 135
r:s 90-heading 20*sqrt 2 rt 45]
end
```
Try it out on [Calormen.com's Logo interpreter](http://www.calormen.com/jslogo/).
To call it, append a line and call `b` in the following format:
```
b 7
```
[](https://i.stack.imgur.com/1zIUG.png)
... or try the sampler platter, which draws four samples in sizes 5, 7, 9, and 11, rotating 90 degrees in between:
```
repeat 4[
b repcount*2+3
rt 90
]
```
[](https://i.stack.imgur.com/CarSZ.png)
[Answer]
# R, 102 bytes
```
n=scan();for(i in 1:n){for(j in 1:n){z=" ";if(i%in%c(1,n,n-j+1)|j%in%c(1,i,n))z="*";cat(z)};cat("\n")}
```
Note that it is more efficient to express the condition using %in% than i==1|j==1|...
[Answer]
# Haskell, ~~102~~ ~~100~~ ~~96~~ ~~91~~ 87 bytes
```
c s=unlines.f$f.(#)where f=(<$>[1..s]);x#y|elem y[1,s,x]||elem x[1,s,s-y+1]='*'|1>0=' '
```
* Saved 2 bytes, thanks to [flawr](https://codegolf.stackexchange.com/users/24877/flawr "flawr").
* Saved 4 more bytes by using list comprehensions.
* 5 bytes saved combining [flawr](https://codegolf.stackexchange.com/users/24877/flawr "flawr")'s improvement with `any`
* 4 bytes saved by replacing `any` with `elem`
**Ungolfed version:**
```
cross :: Int -> String
cross s = unlines $ map line [1..s]
where line y = map (pos y) [1..s]
pos y x | x == y = '*'
| x == s - y + 1 = '*'
| y `elem` [1, s] = '*'
| x `elem` [1, s] = '*'
| otherwise = ' '
```
I'm sure this can still be improved, but this is what I've come up with for now.
**Old version:**
```
c s=unlines.f$f.(#)where f=(<$>[1..s]);x#y|any(==y)[1,s,x]||any(==x)[1,s,s-y+1]='*'|1>0=' '
```
[Answer]
# Java, 130 bytes
```
s->{for(int i=0;i<s;i++)for(int j=0;j<s;j++)System.out.print((s-1-i==j||i==j||i==0||j==0||i==s-1||j==s-1)?j==s-1?"*\n":"*":" ");};
```
# Test Program
```
Consumer<Integer> consumer = s -> {
for (int i = 0; i < s; i++) {
for (int j = 0; j < s; j++) {
System.out.print((s - 1 - i == j || i == j || i == 0 || j == 0 || i == s - 1 || j == s - 1) ? j == s - 1 ? "*\n" : "*" : " ");
}
}
};
consumer.accept(20);
```
[Answer]
# C, ~~140~~ ~~121~~ 114 bytes
**19 bytes thanks to Quentin.**
7 bytes saved by switching from a double-nested loop to one loop.
```
main(a){scanf("%d",&a);for(int i=0;i<a*a;i++,i%a||puts(""))putchar(i/a&&i/a^a-1&&i%a&&-~i%a&&i%-~a&&i%~-a?32:42);}
```
Golfing suggestions welcome.
[Answer]
## PowerShell (133)
```
filter s($x){1..$x|%{$o="";$r=$_;1..$x|%{if($_-eq1-or$r-eq1-or$_-eq$x-or$r-eq$x-or$r-eq$_-or$r-1-eq$x-$_){$o+="*"}else{$o+="_"}};$o}}
```
Clunky, but it works well enough.
```
s(11)
***********
**_______**
*_*_____*_*
*__*___*__*
*___*_*___*
*____*____*
*___*_*___*
*__*___*__*
*_*_____*_*
**_______**
***********
```
Golfing suggestions definitely welcome, it's been too long since I've PowerShell'd.
[Answer]
# [S.I.L.O.S](http://github.com/rjhunjhunwala/S.I.L.O.S), 212 bytes
```
readIO
a = i
lbla
a - 1
t = a
t + 1
t % i
t * a
b = i
lblb
b - 1
u = b
u + 1
u % i
u * b
u * t
v = a
v - b
u * v
v = a
v + b
v + 1
v % i
u * v
u |
if u c
print #
GOTO d
lblc
print .
lbld
if b b
printLine
if a a
```
[Try it online!](http://silos.tryitonline.net/#code=cmVhZElPIAphID0gaQpsYmxhCmEgLSAxCnQgPSBhCnQgKyAxCnQgJSBpCnQgKiBhCmIgPSBpCmxibGIKYiAtIDEKdSA9IGIKdSArIDEKdSAlIGkKdSAqIGIKdSAqIHQKdiA9IGEKdiAtIGIKdSAqIHYKdiA9IGEKdiArIGIKdiArIDEKdiAlIGkKdSAqIHYKdSB8CmlmIHUgYwpwcmludCAjCkdPVE8gZApsYmxjCnByaW50IC4KbGJsZAppZiBiIGIKcHJpbnRMaW5lIAppZiBhIGE&input=&args=MTU)
[Answer]
## GNU sed, ~~117~~ 114 + 1(r flag) = 115 bytes
```
p;/^0$/Q;/^000$/{p;q}
h;s/./ /3g;s/ $/00/
:f;/ 00 /!{G;h;s/\n.*//p;t;:}
s/^(0 *)0 ?( *)0/\1 0\20 /
tf;s/00/0/p;g
```
Since sed has no native support for numbers, the input is given in unary based on this [consensus](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary?answertab=votes#tab-top "consensus"). The second half of the square is the first half that was stored in reverse order in hold space.
**Run:**
```
sed -rf crossed_square.sed <<< "00000"
```
**Output:**
```
00000
00 00
0 0 0
00 00
00000
```
[Answer]
# Python, 89 bytes
This was a throwback! I used python's turtle module.
```
from turtle import*
n=input()
for i in[(n,n),(n,0),(0,n),(0,0),(n,0),(0,n),(n,n)]:goto(i)
```
Here's the result when n=200:
[](https://i.stack.imgur.com/5deDQ.png)
[Answer]
# Scala, 141 137 bytes
```
val s=args(0).toInt-1;val t=0 to s;print(t.map{x=>t.map{y=>if(x==0||x==s||y==0||y==s||x==y||x==s-y)"*" else " "}.mkString+"\n"}.mkString)
```
Run:
`$ scala cross.scala 10`
Technically I could remove the print stuff and go to something like
```
def c(n:Int)={val (s,t)=(n-1,0 to n-1);t.map{x=>t.map{y=>if(x==0||x==s||y==0||y==s||x==y||x==s-y)"*" else " "}.mkString+"\n"}.mkString}
```
This would make it 135 or 121 bytes depending on whether you count the function syntax stuff.
Readable version:
```
def cross(n: Int) = {
// Declares both s and t as variables with tuple expansion
// s is the zero-based size and t is a range from 0 to s
val (s,t) = (n-1, 0 to n-1)
// Maps all rows by mapping the columns to a star or a space
t.map { x =>
t.map { y =>
if (x == 0 || x == s || y == 0 || y == s || x == y || x == s-y) "*"
else " "
}.mkString+"\n" // Concatenate the stars and spaces and add a newline
}.mkString // Concatenate the created strings
}
```
[Answer]
# Pyth, ~~27~~ 25 bytes
```
jmsm?|qFKaLJ/Q2,dk}JKN\ Q
```
[Try it online!](http://pyth.herokuapp.com/?code=jmsm%3F%7CqFKaLJ%2FQ2%2Cdk%7DJKN%5C+Q&input=11&debug=0)
Probably golfable.
[Answer]
## Python 2, 83 bytes
```
i=n=input()
while i:l=['* '[1<i<n]]*n;i-=1;l[0]=l[~0]=l[i]=l[~i]='*';print`l`[2::5]
```
Modifies a list of the row's characters to put a `*` into the first, last, i'th, and i'th-to-last place. The first and last row start as all `*`, and the rest as all spaces. Works for evens too. A `lambda` expression is probably shorter than modification, but I like this method.
[Answer]
## Pyke, ~~28~~ ~~24~~ 23 bytes
```
]Ua]jshqjXq|0[j{|)Qt[)P
```
[Try it here!](http://pyke.catbus.co.uk/?code=%5DUa%5DjshqjXq%7C0%5Bj%7B%7C%29Qt%5B%29P&input=7&warnings=0)
[Answer]
# Mathematica, 81 bytes
```
""<>#&/@Table[If[i^2==j^2||i^2==#^2||j^2==#^2,"*"," "],{i,-#,#},{j,-#,#}]&[(#-1)/2]&
```
Creates a coordinate system with the origin in the center, and computes where the `*`s should go. Outputs an array of strings, one per row.
[Answer]
# Javascript (289 270 bytes)
```
function s(a){b=[];for(i=0;i<a;i++)if(b.push([]),0==i||i==a-1)for(j=0;j<a;j++)b[i].push("*");else for(j=0;j<a;j++)0==j||j==a-1?b[i].push("*"):j==i||a-1-j==i?b[i].push("*"):b[i].push(" ");c="";for(i=0;i<b.length;i++){for(j=0;j<b[i].length;j++)c+=b[i][j];c+="\n"}return c}
```
Ungolfed:
```
function square(size){
str=[];
for(i=0;i<size;i++){
str.push([]);
if(i==0||i==size-1){
for(j=0;j<size;j++){
str[i].push("*");
}
}else{
for(j=0;j<size;j++){
if(j==0||j==size-1){
str[i].push("*");
}else if(j==i||size-1-j==i){
str[i].push("*");
}else{
str[i].push(" ");
}
}
}
}
out="";
for(i=0;i<str.length;i++){
for(j=0;j<str[i].length;j++){
out+=str[i][j];
}
out+="\n";
}
return out;
}
```
EDIT:
Saved 19 bytes thanks to Philipp Flenker.
[Answer]
# Charcoal, 8 bytes (noncompeting; language postdates challenge)
```
GH+↘↑↙N*
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8gP6cyPT/PIz8nJ79cw0pbwcolvzwvKDM9o0TBKrQAwvVJTSvRUfDMKygt8SvNTUot0tDUUVDSUtK0/v/f/L9u2X/d4hwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: When used as a parameter to the `PolygonHollow` command, `+` draws a box, and the arrows then create the diagonals. There are some other shortcut characters but they would need to be redefined to be useful e.g. `Y` is equivalent to `↖↗↓` but if it was eqivalent to `↗↓↖` then `Y+` would suffice.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0•V¾²•Λ
```
[Try it online](https://tio.run/##yy9OTMpM/f/f4FHDorBD@w5tAtLnZv//bw4A) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GdWib/X@DRw2Lwg7tO7QJSJ@b/R8kzFWekZmTqlCUmpiikJnHlZLPpaCgn19Qog/RDaXQDLRRUAGrzUv9b8hlzGXKZc5laMwFAA).
**Explanation:**
```
0 # Push 0
•V¾²• # Push compressed integer 2064147
Λ # Use the Canvas builtin with the given three options:
# Length of the lines: the (implicit) input-integer
# Character/string to display: the "0"
# Directions: [2,0,6,4,1,4,7]
# (after which the result is output implicitly immediately)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•V¾²•` is `2064147`.
The Canvas Builtin uses three arguments to draw a shape:
* Length of the lines we want to draw: which is the input in this case
* Character/string to draw: the `0` (could be any other digit as well)
* The direction to draw in: the `[2,0,6,4,1,4,7]`, where each digit represents a certain direction:
```
7 0 1
↖ ↑ ↗
6 ← X → 2
↙ ↓ ↘
5 4 3
```
So the `[2,0,6,4,1,4,7]` in this case translates to the directions \$[→,↑,←,↓,↗,↓,↖]\$.
Here a step-by-step explanation of how it draws for example input `7` with these steps:
Step 1: Draw 7 characters (`"0000000"`) in direction `2→`:
```
0000000
```
Step 2: Draw 7-1 characters (`"000000"`) in direction `0↑`:
```
0
0
0
0
0
0
0000000
```
Step 3: Draw 7-1 characters (`"000000"`) in direction `6←`:
```
0000000
0
0
0
0
0
0000000
```
Step 4: Draw 7-1 characters (`"000000"`) in direction `4↓`:
```
0000000
0 0
0 0
0 0
0 0
0 0
0000000
```
Step 5: Draw 7-1 characters (`"000000"`) in direction `1↗`:
```
0000000
0 00
0 0 0
0 0 0
0 0 0
00 0
0000000
```
Step 6: Draw 7-1 characters (`"000000"`) in direction `4↓`:
```
0000000
0 00
0 0 0
0 0 0
0 0 0
00 0
0000000
```
Step 7: Draw 7-1 characters (`"000000"`) in direction `7↖`:
```
0000000
00 00
0 0 0 0
0 0 0
0 0 0 0
00 00
0000000
```
After which the result is output implicitly immediately afterwards.
[See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210)
[Answer]
# Perl, 83 +1 = 84 bytes
Run with the `-n` flag.
```
$\="*
*";print$c="*"x($_+1);for$b(1..$_){@a=($")x$_;@a[$b-1,-$b]=(a,a);print@a}say$c
```
The literal newline saves 1 byte over `\n` or `$/`.
Readable:
```
$\="*\n*";
print$c="*"x($_+1);
for$b(1..$_){
@a=($")x$_;
@a[$b-1,-$b]=(a,a);
print@a
}
say$c
```
The code prints the top line and saves it in `$c`, then prints a bunch of spaces with the appropriate slots replaced with `a`s, then prints the top line again.
The assignment to the `$\` variable tells the interpreter to print the contents (an asterisk, a newline, and another asterisk) after every `print`, but this does NOT occur after a `say`.
[Answer]
# SmileBASIC, 46 bytes
```
INPUT I
GBOX I,I,1,1GLINE 1,I,I,1GLINE 1,1,I,I
```
(No, SB does NOT use 1-indexed graphics...)
[Answer]
**SHELL** ( **135 Bytes**):
```
C(){ j=$(($1-1));for i in $(seq 0 $j);do dc<<<2o10i`echo $((1|2**$i|2**($j-$i)|2**$j|(($i==0||$i==$j))*(2**$j-1)))`p;done|tr 01 ' X';}
```
tests:
```
C 1
X
C 3
XXX
XXX
XXX
C 5
XXXXX
XX XX
X X X
XX XX
XXXXX
C 7
XXXXXXX
XX XX
X X X X
X X X
X X X X
XX XX
XXXXXXX
C 9
XXXXXXXXX
XX XX
X X X X
X X X X
X X X
X X X X
X X X X
XX XX
XXXXXXXXX
```
[Answer]
# [Kotlin](https://kotlinlang.org), ~~123~~ 116 bytes
change if with \n to println
```
{s:Int->val n=s-1
for(r in 0..n){for(c in 0..n)print(if(n-r==c||r==c||r<1||c<1||r==n||c==n)"#"
else " ")
println()}}
```
[Try it online!](https://tio.run/##hVZNb9s4EL3rVwycQ20jtmsUaXeNukCRbYFetguklwV6oaWxxTVFqiQV25v0t2dnSEqW4garNhIpzve8efLeeCX102IKtxaFxwK2xkJuCoSdUVvIS6EU6h1mpfe1Wy0WfMZHc@dFvscjSdDxPDfV4keDzkuj3eL35eu3vy1yNin1biZmuTXOYTFzPxphMbtNJyDIbziBu3iS/W0aoAV4A17sEaSuGw9mC0LT2uMOLe@MRqBIK0OiQhdgGs9yAqIHqASlELROUFtSFBuFnI4VuY8mTqahVEsjc4SD9CUpF1LsjBYKQrzgS2uaXUlPUkXtLc6z7BttdqjRkpgsUIB0oWgslKKg2DcUFpRGKXNoQ/Kl8FAK97If6eerLPvCGa/gXfY1WFtl03hl0ysAuKInXNE/ftIDevv2PMmTpRCV2Jh7BDyKqlYY3ryavnJgsbboKK02dCrLxhxDOYPQ1YXQMG4qxp/Gp8QuHTUOKbWDIa3tFi3b6OrvwJmoJz0XEIWT5J4K55C60RpM9VTG7B0oucfr2LXamp0VFbjSNKpgTwEQvfZqdZqnUmbZxwF0li1wrpPzHbVH0DmhMHbOFAUpx/KT9qCBJB@w1dQBXv8LqUskVbIoFCOJugWMpihSNc6z87bG3XGH6FOILZbkXopgbNvonGeOczpY6T1qTiJKRRNWSMWzpvFAT@oJWzN7cQrHtzRX7fAwNKmudSnz6xAH15gMy0rsaBJDfpSXozyMybJPsdGug@zyDNnu3Zs@jLu/9vRmCHK6A99hCt162pf/xVDQFHQ6cSimcSg6K9DZYUt3NeYuFv9zKp7jJLeNUi2wYo0ETy8WQZRpKadS7dAnStqcWiwiodsSeCoU2gXpO09DJGzByK2JBVLRC@n6Nv9qnYXWH4zdB9AYbgXRligKydHRuBHXeqxoghzIOc4J8NRQWmu4vbpmHJw6@Eidq6agaGQcfqat0yCF1O2tNRX1uw@gQJRBi2a@UZ7JjvBO/89fhDC3yJNnPdE97VUT9A9SEyNMF1m2WMCnY00VoCiUqDbF2cs8oxUcI9mPnfwXV/BF@wk8cEdI8U7cM3NuTsQrVGHXbJzn@WIAl0QilJbzKIjwt1EB79ESxSuRR2q7F6pBDlnTPCPNMfAr0E21oRldA/ucLZO3z5Q0irwESzSdChbH7ZqhkCPNJZEyCTPDj5PU6/k8mptEGPUN5VSOSl/aSoVt5TvWmIc3wfpZtecAwhX0x1naJRtfttFHbQIrJZcL5iFeHKmjQ4Uk8b0vAVtpqYucWbsZKqWo6FCJs2BYx6NrOOBQRScmbb@GJT7PN15EKOOY54zNrtets8dHGLzo6fCVjt8Tk9My6cTdM8lkJTX/LNy9m2QDjbaqEfQc@CBRml8C2um5yiDB8PlknoUtRvgNE76MYBjy6Oq7Hl1E9ZV8WGJe7IKAf3jgX6wtACqHF7ZHzzD0C7v0E6rmYRIuFoLx9QxHTr/yUAvrWyTVgj48VvcDuHA/gtEk@8n6x/a33mLxjSmksPK@Ldyv6KISUo@F3bkVfLRWnN7feZqH3Ycza/yBuYpfaOzp8uTb9vO5Dry0XL4N3OKypwe3IuaZfQjssHbECTSFY9vO3@SBt3m3jSMot2M9s@t1/viY7u@Xj48532ivaUn3CdeZ8485B02lx5OfP59iuLf0FUipcpStwOiOuCn8QhkxKmLg4@WkL/Jdt0Jv@kJvXhC66QvdvCD0ri/07gWh5cDU8ib1knuTPf0H "Kotlin – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
×» Ḣ¡»ø∧
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDl8K7IOG4osKhwrvDuOKIpyIsIiIsIjciXQ==)
Port of 05AB1E. Uses canvas builtin.
## How?
```
×» Ḣ¡»ø∧
× # Push asterisk
» Ḣ¡» # Push compressed integer 2064147 (translates to directions [→,↑,←,↓,↗,↓,↖])
ø∧ # Canvas builtin with implicit input as the length, 2064147 as the directions, and asterisk as the character
```
] |
[Question]
[
All integers \$n > 0\$ can be expressed in the form
$$n = \prod\_{\text{prime } p} p^e = 2^{e\_2} 3^{e\_3} 5^{e\_5} 7^{e\_7} \cdots$$
This form is also known as it's [prime factorisation](https://en.wikipedia.org/wiki/Prime_number#Unique_factorization) or prime decomposition, and each integer has a [unique prime factorisation](https://en.wikipedia.org/wiki/Fundamental_theorem_of_arithmetic).
As the bases are fixed, it is possible to reconstruct an integer when just given a list of the exponents of it's prime factorisation. For example, given \$E = [0,3,2,1,0,2]\$ we can reconstruct \$n\$ as
$$
\begin{align}
n & = 2^0 3^3 5^2 7^1 11^0 13^2 \\
& = 1 \cdot 27 \cdot 25 \cdot 7 \cdot 1 \cdot 169 \\
& = 798525
\end{align}
$$
Therefore, \$[0,3,2,1,0,2] \to 798525\$, and is the only such list (ignoring trailing zeros) that does so.
You are to take an input consisting of non-negative integers representing the exponents of the prime factorisation of some integer and output the integer with that prime factorisation.
Both the integer and the elements of the input will be within the bounds of your language, and you can take input in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). You may have an arbitrary (from 0 to infinite) number of trailing zeros in the input. The array will never be empty, but may be `[0]`
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins
## Test cases
```
[0] -> 1
[1] -> 2
[3, 2] -> 72
[0, 1, 2] -> 75
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] -> 347
[6, 2] -> 576
[1, 7] -> 4374
[5, 7] -> 69984
[10, 5] -> 248832
[1, 0, 0, 8, 4] -> 168804902882
[3, 8, 10] -> 512578125000
[7, 9, 0, 8] -> 14523977994624
[4, 4, 7, 0, 0, 5, 5] -> 53377275216476250000
[1, 8, 1, 7, 8, 1] -> 150570936449966222190
[10, 0, 2, 8, 9] -> 347983339699826969600
[4, 8, 2, 3, 7, 9] -> 186021488852335961308083600
[7, 6, 6, 8, 6, 8, 4] -> 1014472920935186644572261278658000000
[9, 6, 7, 5, 1, 8, 10] -> 8865565384329431006794755470280000000
```
[Answer]
# [Python 2](https://docs.python.org/2/), 61 bytes
Wilson's theroem FTW!
```
f=lambda p,a=1,b=1:p==[]or b**(a%b*p[0])*f(p[a%b:],a*b*b,b+1)
```
[Try it online!](https://tio.run/##3VHtitswEPzvp9CfcrarltVK@6GA@yImFJteuEAuEWmuR58@3Ujn0mcoCHkH7czujMvv28vljPf7YTotr@uPxRW/TMGvU9iVaZr3l6tbx7FfPq1jmWE/jIe@zIZ2e7@M67j69XMY7u8vx9OzC7vOHc/Fu8vbrbjJvS6lf/61nLy7Lu/f7eXt1g9ff5bT8dY/uS/f3NMwdK5cj@ebO/T2PrhpquS7jXo0hG4OtcBujt5hrcUAeBf@Yqr4vznNcUzSzbx5JGGLwjupKEVJ3Uwb5JzVcDAutbSSasRKaJLqXWqBsiqkDKjaIrWX0LKmgCRqFwB0s3iXG7XxEmHMIjknRpuVTNDGb/q0TaYYRVAIAyfhqgV1D60/TFrRJAlIIEdOKWdmRAwZmgs7WDvzFkXWGGN@GEW2Dz9UU22xxliFW29QBgzmX23hSJlDBAWN/GGK69Ht/kgFQkqCGW0dMgVbiQSRA4oyKUCzkStLqt3wb3RqXcQUNUXMKQYAlpyEKIkl3ejwBw "Python 2 – Try It Online")
### [Python 2](https://docs.python.org/2/), 62 bytes
```
f=lambda p,a=1,b=1:p==[]or(a%b<1or b**p.pop(0))*f(p,a*b*b,b+1)
```
[Try it online!](https://tio.run/##3VHtatwwEPzvp9CfEtt1wmql/VCo@yImFJvmyMHlLK5OQp/@uifFpc9QWGQtOzPaGeff28t6xuv1MJ7m1@Xn7PIwj35YRv@Yx3F6Wi/t/GX55teLW/o@P@Q1t9B1/aE1YL/0y7B89d314@V4enb@sXHHcx7c@rZlN7rXObfP7/NpcJf544dN3ra2e/iVT8etvXP3391d1zUuX47nzR1am3duHAv5OsHTDeCbyZcLNlMYHJa7WAOD8397Kv1/U9VxiNJMvHskYYticFK6GCQ2E@0tp6TWe@NSTSuqBiyEKqmDizVQVoWYAFVrpDbxNWvySKJ2AEAzyeBSpVZeJAxJJKXIaG9FE7Tnd33aX6YQRFAIPUfhogVlDy0/TOqlShKQQAocY0rMiOgTVBdWWJBpjyJpCCHdjCLbh2@qsUAMGIpwxXplQG/@1RYOlNgHUNDAn6a4lO7nZyrgYxRMaOuQKdhKJIjsUZRJAaqNVFhS7Pp/o1NDEVPQGDDF4AFYUhSiKJZ0pcMf "Python 2 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 13 7 bytes
```
_&q:inv
```
[Try it online!](https://tio.run/##3ZA9CgJBDIX7PcXDwkUYl8xPkpmBrQQrKy9gIS66hWLj9cdlxr2EIQm8F17xZS6boZ8wZvQwIORl9gMO59OxXLbv/Hh@yq7rutv1/oLFiAnUhKvCNqHcTgbWwDXPB13Nv@kfLqtUNFlZYxRmYR@Ddyl4SySagjIHJRepVY0kAzFQA66/issmlC8 "J – Try It Online")
As described [here](https://code.jsoftware.com/wiki/Vocabulary/qco#dyadic), the verb `_ q: n` returns the prime exponents of `n`. So the inverse `inv` of that verb is exactly what we want.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes
```
1##&@@(i=0;Prime@++i^#&/@#)&
```
[Try it online!](https://tio.run/##3VBLCoMwEN17ikAgtJhS4y8JxZIjFLosLQRRzEIXxZ3o1dNkTPAOhWG@781v1PPQjXo2rbZ9YxnGRKmTabLb42vGTqWp@WByVfhMrMtM8wtf7r3Cb7I9Wz1tS7JkK00W5lVBUe5tRhE73L8RuLEOh7kDubdVsMwBqlDY4YKiMnzFuQzexCmSe9FHpUM4eiRURwcBH@S7E9s7ySEjA1lAogCgDO1rEBE1bCAh4jCBxW2S1f4A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
ÆẸ
```
[Try it online!](https://tio.run/##y0rNyan8//9w28NdO/4fbn/UtCby//9og1idaEMgNtZRMAJSBjoKhnDWsEEgD5pBvAX0nTmQMoVQhkBJU4goRKWFjoIJJDSALENQ4JjrKFhCpIAcE6A0UCdMtSlctwU43MwhDKjBQGQEFrCE6LQA843ByiwhJpuBkQWMBFltCeaYgw03hDkDAA "Jelly – Try It Online")
Just the builtin.
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
JÆN*µP
```
[Try it online!](https://tio.run/##y0rNyan8/9/rcJuf1qGtAf8Ptz9qWhP5/3@0QaxOtCEQG@soGAEpAx0FQzhr2CCQB80g3gL6zhxImUIoQ6CkKUQUotJCR8EEEhpAliEocMx1FCwhUkCOCVAaqBOm2hSu2wIcbuYQBtRgIDICC1hCdFqA@cZgZZYQk83AyAJGgqy2BHPMwYYbwpwBAA "Jelly – Try It Online")
If those brownie points are attainable, it's going to be hard!
```
ÆN n-th prime
J for each n in 1 .. len(input).
* Raise each prime to the corresponding exponent,
µ then
P output the product.
```
[Answer]
# [Factor](https://factorcode.org/) + `math.primes`, 43 bytes
```
[| x | 1 x length nprimes x [ ^ * ] 2each ]
```
-3 from Leo
[Try it online!](https://tio.run/##LYyxCsIwFEV3v@LODqUtuOgHiIuLOJUKIbzaYvKSJilE2n57jNXlci4HTidkMC7db5fr@YgXOSYFZaRQHtZRCG/rBg7QIvTbFPlr8j/uJpZhMOzhaZyIZRan3YwZJSrUWDf6blXikGFNzYKIJdsIRfzMVf4XIxo8sEeLmoTs0SYtLIr0AQ "Factor – Try It Online")
[Answer]
# [Factor](https://factorcode.org) + `math.primes math.unicode`, ~~38~~ 33 bytes
```
[ dup length nprimes swap v^ Π ]
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjUFCUWlJSWVCUmVeikJtYkqEHZOamFkPYpXmZyfkpqRBOWSpIe7FCcWphaWpeMlCNNVe1QrWCgYKhgpGCsUItmA0iTRQMTYGM2v/RCimlBQo5qXnpJRkKeVCTi8sTCxTK4hTOLVCI/Z8LZOv9BwA "Factor – Try It Online")
Explanation:
* `dup` duplicate the input (e.g.) `{ 0 1 2 3 } { 0 1 2 3 }`
* `length` find the length of a sequence `{ 0 1 2 3 } 4`
* `nprimes` generate primes given the number on top of the data stack `{ 0 1 2 3 } { 2 3 5 7 }`
* `swap` swap the top two objects on the data stack `{ 2 3 5 7 } { 0 1 2 3 }`
* `v^` vector exponentiation (component-wise) `{ 1 3 25 343 }`
* `Π` find the product of a sequence `25725`
# [Factor](https://factorcode.org) + `math.primes math.unicode`, ~~38~~ 33 bytes
```
[ [ length nprimes ] keep v^ Π ]
```
An equivalent answer using the data flow combinator `keep` instead of stack shufflers. Data flow combinators generally keep the data stack more static and easier to reason about than stack shufflers.
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjUFCUWlJSWVCUmVeikJtYkqEHZOamFkPYpXmZyfkpqRBOWSpIe7FCcWphaWpeMlCNNVe1QrWCgYKhgpGCsUItmA0iTRQMTYGM2v/RCtEKOal56SUZCnlQc2OBFqcWKJTFKZxboBD7PzexQEHvPwA "Factor – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 4 bytes
```
ẏǎeΠ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=r&code=%E1%BA%8F%C7%8Ee%CE%A0&inputs=%5B5%2C%207%5D&header=&footer=)
```
ẏǎeΠ
ẏ # range(0, len(input))
ǎ # nth_prime(^) // vectorises
e # ^ ** input // vectorises element-wise
Π # product(^)
```
The `r` flag tells Vyxal to pass arguments to built-ins in reverse order. It's been around before this challenge, so I didn't add it to cheat this one time. Without it, this would be 5 bytes (`ẏǎ$eΠ`)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
Πz`^İp
```
[Try it online!](https://tio.run/##yygtzv7//9yCqoS4IxsK/v//H22pY6ZjrmOqY6hjoWNoEAsA "Husk – Try It Online")
## Explanation
```
Πz`^İp implicit input
z zip the input
İp with the infinite list of primes, removing extras
^ using the power function,
` with flipped arguments.
Π take its product.
```
[Answer]
# [R](https://www.r-project.org/), ~~83~~ ~~82~~ ~~79~~ ~~78~~ 68 bytes
*Edit: -4 bytes thanks to Kirill L. and -1 byte thanks to Robin Ryder.*
```
function(l,p=1){for(i in l){while(sum(!(T=T+1)%%2:T)-1)1;p=p*T^i};p}
```
[Try it online!](https://tio.run/##3dJLasMwEAbgfU4xpQSkVgGNLFnjBvcUXtcUExOBH0Jx6CLk7K6h2HgjHaAgtPok5vGH2Q1T3Yaxr31w/aVuv5tpDLdybu9DM7lxYJ3wJfJHOwbmwA3Q8cfP1XUXdrv37IVVZfWO/HhUHxU/IcezL/1b9eWeZ/@MfM4aJjmHVzh9Ah6iBlej4iYToFZmE04KwD01SfpvzjbCTNt4x/luMsbmiY0IsCvUmdVxaXYyLwpKUFzqNNuqNVGmkhX8dUYC9JahnEjqQiqidFSWR7glz6AylpZLSnmYfwE "R – Try It Online")
Loops over the list `l` of prime exponents, each time using `while(sum(!(T=T+1)%%2:T)-1)1` to update `T` to the next prime, and multiplying the cumulative product `p` (initialized to 1) by `T` to the power of the current exponent. Finally, returns `p`.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes
```
wᵐ<₁ṗᵐ≜;?z^ᵐ×
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6amh1snWNtXVZeUKyno2ikoldtnPNzVWQsU/V8OJGweNTU@3DkdyHrUOQeoLg7IOjz9///oaINYnWhDIDbWUTACUgY6CoZw1rBBIA@aQbwF9J05kDKFUIZASVOIKESlhY6CCSQ0gCxDUOCY6yhYQqSAHBOgNFAnTLUpXLcFONzMIQyowUBkBBawhOi0APONwcosISabgZEFjARZbQnmmIMNN4Q5IxYA "Brachylog – Try It Online")
Function submission which dumps some garbage to STDOUT since it saves a byte over `l~l<₁ṗᵐ≜;?z^ᵐ×` or `∧ċ<₁ṗᵐ;?z₂≜^ᵐ×`.
```
wᵐ Create a list of unbound variables with the same length as the input.
(This also prints each element, but that's besides the point.)
<₁ This list is strictly increasing,
ṗᵐ and each of its elements is prime.
≜ Assign a value to each element.
;?z^ᵐ Raise each prime to the power of the corresponding element of the input,
× and output the product of the powers.
```
Without the `≜`, it completely breaks given exponents of zero--I suppose because they are mathematically eliminated from the final product?
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
í!pÈj}jUl¹×
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=7SFwyGp9alVsudc&input=WzAgMyAyIDEgMCAyXQ)
[Answer]
# JavaScript, ~~91~~ ~~86~~ 84 bytes
```
a=>{p=[],r=1;for(i=2;0 in a;i++)r*=p.every(x=>i%x)?i**a.shift(p.push(i)):1;return r}
```
[Try it online!](https://tio.run/##3c9LCsIwFIXhuavIREjSWpKKDwy3LqR0EKSht4MabtNSEdceBUGIuALhTM43@3s72/FC6MNmPkYH0UJ191A3OYE27kocoTSK4cCswSwTJMEX7dzSjS9Q4XoRZ5TSFmOHLnBf@GnsOApx0obaMNHA6BE94RC447VqhFh9nk7eNmdlAipn@of9zdL8/Xfqq/2QwO4N8Qk)
*Saved 2 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602)*
## Explanation
```
a=>{
p=[],//array of primes
r=1;//product/result
for(i=2;
0 in a;
//if 0 exists as a key in the array, then the first element exists
//and it is not empty
i++)
r*=
p.every(x=>i%x)?
//check if there is a remainder after division with each previous prime
//if so, then i is prime
i**a.shift(
p.push(i)//add to prime array, (shift ignores all arguments)
)
//multiply result by i to the power of the first
//input array element (and remove it)
:1; //multiply by 1 if i is not prime
return r
}
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~83 69~~ 57 bytes
Thanks to thanks to @AZTECCO and @Unrelated String for bringing it down to 57 bytes :)
```
f=product.zipWith(^)(s[2..])
s(x:t)=x:s[y|y<-t,y`mod`x>0]
```
[Try it Online!](https://tio.run/##y0gszk7Nyfmfm5iZp2CrUFCUmVeikaYQbamjYKajYK6jYKqjYKijYAEkDWI1/6fZFhTlp5Qml@hVZRaEZ5ZkaMRpahRHG@npxWpyFWtUWJVo2lZYFUdX1lTa6JboVCbk5qckVNgZxP7/DwA)
**Edit:** Realised that newlines are also one byte so putting multiple lines on a single line with semicolons doesn't change the size.
**Edit #2:** Realised that I don't need to `take (length x)` to my list of primes, zipWith only takes how many it needs to.
**Edit #3:** Reduced to 57 bytes, thanks to thanks to @AZTECCO and @Unrelated String (See Comments)
## Explanation:
(My solution wasn't very difficult to understand but I'm a beginner with Haskell so writing this out helps me xD)
A more readable version would be:
```
sieve (x:xs) = x:sieve [y | y<-xs, y `mod` x > 0]
primes = sieve [2..]
applyExponents x = zipWith (^) primes x
reconstruct = product . applyExponents
```
Recursive function used to generate a list of primes---use list comprehension to remove multiples of the last prime inserted into the list.
```
sieve (x:xs) = x:sieve [y | y<-xs, y `mod` x > 0]
```
Apply recursive sieve function to an infinite list of natural numbers from 2 onwards to get an infinite list of primes.
```
primes = sieve [2..]
```
~~Use `take (length x)` to evaluate the list of primes and get the right number of prime numbers for the length of list x.~~ Use zipWith to apply the correct exponent to each prime number.
```
applyExponents x = zipWith (^) p x
```
Then use `product` to multiply the list resulting from the previous step together.
```
reconstruct = product . applyExponents
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~110~~ \$\cdots\$ ~~79~~ 75 bytes
Saved ~~5~~ 9 bytes thanks to [xibu](https://codegolf.stackexchange.com/users/90181/xibu)!!!
```
d;p;r;f(a,l)int*a;{for(r=p=1;l;r*=pow(p,d<2?l--,*a++:0))for(d=++p;p%--d;);}
```
[Try it online!](https://tio.run/##3ZTbjpswEIbv8xQjJCRsjArmvA7di6pPsYkqxGGLyiYIIm3UiFcvHbATiNUnaIQz8f95xvGMmcJ5L4ppKkUnelFbOWtJc7rQXNzqc2/1WZd5ohU9zbrzp9Wxcs9fW8dhNLftF5eQeVGZ2XYnOtNxSkHEOHU9RrBwAM0ZzLYlMIeDRWwgA1eg2UMrwLYbAotHbRnmYJYGw2VZ5sIrGAa8AM4NwiB/a44YfPeRNyeL7G47wM8c7lINlx/u2xGj3jwG6zOKlXuSu1uNK5@t5kvNZ8C3cqDcl8BPJHyQ/@Z5Skgkzxdpx44f@Y63ciLlUJNTtRqDh6O4V44ucJBMVpGpainLlfWVDZQNlY2UjZVNlE3XTUAqrdxlaH5X59qSm5EvakrVnMGWexr3NM41zjXua9zXeKDxQOOhxkONRxqPNB5rPNZ4ovFE46nGU7LJanXtquJSlTKtnPo0pDH15JuHZYvngWXyA6xNGGOhAj/G8kVpmqDhQZL4XMUrfuY9xe@q@FX1MqBxuH7nh2v6DUc4N4DN3DeU39pQTmV1VU1l@bm/H@T@N9ejPJSl88yrsTUt4dZbiaHkzVz4UWwxtIrilfoXHhBjArGLPusV6o@k6Y6yYT473VsiOF/BLMEcDidMxMAeiRqyrDoqh3E3Tn@Kus3fh8n5nJz24y8 "C (gcc) – Try It Online")
Inputs an array of prime exponents and its length \$l\$ (because C arrays have undefined length) and returns the product of the first \$l\$ primes to those exponents.
### Explanation (before some golfs)
```
d;p;r;f(a,l)int*a;{ // function taking an array of
// ints and its length l
for(r=p=1;l--; // loop over the array elements
// setting the product r and
// the previous prime to 1
r*=pow(p,*a++) // once we've found the next
// prime multiply r by it
// to the power of the current
// value in a
for(d=2;d>1;) // loop until we find the next
// prime, d==1 will flag this
for(d=++p; // set d to p bumped
p%--d;) // bump d down and loop
// until we find the highest
// divisor of p
d=r; // return r
} //
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 106 bytes
```
$s=1;while($n-lt$a.length){if(('1'*(++$i))-notmatch'^1?$|^(11+?)\1+$'){$s*=[math]::pow($i,$a[($n++)])}};$s
```
[Try it online!](https://tio.run/##3cxBCoMwEEDRq2QxkBmjpbNVgr2HVQglbQKpkSaQhfXsqeco/N2Dv8ViP8nZECoYocUNr634m5gqJM1DcT5YhLULGcwl2PWVHe3@iShZNqgUeKJujflt8sPJhUf4LsisRrqzAkk7pEZPp7q577dYEHwLZjqXStFMxzFAqvUH "PowerShell – Try It Online")
Uses a regex to match prime numbers, more about it [here](https://www.noulakaz.net/2007/03/18/a-regular-expression-to-check-for-prime-numbers/)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 2 bytes
```
.Ó
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f7/Dk//@jLXUUzHQUzHUUTHUUDHUULICkQSwA "05AB1E – Try It Online")
```
.Ó # full program
.Ó # push the number with a prime factorization with exponents in...
# implicit input
# implicit output
```
[Answer]
# [Raku](http://raku.org/), 31 bytes
```
{[*] grep(&is-prime,^∞)Z**$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OlorViG9KLVAQy2zWLegKDM3VSfuUcc8zSgtLZX42v/FiZUKSirxCrZ2CtVpCkARJYW0/CIFGwM7HQUbQxBhrGAEogwUDCEMcwVLBQMFC7C8AZBlpGChYGn3HwA "Perl 6 – Try It Online")
`grep(&is-prime, ^∞)` is an infinite, lazy sequence of primes. `Z**` zips that sequence with `$_`, the list argument to the function, using exponentiation. Then `[*]` computes the product of that sequence.
[Answer]
# [Haskell](https://www.haskell.org/), ~~61~~ 56 bytes
```
f=product.zipWith(^)[x|x<-[2..],all((>0).rem x)[2..x-1]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P822oCg/pTS5RK8qsyA8syRDI04zuqKmwkY32khPL1YnMSdHQ8POQFOvKDVXoUITJFihaxgb@z83MTNPwVahoCgzr0RBRSEt2lBHwQCMLHQUTGL/AwA "Haskell – Try It Online")
* saved 5 by stealing @Unrelated String advice to @M. Salman Khan answer.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~12~~ 11 bytes
-1 thanks to Adám
```
⊢×.*⍨¯2⍭⍳∘≢
```
```
⊢×.*⍨¯2⍭⍳∘≢
¯2⍭⍳∘≢ ⍝ the first n primes
⊢×.*⍨ ⍝ powers and product
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG9qQMCjtgnGJlxAplsQkGloZGH@/1HXosPT9bQe9a44tN7oUe/aR72bH3XMeNS56H8aUMmj3r5HXc2Petc86t1yaL3xo7aJQM3BQc5AMsTDM/h/moKhgjkXiDQAQgsFEwA "APL (Dyalog Extended) – Try It Online")
[Answer]
# JavaScript (ES7), ~~64~~ 58 bytes
```
a=>(g=d=>a+a?n%--d?g(d):(d>1||n**a.shift())*g(++n):1)(n=2)
```
[Try it online!](https://tio.run/##bcnLCsMgEEDRff@jMOMjaPokoPmQ0oXEaBPCWGroKv9usy5yd@fO7uvy8Jneq6TkxxJMccZCNN5Yx11PRyl9H8FjB97qbSPGXJNfU1gBkUXgnLDTCGRaLEOinJaxWVKEAA/1RDz8ma7YSbQVVUJX/VpVLW4VvVRVC7V3F@f9lR8 "JavaScript (Node.js) – Try It Online")
## With BigInts, 61 bytes
A version that supports large integers. Expects a list of BigInts.
```
a=>(g=d=>a+a?n%--d?g(d):(d<2?d:n**a.shift())*g(++n):1n)(n=2n)
```
[Try it online!](https://tio.run/##XcrLCsIwEIXhve8hzCRNMcVrMM2DiIuhaWKlTMQUXz9qwI1w@Dfnu9OL8vCcHovi5McSbCHbQ7Te9iTJ8Vop7yJ4NODPnfOGhaA236awAKKIICWj0YzAtmMsQ@Kc5rGdU4QAlwM3@7rjr1u@Iq7@2Km@H7zjRlemN19X3g "JavaScript (Node.js) – Try It Online")
### Commented
```
a => ( // a[] = input array
g = d => // g is a recursive function taking a divisor d
a + a ? // if a[] is not empty:
n % --d ? // decrement d; if it's not a divisor of n:
g(d) // do recursive calls until it is
: // else:
( // multiply the final result by:
d > 1 || // - 1 if d is greater than 1 (n is composite)
n ** a.shift() // - the prime n raised to the power of the next
) // exponent extracted from a[] otherwise
* g(++n) // and multiply by the result of a recursive call
// with n + 1
: // else:
1 // stop the recursion and return 1
)(n = 2) // initial call to g with d = n = 2
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
≔¹ζFA«≦⊕ζW﹪⊕Π…¹ζζ≦⊕ζ⊞υXζι»IΠυ
```
[Try it online!](https://tio.run/##fYy9CsIwGEXn9im@8QvEwR9Q6SROHQrBtXQIaWwDMSn5sVDx2WOxIk4udzj3cETPnbBcp3TyXnUG1xQmUuRX6wBLM8SAhMAjzyo@fIzSCCdv0gTZLm429kpLwMq2UdvfH5mbmQh44aaTS5uQ98K/IIu@x0iB2VE6nCgoMuNnzpwyAc/ch285zsEipbreUThQ2FDYUthTODZNWt31Cw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔¹ζ
```
Start finding prime numbers.
```
FA«
```
Loop over the input list.
```
≦⊕ζW﹪⊕Π…¹ζζ≦⊕ζ
```
Increment the integer it until it's prime via Wilson's theorem.
```
⊞υXζι
```
Take the appropriate prime power.
```
»IΠυ
```
Print the product of the resulting prime powers.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
ā<ØsmP
```
[Try it online!](https://tio.run/##yy9OTMpM/f//SKPN4RnFuQH//0eb6RjFAgA "05AB1E – Try It Online")
In other words:
```
P sm Ø ā <
product(exponate(nth_prime_number(range(1, len(input())) - 1), input()))
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 bytes
```
£Èj}iY pXÃ×
£ // Map the input array with X as items and Y as indexes to
È }iY // Y-th positive number
j // that is prime
pX // to the power of X,
Ã× // then reduce with multiplication.
```
[Try it out here.](https://ethproductions.github.io/japt/?v=1.4.6&code=o8hqfWlZIHBYw9c=&input=WzAsIDEsIDJd)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 83 bytes
```
$
,__
m)+`,(_+)$(?<=\1¶.+)|,(__+)\2+$
$&_
~["L$`^¶$.("|""]'_L$`(.+),(_+)
$1*$($.2$*
```
[Try it online!](https://tio.run/##K0otycxLNPz/X4VLJz6eK1dTO0FHI15bU0XD3sY2xvDQNj1tzRqgCFAoxkhbhUtFLZ6rLlrJRyUh7tA2FT0NpRolpVj1eCBfA6gSrJVLxVBLRUNFz0hF6/9/Ey4LLiMuYy5zLksA "Retina – Try It Online") Takes a newline-separated list. Explanation:
```
$
,__
```
Pair each element of the input array with 2 in unary.
```
+`,(_+)$(?<=\1¶.+)|,(__+)\2+$
$&_
```
Increment each unary part until it is a prime greater than the previous one.
```
m)`
```
Turn on per-line `$` for all of the stages up to and including the above.
```
["L$`^¶$.("|""]'_L$`(.+),(_+)
$1*$($.2$*
```
Transform each pair into a repeated multiplication, so that for example `3,__` becomes three copies of `2*` i.e. `2*2*2*` while `2,___` becomes two copies of `3*` i.e. `3*3*`. Append a `_` to handle the case of zero input, and prepend `L$`^` and `$.(` to create a Retina program that replaces the current value with the total product.
```
~`
```
Evaluate that Retina program. For example, in the case of an input of `3` `2`, the resulting program is as follows:
```
L$`^
$.(2*2*2*3*3*_
```
`3*_` is `$(___)` and so on, with `$.(` taking the final length in decimal (Retina actually optimises this and simply multiplies the values together).
[Answer]
# [R+primes](https://www.r-project.org/), ~~46~~ 43 bytes
Exploiting the primes library
```
prod(primes::nth_prime(seq(a=l<-scan()))^l)
```
[Don't try it online!](https://tio.run/##K/r/P8e2ODkxT0PTuqAoP0WjoCgzN7XYyiqvJCMezNYoLs3VMIzL0dQE4v//AQ "R – Try It Online") (as primes is not recognised by tio.run, apparently) Here is the output on rrdr.io:
```
prod(primes::nth_prime(seq(a=l<-scan()))^l)
0 0 0 0 1
Read 5 items
[1] 11
prod(primes::nth_prime(seq(a=l<-scan()))^l)
2 3 1 0 0 1
Read 6 items
[1] 7020
prod(primes::nth_prime(seq(a=l<-scan()))^l)
9 0 0 1 0 0 2
Read 7 items
[1] 1035776
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-rprime`, ~~54~~ 37 bytes
A whopping 17 bytes off by Sisyphus.
```
->x{c=1;x.zip(Prime){|a,b|c*=b**a};c}
```
[Try it online!](https://tio.run/##3VPLSgNBELz7FQNeNGykp99NiN/gXTyYoJCDGqKCGv1113E2O1n8BGGYnS66q6ur2d3r6r2/X/bzy7f9epkXbxcfm@3Z1W7zcHe@/7ztVp/r2XI1m91@LdZf/TbdX1/DzU06TfPLlE9qnMcYh5i6hCNkBwy6lKewNPjfnGYDsQ3T6WRiMT241SUbQSbjAZUJqhF@gHPhlWYvuxM2lqGrd4nbPtQdOADdj6soCbltTDKKebkAYMiwLsVA1FhYkMIsghUPOrh0KQrHpjJRJURmaIJZ2bQyQ9Pode02PFoDATEIUuYIVUTMAcd5y8FaEBNDw4kofp1BLR8de3DNLPlU27SS7AqYi2FehiEJzQQOTjqZW@vx8T7aCJnZMLBolEJUdIohakZzFQc4jhi12Koj@Y/XXpJFhZwJgykDqAWbCFvZ0MAC/ffT9mXz9Pjcz3fb35/uBw "Ruby – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 29 bytes
```
(i=s=1;s*=Prime@i++^#&/@#;s)&
```
[Try it online!](https://tio.run/##3VBLCoMwEN17ikBA2ppS4y8JkuIRuhcLUhSzsIvqTjx7OkyY4hkKw/Dmzbz5zf06DXO/ulfvR@tPzi5W1svFPj5uHhqXJE8e3xpeL@fYA/deW369jy3vOqCjbUt3EbFNos8FyxCkgskD/hsLZ1Z0GtyoEJQEJBSVlAsaLVhB3wEsw8OUYCakMSygCHqQpjx00fhLFcBvCFiGlCG9RibHUkMzKjRNPixiMFQ4RtJSu/df "Wolfram Language (Mathematica) – Try It Online")
One character longer than [@att's solution](https://codegolf.stackexchange.com/a/220273/87058) but maybe it has potential for golfing down.
] |
[Question]
[
Had my software final exams recently, one of the last questions had me thinking for a while after the exam had finished.
## Background
IEEE754 numbers are according to the below layout
[](https://i.stack.imgur.com/V5zks.png)
The exponent is stored as n + 127 so for an exponent of 20 the exponent in binary would be:
`127 + 20 = 147` then
`10010011`
## The Challange
Write a program that when given text representing a binary floating point number to the [IEEE754](https://en.wikipedia.org/wiki/IEEE_754) standard, returns the exponent given as a decimal value.
## Example
Input: `00111101110011001100110011001101` (0.1)
Isolated exponent bits: `01111011`
Convert to binary: `0 + 64 + 32 + 16 + 8 + 0 + 2 + 1 = 123`
Remove offset: `123 - 127 = -4`
Output `-4`
---
Input: `10111111110111101011100001010010` (-1.64)
Isolated exponent bits: `01111111`
Convert to binary: `0 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 127`
Remove offset: `127 - 127 = 0`
Output `0`
## Rules
* Input must be text/string/equivalent indexable datatype, eg. strings **not** integer or numerical
* Output can be any type, as long as it is decimal
* Aim for shortest solutions
---
Adapted from the [2020 Software Design and Development HSC Paper](https://educationstandards.nsw.edu.au/wps/portal/nesa/resource-finder/hsc-exam-papers/2020/software-design-and-development-2020-hsc-exam-pack): 30) d) ii
>
> Design an algorithm that takes in a string of 32 characters representing
> a floating point number, and displays the exponent as its signed decimal
> value.
>
>
>
Any feedback is appreciated as this is my first question
[Answer]
# [Haskell](https://www.haskell.org/), 33 bytes
```
foldl1(\x y->x*2+y-1).take 8.tail
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPy0/JyXHUCOmQqFS165Cy0i7UtdQU68kMTtVwQJIZeb8z03MzFOwVSgoyswrUVBRSFOINtAx0DGEQgM4bUAkbRj7/19yWk5ievF/3eSCAgA "Haskell – Try It Online")
Input is a list of integers 0 or 1.
It's slightly shorter to `foldl1` by `x*2+y-1` than to subtract 127 at the end. This works because
```
foldl1 (\x y->x*2+y-1) [a,b,c,d,e,f,g,h]
= ((((((a*2+b-1)*2+c-1)*2+d-1)*2+e-1)*2+f-1)*2+g-1)*2+h-1
= a*128 + b*64-64 + c*32-32 + d*16-16 + e*8-8 + f*4-4 + g*2-2 + h-1
= 128a + 64b + 32c + 16d + 8e + 4f + 2g + h - 127
= fromBinary[a,b,c,d,e,f,g,h]-127
```
[Answer]
# [Python 3](https://docs.python.org/3/), 26 bytes
```
lambda s:int(s[1:9],2)-127
```
[Try it online!](https://tio.run/##ZU5BCoMwELz7ir1tAhESFaRC@hH1YG2Cpa1Kkh6K@PY0Se2pAzvMsrO7s77dtMyl17Lzj@F5uQ5gm9vsiG1Fc@pZQXNR1N4p6yxIIBkEEORcBESK6q8Esryi7DAnn/gtBPru8SgiIQMezDQbJzXelYl/sHsVdTWGUVKiRJrpxYBjCm4zpDxNuh/tmjiamtXE7Bo3t0N@hs3ssB1XWyOl6nek/gM "Python 3 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~55~~ \$\cdots\$ ~~40~~ 36 bytes
Saved ~~2~~ 6 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
Saved ~~2~~ a whopping 13 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!
```
#define f(s)strtol(s+1,s[9]=0,2)-127
```
[Try it online!](https://tio.run/##jVHbboMwDH3vV1hMSKENGpdNU8XYy7SvaHlIQ9KidRThSGOr@PUxh0vbdS@NZMucHI7tE@lvpey6u1zpolSgGXpoanPYM1yEHFfLLA145Plh9NQVpYEPUZTMmx1nQEfuRD0Ho9DgKoMUjk4QhHRsstW/CB0OTngDp6fcpDPxKA30wBY2OW3ST2nHVk2lpFH5MKb/wMFGGFEKRlq/jNwp@a5qovXrrJu3aN0sXykebcuL73iS14camO1RlLlq6LcgGctnwOJbHTSbunv3IzA/IQksFj3bg8HTs69IWoO3PSFL/tzDZhXHFxi9mqy@2IajdwbtWIJkNNtcoYrQkynX@lVNFM0cF8F/ATcHF9cl7Y8cBIfJI5WmIhtl21nb/Ui9F1vs/M9f "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes
```
¦8£CƵQ-
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0DKLQ4udj20N1P3/38DAEAhABIiFgQ0B "05AB1E – Try It Online")
```
¦8£CƵQ-
¦ remove first element
8£ take next 8 elements
C convert from binary string to an integer
ƵQ push 127
- subtract
```
Thanks to Kevin for -1 byte
[Answer]
# x86 machine code, 14 bytes
Same machine code works in 32 or 64-bit mode. (Same length for 16-bit mode would be easy with different regs). Callable from C as x86-64 System V `int8_t getexp(const char *b2_str);`
```
23 ; input: char *str in RDI
24 ; return: int8_t AL; (calling convention allows garbage in high bytes of RAX)
25 getexp_scalar:
26 00000030 6A09 push 9 ; sign bit gets shifted out the top.
27 00000032 59 pop rcx
28 00000033 B030 mov al, '0'
29 .loop:
30 00000035 AE scasb ; set FLAGS like cmp '0', [rdi] would, if it was encodeable
31 00000036 10D2 adc dl,dl ; DL = DL<<1 | CF, rotate CF into DL.
32 00000038 E2FB loop .loop
33 0000003A 8D4281 lea eax, [rdx-127] ; no shorter than sub dl, 127 or xchg eax,edx / sub al,127
34 0000003D C3 ret
```
We just do base 2 ASCII->integer conversion for 9 bits, letting the first bit (sign bit) overflow off the top of DL. The 8-bit return value is only the 8-bit AL register, as a 2's complement binary integer.
`adc dl,dl` to rotate CF into DL is more efficient on modern CPUs than `rcl dl, 1` (rotate through carry, i.e. shift in CF). They're equivalent except for some FLAGS output semantics. I could have used EDX for the same code size; that would simply leave different garbage in the high bytes outside the AL return value in RAX. (And yes, high garbage above narrow return values is [100% allowed by standard x86 calling conventions](https://stackoverflow.com/questions/36706721/is-a-sign-or-zero-extension-required-when-adding-a-32bit-offset-to-a-pointer-for/36760539#36760539).)
[Try it online!](https://tio.run/##hVVtb9s2EP7OX/GgX/pme5a7tZ3dYUhXdAhgYECyDwOKwDiJtEREIhWScuRh/z07Uo4VOxsqwHrhkc89d/fcmbxXTV7vp4Z88/BAtS4NsvdihUC3yi9RWOMDiooc3vjgoA2uvlyy3anQOcM7tAkfNwEX6xWASpcV8n1QHnaLq4u/0NAeuUJJLqdSgTxa5eADGUlOoqC61qaMfnbKBM3uZqJUQfXtxrOR3FLgcLWdr/Azzq8VfGSd6wDN6M4WiqOSYA9gJA9f6W3gBdsFhEoh2HY2gtoWcEV/XGjsDqB6gpfzl2JWW9uODJiRz/EfF3NQAV/XF79fo9a3CkXTRoAJvjmpb4B729VyAr0F07znLChTWKkor9URnWQByHoi62foX9b4hW@fPmX4B799ncDZQEHxa8y/ZdMYUaSMRHxcUgQo6hOdfpotPtw8IhvL@bEucFFCRQa@yyMH8B7AOqAvqjKdVbLHD8nO2WHzEZ2lIMQT6WjTdmGJq@vLScx5@rhYn1Z1cV7W5wU5yz3HJX0@fsbypjplT7akOOUhzjcLvIWj/ua7qTnLzf9EdgigafonrDiFiRi7is87fub@ntp4mnq@syY9NYodmTJUsQFYYdwRbnDp9dvs6HCwDEcH6bAx@Yg9NXVqp5xXeJXrcqqM1GRes1eSsdmispmeNdxG2GpVyxkLlnbcitln7PwsKfvA7tGhrw5aSw4/nAR1n1qKxZWamhtfUTE0dwLmkLz@e@hoX9cSTTNniNmTWO6Gl7jO@I@Gli2Nv82HpLP16LOl4hY7VQTW3TBJNLdvEniWHB9pd4cupEGpYqzXg1Rb6urA77Uoa5tTjQ2PGxfE8FiKOKh2TELeEfaJ3TcebfNNdmyKqK2TjDOD9fXn6VY7H34VYhQOl2g8Lo7zA1zXSTSmpTjkgFE@4uCGt/oeKm8nHMiIms6eYCaA0/45x@jPMOT3McQj3wgQ9zPAMYBUnMW71Fx@74cQno891euwKZ3t2lcx@zvO9mshViv8efkHz2KuncfHaRRS3Bnnfuh81Exn4tRWPBO9xd52qFiqMc/SJikvflpgyvf3PPimP0b58SaWhSI5E8KzSPi/AjNnJQU69Oi7hRgiXkLmeDGfZ3zFW3x79stePPwL "Assembly (nasm, x64, Linux) – Try It Online") 3 versions with a test caller.
(Including alternate 15-byte scalar version using `lodsb` / `and al, 1` / `lea edx, [rdx*2 + rax]`)
# x86-64 SIMD (MMXext+MOVBE) machine code, 20 bytes
Having base-2 digits in MSB-first printing order is a major inconvenience for little-endian x86, where the lowest SIMD vector element comes from the lowest address in memory. x86 lacks a bit-reverse like ARM's `rbit`, so I used x86-64 features to byte-reverse 8 bytes. Without that, `movq mm0, [e/rdi+1]` (4B) / `pslld mm0,7` (4B) would be 32-bit-mode compatible and work on a Pentium III (`pmovmskb r32, mm` was new with SSE, [aka MMXext](https://en.wikipedia.org/wiki/Extended_MMX), so not original P5 Pentium-MMX).
```
; input: char *RDI; result int8_t AL
; clobbers: MM0. Leaves FPU in MMX state (no EMMS)
12 getexp_mmx:
14 00000010 480F38F04701 movbe rax, [rdi+1] ; byte-reverse (big-endian) load of the exponent field. saves 1B vs. mov + bswap
15 00000016 48C1E007 shl rax, 7 ; low bit to high in each byte. same size as pslld mm0, 7.
16 0000001A 480F6EC0 movq mm0, rax
17 0000001E 0FD7C0 pmovmskb eax, mm0 ; pack vector high bits into 1 byte
18 00000021 2C7F sub al, 127
19 00000023 C3 ret
; size = 0x24 - 0x10 = 0x14 = 20 B
```
MMX instructions typically need 1 fewer prefix byte than SSE2 and later; if you were doing this for real you'd probably use XMM0, and avoid the EMMS (exit MMX state) that real code would normally use. (And maybe a `pshufb` for the byte reverse if you have SSSE3, to avoid bouncing through integer regs...) This should still be much faster than a loop with adc and false dependencies, and the slow `loop` instruction itself. **It's handy that the exponent field is exactly 8 bits wide.** Doing this for `double` would need an SSE2 16-byte load (or 2 byte reverses and annoying shuffles to combine into a 16-byte vector), and would have to mask away the sign bit.
lodsb (1) + lodsq (2) + bswap rax (3) is the same total length as `movbe rax, [rsi+1]` (6), although that would make this portable to machines without `movbe` (Atom, Haswell and later).
---
For subnormal (aka denormal) floats including `0.0`, this just returns `-127`, the unbiased the exponent *field*, as requested by the question. And `-128` (overflowed from +128) for Inf / NaN inputs. (I only realized this overflow issue after the fact, posting anyway because all 255 possible outputs are *unique*, and that puts both special exponents at adjacent values so the caller can test for subnormal or inf/nan with `e <= -127`.)
It doesn't return the actual `floor(log2(|x|))` of the represented value like AVX512 `vgetexpps xmm, xmm` does: (`-Inf` for an input of 0, and values below -127 for non-zero subnormals, matching [the pseudocode in the documentation](https://www.felixcloutier.com/x86/vgetexpps#tbl-5-15)).
So even if we could take input as an actual *binary* floating-pointer number in [IEEE754 binary32 format](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) (aka `float`) in an XMM register, we couldn't just use that one 6-byte AVX512 instruction to produce an integer-valued `float` result.
---
### not competing AVX2 version, 15 bytes
This takes its arg as 32 bytes of ASCII digits in a YMM register, but they have to be in least-significant-digit first order, hence not competing.
```
2 getexp_avx2_ymm_reversed:
3 ; input: LSD-first ASCII digits in ymm0. Probably can't justify that and would need to byte-reverse
5 00000000 C5FD72F007 vpslld ymm0, ymm0, 7
6 00000005 C5FDD7C0 vpmovmskb eax, ymm0
7 00000009 C1E817 shr eax, 23 ; AL = exponent
8 0000000C 2C7F sub al, 127
9 0000000E C3 ret
```
Fun fact: AVX-512 allows `vpslld ymm0, [rdi], 7`, if you had bytes in the LSD-first order in memory. (7 bytes including 4-byte EVEX, so an extra 2 bytes to take a char\* instead of YMM arg.)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
╞8<å♣(-
```
[Try it online.](https://tio.run/##y00syUjPz0n7///R1HkWNoeXPpq5WEP3/38lAwNDIAARIBYGNlTigioB8g1AGBOAlBiCJSEGYQFKAA)
**Explanation:**
```
╞ # Remove the first character of the (implicit) input-string
8< # Slice to only keep the first 8 characters of the string
å # Convert it from a binary-string to a base-10 integer
♣ # Push constant 128
( # Decrease it by 1 to 127
- # Subtract it from the integer
# (after which the entire stack joined together is output implicitly as result)
```
[Answer]
## JavaScript (ES6), 23 bytes
```
f=
b=>(`0b${b}0`>>>24)-127
```
```
<input oninput=o.textContent=f(this.value)><pre id=o>
```
Uses the fact that `>>>` truncates to 32 bits.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, ~~24~~ ~~23~~ 20 bytes
*-1 byte thanks to [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus)*
*-3 bytes using `-n` command-line flag, inspired by [this answer](https://codegolf.stackexchange.com/a/213642/83605)*
```
p$_[1,8].to_i(2)-127
```
[Try it online!](https://tio.run/##KypNqvz/v0AlPtpQxyJWryQ/PlPDSFPX0Mj8/38DA0MgABEgFgY25ALLGcIUAQmIWgMQA0T8yy8oyczPK/6vmwcA "Ruby – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), ~~26~~ ~~31~~ 29 bytes
Converted to a valid anonymous function, thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)
-2 bytes thanks to [user](https://codegolf.stackexchange.com/users/95792/user)
```
{it.slice(1..8).toInt(2)-127}
```
[Try it online!](https://tio.run/##y84vycnM@59WmqeQm5iZp5FYlF5speBYVJRYaRNcUpSZl26nqVDNpQAFZYk5CmkVVgoaEDlNBV07Bc@8EgXb/9WZJXrFOZnJqRqGenoWmnol@UBxDSNNXUMj89r/nAVA5SU5eRppFRpKBgaGQAAiQCwMbKikqclV@x8A "Kotlin – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 22 bytes
```
echo $[2#${1:1:8}-127]
```
[Try it online!](https://tio.run/##S0oszvj/PzU5I19BJdpIWaXa0MrQyqJW19DIPPb///8GBoZAACJALAxsCAA "Bash – Try It Online")
# [Bash](https://www.gnu.org/software/bash/), ~~37~~ 27 bytes
Input is from STDIN, output is to STDOUT.
```
expr $[2#`cut -b2-9`] - 127
```
[Try it online!](https://tio.run/##S0oszvj/P7WioEhBJdpIOSG5tERBN8lI1zIhVkFXwdDI/P9/AwNDIAARIBYGNgQA "Bash – Try It Online")
## Explanation
```
expr # Evaluate the following:
`cut -b2-9` # Slice all characters from the 2nd character
# to the 9th character in standard input
$[2# ] # Convert it from base 2
- 127 # And subtract by 127
```
[Answer]
# [Desmos](http://desmos.com/calculator), ~~42+9=51~~ ~~40+9=49~~ 30 bytes
```
f(l)=\sum_{i=0}^7l[9-i]2^i-127
```
Input as a list of 1's and 0's.
[](https://i.stack.imgur.com/pWCJD.png)
[Try It On Desmos!](https://www.desmos.com/calculator/urde7webzo)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
```
¯127+2⊥8↑1↓⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////9B6QyNzbaNHXUstHrVNNHzUNvlR16L/aY/aJjzq7XvU1fyod82j3i2H1hsDZR/1TQ0OcgaSIR6ewf/TFAyA0BAKDeC0AZG0IQA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 63 bytes
```
2=M&!`.{8}
1
01
+`10
011
$
-127$*
(1*)-\1
-
^0*(-)?(1*)-?
$1$.2
```
[Try it online!](https://tio.run/##K0otycxL/P/fyNZXTTFBr9qilsuQy8CQSzvB0ABIG3KpcOkaGpmraHFpGGpp6sYYculyxRloaehq2oMF7LlUDFX0jP7/NwAqNjQEESAWBjYEAA "Retina 0.8.2 – Try It Online") Explanation:
```
2=M&!`.{8}
```
Get the second overlapping 8-character substring.
```
1
01
+`10
011
```
Convert to binary (may leave leading `0`s).
```
$
-127$*
(1*)-\1
-
```
Subtract 127 (may leave trailing `-`).
```
^0*(-)?(1*)-?
$1$.2
```
Convert to decimal, removing garbage.
[Answer]
# [J](http://jsoftware.com/), 12 bytes
```
127-~1{8#.\]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DY3MdesMqy2U9WJi/2tyKXClJmfkK6QBVRgoGEKhAZw2IJI2/A8A "J – Try It Online")
```
#. convert to binary
8 \ all the infixes with length 8
] of the argument
1{ take the second one (0-indexed)
127-~ subtract 127
```
[Answer]
# C#, 120 115 42 32 bytes
```
s=>Convert.ToByte(s[1..9],2)-127
```
Thanks to @SunnyMoon for realising that the code is not actually 120 bytes (-2)
Thanks to @Sunnymoon for slaying 3 *sneaky* spaces in the code (-3)
Thanks to @user for coding a much **much** shorter lambda solution (***-73***)
Thanks to @thedefault. for using the `..` operator and `Convert.ToByte` (***-10***)
[Try it online!](https://tio.run/##ZYyxCsIwEIb3PMXRqYE2NF1EagsquDkpOIhDiKkEagK9a6FInz2mxc2DO35@vu805hp1GNC6F1wmJPOumO4UIuzhwwCQFFkNo7dPOCvrUr7W8IPFaXB6h9RHPwPrqIEW6oB1c/RuND2Jqz9MZFK8SyG2j6zkuSw3oVp/RAZ9Z8SttxFp06QoZJzlLOlvZcL5Ys5sDl8)
**As it turns out, C# is actually quite useful for golfing! Lambdas are the way to go!**
---
Welcome to code golf, Maximilian Rose!
[Answer]
# [Python 3](https://docs.python.org/3/), 54 bytes
ty to @Bubbler and @Kevin Cruijssen for corrections
```
lambda n: sum([2**i*int(n[8-i])for i in range(8)])-127
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PycxNyklUSHPSqG4NFcj2khLK1MrM69EIy/aQjczVjMtv0ghUyEzT6EoMS89VcNCM1ZT19DI/P9/MwtTyxQA "Python 3 – Try It Online")
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 30 bytes
```
r~8[01:@{2%*+$2*60l4)?.{""-n;
```
(contains an unprintable `DEL` between the quotes)
[Try it Online!](https://tio.run/##S8sszvj/v6jOItrA0Mqh2khVS1vFSMvUIMdE016vWqleSTfP@v///7rFBgaGQAAiQCwMbAgA)
```
r~8[ grab relevant part of string
01 accumulator and exponent initialization
main loop
@{2% convert current digit charcter to 0 and 1
*+$ accumulate
: 2* increment exponent
60l4)?. loop while digits remaining
{""-n; print result sub 127 and terminate
```
Most of the work is constructing a number from binary notation.
[Answer]
# Scala, 27 bytes
Uses Lynn's [clever approach](https://codegolf.stackexchange.com/a/214774/95792)
```
_.slice(1,9)reduce(_*2+_-1)
```
[Try it online](https://scastie.scala-lang.org/pUShRsE7TVSCWYzYpJK8yg)
# Scala, 29 bytes
```
n=>BigInt(n.slice(1,9),2)-127
```
[Try it online!](https://scastie.scala-lang.org/9DgvUdWjRki0fkZ2BXCjhQ)
Very straightforward. Takes a `String`, parses the exponent's bits as an integer in binary, then subtracts 127, returning a `BigInt`.
# Scala, 29 bytes
```
n=>(BigInt(n.tail,2)>>23)-127
```
[Try it online](https://scastie.scala-lang.org/pSvsZAQ3S5aOOVkOhC2kjg)
Unfortunately, because of operator precedence, the outer parentheses are needed.
# Scala, 29 bytes
```
_.slice(1,9)./:(0)(_*2+_)-127
```
[Try it online](https://scastie.scala-lang.org/bAxtSdGJRKqCgeNT3py96Q)
Yet another solution, this time taking a list of digits (`List[Int]`).
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 49 bytes
```
: b drop 1+ 8 ['] evaluate 2 base-execute 127 - ;
```
[Try it online!](https://tio.run/##S8svKsnQTU8DUf//WykkKaQU5RcoGGorWChEq8cqpJYl5pQmlqQqGCkkJRan6qZWpCaXArmGRuYKugrW/4uVFAwMDIEARIBYGNhQCWio3n8A "Forth (gforth) – Try It Online")
Done using (a lot of) Bubbler's help.
Forth has one(1) convenient command that allows interpretation of strings as binary, and that's used here(`base-execute`).
[Answer]
# [Rust](https://www.rust-lang.org/), 43 bytes
```
|s|Ok(i32::from_str_radix(&s[1..9],2)?-127)
```
[Try it online!](https://tio.run/##ZYyxCsIwFEV3vyJ2kATaklRBjFonByfFVaQEmkCxTfG9FATrt9fE4qIP3uUO9xzo0A3GkkZVlrInqbUjRhpLZ@iAJflZY1e7TTXPYnSllLZrpDwpQH2wbg/QQk62Q4/98Ub9SEoDbVN4tgBVVg@vuYg0XV3jjO0SkS3ZsJ4oRA2u0PcpNTTiXPgLEdrfi4jF3p0sGPslP5D40j5GCQ8lxEjyAL6GNw "Rust – Try It Online")
Returns a `Result<i32,ParseIntError>`. I would have loved to use an `i8` instead of an `i32` but that would panic if the leading bit is 1.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~174~~ ~~113~~ 111 bytes
-61 bytes for many optimizations
-2 bytes thanks to RezNesX
```
,>++++++++>>--[>-<--]>-<<<[>,>>>[--<+>]<[->+<]<-[<->-----]<+++[->>>[->+>+<<]>>[-<<+>>]<<<<<]<-]>>>>---[>-<--]>.
```
[Try it online!](https://tio.run/##ZYxBCoRQDEMP9H8G3YdcpHQxCoIILgTP/yeFwY2BhpK@Zrm@@7nd6zFGV/tLAkIgkHYy1CUFwKZkQI1JBGHOSvrHaSFqPjJrpWnjJdOOqvbp/YwxTbNVVttr5h8 "brainfuck – Try It Online")
Input is 32 bits taken one at a time.
Explanation:
```
,> first bit garbage
++++++++ set cur cell (cell 2) to 8
>>--[>-<--]>-<<< set cell 5 to 128 (so the first division moves it over)
[> do 8 times
, input to cell 3
>>> cell 6
[--<+>] div 2 to 5
<[->+<] move back to 6
< cell 4
-[<->-----]<+++ convert to bin value (sub 48) using cell 4
[- if 1 (in cell 3)
>>>[->+>+<<] add cell 6 into cell 7 & 8
>>[-<<+>>] move cell 8 back to 6
<<<<<
]
<-] ends on c2
>>>> to c6 (has 1 and next cell has value)
---[>-<--]> sub 127
. outputs final answer (as ASCII= if this is invalid let me know)
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~11~~ 6 bytes
```
9ŻB⁺ɽ-
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=9%C5%BBB%E2%81%BA%C9%BD-&inputs=00111101110011001100110011001101&header=&footer=)
I've got an advantage that y'all don't have: I actually sat the exam this question is based upon as well at the same time as the OP (#hsc\_gang #option\_topic\_2 #ir\_sw\_hw). Hopefully I got both that question and this answer right!
## Explained
```
9ŻB⁺ɽ-
9Ż # input[1:9]
B # int( , 2)
⁺ɽ # 127 (N.B. Pushes the index of ɽ in the codepage + 101)
- # -
# int(input[1:9], 2) - 127
```
**Update**: Turns out I got the wrong answer in the exam. Not pog.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
Ḋḣ8Ḅ_127
```
[Try it online!](https://tio.run/##y0rNyan8///hjq6HOxZbPNzREm9oZP7//38DHQMdQyg0gNMGRNKGAA "Jelly – Try It Online")
Takes input as a list of digits
## How it works
```
Ḋḣ8Ḅ_127 - Main link. Takes a list of bits B on the left
Ḋ - Dequeue; Remove the first element of B
ḣ8 - Take the first 8 elements
Ḅ - Convert from binary
_127 - Subtract 127
```
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 11 bytes
```
-127+2/8#1_
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NStfQyFzbSN9C2TD@f5qCARAaQqEBnDYgkjb8DwA "K (ngn/k) – Try It Online")
```
1_ drop one
8# take 8
2/ to binary
-127+ subtract 127
```
# [K (ngn/k)](https://bitbucket.org/ngn/k), 14 bytes
Just an experiment - a port of [Lynn's Haskell answer](https://codegolf.stackexchange.com/a/214774/75681)
```
{y-1+2*x}/8#1_
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqrpS11DbSKuiVt9C2TD@f5qCARAaQqEBnDYgkjb8DwA "K (ngn/k) – Try It Online")
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 31 bytes
```
[[email protected]](/cdn-cgi/l/email-protection)~'$$<
_1->\2*~2%+\#^:!
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@vUzEvc9DTNdStU1dRseGKN9S1izHSqjNS1Y5RjrNS/P/fwMAQCEAEiIWBDQE "Befunge-98 (PyFunge) – Try It Online")
---
### Animation
[](https://i.stack.imgur.com/whCvt.gif)
### Explanation
`~$7v` is the initialization code:
`~$` read and discard the first character
`7` push initial value of the loop counter
`v` redirect the instruction pointer down
The second line is the main loop, since `>` is the entry point it is executed as `\2*~2%+\#^:!_1-` from left to right. Initially the loop counter is on top of the stack and the current result on the second position:
`\` swap to the current exponent value
`2*` double it
`~` read the next digits
`2%` modulo `2` maps `'0'` to `0` and `'1'` to `1`
`+` add to the current result
`\` swap to the loop counter
`#` skips the the command (`^`)
`:!` duplicate the loop counter and boolean negate the copy
If the value on the top of the stack is now falsey (loop counter was `>0`), `_` lets the IP move east and the main loop continues by subtracing `1` from the loop counter (`1-`). Otherwise the IP moves west and executes the following:
```
@.-1-~'$$<
_ ^:!
```
By removing the IP movement commands and writing everything from left to right, this results in `!:$$'~-1-.@`:
`!` invert the loop counter again
`:$$` duplicate the value and pop both copies
`'~-` subtract `'~' = 126`
`1-.` subract `1` and print
`@` terminate the program
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 27 bytes
```
/.(.{8})/;$_=-127+oct"0b$1"
```
[Try it online!](https://tio.run/##K0gtyjH9/19fT0Ov2qJWU99aJd5W19DIXDs/uUTJIEnFUOn/fwMDQyAAESAWBjbkAssZwhQBCYhaAxADRPzLLyjJzM8r/q@bUwAA "Perl 5 – Try It Online")
[Answer]
# [Nim](http://nim-lang.org/), 58 bytes
```
import strutils
echo stdin.readAll[1..8].fromBin[:int]-127
```
[Try it online!](https://tio.run/##y8vM/f8/M7cgv6hEobikqLQkM6eYKzU5Ix/IS8nM0ytKTUxxzMmJNtTTs4jVSyvKz3XKzIu2yswridU1NDL//9/AwBAIQASIhYENAQ "Nim – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
I⁻⍘Φ…S⁹겦¹²⁷
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczr7RYwymxODW4BCiaruGWmVOSWqThXJmck@qckV@g4ZlXUFoCldTUUbAE4mwgNgJiQyNzTU1N6///DQwMgQBEgFgY2PC/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
… ⁹ Take first 9 characters
Φ κ Remove first character
⍘ ² Convert from base 2
⁻ ¹²⁷ Subtract 127
I Cast to string
Implicitly print
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 13 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
[]9@j{┤]2┴‾p-
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjNCJXVGRjNEJXVGRjE5JXVGRjIwJXVGRjRBJXVGRjVCJXUyNTI0JXVGRjNEJXVGRjEyJXUyNTM0JXUyMDNFcCV1RkYwRA__,i=JTIyMDAxMTExMDExMTAwMTEwMDExMDAxMTAwMTEwMDExMDElMjI_,v=8)
## Explanation
```
[]9@j{⊣]2⊥¯p⊣-
[] get all prefixes
9@ 9th prefix
j remove first element
{⊣] cast each element to integer
2⊥ decode from base 2
¯p 127
- subtract that from it
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~26~~ 24 bytes
```
x=>'0b'+x.slice(1,9)-127
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1k7dIEldu0KvOCczOVXDUMdSU9fQyPx/cn5ecX5Oql5OfrpGmoa6gYEhEIAIEAsDG6prav4HAA "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
[The Möbius function](https://en.wikipedia.org/wiki/M%C3%B6bius_function) is an important number theoretic function.
Your submission should accept a positive integer \$n\$ and return the value of the Möbius function evaluated at \$n\$.
### Definition
The Möbius function \$μ(n)\$ is defined as follows:
$$\mu(n) = \begin{cases}
\hphantom{-}1, &n\text{ is squarefree and has an even number of distinct prime factors} \\
-1, &n\text{ squarefree and has an odd number of distinct prime factors} \\
\hphantom{-}0, &\text{otherwise}
\end{cases}$$
\$n\$ is called *squarefree* if the exponents of the prime factorization of \$n\$ are all strictly less that two. (Alternatively: No prime to the power of two divides \$n\$).
### Test cases
Here you can see the first 50 values of μ:

Public Domain Image from Wikipedia
The Möbius function is sequence number [A008683](https://oeis.org/A008683) in the OEIS.
These are the first 77 values:
```
1, -1, -1, 0, -1, 1, -1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1, 0, -1, 0, 1, 1, -1, 0, 0, 1, 0, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, 1, 1, 0, -1, -1, -1, 0, 0, 1, -1, 0, 0, 0, 1, 0, -1, 0, 1, 0, 1, 1, -1, 0, -1, 1, 0, 0, 1, -1, -1, 0, 1, -1, -1, 0, -1, 1, 0, 0, 1
```
Larger values can also easily be checked [in Wolframalpha.com](http://www.wolframalpha.com/input/?i=MoebiusMu+123) or in the [b-file of OEIS](https://oeis.org/A008683/b008683.txt), as suggested by @MartinBüttner.
[Answer]
## Python 2, 48 bytes
```
m=lambda n,d=1:d%n and-m(d,n%d<1)+m(n,d+1)or 1/n
```
Earlier 51 byte version:
```
m=lambda n:1/n-sum(m(k)for k in range(1,n)if n%k<1)
```
[Möbius-inverts](https://en.wikipedia.org/wiki/M%C3%B6bius_inversion_formula) the sequence `1,0,0,0,0...`.
The Möbius function has the property that for any `n>1`, the Möbius functions of `n`'s divisors sum to 0. So, for `n>1`, `μ(n)` is computed by negating the sum of `μ(k)` for all proper divisors `k` of `n`. For `n=1`, the output is `1`.
The code handles the base case by adding a floor-division `1/n`, which gives `1` for `n==1` and `0` otherwise.
Thanks to Dennis for saving 3 bytes with better recursive handling inspired by a similar structure in [this challenge](https://codegolf.stackexchange.com/a/83636/20260).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
Code:
```
ÆF>1’PS
```
Explanation:
```
ÆF # This computes the prime factorization as well as the exponent
>1 # Compares each element if it's greater than 1, resulting in 1's and 0's
’ # Decrement on each element
P # Compute the product
S # Compute the sum of the list
```
For example, the number **10**:
```
ÆF # [[2, 1], [5, 1]]
>1 # [[1, 0], [1, 0]]
’ # [[0, -1], [0, -1]]
P # [0, 1]
S # 1
```
And results in **1**.
[Try it online](http://jelly.tryitonline.net/#code=w4ZGPjHigJlQUw&input=&args=MTA).
[Answer]
## Mathematica, 9 bytes
```
MoebiusMu
```
Of course, Mathematica has a built-in. (And ~~will probably be~~ is beaten by Jelly anyway.)
[Answer]
## CJam, ~~18~~ 15 bytes
```
WrimFz~\1&+f/:*
```
The fact that CJam returns 1 in factorisation builtins for `n = 1` makes things a bit tricky.
[Try it online](http://cjam.aditsu.net/#code=WrimFz~%5C1%26%2Bf%2F%3A*&input=1) | [Test suite](http://cjam.aditsu.net/#code=20%7B%29%0A%0AW%5CmFz~%5C1%26%2Bf%2F%3A*%0A%0A%7D%25p)
Thanks to @PeterTaylor for the neat `1&+` trick for handling the 1 case.
## Explanation
```
W Push -1
ri Push input as int
mF Factorise input into [base exponent] pairs
z~ Zip and unwrap pairs, leaving stack like [-1 bases exponents]
\1& Setwise intersect bases with 1, giving [1] for 1 and [] otherwise
+ Append to exponent array
f/ Divide the previously pushed -1 by each element in the array
This gives -1 for 1s and 0 otherwise, since / is int division
:* Take product
```
For `n > 1`, the modified array is just the exponents array. If `n` is squarefree then the array is all 1s, which become all -1s after division. Otherwise, if n has a prime square divisor, then there will be a 0 somewhere after division, giving a product of 0.
For `n = 1` the modified array is `[1] + [1]`, which becomes `[-1 -1]` after division, giving a product of 1.
---
Alternative 16:
```
rimF{1#2+3%(}%:*
```
This uses `#` (find) on each `[base exponent]` array to look for a 1, then maps `-1 -> 0, 0 -> 1, 1 -> -1`.
[Answer]
## Ruby, ~~65+7=72~~ 62+7=69 bytes
```
->x{((d=x.prime_division).all?{|_,n|n<2}?1:0)*(d.size%2*-2+1)}
```
+7 bytes for the `-rprime` flag.
We're doing this the very naïve way:
```
->x{
(
(d=x.prime_division) # ex. input 20 results in [[2,2],[5,1]] here
.all?{|_,n|n<2}? # are all factors' exponents under 2?
1:0 # if so, result in a 1; otherwise, a 0
)
* # multiply that 1 or 0 by...
(d.size%2*-2+1) # magic
}
```
The "magic" part results in 1 if the number is even and -1 otherwise. Here's how:
```
Expression Even Odd
--------------------------
d.size%2 0 1
d.size%2*-2 0 -2
d.size%2*-2+1 1 -1
```
[Answer]
## [Labyrinth](https://github.com/mbuettner/labyrinth), 87 bytes
```
1
:
}
? @ "}){/{=:
""({! " ;
} ) :}}:={%"
* _}}){ ;
{ #}):{{
")`%#/{+
```
[Try it online!](http://labyrinth.tryitonline.net/#code=MQo6Cn0KPyAgIEAgIn0pey97PToKIiIoeyEgIiAgICAgIDsKfSApICAgOn19Oj17JSIKKiBffX0peyAgICAgOwp7ICAgICAgI30pOnt7CiIpYCUjL3sr&input=MTE)
### Short explanation
Here's a port of the algorithm used, in Python:
```
divisor = 1
mobius = 1
n = int(input())
while n != 1:
divisor += 1
count = 0
while n % divisor == 0:
n //= divisor
count += 1
mobius *= (count + 3)//(count + 1)%3*-1 + 1
print(mobius)
```
### Long explanation
The usual primer on Labyrinth:
* Labyrinth is stack-based and two-dimensional, with execution starting at the first recognised character. There are two stacks, a main stack and an auxiliary stack, but most operators only work on the main stack.
* At every branch of the labyrinth, the top of the stack is checked to determine where to go next. Negative is turn left, zero is straight ahead and positive is turn right.
Execution for this program starts at the top-left `1`.
```
Outer preparation
=================
1 Pop 0 (stack is bottomless and filled with 0s) and push 0*10+1 = 1
:} Duplicate and shift to auxiliary stack
? Read int from input
Stack is now [div=1 n | mob=1]
Top of stack positive but can't turn right. Turn left into outer loop.
Begin outer loop
================
Inner preparation
-----------------
( Decrement top of stack
If top was 1 (and is now zero), move forward and do...
------------------------------------------------------
{! Print mob
@ Terminate
If top of stack was greater than 1, turn right and do...
--------------------------------------------------------
) Increment n back to its previous value
_} Push 0 and shift to aux
This will count the number of times n can be divided by div
}){ Increment div
Stack is now [div n | count mob]
Inner loop
----------
:}} Dup n, shift both n's to aux
:= Dup div and swap top of main with top of aux
{% Shift div down and take mod
Stack is now [div n%div | n count mob]
If n%div == 0, move forward and do...
-----------------------------------
; Pop n%div
:={/ Turn n into n/div
{)} Increment count
(continue inner loop)
If n%div != 0, turn right (breaking out of inner loop) and do...
================================================================
; Pop n%div
{{ Pull n and count from aux
:)} Dup and increment count, giving (count+1), and shift to aux
#+ Add length of stack to count, giving (count+3)
{/ Calculate (count+3)/(count+1)
#% Mod by length of stack, giving (count+3)/(count+1)%3
` Multiply by -1
) Increment, giving (count+3)/(count+1)%3*-1 + 1
This is 1 if count was 0, -1 if count was 1 and 0 if count > 1
{*} Multiply mob by this number
(continue outer loop)
```
[Answer]
## Pyth, 9 bytes
```
^_{IPQlPQ
```
Explanation:
```
^_{IPQlPQ Implicit: Q=input
PQ Prime factorization of Q
{I Is invariant under uniquify.
{IPQ 1 if Q is squarefree; 0 otherwise.
_{IPQ -1 if Q is squarefree; 0 otherwise.
^ lPQ Exponentiation to length of PQ.
```
Try it [here](https://pyth.herokuapp.com/?code=%5E_%7BIPQlPQ&input=14&test_suite=1&test_suite_input=1%0A5%0A10%0A15%0A20&debug=1).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
Code:
```
.p0K1›<P
```
Explanation:
```
.p # Get the prime factorization exponents
0K # Remove all zeroes from the list
1› # Compare each element if greater than 1
< # Decrement on each element
P # Take the product
```
Uses the CP-1252 encoding
[Answer]
# Java 8, ~~72~~ ~~68~~ ~~65~~ 64 bytes
```
n->{int r=1,i=1;for(;i++<n;)r=n%i<1?(n/=i)%i<1?0:-r:r;return r;}
```
-4 bytes thanks to *@PeterTaylor*.
Port of [@Meerkat's .NET C# answer](https://codegolf.stackexchange.com/a/174900/52210), which I first golfed a bit further, so make sure to upvote him!
[Try it online.](https://tio.run/##LY7PDoIwDMbvPEVDYrJlgnIwJo7pE@iFo/EwEUz9U0wZJobw7Lihly/t1/bX72bfNrld7mP5sG0Le4vURwBIruLalhUcQjsZUIqgJLV3hshL66zDEg5AYGCkZNuHBTbZHE2m64aFRqVy0pINzTDPdoIWBuVULjcJb1hz5TomYD2MOjBf3fnhmX/0u8ELPH0oUThGuh5PYOUvUcCHd@EVYL5eeVVKTjOA4tO66pk2nUtf/tAJSn18qeJ5/M8/jF8)
**Explanation:**
```
n->{ // Method with integer as both parameter and return-type
int r=1, // Result-integer, starting at 1
i=1;for(;i++<n;) // Loop `i` in the range [1, n]:
r=n%i<1? // If `n` is divisible by `i`:
(n/=i) // Divide `n` by `i` first
%i<1? // And if `n` is still divisible by `i`:
0 // Change `r` to 0
: // Else:
-r // Swap the sign of `r` (positive to negative or vice-versa)
: // Else:
r; // Leave `r` unchanged
return r;} // Return `r` as result
```
[Answer]
## CJam, 20 bytes
```
rimf1-___&=\,2%!2*(*
```
[Run it against a range of inputs here.](http://cjam.aditsu.net/#code=20%7B)%0A%0Amf1-___%26%3D%5C%2C2%25!2*(*%0A%0Ap%7D%2F)
Seems golfable.
[Answer]
# R ~~39~~16 bytes
```
numbers::moebius
```
Requires you having the [numbers](https://cran.r-project.org/web/packages/numbers/index.html) package installed on your system...
Edit: Far simpler if I read the specs appropriately [thanks @AlexA.]
[Answer]
# [Factor](https://factorcode.org) + `math.extras`, 6 bytes
```
mobius
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70sLTG5JL9owU3H0GBPP3crhdzEkgy91IqSosRiCLsoMS89tVihOLWwNDUvGcgqKEotKaksKMrMK1Gw5jI3UIg21EmKVYheWlqSpmuxLDc_KbO0GMJZHgs0o0BBD8JbsABCAwA)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 16 Bytes
```
?nl{PQlPQZ^_1lPQ
```
[Try it online!](http://pyth.herokuapp.com/?code=%3Fnl%7BPQlPQZ%5E_1lPQ&debug=0)
My first actual Pyth answer. Suggestions appreciated! :)
## Explanation
My solution uses the fact that a number is squarefree, if its prime-factors contain no number more than once. If the input is squarefree, the Möbius-Function takes the value -1^(number of primefactors).
```
?n if not equal
l{PQ length of the list of the distinct input-Primefactors
lPQ length of the list of primefactors including duplicates
Z Input is not squarefree, so output Zero
^_1lPQ if input is squarefree, output -1^(number of prime-factors)
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 15 ~~17~~ bytes
```
tq?YftdAwn-1w^*
```
This uses [current release (10.1.0)](https://github.com/lmendo/MATL/releases/tag/10.1.0) of the language/compiler.
[**Try it online!**](http://matl.tryitonline.net/#code=dHE_WWZ0ZEF3bjJcLTIqUSo&input=MTA)
### Explanation
```
t % implicit input. Duplicate that
q % decrement by 1. Gives truthy (nonzero) if input exceeds 1
? % if input exceeds 1, compute function. Otherwise leave 1 on the stack
Yf % vector of prime factors. Results are sorted and possibly repeated
td % duplicate and compute differences
A % true if all differences are nonzero
w % swap
n % number of elements in vector of prime factors, "x"
-1w^ % -1^x: gives -1 if x odd, 1 if x even
* % multiply by previously obtained true/false value, so non-square-free gives 0
% implicitly end "if"
% implicitly display stack contents
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 86 73 72 65 bytes
```
a=>{int b=1,i=1;for(;++i<=a;)b=a%i<1?(a/=i)%i<1?0:-b:b;return b;}
```
[Try it online!](https://tio.run/##NYzLCsIwFET3/Yq7ERL60OpCbJqKCIKgGxVcJ2kqF2oCSVqQ0m@vRXBg4BwGRvlUWaenzqN5wf3jg34zUK3wHg4wRD6IgApOnVElmpDMraDhk@DVMDNInifIc9ZYR1gcY8kFo5KLBZb5noglR/rDVZHKQjKnQ@cMSDZO7P/dW6zhKtAQOkQAcLTG21ZnT4dBk4bM3msXsoc9m7BZk/9@06K@oNGEzmHROE677Rc "C# (.NET Core) – Try It Online")
*-13 bytes: streamlined loops, added return variable (thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/questions/69993/the-m%C3%B6bius-function/174900?noredirect=1#comment421566_174900))*
*-1 byte: changed setting b to zero to a ternary from an if (thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/questions/69993/the-m%C3%B6bius-function/174900?noredirect=1#comment421571_174900))*
*-7 bytes: changed if statement in for loop to a ternary (thanks to [Peter Taylor](https://codegolf.stackexchange.com/questions/69993/the-m%C3%B6bius-function/174900?noredirect=1#comment421625_174900) and [Kevin Cruijssen](https://codegolf.stackexchange.com/questions/69993/the-m%C3%B6bius-function/174900?noredirect=1#comment421632_174900))*
Ungolfed:
```
a => {
int b = 1, i = 1; // initialize b and i to 1
for(; ++i <= a;) // loop from 2 (first prime) to a
b = a % i < 1 ? // ternary: if a is divisible by i
((a /= i) % i < 1 ? 0 : -b) : // if true: set b to 0 if a is divisible by i squared, otherwise flip sign of b
b; // if false: don't change b
return b; // return b (positive for even numbers of primes, negative for odd, zero for squares)
}
```
[Answer]
# Pyth, 11
```
*{IPQ^_1lPQ
```
[Test suite](https://pyth.herokuapp.com/?code=%2a%7BIPQ%5E_1lPQ&input=10&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10&debug=0)
This multiplies the boolean value of if the prime factors are squarefree by `-1` to the power of the number of prime factors that the number has.
`I` is an invariance check on the preceeding operator, which here is `{`, which is the unique-ify operator.
[Answer]
# Japt, 21 bytes
```
V=Uk)¬¥Vâ ¬?Vl v ªJ:0
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=Vj1VaymspVbiIKw/VmwgdiCqSjow&input=NQ==)
[Answer]
# Julia, 66 bytes
```
n->(f=factor(n);any([values(f)...].>1)?0:length(keys(f))%2>0?-1:1)
```
This is a lambda function that accepts an integer and returns an integer. To call it, assign it to a variable.
Ungolfed:
```
function µ(n::Int)
# Get the prime factorization of n as a Dict with keys as primes
# and values as exponents
f = factor(n)
# Return 0 for non-squarefree, otherwise check the length of the list
# of primes
any([values(f)...] .> 1) ? 0 : length(keys(f)) % 2 > 0 ? -1 : 1
end
```
[Answer]
# PARI/GP, 7 bytes
```
moebius
```
Sadly `möbius` is not available. :)
[Answer]
## Seriously, ~~19~~ 18 bytes
```
,w;`iX1=`Mπ)l1&τD*
```
[Try it online!](http://seriously.tryitonline.net/#code=LHc7YGlYMT1gTc-AKWwxJs-ERCo&input=NA)
Explanation:
```
,w;`iXDY`Mπ)l1&τD*
,w; push two copies of the full prime factorization of the input
(a list of [base, exponent] pairs)
` `M map the following function:
iX1= flatten list, discard, equal to 1
(push 1 if exponent == 1 else 0)
π) product of list, push to bottom of stack
1& push 1 if the # of prime factors is even else 0
τD double and decrement (transform [0,1] to [-1,1])
* multiply
```
[Answer]
# Julia, 35 bytes
```
\(n,k=1)=k%n>0?n\-~k-k\0^(n%k):1÷n
```
Based on [@xnor's Python answer](https://codegolf.stackexchange.com/a/70024). [Try it online!](http://julia.tryitonline.net/#code=XChuLGs9MSk9ayVuPjA_blwtfmsta1wwXihuJWspOjHDt24KCmZvciBuIGluIDE6NzcKICAgIEBwcmludGYoIiUyZCAtPiAlMmRcbiIsIG4sIFwobikpCmVuZA&input=)
[Answer]
# Seriously, 11 bytes
Golfing suggestions welcome. [Try it online!](http://seriously.tryitonline.net/#code=O3k7bDB-4oG_Kc-APSo&input=MjMxMA)
```
;y;l0~ⁿ)π=*
```
**Ungolfing**
```
Implicit input n.
; Duplicate n.
y Push a list of the distinct prime factors of n. Call it dpf.
; Duplicate dpf.
l Push len(dpf).
0~ Push -1.
ⁿ Push (-1)**len(dpf).
) Rotate (-1)**len(dpf) to BOS. Stack: dpf, n, (-1)**len(dpf)
π Push product(dpf).
= Check if product(dpf) == n.
This is only true if n is squarefree.
* Multiply (n is squarefree) by (-1)**len(dpf).
Implicit return.
```
[Answer]
# GNU sed, 89 bytes
```
#!/bin/sed -rf
s/.*/factor &/e
s/.*://
/\b([0-9]+) \1\b/!{
s/[0-9]+//g
s/$/1/
s/ //g
y/ /-/
}
s/ .*/0/
```
[Answer]
# J, 18 bytes
```
[:*/3<:@|2+2<._&q:
```
[Answer]
## Microsoft Office Excel, British version, 196 bytes
```
=IF(ROW()>=COLUMN(),IF(AND(ROW()=1,COLUMN()=1),1,IF(COLUMN()=1,
-SUM(INDIRECT(ADDRESS(ROW(),2)&":"&ADDRESS(ROW(),ROW()))),
IF(MOD(ROW(),COLUMN())=0,INDIRECT(ADDRESS(FLOOR(ROW()/COLUMN(),1),
1)),""))),"")
```
Excel cell formula to be entered in cells A1 to AX50.
[Answer]
## Javascript (ES6), 48 bytes
```
f=(n,i=1)=>n-1?n%++i?f(n,i):(n/=i)%i?-f(n,i):0:1
```
First of all - this is my first code golf post so I may misunderstand the rules to some extent. In this submission the last character `;` could be omitted and it'll still work but I'm not even sure if the code would be valid according to the ES6 specs. Anyways, a short explanation.
First, I'll explain the idea a bit; we take `n`, and we try dividing it by the integer `i`. If it's divisible, then we do so and we check if it's divisible by `i` again. If that's the case, then we need to return `0`. Otherwise, we can try another `i`. The cool thing is, we can just start at `i=2` and just add increase it by `1` every time, so that we divide out all the prime factors.
So, the code works like this:
```
f=(n,i=1)=> We will increase i by one at the start of
the function body, so default is 1
n-1? Check if n==1.
n%++i? If i isn't, increase i by 1, check if n
is divisible by i
f(n,i): if it isn't, we check the next i
(n/=i)%i? if it is, divide n by i, and check for
divisibility by i again
-f(n,i): if it not, then we flip the value to
account for the 1 and -1 depending on the
amount of factors
0: if it's divisible by i twice, done.
1 if we're at 1, divided out all factors,
then we return 1. The line with
-f(n,i) will then take care of the sign
```
So, that's my submission.
[Answer]
# [Haskell](https://www.haskell.org/), 96 bytes
```
import Data.Numbers.Primes
import Data.List
m=(\f->last$0:[(-1)^length f|f==nub f]).primeFactors
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRz680Nym1qFgvoCgzN7WYC1nKJ7O4hCvXViMmTdcuJ7G4RMXAKlpD11AzLic1L70kQyGtJs3WNq80SSEtVlOvAKTfLTG5JL@o@H9uYmaeLVAkr0QlV8HQ6D8A "Haskell – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 47 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 5.875 bytes
```
ǐÞu$†Ǎ*
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyI9IiwiIiwix5DDnnUk4oCgx40qIiwiIiwiNzciXQ==)
What do you mean it's not morbin' time? I love vyncode and how just re-arranging things makes the program shorter.
## Explained
```
ǐÞu$†Ǎ*
ǐ # prime factors of input with duplicates
Þu # all unique?
$†Ǎ # -1 ** len(prime_factors(input))
* # multiply
```
] |
[Question]
[
Your task today is to apply a wave to an array of numbers. A wave looks like this: `[1, 0, -1, 0, 1, 0, -1, 0, 1...]` Applying it to a given array means adding together the first elements, the second elements, etc.
More precisely:
Your program or function will receive an array of integers. It must print or return an equally sized array with `1` added to the 1st, 5th, 9th, etc. element of the original array, `-1` added to the 3rd, 7th, 11th, etc. element of the original array, and the rest of the elements should be left untouched.
The input array is guaranteed to have at least one element.
Test cases:
```
Input | Output
[0] | [1]
[-1] | [0]
[-4, 3, 0, 1, 7, 9, 8, -2, 11, -88] | [-3, 3, -1, 1, 8, 9, 7, -2, 12, -88]
[0, 0, 0, 0, 0] | [1 ,0 ,-1 ,0 ,1]
[1, 1] | [2, 1]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins!
[Answer]
# [LOGO](https://sourceforge.net/projects/fmslogo/), 18 bytes
```
[map[?+sin 90*#]?]
```
There is no "Try it online!" link because all online LOGO interpreter does not support template-list.
That is a template-list (equivalent of lambda function in other languages).
Usage:
```
pr invoke [map[?+sin 90*#]?] [-4 3 0 1 7 9 8 -2 11 -88]
```
(`invoke` calls the function, `pr` prints the result)
prints `[-3 3 -1 1 8 9 7 -2 12 -88]`.
Explanation (already pretty understandable):
```
map[?+sin 90*#]? map a function over all the items of the input
# the 1-based index of the element in the input
sin 90*# equal to the required wave
? looping variable
?+sin 90*# add the wave to the input
```
[Answer]
# [Haskell](https://www.haskell.org/), 26 bytes
```
zipWith(+)$cycle[1,0,-1,0]
```
[Try it online!](https://tio.run/##LYpNCsIwGESvMosulE4gsQXjoufoImQR@kODaQ3aTb18/BRheDDzZgmv@5RSKXP3jrmP@3Kqz9VwDGlyhppK4Msa4oYO4wP5GbcdFdaQMcM57emU@aIlGkIThrgSN8IS6iJdBmWtfPTP/yNdhPG@fAA "Haskell – Try It Online") (runs all test cases)
Explanation:
```
zipWith(+)$cycle[1,0,-1,0] -- anonymous tacit function
zipWith(+) -- pairwise addition between input list
$cycle[1,0,-1,0] -- and an infinitely-cycling "wave" list
```
[Answer]
## JavaScript (ES6), 28 bytes
```
a=>a.map((x,i)=>x-(i%4-1)%2)
```
The calculation goes like this:
```
i%4 -1 %2
0 -1 -1
1 0 0
2 1 1
3 2 0
```
The last bit taking advantage of the fact that in JS, a negative number when modulated will retain its negative sign (i.e. `-5 % 3 -> -2`, instead of `1` as it would be in Python).
[Answer]
# Mathematica, ~~26~~ ~~23~~ 22 bytes
```
Im[I^Range@Tr[1^#]]+#&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvvfMzfaMy4oMS891cEnNS@9JMNBOVZbWe1/QFFmXolDmkO1romOgrGOgoGOgqGOgrmOgqWOgoWOgq4RkA8U0LWwqP0PAA "Mathics – Try It Online") (Mathics)
Note: The TIO link is for the 23-byte version, the 22-byte version is not Mathics-compatible.
[Answer]
# [Python 2](https://docs.python.org/2/), 40 bytes
```
i=2
for x in input():print~-x+i%5%3;i*=2
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9PWiCstv0ihQiEzD4gKSks0NK0KijLzSup0K7QzVU1Vja0ztWyBKqN1TXQUjHUUDHQUDHUUzHUULHUULHQUdI2AfKCAroVFLAA "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Jı*Ċ+
```
[Try it online!](https://tio.run/##y0rNyan8/9/ryEatI13a////j9Y10VEw1lEw0FEw1FEw11Gw1FGw0FHQNQLygQK6FhaxAA "Jelly – Try It Online")
### How it works
```
Jı*Ċ+ Main link. Argument: A (array)
J Indices; yield [1, ..., len(A)].
ı* Elevate the imaginary unit to the power 1, ..., len(A), yielding
[0+1i, -1+0i, 0-1i, 1+0i, ...].
Ċ Take the imaginary part of each result.
+ Add the results to the corresponding elements of A.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~11~~ 8 bytes
```
Jyn:^Yj+
```
Try it at [**MATL Online!**](https://matl.io/?code=Jyn%3A%5EYj%2B&inputs=%5B-4%2C+3%2C+0%2C+1%2C+7%2C+9%2C+8%2C+-2%2C+11%2C+-88%5D&version=20.2.2)
### Explanation
```
J % Push 1j (imaginary unit)
% STACK; 1j
y % Implicit input. Duplicate from below
% STACK: [-4 3 0 1 7 9 8 -2 11 -88], 1j, [-4 3 0 1 7 9 8 -2 11 -88]
n % Number of elements
% STACK: [-4 3 0 1 7 9 8 -2 11 -88], 1j, 10
: % Range
% STACK: [-4 3 0 1 7 9 8 -2 11 -88], 1j, [1 2 3 4 5 6 7 8 9 10]
^ % Power, element-wise
% STACK: [-4 3 0 1 7 9 8 -2 11 -88], [1j -1 -1j 1 1j -1 -1j 1 1j -1]
Yj % Imaginary part
% STACK: [-4 3 0 1 7 9 8 -2 11 -88], [1 0 -1 0 1 0 -1 0 1 0]
+ % Add, element-wise. Implicit display
% STACK: [-3 3 -1 1 8 9 7 -2 12 -88]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
-1Jm2$$¦+2Jm4$$¦
```
[Try it online!](https://tio.run/##y0rNyan8/1/X0CvXSEXl0DJtI69cExDj////0QY6UBgLAA "Jelly – Try It Online")
heh I'm sure this is too long
# Edit
I know a 5 byte solution is possible but my wifi appears to be starting to cut me off so I'll golf this tomorrow. If someone posts the short Jelly solution before I can golf this, that's fine with me; I'll just keep this here for reference as to ~~how bad I am at Jelly lol~~ another way of doing it. I mean, I *could* just look at the link Phoenix posted in the comments, but since I'm still learning, I don't want to look at the solution until I've figured it out myself. This might cost me reputation but the learning is what I'm here for :)))
[Answer]
# [R](https://www.r-project.org/), ~~29~~ 24 bytes
```
(l=scan())+Im(1i^seq(l))
```
[Try it online!](https://tio.run/##K/r/XyPHtjg5MU9DU1PbM1fDMDOuOLVQI0dT87@hgpGCsYKJgqmCmYK5goWCpYKhwX8A)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~50~~ 42 bytes
Saved 8 bytes thanks to @Sisyphus!
```
lambda l:map(sum,zip(l,[1,0,-1,0]*len(l)))
```
[Try it online!](https://tio.run/##jZJRa4MwEMff/RT3ljguRdtBneBgL4PBHvZug7g20kBMxMTBtu6zd0m0DAajEzHJ/373v/PI8O6ORq/P3Wh6aJpuctMomgZkP5jRwTBK7byq904anXTV7qza/vXQgir7dqB26vFDDlRhnWOGzH/4jRKaqjRNz05YZ6ECQkhSZxyuPSeoc57ULOf/ILNA3iJsEDKEHGGLcIdQILC1P3uBFQUPJNtEyjcXsCJi2wVbz5hvL9osL/@zPcAM/G/GJfQaPPnVXkMlnoQxJJ0ZQUktQGqI81nZQUlHyU6TtExCQgxXcbkETySNIdmBNi6G/ABK2BvtpJ7EnHcMwxZvraILMCeNv/T8oougd9TnzcLQWhs18uJ3JQnlIlRFD6GsAPL48PRckpkPt4POWRjKIxDG7gkupv4YPS6@P8azVQn2aCZ1gFcBn19k5WfTt476Wv7yfAM "Python 2 – Try It Online")
### 53 bytes
```
lambda l:[int(x+(1j**i).real)for i,x in enumerate(l)]
```
[Try it online!](https://tio.run/##jZJRS8MwFIXf@yvuW5KZjHYTVgsVfBEEH3zv8tC5lEWydDSZTJy/veYmHYIgsxTSnPvdcy@HHj78rrfLsavXo2n3m20Lpmq09fR0Q4u32Uyz@aBaw7p@AM1PoC0oe9yrofWKGiZHr5x3UAMhJGtyCdeeMzSFzBpRyH@QOZK3HJYccg4FhxWHOw4lB7EI9yCIspRIimWkRBGxMmKrCVskLKwXbaZX/rke8By4SAfuip7y6q44SWYYQ4ZhGW0VphXzmbuD0Z6StSWsyrAhlut4XIpnwmJJd2B7H0shgApee@u1ParUt8Ow1Xtr6ASkpuGXXlx0hXpHQ18SDq1zUSMv4asiOC5CdfRQxikgjw9PzxVJ/IB/Q@riOJ4DEeKe8Mk0XKPHxffHOFlV4Hb90Wxho@Dzi8xDNvvW0zCLsfEb)
[Answer]
# [Haskell](https://www.haskell.org/), 26 bytes
*@Mego beat me to this solution*
```
zipWith(+)$cycle[1,0,-1,0]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P822KrMgPLMkQ0NbUyW5MjknNdpQx0BHF0jE/s9NzMyzLSjKzCtRSQMKG@kY65jomOqYxf4HAA "Haskell – Try It Online")
This is what Haskell is great at. This declares a point-free function that zips the input with an infinite list.
# [Haskell](https://www.haskell.org/), 56 bytes
Here's a solution that uses complex numbers. Not very competitive because of the import but never the less pretty cool.
```
import Data.Complex
zipWith((+).realPart.((0:+1)^))[0..]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzzk/tyAntYKrKrMgPLMkQ0NDW1OvKDUxJyCxqERPQ8PASttQM05TM9pATy/2f25iZp5tQVFmXokKMeqjdU10FIx1FAx0FAx1FMx1FCx1FCx0FHSNgHyggK6FRex/AA "Haskell – Try It Online")
[Answer]
# Mathematica, 19 bytes
```
i=1;#+Im[i*=I]&/@#&
```
### Explanation
```
i=1;#+Im[i*=I]&/@#&
i=1; (* set variable i to 1 *)
/@# (* iterate through the input: *)
#+Im[i ]& (* add the imaginary component of i... *)
*=I (* multiplying i by the imaginary unit each iteration *)
```
Note: `i=1` appears outside of the function, which is okay [per this meta consensus](https://codegolf.meta.stackexchange.com/q/5532/60043).
[Answer]
# J, 12 bytes
```
+1 0 _1 0$~#
```
[Try it online!](https://tio.run/##y/r/P03BVk9B21DBQCEeSKjUKXOlJmfkK6QpxJsoGANFDRXMFSwVLBTijRQMDRXiLSz@/wcA "J – Try It Online")
Because J's shape operator `$` fills cyclically, when we shape it to the length `#` of the input, it does exactly what we want, and we can just add it to the input `]`
[Answer]
## C++, ~~93~~ ~~85~~ ~~83~~ 63 bytes
```
auto w=[](auto&i){for(int j=0;j<i.size();j+=2)i[j]+=j%4?-1:1;};
```
-8 bytes, thanks to [this answer](https://codegolf.stackexchange.com/a/135262/72535), i discovered that lambda parameters can be `auto` and you can pass with the correct parameter, it will work
-2 bytes thanks to Nevay
-2 bytes thanks to Zacharý
I removed the `vector` include. You will need to pass as argument to w a container that respect the following conditions :
* Have a method called `size` with no arguments
* Have overloaded the subscript operator
STL Containers that respect the following conditions are `array`, `vector`, `string`, `map`, `unordered_map`, and maybe others
If outputting by modifying arguments arguments is not allowed, then :
## C++, ~~112~~ 110 bytes
```
#include<vector>
std::vector<int>w(std::vector<int>i){for(int j=0;j<i.size();j+=2)i[j]+=(j%4)?-1:1;return i;}
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 30 bytes
```
a->[a[x]+imag(I^x)|x<-[1..#a]]
```
[Try it online!](https://tio.run/##LYrBCsIwEER/ZaiXBHdLo4IRtHe/Iaywl5aASig9RPDfY1KEYZg3M0mXyHMqE25FeQwasuzjS2dzf2T7zVcOru93KlI0pefHKHhEWuJ7rbFr0GEyai0hhEGqs9v8RDgSBoIjnAkXgifwoXIt2Pt2GrbDX62okxOx5Qc "Pari/GP – Try It Online")
[Answer]
# Dyalog APL, 13 bytes
```
⊢+1 0 ¯1 0⍴⍨≢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHXYu0DRUMFA6tB5KPerc86l3xqHMRUA4oYqJgDJQxVDBXsFSwAPKNFAwNgZSFBQA)
**How?**
`1 0 ¯1 0` - the array [1, 0, -1, 0]
`⍴⍨≢` - reshape to the length of the input, cyclic
`⊢+` - vectorized sum with the input
[Answer]
# [Ruby](https://www.ruby-lang.org/), 38 bytes
```
->a{a.zip([1,0,-1,0].cycle).map &:sum}
```
[Try it online!](https://tio.run/##KypNqvxfnlhm@1/XLrE6Ua8qs0Aj2lDHQEcXSMTqJVcm56Rq6uUmFiioWRWX5tb@LygtKVYAaoiONoiN1cvMKy5ITS7hQojqGmIXNtFRMNZRMNBRMNRRMNdRsNRRsNBR0DUC8oECuhYWCF0KSNoMwFqgCEkJGkDSATQNyQX/AQ "Ruby – Try It Online")
[Answer]
# D, 56 bytes
```
void w(T)(T[]i){for(T j;j<i.length;j+=2)i[j]+=j%4?-1:1;}
```
[Try it online!](https://tio.run/##HYtBCoMwFETX9RR/U0jwR6oVaptKL@EuZCFo6w@aFBvqQjx7mroYhveY6UL4OupgYQ1njdLE16ebWQNGmjtlY29ffpAmrQtOyui0NsfyIfJbLrdkP04tWcZhTQ40vd3s4eO7LIacjMp6paGFGpQoEc4IJ4Qc4YJwRagQRBE5ClFVOu4X1vJ/zeT70e6whfAD)
This is a port of [HatsuPointerKun's C++ answer](https://codegolf.stackexchange.com/a/135186/55550), so don't forget about them!
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~11~~ 10 bytes
Takes advantage of Japt's index wrapping.
```
Ë+[1TJT]gE
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=yytbMVRKVF1nRQ==&input=Wy00LCAzLCAwLCAxLCA3LCA5LCA4LCAtMiwgMTEsIC04OF0=)
---
## Explanation
Implicit input of array `U`.
```
Ë
```
Map over the array.
```
+
```
To the current element add...
```
gE
```
The element at the current index (`E`)...
```
[1TJT]
```
In the array `[1,0,-1,0]`.
[Answer]
# [Perl 6](http://perl6.org/), ~~28~~ 22 bytes
~~{((1+0i,*×i...*)Z+$\_)».re}~~
```
(*Z-(i*i,*i...*))».re
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfQytKVyNTK1NHK1NPT09LU/PQbr2i1P/WCsWJlQppGnGGBpr/AQ "Perl 6 – Try It Online")
`i*i, *i ... *` produces an infinite list of the numbers `-1, -i, 1, i` repeateded in a cycle. Those numbers are zipped with subtraction (`Z-`) with the input list (`*`), and then the real components of the resulting complex numbers are extracted (`».re`).
[Answer]
# [Actually](https://github.com/Mego/Seriously), 11 bytes
```
;r⌠╦½*C≈⌡M¥
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/6hnwX/rIiD5aOqyQ3u1nB91djzqWeh7aOl/EJX5PzraIFYnWtcQRJjoKBjrKBjoKBjqKJjrKFjqKFjoKOgaAflAAV0LC6AaA7A8FAH5QAnD2FgA "Actually – Try It Online") (runs all test cases)
Explanation:
```
;r⌠╦½*C≈⌡M¥
;r range(len(input))
⌠╦½*C≈⌡M for each value in range:
˫*C cos(pi/2*value)
≈ floor to integer
¥ pairwise addition of the input and the new list
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
.e+bss^.j)k
```
[Try it online!](https://pyth.herokuapp.com/?code=.e%2Bbss%5E.j%29k&input=%5B-4%2C+3%2C+0%2C+1%2C+7%2C+9%2C+8%2C+-2%2C+11%2C+-88%5D&debug=0)
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 15 bytes
```
l~_,,[1TW0]f=.+
```
[Try it online!](https://tio.run/##S85KzP3/P6cuXkcn2jAk3CA2zVZP@///aAMFKIwFAA "CJam – Try It Online")
[Answer]
# [Math.JS](http://mathjs.org/), 34 bytes
```
f(k)=k.map(j(x,y,z)=x+im(i^y[1]))
```
## Explained
```
f(k)=k.map(j(x,y,z)=x+im(i^y[1]))
f(k)= # Define a function f, which takes argument k.
k.map( ) # Map k to a function
j(x,y,z)= # Function j. Takes arguments x, y, and z. Where x is the item, y is the index in the form [i], and z is the original list.
im( ) # The imaginary component of...
i^y[1] # i to the power of the index.
x+ # x +, which gives our wave.
```
[Try it Online!](https://a-ta.co/math/&ZihrKT1rLm1hcChqKHgseSx6KT14K2ltKGleeVsxXSkpCnByaW50KAogICAgZihbMSwyLDMsNCw1XSkKKQo=)
[Answer]
# [8th](http://8th-dev.com/), ~~96~~ 63 bytes
**Code**
```
a:new swap ( swap 90 * deg>rad n:cos int + a:push ) a:each drop
```
This code leaves resulting array on TOS
**Usage and examples**
```
ok> [0,0,0,0,0] a:new swap ( swap 90 n:* deg>rad n:cos n:int n:+ a:push ) a:each drop .
[1,0,-1,0,1]
ok> [-4,3,0,1,7,9,8,-2,11,-88] a:new swap ( swap 90 * deg>rad n:cos int + a:push ) a:each drop .
[-3,3,-1,1,8,9,7,-2,12,-88]
```
**Explanation**
We use cos(x) in order get the right sequence [1,0,-1,0]. Each array element's index is multiplied by 90 degrees and then it is passed to cos() function to get the desired "wave factor" to be added to the corresponding item.
```
: f \ a -- a
a:new \ create output array
swap \ put input array on TOS
\ array element's index is passed to cos in order to compute
\ the "wave factor" to add to each item
( swap 90 n:* deg>rad n:cos n:int n:+
a:push ) \ push new item into output array
a:each
drop \ get rid of input array and leave ouput array on TOS
;
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 50 bytes
```
n=>{for(int i=0;i<n.Length;i+=2)n[i]+=i%4<1?1:-1;}
```
[Try it online!](https://tio.run/##VY3BagIxFEX3@YqHIEwwEccKjmZiKd22qy66EBchxpk36AudpJYS8u3T4K7Le@CeY4O0fnTTd0Dq4OM3RHdTzF5NCPCVWIgmooW7xzO8G6SKJ/ZiI3pqkeLxdIBOT6QP6eLHqhBAvVLY0vLNURd7hQu95nTE00LjfNPWz/Ve1ipPit3NCIMm9wMPUZIbAU8CVgJqAVsBOwGNALkuuwDZNFmxrhq4YiXljO0fub68YeDp1VPwV7f8HDG6qufqP5gJmHGVWc7THw "C# (.NET Core) – Try It Online")
Uses a simple lambda. Modifies the original array and returns the output through reference.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
```
vy3L2.SR0¸«Nè+})
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/rNLYx0gvOMjg0I5Dq/0Or9Cu1fz/P9pABwxjAQ "05AB1E – Try It Online")
---
`3L2.SR0¸«` is the shortest thing I can think of for `sin(x % 4)` in 05AB1E.
[Answer]
# [Arturo](https://arturo-lang.io), 33 bytes
```
$=>[i:0map&=>[&-((i%4)-1)%2'i+1]]
```
[Try it](http://arturo-lang.io/playground?mAebjN)
Port of ETHproductions' [JavaScript answer](https://codegolf.stackexchange.com/a/135135/97916).
[Answer]
# [Zsh](https://www.zsh.org/), 34 bytes
```
for i;echo $[++j%2*(j%4>2?-1:1)+i]
```
[Try it online!](https://tio.run/##NYrBDoIwGIPvPEUPkIDLEv45dbBEeQ/iyTDYDpIwvYg8@/w5mKZNv7SfOCVXVuv7GYcXPIIdmZKbF3g7PKYZeS9EKNShDIW@qpuklirh72mzI/Luu8Qtyxw0TjjjAoOGqWZL2kPjiBrES8ObVCCCNGb//MWdQOkH "Zsh – Try It Online")
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 9 bytes
```
ĐŁřπ*₂šƖ+
```
[Try it online!](https://tio.run/##K6gs@f//yISjjUdnnm/QetTUdHThsWna//9H65roKBjrKBjoKBjqKJjrKFjqKFjoKOgaAflAAV0Li1gA "Pyt – Try It Online")
```
Đ implicit input; Đuplicate
Ł get Łength
ř řangify
π*₂ multiply by pi/2
š take šin
Ɩ cast to Ɩnteger
+ add the two arrays element-wise
```
] |
[Question]
[
Driftsort is a simple way to "sort" an array. It works by "sliding" or "rotating" the elements over in the array until the array is sorted, or until the array fails to be sorted.
Let's walk through two examples. First, consider the array `[10, 2, 3, 4, 7]`. Since the array is not sorted, we rotate it once. (This can happen in either direction, so long as it remains the same direction.) Then, the array becomes:
```
[7, 10, 2, 3, 4]
```
This is not sorted, so we rotate again.
```
[4, 7, 10, 2, 3]
```
And again:
```
[3, 4, 7, 10, 2]
```
And a final time:
```
[2, 3, 4, 7, 10]
```
And it's sorted! So the array `[10, 2, 3, 4, 7]` is driftsortable. Here are all the rotations of the array, for clarity:
```
[10, 2, 3, 4, 7]
[7, 10, 2, 3, 4]
[4, 7, 10, 2, 3]
[3, 4, 7, 10, 2]
[2, 3, 4, 7, 10]
```
Consider now the array `[5, 3, 9, 2, 6, 7]`. Look at its rotations:
```
[5, 3, 9, 2, 6, 7]
[7, 5, 3, 9, 2, 6]
[6, 7, 5, 3, 9, 2]
[2, 6, 7, 5, 3, 9]
[9, 2, 6, 7, 5, 3]
[3, 9, 2, 6, 7, 5]
```
None of these arrays are sorted, so the array `[5, 3, 9, 2, 6, 7]` is not driftsortable.
---
**Objective** Given a nonempty array/list of integers as input to a program/function, implement driftsort on the input and output it, or output a falsey value (**or** an empty array/list) if it cannot be driftsorted. The integers are bound to your languages max/min, but this must be at least 255 for the max, and 0 for the min.
You may use built-in sorting methods, but not a built-in which solves the challenge.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes.
## Test cases
```
input => output
[1] => [1]
[5, 0, 5] => [0, 5, 5]
[3, 2, 1] => false
[0, 9, 3] => false
[1, 2, 3, 4] => [1, 2, 3, 4]
[4, 1, 2, 3] => [1, 2, 3, 4]
[0, 2, 0, 2] => false
[5, 3, 9, 2, 6, 7] => false
[0, 0, 0, 0, 0, 0, 0] => [0, 0, 0, 0, 0, 0, 0]
[75, 230, 30, 42, 50] => [30, 42, 50, 75, 230]
[255, 255, 200, 200, 203] => [200, 200, 203, 255, 255]
```
[Answer]
# Ruby, 33
```
->a{a.any?{a.sort==a.rotate!}&&a}
```
`a.any?` fires up to once for each element in the array, except it stops (and returns true) as soon as the array has been mutated into a sorted state. If this happens, we return the mutated array. Otherwise we return the false value that `any?` returns.
[Answer]
## Python 2, 51 bytes
```
lambda l:sorted(l)*(map(cmp,l[-1:]+l,l).count(1)<3)
```
Doesn't bother rotating. Instead, sorts the list, then sees if the original is drift-sortable by checking if there's at most one decrease among consecutive elements of the cyclified list. The count is `<3` because `map` pads the shorter list with `None` at the end, adding a fake decrease.
[Answer]
## Pyth, 9 bytes
```
*SQ}SQ.:+
```
Explanation:
```
- Q = eval(input())
+ - Q+Q
.: - sublists(^)
} - V in ^
SQ - sorted(Q)
*SQ - ^ * sorted(Q) (return sorted(Q) if ^ True)
```
[Try it here!](http://pyth.herokuapp.com/?code=%2aSQ%7DSQ.%3A%2B&input=%5B5%2C0%2C5%5D&test_suite_input=%5B1%5D%0A%5B5%2C+0%2C+5%5D%0A%5B3%2C+2%2C+1%5D%0A%5B0%2C+9%2C+3%5D%0A%5B1%2C+2%2C+3%2C+4%5D%0A%5B4%2C+1%2C+2%2C+3%5D%0A%5B0%2C+2%2C+0%2C+2%5D%0A%5B5%2C+3%2C+9%2C+2%2C+6%2C+7%5D%0A%5B0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%5D%0A%5B75%2C+230%2C+30%2C+42%2C+50%5D%0A%5B255%2C+255%2C+200%2C+200%2C+203%5D&debug=0)
[Or use a test suite!](http://pyth.herokuapp.com/?code=%2aSQ%7DSQ.%3A%2B&input=%5B5%2C0%2C5%5D&test_suite=1&test_suite_input=%5B1%5D%0A%5B5%2C+0%2C+5%5D%0A%5B3%2C+2%2C+1%5D%0A%5B0%2C+9%2C+3%5D%0A%5B1%2C+2%2C+3%2C+4%5D%0A%5B4%2C+1%2C+2%2C+3%5D%0A%5B0%2C+2%2C+0%2C+2%5D%0A%5B5%2C+3%2C+9%2C+2%2C+6%2C+7%5D%0A%5B0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%5D%0A%5B75%2C+230%2C+30%2C+42%2C+50%5D%0A%5B255%2C+255%2C+200%2C+200%2C+203%5D&debug=0)
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṙỤċṢȧṢ
```
[Try it online!](http://jelly.tryitonline.net/#code=4bmZ4bukxIvhuaLIp-G5og&input=&args=WzI1NSwgMjU1LCAyMDAsIDIwMCwgMjAzXQ) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmZ4bukxIvhuaLIp-G5ogrDh-KCrOG5hOKCrOG5m-KAnA&input=&args=WzFdLCBbNSwgMCwgNV0sIFszLCAyLCAxXSwgWzAsIDksIDNdLCBbMSwgMiwgMywgNF0sIFs0LCAxLCAyLCAzXSwgWzAsIDIsIDAsIDJdLCBbNSwgMywgOSwgMiwgNiwgN10sIFswLCAwLCAwLCAwLCAwLCAwLCAwXSwgWzc1LCAyMzAsIDMwLCA0MiwgNTBdLCBbMjU1LCAyNTUsIDIwMCwgMjAwLCAyMDNd).
### How it works
```
ṙỤċṢȧṢ Main link. Argument: A (list)
Ụ Grade up; return the indices of A, sorted by their corresponding values.
ṛ Rotate A by each index, yielding the list of all rotations.
Ṣ Yield A, sorted.
ċ Count the number of times sorted(A) appears in the rotations.
This gives 0 if the list isn't driftsortable.
ȧṢ Logical AND with sorted(A); replaces a positive count with the sorted list.
```
[Answer]
# Matlab, ~~61~~ ~~47~~ 41 bytes
Thanks @Suever for -6 bytes!
```
@(a)sort(a)+0*min(strfind([a,a],sort(a)))
```
If `strfind([a,a],sort(a))` tries to find the sorted input vector as a 'substring' of the unsorted, that was appended to itself. If true, the input is driftsortable and we get a vector of length 2, if not we get a empty vector. `min` just transforms this to an number / empty vector. Adding the sorted vector to 0 just displays it, adding it to an empty vector throws an error.
[Answer]
# Julia, ~~71~~ ~~66~~ 52 bytes
```
x->(y=sort(x))∈[circshift(x,i)for i=1:endof(x)]&&y
```
This is an anonymous function that accepts an array and returns an array or a boolean. To call it, assign it to a variable.
For an input array *x*, we construct the set of all rotations of *x* and check whether the sorted version *x* is an element of that list. If it is, we return *x* sorted, otherwise we return false.
Saved 19 bytes thanks to Dennis!
[Answer]
# [Pip](http://github.com/dloscutoff/pip), 15 + 1 = ~~17~~ 16 bytes
Ugh, the other golfing languages are blowing this out of the water. However, since I've already written it...
```
L#gI$<gPBPOgYgy
```
Takes input as space-separated command-line arguments. Requires `-p` or another array-formatting flag to display the result legibly rather than concatenated. The false case outputs an empty string, which is visible by virtue of the trailing newline.
```
Implicit: g is array of cmdline args; y is empty string
L#g Loop len(g) times:
POg Pop the first item from g
gPB Push it onto the back of g
$< Fold on < (true if g is now sorted)
I Yg If true, yank g into y
y Autoprint y
```
[Answer]
## JavaScript (ES6), ~~72~~ ~~70~~ 65 bytes
```
a=>a.map(y=>{c+=x>y;x=y},x=a.slice(c=-1))|c<1&&a.sort((a,b)=>a-b)
```
Returns `0` on failure. Previous ~~85~~ ~~83~~ 80-byte version avoided calling `sort`:
```
a=>a.map((y,i)=>{x>y&&(c++,j=i);x=y},x=a.slice(c=-1))|c<1&&a.splice(j).concat(a)
```
Edit: Saved 2 bytes by initialising `c` to `-1` instead of `0`. Saved 5 bytes by switching from `reduce` to `map`, sigh...
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 12 bytes
Code:
```
DgFÀÐ{Qi,}}0
```
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=RGdGw4DDkHtRaSx9fTA&input=WzI1NSwgMjU1LCAyMDAsIDIwMCwgMjAzXQ).
[Answer]
## [Snowman 1.0.2](https://github.com/KeyboardFire/snowman-lang/releases/tag/v1.0.2-beta), 27 bytes
```
((}#AsO|##aC,as|aLNdE`aR*))
```
This is a subroutine that takes input from and outputs to the current permavar.
[Try it online!](http://snowman.tryitonline.net/#code=Ly8gdGhlIGJlbG93IHN0cmluZyAoY2RlZmFiKSBpcyB0aGUgaW5wdXQuIEluIFNub3dtYW4sIHN0cmluZ3MgYXJlIHJlYWxseSBqdXN0Ci8vIGFycmF5cyBvZiBBU0NJSSBjb2Rlcy4gSSdtIHVzaW5nIGEgc3RyaW5nIGhlcmUgYmVjYXVzZSBpdCdzIHZlcnkgYW5ub3lpbmcKLy8gdG8gcHJvZHVjZSBhcnJheXMgb2YgY29uc3RhbnQgbnVtYmVycyBpbiBTbm93bWFu4oCUYnV0ICJjZGVmYWIiIGV4cGFuZHMgdG8KLy8gWzk5IDEwMCAxMDEgMTAyIDk3IDk4XS4gRm9yIGFuIGV4YW1wbGUgb2YgYSBmYWxzeSB0ZXN0IGNhc2UsIHRyeSBjaGFuZ2luZwovLyAiY2RlZmFiIiB0byBzb21ldGhpbmcgbGlrZSAiY2VkYWZiIi4KfiJjZGVmYWIiKgoKLy8gaGVyZSdzIHRoZSBzdWJyb3V0aW5lIGNhbGw6CigofSNBc098IyNhQyxhc3xhTE5kRWBhUiopKQoKLy8gbm93IHdlIG91dHB1dCB0aGUgcmVzdWx04oCUZW1wdHkgYXJyYXkgaXMgcmV0dXJuZWQgZm9yIHRoZSBmYWxzeSB2YWx1ZSAoYWthCi8vIGVtcHR5IHN0cmluZywgc28gbm90aGluZyB3aWxsIGJlIHNlbnQgdG8gU1RET1VUKQojc1A&input=)
```
(( )) subroutine
} set our active variables b, e, and g:
.[a] *[b] .[c]
.[d] *[e] (* represents an active variable)
.[f] *[g] .[h]
# store the input in variable b
AsO sort in-place
| swap b with g; now sorted input is in g
## store the input again in b and e
aC concat; now the input doubled is in b and e is empty
, swap e/g; now b has 2*input and e has sorted input
as split 2*input on sort(input) and store result in g
| bring the result up to b (we no longer care about g)
aLNdE take length and decrement; now we have 0 in b if the
array is not driftsortable and 1 if it is
`aR repeat e (the sorted array) b times:
if b is 0 (nondriftsortable), returns [] (falsy)
otherwise (b=1), returns sorted array unchanged
* put this back into the permavar
```
[Answer]
# MATL, ~~13~~ ~~12~~ ~~10~~ 9 bytes
```
SGthyXfa*
```
The same idea as [@flawr's answer](https://codegolf.stackexchange.com/a/78191/51939) where we hijack `strfind` (`Xf`) to find the sorted version of the input within the concatenation of two copies of the input.
[**Try it Online!**](http://matl.tryitonline.net/#code=U0d0aHlYZmEq&input=WzQsMSw0LDNd)
**Explanation**
```
% Implicitly get input
S % Sort the input
Gth % Explicitly grab the input again and concatenate with itself
y % Copy the sorted version from the bottom of the stack
Xf % Look for the sorted version as a subset
a % Gives a 1 if there were matches and 0 otherwise
* % Multiply by the sorted array. Yields all zeros for no match and the
% sorted array when a match was found
% Implicitly display the stack contents
```
[Answer]
# Julia, 33 bytes
```
x->sum(diff([x;x]).<0)<3&&sort(x)
```
[Try it online!](http://julia.tryitonline.net/#code=ZiA9IHgtPnN1bShkaWZmKFt4O3hdKS48MCk8MyYmc29ydCh4KQoKZm9yIHggaW4gKFsxXSwgWzUsMCw1XSwgWzMsMiwxXSwgWzAsOSwzXSwgWzEsMiwzLDRdLCBbNCwxLDIsM10sIFswLDIsMCwyXSwgWzUsMyw5LDIsNiw3XSwgWzAsMCwwLDAsMCwwLDBdLCBbNzUsMjMwLDMwLDQyLDUwXSwgWzI1NSwyNTUsMjAwLDIwMCwyMDNdKQogICAgcHJpbnRsbihmKHgpKQplbmQ&input=)
### How it works
This concatenates the array **x** with itself and counts the number of pairs that are out of order, i.e. the number of contiguous subarrays **[a, b]** for which **b - a < 0**. If **c** is the number of unordered pairs of **x** itself and **t** is **1** if **x**'s last element is larger than its first, `sum` will return **2c + t**.
The array **x** is driftsortable iff **(c, t) = (1, 0)** (**x** has to be rotated to the smaller value of the only unordered pair), **(c, t) = (0, 1)** (**x** is sorted) or **(c, t) = (0, 0)** (**x** is sorted and all of its elements are equal), which is true iff **2c + t < 3**.
[Answer]
# Javascript ES6, ~~48~~ ~~45~~ 43 chars
```
x=>~(x+[,x]).indexOf(x.sort((a,b)=>a-b))&&x
```
Test:
```
f=x=>~(x+[,x]).indexOf(x.sort((a,b)=>a-b))&&x
;`[1] => [1]
[5, 0, 5] => [0, 5, 5]
[3, 2, 1] => false
[0, 9, 3] => false
[1, 2, 3, 4] => [1, 2, 3, 4]
[4, 1, 2, 3] => [1, 2, 3, 4]
[0, 2, 0, 2] => false
[5, 3, 9, 2, 6, 7] => false
[0, 0, 0, 0, 0, 0, 0] => [0, 0, 0, 0, 0, 0, 0]
[75, 230, 30, 42, 50] => [30, 42, 50, 75, 230]
[255, 255, 200, 200, 203] => [200, 200, 203, 255, 255]`
.split`
`.map(t => t.replace(/^(.*) => (.*)$/, "f($1)+'' == $2")).every(eval)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 39 bytes
```
l:0re:?{[0:L],!L.|rh$(L,?h-1=:L:1&.}.o.
```
I really need to add an optional argument to `$( - circular permute left` to permute more than once... this would have been 13 bytes. This will wait after implementing a stable new transpiler in Prolog.
### Explanation
```
l:0re I = a number between 0 and the length of Input
:?{[0:L],!L.|rh$(L,?h-1=:L:1&.} All this mess is simply circular permutating the
input I times
.o. Unify the Output with that circular permutation
if it is sorted, else try another value of I
```
[Answer]
# Ruby, 47 bytes
Recursive function. Returns `nil` if the input array cannot be driftsorted.
```
f=->a,i=0{a.sort==a ?a:a[i+=1]?f[a.rotate,i]:p}
```
[Answer]
## CJam, ~~17~~ 13 bytes
*Thanks to Dennis for saving 4 bytes.*
```
{_$\_+1$#)g*}
```
An unnamed block (function) which takes and returns a list.
[Test suite.](http://cjam.aditsu.net/#code=qN%2F%7B'%2C-%22%20%3D%3E%20%22%2F0%3D~%0A%0A%7B_%24%5C2*1%24%23)g*%7D%0A%0A~pNo%7D%2F&input=%5B1%5D%20%3D%3E%20%5B1%5D%0A%5B5%2C%200%2C%205%5D%20%3D%3E%20%5B0%2C%205%2C%205%5D%0A%5B3%2C%202%2C%201%5D%20%3D%3E%20false%0A%5B0%2C%209%2C%203%5D%20%3D%3E%20false%0A%5B1%2C%202%2C%203%2C%204%5D%20%3D%3E%20%5B1%2C%202%2C%203%2C%204%5D%0A%5B4%2C%201%2C%202%2C%203%5D%20%3D%3E%20%5B1%2C%202%2C%203%2C%204%5D%0A%5B0%2C%202%2C%200%2C%202%5D%20%3D%3E%20false%0A%5B5%2C%203%2C%209%2C%202%2C%206%2C%207%5D%20%3D%3E%20false%0A%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%20%3D%3E%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%0A%5B75%2C%20230%2C%2030%2C%2042%2C%2050%5D%20%3D%3E%20%5B30%2C%2042%2C%2050%2C%2075%2C%20230%5D%0A%5B255%2C%20255%2C%20200%2C%20200%2C%20203%5D%20%3D%3E%20%5B200%2C%20200%2C%20203%2C%20255%2C%20255%5D)
### Explanation
This essentially uses xnor's observation that the sorted list appears in twice the original list if its drift sortable:
```
_$ e# Duplicate input and sort.
\_+ e# Get other copy and append to itself.
1$ e# Copy sorted list.
# e# Find first position of sorted list in twice the original,
e# of -1 if it's not found.
)g e# Increment and take signum to map to 0 or 1.
* e# Repeat sorted array that many times to turn it into an empty
e# array if the input was not drift sortable.
```
[Answer]
# C++ 14, 242 chars
```
#include<iostream>
#include<vector>
#include<algorithm>
#define b v.begin()
using namespace std;int main(){vector<int>v;int x,n=0;for(;cin>>x;++n)v.push_back(x);for(x=n;x--;rotate(b,b+1,b+n))if(is_sorted(b,b+n)){for(x:v)cout<<x<<' ';return 0;}}
```
If I can't leave output empty, 252 chars <http://ideone.com/HAzJ5V>
```
#include<iostream>
#include<vector>
#include<algorithm>
#define b v.begin()
using namespace std;int main(){vector<int>v;int x,n=0;for(;cin>>x;++n)v.push_back(x);for(x=n;x--;rotate(b,b+1,b+n))if(is_sorted(b,b+n)){for(x:v)cout<<x<<' ';return 0;}cout<<'-';}
```
Ungolfed version <http://ideone.com/Dsbs8W>
```
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
#define b v.begin()
int main()
{
vector <int> v;
int x, n=0;
for(;cin>>x;++n)
v.push_back(x);
for(x=n;x--;rotate(b,b+1,b+n))
if(is_sorted(b,b+n))
{
for(x:v) cout<<x<<' ';
return 0;
}
cout << '-';
}
```
PS: Based on @MichelfrancisBustillos's [idea](/a/78205/32091).
[Answer]
# Java 7, 207 bytes
```
int[]D(int[]i){int x,z;z=x=-1;int[]d=new int[i.length];while(++x<i.length)if(i[x]>i[(x+1)%i.length])if(z<0)z=(x+1)%i.length;else return null;if(z<0)z=0;x=-1;while(++x<d.length)d[x]=i[z++%i.length];return d;}
```
**Detailed** [*try here*](http://ideone.com/q5YrL6)
```
// driftsort in ascending-order
int[] D(int[]i)
{
int x = -1,z = -1;
int[] d = new int[i.length];
while ((++x) < i.length)
{
if (i[x] > i[(x+1)%i.length])
{
if(z < 0) z = (x+1)%i.length;
else return null; // not driftsortable
}
}
if(z < 0) z = 0;
x = -1;
while ((++x) < d.length)
{
d[x] = i[(z++)%i.length];
}
return d;
}
```
[Answer]
# Java 175
prints out the output as space separated values, or prints `f` for a falsey value.
```
void d(int[]a){String s;for(int v,w,x=-1,y,z=a.length;++x<z;){v=a[x];s=""+v;for(y=0;++y<z;v=w){w=a[(x+y)%z];if(v>w){s="f";break;}s+=" "+w;}if(y==z)break;}System.out.print(s);}
```
goes through all the combinations of the array of integers until it finds the valid sequence or runs out of combinations. the array isn't modified, but instead the driftsorted sequence is stored as a space delimited string.
a bit more readable:
```
void driftsort(int[]array){
String str;
for(int previous,current,x=-1,y,len=array.length;++x<len;){
previous=array[x];
s=""+previous;
for(y=0;++y<len;previous=current){
current=array[(y+x)%len];
if(previous>current){
str="false";
break;
}
str+=" "+current;
}
if(y==len)break;
}
System.out.print(str);
}
```
[try it online](http://ideone.com/zQwJZ9)
[Answer]
# C, 105 bytes
```
i,s;main(c,v)char**v;{c--;while(i++<c)if(atoi(v[i])>atoi(v[i%c+1]))c*=!s,s=i;while(--i)puts(v[s++%c+1]);}
```
This accepts the input integers as separate command-line arguments and prints the output list as one integer per line.
If the list isn't driftsortable, the program exits prematurely due to a floating point exception, so its empty output represents an empty list.
### Verification
```
$ gcc -o driftsort driftsort.c 2>&-
$ ./driftsort 1 | cat
1
$ ./driftsort 5 0 5 | cat
0
5
5
$ ./driftsort 3 2 1 | cat
$ ./driftsort 0 9 3 | cat
$ ./driftsort 1 2 3 4 | cat
1
2
3
4
$ ./driftsort 4 1 2 3 | cat
1
2
3
4
$ ./driftsort 0 2 0 2 | cat
$ ./driftsort 5 3 9 2 6 7 | cat
$ ./driftsort 0 0 0 0 0 0 0 | cat
0
0
0
0
0
0
0
$ ./driftsort 75 230 30 42 50 | cat
30
42
50
75
230
$ ./driftsort 255 255 200 200 203 | cat
200
200
203
255
255
```
[Answer]
## Ruby, 28
```
->a{(a*2*?,)[a.sort!*?,]&&a}
```
Returns either the sorted array, or `nil` (which is a falsy value) if the input is not drift-sortable.
[Answer]
# Python, 53 bytes
```
s,N=sorted,lambda x:s(x)*(str(s(x))[1:-1]in str(x+x))
```
If you want to test this head over to <https://www.repl.it/languages/python3> and copy paste this:
```
s,N=sorted,lambda x:s(x)*(str(s(x))[1:-1]in str(x+x))
print(N([1,2,3,4,5,0]))
```
How it works:
* `s` is a variable storing the `sorted` python function which sorts lists
* `N` is the main function
* The input list sorted: `s(x)` is multiplied by whether or not the list is driftsortable `str(s(x))[1:-1]in str(x+x)` (thanks to @xnor)
+ This works because `[1,2,3,4]*false` results in an empty list `[]`
+ and `[1,2,3,4]*true` results in `[1,2,3,4]`
[Answer]
# Python, 83 bytes
```
def f(l):g=sorted(l);return g if any(l[x:]+l[:x]==g for x in range(len(l)))else 1>2
```
This got put to shame by the other python answers, but I might as well post it anyway. I really dislike the
```
range(len(l)))
```
part. Is there a faster way to iterate through the list?
[Answer]
# MATLAB/Octave, 118 bytes
```
function r(a)
i=0
while (~issorted(a) && i<length(a))
a=a([2:end 1]),i=i+1
end
if issorted(a)
a
else
0
end
```
[Answer]
## PowerShell v2+, ~~87~~ 80 bytes
```
param($a)0..($a.length-1)|%{if($a[$_-1]-gt$a[$_]){$c--}};(0,($a|sort))[++$c-ge0]
```
Steps through the input list `$a`, checking each pairwise element (including the last and first) to see if there is more than one decreasing pair. If the particular pair is decreasing, we decrement `$c`. Outputs either the sorted list, or single element `0`, based on the value of `$c` at the end. If more than one "bad" pair is present, then `++$c` will still be negative, otherwise it will be at least `0`, so the second element of the pseudo-ternary is chosen (`$a|sort`).
I see xnor did [something similar](https://codegolf.stackexchange.com/a/78182/42963), but I came up with this independently.
[Answer]
# Factor, 47 bytes
```
[ dup dup append [ natural-sort ] dip subseq? ]
```
join the sequence onto itself, then check if the sorted rendition of the original is a subsequence.
[Answer]
## C++, 313 ~~359~~ ~~370~~ bytes
*Huge shoutout to @Qwertiy for getting this working and teaching me some great golfing methods!*
### Golfed:
```
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){vector<int> v;int x,c=0,s=0,y;while(cin>>x)v.push_back(x);do if(rotate(v.begin(),v.begin()+1,v.end()),c++,is_sorted(v.begin(),v.end()))s=1;while(!s&c<=v.size());if(s)for(y=0;y<v.size();y++)cout<<v[y]<<" ";else cout<<"False";}
```
### Ungolfed:
```
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
vector <int> v;
int x, c=0, s=0, y;
while(cin>>x)
v.push_back(x);
do
if (
rotate(v.begin(),v.begin()+1,v.end()),
c++,
is_sorted(v.begin(),v.end())
) s = 1;
while(!s & c <= v.size());
if (s)
for(y=0; y<v.size(); y++)
cout<<v[y]<<" ";
else
cout<<"False";
}
```
[Answer]
# Mathcad, TBD
[](https://i.stack.imgur.com/4cgE8.jpg)
In Mathcad, 0 (scalar) == false.
(Equivalent) byte count is TBD until counting method agreed. Approx 52 bytes using a byte = operator / symbol keyboard equivalence.
[Answer]
# Mathematica ~~55 50 61~~ 58 bytes
With 3 bytes saved thanks to Martin Büttner.
My earlier attempts did not pass all of the test case. I needed to add `Union` to avoid repetitions in list that were input in order.
```
Join@Union@Cases[NestList[RotateRight,#,Length@#],Sort@#]&
```
**Tests**
```
Join@Union@Cases[NestList[RotateRight,#,Length@#],Sort@#]&/@
{{1},{5,0,5},{3,2,1},{0,9,3},{1,2,3,4},{4,1,2,3},{0,2,0,2},{5,3,9,2,6,7},
{0,0,0,0,0,0,0},{75,230,30,42,50},{255,255,200,200,203}}
```
>
> {{1}, {0, 5, 5}, {}, {}, {1, 2, 3, 4}, {1, 2, 3, 4}, {}, {}, {0, 0, 0,
> 0, 0, 0, 0}, {30, 42, 50, 75, 230}, {200, 200, 203, 255, 255}}
>
>
>
---
**Explanation**
Right rotate the input list from 1 to `n` times, where `n` is the length of the input list. If the sorted input list is among the output rotated lists, return it; otherwise return an empty list.
[Answer]
# PHP, 98 bytes
Outputs a `1` if driftsortable, else nothing
```
$a=$argv[1];$b=$a;sort($a);foreach($a as $v){echo($a===$b?1:'');array_unshift($b, array_pop($b));}
```
] |
[Question]
[
Diagonalize a vector into a matrix.
## Input
A vector, list, array, etc. of integers \$\mathbf{v}\$ of length \$n\$.
## Output
A \$n \times n\$ matrix, 2D array, etc. \$A\$ such that for each element \$a\_i \in \mathbf{v}\$,
$$
A =
\left( \begin{array}{ccc}
a\_1 & 0 & \cdots & 0 \\
0 & a\_2 & \cdots & 0 \\
\vdots & \vdots & \ddots & \vdots \\
0 & 0 & \cdots & a\_n
\end{array} \right)
$$
where the diagonal of \$A\$ is each element in \$\mathbf{v}\$.
## Notes
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program or function in bytes wins!
* [Construct the Identity Matrix](https://codegolf.stackexchange.com/questions/70365/construct-the-identity-matrix) may be of use to you.
* If the length of \$\mathbf{v}\$ is 0, you may return an empty vector, or an empty matrix.
* If the length of \$\mathbf{v}\$ is 1, you must return a \$1 \times 1\$ matrix.
## Not Bonus
You can receive this Not Bonus if your program is generic across any type, using the type's zero-value (if it exists) in place of \$0\$.
## Test Cases
```
[] -> []
[0] -> [[0]]
[1] -> [[1]]
[1, 2, 3] -> [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
[1, 0, 2, 3] -> [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]
[1, -9, 1, 3, 4, -4, -5, 6, 9, -10] -> [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, -9, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 3, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 4, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -4, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, -5, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 6, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 9, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, -10]]
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 7 bytes
```
{x*=#x}
```
My first K post. I tried real hard to make a Bubbler train work here but failed.
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6qu0LJVrqjl4krT0ORKUzAAYkMQVjBSMAbTBnCWriWQMFYwUdAFIlMFMwVLBV1DAwDqfA0a)
[Answer]
# [Haskell](https://www.haskell.org/), 39 bytes
```
f[]=[];f(a:b)=(a:map(0*)b):map(0:)(f b)
```
Recursively generates the matrix by appending a value at the top left corner of a smaller matrix.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
Xd
```
The code uses the builtin function `Xd` (which corresponds to MATLAB's `diag`). [Try it online!](https://tio.run/##y00syfn/PyLl//9oQx0FAx0FIx0F41gA "MATL – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
J=þ`a
```
[Try it online!](https://tio.run/##y0rNyan8/9/L9vC@hMT/h9vdNbMeNe7j4vr/PzpWRyHaEEzoKBjpKBhDmbqWOgpAylhHwQTIAWFTHQUzHQWgsK6hQSwA "Jelly – Try It Online")
```
J=þ` Identity matrix:
þ table
J [1 .. length]
` with itself
= by equality.
a Vectorizing logical AND; replace ones with elements of the vector.
```
If output can be flat:
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
jn`
```
[Try it online!](https://tio.run/##y0rNyan8/z8rL@H/4XZ3zaxHjfu4uP7/j47VUYg2BBM6CkY6CsZQpq6ljgKQMtZRMAFyQNhUR8FMRwEorGtoEAsA "Jelly – Try It Online")
```
j Join the vector on
n the list of, for each element, if it doesn't equal
` itself.
```
If the empty vector didn't have to be handled, this could tie non-flat as `jn`sL`; it passes all current test cases as `j¬` owing to all inputs being nonzero (which is not guaranteed by the spec).
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 4 bytes
```
diag
```
[Try it online!](https://tio.run/##y08uSSxL/f//f0pmYrqGoZWhgeZ/AA "Octave – Try It Online")
# [Python](https://www.python.org), 23 bytes
```
from numpy import*
diag
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhbb04rycxXySnMLKhUycwvyi0q0uFIyE9MhsjsKijLzSjRAAhpFiXnpqRqGOoZGmpqaEGmYIQA)
[Answer]
# [Haskell](https://www.haskell.org/), 34 bytes
```
foldr(\a m->(a:(0<$m)):map(0:)m)[]
```
[Try it online!](https://tio.run/##fVLLbsMgELz7K@aQA0hraZ20lWrF/YN@AeGAXLu1YmIr9rHfXgo4fdiRQMCyM8MurPbDTOem711bnVw79G9XcTKw@YswpeDjzkpZWjMKLqWVSru5mebaTM2ECiqDH0JpgtKSbh4H1@9/SBGR4j9C2BMOC05gP8OZI/xz5KBY3eH7ayv52ttvuU20/JngzYHw4J2wHglPBA/nBW@S3M9b6BAlKeCYJclzfEWS5/jKJM/LL5ICXn6ZFHCsQpLnWKUkz0sVtdRZZk138f3i@@gV47W7zNhBiRZdVQ0EbyU@IToaJI45fltMu6@67c375PJ6HL8B "Haskell – Try It Online")
Uses the recursive method [from Magma](https://codegolf.stackexchange.com/a/262878/20260) of expanding the matrix with a new value in the top left, but with `foldr` and `<$`.
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 6 bytes
```
x:ᵒ-¬*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpKuoVLsgqWlJWm6FisrrB5unaR7aI3WkuKk5GKo6IKbrtGxXNEGQGwIwjoKRjoKxhCWATJH11JHAUgZ6yiYADkgbKqjYKajABTWNTSIhZgGAA)
Multiplies the identity matrix like other answers.
```
x:ᵒ-¬*
x [0 .. length - 1]
: Duplicate
ᵒ Outer product with
- Subtract
¬ Logical NOT
* Multiply
```
[Answer]
# [J](http://jsoftware.com/), 6 bytes
```
*[:=#\
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/taKtbJVj/mtypSZn5CukKairQ1gwOk1Bx8oQXcgICI2B0OQ/AA "J – Try It Online")
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ƒóD»∑=√ó
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNCU5N0QlQzglQjclM0QlQzMlOTcmZm9vdGVyPSZpbnB1dD0yJTJDMyUyQzUmZmxhZ3M9)
Inspired by Unrelated String's Jelly answer.
#### Explanation
```
ƒóD»∑=√ó # Implicit input
ƒó # Length range
D # Duplicate
»∑ # Outer product over:
= # Check for equality
√ó # Multiply by the input
# Implicit output
```
[Answer]
# [Haskell](https://www.haskell.org), 67 bytes
```
f v=m.(m.).h where m g=map g[0..length v-1];h z i j|i==j=v!!i|1>0=z
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fVJLTsMwFJRY5hRTiUUiOdFLCwgEZsOWHcsoiwicT8mnatxUqnITNt0gzgSnwbHbQlLJln9vZvxsP83HV56076Is9_vPjUz92--nFB2vArcKvCDHNhdrgQoZr5IVsoiCoBR1JnN0fhjf59ihwLIvOF_ybjYr-vCR-M6k-rnopGjla9KKFhyRA9XcKGaIYo8dIhpCNf8hoUbC_wjDnGFhcAZSfdiTho9bGhSjM3R-bCQfR_MpN8nm3zGoZcFwpYJhXDPcMCjYD2lyyXk_pB6yWAWkb7HypF9h5Um_0sqT-YVVQOaXVgHpKlh50lWy8mSqGHux41RJUSu_rDbyRa6fa1yizZutWpKyRPGGKFWeI3COBj3cgjUeHnycvBYb-x0d_Qs)
[Answer]
# [Go](https://go.dev), ~~135~~ 130 bytes
```
func(v[]int)(A[][]int){for i,_:=range v{r:=make([]int,len(v))
for j,_:=range v{e:=0
if i==j{e=v[i]}
r[j]=e}
A=append(A,r)}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZU9LasMwEN3rFNOsJBgXp2lLa9DCN-jemCBSKciJx0a1vRHe9BrdmEIv0xvkNpVikwS6EO-jmeG9r-99M53uWrU7qL2GWllizNZt47r7lam7FRuUAyN_-s4kL6dP09OOD0VpqRM8L8qZedM4sLjNpFMUzgzeZbJWB83P_3jUxAchWByrbsd0JlNmDVgpK6_lUNhyZK6oSqlHlkvVtpreeY5OBFt3vaNxSfIbk5zzcgGeWfqATMISyLMZRlxIemHrK0N4QNjc6vS_lbwiBNggPAYR3xPCM0Kwk3U8O55bbdFSDDAXi2k8e3PhxpG4JXHhJqqrFGF9aTRNM_4B)
# [Go](https://go.dev), ~~141~~ 136 bytes + Not Bonus
```
func f[T any](v[]T)(A[][]T){for i,_:=range v{r:=make([]T,len(v))
for j,_:=range v{var e T
if i==j{e=v[i]}
r[j]=e}
A=append(A,r)}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVBBasMwEKRXvWLxSQKlJE2TtgEd8oMWcjMmqIkUlNiKkR1DEbr3D72EQj_Rn7Sv6SpOYkNBo51d7Q6z-vjc7I_fpVzt5EZBIY0lxBTl3tW3iS7q5OtQ68Hjz7s-2BXodAHSvmW0SbMFo_M0i9HrvQPDlzPhpEWRxruZKOROUXzlubK0YYzEpm2_qZEOFCyI0WCE2HolmtRkgbh0mwkVyFzIslR2TefcMSyr-uBsaP383rycDEW_lIEnxlYwExANGVt70obAz2R4ZaOOcbjjMO7nw_-lwRMHDGMO95hETDhMOWB5MIqy4bTZkhsbDbTLRTeePDvUyC01ll25jlmXMhwnZ-dVjcWNT2TCk1fECoFnjVAInYTrWNUXrFCP5P3t23sSeEumF_IQOom8L5GjxPlnj8c2_gE)
[Answer]
# [Python](https://www.python.org), ~~56~~ 55 bytes
*-1 byte thanks to xnor*
```
def f(a,i=0):
for b in a:l=a[i]=[0]*len(a);l[i]=b;i+=1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fVJLTsMwEJVY5hRDVwlMpEnLt5UXnMPywqG2sLCSKA4LbsAd2HQDd4LT4E9a0VZy5Ngz7z2P7dH7_B7ep5e-2-2-3iZdP_zcb5UGXUo0jKp1AbofoQXTgVxbJrkRjJO4sqorZbWxIW835po1afvvxcek3PQsnXLAgBecCwQuBPqIBIYpJU3A_TxnCEuEVcIQyI8QU4T3IQXFQU_nW46kx9nylPtXqX5E8MsK4cYn4b9FuEPwcN3QyQHnYy4bqmQFFE_J8hRvkeUp3jLLU3pFVkDplVkBxS5keYpdyvKUuui_oghmMtgHOx1s4j3m_WYqvxgNBi4Z9AEDGEbTTeVCS2PVdoEQNQDtqORroaxTQTaLnqyNJR0M0jkvr5Ih977-Aw)
[Outputs by modifying arguments](https://codegolf.meta.stackexchange.com/a/4942/70761).
[Answer]
# Dyalog APL, 9 bytes
Thanks to [@att](https://codegolf.stackexchange.com/users/81203/att) for -4
```
⊢×⍤1⍋∘.=⍋­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌­
⊢ # ‎⁡v
×⍤1 # ‎⁢multiplied row-wise with
⍋∘.=⍋ # ‎⁣the identity matrix of size (#v)
```
üíé Created with the help of [Luminespire](https://vyxal.github.io/Luminespire)
## Dyalog APL, 16 bytes + Not Bonus
The only other applicable scalar type are characters, where APL uses the space as the empty character, so this code also does
```
,⍨∘≢⍴∊⍤(⊢↑¨⍨1+≢)­⁡‎‎⁡⁠⁢⁡‏‏⁡⁠⁡‌⁢‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‏⁡⁠⁡‌⁣‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏⁡⁠⁡‌⁤‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁣‏‏⁡⁠⁡‌⁢⁡‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁤‏‏⁡⁠⁡‌⁢⁢‎‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏⁡⁠⁡‌­
⍴ # ‎⁡Reshape
,⍨∘≢ # ‎⁢to (#v)*(#v) matrix
∊⍤ # ‎⁣the flattened list of lists built by
⊢ ¨ # ‎⁤taking each item of v
↑ ⍨ # ‎⁢⁡and padding it with
1+≢ # ‎⁢⁢(#v) zeros
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire)
This works by noticing that, if the diagonalized matrix is read as a single list, row by row, each entry of `v` is spaced with as many zeros as the length of `v`.
[Answer]
# PARI/GP, 11 bytes
```
matdiagonal
```
Builtins are always a sad answer, aren't they?
[Answer]
# [Factor](https://factorcode.org/) + `math.matrices`, 15 bytes
```
diagonal-matrix
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQm1iSoQckijKTU4sVCopSS0oqC4oy80oUilMLS1PzQKKZ@QrWXFzVXApAUK1QC6UN4CxDJJaBgpGCMZBfqxD9PyUzMT0/LzFHF2x@xf/izNyCnFTdksSknFQ9hbwchViF1MTkjP8A "Factor – Try It Online")
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 9 bytes [SBCS](https://github.com/abrudz/SBCS)
```
-∘⍳⍤≢↑⍤0⊢
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=033UMeNR7@ZHvUsedS561DYRyDB41LUIAA&f=S1N41LuGK03BAIgNQVjBSMEYTBvAWYfWWwJJYwUTIAuETRXMFCyBtCFIk3pJanGJOlideqI61DQNAwUNQwWNR11NOkaamppAvRo6j3pXPOqYARR61LvY5FHXIlNNBQ11M3UFc00A&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
Left-pads each \$v\_i\$ to a vector of length \$i\$ and implicitly mixes.
Each row's fill elements match the type of the corresponding element of the vector.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 34 bytes
```
x=>x.map((v,i)=>x.map(_=>i--?0:v))
```
[Try it online!](https://tio.run/##NU1LCoMwEL3KLBOYEa220JboQUIowU9JUSNVQm6fjlIX77t472ODXduvWzaafdenQaWo6phNdhEioJNneKnaETX5I0iZnlobBF0chHBBKP@W7ggsJULFYccV4YbANRW5MccWP7R@Xv3YZ6N/i0FEyaPpBw "JavaScript (Node.js) – Try It Online")
[Answer]
# Mathematica, 14 bytes
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yUzMT0/LzHHN7GkKLPif1p0UGJeemq0oY6hgY5hbKy@fkBRZl7JfwA)
```
DiagonalMatrix
```
[Answer]
# Excel, 33 bytes
```
=IFERROR(MUNIT(ROWS(A1#))*A1#,"")
```
# Excel, 39 bytes + Not Bonus
```
=IFERROR(IF(MUNIT(ROWS(A1#)),A1#,0),"")
```
Input is *vertical* spilled range `A1#`.
Having to deal with the empty vector is inconvenient; otherwise these would be just 21 and 27 bytes respectively.
[Answer]
# [TypeScript](https://www.typescriptlang.org/)'s Type System, 62 bytes
```
type F<V>={[I in keyof V]:{[J in keyof V]:J extends I?V[J]:0}}
```
[Try it at the TypeScript Playground!](https://www.typescriptlang.org/play?#code/C4TwDgpgBAYgPANQHwF4DeBtAklAlgOygGsIQB7AMygQF0AuTAKT0JPKtruYgA9gJ8AEwDOULAH4EGRvQAMAX3kAoJaEhQAKhGHAAjFBSw4GWTSQBuJQHorUOwD1xq8NC06ATAaMZdAGiju-gDMZta2Dk5qrtrAQV7wPv6y-oFQIUhhdlCOzupuwAAs8cZ+UAC0AJz+pUH+Bf5l9eUArP4AbP5V5bqmGTZZOUA)
It's been a little while since I've golfed in TS types, so it's possible (though I think unlikely) that I missed a shorter way to do this. This one is pretty simple, but I'll leave an explanation anyway:
```
type F<V> = // type F taking generic tuple type V
{ [I in keyof V]: // for each I in V's indices:
{ [J in keyof V]: // for each J in V's indices:
J extends I // are J and I the same type?
? V[J] // if so, index into V with J
: 0 // otherwise, 0
} // end
} // end
```
I tried putting `keyof V` into `type F<V,K=keyof V>` but that doesn't work since the compiler complains that `K` could be a type unrelated to an array key, and it doesn't save enough bytes for `//ts-ignore` to be worth it.
[Answer]
# [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 9 bytes
`#äLºµÍ·®£`
prints the elements of the matrix separated by spaces, with `,` separating the rows. Does not print the zero entries above the diagonal.
[online interpreter](https://bsoelch.github.io/OneChar.js/?lang=itr&src=I-RMurXNt66j&in=WzEsIDAsIDIsIDNd)
# Explanation
```
# ; read array from standard input
äLº ; push the range from zero to array.length-1
µÍ ; replace each element in the range with a vector having a one at the given index
; this will give an identity matrix of size array.length represented as 2D array
· ; point-wise multiplication
® ; convert result to matrix
£ ; print
```
---
# Itr, ~~10~~ [9 bytes](https://bsoelch.github.io/OneChar.js/?lang=itr&src=I0y6tc23riuj&in=WzEsIDAsIDIsIDNd)
~~`#äLºµÍ·®+£`~~ (broken in current version)
`#LºµÍ·®+£`
Adds zero to the result to force the entries above the diagonal to be printed.
---
# Itr, [8 bytes](https://bsoelch.github.io/OneChar.js/?lang=itr&src=I0y6tc23rqM&in=WzEsIDAsIDIsIDNd)
`#LºµÍ·®£`
the `√§` before the `L` is no longer necessary in newer versions
[Answer]
# [R](https://www.r-project.org), 20 bytes
```
\(x)diag(x,sum(x|1))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhZbYjQqNFMyE9M1KnSKS3M1KmoMNTUhUjcT0jSSNTQ1uUCUAZQ2hNJGML6OkY4xnG2AwlPQtdRRAFLGOgomQA4Im-oomOkoAIV1DQ1g9ixYAKEB)
The `diag` built-in almost works here, but fails for inputs of length 1, where it produces identity matrix of size of the input. Unless specified `nrow` argument.
---
Less boring - without `diag` built-in:
# [R](https://www.r-project.org), 54 bytes
```
\(x,`[`=matrix)c(x,rep(0*x,n<-sum(x|1)))[n+1,n,T][n,n]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3zWI0KnQSohNscxNLijIrNJOB3KLUAg0DrQqdPBvd4tJcjYoaQ01Nzeg8bUOdPJ2Q2Og8nbxYqO6ENI1kDU1NLhBlAKUNobQRjK9jpGMMZxug8BR0LXUUgJSxjoIJkAPCpjoKZjoKQGFdQ6CJEHsWLIDQAA)
Idea: construct a vector such that every entry of the input \$x\$ of length \$n\$ is followed by \$n\$ zeros. A matrix with \$x\$ in the first row and followed by \$n\$ rows of zeros works too. Then, we can put this in a \$n\times n\$ `matrix` resulting in \$x\$ on the diagonal.
Ungolfed:
```
\(x){n=length(x)
m=matrix(c(x,rep(0,n^2)), nrow=n+1, ncol=n, byrow=TRUE)
matrix(m, nrow=n, ncol=n)}
```
---
# [R](https://www.r-project.org), 27 bytes
```
\(v,x=seq(a=v))v*!x%o%x-x^2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuha7YzTKdCpsi1MLNRJtyzQ1y7QUK1TzVSt0K-KMICpuJqRpJGtoanKBKAMobQiljWB8HSMdYzjbAIWnoGupowCkjHUUTIAcEDbVUTDTUQAK6xoCTYTYs2ABhAYA)
Heavily inspired by [@Kirill L.'s answer to the linked challenge](https://codegolf.stackexchange.com/a/163556/55372).
[Answer]
# [Python](https://www.python.org), 23 bytes
```
import numpy
numpy.diag
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhbbM3ML8otKFPJKcwsqucCkXkpmYjpEdldBUWZeiQZCWCPaSMdYxzRWUxOiAGYMAA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 25 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 3.125 bytes
```
L√û‚ñ°*
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJ+UD0iLCIiLCJMw57ilqEqIiwiIiwiW10gLT4gW11cblswXSAtPiBbWzBdXVxuWzFdIC0+IFtbMV1dXG5bMSwgMiwgM10gLT4gW1sxLCAwLCAwXSwgWzAsIDIsIDBdLCBbMCwgMCwgM11dXG5bMSwgMCwgMiwgM10gLT4gW1sxLCAwLCAwLCAwXSwgWzAsIDAsIDAsIDBdLCBbMCwgMCwgMiwgMF0sIFswLCAwLCAwLCAzXV1cblsxLCAtOSwgMSwgMywgNCwgLTQsIC01LCA2LCA5LCAtMTBdIC0+IFtbMSwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMF0sIFswLCAtOSwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMF0sIFswLCAwLCAxLCAwLCAwLCAwLCAwLCAwLCAwLCAwXSwgWzAsIDAsIDAsIDMsIDAsIDAsIDAsIDAsIDAsIDBdLCBbMCwgMCwgMCwgMCwgNCwgMCwgMCwgMCwgMCwgMF0sIFswLCAwLCAwLCAwLCAwLCAtNCwgMCwgMCwgMCwgMF0sIFswLCAwLCAwLCAwLCAwLCAwLCAtNSwgMCwgMCwgMF0sIFswLCAwLCAwLCAwLCAwLCAwLCAwLCA2LCAwLCAwXSwgWzAsIDAsIDAsIDAsIDAsIDAsIDAsIDAsIDksIDBdLCBbMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgLTEwXV0iXQ==)
The `P` flag on the permalink is to make the test cases pass (for some strange reason, I never made it not check exact string representation.) Individual cases all produce the right output with vyxal list syntax without the flag.
## Explained
```
LÞ□*­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌­
L # ‎⁡Push the length of the input
Þ□ # ‎⁢Construct an NxN identity matrix
* # ‎⁣and pair-wise vectorise multiplication
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Rust](https://www.rust-lang.org/), ~~83~~ 81 bytes
Simple and dirty imperative solution.
-2 bytes by taking a slice instead of a vec
```
|v:&[i8]|{let l=v.len();let mut r=vec![vec![0;l];l];for i in 0..l{r[i][i]=v[i]}r}
```
[Try it online!](https://tio.run/##fY3NCoMwEITvfYrxIgoxxNqWtiFPIjn0x5RATCHVXNRnT6O9tVKY3WW@2WVd/@qCsmgv2mY5BtN0UBBh9Oe01kc5LsQIT00TF/js2r6DE765JfXSGDdylno6aGgLRqkZXK1llPCxTW4KfHO/PpJMZelyJPP8i7BfVK4ggi1BtRqwP1lxIoijIthFM9ee4EAQcVF@Xk/hDQ "Rust – Try It Online")
# [Rust](https://www.rust-lang.org/), ~~126~~ 124 bytes + Not Bonus
The Copy bound is technically too strict and a Clone bound would be enough, but it would also be one byte longer *:shrug:*.
```
fn f<T:Default+Copy>(v:&[T])->Vec<Vec<T>>{let l=v.len();let mut r=vec![vec![T::default();l];l];for i in 0..l{r[i][i]=v[i]}r}
```
[Try it online!](https://tio.run/##dY5NDoIwEIX3nmLcmDYWAqImFuhGj0DcEBYIrSEpYCo0MYSzYyvu0GR@8r6ZvBnVP7tpEg2IKKEXLvJedttz@3gxpOkmTTLssCsvIpsJY4PkHchYu5I3CIdW1X0HKta8WKefklBazj52IbMhWgUVVA14risHlVaZiVibMqrRHq/zytjBsCpv9zUSlEYImwesXYZx@MUz8BbEXxICOwLBL@79HzknAqYFBPZG2DwQOBIw2PHns@P0Bg "Rust – Try It Online")
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), 53 bytes
```
")

")")")")")")
")")")")
```
Hover over any symbol to see what it does
[Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoibDo6MCk/XFw7XG4kOkA6P3ZcXFxuMS0yMS5cXDomezp9MGw1LSY9PyRufjlvXG5+MS0xMC5cXH57fmFvIiwiaW5wdXQiOiIiLCJzdGFjayI6IjI5MiAxOSAyNyAxMiA4MTIiLCJzdGFja19mb3JtYXQiOiJudW1iZXJzIiwiaW5wdXRfZm9ybWF0IjoiY2hhcnMifQ==)
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-P`, 6 bytes
```
g*EY#g
```
(The flag is only necessary to format the output in a readable way; any of `-P`, `-p`, `-S` will do.)
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboBS7IKlpSVpuhbL0rVcI5XTIRyo2JpoQx0FAx0FIx0FY5g6AA)
### Explanation
```
g*EY#g
g ; List of command-line arguments
# ; Length
EY ; Identity matrix of that size
g* ; Multiply each row by the corresponding element of g
```
[Answer]
# [Uiua](https://uiua.org), ~~7~~ 6 [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==)
```
√ó‚äû=.‚çè.
```
-1 thanks to Bubbler
[Try it!](https://uiua.org/pad?src=RiDihpAgw5fiip49LuKNjy4KCkYgW10KRiBbMV0KRiBbMSAyIDEgMl0KRiBbMSAwIDEgMl0=)
```
√ó‚äû=.‚çè.
. # duplicate
‚äû=.‚çè # identity matrix
√ó # multiply
```
[Answer]
# [Python](https://www.python.org), 66 bytes
```
def f(a):n=range(len(a));return[[(i==j)*a[i]for i in n]for j in n]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3nVJS0xTSNBI1rfJsixLz0lM1clLzgFxN66LUktKivOhojUxb2yxNrcTozNi0_CKFTIXMPIU8MDMLwoSapBxdUJSZV6KRqakAV5emATHTUEfB0FBTE6oUZjkA)
# [Python](https://www.python.org), 66 bytes
```
def f(a):x=len(a);return[[0]*i+[a[i]]+[0]*(x+~i)for i in range(x)]
```
This solution was inspired by [this](https://codegolf.stackexchange.com/a/70368/106829) answer.
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3nVJS0xTSNBI1rSpsc1LzgAzrotSS0qK86GiDWK1M7ejE6MzYWG0QR6NCuy5TMy2_SCFTITNPoSgxLz1Vo0IzFmqScnRBUWZeiUampgJcTZoGRJWhjoKhoSZMKcxyAA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes + Not Bonus
```
⭆¹EθEθ×⁼μξν
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaBjqKICoQjgVkpmbWqzhWliamFOskaujUKGpo5CnCQLW//9HRwPVG@goGOkoGMfG/tctywEA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input array
E Map over elements
θ Input array
E Map over elements
μ Row index
⁼ Equals
ξ Column index
√ó Multiplied by
ν Inner element
⭆¹ Pretty-print
```
Using `And` instead of `Times` would have made the code minusculely more efficient but this way the code produces empty strings on the non-diagonal entries when given a string array as input.
] |
[Question]
[
Given a word, decide if it is an ambigram.
When rotated:
```
b > q
d > p
l > l
n > u
o > o
p > d
q > b
s > s
u > n
x > x
z > z
```
Assume only lowercase letters as input.
---
Test input:
```
this,
another,
lll,
lol,
dad,
dab,
dap,
wow,
ooi,
lollpopdodllol,
```
---
Ones That Should Return Truthy Values:
```
lll,
lol,
lollpopdodllol,
```
---
Note that **input and output** can be taken in any format (except for Standard Loopholes).
[Answer]
# [Factor](https://factorcode.org) + `flip-text`, 34 bytes
```
[ dup flip-text "ʃ""l"replace = ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY0xCsJAEEX7OcWwfaxFsRYbG7ESizU7MYvj7mQzIYpYeQybNHoYb5DbGElj8fmfx4P_fBc215i6_rbdrNbLGZ4oBWIs2EumdFGshb2qD0eURKpXST4MlKqGQk41Vi3OAar2Blr6GmyIWlICZgaODM66IYchAm1sIUb_4yxRXHT8U-6vRots2psdukb-rs3nYQybRMI2J1zgfjRfZys4GXfXjf0F)
Factor has a vocabulary for ʇxǝʇ ᵷuᴉddᴉʃɟ, but for some reason it turns `l` into `ʃ`, so I have to change it back.
[Answer]
# [Python](https://www.python.org), ~~70~~ 69 bytes
*-1 byte thanks to Kyle G*
```
lambda s:[i*(i in b'losxz')or b'dbq0pnu0'[i%8]for i in s][::-1]==[*s]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3XXMSc5NSEhWKraIztTQyFTLzFJLUc_KLK6rUNfOLgOyUpEKDgrxSA_XoTFWL2DSgGFhRcWy0lZWuYaytbbRWcSzUsGcFRZl5JRppGknqSYXqmpoKKEBZIYQLoSAnPwddBYaCnIL8gpT8lByYWlQFKYkpmCa4ISkozy_HryA1Pw-_goKCAnQ7gAogvl2wAEIDAA)
Accepts a bytes object as input.
## Explanation
`[... for i in s]` Build an array mapping each letter `i` of `s` to...
`i*(i in b'losxz')` ... `i`, if `i` is one of the letters that should remain unchanged, `or`...
`b'dbq0pnu0'[i%8]` ... its rotation. Since the rotatable letters have unique code points *mod 8*, we can use that to index into a string of possible rotations. Note that multiple letters may map to a given letter (e.g. `u` and `e` both map to `n`), but that's fine since only the rotatable letters will form a reversible map (e.g. `b`->`q`->`b`)
`[...][::-1]==[*s]` Reverse the new array and compare to the original string, unpacked into an array.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
θ⟲T⁴≔⪫KAωη⎚⁼θΦη№bdlnopqsuxzι
```
[Try it online!](https://tio.run/##JYzBCsIwEETvfkXoaQPx5q2nUvTgqYg/sNZog@um2U1U/PkYcGBgeA9mXlDmiFTrJIEzJNtvTjFj9mdB1luUJ@waG1TDneEYA8Pk/WMgAuvMu3VpeiSPAm38X/apICkkZw6BshdYnBljaaa7XInjmrR8vp0zwbb0tWphrdsX/QA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ
```
Print the input string to the canvas.
```
⟲T⁴
```
Rotate the canvas by 180°, transforming the characters as required.
```
≔⪫KAωη
```
Read the transformed rotated string back from the canvas.
```
⎚
```
Clear the canvas.
```
⁼θΦη№bdlnopqsuxzι
```
Compare the two strings, and check that all of the letters in the string were valid. (This check costs half of the byte-count, ugh.)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 23 bytes
```
ka«ƛG₈₀2ǔvȯF±ɾF)ǍrT«ĿṘ⁼
```
[Try it online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrYcKrxptH4oKI4oKAMseUdsivRsKxyb5GKceNclTCq8S/4bmY4oG8IiwiIiwicWxwb2RsYiJd) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyIiLCLilqE6xpsiLCJrYcKrxptH4oKI4oKAMseUdsivRsKxyb5GKceNclTCq8S/4bmY4oG8IiwiO1rGm2AgPT4gYGo74oGLIiwidGhpc1xuYW5vdGhlclxubGxsXG5sb2xcbmRhZFxuZGFiXG5kYXBcbndvd1xub29pXG5sb2xscG9wZG9kbGxvbCJd).
## How?
```
ka«×¢₇}Ẇ₇]↲βjEβ&ɾṗµ«ĿṘ⁼
ka # Push the lowercase alphabet
«×¢₇}Ẇ₇]↲βjEβ&ɾṗµ« # Push compressed string "bqapaaaaaaalauodbasanaaxaz"
Ŀ # Transliterate the (implicit) input from the lowercase alphabet to that
Ṙ # Reverse
⁼ # Is it equal to the (implicit) input?
```
A port of Kevin's 05AB1E answer is 23 bytes as well:
# [Vyxal](https://github.com/Vyxal/Vyxal), 23 bytes
```
Ḃ«ƛ≠ȧ‹«:£ḂĿka¥«g₴Ṡ«JFF=
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLilqE6xpsiLCLhuILCq8ab4omgyKfigLnCqzrCo+G4gsS/a2HCpcKrZ+KCtOG5oMKrSkZGPSIsIjtaxptgID0+IGBqO+KBiyIsInRoaXNcbmFub3RoZXJcbmxsbFxubG9sXG5kYWRcbmRhYlxuZGFwXG53b3dcbm9vaVxubG9sbHBvcGRvZGxsb2wiXQ==)
[Answer]
# JavaScript (ES6), 68 bytes
*Saved 1 byte thanks to @Shaggy*
Returns \$0\$ or \$1\$.
```
s=>[...s].map(c=>o=S[S.search(c)^1]+o,S=o='bqdpnulloossxxzz')|o==s+S
```
[Try it online!](https://tio.run/##dc1NDoIwFATgvcdgU4jaxAOUpRfAHWJSWxTMs/PkgX/x7hgTFxrr9pvJzMGerbiu5X4e4OtxZ0Yxeam1lkofLafO5DBFWWipbeea1GWbRTXFrDAwanvyHAYiQOR6vd9V9oAxMi1GhyCgWhP2qSpX3dA3t0plk0/fpQkRJdmv4o8Sgz08vQtfDbUO5dKSxG76ppXIog3om7qLJN76qG6jyhG94BJRoI0oM7/uxic "JavaScript (Node.js) – Try It Online")
[Answer]
# [C](https://en.wikipedia.org/wiki/C_(programming_language)) ([gcc](https://gcc.gnu.org/)): ~~171~~ 143 bytes
**Edit**: Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for shortening the code to *~~171~~ 160 bytes* by using some nifty tricks! I did some simple cleanups to reduce it further to 143 bytes.
Hello, first time posting code golf here! Criticism is welcome. :)
```
d[]=L"q.p.......l.uodb.s.n..x.z";main(c,v)int**v;{for(char*s,*e;--c;s>e&&puts(v[c]))for(e=index(s=v[c],0);s<e--&d[*e-98]-*s+d[*s-98]==*e;)s++;}
```
[Try it online](https://tio.run/##hVPdT9swEH/PX3HjgTSBpOxDE6jrpA14qLSHSfCGeHDta@Ph2sHntHTT/vVl5yQt1UCa1VTW5fr7uqssllK2bTLO8wRyuK2EfSAIDiRqo@1SigAL54Eq5wNarkCoEKRTGLvefjyD@TYg8Tc0FF@TWyFYvQhbCF7LB3oTga@06t9Ig8I2dcfhUTUSQYcO6sP7Hqrk/nGyU3QTnGf4SLowuq5RAT42ei0M2gBuAQJkJbyQAT1oC19uLmczGJHzfhthhd06i4O266@XV7PLLOJyq@CP92LLOmrmYDwGF8SIxMrtsoRbB0sMHbm2Cp8i36GSZ2bSq9psIzA18xCLcHEOo15NDDCdpxksvFt1AH2dTTS4w9xjRf@Qlilogh8NBaiFUlFOl4u6u59@O3os67I/pmycmpdU2rJ8Kn8eTZKV0HYkT9eZtiHP15NfCQxnPIbvbCzQYBB0T/0Oasdl9ATSOyJ2FssrrZRB2FRaVrBxjVGHSCueY9dGKJ1VYJyrweKaw8AnHaMc6ZhlLXiPFBvHDESfJVpV7qE4nFH0ntNpjpOikBP6jMfHdRNotL6T91m2bz1gT3HaTWRE09h0epalcVT9ouzdxOC7eWnPOYqoUlB4De95ksM4hhV4rfea7fVEnedNhfbg92lO3eisC3FThYlb@HJh0hzTqOg1grXmfwUHSQIGA/9OaJfkMKL/aI4Rv8hrQp@wKI7VXY7Fxfl9kdMJ3ynep1OexMvYd4dOTibJ76Rt21BpagU7rdC3xpjWONMqofiZ81O3G7dpndOxbmpXK6cMX//IhRFLaovNXw) (with explanation)
**Explanation**:
```
/**
* Thanks to ceilingcat for shortening the code to 160 bytes by using some nifty tricks!
* Did some cleanups to reduce it to 143 bytes.
*/
/**
* Stores the flipped equivalent of a character in ASCII (sorry to anyone using EBCDIC)
* in an array represented as a string. To get the index of the flipped character simply
* subtract 98 (ASCII for 'b') from the ASCII value of the character.
* '.' is just padding.
*/
d[]=L"q.p.......l.uodb.s.n..x.z";
main(c,v)int**v;{
// Prints string if the 2 pointers crossed the middle which would
// mean the second loop never exited (is a palindrome) at the end.
for(char*s,*e;--c;s>e&&puts(v[c]))
// 'e=index(s=v[c],0)' gets the pointers for the first and last
// character of the string.
// Exits the loop when character '*s' is not equal to flipped character '*e' and
// vice versa or the 2 pointers cross at the middle of the string.
for(e=index(s=v[c],0);s<e--&d[*e-98]-*s+d[*s-98]==*e;)
s++;
}
```
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), ~~153~~ ~~148~~ ~~56~~ ~~55~~ 53 bytes
```
:=~&(:~|~:tr&"pq#{?p*9}lpuodbpspnppxpp"&[*?a..?z]*'')
```
[Try it online!](https://tio.run/##jc29CsIwGEbh3auQCGkbMLuB0gspDokRqnw0r01C/c2tR3CzcXB9hnPO22hu2bRZtYnXKj2TChNnuGweHcTuRYjOGniMwBVgvBedlrK770VVNRkx@LWRB01UszCcPGtWX6ZHF4bjtGQiKsj9Q1bbkkxJWNLs5h95goN1lj6n/AY "J-uby – Try It Online")
Just learning J-uby so this definitely is terrible.
Edit: I knew it. -95 bytes thanks to Steffan
[Answer]
# [R](https://www.r-project.org), 56 bytes
```
\(s)all(chartr("a-y","AqCpE-KlMuodbRsTnVWxY",s)==rev(s))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ddCxCsIwEAZgXH2MTAm0zl0yiDiJi4giuKSmpYWjdyap1WdxiYIPpU9jIbgIN93w8f_83P3h4rPWrz7UefEujtIrAyBPjXHBSWHym8jE_LygZb6CdY-23Phtt9tfDyLzSmtXXcaISvnPZFbLCqQPzhO0QYrQtH4sEEqp6R-ZDkNTOUYBgBPkxBrLSskKMTLgwAhiy28DQrJogZ9JRL-d6W0xpvsF)
Takes input as a vector of characters.
Translates all characters from the dictionary in the question to their counterparts and all others to uppercase equivalents (comparison is case sensitive in R, so those will break the equality).
[Answer]
# Regex (Perl / PCRE2 / Boost / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), 65 bytes
```
^(([losxz])((?1)\2|)|b(?1)q|q(?1)b|d(?1)p|p(?1)d|n(?1)u|u(?1)n|)$
```
[Try it online!](https://tio.run/##TYzBasMwEETv@oolCCxBiuNCL1YcE0h77Cm3phV25RDB1pJlm7S13F93JdpDDsPbnZld2zh8WD6@gDoBE5r3CoGmIqzF9rA/7nczORvHqC42YrsTgRmfQJ@DwyfrdDvA6tSuxAwUoYB@rPsh1OX6LltnvOliCOWNvwkJhxyoFATg7wNj8fgHUupSXiZHNzY5QJInTxX2YUy4@G9SFDBL@fh8kHJ5Y@wFTf/5/coZKzN@uvfc13HqfBdRexVhvY1Qvo0Y/RjRek6XZbjonlStGS6NI4hI0CBRlQqqgyy5misxRkcfrbHKKIyVUMVf "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##XZDBbsIwEETv@QrXsoRdBWh6xI1yKVRIFVQpN0KtQAyJtMTGDqJq02@na3rrYTXr8dPs2ra216fM1pYwR1JCx5SMiHX6oJy2UO40H4xH95lSdQmd2pmjbUC7ghdCFvnYD2IywNqjqQ46AG2n285zpWbz16lSIiaJwEgMltHeOM6a9EEySPeIe/6@ep4vhBTfpNlzBmvfOdAtdmKYbNKUFi0VCPvzFm/Qjh/iYSLkjW6E3tUmIJJgaiIjQtgxvS1/LLtdzZmLMUmSwP09CkrfKe0cLiLu0rd8@qIWSzXN82We0WnwJ4ROODtmdOXOekLwRGcleGypCBNuWZQBlT//PoULef3gfA3Gf35tBOdZIorHXvTb0J36U5BtXwWxvQ1S9W2Qc38O0vaCXa9d3fiobE1XaxcBQAQGoqqssLZYNrqYS2RME3ywxlamgoAgCr8 "PHP – Try It Online") - PCRE2
[Try it online!](https://tio.run/##XZDRbtsgFIbveYojr1KhS7a5lXZhJ63Uiz7A1ItNaWZhTGxUAhSw3KbOq9cD3G7tkOAcDj8fP4cZs2wZmz4JxWTfcFjVWjv/1fKWP37pjLlErKMWKrPZwhp@ZNfDcF9f9L@enn7edt@HDk@/Md5I7R4PW4LxVU7uzkcy1jF7GB9iqMcmBjOaGJpRxdCPfQxqJCcT@R@aLeDMrCvzOS/RP2ciGLOc7i@RUB6MDWvFrdUWM62ch2T0bM@doy0nz843RcGCAFYreK3GNNW5amQJlvveKsjLY0LuqVCYwDOCMMwmvCa5woYs8@36Wwl90FycVx503MULbUiSODGDXqg2HJjelzB7St0sitTO8FyAlW81t6eedTB01M@QnbaAI/YQ@QnZci@F4nj@i1CLmR4gh3X@5jQOsQN8IPMlpnsfP3p6p07Lv4oPR/i9r8pxalmHE3qRDC2CVwJXkN3anhcAGRSQ3VDpwiYjkTD/MtGPaX3tZWjIcfKdcIgq7TtukZQSSS1RQ5sw6zANGvSAtBaxLo02jW5klASpfGE7SVs3LWXyWCWLfwA "C++ (gcc) – Try It Online") - Boost
[Attempt This Online!](https://ato.pxeger.com/run?1=bY_BSgMxEIbveYohCE2gXbqeZMsiIvgE3rYVtiZ1A2MmTbK0lbyJl170GcQ36duY2B57GL7J8PNN5vPbHeJA9vhr3h35COEQpl6_6f0CPLTgOedfY9zM7k4PL0J0SGH_sZJC3NdyeZtkWpdum7YF66QKXHIFKtmCMY0FNsmbi-gnO7u6mdWrBZh2zjbkAcHYsrsKURnbMACzAdOA88ZGIcu7rc9T1FaghN4qwC5L2naytJMGsMVuXqw5djHRGKudN1EL_uxH3QDwYvi_rwq696-D8FPINo1BA3_qMxrg8poC5fn_x9NjHExgvaU4aM8QkSEhU73Ktc7l2I52jMiUOTpyihSWCF6yRHh2_QE "Python - Attempt This Online") - Python `import regex`
This is a straight port of my answer to [Numbers with Rotational Symmetry](https://codegolf.stackexchange.com/a/248959/17216).
```
^ # Assert this is the start of the string
( # Define (?1) recursive subroutine call
([losxz]) # \2 = match a char that is its own rotation
((?1)\2|) # Optionally match (?1) followed by \2
|
b(?1)q
|
q(?1)b
|
d(?1)p
|
p(?1)d
|
n(?1)u
|
u(?1)n
|
# Match an empty string at the center of an even-length string
)
$ # Assert this is the end of the string
```
If there just one more matched pair of distinct characters, e.g. `a`↔`e`, another method would win by 3 bytes:
```
^(([losxz])((?1)\2|)|a(?1)e|e(?1)a|b(?1)q|q(?1)b|d(?1)p|p(?1)d|n(?1)u|u(?1)n|)$
^((?=([losxz]|a.*e|e.*a|b.*q|q.*b|d.*p|p.*d|n.*u|u.*n)(?<=(.))).((?1)\3|)|)$
```
But instead it loses by 1 byte:
```
^(([losxz])((?1)\2|)|b(?1)q|q(?1)b|d(?1)p|p(?1)d|n(?1)u|u(?1)n|)$
^((?=([losxz]|b.*q|q.*b|d.*p|p.*d|n.*u|u.*n)(?<=(.))).((?1)\3|)|)$
```
## Regex (Ruby), 72 bytes
```
^((?=([losxz]|b.*q|q.*b|d.*p|p.*d|n.*u|u.*n)(?<=(.))).(\g<1>\k<3+0>|)|)$
```
[Try it online!](https://tio.run/##RYuxboMwFEV3f8Wr1QEUBUHGEKeKlHTsUGUDikB2wcqT7RgQaWX116lxhw5XR@@@c@3Ufi0WGLyLTjxMosQM59P1lFjR8BwkS3OYe4kCkHViHAiA/AT5tPZmGocchApelq8PLLZZxRgtFc39Aos0Sba7Klh@aqxUIyCwH7DwAvRqJ7EHoLAH@trg4A/6r/2t6vrydq7r5SOKCtTD47uKo7I7ZMfydtht0qOLXRvuu7sHto4HGmcCuVOBk5sClYufl2Xs5UAapcdeWIKIBDUS3nCf1seQWc9Ea7n2aLThmuOqeBV/AQ "Ruby – Try It Online")
In this port, unlike the Perl/PCRE2/Boost/Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) version, the alternative method wins by 5 bytes:
```
^(([losxz])(\g<1>\k<2+0>|)|b\g<1>q|q\g<1>b|d\g<1>p|p\g<1>d|n\g<1>u|u\g<1>n|)$
^((?=([losxz]|b.*q|q.*b|d.*p|p.*d|n.*u|u.*n)(?<=(.))).(\g<1>\k<3+0>|)|)$
```
## Regex (.NET), 75 bytes
```
^((?=([losxz]|b.*q|d.*p|n.*u|p.*d|q.*b|u.*n)(?<=(.))).?)+(?<-3>\3)*(?(3)^)$
```
[Try it online!](https://tio.run/##dY6xasMwEIZ3PYUwAuvUWrRkc@o6UOjWrVuagBNdasFVUmQbh9h5dleZOnX4Oe67j58LfsTYtUi0iFhtI37jZVeWDke5yZe9lHUlt@S7y3U3H7Q6z0arMDuthjloZeazVod50MqBrF8qqQFA1/CQlmL1@rUCJWu5gj2IJd88Zm/@J1hCk8FaXKun9clHbI6tFMSt48K6MPQwMc7tSYorTGO0PRat7/pb8p/T4Y/wwvn0JlmHPBPSnrgUUX80/bHFLjUC8Cn/jAOWnOc3jtRhAu9NmmUCkP3bJojdlr61HWuc71uMjIgYeWKmMSmHlMBGPzLv7Z1T8MF4Q3clqfQL "PowerShell – Try It Online")
## Regex (Perl / PCRE / .NET), 79 bytes
```
^((?=([losxz]|b.*q|q.*b|d.*p|p.*d|n.*u|u.*n)(?<=(.))).?(?=.*(\3(?(4)\4))))*\4?$
```
[Try it online!](https://tio.run/##TYzBboMwEETv/opVZAnbSp2gphcMsSKlPfaUW0kRFKIgbbFjQGkb6K9To/bQw2h338ysrRw@TO@fQJ2CG5q3HIGulD@TeL877LYjORnHaJ2sVbxVfob8BvXJE36zrm46WKTNQo1AERJo@6LtfDxb3oXLkFeX2QT9j6@9wyECmikC8PuBsbn8DSvqVlwHB9dXEUAQBU85tn4NuPpLUlQwZtnj8z7LplfGdMJe0LQfX8ehkOIyXKQohlIKO1gpyqGRoh96KRrOdJwwyTmX2pekYOk902zD041nXKQbTaepO9ctyRvTnStHEJGgQVLmpVfhZcnVXIkx9czRGluaEueIj@IP "Perl 5 – Try It Online") - Perl
**[Try it online!](https://tio.run/##fVLvb9MwEP2ev@JWGLNDFq10Qqg/Vo2xiQ9lQ1UngdoSpYnTRrix5zh069J/nXKO09ENiSiR7s7v3r17TiTl8TyKtq/SLOJFzKArI8X8xZkTLUIFgRxPoQfDxsfV6uesVXx/ePg2WrxfLcj2ByH9Hhlzkd@vp@XMd@/KO9@dlbHvylL6blxmvluUhe9mlPS7PeJTSv0@NvkumbRIn5zSySnWqDs57b/e0pcjGh64shfIt82O81deruNUGH37JZVm8@e1VGCVhct/cWdOmmmQGOqAKSUUiUSWa6j2dZcsz8M5o484p92OEADdLtRVE1Z1lsW8A4rpQmXQ7GwqymWYZoTCowP4yDFO4ywjkh43p72TDhSIab0LNAiTmYY5BhW44rTq8EAWugPmFsBVrAP76lCO1Mp2K5YXXNvY7JEkOdMeiELj2Lle2BPxi0VaqHFrakcha68iDyKxlClnRHrw9WJ4GXy6GZ0PBlDa7HZ09cGDN3agDXYTTqilShMgB4rRnQ9J5WlCcBtEe9AwRJU0BSEqqdrhMG7DYT7J8Hb3OO2cmjjBBmLEr41TlTlzpnmaMWJvJc086xPtIKa583wnak0Bz4xj5GiSHdWsdnvj2c4Bds8iopgH17eDQc3oRwFeBKG7NE/XzGQn1Vu76UFrj9SMrIm7aM6emBenBz3r7eVweDMMrm@@nI8uPlOobWtcGqfa0MClGM/ZU/0qxKyqPxFvniNGqkDAM0SyUqlm5L87NT1jrjA2Vn0b675iDBXTp/@7/tGczVYv0twJM6EXTDmcc4cL7sRhjN8MP@msxMoRIjV1LoWMRcwNBKH8d5TwcJ5vj7nx/g8 "C++ (gcc) – Try It Online") - PCRE1**
[Try it online!](https://tio.run/##XZBBbxshEIXv@ysoQjKgDY5Vn0wQlzpVpCqptrllE7T24uxK44XAWqnazW93Z91bDk8a3nw8holdPN/Y2EXCEjGELilRJCb/6pKP0Ow9XyyVtM51DYxuH46xB59qXgtdV8u8KMkCdUDTvfoZGEY/jJk7d3v3Y@ucKMlKYCQG6@IQEme9udYMzAHxzH89fru7F1r8Jf2BM3jKYwI/YCWuVs/G0HqgAuF82mEH7fK6vFoJfaF74fddmBFNMHWlC0LY0VyGPzbjvuMslZikycz9/xQ0eXQ@JRxEfDE/q@13d//gtlX1UFm6nf0NoRvOjpY@ppPfEDzR2wYyllTML1yyKAOqPz4thQt9fuHcGv4EIf/@8zztlHyb3pTcTa2ScYpKttOg5Gk6KTkIbm8MV0IIZfGSkrz@yi1fi3qNnpD12rLzeez6XDRDGDufCgAoIEDRNi1qh4rFe3gvQuhnH2KIbWhhRhCFfw "PHP – Try It Online") - PCRE2
[Try it online!](https://tio.run/##dY6xasMwEIZ3PYUwAp9EI1qayalxoNCtW7ckBSc6x4KrpMg2Do7z7K4yderwc/Dddz8X/Iixa5FoEbHcRTzj9VAUDkfY5ss3QFXCjnx3nQ7zUavLfNHqOButwhy0MrPTapgHrZyE6q0ELaXUVTrSCvavUMFa7teJSbVfV2LJt0/Zu/8JltBkciOm8nnT@Ij1qQVB3DourAtDL2@Mc9uAmORtjLbHVeu7/p78l7T4I3zlfHqVrEOeCbANBxH1Z92fWuxSo5T8ln/FAQvO8ztH6jCBjzrNIgGZ/dsmiN2XvrUdq53vW4yMiBh5YqY2KceUwEY/Mu/tg1PwwXhDDyWp9As "PowerShell – Try It Online") - .NET
## Regex (Perl / PCRE / Java / .NET), 86 bytes
```
^((?=([losxz]|b.*q|q.*b|d.*p|p.*d|n.*u|u.*n)(?<=(.))).?(?=.*(\3(\6\4|(?!\6))())))*\4?$
```
[Try it online!](https://tio.run/##TYzBTsMwEETv/oqlshTbKm4rSg9xU6tS4cipNwJRQlI10hK7TqICdfn14AgOHEa7O/NmbeXwfnj/BOoUXNC85Qh0psKZrHfb/XZzJQfjGK2TuVpvVJgLfoH6EBx@sa5uOpikzURdgSIk0PZF2wU8m94upgtencYQ9D9/HhIOMdBMEYDfD4yN5W@YUTfjOtq7vooBojh6zLENa8TVH0lRwTXLHp52WTa8MqYT9oym/fh68YUUJ3@SovClFNZbKUrfSNH7XoqGM71OmOScSx1KUrD0jqWrdOmZvklXnLMQcZEuNR2G7li3JG9Md6wcQUSCBkmZl0FFkCVncybG1KOP1tjSlDgiAcUf "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##fVJtb9owEP6eX3FlL7WzNCqjqiZeirqu1T6wdkJU2gQsCokD0UzsOs5oafjrY@c4dLSTFiXS3fm55557nEjKo3kUbV@lWcSLmEFXRor5izMnWoQKAjmeQg@GjY@r1c9Zq/j@8PBttDhdLcj2ByH9Hhlzkd@vp@XMd@/KO9@dlbHvylL6blxmvluUhe9mlPS7PeJTSv0@NvkumbTI5HRyUpL@weSUUoJH1J2c9F9v6ctJDQ9c2Qvku2bH@asy13EqjMz9kkqz@fNaKrDKwuW/uDMnzTRIDHXAlBKKRCLLNVRru0uW5@Gc0Uec025HCIBuF@qqCas6y2LeAcV0oTJodjYV5TJMM0Lh0QF85BincZYRSY@a095xBwrEtN4HGoTJTMMcgwpccVp1eCAL3QFzGeAq1oF9dShHamW7FcsLrm1s9kiSnGkPRKFx7Fwv7In4xSIt1Lg1taOQtVeRB5FYypQzIj34ejG8DD7djM4HAyhtdju6@uDBWzvQBrsJx9RSpQmQA8Xozoek8jQhuA2iPWgYokqaghCVVO3wJm7Dm3yS4e3ucdo5NXGCDcSIXxunKnPmTPM0Y8TeSpp51ifaQUxz5/lO1JoCnhnHyOEkO6xZ7fbGs50D7J5FRDEPrm8Hg5rRjwK8CEJ3aZ6umcmOq7d204PWHqkZWRN30Zw9MS9OD3rW28vh8GYYXN98OR9dfKZQ29a4NE61oYFLMZ6zp/pViFlVfyLePEeMVIGAZ4hkpVLNyH93anrGXGFsrPo21n3FGCqmT/93/aM5m61epLkTZkIvmHI45w4X3InDGL8ZftJZiZUjRGrqXAoZi5gbCEL57yjh4TzfHnHj/R8 "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XZBBb9wgEIXv/hUEIS2DHDarRjksQVy6qSJVSeXmFifIu2ZjS6wh4FWq1v3t2/H2lsOThjcfbwZiF0@3JnaRsEQ0oUtKJInJvdnkom92ji@WUhhru8aPdhcOsfcu1bwGVVfLvCjJArVH0765GRhGN4yZW3t3/31jLZRkBRiJwarYh8RZr68U83qPeOY/n77eP4CCP6Tfc@af85i8G7CCy9WL1rQeKCCcj1vsoF1elZcrUGe6B7frwowogqkrVRDCDvq8/KEZdx1nqcQkRWbu/6N8k0frUsJF4EL/qDbf7MOj3VTVY2XoZvbXhK45Oxj6lI5uTfBE7xqfsaQwTzhnUeap@vvpUzio0yvnRvNnH/Kv3y/TVor36V2K7dRKEacoRTsNUhynoxQDcHOruQQAafCSFLz@wuub@nri5qK@AeDYAlFfG3Y6jV2fi2YIY@dS4b0vfPBF27SoLSoWH@GjCKGffR9DbEPrZwRR/w8 "PHP – Try It Online") - PCRE2
**[Try it online!](https://tio.run/##bVFRb9MwEH7Pr7hGSLMNeENMe1iIIiGxJ0CI8rYMyYmd1p1jp7GzljX97eXcBsRQHyz7vvvuu7vPK/Ek3q7k40G3nesDrDDm2nGWwb/IELQ5i/VqobYx0w2V0TXURngPX4S2sJsgH0TA68lpCS0myDz02i5A9At//0AhLHu38fBpW6suaIeFCcCdNgqa3KrN8UlSXjupOOZTmn0cmkb1Sn5XQqoeqiPtJUj@VE5hQ2k29fVvQrZZRn1CfF7hCkJ@1lYRSme5HYyhuiGeq/UgjCfpJWMspXT3knpSICScFdihQvirgAKXqFAh7zHzr/OL0l7EO2T7E7b/JkJQvYU@n164bdvFBp5m6Ma8Ftbiptp2Q4Ac4nITRua/fFAt15bi99gAOr/KYNrvyOdL4b@qbcDxYAc4mZ7lV3Qqc5jv0JZgLIkC@bvYDzuevDLY7CRiUWFaHb831Escp8Vsz9tTRAxm/ldtSMsbbSWhUED6ox/ULUAKt5DeoTUYpGeKotJ@v0@i84efhBQ5uTfOb58fxoqz9bjmrBolZ93YcSZHy9kwDpxZSooPOeGUUl5gEWekfE/Km/J6JMWsvKEUHaCUldfFq0P8k0NYap8I6wKOnxhjEuNMIoXEU@Hpko3bJM7piJvOddJJEylINb8B "Java (JDK) – Try It Online") - Java**
[Try it online!](https://tio.run/##dY7BasMwEETv@grVCLwSjWhpyMGpcaDQW2@9xSk40aYWbCVFtnFInG93lVNPPQwLb2aHCX7E2LVINItYbiN@43lXFA5H2OTzF0BVwpZ8d77spr1Wp@mk1X4yWoUpaGUmp9UwDVo5CdVrCVpKqav0pBXUL1Cv6uUE1UO9khKSJVW9rMScbx6zN/8TLKHJ5Fpcyqf10UdsDi0I4tZxYV0YenllnNsjiIu8jtH2uGh9199S/jkZf4QvnE@LyTrkmQB75CCi/mj6Q4tdapSSX/PPOGDBeX7jSB0m8N6kWyQgs3/bBLHb3Le2Y43zfYuREREjT8w0JmmfFNjoR@a9vXMKPhhv6B5JUfoF "PowerShell – Try It Online") - .NET
[Answer]
# APL+WIN, ~~44~~ 37 bytes
-7 bytes thanks to OVS
Prompts for text
```
t≡⌽'qpluodbsnxz '['bdlnopqsuxz'⍳t←,⎕]
```
[Try it online! Thanks to Dyalog Classic APL](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tf8mjzoWPevaqFxbklOanJBXnVVQpqEerJ6Xk5OUXFBaXVlSpP@rdXALUoAPUGfsfqInrfxqXeklGZrE6F5CRmJdfkpFaBGbn5ORA6HwInZKYAqWToHQBmC7PLwfT@fmZMPU5BfkFKfkpOSCtAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Â.•1⋃•©Â‡A®.•(ÖÆ•«ммQ
```
[Try it online](https://tio.run/##yy9OTMpM/f//cJPeo4ZFhocXPWrYeWwSkHlo5eGmRw0LHQ@tA0loHJ52uA0kuvrCngt7Av//z8nPySnIL0jJT8kBMgE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w016jxoWGR5e9Khh57FJQOahlYebHjUsdDy0DiShcXja4TaQ6OoLey7sCfyv8z9aqSQjs1hJR0EpMS@/JCO1CMTMyckBU/lgKiUxBUIlQagCEFWeXw6i8vMzoSpzCvILUvJTcqCaCgoKUpRiAQ).
A port of [*@Steffan*'s Vyxal answer](https://codegolf.stackexchange.com/a/248077/52210) is 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) as well:
```
ÂA.•1ηλ¥nô[˜ζÕPζeí=Ω•‡Q
```
[Try it online](https://tio.run/##yy9OTMpM/f//cJOj3qOGRYbntp/bfWhp3uEt0afnnNt2eGrAuW2ph9fanlsJlHzUsDDw//@c/JycgvyClPyUHCATAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w02Oeo8aFhme235u96GleYe3RJ@ec27b4akB57alHl5re24lUPJRw8LA/zr/o5VKMjKLlXQUlBLz8ksyUotAzJycHDCVD6ZSElMgVBKEKgBR5fnlICo/PxOqMqcgvyAlPyUHqqmgoCBFKRYA).
**Explanation:**
```
 # Bifurcate the (implicit) input-string, short for Duplicate & Reverse
.•1⋃• # Push the compressed string "bdunpq"
© # Store it in variable `®` (without popping)
 # Bifurcate it
‡ # Transliterate all "bdunpq" to "qpnudb"
A # Push the lowercase alphabet
® # Push string `®`
.•(ÖÆ•« # Append compressed string "losxz"
м # Remove all those characters from the alphabet: "acefghijkmrtvwy"
м # Remove all those characters from the modified input
Q # Check if it's equal to the input-string
# (after which the result is output implicitly)
 # Bifurcate the (implicit) input-string, short for Duplicate & Reverse
A # Push the lowercase alphabet "abcdefghijklmnopqrstuvwxyz"
.•1ηλ¥nô[˜ζÕPζeí=Ω•
# Push the compressed string "bqapaaaaaaalauodbasanaaxaz"
‡ # Transliterate the alphabet to these characters
Q # Check if it's equal to the input-string
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•1⋃•` is `"bdunpq"`; `.•(ÖÆ•` is `"losxz"`; and `.•1ηλ¥nô[˜ζÕPζeí=Ω•` is `"bqapaaaaaaalauodbasanaaxaz"`.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 70 bytes
```
s->Vecrev(s)==[Vec("`q`p```````l`uodb`s`n``x`z")[i-96]|i<-Vecsmall(s)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY1BDoIwEEWv0nQFCd0aTYSlR3BDiFMsSJORjhQEjTdxQ2KMZ_I2ttTZvDfJ_zPPD8lOH040v2qWvoe-FuvvzopsXx276hrZOE1z5xGHCxCEQRiMKsFCCzDBnce5FptV8dBb4aL2LBFdsfhfmyQR3iLLRMao023vlPuFs9rF4oTlvG-05QnjsjV9U3VeEXGBWaCkCigDyGM0o4cx-p9EMqSMQl8q4vB_ngN_)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 835 bytes
I never was very good at golf...
```
#include "string.h"
#include "stdio.h"
char z[8][2] = {{'b','q'},{'d','p'},{'n','u'},{'l','l'},{'o','o'},{'s','s'},{'x','x'},{'z','z'},};
void main(int argc, char *argv[])
{
int n = argc-1;
for (int x = 1; x <= n; x++){
int p = 0;
int l = strlen(argv[x]);
char r[l+1];
for (int i = l; i > 0; i--){
char c = argv[x][i-1];
int v = 0;
for (int a = 0; a < 8; a++){
if (c == z[a][0]){
c = z[a][1];
v = 1;
} else if (c == z[a][1]){
c = z[a][0];
v = 1;
}
}
if (!v) {p = 1;}
r[l-i] = c;
}
r[strlen(argv[x])+1] = '\0';
printf("%d\n", memcmp(r, argv[x], l) == 0 && p == 0);
}
}
```
[Try it online!](https://tio.run/##lVLbboMwDH3nKzymFVhhonuqRLsfoTzQhLaR0iQDSlER35456YXSbZoWKfLBPvZxsEm0JUTrZyYIP9AC3Koumdi@7Vzn3keZNC6yy0s4pfMsfc9gCV3nrb3Q@/T6sPMoImWRQHSwiCPiFklE0qIKUWVRi6i16ITohKhPnEYyCvucCZ@JGvJyS0Kwsq@ImzQLnM4BPCYqsAfDiGaJ9W1kCTatxcAsQbNYgkA7nQbnrGumQkKcjFwcXfh4XgjfKrVZMBBsB2XKp7NscN7kGKbyBM0HFgUWRXdqt2xybtYUTll0X@faQTNuaiSR2xiaBczRjB50q7EBH1WWOKE8S@PsB4rtBi6Mxx6up7F/71uoh4JXxYPK7E@V@J8qzu9fRvqpCaBTNnccxOlEzGwlGYoOjDJ9mC1OErneKvYGusLVrze@@0JXwg1hX@zJXvlleJ1bCDwwL49hMjErhOiyI73Ta63rHat0LmS9K0rNOddcck1zineNV@mjPGopmfFzJRWVlBuKUopqJekX "C (gcc) – Try It Online")
**Original, much more readable version:**
# [C (gcc)](https://gcc.gnu.org/), 1238 bytes
```
#include "string.h"
#include "stdio.h"
char letters_to_rotate[8][2] = {
{'b', 'q'},
{'d', 'p'},
{'n', 'u'},
{'l', 'l'},
{'o', 'o'},
{'s', 's'},
{'x', 'x'},
{'z', 'z'},
};
void main(int argc, char *argv[])
{
int num_inputs = argc-1;
for (int x = 1; x <= num_inputs; x++){
int invalid_char_present = 0;
int inputlength = strlen(argv[x]);
char rotated[inputlength+1];
for (int i = inputlength; i > 0; i--){
char c = argv[x][i-1];
int valid_char = 0;
for (int a = 0; a < 8; a++){
if (c == letters_to_rotate[a][0]){
c = letters_to_rotate[a][1];
valid_char = 1;
}
else if (c == letters_to_rotate[a][1]){
c = letters_to_rotate[a][0];
valid_char = 1;
}
}
if (!valid_char) {invalid_char_present = 1;}
rotated[inputlength-i] = c;
}
rotated[strlen(argv[x])+1] = '\0';
if (memcmp(rotated, argv[x], inputlength) == 0 && invalid_char_present == 0){
printf("%s: True\n", argv[x]);
} else {
printf("%s: False\n", argv[x]);
}
}
}
```
[Try it online!](https://tio.run/##rVTBjpswEL3zFW6qLtBABT2tyqbHfkFvLEJe7ARLxnbBZKON@HZ3jJsA2aCqUpHAj5l5M8/DmCo@VJUxH5moeE8o2nS6ZeLwpd54cxth0pq8qsYt4lRr2nallmUrNdY0fyzyrwXaobN39l/8CPm//CECTCxWDguLe4e5xdxhabF0uLO4c/hk8cnhN4vfLB4yzztKRlCDmQiY0Ai3hypCo7DPgI95EXpnD8FlvaJvSiZUrzuQZ0PjNBude9mikX8CR5rB8rSbRYNhuw1dnksuJo6YM1LaWqVqaUfBuENJdhMFfE7FQdfghHYCDkZhpyKcQkfBrn0kn3G2aTEFXUUySDULysDwHQojFsczkde8ldusLZmzeJ7xonLayXIHi6p49MHyhB5hWTTkmmyPAii3uzMVuMiT4g5llIlWGLdiL9dCcPo@Znhnobyjf5GX/rO85L/IW75ZjR@mBCE6r0xami2Jd8YnZvYcVpOAiXGJvhlJGDhg@M@JP5tjUNTQpmpU8IcVXeYpms9haDuboIeHlbMBzpsGK/i76H2w@dR9Qz/bnj6LzTX17HQM7uutc39g8K@RPfccjDG6Zp3BQuqatoZzbrjkhmAC9wvcyrzKVyMls3aupCKScBuilCJGSfIb "C (gcc) – Try It Online")
[Answer]
# Rust, ~~135~~ 130 bytes
```
let m="bqdpnulloossxxzz";let f=|s:&str|!s.chars().zip(s.chars().rev()).any(|(a,b)|m.find(a).or(Some(99))!=m.rfind(b).map(|x|x^1));
```
I'm pretty new to golfing so I hope I did it alright.
I'm still pretty unhappy with how verbose the code to fix the options is.
[Answer]
# T-SQL, 84 bytes
Returns 1 when palindrome, otherwise 0
```
PRINT IIF(translate(@,'bqdpnu','qbpdun')<>reverse(@)or
@ like'%[^qbpdunolsxz]%',0,1)
```
**[Try it online](https://dbfiddle.uk/?rdbms=sqlserver_2019l&fiddle=4fa0ffad605dfc6f9c0422e1c5df6020)**
[Answer]
# Oracle SQL, 68 bytes
```
o=reverse(translate(o,'bdlnopqsuxzacefghijkmnrstuvwy','qpluodbsnxz'))
```
Tested with
```
with w as (
select column_value o
from
ku$_vcnt(
'this',
'another',
'lll',
'lol',
'dad',
'dab',
'dap',
'wow',
'ooi',
'lollpopdodllol'
))
select o from w
where
o=reverse(translate(o,'bdlnopqsuxzacefghijkmnrstuvwy','qpluodbsnxz'));
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 71 bytes
```
f()(a=bdlnopqsuxz;[ "`echo $1|tr $a qpluodbsnxz|tr -dc $a|rev`" = $1 ])
```
[Try it online!](https://tio.run/##S0oszvj/P01DUyPRNiklJy@/oLC4tKLKOlpBKSE1OSNfQcWwpqRIQSVRobAgpzQ/Jak4r6IKJKKbkgwUrSlKLUtQUrAFKlOI1fyfBqT//8/JzwEA "Bash – Try It Online")
---
Using a more compact tr command as inspired by [pajonk's answer](https://codegolf.stackexchange.com/a/248085/112877):
# [Bash](https://www.gnu.org/software/bash/), 58 bytes
```
f()([ "`echo $1|tr a-y AqCpE-KlMuodbRsTnVWxY|rev`" = $1 ])
```
[Try it online!](https://tio.run/##S0oszvj/P01DUyNaQSkhNTkjX0HFsKakSCFRt1LBsdC5wFXXO8e3ND8lKag4JC8svCKypii1LEFJwRaoTiFW838akP7/Pyc/BwA "Bash – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~72~~ ~~68~~ 51 bytes
```
!(($s=$args)|?{'dbqspn x z l uo'[$_%16]-$s[--$i]})
```
[Try it online!](https://tio.run/##Lc5BCoMwEAXQfU4xhbRRqItuuhN7DxGJJG0CgxMTi6Xq2VOjnc37i/9hHE3aB6MRI39CCXM8ZRkPJZf@FfKlmoXqhuB6gA98AeFNoubt@XZvCh7qouC2WfO4MsbEaGwQVyZkT6PRPkVE3KEdJdVBd@ASE00JIvtvoiOnSGEawQIVzAy2u2zvPVq2xh8 "PowerShell – Try It Online")
The script assumes an input does not contains space chars. I guess It is good constraint for a word.
The script takes a [splatted](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting) string and performs double check for each symbol from the string.
The algorithm for the hash string `dbqspn x z l uo` is: Place an ambigram char at the position (ASCII % 16).
| Source char | ASCII | % 16 | Ambigram char |
| --- | --- | --- | --- |
| p | 112 | 0 | d |
| q | 113 | 1 | b |
| b | 98 | 2 | q |
| s | 115 | 3 | s |
| d | 100 | 4 | p |
| u | 117 | 5 | n |
| x | 120 | 8 | x |
| z | 122 | 10 | z |
| l | 108 | 12 | l |
| n | 110 | 14 | u |
| o | 111 | 15 | o |
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 56 bytes
```
$
¶$`
T`b\dl-qsuxzl`q\p\l_u\o\dbsnxz_`^.+
+`(.)¶\1
¶
^¶$
```
[Try it online!](https://tio.run/##FYtBCoMwEADv@w4LFqnQV/QDPS66CSsYWLLRRBQf5gP8WLo9DAwDs04lRFcf7YdqA/fVEHzJI8trydtxCi2YUMYNFdnneJwjDX0HHbX9877wbQsMttVa5pDBRS3ztIKIgKgAOza8kWDXHVTDv0vSxMpi@gM "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
$
¶$`
```
Duplicate the input.
```
T`b\dl-qsuxzl`q\p\l_u\o\dbsnxz_`^.+
```
Individually rotate the characters of the first copy, but delete characters that aren't rotatable. (`d`, `l`, `o` and `p` need to be quoted when not used as part of a range.)
```
+`(.)¶\1
¶
```
Compare the last character of the first copy with the first character of the second, removing both if they are equal. Repeat until either they don't match or there aren't any left.
```
^¶$
```
If there aren't any left then the original input was a rotational palindrome.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 30 bytes
```
{x~|v(|v:"lnopqsxzxsbdoul")?x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6quqKsp06gps1LKycsvKCyuqKooTkrJL81R0rSvqOXiSlNQykjNyclXArHK88vBdE5+DozOKcgvSMlPyQEJAQA7cBqH)
I took the shortest ambigram which contained all the possible characters and made it into a lookup string: locate where each character of the input is in the string, and then take one character from the reversed version to construct the rotated character. Finally, reverse it and compare against the original input.
[Answer]
# JavaScript, 88 bytes
```
s=>s==[...s].map(x=>'losxz'.includes(x)?x:(r='budpnq')[5-r.indexOf(x)]).reverse().join``
```
[Try it online!](https://tio.run/##VVBdb8IgFH3vr@BhCZBVuixblmioT3veD1CTYqETg1wGVJsZf3tHrbHuiXPuPR837MVRhNprF2cWpOob3gdeBs5XjLGwYQfhSMdLbCB0v5hpW5tWqkA6uuzmxHO8baWzP5iu3mc@raXqvpq03VDm1VH5oAhle9C2qvpFllVZ3OmAeIkaYYLKhIW4U34aGGMGEn2bMExYCjmJpNg@EjeRE5wmAqAfgsEYB06CNI@5FYteH9KNwRkdCV5bTFkD/lPUOxJViIPynCFUg01klSNtXRtzpDqn6rhBHA2q9E8xGQrCnungGN6CLu4@aGNyJXFDrv6HlRMhfchdwVExHFawIZaMLXc1GMUMfJNE0WhcIrxuXz9e3jGaj/Ctxvl1Px56hXhW3oZjTf4vYLBWtyol0dN5hBdaJVnqvtBF/wc "JavaScript (Node.js) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 23 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ç╥Vⁿ2n♣¿æ∞╙♥>5H╜ÜN¡¼}╝î
```
[Run and debug it](https://staxlang.xyz/#p=80d256fc326e05a891ecd3033e3548bd9a4eadac7dbc8c&i=this%0Aanother%0Alll%0Alol%0Adad%0Adab%0Adap%0Awow%0Aooi%0Alollpopdodllol&a=1&m=2)
[Answer]
# [Perl 5](https://www.perl.org/) `-pal`, 52 bytes
```
y/bqdpunloszx//dc;y/bqdpun/qbpdnu/;$_="@F"eq reverse
```
[Try it online!](https://tio.run/##Nco9DsIwDEDh3adAFWtJGTpVSExsnAEl2FIjWbGT9Ac4PKYgMbzl01Mq3Js9Xcioc2Kpr4dzeB/@4nJQTLMb9rdTc740lHeFFiqVzKYxVvBJppEKMDOwMKDHrbClsMoKIvHrrKIoyL9F9C06RUnVWvVs7bU/dMfuAw "Perl 5 – Try It Online")
[Answer]
# [Scala](https://www.scala-lang.org/), 118 bytes
Golfed version. [Try it online!](https://tio.run/##ldDBasMwDAbge59CBAr2xe1xBDLoxo47lZ5KD06sZB6O7Vjquq702TPntnVkUB2Fvl9C1Ginx1C/Y8Pwqq2Hy2iwhVZQucVh/3RmPMiKVK@jsNWjbUXhAn1@FaoJnjMgYRWH5zedpLSAjrAw9bCO/rjOM7m9YWGXDzIPTWFSJfzARKhI9/jisEfPJEiOANPiPkcKnToqYZOSPu@3nKzvDrKEnbcMFVwWkCvmLjsv8j31UKgOeUonKeF3rVbA6Yi3xgU3j@aNiyGaYNxfPmOMNv/uaXV@2C06hdP9CIO/H8UY5@/7ga6L6/gN)
```
def f(s:Seq[Byte])=s.map(i=>if("losxz".contains(i.toChar))i else"dbq0pnu0".charAt(i%8).toByte).reverse.sameElements(s)
```
Ungolfed version.
```
object Main {
def f(s: Array[Byte]): Boolean = {
val result = s.map(i => if ("losxz".contains(i.toChar)) i else "dbq0pnu0".charAt(i % 8).toByte).reverse
result.sameElements(s)
}
def main(args: Array[String]): Unit = {
println(f("bq".getBytes)) // true
println(f("lol".getBytes)) // true
println(f("lollpopdodllol".getBytes)) // true
println(f("dad".getBytes)) // false
println(f("wow".getBytes)) // false
println(f("eon".getBytes)) // false
println(f("pppd".getBytes)) // false
}
}
```
[Answer]
# [Zsh](https://www.zsh.org/), 41 bytes
```
<<<${1//$(tr "bdnpqu" "qpudbn"<<<$1|rev)}
```
[Try it online!](https://tio.run/##qyrO@P/fxsZGpdpQX19Fo6RIQSkpJa@gsFRJQamwoDQlKU8JJGtYU5Rapln7////nPycnIL8gpT8lJycfAA "Zsh – Try It Online")
Truthy/ambigram: returns empty string. Otherwise, the result is non-empty.
] |
[Question]
[
Given a non-negative integer, return the absolute difference between the sum of its even digits and the sum of its odd digits.
## Default Rules
* Standard Loopholes apply.
* You can take input and provide output by any standard Input / Output method.
* You may take input as a String, as an Integer or as a list of digits.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes **in every language** wins!
## Test Cases
```
Input ~> Output
0 ~> 0 (|0-0| = 0)
1 ~> 1 (|1-0| = 1)
12 ~> 1 (|2-1| = 1)
333 ~> 9 (|0-(3+3+3)| = 9)
459 ~> 10 (|4-(5+9)| = 10)
2469 ~> 3 (|(2+4+6)-9| = 3)
1234 ~> 2 (|(2+4)-(1+3)| = 2)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
-*√¶.¬πA
```
[Try it online!](https://tio.run/##y0rNyan8/19X6/AyvUM7Hf8f3eNyuF3lUdMa9///DXUUDHQUDI10FIyNjXUUTEwtdRSMTMwsQWLGJgA "Jelly – Try It Online")
### How it works
```
-*√¶.¬πA Main link. Argument: A (digit array)
-* Raise -1 to A's digits, yielding 1 for even digits and -1 for odd ones.
¬π Identity; yield A.
√¶. Take the dot product of the units and the digits.
A Apply absolute value.
```
[Answer]
# SHENZHEN I/O MCxxxx scripts, 197 (126+71) bytes
Chip 1 (MC6000):
* x0: Input as list
* x2: Chip 2 x1
* x3: MC4010
```
mov 0 dat
j:
mov x0 acc
mov 70 x3
mov -1 x3
mov acc x3
mul x3
mov acc x2
mov dat acc
add 1
tlt acc 3
mov acc dat
+jmp j
slx x0
```
Chip 2 (MC4000):
* p0: Output
* x0: MC4010
* x1: Chip 1 x2
```
mov x1 acc
add x1
add x1
mov 30 x0
mov 0 x0
mov acc x0
mov x0 p0
slx x1
```
[Answer]
## Python 2, 39 bytes
Takes integer as list. [Try it online](https://tio.run/##K6gsycjPM/rvYxvzPycxNyklUcHRKjGpWKO4NFdDQ9dQU0srUytTIS2/SCFTITNPwVFT8z@cE22gY6hjpGNopGNsbKxjYmqpY2RiZgnkG5vEWnEpAEFBUWZeiYKPRm5igQaQpZOQmQA0AAA)
```
lambda A:abs(sum((-1)**i*i for i in A))
```
-3 bytes thanks to @Mr.Xcoder
-1 byte thanks to @ovs
[Answer]
# Mathematica, 20 bytes
```
Abs@Tr[(-1)^(g=#)g]&
```
takes as input a list of digits
special thanx to @LLlAMnYP for letting me know about the "new rules"
[Answer]
# TI-Basic, ~~18~~ 9 bytes
```
abs(sum((-1)^AnsAns
```
**Explanation**
Multiplies each digit in the list by -1 to its power, negating each odd digit, before summing them.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~59~~ ~~58~~ 57 bytes
```
i;f(char*v){for(i=0;*v;v++)i+=*v%2?*v-48:48-*v;v=abs(i);}
```
[Try it online!](https://tio.run/##dctBC8IgGMbx@z7FEAa@OmGpxUqkL9LFDOs9zMLCy9hnt1XXvD38fzxeXL0vBU2g/uYSyzCHe6JoB8OyyZwDcstyJ48sCz0e9Cg@3brzkyKYpUwOI/V9hu99tblp20fC@AqUdJdTJP06BgJg/sGmCrImSqka6e2@RlLvftYs5Q0 "C (gcc) – Try It Online")
[Answer]
## R, 30 29 bytes
```
abs(sum((d=scan())-2*d*d%%2))
```
`d = scan()` takes the input number by one digit after the other.
-1 byte thanks to @Giuseppe!
[Answer]
# C#, 57 bytes
```
namespace System.Linq{i=>Math.Abs(i.Sum(n=>n%2<1?n:-n))}
```
Takes input as `i` and sums the integers by turning the odds to negative.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 bytes
```
x_*JpZÃa
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=eF8qSnBaw2E=&input=WzEsMiwzLDRd)
### Explanation
```
x_ *JpZÃ a
UxZ{Z*JpZ} a
Implicit: U = list of digits
UxZ{ } Take the sum of each item Z in U mapped through the following function:
JpZ Return (-1) ** Z
Z* times Z. This gives Z if even, -Z if odd.
a Take the absolute value of the result.
Implicit: output result of last expression
```
[Answer]
# [Neim](https://github.com/okx-code/Neim), 7 bytes
```
ŒìD·õÉŒûùêç}ùê¨
```
Explanation:
```
Γ Apply the following to each element in the input array
D Duplicate
·õÉ Modulo 2, then perform logical NOT
Ξ If truthy, then:
ùêç Multiply by -1
} Close all currently running loops/conditionals etc
ùê¨ Sum the resulting array
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
≠0ṁṠ!¡_
```
[Try it online!](https://tio.run/##yygtzv7//1HnAoOHOxsf7lygeGhh/P///6MNdYx0jHVMYgE "Husk – Try It Online")
Takes a list of digits as input.
Still missing an "abs" builtin, but a good result all the same :)
### Explanation
`·π†!¬°_` is a function that takes a number `n` and then applies `n-1` times the function `_` (negation) to `n`. This results in `n` for odd `n` or `-n` for even `n`.
`ṁ` applies a function to each element of a list and sums the results.
`≠0` returns the absolute difference between a number and 0.
[Answer]
# APL, 8 bytes
```
|⊢+.ׯ1*⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhJpHXYu09Q5PP7TeUAvIBAoqGHClKRiCsIIRkDQGQSBtomCqYAmkjYAsMwVLAA)
**How?**
`¯1*⊢` - -1n for `n` in `⍵`
[`4 5 9` → `1 ¯1 ¯1`]
`⊢+.×` - verctorized multiplication with `o`, then sum
[`+/ 4 5 9 × 1 ¯1 ¯1` → `+/ 4 ¯5 ¯9` → `¯10`]
`|` - absolute value
[Answer]
# Mathematica, 67 bytes
```
(s=#;Abs[Subtract@@(Tr@Select[IntegerDigits@s,#]&/@{EvenQ,OddQ})])&
```
[Answer]
## JavaScript (ES6), ~~43~~ 38 bytes
Takes input as ~~a string~~ an array of digits.
```
a=>a.map(d=>s+=d&1?d:-d,s=0)&&s>0?s:-s
```
### Test cases
```
let f =
a=>a.map(d=>s+=d&1?d:-d,s=0)&&s>0?s:-s
console.log(f([1])) // ~> 1 ( |1-0| = 1)
console.log(f([0])) // ~> 0 ( |0-0| = 0)
console.log(f([1,2])) // ~> 1 ( |1-2| = 1)
console.log(f([4,5,9])) // ~> 10 ( |4-(5+9)| = 10)
console.log(f([2,4,6,9])) // ~> 3 ( |(2+4+6)-9| = 3)
console.log(f([3,3,3])) // ~> 9 ( |(3+3+3)-0| = 9)
```
[Answer]
***EDIT: A more golf-centered approach:***
## EXCEL, 42 36 29 bytes
Saved 6 bytes thanks to Magic Octopus Urn
Saved 7 bytes by using Dennis' -1^ approach (which, I just learned, works on arrays in excel)
```
=ABS(SUMPRODUCT(A:A,-1^A:A))
```
Takes a list of integers in A column for input. Probably can be golfed further, or by using the string version, taking a string in A1 for input.
## EXCEL, 256 bytes
```
=ABS(LEN(SUBSTITUTE(A1,1,""))-2*LEN(SUBSTITUTE(A1,2,""))+3*LEN(SUBSTITUTE(A1,3,""))-4*LEN(SUBSTITUTE(A1,4,""))+5*LEN(SUBSTITUTE(A1,5,""))-6*LEN(SUBSTITUTE(A1,6,""))+7*LEN(SUBSTITUTE(A1,7,""))-8*LEN(SUBSTITUTE(A1,8,""))+9*LEN(SUBSTITUTE(A1,9,""))-5*LEN(A1))
```
[](https://i.stack.imgur.com/ONy3a.png)
[Answer]
# [Julia 0.5](http://julialang.org/), 19 bytes
```
!x=(-1).^x‚ãÖx|>abs
```
[Try it online!](https://tio.run/##yyrNyUw0/f9fscJWQ9dQUy@u4lF3a0WNXWJS8f@0/CKFPIXMPAUNQx0DHUMjHWNjYx0TU0sdIxMzSyDf2ESTi9OhoCgzryRNQ0nVpFRB105B1ag0Jk9JRyFPR0ExJTM9s6RYI09Tkys1L@U/AA "Julia 0.5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for the -1 power trick. Takes input as a list of digits
```
®sm*OÄ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0LriXC3/wy3//0eb6CiY6ihYxgIA "05AB1E – Try It Online")
### Explanation
```
®sm*OÄ Example [4, 5, 9]
® # Push -1 % STACK: -1
sm # Take -1 to the power of every number % STACK: [1, -1, -1]
in the input list
* # Multiply with original input % Multiply [1, -1, -1] with [4, 5, 9] results in STACK: [4, -5, -9]
O # Sum them all together % STACK: -10
Ä # Absolute value % STACK: 10
# Implicit print
```
[Answer]
# PHP, 51 bytes
```
while(~$n=$argn[$i++])$s+=$n&1?$n:-$n;echo abs($s);
```
adds digit to `$s` if odd, subtracts if even. Run as pipe with `-nR`.
or
```
while(~$n=$argn[$i++])$s+=(-1)**$n*$n;echo abs($s);
```
using Dennis´ `-1` power trick.
[Answer]
# [PHP](https://php.net/), 54 bytes
```
for(;~$n=$argn[$i++];)${eo[$n&1]}+=$n;echo abs($e-$o);
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkYWhgaGJkrGT9Py2/SMO6TiXPFiwTrZKprR1rralSnZofrZKnZhhbq22rkmedmpyRr5CYVKyhkqqrkq9p/f8/AA "PHP – Try It Online")
# [PHP](https://php.net/), 57 bytes
store the even and odd sums in an array
```
for(;~$n=$argn[$i++];)$r[$n&1]+=$n;echo abs($r[0]-$r[1]);
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkaGBoYmSsZP0/Lb9Iw7pOJc8WLBGtkqmtHWutqVIUrZKnZhirbauSZ52anJGvkJhUrAEUNYjVBZKGsZrW//8DAA "PHP – Try It Online")
# [PHP](https://php.net/), 57 bytes
store the even and odd sums in two variables
```
for(;~$n=$argn[$i++];)$n&1?$o+=$n:$e+=$n;echo abs($e-$o);
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkaGBoYmSsZP0/Lb9Iw7pOJc8WLBGtkqmtHWutqZKnZmivkq9tq5JnpZIKoqxTkzPyFRKTijVUUnVV8jWt//8HAA "PHP – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 47 42 39 38 26 25 bytes
*-1 thanks to nimi*
*-12 thanks to Bruce*
*-1 thanks to xnor*
```
abs.sum.map(\x->x*(-1)^x)
```
[Try it online!](https://tio.run/##HclBC4IwAMXxe5/iMS9buJHOAg8KEuGlwkuntFg0SdIhmiBEn32tDu93eP@HGp@6be2be9hnx/yU5TtsiwIe/yzqpLTqNopx6kSnelrOPJ2XlAfsMjPbqcYggQuHK2hpwFP0Q2NeoMZHDeoK6KDVXfTToBkMYwxnsiI@CX4LHVJKZ7SOnWG0if@/jEhlvw "Haskell – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~18~~ ~~15~~ 12 bytes
```
#!+/{x-:/x}'
```
[Try it online!](https://ngn.codeberg.page/k#eJw1jctOwzAQRffzFYNAIlFw/UyRY8GeFR9QVSKkSVu1jUvsoFR9fDt2GjSLmTnnetwUjw8ZPQ+koMP1GcAX56fF6dYVDSIO5svuTPLVlNu9GczJdOnyCn7xwgxbxs4Nj52juA8SQxkdR4U5asPHnECF87DJKRxSyoglAIWN90dXUFrZVb22+2bmfFnt6qHalO26nlX2QH/62vmtbR3lkr/mOXX9t+/KypPDidjVypGms4e41L916wA+2mPv8faOn70PEwCLC8Pkwgi74BuyFHhEPCB+Rzwg8c8E4ROTUkaox7eJzEKlUekUVK7HfLyrSJJnejQ8HBdqPjoZVCIylc1ToqOU8RepohOTS0nCp6MiBfgDYCRoKQ==)
Takes input as a list of digits.
* `{x-:/x}'` negate each digit of the input that many times (e.g., negate `4` four times, and `9` nine times). this makes odd digits negative, leaving even digits positive
* `+/` take the sum
* `#!` take the absolute value (and implicitly return)
[Answer]
# [Perl 6](http://perl6.org/), 28 bytes
```
{abs sum $_ Z*.map(*%2*2-1)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OjGpWKG4NFdBJV4hSksvN7FAQ0vVSMtI11Cz9r@1QnFipUKaho2hgpGCsYKJnab1fwA "Perl 6 – Try It Online")
Takes a list of digits as input.
* `$_` is the input argument.
* `.map(* % 2 * 2 - 1)` maps each digit to either `1` or `-1` depending on whether the digit is odd or even, respectively.
* `Z*` zips the original list of digits with the even/odd list using multiplication.
[Answer]
# [Braingolf](https://github.com/gunnerwolf/braingolf), 18 bytes
```
{.2%?M|}&+v&+c-!s*
```
[Try it online!](https://tio.run/##SypKzMxLz89J@/@/Ws9I1d63plZNu0xNO1lXsVjr////hv@N/hv/N/lvCgA "Braingolf – Try It Online")
Takes input as a list of digits
## Explanation
```
{.2%?M|}&+v&+c-!s* Implicit input from commandline args
{......} Foreach loop, runs on each item in the stack..
.2% ..Parity check, push 1 if odd, 0 if even
? ..If last item != 0 (pops last item)..
M ....Move last item to next stack
| ..Endif
&+ Sum entire stack
v&+ Switch to next stack and sum entire stack
c- Collapse into stack1 and subtract
!s Sign check, push 1 if last item is positive, -1 if last item is
negative, 0 if last item is 0
* Multiply last item by sign, gets absolute value
Implicit output
```
[Answer]
# R, ~~72~~ 43 bytes
```
b=(d=scan())%%2<1;abs(sum(d[b])-sum(d[!b]))
```
First, `d = scan()` takes the number as input, one digit after the other (thanks to @Giuseppe comment !)
Then, `b = d %% 2 <1` associates to `b` a `TRUE` or `FALSE` value at each index depending on the digits' parity.
Therefore, `b` values are `TRUE` for even numbers, and `!b` are `TRUE` for odd values.
Finaly, `abs(sum(d[b]) - sum(d[!b]))` does the job.
[Answer]
# Bash ~~141~~ ~~139~~ 99 Bytes
```
while read -n1 a; do
[ $[a%2] = 0 ]&&e=$[e+a]||o=$[o+a]
done
(($[e-o]>0))&&echo $[e-o]||echo $[o-e]
```
[Try it online!](https://tio.run/##S0oszvj/vzwjMydVoSg1MUVBN89QIdFaISWfK1pBJTpR1ShWwVbBQCFWTS3VViU6VTsxtqYmH8jKB7K4UvLzUrk0NIDiuvmxdgaamkBVyRn5ChCBmhooJ183Nfb/fzMjY0sA)
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 32 bytes
```
00\~:00@(?$-n;
(?\c%:0@2%?$-+i:0
```
[Try it online!](https://tio.run/##S8sszvj/38Agps7KwMBBw15FN8@aS8M@JlnVysDBSBXI1860Mvj/38jEzBIA "><> – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 55 bytes
```
a->{int s=0;for(int d:a)s+=d%2<1?-d:d;return s<0?-s:s;}
```
[Try it online!](https://tio.run/##TVDLboMwELznK/ZSCVRjEUorlUeiXir10FN6i3JwMUSmxCB2SRUhfzs1jyaRDzsz3p0dbSnOwqubXJfyZ2i670plkFUCET6F0tCvABYVSZAt51pJONk/Z0et0sf9AUR7RHdqBSitH@9IVbzodEaq1vyr/tD0vrBEadofNlCkg/A2vWWAqR8XdeuMWEbCxcdUPgTJeuvJSMZtTl2rARN/62GEsRniadHkY5dTjoSQgs5/r9ocBaD3DfuH6zvIght5YvbdaMie2euNBixkL/eCnbUDoZm4maMs4Zcw0ZTIvYbYXZDyE6874o09GFXaKbhomuryhvYwztjuurPTaGtWZvgD "Java (OpenJDK 8) – Try It Online")
Naive implementation.
[Answer]
# C#, 67 bytes
```
namespace System.Linq{a=>Math.Abs(a.Sum(n=>n%2<1)-a.Sum(n=>n%2>1))}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
È2*<*OÄ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cIeRlo2W/@GW//@jTXQUTHUULGMB "05AB1E – Try It Online")
```
# Input | 1234567
È # Is Even? | [0,1,0,1,0,1,0]
2*< # (a * 2) - 1 | [-1,1,-1,1,-1,1,-1]
* # Multiply w/ input. | [-1,2,-3,4,-5,6,-7]
O # Sum. | -10
Ä # Absolute value of. | 10
```
[Answer]
# x86-64 Machine Code, 30 bytes
```
31 C0 99 8B 4C B7 FC F6 C1 01 74 04 01 CA EB 02 01 C8 FF CE 75 ED 29 D0 99 31 D0 29 D0 C3
```
The above code defines a function that accepts a list/array of integer digits and returns the absolute difference between the sum of its even digits and the sum of its odd digits.
[As in C](https://codegolf.meta.stackexchange.com/questions/13210/list-input-in-c-and-length-argument), assembly language doesn't implement lists or arrays as first-class types, but rather represents them as a combination of a pointer and a length. Therefore, I have arranged for this function to accept two parameters: the first is a pointer to the beginning of the list of digits, and the second is an integer specifying the total length of the list (total number of digits, one-indexed).
The function conforms to the [System V AMD64 calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI), which is standard on Gnu/UNIX systems. In particular, the first parameter (pointer to the beginning of the list) is passed in `RDI` (as this is 64-bit code, it is a 64-bit pointer), and the second parameter (length of the list) is passed in `ESI` (this is only a 32-bit value, because that's more than enough digits to play with, and naturally it is assumed to be non-zero). The result is returned in the `EAX` register.
If it's any clearer, this would be the C prototype (and you can use this to call the function from C):
```
int OddsAndEvens(int *ptrDigits, int length);
```
**Ungolfed assembly mnemonics:**
```
; parameter 1 (RDI) == pointer to list of integer digits
; parameter 2 (ESI) == number of integer digits in list (assumes non-zero, of course)
OddsAndEvens:
xor eax, eax ; EAX = 0 (accumulator for evens)
cdq ; EDX = 0 (accumulator for odds)
.IterateDigits:
mov ecx, [rdi+rsi*4-4] ; load next digit from list
test cl, 1 ; test last bit to see if even or odd
jz .IsEven ; jump if last bit == 0 (even)
.IsOdd: ; fall through if last bit != 0 (odd)
add edx, ecx ; add value to odds accumulator
jmp .Continue ; keep looping
.IsEven:
add eax, ecx ; add value to evens accumulator
.Continue: ; fall through
dec esi ; decrement count of digits in list
jnz .IterateDigits ; keep looping as long as there are digits left
sub eax, edx ; subtract odds accumulator from evens accumulator
; abs
cdq ; sign-extend EAX into EDX
xor eax, edx ; XOR sign bit in with the number
sub eax, edx ; subtract sign bit
ret ; return with final result in EAX
```
Here's a brief walk-through of the code:
* First, we zero out the `EAX` and `EDX` registers, which will be used to hold the sum totals of even and odd digits. The `EAX` register is cleared by `XOR`ing it with itself (2 bytes), and then the `EDX` register is cleared by sign-extending the EAX into it (`CDQ`, 1 byte).
* Then, we go into the loop that iterates through all of the digits passed in the array. It retrieves a digit, tests to see if it is even or odd (by testing the least-significant bit, which will be 0 if the value is even or 1 if it is odd), and then jumps or falls through accordingly, adding that value to the appropriate accumulator. At the bottom of the loop, we decrement the digit counter (`ESI`) and continue looping as long as it is non-zero (i.e., as long as there are more digits left in the list to be retrieved).
The only thing tricky here is the initial MOV instruction, which uses the most complex addressing mode possible on x86.\* It takes `RDI` as the base register (the pointer to the beginning of the list), scales `RSI` (the length counter, which serves as the index) by 4 (the size of an integer, in bytes) and adds that to the base, and then subtracts 4 from the total (because the length counter is one-based and we need the offset to be zero-based). This gives the address of the digit in the array, which is then loaded into the `ECX` register.
* After the loop has finished, we do the subtraction of the odds from the evens (`EAX -= EDX`).
* Finally, we compute the absolute value using a common trick—the same one used by most C compilers for the `abs` function. I won't go into details about how this trick works here; see code comments for hints, or do a web search.
\_\_
\* The code can be re-written to use simpler addressing modes, but it doesn't make it any shorter. I was able to come up with an alternative implementation that dereferenced `RDI` and incremented it by 8 each time through the loop, but because you still have to decrement the counter in `ESI`, this turned out to be the same 30 bytes. What had initially given me hope is that `add eax, DWORD PTR [rdi]` is only 2 bytes, the same as adding two enregistered values. Here is that implementation, if only to save anyone attempting to outgolf me some effort :-)
```
OddsAndEvens_Alt:
31 C0 xor eax, eax
99 cdq
.IterateDigits:
F6 07 01 test BYTE PTR [rdi], 1
74 04 je .IsEven
.IsOdd:
03 17 add edx, DWORD PTR [rdi]
EB 02 jmp .Continue
.IsEven:
03 07 add eax, DWORD PTR [rdi]
.Continue:
48 83 C7 08 add rdi, 8
FF CE dec esi
75 ED jne .IterateDigits
29 D0 sub eax, edx
99 cdq
31 D0 xor eax, edx
29 D0 sub eax, edx
C3 ret
```
] |
[Question]
[
## Background
**-rot transform** (read as "minus-rot transform") is a sequence transformation I just invented. This transform is done by viewing the sequence as a stack in Forth or Factor (first term on the top) and repeatedly applying `-rot +`. `-rot` is a command that moves the top of the stack to two places down, and `+` adds two numbers on the top of the stack.
For example, applying -rot transform to the sequence `[1, 2, 3, 4, 5, 6, 7, 8, 9]` looks like this (the right side is the top of the stack in this example, to match Forth/Factor conventions):
```
initial: 9 8 7 6 5 4 3 2 1 <--
-rot : 9 8 7 6 5 4 1 3 2
+ : 9 8 7 6 5 4 1 5 <--
-rot : 9 8 7 6 5 5 4 1
+ : 9 8 7 6 5 5 5 <--
-rot : 9 8 7 6 5 5 5
+ : 9 8 7 6 5 10 <--
-rot : 9 8 7 10 6 5
+ : 9 8 7 10 11 <--
-rot : 9 8 11 7 10
+ : 9 8 11 17 <--
-rot : 9 17 8 11
+ : 9 17 19 <--
-rot : 19 9 17
+ : 19 26 <--
```
`-rot` does not work when there are only two items on the stack, so the operation stops there. Then the top of the stack at the initial state and after each `+` command are collected to form the resulting sequence of `[1, 5, 5, 10, 11, 17, 19, 26]`. Note that it is one term shorter than the input sequence.
## Task
Given a finite sequence of integers (of length ≥ 3), compute its -rot transform.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
[1, 2, 3] -> [1, 5]
[1, -1, 1, -1, 1, -1, 1, -1] -> [1, 0, 0, 1, -1, 2, -2]
[1, 2, 3, 4, 5, 6, 7, 8, 9] -> [1, 5, 5, 10, 11, 17, 19, 26]
[1, 2, 4, 8, 16, 32, 64, 128] -> [1, 6, 9, 22, 41, 86, 169]
[1, 0, -1, 0, 1, 0, -1, 0, 1] -> [1, -1, 1, 0, 1, -1, 1, 0]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
Ä2œPF_@\
```
[Try it online!](https://tio.run/##y0rNyan8//9wi9HRyQFu8Q4x////jzbUMdIx0bHQMTTTMTbSMTPRMTSyiAUA "Jelly – Try It Online")
Based on the older approach below. `Ä` generates cumulative sums, and `2œPF` (ew) throws away the second one. Then `\` scanning by `_@` flipped subtraction gives:
```
[a,
a+b+c-(a),
a+b+c+d-(a+b+c-(a)),
a+b+c+d+e-(a+b+c+d-(a+b+c-(a))),
...]
= [a, b+c, a+d, b+c+e, ...]
```
I feel like there has to be something shorter than `2œPF` to remove the 2nd element of a list.
# Jelly, ~~9~~ 8 bytes
```
Jḟ2b1^\ḋ
```
[Try it online!](https://tio.run/##y0rNyan8/9/LzsjZ@tDSmIc7uh7u6P7//3@0oY6CkY6CiY6ChY6CoZmOgjGQZwbkGhpZxAIA "Jelly – Try It Online")
Based on rak1507's observation that when the input is \$[a,b,c,d,e,f...]\$, the answer is $$[a, ~~b + c, ~~a + d, ~~b + c + e, ~~a + d + f, \dots].$$
That is: cumulative sums of even and odd elements, but with the first two elements swapped.
That means we can calculate (`ḋ` is dot product, padding the shorter argument with 0s at the end):
```
ḋ(input, [1]) = a
ḋ(input, [0, 1, 1]) = b + c
ḋ(input, [1, 0, 0, 1]) = a + d
ḋ(input, [0, 1, 1, 0, 1]) = b + c + e
ḋ(input, [1, 0, 0, 1, 0, 1]) = a + d + f
ḋ(input, [0, 1, 1, 0, 1, 0, 1]) = b + c + e + g
...
```
In this program, `Jḟ2b1^\` computes the triangle `[[1], [0,1,1], [1,0,0,1]…]` and `ḋ` takes dot products with the input.
`Jḟ2` is `[1,3,4,5,…,n]`. `b1` generates lists of 1s of those lengths, and `^\` is a XOR scan.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~53~~ 47 bytes
```
f=lambda a,b,*r:(a,)+(r and f(b+r[0],a,*r[1:]))
```
A variadic function that takes the integers as separate arguments and returns a tuple. [Try it online!](https://tio.run/##bY7BCoMwEETvfsUco27BqLVW6JeEHGI1VKhRYi79ertVBA9dWHZn3zLM/AmvyRXrah9vM7adgaGWEt8IQ3EqPIzrYEWbepVpMkyUbHQcr3byCP0SnmbpMTioCEoSckKhad8v3H/GgX@vhJJwJVSEG6Em3E@03C6SWcGqYinz@uDZ7phtpiehI@gmAtfsBxeEFckRk1N/AQ "Python 3 – Try It Online")
### Explanation
```
f=lambda a,b,*r:(a,)+(r and f(b+r[0],a,*r[1:]))
f= # Define f to be
lambda a,b,*r: # a function of at least two arguments
# where a,b are the first two args
# and any args beyond those are
# put in a tuple and assigned to r
(a,) # Tuple containing a
+ # Add (concat) this tuple:
(r and ) # If r is falsey (empty), then r
f( ) # Else, recursive call with:
b+r[0], # The second arg plus the third
a, # followed by the first arg
*r[1:] # followed by all the rest
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 bytes
```
-œ?UŒœÄZFḊ
```
Thank you very much to caird/Dude/ChartZ for helping golf this in TNB.
-1 thanks to Lynn!
Explanation:
I tried to look for a pattern that could be used to solve this more easily, so a quick [sage script](https://sagecell.sagemath.org/?z=eJyFj8sKgzAQRfeC_3C7MsGp0C4FvyS4iBofYG2Its3nd0ItLvpwVsO5986jMS3cIrzM4whcHgW8yvPjqXwBZ2ZGyismK3r0w2gwmoljOBQ4r9lQmlAR6jAls1crJH00m9kj5dEhghR1uQm8NNPWmqkRVVrL9yXLzU1B24xxNA7zIi7airt2hERXdWPark8kp6wbpkXwe2o9q_xKCc1PgWD-aYR2RyZ0-w5Cz6YneUllfw==&lang=sage&interacts=eJyLjgUAARUAuQ==) did the trick.
From that, we get the pattern
```
[a, b + c]
[a, b + c, a + d]
[a, b + c, a + d, b + c + e]
[a, b + c, a + d, b + c + e, a + d + f]
[a, b + c, a + d, b + c + e, a + d + f, b + c + e + g]
[a, b + c, a + d, b + c + e, a + d + f, b + c + e + g, a + d + f + h]
```
From this, we can see it is an interleaved cumulative sum of [a, d, f, h...] and [b, c, e, g...]. Flipping a and b makes this nicer, [b, d, f, h...] and [a, c, e, g...].
```
-œ?UŒœÄZFḊ
- -1
œ? -1th ordered permutation, i.e. second-from-last. This will always be the array reversed with the last 2 elements swapped
U un-reverse
Œœ uninterleave
Ä cumulative sum
Z zip
F flatten
Ḋ tail
```
[Try it online!](https://tio.run/##y0rNyan8/1/36GT70KOTjk4@3BLl9nBH1//D7Y@a1vz/H22oo2Cko2Acq6MAYuoCMRYKImukY6xjomOqY6ZjrmOhYwnVAtRtoqNgAVRpBjQHyDMDcg2NLKDSBhBjDMAmIXFiAQ "Jelly – Try It Online")
[Answer]
# [convey](http://xn--wxa.land/convey/), 55 bytes
```
3!<
v<#/`:<
?:" \&
v?~`"#:}
>#>>,^^
?v v^-1
>+>,,\{
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiIDMhPFxudjwjL2A6PFxuPzpcIiAgXFwmIFxudj9+YFwiIzp9XG4+Iz4+LF5eXG4gP3Ygdl4tMVxuID4rPiwsXFx7IiwidiI6MSwiaSI6IjEgMiAzIDQgNSA2IDcgOCA5In0=)
Lower right part is letting `length(input) - 1` elements to the output.
Top right part buffers the input for too long inputs, as the row would otherwise attach to itself.
Top left we get a `3` for each iteration: this splits off the first three elements and lets the head wait for 3 extra steps before copying it into the output and then rejoining with the main row. Because the head blocks the tile while waiting, the other 2 elements go into the `+` before joining the row again.
[](https://i.stack.imgur.com/sqO1s.gif)
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~47~~ 46 bytes
*-1 byte thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)*
```
[A,B|T]/[A|R]:-T=[C|U],S is B+C,[S,A|U]/R;T=R.
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P9pRx6kmJFY/2rEmKNZKN8Q22rkmNFYnWCGzWMFJ21knOljHESigH2QdYhuk999KVyHaUMdIx1jHRMdUx0zHXMdCxxIom1pcmlOio1BelFmSqgHhaer9BwA "Prolog (SWI) – Try It Online")
### Explanation
We define `/` as an infix predicate that takes a list as its left argument and sets its right argument to the -rot transformed list.
```
[A,B|T]/[A|R] :-
```
The left argument must have at least two elements, `A` and `B`. Any elements beyond the second are put in `T`. The right argument will always start with `A`; the rest of it will be `R`, which we calculate in one of two ways:
```
T=[C|U], S is B+C, [S,A|U]/R
```
Recursive case: if `T` has at least one element, we put the first element of `T` into `C` and the rest of `T` into `U`. Next, we calculate the sum of `B` and `C` and put it in `S`. Then we do a recursive call with the list `[S,A|U]`: the sum `S`, followed by the first element `A`, followed by all the elements in `U`. The result of that recursive call is put in `R`.
```
; T=R
```
If `T` is empty, the unification `T=[C|U]` fails, and we fall back to the base case: `R` is the empty list (i.e. `T`).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
÷^!‹(…∇+
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C3%B7%5E!%E2%80%B9%28%E2%80%A6%E2%88%87%2B&inputs=%5B1%2C%20-1%2C%201%2C%20-1%2C%201%2C%20-1%2C%201%2C%20-1%5D&header=&footer=)
Woo using a stack based language to solve a stack based problem. Outputs each item on a newline. [11 bytes to output as list](https://lyxal.pythonanywhere.com?flags=&code=%C3%B7%5E!%E2%80%B9%28%3A%E2%85%9B%E2%88%87%2B%29%C2%BE&inputs=%5B1%2C%202%2C%203%5D&header=&footer=): `÷^!‹(:⅛∇+)¾`
Also, look ma, no letters (and flags)! Funnily enough, I don't think there's any flag combination that would get this under 8 bytes.
## Explained
```
÷^!‹(…∇+
÷ # Push every item of the input onto the stack
^ # and reverse the stack to make the list indicative of the stack (Ṙ÷ achieves the same thing, but we're going 100% symbolic)
!‹ # Push len(stack) - 1
( # and that many times:
… # print the top of the stack without popping
∇ # perform rot. Fun fact: I added rot to vyxal after seeing forth/factor as LoTM
+ # add the top two items
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~61~~ ~~58~~ 57 bytes
```
lambda a:[a[~i%2]+sum(a[i:1:-2])for i in range(1,len(a))]
```
[Try it online!](https://tio.run/##bYrBCsIwEETP@hVLQUhwc0haaw3oj8QcVmx1oU1LrQcv/npMFXryMMw83gyv6d6HPDbHc2ypu1wJyDpyb94Yv308O0GOrbbKeNn0IzBwgJHCrRYa2zoIktLHxTinEQxC7nFeKuVP/eR8QygQdgglwh6hQjgsrviyTiZPVCbUpvLerlfDyGESjBmoE2TYCJYyfgA "Python 3 – Try It Online")
-3 bytes thanks to @MarcMush
-1 byte thanks to @ovs, by shifting the range by 1
a is the original sequence and b is the -rot transform (both 0-based):
b is define like this :
`n` is even : `b(n) = a(0) + (sum of all odd terms from a(3) to a(n+1))`
`n` is odd : `b(n) = a(1) + (sum of all even terms from a(2) to a(n+1))`
[Answer]
# JavaScript, 42 bytes
Saved 4 bytes prior to posting by following [DLosc's lead](https://codegolf.stackexchange.com/a/233668/58974) and taking the input integers as individual arguments rather than as a single array.
```
f=(x,y,z,...a)=>[x,...1/z?f(y+z,x,...a):a]
```
[Try it online!](https://tio.run/##XY5NC4JAEIbv/QqPK75u7mpmhXbq0qEOHWXBxS8MU1EJ9c@bJhE1h@GZ552BucunbMI6q1q9KKN4HBOXdOgxgFIqVdfzu5nYejgmpNcGdEuwl2I8@CufgcMUmEFn@G2LnnJY2MDGFg52H2lNA7NhctgWGHcWb8y3Br4gVoI@ZEWk64Vl0ZR5TPMyJefb9UKbts6KNEt6IlVayehURIRzVQsU3VMC7W8nIe/Hpxpf)
Or, if outputting a comma delimited string with a trailing comma is allowed then:
# JavaScript, 40 bytes
```
f=(x,y,z,...a)=>x+[,1/z?f(y+z,x,...a):a]
```
[Try it online!](https://tio.run/##VY7NCoJAAITvPoXHXRw3dzWzQjt16VCHjiK4@IdhKiqhvrxpEtFlmPmGgXnIl2yjJq87vaziZJpSl/QYMIIxJqnr9ZoPvhlPKRm0Ef2KDzKYjr7icwiYARajc/zLiuceFrawsYOD/Rdac@A2TAHbAhfOyo1la@BnAiVgT1kT6XpRVbZVkbCiysjlfruytmvyMsvTgUjKahmfy5gIQbVQ1T011FLyeUrp9AY)
[Answer]
## [Perl 5](https://www.perl.org/), ~~57~~ 56 + 4 (`-apl` options) = 60 bytes
```
$F[$_-1]+=$F[$_],$F[$_]=$F[$_-2]for 2..$#F;pop@F;$_="@F"
```
[Try it online!](https://tio.run/##VYtBCoMwFET3OcVgs2sj/hhTRQRXuUQJ0kULBWk@tuf318ZF6WbmzQzDt2VuRHS46MlQPA6Z4mm3PRkb72mBLUt9CD0nHkOvp6EYQyFCsKgVwRD@ReUFDg08zmjR5cZtRB61hXcg225l9b1U@IFaE78f6fkSc@X5Aw "Perl 5 – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~44~~ 39 bytes
```
f(*a,l){for(;--l;a[1]=*a++)a[1]+=a[2];}
```
[Try it online!](https://tio.run/##rVPLrpswEN3frxgh5YqHUXmmSWnaRdWvICwQMbeoDokCUqNG/Hrp2AZscyN1UxQyHp8znscxlV@xsn0bx9p2S8KcR3252Znvs6zMw@Lglp7n8JV3KPOoyIaxaXs4l01rO/B4AXz4Rk@7PswLOMAjJBARiIdsAaIF8PF9YjRubBxCICGQEtgS@EhgR2CvUROdmgg4RGKM3hbdMNpp5HQhBzJxIHJrjiS7gt1JtuiKyB6kiaVJpEmHzJgAk2Fd85tealtEOx8mz5UuAQ2NTDQy0dhEYxNNTDQx0dREU0erlN6vtOrpSemVToOakUgfVrBohTPwoxVV6ZWKX8jpXFfUK9xjzHYVoFRDrTiBi4febsvl26/Y6frqBPrNCWbNZrpkLw0S1ZFaxmqZqKUmpQvVD1r9pDd5mnW8f4@O9/03fFOLgO7H1hSGHw3YvPCmPdE7hgXZtPw8yzJnUsosOxl4nmDPn9RSyRmPkhdS4EWmw8AmlD1D8SYjXJWMXSqbkcRR6PWGeG1buaVtqham8rF0JirTq@JPnzd8Mmc0mQHM5266zQkn1Xzl4/pk4T8P0XIN70opwP8CZj12T4A5q54oJl7UfjaTa9l1yAn/0Rj4SHnW3BQvzOvr1Cvm/L/Nbrpji8z5ovFsekh9o9Tup43hZRj/VDUr37rR//UX "C (clang) – Try It Online")
Saved 5 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!!
Inputs a pointer to a finite sequence of integers and its length (since pointers in C carry no length info), and computes its -rot transform in place.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 40 bytes
```
\d+
$*
+1`(1*),(1*,)(1*)
$1¶$3$2$1
%`\G1
```
[Try it online!](https://tio.run/##HcixDYAgFITh/s3xSASueYCoE1i5gQUmWthYGGdzABZDpPnvy93Hc15bKetuiQ1ZSZ0YjRroX8SSX/bsWEildZZSd/lBSiem/BaBg6dWBPSIGDBiak@okgjvEAPEjR8 "Retina 0.8.2 – Try It Online") Link includes footer that spaces the results out. Takes input as a comma-separated list of non-negative integers due to limitations of unary, and outputs a newline-separated list (+4 bytes for newline-separated input or +5 bytes for comma-separated output). Explanation:
```
\d+
$*
```
Convert to unary.
```
+1`(1*),(1*,)(1*)
$1¶$3$2$1
```
Make a copy of the first number, then rotate it below the sum of the third and second numbers. Repeat until there are only two numbers left.
```
%`\G1
```
Convert the first number on each line to decimal. This outputs the initial first number and all of the copied sums, but avoids duplicating the penultimate sum.
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 75 bytes
```
(d F(q((S)(c(h S)(i(t(t S))(F(c(a(h(t S))(h(t(t S))))(c(h S)(t(t(t S))))))(
```
Defines a function `F` that takes a list and returns a list. [Try it online!](https://tio.run/##RY7BCsIwEETvfsUcZw@CVUH8gR69@AXbptpA2sQalH59XLDa08483sBmP87BP1MpdKj5IK/Clj3seGZmC8LakLJfWv/j8lfzigwWhqgOwTeTTrNsWINVjjjIN99icAFtHFvN4NSlTvP2pQG0VzIqcOzuqERwFFnn5yUPmszUoXEKXgRM8Y09LuZzZ97JRuUD "tinylisp – Try It Online")
### Explanation
Pretty straightforward, once you fight your way through all the parentheses:
```
(d F ; Define F
(q ; to be a list representing a function
((S) ; that takes one argument, S:
(c ; Cons
(h S) ; the first element of S to the following list:
(i (t (t S)) ; If the tail of tail of S is not empty:
(F ; Call F recursively, with an argument of
(c ; cons...
(a ; the result of adding
(h (t S)) ; the second element of S and
(h (t (t S)))) ; the third element of S
(c ; ... to the cons of...
(h S) ; the first element of S and
(t (t (t S)))))) ; S without its first three elements
() ; Else, empty list
```
---
The same thing (but snazzier and less golfy) is **92 bytes** in tinylisp's descendant language [Appleseed](https://github.com/dloscutoff/appleseed):
```
(def F(q((S)(cons(head S)(if(ttail S)(F(cons(sum(take 2(tail S)))(cons(head S)(drop 3 S))))(
```
[Try it online!](https://tio.run/##XY5BcsIwDEX3PcXvTt4lsKCs2OUCPYFqC@rBid1IlOH0wSFkmGEly@/rSVxKEhUJ00RBjujoj@jbkc@D0q9wQG3ikcw4pvndLUgvPRmfBRt6Evc2FMZcsH0AR4vcRM2zioJSVAO1lrF1WExfIH/zSZ6wBQ1yQjvPL8l9rT0XUOHRIieUfMUGh/rdVLxzq2n/bmpWF5pZ5z4e56hVz2cNcf8TGCT/Mti6w@e@ZBWUMQ411LnX9VUw3QE "Appleseed – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 34 bytes
```
f(a:b:c:d)=a:f(b+c:a:d);f(a:_)=[a]
```
[Try it online!](https://tio.run/##FchJDkBAEAXQq9TCosXfmCnpk4hImTuGCO5fWL63yL2O26Y6GeGOex58KzyZLuhZPlT/t76tpdFd3GHPyx2PN9chKALFoASUgjJQDipAZaMv "Haskell – Try It Online")
This takes the straight forward approach. All the other fancy approaches just don't really end up saving any bytes in Haskell.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~47 38~~ 34 bytes
```
->a,b,*l{l.map{|x|a,b=b+x,a;b}<<a}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ0lHK6c6Ry83saC6pqIGyLdN0q7QSbROqrWxSaz9X6CQFm2oY6RjrGOiY6pjpmOuY6FjGfsfAA "Ruby – Try It Online")
Variadic function accepting at least 2 parameters.
[Answer]
# [jq](https://stedolan.github.io/jq/), 53 bytes
```
[while(.[1];.[1]+=.[2]|(.[2]//.[0])=.[0]|.[1:])|.[0]]
```
[Try it online!](https://tio.run/##yyr8/z@6PCMzJ1VDL9ow1hpEaNvqRRvF1miASH19vWiDWE1bEFkDlLSK1awBsWOB2gx1FIx0FIxjuUAsXSDGQkEkQcp0FEx0FEx1FMx0FMx1FCx0FCzhciZgviFQxhjIMwNyDY0sILIGELMMwMYhcWL/5ReUZObnFf/XTQYA "jq – Try It Online")
**Explanation:**
```
Based on example input: [1, 2, 3]
[
while( While
.[1] the array has at least two items
;
.[1]+=.[2] add the second and third number and store them on second position.
|(.[2]//.[0]) Choose third element if it is not null else first element
=.[0] and set its value to the value of the first number.
|.[1:] Drop the first element.
)
| Now we have the evolution of the updated array, e.g. [[1,2,3],[5,1]]
.[0] take the first element of each array
] [1,5]
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 50 bytes
```
{⎕←1↑⍵⋄({(3↓⍵),⍨(+/2↑1⌽3↑⍵),1↑⍵}⍣{⎕←1↑⍺⋄(⍴⍺)<3})⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/@lHf1EdtEwwftU181Lv1UXeLRrWG8aO2yUCOps6j3hUa2vpGQDnDRz17jSFqNHWgimsf9S5G0b4LpP1R7xYgS9PGuFYTpOb/fwA "APL (Dyalog Classic) – Try It Online")
Explanation:
```
(+/2↑1⌽3↑⍵),1↑⍵ take the first three elements, rotate them, sum the first two and stick the third (which was originally the first element) on the end again so (a b c) -> (b c a) -> (b+c a)
(3↓⍵),⍨ concatenate this with the rest of the list
⍣{⎕←1↑⍺⋄(⍴⍺)<3} the above gets run until the list is less than 3 elements
```
Note: locally this seems to iterate one more time, but in tio.run it does not, unsure why. This is my first code golf attempt so certainly a lot to be improved on! Happy to hear from APL experienced users how this could be better, I dont like my use of ⎕ in this solution
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
ḣ2S;ɗḢṄ$ḷ"ƊḊḊ$¿Ḣ
```
[Try it online!](https://tio.run/##y0rNyan8///hjsVGwdYnpz/csejhzhaVhzu2Kx3rergDhFQO7QeK/v//P9pQR8FAR0EXQqFyYgE "Jelly – Try It Online")
Blegh. Full program, outputs each on a separate line
## How it works
```
ḣ2S;ɗḢṄ$ḷ"ƊḊḊ$¿Ḣ - Main link. Takes a list L on the left
¿ - While:
$ - Condition:
ḊḊ - The list is non-empty after dequeuing twice
Ɗ - Body:
$ - Last 2 links as a monad f(L):
Ḣ - First element, X
Ṅ - Print and return
ɗ - Last 3 links as a dyad f(L[1:], X):
ḣ2 - First 2 elements
S - Sum
; - Concat with X
ḷ" - Replace the first 2 elements of L with this pair
Ḣ - Get the first element of the final pair
```
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), 16 bytes
```
÷^(!;|④
,&""&''+
```
[Try it online!](https://tio.run/##y05N////8PY4DUXrmkcTF3PpqCkpqamra///H22oo2Cko2Cso2Cio2Cqo2Cmo2Cuo2Cho2AZCwA "Keg – Try It Online")
## Explained
```
÷^ # Push all items of the input onto the stack and reverse the stack
(!;| # len(stack) - 1 times:
④ # print the top of the stack without popping
, # and print a newline too
&""&'' # perform rot
+ # and add the top two items
```
[Answer]
# [Julia 1.0](http://julialang.org/), 37 bytes
```
a\b=a
\(a,b,c,r...)=[a;\(b+c,a,r...)]
```
Inspired by [DLosc's answer](https://codegolf.stackexchange.com/a/233668/98541)
the numbers are taken as separate arguments, and Julia's multiple dispatch makes it really easy to separate between 2 arguments (first method) and 3 or more arguments (second method)
[Try it online!](https://tio.run/##bY7BCoMwEETv@Yo5RroVo9ZaSvojSQ7RWrBIWjSF/n0aFcFDF5bd2bcM8/wMvRXfEKxupGWaW2qopTFN00Qqe9W8ObRk14MJvpv8BAnFoAQhJxSG1v0Y@8/Y8PxKKAknQkU4E2rCZUfL5SIiK6KqohR5vfFsdcwW050wzDD2eI3w6B2WdAyx3mPv/OC4h7xBcz@nT1jn7uEH "Julia 1.0 – Try It Online")
[Answer]
# Scala, 66 bytes
```
s=>Seq.iterate(s,s.size-1)(s=>s(1)+s(2)::s(0)::s.drop(3))map(_(0))
```
[Try it in Scastie!](https://scastie.scala-lang.org/FPvh9EZTT2eEUvdcrZBqqg)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
å+
j1
ån
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=5SsKajEK5W4&input=WzEgMiAzIDQgNSA2IDcgOCA5XQ)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~31~~ ~~25~~ 22 bytes
```
≔ΦEθΣ…θ⊕κ⊖κθIEθ↨…θ⊕κ±¹
```
[Try it online!](https://tio.run/##fcw9C8IwEIDh3V9x4wXOoX5LJ60IDorgWDoc8WiDaWqTKPjr4wc4uPiO7/Dohr3u2Ka0CsHUDrfGRvG45yv2BKdbi8VDWyma7jN2TntpxUU540W9ItjIzyLoVT44euMiFhzil1pzkL8WwUFqjoLZ21V5SmWZEYwIxgQTginBjGBOsCBYVlUa3u0T "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Now a port of @Lynn's Jelly answer.
```
≔ΦEθΣ…θ⊕κ⊖κθ
```
Calculate the cumulative sums of the input, i.e. the sums of all of its nontrivial prefixes, but then remove the second sum.
```
IEθ↨…θ⊕κ±¹
```
Calculate their cumulative differences, which is done by interpreting their nontrivial prefixes in base `-1`.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 9 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
-˜`⊑∾2↓+`
```
[Try it here.](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgLcucYOKKkeKIvjLihpMrYAoKRsKo4p+oMeKAvzLigL8zLCAx4oC/wq8x4oC/MeKAv8KvMeKAvzHigL/CrzHigL8x4oC/wq8xLCAx4oC/MuKAvzPigL804oC/NeKAvzbigL834oC/OOKAvzksIDHigL8y4oC/NOKAvzjigL8xNuKAvzMy4oC/NjTigL8xMjgsIDHigL8w4oC/wq8x4oC/MOKAvzHigL8w4oC/wq8x4oC/MOKAvzHin6k=)
Based on [Lynn's solution](https://codegolf.stackexchange.com/a/233671/74681).
```
-˜`⊑∾2↓+`
2↓+` # drop 2 elements from the plus scan
∾ # joined to
⊑ # first element of input
-˜` # swapped subtraction scan
```
[Answer]
# C++14 (or newer), 81 bytes
```
[](auto&v){for(int i=1,t;++i<v.size();v[i]=t)t=v[i-2],v[i-1]+=v[i];v.pop_back();}
```
A [lambda function](https://en.cppreference.com/w/cpp/language/lambda) that modifies the passed [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) by reference.
Tests: <https://coliru.stacked-crooked.com/a/759a69be8a6398f1>
[Answer]
# [Perl 5](https://www.perl.org/), 54 bytes
```
sub f{my($a,$b,$c,@r)=@_;($a,@r?f($b+$c,$a,@r):$b+$c)}
```
[Try it online!](https://tio.run/##fZDBToNAFEX3fMVNQzJDfU2AtlhKsOxN7MadEiOGKtpSpBhtmm79AN326/oj@GZaCTGNZJjJfXPPfTNTpOV8WNertwSzzWItzXsyEzIfKCqtMLoLVCEqJzNpJmdc1coaa2Ft68U6qtJVFUoDuHEILqEf49QXXmjDMKajtcf/iSVurLYexz0O7rkNq9oQBhxH8AjnhBHBj1tt9HAUr4LZ4PiMee2EgaYc5vusPJaOO4p/E7isCOVjNfKU029w@3Cqw/laosGP97Hbl7MZtwLj/Smbp1KaWV6QmX4UpJ@QH1svG@6wWCN6XFbhTEbKxQxQlFle4XmZ5VKQILVvIX1tVVSWhQnE8gX73TcgMIbodrtX02tMLyFOxeh8Yiuw//ziWdCfJoTObd4JjG1d/3vzHw "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 65 bytes
```
l=input();print l[0]
while l[2:]:k=l[1]+l[2];print k;l[:3]=k,l[0]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8c2M6@gtERD07qgKDOvRCEn2iCWqzwjMycVyDSyirXKts2JNozVBnJioUqyrXOirYxjbbN1QIr//4821DHSMdYx0THVMdMx17HQsYwFAA "Python 2 – Try It Online")
-17 thanks to @ovs
-3 from me on ovs improvement
[Answer]
# [J](http://jsoftware.com/), 16 bytes
```
1{1-/\.&.|.\.+/\
```
[Try it online!](https://tio.run/##y/r/P81WT8Gw2lBXP0ZPTa9GL0ZPWz/mf2pyRr5CmoKhgpGCMRcyR8FEwVTBTMFcwULBEiERb4hGIOsxAao1NFMwNlIwM1EwNLL4DwA "J – Try It Online")
Translated from [Lynn’s Jelly solution](https://codegolf.stackexchange.com/a/233671/74681)
[Answer]
# [Zsh](https://zsh.sourceforge.io/), ~~72~~ 50 bytes
```
for _ ({2..$#}){printf $1\ ;2=$[$3+$2];3=$1;shift}
```
Used shell parameters instead of variables, saved 22 bytes!
[try it online!](https://tio.run/##XYzBCoMwGIPvfYrg/kNlKLbVziEde485dhgr9aJDPa302TuVMcYuyUdC8ppctDz17HF3A7IeCadzinaGMafFkmiHETdwL/OcdiH1z7HrZwsSLRpp6EJqT/LaKEOimVxn5xDXLxaYhYCEwgaZ@JNvXaKCxgE1jp@sXFhoKAldQsh6i4t1WPxAfAM)
~~[72 bytes](https://tio.run/##XY3RCoIwGIXv9xQH2YUSgptmhix6jzm6CIcGm6HrJvHZl7OI6OY/H9/h8D@nzus4mcnDTq1DjxsMLGmv3YDUIorpOUHjIMRpjcgbEUw9db12RA8jLvV8H3vrNKiRTDUgRnIlqDQyV7vAqg4otvo9hFl8@EAWosHAkWODlP2db11gjxIHVDh@XLEyK5FzlAUYrzadhWH2A/4F)~~
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
R`[=.g<#Š+
```
[Try it online](https://tio.run/##yy9OTMpM/f8/KCHaVi/dRvnoAu3//6MNdRSMdBSMdRRMdBRMdRTMdBTMdRQsdBQsYwE) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6mj5F9aAuHoVP4PSoi21Uu3UT66QPt/7aFt9pox/6OjDXWMdIxjdYC0rqEOKgEWBcrqmOiY6pjpmOtY6FhCxUyAbEMzHWMjHTMTHUMjC7CwAUijgQ6CERsLAA).
A port of [*@Lynn*'s top Jelly answer](https://codegolf.stackexchange.com/a/233671/52210) is **10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** as well:
```
ηO¯1ǝ˜Å»s-
```
[Try it online](https://tio.run/##ATUAyv9vc2FiaWX//863T8KvMcedy5zDhcK7cy3//1sxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5XQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c9v9D603PD739JzDrYd2F@v@r9X5Hx1tqGOkYxyrA6R1DXVQCbAoUFbHRMdUx0zHXMdCxxIqZgJkG5rpGBvpmJnoGBpZgIUNQBoNdBCM2FgA).
**Explanation:**
```
R # Reverse the (implicit) input-list
` # Pop and dump all items separated to the stack
[ # Start an infinite loop:
= # Print the top item with trailing newline (without popping)
.g # Get the amount of items on the stack
< # If this is 2:
# # Stop the infinite loop
Š # Triple swap the top three items (a,b,c to c,a,b)
+ # Add the top two items together
η # Get the prefixes of the (implicit) input-list
O # Sum each inner prefix together
# Remove the second item by:
¯1ǝ # Replacing the second item (at index 1) with an empty list
˜ # And then flatten the list of lists
Å» # Cumulative left-reduce the list by:
s # Swapping the two items
- # And subtracting them from one another
# (after which the list is output implicitly as result)
```
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 58 bytes (12 bytes in Binary Whitespace)
```
LSSTLSLSTLSTSSLSLTTTSLSSLTSSSSLSTLSTSSLTTTSLTSSLSLTTTSLSLL
```
where S is space (ASCII 32), T is tab (ASCII 9), and L is line feed (ASCII 10).
Whitespace is a stack-based language, which would seem ideal for this challenge, however it provides very limited stack instructions—none of which can modify the stack below the top two elements. The heap can be used as scratch space though. For this challenge, only one heap address is needed, which we'll call the accumulator `acc` in the pseudocode.
The program ends once the stack underflows. Label `1` is not necessary, but it makes the program a callable procedure to follow [Code Golf rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422).
Formatted as readable Whitespace Assembly:
```
1: # LSSTL
dup printi # SLS TLST
0 swap store # SSL SLT TTS
_: # LSSL
+ dup printi # TSSS SLS TLST
0 retrieve swap # SSL TTT SLT
0 swap store # SSL SLT TTS
jmp _ # LSLL
```
Notes on syntax:
* `_` represents a label with no digits. It is unique from label `0`.
* A raw digit literal represents a `push` instruction.
Pseudocode:
```
func f(stack) {
print(stack.top())
var acc = stack.pop() # heap address 0
loop {
var x = stack.pop() + stack.pop()
print(x)
acc, x = x, acc
stack.push(x)
}
}
```
## Binary Whitespace, 12 bytes
Whitespace has a trinary alphabet (space, tab, LF), but it can be represented with a binary alphabet with a simple mapping. Space becomes `0`, tab becomes `10`, and LF becomes `11`. All trailing zeros on the last byte are ignored. If the final character ends with `0` (i.e. space or tab), then append a `1` to the bit stream. This encoding is implemented by [Nebula](https://github.com/andrewarchi/nebula).
If other code golf languages can pick arbitrary encodings, then this should be fair :).
```
11000110 11010110 10001101 11010100
11001110 00001101 01101000 11101010
01110001 10111010 10011011 11000000
```
## Running
These are the five provided test cases. Run the program with one of these prefixed. Digits are outputted without delimiters to save bytes.
1. `SSSTTL SSSTSL SSSTL LSTTL`
2. `SSTTL SSSTL SSTTL SSSTL SSTTL SSSTL SSTTL SSSTL LSTTL`
3. `SSSTSSTL SSSTSSSL SSSTTTL SSSTTSL SSSTSTL SSSTSSL SSSTTL SSSTSL SSSTL LSTTL`
4. `SSSTSSSSSSSL SSSTSSSSSSL SSSTSSSSSL SSSTSSSSL SSSTSSSL SSSTSSL SSSTSL SSSTL LSTTL`
5. `SSSTL SSL SSTTL SSL SSSTL SSL SSTTL SSL SSSTL LSTTL`
```
3 2 1 call 1 # => 15
-1 1 -1 1 -1 1 -1 1 call 1 # => 1001-12-2
9 8 7 6 5 4 3 2 1 call 1 # => 1551011171926
128 64 32 16 8 4 2 1 call 1 # => 169224186169
1 0 -1 0 1 0 -1 0 1 call 1 # => 1-1101-110
```
The interpreter must allow empty labels and argument literals. The reference interpreter [wspace](https://web.archive.org/web/20150717140342/http://compsoc.dur.ac.uk/whitespace/download.php) (and thus TIO) does not support this; [Nebula](https://github.com/andrewarchi/nebula) and [Whitelips](https://vii5ard.github.io/whitespace/) do.
] |
[Question]
[
Inspired by this listing from the Commodore 64 User's Guide:
```
10 PRINT "{CLR/HOME}"
20 POKE 53280,7 : POKE 53281,13
30 X = 1 : Y = 1
40 DX = 1 : DY = 1
50 POKE 1024 + X + 40 * Y, 81
60 FOR T = 1 TO 10 : NEXT
70 POKE 1024 + X + 40 * Y, 32
80 X = X + DX
90 IF X <= 0 OR X >= 39 THEN DX = -DX
100 Y = Y + DY
110 IF Y <= 0 OR Y >= 24 THEN DY = -DY
120 GOTO 50
```
Make a similar program in your chosen language/platform to bounce a ball-alike object around your terminal, screen, canvas or other visual display area.
You don't have to mimic the C64's PETSCII graphics exactly, a simple `O` or `o` will do, nor do you have to use the `GOTO` command if it exists in your language still. As long as your ball starts at the top of your canvas and travels diagonally until it hits a canvas limit, and then bounces accordingly, as follows:
* Travelling downwards and right and hits the bottom of the screen area, bounces up and continues right;
* Travelling up and right and hits the right-most boundary, and bounces left and up;
* Travelling left and up and hits the top, bounces left and down;
* Travelling left and down and reaches the left-most boundary, bounces right and down;
* Hits any corner and reverses direction;
Then we're all good.
You don't have to move the ball 8-pixels at a time either, like is happening in the BASIC listing on the C64; you can move one character block or one pixel at a time, whichever you think is most appropriate.
To see this BASIC listing working, you can type it in with [this online Commodore 64 emulator](https://c64emulator.111mb.de/index.php?site=pp_javascript&lang=en&group=c64) providing your browser supports JavaScript.
[Answer]
# Bash + Unix utilities, ~~125~~ 117 bytes
```
for((x=y=u=v=1;;x+=u,y+=v,u=(x<1||x>=`tput cols`-1)?-u:u,v=(y<1||y>=`tput lines`-1)?-v:v)){
tput cup $y $x
sleep .1
}
```
---
Animation of sample run:
[](https://i.stack.imgur.com/0iZjQ.gif)
[Answer]
## [CP-1610](https://en.wikipedia.org/wiki/General_Instrument_CP1600) assembly, ~~67~~ … ~~64~~ 62 DECLEs = 78 bytes
This code is intended to be run on an [Intellivision](https://en.wikipedia.org/wiki/Intellivision). It's using one of its hardware sprites, known as a MOB (for Mobile Object).
A CP-1610 opcode is encoded with a 10-bit value, known as a 'DECLE'. This program is 62 DECLEs long, starting at $4800 and ending at $483D.
### Hexadecimal dump + source
```
ROMW 10 ; use 10-bit ROM
ORG $4800 ; start program at address $4800
FRAME EQU $17E ; frame #
;; ------------------------------------------------ ;;
;; main entry point ;;
;; ------------------------------------------------ ;;
main PROC
4800 0001 SDBD ; load Interrupt Service Routine
4801 02B8 002B 0048 MVII #isr, R0 ; into R0
4804 0240 0100 MVO R0, $100 ; update ISR
4806 0040 SWAP R0
4807 0240 0101 MVO R0, $101
4809 02B9 0208 MVII #$0208, R1 ; initialize R1 = X
480B 02BA 0108 MVII #$0108, R2 ; initialize R2 = Y
480D 02BB 0001 MVII #1, R3 ; initialize R3 = DX
480F 009C MOVR R3, R4 ; initialize R4 = DY
4810 0002 EIS ; enable interrupts
;; ------------------------------------------------ ;;
;; main loop ;;
;; ------------------------------------------------ ;;
4811 0280 017E @@loop MVI FRAME, R0 ; R0 = current frame #
4813 0340 017E @@spin CMP FRAME, R0 ; wait for next frame
4815 0224 0003 BEQ @@spin
4817 00D9 ADDR R3, R1 ; X += DX
4818 0379 02A0 CMPI #$2A0, R1 ; reached right border?
481A 0204 0003 BEQ @@updDx
481C 0379 0208 CMPI #$208, R1 ; reached left border?
481E 002F ADCR PC
481F 0023 @@updDx NEGR R3 ; DX = -DX
4820 00E2 ADDR R4, R2 ; Y += DY
4821 037A 0160 CMPI #$160, R2 ; reached bottom border?
4823 0204 0003 BEQ @@updDy
4825 037A 0108 CMPI #$108, R2 ; reached top border?
4827 002F ADCR PC
4828 0024 @@updDy NEGR R4 ; DY = -DY
4829 0220 0019 B @@loop ; loop forever
ENDP
;; ------------------------------------------------ ;;
;; ISR ;;
;; ------------------------------------------------ ;;
isr PROC
482B 01DB CLRR R3 ; clear a bunch of STIC registers
482C 02BC 0020 MVII #$20, R4
482E 0263 @@clear MVO@ R3, R4 ; (including background color,
482F 037C 0032 CMPI #$32, R4 ; border color, etc.)
4831 0226 0004 BLE @@clear
4833 0259 MVO@ R1, R3 ; update X register of MOB #0
4834 0242 0008 MVO R2, $8 ; update Y register of MOB #0
4836 02BB 017E MVII #$017E, R3 ; update A register of MOB #0
4838 0243 0010 MVO R3, $10 ; (using a yellow "O")
483A 0298 MVI@ R3, R0 ; increment frame #
483B 0008 INCR R0
483C 0258 MVO@ R0, R3
483D 00AF JR R5 ; return from ISR
ENDP
```
### Output
[](https://i.stack.imgur.com/S20vi.gif)
[Answer]
# TI-BASIC, ~~71~~ 70
```
1->A
1->B
1->C
1->D
While 1
ClrHome
Output(B,A,0
A+C->A
B+D->B
If A<2 or A>15
~C->C
If B<2 or B>7
~D->D
End
```
Quite literal translation, I wouldn't be surprised if there are tricks to make it smaller.
The screen is 16x8 and 1-indexed so the constants are different.
`~` is the SourceCoder way to write the negation symbol.
[](https://i.stack.imgur.com/CcPtc.gif)
It looks smoother on hardware.
[Answer]
# HTML (Microsoft Edge/Internet Explorer), 81 bytes
Pretend it's 1998 with these nested `<marquee>` tags:
```
<marquee behavior=alternate direction=down><marquee behavior=alternate width=99>O
```
Tested in Microsoft Edge, though from what I've read IE should also still support marquees. Decidedly does *not* work in Chrome.
Setting `direction=up` would save 2 bytes, but break the rule that the ball has to start at the top of the canvas.
[Answer]
# Befunge, 209 bytes
```
>10120130pppp>"l52?[J2["39*,,,,39*,,,,,,v
v+56/+55\%+55:+1g01*83-"6!"7\-"6!?"8-*86<
>00g1+:55+%\55+/"+!6"-48*,68>*#8+#6:#,_v$
v:+g03g01p02+-\g02*2!-*64\*2!:p00:+g02g<$
>10p:!2*\"O"-!2*30g\-+30p"2"::**>:#->#1_^
```
This assumes a screen size of 80x25, but you can easily tweak the range by replacing the `"O"` (79) on the last line and the `*64` (24) on the second last line (note that the second last line is executed right to left). The speed can also be adjusted by replacing the `"2"` (50) on the last line.
[Answer]
# Java, ~~184~~ 176 bytes
```
class A{public static void main(String[]a)throws Exception{for(int X=1,Y=1,x=1,y=1;;System.out.print("\033["+X+";"+Y+"H"),Thread.sleep(50),X+=x=X%25<1?-x:x,Y+=y=Y%85<1?-y:y);}}
```
This makes use of [ANSI Escape Sequences](http://ascii-table.com/ansi-escape-sequences.php) to relocate the cursor, which is the object that bounces around a `85 x 25` terminal display. Save in a file named `A.java`.
## Ungolfed
```
class Terminal_Bouncing_Ball {
public static void main(String[] args) throws InterruptedException {
int X = 0, Y = 0, dx = 1, dy = 1;
while (true) {
System.out.print(String.format("\033[%d;%dH",X,Y));
Thread.sleep(50);
dx = (X < 1) ? 1 : (X > 71) ? -1 : dx;
dy = (Y < 1) ? 1 : (Y > 237) ? -1 : dy;
X += dx;
Y += dy;
}
}
}
```
## Demo
[](https://i.stack.imgur.com/BX36B.gif)
[Answer]
# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 90 89 91 bytes
+2 bytes because it **needs** a load address (not PIC because of self modification)
```
00 C0 20 44 E5 CA D0 FD C6 FC D0 F9 A2 20 86 FC A9 D8 85 9E A9 03 85 9F A4 CA
18 A5 9E 69 28 85 9E 90 02 E6 9F 88 10 F2 A4 C9 8A 91 9E C9 20 D0 08 E6 C9 E6
CA A2 51 10 D7 A5 C9 F0 04 C9 27 D0 08 AD 2F C0 49 20 8D 2F C0 A5 CA F0 04 C9
18 D0 B4 AD 31 C0 49 20 8D 31 C0 D0 AA
```
**[Online demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"ball.prg":"data:;base64,AMAgROXK0P3G/ND5oiCG/KnYhZ6pA4WfpMoYpZ5pKIWekALmn4gQ8qTJipGeySDQCObJ5sqiURDXpcnwBMkn0AitL8BJII0vwKXK8ATJGNC0rTHASSCNMcDQqg=="%7D,"vice":%7B"-autostart":"ball.prg"%7D%7D)**
Usage: `sys49152`
I tried hard to reduce size (e.g. NOT using IRQs for timing but stupid empty loops instead), still impossible to reach the level of [Titus' golfed C64 BASIC](https://codegolf.stackexchange.com/a/110878/71420) :o oh, well. But it looks less flickering ;)
**Explanation:** (vice disassembly)
```
00 C0 .WORD $C000 ; load address
20 44 E5 JSR $E544 ; clear screen
CA DEX
D0 FD BNE $C003 ; inner wait (256 decrements)
C6 FC DEC $FC
D0 F9 BNE $C003 ; outer wait (32 decrements in zeropage)
A2 20 LDX #$20 ; wait counter and screen code for "space"
86 FC STX $FC ; store wait counter
A9 D8 LDA #$D8 ; load screen base address ...
85 9E STA $9E ; ... -40 (quasi row "-1") ...
A9 03 LDA #$03 ; ... into vector at $9e/$9f
85 9F STA $9F
A4 CA LDY $CA ; load current row in Y
18 CLC ; clear carry flag
A5 9E LDA $9E ; add ...
69 28 ADC #$28 ; ... $28 (40 cols) to ...
85 9E STA $9E ; ... vector
90 02 BCC $C023
E6 9F INC $9F ; handle carry
88 DEY ; count rows down
10 F2 BPL $C018
A4 C9 LDY $C9 ; load current col in Y
8A TXA ; copy screen code from X to A
91 9E STA ($9E),Y ; store at position of screen
C9 20 CMP #$20 ; screen code was "space"
D0 08 BNE $C037 ; if not, ball was drawn
E6 C9 INC $C9 ; next column | opcodes are modified
E6 CA INC $CA ; next row | here for directions
A2 51 LDX #$51 ; screen code for "ball"
10 D7 BPL $C00E ; and back to drawing code
A5 C9 LDA $C9 ; load current column
F0 04 BEQ $C03F ; if zero, change X direction
C9 27 CMP #$27 ; compare with last column (39)
D0 08 BNE $C047 ; if not equal, don't change X direction
AD 2F C0 LDA $C02F ; load opcode for X direction
49 20 EOR #$20 ; toggle between ZP INC and DEC
8D 2F C0 STA $C02F ; store back
A5 CA LDA $CA ; load current row
F0 04 BEQ $C04F ; if zero, change Y direction
C9 18 CMP #$18 ; compare with last row (24)
D0 B4 BNE $C003 ; if not equal, don't change Y direction
AD 31 C0 LDA $C031 ; load opcode for Y direction
49 20 EOR #$20 ; toggle between ZP INC and DEC
8D 31 C0 STA $C031 ; store back
D0 AA BNE $C003 ; -> main loop
```
---
Just for fun, here's a more professional variant using a sprite for the ball and flashing the border when hit in **385** bytes (containing the sprite data that's used *in place*):
```
00 C0 AD 15 D0 F0 30 A9 CC 85 FC A9 04 20 A2 C0 A9 97 8D 00 DD A9 15 8D 18 D0
A9 00 8D 15 D0 8D 1A D0 A2 81 8E 0D DC A2 31 8E 14 03 A2 EA 8E 15 03 58 A6 D6
4C F0 E9 A9 04 85 FC A9 CC 20 A2 C0 A2 31 86 01 A2 10 A9 D0 85 FC B1 FB C6 01
91 FB E6 01 C8 D0 F5 E6 FC CA D0 F0 A9 37 85 01 A9 94 8D 00 DD A9 35 8D 18 D0
8D 27 D0 A2 05 8E F8 CF A2 01 8E 15 D0 8E 1A D0 8E 12 D0 86 FD 86 FE A2 18 8E
00 D0 A2 1B 8E 11 D0 A2 32 8E 01 D0 A2 7F 8E 0D DC AE 0D DC AE 20 D0 86 FB A2
C1 8E 14 03 A2 C0 D0 8A 85 FE 8D 88 02 A9 00 85 FB 85 FD A2 04 A0 00 78 B1 FB
91 FD C8 D0 F9 E6 FC E6 FE CA D0 F2 60 A6 FB 8E 20 D0 CE 19 D0 A5 FD F0 20 AD
00 D0 18 69 04 8D 00 D0 90 03 EE 10 D0 C9 40 D0 2C AD 10 D0 29 01 F0 25 20 38
C1 C6 FD F0 1E AD 00 D0 38 E9 04 8D 00 D0 B0 03 CE 10 D0 C9 18 D0 0C AD 10 D0
29 01 D0 05 20 38 C1 E6 FD A5 FE F0 14 AD 01 D0 18 69 04 8D 01 D0 C9 E6 D0 19
20 38 C1 C6 FE F0 12 AD 01 D0 38 E9 04 8D 01 D0 C9 32 D0 05 20 38 C1 E6 FE 4C
31 EA A9 01 8D 20 D0 60 00 00 00 7E 00 03 FF C0 07 FF E0 1F FF F8 1F FF F8 3F
FF FC 7F FF FE 7F FF FE FF FF FF FF FF FF FF FF FF FF FF FF 7F FF FE 7F FF FE
3F FF FC 1F FF F8 1F FF F8 07 FF E0 03 FF C0 00 7E 00 00 00 00
```
**[Online demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"spball.prg":"data:;base64,AMCtFdDwMKnMhfypBCCiwKmXjQDdqRWNGNCpAI0V0I0a0KKBjg3cojGOFAOi6o4VA1im1kzw6akEhfypzCCiwKIxhgGiEKnQhfyx+8YBkfvmAcjQ9eb8ytDwqTeFAamUjQDdqTWNGNCNJ9CiBY74z6IBjhXQjhrQjhLQhv2G/qIYjgDQohuOEdCiMo4B0KJ/jg3crg3criDQhvuiwY4UA6LA0IqF/o2IAqkAhfuF/aIEoAB4sfuR/cjQ+eb85v7K0PJgpvuOINDOGdCl/fAgrQDQGGkEjQDQkAPuENDJQNAsrRDQKQHwJSA4wcb98B6tANA46QSNANCwA84Q0MkY0AytENApAdAFIDjB5v2l/vAUrQHQGGkEjQHQyebQGSA4wcb+8BKtAdA46QSNAdDJMtAFIDjB5v5MMeqpAY0g0GAAAAB+AAP/wAf/4B//+B//+D///H///n///v///////////////3///n///j///B//+B//+Af/4AP/wAB+AAAAAA=="%7D,"vice":%7B"-autostart":"spball.prg"%7D%7D)** -|- **[browse ca65 assembler source](https://github.com/Zirias/c64spball)**
Start and stop the bouncing ball with `sys49152`.
* This leaves the C64 BASIC running, that's done by moving the VIC-II address space up to `$C000`, which requires copying the screen contents and the character set (font).
* It hooks into the system IRQ and to avoid flicker, changes the source of this IRQ to the VIC-II graphics chip, so updates are always done between frames.
* Glitches:
1. `RUN/STOP + RESTORE` is broken, don't try.
2. With the VIC-II as IRQ source, the cursor blinks slightly slower and `TI$` will lag behind as well.
3. when stopping while the border is flashed (very unlikely but possible), it **stays** white -- you have to restore it manually.
[Answer]
# Clojure, ~~398~~ ~~380~~ 375 bytes
```
(ns g(:require[quil.core :as q]))(def w 1e3)(def h 1e3)(def f 100)(def b(atom{:x f :y f :n 1 :m 1}))(q/defsketch . :size[w h]:setup #(do(q/text-font(q/create-font""f))(q/fill 255 255 255)):draw #(let[s 9{x :x y :y n :n m :m}@b c(+ x(* n s))u(+ y(* m s))](q/background 0 0 0)(reset! b{:x c :y u :n(if(< 0 c(- w f))n(* -1 n)):m(if(<(+ 0 f)u h)m(* -1 m))})(q/text"O"(:x @b)(:y @b))))
```
-18 bytes by changing the font name to an empty string to default it, inlining the boundary checks, and fixing the bottom boundary issue (which you can see in the GIF). Fixing that actually saved bytes.
-5 bytes by changing to a more succinct destructuring syntax and shrinking the ball by a pixel.
Uses [Quil](http://quil.info/).
I tried to switch to functional mode, but it required a lot of extra code and ended up being more expensive.
```
(ns bits.golf.ball-bounce
(:require [quil.core :as q]))
(def width 1000)
(def height 1000)
(def font-size 100)
; Mutable state holding the properties of the ball. n and m are the directions on the x and y axis.
(def ball (atom {:x 300 :y 600 :n 1 :m 1}))
(q/defsketch b
:size [width height] ; Window size
:setup #(do
(q/text-font (q/create-font "Arial" font-size)) ; Set the font
(q/fill 255 255 255)) ; And the text color
:draw
#(let [speed 9
; Deconstruct the state
{:keys [x y n m]} @ball
next-x (+ x (* n speed))
next-y (+ y (* m speed))
; I'm adding/subtracting the font-size so it stays in the window properly
x-inbounds? (< 0 next-x (- width font-size))
y-inbounds? (< (+ 0 font-size) next-y height)]
; Wipe the screen so the ball doesn't smear
(q/background 0 0 0)
; Reset the state
(reset! ball
{:x next-x
:y next-y
:n (if x-inbounds? n (* -1 n))
:m (if y-inbounds? m (* -1 m))})
; Draw the ball
(q/text "O" (:x @ball) (:y @ball))))
```
[](https://i.stack.imgur.com/nM7nb.gif)
(Note, the new version doesn't bounce early along the bottom of the screen like it does in the GIF.)
[Answer]
## Racket 247 bytes
```
(let*((w 500)(h(* w 0.6))(x 100)(y 0)(d 10)(e d)(G(λ(t)(set! x(+ x d))(when(or(> x w)(< x 0))
(set! d(* d -1)))(set! y(+ y e))(when(or(> y h)(< y 0))(set! e(* e -1)))
(underlay/xy(rectangle w h"solid""white")x y(circle 10"solid""black")))))(animate G))
```
Ungolfed:
```
(require 2htdp/image
2htdp/universe)
(let* ((wd 500) ; define variables and their initial values
(ht 300)
(x 100)
(y 0)
(dx 10)
(dy 10)
(imgfn ; define function to draw one frame; called repeatedly by animate fn;
(λ (t) ; t is number of ticks till now- sent by animate fn; ignored here;
; update location (x and y values):
(set! x (+ x dx))
(when (or (> x wd) (< x 0))
(set! dx (* dx -1))) ; invert direction at edges
(set! y (+ y dy))
(when (or (> y ht) (< y 0))
(set! dy (* dy -1))) ; invert direction at edges
; draw image:
(underlay/xy
(rectangle wd ht "solid" "white") ; draw background
x y ; go to location (x,y)
(circle 10 "solid" "black") ; draw ball
))))
(animate imgfn)) ; animates the images created by imgfn (default rate 28 times/sec)
```
Output:
[](https://i.stack.imgur.com/UNdnr.gif)
[Answer]
# Simons´ BASIC (C64), ~~66~~ 65 bytes
One byte saved thanks @ShaunBebbers.
I need only one line here, because Simons´ Basic has a modulo function.
AfaIk, this requires a physical C64 and a Simons´ BASIC module
(or any other BASIC extension that has a `mod` function).
```
0fori=0to623:print"{CLR}":poke1024+40*abs(mod(i,48)-24)+abs(mod(i,78)-39),81:next:goto
```
Type in these 69 characters:
```
0fOi=0TO623:?"{CLR}":pO1024+40*aB(mod(i,48)-24)+aB(mod(i,78)-39),81:nE:gO
```
`{CLR}` is [PETSCII](https://dflund.se/%7Etriad/krad/recode/pet2.jpg) 147, which clears the screen. Use Shift+CLR/HOME to type it in.
**bytecount**
When saved to disk, it takes 65 bytes, because the commands are tokenized:
`for`, `to`, `poke`, `abs`, `next` and `goto` are one byte each; `mod` takes two bytes.
That makes 59 bytes of code plus 4 bytes for pointers and 2 bytes for the line number.
For reference, see [Mapping the C64](http://www.unusedino.de/ec64/technical/project64/mapping_c64.html) and search for `$800` (BASIC Program Text).
(You can find the Video Screen Memory Area at `$400`.)
**breakdown**
The program loops `I` from 0 to 623 (=LCM of 48 and 78 minus 1). In the loop
* the screen is cleared
* `I` gets mapped to 39..0..38 respectively 24..0..23
* and the blob (PETSCII 81) is put at the corresponding position in the video memory
(like the original program does).
When the loop is done, the program is restarted by jumping to line 0.
# C64 BASIC, ~~77~~ 76 bytes
```
0fori=0to623:print"{CLR}"
1poke1024+40*abs(i-48*int(i/48)-24)+abs(i-78*int(i/78)-39),81:next:goto
```
---
Unfortunately I need two lines, because even with all possible abbreviations it would take 83 characters - too many to use the C64 line editor:
```
0fOi=0to623:?"{CLR}":pO1024+40*aB(i-48*int(i/48)-24)+aB(i-78*int(i/78)-39),81:nE:gO
```
(A hex editor could be used to create a longer line - which would make it 73 bytes.)
[Answer]
# Jelly, 37 bytes
```
“ñc‘Ọ24ḶŒḄṖ⁸ị⁷x⁸µ80ḶŒḄṖ⁸ị⁶x⁸‘œS.1
Ç1¿
```
With some help from [this answer](https://codegolf.stackexchange.com/a/110480/63647) for getting the loop and escape characters right. Currently it bounces around in a 80x24 screen, but that can be easily modified in the code.
The coördinates in each direction can be represented as elements of two lists `[0, 1,..., 24, 23,..., 1]` and `[0, 1,..., 80, 79,..., 1]`, let's call them `Y` and `X`, that are infinitely repeated. This infinite repetition can be emulated using modular indexing -- using `ị` in Jelly. Example: in the `i`th iteration the ball is at position `(X[i%|X|], Y[i%|Y|]) = (iịY, iịX)`. The moving *ball* is just the cursor that is put into position by emitting `iịY` newlines and `iịX` spaces.
## Demo
[](https://i.stack.imgur.com/5bsw3.gif)
## Explanation
```
“ñc‘Ọ24ḶŒḄṖ⁸ị⁷x⁸µ80ḶŒḄṖ⁸ị⁶x⁸‘œS.1 Monadic helper link - argument i.
Resets the terminal, prints Y[i] newlines,
X[i] spaces and returns i + 1.
“ñc‘ Set the output to [27, 99]
Ọ Convert to characters and print (\x1bc)
-> Cursor is at position (0,0)
24Ḷ Lowered range of 24. Yields [0,...,23].
ŒḄ Bounce. Yields [0,...,23,22,...,0].
Ṗ Pop. Yields [0,...,23,22,...,1] = Y.
⁸ị Modular index i (⁸) into Y. The current
value is the Y coordinate, y.
x Repeat y times
⁷ the newline character ('\n').
⁸ Output that (y times '\n') and continue
with value i.
-> Cursor is at position (0, y)
µ Monadic chain separation.
80ḶŒḄṖ Same as above, but this time yielding X.
⁸ị Modular index i into X, yielding the
value for x.
x Repeat x times
⁶ the whitespace character.
⁸ Output that (x times ' ') and continue
with value i.
-> Cursor is at position (x, y), the
final position.
œS.1 Wait 0.1 seconds.
‘ Return i + 1.
Ç1¿ Main (niladic) link.
1¿ While true.
Ç Call the helper link. The first time
there is no argument and i will be [],
which is cast to 0 when used as integer
(e.g. try ‘¶Ç). After that, the previous
return value (i + 1) is used.
```
[Answer]
# SmileBASIC, ~~85~~ 74 bytes
```
SPSET.,9M=MAINCNT
SPOFS.,ASIN(SIN(M/5))*122+192,112+71*ASIN(SIN(M/3))EXEC.
```
The position of the ball can be modelled with 2 triangle waves, and the shortest way I could find to produce them in SmileBASIC was arcsine(sine(x)). (the algorithm using MOD was longer since SB uses `MOD` instead of `%`)
[Answer]
## CSS/HTML, 200 + 7 = 207 bytes
```
p{position:relative}a{position:absolute;animation:infinite linear alternate;animation-name:x,y;animation-duration:7.9s,2.3s}@keyframes x{from{left:0}to{left:79ch}}@keyframes y{from{top:0}to{top:24em}}
```
```
<p><a>O
```
This version shows you the size of the canvas and also gives the animation a more pixilated feel:
```
p {
position: relative;
width: 80ch;
height: 25em;
border: 1px solid black;
}
a {
position: absolute;
animation: infinite alternate;
animation-name: x, y;
animation-duration: 7.9s, 2.3s;
animation-timing-function: steps(79), steps(23);
}
@keyframes x {
from {
left: 0;
} to {
left: 79ch;
}
}
@keyframes y {
from {
top: 0;
} to {
top: 24em;
}
}
```
```
<p><a>O</a></p>
```
[Answer]
# Dyalog APL, 44 bytes
```
{⎕SM∘←0,G←⍺+⍵⋄G∇⍵×1-2×⊃1 G∨.≥G⎕SD⊣⎕DL.1}⍨1 1
```
Explanation:
* `{`...`}⍨1 1`: call the given function with ⍺=⍵=1 1
+ `⎕SM∘←0,G←⍺+⍵`: store `⍺+⍵` in `G`, display a `0` at that location in the `⎕SM` window.
+ `⎕DL.1`: wait 1/10th of a second
+ `⊃1 G∨.≥G⎕SD`: check if `G` is at the `⎕SM` window boundary (`1≥G` or `G≥⎕SD`, `⎕SD` is the **s**creen **d**imensions)
+ `1-2×`: map `[1,0]` onto `[¯1,1]`, to flip the direction of travel
+ `⍵×`: multiply the current direction of travel by that
+ `G∇`: recursion, let `G` be the new location (`⍺`) and `⍵....` be the new direction (`⍵`).
[Answer]
# PHP, ~~112~~ ~~97~~ ~~94~~ ~~103~~ 102 bytes
```
for(;;usleep(1e5),$i%=624)echo($r=str_repeat)(A^K,99),$r(A^a,abs($i%78-39)),O,$r(A^K,abs($i++%48-24));
```
bounces a capital `O` on a 40x25 grid, starting at the top right corner;
prints 99 newlines to clear the screen.
Run with `-nr`.
`A^K` = `chr(10)` = newline
`A^a` = `chr(32)` = space
[Answer]
# C + curses, 190 bytes
```
#include<curses.h>
w;h;x;y;d;main(e){initscr();curs_set(0);getmaxyx(stdscr,h,w);for(d=e;;usleep(20000),mvaddch(y,x,32)){mvaddch(y+=d,x+=e,48);if(!y||y>h-2)d=-d;if(!x||x>w-2)e=-e;refresh();}}
```
**Explanation:**
```
#include<curses.h>
w;h;x;y;d;
main(e)
{
initscr();
curs_set(0);
getmaxyx(stdscr,h,w);
// initialize distances to 1 (e is 1 when called without arguments)
// wait for 1/5 second, then write space character at current pos
for(d=e;;usleep(20000),mvaddch(y,x,32))
{
// advance current pos and write ball character (`0`)
mvaddch(y+=d,x+=e,48);
// check and change direction:
if(!y||y>h-2)d=-d;
if(!x||x>w-2)e=-e;
// trigger output to screen:
refresh();
}
}
```
[Answer]
# [QBasic](https://en.wikipedia.org/wiki/QBasic), 71 bytes
```
DO
CLS
LOCATE 24-ABS(i MOD 46-23),80-ABS(i MOD 158-79)
?"O";
i=i+1
LOOP
```
This version loops forever, although it might break when `i` gets too large--I haven't tested. Also, how fast it moves depends on the hardware you use, but on the emulator at [Archive.org](https://archive.org/details/msdos_qbasic_megapack) it runs too fast to see the motion. Therefore, here's a somewhat friendlier version that terminates once the ball gets back to the top left corner:
```
FOR i=0TO 3634
CLS
LOCATE 24-ABS(i MOD 46-23),80-ABS(i MOD 158-79)
?"O";
z=COS(1)
NEXT
```
Change the `COS(1)` to `COS(1)+COS(1)+COS(1)` (etc.) to slow it down further. [Try it here!](https://archive.org/details/msdos_qbasic_megapack)
### Explanation
Our bounding box is QBasic's standard text mode screen, 80 characters wide by 24 characters tall, 1-indexed. As several other answers have observed, we can calculate the correct x and y coordinates, given a frame number, using modular arithmetic:
| Frame `i` | `i MOD 46` | `(i MOD 46)-23` | `ABS((i MOD 46)-23)` | y = `24-ABS(...)` | x = `80-ABS(...)` |
| --- | --- | --- | --- | --- | --- |
| 0 | 0 | -23 | 23 | 1 | 1 |
| 1 | 1 | -22 | 22 | 2 | 2 |
| 22 | 22 | -1 | 1 | 23 | 23 |
| 23 | 23 | 0 | 0 | 24 | 24 |
| 24 | 24 | 1 | 1 | 23 | 25 |
| 45 | 45 | 22 | 22 | 2 | 46 |
| 46 | 0 | -23 | 23 | 1 | 47 |
| 47 | 1 | -22 | 22 | 2 | 48 |
| 79 | 33 | 10 | 10 | 14 | 80 |
| 80 | 34 | 11 | 11 | 13 | 79 |
After that it's just an issue of clearing the screen with `CLS`, moving to the proper coordinates with `LOCATE`, and printing `"O"`.
[Answer]
# Python 2, ~~176~~ 168 Bytes
This assumes a terminal size of 80x24. Definitely not optimal but I'm new to golfing so yeah.
```
import time;x=y=d=e=1
while 1:
m=[[' 'for i in' '*80]for j in' '*24];x+=d;y+=e;m[y][x]='O';time.sleep(.1)
if x%79<1:d=-d
if y%23<1:e=-e
for r in m:print''.join(r)
```
Thanks to R. Kap for suggesting the x%79<1 instead of x<1or x>79 and ditto for y.
[Answer]
# Rebol/View, 284 266 bytes
```
rebol[]p: 3x9 d:[3 3]view layout[b: box blue 99x99 effect[draw[circle p 2]]rate :0.01 feel[engage: func[f a e][if a = 'time[case/all[p/x < 2[d/1: abs d/1]p/y < 2[d/2: abs d/2]p/x > 98[d/1: negate d/1]p/y > 98[d/2: negate d/2]]p/x: p/x + d/1 p/y: p/y + d/2 show b]]]]
```
Ungolfed:
```
rebol []
p: 3x9 ;; starting position
d: [3 3] ;; direction
view layout [
b: box blue 99x99 effect [
draw [
circle p 2
]
]
rate :0.01 feel [
engage: func [f a e] [
if a = 'time [
case/all [
p/x < 2 [d/1: abs d/1]
p/y < 2 [d/2: abs d/2]
p/x > 98 [d/1: negate d/1]
p/y > 98 [d/2: negate d/2]
]
p/x: p/x + d/1
p/y: p/y + d/2
show b
]
]
]
]
```
[Answer]
## C 294 bytes
```
#include<graphics.h> f(){int d=0;g,x,y,a=0,b=0;initgraph(&d,&g,NULL);x=30;y=30;while(1){x+=6;y+=7;if(y<60)b=0;if(x<60)a=0;if((y>getmaxy()-40)) b=!b;if((x>getmaxx()-40))a=!a;if(b){y-=18;x+=3;}if(a){x-=15;y+=2;}usleep(10000);setcolor(4);cleardevice();circle(x, y,30);floodfill(x,y,4);delay(45);}}
```
Ungolfed version:
```
#include<graphics.h>
void f()
{
int d=DETECT,g,x,y,r=30,a=0,b=0;
initgraph(&d,&g,NULL);
x=30;
y=30;
while(1)
{
x+=6;
y+=7;
if(y<60)
b=0;
if(x<60)
a=0;
if((y>getmaxy()-40))
b=!b;
if((x>getmaxx()-40))
a=!a;
if(b)
{
y-=18;
x+=3;
}
if(a)
{
x-=15;
y+=2;
}
usleep(10000);
setcolor(RED);
cleardevice();
circle(x,y,r);
floodfill(x,y,RED);
delay(45);
}
}
```
## Explanation
* So in order to begin with this, I had to get `graphics.h` in my `/usr/include` directory. Therefore, i searched and [this](https://askubuntu.com/questions/525051/how-do-i-use-graphics-h-in-ubuntu) is what I found. It is a TurboC Graphics implementation using SDL for Linux. One could also use OpenGL. In windows, I guess it is already installed, not sure about MacOS.
* `void initgraph(int *graphdriver, int *graphmode, char *pathtodriver);` initialises the system and puts it in a graphics mode, in this case graphics driver is automatically detected. Please refer to this [link](https://www.cs.colorado.edu/~main/bgi/doc/initgraph.html) for more details.
* `x` and `y` are coordinates that determines the ball's position.
* `a` and `b` are flags, `a` is set to zero when the `x` value drops below 60 and `b` is set to zero when `y` drops below 60.
* The flags are toggled when `x` and `y` exceeds boundary values of window, and the coordinates are accordingly adjusted.
* I put a `usleep` so that my CPU does not get stressed out.
* One should normally use a `closegraph()` call, in order to close the window. But it's missing here.
Must be compiled with the linker flag `-lgraph`
It runs smoother on real hardware. :)
[](https://i.stack.imgur.com/ZbXAV.gif)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 42 bytes
```
1thXH_XI`Xx8E70hZ"79HZ}&(DH4M\1>EqI*XIH+XH
```
This uses a 70×16 screen and character `O`. If you wait for a few bounces you'll see the ball hitting a corner.
[**Try at MATL Online!**](https://matl.suever.net/?code=1thXH_XI%60Xx8E70hZ%2279HZ%7D%26%28DH4M%5C1%3EEqI%2aXIH%2BXH&inputs=&version=19.8.0)
Screen size can be easily modified in the code. The relevant part is `8E70`, which pushes `8`, doubles it, and pushes `70`. For example, for a 80×25 screen replace by `5W80`, which pushes `5`, squares it, and pushes `80` (or replace by `25 80`, but that requires one more byte).
Also, adding `tD` at the end of the code shows the current position in real time (vertical, then horizontal, `1 1` is upper left). As an example, for a `80×18` screen,
```
1thXH_XI`Xx9E80hZ"79HZ}&(DH4M\1>EqI*XIH+XHtD
```
[**Try it too!**](https://matl.suever.net/?code=1thXH_XI%60Xx9E80hZ%2279HZ%7D%26%28DH4M%5C1%3EEqI%2aXIH%2BXHtD&inputs=&version=19.8.0)
### Explanation
This uses an infinite loop. Position is kept in clipboard `H` as a 1×2 vector, and direction is kept in clipboard `I` as a 1×2 vector with entries `1` or `-1`.
Each iteration clears the screen, defines a matrix of spaces, writes an `O` at the relevant position, and displays it. Then the position and directio need to be updated.
Position is `1`-based, and thus the edges of the screen are `1` and the maximum screen size. So if position modulo screen size gives `0` or `1` in either the first or second components, which means we have reached a vertical or horizontal edge respectively, that component of the direction vector is negated. After that, the new direction is added to the current position to obtain the new position.
[Answer]
Here's the ZX Spectrum listing.
```
10 FOR n=0 to 7
20 READ a: POKE USR "a"+n, a
30 NEXT n
40 DATA 60,126,243,251,255,255,126,60
50 LET x=10:LET y=10:LET vx=1: LET vy=1
60 PRINT AT y,x;"\a"
70 IF x<1 OR x>30 THEN LET vx=-vx
80 IF y<1 OR x>20 THEN LET vy=-vy
90 LET x=x+vx: LET y=y+vy
100 PRINT AT y-vy,x-vx;" ": GO TO 60
```
[Answer]
# [Lua](https://en.wikipedia.org/wiki/Lua_(programming_language)) ([LÖVE 2D](https://love2d.org/)), 130 bytes
```
x,y,a,b=0,0,1,1
function love.draw()a=(x<0 or x>800)and-a or a
b=(y<0 or y>600)and-b or b
x=x+a
y=y+b
love.graphics.points(x,y)end
```
Lua is not the best language when it comes to code golf, but here you go! A few points worth mentioning:
* The default canvas size is 800 x 600. It can be changed in the configuration file, but I didn't see any size restrictions, so I left it as is.
* [`love.draw()`](https://love2d.org/wiki/love.draw) is LÖVE's drawing function and it has a predetermined name. Alternative LÖVE functions that could be used would be [`love.update(dt)`](https://love2d.org/wiki/love.update) and [`love.run()`](https://love2d.org/wiki/love.run) -- the first being longer, in bytes, and the latter being shorter, yes, but without a built-in infinite loop. Thus, `draw()` seems to be our best bet here.
* The above version uses [`love.graphics.points`](https://love2d.org/wiki/love.graphics.points) to draw the ball. Although shorter, I am not sure it is allowed. Here is a GIF of how it runs:
[](https://i.stack.imgur.com/yW6aL.gif)
As you can see (or perhaps can't), there is a single pixel moving on the screen. While that saves up bytes, it's not the most satisfying of results.
So I've made an **alternative 131 bytes solution**:
```
x,y,a,b=0,0,1,1
function love.draw()a=(x<0 or x>795)and-a or a
b=(y<0 or y>595)and-b or b
x=x+a
y=y+b
love.graphics.print(0,x,y)end
```
This one uses [`love.graphics.print`](https://love2d.org/wiki/love.graphics.print) -- which prints text -- and a `0` as a ball, making it much more visible and appealing.
[](https://i.stack.imgur.com/MFG7s.gif)
[Answer]
# CHIP-8, ~~36~~ ~~34~~ 28 bytes
```
FF29 'LDF I,vF //load digit sprite for the value of vF (should be 0)
4000 'SNE v0,0 //if x is 0...
6201 'LD v2,1 //set x velocity to 1
403C 'SNE v0,3C //if x is 3C...
62FF 'LD v2,FF //set x velocity to -1
4100 'SNE v1,0 //if y is 0...
6301 'LD v3,1 //set y velocity to 1
411B 'SNE v1,1B //if y is 1B...
63FF 'LD v3,FF //set y velocity to -1
D015 'DRW v0,v1,5 //draw sprite
D015 'DRW v0,v1,5 //draw sprite again to clear it.
8024 'ADD v0,v2 //add x velocity to x
8134 'ADD v1,v3 //add y velocity to y
1202 'JMP 202 //jump to second instruction
```
No fancy tricks here...
Requires an interpreter that draws sprites correctly (only one sprite can be drawn per frame, which slows down the program enough for you to be able to see it).
[Low quality video](https://www.youtube.com/watch?v=jJpk0vTjhss)
[Answer]
## PostScript (GhostScript), 259 bytes
I don't think PostScript was built for animation... improvements welcome!
```
[/x{4}/y{196}/X{2}/Y{-2}/b{x y 4 currentgray add 0 360 arc fill}/p{/x x X add def}/q{/y y Y add def}/g{setgray}>>begin[/PageSize[320 200]>>setpagedevice{1 g
b p q
x 316 gt x 4 lt or{/X X -1 mul def}if
y 196 gt y 4 lt or{/Y Y -1 mul def}if
0 g b flushpage}loop
```
Needs GhostScript for `flushpage`.
[](https://i.stack.imgur.com/1cSNe.gif)
(It runs smoother when the screen recorder isn't also running.)
[Answer]
# Commodore C64 BASIC - 75 71 tokenised BASIC bytes, 77 73 characters with keyword abbreviations
The following answer is taken from the YouTube channel [8-BIT Show and Tell](https://youtu.be/jhQgHW2VI0o "8-BIT Show and Tell, One-Line Bouncing Ball: Commodore 64 BASIC"), so Robin Harbron deserves the credit, along with credit to the YouTube channel [JosipRetroBits](https://www.youtube.com/@JosipRetroBits).
```
0?"{CLEAR}":DEFFNA(B)=ABS(T-INT(T/B)*B-B/2):POKE1024+FNA(48)*40+FNA(78),81:T=T+1:GOTO
```
### Older solution
```
0?"{CLEAR}":DEFFNA(B)=ABS(T-INT(T/B)*B-B/2):Z=1024+FNA(48)*40+FNA(78):POKEZ,81:T=T+1:GOTO
```
The listing is above one logical (Commodore C64) line in Commodore BASIC, so it must be typed with keyword abbreviations, as in the screen shot below.
A full explanation of what is going on is linked above.
[](https://i.stack.imgur.com/lhHlY.png)
[Answer]
# ZX Spectrum BASIC - 179 bytes
Here it is just condensed a little bit. It's 179 bytes with the ball graphics included
```
10 LET a=10: LET b=10: LET c=1: LET d=-1: FOR e=0 TO 7: READ f: POKE USR "a"+e, f: NEXT e
20 DATA 60, 126,243,251,255,255,126,60
30 PRINT AT b,a;"\a"
40 IF a<1 OR a>30 THEN LET c=-c
50 IF b<1 OR b>20 THEN LET d=-d
60 LET a=a+c: LET b=b+d: PRINT AT b-d, a-c;" ": GO TO 30
```
] |
[Question]
[
## Description
Given a list of positive integers, write the shortest code to find the number count of the longest consecutive sequence of numbers within the list.
## Input
A list of positive integers. You can assume the list is not empty and may contain duplicates.
## Output
The length of the longest consecutive sequence of numbers within the list.
## Test cases
```
Input: [100, 4, 200, 1, 3, 2]
Output: 4 // because of [1, 2, 3, 4]
Input: [1, 2, 3, 4, 5]
Output: 5 // because of [1, 2, 3, 4, 5]
Input: [10, 9, 8, 7, 6, 5]
Output: 6 // because of [5, 6, 7, 8, 9, 10]
Input: [1, 1, 1, 2, 3]
Output: 3 // because of [1, 2, 3].
Input: [5]
Output: 1 // No consecutive numbers exist. You can leave the Output empty too or output -1. It must be shown by this no consecutive numbers exist
Input: [7, 3, 9, 5, 4, 2, 8]
Output: 4 // because of [2, 3, 4, 5].
```
Code with shortest bytes win, and if equated, the earlier post wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
f‘$ƬL’
```
[Try it online!](https://tio.run/##y0rNyan8/z/tUcMMlWNrfB41zPx/uP1R05rI//@jow0NDHQUTHQUjEC0oY6CMZAZq8OlEA1kG4G5QElTiAhQhaWOgoWOgrmOghlcFKwNqhosAhE3B2sGqjeFmA/UGBsLAA "Jelly – Try It Online")
```
Ƭ -- iterate until the result doesn't change, collecting intermediate value
f‘ -- keep the values that are still in the list when each value is incremented
L -- take the length (number of intermediate values, including the initial list and the empty list at the end)
‘ -- decrement
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṬŒg§Ṁ
```
A monadic Link that accepts a list of positive integers and yields the length of the longest consecutive sequence.
**[Try it online!](https://tio.run/##y0rNyan8///hzjVHJ6UfWv5wZ8P/o5Me7pyhc7g961HDHAVbO4VHDXM1I///j442NDDQUTDRUTAC0YY6CsZAZqwOl0I0kG0E5gIlTSEiQBWWOgoWOgrmOgpmcFGwNqhqsAhE3BysGajeFGI@UCNY3BgsYg6WMjSEKYWYaAaWM42NBQA "Jelly – Try It Online")**
### How?
```
ṬŒg§Ṁ - Link: list of positive integers, A e.g. [4, 8, 3, 4, 2, 7, 4]
Ṭ - untruth {A} [0, 1, 1, 1, 0, 0, 1, 1]
( i.e.: 2 3 4 7 8 )
Œg - group runs of equal elements [[0], [1, 1, 1], [0, 0], [1, 1]]
§ - sums [0, 3, 0, 2]
Ṁ - maximum 3
```
[Answer]
# [Haskell](https://www.haskell.org/), 32 bytes
```
f[]=0
f l=1+f[n|n<-l,elem(n+1)l]
```
[Try it online!](https://tio.run/##XU7NDsIgDL7vKXrcsmoAndNEHsEnIBw4QFwEsgyOvjsWtpNJk/b7Td8mfaz3pTilJesceMlHp@I3Pk8erbehjyMfvC7ZppykUpwxhCuCqJsjXOjUqOgSDZA0VUzqA@GOMCPcDq4FDifhys0tRM5pb6XIX5vYR@sumCWChGDWF/TrtsR8dgO0x8oP "Haskell – Try It Online")
Repeatedly filters `l` by only keeping elements `n` where `n+1` is also in `l`, and counts how many repetitions until the list is empty.
[Answer]
# [Python 3](https://docs.python.org/3/), 45 bytes
```
f=lambda l:len(l)and-~f({*l}&{x-1for x in l})
```
[Try it online!](https://tio.run/##XY7RCsIgFIbve4pzFRpnMOfcVtCTRBfGkgbmxtjFYqxXtzMtVqHowe87v6d7DLfWSe/N0er7pdZgD/bqmOXa1cnTsGln5@00JsK0PYzQOLAz913fuIHlCIadRJoiUJktt0CQVJ4530RHRYfeAiFPrbB4ByDsESqEEqH4EeSnO@4lY4UiwC87zlOGjyhQxbEo@V8RmKHEnE5aBP0L "Python 3 – Try It Online")
Without using sets:
**[Python](https://docs.python.org/3/), 48 bytes**
```
f=lambda l:l>[]and-~f([x for x in l if-~x in l])
```
[Try it online!](https://tio.run/##XY7NCoMwEITvfYo5GljBGH/aQvsikkOKhAppFPFgL756upoW25IlGXa@nezwnO69VyHYizOPW2vgzu7aaOPbdLFJM8P2I2Z0Hg6dTZcotQjD2PkpKQhMySwjsMzXVxIUSy3EITJlZLi3OcyVu1m9AwgnwpFQE6ofQH2mY60Zuyk384uO@9TbRxxYxrU4@R@RlJOigm8@bIYX "Python 3 – Try It Online")
Repeatedly filters `l` by only keeping elements `x` where `x+1` is also in `l`, and counts how many repetitions until the list is empty.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 35 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.375 bytes
```
ÞǔĠṠG
```
**[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9QSIsIiIsIsOex5TEoOG5oEciLCIiLCJbMTAwLCA0LCAyMDAsIDEsIDMsIDJdXG5bMSwgMiwgMywgNCwgNV1cblsxMCwgOSwgOCwgNywgNiwgNV1cblsxLCAxLCAxLCAyLCAzXVxuWzVdXG5bNywgMywgOSwgNSwgNCwgMiwgOF1cblszLCA1LCA3LCA5LCAxMV1cbls3LCA3LCA2LCA2LCA1LCA1XSJd)**
### How?
Port of my Jelly answer.
```
ÞǔĠṠG - list of positive integers e.g. [4, 8, 3, 4, 2, 7, 4]
Þǔ - unthruth [0, 1, 1, 1, 0, 0, 1, 1]
( i.e.: 2 3 4 7 8 )
Ġ - group runs of equal elements [[0], [1, 1, 1], [0, 0], [1, 1]]
Ṡ - sums [0, 3, 0, 2]
G - maximum 3
```
[Answer]
# [J](https://www.jsoftware.com), 22 bytes
```
[:#[:+/ .*~^:a:~1=-//~
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrsS3aSjnaSltfQU-rLs4q0arO0FZXX78OInmzS5MrNTkjXyFNwdDAQEfBREfBCEQb6igYA5kwOXMw11JHwRSiREfBAq4NzDUGi5sizAKrttAB6TRDkjDFYyLERQsWQGgA)
We view this is a graph problem. Let's consider the example `10, 9, 8, 7, 6, 5` for the explanation:
* `1=-//~` Create an adjacency matrix, where two numbers are connected if their difference is 1 (signs matter):
```
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1
0 0 0 0 0 0
```
This says that 10 connects to 9, 9 connects to 8, etc.
* `[:+/ .*~^:a:` Multiply this matrix by itself until we reach a fixed point. One self-multiplication, eg, tells us the connections after two steps:
```
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1
0 0 0 0 0 0
0 0 0 0 0 0
```
After two steps, 10 connects to 8, 9 to 7, etc. Then two self multiplications show us the connections after 3 steps, and so on. Eventually, we'll reach a matrix of all zeroes and stop, and the length of this chain tells us the length of the longest consecutive run of numbers.
* `[:#` So we return that length.
## [J](https://www.jsoftware.com), port of ovs's answer, ~~21~~ 20 bytes
```
1#@}.((e.>:)#[)^:a:~
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrscVQ2aFWT0MjVc_OSlM5WjPOKtGqDiJ1s0uTKzU5I18hTcHQwEBHwURHwQhEG-ooGAOZMDlzMNdSR8EUokRHwQKuDcw1BoubIswCq7bQAek0Q5IwxWMixEULFkBoAA)
[Answer]
# [R](https://www.r-project.org), ~~50~~ ~~38~~ 37 bytes
*Edit: -1 bytes thanks to Giuseppe*
```
\(x,y=rle(1:max(x)%in%x))max(y$l*y$v)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3VWM0KnQqbYtyUjUMrXITKzQqNFUz81QrNDVBnEqVHK1KlTJNqOLtaRrJGoYGBjoKJjoKRiDaUEfBGMjU1FRQVjDhAksDuWBBoBJTsLgpRByo2lJHwUJHwVxHwQwmZwbTA0EgnWBxY7A4RI2BQn6RgiFYwBxsMtAYU4gTgObhsNoIgiCyEOcvWAChAQ)
[Answer]
# [Scala 3](https://www.scala-lang.org/), ~~74~~ ~~73~~ 70 bytes
Port of [@xnor's Python answer](https://codegolf.stackexchange.com/a/265097/110802) in Scala.
Thanks to [@corvus\_192](https://codegolf.stackexchange.com/users/46901/corvus-192)'s comment and [@Kjetil S](https://codegolf.stackexchange.com/users/64733/kjetil-s)'s comment.
---
```
def f(l:Seq[Int]):Int=if(l.size<1)0 else 1+f(l.filter(l contains _+1))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hVHLSsNAFMVtvuJQXMzQUTJN0tZgF24EQVfFVRGJcVJGxqlmxoWWrP0IN3Wh_2S_xpsEwZSIzHDvncM59zVvny7PTBZttnuvq5s7lXtcZNpiHQC3qsA9PVhWLl2Kk7LMnhdzX2q7vOIpLq32mDVM4IFQbyxzg5iw_XXBzrXzTIahQCwwqr0UiCjkvBrwHVHSERGpoZIw6WOPuyUEjgSmAhOB8R-KaCd_e-sqfWz5m92brzPkpGmWekjaWamZfzVSjEQkYrJ0fthVQCb4ePLFwfTrtF5_wUw6V4-LM-tp5WRnmqBDp1_UseQhlHEKclhjhTZelcwgX1lPv-ZwPZSct9neq9ZvNq3_Bg)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 56 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 7 bytes
```
ṗ's¯1=A;@
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJHPSIsIiIsIuG5lydzwq8xPUE7QCIsIiIsIjEwMCwgNCwgMjAwLCAxLCAzLCAyIl0=)
#### Explanation
```
ṗ's¯1=A;@ '# Implicit input
ṗ' ; '# Filter the powerset by:
s¯ # Sort and get deltas
1=A # All equal to 1?
@ # Length of each inner list
# Take the maximum
# Implicit output
```
[Answer]
# [julia](https://julialang.org/), ~~24~~ 22 bytes
*Edit: 2-byte improvement due to [MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush)*
Same approach as most others here, counting how many times `v` can be intersected with `v-1` before we get an empty list
```
!v=v>[]&&!(v∩.~-v)+1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FtsUy2zL7KJj1dQUNcoedazUq9Mt09Q2hEjePKcYbWhgoKNgoqNgBKINdRSMgcxYhRo7hYKizLySnDwuoBKgEFgCqMwUXQ6oy1JHwUJHwVxHwQyLPNhQqAlocuhqzcGWAE0zhbgIaCwelxhBELIKiK9gXgcA)
### How?
```
!v =
v > [] && # return 0 if v == [] and terminate, otherwise proceed
!(v ∩ .~ -v) + 1 # recurse on the intersection of v with v + 1 and add 1
to count recursion depth. Here, ~ is bitwise not, so
~(-k) == k-1 for signed integers.
```
[Answer]
# [Factor](https://factorcode.org) + `math.extras`, 51 bytes
```
[ sort members [ - -1 = ] max-monotonic-count 1 + ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY-9bsIwFIX3PMXZkVGctA0UMVddulRMiCFEFxqB7dS-kUCIJ-mShb4TL9K5N4kiEL6SffzdP52f301esPPN9W_x-f7x9orgPJd2i0AcYHL-wo68pX2nx3RgnwdJftdkCwqoPDEfK19axiyKThHknKDjGE9I5NZIkeA8cNGpZJ5vJMYUE2R4uYddtKUDueUyoVP5y3jpexycdDHQVOoyqdb6rr1d1S5rR54vNW_U5JouO-MwZNbkA5ZQUBpzrMT3QRlnHTtbFqpwtTjVGGHVt15MXmHc66bp338)
Sort, uniquify, then count the longest run of two adjacent numbers differing by one.
[Answer]
# [Python](https://www.python.org), ~~122~~ ~~113~~ ~~101~~ ~~52~~ 51 bytes
Port of Arnaulds answer
```
lambda a:max(map(g:=lambda v:v in a and-~g(v+1),a))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY9NDoIwEIX3nmKWbRgTyr8knERZ1BCQRAox2OhZ3JAYvY5rb-NAS1DTpjOZ982b6e3ZXftDq4Z7me0e575cJ-_gKJt9IUGmjbywRnasSjNb06mGWgGJqgDhVEw7gqPk3Pa-ulOtehYglGwrXBeBUm-MAsGnNOd8ZZjQMFSbFOLCRYysAcIGIUGIEaIfwJ-7zR09FlFM4hdt9omnQWQYmrXI-R8R6KGPAb108vlbw2DiBw)
Previous Answer
```
lambda a:max(len([*l])for b,l in groupby(r in a for r in range(max(a)+1))if b)
from itertools import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY9LDgIhDIb3nqJL0JqI4_hKPIm6YOKgJAxMEBM9i5tJjF7HtbexDBofgdDC9_dvOd_qU9g521zUYnU9BNWfPkojq2IjQc4reWSmtGzZNWuunIcCDWgLW-8OdXFiPl4kRNKmXtptyWKV5D3BuVZQ8I7yrgIdSh-cM3vQVe186L6a3WuvbWAjBMWWYjBAoHQYo0DIKF1z3kmaPGnorSWkyz9w_DJAmCFMESYI4x9B9q5OO3p8oGjhlzrNM2kbkWGexiLnf4nAIWY4opMWwfStpknxCQ)
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 7 bytes
```
ˡ{N→ᵈ:∩
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FutOL6z2e9Q26eHWDqtHHSuXFCclF0OlFtz0iTY0MNAx0TECkoY6xjpGsVzRhjpGQJaJjimIbaBjqWOhY65jBuHqgCBQGsgG8c2BCi11TEEG6FjEQgwFAA)
A port of [@ovs's Jelly answer](https://codegolf.stackexchange.com/a/265096/9288).
```
ˡ{N→ᵈ:∩
ˡ{ Loop until failure, and return the number of iterations
N Check if the list is nonempty
→ Increment
ᵈ:∩ Intersect with the input
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ZLåγOà
```
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/265099/52210), so make sure to upvote him as well!
[Try it online](https://tio.run/##yy9OTMpM/f8/yufw0nOb/Q8v@P8/2tDAQMdEx8hUx0zHWMc0FgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/KJ/DS89t9j@84L/O/@hoQwMDHRMdIyBpqGOsYxSrE22oYwRkmeiYgtgGOpY6FjrmOmYQrg4IAqWBbBDfHKjQUscUZICOBVg52DBToHJjoIZYAA).
**Explanation:**
```
Z # Push the maximum of the (implicit) input-list (without popping)
L # Pop and push a list in the range [1,max]
å # Check for each value whether it's in the input-list (1 if truthy; 0 if falsey)
γ # Group adjacent equal bits together
O # Sum each inner list
à # Pop and push the maximum
# (which is output implicitly as result)
```
---
Since I was curious: a port of [*@ovs*' Jelly answer](https://codegolf.stackexchange.com/a/265096/52210) is 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) instead:
```
.ΓÐ<åÏ}g
```
[Try it online](https://tio.run/##yy9OTMpM/f9f79zkwxNsDi893F@b/v9/tKGBgY6JjpGpjpmOsY5pLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/vXOTD0@wObz0cH9t@n@d/9HRhgYGOiY6RkDSUMdYxyhWJ9pQxwjIMtExBbENdCx1LHTMdcwgXB0QBEoD2SC@OVChpY4pyAAdC7BysGGmQOXGQA2xAA).
**Explanation:**
```
.Γ } # Continue until the list no longer changes, keeping all intermediate results
# (excluding the initial value), using the (implicit) input-list
Ð # Triplicate the current list
< # Pop the top copy, and decrease all its values by 1
å # Pop it and another list, and check for each value-1 whether it's in thelist
Ï # Pop both again, and keep all values at the truthy positions
g # After the changes-loop: pop and push its length
# (which is output implicitly as result)
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~5.5~~ 5 bytes (10 nibbles)
```
,|`.$`&+~$
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWq3RqEvRUEtS061QgAlDxndFK0eY6CsY6CpY6CqY6CiY6CkY6ChaxSrFQBQA)
Port of [ovs' Jelly answer](https://codegolf.stackexchange.com/a/265096/95126).
```
,|`.$`&+~$ # full program
,|`.$`&+~$$ # with implicit arg:
`. # iterate while unique
$ # starting with input:
+~$ # add 1 to every element
`& # intersection with original list
| # now, filter this list-of-lists
$ # to include only non-empty lists
, # and return its length
```
[Answer]
# JavaScript (ES6), 51 bytes
```
a=>Math.max(...a.map(g=v=>a.includes(v)&&1+g(v+1)))
```
[Try it online!](https://tio.run/##jc9LDoIwEAbgvaeYFWlDLRQEdFFu4AkMi4aXGKREsPH2tVBDFF3YTNJJ@uXvzEUoMeS3ph@3nSxKXXEteHoU45lexQNRSoVpelRzxVNBmy5v70U5IIUdh7k1Ui7DGOtcdoNsS9rKGlXoxHyfwI5AMN2MQGjaDGPwPNht1ta8zcL4KAN7rI2@rIk7ENgTSAjEL29t/CPX1pT@mRuu7fLv@7GWrW0yD2umiOyKZpwM/tgtsLVY/QQ "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array
Math.max(... // return the maximum value in this:
a.map(g = v => // for each value v in a[],
// using a recursive callback function g:
a.includes(v) && // if a[] includes v:
1 + // increment the final result
g(v + 1) // and do a recursive call with v + 1
) // end of map()
) // end of Math.max()
```
---
# JavaScript (ES6), 56 bytes
*This version was originally shorter (50 bytes), but invalid (as pointed out by [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)). Now fixed at the cost of 6 bytes by adding `p^v?...:0`, which makes it uncompetitive.*
Expects an `Uint32Array`.
```
a=>a.sort().map(p=v=>p^v?p+1^(p=v)?i=1:m+=++i>m:0,m=1)|m
```
[Try it online!](https://tio.run/##nZDbCsIwDIbvfYpctqzOdUcVOvEhvJINytxkYteyjYngu9fugIo3E0MgCeTLn@TCO95kdanaZSVPuS6Y5izmdiPrFmFbcIUU61is0m6nLJr2Fd6VjG6FxSyrjMXWIYJR/BA6k1Ujr7l9lWdUoCq/waGsWs/d1zW/oyN1HAI@AbePlIBn0gRjDKsV@Is52DQPiBkQJDDaBAezsBHcEFgTiAiE04AJDn9QHr3X/1L25uDXqp82wXQOjoaDzeLB@DdzQQL/PMwd/Q3rJw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~48~~ 47 bytes
```
->l{1.step.find{|z|l.all?{|x|[*x..x+z]-l!=[]}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6n2lCvuCS1QC8tMy@luqaqJkcvMSfHvrqmoiZaq0JPr0K7KlY3R9E2Ora2tvZ/gUJadLShgYGOgomOghGINtRRMAYyY2O5wHImOuY6lrGx/wE "Ruby – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~23~~ ~~19~~ 13 bytes
```
IL⌈⪪⭆⊕⌈θ¬№θι1
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwyc1L70kQ8M3sSIztzRXI7ggJ7NEI7gEqCDdN7FAwzMvuSg1NzWvJDUFrqZQU1NHwS8faEB@KdCYQh2FTE2QkJKhkiYIWP//Hx1tqKMAQUY6Csaxsf91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @JonathanAllan's Jelly answer, with the "untruth" replaced by a map over range using `0` for present and `1` for absent as this lets me split on `1`s to find the longest run of `0`s. (I can't split on `0`s as this will fail if there are `10` of the same value in the list.)
```
θ Input list
⌈ Maximum
⊕ Incremented
⭆ Map over implicit range and join
№ Count of
ι Current value
θ In input list
¬ Logical Not
⪪ 1 Split on `1`s
⌈ Take the longest run of `0`s
L Take the length
I Cast to string
Implicitly print
```
Previous 19-byte solution also works with negative integers:
```
I⌈Eθ⌈Eθ∧¬⁻…·ιλθ⊕⁻λι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexIjO3NBdIF2gU6iigcR3zUjT88oGqMvNKizU885JzSoszy1KDEvPSUzUydRRyNHUUCjWBBFCqKDU3Na8kNQWqOEdHIVMTAqz//4@ONtRRgCAjHQXj2Nj/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Creates inclusive ranges between all pairs of input elements and outputs the length of the longest range that is a subset of the input.
```
θ Input array
E Map over elements
θ Input array
E Map over elements
…· Inclusive range from
ι Outer value to
λ Inner value
⁻ Remove elements found in
θ Input array
¬ Is empty
∧ Logical And
λ Inner value
⁻ Minus
ι Outer value
⊕ Incremented
⌈ Take the maximum
⌈ Take the maximum
I Cast to string
Implicitly print
```
[Answer]
# [Perl 5](https://www.perl.org/), 32 bytes
```
sub f{@_?1+f(grep$_+1~~@_,@_):0}
```
[Try it online!](https://tio.run/##hVFNb4JAFDyXXzGhGDGuFqpoq6FybZropZfGEiJ0UVJhCbu0GqN/3S7g16G1ZAPsvJl583ZTmi2t/Z7nPsKN443MZqjPM5pqXtPc7RyPOF5jYGz3Ict0BZhiahoGQZfgvviaBB3568J@QhdwCXCLuzv4NJjlnIKFUiAJJa3rHhxOAIFVSq1/pQXz2J/gkeCBoE/QOzr0/nCwSk6/5EuVaZwzVKvwLx061zO47UpYtTMvyGOGgCWcBrmIviiSPPZpxkFXERdtvLEcwSzBks5kUSwoJrlIcwEap2INwRhYBlZhLbONZ4E450JmAF@w7wS@ZC0ijuRKnypbvzwrOaZV3ZCc@nQzv0x2cbRtpbGRHkC81rUokVkINLpKaSDoRwM2HM0bHgjanAk71J2K16jgNIsSEaq1Vo8DZWGAWsssdjj6DM6WEpUuEpDv90Qlys2pZNsFiBHq7LOOAerjySsmL3VS9ike9dBaHSrb/Q8 "Perl 5 – Try It Online")
Copied idea from others here. Return count of rounds of removal of ints n where n+1 dont exists before list is empty.
[Answer]
# Rust, 74 bytes
[Try it online!](https://tio.run/##dY/dDoIgFIDvfYrTjYPGmGb@lOtJnHOs4XIpFeJ0y57dDlp3yhgcOB/f4eiuNVOpoBGVIvQNOBy71NJACReYRnF2sy7JR7IXvDJSE8oby/JO9Vo8MeCUG3GXRX@raknGYRT8@lAGjS0ZKMVDpwyhU@rMatG2UptCvnakJG7mex6DI4OD3X0GAYY5xSuaruKYniF8Elou3ODQdmKQMIgZRD822nQu05otF6xzs8Nfz8Xzp7BiuHSDpf9dfKYv)
```
|a:&[u8]|(*a.iter().min().unwrap()..).take_while(|x|a.contains(x)).count()
```
Explanation:
```
let f = |a: &[u8]| {
// create an iterator starting from the least element
(*a.iter().min().unwrap()..)
// take item if in list, stopping at the first item not in list
.take_while(|x| a.contains(x))
// get total number of items taken
.count()
};
```
[Answer]
# [**T-SQL**](https://learn.microsoft.com/en-us/sql/t-sql/language-reference?view=sql-server-ver16), 114 bytes
`SELECT MAX(c)FROM(SELECT COUNT(b)c FROM(SELECT a*(a+1)/2-SUM(a)OVER(ORDER BY a)b FROM @t GROUP BY a)X GROUP BY b)Y`
[dbfiddle](https://dbfiddle.uk/uXXcla-Q)
Readable version of the code:
```
DECLARE @t TABLE(i INT NOT NULL IDENTITY(1,1) --table with identity to emulate a 'list' (not counted in byte count)
, a INT NOT NULL);
INSERT INTO @t (a) --Assigning the 'list' values (not counted in byte count)
VALUES(100)
, (4)
, (200)
, (1)
, (3)
, (2);
SELECT MAX(c) --5. Determine the maximum count from the subquery
FROM(
SELECT COUNT(*)c --4. Count how many rows make up each group
FROM(
--After this query it is simply a matter of determining which value of b appears the most times, and how many times that is.
SELECT a*(a+1)/2-SUM(a) OVER(ORDER BY a)b /*2. Calculates the sum of values which are missing from the consecutive sequence
between 1 and a (both inclusive).
This utilises the default behaviour of the windowed function. This defaults to:
SUM(a) OVER(ORDER BY a ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
Which is far more descriptive, but too verbose for golf :).*/
FROM @t
GROUP BY a --1. Removes duplicate occurences of a, as this is just noise anyway...
)X --necessary alias
GROUP BY b -- 3. Group by b as these are the groups we want to know the size of
)Y --necessary alias
```
This algorithm does the following:
* Remove duplicate elements (essentially turn a list into a set)
* Order the elements
* Find all the consecutive sequences
* Prescribe a unique identifier for each consecutive sequence
* Get the count of elements in each distinct sequence (length of each sequence)
* Get the maximum count.
In my opinion the interesting part of this is prescribing the unique identifier.
Let's generalise the problem, starting with an arbitrary subset of the natural numbers.
$$X \subseteq \mathbb N\_{\ne 0}$$
Consider the following binary relation
$$R = \{(a, b): |a - b| \leq 1, (a, b) \in X \times X\}$$
`R` is the set of all ordered pairs which are no more than 1 distance apart.
Here the distance is taxicab or L1 or whatever you want to call it.
It's fairly easy to see that `R` is symmetric, and reflexive, but NOT transitive.
Take the example
$$X = \{1, 2, 3, 5, 6, 7, 8\}$$
$$(1, 2) \in R , (2, 3) \in R , (1, 3) \notin R$$
You can't have three distinct natural numbers all within a distance of 1 from eachother.
We need to extend the definition of `R` so that it is transitive. We need to find
the transitive closure of `R`.
$$R^{+} = R \cup \{(a, c): (a, b) \in R \wedge (b, c) \in R\}$$
Now we have an equivalence relation, and it properly describes the equivalence classes that underly this problem. However we still need to determine a label for each of these equivalence classes. Normally the smallest positive representitve of each equivalence class is chosen. This would be `[1]` and `[5]` in the example above. But these are just labels, as long as they are unique they could be anything. Let's make a function that sufficiently labels an element's equivalence class.
$$Label(i) = \sum\_{k=1}^{i} k - \sum\_{j\in X \wedge j\leq i}{j}$$
We can replace the first sum with the equivalent expression
$$ \sum\_{k=1}^{i} k = \frac{i(i + 1)}{2}$$
Thus,
$$Label(i) = \frac{i(i + 1)}{2} - \sum\_{j\in X \wedge j\leq i}{j}$$
Intuitively this is just the sum of everything 'missing' up to the current element.
$$Label(i) = \sum\_{j \in \mathbb N\_{\ne 0} \setminus X \wedge j \leq i} j$$
Now i am really interested, is there a generalisation of this? That is to say if we take the base relation `R` and redefined it:
$$R = \{(a, b): |a - b| \leq k, (a, b) \in X \times X\}, k \in \mathbb N\_{\ne 0}$$
Would there be an equivalent intuitive 'label function' for any value of `k`?
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 51 bytes
```
$
,
\d+
$*
D`1+,
O`1+
(\G1+, |1\1)+
$#1¶
O#^`
1G`
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX4VLR4ErJkWbS0WLyyXBUBvI8wdSXBox7iBOjWGMoSZQUtnw0DYuf@W4BC5DoKb/hgYGOgomOgpGINpQR8EYyOQC0kZgJlDClMsQKGOpo2Cho2Cuo2AGFgErhariMuUyBysGqjGFmAVUDAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
$
,
```
Suffix a comma to the last entry too.
```
\d+
$*
```
Convert to unary.
```
D`1+,
```
Deduplicate.
```
O`1+
```
Sort ascending.
```
(\G1+, |1\1)+
$#1¶
```
Count consecutive sequences. The first alternation is only possible at the start of the match, while the second alternation is only possible on subsequent repetitions of the capture group.
```
O#^`
```
Sort descending numerically.
```
1G`
```
Take the first (i.e. largest).
[Answer]
# Excel, 65 bytes
```
=MAX(LEN(TEXTSPLIT(CONCAT(FREQUENCY(A1#,SEQUENCE(MAX(A1#)))),0)))
```
Input is spilled *vertical* array in `A1#`.
[Answer]
# C (clang 16), 93 bytes
Using C23 `_BitInt(65536)` as a clang extension in C89 for implicit `int`. Works for input integers in the range [0,65535], e.g. 16-bit unsigned (but it takes them as an array of `int`, with an `int n` length). It returns the count.
```
typedef _BitInt(1<<16)T;f(*p,n){T b=0;for(;n--;)b|=(T)1<<p[n];for(n=1;b&=b<<1;n++);return n;}
```
First loop: Add each input to a set implemented as a bitmap (`bitset |= 1<<n`). Second loop: treating that as a wide integer, count the longest run of set bit. (Shift and AND to remove the low bit from each run of bits, count iterations until the whole thing becomes zero.)
[Godbolt](https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename:%271%27,fontScale:14,fontUsePx:%270%27,j:1,lang:___c,selection:(endColumn:1,endLineNumber:14,positionColumn:1,positionLineNumber:2,selectionStartColumn:1,selectionStartLineNumber:14,startColumn:1,startLineNumber:2),source:%27%23if+0%0Atypedef+_BitInt(1%3C%3C8)T%3Bungolfed(*p,n)%7B%0A++++T+bitset+%3D+0%3B%0A++++for(%3Bn--%3B)%7B%0A++++++++bitset+%7C%3D+(T)1%3C%3Cp%5Bn%5D%3B%0A++++%7D%0A++++int+retval%3D1%3B%0A++++//+https://stackoverflow.com/questions/3304705/finding-consecutive-bit-string-of-1-or-0%0A++++while(bitset+%26%3D+bitset%3C%3C1)%7B+//+doesn!%27t+count+the+iteration+that+clears+the+last+bit,+hence+retval%3D1+to+start%0A++++++++retval%2B%2B%3B%0A++++%7D%0A++++return+retval%3B%0A%7D%0A%23endif%0Atypedef+_BitInt(1%3C%3C16)T%3Bf(*p,n)%7BT+b%3D0%3Bfor(%3Bn--%3B)b%7C%3D(T)1%3C%3Cp%5Bn%5D%3Bfor(n%3D1%3Bb%26%3Db%3C%3C1%3Bn%2B%2B)%3Breturn+n%3B%7D%0A%0A%23include+%3Cstdio.h%3E%0Aint+main()%7B%0A++++int+arr%5B%5D+%3D+%7B%0A++++//++++7,+3,+9,+5,+4,+2,+8%0A++++//+1,+1,+1,+2,+3%0A++++//10,+9,+8,+7,+6,+5%0A++++//+5%0A++++100,+4,+200000,+1,+3,+2%0A++++%7D%3B%0A++++%0A++++int+n+%3D+sizeof(arr)/sizeof(arr%5B0%5D)%3B%0A++++printf(%22%25d%5Cn%22,+f(arr,n))%3B%0A%7D%27),l:%275%27,n:%270%27,o:%27C+source+%231%27,t:%270%27)),k:50,l:%274%27,m:100,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((g:!((h:compiler,i:(compiler:cclang1600,deviceViewOpen:%271%27,filters:(b:%270%27,binary:%271%27,binaryObject:%271%27,commentOnly:%270%27,debugCalls:%271%27,demangle:%270%27,directives:%270%27,execute:%270%27,intel:%270%27,libraryCode:%270%27,trim:%271%27),flagsViewOpen:%271%27,fontScale:14,fontUsePx:%270%27,j:1,lang:___c,libs:!(),options:%27-std%3Dgnu89+-Os+-Wall+-Wno-implicit-int%27,overrides:!(),selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:%275%27,n:%270%27,o:%27+x86-64+clang+16.0.0+(Editor+%231)%27,t:%270%27)),header:(),k:100,l:%274%27,m:60.39213615643205,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((h:output,i:(compilerName:%27x86-64+gcc+13.2%27,editorid:1,fontScale:14,fontUsePx:%270%27,j:1,wrap:%271%27),l:%275%27,n:%270%27,o:%27Output+of+x86-64+clang+16.0.0+(Compiler+%231)%27,t:%270%27)),l:%274%27,m:39.60786384356794,n:%270%27,o:%27%27,s:0,t:%270%27)),k:50,l:%273%27,n:%270%27,o:%27%27,t:%270%27)),l:%272%27,n:%270%27,o:%27%27,t:%270%27)),version:4) including a test caller with the test cases from the question.
See [Add two really big numbers](https://codegolf.stackexchange.com/questions/264867/add-two-really-big-numbers/265112#265112) re: `_BitInt`. Clang 16 supports very large widths: the current max is 8388608 bits for signed or unsigned, `_BitInt(1<<23)`. So not enough to handle values up to `INT_MAX`, but we don't handle negative `int` values either.
And yes, shifting and ANDing a 64KiB bitmap as a wide integer takes a ridiculous amount of asm instructions since clang fully unrolls it. I used `_BitInt(1<<8)` while developing this to keep edit/compile/run cycles short. With 1<<16 width, `clang16 -std=gnu89 -Os -Wall -Wno-implicit-int` makes 24249 lines of asm for x86-64 (only a couple of them labels instead of instructions.) It also uses about 30472 + 128 (red zone) = 30600 bytes of stack space. (64Kib = 8KiB)
Ungolfed:
```
typedef _BitInt(1<<8) T; // narrower for testing with small number inputs
/* int */ ungolfed(int *p, int n){
T bitset = 0;
for(;n--;){
bitset |= (T)1<<p[n]; // cast needed *before* the shift
}
int retval=1; // reuse n for this in the golfed version
// https://stackoverflow.com/questions/3304705/finding-consecutive-bit-string-of-1-or-0
while(bitset &= bitset<<1){ // doesn't count the iteration that clears the last bit, hence retval=1 to start
retval++;
}
return retval;
}
```
With `clang -fsanitize=undefined`, it will reject out-of-bounds inputs, e.g. *runtime error: shift exponent 200000 is too large for 65536-bit type 'T' (aka '\_BitInt(65536)')*
[Answer]
# Google Sheets, 61 bytes
`=sort(max(len(split(join(,frequency(A:A,sequence(9^4))),0))))`
Put the input in cells `A1:A` and the formula in `B1`.
Uses `frequency()` like the [Excel answer](https://codegolf.stackexchange.com/a/265111/119296). Does not require [CSE](https://support.microsoft.com/en-us/office/create-an-array-formula-e43e12e0-afc6-4a12-bc7f-48361075954d).
[Answer]
# Haskell + [hgl](https://www.gitlab.com/wheatwizard/haskell-golfing-library), 19 bytes
```
l<ixe(fl~<(<P1)<fe)
```
Uses [xnor's method](https://codegolf.stackexchange.com/a/265098/56656).
## 20 bytes
Here's one that works online:
```
P1<l<ih eq1<δ<sr<nb
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FN_czcgvyiEoUALiijsDQxJzMtMzVFIaAoNac0JZUrzcoq2jOvJFbXDkguLS1J07XYlmYbYGiTY5OZoZBaaGhzbotNcZFNXhJE8qZxbmJmnoKtQko-l4JCQZGCikKaQrShjpGOmY6xjomOZSySsDFQ2FjHMBaidcECCA0A)
### Explanation
* `nb` removes all duplicates from the list
* `sr` sorts the list
* `δ` gets the differences between consecutive elements
* `ih eq1` gets the longest contiguous sublist of `1`s
* `l` takes the length
* `P1` adds 1
## Reflection
Some things can be improved:
* The glue in `fl~<(<P1)<fe` is too much, there should be some helper function that can reduce the amount of glue here.
* `sr<nb` could probably be a single function.
[Answer]
# [Uiua](https://uiua.org), 12 [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==)
```
/↥⍘⊚-⇡⧻.⊝⊏⍏.
```
[Try it!](https://www.uiua.org/pad?src=RiDihpAgL-KGpeKNmOKKmi3ih6Hip7su4oqd4oqP4o2PLgoKRiBbMTAwIDQgMjAwIDEgMyAyXQojIE91dHB1dDogNCAvLyBiZWNhdXNlIG9mIFsxLCAyLCAzLCA0XQoKRiBbMSAyIDMgNCA1XQojIE91dHB1dDogNSAvLyBiZWNhdXNlIG9mIFsxLCAyLCAzLCA0LCA1XQoKRiBbMTAgOSA4IDcgNiA1XQojIE91dHB1dDogNiAvLyBiZWNhdXNlIG9mIFs1LCA2LCA3LCA4LCA5LCAxMF0KCkYgWzEgMSAxIDIgM10KIyBPdXRwdXQ6IDMgLy8gYmVjYXVzZSBvZiBbMSwgMiwgM10uCgpGIFs1XQojIE91dHB1dDogMSAvLyBObyBjb25zZWN1dGl2ZSBudW1iZXJzIGV4aXN0LiBZb3UgY2FuIGxlYXZlIHRoZSBPdXRwdXQgZW1wdHkgdG9vIG9yIG91dHB1dCAtMS4gSXQgbXVzdCBiZSBzaG93biBieSB0aGlzIG5vIGNvbnNlY3V0aXZlIG51bWJlcnMgZXhpc3QKCkYgWzcgMyA5IDUgNCAyIDhdCiMgT3V0cHV0OiA0IC8vIGJlY2F1c2Ugb2YgWzIsIDMsIDQsIDVdLg==)
```
/↥⍘⊚-⇡⧻.⊝⊏⍏.
⊏⍏. # sort
⊝ # deduplicate
⇡⧻. # copy & make series of same length
- # subtract
⍘⊚ # invert where
/↥ # maximum
```
[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==)
```
/↥⊜⧻.⍘⊚⊝
```
[Try it!](https://uiua.org/pad?src=RiDihpAgL-KGpeKKnOKnuy7ijZjiipriip0KCkYgWzEwMCA0IDIwMCAxIDMgMl0KRiBbMSAyIDMgNCA1XQpGIFsxMCA5IDggNyA2IDVdCkYgWzEgMSAxIDIgM10KRiBbNV0KRiBbNyAzIDkgNSA0IDIgOF0=)
Inspired by Dominic van Essen's [Uiua answer](https://codegolf.stackexchange.com/a/265952/97916).
```
/↥⊜⧻.⍘⊚⊝
⊝ # deduplicate
⍘⊚ # inverted where, i.e. how many times each element occurs
⊜⧻. # lengths of contiguous equal elements
/↥ # maximum
```
Original answer:
# [Uiua](https://uiua.org), 18 [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==)
```
+1/↥⊜⧻.=1≡/-◫2⊝⊏⍏.
```
[Try it!](https://uiua.org/pad?src=RiDihpAgKzEv4oal4oqc4qe7Lj0x4omhLy3il6sy4oqd4oqP4o2PLgoKRiBbMTAwIDQgMjAwIDEgMyAyXQpGIFsxIDIgMyA0IDVdCkYgWzEwIDkgOCA3IDYgNV0KRiBbMSAxIDEgMiAzXQpGIFs1XQpGIFs3IDMgOSA1IDQgMiA4XQpGIFszIDUgNyA5IDExXQpGIFs3IDcgNiA2IDUgNV0=)
```
+1/↥⊜⧻.=1≡/-◫2⊝⊏⍏.
⊏⍏. # sort
⊝ # deduplicate
◫2 # windows of size two
≡/- # difference of each window
=1 # change non-ones to zeros
⊜⧻. # find length of each contiguous group of ones
/↥ # maximum
+1 # plus one
```
] |
[Question]
[
Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details.
The story continues from [AoC2015 Day 5](https://adventofcode.com/2015/day/5), Part 2.
---
Santa needs help figuring out which strings in his text file are naughty or nice. He has already tried two sets of rules, but they're totally ad-hoc, cumbersome, and janky, so he comes up with a single rule that will rule them all:
* A string is nice if it contains a pattern `n..i..c..e` where the letters `n`, `i`, `c`, and `e` are equally far apart from each other.
In other words, a string is nice if, for some non-negative integer `x`, it matches the regex `n.{x}i.{x}c.{x}e`.
**Input:** A nonempty string of lowercase English letters (you can choose to take uppercase instead).
**Output:** Truthy or falsy indicating whether the input string is nice or not. You can choose to
* output truthy/falsy using your language's convention (swapping is allowed), or
* use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
Truthy:
```
nice
noizcue
aaaaanicezzzz
nnicceee
```
Falsy:
```
x
abc
ince
nnicce
nniccexe
precinct
```
[Answer]
# [J](http://jsoftware.com/), 35 bytes
```
1 e.[:,'nice'E."1]#~#$"1&><@=\@i.@#
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRVS9aKtdNTzMpNT1V31lAxjleuUVZQM1exsHGxjHDL1HJT/a3KlJmfkK6iHFJWWZFSqQ3hpChA9CF5@ZlVyKZJAIgiA1FQBAZI6oFByaipQIdRYt8ScYiRTK5BMSEpGcDLzUGwDm4LOr0ASKShKTQbqKVHn@g8A "J – Try It Online")
Consider `f 'noizcue'`:
* `<@=\@i.@#` Create a bunch of identity matrixes, up to the input length:
```
┌─┬───┬─────┬───────┬─────────┬───────────┬─────────────┐
│1│1 0│1 0 0│1 0 0 0│1 0 0 0 0│1 0 0 0 0 0│1 0 0 0 0 0 0│
│ │0 1│0 1 0│0 1 0 0│0 1 0 0 0│0 1 0 0 0 0│0 1 0 0 0 0 0│
│ │ │0 0 1│0 0 1 0│0 0 1 0 0│0 0 1 0 0 0│0 0 1 0 0 0 0│
│ │ │ │0 0 0 1│0 0 0 1 0│0 0 0 1 0 0│0 0 0 1 0 0 0│
│ │ │ │ │0 0 0 0 1│0 0 0 0 1 0│0 0 0 0 1 0 0│
│ │ │ │ │ │0 0 0 0 0 1│0 0 0 0 0 1 0│
│ │ │ │ │ │ │0 0 0 0 0 0 1│
└─┴───┴─────┴───────┴─────────┴───────────┴─────────────┘
```
* `#$"1&>` Extend each row to the input length, filling extra rows with zeroes:
```
1 1 1 1 1 1 1
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
1 0 1 0 1 0 1
0 1 0 1 0 1 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
1 0 0 1 0 0 1
0 1 0 0 1 0 0
0 0 1 0 0 1 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
1 0 0 0 1 0 0
0 1 0 0 0 1 0
0 0 1 0 0 0 1
0 0 0 1 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
1 0 0 0 0 1 0
0 1 0 0 0 0 1
0 0 1 0 0 0 0
0 0 0 1 0 0 0
0 0 0 0 1 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
1 0 0 0 0 0 1
0 1 0 0 0 0 0
0 0 1 0 0 0 0
0 0 0 1 0 0 0
0 0 0 0 1 0 0
0 0 0 0 0 1 0
0 0 0 0 0 0 0
1 0 0 0 0 0 0
0 1 0 0 0 0 0
0 0 1 0 0 0 0
0 0 0 1 0 0 0
0 0 0 0 1 0 0
0 0 0 0 0 1 0
0 0 0 0 0 0 1
```
* `#$"1&>` Use those as masks to filter the input (rows of all zeroes elided to save space):
```
noizcue
nice
ozu
nze
oc
iu
nc
ou
ie
z
nu
oe
i
z
c
ne
o
i
z
c
u
n
o
i
z
c
u
e
```
* `1 e.[:,'nice'` Is "nice" in any resulting rows?
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
ā€ι»'ŒÁå
```
[Try it online!](https://tio.run/##yy9OTMpM/f//SOOjpjXndh7arX500uHGw0v//08EgbzM5NQqIAAA "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/2/0jjo6Y153Ye2q1@dNLhxsNL/wMFubjKMzJzUhWKUhNTFDLzuFLyuRQU9PMLSvQheqEUmnE2CipgtXmp//Myk1O58vIzq5JLU7kSQQAkUgUEXHlAVnJqaipXBVdiUjJXZh5IJVgMSlWkchUUpSYDJUq4AA)
```
ā -- range from 1 to the length of the input s
€ι -- for each value k in this range, push [s[0::k], ..., s[k-1::k]]
» -- join each inner list by spaces and the resulting strings by newlines
'ŒÁ -- dictionary compressed word "nice"
å -- is this a substring?
```
Or look at the output of just [`ā€ι»`](https://tio.run/##yy9OTMpM/f//SOOjpjXndh7a/f9/Xl5mZnJyRSoA)
[Answer]
# JavaScript (ES6), 59 bytes
```
s=>[...s].some((_,i)=>s.match(`n.{${i}}i.{${i}}c.{${i}}e`))
```
[Try it online!](https://tio.run/##dY7BCoMwEETv/QzpIYF2/yD@SCk13a7tFs2KSYsofnsaxZOkcxmYxwzztl/rsecunJ08KNYmelNeAMBfwUtLSt1OrE3pobUBX6pyMB0nnmfeHDenSuuI4rw0BI08Va0Kx0iF1od9LDziJ0fsoqU1JuWaiSHRWt2zIbd3x0zKLn9rHf8LhhzqesI0FxKKPw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ ~~12~~ 11 bytes
```
ẆmþJẎ“£uƇ»e
```
[Try it online!](https://tio.run/##y0rNyan8///hrrbcw/u8Hu7qe9Qw59Di0mPth3an/n@4e8vh9kdNa45OerhzBpCO/P8/LzM5lSsvP7MquTSVKxEEQCJVQMCVB2Qlp6amclVwJSYlc2XmgVSCxaBURSpXQVFqMlCiBAA "Jelly – Try It Online")
-5 bytes by adapting [emanresu A's approach](https://codegolf.stackexchange.com/a/237937/66833)
-1 byte thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!
## How it works
```
ẆmþJẎ“£uƇ»e - Main link. Takes a word W on the left
Ẇ - Contiguous substrings S of W
J - Yield the range 1 ‚â§ i ‚â§ len(W)
þ - For each pair (S, i):
m - Take the ith elements of s
Ẏ - Tighten into a list of strings
“£uƇ» - Compressed string; "nice"
e - Is this in the list of strings?
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~42~~ 41 bytes
```
n(.)*i(?<2-1>.)*(?(1)^)c(?<-2>.)*(?(2)^)e
```
[Try it online!](https://tio.run/##LcqxCoAwDATQPf8hpIJCO4sd/QuxhgxZIohC6c/XVHrLHY@7@RFNdcDtqIqzGwXjEia/2sSI3u2OTKbQIRhwrSrEoJcUehlSS5NiAbVFzAwZ0kkg2p6/9cr8AQ "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 1 byte by porting @ZaelinGoodman's regex. Explanation:
```
n(.)*i
```
Match `n`, followed by `x` characters, capturing `x` in capture group `1`, followed by `i`.
```
(?<2-1>.)*(?(1)^)c
```
Match `x` characters by popping from capture group `1`, simultaneously capturing into capture group `2`, followed by `c`.
```
(?<-2>.)*(?(2)^)e
```
Match `x` characters by popping from capture group `2`, followed by `e`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
ǎ?żvef‛ߦc
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLHjj/FvHZlZuKAm8OfwqZjIiwiIiwibm4uaS5jLmVlISEhIl0=)
```
«é # Substrings
v # Each...
e # Get every nth character for each of...
?ż # 1...input length
f # flattened
c # Includes
‛ߦ # Compressed string 'nice'
```
[Answer]
# [Python](https://docs.python.org/3/), 66, 64, 62, 61 (@dingledooper), 60 bytes (@Kevin Cruijssen)
```
f=lambda s,i=1:s>s[:i]and('nice'in s[::i])|f(s,i+1)|f(s[i:])
```
[Try it online!](https://tio.run/##bY3BCoMwDIbvewpvtmwX2a3gXkQ81NhiwMViO3Cyd@@iDEbE/5R8fH8S3mmY6J6zr0f77HpbxBvWlYmP2BhsLfWqJARXIhVMGOmPV@xcq31o0LQ6hxkpKf9Ttb78wYQrvCSzWzZz5UibKTgn9UWWOxA70vHjfuMELRKG2QGXE8P8BQ "Python 3 – Try It Online")
[Old version](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRoVgn09bQSknJpjg60yo2MS9FQz0vMzlVPTNPoTjayiozVrMmTQOoSNsQzAAp0vxfUJSZV6KRBlWqqcmFEMjPrEouRRVLBAGQyiogQFUNFE1OTUVVXoGqOSkZhZ@Zh24j2AwsQhWoggVFqclAzSVAwf8A "Python 3 – Try It Online")
[Old version](https://tio.run/##K6gsycjPM/6fZhsDxDmJuUkpiQrFOpm2hlZKSjbF0ZlWsYl5KRppGkAxbUPNGiADJKaZX6Sel5mcqp6Zp1AcbWWVGav5v6AoM68EqBIioanJhRDIz6xKLkUVSwQBkMoqIEBVDRRNTk1FVV6BqjkpGYWfmYduI9gMLEIVqIIFRanJQM0lQMH/AA "Python 3 – Try It Online")
[Old version](https://tio.run/##bY3BCsIwDIbvPkXZZSt6Kd6Ke5LaQ9d1GNB0tB3MvXzN9CARA4E/X/4/mZ/lFvFcp/5KfXePYXQin6BXumku2YC2Dsdu6ogdlYxJkDRKW5Itgg8toMhGa7CyzgmwkPezkPLwBRE2v3Dm9tqdGxV3E/UhcPvKw4NnM@Dvx/eNP2jlcE7BU7gQrC8 "Python 3 – Try It Online")
[Old version](https://tio.run/##bY3BCsIwDIbvPkXZZSvuUrwV9yS1h67rMKDpaCvMvXzN9CARA4H8X/4/WZ7lGvFU5@FCfXP3cXIi9zAo3TTnbEBbh1M3d8SOSsYkaDRK2x5ItAg@tIAiG63ByrokwELuz0LKwxdE2PyDM7fX7tyouJuoD4HbVx4ePdOAvx/fN/6glcMlBU/hQrC@AA "Python 3 – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 72 bytes
```
lambda s:'nice'in[L:=range(len(s))]+[s[i::j+1][:4]for j in L for i in L]
```
[Try it online!](https://tio.run/##bY1BDsIgFET3noJdIV0ZXRiS3qA3QBYUQX9TfwnQpPbyCHVhMM5q/svMfPeKjxlPF@eT7a5pUs/hpkjgDYI2DaDoeecV3g2dDNLAmGxFEMD52B6l4GdpZ09GAkh6UizsVibnASO19LPD2OELZtj0UjNVVJJbVp3OVBtTx9e6POjqBvz9uG/8QWsNnTc6l2OG6Q0 "Python 3.8 (pre-release) – Try It Online")
Same code pattern as yesterday?
[Answer]
# Excel, 78 bytes
```
=MAX(LET(q,REPT("?",SEQUENCE(LEN(A1))-1),COUNTIF(A1,"*n"&q&"i"&q&"c"&q&"e*")))
```
[](https://i.stack.imgur.com/cgLRa.png)
Input is in the cell `A1`. Returns `1` for truthy and `0` for falsey.
* `REPT("?",SEQUENCE(LEN(a))-1)` creates an array of strings, all made entirely of `?` and varying in length from 1 to the length of the input minus 1. If the input is `nice` then this returns `['','?','??','???']`.
* `LET(q,REPT(~)` defines the results of the previous step to be `q` so we can reference it multiple times later using just the variable name and save bytes.
* `COUNTIF(A1,"*n"&q&"i"&q&"c"&q&"e*")` does the actual checking. `COUNTIF()` accepts wild cards where `*` is any number of characters (including zero) and `?` is exactly one character. Here, we search for something like `*n?i?c?e*` except the number of question marks varies with the results of the `REPT()` function. For a four letter word, we will search for all of these combinations: `*nice*`, `*n?i?c?e*`, `*n??i??c??e*`, and `*n???i???c???e*`.
* `MAX(LET(~,COUNTIF(~)))` returns the max value of all those `COUNTIF()` checks. Since we only ever check one cell in any one of those, the max value will be `1` even if it appears multiple times such as in `nicenice` or `nicenoiocoe`.
[Answer]
# TypeScript Types, 313 bytes
```
//@ts-ignore
type a<S,T>=T extends[infer C,...infer T]?S extends`${0 extends C?string:C}${infer S}`?a<S,T>:0:1;type b<S,T>=a<S,T>|(S extends`${string}${infer S}`?b<S,T>:never);type c<S,T=S,N=[],>=b<S,["n",...N,"i",...N,"c",...N,"e"]>|(T extends`${string}${infer T}`?c<S,T,[...N,0]>:0);type M<S>=1 extends c<S>?1:0
```
[Try it online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4BlAGgBUA+AXmsPQA9x1EATSAbVkQBm6VIQDClAHRT+QkdQC6AfnLM2HbgAMAJAG8ADKvZdIYxZHCp+8AFyiAvrpnDC5OxsVkqda3usBGAG5cAkIAIwoaBk9IgB8AChVWI01dc0tEeAcdJxFXd3CvWmtEdAA3YQBKIPwiAGMI6noqADl6HnlKBgLKHgAiRF7JKWbKXthBqQkR3tqJ4dH0XvlaeKYk9UhtHTSrLJzCajdFeq8eyZG9ZZ8q4KIAWQoGP0MNwhPaRT8fAMxsGoODPRCA9+rBaotaD8QIQYQA9RR-ELUZ5AkEoWAAL1qAFcIVDgDDCPDEURqAAmQio0i9Yi02mIMHoDHMjG9SGYaFwhG3A4AZkpwOpiAZtXB6DxHIJXN+PIAYoDBb0WGz8YTiXKUYriKFZuzOUTuf9ZRSqWNEOCVZK1YaQrL+abhWCLXqpQaSYRZQAWAVokXglgS-XEoA)
[Answer]
# Python 3, 79 bytes:
```
import re
lambda s:any(re.findall(('.'*i).join('nice'),s)for i in range(len(s)))
```
[Try it online!](https://tio.run/##bY1BCsIwEEX3PUV2yYh040YEb@ImphMdSSdhGqHt5WMqiET8u/94fyYt@R75cExSaExRshLs/PlSgh2vg1XTyfJiBHtPPNgQjNG93hH0j0hsNJNDDfsJfBRFiliJ5RuagGwmAChJiLPxHxO6L4i0umfL7JbNXGtau1KH2OpzO766phP/fnzf@IPmFiZBV8e5wvIC)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~25~~ 16 bytes
```
⊙θ⊙θ№✂θκLθ⊕μnice
```
[Try it online!](https://tio.run/##XYyxCsMwDER/xXiSwJ06dgq0hQ6FQr/AyIIIVJU4TiBfr9prb3uPu6M5V/pmdX9VsQaTHXAXK5MqLClEjpjCv7Qhb8uWdYW3CvGwmsLDqPKHrXEBwcHtKrsUhqfYtoL0VtdnxHHSdxF7Lu7WgZjZT7v@AA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if nice, nothing if not. Explanation:
```
θ Input string
‚äô Any index satisfies
θ Input string
‚äô Any index satisfies
θ Input string
‚úÇ Sliced in steps of
μ Inner index
‚äï Incremented
κ From outer index
Lθ To the end of the string
‚Ññ Count i.e. contains substring
nice Literal string `nice`
```
[Answer]
# [Rust (1.53+)](https://www.rust-lang.org/), 118 111 bytes
```
|mut s:&str|loop{(1..s.len()).any(|j|s.bytes().step_by(j).take(4).eq(*b"nice"))|(s=="")&&break ""!=s;s=&s[1..]}
```
[Try it online!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=bc39c366434f7cf71b794613fe42843a "Rust – Try It Online")
This only works on Rust 1.53 and newer as older Rust versions did not implement `IntoIterator` for arrays, but only for array references, so the `eq` comparison would end up trying to compare `u8` with `&u8` which would not work without doing something like `b"nice".iter().copied()`, a good 15 extra characters.
* -7 bytes by replacing the outer range with `loop` (thanks @AnttiP)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 57 bytes
Developed on my own, then discovered as I checked the other solutions before posting that Neil beat me to this method with their excellent [Retina Answer](https://codegolf.stackexchange.com/a/237923/99902); so credit where credit is due.
Outputs False for Nice, and True for Naughty.
```
!($args-match'n(.)*i(?<2-1>.)*(?(1)$)c(?<-2>.)*(?(2)$)e')
```
[Try it online!](https://tio.run/##TY/LCsIwEEXX9itqiJqIFexWq4V@gKLuRKSG0Ub6kCbF0tpvjxMV8S7C4Z5khtyLB5QqgTQ1Lr24gduaPqNxeVVeFmuRjHI25WPJVgvfmy0R2YrNOOUCG8//Fj4WMOKmc6gGpaNYgcJRISO5FEAmJC9kIypLsY1tG4w1yALAqtrqs8BT5p9Xb/eD2uK9BIFaE/6/6@kOWqd32OyiSukiW59vIPQxbPd4I6Cn@RZUleqADfGL9MQ7pzPmBQ "PowerShell – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 71 bytes
```
s->sum(i=1,#s,sum(j=1,(#s-i)\3,[Vec(s)[i+j*k]|k<-[0..3]]==Vec("nice")))
```
[Try it online!](https://tio.run/##RYvBDsIgEER/hdALq9BoepV@hhfkUAk12yolxSa18d8R0MS57JudGd/NKG4@9kTGINqwPBjKI68CzzgkZFUQCJeGq7M1LIDC/bAb9Xs8CXWo60ZrKXNCHRpLASB23t9fLBDREj@jeyak2VDSpz1wor5dTqibcDNLwS4r/7ekkiVjrC3hWhpXkw@637bkf1ot1RA/ "Pari/GP – Try It Online")
Outputs the number of "nice" patterns, truthy when this number is nonzero.
[Answer]
# Java 8, 94 bytes
```
s->{int i=s.length();for(;!s.matches(".*n.{"+i+"}i.{"+i+"}c.{"+i+"}e.*")&&i-->0;);return i<0;}
```
Outputs `false` for truthy results and `true` for falsey results.
[Try it online.](https://tio.run/##PZAxc8IwDIV3foXqgYvJxcdcF5bOZWHsdTBGgCBRcrHCUbj89lRpQzXYz3qne591DtdQnPeXIZYhJfgIxI8ZALFgewgRYTM@AXZ1XWJgiNlWWuIjJOvV6Gd6JAlCETbAsBpSsX7oNNAquRL5KKfM@kPdZv4luSpIPGHKjFuwe5icctPTU8SnQLcwdj6nolgvvfUtStcy0NvS94MfA5tuV2rglHutaQ@Vgk9on18Q7B/1mDvxCiZ5DwnhFQyTfoxruscOIYw1du5awKoiIo5C1Q3hBmEXdSERJ3O61GpajGqIcakpSTIDxtrfYIDtdxKsXN2JaxRASs6eCLlRhpxd/O/YaZn98AM)
**Explanation:**
```
s->{ // Method with String parameter and boolean return-type
int i=s.length(); // Start `i` at the length of the input-String
for(; // Continue looping as long as:
!s.matches(".*n.{"+i+"}i.{"+i+"}c.{"+i+"}e.*")
// We haven't found "nice" yet (with `i` delimited chars)
&&i-->0;); // And `i` hasn't reached 0 yet
// (Decreasing `i` by 1 after every check with `i--`)
return i<0;} // After the loop: return whether `i` is -1
```
Java's [String#matches](https://docs.oracle.com/javase/10/docs/api/java/lang/String.html#matches(java.lang.String)) checks the entire String with implicit leading `^` and trailing `$`, hence the need for the leading/trailing `.*` in the regex-check.
[Answer]
# [Zsh](https://www.zsh.org), 37 bytes
```
repeat $#1 {<*~*n$2i$2c$2e*;2+=?;}>$1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwU01jeLUkvyCEoXUipLUvJTUlPSc_CSF1KKi1IrMEgUQp7g0qbhkaWlJmq7FTdWi1ILUxBIFFWVDhWobrTqtPBWjTBWjZBWjVC1rI21be-taOxVDiOLlmlw2NjYq9hDe6milvPzMquTSVKXYBRAhAA)
Outputs via exit code: `0` for naughty, `1` for nice. Requires options `extendedglob errexit globsubst`.
Explanation:
* `>$1`: create a file named {input}
* `repeat $#1`: do {length of input} times:
+ `<*~`: search for a file *not* matching:
- `*n$2i$2c$2e*`: construct a pattern using the variable `$2`
* over the course of the loop, this makes `*nice*` `*n?i?c?e*` `*n??i??c??e*` etc.
* `*` matches anything; `?` matches any single character. These patterns match all possible "nice" strings
+ `errexit`: if there was no non-matching file (i.e., `*n$2i$2c$2e*` *did* match), then exit the program with code `1`
+ append `?` to the variable `$2` (which starts out empty) to construct the new level of pattern
* I used a numbered variable `$2` rather than a named variable because it can be placed directly adjacent to a letter (like `$2i`)
* `globsubst` is needed so that `$2` can be treated as a pattern, not a literal string
* `extendedglob` is needed to enable the `~` pattern negation syntax
Combining `errexit` with pattern negation basically does a De Morgan's Law transformation on the whole program, matching *any* of the constructed patterns.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~56 ...~~ 51 bytes
```
->s{(0..s.sum).any?{|x|s[/#{%w(n i c e)*(?.*x)}/]}}
```
[Try it online!](https://tio.run/##NY1NCsIwEIX3c4qAKEnR1AO0FkVw2QOIizROJdCmpbGY/p09JmLfZh4z33vT9cXgytQdTmaiR84NN33NuNBDNs12Nvd4M20/VBNFJEEW0YxHli3xY1ncq2meaZLc8vzKK6XRgFYSQTdqlD2CCAqb0Qu0dxIRIeAAhQjRy3lNWhCFBKVD/kf@h0VoO5T@8AZPA7QkvOW1aOmuZHvfs3r3BQ "Ruby – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, ~~75~~ 74 bytes
```
[ all-subseqs [ dup length 4 / ⌈ group flip first "nice">array = ] ∃ ]
```
[Try it online!](https://tio.run/##RY@xbsMwDER3f8XBe9wW6NSgc9GlS5ApyKAojCtUpRSJAhyvWTL0K/MjDhWjLYfjgY@ETgdjJaRpvXr/eHtBpmMhtpQ7GiSZjC9KTP5/jm8jn3fpCjsb9oQ@hRId94iJRE4xORb0xJSMd6MRFzhj2TSt7lOrLbjRlupMrTodtSpRb4kUNe1Q@c6qOp7P7vDPDNXqi1axtNMGxvtFLjtNmrHBvkR44l7DPuMB15/LnBMH71RcyoI50O/XXrHF9XLGdnp6BJsY/QldhvVk0nQD "Factor – Try It Online")
```
all-subseqs [ ... ] ∃ ! Is there any subsequence in the input that...
dup length 4 / ‚åà group ! ...when divided into quarters, with last quarter cut off...
flip first "nice">array = ! ...the first column of these parts is equal to "nice"?
```
[Answer]
# [PHP](https://php.net/), 80 bytes
```
for($i=-1;$argn[++$i];)preg_match("~n.{{$i}}i.{{$i}}c.{{$i}}e~",$argn)?die(A):0;
```
[Try it online!](https://tio.run/##rU9BCsIwELznFSH00GIVvVpFRPQD9WZFYlztHtyEWqFY6tOt21jxA@4hM8nObmZc7trZwvF5tkUY4Hw4SQJdXGg3GAS4TyJXwOVw1aXJQ/WkUV0H2DTYo@kRnir2U9HihBAuo@k4aQWY3EqVUUbbdbqVq2W6TjNSiRD8F2jeuBOK0ICKGS0@zN1T3VX3/uDyPb4YgK4pVOUlR9MBUj/sBT9Wec7WDStK5nupb/LjsBaS609pXYFUfvL6td/IHLIRLZthNxWIr5OXdSVaurXDzRs "PHP – Try It Online")
Port of [Arnauld's answer](https://codegolf.stackexchange.com/a/237929/90841), terminates with a truthy `A` if nice, or a falsy empty string if naughty.
Note: one of the input lines has to be a falsy one if you want to see the test cases, as the program terminates if truthy (for the same reason the `die` in the test cases is changed to a `print`)
[Answer]
# [R](https://www.r-project.org/), 78 bytes
Or **[R](https://www.r-project.org/)>=4.1, 71 bytes** by replacing the word `function` with `\`.
```
function(s){for(i in 0:nchar(s))F=F|grepl(gsub("x",i,"n.{x}i.{x}c.{x}e"),s);F}
```
[Try it online!](https://tio.run/##TYzNCsMgEITvfYqwJwUpPbfk6nski6YLZQ0aQfLz7FYTKZ3DMLPzsT7bPtvIuJBjEeRmnRfUEXePJ@N78OUmda/3yZv5I6YQRwEJFCng@5YOqobVDEgV5Esf2QpgwtJvNTlaMbYyVNVtLWp7qWhMA1LjRrwC8e/Pyf3n1NrsDRZuAZm/ "R – Try It Online")
[Answer]
# [ayr](https://github.com/ZippyMagician/ayr), 29 bytes
Thanks to [this great answer](https://codegolf.stackexchange.com/a/237938/90265) for the method! I've never been very good at algorithms, so this was a great help.
```
v./'nice'E.&:,]#\:#$@1"i:&~&#
```
[Try it!](https://zippymagician.github.io/ayr#Zjo@/di4vJ25pY2UnRS4mOixdI1w6IyRAMSJpOiZ+JiM@/PShdLCc6ICcsNDgrZikiJ25pY2UnICdub2l6Y3VlJyAnYWFhYWFuaWNlenp6eicgJ25uaWNjZWVlJyAneCcgJ2luY2UnICdubmljY2V4ZScgJ3ByZWNpbmN0Jw@@//)
Glad I saw this challenge, I have only just implemented `E.`, nice to see it's already coming in handy!
# Explained
`i:&~&#` List of identity matrices of increasing size, up to the length of the string
`#$@1"` For each of these matrices, extend it to match the size of the string
`]#\:` Then filter the string using each row of the identity matrices as a boolean mask.
`'nice'E.&:,` Flatten this to a single string, find matches of the string `nice`
`v./` Or reduce. Is there a match?
[Answer]
# [Julia 1.0](http://julialang.org/), 65 bytes
```
!x=any(i->x>replace(x,Regex(join("nice",".{$i}"))=>1),keys(x).-1)
```
[Try it online!](https://tio.run/##LYzBCoMwEETv@xUx9JBAFLwW9CP6B2nclrVhlaiwWvrtqSl9lxlmhhm3SL6VnCvpPO@G6l76hHP0AY24Gz5RzDgRG80UUDvdvC/00dZ2fWvdC/fFiG3q1ubHlFRUxCqhHyIxLsaCOpkT8RrZVNEpfVXaqWgBecjlEXiiI2wIvlCS4wT4dAERQcDfAxCX5S/7iyDMCcNZrF8 "Julia 1.0 – Try It Online")
[Answer]
# [SnakeEx](http://www.brianmacintosh.com/snakeex/spec.html), 30 bytes
```
m:n{s<>}i{s<>}c{s<>}e
s{P0}:.*
```
Matches (at least once) for truthy; doesn't match for falsey.
[Try it here!](http://www.brianmacintosh.com/snakeex/) No permalinks, so you'll need to enter the input and code yourself. (FYI: Newlines in the text boxes display correctly in Chrome but not in Firefox.) You can run all of the test cases at the same time; the program will find one match for each truthy case.
### Explanation
```
s{P0}:.*
s : Define snake s as
.* Match any run of 0 or more characters
{ } With these parameters:
P After matching, move the location pointer to the end of the match
0 All matches of s are in group 0, meaning they must have the same length
m:n{s<>}i{s<>}c{s<>}e
m: Define main snake m as
Start out moving rightward (implicit)
n Match "n"
{s } Match snake s
<> in the same direction (rightward)
i{s<>} Match "i" followed by snake s again
c{s<>} Match "c" followed by snake s again
e Match "e"
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 53 bytes
```
!(($t=$args)|?{$i++;"$t"-match"n.{$i}i.{$i}c.{$i}e"})
```
[Try it online!](https://tio.run/##ZZBRTsMwDIbfc4pQAmu1jgugiko7wBDjDSHUBW8LytqSOKJa17MXJy3VKvxgyZ9//7ZcVz9g7BG07sWeZ7ztb@JYYCYKc7DJ5akVarl8jARGq1OB8hiVD4Q6FbIMGaIu6TvG8pixNF6USsIiFftCW0gCqNRZujkrfHjlmWKuJioB5vKGKjRunN3J61KVYd9UDwb/STNjtQFJkzgxlvALv@Mt4xQCocGUC2hqkAif9BjxMXQMWKeRwD39K/c6j/ktt7UuEFV5CLq35@3aWaxOm90XWbzng7GPraNrrPWeo9kKvq92TcJXb54Nx0zw5W//OBwaHev6Xw "PowerShell – Try It Online")
---
and 57 bytes alternatives:
```
!(($t=$args)|?{"$t"-match('nice'-replace'\B',($s+='.'))})
```
[Try it online!](https://tio.run/##ZZDRToQwEEXf@xV1rdJG8A@IRD9A4/qmxrB1dhfTBWynkSzLt@MUkCzxPnVO79yZTF39gHV7MKYXW57ytr@QUmAqcrtz6nTXrgSukkOOei@jstAQJRZqk9Pj7T6KpXA3aXQbKdWpvmMsk4zFkzEW29w4UAOoiqP2S5YHBeeRtHQT1QBLe0MVWj/1bvR5WZTDvLkeA/6TZsFqC5o6cWZM8RO/4i3jJIHQYMwFNDVohE86jvgYfyw4b5DANd0sC76A@SV3dBnEotwNvten9YN3WB0eN18U8Z6NwUFrT9s4FzKnsAS@z2bNxpcQno7LzPD5b/7UPHx0rOt/AQ "PowerShell – Try It Online")
```
!(($t=$args)|?{"$t"-match((echo n i c e)-join($s+='.'))})
```
[Try it online!](https://tio.run/##ZZDRboMwDEXf8xVel41Eg/0BGtI@YNW6t2maaOaWVClQYjRUyrezBBgq6n3z8fW15bL4xcpmaEzPdxBD298JwSnmabW38vLSrjitomNKKhMCVVZADhoUoIwOhc4Ft09x8BxI2cm@YywRjIUiyLXCIOS71FiUAyj0WdVLlnp559lp6XZUIS7tjauoqqfZrboudT7sm@sx4JY0C1ZWqNwkzYxJuMADtAycOGFDIXBsSlSEP@45/HvsVGhrQw48up8l3ucx3IMtTUqk8/3g@1xvXmtLxfFte3ARX8kY7LWp3TXW@swpLMLT1a7Z@OHD4/GYGb7/75@Gh0bHuv4P "PowerShell – Try It Online")
see also [Zaelin Goodman](https://codegolf.stackexchange.com/a/237982/80745)'s answer.
[Answer]
# BQN, 44 bytes
```
{‚஬¥("nice"‚â°/‚üúùï©)¬®‚àæ{(‚Üïl)‚åΩ¬®<l‚Üë‚àæ4‚•ä<ùï©‚Üë1}¬®1+‚Üïl‚Üê‚â†ùï©}
```
[Try it!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge+KIqMK04oi+KCJuaWNlIuKNty/in5zwnZWpKcKo4oi+eyjihpVsKeKMvcKoPGzihpHiiL404qWKPPCdlanihpExfcKoMSvihpVs4oaQ4omg8J2VqX0KClQg4oaQIOKAolNob3cgRgpUICJuaWNlIgpUICJub2l6Y3VlIgpUICJhYWFhYW5pY2V6enp6IgpUICJubmljY2VlZSIKVCAieCIKVCAiYWJjIgpUICJpbmNlIgpUICJubmljY2UiClQgIm5uaWNjZXhlIgpUICJwcmVjaW5jdCIKCgo=)
Not sure if J can be ported here, but I'm sure there's much scope for golfing.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 68 bytes
```
Array[c=Characters@#;""<>c[[Span@##]]==="nice"&,0{,,}+Tr[1^c],1,Or]&
```
[Try it online!](https://tio.run/##TU5NSwMxEL3vrxiysGgb0V5TU1a8eWlhewsRxpDYIJuUJMXdlv72Nd0o@C7z5n0M02M66B6TVTjdLWB/Cg68MRB9r8F5G0f4xuCs@4ywuK@2xohudAkHxpTv5XpWdhgSYwm/9K/QpZAbb946xuLMs1EZ4NNLCDgKxV8PGFAlHWJbrwl53ighuiO6tq6l5JwTZ5UmDX26UHpd7oNYvStJV3QbZDPt8sUkanjYgBE5Dw08ttWldGgFJD9@VqfC8Yabc84obt6U1sUeSuhDzdO6vwtz5h8dNLlOPw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 44 bytes
```
ay(Uc mp<bm(lt2<l<nb<δ)(eq"nice")<uz)<ss<eu
```
### Explanation
Here we are looking for the subsequence "nice" where all the elements are evenly spaced. So the first things we do to the input are, pair it with it's indexes and get all possible subsequences.
```
ss<eu
```
Now that we have these we want to check if any meet the criteria. So we use `ay` for any.
```
ay ... <ss<eu
```
Now we want to check two separate things here. One is that the values are equal to `nice` and the second is that the indexes are evenly spaced. So it would be nice to unzip the two parts e.g. `[(0,'n'),(3,'i'),(4,'c'),(9,'e')] -> ([0,3,4,5],"nice")`.
```
ay(...<uz)<ss<eu
```
Now lets formulate our two tests. One is very easy:
```
eq"nice"
```
So now we want to determine if the indices are evenly spaced. We use `δ` to determine the distances, then to check if the list only contains one value we do `lt2<l<nb`, that is we nub the list and check the length is less than 2.
```
lt2<l<nb<δ
```
Now we use `bm` to map the two functions across our tuple:
```
ay(...<bm(lt2<l<nb<δ)(eq"nice")<uz)<ss<eu
```
Lastly we convert this tuples booleans to a single boolean with `Uc mp`, which is and (`mp`) uncurried (`Uc`).
```
ay(Uc mp<bm(lt2<l<nb<δ)(eq"nice")<uz)<ss<eu
```
## Reflection
With that I'd like to reflect a bit on ways we might improve hgl in light of this. It doesn't score very well here, 44 bytes is pretty long. There are a couple of things that could be improved.
* `lt2<l<nb` is really long to determine if a list is unique. This should probably be 1 function.
* Although it wouldn't help with the size here there probably should be some way to get subsequences of a particular size. We almost had to get all the subsequences and then filter by size. It also would make this much faster.
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 47 bytes
*Here's it solved with the parsing library*
```
pP$lF bn_(h'*> Én*>l<h')$is(rM hd)$p< É<p<"ice"
```
This is a good deal faster than the previous solution since it doesn't calculate every single subsequence.
## Explanation
Let's start with the string we are looking for:
```
"nice"
```
Now we want to parse these letters with things in between them. It would be nice to use an `is` which intersperses elements in a list. So lets turn these into parsers:
```
χ<"nice"
```
This creates a list of parsers each which parses a single letter. Now we want to intersperse it with something that parsers that all parse the same amount of characters. `hd` parses a single character so `rM hd` takes a number and parses exactly that many of the character.
However this is a function, not a parser so we can't intersperse it with our parsers. We could try to supply the argument first and then intersperse but it's easier to just make our char parsers into functions. They take a single argument, a number, and just ignore it. To do this we just map `p`, (short for `const`) across the list.
```
p<χ<"nice"
```
However we can't intersperse yet. Unfortunately the parsers for `rM hd` return a string while our other parsers return a character. Even though we don't care about the results we can't put them in a list together. So we have to change one of them. It's fairly easy to just make our char parsers into string parsers:
```
p< É<p<"nice"
```
`p` turns the char into a string, `É` turns the string into a parser `p` turns the parser into a parser function. Now we can intersperse:
```
is(rM hd)$p< É<p<"nice"
```
At this point we have a list of functions to parsers. We would like to supply all these parsers with the same argument since the gaps need to be the same sizes.
There are a couple of ways to do this. The first way that springs to mind is to use a traverse. `sQ` will pull all the arguments outside and it's super cheap. But it gets a little messy instead we can use a fold.
`bn_` is a sort of chaining operator like `>>=`.
```
bn_ :: Monad m => m a -> (a -> m b) -> m a
```
We can use a fold across the list to then chain everything together.
```
lF bn_ :: (Foldable t, Monad m) => m a -> t (a -> m b) -> m a
```
So if we apply this to what we have:
```
ghci> :t F(lF bn_)$is(rM hd)$p< É<p<"nice"
F(lF bn_)$is(rM hd)$p< É<p<"nice"
:: (Integral i, Ord i) =>
Parser (List Prelude.Char) i -> Parser (List Prelude.Char) i
```
This takes a parser which produces the initial integer and gives us back the parser we want.
Now the question is "How do we figure out which integer?" We could try and have it do something like, guess every size less than the list to see, but the best way seems to be to break the `n` off of nice and get the number just as the size of the first gap after the `n`.
To parse an `n` we can do:
```
Én
```
Then after it we want a known number of characters. `h'` will parse any number of characters. And `l<` will convert that into a length.
```
Én*>l<h'
```
And we also have to allow for arbitrary characters before the first `n`:
```
h'*> Én*>l<h'
```
So now we slot that in:
```
lF bn_(h'*> Én*>l<h')$is(rM hd)$p< É<p<"ice"
```
And we have a full parser. To turn that parser into a function we use `pP`, which returns true whenever there is a parse even if it doesn't consume the entire string.
## Reflection
The parsers are very powerful but disappointingly parser based answers are usually a bit shy of the non-parser answer. Here it's 3 bytes, which is the cost to invoke a parser.
* It's probably going to be eventually necessary to add a regex processor. Sometimes we will beat regex, but it would really open up a lot of opportunities.
* I should probably make a parser evaluator that matches the parser anywhere in the input. Would save a `h'*>` here and probably in a few other places.
* `lMy` could have been useful here but `l<h'` was shorter than `lMy hd`. Not sure if this is actionable, even shortening `lMy` to one character would leave them tied. But it's of interest to note.
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 63 bytes
```
f(_++'n':x++'i':y++'c':z++'e':_)=g$map length[x,y,z]
g[x,x,x]=1
```
[Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NI15bWz1P3aoCSGWqW1UCqWR1qyoglapuFa9pm66Sm1igkJOal16SEV2hU6lTFcuVDmQAYayt4f/cxMw8BVuFNAWlvLzM5OTU1FSl/wA "Curry (PAKCS) – Try It Online")
This returns `1` if the input string is nice, and nothing otherwise.
] |
[Question]
[
This is a copy cat question of [Simplify ijk string](https://codegolf.stackexchange.com/questions/226278/simplify-ijk-string) applied to the other nonabelian group of order 8. See also [Dihedral group composition with custom labels](https://codegolf.stackexchange.com/questions/185140/dihedral-group-d4-composition-with-custom-labels).
## Challenge
Given a string made of `r` and `s` interpret it as the product of elements of the dihedral group \$D\_8\$ and simplify it into one of the eight possible values `""`, `"r"`, `"rr"`, `"rrr"`, `"s"`, `"rs"`, `"rrs"`, and `"rrrs"`. The empty string denotes the identity element \$1\$.
The evaluation rules are as follows:
$$
rrrr = 1\\
ss = 1\\
sr = rrrs
$$
The multiplication on the dihedral group is associative but not commutative. This means that you may do the simplification in any order, but you cannot reorder the items.
For the I/O format, function parameter and return from a function should be done as a string or list. You may output any amount of leading and trailing whitespace (spaces, tabs, newlines). You may use any other pair of distinct characters for `r` and `s` except for a tab, space, or newline. (If you really want to you can pick `r` or `s` to be whitespace, you can as long as you don't have leading or trailing whitespace.) It's also fine to use numbers for `r` and `s`, for example if you take `0` for `r` and `1` for `s`, it would be okay to do I/O like `[1, 0] ==> [0, 0, 0, 1]`.
## Test cases
```
"" -> ""
"r" -> "r"
"rrr" -> "rrr"
"s" -> "s"
"rs" -> "rs"
"rrs" -> "rrs"
"rrrr" -> ""
"rrrrrr" -> "rr"
"sr" -> "rrrs"
"rsr" -> "s"
"srsr" -> ""
"srr" -> "rrs"
"srs" -> "rrr"
"rsrsr" -> "r"
"rrsss" -> "rrs"
"sssrrr" -> "rs"
```
## Reference implementation
Here is a Javascript reference implementation.
```
function f(x) {
let lastx;
while(lastx !== x){
lastx = x;
x = x.replace("rrrr", "");
x = x.replace("sr", "rrrs");
x = x.replace("ss", "");
}
return x;
}
```
[Answer]
# [J](http://jsoftware.com/), 23 bytes
```
~:/I.@,~4|[:-/1#;._1@,]
```
[Try it online!](https://tio.run/##jY8/C8IwEMX3fopDwbOQphacUioBQRCcXKU4iG11ULgDF6VfPabN@afg4BBe3uPld7mzG2nACgqDCmZg/Ek0LLeblWtNutZWtfPHziRpNs71PrOqdHFU@zogY1FG9ely6x0x3tsyOh6aK3ShrWw90QtAzGGqkDDOfYkoWA6WMTz4qzSgko9Dl14abhy8F0FLM7Sky@8BP9BMLCQRFqKgiblPvHQzPxt8fWq4jwDQPQE "J – Try It Online")
Takes a boolean vector where `0` represents `r` and `1` represents `s`, and returns the result in the same encoding.
### How it works
Imagine evaluating the chunks of \$r^n s r^m s\$ from the start. If we evaluate \$sr\$ in the middle \$m\$ times, we get \$r^{n+3m}s^2 = r^{n+3m}\$. We can repeat the process to the end. Let's represent the input as a sequence of integers which represent the number of \$r\$'s when separated by \$s\$'s, like `sssrrr -> [0, 0, 0, 3]`. Then the following holds:
* The alternating sum (`[a, b, c, d, ...] -> a - b + c - d + ...`) modulo 4 is the final number of \$r\$'s.
* The length plus 1 modulo 2 is the final number of \$s\$'s.
```
~:/I.@,~4|[:-/1#;._1@,] NB. Input: a boolean vector
1#;._1@,] NB. Get the lengths of runs of r's between s's
4|[:-/ NB. Alternating sum modulo 4 = the number of final r's
~:/ NB. Reduction by unequal on the original input,
NB. i.e. the number of s's in the input mod 2
NB. = the number of final s's
I.@,~ NB. Reverse concat and generate that many 0's and 1's
```
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
ṣ1ẈṚḅ3%4,SḂ$Ø.x
```
[Try it online!](https://tio.run/##y0rNyan8///hzsWGD3d1PNw56@GOVmNVE53ghzuaVA7P0Kv4/6hxX1Fx5qON64Do0M5HDTMPtz9qWvNwdzdQorgo8v//aHV1HQX1IjBRBKaKwWwICaOKYApgaiD8YigHRsO4UEmoqqLiYrAIkAJpjwUA "Jelly – Try It Online")
Same algorithm as above. Doesn't feel well golfed to me though; maybe I missed some good alternative built-ins.
```
ṣ1ẈṚḅ3%4,SḂ$Ø.x Input: a list of zeros and ones
s1Ẉ Split at ones, then get length of each chunk
Ṛḅ3%4 Reverse, evaluate in base 3, modulo 4
, Pair with...
SḂ$ Sum % 2
Ø.x Generate that many zeros and ones respectively
```
[Answer]
# perl -p, 31 bytes
```
1while s/rrrr|ss//||s/sr/rrrs/;
```
Takes advantage of substitution returning truthy iff anything was substituted.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 18 bytes
```
{`rrrr|ss
sr
rrrs
```
[Try it online!](https://tio.run/##HYyxEgAgCEJ3vrKGhpYGaKt/N8ITfcehHHuuXnUaXVcCRBhVhQAEuiPGiWnSXxmBb@RW/mI59gA "Retina 0.8.2 – Try It Online") Straightforward port of the reference implementation.
[Answer]
# [Python 2](https://docs.python.org/2/), 58 bytes
* *[@dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper) saves 12 bytes by switch to Python 2 and finding out some bit-wise operators expression which I cannot understand!*
```
p=q=0
for b in input():p^=b;q+=~p/~b^p
print q%4*[0]+p*[1]
```
[Try it online!](https://tio.run/##XY3NCoMwEITv@xSLUPCnUFN6Sslb9CYK1aYoFLPGSPXiq6cRqymFXdhvdoahydSqPdtKPSQKDILAkuhECk@lscSmdUODCSNOhSivXSJmOs1lQUC6aQ12h0ucpXlCccZy6@IARk8cEN9185J404PkKEdZhUtFBHKsJBmOdO97m@Xgwm6PuIy72EpsF/31dXjwof3DvPAHP7K37p50A7b@2QZbyQc "Python 2 – Try It Online")
I/O as an array of integers, r = 0, s = 1.
JavaScript needs [too many bytes](https://tio.run/##dY7BTsMwDIbveQpfNidLl1HgtCmdeA5AWhSyqag0qV2hIcazlyQHbki28@t3/Nnv7tOxpz7N2zG@heVsF7bdszGGX82HS9LbbuuPSev9pO3DZpOaZCd7p9brJyL3JafVo26Vlml1f7shqmUOPHvHgcHCSZAgIsGCctSk6lQzKy5PLVUUo9jEzCJn/nYynIZ@lvgyojqIP3o97gq2g28B0OdlV0MhDc4HuTO7SwO@NHOxgIxwBGwR9oBNwQDEPHGWfdU@jhyHYIZ4kfF/SlspXCmEKo/@qMPyCw) to repeat some strings.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ ~~14~~ ~~13~~ ~~12~~ 10 bytes
*-3 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs).*
*-2 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).*
```
Δ48bγKT₄R:
```
[Try it online!](https://tio.run/##yy9OTMpM/V9TVvn/3BQTi6Rzm71DHjW1BFn9r9X5b8BlYGDAZchlAERgbAAWAQsCWYYgCkyAGSABkLCBoaEhFxCDlRkaAAA "05AB1E – Try It Online") Beats all other answers. Uses `0` for `r` and `1` for `s`.
```
Δ48bγKT₄R: # full program
Δ # while top of stack changes:
: # replace all instances of...
T # 10...
: # in...
# implicit input...
# (implicit) or top of stack if not first iteration...
K # with none of the elements of...
48 # literal...
b # in binary...
γ # split into chunks of consecutive equal elements...
: # with...
₄ # 1000...
R # in reverse
# implicit output
```
[Answer]
# JavaScript (ES6), ~~54~~ 53 bytes
Expects a string with `1` for `s` and `2` for `r`. Returns another string in the same format.
```
f=s=>s-(S=s.replace(/2222|1./,s=>s%3?"":2221))?f(S):s
```
[Try it online!](https://tio.run/##dU89a8MwEN39Kw5BQSK2TJohkKBkytwhYwhByJKbYixzF0qh7W93T8GxukSD7t37gvuwn5YcXodb1cfGj2MwZHZUyaMhjX7orPOyfuX3s9R1mbSX1V6IDTNLpfZBHtWGxu2pABCiTD9OAydA0/6YGWC2ZveDo5nIKFOzafYj0cQySHXFudAh4sG6d0lgdvDNIt0QDPw7TddtCS7J4sJd@to3/ustSKfUlv3oOQpBcu6@u9hT7LzuYitJD7Y59I1cK1iAqLiCJyeetp/cOdX@qvEP "JavaScript (Node.js) – Try It Online")
### Commented
```
f = s => // f is a recursive function taking the input string s
s - ( // test whether s is different from the updated string S
S = s.replace( // which is obtained by looking for the 1st occurrence
/2222|1./, // of either "2222", "11" or "12"
s => // and replacing it with
s % 3 ? "" // an empty string for "2222" and "11"
: 2221 // or "2221" for "12"
) // end of replace()
) ? // if s is not equal to S:
f(S) // repeat the process with S
: // else:
s // we're done: return s
```
[Answer]
# [J](http://jsoftware.com/), 29 27 bytes
```
rplc&(sr`rrrs,,.rrrr`ss)^:_
```
[Try it online!](https://tio.run/##bY/BCgIxDETvfkXwYF3oFs@FPQmePPkBurC4iAjKzP9TW6hNwB5CkscwkzzTNrhVpihOvBwk5hqDHC/nU8Lntez2xAyA3ofcMJPDNd7SsLkvj7c4J2OUNfe6w8lUdjQA/DRlrJRVxiZjUykzUKlxMyGWWq4W/AuHIhURnXii9w/NqWrZNcgjO79mWPzSFw "J – Try It Online")
* `rplc&(sr`rrrs,,.rrrr`ss)` Keep doing the needed replacements...
* `^:_` Until it stops changing
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes
```
œṣØ0Fœṣ1x4¤FœṣØ.j14BFµÐL
```
[Try it online!](https://tio.run/##y0rNyan8///o5Ic7Fx@eYeAGZhhWmBxa4gYV08syNHFyO7T18AQfiLJHDXMUdO0UHjXMfbhj0cMdXQ93TvN/uKPJ@XD7w93djxr3FRVzPdy95XD7o6Y1kf//KymBFCspcSkVQVhFIGYRjFME4hZDOMUgGSi7CMyB86BcmDYoB2EKyBCEkRCDihCmFsN5YE4RsqnFCEuKIPqgaiEOLS5GcQOQi7C2WAkA "Jelly – Try It Online")
Uses `1` for `r` and `0` for `s`
## How it works
Jelly does not have a good time with replacements. Its translate atom, `y`, only handles replacing specific, individual values (such as integers) with others, and cannot work with replacing groups of items.
Instead, we split on the values we want to replace, and join with their replacements
```
œṣØ0Fœṣ1x4¤FœṣØ.j14BFµÐL - Main link. Takes a list of bits B on the left
µÐL - Apply the chain to the left on B until it reaches a fixed point
Ø0 - Yield [0, 0]
œṣ - Split around 0,0
F - Flatten
1x4¤ - Yield [1,1,1,1]
œṣ - Split around 1,1,1,1
F - Flatten
Ø. - Yield [0, 1]
œṣ - Split around 0,1
j14 - Join with 14
B - Convert to binary
F - Flatten
```
[Answer]
# [Factor](https://factorcode.org/), ~~69~~ 65 bytes
```
[ [ "sr""rrrs""rrrr""" "ss"""[ replace ] 2tri@ ] to-fixed-point ]
```
[Try it online!](https://tio.run/##bZGxjgIhEIb7fYq57dfiSk0u111sbMxVGwvEWUNcAWfmEo3x2fdQQFmVhvDly88/0Cktjobf5XzxM4UdksUe2PdGxNgtaLdfG6uCwsB4@EOrkcETipw8GSswq@aLKWxd31XVuYKw6hri@oDmK5wipLqElClFnihlziObs51wsu848Rzy4DF93IMiznK@kEbRRQiXDfmu82s0Pw1TyG@HpJRy448XYeb6TQhz2Tvgy9BCe2se@8Z5w@sHN2wtEPpeaYQVfAqZ77CLazpzxE3j3fXvVsNeeWBRejcZ/gE "Factor – Try It Online")
*-4 thanks to @Bubbler*
* Abuse the fact that strings don't require trailing whitespace in the version of Factor TIO uses.
* `2tri@` Call a quotation on three pairs of objects. e.g. `1 2 3 4 5 6 [ + ] 2tri@` -> `3 7 11`.
* `to-fixed-point` Call a quotation until its input stops changing.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~25~~ ~~21~~ 20 bytes
```
⁻⭆⪪θs×ι⊕⊗κ×r⁴×s﹪№θs²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3M6@0WCO4BMhJ900s0AguyMks0SjUUVAqVtLUUQjJzE0t1sjUUfDMSy5KzU3NK0lN0XDJL03KAdLZmkAAU6NUpKSjYAIUsOaCmAwVLgYK@@anlObkazjnl@YhmW0EUvz/f3HRf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Based on a method @Bubbler mentioned in chat. Explanation:
```
⁻⭆⪪θs×ι⊕⊗κ×r⁴
```
Split the input on `s`s, repeat alternate segments thrice, then use string substitution to reduce the length modulo `4`.
```
×s﹪№θs²
```
Output an `s` if there were an odd number of `s`s in the input. `⁻⁻θr¦ss` also works for the same byte count, but I can't find anything shorter.
~~20~~ 19 bytes by taking I/O as strings of `0`s and `1`s:
```
⁻⭆⪪θ1×ι⊕⊗κ×0⁴×1﹪Σθ²
```
[Try it online!](https://tio.run/##NYyxDgIhEER7v4JQ7SWYHMbO1saC5BL8AeSIEhe448DfX9eo00zmZWb8w1VfHBJNNeYGJua@gW0c7sYtYBeMDVYlpJaDEteYwgZRiUv2NaSQW5jhXPoN2Z8D69@Ro1TiyOC0@z7/sGZsytyxgO0JVh4cPi0iPdL@hW8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: As above but counts `1`s by taking the digital sum of the input.
Previous 25-byte string substitution answer:
```
W№θsr≔⪫⪪θsr¦rsssθ⁻⁻θ×r⁴ss
```
[Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDOb80r0SjUEdBqbhISVNTwbG4ODM9T8MrPzNPI7ggJxMhB6SKiouLQYxCTWuugKJMoEbfzLzSYigJVBiSmZtarKFUpKSjYKIJ0gFSr2n9/39x0X/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
W№θsr
```
While the input contains `sr`...
```
≔⪫⪪θsr¦rsssθ
```
... replace all occurrences of `sr` with `rsss`.
```
⁻⁻θ×r⁴ss
```
Remove `rrrr` and `ss` and output the result.
I tried a numeric approach but it turned out to be slightly longer at 29 bytes:
```
≔⁰θFS¿Σι≦⁻³θ≦⁺²θ§⪪”)∨'✂/O;”2θ
```
[Try it online!](https://tio.run/##XYyxCsMgGIT3PsWP0y9Y@HXpkCljoIFAniCkmgrWpFFL395qsnW5O7j7bn5O@7xOLuc2BLt4JAFv3lzMugN2fktxjLv1C3IO1gCO6YW25H7aTuCuTcTe@hQE3A4WtAv6bzC42qvzeyiHEdvY@Yf@4rg5G5EpIpKK1KHFqpKSTABTjFeQNzlLyteP@wE "Charcoal – Try It Online") Link is to verbose version of code. I/O is as strings of `0`s and `1`s. Explanation: The values are encoded to integers equivalent to `0..7` (modulo `8`) in the order , `01`, `0`, `1`, `00`, `0001`, `000`, `001`. A `1` subtracts the integer from `3` while a `0` adds `2` to the integer.
```
≔⁰θ
```
Start with `0`.
```
FS
```
Loop over the input.
```
¿Σι
```
If the digit is nonzero, ...
```
≦⁻³θ
```
... then subtract the integer from `3`, ...
```
≦⁺²θ
```
... otherwise add `2` to it.
```
§⪪”)∨'✂/O;”2θ
```
Index into a look-up table to find the final result. (The number of zeros is actually given by `(x>>1)^(x&1)` and the number of ones by `x&1` but Charcoal has no bitwise XOR operator, so the best I could do was this look-up table.)
I was able to save a byte by using two variables:
```
≔⁰θ≔⁰ηFS¿Σι≦¬θ≦⁺⊕⊗θη×0﹪η⁴×1θ
```
[Try it online!](https://tio.run/##XU3JCoMwEL33KwZPM5CCQm@eCr0ItQj2B6yOGoiJZunvp@kCQk9v4S393NnedCrGs3Ny0pgL2Kg87GpOajQWsNJr8K23Uk9IBHIEbMOCMvG6W3@Fm/GfAWDlePevPHpsVHACKt1bXlh7HvBiwkMl3Ii@R01a93iXCzvM8kxAbYagDM4CTkT/gSJ7f1EZY5HH41O9AA "Charcoal – Try It Online") Link is to verbose version of code. I/O is as strings of `0`s and `1`s. Explanation: The two variables track the number of `1`s and `0`s. If there are an odd number of `1`s so far then each input `0` adds `3` otherwise it adds `1`.
```
≔⁰θ≔⁰η
```
Start with `0` `1`s and `0` `0`s.
```
FS
```
Loop over the input.
```
¿Σι
```
If the digit is nonzero, ...
```
≦¬θ
```
... then invert the parity of the `1`s, ...
```
≦⁺⊕⊗θη
```
... otherwise add `1` or `3` `0`s as appropriate.
```
×0﹪η⁴
```
Output the number of `0`s (mod 4).
```
×1θ
```
Output a `1` if appropriate.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~17~~ 16 bytes
```
λ88ok2‹o89k2⇩V;Ẋ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%CE%BB88ok2%E2%80%B9o89k2%E2%87%A9V%3B%E1%BA%8A&inputs=%60888999%60&header=&footer=)
Creative input abuse. Takes r as 9 and s as 8.
```
λ ;Ẋ # Repeat until input doesn't change
88o # Get rid of 88s (`ss`)
k2‹ # 10000 - 1 = 9999 (=`rrrr`)
o # Get rid of those as well
89 # 89 (`sr`)
k2⇩ # 10000 - 2 = 9998 (`rrrs`)
V # Replace (`sr` with `rrrs`)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes
Uses `0` and `1` for `r` and `s`.
```
Δ•BƵ?ù•₂вb€¦ι`:
```
[Try it online!](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRfqVRUrKRkYKj0qGHh/3NTHjUscjq21f7wTiDjUVPThU1Jj5rWHFp2bmeC1f9akDKQcqBSnf/RSko6CkpFYKIITBWD2RASRhXBFMDUQPjFUA6MhnGhklBVRcXFYBEgBdIeCwA "05AB1E – Try It Online")
```
Δ # Until the output doesn't change:
•BƵ?ù•₂в # Compressed integer list
[16, 1, 7, 1, 6, 17]
b€¦ # Convert to binary and remove most significant digit
["0000", "", "11", "", "10", "0001"]
ι` # Split into two separate lists by alternating the values
["0000", "11", "10"], ["", "", "0001"]
: # Replace
```
[Answer]
# Java, 76 bytes
```
s->{for(;s!=(s=s.replaceAll("rrrr|ss","").replace("sr","rrrs")););return s;}
```
[Try it online!](https://tio.run/##lZOxbsMgEIZn@ykoS6BJeAHqSF26dcpYdaCOHeFiQHc4UuT62d2rkkode7ec7v5PP/xIDO7i9sPpc/VjTlDEQLOZig@mn2JbfIrm0dZ5@gi@FW1wiOLV@SjmWlDd91hcoXZJ/iRGUtWxgI/nt3cHZ9RzXb3cvZ5uwu7WDn2z4v4w9wmUxYdGYYMGuhxc2z2HoCRQfSHKnZT6V1ASgRakoNTaagtdmSAKtMta2bo6XrF0o0lTMZkOKSGqjdxse@NyDldFTlua9T9IYKDAgJHhy2F5MPDi8RJyvJFlzKN51qxLszICIsOd4L/P/fPRlnpZvwE)
[Answer]
# [Red](http://www.red-lang.org), 82 bytes
```
func[s][while[parse s[some thru[remove["rrrr"|"ss"]| change"sr""rrrs"]to end]][]s]
```
[Try it online!](https://tio.run/##TZAxDsMwCEXn5hSIvXvVoYfoihiimNSREjuCpF16d9dVJAcWnp/9kYxKKE8JxN14hzLuaSBj@sRpFlp7NQEjy4vAFnUnlSW/hVBr4RfNkL8wxD69BE3x76vaMkgKzMTGZcwq/RDBgDqohQhH1wba0Jo7yaP6kM@d3pz07LV77JJq1m4qHuOZVp3SVncRYMlzqP@4AV4feJxGMOZL@QE "Red – Try It Online")
[Answer]
# [Bash with sed](https://www.gnu.org/software/bash/), ~~86~~ 84 bytes
Saved 2 bytes thanks to [Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma)!!!
```
until [[ $a = $1 ]];do a=$1
set -- `sed 's/sr/rrrs/;s/rrrr\|ss//'<<<$a`
done
echo $a
```
[Try it online!](https://tio.run/##fVHLasMwELz7KxYhyAMUkZYeQuxeQr8iTokbS1gQ5LKrQCDtt7urtU3ppQJ5xp7ZESN/NNQN/hYvKfQR/HL1GG4xhSscj6AbqEBv4XTatz00ld4W5BIYA2dyLSzIElpEJLunjFh/EVm7KMtSN@ei7aMr3KXrOWj4LnyPQBAiKKtA8WB@ogQw46z8zjmCmUyMLROKOXvHU8WPMkeZCOI0R5KAo4fm04jmXGaSR4q7FcArVXo51jJ2s9bGSA9aieh@xffN2v4ViUUPOk3W3NhwzVrpVCswr8CMmCnRg893y18UVBWjU/mCIXUuip7XJ4aYPEfc357q@@7A@7mO47y7kvvP@DIbfZBfMPwA "Bash – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Not Jelly's forté! ~~Perhaps~~ There is [a clever way](https://codegolf.stackexchange.com/a/226380/53748) to do it though~~?~~.
```
2“С©¡¦Ñ‘ḃœṣjƭƒµÐL
```
A monadic Link that accepts a list of `1`s (`r`) and `2`s (`s`), and yields the same.
**[Try it online!](https://tio.run/##y0rNyan8/9/oUcOcwxMOLTy0EoiXHZ74qGHGwx3NRyc/3Lk469jaY5MObT08wef/o8Z9RcWZjzauO9z@cHc3mPf/f3FxcVFREQA "Jelly – Try It Online")** (The footer translates from an `rs` string, calls the link and translates back.)
Or see the [test-suite](https://tio.run/##y0rNyan8/9/oUcOcwxMOLTy0EoiXHZ74qGHGwx3NRyc/3Lk469jaY5MObT08wef/o8Z9RcWZjzauO9z@cHc3mMd1dM/h9kdNa9z//49WUtJRKgLhIhBZDGKBCShZBJWDSoN5xRAmlIJyIBIQBUXFxSA@kARpiwUA "Jelly – Try It Online").
### How?
```
2“С©¡¦Ñ‘ḃœṣjƭƒµÐL - Link: list of integers (in [1,2]): S
µÐL - loop until no change f(X=S)->X:
2 - two
“С©¡¦Ñ‘ - code-page indices = [15,0,6,0,5,16]
ḃ - to bijective base (2) -> [[1,1,1,1],[],[2,2],[],[2,1],[1,1,1,2]]
ƒ - start with X and reduce using:
ƭ - tie (call each of these two links in turn):
œṣ - split (left) at sublists equal to (right)
j - join (left) with (right)
}...i.e:
split at [1,1,1,1], join with []
split at [2,2], join with []
split at [2,1], join with [1,1,1,2]
```
[Answer]
# [R](https://www.r-project.org/), ~~68~~ 66 bytes
```
function(x){while(x!=(x=sub("rrrr|ss","",sub("sr","rrrs",x))))0;x}
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQrO6PCMzJ1WjQtFWo8K2uDRJQ6kICGqKi5V0lJR0wALFRUA2UBAoVKEJBAbWFbX/0zSUlDS50iDKESwYu7i4GMz@DwA "R – Try It Online")
*-2 bytes thanks to [iota](https://codegolf.stackexchange.com/users/99986/iota)*
Applies reference implementation.
[Answer]
# Python 3.8, 86 bytes
```
f=lambda s,r=str.replace:f(s)if s!=(s:=r(r(r(s,"rrrr",""),"ss",""),"sr","rrrs"))else s
```
[Try it online!](https://tio.run/##ZY5BC0IhEITv/Qrbk4J06RIP/DFWSg/sJTNe@vXmIwrU3ct@M8Ow@V0er@18yag1uuSf17tXtHAsOCHk5G9hiZpmjYpHp7k46H1pBW3Eihgr5O/YlaZTjAmJQbFmrFvRUTffHP6AntAze3fAiTG1TYVDgqM9CVNgLBgrQfaZxt836gc)
[Answer]
# [Python 3](https://docs.python.org/3/), 90 bytes
```
f=lambda x,s=str.replace:f(s(s(s(x,"r"*4,""),"ss",""),"sr","rrrs"))if x not in"rrrs"else x
```
[Try it online!](https://tio.run/##VY/BbsIwDIbPy1NYPiVTxmU7IXXXvcBeIAUXIoUS2QGKJp6dpU1KQTnk/@z4/514Tftj/3ln2nlJxNAAolLxGtn3KdN0K7Wlrkg9mLV624Vj6wLMU@rtaX64d01wh3brYLDSSOIVUwxuQ@tOy3QGi4zvXxbRWBTBKjgLZhY0xncwQH9M4PtSoiCUrS97Hwh@@UR5C2ehzYEHFzWdXbD5cTwlbVYSg08a4eMbstfLdp12uVD/pzv88Wfq4S9vyLlzs0BDpE2iba21Y03cZV15tjI30AeXNnuSqTUHNNDeDJo7lnRU@aeT4lHyDDyiFJCxUzVP8KCK81iFxWU0WSyLES@u8qAJ@NlVlhAuc/VtWVTkZYeMS6zgPw "Python 3 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╚ò/i»┬⌐ÇÑ ╒‼î┐╟▌z¥²
```
[Run and debug it](https://staxlang.xyz/#p=c8952f69afc2a980a520d5138cbfc7dd7a9dfd&i=%22%22%0A%22r%22%0A%22rrr%22%0A%22s%22%0A%22rs%22%0A%22rrs%22%0A%22rrrr%22%0A%22rrrrrr%22%0A%22sr%22%0A%22rsr%22%0A%22srsr%22%0A%22srr%22%0A%22srs%22%0A%22rsrsr%22%0A%22rrsss%22%0A%22sssrrr%22%0A&m=2)
Plain Regex.
Bubbler's method is a bit long in Stax since zeroes get converted to spaces.
[Answer]
# [sed 4.2.2](https://www.gnu.org/software/sed/), 26
```
:
s/rrrr|ss//
s/sr/rrrs/
t
```
[Try it online!](https://tio.run/##HYoxDsAwCAN3/yVi73vSoUtT2Rn79lIDwnCc0DkzDyjoeqUIs1inAjsThBkC3R22aWlSrR4NJUpTEpx6@9azr3UrB38 "sed 4.2.2 – Try It Online")
[Answer]
# [///](https://esolangs.org/wiki////), 21 bytes
```
/sr/rrrs//rrrr///ss//
```
[Try it online!](https://tio.run/##K85JLM5ILf7/X7@4SL@oqKhYH0QW6evrFwOZ/4uLi4G8/wA "/// – Try It Online")
Input is appended to the end of the code.
A straightforward implementation of the three evaluation rules. Note that after every `sr` is replaced by `rrrs` recursively, the resulting string is of the form \$r^xs^y\$, and neither of the remaining rules will change this fact. Thus, we do not need to revisit `sr -> rrrs` after applying the other two rules.
[Answer]
# Pure [Bash](https://www.gnu.org/software/bash/), 75 bytes
```
a=${1//sr/rrrs};a=${a//rrrr/};a=${a//ss/};[ "$a" = "$1" ]&&echo $1||. $0 $a
```
[Try it online!](https://tio.run/##S0oszvj/P9FWpdpQX7@4SL@oqKi41hrET9QHcYr04bziYiA7WkFJJVFJwRZIGSopxKqppSZn5CuoGNbU6CmoGCioJP7//7@4uBioEQA "Bash – Try It Online") Why use sed when you don't need to?
[Answer]
# [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), 81 bytes
```
mod D is inc LIST{Nat}. eq 0 0 0 0 = nil . eq 1 1 = nil . eq 1 0 = 0 0 0 1 . endm
```
### Example Session
```
\||||||||||||||||||/
--- Welcome to Maude ---
/||||||||||||||||||\
Maude 3.1 built: Oct 12 2020 20:12:31
Copyright 1997-2020 SRI International
Fri May 28 22:50:23 2021
Maude> mod D is inc LIST{Nat}. eq 0 0 0 0 = nil . eq 1 1 = nil . eq 1 0 = 0 0 0 1 . endm
Maude> red nil .
reduce in D : nil .
rewrites: 0 in 0ms cpu (0ms real) (~ rewrites/second)
result List{Nat}: nil
Maude> red 0 .
reduce in D : 0 .
rewrites: 0 in 0ms cpu (0ms real) (~ rewrites/second)
result Zero: 0
Maude> red 0 0 0 .
reduce in D : 0 0 0 .
rewrites: 0 in 0ms cpu (0ms real) (~ rewrites/second)
result NeList{Nat}: 0 0 0
Maude> red 1 .
reduce in D : 1 .
rewrites: 0 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 1
Maude> red 0 1 .
reduce in D : 0 1 .
rewrites: 0 in 0ms cpu (0ms real) (~ rewrites/second)
result NeList{Nat}: 0 1
Maude> red 0 0 1 .
reduce in D : 0 0 1 .
rewrites: 0 in 0ms cpu (0ms real) (~ rewrites/second)
result NeList{Nat}: 0 0 1
Maude> red 0 0 0 0 .
reduce in D : 0 0 0 0 .
rewrites: 1 in 0ms cpu (0ms real) (~ rewrites/second)
result List{Nat}: nil
Maude> red 0 0 0 0 0 0 .
reduce in D : 0 0 0 0 0 0 .
rewrites: 1 in 0ms cpu (0ms real) (~ rewrites/second)
result NeList{Nat}: 0 0
Maude> red 1 0 .
reduce in D : 1 0 .
rewrites: 1 in 0ms cpu (0ms real) (~ rewrites/second)
result NeList{Nat}: 0 0 0 1
Maude> red 0 1 0 .
reduce in D : 0 1 0 .
rewrites: 2 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 1
Maude> red 1 0 1 0 .
reduce in D : 1 0 1 0 .
rewrites: 3 in 0ms cpu (0ms real) (~ rewrites/second)
result List{Nat}: nil
Maude> red 1 0 0 .
reduce in D : 1 0 0 .
rewrites: 3 in 0ms cpu (0ms real) (~ rewrites/second)
result NeList{Nat}: 0 0 1
Maude> red 1 0 1 .
reduce in D : 1 0 1 .
rewrites: 2 in 0ms cpu (0ms real) (~ rewrites/second)
result NeList{Nat}: 0 0 0
Maude> red 0 1 0 1 0 .
reduce in D : 0 1 0 1 0 .
rewrites: 3 in 0ms cpu (0ms real) (~ rewrites/second)
result Zero: 0
Maude> red 0 0 1 1 1 .
reduce in D : 0 0 1 1 1 .
rewrites: 1 in 0ms cpu (0ms real) (~ rewrites/second)
result NeList{Nat}: 0 0 1
Maude> red 1 1 1 0 0 0 .
reduce in D : 1 1 1 0 0 0 .
rewrites: 12 in 0ms cpu (0ms real) (~ rewrites/second)
result NeList{Nat}: 0 1
```
### Ungolfed
```
mod D is
inc LIST{Nat} .
eq 0 0 0 0 = nil .
eq 1 1 = nil .
eq 1 0 = 0 0 0 1 .
endm
```
I chose to encode `r` as `0` and `s` as `1`. (It would cost 19 more bytes to use `r` and `s` directly instead.)
I am shocked and thrilled that Core Maude is actually competitive in this question! Maude's built-in list module implements lists using the `__` operator (juxtaposition), which is associative and has `nil` as its identity. This means an equation can match any sublist. Since this is just "reduce until done", we don't even need our own function symbol to separate input from output.
We could probably get away with shaving off one byte, but it would not technically be a correct Core Maude program anymore. The existing Maude interpreter does not differentiate between protecting (`pr`) and including (`inc`) modules, but according to the spec our equations would not be valid with protecting.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~118~~ \$\cdots\$ ~~96~~ 95 bytes
```
i;b;p;q;f(char*s){for(;s[i];q+=~p/~b^p)p^=b=s[i++]-48;for(i=p+q%4;i--;*s++=48^i<p);i=p=q=*s=0;}
```
[Try it online!](https://tio.run/##pVLBbtswDL3nKzgDheUoRpM1A7qp6g7DviJxgESVW2Wpq4guli1IP30eJcuGU/RQoAYsUuTj06Mold8r1TRGbIQVe1Ey9bB2Y8yO5ZNjAhemEHsuX@zly2ZlM7uSG0lBzot8fi08xkjL9xdzYfJcjJFzOb9emRubCUrIvRyjnIpTY6oaHtemYtnoOAL6wjFQa6xxUYCEow8myQQSFxYXDAa/XTvjOkCH8atHxV1nu21LEcPEgiFCxtefxECNPlitan0XBb1DjT/Z6w756PlMgMaG2ii2IqP483AgPVOiHrT6pR0JAS8lWR5@fl4evv6g/4snGOyvukoaBjB/z6a60wcqm4ro3gCav/qpZF2D2WUMjPuIAM4DOoN2QIMhEVc7qAAoRJ/3p@0oi7Xb6YrVmTgrhc1zWS52wGE2KCKwsn@Yz01gWNI3sG3Fh@ptIWDLedbtKMWiK2WK6XdIZyl8g3SaDqkC5mPcM8@Ngdulrzqjt0Lg/r28dS92jUiYT77dR8v0BF5Jso5gJUuWyQUuE8hvIXq0VDTkuq2Y9I/BMxaR4DQ6Nf9UuVvfY5P//g8 "C (gcc) – Try It Online")
Uses `'0'` for `'r'`, `'1'` for `'s'`, and [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)'s formula for [tsh](https://codegolf.stackexchange.com/users/44718/tsh)'s [Python answer](https://codegolf.stackexchange.com/a/226384/9481).
] |
[Question]
[
Given the coordinates of the centres and the radii of 2 circles, output a truthy value of whether they do or do not overlap.
## Input
* Input may be taken via STDIN or equivalent, function arguments, but not as a variable. You can take them as a single variable (list, string etc) or as multiple inputs / arguments, in whatever order you want.
* The input will be six floats. These floats will be up to 3 decimal places. The coordinates can be positive or negative. The radii will be positive.
## Output
* Output can be via STDOUT or function return.
* The program must have exactly 2 distinct outputs - one for a True value (the circles do overlap) and one for a False output (they don't overlap).
### Test cases
(Input is given as list of tuples `[(x1, y1, r1), (x2, y2, r2)]` for the test cases; you can take input in any format)
### True
```
[(5.86, 3.92, 1.670), (11.8, 2.98, 4.571)]
[(8.26, -2.72, 2.488), (4.59, -2.97, 1.345)]
[(9.32, -7.77, 2.8), (6.21, -8.51, 0.4)]
```
### False
```
[(4.59, -2.97, 1.345), (11.8, 2.98, 4.571)]
[(9.32, -7.77, 2.8), (4.59, -2.97, 1.345)]
[(5.86, 3.92, 1.670), (6.21, -8.51, 0.4)]
```
---
This is Code Golf, shortest answer in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
IA<S}
```
Takes two complex numbers (centers) as first argument, and two real numbers (radii) as second argument.
[Try it online!](https://tio.run/##y0rNyan8/9/T0Sa49v///6Z6FmYK2grGepZGWToKhoZ6FkCekZ6lRdZ/Qz0zcwMdBRM9U3NDAA "Jelly – Try It Online")
### How it works
```
IA<S} Main link.
Left argument: [x1 + iy1, x2 + iy2]
Right argument: [r1, r2]
I Increments; yield (x2 - x1) + i(y2 - y1).
A Absolute value; yield √((x2 - x1)² + (y2 - y1)²).
S} Take the sum of the right argument, yielding r1 + r2.
< Compare the results.
```
[Answer]
## JavaScript (ES6), 38 bytes
Takes input as 6 distinct variables ***x1***, ***y1***, ***r1***, ***x2***, ***y2***, ***r2***.
```
(x,y,r,X,Y,R)=>Math.hypot(x-X,y-Y)<r+R
```
### Test cases
```
let f =
(x,y,r,X,Y,R)=>Math.hypot(x-X,y-Y)<r+R
// True
console.log(f(5.86, 3.92, 1.670, 11.8, 2.98, 4.571))
console.log(f(8.26, -2.72, 2.488, 4.59, -2.97, 1.345))
console.log(f(9.32, -7.77, 2.8, 6.21, -8.51, 0.4))
// False
console.log(f(4.59, -2.97, 1.345, 11.8, 2.98, 4.571))
console.log(f(9.32, -7.77, 2.8, 4.59, -2.97, 1.345))
console.log(f(5.86, 3.92, 1.670, 6.21, -8.51, 0.4))
```
[Answer]
# Pyth, 5 bytes
```
gsE.a
```
Input format:
```
[x1, y1], [x2, y2]
r1, r2
```
[Try it online](https://pyth.herokuapp.com/?code=gsE.a&input=%5B5.86%2C+3.92%5D%2C+%5B11.8%2C+2.98%5D%0A1.670%2C+4.571)
### How it works
```
Q autoinitialized to eval(input())
.a L2 norm of vector difference of Q[0] and Q[1]
gsE sum(eval(input()) >= that
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
ZPis<
```
Input format is:
```
[x1, y1]
[x2, y2]
[r1, r2]
```
[Try it online!](https://tio.run/##y00syfn/Pyogs9jm//9oUz0LMx0FYz1Lo1iuaENDPQsdBSM9SwsQR8/M3EBHwUTP1NwwFgA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##ZY87DgIxDER7TpEDhNHa@diWKDkABRUrJCiRoIL7B2eFBFnKZ4/nyY/r694u7XS4PXdtf2xzgdYYEozPm5kIGgPDtAOqTDFkFCFHBXtwy5Ce9KktZOLEyOqHhJSLoyGxLwXSlxVMTopCS9SDE/Jfx8rtTV/3WLh2/5iHb0bx552ufgM).
### How it works
```
ZP % Take two vectors as input. Push their Euclidean distance
i % Input the vector of radii
s % Sum of vector
< % Less than?
```
[Answer]
# [R](https://www.r-project.org/), 39 bytes
```
function(k,r)dist(matrix(k,2,2))<sum(r)
```
takes input `k=c(x1,x2,y1,y2)` and `r=c(r1,r2)`; returns `FALSE` for tangent circles.
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jW6dIMyWzuEQjN7GkKLMCyDfSMdLUtCkuzdUo0vyfBhNP1jDQMdAx1jHRBCnQCdHUSdYw1jHW1PwPAA "R – Try It Online")
### 27 bytes:
```
function(m,r)dist(m)<sum(r)
```
Takes input as a matrix with the circle centers given as rows and a vector of radii.
[Try it online!](https://tio.run/##DcLBCYAwEATAdnZhH8H41C5sQCKBPC7CJYLdnzLjUfeoTy@z3R0m59XGhHEbj8EZFXZOby8KkpKyVmr5HVRBVibjAw "R – Try It Online")
[Answer]
# [Python](https://docs.python.org/2/), 40 bytes
```
lambda x,y,r,X,Y,R:abs(x-X+(y-Y)*1j)<r+R
```
[Try it online!](https://tio.run/##dc/NDoIwDAfwszzFjp2Who2PbURewpNGPWCUgEEkiFGeHsdOJuJlS9rf/u3aoS/vjRyL7DDW@e10ztkbB@xwizvcpPnpAW9/u4LB3/GluPJ1t9qMr7KqL0yk3gIc5giO86xq2mcP3Fu0XdX0rICvMD7uISadIAvJSGSCEhVwZCAEaWSSjD0jipXgR28PmqSlviQlp2ak9WRt37iqUVNCGMUOGwqt8hUpNWFHE5LC1jTF9goocnDm/d8N5kL/zJ/91@8CHw "Python 2 – Try It Online")
Uses Python's complex arithmetic to compute the distance between the two centers. I'm assuming we can't take the input points directly as complex numbers, so the code expresses them like `x+y*1j`.
[Answer]
# [Python 3](https://docs.python.org/3/), 45 bytes
```
lambda X,Y,R,x,y,r:(X-x)**2+(Y-y)**2<(R+r)**2
```
[Try it online!](https://tio.run/##FcZLCoAgFEDRrTh81vOR9o/ahCODJkVEQR@RBrl6q8m9x/p7vc40LN0Q9vGY5pEZ7FHjgx5dA0Y8PIpUDL3wP1rQsfsRrNvOGxbIqSqQpVQrZJKKMvkmqUKmqP6aUV5KzsML "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
αs--0›
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3MZiXV2DRw27/v831bMwU9BWMNazNMriMjTUswByjPQsLYAcPTNzAy4TPVNzw/@6KQA "05AB1E – Try It Online")
-1 byte by using `a - b > 0` rather than `(reverse) b - a < 0`
[Answer]
# [Python 3](https://docs.python.org/3/), 45 bytes
```
lambda a,b,c,d,e,f:(a-d)**2+(b-e)**2<(c+f)**2
```
[Try it online!](https://tio.run/##FcY5DoAgEEDRq1AOMk4EFZfoTWxAJJq4xdh4eoTm/3d/73qdZfDjFHZzWGeYQYszOlzQ92Byx7NMCbD5kjDALHxCuJ/tfMFDTa1GVlKnkEnSTREnqUWmqIutqG4k5@EH "Python 3 – Try It Online")
-8 bytes thanks to Neil/Step Hen
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 10 bytes
Prompts for circle centers as list of two complex numbers, then for radii as list of two numbers
```
(+/⎕)>|-/⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdvyy1KCex4L@Gtv6jvqmadjW6IBok8/9R71yFkKLSVCsuBTCAKuUy1bMw8zLWszRSMDTUs/Ay0rO04DLUMzM3UDDRMzU3RFNtoWdk5nVovZGeuRFI3hLMtjTnMtIzsbBQMNQzNjFF02GpZ2wEVGWuZ26uYKZnZAhkW@iZGgJ1WCgY6JlwcYEc5paYU4zhMiTzUdwGtAOr25BtQnMcdqchvI7sMIjngU4DAA "APL (Dyalog Unicode) – Try It Online")
`(+/⎕)` [is] the sum of the radii
`>` greater than
`|` the magnitude of
`-/⎕` the difference in centers
[Answer]
# Mathematica, 16 bytes
```
Norm[#-#2]<+##3&
```
Input: `[{x1, y1}, {x2, y2}, r1, r2]`
---
Mathematica has a `RegionIntersection` builtin, but that alone is 18 bytes long...
Built-in version:
```
RegionIntersection@##==EmptyRegion@2&
```
Takes 2 `Disk` objects. `[Disk[{x1, y1}, r1], Disk[{x2, y2}, r2]]`.
[Answer]
# [Haskell](https://www.haskell.org/), ~~37~~ 36 bytes
```
(u#v)r x y s=(u-x)^2+(v-y)^2<(r+s)^2
```
[Try it online!](https://tio.run/##dZDbqsIwEEXf@xUbfDDBdLDpJQmcfsL5AlEpWFC8IEnb0359z7T2TX2ZDTNrbvtchWt9u42jaFed9OgxIJSijXt50BvRxQPrj/CbwDo2dWgCygjYQeRkC4WUnFZIqDBbloSsgibHMaPcJJJRBWFJMxprMnoqZ/ZVd3POmak/zfIFdpQyFRsyZoIZLUgnnLGUs2wpW8D3Cd8veB/6df@Hvz4dsI@ie3V5oMS9ev4eIZ7@8mjotJaYbWLk71z7Gqc1RKs65VWvBhUkd8xmY3F7/Ac "Haskell – Try It Online")
Thanks @AndersKaseorg for `-1` byte!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
I²+⁴I²¤<⁵S²¤
```
[Try it online!](https://tio.run/##y0rNyan8/9/z0CbtR41bgNShJTaPGrcGgxj////XMNWzMNNRMDTUs9D8r2GsZ2mko2CkZwniGOqZmRvoKJjomZobagIA "Jelly – Try It Online")
-2 bytes thanks to Dennis
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 38 bytes
```
(a,b,c,x,y,z)->Math.hypot(a-x,b-y)<c+z
```
[Try it online!](https://tio.run/##lZA9b4MwEIb3/IobQTWn8GlQ2o7ZMmWsOpivhJRgBE4EVPx2elCYEiXKYN/rk97nvfNJXIUhy6Q4xT9DeQnzLIIoF3UNO5EV8LsCyAqVVKmIEthOb4BQyjwRBaRaLMmSgGCzCBcRLaJZRLuITt8Qpacz59VKKCpXmcVwplRtr6qsOHx9g6gOtT6HbiGFDxg0wUIWsYa1rNONz51QRzy2pVSaMBoWGq3@Hr11w2by7NtaJWeUF4UlIVVeaCmmmou@x8DGwGJgosfXVEz0GVgY0O2gy01df4jw0SKEYSG3Rpvj//uCqRfwkWs77hNIgDa5DY6cjxBCeGiZ1PHRpbJG5wngNvH1TW6HeHmPO/95f5F@1Q9/ "Java (OpenJDK 8) – Try It Online")
[Answer]
# Java 8, ~~41~~ 38 bytes
```
(x,y,r,X,Y,R)->Math.hypot(x-X,y-Y)<r+R
```
[Try it here.](https://tio.run/##lZBNboMwEIX3OcUsQTWj8g9K2xskC7IBVV044DakxEbgRKCKs9MhCauoSiPZ4@ex3udn7/mJW6oWcl98j3nF2xZWvJQ/C4BSatF88lzAetoCbJWqBJeQG4U6bisBHbuKfhbNLNJZZLNIzCVRBpo0Ws11mcMaJLzCaHSsZw1LWcYS03pbcb3DXV8rbXRWynorM1@ap2RcXrw14ch7RZxUWcCBIhsb3ZTy6/0DuHnJu@lbLQ6ojhprOtKVNCTmho9RwMDF2GFgYxBStTFi4GBM1UM/tM1z1j8JETpEsBwMncnmRRdffO7FExBdz78DidEltxViGE4QQgTo2NSJ0KflGb07gNsbH3/J7V88GOK/gGExjL8)
Apparently, Java also has `Math.hypot`, which is 3 bytes shorter.
EDIT: Just realized this answer is now exactly the same as [*@OlivierGrégoire*'s Java 8 answer](https://codegolf.stackexchange.com/a/136035/52210), so please upvote him instead of me if you like the 38-byte answer.
**Old answer (41 bytes)**:
```
(x,y,r,X,Y,R)->(x-=X)*x+(y-=Y)*y<(r+=R)*r
```
[Try it here.](https://tio.run/##lZDfboIwFMbvfYpz2WI5GcjfOPYG8wJvIMsuKrIFh8VANZDFZ2cHkStjnEl7@vU0369fu5MnaVaHXO22P31WyqaBd1mo3xlAoXRef8ksh9WwBdhUVZlLBRnbVsdNmUMrrqKbRD2JZBLpJGK@JMqZJo1GS11ksAIFEfSsFZ2oRSJSEXPzjbVmlHCjnbPOjFJudK@snkcxN@p@OdoPRCT7lXKqii3sKTVb67pQ3x@fIPkYed01Ot9jddR4oCNdKqYwYy4GnoAFhrYACz2fqoWBABtDqg66vsUvce8SArSJYNro24PNCUZfeOmFAxAXjvsAEuKC3KaPvj9ACOGhbVEnQJeWF3QeAG5vfP4lt3/xZIj/As6zc/8H)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
<sm^-EE2 2^+EE2
```
Takes input in the order x1,x2,y1,y2,r1,r2
[Test suite!](https://pyth.herokuapp.com/?code=%3Csm%5E-EE2+2%5E%2BEE2&input=5.86%0A11.8%0A3.92%0A2.98%0A1.670%0A4.571&test_suite=1&test_suite_input=5.86%0A11.8%0A3.92%0A2.98%0A1.67%0A4.571%0A%0A8.26%0A4.59%0A-2.72%0A-2.97%0A2.488%0A1.345%0A%0A9.32%0A6.21%0A-7.77%0A-8.51%0A2.8%0A0.4%0A%0A4.59%0A11.8%0A-2.97%0A2.98%0A1.345%0A4.571%0A%0A9.32%0A4.59%0A-7.77%0A-2.97%0A2.8%0A1.345%0A%0A5.86%0A6.21%0A3.92%0A-8.51%0A1.67%0A0.4%0A&debug=0&input_size=7)
[Answer]
# [Perl 6](http://perl6.org/), 13 bytes
```
*+*>(*-*).abs
```
[Try it online!](https://tio.run/##ZY49DoJAFIR7TjGVgVUm7LK/IXoRQqFREhMUA4XhbHZeDBEroXnJfJmZN49L19jxNmBTYz@KrTjEIhUJj6d@LNAfB9QxS1XtwNLMN6u2V8FSziL/CV0lqNsOzfV@6d8vPtvu3BejobfIGRQkrcsgJT0Ug4emcTLyVBapolMT1X7G4QuCmxK5NlFgrpA6Ojc5PCyVROppJDLqaGlfPVjEV/XLgf/9Hw "Perl 6 – Try It Online")
The first two arguments are the radii, in either order. The third and fourth arguments are the coordinates of the centers, as complex numbers, in either order.
[Answer]
# [Taxi](https://bigzaphod.github.io/Taxi/), 1582 bytes
```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Pickup a passenger going to Tom's Trims.Pickup a passenger going to Tom's Trims.Go to Tom's Trims:n.[a]Go to Post Office:s.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to What's The Difference.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 5 l.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 r.Pickup a passenger going to Multiplication Station.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to Addition Alley.Go to Tom's Trims:s 1 r 3 r.Pickup a passenger going to The Babelfishery.Switch to plan "b" if no one is waiting.Switch to plan "a".[b]Go to Addition Alley:n 1 r 1 l 3 l 1 l.Pickup a passenger going to Magic Eight.Go to Post Office:n 1 r 1 r 3 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Addition Alley.Go to Addition Alley:n 5 l 1 l.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Multiplication Station.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to Magic Eight.Go to Magic Eight:s 1 r.Switch to plan "c" if no one is waiting.'1' is waiting at Writer's Depot.[c]'0' is waiting at Writer's Depot.Go to Writer's Depot:w 1 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.
```
[Try it online!](https://tio.run/##1VSxbsIwEN3zFScWJiwSoNBstFSdUJFAYkAMxjjJqcaOYiPK11OHGAkIEKBTB8vy@e787t07G/qDu92nAqNgpLSBryhCxsMN@CDsyvKdjJB9r1OgkFKtuYx5BrFCGedRk4TDG11wEaFOeLa97axWdQ2TDFf6br8C3JEllGRG52XM@jGcLu@ZOdSHym9mmybU5Hhs9ACjiGdcMv5ERAHi4l0ooVPB/fuWCSUPWdwp5JXoh2thMBXIqEElYWz2@zMhxcuXLx2VgRVRu6KQ/nKJ@9C@EHx7oeV6r8VWRV2lHo83aFiSX6WCSqgtaoARSAWWJ0ANG2qflXHJj9bIbOEkdorNdsVNhUUjKqdjSGNk8IFxYkhZsYdc@8oen7Q/KfiM8oe7U6KlcwcdlwUrHWDxv0Rb7u2RpVBsSVjsigDrfv3oCNTANEPDMzsAA54qQ2ZsXm9W@LjP5MTofvKgopYjVV7VaeA0utu9klbgNbqk2/UC0vNeSOB7jR7p@F6TtH8B)
Outputs `1` for overlapping circles.
Outputs `0` for non-overlapping circles (including tangential circles).
Ungolfed / formatted:
```
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Pickup a passenger going to Tom's Trims.
Pickup a passenger going to Tom's Trims.
Go to Tom's Trims: north.
[a]
Go to Post Office: south.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to What's The Difference.
Pickup a passenger going to What's The Difference.
Go to What's The Difference: north 5th left.
Pickup a passenger going to Cyclone.
Go to Cyclone: east 1st right.
Pickup a passenger going to Multiplication Station.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station: south 1st left 2nd right 4th left.
Pickup a passenger going to Addition Alley.
Go to Tom's Trims: south 1st right 3rd right.
Pickup a passenger going to The Babelfishery.
Switch to plan "b" if no one is waiting.
Switch to plan "a".
[b]
Go to Addition Alley: north 1st right 1st left 3rd left 1st left.
Pickup a passenger going to Magic Eight.
Go to Post Office: north 1st right 1st right 3rd right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Addition Alley.
Go to Addition Alley: north 5th left 1st left.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st left 1st left.
Pickup a passenger going to Multiplication Station.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station: south 1st left 2nd right 4th left.
Pickup a passenger going to Magic Eight.
Go to Magic Eight: south 1st right.
Switch to plan "c" if no one is waiting.
'1' is waiting at Writer's Depot.
[c]
'0' is waiting at Writer's Depot.
Go to Writer's Depot: west 1st left 2nd left.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.
```
[Answer]
# C#, ~~50~~ 41 bytes
```
(x,y,r,X,Y,R)=>(x-=X)*x+(y-=Y)*y<(r+=R)*r
```
*Saved 9 bytes thanks to @KevinCruijssen.*
[Answer]
# [Scala](http://www.scala-lang.org/), 23 bytes
Thanks @Arnauld for [his *almost polyglot* answer](https://codegolf.stackexchange.com/a/135971/71499).
```
math.hypot(a-x,b-y)<r+q
```
[Try it online!](https://tio.run/##jZDNToNAFIXX8hQ3XTHpcNOZ8jM0aqJx6xMYF0M7pjXIUIoG0vTZcbh0EjUs3MAJ@b5zmDltdakHW7ybbQvP@lCB6VpT7U7wUNfn4GZn3sB@mabUdag3T/azKA3vfCh86H1ofDheA9s8WlsaXd2dhw/d7nHf17YNddTxIurZbbM8DpcgqJtD1ZZVuHgJE1QphzXmkoPANFsxDqEQqDhIzN0zxiQT7BWie1gs/c@RRRSZRI42n2j2c0GhdAuRxEyOnbFS44QDc/qaZ@PwOk7@bpBH2OROLBXwSfg1M1P4n5OQRpTvz6/1c2eZva0UpXDLChP3WmE8e1kEkTiBZPORZsFl@AY "Scala – Try It Online")
[Answer]
# PostgreSQL, 41 characters
```
prepare f(circle,circle)as select $1&&$2;
```
Prepared statement, takes input as 2 parameters in any [`circle` notation](https://www.postgresql.org/docs/current/static/datatype-geometric.html#DATATYPE-CIRCLE).
Sample run:
```
Tuples only is on.
Output format is unaligned.
psql (9.6.3, server 9.4.8)
Type "help" for help.
psql=# prepare f(circle,circle)as select $1&&$2;
PREPARE
psql=# execute f('5.86, 3.92, 1.670', '11.8, 2.98, 4.571');
t
psql=# execute f('8.26, -2.72, 2.488', '4.59, -2.97, 1.345');
t
psql=# execute f('9.32, -7.77, 2.8', '6.21, -8.51, 0.4');
t
psql=# execute f('4.59, -2.97, 1.345', '11.8, 2.98, 4.571');
f
psql=# execute f('9.32, -7.77, 2.8', '4.59, -2.97, 1.345');
f
psql=# execute f('5.86, 3.92, 1.670', '6.21, -8.51, 0.4');
f
```
[Answer]
## Java, ~~50~~ 38 bytes
```
(x,y,r,X,Y,R)->Math.hypot(x-X,y-Y)<r+R
```
[Answer]
# x86 Machine Code (with SSE2), 36 bytes
```
; bool CirclesOverlap(double x1, double y1, double r1,
; double x2, double y2, double r2);
F2 0F 5C C3 subsd xmm0, xmm3 ; x1 - x2
F2 0F 5C CC subsd xmm1, xmm4 ; y1 - y2
F2 0F 58 D5 addsd xmm2, xmm5 ; r1 + r2
F2 0F 59 C0 mulsd xmm0, xmm0 ; (x1 - x2)^2
F2 0F 59 C9 mulsd xmm1, xmm1 ; (y1 - y2)^2
F2 0F 59 D2 mulsd xmm2, xmm2 ; (r1 + r2)^2
F2 0F 58 C1 addsd xmm0, xmm1 ; (x1 - x2)^2 + (y1 - y2)^2
66 0F 2F D0 comisd xmm2, xmm0
0F 97 C0 seta al ; ((r1 + r2)^2) > ((x1 - x2)^2 + (y1 - y2)^2)
C3 ret
```
The above function accepts descriptions of two circles (x- and y-coordinates of center point and a radius), and returns a Boolean value indicating whether or not they intersect.
It uses a vector calling convention, where the parameters are passed in SIMD registers. On x86-32 and 64-bit Windows, this is the [`__vectorcall` calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_vectorcall). On 64-bit Unix/Linux/Gnu, this is the standard [System V AMD64 calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI).
The return value is left in the low byte of `EAX`, as is standard with all x86 calling conventions.
This code works equally well on 32-bit and 64-bit x86 processors, as long as they support the [SSE2 instruction set](https://en.wikipedia.org/wiki/SSE2) (which would be Intel Pentium 4 and later, or AMD Athlon 64 and later).
### AVX version, still 36 bytes
If you were targeting [AVX](https://en.wikipedia.org/wiki/Advanced_Vector_Extensions), you would probably want to add a VEX prefix to the instructions. This does not change the byte count; just the actual bytes used to encode the instructions:
```
; bool CirclesOverlap(double x1, double y1, double r1,
; double x2, double y2, double r2);
C5 FB 5C C3 vsubsd xmm0, xmm0, xmm3 ; x1 - x2
C5 F3 5C CC vsubsd xmm1, xmm1, xmm4 ; y1 - y2
C5 EB 58 D5 vaddsd xmm2, xmm2, xmm5 ; r1 + r2
C5 FB 59 C0 vmulsd xmm0, xmm0, xmm0 ; (x1 - x2)^2
C5 F3 59 C9 vmulsd xmm1, xmm1, xmm1 ; (y1 - y2)^2
C5 EB 59 D2 vmulsd xmm2, xmm2, xmm2 ; (r1 + r2)^2
C5 FB 58 C1 vaddsd xmm0, xmm0, xmm1 ; (x1 - x2)^2 + (y1 - y2)^2
C5 F9 2F D0 vcomisd xmm2, xmm0
0F 97 C0 seta al ; ((r1 + r2)^2) > ((x1 - x2)^2 + (y1 - y2)^2)
C3 ret
```
AVX instructions have the advantage of taking *three* operands, allowing you to do non-destructive operations, but that doesn't really help us to compact the code any here. However, mixing instructions with and without VEX prefixes can result in sub-optimal code, so you generally want to stick with *all* AVX instructions if you're targeting AVX, and in this case, it doesn't even hurt your byte count.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
-¨nOt²¹+θ‹
```
[Try it online!](https://tio.run/##MzBNTDJM/f9f99CKPP@SQ5sO7dQ@t@NRw87//6NN9SzMdBSM9SyNdBQM9czMDWK5og0N9Sx0FIz0LIGkiZ6puWEsAA "05AB1E – Try It Online")
[Answer]
# [PHP](https://php.net/), 66 bytes
```
<?php $i=$argv;echo hypot($i[1]-$i[4],$i[2]-$i[5])<$i[3]+$i[6]?:0;
```
[Try it online!](https://tio.run/##HcZBCoMwEEbhq7jIosV2cKKJsSoeRGYhRYyrDCJCT/83uPne06jAMGnUwuyjWY7t6tdvTEX8aTofZp9Z3tlGXll7v5PnkFNLmfUyfaoegKPgUVNnweTbCswUYKkLaMi1/Ac "PHP – Try It Online")
Runs from the command line, taking input as 6 command-line parameter arguments, and prints 1 if the circles overlap, else 0.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 22 bytes
```
9k?+_5R-d*_3R-d*+v-vzp
```
[Try it online!](https://tio.run/##S0n@/98y21473jRIN0Ur3hhEapfpllUV/P9vqmdhpmBoqGehYKxnaaRgpGdpoWCoZ2ZuoGCiZ2puCAA "dc – Try It Online")
[Or try the test suite!](https://tio.run/##RY7BboMwEETv/ooRyqmIbWwwtqUoPbXXSPkBiwItUZMQ0Tat@vPEXiCVpd3Vembevlaf3VhXX9jiMvTvQ3XCZoPkefeSjO7jKfV6nzUPPo81vWbXv8sY/kTdnfoG3@nv4hI/3eHYYmirBsfDuRVA04cSWo3sDfT4Hx/yV1GTsOjcjppsCSnJIienoMhZSCrNGgVpIyEsqTLODl6RUbE6E3SFjcK80BCOcoWSlIQ3ZAy8JS2DxGJNBQSbGbF43WKdGRwwMaaAWXcn8JVM4CsnwHQmI0LjF5Y8q3m@AQ)
Input is read from stdin in the format `x1 x2 y1 y2 r1 r2`. Note that negative numbers are written in dc with an underscore `_` instead of a minus sign `-`.
Output is on stdout: 1 for truthy, 0 for falsey. If the two circles are tangent to one another or if they're identical, they're considered to be overlapping.
---
This requires a recent version of GNU dc which supports the `R` operation (rotate).
On versions of dc which don't support `R`, you can instead use
`9k?-d*sY-d*lY+vsD+lD-vzp`
(24 bytes long), with input presented on stdin in the order `r1 r2 x1 x2 y1 y2`. Here's a [test suite for the 24-byte program, for older versions of dc](https://tio.run/##RY7NTsMwEITvfopR1BNRtvHmx7ZUwaVw5dxTFJKUVKRNlUBBvHxw1gJkabzSzsy3L/XcL039jntcp/F1qs/Y7RA9Pj9Fi3t7SNq7@eBlOMS3eR8P@@T2fV38VjX9eWzxEX/95tRnfxo6TF3dYjhdOgW0oxf/NUiOoO0/wBM2qycS06VbNJUmRU6F0SjIltCaLDJyDCZnFVNuLTRleQFLXK5Wh4rJ8KrOeIdFSjkcZYySWKMyZAwqS4WGCtEAkKwAJCoESEFwSUUAhAoBhBNXhBwoCDlQCEpDIw3vb2Y//wA)
---
**Explanation**
```
9k Set precision to 9 decimal places.
? Read the input and push all 6 numbers on the stack (r2 is at the top of the stack since it's entered last).
+ Add r1 and r2
_5R Rotate the stack so that r1+r2 is now at the bottom.
-d* Compute (y1-y2)^2.
_3R Rotate the stack so that it's now: r1+r2 (y1-y2)^2 x1 x2 (top on the right)
-d* Compute (x1-x2)^2.
+ Compute (x1-x2)^2 + (y1-y2)^2.
v Take the square root to compute the distance between the centers.
- Subtract the distance between the centers from r1-r2.
v Pop one number from the stack. If it's non-negative, then compute its square root and push that back on the stack.
z Push the size of the stack onto the stack. (This is 0 if the difference was negative, and it's 1 if the difference was positive.)
p Print the item at the top of the stack.
```
[Answer]
## Julia 0.6.0 (46 bytes)
```
a->((a[1]-a[2])^2+(a[3]-a[4])^2<(a[5]+a[6])^2)
```
[Answer]
# Clojure, 68 bytes
```
#(<(+(*(- %4 %)(- %4 %))(*(- %5 %2)(- %5 %2)))(*(+ %6 %3)(+ %6 %3)))
```
Takes six arguments: x1, y1, r1, x2, y2, r2. Returns true or false.
Sadly, Clojure does not have a `pow` function of some sorts. Costs a lot of bytes.
[Answer]
# [Actually](https://github.com/Mego/Seriously), 8 bytes
```
-)-(h@+>
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/19XU1cjw0Hb7v9/Ez1Tc0MFZYUiIy5DPTNzAxDTkMvQUM8CyKow4jLVszADsQy5jPQsQWKVRlzGepZGIJYhAA "Actually – Try It Online")
Explanation:
```
-)-(h@+> (implicit input: [y1, y2, x1, x2, r1, r2])
- y2-y1 ([y2-y1, x1, x2, r1, r2])
)- move to bottom, x1-x2 ([x1-x2, r1, r2, y2-y1])
(h move from bottom, Euclidean norm ([sqrt((y2-y1)**2+(x2-x1)**2), r1, r2])
@+ r1+r2 ([r1+r2, norm])
> is r1+r2 greater than norm?
```
[Answer]
# R (+pryr), 31 bytes
```
pryr::f(sum((x-y)^2)^.5<sum(r))
```
Which evaluates to the function
```
function (x, y, z)
sum((x - y)^2)^0.5 < sum(z)
```
Where `x` are the coordinates of circle 1, `y` are the coordinates of circle 2 and `z` the radii.
Calculates the distance between the two centers using Pythagoras and tests if that distance is smaller than the sum of the radii.
Makes use of R's vectorisation to simultaneously calculate `(x1-x2)^2` and `(y1-y2)^2`. These are then summed and squarely rooted.
] |
[Question]
[
[American odds](https://en.wikipedia.org/wiki/Fixed-odds_betting#Moneyline_odds) (aka *moneyline odds*) are numbers like \$+150\$ or \$-400\$ used to express how much a winning bet would pay out. Convert odds to a fair win probability like this:
* Positive odds \$+n\$ with \$n \geq 100\$ correspond to $$p=\frac{100}{100+n},$$ producing a probability with \$0 < p \leq 1/2\$.
* Negative odds \$-n\$ with \$n > 100\$ correspond to $$p=\frac{n}{100+n},$$ producing a probability with \$1/2 < p < 1\$.
Note that in both formulas above, \$n\$ is the absolute value of the input. Inputs with absolute value under \$100\$ are invalid, and so is \$-100\$ (since \$+100\$ is used for \$p=1/2\$), so you don't need to handle these.
The input will be a whole number. If you take it as a string, expecting a leading `+` for positive values is optional.
Your output can be a decimal to some reasonable precision or a reduced fraction.
**Test cases**
```
+1500 0.0625
+256 0.2808988764044944
+100 0.5
-200 0.6666666666666666
-300 0.75
```
[Answer]
# [Python](https://www.python.org), 25 bytes
```
lambda x:x/(~99-abs(x))%1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY1LDoIwFEXnrOJNTNrwsWCBloS5i9BBiRBroDRQDU7ciBMSo3twKezGKox8o3tzTu67v_TVHFs1Pqp89zybymfvWjTFQcCQDWt049wXRY8GjFfhzKdt1XZQS1WCVNDqUiGCMwdAenCCHBqhUXkRtfdVgl7X0iCMLdedVAZZq0ISWxfPe-O0d8OYEAAgAUmi2AE3ipNfjRhhnLE0oYRSTqlF4WJazY-WnPydRZsFpfH85QM)
#### Thanks @Jonathan Allan for -1.
### Original [Python](https://www.python.org), 26 bytes
```
lambda x:-x/(100+abs(x))%1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Xc1BDoIwEEDRPaeYjUkbBAdsoZCw9xC6KBFiDZQG0OBZ3JAYPYQ34TZWYWVXM_kv0_vL3PpTo8dHme2fl770xLuSdX6UMKTesCEBoivzjgyUroIZTLuyaaFSugCloTGFJkhTB0Ct4QwZ1NKQ4iqr9Zf4nalUTyi13bRK98SqkihqLZ3vjdPBDTgiAKCPUcgdcEMe_dZQoEiEiCOGjCWM2RQs0jIvXObo79m0XVLM518-)
Test bed from @MTN via @AnttiP.
### How?
Based on the observation
\$-n \equiv 100 \mod 100+n\$
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
,³ṢAÄ÷/
```
[Try it online!](https://tio.run/##y0rNyan8/1/n0OaHOxc5Hm45vF3/v6GpgYGOkamZjiGQ1jUCEcYGBofbHzWt@Q8A "Jelly – Try It Online")
Function I/O only because lmao `³`. (Replace with `ȷ2` if that's too borderline.)
```
n ≥ 100 | n < -100
,³ Pair n with 100. [n, 100] | [n, 100]
Ṣ Sort. [100, n] | [n, 100]
A Map absolute value. [100, n] | [-n, 100]
Ä Cumsum. [100, 100 + n] | [-n, 100 - n]
÷/ Divide. 100 / (100 + n) | -n / (100 - n)
```
[Answer]
# [R](https://www.r-project.org), 24 bytes
```
\(n)(-n/(100+abs(n)))%%1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY7YjTyNDV08_Q1DA0MtBOTioFcTU1VVUOI9E3l4sSCgpxKjWQNQ1MDAx0jUzMdoEIdXSMQYWxgoKmTpglRumABhAYA)
Port of [loopy walt's Python answer](https://codegolf.stackexchange.com/a/265181/55372).
[Answer]
# [Python](https://www.python.org), 33 bytes
```
lambda n:1/[1+n/100,1-100/n][n<0]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY1NDoIwEEb3nGJ01Ya_KRasRk6iLGqEWINDg2jiWdyQGL2Tt7EIK2cxmS_vTb7H2967Y0P9s8p3r2tXheozq_V5f9BAaxFvhU-xQAxE6HZMxZY2WEyirpoWakMlGILGlsSQR22pD4xHF1ubbmAXxtcegAngBDmctWXlTdfBgEaJzQFgzrmTbGuoY06tmOHugY9F_afwRYroPIwwS1IP_CTNfjFRqFZKLTOJUq6kdEhMptPCZLqzv3FoMaFlOrZ8AQ)
Testing code from [MTN's answer](https://codegolf.stackexchange.com/a/265170/84290)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~29~~ 26 bytes
```
->n{(n>0?100:n=-n)/n+=1e2}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuha7dO3yqjXy7AzsDQ0MrPJsdfM09fO0bQ1TjWohCm4GFqUmpuRk5qUW66UmJmcopOQr1IC4NVwKCgWlJcUKII5eSmpOakmqhlJMnpKmgraCkoICEGsrpEWDZUvy4zNjQWQxV2peCsTgBXu1DU0NDLgUtI1MzYCkIYitawQmjQ0MIIoA)
Saved 3 bytes thanks to @MTN and @G B.
Ports [Luis felipe De jesus Munoz’s JavaScript submission](https://codegolf.stackexchange.com/a/265171/108687).
# [Ruby](https://www.ruby-lang.org/), ~~34~~ 28 bytes
```
->n{[-n,o=1e2].max/o+=n.abs}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhZ7dO3yqqN183TybQ1TjWL1chMr9PO1bfP0EpOKayFKbgYWpSam5GTmpRbrpSYmZyik5CvUgLg1XAoKBaUlxQogjl5Kak5qSaqGUkyekqaCtoKSggIQayukRYNlS_LjM2NBZDFXal4KxOAFe7UNTQ0MuBS0jUzNgKQhiK1rBCaNDQwgigA)
Thanks to @G B for saving 8 bytes!
I'm still learning Ruby, so this answer might be improvable, although @G B has improved it quite a bit already.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 55 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 6.875 bytes
```
₁"sȧ¦ƒ/
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJ+PSIsIiIsIuKCgVwic8inwqbGki8iLCIiLCIrMTUwMCA9PiAwLjA2MjVcbisyNTYgID0+IDAuMjgwODk4ODc2NDA0NDk0NFxuKzEwMCAgPT4gMC41XG4tMjAwICA9PiAwLjY2NjY2NjY2NjY2NjY2NjZcbi0zMDAgID0+IDAuNzUiXQ==)
Port of Jelly.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 50 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 6.25 bytes
```
ȧ₁+/N1%
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJ+PSIsIiIsIsin4oKBKy9OMSUiLCIiLCIrMTUwMCA9PiAwLjA2MjVcbisyNTYgID0+IDAuMjgwODk4ODc2NDA0NDk0NFxuKzEwMCAgPT4gMC41XG4tMjAwICA9PiAwLjY2NjY2NjY2NjY2NjY2NjZcbi0zMDAgID0+IDAuNzUiXQ==)
Port of [loopy walt's Python](https://codegolf.stackexchange.com/a/265181/85334). It's longer in Jelly due to the argument order for division, but I intuited it would at least tie in Vyxal SBCS bytes, and it turns out it also Vyncodes marginally better.
```
₁+ Add 100 to
ȧ the absolute value of n.
/ Divide n by that,
N negate the result,
1% and mod 1.
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 12 bytes
```
-a/(h+ABa)%1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboFS7IKlpSVpuhZrdBP1NTK0HZ0SNVUNIUJQmWXRuiYGBjB1AA) | *[Based on @loopy\_walt's Python answer](https://codegolf.stackexchange.com/questions/265168/american-odds-to-probabilities/265181#265181)*
Trivial implementation, 16 bytes.
```
(@YABSNgAEh)/$+y
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboFS7IKlpSVpuhYbNBwiHZ2C_dIdXTM09VW0KyHCUNll0bomBgYwtQA)
[Answer]
# [JavaScript (Babel Node)](https://babeljs.io/), 25 bytes
```
_=>(_>0?100:_=-_)/(100+_)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNFNSkxKzdHNy09J/Z9m@z/e1k4j3s7A3tDAwCreVjdeU18DyNSO1/yfnJ9XnJ@TqpeTn66RpmFoamCgqcmFKmhkaoYhZohFna4RNkFjkOB/AA "JavaScript (Babel Node) – Try It Online")
[Answer]
# Excel, 30 bytes
```
=1/(1+IF(A1<0,-100/A1,A1/100))
```
Input in cell `A1`.
[Answer]
# [Arturo](https://arturo-lang.io), 34 bytes
```
$->n[abs//(n<0)?->n[100]100+abs n]
```
[Try it!](http://arturo-lang.io/playground?PgvHMN)
[Answer]
# [R](https://www.r-project.org), 31 bytes
```
\(n)"if"(n<0,n<--n,100)/(100+n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGSNAUb3aWlJWm6FvtjNPI0lTLTlDTybAx08mx0dfN0DA0MNPU1gKR2niZE1U3l4sSCgpxKjWQNQ1MDAx0jUzOQKh1dIxBhDFSvkwZVumABhAYA)
# [R](https://www.r-project.org), 31 bytes
```
\(n,z=sign(n))1/(1+(n/100)^z*z)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGSNAUb3aWlJWm6FvtjNPJ0qmyLM9PzNPI0NQ31NQy1NfL0DQ0MNOOqtKo0Iar2pGkkaxiaGhjoGJma6QAldXSNQIQxUBlUyYIFEBoA)
I feel like *one* of these can be golfed down.
[Answer]
# [J](https://www.jsoftware.com), 9 bytes
```
1|-%100+|
```
-5 bytes by porting [loopy walt's answer](https://codegolf.stackexchange.com/a/265181/15469)!
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrsdKwRlfV0MBAuwbCv7lVk8vPSU8BKKSmoWGnp6upqqFdo6nJlZqcka-QpmBoamAAYxuZmsGFEaLxRkhsYxC7IrME6BBtkFYFBQUDPQMzI1MuBW2gdjDXyMLAwtLCwtzMxMDExNLEBChlCFUJVKZrBGWboQGglDFUytwU4vgFCyA0AA)
## [J](https://www.jsoftware.com), original answer, 14 bytes
```
(100>.-)%100+|
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrsU7D0MDATk9XUxVIa9dABG9u1eTyc9JTAAqpaWiAZTW0azQ1uVKTM_IV0hQMTQ0MYGwjUzO4MEI03giJbQxiV2SWAF2jDdKqoKBgoGdgZmTKpaAN1A7mGlkYWFhaWJibmRiYmFiamAClDKEqgcp0jaBsMzQAlDKGSpmbQhy_YAGEBgA)
* `100>.-` The larger of the negative of the input and 100
* `%` Divided by...
* `100+|` 100 plus the absolute value of the input
My attempts to avoid repeating 100 led to longer solutions.
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), ~~51~~ 42 bytes
```
: f dup 100 min abs s>f abs 100 + s>f f/ ;
```
[Try it online!](https://tio.run/##JYs9DoAgFIN3TtG4GhAwOEjCXfzJUweVgJ4fAZd@bdPSHZ6db1SQ0gjC@nooKXEeF6Y5IjqqLF1bE3Wweerr1EAEiAbgDk2@k8ASYBlTJh8802bIqqrn@kdfkD4 "Forth (gforth) – Try It Online")
## Explanation
Originally, I used a conditional statement, but those use a lot of characters in gforth. I eventually realized that the goal is mostly just to determine what goes on top of the fraction, 100 or n. Since n will always be greater than 100 or less than -100, we can use min to get the value we want (if negative, n will always be less than 100, if positive, 100 will always be smaller).
## Code Explanation
```
: f \ Begin word definition
dup \ duplicate n on the top of the stack
100 min \ take the smaller of n and 100
abs s>f \ send the absolute value to the floating point stack
abs 100 + \ add 100 to the absolute value of n
s>f \ move the result to the floating point stack
f/ \ divide the top two floating point stack values
; \ end word definition
```
[Answer]
# [Julia](https://julialang.org), ~~29~~ 24 bytes
```
!n=mod(n/(~99-abs(n)),1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FjsU82xz81M08vQ16iwtdROTijXyNDV1DDUh0jcXOBRn5JcrKOoaGRhwOSQWF6cWlSgoGpoaGCg86uxQUDDQMzAzMkXIGJmaKcBkjCwMLCwtLMzNTAxMTCxNTJD0A7XDVCFpBlkCEzZDA0iqjBGqzE0h7oR5BwA)
A port of [loopy walt's solution](https://codegolf.stackexchange.com/a/265181/114865).
`mod` is used (suggested by MarcMush), since Julia's default modulo `%` doesn't match [Python's convention for negative numbers](https://stackoverflow.com/questions/3883004/how-does-the-modulo-operator-work-on-negative-numbers-in-python); using `rem` with rounding mode `RoundDown` would also work.
[Answer]
# [Python](https://www.python.org), 37 bytes
```
lambda n:(100,x:=abs(n))[n<0]/(100+x)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY1NboNADEb3OYUVKZItfmLoABMUTtJkMVFAnYoMIyBVepZskKLmTrlNhzKremV_71nf_Wm_x4_OTI-mOvxcxyaSr02rLqezAlNiwhzeykqdBjRE72bPx-0cBjfysmq6HlptatAGOlsbZIr7Wp2R4sG2epzZgFSuAHQIn1DBRVmsv1QbzmiRcA0AayIn2V6bEZ3aoCb34Ium1zFIMmbnccx5mq0gSLP870wly52URS5YiJ0QDiXedFqU-j3_Nw69eVRkS8sv)
[Answer]
# [Octave](https://www.gnu.org/software/octave/) / MATLAB, 30 bytes
```
@(n)min(100,n)/(n+100*sign(n))
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI08zNzNPw9DAQCdPU18jTxvI0irOTM8DSmj@T9MwNDUw0PwPAA "Octave – Try It Online") Or [verify all test cases](https://tio.run/##y08uSSxL/Z9mq6en999BI08zNzNPw9DAQCdPU18jTxvI0irOTM8DSmj@T8svyk0sUcjJz0vnSiwqSqxMK83TSNNRiDY0NTCwVjAyNbNWMASxdI3ApLGBQazmfwA).
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands/2649a799300cbf3770e2db37ce177d4a19035a25), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Äт+/(1%
```
Port of [*@loopyWalt*'s Python answer](https://codegolf.stackexchange.com/a/265181/52210), so make sure to upvote that answer as well!
[Try it online](https://tio.run/##MzBNTDJM/f//cMvFJm19DUPV//@1jUzNAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfaXL/8MtF5u09TUMVf/r/I9W0jY0NTBQ0lHSNjI1A1GGIJ6ukYGBjq6xgUEsAA).
A port of [*@UnrelatedString*'s Jelly answer](https://codegolf.stackexchange.com/a/265169/52210) (in the [new 05AB1E version](https://github.com/Adriandmen/05AB1E/wiki/Commands)) would be a byte longer:
```
т‚{ÄηO`/
```
[Try it online](https://tio.run/##yy9OTMpM/f//YtOjhlnVh1vObfdP0P//X9vI1AwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/4tNjxpmVR9uObfdP0H/v87/aCVtQ1MDAyUdJW0jUzMQZQji6RoZGOjoGhsYxAIA).
**Explanation:**
```
# Example inputs: +256 -256
```
Uses the legacy version of 05AB1E built in Python 3 for `1%` to work. In the new version built in Elixir, it'll give incorrect results.
```
Ä # Get the absolute value of the (implicit) input-integer
# 256 256
т+ # Add 100 to it
# 356 356
/ # Divide the (implicit) input by this abs(input)+100
# 0.719... -0.719...
( # Negate it
# -0.719... 0.719...
1% # (Python-style) modulo-1
# 0.280... 0.719...
# (after which it's output implicitly as result)
```
Uses the new version of 05AB1E builtin Elixir for `{` to work. In the legacy version, it'll always keep the input first because it's seen as [string,integer] instead of [integer,integer].
```
т‚ # Pair the (implicit) input-integer with 100
# [256,100] [-256,100]
{ # Sort this pair
# [100,256] [-256,100]
Ä # Get the absolute value of each
# [100,256] [256,100]
η # Get the prefixes of this pair
# [[100],[100,256]] [[256],[256,100]]
O # Sum each inner list
# [100,356] [256,356]
` # Pop and push both values separated to the stack
/ # Divide them from one another
# 0.280... 0.719...
# (after which it's output implicitly as result)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
NθI∕↔⌊⟦¹⁰⁰θ⟧⁺¹⁰⁰↔θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMMlsywzJVXDMak4P6e0JFXDNzMvM7c0VyPa0MBAR6EwVlNTRyEgp7RYA8yHKyvUBAHr//91jQ0M/uuW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Turns out to be a port of @noodleman's original Ruby answer.
```
Nθ Input `n` as a number
¹⁰⁰ Literal integer `100`
θ Input `n`
⟦ ⟧ Make into list
⌊ Take the minimum
↔ Absolute value
∕ Divided by
¹⁰⁰ Literal integer `100`
⁺ Plus
θ Input `n`
↔ Absolute value
I Cast to string
Implicitly print
```
A slightly less accurate version is 16 bytes:
```
NθI∕χ⁺χ⌈⟦∕θχ±∕φθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMMlsywzJVXD0EBHISCntBjM8E2syMwtzdWIhkoW6igYGmjqKPilpieWpCK0GADVFmpqxmqCgPX//7rGBgb/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: "Illegal" positive odds and negative odds can be converted into "legal" odds by dividing into `-10000`, but we can also use this to convert all odds into positive odds and then use a modified version of the formula for those odds, the modification being `10/(10+n/10)`, since this is golfier in Charcoal.
```
Nθ First input as a number
χ Predefined variable `10`
∕ Divided by
χ Predefined variable `10`
⁺ Plus
θ Input odds
∕ Divided by
χ Predefined variable `10`
φ Predefined variable `1000`
∕ Divided by
θ Input odds
± Negated
⟦ Make into list
⌈ Take the maximum
I Cast to string
Implicitly print
```
[Answer]
# [Uiua](https://www.uiua.org/), 10 [bytes](https://codegolf.stackexchange.com/a/265917/95126)
```
◿1`÷+100⌵.
```
[Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4pe_McKvw7crMTAw4oy1LgpmIDE1MDBfMjU2XzEwMF_CrzIwMF_CrzMwMA==)
Port of [loopy walt's Python answer](https://codegolf.stackexchange.com/a/265181/11261). If scored in UTF-8, beats the solution I wanted to post even harder because ``` [autoformats](https://www.uiua.org/docs/basic#formatting) to `¯` to save a single byte.
The solution I wanted to post:
# [Uiua](https://www.uiua.org/), 11 [bytes](https://codegolf.stackexchange.com/a/265917/95126)
```
÷+,⊙⌵⊃↥↧100
```
[Try it online!](https://www.uiua.org/pad?src=ZiDihpAgw7crLOKKmeKMteKKg-KGpeKGpzEwMApmIDE1MDBfMjU2XzEwMF_CrzIwMF_CrzMwMA==)
Indirect port of [my Jelly solution](https://codegolf.stackexchange.com/a/265169/85334). A [direct port](https://www.uiua.org/pad?src=ZiDihpAgL8O34oeMXCvijLXiio_ijY8u4oqfMTAwCuKItWYgMTUwMF8yNTZfMTAwX8KvMjAwX8KvMzAw) comes out considerably longer due to scan/reduce operating right to left and it taking 3 characters to sort an array, but `⊃↥↧ fork max min` sorts the top two values on the stack right in place on the stack, taking arrays out of the picture entirely... unfortunately also needing an extra `⊙ dip` (or some restructuring and a `: flip`) to abs afterwards.
[Answer]
# Google Sheets, 25 bytes
`=mod(-A1/(abs(A1)+100),1)`
Put the input in cell `A1` and the formula in `B1`.
Uses `mod()` like the [Python answer](https://codegolf.stackexchange.com/a/265181/119296).
[Answer]
# [Ruby](https://www.ruby-lang.org/), 21 bytes
Direct port of [loopy walt's Python answer](https://codegolf.stackexchange.com/a/265181/11261), for completeness.
```
->n{n/(-1e2-n.abs)%1}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhZbde3yqvP0NXQNU4108_QSk4o1VQ1rIXI3zcszMnNSFdJTS4o1kjPycwusFEqKSlM1uRQUCkpLihWUlFXiY0qUq92iVeL1SvLjM2NrlbhS81Ig2hfs1TY0NTDgUtA2MjUDkoYgtq4RmDQ2MIAoAgA)
[Answer]
# [C (GCC)](https://gcc.gnu.org), ~~49~~ ~~36~~ ~~34~~ 33 bytes
```
f(n,r){r=(n?100:(n=-n))/(1e2+n);}
```
Saved a byte by negating `n` within the ternary and eliminating the `abs` call.
[Attempt This Online!](https://ato.pxeger.com/run?1=XVDdToMwFL7nKY5LSNpRtNTCmIg-yCRmYevSRMvSFW8I72HiDRfuofY2HihZ1Cbnp9_5-875Otevh7oeLp91Y04OtBnl2LrTpoISOoiSlHMGkUgz1Mnox2LS95xDXwS-Tr01WwdN636VAvBbnomUTZ7Ieb7O81UmuZRrKT06B7N_z6OrFAecW6fi_HKjiGGWdrYk5hlpPBBTxobSO5LsRWRo0c-J3-MK71ttyEejdxS6AEA1Fsi0GhLjBZpHSNFEkY_DzH9p967wfzJfQVcMEKUePlrsosgi3EH8BKGCTaiqF7Ng8DedXU-hq6m0R0G8tQbnBzPXYfD2Bw)
---
```
f(n,r){r=(n?100:-n)/(1e2+abs(n));}
```
Changed `100.0` to `1e2` to save 2 bytes, since want 100 as float.
[Attempt This Online!](https://ato.pxeger.com/run?1=XVBdToQwEH7nFBMSklaKFgSWFVcPspINsttNk7XdlOIL4R4mvvDgHmpv40CJUZvMfNNv_ufz0uyOTTNePxqtWgtSTXLubLutYAM9hHHGOYMwyXLU8WRHyazvOYeh9FyeOOnagu7sr1QAfsvzJGOzlRS8WBfFKk95mq7T1LGLM__3HLvKsMGlsyIqrr4gihnamw1RzzjGQ6ToHYkPSVi_tkRRWg5L5Ne0w1stFXnXck-h9wCENkDm3XAyXiI8QoYQhs4PywI35mBL9yfLGWTFAFnq6LPBKoL4wR6iJwgEbANRvSifwd9w9nMLWc2pAwrynVHY31tmHUeH3w)
---
```
f(n,r){r=(n?100:-n)/(100.0+abs(n));}
```
Changed the function name to a single char :P, used just `n` instead of `n>0` in the ternary to check for positivity of the number `n`, used the out param `r` to store the return value.
[Attempt This Online!](https://ato.pxeger.com/run?1=XVDdToMwFL7nKU4WSdq1zI4BY-L0QSYxyKxpomUpxRvCe5h4w4V7qL2NB9oYtck53-l3_s_nuX58qevx8lE3urWg9CSnzraHEvbQA1unQnBgcZqhXk92FM96IwQMReDy5GtTWWg6-ysVQKxEFqd8tuJc5Ls832aJSJJdkjjWO7N_z7HbFBucOyuj_HIlieaG9mZP9D2OcRNpek3QWAlWPbVEU1oMPvZr2uKtUpq8N-pIoQ8AZGOAzNvhbKJAuIUUgTHnB7_C0jzbwv2JP4QqOSBLHX0yWEWSRXiE6A5CCYdQlg96weFvOP-5hirn1AEF-c5o7B_4WcfR4Tc)
---
```
float golf(n){return(n>0?100:-n)/(100.0+abs(n));}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVDdaoMwFL7PUxwKQkTtjk5tWrfuQToZzi5FaJOicTcie43BbrzpQ_VtdjS2jAVy_r-c78vPpXw7lOVw_S61agxUarzn1jS7HJ6hAy9MEH3woiQlG45xEE32ERH6jFmcPOrCgG7NHygALjGNEn-KIoFiLcQqjTGO13Fsq3Mz_XdsdZXQgktrZCCuod1w0EfJldvVH6atFVdbfCFOm0C5D5yCJXrFe0MDbtbPwK9R0qmoFP_U1d6FjkldA5-EEk3MyD1BQs7zxu65ppbkC2cPwRYcCTtH5q9q4d_-pcp9S-Oeu_5dOSUZ65mlR4-zmcYwWP8L)
This is my low effort attempt at golfing this problem using C. Need help!
] |
[Question]
[
In chess, *fork* means to target two pieces with just one piece, and one of the best pieces for forking is the knight.
In this challenge, you will be given three coordinates in `a` to `h` and `1` to `8` (like `a8` or `e7`) format. The first and second coordinates are for two other random pieces, and the third is the knight's coordinate. You must return or output the coordinate where the knight can move to create a fork, attacking both pieces. An example is this:
[](https://i.stack.imgur.com/jRBoc.png)
Here, the first and second inputs will be `d6` and `f6` and the third (knight) will be `g3`. You must return `e4`, where the knight can attack both rooks.
### Testcases
```
Input: d6,f6,g3 | Output:e4
Input: d4,d6,e7 | Output:f5
Input: c3,f2,b2 | Output:d1
```
#### Notes
* You may assume it is possible to find a fork with the given input.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins!
[Answer]
# [Python 2](https://docs.python.org/2/), 129 bytes
```
def f(a):x,p,y,q,z,r=map(ord,a);x-=z;y-=z;p-=r;q-=r;u=x*x+p*p;v=y*y+q*q;w=x*q-y*p<<1;return chr((u*q-v*p)/w+z)+chr((v*x-u*y)/w+r)
```
[Try it online!](https://tio.run/##VchLDoIwEADQvacgrNppGyMYTCw9DFIqLoTphE/L5Su4MW7e4mGc@nEoUrKdyxxr@D1IlFF6uUky7wbZSFY2XAdlNh0PUBnS/mA2AYJAQL2YCFF48Hrdz6sIWNcXTd0005C1PTE2770A8vMqNi6@tUBQM8SjiCek1zAxx3JbuepZ5pyffnW1VXf7q7Z0xaPYK30A "Python 2 – Try It Online")
Input as a single string like `f("d6f6g3")`.
For given three points \$\left(x\_1,y\_1\right)\$, \$\left(x\_2,y\_2\right)\$, \$\left(x\_3,y\_3\right)\$, the center of the circle determined by these three points is
$$
\left(
\frac{\left|\begin{matrix}x\_1^2+y\_1^2 & y\_1 & 1 \\ x\_2^2+y\_2^2 & y\_2 & 1 \\ x\_3^2+y\_3^2 & y\_3 & 1 \end{matrix}\right|}{2\cdot\left|\begin{matrix}x\_1 & y\_1 & 1 \\ x\_2 & y\_2 & 1 \\ x\_3 & y\_3 & 1 \end{matrix}\right|},
\frac{\left|\begin{matrix}x\_1^2+y\_1^2 & x\_1 & 1 \\ x\_2^2+y\_2^2 & x\_2 & 1 \\ x\_3^2+y\_3^2 & x\_3 & 1 \end{matrix}\right|}{2\cdot\left|\begin{matrix}x\_1 & y\_1 & 1 \\ x\_2 & y\_2 & 1 \\ x\_3 & y\_3 & 1 \end{matrix}\right|}
\right)
$$
And this formula is find out from [this SE post](https://math.stackexchange.com/a/1460096). I'm too lazy to find out the formula by myself.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~50~~ ~~21~~ 19 bytes
```
ƛk-:dẊ:RJ$Cv+C;Þf∆M
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLGm2stOmThuoo6UkokQ3YrQzvDnmbiiIZNIiwiIiwiXCJkNlwiLCBcImY2XCIsIFwiZzNcIiJd)
One of the programs ever written. Luckily, there's no enpassant with horseys, so there's no bricks needed. However, I will note that this doesn't account for knightboosting. Also doesn't account for knook movements.
Uses the simplification of the problem pointed out by @mousetail in the comments.
## Explained
```
□ƛ # To all squares in the input
k-:dẊ:RJ # Generate all vector directions of how the horsey moves. This is the hardest part because until recently, not even the smartest scientists knew how the horsey moved.
# This will be a list of [horizontal spaces, vertical spaces]
# [[-1, 2], [2, 1], ...]]
# Generated by:
# Doubling the list [1, -1] (k-:d)
# Getting the cartesian product of those two lists (Ẋ)
# Pushing a second copy and reversing each list in it (R)
# And joining it to the cartesian product (J)
Cv+C # To a list of ordinal points of where the horsey is, add each horsey move
ÞfĊ↑h # Flatten by a layer and get the most common square.
```
If you can't tell from that, I am somewhat of a chess anarchist :p
[Answer]
# [Factor](https://factorcode.org/), ~~86~~ ~~79~~ ~~76~~ 67 bytes
```
[ [ """"zip [ 3 v-n v+ ] with map ] map-flat mode ]
```
[Try it online!](https://tio.run/##JY6xTsNAEERly278FYNbFEvESZBCQ4doaBBVlOI475FVzvb5bmMLEN9uLk4zWr23Go1RWno/f7y/vr3sEWi4UKcpoFVyqka6ygDnSeTbee4Ew4Qz@Y7s7SWIEg7COkD3rWNLvroIWxaOLSqEPpqnohimXzQ7mB2@avzhDrS5sc0V0@PCzHZhuoZZ43O9sOahmA84oMyyPE/TJCnLPMnSJE@z8oddNDXGVYfxHkdMLKe4y8Uz5spYJWj7hnCcxfMzqrjSkvLzPw "Factor – Try It Online")
Takes input as a sequence of three strings.
* `[ ... ] map-flat` Map over each element in the input, flattening the results.
* `""""` Two strings with eight literal control characters each. (You can see them on TIO.)
* `zip` Zip them together. These are the knight moves + 3 -- i.e.
```
{ { 4 5 } { 4 1 } { 5 4 } { 5 2 } { 2 1 } { 2 5 } { 1 2 } { 1 4 } }
```
* `[ 3 v-n v+ ] with map` Add the element we're mapping over to each of the knight moves. For example, if the current element is `"d4"`, this is the result:
```
{ "e6" "e2" "f5" "f3" "c6" "c2" "b5" "b3" }
```
* There will occasionally be results that are outside of the board, but it doesn't matter because these will never be the most frequent move.
* `mode` Find the most common move.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 32 bytes
Takes input as a single list of three strings.
```
`c$*>#'=,/(2-5\28848 84144)+/:\:
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs0pIVtGyU1a31dHXMNI1jTGysDCxULAwMTQx0dTWt4qx4uJKc1DSUYpRSjHTSTPTSTdWAgAvpQti)
Apply all 8 knight moves to each of the pieces, then find the most common target square.
The knight moves are hardcoded using base encoding, the shortest way I found to actually generate them was 5 bytes longer:
```
+,/|:\',/2 -2,'/:1 -1
```
[Answer]
# [Python](https://www.python.org), 96 bytes (@tsh)
```
f=lambda A,R=1:{5}^{(R//9-ord(f))**2+(R%9-int(r))**2for f,r in A}and f(A,R+1)or f"{R//9:c}{R%9}"
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3E9JscxJzk1ISFRx1gmwNrapNa-OqNYL09S1184tSNNI0NbW0jLQ1glQtdTPzSjSKwPy0_CKFNJ0ihcw8BcfaxLwUhTQNoG5tQ02QuFI1SLdVcm01UFOtEtSegIIikP40jWilFDMlHaU0EJFurBSrqcmFJGUCFAXLp5qjSSUbg3QZAYkkI5AUxFyYPwA)
### Old [Python](https://www.python.org), 100 bytes
```
f=lambda A,R=1,F=97:{5}^{(F-ord(f))**2+(R-int(r))**2for f,r in A}and f(A,R%8+1,F+R//8)or f"{F:c}{R}"
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3U9JscxJzk1ISFRx1gmwNddxsLc2tqk1r46o13HTzi1I00jQ1tbSMtDWCdDPzSjSKwLy0_CKFNJ0ihcw8BcfaxLwUhTQNoG5VC22gfu0gfX0LTZACpWo3q-Ta6qBaJahdAQVFIDPSNKKVUsyUdJTSQES6sVKspiYXkpQJUBQsn2qOJpVsDNJlBCSSjEBSEHNhfgEA)
Expects a list of three two-character strings. Trusts OP's promise that it is a forkable position (will never return otherwise).
### How?
Well, there are only 64 candidate squares so we check them all.
[Answer]
# [Python](https://www.python.org), 144 bytes
```
lambda a,b,c:(g(a)&g(b)&g(c)).pop()
g=lambda x:{chr(ord(x[0])+i)+str(int(x[1])+j)for(k,l)in((1,2),(-1,2),(1,-2),(-1,-2))for(i,j)in((k,l),(l,k))}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY5NDoIwEIX3nIKwMDNhMFaNGhJOoi74sbWA0NSaYIx3cO-GDd7J21h-EjfvZd77ZjLvj7qbc121HXcj99DdDA9231cZX5IsdmNKKA1BQIwzAUkvKeJc1QrQEdFENeEjPWuodQbNfnFEX6J_NRpkZWzAbJAjrzUUVKKsABgtkSAYjVEwTdYHTFI-YD1OUFKB-Jz-Ykr3Rzl42cYjj_ciVh6i8y_WNhva09YW42Lbjv4D)
Performs "en passant" whenever possible. Which is never, since there are no white pawns.
[Answer]
# Excel, ~~126~~ 122 bytes
Saved 4 bytes by dropping `m` as a variable.
```
=LET(a,A1:C3,x,CODE(A1:A3)-96,c,MMULT(MINVERSE(2*IFS(a=0,.5,ISTEXT(a),x,1,a)),x^2+B1:B3^2),CHAR(INDEX(c,1)+96)&INDEX(c,2))
```
Inspired by [tsh's answer](https://codegolf.stackexchange.com/a/256856/38183) although I found a different formula. Note that Excel will change `IFS(a=0,.5,` to `IFS(a=0,0.5,` after you enter the formula.
Input is in the range `A1:B3` with one half of each coordinate per cell. The range `C1:C3` must be left blank. The formula can go anywhere except in the range `A1:C3`. The first testcase is input like this:
[](https://i.stack.imgur.com/DQB0p.png)
The `LET()` function allows you to store data as variables and later reference those variables. The terms are in pairs except the last which is the output.
* `a,A1:C3` stores the input range as a 3x3 array.
* `x,CODE(A1:A3)-96` stores the number version of the input letters in a 1x3 array.
+ You *could* leave off the `-96` part here and the `+96` part later but doing that matrix math with larger numbers has rounding errors so you may sometimes get answers like `e4.00000000000023` and these two offsets are less bytes than trying to round it later.
* `IFS(a=0,.5,ISTEXT(a),x,1,a)` converts the input array into a more usable form by:
+ Replacing the blanks in `C1:C3` with `.5`
+ Replace the characters in `A1:A3` with their numerical equivalent
+ The end result looks like this:
[](https://i.stack.imgur.com/nGzg7.png)
* `c,MMULT(MINVERSE(2*IFS(~)),x^2+B1:B3^2)` does fancy math stuff ([that I did not write myself](https://www.mrexcel.com/board/threads/find-centre-radius-from-3-x-y-points.1132340/#post-5476135) but I did tweak a bit) and it spits out a 1x3 array with the x-coordinate, y-coordinate, and constant from the general equation for a circle. For the first testcase, the value of `c` looks like this:
[](https://i.stack.imgur.com/aMcRz.png)
* `CHAR(INDEX(c,1)+96)&INDEX(c,2)` changes the x-coordinate to a letter and concatenates it with the y-coordinate.
---
Here are the results for the three testcases:
[](https://i.stack.imgur.com/eUX0X.png)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~52~~ 30 bytes
```
F³⊞υSΦΣEβEχ⁺ιλ⬤υ⁼⁵ΣXEλ⁻℅ν℅§ιξ²
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY69CsIwFIX3PkVwuoEIarEITh0UOoiFjuKQtrYNXNOaH-27uHRQ9JV8GxN_znIPB76Pe30WDVdFy3EY7tZU48XrXrWKQEhJanUDlpFEdtZkRglZA6XLIHXNwFqgOSjI7BE2vIOcEX-mE0ZStBoEI0hdGIkRvWV1shw1zBnxSNpeHOwJdKCQjtiqUkiOIB3z77FJZHnova3_2mb0k-VN54X-vfzYjcZnHO2fZRRUUVCH3_kN) Link is to verbose version of code. Explanation:
```
F³⊞υS
```
Input the three strings.
```
ΦΣEβEχ⁺ιλ
```
Create the 260 strings `a0` to `z9` and filter on the one that satisfies...
```
⬤υ⁼⁵ΣXEλ⁻℅ν℅§ιξ²
```
... the sum of the squared ordinal differences between corresponding code points is equal to `5`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
O+€Ø+pḤUƬẎ¤f/Ọ
```
A monadic Link that accepts a list of the three distinct, pairs of characters and yields a list of one pair of characters representing the destination square. When run as a full program the destination is printed.
**[Try it online!](https://tio.run/##y0rNyan8/99f@1HTmsMztAse7lgSemzNw119h5ak6T/c3fP///9o9WRjdR0F9TQjEJlkpB4LAA "Jelly – Try It Online")**
### How?
The square on which the knight may fork is the square all three pieces could move to *if* they were all knights. The code finds those three sets of squares (including off-board ones\*) and finds the intersection.
```
O+€Ø+pḤUƬẎ¤f/Ọ - Link: list of lists of characters, C
O - cast (C) to ordinals
¤ - nilad followed by link(s) as a nilad:
Ø+ - [-1, 1]
Ḥ - double -> [-2, 2]
p - cartesian product -> [[1,2],[1,-2],[-1,2],[-1,-2]]
Ƭ - collect while distinct applying:
U - reverse each -> [[[1,2],[1,-2],[-1,2],[-1,-2]],[[2,1],[-2,1],[2,-1],[-2,-1]]]
Ẏ - tighten -> [[1,2],[1,-2],[-1,2],[-1,-2],[2,1],[-2,1],[2,-1],[-2,-1]]
+€ - add to each ordinal pair (vectorises)
/ - reduce by:
f - filter keep
Ọ - cast to characters
```
---
\* Even though off-board positions may be present in the three sets I believe that this will yield the single destination square if possible or an empty list if not possible. (The three inputs just need to be distinct!)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 20 bytes
```
{l;1~ȧᵐ≜p;?ạᵗz+ᵐ~ạ}ᵛ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wvzrH2rDuxHIg81HnnAJr@4e7Fj7cOr1KGyhQB2QD1cz@/z86WinFTElHQSkNTKYbK8XqKADFTEA8iEyqOUQs2RiszghEJhkpxcYCAA "Brachylog – Try It Online")
```
{ }ᵛ Produce the same output from all elements of the input:
l take the element's length (2),
;1 pair it with 1,
~ȧᵐ≜ un-absolute-value both,
p and permute;
; z+ᵐ sum with corresponding elements of
ạᵗ the character codes of
? the element;
~ạ convert from character codes.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ç®X‚xâDí«δ+çJ˜.M
```
Inspired by [*@mousetail*'s comment](https://codegolf.stackexchange.com/questions/256814/knight-to-fork#comment568140_256814)!
[Try it online](https://tio.run/##yy9OTMpM/f//cPuhdRGPGmZVHF7kcnjtodXntmgfXu51eo6e7///0UopZko6SmkgIt1YKRYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w@2H1kU8aphVcXiRy@G1h1af26J9eLnX6Tl6vv91/kdHK6WYKekopYGIdGOlWB2ggAmQDRZNNQcLJBuDVBgBiSQjpdhYAA).
**Explanation:**
```
Ç # Convert the (implicit) input-triplet of strings to pairs of their codepoints
®X‚xâDí« # Push list [[-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[2,-1],[-2,1],[2,1]]:
®X‚ # Push pair [-1,1]
x # Double the values in this pair (without popping): [-2,2]
â # Get the cartesian product of the two pairs
D # Duplicate this list
í # Reverse each inner pair
« # Merge the two lists together
δ # Apply on the two lists double-vectorized:
+ # Add them together
ç # Convert each inner-most integer back to a character with this codepoint
J # Join each inner pair together to a string
˜ # Flatten the list of lists of strings
.M # Pop and leave the most frequent string
# (which is output implicitly as result)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
⁹p`ạỤ€Ƒ¥ƇOỌ
```
[Try it online!](https://tio.run/##y0rNyan8//9R486ChIe7Fj7cveRR05pjEw8tPdbu/3B3z//D7ZqR//9Hq6eYqesoqKeByXRj9VgdBaCYCYgHkUk1h4glG4PVGYHIJCP1WAA "Jelly – Try It Online")
Sidesteps actually generating knight moves by just checking them with good old brute force.
```
⁹p` Generate the Cartesian product of [1 .. 256] with itself.
⁹p` 256 is Jelly's smallest single byte constant >= 108,
O the character code of 'h'.
Ƈ Filter that list of pairs to the single one for which
ạ ¥ the list of its element-wise absolute differences from each of
O the input pairs converted to character codes
Ƒ is equal to itself with
€ each difference pair
Ụ graded up (converted to a list of indices sorted by their values).
Ụ Ƒ Every list of length 2 grades up to either [1, 2] or [2, 1].
Ọ Convert the surviving pair from character codes.
```
[Answer]
# [C (GCC)](https://gcc.gnu.org), ~~138~~ ~~133~~ ~~131~~ 126 bytes
*-12 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
```
f(s,x,b,i)char*s,*x;{b=0;for(*x=96;b=i=!b&(++x[1]<58||++*x<105&&(x[1]=48));)for(;i<8;i+=3)b*=abs((*x-s[i-1])*(x[1]-s[i]))==2;}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fZBNbsIwEIXX5BQuUiOPPRE4f03l-CQ0qmKDqSUaqphKloBepBs2rHqi3qYJ0C3L-fS9p6f5PpvXtTGn0_lzZ5Pq98tSjwE1OjBvbc88siD3Ws2l3faUBfVcSq2cetAx5TwsRFMX1eHAOQu1mBdxTEem8gpAwhiRrq6k4yoDzVSrPR1KEr9wiWiAXeTxagCUSuXxtuLHdTvy3rqOwj6ajEMIC0QR0242W0MzJAJkNLF0uizRlrjOpkgCSPLRD8kBP_qX7oZmM7LKr26Og756uuva4uKaDG2KOr3rLkV0jK6T_x_4Bw)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 113 bytes
```
->s{a=s.bytes
20000.times{|i|(a[1+j=i%3*2]-y=i/3%58)**2+(a[j<1?C=0:j]-x=i/174)**2==5&&C+=1
C>2&&(p x.chr+y.chr)}}
```
[Try it online!](https://tio.run/##TclLCoMwFIXhuasQi8EHWpP4KNJrBy6gCxAHPpJWoSBGwaCuPdWZZ3AG3z/OtVQclJeJtQLh13JiQiPBMX/qfkysW7dZVYHdHjqTOqT0JHR3akYP23GIe6T@iV85BGlfesuRcBKeBSBCKHcBa3lGELIGffGb7@jK8@19V7ww2pjHH2qUN11/z9MwTykLtdPDNmbJ1Xl0ekM5qcnVW6z@ "Ruby – Try It Online")
Function takes input as a single string like `d6f6g3` and prints output to stdout.
The idea is to find coordinates whose euclidean distance squared from all three inputs is 5. This is counted in `C`, which is reset every third iteration when `j=i%3*2` is zero. A lowercase `c` (variable) would halt execution because Ruby assumes that it may not be initialized by the time it is needed. Therefore we use an uppercase constant `C` which executes fine (but generates a warning to stderror every time it is changed.)
Input is converted from characters to ASCII codes and final result is converted back from ASCII codes to characters. As ASCII codes for `h8` are 104 and 56, there are nearly 6000 possibilities for the output. For each of these we have to check the 3 inputs so the minimum number of iterations required is a little under 20000. Code is short, but inefficient! If uppercase input is allowed, this can be reduced to just over 12000 iterations.
[Answer]
# [Desmos](https://desmos.com/calculator), 126 bytes
```
L=[-2...2]
P=[(a,b)fora=L,b=L]
A=[p+qforp=l+0P,q=P[P.x^2+P.y^2=5]]
X=A[A.x=i.x]
C=[X[X.y=i.y].lengthfori=A]
f(l)=A[C=C.max][1]
```
Takes in a list of points, with each coordinate being a charpoint, and returns a point, with each coordinate being a charpoint.
This is just a port of one of the strategies I saw while scrolling through here. It finds all possible positions that can be reached if all three pieces are treated as knights, and find the mode (most common value) of those positions. There is probably a better way to do this (maybe something more mathematical?), but I think this is fine for now.
As a bonus, I included a simple chessboard graphic so y'all can visualize the test cases :D
[Try It On Desmos!](https://www.desmos.com/calculator/jnkfm1qnkx)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/rdedssqasm)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~77~~ 76 bytes idea from tsh
-1 byte from
naffetS
```
f=(a,i)=>a.some(x=>(parseInt(x,18)-i)**2%323%179^77)?f(a,-~i):i.toString(18)
```
[Try it online!](https://tio.run/##VZbNbtswEITvfQrXaAKrcAJIFEm1hdNLLznXt8BF9UPJLlo7iI0iQOC@erqcCVfyZRyR2tXOx@Uiv@q/9bF92j2ebvaHLry@9qtFvdxlq7v69nj4ExbPq7vFY/10DPf70@J5mVfZzS77@LG4MoW5yv2nH95nX3uJufm3yz7vbk@H76en3X5YyJuv63A8HVcv8zqff36YN2a@nLfFfLOc1wUWyriQRzFYNViNC43luyIltkpsxYXGMUDEYstq8sYzQMRhy@lnmooBIh5bHluW74pUWK2w6vS1BpXXJn2yQ/kNyq/L9LUultzBQwMPdVyordqzDBWBmwZu6rhQOzXqmEQEvhqrn669WvZMIgKHjdNK6krNV0wiQhPwynIsQ0VguIFhFuE0oM21PnBFVQHW22L0B@RlKijEtQAIrRn9Ab4eKUlZphMBjrYcncat8ZjJzDGxCMC0dvTsUok4etLzTCwCRK1T9@A4tgM5VkwsQu9eiYAoy7ZMJwJsLbF5rdNpfJdrp@LEUHgPdl0x9rdJh4VK@7jWg11nxk4vLxqIgC3TiYBdV47dby9aiYAdE4uAXWfHG@EumoqAPROLgF3n9JZM7lalgCsmFqF3r9dnvG@sGHWAXcc75rVOp/EB7GABR4nCB7ALYJeGxdvZodIhrg1gF4zGT@6lVcCW6UTALoBdGiXTbiNgx8QiYBfALo2XabcRsGdiEbALYJdGzrTbCLhiYhF6B7s0i1LZlulEwC6AHdM5LRHxPdjBAo4ShW/Brge7NKTezg6VbuPaFux6o/GT62wVsGU6EbDrwS6Nq2m3EbBjYhGw68EuDa5ptxGwZ2IRsOvBLo2wabcRcMXEIvQOdmmspbIt04mAXQ92TOe0RMQPYAcLOEoSGYAtjbW3Y6P7wWjA5P5aJQrPAxClwTVtKnKE0wFg0riathLpsT7gSENq2kBkBn8DIKQhlcphJbDOUKef3sI1quL12cJwmkXplmyNvja5b8i7hcM0Xsaj3@DDcau8vEdws4WbNDbGI93Abtxyk/uxgb@46t@Sn7@86w9Pi/jPxf232W4/w78Z2Uv8WeHvB@5tvuC9fHbo8U6Gx@Ly0ejjrpd336/WxfW6kB9zvTbyk8f1fvGwzpfrYrk2m@z9iumz9rA/Hn6H29@HYfHzw8s6Py9FC6g5z8LzY2hPoZt9eGHAeTkbwkkeL9Kdf2bn1/8 "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), ~~87~~ 85 bytes
```
f=(a,i=180)=>a.every(x=>/16|20|35|37/.test(parseInt(x,18)-i))?i.toString(18):f(a,-~i)
```
[Try it online!](https://tio.run/##VZZPb9pAEMXv/RQUVRGWCIm93rWVivTSS8/lFiHVf9aGKoIIUJWK0K@ezr6XHZvLI571juf9dnaU39Wf6tgcti@n292@9e/v3XJWzbfLtLxPlo/Vwv/xh7@z1@XjXeresvs3Y99Mcbc4@eNp9lIdjv7H7jR7nadlcrtNkm/bxWn/83TY7vqZhB46yXX7b5u8r@T94/I8rdLpw9O0NtP5tMmm6/m0yhDIQyANYhA1iIZAbfmuSI6lHEshUDtuELFYspq8LrhBxGHJ6WfqkhtECiwVWLJ8V6REtETU6Ws1Kq9M/GSL8muUX@Xxa20ouYWHGh6qEKis2rPcKgI3NdxUIVA5NeqYRAS@aqufrgq1XDCJCBzWTiupSjVfMokITcAry7HcKgLDNQyzCKcbmlTrA1dU5WG9yQZ/QJ7HgnyIeUBozOAP8PVIScoynQhwNPngNCwNx0xmjolFAKaxg2cXS8TRk17BxCJA1Dh1D45DO5BjycQi9F4oERBl2ZbpRICtIbZC63S6v021U3FiKLwDuzYb@tvEw0KlXYh1YNeaodPzqwYiYMt0ImDX5kP326tWImDHxCJg19rhRrirpiLggolFwK51ektGd6tUwCUTi9B7oddnuG@sGHWAXcs7VmidTvd7sIMFHCUK78HOg10cFh9nh0r7EOvBzhvdP7qXVgFbphMBOw92cZSMu42AHROLgJ0Huzhext1GwAUTi4CdB7s4csbdRsAlE4vQO9jFWRTLtkwnAnYe7JjOaYnY34EdLOAoUfgG7Dqwi0Pq4@xQ6SbENmDXGd0/us5WAVumEwG7DuziuBp3GwE7JhYBuw7s4uAadxsBF0wsAnYd2MURNu42Ai6ZWITewS6OtVi2ZToRsOvAjumcloj9PdjBAo6SRHpgi2Pt49jovje6YXR/rRKF5x6I4uAaNxU5wmkPMHFcjVuJ9FgfcMQhNW4gMoO/HhDikIrlsBJY51ann97ANari9dnAcJxF8ZZsjL42um/Iu4HDOF6Go1/jw2Epv75HcLOBmzg2hiNdw25YcqP7sYa/EC0@kl@@fur2h1n45@LH98l2N8G/Gck5/Czx9xPX1l/xXjrZd3gnwWN2/Wj0cdvJu5@Xq@xmlcmPuVkZ@UlDvJs9rdL5KpuvzDr5vGT6pNnvjvtnv3je97NfX86r9DIXzaDmMvGvL745@Xby5cwNl/mk9yd5vEp3@ZVc3v8D "JavaScript (Node.js) – Try It Online")
Discuss in base 18
[18 is only choice](https://tio.run/##VZY9b9swEIb3/IrUQyLVdlB9kBLiKl3awYuG1ksQeNAHJbsI7MA2ghRp@tfT4/uGlLyc7CPvdO/D40G/q@fq2By2T6f5bt@a925/CMoiyhfl10QvptMyfF0W13@vFxf3xU/T/3h5CoJyHofT5TQop@5ZziP3axqF4eK9K4Jqti2iL5/LsLirbsyzOfwJXoq7@5uTOZ6Cp@pwNMvdKXiZleF8G4bftjen/a/TYbvrgzK87SR8/m8bvq9k97F4nVTR5PZhUieT2aSJJ@vZpIrhSK0jsiaBN4HXOmrFvWJSLKVYso5aM0CMwpLyyeuMAWI0lrR/TZ0zQEyGpQxLinvF5PDm8Gq/rUblVeJe2aL8GuVXqXtba0tuoaGGhso6KuXlKYaKgZoaairrqLQXqplEDHTVyr@6yrzkjEnEQGGtfSVV7sXnTCKGIqCV5SiGioHgGoJZhPYBTeTrA1dUZSC9iQd9QJ66goz1GUBokkEf4PsjJSnFdGKAo0kHpXZpOGYy00wsBmAaNWjWrkQcPellTCwGiBrt1YPj0A7kmDOxGGrPPBEQZdmK6cQAW0Nsma9T@/g28p2KE0PhHdi18dDfiTssVNpZXwd2bTJ0enrWQASsmE4M2LXp0P3qrJUIWDOxGLBr1XAj9FlTEXDGxGLArtX@lozuVu4B50wshtozf32G@8aKUQfYtbxjma9T@3gDdpCAo0ThPdgZsHPD4uPsUGlvfT3YmcTHj@6l8oAV04kBOwN2bpSMu42ANROLATsDdm68jLuNgDMmFgN2BuzcyBl3GwHnTCyG2sHOzSJXtmI6MWBnwI7ptC8R8R3YQQKOEoVvwK4DOzekPs4OlW6sbwN2XeLjR9dZecCK6cSAXQd2blyNu42ANROLAbsO7NzgGncbAWdMLAbsOrBzI2zcbQScM7EYagc7N9Zc2YrpxIBdB3ZMp32JiO/BDhJwlCTSA5sbax/HRvV94gNG91d5otDcA5EbXOOmIkco7QHGjatxK5Ee6wMON6TGDURm0NcDghtSrhxWAukM1f7VG6hGVbw@Gwh2s8jdkk3it43uG/JuoNCNl@Ho13ixXUrP7xHUbKDGjY3hSNeQa5f06H6soc96s4/kb4sL@6FjPy6W3y@3u0t8ZoSv9lHg9wPX1gvsiy73HfaE@Buf/038320nez8Vq/hqFcsjuVol8oisvwseVtFsFc9WyTr8VDB9KN9W14u3iwvZsAyb/e64fzQ3j3v7DbR4e/8P)
[25-29 to only save a `$`](https://tio.run/##VZZNb9pAEIbv@RUph2ALiOSPXVuhTi7tgQuHlksUUckfa0MVQQQoSpWmfz2dfV92bS5jmN0Zz/vs7Mi/y9fyWB@2L6fZbt@Yz3Z/CJZFlM@XXxM9n0yW4fuiGP8dz68eix@m@/72Eox/zR6C8SRYzuJwspDnxD2Xs8j9msivcTgO559tEZTTbVjcl7fm1Rz@BG/F/ePtyRxPwUt5OJrF7hS8TZfhbBuGD9vb0/7n6bDddcEyvGslcvZvG36uZPexeB@V0ejuaVQlo@mojkfr6aiM4UitI7ImgTeB1zoqxb1iUiylWLKOSjNAjMKS8smrjAFiNJa0f02VM0BMhqUMS4p7xeTw5vBqv61C5WXiXtmg/Arll6l7W2NLbqChgobSOkrl5SmGioGaCmpK6yi1F6qZRAx0Vcq/usy85IxJxEBhpX0lZe7F50wihiKgleUohoqB4AqCWYT2AXXk6wNXVGUgvY57fUCeuoKM9RlAqJNeH@D7IyUpxXRigKNOe6V2qT9mMtNMLAZgatVr1q5EHD3pZUwsBohq7dWDY98O5JgzsRhqzzwREGXZiunEAFtNbJmvU/v4JvKdihND4S3YNXHf34k7LFTaWl8Ldk3Sd3p60UAErJhODNg1ad/96qKVCFgzsRiwa1R/I/RFUxFwxsRiwK7R/pYM7lbuAedMLIbaM399@vvGilEH2DW8Y5mvU/t4A3aQgKNE4R3YGbBzw@J8dqi0s74O7Ezi4wf3UnnAiunEgJ0BOzdKht1GwJqJxYCdATs3XobdRsAZE4sBOwN2buQMu42AcyYWQ@1g52aRK1sxnRiwM2DHdNqXiPgW7CABR4nCN2DXgp0bUuezQ6Ub69uAXZv4@MF1Vh6wYjoxYNeCnRtXw24jYM3EYsCuBTs3uIbdRsAZE4sBuxbs3AgbdhsB50wshtrBzo01V7ZiOjFg14Id02lfIuI7sIMEHCWJdMDmxtr52Ki@S3zA4P4qTxSaOyByg2vYVOQIpR3AuHE1bCXSY33A4YbUsIHIDPo6QHBDypXDSiCdodq/egPVqIrXZwPBbha5W7JJ/LbBfUPeDRS68dIf/Rovtkvp5T2Cmg3UuLHRH@kacu2SHtyPNfRZb3ZO/jG/sp879uNi8e16u7vGZ0b4bh8Ffj9xbT3Hvuh632JPiL/x5d/E/922svdLsYpvVrE8kptVIo/I@tvgaRVNV/F0lazDLwXTh/KFNZ5/XF3JhkVY73fH/bO5fd7bb6D5x@d/)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~182~~ 170 bytes
Saved 12 bytes thanks to comment.
```
Module[{x,p,y,q,z,r,u,v,w},{x,p,y,q,z,r}=ToCharacterCode@a;x-=z;y-=z;p-=r;q-=r;u=x^2+p^2;v=y^2+q^2;w=(x*q-y*p)*2;FromCharacterCode@{⌊u*q-v* p⌋/w+z,⌊v*x-u*y⌋/w+r}]
```
[Try it online!](https://tio.run/##Vc5BCsIwEAXQvacQVxqnCFEqGAKC4E4QdFeqxDZVwdo0JG1S6QXUU3qRGnGh3Xw@j88wKVMnnjJ1jliTBGy/UfJ8PYYz2m1WWawvPLgZEGAhhwokaCigrOHfarrNFicmWaS4XGQxnzNiPFoR@wnhUUnyT2hqdngodpgU1LqWu1bSvkG5Z5EYIEyWMkvbl26v5127QYG64vV8jMphBY4KZDyN7FdkHTZr97QKkqAX@4l/HPfCsPOjSezzaYuicYIP2FHzBg)
A port of [@tsh's answer](https://codegolf.stackexchange.com/a/256856/110802).
Explicit Mathematica code
```
f[a_String] := Module[{x, p, y, q, z, r, u, v, w, char1, char2},
{x, p, y, q, z, r} = ToCharacterCode[a];
x -= z;
y -= z;
p -= r;
q -= r;
u = x*x + p*p;
v = y*y + q*q;
w = BitShiftLeft[x*q - y*p, 1];
char1 = FromCharacterCode[Quotient[(u*q - v*p), w] + z];
char2 = FromCharacterCode[Quotient[(v*x - u*y), w] + r];
StringJoin[char1, char2]
]
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 13 bytes
```
eᵐ{2R↕ᵐᶜ_+}≡H
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FttTH26dUG0U9KhtKpDxcNuceO3aR50LPZYUJyUXQ9UsuGkUrZRipqSjlAYi0o2VYrmAAiZANlg01RwskGwMUmEEJJKMlGIhWgE)
```
eᵐ{2R↕ᵐᶜ_+}≡H
e Char to codepoint
ᵐ{ } Map
2R↕ᵐᶜ_ Any of the 8 knight moves
+ Add
≡ Check if all equal
H Char from codepoint
```
The `2R↕ᵐᶜ_` part is taken from [my answer to the challenge *Generate All 8 Knight's Moves*](https://codegolf.stackexchange.com/a/260297/9288).
] |
[Question]
[
[Elixir](https://elixir-lang.org/) is a programming language with a feature called the [pipe operator](https://elixirschool.com/en/lessons/basics/pipe-operator/), `|>`, similar to the pipe in Bash and other languages. It passes the result of an expression on the left as the first parameter of a given function on the right.
To clarify, here are some examples.
```
2 |> myFunction()
```
is equivalent to
```
myFunction(2)
```
Here, the expression `2` is passed as the first parameter of the function `myFunction()`.
Now, consider how an expression with multiple pipes is evaluated. Multiple pipes are evaluated left to right, so all of these lines are equivalent:
```
other_function() |> new_function() |> baz() |> bar() |> foo()
new_function(other_function()) |> baz() |> bar() |> foo()
baz(new_function(other_function())) |> bar() |> foo()
bar(baz(new_function(other_function()))) |> foo()
foo(bar(baz(new_function(other_function()))))
```
Here, in each line the leftmost pipe is calculated, which takes the first expression and passes it to the second expression (which is a function).
## Challenge
Your challenge will be to write a program or function which, when given an Elixir expression with one or more pipes, will return or output an equivalent expression with no pipes. In real Elixir code the functions may have multiple parameters but to keep this challenge simpler, you may assume all functions will take only one parameter.
## Examples
```
Input -> Output
2 |> myFunction() -> myFunction(2)
otherfunction() |> newfunction() |> baz() |> bar() |> foo() -> foo(bar(baz(newfunction(otherfunction()))))
```
## Rules
* Function names will only contain ASCII letters and underscores, and end in `()`
* The leftmost expression will only contain alphanumeric ASCII, underscores, and parentheses
* You may assume there is no whitespace in the input (the examples here have spaces for readability)
* You may also assume there are spaces surrounding the pipe operators like in the examples, if you wish
* All functions only take one parameter
* Leading or trailing whitespace is allowed in output
* Whitespace around parentheses is allowed in output
* Any reasonable form of input/output is allowed
* No standard loopholes
* Shortest code in bytes for each language wins
[Answer]
# [J](http://jsoftware.com/), ~~23~~ 22 bytes
```
(];/:')'=;)&|._2{.\cut
```
[Try it online!](https://tio.run/##y/r/P81WT0Ej1lrfSl1T3dZaU61GL96oWi8mubTkf2pyRr5CmoK6kUKNnUJupVtpXnJJZn6ehqY6F0wqvyQjtSgNLgFSmJdajiqQlFgFYxRBGGn5@UBD/gMA)
```
cut split by space
_2{.\ only odds
|. reverse
;/:')'=; join and sort by equality with ')'
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ßN¶e╣╨j,
```
[Run and debug it](https://staxlang.xyz/#p=e14e1465b9d06a2c&i=2%7C%3EmyFunction%28%29%0Aotherfunction%28%29%7C%3Enewfunction%28%29%7C%3Ebaz%28%29%7C%3Ebar%28%29%7C%3Efoo%28%29&m=2)
## Explanation(unpacked)
```
.|>/kNas++
.|>/ split the string on "|>"
k reduce the list by:
N push the 2nd string with the last element popped, then push the last element
a put the previous iteration on top of the stack
s swap the bracket with the prev iteration
++ concatenate into one string
```
[Answer]
# Excel VBA (Immediate Window), ~~85~~ 75 bytes
*-10 bytes thanks to @TaylorScott*
```
For Each s In Split([A1],"|>"):o=IIf(o="",s,Left(s,len(s)-1)+o+")"):Next:?o
```
## Excel, ~~165~~ 154 bytes
*-11 bytes rethought the Excel based on changes to VBA*
```
=LET(x,FILTERXML("<a><b>"&SUBSTITUTE(A1,"|>","</b><b>")&"</b></a>","//b"),n,ROWS(x),a,n+1-SEQUENCE(n),CONCAT(INDEX(LEFT(x,LEN(x)-(a<n)),a),REPT(")",n-1)))
```
[Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnA8jZJRpmljaGOAa?e=sxyeGS)
```
=LET( 'define variables
return last parameter
"<a><b>"&SUBSTITUTE(A1,"|>","</b><b>")&"</b></a>" 'Convert piped string to XML
x,FILTERXML( ,"//b") 'x = XML converted to array
n,ROWS(x) 'n = # rows in x
a,n+1-SEQUENCE(n) 'a = n .. 1
CONCAT(INDEX(LEFT(x,LEN(x)-(a<n)),a),REPT(")",n-1)) 'final calculation
INDEX( ,a) 'x in reverse order
LEFT(x,LEN(x)-(a<n)) 'if not first element delete
rightmost char
REPT(")",n-1) 'n-1 ")"
CONCAT( ) 'concatenate everything
```
## Original
```
=LET(s,SUBSTITUTE(A7,")",""),x,FILTERXML("<a><b>"&SUBSTITUTE(s,"|>","</b><b>")&"</b></a>","//b"),n,ROWS(x),CONCAT(INDEX(x,n+1-SEQUENCE(n)),REPT(")",LEN(A7)-LEN(s))))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 9 bytes
```
Ḳm2ɓṪṭ;µ/
```
[Try it online!](https://tio.run/##y0rNyan8///hjk25RicnP9y56uHOtdaHtur/P9yuGfn/v1J@SUZqUVppXnJJZn6ehqZCjZ1CXmo5qkBSYhWMUQRhpOXna2gq6SgoGYF4uZVucPVKAA "Jelly – Try It Online")
-2 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!
The `|>` must be surrounded by spaces
## How it works
```
Ḳm2ɓṪṭ;µ/ - Main link. Takes a string S on the left
Ḳ - Split S on spaces
m2 - Take every second element, ignoring the "|>" elements
ɓ µ - Create a new dyadic chain f(a, b):
Ṫ - Remove the trailing ")" from a and yield it
; - Concatenate the modified a and b
ṭ - Tack the ")" to the end
/ - Reduce the split S by this. The ɓ in the chain tells
the quick to reduce from the left with arguments reversed
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~105~~ ~~98~~ ~~87~~ 78 bytes
```
I =INPUT
S I ARB . L '|>' ARB . F ')' REM . R =F L ')' R :S(S)
OUTPUT =I
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/n9NTwdbTLyA0hCsYyHQMclLQU/BRUK@xU4dy3BTUNdUVglx9gewgBVs3kCxIgNMqWCNYk4vTPzQEqBtoCJern8v//0Y1dk6OURqaICoIRLn5@2toAgA "SNOBOL4 (CSNOBOL4) – Try It Online")
Thanks to Razetime for -2 bytes.
### Explanation:
```
I =INPUT ;* read input, assign to I
S ;* label S
I [lhs] = [rhs] ;* replace the part of I matching the following pattern:
ARB . L '|>' ;* something followed by '|>' (assign to L)
ARB . F ')' ;* followed by something followed by a ')' (assign to F)
REM . R ;* and the rest of the string (assign to R)
;* with:
F L ')' R ;* F, L, ')', and R concatenated together
:S(S) ;* on SUCCESS (a match was found), goto S
OUTPUT =I ;* on FAILURE, proceed to output and end the program
END
```
[Answer]
# [Elixir](https://elixir-lang.org/), 64 bytes
```
&Macro.to_string Macro.expand Code.string_to_quoted!(&1),__ENV__
```
[Try it online!](https://tio.run/##VY29CsIwFIX3PsU1Q2mhBHTXRSo4qJuLSIjtjQ3Y3JomWMV3jy1Bwe07fxy86UHboGAZ0p2sLHFHondWmytEjUMnTQ1rqpHHQIyVuyeH9SxL53khRLk/ChFK41uOsmrgxBbwXkH73HhTOU0my1mRMHINWvWzporBx79xka8v2AiKaJyfiyTNtgfeedeD4tNxHj4 "Elixir – Try It Online")
Well, this looks a bit longish for a solution relying on built-in functionality, but I guess we need a "reference" implementation with Elixir doing it itself.
[Answer]
# [R](https://www.r-project.org/), ~~94~~ ~~92~~ 86 bytes
*Edit: -2 bytes thanks to Giuseppe*
```
function(s,t=el(strsplit(s,"[)]?(.>|$)")))Reduce(paste,c(rev(t),")"[+grepl("[(]",t)]))
```
[Try it online!](https://tio.run/##bY69CsJAEIT7PMZisYuHhX1i5wPYhkNi3Ggg3h17G//Iu5@RQFSwGr5ivhlJvQtt4Dw1vau19Q6j0Zw7jCoxdK2ODCXZDa6KYUFARDs@9jVjqKKyqVH4ikoGCMrlSTh0CCVaMEqWKPE9CMc4inPwembZz0M0FI5vP3yonlPIOxrvkSCbHuLHRFn2rV0PxeWxnS1/C@kF "R – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~30~~ ~~23~~ 22 bytes
```
+`^(.+?).>(.+?\()
$2$1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wXzshTkNP215Tzw5ExWhocqkYqRj@/29UY5db6Vaal1ySmZ8HFM0vyUgtSoPza@zyUsuRuUmJVRCqCESl5edraAIA "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved ~~7~~ 8 bytes thanks to @tsh. Explanation:
```
+`
```
Repeat until all pipes have been processed.
```
+`^(.+?).>(.+?\()
```
Match the first two terms up to the second term's opening bracket.
```
$2$1
```
Move the first term into the second term's argument.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 60 bytes
```
s=>s.match(/\w+\(?/g).reverse().join``+s.match(/\)/g).join``
```
[Try it online!](https://tio.run/##jZDBcsIgEIbvPsUeOgOMJnY8tkO8@QIea2dCcRNxEFIgWmt99pSIqbWnctmf/f/92GEr9sJLp5qQGbvGTlrjA3ir26CsAd55Xvh8J4Lc0OnqMF7R@bRmucM9Oo@U5VurTFmObxnW@6l7pUnh0QMHh@@tckhJ5UmPEOuF0rg8GkkfWR7sMjhl6sj0jVaBkpWJsZ1oqFYGgRfQ18HMiqspXN17sURko4XEuISf1hMghDH2PKqsA5o2eVGmacME8KNBGXD9CrZK6zE4jQBSyqFvdYgLD99AL2MRlRJWY65tTcuHU4qegQ4SOOc/eJgDkda5eCHwBOTgrKnJmZURde5m8FXA7rhojbw8wuD/J7ubnLGRDRt01Q0V0QYP94038TkIl0RlbRRZEn23j/ye@4PtT/cN "JavaScript (Node.js) – Try It Online")
This would fail if there were no pipes (not possible according to challenge rules) but here's an alternative version which can also handle that:
## [JavaScript (Node.js)](https://nodejs.org), 61 bytes
```
s=>(f=a=>a[1]?a.pop().slice(0,-1)+f(a)+')':a[0])(s.split`|>`)
```
[Try it online!](https://tio.run/##jZDPcsIgEMbvPsUeOgM7NfHP0Q7x5gt4VGdCkaR0ECiQWqs@e0qMtrWnctmP3W9/fMMrf@dBeOViZuxWtsKaECFY3URlDbA2sIJWjLOCryabOc@ddRTzoJWQdDzMJvhYUY6PBMmMr8YbpCEPTqtYnooSrzjBgwzAwMu3RnlJSRUI5l7y7UJpuTwYQceYR7uMXpm6w3cEStYm2XbcUa2MBFZAV2/DrLgOua@7WSoJ6TRPwUbrMKqHQAgiPg0q64H2SVbKuCYOQX44KaLcbsBWfTyE4wCgd3kZGh1T4Ns/0MtaQvUOq2WubU3Lh2NvPQO9SWCMfeNhDkRY79OFwAzI3ltTkzOWCXVup3AqYHdYNEZcHkH4/8nuNqc4sPFF@uoHldBG7u8bz/zzJnwvKmuTyHrRdTvL770/2O60Xw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
≔⪪S|>θ⭆⮌θ…ι⊖Lι⭆θ✂ι±¹
```
[Try it online!](https://tio.run/##ZYzBCsIwDIbvPsXYKYV58CwMZF4EFXFPUGvWFmraddlE2bvXzV0E/8vHny@JMjIqL11Ku66zmqAOzjIcKPRcc7SkQRRZPpb5hFZsV5dpxrCokwxwxQFjh9BOvnoph5XxAWyR7VFFfCAx3uGIpNmAFXP@f7RFVjurcD47o5aMsPlupuTZYGx6Umw9gRhLwudvvcn3gjij8R5EWg/uAw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪪S|>θ
```
Split the input on `|>`.
```
⭆⮌θ…ι⊖Lι
```
Print the strings in reverse order without their last character.
```
⭆θ✂ι±¹
```
Print the last characters of the strings. This means that the first term gets reunited, while the remaining terms have their brackets moved to the end.
[Answer]
# [Python 2](https://docs.python.org/2/), 54 bytes
```
lambda s:reduce(lambda r,x:x[:-1]+r+')',s.split('|>'))
```
[Try it online!](https://tio.run/##TcnRCsIgFIDh@55idx7ZCrbuhLzsJSrCbcoEp3JUtoXvbkURXf18/H6Lk7NdUadrMWLuR1EFhnJMg4SvsVnZemH79lZjTShpwiF4oyOQzAmlZZm0kVXLPGobQQGK5a6tTxHo63bHzOftnOwQtbNAdy5OEtXPmVu5/LMXj0/wHeUc0Cc "Python 2 – Try It Online")
For each function going to left to right, insert the string `r` we have so far between the parens of the function `x`.
```
string |> new_function() = new_function(string)
```
This is done by removing the last character (a close paren), appending the string, then adding back the close paren. Because `reduce` starts the accumulator at the first element by default, we don't need any special handling if it's not a function.
This is longer in Python 3, which lacks `reduce` but can use a starred assignment to extract the initial value.
**Python 3, 59 bytes**
```
r,*l=input().split('|>')
for x in l:r=x[:-1]+r+')'
print(r)
```
[Try it online!](https://tio.run/##TcvBCgIhFEDRvV8hbvQ1FUztBsZlPxEtalAU7Ckvh3HCf7ciiFaXs7hpzS7isS3OB8P7wRQzKSFEo@0mjB7TnBXsHyn4rGTVEpiNxAv3yMNAYzkPu/7SUSdBskQesyJo7x/aoer7eppxyj6iAhazM2R/rhrN8s/b9fkNfWJjVPAC "Python 3 – Try It Online")
Alternatively:
**Python 3, 59 bytes**
```
r=''
for x in input().split('|>'):r=x[:-1]+r+x[-1]
print(r)
```
[Try it online!](https://tio.run/##TctBCsMgEIXhvacQN46EFtLuhGTZS4Qu2qAopKNMDTHFu1tLoRQefPyLF/fkAp7r5vxieK9NNjMIISoNUjIbiGfusS2uCdTxGRefQJZRKk1DnvShv3bU5anJInlMQKq2v6qnMj72y4pz8gFBsZCcIfvrMqLZ/vN@e32hDzYEUG8 "Python 3 – Try It Online")
[Answer]
# [Zsh](https://www.zsh.org/), 41 bytes
```
for a (${(s:|>:)1})x=${a//\()/($x)}
<<<$x
```
[Try it online!](https://tio.run/##qyrO@F@ekZmTqlCUmpiioFukYGidkq@g8T8tv0ghUUFDpVqj2KrGzkrTsFazwlalOlFfP0ZDU19DpUKzlsvGxkal4r8mUENe6n8jhRo7hdxKt9K85JLM/DwNTa78kozUojQ4HySfl1qOKpCUWAVjFEEYafn5QL0A "Zsh – Try It Online")
* `${1}` - take the input
* `(s:|>:)` - split on `|>`
* `for a ()` - for each element:
+ `${a}` - take the element
+ `///` - replace:
- `\()` - empty parentheses
- `($x)` - with the current value of `$x`, in more parentheses
+ `x=` and assign that to `$x` (it starts as an empty string by default)
* `<<<$x` - print `$x`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Port of [FrownyFrog](https://codegolf.stackexchange.com/users/74681/frownyfrog)'s clever [J answer](https://codegolf.stackexchange.com/a/222594/53748)!
```
Ḳm2ṚF=Þ”)
```
A monadic Link accepting and yielding a list of characters (with the `|>` surrounded by a space on each side like the examples).
**[Try it online!](https://tio.run/##y0rNyan8///hjk25Rg93znKzPTzvUcNczf///@eXZKQWpZXmJZdk5udpaCrU2CnkpZajCiQlVsEYRRBGWn6@hiYA "Jelly – Try It Online")**
### How?
```
Ḳm2ṚF=Þ”) - Link: list of characters, S
Ḳ - split at spaces
m2 - modulo-2 slice [1st, 3rd, 5th, ...]
Ṛ - reverse
F - flatten
Þ - sort by:
= ”) - equals ')'?
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 90 bytes
```
f(s,l,t)char*s;{for(t=0;--l&&s[l-1]-62;t++);s=printf("%.*s",t+!l,s+l)-t||f(")",f(s,l-2));}
```
[Try it online!](https://tio.run/##TU/LbsMgEDyXr3CRGrEG@vChF@oc@xOWDy6CBIlABBtVje1vd3HcVj3NzuzuaEbLg9bLYlkWXiDo45DqrEYbE8P2WUnpd7vcefnSy9dGIeegcntOLqBl9OGxzlQgv/cicw8Sp6moQMXNTjYAal5OgwsMRrJaVzXqrm9HQptpf/p6vwSNLpY1FYRGPJpk/6RpH8znf/oxXDdIK9gYtzc0GX@xKGRWpKSvWIlYuVLBvWV3NdEy1PD0M95qgnKci/MFM6MUgNytJ53rRcbkTdhIqUDm5Rs "C (gcc) – Try It Online")
Expects no spacing.
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 11 bytes
```
òf|xxd0f(pò
```
[Try it online!](https://tio.run/##K/v///CmtJqKihSDNI2Cw5v@/88vyUgtik8rzUsuyczP09BUqLFTyEstRxNJSqyCMYogjLT8fA1NAA "V (vim) – Try It Online")
ò…ò repeats the commands until the first error, the rest are normal Vim commands.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
```
„|>¡Å»¨ì')«}θ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcO8GrtDCw@3Htp9aMXhNeqah1bXntvx/39@SUZqUVppXnJJZn6ehmaNXV5qOTI3KbEKQhWBqLT8fA1NAA "05AB1E – Try It Online") The annoying thing here is `.»` only reduces by the first command after it, not a `}` or `]`-terminated function. And macros don't exist, so… ¯\\_(ツ)\_/¯
```
„|>¡Å»¨ì')«}θ # full program
θ # last element of...
Å» # cumulatively reduced...
# implicit input...
¡ # split by...
„|> # literal...
» # to the right by...
') # literal...
« # concatenated to...
¨ # all characters of...
# (implicit) second element in current reduction step...
¨ # excluding the last...
ì # prepended to...
# (implicit) first element in current reduction step
} # end cumulative reduce
# implicit output
```
`')` can also be `Iθ`, `sθ`, or `¹θ`, `}` can also be `]`, and `θ` (only the one at the end) can be `¤` with no change in functionality.
[Answer]
# Java, ~~103~~ ~~84~~ ~~80~~ 77 bytes
```
s->{var p="";for(var c:s.split("\\|>"))p=c.replace("()","("+p+")");return p;}
```
*Saved 19 bytes thanks to [79037662](https://codegolf.stackexchange.com/users/89930).*
*Saved 4 bytes thanks to [pxeger](https://codegolf.stackexchange.com/users/97857).*
[Try it online!](https://tio.run/##jU@xTsMwFNzzFZYnm1IPjIRkZEMMFRNlcF27dXBs6/klKKT59uDQUnXkltPp7t7pNbKX62b/Ods2BkDSZC06tE6Yziu0wYu7sojdzllFlJMpkRdpPRlJQTIuRkKJmfpg96TNNtsgWH94/yASDomPv9kFb17C8Bo1SAzwdE7VxFRzWtdjL4HEitLSBGCLUI9JpOgsMrrdnmrKeayUAB2dVJpRxuk9ZXQVV5RTXoLGDjyJ5TT/zZXX4c2QULcidChiHkXnmREyRjcw@nCq2@H58m4@yvn/egGPGsy1d6q9/rqVO/l9JljIhHBzeyqm@Qc)
A positive lookahead can be used for a solution of the same length.
```
s->{var p="";for(var c:s.split("\\|>"))p=c.replaceAll("(?=\\))",p);return p;}
```
[Try it online!](https://tio.run/##jU@xTsMwFNzzFZYnG1EPjIQEsbAhhoqJMLip3To4tvX8EhSSfHtwaKk6csvpdHfv9BrZy02z/1xMGzwgaZIWHRordOdqNN6JmzwL3c6amtRWxkhepHFkJBlJOBsRJSbqvdmTNtlsi2Dc4f2DSDhEPv5mV7w5CcNrUCDRw8MpVRJdLHFTjr0EEgpKc@2BraK@jyIGa5DRqppKynkoagEqWFmrJ2sZZY9FVXFObwPPQWEHjoR8Xv7m8svwdoioWuE7FCGNonVMCxmCHRi9m8p2eD6/y3ia@V/P41GBvvSm0qmva7mT3yeClbT3V7fnbF5@AA)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 49 bytes
```
f=a=>a.replace(/(.*).>(.*)./,(_,x,y)=>y+f(x)+')')
```
[Try it online!](https://tio.run/##XYxBDsIgEEX3XoQZizRxD0uvYUYErUGmoVSL6d1Ra2KMm//yk5d3oRsNNnV93kQ@ulq9Jm1IJdcHsg5aUGtUZtlWwl5OsqA2pfEwYSNQYLUcBw5OBT6BB7GdzbXsxmhzxxFeAq7@DM5nl/zXmE109997oMcH6Q3PvFTqEw "JavaScript (Node.js) – Try It Online")
Only works if no extra spaces are there.
---
# [JavaScript (Node.js)](https://nodejs.org), 50 bytes
```
a=>a.split`|>`.reduce((p,q)=>q.replace('(','('+p))
```
[Try it online!](https://tio.run/##XYxBDsIgFET3XoT/Y2XhHpaeo0hBMcinQGs03B1RE2NcTF5m8jIXtaqsk4tlF2gyzYqmhFQ8R@/KWOXIk5kWbQDiMKOQc@/Rqz4wYEPPNiI2TSGTN9zTCSywfZXX@2EJujgKgAxx82dQOZtkv0aVwdx@61E9PkgvWKL3S3sC "JavaScript (Node.js) – Try It Online")
This works if the input does not contais `"$"` character. Otherwise, `'('+` need to be replaced by `x=>x+` with +1 byte cost.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 81 bytes
```
-join($t=$args|% Sp* "|>"|% *m ')')[($l=$t.Count)..0]+")"*($l-!($t[0]|% e*h '('))
```
[Try it online!](https://tio.run/##TYtBDoIwFET3nKI21fbXQIx72Jh4AZeEBZJWMNBPSglR69lrDYlxNTMv80ZclJ1a1fdpg1YFpvNXSO/YGcFczmp7m/yWXEZJqC9orHIgHDiUgvU5c9kJZ@Mgyw7VngKVkaabaJaHKn6VbAkXHCC8k2THNKFHXwyP82wa16ERQFeKrlVW/6gvjFr@57V@rmG/oRGjGT4 "PowerShell Core – Try It Online")
Thanks to @Julian!
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 108 bytes
```
param($s)$n=$s.split("|>");$k=(($n|%{$n[--$q]})|%{$_-replace"\)$"})-join"";$k+")"*($k-replace"[^\(]").length
```
[Try it online!](https://tio.run/##TcrxCoIwEIDxdzkuvCvmC4S@iFksmWmu29oMofTZVxJEf3384PNuMiF2xtqUvA76RhgZpcCYR2/7kWAugfc4FEQo8@aFUimF93rhFScVjLe6MXBghIXV1fUC8Pl3wLAlHH5DdTxQDZxbI5exSyllbuxMaB/SjL0T4rkUM/3zrJ/fhDWtc8TZGw "PowerShell – Try It Online")
* Take a string
* Split it by `|>`
* Save ^ to an array
* Reverse the array
* Loop on each element
* Remove trailing `)`
* Join array
* Append number of `(` in the joined string amount `)`
* Print and bye bye!
[Answer]
# [Red](http://www.red-lang.org), 85 bytes
```
func[s][t: take s: split s"|>"forall s[t: rejoin[replace s/1"()"""mold to-paren t]]t]
```
[Try it online!](https://tio.run/##TY2xDsIwDER3vsLy1A4IwdihIx/AGmUIrSMCaRw5RgjUfw@tkCqm0@ne3QmN9UKjsTvfQfXPNJhijXag7kFQOig5BoWCc4@excUIZY2F7hySEcrRDQt4OGLTIuLEcQTlfXZCCdRatTVLSAoekPVGsn5o4NS0c5/o9W@v7vMTWcUzL5O7rX2a@@l93nCsXw "Red – Try It Online")
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~67~~ ~~57~~ ~~45~~ 44 bytes
```
$args-split'.>'|%{$r=$_|% rep* '(' "($r"}
$r
```
[Try it online!](https://tio.run/##XU1NT4NAEL3vr5g0g7sY8NA7pImJV409GtO062BrKIuzS6qy/HZkoVbSd3mZ9zW1ORHbPZVlqg1Tj0XW9rjld5vaujw4eZdLH7XIGW58BEz1LUglYaGQF51A7jshVkqIRMmlz4/fD02l3cFUKpYJyNm9jGUcUsbtiYtLyucVnebnbvszEQcqjAlLMnCQgjsvXK0FDG9EDB4iaAUMQPqqORmJtKM3yAA3k8Nkm9INwg0WU27UX57W94115vi4@xgqr6tpKGDdaE3Who1zOaXP/@1L7vlv@RwbjU50/S8 "PowerShell Core – Try It Online")
The `rep*` is the shortcut for the `replace` method.
[Answer]
# [Python 3](https://docs.python.org/3/), 84 79 bytes
```
import re;r=re.findall;i=input()
print(''.join(r('[\w(]+',i)[::-1]+r('\)*',i)))
```
[Try it online!](https://tio.run/##VcjBCsIwDADQu1/RWxOnA/G2MX9kGzK1ZZGZlJAxFP@9KuLB2@Olu43C@5zplkTNaai10VBG4sswTTU1xGk2wFVSYgPvy6sQg4JvuwX6wm8I26ra7vrifR2uP4GYs9gY9BhnPhsJA7rnwXFY/uM0PH7QL6II4As "Python 3 – Try It Online")
* Seems to be a complete solution: works whether there are spaces around the functions/constants/pipes or not, works whether first position contains constant or function.
* Doesn't technically look for pipes, so you could replace |> with |< and it would return the same output. Could add a positive lookforward to the regex but that would eat another ~10 bytes and the contest didn't specify.
* Pays a 27-byte 22-byte penalty just for importing one regex method. Thanks Python.
* Edited for small improvement.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~15~~ 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
q"|>" rÏiXJÉ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cSJ8PiIgcs9pWErJ&input=WyJvdGhlcmZ1bmN0aW9uKCkgfD4gbmV3ZnVuY3Rpb24oKSB8PiBiYXooKSB8PiBiYXIoKSB8PiBmb28oKSIsIjIgfD4gbXlGdW5jdGlvbigpIl0KLW0tUQo)
* saved 3 by assuming no whitespaces as suggested by OP @79037662
```
q"|>" - split on pipe
r - reduce by
ÏiXJÉ - inserting before )
```
[Answer]
# [Python 3](https://docs.python.org/3/), 70 bytes
```
*a,b=input().split("|>")[::-1]
print(*[f[:-1]for f in a],b,")"*len(a))
```
The program first `split`s the `input` into a list using the pipe operator, `"|>"`, as the separator. Using multiple assignment, `b` is set equal to the last element of the list (previously the first element prior to being reversed). `b` contains a string of the first element in the pipe, which may or may not be a function. The rest of the list is assigned to `a`. All of the elements of `a` are strings of functions. Next, the program outputs all the elements of `a` with `)` removed from each, `b`, and `")"*len(a)`.
[Try it online!](https://tio.run/##TcfBCsMgDADQ@75CPCXiCmO3wvoj0oMWQ4WSiEsZG/13R9llp8erb12F77276NOjcN0VcHjWrSjYY7IYxvF6my@1FVZwgcJZkmbIFDZx9slbtG7LDBGxd9E1N9p50SIMeEycX/9N8fOjnZAI4Bc "Python 3 – Try It Online")
If we're allowed to require that only the first item in the pipe has a space after it, but none of others, we can save **1 byte**.
# 69 bytes
```
a=input().split("|>")[::-1]
print(*[f[:-1]for f in a],")"*(len(a)-1))
```
[Try it online!](https://tio.run/##RcfBCsIwDADQu19RekqGE4a3gf2RskPVBQMlKTVDlP57ZXjw9HjlbQ@Vc@/pwlI2Azw9S2YD34LHOM/jtBxKZTEYIsW9pNWRY3FpOXr0A@RVIOE4Ifau@U6b3IxVAF0Lsr7@b@GaPj/qDqkCfgE "Python 3 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
```
.UXtlZZbcQ"|>
```
[Test suite](http://pythtemp.herokuapp.com/?code=.UXtlZZbcQ%22%7C%3E&test_suite=1&test_suite_input=%222%7C%3EmyFunction%28%29%22%0A%22other_function%28%29%7C%3Enew_function%28%29%7C%3Ebaz%28%29%7C%3Ebar%28%29%7C%3Efoo%28%29%22&debug=0)
---
Explanation:
```
.U cQ"|> | Reduce the input split at "|>" on the following lambda, where b is the current value and Z is the next item:
XtlZZb | Insert b into Z at index len(Z)-1
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes
```
#//.{a__,"|",_,b__,"(",c___}:>{b,"(",a,c}&
```
[Try it online!](https://tio.run/##TY3BCsIwEETv@YwNlArRgkfRUBA8Cx5Flm1IaA9NII2Ipumvx1ZBPL15A8P0FFrdU@gUZXPIvKo2kRAFjCBQNEsqQShETDsZm4@RUKnIZ9/ZcOVrCbCXpj625EkF7Yea34rposhOkcF2lP3zdLcqdM6WKxAM3Pzoza8apdWPf23o9YVfYJybZyzlNw "Wolfram Language (Mathematica) – Try It Online")
Takes and returns a list of characters. Requires no spacing.
[Answer]
# [Twue](https://github.com/ConorOBrien-Foxx/Twue/), 123 bytes
```
@::>*
^()::=()!
^_ ::=_ !
^_::=_^
!()::=!
!_::=_!
$!::=$;
|> $;::= $#(;%
##_::~_
$#::= $##
$::=$
_$::=$#_
%::~)
::=
^ @$
```
[Try it on the website!](https://conorobrien-foxx.github.io/Twue/?code=%40%3A%3A%3E*%0A%5E()%3A%3A%3D()!%0A%5E_%20%3A%3A%3D_%20!%0A%5E_%3A%3A%3D_%5E%0A!()%3A%3A%3D!%0A!_%3A%3A%3D_!%0A%24!%3A%3A%3D%24%3B%0A%20%7C%3E%20%24%3B%3A%3A%3D%20%24%23(%3B%25%0A%23%23_%3A%3A%7E_%0A%20%24%23%3A%3A%3D%20%24%23%23%0A%20%24%3A%3A%3D%24%0A_%24%3A%3A%3D%24%23_%0A%25%3A%3A%7E)%0A%3A%3A%3D%0A%5E%20%40%24,input=1337%20%7C%3E%20a()%20%7C%3E%20b())
[](https://i.stack.imgur.com/WMIMz.gif)
---
Twue is a spiritual successor to [Thue](https://esolangs.org/wiki/Thue) I made. I initially tried answering this challenge in Thue, and had to manually describe moving each character one byte to the left, individually, so the byte count came out to ~1kb. Then, I realize I didn't properly handle constants and abandoned the code, not wanting to rewrite that mess from scratch. Enter Twue, which allows wildcards to be used (`_`) to refer to generic characters. Furthermore, it removes the random rule selection from the language, and creates a better standard for input/output.
The language is still a bit of a work in progress, but most of the bugs have been ironed out, and most of the spec has been implemented.
## Explanation
```
@::>*
```
This replaces all `@` in the workspace with a line of input. Basically: readline. For an input of `1234 |> foo() |> bar()`, this populates the workspace with:
```
^ 1234 |> foo() |> bar()$
```
`^` and `$` are characters we'll be using as pointers, of sorts, for iterating forward and backward through the code.
```
^()::=()!
^_ ::=_ !
^_::=_^
```
This section moves the `^` pointer after the first expression, which may or may not contain parentheses. We want to preserve these. This inserts `!` after the first expression, and we are ready to parse.
```
!()::=!
!_::=_!
$!::=$;!
```
Now, for every expression afterwards, we want to strip the `()` from it. So, we move `!` character by character through the input, removing `()` in front of it as we go. After these steps, the input will look like this:
```
1234 |> foo |> bar$;!
```
Now we are ready for the second stage of parsing. We will use `!` later in the final stages of printing. Now, we have two pointers, `$` and `;`, which will define the range we're operating on.
```
|> $;::= $#(;%
##_::~_
$#::= $##
$::=$
_$::=$#_
```
`_$::=$#_` simply moves every character in front of a `$` after it, prepending a `#` to it. This signifies we want to print that character. We repeat this until the `$` pointer is at the leftmost part of the word, after a space. Since we are at the beginning of the word, we start printing the characters after `$#`, by first duplicating the `#`, and printing the character after `#__`. This allows us to only print when we want to—if we didn't duplicate, we'd print the strings in reverse, or lose track of the `$` pointer. If we find the string `|> $;`, we've printed all the characters we could, and we still have more things to parse. We remove the `|>` and append a `%`, signifying we need to print a corresponding closing parenthesis.
These replacements repeat until they can't anymore.
```
%::~)
```
If there are no other substitutions we can possibly make, we simply take each `%` and output a corresponding `)`.
] |
[Question]
[
Given a \$2\times N\$ maze, determine if you can get from the start top left corner to end bottom right corner using only up, down, left, and right moves.
## Input
A \$2\times N\$ block (\$1 \le N \le 100\$) of your choice of two distinct characters, one representing walls and the other representing empty tiles that can be moved through. You may use any reasonable input format, ex. one string with newline, two strings, or two lists of characters, or a binary matrix.
It is guaranteed the start and end positions are empty tiles.
## Output
Truthy or Falsey value indicating if the maze is solvable.
## Examples
In these test cases, `x` represents wall and `.` represents empty tile.
### True cases
```
.
.
```
```
..
x.
```
```
.x
..
```
```
...
...
```
```
..x
x..
```
```
....
..x.
```
```
.x...x...
...x...x.
```
```
...xx.....x
xx.....xx..
```
### False cases
```
.x
x.
```
```
.x.
.x.
```
```
.xx
xx.
```
```
.xxx.
..x..
```
```
..x.
xxx.
```
```
.xx.x..
..xx...
```
```
.....x.x.
xxx.x....
```
```
....xx.xxx
.....xxx..
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 8 [bytes](https://github.com/abrudz/SBCS)
```
∧/⍲⌿2∨/⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9DUgs13/Uu@lRz36jRx0r9B/1TQWJ/@dUDykqTVVITixOLVbn4kzjetS7ykDBAMxqm6gBZGpqGAIJhIChJlgUSQVIDYRCFjQEa0RXCVOLZiZECkZDjUMWRjPFEC4HtwpFQAFqNRenultiTjGKB2G@wHCCpgamu2BGowrCVBsoYHrREBJk2HTBlGugeAE9gKDKkM1BeA5DMUzeEBoxSMJQt1U/6p1X@6h3cbUBkFzDpVfBVaEHJGEYyIXQIBIoBCG5KqCiMBEgBaL1QJJQaZAQRAzEARoEkQYpBQA "APL (Dyalog Unicode) – Try It Online")
Takes input from stdin as a 2-row boolean matrix, where 1 is a wall and 0 is a space. Prints 1 for true, 0 for false (which are the only truthy/falsy values in APL).
### How it works
Given a maze (1=wall, 0=space)
```
0 0 1 0 0 0 1
1 0 0 1 1 0 0
```
Think of putting a bar between every two horizontally adjacent cells, where at least one side must be a wall (1):
```
0 0 | 1 | 0 0 0 | 1
1 | 0 0 | 1 | 1 | 0 0
^
```
Then the maze has a solution if and only if no two bars align vertically, as pointed above.
```
∧/⍲⌿2∨/⎕
⎕ ⍝ Take input from stdin
2∨/ ⍝ Compute the "bars" in the above diagram,
⍝ by ORing every two horizontally adjacent bits
⍲⌿ ⍝ Compute NAND of the two bars vertically;
⍝ each column is passable unless both rows are 1
∧/ ⍝ Reduce by AND; check if all columns are passable
```
[Answer]
# [Python 2](https://docs.python.org/2/), 26 bytes
```
lambda m,n:m&(n/2|n|2*n)<1
```
[Try it online!](https://tio.run/##VU7bbsMgDH3nK/y0wBQxNY/V@JNKFUkTNVNxIkJUT8q/Z4bAqgoZn4t9YP4N9wmbfTCX/WFde7Pgajy7D4lfzYZb84nq@7Tf@gHCdMXVyUWdBfg@rB5hxCCrSv9MI8oleBl5Z0xFlVIwTB46HoFF1Y0S4nkfHz2ceNsab5/XEec1SCWgfacOTHnLMsUXbZnOnh@BQfIv1a4FHy2Ib4pA/xexmHAi0dc6lcidDhRhms4gbdGRWCq5sdMRliMpq0Up6dHMNumiRUKU7Tj6Bw "Python 2 – Try It Online")
Takes inputs as numbers representing bit sequences, which the challenge author okayed. Though I realized this representation is kind-of suspect because leading zeroes are ambiguous.
The idea is to check whether any 1 in the top number (x symbol in the top line) corresponds to a 1 in any of the three adjacent positions in the below number. We do this by "smearing" each bit the bottom number `n` in three positions as `n/2|n|2*n`, or-ing the number with its left and right shift.
It would also work to do `(m|m*2)&(n|n*2)<1`, but precedence means more parens are needed.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~29~~ 28 bytes
```
->t,b{"#{t+2*b}"!~/45|54|6/}
```
[Try it online!](https://tio.run/##RU/RDoIwDHzfV@B8mCKWSMA3/RFCDBiNJBIJzqRmm78@t7Hqw9Lr9e7aTa/uba8Huz3KrFN8qeSmSDvDF5@8rHRV6n1ubJ0wDgx45gownAEyiIwbEUQ3JdbTpAUIj8WKpEHfBVsEZMffGmciGGQR4hxPe91Z/5nnWQynYwBJFDYR7Xv0XwnY57EGLu35pvSgx@RapwM8x3svYWhHpXvdg5xWAlBkYleINcjHqTeNsV8 "Ruby – Try It Online")
Takes input as two integers, `t` and `b`, each representing a row of the maze, with digits `1` representing empty tiles and `2` representing walls. Returns `false` if `t+2*b` contains the digits `45` or `54` (two walls touch diagonally) or `6` (two walls touch vertically). Returns `true` otherwise.
It's possible to get down to 22 bytes by porting [@xnor's very elegant Python 2 answer](https://codegolf.stackexchange.com/a/206962/92901):
[Try it online!](https://tio.run/##RU/RDoIwDHzvVxAeHBCswjP6I4QYZiQukUhwJjWMb5/bWPVh6fV6d@3mt/zY4WT3Z13KRe8yeaiNNHUh86ZabZtAioBp6QoCbYAAI@NGDMlNmfU0axHDg1iJNeS7YIuA7fRb40wMgyxC2uJ5rzvrP/M8xHA@BolFYRPTvif/lYB9HnR466/3xYxmSoa2GPE1PZTGsZ8Wo4xCPWcCSZTiWIkc9fOisjpfu9V@AQ "Ruby – Try It Online")
[Answer]
# Regex ([POSIX ERE](https://en.wikibooks.org/wiki/Regular_Expressions/POSIX-Extended_Regular_Expressions) / [RE2](https://en.wikipedia.org/wiki/RE2_(software)) or better), ~~13~~ 10 bytes
```
x(|
|.
.)x
```
[Try it online!](https://tio.run/##jVTdbtowFL7PU5yCVGygEaHSLqB06g/bLrpOaqnUiSGUJQasBSdyEuF25XYPsEfci7BjO9CEbt0iJbbP@c453/lsJ0iSoyDyxXxT5yKI8pDBSZqFPHYXp86zicdpJpm/LNskmzNVhSGIi/mfbKdOsPAlTJPxBAZwUztfrb59Pc4/PzzcjxZvVguyUeTJeXIdl6oN3ffW2tBMBtOk5fUdLjJY@lwQ6nx3AB/DY5rZ8SJeJjxiYd@4kjFWj5ggCT3yJoOOtfIZEAQHCCWHlag2JG24Gb6fDu9Hw@vL4SU8meX1p9u7c0pNtC2qn1mSZympXcR5FIKIMwhsGs0kj7BbphLJ0pTHwsUOUFYmJe3v4iXLcinAs5a1HRDV61nNgAus4LXt2LX@WSyBaA0esR2LnrMs4oIRswi4KAI82keQR0uMdeePFNCpd4M0vohGic9sJXnGiA12gymyIHSbzE35I9NLz3QS51kpUue1sHFnAoeHsFscDBr1RpnCFn7wGvUuxZBC3qGUsezBLQtiEYJGw5KjqGJe0vRZy3W1EgqF@49HrtJF/wUdW7Zww8FAR73gcIXFUwhj0dBHEDXErBo4zxb/waWqekXt7p7a3VfV1o@5TU0Zr1LsjehVky79KIoDgoSax9ACby9kd3K4Pjn8BHE4tFr7u2OOJiYec5OmM9mq1x3zSf81qLeDev@CdjVUK1FFVRUzeNOORXf20HZ3zA1mwYurrKPb0GnD9d3VFU7owcDe5Y9no4sP8BZq8OvHT3jnRymrQa9YjmTOan8RfSYZIzptyW4Zr53ShcbfzHpTN5kg8FOWOg7@1/DjOkoPSs/wdc2LH4V2a9Emi3Fd8zrFqKxf6bkJKCYmsG6b2BVTRR3XKZIZvJkoW8GWRT5bu7EV@S0TV20BppQ16pVShX9b/CwMeYY/OT8q8bA9mCq/AQ "C++ (clang) – Try It Online") - POSIX ERE
[Try it on regex101](https://regex101.com/r/2wI6jW/8) - RE2
[Try it online!](https://tio.run/##VVDNThsxEL77KaaKhD0QhiAhDkSm4gAP0PaW7sHZmGC6613ZDjg0vfYB@oh9kWB7d1F7mL9vZr5v7Gf1onztTB/OfW822rWd/aH3RyetfoUvensfeyHe5O3F6TGKAzsQI4zH04s3pNB9Dc7YrUDyjam1uJ6fXyGyx86BMHKxBKFAgtNq0xirBSJ8kmB3TbMEIy/xJ5iTkz4xBIFL6HfBBycUMgDzmFap0XYbnqRcwOEAiuon5e6CWKCUfMYR6s4GY3c6za//k/ng4t8tP1tnwjYNiORuoV0tKmpVelSc77EgpXTday5SWO0rJKdftPOJjJ47YwXniChWKyJS1TyHdVVNvaSSNSZR@Pv7D3A4A@EoaB9Ei/AZ@INqvOZwA/yb2@nEx34dZ5BzqJXXnrH0tckRiznEnCWjYsnFhA9IhoYZomJsjHHox5yXhTEpizMoF3yIxVGH2EhW5ksSB4VBNt0z4QUb@YdLKE4DRWoAcxXj2J/E7zYbE0xnVfPPHcMbiso7 "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript
[Try it online!](https://tio.run/##bVBBboMwELz7FStjCRDFotcgpFSVeuuttyhSUeIES8akhihWEq59QJ/Yj9C1TdIeerC9Ozs7M3DoTsL0jVBqYqZaGbEXdr1YaHFKlvFkkyu5csJTO8XLB/rctQepxJamJTtXRbnrjKg3TcIUSA1M6sNxSC8EQO4Sdk4vJyMHkTddP4zIfyzhF4Bcd2iipBbAlF8B1MnFB1AKeWcQXRVr30c0Bac6glC9CMQid4v6qFSYAbC2orQEzIRzjelwnKsBdQquhN4PjUOyDPmshaxyBkyvM5z7l75rOpaODlVQ9rL/R6bw/fkFLPFhDH@th00j@oS1KcrHLzXmjENcbN/MEbuU3j8BEwQXNY5TBG4Om7oXPSH4s/HixLrHugoP9wcvi3hAHBQ4nPtD5teGuXW1X5gLvxiBj3Y3s7MPJ7OY5/vCBodgi3luuMdm/ZCE2xvBWwXQddbO85v503YrB9npWv3JEb7Bu/wA "PowerShell – Try It Online") - .NET
The problem statement didn't say anywhere that there specifically had to be \$2\$ rows and \$N\$ columns rather than \$2\$ columns and \$N\$ rows, or that the input can't be taken in transposed form.
So here is a solution that works on virtually any regex engine. Like [A username's answer](https://codegolf.stackexchange.com/a/223020/17216), this matches iff the maze is ***not* solvable**. The wall character is `x`, and empty tiles can be represented by any other character.
# Regex ([POSIX ERE](https://en.wikibooks.org/wiki/Regular_Expressions/POSIX-Extended_Regular_Expressions) / [RE2](https://en.wikipedia.org/wiki/RE2_(software)) or better), ~~33~~ ~~30~~ 27 bytes
```
^((''
|^)(('.
)*|(.'
)*))*$
```
[Try it online!](https://tio.run/##jVTdbtowFL7PUxxgamygEaHSLqBp1R@2XXSd1FKpE6UoSwxYC0nkJCLtyu0eYI@4F2HHdqAJ7boFhWMff9853zm248Xxvhe44Wzd4KEXZD6DwyT1eWTNj4xnF4@SVDB3UfYJNmN5FYYgHs5e8x0Z3twVMIlHY3Dgqn66XH7/dpB9fXi4Hc7fL@dkfU@Iadae7ilaq0abT8Qy0VDafLemu/B6G5qxM4lbdt/gYQoLl4eEGj8MwEcJm6TankWLmAfM76uleIRyAhaSmO7bY6ejvXwKBMEeQslehdWGuA1Xg4@Twe1wcHk@OIcnNb38cn1zSqli66TymcZZmpD6WZQFPoRRCp4OI5VkAZbP8liwJOFRaGEF2GcmBO1v@YKlmQjB1p6VNojq9XQTgYeYwW5r29Xr00gAkT14xHI0esbSgIeMqInHw4Jg0z6CbFpSLCt/pICLcnuIeReaJT3TpeApI5pseRNUQegmmJXwRyantqokytISU8bVsFFnDHt7sJ3UHLNhliVs4LW3pHcpUor2DoSIRA@umReFPkg0LDg2NZyVevrcy1U1EzYK9x/PYKWK/gs5Om2xDDVHsl5ouMDkCfhRaMojiD3EqBI4S@f/oaXa9Uq3uzvd7r7Zbfmo69UU0TLB2oicNenCDYLIIyioeQAtsHco25PD5cnhh4hD02rt7o46mhh4xFWYznjTve6Ijx3HtMxj8840e1tf/y26vaXbr9Dtf9G7km7WzCqo2lgFV1Ur8F1nB603UV105r248ZLdhk4bLm8uLnBAa46@8p9Phmef4Bjq8PvnLxiKjNWhV8w@uEHC6n/Zm6lgjMiwJb9WvDJK9x6/Rqt1QwUGz01YYhgW/gzLMnJpcjnC11Iv/uXo1x7p0hjLUq9R2Fyv53KsCMVAERta9jZZXuSxjCKYwqtBrjPotKhn41e@Ir5WYuUbgEqlnXKW58X6JvmJ7/MUv4VuUNKha1BZ/gA "C++ (clang) – Try It Online") - POSIX ERE
[Try it on regex101](https://regex101.com/r/2wI6jW/23) - RE2
[Try it online!](https://tio.run/##VZDBbhMxEIbvfoohQbUnTd0gIQ5ELuoBHgC4hVRyNt7UZde7sp3WKeHKA/CIvEgYezcVaDU7M79n5hv7QT/qUHnbx6vQ263xbee@m8PJK2ee4LPZfUy9EM/q5np2uhOCc3a8Q/KS4ewoJCeHOHt9ml0/o4zdl@it2wmUobGVEe/mV28Rl1CDggDqBlZSyrCWre5FlfNKqYmcwAeY8Am8hwpZ3XkQVi2WIDR1eaO3jXVGIMIrBW7fNEuw6g3@AHtx0RMtCgL0@xiiFxoZgK2pVTbG7eK9Ugs4HkHL6l772ygWqBSfcoSqc9G6vaH6zX@Yl1n8m@OXmzywpQLR5nXb1WJYXqT5AYtSUt895YTc6rBG6c2j8YGGyYfOOno0RBSrmtab12KD67NOBIRLyJ4wZy78@fUbOOnCy2hCFC3SA/Gvfm84vRH/pJtgaCT7eZpCVqHSwQTGJH1MSpaySzkik8Xol0gflCwNNVIWY6NPw3nKcWkYg9I4hQJ@gaWRI9k4rNSXIA2EAUv7nPWijfOHTWQ6FxTUIOYspfH8DL/dbm20ndPNP3sMdyiUvw "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript
[Try it online!](https://tio.run/##bU9BTsMwELz7FSvXkm1KrHIligRC4saNGxQRtQuJ5DrFSVULyJUH8EQ@UtZ2ChxQ5Ox6dnZmvO326PsGrT0IX915fMawPD93uFcX8vCglJTs/UFTNUyfvCsjqWh9Ig7y4pRfdZtta3HNdSleq0X51HmsV40SFloHonXb3aDfGED7pMSrftv7dsCi6fphJP5ZCb8AFK4jV9s6BGHTCpBOgS/AORSdJ/RusUz3GdcQVUdA22MmLoq46HbW5hmA2FScl0CZaO4oHY0LO5DOwlh0z0MTkfmc@GID8yoaCLec0zxV/uj4WEY6VFk5yf4fmcPXxycIlcJ4c1MPqwZ7pcSm8Li19Qr5veGnXHKtyVDe@h3KnJ9u1zVVOWr@8yjKlH3tOB5mEOmwqnvsGTP0MWNYiCXEjo5Jh36B8IxEKHOMSYdNNeR5iH1amJq0OIMU5scsTD6GTWKJn5qQHbIt5TniCZv0cxITjoRklcF4C2GaH80v1@t2aDtX2z858huSyzc "PowerShell – Try It Online") - .NET
This is version that matches **solvable** mazes and doesn't match unsolvable mazes. It was interesting to implement in a regex flavor that has no negative lookahead. The way it works is pretty much like actually walking through the maze and solving it.
The empty tile character is `'`, and walls can be represented by any other character. The input given to this regex must not begin with a newline, and must end with a single newline.
The version of POSIX ERE on TIO treats newlines incorrectly in this version, even though with `REG_NEWLINE` not set, newline is supposed to be treated like any normal character. So in the ERE test harness, I made it use `!` as a line separator instead of newline. But when tested locally on my machine, it works with actual newlines.
# Regex ([GNU ERE](https://www.regular-expressions.info/gnu.html#ere) or better), ~~29~~ 24 bytes
```
^((''
|^)(.?'.?
)?\3*)*$
```
[Try it online!](https://tio.run/##jVTdbtowFL7PUxxgahygEaHSLqAp6g/bLrpOaqnUCSjKggFrwYmcRKRdud0D7BH3IuzYDjShXbegYJ/j7zvnO8d2/Cg69AOPzzc1xv0gnVI4jpMpC@3FifHsYmGcCOotiz5B5zQrwxDE@Pw134nhLzwBk2g4Bheuq2er1fdvR@nXh4e7weL9akE294SYZuXp3iJ2z7R7Fas3Oqpb9Xcbax9bbUI9cidRw@kajCew9BgnlvHDAHyUqkmix/NwGbGATrtqKRqiloByElmHzthtaS@bAUGwj1ByUGI1IWrCdf/jpH836F9d9C/gSZlXX25uzyxLsXVS@cyiNIlJ9TxMgynwMAFfh5FK0gBrp1kkaByzkNtYATaZCmF1d3xBk1RwcLRnrQdEdTq6g8A4ZnCaemzr9VkogMgePGI5Gj2nScA4JcrwGc8JjtVFkGMVFMvKHy3ARbk3xBxxs6BnthIsoUSTbX@CKoi1DWbH7JFK01GVhGlSYMq4GjZsjeHgAHZGxTVrZlHCFl55S3rbQkre3r4QoejADfVDPgWJhiXDpvJ5oafPvVyXM2GjcP/xAJaq6L6Qo9Pmy1BxJeuFhktMHsM05KY8gthDjCqB82TxH1rKXS91u73X7fab3ZaPult1Ea5irI1Iq24tvSAIfYKC6kfQAGePsjs5TJ4cdow4HBqN/d1RRxMDD5kK0xpvu9cesrHrmrbZM0em2dn5um/RnR3deYXu/IvelnSzYpZB5cYquKpagUetPbTeRHXRqf/ixkt2E1pNuLq9vMSJVXH1lf98Ojj/BD2owu@fv2AgUlqFTm598IKYVv@yNzNBKZFhC36teG0U7j1@jdabmgoMvhfT2DBs/Bm2bWRyyOQMX1u9@JehX3ukS2NsW71GPmZ6PZNzRcgniljTsnfJsjyPbeTBFF5NMp1Bp0U9W7/y5fG1EjvbAlQq7ZRWluXr2@Sn0ylL8FvoBQUdugaV5Q8 "C++ (clang) – Try It Online") - GNU implementation of POSIX ERE, old version
[Try it on regex101](https://regex101.com/r/2wI6jW/24) - ECMAScript
[Try it online!](https://tio.run/##VZDBbtswDIbvegouGSoxTdkMG3ZYoAY9bA@w7ZamgOIoqTpbNiSlVbr2ugfYI@5FMkl2ig0GTfIXyY/SvXpQvnKmCxe@Mxvtmtb@0Iejk1Y/wle9@xw7IZ7k1eXkeCsE5@z5FgUtOC0YLm7eT3Dy9ji5fEIK7bfgjN0JJF@bSouP04sPiHPYggQP8gqWRORX1KhOVDmvpBzRCBYw4iP4BBWybetAGDmbg1Cpy2m1qY3VAhHeSLD7up6Dke/wJ5izsy7RgkiAbh98cEIhAzDb1Eq1trtwJ@UMnp9BUXWn3HUQM5SSjzlC1dpg7F6n@vV/mNdZ/Mby83Ue2KQC0eR1m@WsX17E6QGLUlLXPuYkueVhheT0g3Y@DaP71tj0Yogoltu03nQr1rg66YmAcA7ZJ8yJC39@/QaedOEoaB9Eg@mB@He31zy9Ef@iaq/TSPZyHENWoVJee8YofYyIxexijpJRsfSLSe@VLPU1RMXY4GN/HnNcGoagNI6hgF9hceAQG4aV@hLEntBj0z4nvWjD/H4TiqeCgurFnMU4nJ/g15uNCaa1qv5nj/4OhfIX "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript
[Try it online!](https://tio.run/##bU/BTuMwEL37K0auJduUWF1xI4oKQuLGbW9QtFE7kEiuU5xUtWBz5QP4xP2R7thOgQOKnBm/efPe8647oO8btPYofHXv8RnD6vLS4UFdyeOjUlKyv49amaU0S6aXDxdn@kwc5dU5v@m2u9bihutSvFaL8qnzWK8bJSy0DkTrdvtBvzGA9kmJV/128O2ARdP1w0j8XyV8AVC4jixt6xCETStAOgW@AOdQdJ7Q@8Uq3WdcQ1QdAW2Pmbgo4qLbW5tnAGJbcV4CZaK5o3Q0LuxAOgtj0T0PTUTmc@KLLcyraCDcak7zVPkfx8cy0qHKykn258gc/r1/gFApjDd39bBusFdKbAuPO1uvkT8Yfs4l15oM5W@/R5nz0@22pipHzT8fRZmyrx3H4wwiHdZ1jz1jhj5mDAuxhNjRMenQLxCekQhljjHpsKmGPA@xTwtTkxZnkMJ8moXJx7BJLPFTE7JDtqU8Jzxhk35OYsKJkKwyGG8hTPOT@fVm0w5t52r7LUd@Q3L5Dw "PowerShell – Try It Online") - .NET
The addition of backreferences allows for a more compact regex. But there doesn't seem to be a clear-cut standard that includes backreferences without lookaheads. The closest appears to be GNU ERE, used by egrep and sed `-E`, but there doesn't seem to be any library interface for it, and neither of those utilities support matching raw newlines.
The version of GNU libc on TIO enables backreferences in ERE, but with an up-to-date version of the libraries, they're only enabled in BRE, not ERE. The version on TIO has the newline bug, though, so same workaround for newlines is used in the TIO test harness.
The empty tile character is `'`, and walls can be represented by any other character. Matches iff the maze is **solvable**. The input given to this regex must not begin with a newline, and must end with a single newline.
# Regex ([ECMAScript](https://262.ecma-international.org/5.1/#sec-15.10) or better + `/s` flag), 17 bytes
```
^(?!.*x(|
|.
.)x)
```
[Try it on regex101](https://regex101.com/r/2wI6jW/10) - ECMAScript 2018
[Try it online!](https://tio.run/##bVFLbtswEN3rFGMYCMlWGdjbCEqQRQt023bnqggjMQ4DmlJJKmbgeNsD9Ii9iDuk5CKLLIYzfPN5b8gn@Sx96/QQLm3fqZOuV5Ws7WhM5eqvavspDvxbcNpu0cn93eknv1ngh8hfi1csUERxukNvdKv4urxcixKYZ6Jy6teoneLMKdkZbRUT2FIc1BcblHuQVH/QdhjD1eD6VnmPPnTaHgX2lrPcUZr6@lAAaLi4gDdV/Rhw73Sg6T8scYGu19X7BUZUacADcLnIO4kD3NeGMIAd1MDpuIbdZtXgTg6cx/JFZCRfXb9PF3Kbl0agU8/KecUFPvWaRDIhBN9sEFE2ZXL3TXPOJWGZ5X3d8Pf3H2DwEbjDoHzgOwE3wL67UTG4AvZZGk9PRrtNX0GjjoqgvIpBo@w2PC7qVXoZg@2jdLeBr8SiZksmqMcUR3FaQpoHrfTKFwV9Fh1YxORiisgwGx2R8AlJ0FSDmK2YfZzyMcW5YQ5y4xKy5P9kcebBYh6W63MQJ4aJlvSc8YzN8yclGM8FmWoC0y3GOX8mv@06HXRvpXmjY9ohs/wD "JavaScript (Node.js) – Try It Online") - ECMAScript 2018
[Try it online!](https://tio.run/##bVBBTsMwELznFYtrKQltrHBtFFGExAlOcENFRO22seQ6JUlVq22uPIAn8pGwttPCgYO969nZmUm21R7rpkSlel7nrzWu0cynU437aBb2b9Htlbg20Sk4iUDEJu7D2YQ9S71W@Cg1Tu6rzVYqXLI444c8zVZVjcWijLgCqYFLvd218TEAkKuIH@LjvpYtJmXVtB3xbzL4BSDRFdkqkgWu3AqQToIfwBgkVU3oazp37xGLwap2gKpBT0wTu6h3SvkZAN/kjGVAmWiuKR2NE9WSTioU6nVbWmQ8Jj7fwDi3BlzPxzR3lb1r1mWWDrlXdrL/R2bw/fkFPHJhavFUtIsSm4hvYpIPX@odhj4tvR4KqmEXs8snUALvorquH4Glw6JosAkC@vF0icDYYmxHR7hDlyHcIxbyHCHcCYZq/NzY3i0MjVscgQtzMTODjwgGMcd3jfEO3pbynHGHDfo@iTBngrPyoH0ZM8zP5nfLpWxlpQv1J4f/BufyAw "PowerShell – Try It Online") - .NET
With negative lookahead it is trivial to modify the 10 byte regex into one that matches iff the maze is **solvable**.
As in the regex it's based on, the wall character is `x`, and empty tiles can be represented by any other character.
Note that the `/s` flag was introduced in ECMAScript 2018 (JavaScript ES9).
# Regex (Perl / Java / PCRE2 / .NET), 29 bytes
```
^(.(?=.*
(\2.|)))+x.*
\2.?.?x
```
[Try it online!](https://tio.run/##lVJBbsIwELz7FatgQdzShSD1ggkREu2xJ46IiEKQLLmBJiC5StNjH9An9iPp2g5pr1XkeHd2Zmci5ZQV@r55eQNeSKj0cbfVwEeS2ni2XKwW85odjkXIVTyWs7mkOxIVqAMhojoVKj9DsM4DWQPXEEN5eS7PRE@Hd9EwEtmrHULyBx/TRMAUeCoZgN/Ata3VAUJa0u93bE3sSOTZoDcQFTGAVDGlIMHkv2bQhSVxIH1crtFqkCDp9ntSaHPEHzDixUiJJIDvzy943OoyC6a@WRWXLBBWU7M6TR@elmnabEIMkxhvWLie4LsQ4tZQQ3WCiWmanlPBbltmJWNID0Nkxl7GVnTQHXoZwj1iIc9BdIe1t/FzY2snaAsn7Pm4nZlpfZC1yxzfFcY7eFvKc8Ud1u73SdBcCc7Kg7Yzpp1fzRf7vTqrY04/028O/w3O5Qc "Perl 5 – Try It Online") - Perl
[Try it on regex101](https://regex101.com/r/HCrbRP/4) - PCRE2
[Try it online!](https://tio.run/##bY/BTsMwDIbveQori9SG0ajsuKnaEBI3btzGENWW0UghHWmnRRu98gA8Ii9SnKQbHFCVxP7925@7qw/SNpXUume2WFr5Kt1qOjXykC6S/jkV6bwQVyR9mogPzvnYYYLxXMxdnyyu6V39tlNabiifsWORz7a1leW6SpkGZYAps9u3/EQA1DZlR346WNXKrKqbtkP/DRZ@FchMjWCtjASmQw/goEy@A6WQ1RbVZb4K@Yhy8GM7kLqR0ZhnvtHstY41QD8UeOVj@mLomOmZT7zkTcHxP53C9@cXsDTMteKhbNeVbBDBcXJyXyIyiWRMH@0eM04v21zgAeU5Hen6EXgjrMtGNoQI/IgQxPnH@QiPCAcvh3pUvBQ9QoRDhtfFuvNxaBiC0DiCsOMF5gaOIMOw4A@Bi4SIxX3OetCG@XET4c6GgIqiz5wb6mf47WajWlWbUv/ZI/5DoPwA "PowerShell – Try It Online") - .NET
This takes the input in the form of \$2\$ rows of \$N\$ columns. The challenge just wouldn't be complete with that submitted only [in .NET flavor](https://codegolf.stackexchange.com/a/223020/17216) and not PCRE as well. Matches iff the maze is ***not* solvable**. The wall character is `x`, and empty tiles can be represented by any other character.
The .NET balanced group method is still shorter (at 27 bytes), as expected.
This solution takes advantage of the fact that the upper-left corner will never be blocked. It would need to be modified otherwise, because it looks for a wall in the top row that has a wall diagonally or orthogonally below it. It starts this search at the second column from the left.
[Answer]
# [Snails](https://github.com/feresum/PMA), 7 bytes
Based on [@xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s observation, this checks if there are `x`s above (`u`), below (`d`) or diagonally from (`y`) another `x`. Returns `0` for solvable mazes a positive integer otherwise. I've wanted to use this language for so long!
```
\xudy\x
```
[Try it online!](https://tio.run/##K85LzMwp/v8/pqI0pTKm4v9/PRCoAEKuigoQBQQA "Snails – Try It Online")
## Explanation
[Snails is a 2D pattern matching language that was created by](https://codegolf.meta.stackexchange.com/a/7199/9365) [@feresum](https://codegolf.stackexchange.com/users/30688/feersum) which is not entirely unlike regex.
In this program, the `\x` matches a literal `x`, then looks above, below or diagonally to it (`udy`) for another literal `x` (`\x`).
[Answer]
# [J](http://jsoftware.com/), 19 17 bytes
```
0=1#.[:,*&#./;._3
```
[Try it online!](https://tio.run/##bZFdq8IwDIbv8yuCk5WJxm1eHKgMRMEr8UK8ExGRjcPhgOAH5N/PNOtQ1zWElqdvk7z0rx6QqbCwaHCMKVrJCeFqt1nXaZFFdLDjURzRdE6nWZ3AdkmoPB9NFzYih48fNH5jgEd5f2BBeLBYXn6viwoNm7iQyxzAETT727M0XindUyCJ5AswUBcRcIBIswNZhKHSSYMCItQEv/d0YMe1qD/44o2V9fn/3vHC0NMGenpryQByM2joSvz36VXrxwxNE7cPdfpQ4G6Yvbb1psv9r5qsMMcfHMqbTCLVbCJrz/UL "J – Try It Online")
-2 thanks to Bubbler for suggesting Max Cubes instead of subarrays.
A port of Bubbler's APL solution saves 1 byte:
```
2 e.[:+/2+./\"1]
```
but it seemed a shame not use J "Max Cubes" here, as the problem seems almost tailor-made for it.
## How
Let's take the example:
```
0 1 1 1 0 0
0 0 0 0 1 0
```
`v;._3` will apply the verb `v` to every 2x2 block. Eg, `<;._3` will produce:
```
┌───┬───┬───┬───┬───┐
│0 1│1 1│1 1│1 0│0 0│
│0 0│0 0│0 0│0 1│1 0│
└───┴───┴───┴───┴───┘
```
In our case, we want a verb that detects "walls" (diagonal or vertical). `*/@:#.` does the job. It converts each row from a binary number into an integer `#.`, and then multiplies the resulting 2 integers together `*/@:`. This result will always be `0` if there is no wall.
So now we can just sum all of the results `1#.` and check if the result is 0 `0=`. If it is, there are no walls and we can get through. Otherwise, we're blocked.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~10~~ ~~9~~ 7 bytes
```
4&1ZI2<
```
Input is a binary matrix, with `1` for `.` and `0` for `x`.
Output is an array of ones (which is truthy) if the maze is solvable, or an array containing at least a zero (which is falsey) if not solvable.
[Try it online!](https://tio.run/##y00syfn/30TNMMrTyOb//2hDBRA0AEJDODSwRheA8GIB) Or [verify all test cases including check for truthyness or falsiness](https://tio.run/##bZA9D8IgEIZ3fsUt2hWMGyYuLiaOTjZNJLZaIrakUJMO/nakAgUSWe7uvee@eDEtzBX8W8Gp7yX072YAJgTwTo5ame2aXI6bndlHjt9Bz6Q1bQNKs9sTuAI9jLqdUOFsYUE5qtYyNqf0wLsH@sQmjVANKu5MKIv@Y6uE7ep5KKBD1GqupGATOueYsDeYklAgFSoJWAd7F1stqLNOkhD/sJgN@aXWicHSPFww5wd1aZwJySBM0wE0mxcKQxgIki2K3YE56RGarxNP80BaG1dMsJDB/usS2e/wBQ).
# Explanation
### Solvability is equivalent to full connectedness of all non-wall tiles
The maze is solvable if and only if all non-wall tiles are connected to each other using 4-neighbourhood.
**Proof**
*All connected ⇒ solvable*: this is clear.
*Solvable ⇒ all connected*. Let the maze be
```
A ··· SUWY
B ··· TVXZ
```
This maze is solvable by assumption. Consider its rightmost square of size 2:
```
WY
XZ
```
There are two ways that `Z` can be connected to the input:
* Through tiles `W` and `Y`: this means that `W` and `Y` are non-wall. They are connected to `Z`. If `X` is non-wall it is connected to `W`, `Y` and `Z` too.
* Through tile `X`: this means that `X` is non-wall. It is connected to `Z`. If `W` or `Y` are non-wall they are connected to `X` and `Z` too.
We now proceed from either `W` or `X` to the left, considering the square
```
UW
VX
```
By the same reasoning as above, all non-wall tiles in this square will be connected to each other, and to the tiles from the previous square.
This way we proceed until `A` is reached (which is possible by hypothesis), and all non-wall tiles are connected.
### How the code works
The program checks that the image formed by considering wall tiles as background and non-wall tiles as foreground has a single connected component.
```
4 % Push 4
&1ZI % Implicit input: binary matrix. Label connected components using
% 4-neighbourhood. This assigns a different label to each connected
% component of ones in the input. Labels are positive integers. The
% result is a matrix of the same size as the input
2< % Less than 2? Element-wise. All comparisons will be true if and
% only if there is a single connected component
% Implicit diplay
```
[Answer]
# [R](https://www.r-project.org/), 38 bytes
```
function(t,b)all(c(b[-1],T,b,T,b)[!t])
```
[Try it online!](https://tio.run/##K/pfnJ9Tlmr7P600L7kkMz9Po0QnSTMxJ0cjWSMpWtcwVidEJwmENaMVS2I1/ysrhASFulpxleQX2BpyJeWXAEmwCRpAER0gXxMslaxhqGOoCZZP1jAAMXEoAsqBIZSGaUER1MFnAEQephLMQ9iLIgzhYRjEpazg5ugTDPUT2E1EOhzhWEIOhHnGADlQDGBCMK/jNQCm2gDhPFS/4fDdfwA "R – Try It Online")
Checks that the bottom row is 'open' at position x-1, x and x+1 for every 'closed' position in the top row.
How?
* consider matrix of 3 rows:
1. remove first item from bottom row of maze + add `1` at the end
2. bottom row of maze
3. add `1` at the start of the bottom row of maze without last item
* check that all elements are `1` in columns where top row of maze is `0`
Golfing:
* R 'recycles' logical indices, so we don't actually need to make a matrix, we can just list the elements
* no need to remove the last item of the bottom row of maze since it's guaranteed to be true
# [R](https://www.r-project.org/), a different approach, still 38 bytes
```
function(t,b)all(t&t[-1]|b&c(b[-1],1))
```
[Try it online!](https://tio.run/##K/pfnJ9Tlmr7P600L7kkMz9Po0QnSTMxJ0ejRK0kWtcwtiZJLVkjCcTSCdHU/K@sEBIU6mrFVZJfYGvIlZRfAiTBJmgARXSAfE2wVLKGoY6hJlg@WcMAxMShCCgHhlAapgVFUAefARB5mEowD2EvijCEh2EQl7KCm6NPMNRPYDcR6XCEYwk5EOYZA@RAMYAJwbyO1wCYagOE81D9hsN3/wE "R – Try It Online")
Completely different approach, but annoyingly the same number of characters.
Checks that it's always possible to move rightwards, either on the top or on the bottom.
How?
`top & top[-1]` = logical AND of each element of `top` with it's neighbour to the right
`|` = logical OR
`bot & bot[-1]` = logical AND of each element of `bot` with it's neighbour to the right
The last element (that has no rightward neighbour) is a problem, because R 'wraps around' the longer vector, so if the last top element is `0` and the first bottom element is `0` then it will fail.
We can fix this by forcing it to evaluate to `TRUE`, which we can do by adding a `1` at the end of the 'chopped-off' bottom row (since we know the last element of the full-length row must be 1).
[Answer]
## Excel, 38 bytes
```
=AND(ISERROR(FIND({12,3,21},A1+2*A2)))
```
Input is 2 strings (1 for each row of the maze), in cells `A1` and `A2`, with `1` for a Wall, and `0` for a space.
First, it adds the first row, and twice the second row together. This will convert each column to base-4 representation of whether it contains no walls (`0`), wall in the top row only (`1`), wall in the bottom row only (`2`), or wall in both rows (`3`)
We then try to `FIND` any examples where there are walls in both rows (`3`), **or** walls in different rows of adjacent columns (`12` or `21`)
If both of these return errors, then there is a clear path
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
+ƝẠƇ
```
[Try it online!](https://tio.run/##NU45DsJADOz9FST/gI/Q06A8YOiAgn0AdSQkWkoUKSBRJCL/2P2I8RVpZz07Ho/3sO@6o8hm6ev7vhSpn9du20495lLHqx763er4aOfvNEzDXNrlKcLERMwEKzCmYIdeUD0Uk8LD7KCsiD6M@0CSGEQGM@W0G5wgImOPfmDVXcvAWM1YDZ4dor2A7Jv5Dw "Jelly – Try It Online")
Takes a list of pairs, where `0` represents a path and `1` represents a wall. Returns a falsy value if the maze is solvable and a truthy value if not.
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ḋ×ṛɗ/Ẹ
```
[Try it online!](https://tio.run/##NU6rEsJADPT5mOUL@BE8hukHBAeYCiSiolOFRTKdFmYQvUHwGbkfOS6Pilw2m93NHfZNcyxFpmvqZO5/3UZeU5H3c7fNpwGppe9N5ns@f5ZxGVObL49SQCACiLWxolqwqg9X3hmlXANYUXT2PSs2QwA3cgSDwm0CA@yRfqd@YOWNi0A/DV4Flu2kTsyxV/Ef "Jelly – Try It Online")
Takes a list of pairs, where `0` represents a wall and `1` represents a path. Returns `1` if the maze is solvable and `0` if not.
[Answer]
# Regex (.NET), ~~35~~ ~~31~~ 27 bytes
```
^(.)* ?#.*
(?>(?<-1>.)*) ?#
```
This had to be done. Checks if the string contains one of the following (uses #s and spaces) :
```
#
#
```
```
#
#
```
```
#
#
```
Matches impassible grids, doesn't match passible ones.
See [Martin Ender's excellent capture group documentation](https://stackoverflow.com/questions/17003799/what-are-regular-expression-balancing-groups/17004406#17004406).
[Try it online!](http://regexstorm.net/tester?p=%5e%28.%29*+%3f%23.*%0d%0a%28%3f%3e%28%3f%3c-1%3e.%29*%29+%3f%23&i=++++%23%23+%23%23%23%0d%0a+++++%23%23%23++&o=m)
Thanks to Deadcode for -9 bytes.
[Answer]
# [Perl 5](https://www.perl.org/) `-p0`, 67 bytes
```
$x=$_;$_=!grep{$b=$_-1;$x=~/^.{$b,$_}x.*?\n.{$b,$_}x/gm}1...5*y///c
```
[Try it online!](https://tio.run/##K0gtyjH9/1@lwlYl3lol3lYxvSi1oFolCcjVNbQGCtfpx@kB@Toq8bUVelr2MXlwnn56bq2hnp6eqValvr5@8v//enoVelwVFXp6//ILSjLz84r/6/qa6hkYGvzXLTAAAA "Perl 5 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~26~~ 23 bytes
```
⭆⪫E²S¶⎇⁼ι.ψι←¤-J⁰¦⁰T¹¦¹
```
[Try it online!](https://tio.run/##NYnBCoMwEETvfkXIaQMxaI/13IJSoVCPvQSx7UJM0jRK/Pp0pXQu783M@NJhdNrkfA1oI9wi4dlrD51DC7scJGutX@LvAiEk43fLCcMUrA4bnN6LNh9AOtS@b5KhEKIperdOcLxMj0jljMYALzlpt8x@cFBJVlEbAs5QS1aLJmelVEpqTyr@Qsjlar4 "Charcoal – Try It Online") Link is to verbose version of code. Takes two strings of `.`s and `x`s as input (actually any character other than space or `.` would work) and outputs `-` if the maze can be solved or a blank space if it cannot. Edit: Saved 3 bytes because I had misread the question. Explanation:
```
⭆⪫E²S¶⎇⁼ι.ψι
```
Print the input, but change all the `.`s to null bytes, since Charcoal knows how to fill those.
```
←
```
Move to the end position.
```
¤-
```
Flood fill the null bytes with `-`s (chosen because this is Charcoal's default output character for a Boolean true value, but any character other than space would work).
```
J⁰¦⁰
```
Jump back to the start position.
```
T¹¦¹
```
Delete everything other than the start position, which is now `-` if the maze could be solved, or blank if it could not be solved.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 54 bytes
```
Max@MorphologicalComponents[#,CornerNeighbors->1<0]<2&
```
[Try it online!](https://tio.run/##dVFBC4MgGL3vV0iDnRzYzm0Mgt0aO@wWHdywDEpDHWxEv91FqRXZReW9773v@541VpTUWJVvrHNwBjrB32vCRUN5xYserWJeN5wRpmS6hzEXjIg7KQv64kIeL2GEsuh00LuHKJlKg6f4KPoDMZZEBplB87Rtww6C/uiyBQgHGME1gYZ6D2E042NNImPoV05ab8@xxN6uzZwYRDu77g1X0rutm8PXZDT2k0a3QU5qM5QvARvqtosVOye7sTcyU770dZlsiWwVcl85I6bZ9R8 "Wolfram Language (Mathematica) – Try It Online")
Credit for this idea goes to [this answer by alephalpha](https://codegolf.stackexchange.com/a/154374/15469) from a couple years ago, where it used in a different context.
The core insight here is that -- if the maze can be solved -- then the "spaces" form a single contiguous morphological chunk. And Wolfram has a built-in for detecting that.
[Answer]
# [Io](http://iolanguage.org/), 90 bytes
```
method(x,y,x map(i,v,v>0and(list(i-1,i,i+1)map(c,y at(c abs))detect(>0)))reduce(or)!=true)
```
[Try it online!](https://tio.run/##tVOxbsIwEN3zFQeTT1yleK1kpC6IgamlAxJLmhjVEiQoGARfH4gA67Bjb2wXv@f3Xu7Opuk28KlgDd1O2/@mEme60Bl2xV4YOtFpmhd1JbbmYIX5kGTITCT2aEkXKKwoofg7IFba6tKKaY6Ira6OpRZNiyNl26PGbqyUWn7/LuerWzGGfWtqu62zbHMXzpHgUaADnxiBg2VfDzGkE4gxuMzzM8KT3C6lF0jG87kLvPbyhLSEs3xlh8kHUHf4poxZP@bZ1@InMmWvtdEUzDPF8/82ygtU83QnvBhMIu7AJH0f1szEJjGJYXNvpGktfkd67yOghb0I1wIpg/iqd1c "Io – Try It Online")
# [Io](http://iolanguage.org/), 98 bytes
Port of Bubbler's APL solution.
```
method(x,(o :=x map(o,o slice(0,-1)map(i,v,v+o at(i+1))))at(0)map(i,v,v*o at(1)at(i))push(0)sum<1)
```
[Try it online!](https://tio.run/##tVOxbsIwEN3zFScmXzFSbkXN0AUxdCowIHVBbSIsJTgiAfH3wQFqLnYSs9RD9HL37t3z6ax0k8E8gW9oirTe619xkUKbyAWKXSm01FDl6icVsZwRtiElz/I81bCrhZoSmmNQ/Ey93VLURhViear2JludinfCZpIkyfprs15uDZhAeVSHOj9EUSZyVdX3T4wSHgDRUjoMCZZELR7mkRUb53HJv99RNnEDYW1PPuTblnHsOPRpQRfUrfHv0pO1wf/1G7XLsfj4XI3thjP4gCPWP8x2pxBgex3iV@bkGGNCoW5M3u3JBh7cQibUb8RZgVcUeSU5b86j9cxoYJlQRjDyZJor "Io – Try It Online")
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 7 bytes
Port of @Bubbler's answer.
```
€ü~øP_P
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UdOaw3vqDu8IiA/4/z862kDHQMdQxwAMDWN1oiFsQ4hYbCwA "05AB1E (legacy) – Try It Online")
## Explanation
```
€ Map:
ü Apply to pairs:
~ OR
ø Transpose
P Product
_ NOT
P Product
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~53~~ 51 bytes
```
or.map(or.foldr1(zipWith(&&))).mapM(\x->[x,tail x])
```
[Try it online!](https://tio.run/##fVBdT4MwFH3nV9wxs9EMTPsDuoQY3Auaxbn4AMQQhUCEQWhVovG3Y1tgo5jYpB/n3HPu7b1ZzN6Soui@nSX47v3u6O48uNnvYen8GCkNu6q5LuPaEldaFa8Nsb7y@innmbVaIYRk7M4KW2cbtDaP8wLaCHWsKj4SKIFCClcgJGCpg9I1WSMEpVHG@YlK7zPU7/zAG/80KsMSnC2wrPoUrsUCI9hswLTBlPeZJj0tpZPAUFiU4AnjLzFLGBiXJ4XAALEcB25d/@ApEJjYtMWO7BFKTKYEkQJNoSw6RZRLV/UyPRfGavcJeqR5iOSGdMNTT/tfBtHZ48PRm358Vl26dGqopFFk/LneoprMXKtUSk3wvH9MLibVjB6WLOmnq9CfRs/zi7pf "Haskell – Try It Online")
The anonymous function takes a list of two lists where True is a wall and False is empty. Returns False if the maze is solvable.
[Answer]
# Prolog, 99 bytes
```
f([[1,_],[_,1]|_]):- !,0=1.
f([[_,1],[1,_]|_]):- !,0=1.
f([[1,1]|_]):- !,0=1.
f([_|T]):-T==[];f(T).
```
[Try it in SWISH](https://swish.swi-prolog.org/p/XsBgCCdu.swinb)
xnor's [comment](https://codegolf.stackexchange.com/questions/206957/solve-a-2xn-maze#comment490697_206957) that the problem statement was equivalent to checking if no 2 x's touched vertically or diagonally helped me a lot here.
---
## Imperfect version (never terminates if false), 66 bytes
```
f([X|T],C):-nth0(C,X,0),(T==[];f(T,C);D is mod(C+1,2),f([X|T],D)).
```
[Try it in SWISH](https://swish.swi-prolog.org/p/LAvitXCu.swinb)
Requires the first input to be a list of length N containing lists of length 2. Empty tiles are denoted by 0, and walls are denoted by anything else (I could also have used characters, I suppose, but this seemed easier). The second input (`C`) is 0 if we're currently at the tile on top, and 1 if we're at the tile on the bottom.
An example query would be:
```
?- f([[0,1],[0,1],[0,0],[1,0],[1,0],[0,0],[0,0],[0,1],[0,1],[0,0],[1,0]],0).
true.
```
However, if the maze is unsolvable, there wouldn't be any output, it'd just keep running.
[Answer]
# JavaScript, 63 bytes
```
n=>k=>!n.filter((e,i)=>e>0&[k[i-1],k[i],k[i+1]].includes(1))[0]
```
Takes input in currying format, each argument being an array of 1s and 0s. Outputs `true` if the maze is solvable and `false` if unsolvable.
] |
[Question]
[
Given a decimal integer `n` as input, output the smallest (in terms of absolute value) decimal integer `m` such that the absolute value of `n-m` is a binary integer (composed only of `1`s and `0`s).
`n` and `m` can be any integer, positive or negative.
### Example
Let `n = 702`. The closest binary integer is `1000 = |702 - (-298)|`, so `m = -298`.
Let `n = -82`. The closest binary integer in absolute value is `100 = |-82 - 18|`, so `m = 18`.
### Test Cases
```
Input n Output m
0 0
1 0
4 3
-4 -3
6 -4
15 4
55 44
56 -44
-82 18
702 -298
-1000 0
```
### Scoring
This is code-golf, so the shortest answer in bytes wins.
[Answer]
# JavaScript (ES6), 43 bytes
Starting with \$k=0\$ and using the expression `(k < 1) - k` to update \$k\$ after each iteration, we recursively generate \$k=0,1,-1,2,-2,3,-3,\dots\$ ([A001057](https://oeis.org/A001057)) until the regular expression `/[2-9]/` applied to \$n-k\$ doesn't match anything.
```
f=(n,k=0)=>/[2-9]/.test(n-k)?f(n,(k<1)-k):k
```
[Try it online!](https://tio.run/##dc/BDoIwDAbgu0/BcUss6@ZAMKIPYjwQBIMjm3GLrz85KGCNvf350v7prX7Wvnn09wDWXdoYu4rZtamQVwdxUlCeRRpaH5gFw4/daMzsJR/DzsTGWe@GNh3clXUMk3E4T4RIcPVN8j/pmTaEQE8E1PJ5DTRtyyajlC3ox/LFSYpQqA/KgtgWJwNVUgWJiO/f4ws "JavaScript (Node.js) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 48 bytes
```
f n=[m|k<-[0..],m<-[k,-k],all(<'2')$show$n-m]!!0
```
[Try it online!](https://tio.run/##DcZBCoMwEAXQq4wQsIU/Mglqu9CThCyyqCjJpKKFbnr3VHiLt8YzvXKudaEye/2lib10XYBeSeAUEHO@Ta1r7@Zc319TWEPTSNW4FZppP7byIUMad1rICyx6cI8RdsBwGcFPh4c4sBWRUP8 "Haskell – Try It Online")
xnor saved 7 bytes, thanks!
[Answer]
# [Python 2](https://docs.python.org/2/), 49 bytes
```
f=lambda n,m=0:f(n,(m<1)-m)if"1"<max(`n-m`)else m
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWNw3TbHMSc5NSEhXydHJtDazSNPJ0NHJtDDV1czUz05QMlWxyEys0EvJ0cxM0U3OKUxVyoRr7C4oy80o00jQMNDW5YGxDJLYJElsXmWOGrMEUiWOKwkFWpmthhMQzN0Dm6RoaGADdAHEWzF8A)
Port of Arnauld's answer, thanks to Kevin Cruijssen.
`"1"<max(`n-m`)` checks if any digits of `n-m` are more than `1`, i.e. `n-m` is not a binary number.
## [Python 2](https://docs.python.org/2/), 68 bytes
```
lambda n:min((m for m in range(-n*n,n*n+1)if"2">max(`n-m`)),key=abs)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMHiNNuYpaUlaboWN11yEnOTUhIV8qxyM_M0NHIV0vKLFHIVMvMUihLz0lM1dPO08nSAWNtQMzNNyUjJLjexQiMhTzc3QVNTJzu10jYxqVgTalZ_QVFmXolGmoaBpiYXjG2IxDZBYusic8yQNZgicUxROMjKdC2MkHjmBsg8XUMDA6AbIM5asABCAwA)
The requirement to handle negative numbers is annoying.
Pretty naïve brute-force type method.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
LbI.x-
```
[Try it online](https://tio.run/##yy9OTMpM/f/fJ8lTr0L3/39dCyMA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf5@kSr0K3f86/6MNdAx1THR0TXTMdAxNdUyByExH18JIx9zASEfX0MDAIBYA) or [see this step-by-step output](https://tio.run/##Vc2/CsIwEMfx3ac4OqeCTiJIB6diN0dxuNTTHMSk5E/VF/MBfLFoUkRcf3zuvtajZEqpas0QwxoqsXk9m1m1tWYkF4ADBAsIh4Uwx9qhudAJNPtCu39L2KusJRt0jwzkBHZEAwRFMKKOBL22nnx5nEf@ltv5ffL7KIPDvtTPzl5/TMBN8afCvmyOfNTltm5SqlfLNw).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input-integer]
b # Convert each to a binary-string
I # Push the input-integer again
.x # Pop both, and keep the binary-string that's closest to the input
- # Subtract it from the (implicit) input-integer
# (after which the result is output implicitly)
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 22 bytes
```
{(|/49<$x-){-x-x<1}/0}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rWqNE3sbRRqdDVrNat0K2wMazVN6jl4jJMi1FXMFAwVDBR0DVRMFMwNFUwBSIzBV0LIwVzAyMFXUMDAwMAArcOKA==)
-3 bytes thanks to @coltim!
Port of [Arnauld's answer](https://codegolf.stackexchange.com/a/248925/41247).
My first-ever K submission! Been having a lot of fun learning all these APL-esque languages.
---
# [K (ngn/k)](https://codeberg.org/ngn/k), 34 bytes
```
{*a@<a|-a:x-,/-:\.'""/'$+!2,2|^$x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rWSnSwSazRTbSq0NXR17WK0VNXUtJXV9FWNNIxqolTqajl4jJMi1FXMFAwVDBR0DVRMFMwNFUwBSIzBV0LIwVzAyMFXUMDAwMAvYsQgA==)
Wanted to find another approach, but it ended up becoming @Jonah's approach.
## Explanation
Input is *x*.
* `+!2,2|^$x` binary sequences of (length of *x*)+1
* `.'""/'$` join each binary sequence and convert to decimal
* `,/-:\` append negatives
* `x-` subtract *x* from each
* `*a@<a|-a:` absolute minimum
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 193 bytes
```
[S S S N
_Push_0][S N
S _Duplicate_0][T N
T T _Read_STDIN_as_integer][N
S S N
_Create_Label_OUTER_LOOP][S N
S _Duplicate_m][S S S N
_Push_0][T T T _Retrieve_input][S N
T _Swap_top_two][T S S T _Subtract_:_input-m][S N
S _Duplicate_input-m][N
T T S N
_If_neg_jump_to_Label_ABS][N
S S T N
_Create_Label_INNER_LOOP][S N
S _Duplicate_abs(input-m)][N
T S S S N
_If_0_jump_to_Label_PRINT_RESULT][S N
S _Duplicate][S S S T S T S N
_Push_10][T S T T _Modulo_:_abs(input-m)%10][S S S T S N
_Push_2][T S S T _Subtract_:_abs(input-m)%10-2][N
T T S T N
_If_neg_jump_to_Label_CONTINUE_INNER][S N
N
_Discard_top][S S T T N
_Push_-1][T S S N
_Multiply_:_-m][S N
S _Duplicate][N
T T T S N
_If_neg_jump_to_Label_NON_NEG][S N
S _Duplicate][N
T S T S N
_If_0_jump_to_Label_NON_NEG][N
S N
N
_Jump_to_Label_OUTER_LOOP][N
S S S N
_Create_Label_ABS][S S T T N
_Push_-1][T S S N
_Multiply_:_abs(input-m)][N
S N
T N
_Jump_to_Label_INNER_LOOP][N
S S S T N
_Create_Label_CONTINUE_INNER][S S S T S T S N
_Push_10][T S T S _Integer_divide_:_abs(input-m)//10][N
S N
T N
_Jump_to_Label_INNER_LOOP][N
S S T S N
_Create_Label_NON_NEG][S S S T N
_Push_1][T S S T _Subtract_:_-m-1][N
S N
N
_Jump_to_Label_OUTER_LOOP][N
S S S S N
_Create_Label_PRINT_RESULT][S N
N
_Discard_top][T N
S T _Print_to_STDOUT_as_integer]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
Just like [my Java answer](https://codegolf.stackexchange.com/a/248926/52210), this is an iterative port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/248925/52210).
[**Try it online**](https://tio.run/##TY5BCsNADAPP41foA7n0lO@EEEhvhRT6/I1lN21YMNJIa/zZn@/teC3rNoakyEdAtDQBPCSMbJITZfSr4TgHpZ14TfVcx6T/wFeoVoVz/TtOChG3tbow6oy@IfrGFOkYY5ofJw) (with raw spaces, tabs and new-lines only).
**Explanation in pseudo-code:**
```
Integer m = 0
Read STDIN as integer
Start OUTER_LOOP:
Integer t = abs(input - m)
(abs is necessary because of the modulo-10 on negative values)
Start INNER_LOOP:
If t ==0:
Print m as integer to STDOUT
(implicitly stop the program with an error: no exit defined)
Integer p = t modulo-10
If p-2 <0 (thus either 0 or 1):
t = t integer-divided by 10
Continue INNER_LOOP
m = -m
If m <=0:
m = m - 1
Continue OUTER_LOOP
Continue OUTER_LOOP
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 78 bytes
```
p;r;m;f(n){for(r=m=0;r=!r;m=r?m:(m<1)-m)for(p=abs(n-m);p;p/=10)r&=p%10<2;n=m;}
```
[Try it online!](https://tio.run/##XVDbTsMwDH3nK0yloWRLtbRjsJEFHhBfwfZQsnRUkCxKKlEx9dcp7mUVI7KP7GP7KLaKD0o1jRNeGJETS0/50RMvjeTCy2tkpX8yD8RsEhob2hadzN4CsZgJJ9xcJpz6G@kmCd@kwkoj6qawJZissITC6QrwtUSpQxledyDhxBkkDG4ZxOh3mCwZLFvHOF6lDO45QpxwzmsxCujKaVXq/aiBtsC2Ra/TWieJkKwwSNeIZwF1tKEE9Z75KaJWH9r3OtG2ekm31foZfRkx@JsvomEa9wbS/qGwe13hGBdDuIFQfOtjTs6/o/OBmI6MgNms66adWH@S8Syo1p@ma9mJi2rAak5KeslqZMdr/B9zHltyEk32ED8C4iRsLS5WMghs3D1IqXeDbH1VNz8q/8wOoYm/fgE "C (gcc) – Try It Online")
Uses [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s idea from his [Javascipt answer](https://codegolf.stackexchange.com/a/248925/9481) to generate \$m=0,1,-1,2,-2\dots\$
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, ~~73~~ ~~66~~ 62 bytes
```
[ 0 [ 2dup - >dec "-01" ⊂ ] [ dup 1 < 1 0 ? swap - ] until ]
```
A port of @Arnauld's [JavaScript answer](https://codegolf.stackexchange.com/a/248925/97916). Needs modern Factor for [>dec](https://docs.factorcode.org/content/word-__gt__dec,math.parser.html), so no TIO/ATO link. Here's a version that works on TIO for 2 more bytes, though:
[Try it online!](https://tio.run/##PY29CsIwHMT3PsXRPSUpbRUVHMXFRZxKh5D@xWKb1nwgIi6OPqYvUpNFuBvu7gd3lsqNZj4d94fdClcymnoM0l0wGbKkHSzdPGlFNjbOPSbThTYimdedGlvCOkme4BAowApUECXKoApsmWPBczDBOcdrrgNVI2/9BPY/SBkX6ffzRhO2OAlsgjm2sHcZyQZeu65HMw8hZ1A9STP/AA "Factor – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 54 bytes
```
n=>(-n*n to n*n)filter(m=>(n-m+"").max<50)minBy(_.abs)
```
A bit late to the party. All tricks I came up with were already in use by somebody else. However, the `-n*n to n*n` trick by *@pxeger* was new to me, thanks!
[Try it online!](https://tio.run/##bZBRT4MwFIXf@RVHsgeq7cLm0LkMEpe4aHxYgj/AdKMkGCgInW4x@@14BwN88KU9p/3u6b2tdjKVdb79UDuD5/x7Lct1mWerRMvyCHUwSkcVHosCPxYQqRjxAi/awA/ardZ@4Ah9rWFy0MbiJDWqdDI61iK7sW02zuRh6bksS/Tq6LyP5bZiNaV9yZRekFmRqgo@3tSnQ6eA43KX8VZOBjnjt50UMy56c8fFrMc93muP9GDOVO/EfMon887du1Mupg@9FxPXPbdAjlm0xHnZTE9XiS72hlPXBf2XihiWoh@hIfK9IYKmiVv2HHK6VBdlok2q2yGBJIbT4f4QebkFKnvzigVGTQ5EgFFL2xdCpZX6Az@F4Sb8j8eVj1EX3xY3XVmn@hc "Scala – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 57 bytes
[-4 thanks to Neil](https://codegolf.stackexchange.com/questions/248922/how-far-from-binary#comment556309_248963)
```
int@B(int@n,int@m=0)=>$"{n-m}".Max()<50?m:B(n,m<0?-m:~m);
```
[Try it online!](https://tio.run/##Sy7WTS7O/P8/M6/EwUkDRObpgMhcWwNNWzsVpeo83dxaJT3fxAoNTRtTA/tcKyeNPJ1cGwN73VyrulxN6//O@XnF@TmpeuFFmSWpPpl5qRpAXU4aBpq1SprWXDhkDfHKmuCV1cUvbYbfYlO80qYEpPEbrmthhFfe3AC/vK6hgQE03P4DAA "C# (Visual C# Interactive Compiler) – Try It Online")
Kinda abuses the fact that the Visual C# Interactive Compiler mode seems to import System.Linq by default.
A version that doesn't use Linqin 87 bytes
```
int@B(int@n,int@m=0)=>$"{n-m}".IndexOfAny("23456789".ToCharArray())<0?m:B(n,m<0?-m:~m);
```
[Try it online!](https://tio.run/##Sy7WTS7O/P8/M6/EwUkDRObpgMhcWwNNWzsVpeo83dxaJT3PvJTUCv80x7xKDSUjYxNTM3MLSyW9kHznjMQix6KixEoNTU0bA/tcKyeNPJ1cIEs316ouV9P6v3N@XnF@TqpeeFFmSapPZl6qBtBMJw0DzVolTWsuHLKGeGVN8Mrq4pc2w2@xKV5pUwLS@A3XtTDCK29ugF9e19DAABpu/wE "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
;.≜-ẹ~ḃ∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w31rvUecc3Ye7dtY93NH8qGP5///RBjoKhjoKJjoK8UBsBuSY6iiYgjCQHW9hpKNgbgAk4g0NDAxiAQ "Brachylog – Try It Online")
Something less *blunt* seems possible.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
*Edit: bug fixed thanks to Kevin Cruijssen (same bytes)*
```
ḟȯΛεd≠⁰İZ
```
[Try it online!](https://tio.run/##AR8A4P9odXNr///huJ/Ir86bzrVk4omg4oGwxLBa////NzAy "Husk – Try It Online")
```
ḟ # find the first element of
İZ # the infinite sequence of positive & negative integers 0,1,-1,2,-2,3,...
ȯ # that satisfies (composition of 3 functions):
Λ # all of the
d # decimal digits of the
≠⁰ # absolute difference to the input
ε # are at most 1
```
[Answer]
# [J](http://jsoftware.com/), 45 41 40 38 bytes
```
-0{[(]/:|@-/)[:(,-)10#.[:#:@i.2^1+#@":
```
[Try it online!](https://tio.run/##dZDBCoJAEIbv8xRDHlRydFZXs4VACIIgCLpKeYgkg6yDQlDvbnpYg1gHFj7225lh/1s38@0SVwpt9JBR9Yd8XB92m474nTvHQH0yCtxcOR65gi0/V5bKKj88ibmVzVTnwuV8fWCJrEFokBqKkZLxUawp/tFoizTUuOARC8Hcb3lVjW3Dtn62Ddb4V/u2Ge7vwGgsBjElpFlEQGZDESTmFpIgYqOREE@I3iQTwyRQGpqUSKGPx9gULlOgIS/DT7sv "J – Try It Online")
*-4 thanks to Kevin Cruijssen*
This is much longer than a port of Arnauld's answer would have been, but I figured a different conceptual approach might be interesting, and in another language the approach might even be shorter:
Consider 702:
* It's length is 3.
* Generate integers 0... 2^3, in binary:
```
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
```
* Convert them to decimal
```
0 1 10 11 100 101 110 111
```
* Add their negative values too:
```
0 1 10 11 100 101 110 111 0 _1 _10 _11 _100 _101 _110 _111
```
* Also add `10^<length of input> = 1000`
```
0 1 10 11 100 101 110 111 0 _1 _10 _11 _100 _101 _110 _111 1000
```
* Find which of these numbers has the smallest absolute different with the input:
```
1000
```
* Original input minus that.
```
_298
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 53 bytes
```
f=->n,k=0{(n+k).to_s=~/[2-9]/?f.call(n,k<0?-k:~k):-k}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y5PJ9vWoFojTztbU68kP77Ytk4/2kjXMlbfPk0vOTEnRwOowMbAXjfbqi5b00o3u/Z/gQJUxkCTC842RGKbILF1kTlmyBpMkTimKBxkZboWSBxzAyNkKUMDAwPN/wA "Ruby – Try It Online")
Port of [Arnauld's answer.](https://codegolf.stackexchange.com/a/248925/112099)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 15 bytes
```
0λ?εf1>a;₍><⁽ȧ∵
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIwzrs/zrVmMT5hO+KCjT484oG9yKfiiLUiLCIiLCI3MDIiXQ==)
## How?
```
0λ?εf1>a;₍><⁽ȧ∵
‚Çç # Apply both of the following two commands and wrap the results in a list:
> # Increment until lambda returns false...
< # and decrement until lambda returns false.
λ ; # With the following lambda:
?ε # Absolute difference with input
f # List of digits
1>a # Are there any that are greater than 1?
0 # ...starting from 0.
⁽ȧ∵ # Take the minimum of these two by the absolute value.
```
Another 15 byter: `Nṡ:ȧbvṅ⌊$±*-⁽ȧ∵`. In fact, `:ȧbvṅ⌊$±*` is all to create a binary string, but handling negative values.
[Answer]
# [Haskell](https://www.haskell.org), 84 bytes
```
f n=head$filter(all(`elem`"-10").show.(n-))$concat$zipWith(\a b->[a,b])[0,-1..][1..]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN0PSFPJsM1ITU1TSMnNKUos0EnNyNBJSc1JzE5R0DQ2UNPWKM_LL9TTydDU1VZLz85ITS1SqMgvCM0syNGISFZJ07aITdZJiNaMNdHQN9fRio0EExGyoFTCrAA)
[Answer]
# BQN, 29 bytes
```
{'1'<‚åଥ‚Ä¢Fmt|ùï®-ùï©?ùï®ùïä<‚üú1‚ä∏-ùï©;ùï©}‚üú0
```
[Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeycxJzzijIjCtOKAokZtdHzwnZWoLfCdlak/8J2VqPCdlYo84p+cMeKKuC3wnZWpO/Cdlal94p+cMAoK4oCiU2hvd+KImEbCqOKfqAowCjEKNAotNAo2CjE1CjU1CjU2Ci04Mgo3MDIKLTEwMDAK4p+pCkA=)
Port of [Arnauld's answer](https://codegolf.stackexchange.com/a/248925/41247).
[Answer]
# Java 8, ~~69~~ 68 bytes
```
n->{int m=0;for(;!(n-m+"").matches("[01-]+");m=m<0?-m:~m);return m;}
```
Iterative port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/248925/52210), and an additional -1 thanks to *@Arnauld* as well.
[Try it online.](https://tio.run/##PY/BTsMwEETv/YrFp1ixI6dqC4oJHDjTS48hB@O6kBI7VbwpQlH49WCXgrQaaWelN7NHdVb8uP@Ydau8h2fVuHEB0Dg0/UFpA9u4XgzQSVRHZXCmRRCPChsNW3BQzo4/jPFuSyEPXZ/Im8RxmxJCM6tQvxufkErkvE4Jlba09@KR2@LbUtkbHHoHVk6zjNjT8NoG7JV@7po92NAr2WHfuLeqVvS3U0yJiWg8PilvoABnPmPVqh4Fy9mK8RXbsHzN1mE2jN8t2a1YMp4LISZ6gQDsvjwam3UDZqcQgK1L/ogpKV6QpC7T/xa9vj/NPw)
**Explanation:**
```
n->{ // Method with integer as both parameter & return-type
int m=0; // Result-integer, starting at 0
for(;!(n-m+"") // Loop as long as n-m converted to a String
.matches("[01-]+")// contains anything other than just 0s/1s/"-"s
; // After every iteration:
//m=m<0?-m:~m // (iterate to the next `m` in 0,1,-1,2,-2,3,...)
m= // Update the result to:
m<0? // If the result is negative:
-m // Change it to its positive form
: // Else (it's 0 or positive):
~m) // Change it to -m-1 instead
; // After the loop,
return m;} // simply return the result
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 41 bytes
```
Fh,2{W$|1<_M^aAD(h?iv){h?UiDv}}ABi<ABv?iv
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboFS7IKlpSVpuhY3Nd0ydIyqw1VqDG3ifeMSHV00MuwzyzSrM-xDM13KamsdnTJtHJ3KgGIQDVB9S6PNDYxghgAA)
Argh.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 112 bytes
```
$
¶$`
(¶-?)(([01]*)0)?(5*[6-9].*)
$1${3}1$.4$*0
(¶[-01]*)([2-9].*)
$1$.2$*1
\d+
$*
(1*)¶-?\1
-
--
r`(1*)-*$
$.1
```
[Try it online!](https://tio.run/##RcwxCsJAEIXh/p1jhNmRWWbWJGqV0kNsAitoYWMR0onXygFysdXYCK/6@XjTfX48r3XHl1IJ60IFvC7aB@ZsPkqw0HMrudPzGCWAnF6Ht1NsSGyjWX@Mc/qLmEgcw20PErBL2B4Hh0IVmMqWVAgUvVaDo4E26OAt2u866CnhaAnqZvYB "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
$
¶$`
```
Duplicate the input.
```
(¶-?)(([01]*)0)?(5*[6-9].*)
$1${3}1$.4$*0
```
If the second copy has a digit between `6` and `9`, optionally preceded by any number of `5`s, either at the start of the number or after a `0`, then round those `5-9`s away from zero. For example, `-1056` rounds to `-1100`.
```
(¶[-01]*)([2-9].*)
$1$.2$*1
```
Otherwise if it still has a digit of at least `2` then "round it towards zero" (fill with `1`s). For example, `19` rounds to `11`.
```
\d+
$*
```
Convert to unary.
```
(1*)¶-?\1
-
```
Subtract the two numbers.
```
--
```
If we subtracted a more negative number from another, the result is now positive. (This saves a byte over doing it in the decimal conversion.)
```
r`(1*)-*$
$.1
```
Convert to decimal, ignoring any trailing `-`s which result when the first number's absolute value is no less than the second.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
rNBḌ⁸_AÐṂ
```
[Try it online!](https://tio.run/##y0rNyan8/7/Iz@nhjp5HjTviHQ9PeLiz6f/hds3I//8NdBQMdRRMdBR0gdgMyDHVUTAFYSBb18JIR8HcAEjoGhoYGAAA "Jelly – Try It Online")
Absolutely awful...
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
Nθ≔⁰ηW‹1⌈I⁻θη≔⁻‹η¹ηηIη
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05rLsbg4Mz1Pw0BHIQPIK8/IzElV0PBJLS7WUDJU0lHwTazIzC3N1XBOLC7R8M3MKy3WKAQpBQEFqF6IMFhPho6CoSZIHmJcQFFmXglEL1CL9f//5gZG/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @pxeger's Python port of @Arnauld's JavaScript answer.
```
Nθ
```
Input `n`.
```
≔⁰η
```
Start testing with `m=0`.
```
W‹1⌈I⁻θη
```
Repeat while `n-m` contains a digit greater than `1`.
```
≔⁻‹η¹ηη
```
Get the next value of `m` to test.
```
Iη
```
Output the found value of `m`.
31 bytes for an efficient version that uses @Jonah's alternative approach:
```
Nθ≔IE⊕X²Lθ⍘ι²υ≔⁻θ⁺υ±υυI§υ⌕↔υ⌊↔υ
```
[Try it online!](https://tio.run/##Tc3BCsIwDAbgu0/RYwYVZBcPO01BGLgx8Am6LXSFLtvaVH37WieouQR@vvzpR@X6WdkYK1oCN2Hq0MGaFbvSe6MJzsoz1GqBinqHExLjAO38SCqX4oqkeUw@y6Q4KY83doY0GCnyLQu/ptpQ8LBK0dq0gxQNasUI4QvbdMufjyVXNODzzS6GBig7P9uwaSlSk5nC9B9uU8R4PORxf7cv "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `n`.
```
≔IE⊕X²Lθ⍘ι²υ
```
Generate all the base `2` values from `0` to the first value whose length in base `2` exceeds `n`'s length, and interpret the base `2` values as base `10`.
```
≔⁻θ⁺υ±υυ
```
Append the negations of those values, and then subtract all of them from `n`.
```
I§υ⌕↔υ⌊↔υ
```
Output the value with the lowest absolute value.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
-QhaDQ.m-`bT+Uy
```
[Try it online!](https://tio.run/##K6gsyfj/XzcwI9ElUC9XNyEpRDu08v9/CyMA "Pyth – Try It Online") or [Try all test cases](https://tio.run/##K6gsyfiv/F83MCPRJVAvVzchKUQ7tDIwUMHW9f9/Ay5DLhMuXRMuMy5DUy5TIDLj0rUw4jI3MOLSNTQwMAAA "Pyth – Try It Online")
```
-QhaDQ.m-`bT+Uy(QQ)
# Implicitly initialize Q as the input
UyQ # Range from 0 to 2*Q (half-inclusive)
+ Q # Append Q (necessary for the 0 case)
.m # Filter for elements `b` that are minimized by...
-`b # ...the string representation of `b` minus...
T # ... the characters in "10"
aDQ # Sort by absolute difference from Q
h # Take the first element
-Q # Subtract that from Q
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 52 bytes
```
n->k=0;while(n-k&&vecmax(digits(n-k))>1,k=(k<1)-k);k
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYxdCsIwEISvsvShJLALibRaqMkVPICIFG1rSBtCjX9n8aUg4pm8jSn1YXbmW5h5fnw1mH3rx1cD6n0JDRXfzJG2SpS3k-lq5sim6bU-9NWdHU1rwnl6ca4lWsXsWvJIpf13N5X33YM5IA1-MC7EmEyQQMMc5whbgSARMgSKWkbIEfJJMVOxQFiJeEgKIXZ8nh3H2X8)
A port of [@Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/248925/52210).
[Answer]
# [Perl 5](https://www.perl.org/) + `-al060p`, 36 bytes
```
$_="@F"-($\=($\<1)-$\)while/[2-9]/}{
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJF89XCJARlwiLSgkXFw9KCRcXDwxKS0kXFwpd2hpbGUvWzItOV0vfXsiLCJhcmdzIjoiLWFsMDYwcCIsImlucHV0IjoiNzAyIn0=)
## Explanation
A translation of [@Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/248925/9365). `$\` is initialised to `0` via the `-l060` flag and `$_` is set to the original number (stored in `@F` at index `0` via `-a`, interpolated as `"@F"`) with `$\` subtracted, and can then be matched via bare `m//` for digits `2`-`9`.
] |
[Question]
[
Given an integer `n`, find the next number that follows the following requirements:
* The next greater number is a number where each digit, from left to right, is greater than or equal to the previous one. For example, `1455`:
`1<4`
`4<5`
`5<=5`
* The next greater number has to be bigger than `n`
# Testcases
```
10 -> 11
19 -> 22
99 -> 111
321 -> 333
1455 -> 1456
11123159995399999 -> 11123333333333333
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
These numbers make up **[A009994](https://oeis.org/A009994)** - Numbers with digits in nondecreasing order.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
<.o
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/30Yv//9/S8v/UQA "Brachylog – Try It Online") or [Try more cases](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompoe7Omsfbp3w30Yv////aEMDHQVDSx0FSyA2NjIEckxMTWMB "Brachylog – Try It Online")
```
?<.o. # implicit input (?) and output (.)
?<. # the input is smaller than the output
.o. # the output is itself when ordered
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
ḟoΛ≤d→
```
[Try it online!](https://tio.run/##yygtzv7//@GO@fnnZj/qXJLyqG3S////DS0B "Husk – Try It Online")
### Explanation
```
ḟoΛ≤d→
ḟ find the first integer
→ starting from input incremented
o such that composed function
Λ d every digit
≤ is less that or equal to the previous
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
‘DṢƑ$1#
```
[Try it online!](https://tio.run/##y0rNyan8//9RwwyXhzsXHZuoYqj8//9/QxNTUwA "Jelly – Try It Online")
## How it works
```
‘DṢƑ$1# - Main link. Takes n on the left
‘ - Yield n+1
$1# - Starting from n+1, find the first integer after such that:
D - The digits are
Ƒ - Invariant under
Ṣ - Sorting
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~[52](https://codegolf.stackexchange.com/revisions/240764/1)~~ 41 bytes
*9 bytes saved by AZTECCO and 2 bytes saved by xnor*
```
g(a:b)|[a]>b=a<$a:b|1>0=a:g b
g.show.(+1)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P10j0SpJsyY6MdYuyRbItLMDMmsM7QyAnHSFJK4023S94oz8cj0NbUPN/7mJmXm2KflcCgoFRZl5JQoqCmkKhkbGKHwjQ3MUvqWFoYkRqgoQQFVjiaoAjW@Bqvg/AA "Haskell – Try It Online")
Solves all the cases nearly instantly.
# Explanation
The first thing to observe is that:
>
> Find the smallest ascending digit number *greater* than \$n\$.
>
>
>
Is significantly harder than:
>
> Find the smallest ascending digit number *greater or equal to* than \$n\$.
>
>
>
The former has a lot of edge cases around numbers that are themselves ascending in digits while the latter can be solved fairly easily.
But we can turn the latter to the former by just adding 1 before we run our algorithm. If `g` is the function that solves it then we just have `g.show.(+1)` to solve the actual problem.
So I solve the latter first:
```
g(a:b)|[a]>b=a<$a:b|1>0=a:g b
```
This goes along the list until either we meet a pair of digits that is descending (e.g. `21`) or we reach the end. At that point we replace everything left with the digit we just read and exit.
So for example
```
122334555612990
^^
122334555666666
```
---
Here's what the solution looks like without this observation just handling the edge cases naively:
### 92 bytes
```
x!q@(a:b:c)|a>b=a<$q|1>0=(x++[a])!(b:c)
x!"9"=""!x++"1"
x!""="1"
x!y=x++show(1+read y)
f=(""!)
```
[Try it online!](https://tio.run/##ZYtBDoIwEEX3PUU7YdGmG1tNpMQS72FcDAKBiCBgIiTcvbburH81/837Dc73quucW9h45pgV2U1smBcWT8m4qXxn@SLlBa@C8fAjCwMDFoB5DApC9/V7rNazuRneXMmpwpKugtSWe1e4B7a9LQdC6XNq@xdNaE1B6T38Eq2OETGpOujYCok9E0t/JI0n4D4 "Haskell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 35 bytes
```
->x{x.next![x.chars.sort*'']||redo}
```
[Try it online!](https://tio.run/##TYmxDsIgAER3vuKcUFOJgJgw4I80HWhLo4lpG1oTjPjtSJm84fLunX@17zSYdLqFT2CjC@uuDqy7W7@wZfLrkdImRu/66ZtqQvkZnNMqg4YQG2idTVFScEgpy3tRCrmuZXAuJFdaayX1FhTzH0oa5mx3Rz8hhkgAW6GFQWDL/Hysewp6yHbGUNsGxqAlbuzTDw "Ruby – Try It Online")
*-8 thanks to Dingus!*
[Answer]
# [R](https://www.r-project.org/), ~~65~~ 58 bytes
Or **[R](https://www.r-project.org/)>=4.1, 51 bytes** by replacing the word `function` with a `\`.
*Edit: -7 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
function(n){while(any(diff((n=n+1)%/%10^(n:0)%%10)<0))0
n}
```
[Try it online!](https://tio.run/##TYvRCsIwDEXf@xWDUUiQYdOsQsT5KYKoxYJkIMoQ8dtry1S8Tzk5915zHHK86@GWRgXF53ROlxPs9QHHFCOADrogtEtLbge6dmjLhRuH6Iy@coRCbdNtGyJTQGbwvoDI11TFnmZk5trsQ/joPqxMWz5EnimISGCp@a09/ye/AQ "R – Try It Online") [Try it on rdrr.io (for larger test-cases)!](https://rdrr.io/snippets/embed/?code=f%3Dfunction(n)%7Bwhile(any(diff((n%3Dn%2B1)%25%2F%2510%5E(n%3A0)%25%2510)%3C0))0%0An%7D%0Af(10)%23%20-%3E%2011%0Af(19)%23%20-%3E%2022%0Af(99)%23%20-%3E%20111%0Af(321)%23%20-%3E%20333%0Af(1455)%23%20-%3E%201456%0A)
Straightforward brute-force:
1. Increment `n`.
2. Split to digits (with leading `0`s that don't matter).
3. Take differences.
4. If any of the differences is `<0`, loop back to 1. Otherwise, stop and output `n`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
{›Ds≠|
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ74oC6RHPiiaB8IiwiIiwiMTM5NSJd)
```
{ # While...
› # Increment
D # Make three copies
s≠ # Check if sorted
| # Do nothing
```
[Answer]
# [Perl 5](https://www.perl.org/) -p, 26 bytes
```
1while++$_-join'',sort/./g
```
[Try it online!](https://tio.run/##DckxDoAgEATA/t5hQoGoC15xr7EiiiFAgMTfi047xdfIY@C5QvRaT4e5c0hKzS3Xvi7r@d9GEBIhZ0HYmQmAdWARYffm0kNObZgSPw "Perl 5 – Try It Online")
The last test case would take about 194 hours (which is 8 days where I live). So I removed the last five digits from the test case to get the result in 7 sec. For "instant" result, also for the last big test case, this is a 78 byte suggestion: `$_++;s/(@{[join"|",map$_."[0-".($_-1)."]",1..9]}).*/substr($1,0,1)x length$&/e` [...try it online!](https://tio.run/##VcfdCsIgGADQe58iRMI1/76ZFx/d9B5jSIHUhm0yDYLq1TO67NydFNboamW@bQ9Z8@Ozn5Zxpi8qbqfEvKK9kVRx5iU0ig5UgFI4vBu10/l@zmXlDIQR0Dw2McyXcmVbHWoFQwAJIrEdENg7RwCgs@AQ0dm/4M9nSWVc5lxlil8 "Perl 5 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 48 bytes
```
i;f(n){for(i=++n;n=n%10<n/10%10?++i:n/10;);i=i;}
```
[Try it online!](https://tio.run/##NY3BbsIwDIbveQqrUlGiFi1uWkYI2W57gt22HVCgmyUwVVfEAbFX75JW@OLfnz7bYfkdwjiSayWrW3vuJfmiYMeec9RbfkId@2tR0CZlpxx5cveReIDTjlgquAlIE3FXwvkydE7A9YeOB5B/v2HHrczyPSxfIN9nJSwmbZE8pQRA18fdWfE@KiDzoD45mq2MqppPlpC9vWcfM0pigl8qfuoPw6Vn0E7cR9TpDaJAm0JVCWtnEpHGRzTVFI0xAuummXDdrIRdP2NlVk2diH3UPw "C (gcc) – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), ~~34~~ 31 bytes
```
~x=issorted("$(x+=1)") ? x : ~x
```
[Try it online!](https://tio.run/##PYtBCoMwFET3OcUgXURqS39SCxZiu@0xIqaQIlGSFLLy6tYodFbvv5n/@Q5WU1qWOSkbwuij6Xlx4OmoqCxKPJBwx5yW9@gxWGdgHbzRfebAS4Y1uuqgMGkfzJm/XKwQpsFGnjcVCpxaFOU@nbx1cXBcQ7WY9S6fOgTj43pDKXTMuH6hS34jYtRkEII1zW6ISUEZpZSMrnW96Wt9Y2snJNXNfynklh8 "Julia 1.0 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 49 bytes
```
f=lambda n:-~n*(list(`-n`)<sorted(`~n`))or f(-~n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY1BDoIwEEX3PUXDamrAOC011ohn8AaAEWITLA2UEDdexA0b45m8ja244K_-_Hl_5vm2d3dtDZ-m1-DqZPfBOmvK2_lSUrNPHmYFje4dFIkp2KFvO1ddoHj4gbUdrcET7F88jVfdVBT3hOq4zW6lBW1c3JVjro0dHLB1bxvtIKLJkUaMEWo7T4Cn4xp0CPJsgc93p0-Om9BAJARVcJwTotSc-VBwDF4I4YFUyt8ilVs_IXKBUiklhQr6d7hYav7zBQ)
Brute force: increments the given number until it is great. Unsurprisingly, chokes on the larger test case.
#### [Python](https://www.python.org), 77 bytes
```
f=lambda n,t=1:(n:=n+t)*([*str(n)]<=sorted(str(n)))or 10*(g:=f(n//10,0))+g%10
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TU1LbsIwEN37FBZSpXEwxWPjCkeYNZueoKpQEAQsBcdKjKqepZts4E7cpnaTRd_q_ebNzyN8x0vrh-F-i_Vi_XyvbVNdD8eKeh4tluBL6-eRFfBR9LEDzz43tm-7eDrCqBlrO4qigHNpa_DLJQouGJufX1BMo7uvi2tOFEtCHW_ttQrgfOTOh1sE9tqHxkWY0cWWzhgjNHQphdTkNbhs7O1UHfeG5x5FbiMSgiYzKQkxZvSSqSRmrpRKhZXWf8FKvyWFKBVqY4xWJmO6keo_xj-_)
This constructs the result directly. Handles all test cases.
[Answer]
# [Python 3](https://docs.python.org/3/), 84
```
f=lambda n:n+1if all(int(i)<=int(j)for i,j in zip(str(n+1),str(n+1)[1:]))else f(n+1)
```
Fails on the last case due to exceeding the maximum recursion depth.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~59~~ 48 bytes
```
f(n,t){t=++n?t=f(n/10-1),10*t+t%10:0;n=t>n?t:n;}
```
[Try it online!](https://tio.run/##LY1BCsMgEEXX9RQSCGg1RJO6MNb0IG0WxdTioqaks2rI2dMJdDGf/3h8JlTPELYtsiyBL@CFyBfwiLVWleZSqyMIKLXqlMseerRdduv2uqfM@EJSBgrhOviFaCWJtpJYvLbRCCdjMJtWG2taS1ZH4jRTtm@SV44meqaf9H1MkUHg9b@i5uiE4OTwnpEiK0o70qqn5XjLhcR/aZB0H2Hh3JF1@wE "C (gcc) – Try It Online")
```
f(n,t){
t=++n // increment input
? t=f(n/10-1), // recurse on prefix
10*t+t%10 // and append its last digit
: 0; // (base case =0)
n=t>n?t:n; // max of above and input
}
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 48 bytes
Very simply iterates through numbers starting from the input until a number equals the sorted string representation of itself, then returns that number.
```
param($n)for(;++$n-ne-join("$n"|% T*y|sort)){}$n
```
[Try it online!](https://tio.run/##TY1dS8MwFIbv@yvCyCRxKZh2E0sJFIYXXinOO5FR6yludElNUlTa/vaaplV3Lg6H9@M5tfoEbd6hqgZcinaoc52fCJa0VJqkqxWWoYTwqA6SLLBcdEv0dPndGaUtpW2P5dAH2IKx29yAERnJCL9inFPmjoRF0XgkiVO8FEecxXHs3fVmw9y69okbvo5YMg6lZ0DUoWUbIDf4IOvGMoThq4bCwhsSCO8nS4NpKuuEC1zOwckwTVGAMWN0zoTw8Y/woeeH3bYxVp3uX49OfcnauxEgJk766Hti7qe3c1X8QdLd9ET8fuuDfvgB "PowerShell – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 67 bytes
```
T`9d`d`.9*$
^0
10
.
$*_¶
+`((_+¶)(?!_*\2)(_*¶)*)_*¶$
$2$1
(_+)¶
$.1
```
[Try it online!](https://tio.run/##FYsxCsMwEAT7/UXgAtIZhFeKiqtS5gMpQ3QBp0iTIuRtfoA/JsvbDAOzv/f/8331c7h5v7stvngyFTxncEaCaNtWTB5Cm7Y1huup6SPH0HSYxgMCyUKMII5UEnsfVxrMUDLBS60gmQurmdVix3Y "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`9d`d`.9*$
```
Increment the input.
```
^0
10
```
Deal with any carry.
```
.
$*_¶
```
Convert each digit to unary.
```
+`((_+¶)(?!_*\2)(_*¶)*)_*¶$
$2$1
```
Propagate the first digit greater than its successor to the end of the number. E.g. `11123159995400000`, `11123315999540000`, `11123331599954000`, ... `1123333333333331`, `1123333333333333`.
```
(_+)¶
$.1
```
Convert the digits back to decimal.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
≔I⊕Nθ…θ⌕Eθ›ι§θ⊕κ¹×⁻Lθⅈ§θⅈ
```
[Try it online!](https://tio.run/##TYwxC4MwEIX3/grHC9ghFYfQSYQWoZYOHbqm8dBQPTWJpf31aSIUvOHxeHz3qU4aNcre@8Ja3RKU0jqoSBkckBw2oU@Luy7DEw0wxtJkZsfdzWhyUH5Vj2U3TjCnyUlTA7Vc@9mgdIHXaVK4ihr8xHVrfbHVxUP@bXc9oIVa02LhgtS6DuaAPCCCG00cwpf3nPNDxnMhRJ6JeH7/7n8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔I⊕Nθ
```
Input `n`, increment it, and turn it into a string.
```
…θ⌕Eθ›ι§θ⊕κ¹
```
Print the prefix up to the first digit that is greater than its subsequent digit. (There is an edge case here when all the digits are equal but the remaining code will just fill with that digit because it has no other choice.)
```
×⁻Lθⅈ§θⅈ
```
Fill the rest of the string with that digit.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
È-ìn}fUÄ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yC3sbn1mVcQ&input=MzIx)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
)∙▒sy=▼
```
Port of [my 05AB1E answer](https://codegolf.stackexchange.com/a/240767/52210).
[Try it online.](https://tio.run/##y00syUjPz0n7/1/zUcfMR9MmFVfaPpq25/9/QwMuQ0suS0suYyNDLkMTU1MuQ0NDI2NDU0tTAA)
**Explanation:**
```
▼ # Do-while false with pop:
) # Increase the current integer by 1
# (which will be the implicit input in the first iteration)
∙ # Triplicate it
▒ # Convert the top copy to a list of digits
s # Sort those digits
y # Join it back together to an integer
= # Check if the sorted integer is still the same as the triplicated integer
# (after the do-while loop, output the entire stack implicitly as result)
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 8 bytes
```
T$<=Ua_a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhYrQlRsbEMT4xMhXKjosmhDE2OLWCgPAA)
### Explanation
```
; a is command-line argument
T ; Loop till
Ua ; Increment a, and
$ ; Fold on
<= ; Less-than-or-equal
; is true:
_ ; No-op
a ; After the loop, autoprint the modified value of a
```
Folding a number such as `1455` on `<=` is the equivalent of computing `1 <= 4 <= 5 <= 5`, which (thanks to Pip's chaining comparison operators) is equivalent to `(1 <= 4) & (4 <= 5) & (5 <= 5)`.
---
Here's a **19-byte** version that can handle the largest test case:
```
O@Ua{y?ya>b?Yab}MPa
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhab_R1CE6sr7SsT7ZLsIxOTan0DEiEyMAXRhoaGRsaGppaWlqbGliAQC5UCAA)
```
O@Ua{y?ya>b?Yab}MPa
Ua ; Increment a
@ ; Get its first digit
O ; Output it without a newline
{ }MPa ; Map this function to each pair of adjacent digits in a:
y? ; Has y been assigned yet?
y ; If so, use that as the next digit
a>b? ; Otherwise, is the first digit of the pair greater than
; the second digit of the pair?
Ya ; If so, assign the first digit to y and use that
b ; Otherwise, use the second digit
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[>Ð{Q#
```
[Try it online](https://tio.run/##yy9OTMpM/f8/2u7whOpA5f//jY0MAQ) or [verify almost all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/aLvDE6oDlf/X6vyPNjTQMbTUsbTUMTYy1DE0MTXVMTQ0NDI2NLU0jQUA) (except for the last one, which is shortened a bit).
**Explanation:**
```
[ # Loop indefinitely:
> # Increase the current value by 1
# (which will be the implicit input in the first iteration)
Ð # Triplicate it
{ # Sort the digits in the top copy
Q # Pop it and another copy and check if they're still the same
# # If it is: stop the infinite loop
# (after which the remaining third value is output implicitly as result)
```
---
Here a different approach which also handles the largest test case (**14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**):
```
>Dü›Å¡ćJs˜¬s∍«
```
[Try it online](https://tio.run/##yy9OTMpM/f/fzuXwnkcNuw63Hlp4pN2r@PScQ2uKH3X0Hlr9/7@hoaGRsaGppaWlqbElCAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLfzuXw3seNew63Hpo4ZF2r@LTcw6tKX7U0Xto9X@d/9GGBjqGljqWljrGRoY6hiampjqGhoZGxoamlgiWpaWpsSUIxAIA).
**Explanation:**
```
# E.g. input = 11123159995399999
> # Increase the (implicit) input-integer by 1
# STACK: 11123159995400000
D # Duplicate it
# STACK: 11123159995400000,11123159995400000
ü # For each overlapping pair of digits:
› # Check if the first is larger than the second
# STACK: 11123159995400000,[0,0,0,0,1,0,0,0,0,1,1,1,0,0,0,0]
Å¡ # Split the (implicit) input-integer at the truthy positions
# STACK: [[1,1,1,2],[3,1,5,9,9],[9],[5],[4,0,0,0,0,0]]
ć # Extract head; pop and push first list and remainder-lists
# separated to the stack
# STACK: [[3,1,5,9,9],[9],[5],[4,0,0,0,0,0]],[1,1,1,2]
J # Join this first list together to a single integer
# STACK: [[3,1,5,9,9],[9],[5],[4,0,0,0,0,0]],1112
s # Swap to get the remainder-list
# STACK: 1112,[[3,1,5,9,9],[9],[5],[4,0,0,0,0,0]]
˜ # Flatten it
# STACK: 1112,[3,1,5,9,9,9,5,4,0,0,0,0,0]
¬ # Push its first digit (without popping the list)
# STACK: 1112,[3,1,5,9,9,9,5,4,0,0,0,0,0],3
s # Swap so the list is at the top
# STACK: 1112,3,[3,1,5,9,9,9,5,4,0,0,0,0,0]
∍ # Extend this digit to the length of this list
# STACK: 1112,3333333333333
« # Append the two strings together
# STACK: 11123333333333333
# (after which the result is output implicitly)
```
[Answer]
**APL 16~~12 16~~ bytes**
~~New Approch~~
`10⊥⌈/\⍎¨⍕1∘+`
It's just a append scan and then maximum of each cell
doesnt work in case idetified by @ova
`1∘+⍣{∧/2≤/⍎¨⍕⍺}`
Explanation
`1∘+` adds 1
`{∧/2≤/⍎¨⍕⍺}` checks weather each number is bigger than the one preceding it
`1∘+⍣{∧/2≤/⍎¨⍕⍺}` continously adds 1 untill the previous function returns true i.e. A fixed point function
[Answer]
# [Desmos](https://desmos.com/calculator), ~~159~~ ~~155~~ 149 bytes
The code below supports all integers, with negative integers supported as described in [Jonathan Allan's comment](https://codegolf.stackexchange.com/questions/240743/next-greater-number#comment543290_240743).
```
o->T(o+1-sign(o-c)min(1-sign(L-sort(L))^2)),c->T(c)
i=0
o=0
c=0
s=sign(o)
a=abs(o)
L=smod(floor(a/10^{[floor(log(a+1-ss))...0]}),10)
T(n)=\{i=c:n,i\}
```
[Try It On Desmos!](https://www.desmos.com/calculator/kudyekaxyp?nographpaper)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/zmxjxzptrn?nographpaper)
This uses a variable `c` to cache the input so that changes in the input can be detected (with the function `T(n)`), causing the rest of the program to react accordingly (That is why the program won't break if the input is changed while the ticker is still running).
The byte count can actually be lowered significantly if some liberties (A.K.A. removing the caching variable) can be taken with the I/O method:
### ~~127~~ ~~123~~ 117 bytes, with modified I/O method
```
o->o+1-sign(o-i)min(1-sign(L-sort(L))^2)
i=0
o=0
s=sign(o)
a=abs(o)
L=smod(floor(a/10^{[floor(log(a+1-ss))...0]}),10)
```
[Try It On Desmos!](https://www.desmos.com/calculator/r1mmsvewf8?nographpaper)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/ifq2b6tpfy?nographpaper)
This version removes the caching variable `c` and the function `T(n)` completely, which means that the code cannot detect any changes in the input. This means that extra steps have to be taken in order to enter in or change the input and run the code.
I'm not too sure which I/O method is considered the "accepted" version, so I'm putting both.
Also, it's unclear whether or not we have to support negative integers. If we only have to support non-negative integers or positive integers, the code can be shortened even more (the code below uses the caching variable):
### ~~140~~ 134 bytes, supports all non-negative integers
```
o->T(o+1-sign(o-c)min(1-sign(L-sort(L))^2)),c->T(c)
i=0
o=0
c=0
L=mod(floor(o/10^{[floor(log(a+1-sign(o)))...0]}),10)
T(n)=\{i=c:n,i\}
```
[Try It On Desmos!](https://www.desmos.com/calculator/wjnb18vjnj?nographpaper)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/z6px5jlecv?nographpaper)
### ~~128~~ 122 bytes, supports positive integers
```
o->T(o+1-sign(o-c)min(1-sign(L-sort(L))^2))),c->T(c)
i=1
o=1
c=0
L=mod(floor(o/10^{[floor(logo)...0]}),10)
T(n)=\{i=c:n,i\}
```
[Try It On Desmos!](https://www.desmos.com/calculator/kty7afvsl8?nographpaper)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/dgavfbyqsg?nographpaper)
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 95 bytes
```
(load library
(d F(q((N)(i(e N(from-base 10(merge-sort(to-base 10 N))))N(G N
(d G(q((N)(F(a N 1
```
[Try it online!](https://tio.run/##NcsxDsMgFIPhvafw6AyRStMMXCBs7w5EoRUSlBRYcnpCpcbjL3/Vf47gy94aQ7Ibgl@zzceNGxZ@SRno6SB85RTH1RYHdWd0@e3GknJlTVeFDH1CA/lx8@cLLQSqMdodBr32q9LQGtNDQT3nubN2Ag "tinylisp – Try It Online")
-3 from dlosc
`merge-sort` is shorter than `insertion-sort`. Surprisingly there's no plain sort alias. Since variable assignment is global, i've resorted to using `(+ n 1)` everywhere.
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 49 bytes
```
[ [ 1 + dup present [ <= ] monotonic? ¬ ] loop ]
```
[Try it online!](https://tio.run/##PYw5DsIwFAX7nOL1SBEGUphFlIiGBlFZKazkEyJif@OlQIgbcQouZgIF5WhGc9ZNZJ9Px/1ht4TR8YIreUsDnKdANqLznFxvu58sk@0bbgmBbolsQ@HbxXh3vh/bVVE8IKYQElJiPhMQi6rCMysoCEzQJvcfK6w3qGHYcuRxu8X7NfLA7FBnox3K/AE "Factor – Try It Online")
Add 1. If the string representation of the number isn't sorted, repeat.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 39 bytes
```
a->until(vecsort(d=digits(a))==d,a++);a
```
[Try it online!](https://tio.run/##FYrLCoAgEAB/ZemkpJA9DhH2I9FhyYqFqEUt6OvNDgMzMIye9M5pA5tQj/cZ6RDPuoTLR@Gso51iECiltU5hWcoBEzIfr0DQI7CnM2Yt/ihg@08Fk6kUmF5Bn2lqk6PtulmmDw "Pari/GP – Try It Online")
[Answer]
# APL+WIN, 48 bytes
Prompts for integer
```
n←⍴v←⍎¨⍕⎕+1⋄10⊥⌽((n-⍴v)⍴¯1↑v),⌽v←(^\0≤1,-2-/v)/v
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlCGIFBIBY5lyPOtrT/ucB2Y96t5SBqb5DKx71TgUq0TZ81N1iaPCoa@mjnr0aGnm6ICWaQOLQesNHbRPLNHWA4iA9GnExBo86lxjq6Brp6pdp6pf9B5rK9T@Ny9CAC0hYAglLEGFsZAjim5iagihDQyNjQ1NLS0tTY0sQwCIGAA "APL (Dyalog Classic) – Try It Online")
The final example throws an error in the final digit in Dyalog Classic on TIO. Dropping the last digit of that example gives the expected result.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 39 bytes
```
f=n=>(p=[...++n+''])+''>p.sort()?f(n):n
```
[Try it online!](https://tio.run/##DcRBCoMwEEDR/VzEGZIOpq0LhdiDiItgTWmxM8GEXj8N/P8@4Rfydr5TuYg@9xp9S/yMyS/MbIyYrlupMSfOehakR0ShSWrxC7jeghstjG3XOwu3a8Pdh8HCCptK1mPnQ19Y@BsSRqL6Bw "JavaScript (Node.js) – Try It Online")
Fixed tsh's answer
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 14 bytes
```
1[p`sSaJlf=!]p
```
[Try it online!](https://tio.run/##y6n8/98wuiChODjRKyfNVjG2AMg3MTUFAA "Ly – Try It Online")
This is a pretty straightforward iterative take on the question. It splits the number into digits, sorts them, collapses back to a number, and compare that to the original. The loop ends when the digits are sorted.
```
1 - push a '1' to start the loop
[p ] - loop until the top of the stack is '0'
` - increment the current var (first time reads STDIN)
s - save number to backup cell
S - split the number into digits
a - sort the stack
J - recombine the digits into a number
l - pull the number from the backup cell
f - flip the top two entries of the stack
= - compare the original and sorted digits
! - negate result of comparison
p - delete iterator var, leaves the answer on the stack
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 38 bytes
```
$_++;s/./$t||($&<$`%10?$t=$`%10:$&)/ge
```
[Try it online!](https://tio.run/##K0gtyjH9/18lXlvbulhfT1@lpKZGQ0XNRiVB1dDAXqXEFsywUlHT1E9P/f/fxNjQ6F9@QUlmfl7xf11fUz0DQ4P/ugUA "Perl 5 – Try It Online")
It's a little longer than @KjetilS' [answer](https://codegolf.stackexchange.com/a/240761), but it has the advantage of being nearly "instant" for any number. Its runtime is based on the length of the number rather than the value. For really big numbers, `-Mbigint` should be added to the command line flags.
[Answer]
# [Raku](https://raku.org/), 27 bytes
```
{first {[<=] .comb},$_^..*}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Oi2zqLhEoTraxjZWQS85PzepVkclPk5PT6v2f3FipYKSSryCrZ1CdZqCSnytkkJafpGCoYGOgqGljoIlEBsbGQI5Jqam/wE "Perl 6 – Try It Online")
* `$_ ^.. *` is the infinite sequence of numbers starting with, but not including (thanks to the `^`), the input number `$_`.
* `first { ... }, ...` returns the first number in that sequence for which the brace-delimited anonymous function returns a true value.
* `.comb` splits the input number into its individual digits.
* `[<=]` reduces the digits with the `<=` operator. It's equivalent to `digit₁ <= digit₂ <= ... <= digitₙ`.
] |
[Question]
[
# Challenge
Here's a simple one.
Write a function or program when given a number in base 10 as input, it will return or print that number's value in [Hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal "Hexadecimal - Wikipedia").
# Examples
```
15 -> F
1000 -> 3E8
256 -> 100
```
# Rules
* No built-in Hexadecimal functions whatsoever
* Letters may be lowercase or uppercase
* You will only need to worry about non-negative integers, no negatives or pesky decimals
* It should work with any arbitrarily large number up to language's default type's limit.
* Newline not mandatory
* As usual, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code measured in bytes wins!
[Answer]
# Turing Machine Code, 412 bytes
As usual, I'm using the rule table syntax defined [here.](http://morphett.info/turing/turing.html) You can test it on that site or, alternatively, using [this java implementation.](https://github.com/SuperJedi224/Turing-Machine)
```
0 * * l B
B * * l C
C * 0 r D
D * * r E
E * * r A
A _ * l 1
A * * r *
1 0 9 l 1
1 1 0 l 2
1 2 1 l 2
1 3 2 l 2
1 4 3 l 2
1 5 4 l 2
1 6 5 l 2
1 7 6 l 2
1 8 7 l 2
1 9 8 l 2
1 _ * r Y
Y * * * X
X * _ r X
X _ _ * halt
2 * * l 2
2 _ _ l 3
3 * 1 r 4
3 1 2 r 4
3 2 3 r 4
3 3 4 r 4
3 4 5 r 4
3 5 6 r 4
3 6 7 r 4
3 7 8 r 4
3 8 9 r 4
3 9 A r 4
3 A B r 4
3 B C r 4
3 C D r 4
3 D E r 4
3 E F r 4
3 F 0 l 3
4 * * r 4
4 _ _ r A
```
Counts down from the input in base 10 while counting up from 0 in base 16. On decrementing zero, it erases the input block and terminates.
[Answer]
# Java, ~~92~~ 89 bytes
```
String x(int v){String z="";for(;v>0;v/=16)z="0123456789ABCDEF".charAt(v%16)+z;return z;}
```
[Answer]
# Javascript, ~~49~~ 43 bytes.
```
h=i=>(i?h(i>>4):0)+"0123456789abcdef"[i%16]
```
6 bytes saved by [user81655](https://codegolf.stackexchange.com/users/46855/user81655).
Test it [here](https://jsfiddle.net/g1smkay1/).
This has two leading zeroes, which is allowed by the rules.
Here's a version without leading zeroes: (47 bytes).
```
h=i=>(i>15?h(i>>4):"")+"0123456789abcdef"[i%16]
```
Test it [here](https://jsfiddle.net/y2drn9qv/).
Both of these uses exactly the same approach as my [Python answer](https://codegolf.stackexchange.com/a/68249/34543).
[Answer]
# CJam, ~~22~~ 21 bytes
```
ri{Gmd_A<70s=+\}h;]W%
```
*Thanks to @MartinBüttner for golfing off 1 byte!*
[Try it online!](http://cjam.tryitonline.net/#code=cml7R21kXzk-eyc3K30mXH1oO11XJQ&input=MTAwMA)
### How it works
```
ri e# Read an integer from STDIN.
{ }h e# Do:
Gmd e# Push qotient and residue of the division by 16.
_A< e# Check if the residue is less than 10.
70s e# Push "70".
= e# Select the character that corresponds to the Boolean.
+ e# Add the character to the digit.
e# This way, 10 -> 'A', etc.
\ e# Swap the quotient on top of the stack.
e# While the quotient is non-zero, repeat the loop.
; e# Pop the last quotient.
]W% e# Reverse the stack.
```
[Answer]
# Pyth, 33 26 21 20 bytes
This was a fun one.
```
sm@+jkUTGi_d2_c_.BQ4
```
[Try it online.](http://pyth.herokuapp.com/?code=sm%40%2BjkUTGi_d2_c_.BQ4&input=11259375&debug=0)
Explained:
```
.BQ Convert input to a binary string, e.g. 26 -> '11010'
_c_ 4 Reverse, chop into chunks of 4, and reverse again. We reverse
because chop gives a shorter last element, and we want a shorter
first element: ['1', '0101']
Reversing three times is still shorter than using .[d4 to pad the
binary string to a multiple of 4 with spaces.
m Map across this list:
i_d2 Take the value of the reversed string in binary,
@ and use it as an index into the string:
+jkUTG '0123456789abcdefghijklmnopqrstuvwxyz'
(The alphabet appended to the range 0 to 10)
s Concatenate to create the final string.
```
[Answer]
# C (function), 51
Recursive function takes input integer as a parameter:
```
f(n){n>>4?f(n>>4):0;n&=15;n+=n>9?55:48;putchar(n);}
```
### Test driver:
```
#include <stdio.h>
f(n){if(n>>4)f(n>>4);n&=15;n+=n<10?48:55;putchar(n);}
int main (int argc, char **argv) {
f(15);puts("");
f(1000);puts("");
f(256);puts("");
f(0);puts("");
return 0;
}
```
[Answer]
# Python, ~~59~~ 58 bytes
```
h=lambda i:(i>15 and h(i/16)or'')+"0123456789abcdef"[i%16]
```
1 byte saved by [CarpetPython](https://codegolf.stackexchange.com/users/31785/carpetpython)
Run as: `print h(15)`
Test it [here](http://ideone.com/fork/TnwsF4) (Ideone.com).
Explanation:
```
h=lambda i: # Define h as a function that takes two arguments
(i>15 and h(i/16)or'') # Evaluate h(i/16) if i > 15, else, give ''
+"0123456789abcdef"[i%16] # Append (i%16)'th hexadecimal number.
```
[Answer]
## Haskell, ~~59~~ ~~58~~ ~~43~~ ~~41~~ 39 bytes
```
s="0123456789ABCDEF"
(sequence(s<$s)!!)
```
Usage example: `sequence(s<$s)!!) $ 1000` -> `"00000000000003E8"`.
This creates a list of all hexadecimal numbers up to 16 hex-digits. Luckily this happens in order, so we can simply pick the `n`th one.
Edit: @Mauris squeezed out 2 bytes. Thanks!
[Answer]
# [APL (Dyalog APL)](https://www.dyalog.com/), 17 bytes
Must be run with `‚éïIO‚Üê0`, which is default on many APL systems.
```
(⎕D,⎕A)[16⊥⍣¯1⊢⎕]
```
[Try it online!](https://tio.run/nexus/apl-dyalog#e9Q31dP/UdsEA65HHe1p/zUe9U110QESjprRhmaPupY@6l18aL3ho65FQLHY/0A1/9O4DE25gISBgQGQMjI1AwA "APL (Dyalog APL) – TIO Nexus")
`(⎕D,⎕A)[`…`]` **D**igits concatenated to **A**lphabet, then indexed by…
`16⊥⍣¯1` the inverse of 16-Base-to-Number, i.e. Number-to-Base-16
`⊢` applied to
`‚éï` numeric input
[Answer]
# dc, 37
```
?[16~rd0<m]dsmxk[A~r17*+48+Pz0<p]dspx
```
Recursively divmods by 16, pushing the remainder to the stack until nothing left to divide. Then print each element of the stack, using divmod by 10 to achieve A-F digits. Probably more detail tomorrow... (and hopefully less bytes).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~45~~ 44 bytes
```
f(n){n&&f(n/16);n%=16;putchar(n+48+n/10*7);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOk9NDUjrG5ppWuep2hqaWReUliRnJBZp5GmbWGgDJQy0zDWta//nJmbmaWhWK6RpmJmYG1toWivU/gcA "C (gcc) – Try It Online")
[Answer]
# Bash (function), 62
Thanks to @manatwork for suggesting using recursion.
```
h()(x=({0..9} {A..F})
echo `(($1>15))&&h $[$1/16]`${x[$1%16]})
```
[Answer]
# [Perl 6](http://perl6.org), ~~ 53 ~~ 48 bytes
```
~~{[R~] (0..9,'A'..'F').flat[($\_,\*div 16...^0)X%16]||0}~~
{[R~] (0..9,'A'..'F').flat[.polymod(16 xx*)]||0}
```
This creates a sequence of values that are Integer divided (`div`), until the result is `0` excluding the `0` from the sequence
```
$_, * div 16 ...^ 0
```
It then crosses (`X`) that sequence using the modulus operator (`%`) with `16`
```
( … ) X[%] 16
```
It uses those values as indexes into a flattened list consisting of two Ranges `0..9` and `'A'..'Z'`
```
( 0 .. 9, 'A' .. 'Z' ).flat[ … ]
```
Finally it concatenates (`~`) them using the reverse (`R`) meta operator
```
[R[~]] …
```
If that results in a False value (empty string), return `0`
```
… || 0
```
---
Usage:
```
# (optional) give it a lexical name for ease of use
my &code = { … }
say <15 1000 256 0>.map: &code;
# (F 3E8 100 0)
say code 10¹⁰⁰;
# 1249AD2594C37CEB0B2784C4CE0BF38ACE408E211A7CAAB24308A82E8F10000000000000000000000000
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 27 bytes
```
i`16H#\wt9>?7+]wt]xN$hP48+c
```
This uses [release 5.1.0](https://github.com/lmendo/MATL/releases/tag/5.1.0) of the language/compiler, which is earlier than this challenge.
### Example
```
>> matl
> i`16H#\wt9>?7+]wt]xN$hP48+c
>
> 1000
3E8
```
### Explanation
```
i % input number
` % do...
16H#\ % remainder and quotient of division by 16
w % move remainder to top of stack
t9> % does it exceed 9?
? % if so
7+ % add 7 (for letter ASCII code)
] % end if
w % move quotient back to the top
t % duplicate
] % ...while (duplicated) quotient is not zero
x % delete last quotient (zero)
N$h % create vector of all remainders
P % flip vector
48+c % add 48 and convert to char (will be implicitly displayed)
```
[Answer]
# ùîºùïäùïÑùïöùïü, 31 chars / 62 bytes
```
↺a=⬯;ï;ï≫4@a=⩥ḊĀⒸª⩥⁽ṁṇ⸩⨝[ï%Ḑ]+a
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=256&code=%E2%86%BAa%3D%E2%AC%AF%3B%C3%AF%3B%C3%AF%E2%89%AB4%40a%3D%E2%A9%A5%E1%B8%8A%C4%80%E2%92%B8%C2%AA%E2%A9%A5%E2%81%BD%E1%B9%81%E1%B9%87%E2%B8%A9%E2%A8%9D%5B%C3%AF%25%E1%B8%90%5D%2Ba)`
Okay, I figured out some more stuff that golfed it down.
# Explanation
It's essentially the same solution as @SuperJedi224's ES6 solution - but with something different.
See `⩥ḊĀⒸª⩥⁽ṁṇ⸩⨝`? That's a really fancy way of writing `"0123456789ABCDEF"`. `⩥Ḋ` creates a range from 0 to 10, `Ⓒª⩥⁽ṁṇ⸩` creates a range from 65 to 71 and converts it to a string of ASCII, and `Ā...⨝` concatenates the two ranges and joins them into one string. This was probably the coolest part of my solution.
# Bonus non-competitive version, 24 chars / 45 bytes
```
↺;ï;ï≫4@ᵴ=(⩥Ḋ⨝+ᶐ)[ï%Ḑ]+ᵴ
```
I decided to add an alphabet string, like in Pyth.
[Answer]
# sed, 341 bytes
```
:
s/\b/_/2
s/[13579]/&;/g
y/123456789/011223344/
s/;0/5/g
s/;1/6/g
s/;2/7/g
s/;3/8/g
s/;4/9/g
s/;_;_;_;_/=/
s/;_;_;__/+/
s/;_;__;_/:/
s/;_;___/>/
s/;__;_;_/</
s/;__;__/?/
s/;___;_/(/
s/;____/*/
s/_;_;_;_/-/
s/_;_;__/^/
s/_;__;_/%/
s/_;___/$/
s/__;_;_/#/
s/__;__/@/
s/___;_/!/
s/____/)/
/[1-9_]/b
y/)!@#$%^-*(?<>:+=/0123456789ABCDEF/
s/^0*//
```
It's not the obvious language for this challenge, but it does have the advantage of supporting input numbers up to (depending on your implementation) between 4000 digits and the limit of your system's available (virtual) memory. I converted RSA-1024 to hex in about 0.6 seconds, so it scales reasonably well.
It works using successive division by two, accumulating every 4 bits of carry into a hex digit. We use non-letter characters to represent our output, so that we always accumulate carry between the decimal input and the hex output, and convert to conventional hexadecimal at the very end.
[Answer]
# PHP, ~~65 66 64+1 62~~ 59 bytes
```
function h($n){$n&&h($n>>4);echo"0123456789abcdef"[$n&15];}
```
recursive printing function, prints a leading zero (insert `>16` before `&&` to remove it)
---
programs, 64 bytes +1 for `-R` (run as pipe with `-nR`)
```
for(;$n=&$argn;$n>>=4)$s="0123456789abcdef"[$n&15].$s;echo$s?:0;
```
requires PHP 5.6 or later (5.5 cannot index string literals)
or
```
for(;$n=&$argn;$n>>=4)$s=(abcdef[$n%16-10]?:$n%16).$s;echo$s?:0;
```
requires PHP 5.6 or 7.0 (7.1 understands negative string indexes)
---
[Answer]
# Julia, 55 bytes
```
h(n)=(n>15?h(n√∑16):"")"0123456789ABCDEF"[(i=n%16+1):i]
```
This is the basic recursive function implementation. It accepts an integer and returns a string.
If the input is less than 15, floor divide it by 16 and recurse, otherwise take the empty string. Tack this onto the front of the appropriately selected hexadecimal character.
[Answer]
# [Pyre](https://github.com/tuomas56/pyre), 98 bytes
Doing this in a language without arithmetic operators was probably a mistake.
```
let h=def (n)(if n.gt(15)h(n.div(16).int!)else "").concat("0123456789abcdef".list!.get(n.mod(16)))
```
Use like this:
```
do
let h = ...
print(h(15))
end
```
Ungolfed:
```
let h = def (n) do
if n.gt(15)
let x = h(n.div(16).int!)
else
let x = ""
x.concat("0123456789abcdef".list!.get(n.mod(16)))
end
```
[Answer]
# Ruby, 48 characters
(Copy of [Loovjo](https://codegolf.stackexchange.com/users/34543/loovjo)'s [Python answer](https://codegolf.stackexchange.com/a/68249).)
```
h=->n{(n>15?h[n/16]:'')+[*?0..?9,*?a..?f][n%16]}
```
Sample run:
```
2.1.5 :001 > h=->n{(n>15?h[n/16]:'')+[*?0..?9,*?a..?f][n%16]}
=> #<Proc:0x00000001404a38@(irb):1 (lambda)>
2.1.5 :002 > h[15]
=> "f"
2.1.5 :003 > h[1000]
=> "3e8"
2.1.5 :004 > h[256]
=> "100"
```
[Answer]
## Seriously, 35 bytes
```
,`;4ª@%)4ª@\`╬Xε D`@;7ªD+@9<7*+c+`n
```
Hex Dump:
```
2c603b34a640252934a6405c60ce58ee204460403b37a6442b40393c372a2b632b606e
```
[Try It Online](http://seriouslylang.herokuapp.com/link/code=2c603b34a640252934a6405c60ce58ee204460403b37a6442b40393c372a2b632b606e&input=1000)
Explanation:
```
, Get evaluated input
` `╬ Repeat the quoted function until top of stack is 0
;4ª@% Make a copy of the number mod 16
) Send it to bottom of stack
4ª@\ Integer divide the original copy by 16
X Delete the leftover zero. At this point the stack is
the "digits" of the hex number from LSD to MSD
ε Push empty string
D` `n Essentially fold the quoted function over the stack.
@; Roll up the next lowest digit, make a copy
7ªD+ Add 48
@ Bring up the other copy
9< 1 if it's at least 10, else 0
7* Multiply with 7.
+ Add. This will shift 58->65 and so on.
c Convert to character.
+ Prepend to current string.
```
Note that the `;7ªD+@9<7*+c` is equivalent to `4ª▀E`, which would save 8 bytes, but I thought that perhaps a function that pushes the base b digits as a string might be considered too much of a "heaxadecimal built-in".
[Answer]
# Javascript ES6, ~~64~~ 58 bytes
```
v=>eval('for(z="";v;v>>=4)z="0123456789ABCDEF"[v%16]+z')
```
Saved 6 bytes thanks to ןnɟuɐɯɹɐןoɯ and user81655.
[Answer]
# Befunge-93, 58
```
&:88+%"0"+:"9"`7*+\8/2/:!#|_#
,_@ >:#
```
First time doing a real golfing challenge in Befunge, I bet there's a one-liner for this that's shorter since all those spaces in the middle of the second line seem wasteful.
You can step through it [here](http://www.quirkster.com/iano/js/befunge.html). Partial explanation:
`&`: Take input.
`:88+%`: Take the remainder modulo 16.
`"0"+`: Add it to the ASCII value of 0.
`:"9"``: If the result is greater than the ASCII value of 9...
`7*+`: Add 7 to convert it to a letter.
`\`: Save the resulting character on the stack.
`8/2/`: Divide by 16 rounding down.
`:!#|_`: Exit the loop if the result is 0.
`#`: Otherwise go back to the modulus step.
`>:#,_@` (wrapping around): Once finished, output the stack in LIFO order.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 46 + 3 = 49 bytes
This would have been shorter if ><> had integer division, which we now have to emulate by subtracting modulo 1. Still, I think this uses some pretty neat wrapping around tricks!
```
>:?!v:f1+%:a(?v v
\-%1:,+1f}+"0"<+7<
!?:r/ro;
```
[Try it online!](https://tio.run/nexus/fish#@29nZa9YZpVmqK1qlahhX6agUMYVo6tqaKWjbZhWq61koGSjbW7DpWhvVaRflG/9//9/3TIFQwMDAwA "><> – TIO Nexus")
## Explanation
**First loop**
```
>:?!v:f1+%:a(?v v
\-%1:,+1f}+"0"<+7<
```
The first loop performs the classic converting to hex
algorithm. It does modulo 16 (`:f1+%`) and checks if
the result is < 10 (`:a(?`). If it's not, we need to add
7 (`7+`) in order to go from the decimals to the capital alphabet
in the ASCII table. Else, we can proceed by adding the ASCII
value for 0 (`"0"+`) and shifting the character to be output
to the bottom of the stack because we'll have to output them
in reverse order. The top value is then replaced by its result
of integer division by 16. This is emulated by computing
*a/b - (a/b)%1* (`f1+,:1%-`). When the loop is finished, the stack contains the hexadecimal characters in reversed output order and a 0.
**Second loop**
```
!?:r<ro;
```
The second loop reverses the list and checks if top element is 0.
If it is, we know all nonzero were printed and we should terminate.
Else, we output the character and reverse the list again to prepare
for the next iteration. The `:` when entering the second loop will duplicate the 0 which has no effect.
[Answer]
# SpecBAS - 110 bytes
```
1 h$="0123456789ABCDEF",r$=""
2 INPUT d
4 q=INT(d/16),r=d-(q*16),r$=h$(r+1)+r$,d=q
5 IF q>15 THEN 4
6 ?h$(q+1)+r$
```
This uses an algorithm I found on [WikiHow](http://www.wikihow.com/Convert-from-Decimal-to-Hexadecimal) (2nd method).
Strings in SpecBAS are 1-based, hence the `+1` to pick out the correct element.
[Answer]
# [C (clang)](http://clang.llvm.org/), 83 bytes
```
f(n){char h[8]={0};int i=8;while(i>0){h[i-1]=n%16;n/=16;printf("%x",h[8-i]);i--;}}
```
[Try it online!](https://tio.run/nexus/c-clang#FYxBCoMwEADvfcViERJo2ngpwjZ@RHKQGMmCXSWNtBDy7J6tvcxpZs7Ebt5G/3ilkZZr6PZJsMwuDBFC31qTdUHiBGRafAeavaBOyxx6Uo01XDd35Js5uMZDm0RVf6rLUSqyEkkpLOW0/wfPgVjIDJNotNYSIfq0RQaNUPYvL8oNLvgf "C (clang) – TIO Nexus")
Alternate solution in C
[Answer]
# Ruby, 40 bytes
~~Stolen from~~ Inspired by manatwork's answer, but using an interesting loophole to make it shorter.
```
h=->n{(n>15?h[n/16]:'')+(n%16).to_s(17)}
```
[Answer]
## REXX, ~~80~~ 78 bytes
```
arg n
h=
do while n>0
h=substr('0123456789ABCDEF',n//16+1,1)h
n=n%16
end
say h
```
[Answer]
# C, 48 bytes
```
h(x){x/16&&h(x/16);x%=16;putchar(x+=48+x/10*7);}
```
This is not completely original, I shaved 5 bytes off of the version Digital Trauma put up.
[Answer]
# APL(NARS), chars 34, bytes 68
```
{⍵≤0:,'0'⋄(∇⌊⍵÷16),(1+16∣⍵)⊃⎕D,⎕A}
```
test:
```
g←{⍵≤0:,'0'⋄(∇⌊⍵÷16),(1+16∣⍵)⊃⎕D,⎕A}
g 0
0
g 100
064
g 1000
03E8
g 1
01
```
] |
[Question]
[
Simple challenge: try to output the following text in as few bytes as you can:
```
the answer
toli fetheuniv
ersea nde ver
ything the ans
wer tol ife the
uni ver sean
dev ery thin
gth ean swer
tolifetheuni ver
seandeveryth ing
the ans wer
tol ifetheuniver
sea ndeverything
```
The original drawing contains 332 characters.
### Rules
* No input or an unused input.
* Output can be in any reasonable format (string, list of strings, matrix of chars and so on).
* You can use uppercase instead of lowercase for the drawing if your prefer so.
* Trailing whitespaces and newlines allowed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest program/function for each language win!
### Notes
* This has been identified as a possible duplicate of [We're no strangers to code golf, you know the rules, and so do I](https://codegolf.stackexchange.com/questions/6043/were-no-strangers-to-code-golf-you-know-the-rules-and-so-do-i). That question was about searching and replacing text. Here you have to draw a shape using a given text, and at least two of the current answers demonstrate that golfing languages can beat plain compression algorithms in this case.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~224 220 219 215 211~~ 194 bytes
* Thanks to @TFeld for ~~1~~ 5 bytes: `if(j%27<1)*j` instead of `if j*(j%27<1)` and simplified print statement.
* Thanks to @Leaky Nun for 4 bytes:Inverting 0 and 1, did not require the padding by zeros `7*'0'`
* **@Leaky nun saved 17 bytes with his awesome golfing skills(Thanks a lot!!!!): awesome use of modular indexing**
```
i=j=0
k=int("OHZE5WCKDTW6JYMO1JNROAAJQVAN6F8KEO0SMKJM86XIBMCEH5FXXONZGBAVCN3689DS",36)
while k:j+=1;print(k%2*'theanswertolifetheuniverseandeverything'[i%39]or' ',end='\n'*(j%27<1));i+=k%2;k//=2
```
[Try it online!](https://tio.run/##FY7LCoJAAEX3fYUIMlpBPmiybBZq9lB06EHZaxE45WiMolb09Tbt7jmLwy2/TVowo20pypDayRFljSzi5ckbHtxgtjtA/xhizY822Lb99d6O4NwMPKxuw8APTRivnND1lsN5HOPotHDsvRsZ0BzPtmLfgErnk9InEfJJ1kOaVVb/ei7pXdCk5MbqD6ma4knvhOOL0Tepaq4Twgf/RdkDnKlkjK9FBQTQJyxB4MJAV84kfTTVFMWiPcRzVj4YIL1tfw "Python 3 – Try It Online")
## Explanation:
Uses base-36 compression to compress this binary number(new-line excluded)
```
111111100011111111000000111
111111000011111100000000011
111110000011111000111110001
111100000011111000111110001
111000100011111000111110001
110001100011111111111000011
100011100011111111100001111
000111100011111110000111111
000000000000111100011111111
000000000000111000111111111
111111100011111000111111000
111111100011111000000000000
111111100011111000000000000
```
We basically have two counters `i` and `j`. On encountering a `1` we print a space; Else if `0` is encountered we print next letter from the string and increase `i`. `j` increases for each `0 or 1`. We also print new-lines whenever necessary i.e. when `j%27<1` becomes true.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~235~~ ~~218~~ 213 bytes
```
x=bin(int('OC5POO6MZYQNBWY0RP6BKBZCOZL13MIAB6I8YZ5N7LXSZBVKX7GC57AW5631YCJ6XCLC',36))[2:].replace('1',' ')
for c in'theanswertolifetheuniverseandeverything'*4:x=x.replace('0',c,1)
while x:y,x=x[:27],x[27:];print y
```
[Try it online!](https://tio.run/##RY@xboMwGIT3PIW3HyorClDsylWG2EOVhoS0lRIwYkipUywhgxzamKen3rrd3Sed7oZpbHsTz7Nbf2oTaDMGkIv0mOdkL8u3Az@Xq/cj4TsuRS6zKNlvN5xsn0qZHmhWfEh@2hX0RaR0c05JEpXilRQiE4ATEoZVzOqlVUN3aVQAEWBAEC6uvUUN0gbGVl3M7a7s2Hf6qrz9MfpX2ZuPv5QXfpw23/DwyNza/RetADc4Chf3VncKOTZhjysW0xq7Kqasfh6sf4Kmef4D "Python 2 – Try It Online")
Switched to a base 36 encoded int of the positions of letters as hinted in thew question.
Replaces each character one at a time.
```
111 111111 the answer
1111 111111111 toli fetheuniv
11111 111 111 ersea nde ver
111111 111 111 ything the ans
111 111 111 111 wer tol ife the
111 111 1111 uni ver sean
111 111 1111 ---> dev ery thin
111 111 1111 gth ean swer
111111111111 111 tolifetheuni ver
111111111111 111 seandeveryth ing
111 111 111 the ans wer
111 111111111111 tol ifetheuniver
111 111111111111 sea ndeverything
```
Edit: It seems [officialaimm](https://codegolf.stackexchange.com/a/133254/38592) used base 36 before me.
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 125 bytes
```
0000000: 45 8f c5 01 03 31 0c 04 ff ae 62 4b 0b 99 02 c7 E....1....bK....
0000010: d8 7d 84 e7 f9 59 30 5e 41 59 4a 84 71 ef e6 3d .}...Y0^AYJ.q..=
0000020: 4e c1 ea fd b7 42 48 91 66 d6 ae 6e da 89 d3 1c N....BH.f..n....
0000030: ef 60 ba 97 ae 6e b6 74 2e a5 76 d9 ad ae e4 16 .`...n.t..v.....
0000040: 69 59 08 a6 a6 e8 23 d4 22 af 08 d0 20 7d 17 f0 iY....#."... }..
0000050: 8a 9b 7c 76 c2 61 7b c8 4b 01 41 23 50 24 32 87 ..|v.a{.K.A#P$2.
0000060: f5 98 9e 88 35 24 21 83 ac 50 b2 e0 a2 16 0e 42 ....5$!..P.....B
0000070: bb ba a5 bc ae 6e bd 76 b7 69 d9 f9 07 .....n.v.i...
```
[Try it online!](https://tio.run/##RZHLSsRAEEX3fsVVZ130@yG4UBBEQWY7G7GfIqggOLNRv32syvhoQiWkUye3Ttdtrc/jcfuy36vDOoPzSBPNQ2koC8u1QTnMiTIQDFyFqsgZyqBF4Ip4aSn1VurRAtKM6gmxIzmMiJnhM6yCH3Banl2RragxJkaA7QB9cf9G3V9sbuiN6PyAMpJqoPGXBbOjRjiOkZA1QkAPS7CBzsCMbqEbcCdRLq9pEr3@p7KM4t8FhVqQ409jDYgOZqB4RAZmlC5bw0EHTvVAAnkn2tE/yjEqLEOphBLkGgnGojPKoEx53xWMEgmaDSjgaSOAUzrhiq9flGdU4jwVsUmAZhA0YkVLi20txpjsmeZgDRJrJ/rcUfmgW7o4Xa/MDyowanpkljOQEqyXFqORLEoTQjUYCsXIaGqISUgmvzomWi/zXR5QkVG1iijWUtuvqy4J@Qh4dhbFx6o4zN9aAK8s6onv@/03 "Bubblegum – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~83~~ ~~79~~ 74 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md)
-4 bytes thanks to Erik the Outgolfer
Outputs a list of strings to save a byte.
```
•2ÖH₆Ôn₅Ò\ÊÑĆ¸Ý¾*£„ÔûC∞qΘœ™‚¹µ—₃₄fm•vNÈy×vyiðë¾¼’€€Ž»to‚쀀ªÜ€ƒ‰Ö’è}}}J27ô
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UcMio8PTPB41tR2ekveoqfXwpJjDXYcnHmk7tOPw3EP7tA4tftQw7/CUw7udH3XMKzw34@jkRy2LHjXMOrTz0NZHDVMeNTU/ampJywUaU@Z3uKPy8PSyyszDGw6vPrTv0J5HDTMfNa0BoqN7D@0uyQfqOrwGInBo1eE5QOrYpEcNGw5PA6o7vKK2ttbLyPzwlv//AQ "05AB1E – Try It Online")
### Explanation
`2ÖH₆Ôn₅Ò\ÊÑĆ¸Ý¾*£„ÔûC∞qΘœ™‚¹µ—₃₄fm` is the base 255 representation of the decimal number:
```
73869469755353565353431353533323902433339443437469034389033390735363735903735903
```
Which encodes runs of `1`s and `0`s respectively, even indices being the `1`s and uneven indeices the `0`s. This evaluates to the binary number:
```
111111100011111111000000111
111111000011111100000000011
111110000011111000111110001
111100000011111000111110001
111000100011111000111110001
110001100011111111111000011
100011100011111111100001111
000111100011111110000111111
000000000000111100011111111
000000000000111000111111111
111111100011111000111111000
111111100011111000000000000
111111100011111000000000000
```
### Code
```
•...• Convert from base 255 to decimal
v } For each digit, do:
NÈy× is_even(index) repeated that many times
v } For each digit, do:
yi } If digit is truthy, then:
ð Push space
ë Else:
¾¼ Get and increment counter, starts at 0
’€€Ž»to‚쀀ªÜ€ƒ‰Ö’ Push "theanswertolifetheuniverseandeverything"
è Get the character at that index
J Join whole stack
27ô Split into parts of 27
```
[Answer]
# [Python 2](https://docs.python.org/2/), 220 213 212 bytes
*-1 byte by switching `()*4` for `%39` from* **@officialaimm**
```
s=""
w=l=i=0
for g in`int("352G7FS4XC8J2Q2M2HNK7IZI65Z9TVUMHOZ6MR3HY46RQBLWY4PR",36)`[:-1]:
for j in g*int(g):l+=1;s+=[' ',"theanswertolifetheuniverseandeverything"[w%39]][i%2]+"\n"*(l%27<1);w+=i%2
i+=1
print s
```
[Try it online!](https://tio.run/##FY5bC4IwAIWf268YAymzIKdpWXspKLvYxe6aUNCyhcxwlvTrbb2d8z1857y@@SPluCwFQQgUJCGMtMA9zWAMGb8wnteQ0cZje7Qxj8POFK@xh93FzJ4EE6sddLf7necuA8vzDfdkWv56MD@czJWPGoalXkKnqUcOqPx9T@mDcf1vjFUn0YjeExoJq7DaQPmDXrkoaJanCbtTWd@cfWgmJL5RGeRLxmMUForRjaKQKTjS0Jmjei1RsN3X1V6hEUlBhUkxeGVyBoqy/AE "Python 2 – Try It Online")
This is a different approach from the other Python answers. I use a hex **base-36** (saved 7 bytes) encoding of a PNG-style [RLE-style encoding](https://en.wikipedia.org/wiki/Run-length_encoding "RLE-style encoding") of the image (a string of digits indicating the number of consecutive repeated pixels).
**The string of digits is**:
```
73869469755353565353431353533323902433339443437469034389033390735363735903735903
```
Then I iterate through those digits and alternately print that number of ' 's or characters from the palette ('theanswer...'). When more than 9 of a character is repeated, I'd simply add a 0 and then the remainder.
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 74 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
"ō⅓׀?@C⁶¬IΧΖO‘@øŗč"βΘ⅔Μv∙KΩqψ3╥W≡A;2ļm½±iq╗∆Δ⁶Πqīσ‽ε⁰5τΩ⅜δσΞoΤi┘‽N¹\Λ:‘' n
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/comp/index.html?code=JTIyJXUwMTREJXUyMTUzJXUwNUMwJTNGQEMldTIwNzYlQUNJJXUwM0E3JXUwMzk2TyV1MjAxOEAlRjgldTAxNTcldTAxMEQlMjIldTAzQjIldTAzOTgldTIxNTQldTAzOUN2JXUyMjE5SyV1MDNBOXEldTAzQzgzJXUyNTY1VyV1MjI2MUElM0IyJXUwMTNDbSVCRCVCMWlxJXUyNTU3JXUyMjA2JXUwMzk0JXUyMDc2JXUwM0EwcSV1MDEyQiV1MDNDMyV1MjAzRCV1MDNCNSV1MjA3MDUldTAzQzQldTAzQTkldTIxNUMldTAzQjQldTAzQzMldTAzOUVvJXUwM0E0aSV1MjUxOCV1MjAzRE4lQjklNUMldTAzOUIlM0EldTIwMTglMjclMDlu)
```
"...‘ push "the answer to life the universe and everything". because of a bug-not-really-bug, the starting quote is required
@øŗ remove spaces
č chop it into characters
"...‘ push a string of spaces and ŗ where ŗ gets replaced with each next characters of the character array
' n split into an array of line length 27
```
[Answer]
Allow me to answer my own question...
# [Charcoal](https://github.com/somebody1234/Charcoal), 140 126 112 bytes
```
A⟦⟧βF⁶⁸F⁻℅§”c#*U[“⎆Vl¶·δ‴ü"Ip8ξZ{e/⪫¦σMM⪫¢Q⁸ULê←⪫W?—υ⁻$⌀)”ι³⁴«¿﹪ι²§”m⌊0Y℅¿№”XJ-⁵η}Z¿8_*<o%!±Ÿ”L⊞Oβω ¿¬﹪L⊞Oυω²⁷⸿
```
[Try it online!](https://tio.run/##PY69SgNRFIRfxd/CgGiZQvAJLINBCwmLYBGJ2IqwF7OBhCAWoo1x0WKDm4hk3exm9ZALJ/297zAvcB5hvUlhNzMM34x30bj2Wo1mWQq9IYwQDk0iFEFlULOV@EU74CH8gbdZqZ3yAP4L7jtCWZMzzk0KP13QhtDHVdXMhX5uzvcQjziyd0dCn0v5LjRxtJrQeBGj8@Cy40N@toGDb6Hv7zi4KfgbKuURayli55LV5iX6vX2hYvlBo/3Ej3WheBdqavLbE9bVs8pBa3udJxy6thtA71XoyyS2u8aax471H9rAdjmByjHTZfkH "Charcoal – Try It Online")
You have [here](https://tio.run/##bY9NTwMhEIbv/RUEHXamy/awGjXpqUcTP3rXHrZdtkuyAQNsqzH@dpxVqxchMC8vM/PArm/CzjdDzqsY7d7h00aLLS1nnQ8Cr25oJsSXvLdujOhDi6t061rzipJgjqXCkooCeOK0KzibNACcQ6U4QKkUu6RwoWC@AKj5FoGgWExLakukLy6JxDujhLAds3w7Dh6trtleB@vSH3SfetO4eDQh@cF2ho@jswcTItutYfGWeuukvjOOc3E9xv7xxYQm@YBbfSQey5@mUkj@6Yn64NOJ/F/tqAUXa1Ff0@@r5HP47vCRc64OuYrDJw) a link to the closest verbose version.
Explanation (see verbose version for details):
* The `)%*(+&(+)''%'%'('%'%&%#%'%'%%%$%-&%%%%+&&%&%)&(.&%*.%%2%'%(%)%'.)%'.` string (68 bytes, 48 bytes compressed) is a representation of the RLE-encoding of the drawing. Every char code minus 34 is the number of spaces (even positions) or the number of text characters (odd positions) to print consecutively.
* The algorithm just decompress the RLE-encoded string and writes the next char of the `gtheanswertolifetheuniverseandeverythin` string (39 bytes, 27 bytes compressed) every time a non-whitespace character is needed to be written. As I check the length of a list to get the next character and that list starts with one element, the last character of the string is written in the first position.
* Every 27 characters written I insert a new line.
### Acknowledgments
* Many thanks to Neil and his amazing tips for allowing me to save 28 bytes and finally be able to beat Bubblegum. :-)
[Answer]
## JavaScript (ES6), ~~207~~ ~~205~~ 203 bytes
Returns an array of strings with some trailing spaces.
```
let f =
_=>[16515968,33489856,k=58950624,k+16,k-40,31458204,7865230,1966983,462847,233471,117670784,k=134185856,k].map(n=>'heanswertolifetheuniverseandeverythingt '.replace(/./g,(_,i,s)=>s[n>>i&i<27?k++%39:39]))
console.log(f().join('\n'));
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 183 bytes
```
7386¶6469¶555353¶465353¶33135353¶23239024¶133394¶034374¶090343¶090333¶735363¶735903¶735903¶theanswertolifetheuniverseandeverything
.*$
$&$&$&$&
(\d)(.)
$1$* $2$*
+s`1([ 1¶]+)(.)
$2$1
```
[Try it online!](https://tio.run/##RcpNCsIwEAXgfU7RxSD9gdJkktScRQULjTYgEdqoeLEcIBeLU7KQWXxv3sxqg/NTzmzEo05RS21SVEqhwhSlLiJyLEmgQDMImSJHREMOKHHcNXsqIjnSvy5S8zcsdvLbx67h@XA3S@vLu7ddN6pnS@EbFufvrG@BwaEMq89zU/cNAw5tBQJa1m1XXp8qnuKlKycBPOcf "Retina – Try It Online") Explanation: The first stage adds the RLE encoding of the cell bitmap and the text, which the second stage then duplicates to the correct length, while the third stage decodes the RLE encoding. The fourth stage then moves the text into the cells.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 83 bytes
```
“¡eu⁾ṃṣƬİḂṃ½)ṣṾṘƇ@^AṀẆṫ+¢ṗɲ⁾ṭḋZ`⁺×Ṗj½Ṇ-Þḣ2żṿƤc’BCẋ"`“ÆZ⁺ƙ{Æß¥ŀŒ1gỤ3Ḍṭṁ ṃjɓ»ṁȯ€⁶s27Y
```
[Try it online!](https://tio.run/##HY29CoJQGIZvJdoiGqqhtZ@ryCGEkEDcoiFa1MAGmwoyIYrSpoyiIc6nWXBOSl7Gd27ETm3vw/unKpo2znOub@heGXHjiTBF8NLgfUViCqBxSTCCMNbprNlrIegYWginMj0gONntXzojsSWZGyFzEFYqjRGsCtsi8WrJA@GV@n2uu@0OhnZRFm/MkkQ4dSfMYjt6TPRkUR1g5NeRzH9rYBTEuZotaST058LNgBv3Ya3RzfMv "Jelly – Try It Online")
## How it works
```
“XX’BCẋ"`“YY»ṁȯ€⁶s27Y
“XX’ a large number
B binary
C complement
ẋ"` 1 becomes [1] and 0 becomes []
ṁ reshape
“YY» "theanswertolifetheuniverseandeverything"
ȯ€⁶ replace [] with " "
s27 split into chunks of length 27
Y join with newline
```
[Answer]
# [Add++](https://github.com/SatansSon/AddPlusPlus), 1398 bytes
```
+32
&
&
&
&
&
&
&
+84
&
-12
&
-3
&
-69
&
&
&
&
&
&
&
&
+65
&
+13
&
+5
&
+4
&
-18
&
+13
&
-104
&
+22
&
&
&
&
&
&
+84
&
-5
&
-3
&
-3
&
-73
&
&
&
&
&
&
+70
&
-1
&
+15
&
-12
&
-3
&
+16
&
-7
&
-5
&
+13
&
-108
&
+22
&
&
&
&
&
+69
&
+13
&
+1
&
-14
&
-4
&
-65
&
&
&
&
&
+78
&
-10
&
+1
&
-69
&
&
&
&
&
+86
&
-17
&
+13
&
-104
&
+22
&
&
&
&
+89
&
-5
&
-12
&
+1
&
+5
&
-7
&
-71
&
&
&
&
&
+84
&
-12
&
-3
&
-69
&
&
&
&
&
+65
&
+13
&
+5
&
-105
&
+22
&
&
&
+87
&
-18
&
+13
&
-82
&
+84
&
-5
&
-3
&
-76
&
&
&
&
&
+73
&
-3
&
-1
&
-69
&
&
&
&
&
+84
&
-12
&
-3
&
-91
&
+22
&
&
+85
&
-7
&
-5
&
-73
&
&
+86
&
-17
&
+13
&
-82
&
&
&
&
&
&
&
&
&
&
&
+83
&
-14
&
-4
&
+13
&
-100
&
+22
&
+68
&
+1
&
+17
&
-86
&
&
&
+69
&
+13
&
+7
&
-89
&
&
&
&
&
&
&
&
&
+84
&
-12
&
+1
&
+5
&
-100
&
+93
&
+13
&
-12
&
-72
&
&
&
&
+69
&
-4
&
+13
&
-78
&
&
&
&
&
&
&
+83
&
+4
&
-18
&
+13
&
-104
&
+106
&
-5
&
-3
&
-3
&
-3
&
-1
&
+15
&
-12
&
-3
&
+16
&
-7
&
-5
&
-73
&
&
&
&
+86
&
-17
&
+13
&
-104
&
+105
&
-14
&
-4
&
+13
&
-10
&
+1
&
+17
&
-17
&
+13
&
+7
&
-5
&
-12
&
-72
&
&
&
+73
&
+5
&
-7
&
-93
&
+22
&
&
&
&
&
&
&
+84
&
-12
&
-3
&
-69
&
&
&
&
&
+65
&
+13
&
+5
&
-83
&
&
&
&
&
&
+87
&
-18
&
+13
&
-104
&
+22
&
&
&
&
&
&
&
+84
&
-5
&
-3
&
-76
&
&
&
&
&
+73
&
-3
&
-1
&
+15
&
-12
&
-3
&
+16
&
-7
&
-5
&
+13
&
-17
&
+13
&
-104
&
+22
&
&
&
&
&
&
&
+83
&
-14
&
-4
&
-65
&
&
&
&
&
+78
&
-10
&
+1
&
+17
&
-17
&
+13
&
+7
&
-5
&
-12
&
+1
&
+5
&
-7
&
P
```
[Try it online!](https://tio.run/##lVTBDcMgDPx3kH6sSDEUbLboCpU6QPf/pME0BIPbJopkRWB8vuPw4/l8vZYFvLtc1Qd8W@OEeX3yOcTUpaxJMeSIeR/ktxziujrhnJfAOat6qMUlkNdJNEsFKRZ0N4BRTmxVKhoPaCCNf5pEyRJwCUJgB@RSpGYqzsCCifSLHXCqzKRdKSTilG4Jj6s86LsCBgUITL3i7CyBKSqiu@gWz76phA0ocFDSb9dmyMNusMwG4fVFVD3nigSRq3xSdOJoXWnZSibKzbqGD0jyDa5wJdeZpm1NvDFy@Op4nKNhcX/Y0e1r@O684gdLyE675iyQdujOu/iiMWvRyJ0cDqNtuXvZo2vtOXHWyIfnBB1B9qeGxX@hu1FwX5Y3 "Add++ – Try It Online")
It looks like hardcoding it is the shortest way (at least in Add++)
[Answer]
## Vim, 239 keystrokes
```
:h4<CR>3hy5bZZitheanswerto<Esc>p:%s/ \|,//g<CR>ye3P
lqqi<CR><Esc>qqw3li <Esc>lq3@wbhr<CR>16l@q@w3-@w6l@ql@w9l@qll3@whr<CR>3l9@w4l@q 2@w4l@q2@w4l@q9l2@wlr<CR>9l@w4klr<CR>4whr<CR>jj
el<C-v>3k"aD0jji <Esc>qqdiwukPi <Esc>q5@qwy04j$"ap6+<C-v>GPp3kw3i <Esc>2@q4kbXj2@qywh<C-v>4jp2je<C-v>jj4A <Esc>8j5i <Esc>b<C-v>jj2I <Esc>
```
Linebreaks added for "readability"
### Explanation
The first line yanks `life, the universe and everything` from a help page, which is one byte shorter than simply typing it out. It then turns that into this:
```
theanswertolifetheuniverseandeverythingtheanswertolifetheuniverseandeverythingtheanswertolifetheuniverseandeverythingtheanswertolifetheuniverseandeverything
```
The second line breaks the string up into:
```
the answer
toli fetheuniv
ersea nde ver
ything the ans
wer tol ife the
uni ver sean
dev ery thin
gth ean swer
tolifetheuni ver
seandeveryth ing
the ans wer
tol ifetheuniver
sea ndeverything
```
And then the final line indents it to make:
```
the answer
toli fetheuniv
ersea nde ver
ything the ans
wer tol ife the
uni ver sean
dev ery thin
gth ean swer
tolifetheuni ver
seandeveryth ing
the ans wer
tol ifetheuniver
sea ndeverything
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 76 bytes
```
“¡¢ʋỵṆ⁻kỴ⁷ṁḤæ ƊVṛĠ¥¡¢tṢ}ȧƘ=ẒṆ_`-p1ḷṠ’ḃ⁴ĖŒṙḂ¬R“£:(ḥB⁼Ṇ#¥Ṡ1ɗĠðȮ $¿⁹½ɓ»ṁȯ€⁶s27Y
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDCw8tOtX9cPfWhzvbHjXuzn64e8ujxu0PdzY@3LHk8DKFY11hD3fOPrLg0FKQwpKHOxfVnlh@bIbtw12TgBriE3QLDB/uACpf8Khh5sMdzY8atxyZdhQoBeQ0HVoTBLJgsZXGwx1LnR417gHqUD60FKjY8OT0IwsObzixTkHl0P5HjTsP7T05@dBuoKUn1j9qWvOocVuxkXnk//8A "Jelly – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 185 bytes
```
7!8&sw'6Bi6fe!Av¶5#sea5nde5v'4y%g5!5&s¶3w#1B5ife5!¶2A2v#92se&¶1dev3#y9%¶gth4e&7sw'Bife!A4v'se&dev#yth3ing¶7!5&s6w'7B5ife!Av'7sea5ndev#y%g
'
#¶
&
an
%
thin
#
er
!
the
A
uni
B
tol
\d
$*
```
[Try it online!](https://tio.run/##LY1LCsMgFEXnbxUVq0Jn@RibYVxHJ4G8GqFYiNaQjbkAN2ZN6ezCPZyzYbBuLgUUuXO/i0Hb4YlkijlJ6nGWbkEZRX8wI4nkPqdup42W9omS5NRObaRj65Hn1CwYO3qMLCcT1h65qj5tT1sfRUXqT4@wdtaZnNRpG3ahfq4aFOqfqxAzIIDmBBxmBwzCah1QwA1I3QgTfJwFDeH9gscC19ullC8 "Retina – Try It Online")
[Answer]
# JavaScript, 215 bytes
solution based on guest44851
```
$=>'a21xb0k9qf30155yiv016ewp3018lkhz0ohfdb077or302cl5b0mgzr0b8hz028ghs7028gi67028gi67'.split(p=0).map(x=>parseInt(x,36).toString(2).slice(1).replace(/./g,x=>" theanswertolifetheuniverseandeverything"[+x&&1+p++%39]))
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 216 bytes
```
o=i=1
puts"6iffnqxq0opdbco5e3f1zk5d7eezo2j6zwly9z5yykqsc1hl5svaof".to_i(36).to_s(17).chars.map{|c|
o=!o
c.to_i(17).times.map{o ? (i+=1)&&"ngtheanswertolifetheuniverseandeverythi"[i%39]:" "}.join
}.join.scan /.{1,27}/
```
[Try it online!](https://tio.run/##JYrRjoIwFETf@Qq2iQaiqVsJEE2IH2I2m1pu5Sr2Ai26Rf12FsPTnJkzXX/y40gFFiJoemdZhlqb9q/9pqY8KUoh0WK4pmUOMND2kg2P2u@G1Ptra5Wo6tTeJWnGHf1ilGTxB2wk8pirSnaW32TzfKlXQMUXBWq@fazDG8yWwkMY4aoQ8XLJzNlVII19QOeoRg1T7Q3eobPTXMIE3lXIjrhIdj97FrI3vxCaYA5ulTThhj/Fepu/N@P4Dw "Ruby – Try It Online")
**Explanation** Similar to the Python solutions but I used Run Length Encoding before converting to base 36. So the data string is only 54 characters instead of 68.
But it still ended up longer over all, hopefully it can be golfed further.
[Answer]
A port of [my Charcoal answer](https://codegolf.stackexchange.com/a/133271/70347):
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 229 bytes
```
_=>{var r="";for(int i=0,j,k=0,n=0;i<68;i++)for(j=0;j++<")%*(+&(+)''%'%'('%'%&%#%'%'%%%$%-&%%%%+&&%&%)&(.&%*.%%2%'%(%)%'.)%'."[i]-34;){r+=i%2<1?' ':"theanswertolifetheuniverseandeverything"[k++%39];if(++n%27<1)r+='\n';}return r;}
```
[Try it online!](https://tio.run/##bVBNawIxEL37K0LaySZGF12lX9m1h0JvhUIPPViRZY0aPxKYREuR/e3brIK99A158/JmJpCpfL9yqBsSUe1K78k7uhWW@07rnM7cwocymIocnVmQt9JY7gMau5rOSIkrL659fxMtPn580Pv09WCr/DLQu6QJmY8zUnRIMy8mp2OJBAtK1dIhNzYQUwx6m942si0GyuR3D8pIKdryJhobKXMqoMsl41IkCcTgLTO4aTUA3EKfxQSSsegKxlMG3RQgi1UOApK0PXRqZv3RWIkTysJAlg@fE5I80bDWpfXfGoPbmaWO14M1R40@2gsdxU9Yx1/Q6VZKGD3OlFlyKS1k9/lQxKeSL5uoGnU4oCWo6kZ1/tvLi7Pe7XT6iSZoHjfCKRVCXVvrs6qbXw "C# (.NET Core) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~220~~ ~~219~~ ~~217~~ ~~213~~ 210 bytes
-1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
-3 bytes thanks to [Jerry Jeremiah](https://codegolf.stackexchange.com/users/24812/jerry-jeremiah)
```
q,i,j,t;main(c){for(;c="HDIG@GEGJ@FFFDFD@EGFDFD@DDBDFDFD@CDCDLE@BDDDJE@ADEDHE@AMED@AMDD@HDFDGD@HDFM@HDFM"[t++];)for(c%=64,j=c?q=!q,c:2;--j;)putchar(c?q?32:"theanswertolifetheuniverseandeverything"[i++%39]:10);}
```
[Try it online!](https://tio.run/##HYzhCoJAEISfJUFIPKEsgjzEq/Y8k3wC8Ydsl56UpV1FRM9ul3/mm9kdBr0KcRg6okhDNL2Uqp2i8zld@ynF0EpgL5jgImVxHEMMjIsRAFsYzQ52cOBsCwApZxvgkBhkHIwAsMR0xIhsFCvXrltQ57@PdrhakibEqAsnHcHAp57XUOf20FiX5h910cIPLF3Lsr2/ZK@vZ3WSJj5a9ZT93ZyP0pi3rlVbWblyXXuxLoL5zKHfYfgB "C (gcc) – Try It Online")
[Answer]
# JavaScript, ~~265~~ ~~237~~ 219 bytes
```
(i=0)=>'jwq80,13ntvk,26p62g,25g7w8,239k3c,zg4xc,7rpbk,1e9dc,b8mw,5mbc,4f9reg,4f9r0g,4f9r0g'.split`,`.map(b=>parseInt(b,36).toString(2).slice(1).replace(/./g,c=>' theanswertolifetheuniverseandeverything'[+c||2+i++%39]))
```
Few bytes off thanks to @tsh.
# [JSFiddle](https://jsfiddle.net/4nry6Lwm/)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 121 bytes
This contained too many bytes that I couldn't get to show up in TIO, so here's a hexdump:
```
00000000: 7558 6848 477c 2a64 6548 622c 5658 434d uXhHG|*deHb,VXCM
00000010: 2290 8d8d 817e 7e7b 7875 7572 6663 5753 "....~~{xuurfcWS
00000020: 504d 4946 4343 3f3c 3939 3633 302d 2d2a PMIFCC?<99630--*
00000030: 2721 211e 1b16 160d 0909 0300 225d 545d '!!........."]T]
00000040: 3133 6a43 2202 1232 a464 b09d 7303 4244 13jC"..2.d..s.BD
00000050: 9386 74d2 e954 b89e e722 3132 2a34 2e22 ..t..T..."12*4."
00000060: 6179 1aa6 55ad c176 932b 6088 d5c5 556c ay..U..v.+`...Ul
00000070: e4f4 5575 12a0 e7fb 1f ..Uu.....
```
[Try it online!](https://tio.run/##ZZDLasMwEEX3/gqRTZqQh0YjjSwo3WTRbLorJZssJEtuWlrHxC6kkH93J4Y8mnBBSHM1ukcTfLPpunr3UbWlGDqZRxbYxAo2t4aliAh5g0bqqJ0mjRqxxAIdixBRqsjyyipQAAkCEJCM0rFQyqE4iP0@iulOTOtGPIl622SFb8Xjwyl4tXgZDEdcOJbZHl15g/XrGpDdvnFW/7abLDuZkiNReYYK0kWLErXS2mFOVkeVnNEhdynZO4avVN0wfC4uCOz@QwDV53P5Jp/AOvCejPGxAEsOVSCZ59EUxhgqki614eGB8jLZMkB5R/LdvGc3KD@rzfL5MI5pGSZv13Pp068gz@dT51jPLr/gl4/UvjpPjddthWK@rdv58dAvbJ7vdN0f)
You can add a call to `wc` or `xxd` in the bash script to see the byte length or the hexdump I produced above.
Interestingly, this program demonstrates a minor bug (?) in Pyth. Any carriage return bytes (0x0d) are read as newline bytes (0x0a) when in string literals. This forces me to add 6 bytes: `X ... ]T]13` to replace the incorrect ten with a thirteen.
Otherwise the idea behind this code was fairly simple: record each position where a run of whitespace occurs. Then, pair each of those indices with the number of spaces in that run. Then, reconstruct the original string by repeating the phrase four times, then inserting in the correct locations. If the number of spaces recorded was zero, instead a newline is inserted.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~258~~ ~~252~~ 251 bytes
```
z->{int i=0,x,j,N[]={16515968,33489856,x=58950624,x+16,x-40,31458204,7865230,1966983,462847,233471,117670784,x=134185856,x};for(int n:N)for(j=32;j-->0;n/=2)System.out.print(n%2<1?j<1?"\n":" ":"theanswertolifetheuniverseandeverything".charAt(i++%39));}
```
[Try it online!](https://tio.run/##LVDLbsIwELzzFVYkpEQ4qd9xSEPVD2gP5Ug5GDDgNDjIcSgI5dtTg3pY7czuzq52anVRaXvWtt79jOd@05gt2Daq68CHMhbcJwD8VzuvfEiX1uzAKfTipXfGHlZroNyhS56jAHz11qpNo4ED1Rgn6eJurAemQvAKa/i5Wld3LDjmhZCQUiYLyQW8VlwWHAnC4HWGA08ZghQzLgliMJeCE4ogLoQoJIVMEMlySII8xxDjXOQol0FaYcqw5M@NQ7lvXfy4beefyQPXFSVlnaYLVNqXiiTLW@f1KWt7n53DIz62U/KK3@oQ0beN5hEI4Y9a2e5XO982Zq8D7a25aNeF8k4HcPPHYEKUbY/KvfvYzGZTWiRJOYzl5GmIy1xv46QMZJgM4x8 "Java (OpenJDK 8) – Try It Online")
It's a rather naive implementation. First a mask, for the printed characters, then a roll over the text until done.
* 6 bytes saved thanks to Carlos Alejo!
[Answer]
# Javascript, approximate drawing. 319 bytes
```
s=32
t="theanswertolifetheuniverseandeverything"
j=0
o=""
b=document.createElement('canvas'),c=b.getContext('2d')
b.width=b.height=s
c.font="25px Verdana"
c.fillText('42',0,20)
m=c.getImageData(0,0,s,s)
i=0
while(i<m.data.length) {
d=m.data[i+3]
o+=d?t[j%t.length]:" "
if(d)j++
i+=4
}
o.match(/.{1,32}/g).join("\n")
```
^ for what it's worth, not much really, but before I delete the failed code.
] |
[Question]
[
Inspired by [this question](https://askubuntu.com/questions/600018/how-to-display-the-paths-in-path-separately) on AskUbuntu.
Your job is extremely simple. Take the PATH environment variable (`echo $PATH`) and export it such that each entry (separated by the `:` character) is on its own line.
For example, if the PATH is `/bin:/usr/bin:/usr/local/bin`, your program should output:
```
/bin
/usr/bin
/usr/local/bin
```
Your program may not return a leading newline, but it may return a single trailing newline. You do not need to check if the PATH is right, or that the directory exists. Your program should take no input, meaning that your program is responsible for getting the PATH itself. You may safely assume that objects in the PATH do not contain `:` or newlines. However, spaces are fair game.
Reference implementations are present in the answers to the question above.
### Rules
* This is (obviously) code-golf, so the shortest answer will win the prized green checkmark.
* The accepted answer will be tested to make sure it's actually legit.
* Both Windows and \*nix entries are accepted.
+ However, if you don't explicitly specify Windows, I will try running it in Linux and fail. (If it's obvious (hi, Batch!), you don't need to specify explicitly.)
* Only have one solution per answer. If you have both a Windows and \*nix version, I will count the shorter one.
* If two answers have the same length, I will give priority to the one with the higher vote total. If they have the same vote total, I will count the older one. If the time posted is the same, I will choose the one that executes faster. If they execute in the same amount of time, I don't know.
### Leaderboard
```
var QUESTION_ID=96334,OVERRIDE_USER=15422;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]
# Z shell (zsh), 13 bytes
```
<<<${(F)path}
```
Uses the [`$path` parameter](http://zsh.sourceforge.net/Doc/Release/Parameters.html#Parameters-Used-By-The-Shell), which is a special array parameter used by the shell that is [tied](http://zsh.sourceforge.net/Doc/Release/Shell-Builtin-Commands.html#index-typeset) to the `$PATH` parameter, and a [parameter expansion flag](http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion-Flags) to join an array with newlines.
[Answer]
## Bash/Coreutils, ~~17~~ 16 bytes
```
tr : '
'<<<$PATH
```
[Answer]
## Batch, 41 bytes
```
@for %%a in ("%PATH:;=";"%")do @echo %%~a
```
`PATH` is semicolon-delimited on Windows of course. Conveniently, `for` splits on semicolons by default, but inconveniently, also on spaces, so I have to use string replace trickery to quote each path element before splitting. It then remains to remove the quotes afterwards.
[Answer]
# Z shell (zsh), 15 bytes
```
<<<${PATH//:/
}
```
You can test the code on [Anarchy Golf](http://golf.shinh.org/check.rb): click *use form*, select *zsh*, paste the code and submit.
## Bash (pure), 19 bytes
```
echo "${PATH//:/
}"
```
Same idea, but with Bash's less golfy syntax. Test it on [Ideone](http://ideone.com/ri1lrX).
[Answer]
# Powershell, 20 bytes
```
$env:PATH-split':'
```
Edit:
* ***-2** bytes off. Thanks to @TimmyD*
Old:
```
$env:PATH.split(":")
```
[Answer]
# Ruby, 25 bytes
```
puts ENV["PATH"].split":"
```
[Answer]
## Perl, 22 bytes
```
say$ENV{PATH}=~y/:/
/r
```
Needs `-E` or `-M5.010` to run :
```
perl -E 'say$ENV{PATH}=~y/:/
/r'
```
[Answer]
### Bash+Python, 43 bytes
Let's use shell's variable expansion. It eliminates calling `os.environ` , thus less code and less imports. That gives us 46 bytes, and with `xnor`'s trick and removing space before `-c` we've got 43 bytes.
```
python -c"print('$PATH'.replace(*':\n'))"
```
[Answer]
## Java, 58 bytes
```
System.out.print(System.getenv("Path").replace(';','\n'));
```
Full program: 106 bytes
```
class E {
public static void main (String[] args) {
System.out.print(System.getenv("Path").replace(';', '\n'));
}
}
```
[Answer]
## GNU `sed` + `bash`, 25 bytes:
```
sed 's/:/\n/g' <<<"$PATH"
```
If the `PATH` contains no directory name with whitespace, no quoting needed, 23 bytes:
```
sed 's/:/\n/g' <<<$PATH
```
Even shorter, transliterating `:` to newline, thanks to [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis):
```
sed y/:/\\n/<<<"$PATH"
```
[Answer]
# Vim, 19 bytes
`"=$PATH<CR>p:s/:/\r/g<CR>`
Grab `$PATH` from the expression register and paste it. Turn the `:`s into newlines. Nothing tricky.
[Answer]
# C (x86), 60 bytes
```
f(){char*p=getenv("PATH");for(;*p;p++)putchar(*p-58?*p:10);}
```
This won't work on 64-bit platforms without including *stdlib.h*, since *getenv* returns an *int* (32 bits) while *char* pointers are 64 bits wide.
I have yet to find an online 32-bit C compiler.
# C (x86-64), 70 bytes
```
f(){char*getenv(),*p=getenv("PATH");for(;*p;p++)putchar(*p-58?*p:10);}
```
Instead of including *stdlib.h*, we declare *getenv* ourselves as a function returning a *char* pointer.
I've tested this with gcc and clang on Linux; other setups may cry blood. Try it on [Ideone](http://ideone.com/SNfiiv).
[Answer]
## PHP, ~~36~~ ~~35~~ ~~33~~ 32 bytes
*Saved 1 byte, thanks to Blackhole*
*Saved 2 bytes, thanks to user59178*
*saved 1 byte, thanks to Martijn*
### \*nix version
```
<?=strtr(getenv(PATH),":","
")?>
```
### Windows version
```
<?=strtr(getenv(PATH),";","
")?>
```
[Answer]
# Python 2, 49 bytes
Saving 2 bytes thanks to @xnor and 1 byte by replacing `environ` with `getenv` thanks to @Serg and @Oliver
```
import os
print os.getenv('PATH').replace(*':\n')
```
For Python 3, just add `(` and `)` around the `print` argument and add 1 to the byte count.
[Answer]
# jq, 18 characters
(16 characters code + 2 characters command line option)
```
env.PATH/":"|.[]
```
Sample run:
```
bash-4.3$ PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
bash-4.3$ jq -nr 'env.PATH/":"|.[]'
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
```
[Answer]
# C, ~~85~~ 84 bytes
-1 byte for using `#import`
```
#import<stdlib.h>
main(){char*a=getenv("PATH");while(*a)putchar(*a++==58?10:a[-1]);}
```
[Answer]
## Racket 39 bytes
Using sed command of @heemayl :
```
(system "sed 's/:/\\n/g' <<<\"$PATH\"")
```
Ungolfed:
```
(define (f)
(system "sed 's/:/\\n/g' <<<\"$PATH\"")
)
```
Testing:
(f)
Output:
```
/usr/local/bin
/usr/bin
/bin
/usr/games
/usr/lib/java/bin
/usr/lib/java/jre/bin
#t
```
[Answer]
# Scala, 31 bytes
```
sys env "PATH"replace(':','\n')
```
In scala, `a b c` is syntactic sugar for `a.b(c)`, so this compiles to `sys.env("PATH").replace(':','\n')`
[Answer]
# [Perl 6](https://perl6.org), ~~28 25~~ 24 bytes
```
%*ENV<PATH>.split(':')».put
```
```
put %*ENV<PATH>~~tr/:/\n/
```
```
put %*ENV<PATH>~~tr/:/
/
```
[Answer]
# C#, 64 bytes
```
x=>Environment.GetEnvironmentVariable("PATH").Replace(";","\n");
```
Anonymous function which returns the path variable, each directory on a separate line. Note that `x` is just a dummy object to save 1 byte instead of using `()`.
Full program:
```
using System;
namespace ExportPathVariable
{
class Program
{
static void Main(string[] args)
{
Func<object,string>f= x=>Environment.GetEnvironmentVariable("PATH").Replace(";","\n");
Console.WriteLine(f(0));
}
}
}
```
Also works on UNIX systems if you replace `;` with `:`, presuming Mono libraries are available. **Try it online on [ideone](http://ideone.com/SW2O31), .NET Fiddle returns a security exception.**
Alternatively, a full C# program, which is rather verbose:
---
# C#, 118 bytes
```
using System;class P{static void Main(){Console.Write(Environment.GetEnvironmentVariable("PATH").Replace(";","\n"));}}
```
[Answer]
## Haskell, 72 bytes
```
import System.Environment
m ':'='\n'
m x=x
map m<$>getEnv"PATH">>=putStr
```
An expensive import and no `replace` within the standard library make it quite long.
[Answer]
# [Factor](https://factorcode.org), 28 bytes
for unix-likes. I dunno how to do it on Windows since I'm not at a Windows box.
```
"PATH"getenv ":" "\n"replace
```
[Answer]
# Awk, ~~51~~ 44 characters
```
BEGIN{$0=ENVIRON["PATH"];gsub(":",RS);print}
```
Thanks to:
* [ninjalj](https://codegolf.stackexchange.com/users/267/ninjalj) for suggesting to use `gsub()` instead of manipulating built-in variables (-7 characters)
The typical `awk` way would be to set up the built-in variables which influences how `awk` manipulates the data automatically:
```
BEGIN{FS=":";OFS=RS;$0=ENVIRON["PATH"];$1=$1;print}
```
Sample run:
```
bash-4.3$ PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
bash-4.3$ awk 'BEGIN{FS=":";OFS=RS;$0=ENVIRON["PATH"];$1=$1;print}'
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
```
[Answer]
# Node.js, 36 bytes
```
_=>process.env.PATH.split`:`.join`
`
```
Pretty straight forward.
[Answer]
# MATLAB, 34 bytes
```
disp(strrep(getenv('PATH'),58,10))
```
Here is an [online demo](https://ideone.com/zjgtYx) in Octave with a slight modification since `strrep` in octave requires the second and third inputs to be `char` variables rather than numeric values.
[Answer]
# R, 38 bytes
```
cat(gsub(":","\n",Sys.getenv('PATH')))
```
Grab the $PATH, replace `:` with newlines and prints to stdout. [You can try it online here.](http://www.r-fiddle.org/#/fiddle?id=VapdHjKl)
[Answer]
# Groovy, 43 Bytes
```
System.env['PATH'].replaceAll(":","\n")
```
[Answer]
# Gema, 36 characters
```
\A=@subst{\\:=\\n;@getenv{PATH}}@end
```
Sample run:
```
bash-4.3$ PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
bash-4.3$ gema '\A=@subst{\\:=\\n;@getenv{PATH}}@end'
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
```
[Answer]
# Befunge-98 + EVAR fingerprint, 34 bytes
```
"RAVE"4("HTAP"Gv
:!k@:':-!'0*-, >
```
Loads the EVAR fingerprint (`"RAVE"4(`) to easily access environment variables, gets the PATH envvar (`"HTAP"G`), and for each character, exits the program if the character is "\0" (`:!k@`), substracts ASCII 48 "0" if the char is ASCII 58 ":" (`:':-!'0*-`), and outputs the character (`,`).
[Answer]
# ELF/x86, 78 bytes
```
00000000 7f 45 4c 46 01 00 00 00 43 0f 00 00 43 5f eb 10 |.ELF....C...C_..|
00000010 02 00 03 00 0c 50 eb 10 0c 50 eb 10 04 00 00 00 |.....P...P......|
00000020 5f 5f b1 05 be 49 50 eb 10 3d 20 00 01 00 5f f3 |__...IP..= ..._.|
00000030 a6 75 ef 89 f9 80 3f 3a 75 03 80 2f 30 42 ae 75 |.u....?:u../0B.u|
00000040 f4 4a 04 04 cd 80 93 cd 80 50 41 54 48 3d |.J.......PATH=|
0000004e
```
NASM source:
```
BITS 32 ;
ORG 0x10eb5000 ;
; ELF HEADER -- PROGRAM HEADER
; ELF HEADER ; +-------------+
DB 0x7f,'E','L','F' ; | magic | +--------------------+
; | | | |
; PROGRAM HEADERS ; | | | |
DD 1 ; |*class 32b | -- | type: PT_LOAD |
; |*data none | | |
; |*version 0 | | |
; |*ABI SysV | | |
DD 0xf43 ; offset = vaddr & (PAGE_SIZE-1); |*ABI vers | -- | offset |
; | | | |
entry: inc ebx ; STDOUT_FILENO ; |*PADx7 | -- | vaddr = 0x10eb5f43 |
pop edi ; discard argc ; | | | |
jmp short skip ; | | | |
DW 2 ; | ET_EXEC | -- |*paddr LO |
DW 3 ; | EM_386 | -- |*paddr HI |
DD 0x10eb500c ; |*version | -- | filesz |
DD 0x10eb500c ; | entry point | -- | memsz |
DD 4 ; | ph offset | -- | flags: RX |
; | | | |
skip: pop edi ; discard argv[0] ; |*sh offset | -- |*align |
pop edi ; discard argv[1]=NULL ; | | | |
env: mov cl,5 ; \ strlen("PATH=") ; | | | |
mov esi,PATH; > "PATH=" ; |*flags /--| | |
DB 0x3d ; cmp eax,0x10020 ; |*ehsize | +--------------------+
DW 32 ; | phentsize |
DW 1 ; | phnum |
; | |
pop edi ; > envp ; |*shentsize |
repe cmpsb ; > strcmp(envp,"PATH="); |*shnum |
jne env ; / ; |*shstrndx |
mov ecx,edi ; +-------------+
nlcolon:cmp byte[edi],58 ; \ if (char == ':')
jne nosub ; >
sub byte[edi],48 ; > char -= '0'
nosub: inc edx ; > wlen++
scasb ; >
jne nlcolon ; / while(char != 0)
dec edx ; wlen--
add al,4
int 0x80 ; write(1, ecx, wlen)
xchg eax,ebx
int 0x80 ; exit(...)
PATH: db "PATH="
```
] |
[Question]
[
This should be a fairly simple challenge.
For an array of numbers, generate an array where for every element all neighbouring elements are added to itself, and return the sum of that array.
Here is the transformation which occurs on the input array `[1,2,3,4,5]`
```
[1,2,3,4,5] => [1+2, 2+1+3, 3+2+4, 4+3+5, 5+4] => [3,6,9,12,9] => 39
0 => neighbours of item 0, including item 0
[1,2] => 1 + 2 => 3
1
[1,2,3] => 1 + 2 + 3 => 6
2
[2,3,4] => 2 + 3 + 4 => 9
3
[3,4,5] => 3 + 4 + 5 => 12
4
[4,5] => 4 + 5 => 9
3+6+9+12+9 => 39
```
### Test cases
```
[] => 0 (or falsy)
[1] => 1
[1,4] => 10 (1+4 + 4+1)
[1,4,7] => 28
[1,4,7,10] => 55
[-1,-2,-3] => -14
[0.1,0.2,0.3] => 1.4
[1,-20,300,-4000,50000,-600000,7000000] => 12338842
```
### Leaderboard
```
var QUESTION_ID=96188,OVERRIDE_USER=41257;function answersUrl(e){return"http://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"http://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]
# Python, 25 bytes
```
lambda a:sum((a*3)[1:-1])
```
To see why this works, rotate the expansion in the OP by 45 degrees:
```
1 + 2
+ 1 + 2 + 3 2 + 3 + 4 + 5
+ 2 + 3 + 4 = + 1 + 2 + 3 + 4 + 5
+ 3 + 4 + 5 + 1 + 2 + 3 + 4.
+ 4 + 5
```
[Answer]
# Python 2, 28 bytes
```
lambda a:sum(a)*3-a[0]-a[-1]
```
Just 3 times the sum and minus one of each end element
[Answer]
# [MATL](http://github.com/lmendo/MATL), 5 bytes
```
7BZ+s
```
[Try it online!](http://matl.tryitonline.net/#code=N0JaK3M&input=WzEsLTIwLDMwMCwtNDAwMCw1MDAwMCwtNjAwMDAwLDcwMDAwMDBd)
### Explanation
```
7B % Push array [1, 1, 1], obtained as 7 in binary
Z+ % Take input implicitly. Convolve with [1, 1, 1], keeping size
s % Sum of resulting array. Display implicitly
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~11~~ 5 bytes
Saved 6 bytes thanks to *Adnan*.
```
€Ð¦¨O
```
[Try it online!](http://05ab1e.tryitonline.net/#code=4oKsw5DCpsKoTw&input=WzEsLTIwLDMwMCwtNDAwMCw1MDAwMCwtNjAwMDAwLDcwMDAwMDBd)
**Explanation**
```
€Ð # triplicate each item in the list
¦¨ # remove first and last element
O # sum
```
[Answer]
## JavaScript (ES6), ~~40~~ 33 bytes
```
l=>eval(l.join`+`)*3-l[0]-l.pop()
```
Returns `NaN` when given an empty list.
[Answer]
## R, 75 70 52 34 33 31 bytes
Sum times three and subtract first and last element
```
sum(x<-scan())*3-x[1]-tail(x,1)
```
Edit: Saved 3 extra bytes thanks to @rturnbull
[Answer]
# Scala, 47 bytes
```
def&(a:Float*)=(0+:a:+0)sliding 3 map(_.sum)sum
```
Prepends and appends a 0, then uses a sliding window of size 3 to sum the neighbors, and calculates the total sum
[Answer]
# Java 7, 72 Bytes
```
float c(float[]a){float s=0,l=0;for(float i:a)s+=l=i;return 3*s-l-a[0];}
```
[Answer]
## Mathematica, ~~34~~ ~~32~~ 29 bytes
*Taking some inspiration Lynn's neat [Python answer](https://codegolf.stackexchange.com/a/96217/8478)...*
```
Check[3Tr@#-Last@#-#[[1]],0]&
```
or
```
Check[3(+##)-#&@@#-Last@#,0]&
```
or
```
Check[##-#/3&@@#*3-Last@#,0]&
```
Unfortunately, this approach isn't quite as convenient in Mathematica as it is in Python, because there's no short and safe way to discard the first and last element of a list that might be empty.
[Answer]
# MATLAB, ~~31~~ ~~28~~ 26 bytes
*3 bytes saved thanks to @Luis*
```
@(x)sum(conv(x,1:3>0,'s'))
```
This creates an anonymous function named `ans` that can be called like: `ans([1, 2, 3, 4, 5])`
In order to provide an online demo (which uses Octave), I had to use `'same'` instead of `'s'` as the last input to `conv`
[**Online Demo**](http://ideone.com/RB0j0J)
**Explanation**
We perform convolution (`conv`) with a `1 x 3` kernel of all 1's (created by making an array `1:3` and then comparing to zero `>0`) and keep the size of the original by specifying the third input as `'same'` or in MATLAB we can simply shorten this to `'s'`. We then apply the sum to the result.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 5 bytes
```
ẋ3ṖḊS
```
[Try it online!](http://jelly.tryitonline.net/#code=4bqLM-G5luG4ilM&input=)
Translation of my [Python answer](https://codegolf.stackexchange.com/a/96217/3852).
```
ẋ3 Concatenate three copies of the input list
Ṗ Remove the last element
Ḋ Remove the first element
S Sum
```
[Answer]
# J, 9 bytes
```
+/@,}.,}:
```
For `[1, 2, 3, 4, 5]`, the neighbors are
```
1 2 3 4 5
1+2
1+2+3
2+3+4
3+4+5
4+5
```
Then look along the diagonals of the sums
```
(2+3+4+5)+(1+2+3+4+5)+(1+2+3+4)
```
So we need only the find the sum of the input with its head removed and with its tail removed.
## Usage
```
f =: +/@,}.,}:
f 1 2 3 4 5
39
f '' NB. Empty array
0
f 1
1
f 1 4
10
f 1 4 7
28
f 1 4 7 10
55
f _1 _2 _3
_14
f 0.1 0.2 0.3
1.4
f 1 _20 300 _4000 50000 _600000 7000000
12338842
```
## Explanation
```
+/@,}.,}: Input: array A
}: Return a list with the last value in A removed
}. Return a list with the first value in A removed
, Join them
, Join that with A
+/@ Reduce that using addition to find the sum and return
```
[Answer]
# [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak), 68 bytes
```
(<><>)([]){{}({}({})<>{})<>({}<(({})<>{})><>)([][()()])}{}({}{}<>{})
```
[Try it online!](http://brain-flak.tryitonline.net/#code=KDw-PD4pKFtdKXt7fSh7fSh7fSk8Pnt9KTw-KHt9PCgoe30pPD57fSk-PD4pKFtdWygpKCldKX17fSh7fXt9PD57fSk&input=MQoyCjMKNAo1)
Explanation:
```
#Push a 0
(<><>)
#Push the stack height
([])
#While true:
{
#Pop the stack height
{}
#Add the sum of the top 3 elements to the other stack, and pop the top of the stack
({}({})<>{})<>({}<(({})<>{})><>)
#Push the new stack height minus two
([][()()])
#End
}
#Pop the exhausted counter
{}
#Add the top two numbers to the other stack
({}{}<>)
```
[Answer]
## PowerShell v2+, 40 bytes
```
param($a)($a-join'+'|iex)*3-$a[0]-$a[-1]
```
Similar to the other answers, sums the list, multiplies by 3, subtracts the end elements. Barfs out a spectacular error for empty input, and then spits out `0`, but since STDERR is ignored by default, this is OK.
```
PS C:\Tools\Scripts\golfing> .\sum-of-neighbors.ps1 @()
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\sum-of-neighbors.ps1:1 char:22
+ param($a)($a-join'+'|iex)*3-$a[0]-$a[-1]
+ ~~~
+ CategoryInfo : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand
0
PS C:\Tools\Scripts\golfing> .\sum-of-neighbors.ps1 @(1)
1
PS C:\Tools\Scripts\golfing> .\sum-of-neighbors.ps1 @(1,4)
10
PS C:\Tools\Scripts\golfing> .\sum-of-neighbors.ps1 @(1,4,7)
28
PS C:\Tools\Scripts\golfing> .\sum-of-neighbors.ps1 @(1,4,7,10)
55
PS C:\Tools\Scripts\golfing> .\sum-of-neighbors.ps1 @(-1,-2,-3)
-14
PS C:\Tools\Scripts\golfing> .\sum-of-neighbors.ps1 @(0.1,0.2,0.3)
1.4
PS C:\Tools\Scripts\golfing> .\sum-of-neighbors.ps1 @(1,-20,300,-4000,50000,-600000,7000000)
12338842
```
[Answer]
# Ruby, ~~35~~ ~~33~~ 31 bytes
Inspired by Lynn's solution:
```
->a{[*(a*3)[1..-2]].reduce:+}
```
The `to_a` segment is there to handle the empty array.
EDIT: Thanks to m-chrzan and histocrat.
[Answer]
# [Perl 6](https://perl6.org), 25 bytes
```
{.sum*3-.[0]-(.[*-1]//0)} # generates warning
{+$_&&.sum*3-.[0]-.[*-1]}
```
## Expanded:
```
# bare block lambda with implicit parameter 「$_」
{
+$_ # the number of elements
&& # if that is 0 return 0, otherwise return the following
.sum * 3 # sum them up and multiply by 3
- .[ 0 ] # subtract the first value
- .[*-1] # subtract the last value
}
```
## Test:
```
use v6.c;
use Test;
my &code = {+$_&&.sum*3-.[0]-.[*-1]}
my @tests = (
[] => 0,
[1] => 1,
[1,4] => 10,
[1,4,7] => 28,
[1,4,7,10] => 55,
[-1,-2,-3] => -14,
[0.1,0.2,0.3] => 1.4,
[1,-20,300,-4000,50000,-600000,7000000] => 12338842,
);
plan +@tests;
for @tests -> $_ ( :key(@input), :value($expected) ) {
is code(@input), $expected, .gist;
}
```
[Answer]
# PHP, 39 bytes
```
<?=3*array_sum($a=$argv)-$a[1]-end($a);
```
Run like this:
```
echo '<?=3*array_sum($a=$argv)-$a[1]-end($a);' | php -- 1 -20 300 -4000 50000 -600000 7000000 2>/dev/null;echo
```
# Explanation
Challenge can be reduced to adding every number 3 times, except the first and last number (added twice). Therefore I return 3 times the sum, minus the first and last number.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 25 (+3 for `-v`) = 28 bytes
Takes input from the stack with `-v` and assumes stdin is empty, relying on it to provide a `-1` value.
```
:{:}+i*v
:$v?=1l<+++:
;n<
```
[Answer]
# C# with LINQ, 42 bytes
```
a=>3*a.Sum()-(a.Length>0?a[0]+a.Last():0);
```
Requires the `System.Linq` namespace.
---
# C#, 84 bytes
```
a=>{int i=0,l=a.Length;var r=0d;for(;i<l;)r+=3*a[i++];return(l>0?r-a[0]-a[l-1]:0);};
```
Full program with test cases:
```
using System;
namespace SumOfNeighbours
{
class Program
{
static void Main(string[] args)
{
Func<double[],double>f= a=>{int i=0,l=a.Length;var r=0d;for(;i<l;)r+=3*a[i++];return(l>0?r-a[0]-a[l-1]:0);};
// test cases:
double[] x = new double[]{1,2,3,4,5};
Console.WriteLine(f(x)); // 39
x = new double[] {};
Console.WriteLine(f(x)); // 0
x = new double[] {1};
Console.WriteLine(f(x)); // 1
x = new double[] {1,4};
Console.WriteLine(f(x)); // 10 (1+4 + 4+1)
x = new double[] {1,4,7};
Console.WriteLine(f(x)); // 28
x = new double[] {1,4,7,10};
Console.WriteLine(f(x)); // 55
x = new double[] {-1,-2,-3};
Console.WriteLine(f(x)); // -14
x = new double[] {0.1,0.2,0.3};
Console.WriteLine(f(x)); // 1.4
x = new double[] {1,-20,300,-4000,50000,-600000,7000000};
Console.WriteLine(f(x)); // 12338842
}
}
}
```
[Answer]
## Racket 48 bytes
```
(if(null? l)0(-(* 3(apply + l))(car l)(last l)))
```
Ungolfed:
```
(define (f lst)
(if (null? lst)
0
(- (* 3 (apply + lst))
(first lst)
(last lst))))
```
Testing:
```
(f '())
(f '(1))
(f '(1 4))
(f '(1 4 7))
(f '(1 4 7 10))
(f '(-1 -2 -3))
(f '(0.1 0.2 0.3))
(f '(1 -20 300 -4000 50000 -600000 7000000))
```
Output:
```
0
1
10
28
55
-14
1.4000000000000001
12338842
```
[Answer]
# [Gloo](https://github.com/kade-robertson/gloo), 12 Bytes
Turns out a feature of Gloo isn't working as intended so I had to do this a painful way.
```
__]:]:]:,,[+
```
Explanation:
```
__ // duplicate the input list twice
]:]:]: // flatten each list, and rotate stack left
,, // pop the last 2 numbers
// (which are the first and last element of the list)
[+ // wrap all items in a list and sum.
```
[Answer]
# [Elixir](http://elixir-lang.org/), 93 bytes
```
&if (length(&1)>0),do: Enum.reduce(&1,fn(n,r)->n+r end)*3-Enum.at(&1,0)-List.last(&1),else: 0
```
Anonymous function using the capture operator.
Full program with test cases:
```
s=&if (length(&1)>0),do: Enum.reduce(&1,fn(n,r)->n+r end)*3-Enum.at(&1,0)-List.last(&1),else: 0
# test cases:
IO.puts s.([]) # 0
IO.puts s.([1]) # 1
IO.puts s.([1,4]) # 10 (1+4 + 4+1)
IO.puts s.([1,4,7]) # 28
IO.puts s.([1,4,7,10]) # 55
IO.puts s.([-1,-2,-3]) # -14
IO.puts s.([0.1,0.2,0.3]) # 1.4
IO.puts s.([1,-20,300,-4000,50000,-600000,7000000]) # 12338842
```
**Try it online on [ElixirPlayground](http://elixirplayground.com/) !**
[Answer]
# TI-Basic, 17 bytes
Simply three times the sum of the list, minus the first and last element.
```
3sum(Ans)-Ans(1)-Ans(dim(Ans)-1
```
[Answer]
# Ruby, 41 bytes
```
->a{a.reduce(0,:+)*3-(a[0]?a[0]+a[-1]:0)}
```
Full program with test cases:
```
f=->a{a.reduce(0,:+)*3-(a[0]?a[0]+a[-1]:0)}
#test cases
a=[]
puts f.call(a) # 0
a=[1]
puts f.call(a) # 1
a=[1,4]
puts f.call(a) # 10
a=[1,4,7]
puts f.call(a) # 28
a=[1,4,7,10]
puts f.call(a) # 55
a=[-1,-2,-3]
puts f.call(a) # -14
a=[0.1,0.2,0.3]
puts f.call(a) # 1.4
a=[1,-20,300,-4000,50000,-600000,7000000]
puts f.call(a) # 12338842
```
My first attempt in Ruby.
[Answer]
# Javascript, 46 bytes
```
a.reduce((t,c,i)=>t+(a[i-1]|0)+c+(a[i+1]|0),0)
```
```
const a = [1,2,3,4,5];
console.log(a.reduce((t,c,i)=>t+(a[i-1]|0)+c+(a[i+1]|0),0));
```
Thanks @rlemon for the extra 2 bytes
[Answer]
## Pyke, ~~9~~ 5 bytes
```
3*tOs
```
[Try it here!](http://pyke.catbus.co.uk/?code=3%2atOs&input=%5B1%2C4%2C7%2C10%5D)
[Answer]
# Java 8, 60
```
d->d.length>0?Arrays.stream(d).sum()*3-d[0]-d[d.length-1]:0;
```
[Answer]
# C++, 67 bytes
```
#import<valarray>
int f(std::valarray<int>v){return 3*v.sum()-v[0]-v[v.size()-1];}
```
Usage:
```
#include <iostream>
int main() {
std::cout << f({1,2,1});
return 0;
}
```
[Answer]
# Haskell, 25 bytes
From fastest
```
sum.sequence[(0-).head,(3*).sum,(0-).last]$[1..5]
```
via prettiest
```
sum.sequence[sum.init,sum,sum.tail]$[1..5]
```
down to ugliest but shortest
```
let y x=sum$init x++x++tail x in y[1..5]
-- 1234567890123456789012345
```
[Answer]
## Batch, 67 bytes
```
@set/as=l=0
@for %%n in (%*)do @set/as+=l=%%n
@cmd/cset/as*3-%1-l
```
If there are no parameters, the last command turns into `0 * 3 - -0`.
] |
[Question]
[
**Note 2: I accepted `@DigitalTrauma`'s 6-byte long answer. If anyone can beat that I will change the accepted answer. Thanks for playing!**
**Note: I will be accepting an answer at 6:00pm MST on 10/14/15. Thanks to all that participated!**
I am very surprised that this has not been asked yet (or I didn't search hard enough). Either way, this challenge is very simple:
**Input:** A program in the form of a string. Additionally, the input may or may not contain:
* Leading and trailing spaces
* Trailing newlines
* Non-ASCII characters
**Output:** Two integers, one representing *UTF-8* character count and one representing byte count, you may choose which order. Trailing newlines are allowed. Output can be to STDOUT or returned from a function. IT can be in any format as long as the two numbers are distinguishable from each other (2327 is not valid output).
**Notes:**
* You may consider newline as `\n` or `\r\n`.
* Here is a nice [byte & character counter](https://mothereff.in/byte-counter) for your tests. Also, here is a [meta post](https://codegolf.meta.stackexchange.com/questions/4944/byte-counter-snippet) with the same thing (Thanks to @Zereges).
**Sample I/O:** (All outputs are in the form `{characters} {bytes}`)
Input:
`void p(int n){System.out.print(n+5);}`
Output: `37 37`
Input: `(~R∊R∘.×R)/R←1↓ιR`
Output: `17 27`
Input:
```
friends = ['john', 'pat', 'gary', 'michael']
for i, name in enumerate(friends):
print "iteration {iteration} is {name}".format(iteration=i, name=name)
```
Output: `156 156`
**This is code golf - shortest code in *bytes* wins!**
## Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=60733,OVERRIDE_USER=36670;function answersUrl(e){return"http://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"http://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]
# Shell + coreutils, 6
This answer becomes invalid if an encoding other than UTF-8 is used.
```
wc -mc
```
### Test output:
```
$ printf '%s' "(~R∊R∘.×R)/R←1↓ιR" | ./count.sh
17 27
$
```
---
In case the output format is strictly enforced (just one space separating the the two integers), then we can do this:
# Shell + coreutils, 12
```
echo`wc -mc`
```
Thanks to @immibis for suggesting to remove the space after the `echo`. It took me a while to figure that out - the shell will expand this to `echo<tab>n<tab>m`, and tabs by default are in `$IFS`, so are perfectly legal token separators in the resulting command.
[Answer]
# GolfScript, ~~14~~ 12 bytes
```
.,p{64/2^},,
```
Try it online on [Web GolfScript](http://golfscript.apphb.com/?c=OyIoflLiiIpS4oiYLsOXUikvUuKGkDHihpPOuVIiICMgU2ltdWxhdGUgaW5wdXQgZnJvbSBTVERJTi4KCi4scHs2NC8yXn0sLA%3D%3D).
### Idea
GolfScript doesn't have a clue what Unicode is; all strings (input, output, internal) are composed of bytes. While that can be pretty annoying, it's perfect for this challenge.
UTF-8 encodes ASCII and non-ASCII characters differently:
* All code points below 128 are encoded as `0xxxxxxx`.
* All other code points are encoded as `11xxxxxx 10xxxxxx ... 10xxxxxx`.
This means that the encoding of each Unicode character contains either a single `0xxxxxxx` byte or a single `11xxxxxx` byte (and 0 to 5 `10xxxxxx` bytes).
By dividing all bytes of the input by **64**, we turn `0xxxxxxx` into **0** or **1**, `11xxxxxx` into **3**, and `10xxxxxx` into **2**. All that's left is to count the bytes whose quotient is not **2**.
### Code
```
(implicit) Read all input and push it on the stack.
. Push a copy of the input.
, Compute its length (in bytes).
p Print the length.
{ }, Filter; for each byte in the original input:
64/ Divide the byte by 64.
2^ XOR the quotient with 2.
If the return is non-zero, keep the byte.
, Count the kept bytes.
(implicit) Print the integer on the stack.
```
[Answer]
# Python, ~~42~~ 40 bytes
```
lambda i:[len(i),len(i.encode('utf-8'))]
```
Thanks to Alex A. for the two bytes off.
Straightforward, does what it says. With argument `i`, prints the length of `i`, then the length of `i` in UTF-8. Note that in order to accept multiline input, the function argument should be surrounded by triple quotes: `'''`.
EDIT: It didn't work for multiline input, so I just made it a function instead.
Some test cases (separated by blank newlines):
```
f("Hello, World!")
13 13
f('''
friends = ['john', 'pat', 'gary', 'michael']
for i, name in enumerate(friends):
print "iteration {iteration} is {name}".format(iteration=i, name=name)
''')
156 156
f("(~R∊R∘.×R)/R←1↓ιR")
17 27
```
[Answer]
# Julia, 24 bytes
```
s->(length(s),sizeof(s))
```
This creates a lambda function that returns a tuple of integers. The `length` function, when called on a string, returns the number of characters. The `sizeof` function returns the number of bytes in the input.
[Try it online](http://goo.gl/RQLbJ5)
[Answer]
# Rust, 42 bytes
```
let c=|a:&str|(a.chars().count(),a.len());
```
[Answer]
# Java, ~~241~~ ~~90~~ 89 bytes
```
int[]b(String s)throws Exception{return new int[]{s.length(),s.getBytes("utf8").length};}
```
[Answer]
# Pyth - ~~12~~ 9 bytes
Will try to get shorter.
```
lQh/l.BQ8
```
[Test Suite](http://pyth.herokuapp.com/?code=lQh%2Fl.BQ8&input=%28%7ER%E2%88%8AR%E2%88%98.%C3%97R%29%2FR%E2%86%901%E2%86%93%CE%B9R&test_suite=1&test_suite_input=%22void+p%28int+n%29%7BSystem.out.print%28n%2B5%29%3B%7D%22%0A%22%28%7ER%E2%88%8AR%E2%88%98.%C3%97R%29%2FR%E2%86%901%E2%86%93%CE%B9R%22%0A%22%5Cnfriends+%3D+%5B%27john%27%2C+%27pat%27%2C+%27gary%27%2C+%27michael%27%5D%5Cnfor+i%2C+name+in+enumerate%28friends%29%3A%5Cn++++print+%5C%22iteration+%7Biteration%7D+is+%7Bname%7D%5C%22.format%28iteration%3Di%2C+name%3Dname%29%5Cn%22&debug=0).
[Answer]
# PowerShell, 57 bytes
```
$args|%{$_.Length;[Text.Encoding]::UTF8.GetByteCount($_)}
```
[Answer]
# C, ~~68~~ 67 bytes
```
b,c;main(t){for(;t=~getchar();b++)c+=2!=~t/64;printf("%d %d",c,b);}
```
This uses the same idea as [my other answer](https://codegolf.stackexchange.com/a/60745).
Try it online on [Ideone](http://ideone.com/CkOOfy).
[Answer]
# R, 47 bytes
```
a<-commandArgs(TRUE);nchar(a,"c");nchar(a,"b")
```
Input: `(~R∊R∘.×R)/R←1↓ιR`
Output:
```
[1] 17
[2] 27
```
If printing line numbers alongside output isn't allowable under the "any format" then `cat` can fix the issue:
# R, 52 bytes
```
a<-commandArgs(TRUE);cat(nchar(a,"c"),nchar(a,"b"))
```
Input: `(~R∊R∘.×R)/R←1↓ιR`
Output: `17 27`
[Answer]
# Brainfuck, 163 bytes
```
,[>+<,]>[>>+>+<<<-]>>>[<<<+>>>-]<<+>[<->[>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]++++++++[<++++++>-]>[<<+>>-]>[<<+>>-]<<]>]<[->>++++++++[<++++++>-]]<[.[-]<]<
```
With linebreaks for readability:
```
,[>+<,]>
[>>+>+<<<-]>>>[<<<+>>>-]<<+>[<->[
>++++++++++<[->-[>+>>]>[+[-<+>]>.
+>>]<<<<<]>[-]++++++++[<++++++>-
]>[<<+>>-]>[<<+>>-]<<]>]<[->>+++++
+++[<++++++>-]]<[.[-]<]<
```
The most important part is the first line. This counts the number of characters inputted. The rest is just the long junk required to print a number greater than 9.
EDIT: Since BF cannot input/output anything but ASCII numbers from 1-255, there would be no way to measure the UTF-8 chars.
[Answer]
# [Scala](http://www.scala-lang.org/), ~~30~~ 26 bytes
```
s=>s.size->s.getBytes.size
```
[Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFCgUM1VlpijkGalEFxSlJmXrmBrp6DhmVeiA8SaCrb/i23tivWKM6tSdYF0emqJU2VJKkTgfwFQfUlOnkaahpKhguGj3i0mSpqaXLX/AQ "Scala – Try It Online")
My first Scala answer! Thanks to user for making it work.
-4 bytes from user.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
á!╜¡tº
```
[Run and debug it](https://staxlang.xyz/#p=a021bdad74a7&i=%22void+p%28int+n%29%7BSystem.out.print%28n%2B5%29%3B%7D%22%0A%22%28%7ER%E2%88%8AR%E2%88%98.%C3%97R%29%2FR%E2%86%901%E2%86%93%CE%B9R%22%0A%22%5Cnfriends+%3D+%5B%27john%27,+%27pat%27,+%27gary%27,+%27michael%27%5D%5Cnfor+i,+name+in+enumerate%28friends%29%3A%5Cn++++print+%5C%22iteration+%7Biteration%7D+is+%7Bname%7D%5C%22.format%28iteration%3Di,+name%3Dname%29%5Cn%22&m=2)
## Explanation
```
%Px|k%P
% get length
P pop and print with newline
x push input again
|k get byte array
% get length
P pop and print with newline
```
[Answer]
# [Milky Way 1.6.2](https://github.com/zachgates7/Milky-Way), 7 bytes
```
':y!^P!
```
---
### Explanation
```
' ` read input from the command line
: ` duplicate the TOS
y ` push the length of the TOS
! ! ` output the TOS
^ ` pop the TOS
P ` push the length of the TOS in bytes
```
---
### Usage
```
./mw <path-to-code> -i <input>
```
[Answer]
## Perl 6, 33 bytes
```
$x=get;say $x.chars," ",$x.codes;
```
Based on [this blog post](https://perl6advent.wordpress.com/2015/12/07/day-7-unicode-perl-6-and-you) at Perl6Advent.
[Answer]
# beeswax, ~~99~~ 87 bytes
A more compact version, 12 bytes shorter than the first:
```
p~5~q")~4~p")~7~g?<
>)'qq>@PPq>@Pp>Ag'd@{
>@PPPq @dNp"?{gAV_
>@PPPP>@>?b>N{;
```
The same, as easier to follow hexagonal layout:
```
p ~ 5 ~ q " ) ~ 4 ~ p " ) ~ 7 ~ g ? <
> ) ' q q > @ P P q > @ P p > A g ' d @ {
> @ P P P q @ d N p " ? { g A V _
> @ P P P P > @ > ? b > N { ;
```
Output as `characters`, then `bytecount`, separated by a newline.
Example:
the small letter `s` at the beginning of the line just tells the user that the program wants a string as input.
```
julia> beeswax("utf8bytecount.bswx")
s(~R∊R∘.×R)/R←1↓ιR
17
27
Program finished!
```
Empty string example:
```
julia> beeswax("utf8bytecount.bswx")
s
0
0
Program finished!
```
Beeswax pushes the characters of a string that’s entered at STDIN onto the global stack, coded as the values of their Unicode code points.
For easier understanding, here is the unwrapped version of the program above:
```
>@{; >@P@p >@PP@p>@P p
_VAg{?"pN>Ag"d?g~7~)"d~4~)"d~5~)"d@PPp
;{N< d? < < @PP<
```
For this example, the character `α` is entered at STDIN (code point `U+03B1`, decimal:`945`)
```
gstack lstack
_VA [945,1]• [0,0,0]• enter string, push stack length on top of gstack
g [0,0,1]• push gstack top value on top of local stack (lstack)
{ lstack 1st value to STDOUT (num. of characters)
? [945]• pop gstack top value
" skip next if lstack 1st >0
N> print newline, redirect to right
Ag [945,1]• [0,0,1]• push gstack length on top of gstack, push that value on lstack.
" skip if lstack 1st > 0
? [945]• pop gstack top value
g [0,0,945]• push gstack top value on lstack
~ [0,945,0]• flip lstack 1st and 2nd
7 [0,945,7]• lstack 1st=7
~ [0,7,945]• flip lstack 1st and 2nd
) [0,7,7]• lstack 1st = lstack 1st >>> 2nd (LSR by 7)
" skip next if top >0
~4~) [0,0,0]• flip,1st=4,flip,LSR by 4
"d skip next if top >0... redirect to upper right
>@ redirect to right, flip lstack 1st and 3rd
PP@ [2,0,0]• increment lstack 1st twice, flip 1st and 3rd
p redirect to lower left
" (ignored instruction, not relevant)
d? < < []• redirect to left... pop gstack, redirect to upper right
>Ag"d [0]• [2,0,0]• redir. right, push gstack length on gstack
push gstack top on lstack, skip next if lstack 1st > 0
redir. to upper right.
>@ [0,0,2]• redir right, flip lstack 1st/3rd
{; output lstack 1st to STDOUT, terminate program
```
Basically, this program checks each codepoint value for the 1-byte, 2-byte, 3-byte and 4-byte codepoint limits.
If `n` is the codepoint value, then these limits for proper UTF-8 strings are:
```
codepoint 0...127 1-byte: n>>>7 = 0
128...2047 2-byte: n>>>11= 0 → n>>>7>>>4
2048...65535 3-byte: n>>>16= 0 → n>>>7>>>4>>>5
65535...1114111 4-byte: the 3 byte check result is >0
```
You can find the numbers `7`,`4` and `5` for the shift instructions in the code above.
If a check results in `0`, the lstack counter is incremented appropriately to tally the number of bytes of the entered string. The `@PP...@` constructs increment the byte counter. After each tally, the topmost Unicode point is popped from the gstack until it is empty. Then the byte count is output to STDOUT and the program terminated.
There are no checks for improper encoding like overlong ASCII encoding and illegal code points beyond `0x10FFFF`, but I think that’s fine ;)
[Answer]
# Swift 3, 37
`{($0.characters.count,$0.utf8.count)}` // where `$0` is `String`
## Usage
[Test](http://swiftlang.ng.bluemix.net/#/repl/58168b3e586da353fafab4f7)
`{($0.characters.count,$0.utf8.count)}("Hello, world")`
[Answer]
# [Julia](http://julialang.org/), 22 bytes
Improvement of [Alex A.'s answer](https://codegolf.stackexchange.com/a/60741/98541)
```
s->length(s):sizeof(s)
```
[Try it online!](https://tio.run/##yyrNyUw0rPifZvu/WNcuJzUvvSRDo1jTqjizKjU/Dcj6X5JaXFKsYKsQzaVUlp@ZolCgkZlXopCnWR1cWVySmquXX1qiV1AEFNPI0zbVtK5V4lLSqAt61NEFxDP0Dk8P0tQPetQ2wfBR2@RzO4OUuGK5uMDKc/L0NNL0NMDGa2r@BwA "Julia 1.0 – Try It Online")
] |
[Question]
[
Write a function which takes in a list of positive integers and returns a list of integers approximating the percent of total for the corresponding integer in the same position.
All integers in the return list must exactly add up to 100. You can assume the sum of integers passed in is greater than 0. How you want to round or truncate decimals is up to you as long as any single resulting integer returned as a percentage is off by no more than 1 in either direction.
```
p([1,0,2]) -> [33,0,67] or [34,0,66]
p([1000,1000]) -> [50,50] or [49,51] or [51,49]
p([1,1,2,4]) -> [12,12,25,51] or [13,12,25,50] or [12,13,25,50] or [13,13,25,49] or [13,12,26,49] or [12,13,26,49] or [12,12,26,50]
p([0,0,0,5,0]) -> [0,0,0,100,0]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
[Answer]
# Dyalog APL, ~~21~~ ~~19~~ 16 bytes
```
+\⍣¯1∘⌊100×+\÷+/
```
The above is a train equivalent of
```
{+\⍣¯1⌊100×+\⍵÷+/⍵}
```
[Try it online.](http://tryapl.org/?a=p%u2190+%5C%u2363%AF1%u2218%u230A100%D7+%5C%F7+/%20%u22C4%20p%201%201%202%204&run)
### How it works
```
⍝ Sample input: 1 1 2 4
+\ ⍝ Cumulative sum of input. (1 2 4 8)
+/ ⍝ Sum of input. (8)
÷ ⍝ Divide the first result by the second. (0.125 0.25 0.5 1)
100× ⍝ Multiply each quotient by 100. (12.5 25 50 100)
⌊ ⍝ Round the products down to the nearest integer... (12 25 50 100)
∘ ⍝ and ...
⍣¯1 ⍝ apply the inverse of...
+\ ⍝ the cumulative sum. (12 13 25 50)
```
[Answer]
# TI-BASIC, ~~26~~ ~~23~~ 16 bytes
For TI-83+/84+ series calculators.
```
ΔList(augment({0},int(cumSum(ᴇ2Ans/sum(Ans
```
Thanks to @Dennis for a beautiful algorithm! We take the cumulative sum of the list after converting to percents, then floor, tack a 0 onto the front, and take differences. `ᴇ2` is one byte shorter than `100`.
At the same byte count is:
```
ΔList(augment({0},int(cumSum(Ans/sum(Ans%
```
Fun fact: `%` is a [two-byte token](http://tibasicdev.wikidot.com/percent) that multiplies a number by .01—but there's no way to type it into the calculator! You need to either edit the source outside or use an assembly program.
Old code:
```
int(ᴇ2Ans/sum(Ans
Ans+(ᴇ2-sum(Ans)≥cumSum(1 or Ans
```
The first line calculates all floored percents, then the second line adds 1 to the first `N` elements, where `N` is the percentage left over. `cumSum(` stands for "cumulative sum".
Example with `{1,1,2,4}`:
```
sum(Ans ; 8
int(ᴇ2Ans/ ; {12,12,25,50}
1 or Ans ; {1,1,1,1}
cumSum( ; {1,2,3,4}
ᴇ2-sum(Ans) ; 1
≥ ; {1,0,0,0}
Ans+ ; {13,12,25,50}
```
We won't have `N>dim([list]`, because no percentage is decreased by more than 1 in flooring.
[Answer]
# CJam, ~~25~~ ~~23~~ 22 bytes
```
{_:e2\:+f/_:+100-Xb.+}
```
*Thanks to @Sp3000 for 25 → 24.*
[Try it online.](http://cjam.aditsu.net/#code=q~%20e%23%20Read%20input.%20Evaluate.%0A%0A%7B_%3Ae2%5C%3A%2Bf%2F_%3A%2B100-Xb.%2B%7D%0A%0A~p%20e%23%20Execute%20function.%20Print.&input=%5B1%201%202%204%5D)
### How it works
```
_ e# Push a copy of the input.
:e2 e# Apply e2 to each integer, i.e., multiply by 100.
\ e# Swap the result with the original.
:+ e# Add all integers from input.
f/ e# Divide the product by the sum. (integer division)
_:+ e# Push the sum of copy.
100- e# Subtract 100. Let's call the result d.
Xb e# Convert to base 1, i.e., push an array of |d| 1's.
.+ e# Vectorized sum; increment the first |d| integers.
```
[Answer]
### [J (8.04 beta)](http://jsoftware.com/), 59 bytes (30 stolen bytes)
30 byte literal J-port of [Dennis's APL answer](https://codegolf.stackexchange.com/a/60062/571):
```
f=.3 :'+/\^:_1<.100*(+/\%+/)y'
f 1 1 2 4
12 13 25 50
```
59 bytes answer, best I could do myself:
```
f=.3 :0
p=.<.100*y%+/y
r=.100-+/p
p+((r$1),(#p-r)$0)/:\:p
)
```
(Based on the remainder having to go to the highest values, no more than +1 each, split over multiple values in the case of a remainder > 1 or a tie for highest value).
e.g.
```
f 1 0 2
33 0 67
f 1000 1000
50 50
f 1 1 2 4
12 12 25 51
f 0 0 0 5 0
0 0 0 100 0
f 16 16 16 16 16 16
17 17 17 17 16 16
f 0 100 5 0 7 1
0 89 4 0 7 0
```
Explanation
* `f=.3 : 0` - 'f' is a variable, which is a verb type (3), defined below (:0):
* `p=.` variable 'p', built from:
+ `y` is a list of numbers `1 0 2`
+ `+/y` is '+' put between each value '/', the sum of the list `3`
+ `y % (+/y)` is original y values divided by the sum: `0.333333 0 0.666667`
+ `100 * (y%+/y)` is 100x those values: `33.33.. 0 0.66...` to get the percentages.
+ `<. (100*y%+/y)` is the floor operator applied to the percentages: `33 0 66`
* `r=.` variable 'r', built from:
+ `+/p` is the sum of the floored percentages: `99`
+ `100 - (+/p)` is 100 - the sum, or the remaining percentage points needed to make the percentages sum to 100.
* result, not stored:
+ `r $ 1` is a list of 1s, as long as the number of items we need to increment: `1 [1 1 ..]`
+ `#p` is the length of the percentage list
+ `(#p - r)` is the count of items that won't be incremented
+ `(#p-r) $ 0` is a list of 0s as long as that count: `0 0 [0 ..]`
+ `((r$1) , (#p-r)$0)` is the 1s list followed by the 0s list: `1 0 0`
+ `\: p` is a list of indexes to take from `p` to put it in descending order.
+ `/: (\:p)` is a list of indexes to take from `\:p` to put that in ascending order
+ `((r$1),(#p-r)$0)/:\:p` is taking the elements from the 1 1 .. 0 0 .. mask list and sorting so there are 1s in the positions of the biggest percentages, one for each number we need to increment, and 0s for other numbers: `0 0 1`.
+ `p + ((r$1),(#p-r)$0)/:\:p` is the percentages + the mask, to make the result list which sums to 100%, which is the function return value.
e.g.
```
33 0 66 sums to 99
100 - 99 = 1
1x1 , (3-1)x0 = 1, 0 0
sorted mask = 0 0 1
33 0 66
0 0 1
-------
33 0 67
```
and
* `)` end of definition.
I'm not very experienced with J; I wouldn't be too surprised if there's a "turn list into percentages of the total" operation built in, and a cleaner way to "increment *n* biggest values" too. (This is 11 bytes less than my first attempt).
[Answer]
# Mathematica, 41 bytes
```
(s=Floor[100#/Tr@#];s[[;;100-Tr@s]]++;s)&
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
-2 thanks to Dennis, reminding me to use another new feature (`Ä`) and using `:` instead of what I initially had.
```
ŻÄ׳:SI
```
[Try it online!](https://tio.run/##y0rNyan8///o7sMth6cf2mwV7Pk/2lDHUMdIxyT2cPt/AA "Jelly – Try It Online")
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
0;+\÷S×ȷ2ḞI
```
[Try it online!](https://tio.run/##y0rNyan8/9/AWjvm8Pbgw9NPbDd6uGOe5////6MNdQx1jHRMYgE "Jelly – Try It Online")
Done alongside [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) and [user202729](https://codegolf.stackexchange.com/users/69850/user202729) in [chat](https://chat.stackexchange.com/rooms/57815/jelly-hypertraining).
## How it works
```
0;+\÷S×ȷ2ḞI - Full program.
0; - Prepend a 0.
+\ - Cumulative sum.
÷S - Divided by the sum of the input.
×ȷ2 - Times 100. Replaced by ׳ in the monadic link version.
ḞI - Floor each, compute the increments (deltas, differences).
```
[Answer]
# JavaScript (ES6), 81 bytes
```
a=>(e=0,a.map(c=>((e+=(f=c/a.reduce((c,d)=>c+d)*100)%1),f+(e>.999?(e--,1):0)|0)))
```
That "must equal 100" condition (rather than rounding and adding up) nearly doubled my code (from 44 to 81). The trick was to add an pot for decimal values that, once it reaches 1, takes 1 from itself and adds it to the current number. Problem then was floating points, which means something like [1,1,1] leaves a remainder of .9999999999999858. So I changed the check to be greater than .999, and decided to call that precise enough.
[Answer]
# Haskell, ~~42~~ 27 bytes
```
p a=[div(100*x)$sum a|x<-a]
```
Pretty much the trivial method in Haskell, with a few spaces removed for golfing.
Console (brackets included to be consistent with example):
```
*Main> p([1,0,2])
[33,0,66]
*Main> p([1000,1000])
[50,50]
*Main> p([1,1,2,4])
[12,12,25,50]
*Main> p([0,0,0,5,0])
[0,0,0,100,0]
```
Edit: practised my putting, made some obvious replacements.
Original:
```
p xs=[div(x*100)tot|x<-xs]where tot=sum xs
```
[Answer]
### Haskell, ~~63~~ ~~56~~ 55 bytes
```
p l=tail>>=zipWith(-)$[100*x`div`sum l|x<-0:scanl1(+)l]
```
[Answer]
# Perl, 42 bytes
Based on Dennis's algorithm
Includes +1 for `-p`
Run with the list of numbers on STDIN, e.g.
```
perl -p percent.pl <<< "1 0 2"
```
`percent.pl`:
```
s%\d+%-$-+($-=$a+=$&*100/eval y/ /+/r)%eg
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 150 bytes
```
((([]){[{}]({}<>)<>([])}{})[()])<>([]){{}<>([{}()]({}<([()])>)<>(((((({})({})({})){}){}){}{}){}){}(<()>))<>{(({}<({}())>)){({}[()])<>}{}}{}([])}<>{}{}
```
[Try it online!](https://tio.run/##NY0xDoAwCEWv4vgZXHRtepGmQx1MjMbBlfTs@CFtgUA/Dzi@dr3r@bTbDECpokV7hfaUJWUXunYpkDq@6i0QouQYohdwPNIzhBE@MxJIElXEqC9xQVmNE2TpcZcYS7Ntmbb/ "Brain-Flak – Try It Online")
Starting from the end and working backward, this code ensures at each step that the sum of the output numbers so far is equal to the total percentage encountered, rounded down.
```
(
# Compute and push sum of numbers
(([]){[{}]({}<>)<>([])}{})
# And push sum-1 above it (simulating a zero result from the mod function)
[()])
<>
# While elements remain
([]){{}
# Finish computation of modulo from previous step
<>([{}()]({}
# Push -1 below sum (initial value of quotient in divmod)
<([()])>
# Add to 100*current number, and push zero below it
)<>(((((({})({})({})){}){}){}{}){}){}(<()>))
# Compute divmod
<>{(({}<({}())>)){({}[()])<>}{}}{}
([])}
# Move to result stack and remove values left over from mod
<>{}{}
```
[Answer]
# JavaScript (ES6) 60 ~~63 95~~
Adapted and simplified from [my (wrong) answer](https://codegolf.stackexchange.com/a/45717/21348) to another challenge
Thk to @l4m2 for discovering that this was wrong too
Fixed saving 1 byte (and 2 byte less, not counting the name `F=`)
```
v=>v.map(x=>(x=r+x*100,r=x%f,x/f|0),f=eval(v.join`+`),r=f/2)
```
Test running the snippet below in any EcmaScript 6 compliant browser
```
F=
v=>v.map(x=>(x=r+x*100,r=x%f,x/f|0),f=eval(v.join`+`),r=f/2)
console.log('[1,0,2] (exp [33,0,67] [34,0,66])-> '+F([1,0,2]))
console.log('[1000,1000] (exp [50,50])-> '+F([1000,1000]))
console.log('[1,1,2,4] (exp[12,12,25,51] [13,12,25,50] [12,13,25,50] [12,12,26,50])-> '+F([1,1,2,4]))
console.log('[0,0,0,5,0] (exp [0,0,0,100,0])-> '+F([0,0,0,5,0]))
console.log('[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,980] -> '+F([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,980]))
console.log('[2,2,2,2,2,3] -> ' + F([2,2,2,2,2,3]))
```
```
<pre id=O></pre>
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
Ẋ-Θmȯ⌊*100/Σ¹∫
```
[Try it online!](https://tio.run/##yygtzv7//@GuLt1zM3JPrH/U06VlaGCgf27xoZ2POlb///8/2lAHCGMB "Husk – Try It Online") or [Verify all test cases](https://tio.run/##yygtzv7/P/dRUyPXw11duudm5J5Y/6inS8vQwED/3OJDOx91rP7//390tKGOgY5RrA6QBkIQbWBgoAMioGJGOiZAloEOCJrqGMTGAgA "Husk – Try It Online")
Algorithm from Dennis' answer.
## Explanation
```
Ẋ-Θmȯ⌊*100/Σ¹∫
∫ cumulative sums
mȯ map to the follwing 4 functions
/Σ¹ divide by sum of input
*100 times 100
⌊ floored
Θ prepend a zero
Ẋ- fold consecutive pairs with subtraction
```
[Answer]
# Octave, 40 bytes
```
@(x)diff(ceil([0,cumsum(100*x/sum(x))]))
```
[Answer]
### Python 2, 89 bytes
```
def f(L):
p=[int(x/0.01/sum(L))for x in L]
for i in range(100-sum(p)):p[i]+=1
return p
print f([16,16,16,16,16,16])
print f([1,0,2])
->
[17, 17, 17, 17, 16, 16]
[34, 0, 66]
```
[Answer]
# JavaScript, 48 bytes
```
F=
x=>x.map(t=>s+=t,y=s=0).map(t=>-y+(y=100*t/s|0))
// Test
console.log=x=>O.innerHTML+=x+'\n';
console.log('[1,0,2] (exp [33,0,67] [34,0,66])-> '+F([1,0,2]))
console.log('[1000,1000] (exp [50,50])-> '+F([1000,1000]))
console.log('[1,1,2,4] (exp[12,12,25,51] [13,12,25,50] [12,13,25,50] [12,12,26,50])-> '+F([1,1,2,4]))
console.log('[0,0,0,5,0] (exp [0,0,0,100,0])-> '+F([0,0,0,5,0]))
```
```
<pre id=O></pre>
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
.¥IO/т*ï¥
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f79BST3/9i01ah9cfWvr/f7ShDhDGAgA "05AB1E – Try It Online")
*+3 for a bugfix*
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 12 bytes
```
∑/₁*ṙ:∑₁$-Þ…
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%88%91%2F%E2%82%81*%E1%B9%99%3A%E2%88%91%E2%82%81%24-%C3%9E%E2%80%A6&inputs=%5B1%2C%201%2C%201%5D&header=&footer=)
## Explained
```
∑/₁*ṙ:∑₁$-Þ…
∑ # sum(input)
/ # input ÷ ↑ # get the weight of each number
₁* # ↑ * 100 # and make it a percentage
ṙ # map(round, ↑) # rounding each number
:∑ # ↑, sum(↑) # now sum the above
₁$- # 100 - ↑ # and subtract from 100. The result represents any potential round errors that need correction
Þ… # distribute(↑, ↑↑) # spread ↑ over the rounded list evenly
```
[Answer]
# Rust, 85 bytes
This uses vectors instead of arrays because as far as I am aware there is no way to accept arrays of multiple different lengths.
```
let a=|c:Vec<_>|c.iter().map(|m|m*100/c.iter().fold(0,|a,x|a+x)).collect::<Vec<_>>();
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
å+ mzUx÷L)änT
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=5SsgbXpVePdMKeRuVA&input=WzEsMSwxXQ)
[Answer]
# [Jq 1.5](https://stedolan.github.io/jq/), 46 bytes
```
add as$s|.[1:]|map(100*./$s|floor)|[100-add]+.
```
Expanded
```
add as $s # compute sum of array elements
| .[1:] # \ compute percentage for all elements
| map(100*./$s|floor) # / after the first element
| [100-add] + . # compute first element as remaining percentage
```
[Try it online!](https://tio.run/##XY7LCsIwEEX3fkVAFz4mNWmaCi78kTCLYBEqtal94Cbfbpy0VYqTYeCeudzM/RmMkSAgRTbVml8YM0oRy0/IXEsiiyLHFRgphIA48GfVArQYdyAhhQwXMTIF6lSDllOUVF8gZkAO9Q/Ikc@hAuLTsPhwQnQEwRUa9MEWBbPdpvOJkWf0D9tsab1PjoRulXPtzsfLOfnwkITwdk1furoLnNdDVfGyboaeRGtf3A39KK4f "jq – Try It Online")
[Answer]
# PHP, 82 bytes
```
for(;++$i<$argc-1;$s+=$x)echo$x=$argv[$i]/array_sum($argv)*100+.5|0,_;echo 100-$s;
```
takes input from command line arguments, prints percentages delimited by underscore.
Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/a5f5644f5fb6f90b9e9586865e626b1883a6fc8e).
] |
[Question]
[
The goal of radiation hardening is to make a program still work after you remove a byte. However, what if a skilled competitor is purposefully trying to mess with you?
In this game, each bot will take turns removing one character from the next bot down the line. If the bot fails to produce valid output next turn you gain one point. The bot with the most points at the end wins. Simulation will be run several times with different orders to reduce randomness. Final score will be the median of each iteration.
If a program reaches 0 bytes in length it will always be eliminated, regardless of if it produces valid output or not. Otherwise it would be unbeatable.
Note the goal of the game is to get kills, not necessarily to survive the longest. You can be the last one living but if you haven't eliminated anyone you can still lose. Of course, it's impossible to gain any more points after being eliminated.
## IO format
Since I want many languages to be able to compete, I will need to enforce strict IO rules to make it possible for me to run each program. Thus, IO will be purely using STDIN and STDOUT.
The input of a program is the full source code of the next program, piped over STDIN.
The output is the 0-based index of the byte you are trying to remove, then a space, then the byte value. For example if the victim was "abc" a valid output would be "1 b". A optional trailing newline is allowed but any other extra output is invalid. If the character after the space does not match the victim's byte at that position the output will be considered invalid.
## Language selection
This will be a multi language KOTH. Languages must be free to participate and able to run inside a Ubuntu Linux Docker container. Please include a installation script and a script that can run your program. Your script should also install libraries or packages include a script that installs them.
Languages purposefully designed to beat this challenge are disqualified.
Programing languages must be capable of reading the code form a file, taking input from STDIN, and outputing to STDOUT, just because they are hard for me to run reliably otherwise. I may make exceptions to this rule, mostly if you have sufficiently detailed setup and run instructions. Bots posted before this edit are exempt.
## Example post
>
> # Example Bot - C
>
>
> Code:
>
>
>
> ```
> ///////////////////////////////////////////////////////////////////////////////////
> k,j;main(i){for(j=getchar();i<255&&k>=0;i++){k=getchar();if(!((k&168)^'(')){printf("%d %c",i,k);exit(0);}}printf("0 %c",j);}
>
> ```
>
> Base 64 (Only needed if you have unprintable characters or want to use a SBCS)
>
>
>
> ```
> Ly8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8KayxqO21haW4oaSl7Zm9yKGo9Z2V0Y2hhcigpO2k8MjU1JiZrPj0wO2krKyl7az1nZXRjaGFyKCk7aWYoISgoayYxNjgpXicoJykpe3ByaW50ZigiJWQgJWMiLGksayk7ZXhpdCgwKTt9fXByaW50ZigiMCAlYyIsaik7fQ==
>
> ```
>
> ### Installation:
>
>
>
> ```
> apt-get install gcc -y
>
> ```
>
> ### How to run: (Include any command line arguments your program needs here)
>
>
>
> ```
> mv code code.c
> gcc code.c -o code
> ./code
>
> ```
>
> ### Explanation
>
>
> Removes the first instance of `['(', ')', ',', '-', 'h', 'i', 'l', 'm']` from it's target. If none is found remove the first character.
>
>
>
## Controller
<https://codeberg.org/Mousetail/Radiation-Hardened-Koth>
## [Chat room](https://chat.stackexchange.com/rooms/138763/radiation-hardening)
## [Leaderboard (Last updated (FINAL UPDATE) 29-08-2022 6:48 UTC)](https://mousetail.github.io/koth-leaderboard-pages/results.html)
```
window.location.href = "https://mousetail.github.io/koth-leaderboard-pages/results.html"
```
You are free to edit and submit more bots, but if you want to appear on the leader-board you need to run the controller yourself. I'd be happy to accept pull requests to the ranking repo.
## Other rules
1. Program length can be up to 256 bytes
2. No opening files, networking, or any other IO. Writing to STDERR is ok.
3. It's ok to try to crash programs by including NULL bytes and invalid unicode etc. in your source code.
4. Programs must take <1s to complete. Taking longer than 2s is considered invalid output, though try to keep is less than 1s to account for uncertainty.
5. It's ok to submit multiple bots as long as they are not specifically designed to support each-other.
6. Command line arguments are allowed, but no cheating by putting the "real" code in the command line arguments.
7. Any negative votes bots will not participate until they gain more votes. This is intended to help moderate the points above when subjective.
[Answer]
# [A Pear Tree](https://esolangs.org/wiki/A_Pear_Tree), Distributed Damage
A Pear Tree isn't actually that good at this challenge as languages go – its general efficiency at [radiation-hardening](/questions/tagged/radiation-hardening "show questions tagged 'radiation-hardening'") is because it's good at *detecting* damage, but it has no real way to *repair* it, so the best you can do is to write the same program several times in a row and hope that at least one copy stays undamaged.
Nonetheless, I'm entering an answer by [popular demand](https://chat.stackexchange.com/transcript/240?m=61812860#61812860) :-)
This program contains unprintable characters (thus no TIO link). However, it looks something like this (except that `ÔøΩÔøΩ\n` are actually three non-newline nonprintable characters); see below for a hex dump:
```
l=length;(.618*l)=~/\..*/;i=int($&*l);$_=i." ".substr$_,i,1#-ÔøΩÔøΩ
l=length;(.618*l)=~/\..*/;i=int($&*l);$_=i." ".substr$_,i,1#-ÔøΩÔøΩ
l=length;(.618*l)=~/\..*/;i=int($&*l);$_=i." ".substr$_,i,1#-ÔøΩÔøΩ
l=length;(.618*l)=~/\..*/;i=int($&*l);$_=i." ".substr$_,i,1#-ÔøΩÔøΩ
```
## Hexdump
This is the actual submission, as an `xxd` reversible hex dump.
```
00000000: 6c3d 6c65 6e67 7468 3b28 2e36 3138 2a6c l=length;(.618*l
00000010: 293d 7e2f 5c2e 2e2a 2f3b 693d 696e 7428 )=~/\..*/;i=int(
00000020: 2426 2a6c 293b 245f 3d69 2e22 2022 2e73 $&*l);$_=i." ".s
00000030: 7562 7374 7224 5f2c 692c 3123 2db4 9616 ubstr$_,i,1#-...
00000040: 6c3d 6c65 6e67 7468 3b28 2e36 3138 2a6c l=length;(.618*l
00000050: 293d 7e2f 5c2e 2e2a 2f3b 693d 696e 7428 )=~/\..*/;i=int(
00000060: 2426 2a6c 293b 245f 3d69 2e22 2022 2e73 $&*l);$_=i." ".s
00000070: 7562 7374 7224 5f2c 692c 3123 2db4 9616 ubstr$_,i,1#-...
00000080: 6c3d 6c65 6e67 7468 3b28 2e36 3138 2a6c l=length;(.618*l
00000090: 293d 7e2f 5c2e 2e2a 2f3b 693d 696e 7428 )=~/\..*/;i=int(
000000a0: 2426 2a6c 293b 245f 3d69 2e22 2022 2e73 $&*l);$_=i." ".s
000000b0: 7562 7374 7224 5f2c 692c 3123 2db4 9616 ubstr$_,i,1#-...
000000c0: 6c3d 6c65 6e67 7468 3b28 2e36 3138 2a6c l=length;(.618*l
000000d0: 293d 7e2f 5c2e 2e2a 2f3b 693d 696e 7428 )=~/\..*/;i=int(
000000e0: 2426 2a6c 293b 245f 3d69 2e22 2022 2e73 $&*l);$_=i." ".s
000000f0: 7562 7374 7224 5f2c 692c 3123 2db4 9616 ubstr$_,i,1#-...
```
### Strategy/algorithm
Most of the submissions to this challenge so far use one of two hardening strategies: either the "core and chaff" strategy, in which only a part of the program has any meaning and the rest is just junk to distract the opponents, or a more traditional [radiation-hardening](/questions/tagged/radiation-hardening "show questions tagged 'radiation-hardening'") approach which has redundant copies of all the important data and will attempt to find and use an undamaged copy.
Distributed Damage works by trying to spread its deletions evenly over the target program; against "core and chaff" this is probably a bit more likely to hit the core than choosing randomly (the *first* shot is no better than random, but subsequent shots avoid areas that didn't kill the opponent, and are thus more likely to aim for places that could); and against "redundant copies" this is more likely than random to damage every copy and thus prevent the program being repaired.
In order to work out where the program has previously attacked, the attack position is based entirely on the length of the target program (thus, if the program is, e.g., 219 bytes long, it's possible to determine where the previous attack was via knowledge of which byte is attacked in a 220-byte program). The length of the target program is multiplied by (an approximation of) the golden ratio, and the fractional portion of the result is used to give the target to attack – this naturally leads to the attack positions being spread in a distributed way across the target program.
This algorithm was inspired by nature – many plants use the same algorithm to, e.g., place their leaves in such a way that they aren't blocking each others' view of the sun, because it makes it possible to distribute locations approximately evenly even if you don't know in advance how many of them there will be, and the calculation is very simple.
The radiation hardening isn't anything special, just a "redundant copies" approach, with four copies of the 64-byte program (256 bytes in all). The last four bytes of each copy are a checksum; A Pear Tree refuses to run programs unless they have a section that checksums correctly, and will run that section first (thus, if any of the four copies is undamaged, that copy runs). Unfortunately, this means that there's no way to continue if all four copies get damaged, because the program won't parse at all. (It might be possible to put a secondary checksum around the portion from `i=` onwards so that at least the interpreter would have *something* to run if every copy got damaged, but that would be unlikely to get extra kills, and I ran out of bytes so there's no room for extra checksums.)
I'm hoping that this answer will do particularly well defending against, and decently at attacking, "tiny core" programs that aim purely for survival rather than kills, and don't have any algorithm for choosing targets – such programs nearly always choose targets near the start, and this program is unlikely to stop working unless all four quarters of it get hit (in particular, the last quarter has to get hit). Programs like Almost Rare that are designed to detect programs consisting of redundant copies and damage them all in the same way are likely to beat this very quickly, though.
## Installation
Install `perl` if necessary (it's installed by default on Ubuntu).
Install Digest::CRC (Ubuntu package `libdigest-crc-perl`).
Download <http://nethack4.org/esolangs/apeartree-v2.pl>.
To run the program, use `perl apeartree-v2.pl *programfilename*`. A Pear Tree reads in binary (rather than Unicode) by default, so there's no need to worry about changing the default encoding.
### Explanation
The interpreter for A Pear Tree will rotate an undamaged portion of the program to the start (determined by looking for a valid checksum). If it can't, that's a syntax/checksum error (`a partridge`).
If it finds an undamaged portion, that portion will do the following:
```
# {implicit input, reading all of stdin into $_}
l=length; # assign length of {the input} to `l`, as shorthand
(.618*l) # multiply the length by 0.618
=~/\..*/; # regex, matching from `.` to end of string
# i.e. this matches the fractional portion
i=int( # assign to `i` the value, truncated to integer, of
$&*l); # the string matched by the regex, times `l`
$_=i # assign the following to $_: `i`,
." ". # concatenated with " ", concatenated with
substr$_, # the substring of the input
i,1 # starting at `i`, with length 1
# # comment to newline (i.e. end; there is no newline)
# {implicit output of $_}
```
It's a bit surprising that regexing numbers (i.e. converting them to strings and looking for the decimal point) is the tersest way to extract the fractional portion, but I haven't found anything better.
One change for golfiness, necessary to get this down to 64 bytes: the golden ratio is approximately equal to 1.618, not 0.618, but because we're taking the fractional portion of the result it doesn't matter what the integer portion of the value we're multiplying by is.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) with `LANG=C.ISO-8859-1`, The Burrowing Wheel
```
⁸
¹¹»¹«
¬π
ṛ⁸ẈMị⁸ẈMị⁸ẈMị⁸ẈMị⁸ẈMị⁸ẈMị⁸ẈMị⁸ẈMị
¬π
¬π ·∏∑
¹« »
¬π
¬´a
oao
«»«»« »«»«» « »« »
ḷ¹¹ ¹
·πõ
“““““““““““““““““““““““⁹ƈ€µTịµJḟⱮ`ịṙṢṪ€ɗ€JŒgẈNMX©ịṭ®_1¤KȮị““““⁹ƈ€µTịµJḟⱮ`ịṙṢṪ€ɗ€JŒgẈNMX©ịṭ®_1¤KȮị““““⁹ƈ€µTịµJḟⱮ`ịṙṢṪ€ɗ€JŒgẈNMX©ịṭ®_1¤KȮị”µµẈMị¹¹¹⁺VVV⁺
```
[Try it online!](https://tio.run/##1VLNSsNAEL7PUwxpQxOkYB7Ag@Cp0goiRVDR0NYaCbakARFyMJ4K3ryIqAjiRaMBD8Fsc1tQ9DE2LxJnlxT8AU@9mM3MfvPNP8l@z3WPiiIPUwDO6GQkEUEQ7JJYMRk3RXY6GyRbSEGRvqh2EfIMAFDS9PDIBhjYA4loECU4BTzD0lJJVELOq1JpVMiPr2bwhuxtnJ888mSNxuVJQ6Q3@XO8Q4ZgF4LdCvZA7o9zUo3Xsz7t1Wqu83vlf@LxtsXvlt9jufS/qnrNE56UH0n9BSwPJ@12m3RRVCqGYZggLxPAWagavodY25yvkcYacSPihp5z4O8i6iNErepowWEHsd4h7wZilch63ydlIW4Fwd8JHnmN1cXW0kpTH5llBe97hV8x03Ka3kVNxhMlY7w5S7m/4p@d93p2V/amtGHg244rDQvKxT8B "Jelly – Try It Online")
Exits by crashing, putting junk on standard error, but standard output should be correct.
I don't know how fast the OP's computer is, and it matters for this submission – this program takes around 0.5-0.6 seconds to run on my computer and on TIO, so may go over the time limit if the OP's computer is significantly slower.
Jelly uses a custom code page, so here's a hexdump (`xxd` format) of what this looks like after encoding:
```
00000000: 887f 7f81 81fb 81fa 7f81 7fde 88bb 4dd8 ..............M.
00000010: 88bb 4dd8 88bb 4dd8 88bb 4dd8 88bb 4dd8 ..M...M...M...M.
00000020: 88bb 4dd8 88bb 4dd8 88bb 4dd8 7f7f 817f ..M...M...M.....
00000030: 7f81 20da 7f7f 81fa 20fb 7f7f 7f20 817f .. ..... .... ..
00000040: 7f7f 7f7f fa61 7f7f 6f61 6f7f 7ffa fbfa .....a..oao.....
00000050: fbfa 20fb fafb fafb 20fa 20fb fa20 fb7f .. ..... . .. ..
00000060: 7fda 8181 2081 7f7f de7f fefe fefe fefe .... ...........
00000070: fefe fefe fefe fefe fefe fefe fefe fefe ................
00000080: fe89 9c0c 0954 d809 4aeb 9560 d8f3 b7ce .....T..J..`....
00000090: 0c9d 0c4a 1367 bb4e 4d58 06d8 e008 5f31 ...J.g.NMX...._1
000000a0: 034b cad8 fefe fefe 899c 0c09 54d8 094a .K..........T..J
000000b0: eb95 60d8 f3b7 ce0c 9d0c 4a13 67bb 4e4d ..`.......J.g.NM
000000c0: 5806 d8e0 085f 3103 4bca d8fe fefe fe89 X...._1.K.......
000000d0: 9c0c 0954 d809 4aeb 9560 d8f3 b7ce 0c9d ...T..J..`......
000000e0: 0c4a 1367 bb4e 4d58 06d8 e008 5f31 034b .J.g.NMX...._1.K
000000f0: cad8 ff09 09bb 4dd8 8181 818a 5656 568a ......M.....VVV.
```
## Strategy/algorithm
This program checks to see which of the various possible irradiated versions are shortest when compressed, and chooses a byte to delete that produces one of those most-compressible targets.
The idea behind this algorithm is:
* Repetitive chaff (like `///////////////`) compresses very well, so the algorithm avoids damaging it (which is generally a useless thing to do, programs with long repeating runs of characters rarely care about the exact number);
* Redundant parts of a program (that could survive damage) are often repeated multiple times; the algorithm will tend not to damage those because damaging one copy will make the program less compressible, rather than more;
* If one redundant part of a program does have to be damaged (e.g. because the entire program is made of them), the algorithm will then tend to try to damage other parts in the same way;
* If a program is formed of some completely random chaff, plus some meaningful code, the algorithm is more likely to target the meaningful code; this is because meaningful code often contains near-repeats (and the algorithm will tend to make them more exact repeats, thus breaking the code), whereas completely random chaff doesn't, and so there's more of a compressibility gain to attacking the meaningful code than the chaff.
Jelly doesn't have compression (as opposed to decompression) builtins, so in order to work out what the most compressible irradiated versions are, I had to write my own compressor. The idea is to take a Burrows–Wheeler transform of the input (this is the same general technique that `bzip2` uses) – take all cyclic permutations of the irradiated program, sort them, and look at the last bytes of each permutation in their sorted order. If a substring appears repeatedly, then imagine the cyclic permutations that split that substring between the start and end of the string; for each copy, the portion that's at the start will be the same, so they'll sort next to each other, and thus the portion at the end (which is also the same) will also sort next to each other, creating runs of the same value in the list of the last bytes.
Burrows–Wheeler-based compression works by run-length-encoding that list of the last bytes, but to work out which irradiated program is the most compressible, there's no actual need to go through with the rest of the compression; it's possible simply to count how many runs there are. This submission does that, looks for the irradiated version with the fewest runs, and outputs whichever byte will produce that particular irradiated version.
Often there'll be more than one possibility, in which case this program picks at random.
The TIO! link above shows this program attacking NÜL tränslätör – there are only two target bytes it will attack, the `r` of `tr` and the first `"` of `printf "%d "`. Both of these bytes are fatal to the target, so the algorithm is making good choices there. (The attack on the `printf` quotes is because the other `printf`s don't use quotes, so it's trying to make all the `printf`s the same. I'm not totally sure what causes the attack on `tr`, but suspect that it's related to most uses of `r` being in an expression (`r+1`) or to spell `printf` – the algorithm has thus correctly identified meaningful code that doesn't have a redundant copy elsewhere in the program.)
## Installation
There's no change from my other Jelly answer. So that this answer is complete, I'm repeating the instructions here:
* Install python3 and pip3 (on Ubuntu, `python3` and `python3-pip`); also `git` if you haven't already.
* You will need to run from an account with a real home directory – if your container is so stripped down that it doesn't have one, create one with, e.g.,
```
mkdir ./home
export HOME=$(readlink -f ./home)
```
* Install Jelly using the instructions at <https://github.com/DennisMitchell/jellylanguage>:
```
git clone -q https://github.com/DennisMitchell/jellylanguage.git
cd jellylanguage
pip3 install --upgrade --user .
```
To run programs: `LANG=C.ISO-8859-1 ~/.local/bin/jelly f *programfilename*`, where *programfilename* is the name of the program you're running. Standard input can be piped in or redirected from a file, as normal.
## Explanation
### Radiation hardening
The first half of the program is just chaff, intended to create false-positives for most programs that try to aim their attacks, and to take ages to chew through for programs that scan from the start of the program in sequence – it's possible to delete the whole thing and nothing will change. Almost everything here is a) the empty string, or b) a function that always returns one of its arguments literally, so even if some of this code somehow ends up running, it won't do anything. However, Jelly starts execution from the start of the last line of the program, so you need to start deleting newlines in order to even get the code to run.
The radiation hardening is done using three copies of the core program logic – the longest will be run. As an improvement over my previous Jelly submission, I separated them with multiple `“` marks (which in this context are kind-of like commas) – in order to cause two copies to be combined and become longest, you need to delete all the `“` marks in that section. Most likely, it's easier to disrupt the program by damaging all three copies separately than by causing two to be combined.
I didn't radiation-harden the code that selects an appropriate copy to run, but it's only four bytes long and one is hardened (as `¬π` is a no-op in most contexts, making it safe to add redundant copies of it), so hard to hit unless aiming at this program in particular:
```
ẈMị¹
Ẉ Take the length of each program in the list
M Find the indexes of the maximums (i.e. longest programs)
ị Index back into
¬π the original list
```
This gives us a list of the longest programs, which is subsequently evaluated using `V`. The programs actually get concatenated together by `V`, so there's an intentional crash to exit before the program runs a second time and produces output again.
### Target selection
```
⁹ƈ€µTịµJḟⱮ`ịṙṢṪ€ɗ€JŒgẈNMX©ịṭ®_1¤KȮị
⁹ € Form a list of 256 elements
ƈ read from standard input
T Find the truthy elements
µ i and select them
J Take the indexes of the elements
Ɱ` For each index
ḟ produce a list of indexes that omits it
µ ị Index back into the input
ɗ€ On each of those lists, do:
·πô J rotate it by all possible amounts
·π¢ sort the rotated lists
·π™ take the last element
€ of each of the rotated lists
Œg Group consecutive equals in {each list}
Ẉ Take the length of each list
NM Find all indexes of the minimum value
X Pick one at random
© and store it in ®
ị Take the {input character} at that index
·π≠ Prepend
®_1¤ ® - 1
K separated by a space
Ȯ Output the result
ị Index {using a string}, crashes
```
The `ṙ … J` is actually slightly buggy – the `J` is measuring against the length of the original program, not the length of the irradiated version, so one of the rotated lists ends up being added twice. However, this ends up having no impact on the results, because the two identical lists will sort next to each other, and their last elements are the same, thus end up in the same run of consecutive equals and don't change the total number of runs.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) with `LANG=C.ISO-8859-1`, Almost Rare
```
““““““⁹ƈ€µTịµṢœ-QŒrṪÐṂFX©⁸ẹX_1⁶®⁸ị`“⁹ƈ€µTịµṢœ-QŒrṪÐṂFX©⁸ẹX_1⁶®⁸ị`“⁹ƈ€µTịµṢœ-QŒrṪÐṂFX©⁸ẹX_1⁶®⁸ị`“⁹ƈ€µTịµṢœ-QŒrṪÐṂFX©⁸ẹX_1⁶®⁸ị`“⁹ƈ€µTịµṢœ-QŒrṪÐṂFX©⁸ẹX_1⁶®⁸ị`“⁹ƈ€µTịµṢœ-QŒrṪÐṂFX©⁸ẹX_1⁶®⁸ị`“⁹ƈ€µTịµṢœ-QŒrṪÐṂFX©⁸ẹX_1⁶®⁸ị`”¹¹LÐṀoo¹¹VVV”¹¹LÐṀoo¹¹VVV”¹¹LÐṀo¹¹VVV
```
[Try it online!](https://tio.run/##y0rNyan8//9Rwxx01LjzWMejpjWHtoY83N19aOvDnYuOTtYNPDqp6OHOVYcnPNzZ5BZxaOWjxh0Pd@2MiDd81Ljt0DoQb3d3wqjugdA999DOQzt9QKoa8vNB7LCwMGJEoYL//ycmJSanpKalZwAA "Jelly – Try It Online")
Hexdump (`xxd` reversible hexdump format, decode with `xxd -r`):
```
00000000: fefe fefe fefe 899c 0c09 54d8 09b7 1e2d ..........T....-
00000010: 5113 72ce 0fb3 4658 0688 d658 5f31 8608 Q.r...FX...X_1..
00000020: 88d8 60fe 899c 0c09 54d8 09b7 1e2d 5113 ..`.....T....-Q.
00000030: 72ce 0fb3 4658 0688 d658 5f31 8608 88d8 r...FX...X_1....
00000040: 60fe 899c 0c09 54d8 09b7 1e2d 5113 72ce `.....T....-Q.r.
00000050: 0fb3 4658 0688 d658 5f31 8608 88d8 60fe ..FX...X_1....`.
00000060: 899c 0c09 54d8 09b7 1e2d 5113 72ce 0fb3 ....T....-Q.r...
00000070: 4658 0688 d658 5f31 8608 88d8 60fe 899c FX...X_1....`...
00000080: 0c09 54d8 09b7 1e2d 5113 72ce 0fb3 4658 ..T....-Q.r...FX
00000090: 0688 d658 5f31 8608 88d8 60fe 899c 0c09 ...X_1....`.....
000000a0: 54d8 09b7 1e2d 5113 72ce 0fb3 4658 0688 T....-Q.r...FX..
000000b0: d658 5f31 8608 88d8 60fe 899c 0c09 54d8 .X_1....`.....T.
000000c0: 09b7 1e2d 5113 72ce 0fb3 4658 0688 d658 ...-Q.r...FX...X
000000d0: 5f31 8608 88d8 60ff 8181 4c0f c86f 6f81 _1....`...L..oo.
000000e0: 8156 5656 ff81 814c 0fc8 6f6f 8181 5656 .VVV...L..oo..VV
000000f0: 56ff 8181 4c0f c86f 8181 5656 56 V...L..o..VVV
```
Exits via crashing, so a lot of junk goes to stderr and must be ignored, but stdout should be correct.
## Strategy/algorithm
This program looks for characters in the input program that appear more than once, but under that restriction, as few times as possible. (So the ideal is to find a character that appears twice.) It picks one of those characters at random, picks a random occurrence of it, and chooses that.
The program is (unless I've missed something) radiation-hardened against any single deletion, and can frequently withstand quite a lot of random deletions (although there are ways to make it fail with only two deletions, it takes some understanding to realise what needs to be deleted).
Unfortunately, Jelly by default has no byte-level I/O at all – any attempt to read invalid UTF-8 (except by shelling out to Python) will cause a crash in the read routines. This is fixable by explicitly disabling Unicode handling when running the program, using `LANG=C.ISO-8859-1` as a prefix to the command. (This may produce warnings because your OS probably doesn't have non-Unicode locale data files installed nowadays, but Python should still be able to run under these conditions.) Note that the similar `LC_ALL` doesn't work – using this triggers a special case in Jelly which produces output encoded in Jelly's codepage, rather than the specified encoding.
## Installation
* Install python3 and pip3 (on Ubuntu, `python3` and `python3-pip`)
* You will need to run from an account with a real home directory – if your container is so stripped down that it doesn't have one, create one with, e.g.,
```
mkdir ./home
export HOME=$(readlink -f ./home)
```
* Install Jelly using the instructions at <https://github.com/DennisMitchell/jellylanguage>:
```
git clone -q https://github.com/DennisMitchell/jellylanguage.git
cd jellylanguage
pip3 install --upgrade --user .
```
To run programs: `LANG=C.ISO-8859-1 ~/.local/bin/jelly f *programfilename*`, where *programfilename* is the name of the program you're running. Standard input can be piped in or redirected from a file, as normal.
## Explanation
The program that actually does the work is:
```
⁹ƈ€µTịµṢœ-QŒrṪÐṂFX©⁸ẹX_1⁶®⁸ị`
ƈ€ Read characters from standard input
‚Åπ 256
µTị Remove falsey characters (i.e. past EOF)
µ Assign to ⁸
·π¢ Sort the characters,
œ- and remove
Q one occurence of each character.
Œr Run-length encode,
ÐṂ and take the (char, length) pairs with minimal
·π™ last component (i.e. length)
F Convert into a list of chars, no lengths
X Pick one at random
© and assign it to ©
⁸ẹ Find all locations of it within ⁸
X Pick one at random
_1 Subtract 1 (to use 0-based indexing)
⁶ {Output the location}, and a space,
® and ®
⁸ị` Index the input into itself (i.e. crash)
```
This gets repeated many times as elements of a giant list literal, which is then decoded:
```
¹¹LÐṀoo¹¹VVV
¬π¬π no-ops, prevent a crash if the `L` is deleted
ÐṀ take the list elements with the maximum
L length
oo¬π¬π logical-OR with the list literal (a no-op, usually)
V evaluate (running the program and crashing)
VV spare Vs in case one gets deleted
```
The various deletions from this will generally either do nothing, or represent a program that concatenates the entire list literal into a single program and runs it (so in effect it ends up running the first copy of the program rather than the longest, i.e. least mutated, copy) – it's carefully structured to prevent syntax errors appearing as a result of deletions, e.g. `Ðo` is a valid command ("apply to odd elements") and thus won't cause a crash before the evaluation runs.
The decoder is also repeated, but that's mostly irrelevant / chaff to confuse other programs about what we're doing, and matters only if the `”` that closes the list literal gets deleted (in that case, the second copy of the decoder is used instead).
[Answer]
# Parentheses Killer - [PARI/GP](https://pari.math.u-bordeaux.fr/)
### Code
```
/*in"(n1fo]e)itr(s-),)i=nj1sn)io#r]nnsrt()*/print(-1+i=if(a=[i|i<-[1..#s=Vec(strjoin(readstr("/dev/stdin"/*1e=a1i= o""sr==s,fia")[aVtid(ir.iddsr")i*/)))],s[i]=="("],a[random(#a)+1],random(#s)+1)" "s[i])\\)i]so)(smirc/=/o"r,tr+)1++[")=s"[id)nos]
```
### Installation
Just install the `pari-gp` package on Ubuntu.
```
apt install -y pari-gp
```
### How to run
Assume that the filename is `a.gp`:
```
gp -fq a.gp
```
### Explanation
Removes a random `(` if there is one. Otherwise removes a random character.
Some random comments are added to make it more resistant to radiation.
PARI/GP doesn't have a built-in to read a string from STDIN, so I have to use `readstr("/dev/stdin")`. This only works on unix-like systems.
[Answer]
# Ghost, [Whitespace](https://github.com/wspace/meth0dz-c/blob/889c0ba9f9bcf0844f69071f0d3881a1b6b4da74/whitespace.c)
A bot that will remove white-space from other bots, while itself being made of only whitespace.
## Code:
```
v
un
0r
e_
of
e
r\
}
y
g
i
e nc
te
(s
no
l
an
i( \w
n
la
hr
t"
t(
l
'a
.
l=
)
ie
uin'o{tts)fa:
```
## Base64:
```
ICAgIAp2IAogdW4JCgkgCQkJMHIgICAJCmVfCiAgICAKICAgIAogCiAJCgkgCQkJb2YgCiBlCgkJCQkKclwgCiB9ICAgCSAgICAgCnkJICAJCgkgIAkKZyAKIGkgICAJICAJCmUJICAJbmMKCSAgCQp0ZSAKIChzICAgCSAJIApubwkgIAkKCSAgCQpsIAoKYW4gICAJCmkoCSAgIFx3CiAKICAKCiAgCQkKbiAKCmxhIAoKaHIgICAgCnQiIAoJdCgKIAogCQpsCiAgIAkKJ2EgCgkuCQogCSAgIAkgICAgIApsPQkKICApCQogIGllCgoKdWluJ297dHRzKWZhOg==
```
## Disassembled
```
PUSH 0
DUP
READC ; backup character
RETREIVE
PUSH 1
; START MAIN LOOP
MARK 0 ; main loop
PUSH 0
DUP
READC
; SPACE PART
RETREIVE
DUP
JLT -1
DUP
PUSH ' '
SUB
JEQ 1
; TAB PART
DUP
PUSH 9 ; tab
SUB
JEQ 1
; END TAB PART
; LINE BREAK PART
DUP
PUSH 10
SUB
JEQ 1
POP
; END LINE BREAK PART
PUSH 1
ADD
JMP 0
MARK -1
POP
POP
PUSH 0
SWAP
JMP 1
MARK 1
SWAP
WRITEN
PUSH ' '
WRITEC
WRITEC
EXIT
```
## Setup
I spent a long time finding a whitespace interpreter that allowed me to detect EOF and write logic for it.
```
apt-get install -y make
apt-get install -y g++
if [[ ! -d pavelshub-cpp ]]
then
git clone https://github.com/wspace/pavelshub-cpp.git
cd pavelshub-cpp
make
cd ..
fi
```
Run:
```
./pavelshub-cpp/wspace code
```
[Answer]
# [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), Comment Skipper
Note: in the actual submission, the `r`s are replaced with nonprintable or invalid-UTF-8 bytes; see the hexdump below. I've used `r` to represent them in this post and in the TIO link, because all unimplemented commands in Befunge-98 have identical semantics to `r`.
```
50050050050050050050050050050050050050050xxxxxnnnnn#####;;;;;~~~~~:::::~~~~~-----!!!!!!!!!!;;;;;@@@@@,,,,,.....;;;;;#####\\\\\kkkkkrrrrr'''''#####-----:::::ccccc-----*****#####rrrrr!!!!!;;;;;#####-----aaaaa~~~~~+++++;;;;;#####11111kkkkkrrrrr22222+++++;;;;;
```
[Try it online!](https://tio.run/##jc69CoMwFIbh3bsoHYRafyoItl28kC41xl9wEAqdeuuR9xs8ax8yJOecfEnr@886@PReh1AVxX/rixVnPPHDA9qlOB000uCKDKop4IUFG2KooRSFOuh4gboatni78Ya@kcC6N9hDJWwkBGac67zvh3GaozwnqHVdRGUH "Befunge-98 (FBBI) – Try It Online")
## Hexdump
This is the actual submission, as an `xxd` reversible hex dump.
```
00000000: 3530 3035 3030 3530 3035 3030 3530 3035 5005005005005005
00000010: 3030 3530 3035 3030 3530 3035 3030 3530 0050050050050050
00000020: 3035 3030 3530 3035 3078 7878 7878 6e6e 050050050xxxxxnn
00000030: 6e6e 6e23 2323 2323 3b3b 3b3b 3b7e 7e7e nnn#####;;;;;~~~
00000040: 7e7e 3a3a 3a3a 3a7e 7e7e 7e7e 2d2d 2d2d ~~:::::~~~~~----
00000050: 2d21 2121 2121 2121 2121 213b 3b3b 3b3b -!!!!!!!!!!;;;;;
00000060: 4040 4040 402c 2c2c 2c2c 2e2e 2e2e 2e3b @@@@@,,,,,.....;
00000070: 3b3b 3b3b 2323 2323 235c 5c5c 5c5c 6b6b ;;;;#####\\\\\kk
00000080: 6b6b 6bff ffff ffff 2727 2727 2723 2323 kkk.....'''''###
00000090: 2323 2d2d 2d2d 2d3a 3a3a 3a3a 6363 6363 ##-----:::::cccc
000000a0: 632d 2d2d 2d2d 2a2a 2a2a 2a23 2323 2323 c-----*****#####
000000b0: 0000 0000 0021 2121 2121 3b3b 3b3b 3b23 .....!!!!!;;;;;#
000000c0: 2323 2323 2d2d 2d2d 2d61 6161 6161 7e7e ####-----aaaaa~~
000000d0: 7e7e 7e2b 2b2b 2b2b 3b3b 3b3b 3b23 2323 ~~~+++++;;;;;###
000000e0: 2323 3131 3131 316b 6b6b 6b6b c1c1 c1c1 ##11111kkkkk....
000000f0: c132 3232 3232 2b2b 2b2b 2b3b 3b3b 3b3b .22222+++++;;;;;
```
## Strategy/algorithm
Looks at characters in pairs from the start of the program. If they're:
* not equal, deletes the first character of the pair;
* equal but not `//` nor `##`, moves onto the next pair;
* equal and `//` or `##`, moves onto the next line.
The idea is that if programs in practical languages are using "hide where my code is" techniques rather than proper radiation-hardening techniques, we should be able to find the start of the real code. If the program starts with a large number of repetitive no-ops, we can skip over those because every consecutive pair in a long string of repeated characters is equal; if it starts with a comment marker consisting of repeated characters, that's in most practical languages probably going to be `////… \n` or `#####… \n` and we can skip to the next line; if it starts with a comment/literal marker that doesn't consist of repeated characters (such as `/*`) we can in most cases simply delete the first character of the marker to uncomment the chaff code, which will also typically break a program because the chaff isn't valid code. (Python also has `'''` and `"""` as literal markers, but these have an odd length so we damage the marker rather than the useless contents inside.) So there's a reasonable chance that the first or second character we delete will end up breaking the program we're attacking.
## Installation
Install appropriate packages for building C programs (on Ubuntu, this is `build-essential`), and download <https://catseye.tc/distfiles/fbbi-1.0-2015.0729.zip>, then:
```
unzip fbbi-1.0-2015.0729.zip
cd fbbi-1.0-2015.0729/
(cd src; make)
```
Run programs using `bin/ffbi *programfilename*` (while in the `ffbi-1.0-2015.0729/` directory created during the install).
## Explanation
### Radiation hardening
This is based on a technique discovered by Martin Ender for [this answer](https://codegolf.stackexchange.com/a/103555), which is a little difficult to explain to people who don't know Befunge-98, but I'm going to try anyway.
It works using the `x` command; you can think of this command as taking a pair of coordinates interpreted as a vector, and creating something line-like (a "Lahey line") in 2D space by repeatedly moving in the direction of the vector (and the exact opposite direction) starting from itself. For example, if an `x` is given the coordinates (2,1), it creates the following Lahey line (which is also an actual line) in 2D space (marked with `+` signs), stretching out to infinity in both directions:
```
+..........
..+........
....x......
......+....
........+..
..........+
```
Unlike actual lines, though, which pass through every point on them, specifying a vector like (2, 0) gives you a Lahey line that only passes through some of the squares along it:
```
.+.+.+.x.+.+.+.+.
```
While the `x` command is in effect, the Befunge-98 interpreter basically acts as though all the commands that aren't on the Lahey line don't exist. This means that if we can set up an appropriate Lahey line that passes through every fifth character of the program (starting at the first `x` that remains in the program after radiation damage), and every character from then on (including the `x`) is repeated five times, any four characters can be deleted from the program and yet it will still have identical behaviour to the original version – in either case, the set of non-hidden characters from the `x` onwards are identical. (The idea is that before the location of the first deletion, the Lahey line passes through the first character of each set of five; between the first and second deletions, it passes through the second character of each set of five, etc., with the last character of the set being used after the fourth deletion.)
Befunge has a lot of commands that cancel the effect of `x` (including, most notably, `x` itself, plus pretty much all the flow control commands). That made this program a fairly awkward [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") challenge, as I had to write some nontrivial program logic with most of the flow control commands missing. However, the fact that `x` cancels the old Lahey line before creating a new one is useful in setting up the appropriate Lahey line delta, of (5, 0). The idea is to start by putting a lot of 5s and 0s on the stack in the repetitive `050 050 050 …` pattern (the stack starts with a zero on it, so the leading 0 can be omitted); each of these patterns (if non-irradiated) will be interpreted as either (5, 0) or (0, 5) depending on its distance from the top of the stack, and the interpretation of two adjacent patterns alternates between (5, 0) or (0, 5) unless radiation hits the upper copy of the pattern. Because there are many more than four copies of the pattern on the stack, there's thus guaranteed to be a (5, 0) pair on the stack somewhere if it's interpreted as pairs from the top. Also, there's nothing but 0s and 5s on the stack, so any pair must be (0, 0), (0, 5), (5, 0), or (5, 5).
Now, consider what happens when the `x` command gets run. If its argument is (5, 0), it creates the Lahey line that we want, and the program continues in its radiation-hardened way. If it's (0, 0), (0, 5) or (5, 5), then the Lahey line that's created misses our program altogether; (0, 5) and (5, 5) are vertical and diagonal lines that cross our program only at a single point, and the Lahey line (0, 0) is a special case that's inherently a single point. In these cases, therefore, *everything in the program* apart from the `x` we just ran gets hidden, so the interpreter has no choice but to run the `x` again (exiting is always explicit in Befunge), taking the next pair from the stack. Thus, with a one-liner program like this, the behaviour of `x` inherently looks at pairs of values at a time along the stack until it finds the (5, 0) that must exist, and thus is guaranteed to create a Lahey line that runs along the program in the correct way to radiation-harden it.
(There are many more 050 patterns in this program than are actually required for the radiation hardening to survive four deletions – the idea is to be able to survive for more than four rounds if the opponent is primarily attacking the start of the program, because most damage there is survivable; to eliminate the (5, 0) pattern entirely, a number of deletions equal to the number of 5s is required.)
### How to do flow control
When writing the main body of the program, because almost all flow control commands cancel the Lahey line, `; … ;#` and `kr` are pretty much all I had to work with.
`; … ;` is a jump, and adding `#`s in various places controls whether the jump is taken or skipped when executing the code in forward and/or reverse order (it also sometimes has the unfortunate side effect of skipping one character beyond the end of the jump, because `#` is a skip command, but this is easy to work around by repositioning characters; it just makes the program harder to read).
`kr` is a method of creating a conditional without breaking the Lahey line, but it's very quirky (the semantics of `k` are famously confusing). This combination pops the stack, then does nothing if a 0 was popped, reverses the execution direction if an odd or negative number was popped (for different reasons in the two cases), and its semantics are too complicated to easily describe if an even positive number was popped – this program therefore uses only the arguments 0 and 1, to keep the behaviour of `kr` easy to understand.
`r` on its own reverses the execution direction unconditionally, which was useful in one place (as `#r`, which reverses the execution direction only if it's currently going to the left).
As usual for Befunge-98, it's possible to replace `r` with any invalid command, so I picked NUL, plus two high-bit-set characters that aren't valid UTF-8, in the hope of confusing programs that don't have binary-safe input routines. (FBBI itself is binary-safe if run on a Unix-like system, like the one being used in this challenge.) The command in question is nonetheless written as `r` in this post, as that's the "official" name for it.
### Doing the actual work
Once the `x` command gets hit, here's what the remaining program along hte Lahey line looks like, and how it works (there's also some junk 0s and 5s at the start but they never again get executed):
```
xn#;~:~-!!;@,.;#\kr'#-:c-*#r!;#-a~+;#1kr2+;
x establish Lahey line
n clean stack (pop all the 5s)
#; jump label, no-op right now
```
From this point onwards, the element currently on the top of the stack (which at this point is a 0 because the stack has just been cleaned) counts the number of bytes that the program has read.
```
xn#;~:~-!!;@,.;#\kr'#-:c-*#r!;#-a~+;#1kr2+;
~ read byte
: copy it
~ read another byte
- subtract
!! cast to bool (like in C)
; ;# jump … to jump label + skip
kr reverse direction if truthy
```
A truthy value at this point means that the two bytes we read were different, so it's time to select the first of the two bytes and exit the program. Top of the stack at this point is the first of the two bytes; the second stack element is its index (because it's still unchanged from the start of the main loop).
```
xn#;~:~-!!;@,.;#\kr'#-:c-*#r!;#-a~+;#1kr2+;
\ swap
;# jump label, no-op going left
. output integer then space
, output raw byte
@ exit program
```
Very convenient that Befunge's "output integer then space" command is usable in this challenge (because it requires a space after the integer)! If the format didn't allow/require a space there, the integer-to-decimal conversion would take up much, much more room and probably reduce the amount of radiation hardening available as a consequence.
If the two bytes the program read are the same, the program continues by checking to see if they're `//` and/or `##`, via arithmetic on character codes:
```
xn#;~:~-!!;@,.;#\kr'#-:c-*#r!;#-a~+;#1kr2+;
'#- subtract char code of `#`
: * multiply by (itself
c- minus 12)
#r no-op if going right
! logical not
; ;# jump … to jump label + skip
kr reverse direction if truthy
```
The direction reverse here happens if, in C syntax, `!(d*(d-12))`, where `d` is the first byte of the pair minus the character code of `#`; `#` and `/` have character codes that differ by 12, so this is true if the byte is `#` or `/` (the multiplication `*` is being used like a logical AND). In this case, the strategy is to skip until finding a newline. The top of the stack at this point is the byte counter, because everything else has been popped, and that gets update while looking for the newline:
```
xn#;~:~-!!;@,.;#\kr'#-:c-*#r!;#-a~+;#1kr2+;
+ 1 add 1 to top of stack
;# jump label, no-op going left
~ read byte
-a subtract 10
;# jump label, no-op going left
! logical not
r reverse direction
! logical not again
; ;# jump … to jump label + skip
kr reverse direction if truthy
```
In other words, the program adds 1 to the byte counter, then reads the next byte, and continues doing this until a newline was read. (This shares some of the code from the previous case – in that case, the `!` is executed once, so that the loop is exited/not entered if the character *isn't* `/` or `#`, but in this loop, the same `!` is executed twice, so that the loop is exited if the character *is* a newline. In one-line Befunge-98, opportunities like this to use the same character in both directions are rare, but fun when they happen.)
If the byte pair was something other than `//` or `##`, or when the newline has been found, the program's main loop continues:
```
xn#;~:~-!!;@,.;#\kr'#-:c-*#r!;#-a~+;#1kr2+;
2+ add 2 to top of stack
#; ; jump … to jump label
```
This skips over the `xn` at the start, and also skips over any of the 0s and 5s that happen to fall on the Lahey line. (In Befunge-98, execution wraps, but it wraps *along the Lahey line* rather than toroidally around the program, so the same set of characters will be executed after the wrap; the program's length modulo 5 is irrelevant.)
The program "forgot" to add 2 to the byte counter after the pair was checked, so it gets done here; the reason for postponing it is that less stack manipulation is needed to set it here (because there's no need to remember the first character of the pair at this location in order to check whether it's `/` or `#`, so the byte counter is the only thing on the stack at this point), and postponing it still produces the correct results because addition is commutative, so it doesn't matter whether we add the 2 before or after adding the 1s. (The skip-to-newline loop doesn't actually inspect the byte counter, just increment it.)
This program doesn't actually work for all inputs – I didn't add any code to handle EOF, rather the hope is that it won't be given input for which the algorithm reaches EOF before reaching a termination condition. I think this is probably a reasonable tradeoff – code to handle EOF given the stringent restrictions on control flow would make the program much longer and thus reduce the amount of radiation it could withstand, as I'd have to use a higher-frequency Lahey line to fit it all into 256 bytes.
[Answer]
# MVP - [Python 3](https://docs.python.org/3/)
```
import sys
print("0 "+sys.stdin.read()[:1])
```
[Try it online!](https://tio.run/##rc/NCoJAFAXgvU9hA@q9KDYWRjTZi0SB@JPXwVHGWSTis08iBD1AZ3fOtzrDZJpeHa2lbui1ccdpdAZNygDjLgvXGo@mJBXrKi8B75fkgdbu/x9HRq3oclJAONe9hjZ7VaZocg0o6HpIU9@Xt4wLCkOc5S/WsAOQfnI64zOAAHHeHtTAvNL1ChZRJFFUbzLAUSzLV/mG7Tp9AA "Python 3 – Try It Online")
MVP - (noun) Minimum Viable Product. This bot meets all the requirements set out in the challenge with 43 bytes. It is unsurprisingly not particularly radiation-resistant.
### Installation
```
apt-get install python3
```
### How to run
Depending on how you have Python installed:
```
python code.py
```
or
```
python3 code.py
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), The Terrible Bot
```
□⁋□⁋###□⁋□⁋
;;}□⁋□⁋□⁋ ėλntt¶ntt=¬;;;Ḋƛ'kwntc¬; λ\#\#\/\#\/JJJJnttc¬;Ẏ;;;Þf℅h :::: □⁋i \ pJ
;;}□⁋□⁋□⁋ ėλntt¶ntt=¬;;;Ḋƛ'kwntc¬; λ\#\#\/\#\/JJJJnttc¬;Ẏ;;;Þf℅h :::: □⁋i \ pJ
;;}□⁋□⁋□⁋ ėλntt¶ntt=¬;;;Ḋƛ'kwntc¬; λ\#\#\/\#\/JJJJnttc¬;Ẏ;;;Þf℅h :::: □⁋i \ pJ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLilqHigYvilqHigYsjIyPilqHigYvilqHigYtcbjs7feKWoeKBi+KWoeKBi+KWoeKBiyDEl867bnR0wrZudHQ9wqw7OzvhuIrGmydrd250Y8KsOyDOu1xcI1xcI1xcL1xcI1xcL0pKSkpudHRjwqw74bqOOzs7w55m4oSFaCA6Ojo6IOKWoeKBi2kgXFwgICBwSlxuOzt94pah4oGL4pah4oGL4pah4oGLIMSXzrtudHTCtm50dD3CrDs7O+G4isabJ2t3bnRjwqw7IM67XFwjXFwjXFwvXFwjXFwvSkpKSm50dGPCrDvhuo47OzvDnmbihIVoIDo6Ojog4pah4oGLaSBcXCAgIHBKXG47O33ilqHigYvilqHigYvilqHigYsgxJfOu250dMK2bnR0PcKsOzs74biKxpsna3dudGPCrDsgzrtcXCNcXCNcXC9cXCNcXC9KSkpKbnR0Y8KsO+G6jjs7O8OeZuKEhWggOjo6OiDilqHigYtpIFxcICAgcEoiLCIiLCIgICAgaGVsbG8gYXNkLy9hc2RcbmFzZGFzZGFzZC8vYSJd)
Base64-encoded:
```
4pah4oGL4pah4oGLIyMj4pah4oGL4pah4oGLCjs7feKWoeKBi+KWoeKBi+KWoeKBiyDEl867bnR0wrZudHQ9wqw7OzvhuIrGmydrd250Y8KsOyDOu1wjXCNcL1wjXC9KSkpKbnR0Y8KsO+G6jjs7O8OeZuKEhWggOjo6OiDilqHigYtpIFwgICBwSgo7O33ilqHigYvilqHigYvilqHigYsgxJfOu250dMK2bnR0PcKsOzs74biKxpsna3dudGPCrDsgzrtcI1wjXC9cI1wvSkpKSm50dGPCrDvhuo47OzvDnmbihIVoIDo6Ojog4pah4oGLaSBcICAgcEoKOzt94pah4oGL4pah4oGL4pah4oGLIMSXzrtudHTCtm50dD3CrDs7O+G4isabJ2t3bnRjwqw7IM67XCNcI1wvXCNcL0pKSkpudHRjwqw74bqOOzs7w55m4oSFaCA6Ojo6IOKWoeKBi2kgXCAgIHBK
```
### Installation
```
pip install vyxal
```
### Running
```
vyxal code.vy
```
[Answer]
# Natural Radiation - [J](http://jsoftware.com/)
```
( ] ( ( [: ": [ ), ' ', { ) ~ [: ? # ) (1!:1@3 '')
```
[Try it online!](https://tio.run/##y/r/XwEFaEDpWAVMoIGqBAVEW8FYSlbIwgimpg6Cra6groNmQDVUFYiow24yAtjDWcoI85EcaqhoZehgjKpHXV0Ti7v//wcA "J – Try It Online") (although TIO won't accept EOF signals/characters for input as far as I'm aware, so it may not work as intended)
### Installation
([source](http://www.jsoftware.com/download/j903/install/j903_linux64.tar.gz))
These instructions assume you are on a x86\_64 processor. If you are on armv7/armv8/aarch64, use the Raspberry Pi downloads in the link above.
Prior to installation, you may need to install necessary libraries:
```
apt-get install libqtgui4 libqt4-svg libqt4-svg libqt4-opengl libqt4-network libqtwebkit4
```
Then, save the installation archive (recommended location is the home folder, but can be installed anywhere else with sufficient permissions) with a command similar to
```
wget http://www.jsoftware.com/download/j903/install/j903_linux64.tar.gz
```
Now extract the archive. There should be a folder called `j903`. Inside the folder, there should be a file called `jconsole.sh`.
### How to run
#### Option 1
```
./jconsole.sh
```
Then, paste the source code above in to the console (followed by a newline), or pass it in by script.
#### Option 2
Run the code below. The additional `echo` is necessary due to the limitations of program output when running directly from script. The `echo` is generally not counted as part of the source code. In addition, there is an additional character inside the body due to the need to escape the `"` character.
```
./jconsole.sh -js "echo ( ] ( ( [: \": [ ), ' ', { ) ~ [: ? # ) (1!:1@3 '') "
```
#### Option 3
Save source code into file and run:
```
./jconsole.sh code.ijs
```
However, there are some caveats. Firstly, `echo` may need to be added to the beginning of the code to get the output to work correctly (like in Option 2) due to how J is primarily an interpreted language. Also, the appearance of an EOF in stdin may cause extra undesired output to be written to stderr. Finally, I have not tested this on an Ubuntu Linux device as I do not have access to one and am currently unable to access Docker to set one up.
### Explanation
Just like natural random radiation events, this bot will choose a random character to remove from its target. The bot itself has some basic radiation resistance, but is unable to handle targeted radiation attacks.
[Answer]
# Brainfuck, 168 bytes, "the 2nd'er"
```
,#(((((((
>+++++++!
+++++++;/
+++++++//
+++++++/*
+++++++*/
+(+(+(+(+
+#{#+#}#+
!!+++++!!
|v.v|
----|
----v
----|
----v
.<.</
```
```
LCMoKCgoKCgoCj4rKysrKysrIQorKysrKysrOy8KKysrKysrKy8vCisrKysrKysvKgorKysrKysrKi8KKygrKCsoKygrCisjeyMrI30jKwohISsrKysrISEKCnx2LnZ8Ci0tLS18Ci0tLS12Ci0tLS18Ci0tLS12Ci48Ljwv
```
[Answer]
# Sorry, [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/)
```
<<<<<<<<<<<<<<<<<<<<<<<<<<<<.<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<.<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<,. 00000000000000000000000000000000000000000000000000000000
```
[Try it online!](https://tio.run/##K85NSvv/3wYP0LMhE5CtUUdPgUxgQCb4/z8RAA "Self-modifying Brainfuck – Try It Online")
Install (assumes `gcc` and `wget`):
```
wget https://soulsphere.org/hacks/smbf/smbf.c
gcc smbf.c -o smbf
```
Run (assumes the source stored as `src.smbf` in the same folder as `smbf` executable):
```
./smbf src.smbf
```
Does the most obvious thing, maximizing defense against random deletions and nothing else.
[Answer]
# [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 256 bytes (4√ó86=344 codels), picture perfect v3
```
jsamtfjsamtfjsamtfjsaqdusiiiiaaaabbbbddddffffjjjjvvvvtttteeeeeeeeeeeeeeeeeeeeeeeeeeeeEc?b?bed??j???bkaubuebmvmk eeeeeeeeeeeeeeeeeeeeeeeeeee e Edjfvetejkbbraqmusqemqudsiadbdiab eeeeeeeeeeeeeeeeeee ee eE
```
Base64 encoded
```
anNhbXRmanNhbXRmanNhbXRmanNhcWR1c2lpaWlhYWFhYmJiYmRkZGRmZmZmampqanZ2dnZ0dHR0ZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZUVjP2I/YmVkPz9qPz8/YmthdWJ1ZWJtdm1rICAgICAgICAgICAgICAgIGVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZSAgICAgICAgICAgICBlICBFZGpmdmV0ZWprYmJyYXFtdXNxZW1xdWRzaWFkYmRpYWIgICAgICAgICAgICAgIGVlZWVlZWVlZWVlZWVlZWVlZWUgICAgICAgICAgICAgICBlZSBlRQ==
```
[Try Piet online!](http://piet.bubbler.space/#eJzdUUEOgyAQ_Mue14QFUepXjAermJjY1sT21PTvZYFGjta0PZSdLEOWBGbmDt2lt1DVtUGFVCARCiSFm445kkTNXCQoEuQJZAK1wsSiWCIWld9AgzVpJON_FHrpf2QYJu5hcmAJmpn2t3LWT9zc5F18XMr2d1fC6iWrVKyjDC4bluMjkjFU8qEGawi9fBlTLrxZIU3xivgHLuzweiUse0dkf4WmQVjsDBVkWQYI03hynAQvd7RLB9XQTotFGM_z7eqG7bHr7QCPJ_r61AY)
This bot probably won't do too well, considering that all it does is remove the first character each time, but hopefully it survives moderately well to place top 10 :P
V2: Hopefully fixed the vulnerability that I noticed when I took a look in the leaderboards.
V3: Fixes a vulnerability where removing the first 5 characters is fatal. Also added some protection against Thief, which hopefully works.
(credits to @Bubbler for the installation and run instructions)
# Installation
```
pip install Pillow
git clone https://github.com/cincodenada/bertnase_npiet.git piet
cd piet
./configure
make npiet
cd ..
git clone https://github.com/dloscutoff/ascii-piet.git ascii-piet
```
# Run
Save the source code in the text file `src.txt`:
```
python3 ascii-piet/ascii2piet.py src.txt src.png && piet/npiet -q src.png
```
[Answer]
# NÜL tränslätör - Bash
Just run it with `bash`, it should work (TM).
```
##((()
##(()
i=$(tr '\0' ' ')
s=$(printf %s "$i"|wc -c)
[ $s -gt -1 ]||s=$(printf %s "$i"|wc -c)
r=$((RANDOM%s))
[ $r -gt -1 ]||r=$((RANDOM%s))
printf "%d " $r
p=$((r+1))
p=$((r+1))
printf %s "$i"|head -c $p|tail -c1
##((()
```
It can survive some parts being broken, but unfortunately not syntax errors.
Eg. if `$s` isn't a valid integer, `[` will fail and `s` will be reassigned.
```
IyMoKCgpCiMjKCgpCgppPSQodHIgICdcMCcgICcgJykKCnM9JChwcmludGYgICVzICAiJGkifHdj
ICAtYykKClsgICRzICAtZ3QgIC0xICBdfHxzPSQocHJpbnRmICAlcyAgIiRpInx3YyAgLWMpCgpy
PSQoKFJBTkRPTSVzKSkKClsgICRyICAtZ3QgIC0xICBdfHxyPSQoKFJBTkRPTSVzKSkKCnByaW50
ZiAgIiVkICIgICRyCgpwPSQoKHIrMSkpCgpwPSQoKHIrMSkpCgpwcmludGYgICVzICAiJGkifGhl
YWQgIC1jICAkcHx0YWlsICAtYzEKIyMoKCgpCg==
```
## Non-competing version
This one can handle NUL bytes, I think.
```
##()()
##()()
f=ooga
f=ooga
cp /dev/stdin $f
s=$(wc -c < $f)
[ $s -gt -1 ]||s=$(wc -c < $f)
r=$((RANDOM%s))
[ $r -gt -1 ]||r=$((RANDOM%s))
printf "%d " $r
p=$((r+1))
p=$((r+1))
(head -c $p $f||head -c $p $f)|tail -c1
##()()
```
But it saves input in a temp file violating rule 2.
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), Golf Core
```
00000000: 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b ................
00000010: 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b ................
00000020: 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b ................
00000030: 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b ................
00000040: 3132 3334 3536 3738 394a 4a4a 4a4a 4a4a 123456789JJJJJJJ
00000050: 4a4a 4a4a 4a4a 4a4a 4a4a 4a4a 4a20 4449 JJJJJJJJJJJJJ DI
00000060: 3020 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b 0 ..............
00000070: 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b 1b1b ................
00000080: 2f2f 2f2f 2f2f 2f2f 2f2f 2f2f 6162 6365 ////////////abce
00000090: 6620 6768 696b 6d20 6e6f 7071 7220 7374 f ghikm nopqr st
000000a0: 7576 7720 7879 7a41 4220 4345 4648 4a20 uvw xyzAB CEFHJ
000000b0: 4b4c 4d4e 4f20 5051 5253 5420 5557 5859 KLMNO PQRST UWXY
000000c0: 5a20 2829 5b5d 7b7d 2020 2020 2028 5b5d Z ()[]{} ([]
000000d0: 7b7d 2920 285b 7b7d 5d29 20e5 a4a9 e59c {}) ([{}]) .....
000000e0: b0e7 8e84 e9bb 84e5 ae87 e5ae 99e6 b4aa ................
000000f0: e88d 920d 0d0d 0d0d 0d0d 0d0d 1b1b 1b1b ................
```
[Try it online!](https://tio.run/##K/v/X5q6ICvMPSXHxdNAgRjFVmggMSk5NU0hPSMzO1chL7@gsEihuKS0rFyhorLK0UnB2dXNw0vB28fXz18hIDAoOEQhNDwiMkrB0MjYxFTBzNzCUkEjOra6VhNIVdfGaiocXnpoyaGVQHLOoQ2Hlx/qO9RyeOWh3UBy6aF1h9rB5MzDyw5tObTq8IpDvYcmccEAyG3//wcn5hbkpCp45hWUlnBlFnNlpBalAgA "V (vim) – Try It Online")
A stupid program which always remove the first character from input. Try to confuse other programs by the unprintable bytes. The only thing that make sense here is `89J DI0 <esc>`.
---
I'm not sure if this is valid since V doesn't read from stdin but from a file. (I failed to make it read from stdin.)
Starting from Python 3.6 docker container (you may need to mount source code folder into the container so it could be used later)
```
docker run -it --name=thev python:3.6 /bin/bash
```
Download source code and install all dependency
```
cd ~
pip install docopt neovim trollius
apt update
apt install neovim -y
apt install xterm -y
wget https://github.com/DJMcMayhem/V/archive/refs/heads/master.zip
unzip master.zip
cd V-master
```
Place the source code into the container some how
```
xxd -r > ~/program.v
(paste the xxd source code in this post)
```
Open another terminal, and run the program
```
docker exec -i thev /bin/bash -c 'cat - > ~/input && ~/V-master/v ~/program.v -f ~/input'
```
[Answer]
# Tapestry, [<><](https://esolangs.org/wiki/Fish)
No good strategy, focuses on being very hardened. Each character is at least 4x redundant.
```
iiiiiiiivvvvvvv
lllllllllllllll
111111111111111
---------------
nnnnnnnnnnnnnnn
888888888888888
222222222222222
222222222222222
***************
***************
ooooooooooooooo
ooooooooooooooo
;;;;;;;;;;;;;;;
```
## Explanation:
1. `iiiiiiii` push the first 8 characters of our opponent to the stack.
2. `v` go down
3. `l` get the length of the stack. In case one of the `i` was deleted
4. `1` push one to the stack
5. `-` subtract 1 to get a 0 based index
6. `n` print this as a number, this is the index
7. `822**` push "32" to the stack, the ASCII code for space
8. `o` print a space
9. `o` print the original character
10. `;` end the program
## Setup
```
if [[ ! -f fish.py ]]
then
wget https://gist.github.com/anonymous/6392418/raw/3b16018cb47f2f9ad1fa085c155cc5c0dc448b2d/fish.py
fi
```
## Run
```
python3 fish.py code
```
[Answer]
# The Newline Killer, 172 Bytes, In response to the new edit in [this](https://codegolf.stackexchange.com/a/251317/111945).
```
//////
////##
////((
////>>
k,j;main(i){for(j=getchar();i<999;i++){k=getchar();if(k=='\n'||k=='='){printf("%d %c",i,k);exit(0);}}printf("0 %c",j);}
//////
////##
////((
////>>
```
I managed to do this without learning C I am so smart (this is written in C).
Targets the first new line or `=`. Hopefully there won't be too much irrelevant `=`s. Else targets the first character. Most of the code has comments which can cause them to break by commenting their own code.
[Answer]
# Python3, Key Characters Attack, 255 bytes
`# # # # # # # repetitionrepetitionrepetition=lxn_1";=lxn_1";$(>+%cstststststststststststst\n\n\nfrom sys import stdin as s;\ni=s.read();\nfor c in'\\n )}.01+\\n )}.01+'[len(i)%8:][:8]:\n if c in i:print(f'{i.index(c)} {c}');exit();\n\nprint(f'{len(i)-1} {i[-1]}');`
Which is:
```
# # # # # # # repetitionrepetitionrepetition=lxn_1";=lxn_1";$(>+%cstststststststststststst
from sys import stdin as s;
i=s.read();
for c in'\n )}.01+\n )}.01+'[len(i)%8:][:8]:
if c in i:print(f'{i.index(c)} {c}');exit();
print(f'{len(i)-1} {i[-1]}');
```
Base 64:
`ICMgIyAjICMgIyAjICMgcmVwZXRpdGlvbnJlcGV0aXRpb25yZXBldGl0aW9uPWx4bl8xIjs9bHhuXzEiOyQoPislY3N0c3RzdHN0c3RzdHN0c3RzdHN0c3RzdAoKCmZyb20gc3lzIGltcG9ydCBzdGRpbiBhcyBzOwppPXMucmVhZCgpOwpmb3IgYyBpbidcbiApfS4wMStcbiApfS4wMSsnW2xlbihpKSU4Ol1bOjhdOgogaWYgYyBpbiBpOnByaW50KGYne2kuaW5kZXgoYyl9IHtjfScpO2V4aXQoKTsKCnByaW50KGYne2xlbihpKS0xfSB7aVstMV19Jyk7`
The repetition was due to [this answer](https://codegolf.stackexchange.com/a/251268/111945).
The next was to target [this answer](https://codegolf.stackexchange.com/a/251257/111945),
and to prevent it from targeting the actual `stdin`.
The comment up front avoids being target by programs that target the first or second letters, like [this answer](https://codegolf.stackexchange.com/a/251190/111945).
The comment is `# #` instead of `#` or `###` to be robust towards
first letter targetters and [this answer](https://codegolf.stackexchange.com/a/251201/111945), which
targets `##`.
As in [this answer](https://codegolf.stackexchange.com/a/251204/111945), we target
different things every time. We go through `\n`, , `)`, `}`,
`.`, `0`, `1`, and `+`, but `\n` takes priority in the first run,
in the second, et cetera. We decide that newlines, spaces,
closing parenthesis, decimals, numbers, and the plus sign are rarely fake and usually used, while being very vulnerable.
Quick fix: added more comments due to the feedback.
[Answer]
## Thief - C (gcc 8.3)
Sneaks in through the backdoor to steal your rarest most valued characters.
(edited to add two more slashes in the beginning, edited again to add four more nulls at the end)
```
00000000: 2f2f 2f2f 2f2f 2a2a ff20 2029 7d2e 3031 //////**. )}.01
00000010: 2b25 2563 2828 ff28 5d2c 702c 6e74 6628 +%%c((.(],p,ntf(
00000020: 2225 6420 2563 222c 505b 635d 2c63 293b "%d %c",P[c],c);
00000030: 7d5b 323d 702b 2b3b 7768 696c 6528 6d61 }[2=p++;while(ma
00000040: 696e 2863 297b 750a 0a0a 2f2f 2f2a 2a2f in(c){u...///**/
00000050: 0a0a 0a00 6766 2c70 713b 3b00 465b 3235 ....gf,pq;;.F[25
00000060: 365d 2c50 5b32 3536 5d2c 702c 663b 6d61 6],P[256],p,f;ma
00000070: 696e 2863 297b 666f 7228 3b28 633d 0020 in(c){for(;(c=.
00000080: 000a 0020 000a 0020 000a 0020 000a 0000 ... ... ... ....
00000090: 0067 6574 6368 6172 2829 293e 2d31 3b46 .getchar())>-1;F
000000a0: 5b63 5d2b 2b29 505b 635d 3d70 2b2b 3b77 [c]++)P[c]=p++;w
000000b0: 6869 6c65 282b 2b66 3c32 3537 2966 6f72 hile(++f<257)for
000000c0: 2863 3d32 3536 3b2d 2d63 3e2d 313b 2969 (c=256;--c>-1;)i
000000d0: 6628 465b 635d 3d3d 6629 7265 7475 726e f(F[c]==f)return
000000e0: 2020 7072 696e 7466 2822 2564 2025 6322 printf("%d %c"
000000f0: 2c50 5b63 5d2c 6329 3b7d 0000 0000 0000 ,P[c],c);}......
```
The core of this is this 138 byte long string
```
F[256],P[256],p,f;main(c){for(;(c=getchar())>-1;F[c]++)P[c]=p++;while(++f<257)for(c=256;--c>-1;)if(F[c]==f)return printf("%d %c",P[c],c);}
```
### How it works
It searches for the least frequent characters, and of those the last occurrence of the character of the highest value is selected.
```
// Variables are `int` by default. Global variables are initialized to zero.
F[256], // Array of frequency for each character value
P[256], // Array of last position for each character value
p, // position counter variable
f; // frequency iterator variable
main(c) // main function, integer variable for character (argc)
{
// Read input and count frequency and position
for(;
(c = getchar()) > -1; // Read character in while condition
F[c]++ // Update frequency at end of loop
)
P[c] = p++; // Update last position for character
// Find the least frequent character [1..256]
while (++f < 257)
// Find the highest valued character [255..0]
for (c = 256; --c > -1;)
// First match is the best match
if (F[c] == f)
return printf("%d %c",P[c],c);
}
```
### Hardening
* Many unsuccessful attempts to deceive The Burrowing Wheel
* Not much can be done against random targeting bots since the core is so huge.
* Lots of padding in the front to handle a variety of bots removing the 1st (many), 1st to 8th (Tapestry), 10th (Bastarf) and 21st (Redun) character. Inside the damage resistant comment there are traps for Key Characters Attack, Bastarf, Parenthesis Killer and Ghost. Also included are some
invalid UTF-8 bytes and null bytes to hopefully break something before it reaches anything important.
* The middle of the program is attacked by the example Python bot
* Source code is 7.4% null characters.
### base64 (v3)
```
Ly8vLy8vKir/ICApfS4wMSslJWMoKP8oXSxwLG50ZigiJWQgJWMiLFBbY10sYyk7fVsyPXArKzt3
aGlsZShtYWluKGMpe3UKCgovLy8qKi8KCgoAZ2YscHE7OwBGWzI1Nl0sUFsyNTZdLHAsZjttYWlu
KGMpe2Zvcig7KGM9ACAACgAgAAoAIAAKACAACgAAAGdldGNoYXIoKSk+LTE7RltjXSsrKVBbY109
cCsrO3doaWxlKCsrZjwyNTcpZm9yKGM9MjU2Oy0tYz4tMTspaWYoRltjXT09ZilyZXR1cm4gIHBy
aW50ZigiJWQgJWMiLFBbY10sYyk7fQAAAAAAAA==
```
[Answer]
# Protect and Shoot Randomly - [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 256 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
III.....āÀÀÀÀÀ€RðýIII.....āÀÀÀÀÀ€RðýIII.....āÀÀÀÀÀ€RðýIII.....āÀÀÀÀÀ€RðýIII.....āÀÀÀÀÀ€RðýIII.....āÀÀÀÀÀ€RðýIII.....āÀÀÀÀÀ€RðýIII.....āÀÀÀÀÀ€RðýIII.....āÀÀÀÀÀ€RðýIII.....āÀÀÀÀÀ€RðýIII.....āÀÀÀÀÀ€Rðý))))))))))˜˜˜˜˜˜˜˜˜˜.r.r.r.r.r.r.r.r.r.r MMMMMMMMMM
```
Input is a multi-line string.
[Try it online.](https://tio.run/##yy9OTMpM/f/f09NTDwSONB5ugMFHTWuCDm84vHdUDrucJhycnoMJ9YowoQIU@MLB//9KSko5tjmpeeklGdYaemaGFlo5mrZ1@jF6elr61pm2mXklGipqQDFrlXjbTD0lBSW94tKk4pIilXidTB1DZd33@/cCEdcwMgMYIgA) (Using the current highest voted answer as example input program.)
My initial idea was to always target the middle character of a given program, but this proved to be too tricky in combination with the radiant hardening (primarily because 05AB1E's middle builtin `√Ös` will give two results if the argument has an even length). So instead, a much more boring but more stable approach: it (tries to) output a random target.
## Encoding:
05AB1E uses a [custom codepage](https://github.com/Adriandmen/05AB1E/wiki/Codepage), so here are the raw bytes instead:
```
\x49\x49\x49\x2E\x2E\x2E\x2E\x2E\xA0\xC0\xC0\xC0\xC0\xC0\x80\x52\xF0\xFD\x49\x49\x49\x2E\x2E\x2E\x2E\x2E\xA0\xC0\xC0\xC0\xC0\xC0\x80\x52\xF0\xFD\x49\x49\x49\x2E\x2E\x2E\x2E\x2E\xA0\xC0\xC0\xC0\xC0\xC0\x80\x52\xF0\xFD\x49\x49\x49\x2E\x2E\x2E\x2E\x2E\xA0\xC0\xC0\xC0\xC0\xC0\x80\x52\xF0\xFD\x49\x49\x49\x2E\x2E\x2E\x2E\x2E\xA0\xC0\xC0\xC0\xC0\xC0\x80\x52\xF0\xFD\x49\x49\x49\x2E\x2E\x2E\x2E\x2E\xA0\xC0\xC0\xC0\xC0\xC0\x80\x52\xF0\xFD\x49\x49\x49\x2E\x2E\x2E\x2E\x2E\xA0\xC0\xC0\xC0\xC0\xC0\x80\x52\xF0\xFD\x49\x49\x49\x2E\x2E\x2E\x2E\x2E\xA0\xC0\xC0\xC0\xC0\xC0\x80\x52\xF0\xFD\x49\x49\x49\x2E\x2E\x2E\x2E\x2E\xA0\xC0\xC0\xC0\xC0\xC0\x80\x52\xF0\xFD\x49\x49\x49\x2E\x2E\x2E\x2E\x2E\xA0\xC0\xC0\xC0\xC0\xC0\x80\x52\xF0\xFD\x49\x49\x49\x2E\x2E\x2E\x2E\x2E\xA0\xC0\xC0\xC0\xC0\xC0\x80\x52\xF0\xFD\x29\x29\x29\x29\x29\x29\x29\x29\x29\x29\x98\x98\x98\x98\x98\x98\x98\x98\x98\x98\x2E\x72\x2E\x72\x2E\x72\x2E\x72\x2E\x72\x2E\x72\x2E\x72\x2E\x72\x2E\x72\x2E\x72\x20\x20\x20\x20\x20\x20\x20\x20\x4D\x4D\x4D\x4D\x4D\x4D\x4D\x4D\x4D\x4D
```
## Installation, Compilation, Execution:
[Quoted from the 05AB1E docs](https://github.com/Adriandmen/05AB1E):
>
> 05AB1E is written in **Elixir** using the **Mix** build tool, which comes with Elixir.
>
>
> ### Installation
>
>
> 1. Clone this repository (e.g. with `git clone https://github.com/Adriandmen/05AB1E.git`).
> 2. Install **Elixir 1.9.0** or higher using one of the installation options [here](https://elixir-lang.org/install.html).
> 3. Install the package manager **Hex** with `mix local.hex`.
>
>
> ### Compilation
>
>
> Retrieve/update all necessary dependencies using `mix deps.get` (if necessary).
> In the terminal, compile the project using `MIX_ENV=prod mix escript.build`. On **Windows** in the command prompt, compile with `set "MIX_ENV=prod" && mix escript.build`.
>
>
> ### Execution
>
>
> After running the build command, a compiled binary file `osabie` will be generated. For example, running the file `test.abe` is done by running:
>
>
>
> ```
> escript osabie test.abe
>
> ```
>
> Normally, an 05AB1E file ends with `.abe`, but any other file extension can also be used.
>
>
>
* [Here is the same program as in my earlier TIO (with a multiline string input), which is run using Bash as example.](https://tio.run/##S0oszvifnJ@Saqv039PTUw8EjjQeboDBR01rgg5vOLx3VA67nCYcnJ6DCfWKMKECFPjCwX8lrtTkjHwF3TwF3VQFFVBsKNgpgCi9/OLEpMxUrtTi5KLMghIF/fyCEn2IGJRCVvZfSUkpxzYnNS@9JMNaQ8/M0EIrR9O2Tj9GT09L3zrTNjOvRENFDShmrRJvm6mnpKCkV1yaVFxSpBKvk6ljqKz7fv9eIOIaRmYAQwQA)
* [Alternatively, here is another Bash example program using `\n` in the input (as standard single line STDIN input), making use of `EOF`s.](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/239PTUw8EjjQeboDBR01rgg5vOLx3VA67nCYcnJ6DCfWKMKECFPjCwX8dLmDwc3GVZ2TmpCoUpSamKGTmcaXkcykopBYnF2UWlCjo5xeU6ENiC0qhRaCNggpYT17q/xzbnNS89JIMaw09M0MLrRxN2zr9GD09LX3rTNvMvBINFTWgmLVKvG2mnpKCkl5xaVJxSZFKvE6mjqGy7vv9e4EoJm9YGcIFAA)
## Explanation:
Primarily focuses on [radiation-hardening](/questions/tagged/radiation-hardening "show questions tagged 'radiation-hardening'"), while trying to output a random index + character pair.
Let me start with an explanation of the core of the program:
```
I.ā€Rðý.rM
I # Push the input multiline-string
.ā # Enumerate it, pairing each character with its 0-based index
€R # Reverse each inner pair from [char,index] to [index,char]
# (05AB1E does have a single-byte builtin for this `í`,
# but this caused errors if certain characters were removed)
√Ω # Join each inner pair
√∞ # with a space (" ") delimiter to a string
.r # Shuffle the list of strings
M # Push a copy of the maximum (inner-most) value to the stack,
# which basically takes the first character in the list in this case
# (which is output implicitly as result)
```
**Things to improve the radiation hardening:**
* Two I already mentioned: using `M` to get the first item in the list. I could have used `–Ω`, but I can use multiple `MMM` in a row without changing the functionality, whereas multiple `–Ω–Ω–Ω` would have resulted in the first digit of the index instead of the correct result-string.
* And using `€R` instead of `í`, since `.í` can cause errors if `ā` is removed, and `€ðý` or `Rðý` are both fine, and doesn't give too much trash.
* `)))ÀúÀúÀú` are used to wrap the entire stack into a list, and then flatten it. The multiple `)))` do of course result in an additional surrounding list every time, but the multiple `ÀúÀúÀú` are no-ops, as long as at least one of them is executed. If the `)` is removed, it uses the last resulting list (if applicable), so the example C program that focuses on removing parenthesis won't do too much harm here.
* The multiple `.r.r.r` to shuffle doesn't matter much either. And if either character is removed: `..` is a no-op, and `r` is a reverse of the entire stack, which should only contain a single item (the list) at this point anyway.
* Removing some other characters does result in trash in the list we shuffle and output a value from, but the chances aren't too high because we have repeated the program 11 times. E.g. Removing `ý` will put the indices and characters in the list as separated items, plus the additional pushed space ([try it online](https://tio.run/##yy9OTMpM/f/f09NTDwSONB5ugMFHTWuCDm/QhIPTczDh//9KSko5tjmpeeklGdYaemaGFlo5mrZ1@jF6elr61pm2mXklGipqQDFrlXjbTD0lBSW94tKk4pIilXidTB1DZd33@/cCEdcwMgMYIgA)). Removing `ð` or `R` will simply discard the list ([try it online](https://tio.run/##yy9OTMpM/f/f09NTDwSONB5ugMFHTWuCDu/VhIPTczDh//9KSko5tjmpeeklGdYaemaGFlo5mrZ1@jF6elr61pm2mXklGipqQDFrlXjbTD0lBSW94tKk4pIilXidTB1DZd33@/cCEdcwMgMYIgA) or [try it online](https://tio.run/##yy9OTMpM/f/f09NTDwSONB5ugMFHTWsObzi8VxMOTs/BhP//Kykp5djmpOall2RYa@iZGVpo5Wja1unH6Olp6Vtn2mbmlWioqAHFrFXibTP1lBSU9IpLk4pLilTidTJ1DJV13@/fC0Rcw8gMYIgAAA)). Removing `€` will put the index-character pairs in the wrong order ([try it online](https://tio.run/##yy9OTMpM/f/f09NTDwSONB5ugMGgwxsO79WEg9NzMOH//0pKSjm2Oal56SUZ1hp6ZoYWWjmatnX6MXp6WvrWmbaZeSUaKmpAMWuVeNtMPSUFJb3i0qTikiKVeJ1MHUNl3ff79wIR1zAyAxgiAA)). Removing `ā` will convert the input to a list of characters due to the `€`, after which it's joined by spaces ([try it online](https://tio.run/##yy9OTMpM/f/f09NTDwQON8Dgo6Y1QYc3HN6rCQen52DC//@VlJRybHNS89JLMqw19MwMLbRyNG3r9GP09LT0rTNtM/NKNFTUgGLWKvG2mXpKCkp6xaVJxSVFKvE6mTqGyrrv9@8FIq5hZAYwRAA)) - in addition, the `.....ÀÀÀÀÀ` will be some no-op `..`, one stack-rotate `.À`, and some list rotates `À`, all not changing the result too much. If `āÀÀÀÀÀ` would all be removed, the lists of the previous results would also be joined by spaces, which won't leave any correct results in the trailing list, hence why the `À` were added in the first place. Removing all `...` in front of the `ā` will result in a loose list of (1-based) indices, which are then joined together by spaces ([try it online](https://tio.run/##yy9OTMpM/f/f09PzSOPhBhh81LQm6PCGw3s14eD0HEz4/7@SklKObU5qXnpJhrWGnpmhhVaOpm2dfoyenpa@daZtZl6JhooaUMxaJd42U09JQUmvuDSpuKRIJV4nU8dQWff9/r1AxDWMzACGCAA)). Removing a `I` doesn't matter, since I've added two more just in case (it's actually beneficial if some are removed, since the additional `I` input-strings are trash in the original base program) - removing all three will do an additional enumerate, giving an incorrect list with two indices per string ([try it online](https://tio.run/##yy9OTMpM/f/f09NTDwSONB5ugMFHTWuCDm84vBenhCYcnJ6DCf//V1JSyrHNSc1LL8mw1tAzM7TQytG0rdOP0dPT0rfOtM3MK9FQUQOKWavE22bqKSko6RWXJhWXFKnE62TqGCrrvt@/F4i4hpEZwBABAA)).
* And the spaces between the `.r` and `M` are no-ops. So removing or keeping those doesn't change anything to the program. They're simply used to fill in the remaining bytes to make the program length 256 (and to somewhat counter the Whitespace program). I've placed them in between those two, since `.M` if the last `r` is removed is the most-frequent builtin, which would always give the input-string, but will also take about 25-30 seconds to execute, so we'd like to prevent that with the execution time rule of <1 second.
Removing multiple characters in the program simultaneously may result in some undefined behavior. I haven't tested this too much, except for removing `āÀÀÀÀÀ`, which would probably be one of the worst case scenarios if it's done in the final subprogram of the total 11.
I have no idea how well it will do, since it's still pretty random. But overall it should do reasonably well (I think/hope).
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), 256 bytes, rookie v4
```
( (:( (:(:( (:( ( ( ( :(:(:( ( (: ( ( ( (:( (
;
=
s
''
;
=
i
~
1
;
WWWW
>
9999
=
i
+
1
i
=
s
+
s
IIII?=a+''PPPP'null'''+aAAAAJ10OOOOU+++''=a%RRRR-LLLLsTTTT' 'GGGGs aTTTT;;;;;;lnulnuunlsaaiaisas++=%%%%>>>>~~~~''''''''PARLTGIWARTLGPabcdefghijklmnopq101110100
```
Base64 encoded:
```
KCAoOiggKDooOiggKDooICggKCAoIDooOig6KCAoICg6ICggKCAoICg6KCAoCjsKPQpzCicnCjsKPQppCn4KMQo7CldXV1cKPgo5OTk5Cj0KaQorCjEKaQo9CnMKKwpzCklJSUk/PWErJydQUFBQJ251bGwnJycrYUFBQUFKMTBPT09PVSsrKycnPWElUlJSUi1MTExMc1RUVFQnICdHR0dHcyBhVFRUVDs7Ozs7O2xudWxudXVubHNhYWlhaXNhcysrPSUlJSU+Pj4+fn5+ficnJycnJycnUEFSTFRHSVdBUlRMR1BhYmNkZWZnaGlqa2xtbm9wcTEwMTExMDEwMA==
```
V2: I added more buffer at the beginning of my code. Hopefully that allows it to stay alive longer.
V3: I change the comments to parentheses so that I don't get destroyed by Number Basher's newline killer. It should also work well in fending against parentheses killer as well.
V4: Added some stuff at the end to counter any strategies which delete characters from the end.
### Installation
Idk yet, here's a link to the code in an online interpreter instead with some test input: [Try It Online!](https://knight-lang.netlify.app/#WyIoICg6KCAoOig6KCAoOiggKCAoICggOig6KDooICggKDogKCAoICggKDooIChcbjtcbj1cbnNcbicnXG47XG49XG5pXG5+XG4xXG47XG5XV1dXXG4+XG45OTk5XG49XG5pXG4rXG4xXG5pXG49XG5zXG4rXG5zXG5JSUlJPz1hKycnUFBQUCdudWxsJycnK2FBQUFBSjEwT09PT1UrKysnJz1hJVJSUlItTExMTHNUVFRUJyAnR0dHR3MgYVRUVFQ7Ozs7OztsbnVsbnV1bmxzYWFpYWlzYXMrKz0lJSUlPj4+Pn5+fn4nJycnJycnJ1BBUkxUR0lXQVJUTEdQYWJjZGVmZ2hpamtsbW5vcHExMDExMTAxMDAiLCLigbhcblxuwrnCucK7wrnCq1xuwrlcbuG5m+KBuOG6iE3hu4vigbjhuohN4buL4oG44bqITeG7i+KBuOG6iE3hu4vigbjhuohN4buL4oG44bqITeG7i+KBuOG6iE3hu4vigbjhuohN4buLXG5cbsK5XG5cbsK5IOG4t1xuXG7CucKrIMK7XG5cblxuIMK5XG5cblxuXG5cbsKrYVxuXG5vYW9cblxuwqvCu8KrwrvCqyDCu8KrwrvCq8K7IMKrIMK7wqsgwrtcblxu4bi3wrnCuSDCuVxuXG7huZtcbuKAnOKAnOKAnOKAnOKAnOKAnOKAnOKAnOKAnOKAnOKAnOKAnOKAnOKAnOKAnOKAnOKAnOKAnOKAnOKAnOKAnOKAnOKAnOKBucaI4oKswrVU4buLwrVK4bif4rGuYOG7i+G5meG5ouG5quKCrMmX4oKsSsWSZ+G6iE5NWMKp4buL4bmtwq5fMcKkS8iu4buL4oCc4oCc4oCc4oCc4oG5xojigqzCtVThu4vCtUrhuJ/isa5g4buL4bmZ4bmi4bmq4oKsyZfigqxKxZJn4bqITk1Ywqnhu4vhua3Crl8xwqRLyK7hu4vigJzigJzigJzigJzigbnGiOKCrMK1VOG7i8K1SuG4n+KxrmDhu4vhuZnhuaLhuarigqzJl+KCrErFkmfhuohOTVjCqeG7i+G5rcKuXzHCpEvIruG7i+KAncK1wrXhuohN4buLwrnCucK54oG6VlZW4oG6Il0=)
[Answer]
## redun - Bash
```
#@#,_#
a="printf '20 ';head -c21|tail -c1;exit"
b="printf '20 ';head -c21|tail -c1;exit"
[ "$a" == "$b" ]&&[ "$a" == "$b" ]&&eval "$a"
" #"
a="printf '20 ';head -c21|tail -c1;exit"
b="printf '20 ';head -c21|tail -c1;exit"
[ "$a" = "$b" ] && eval "$a"
(
```
Survival odds against 1 random deletion: 253/256
Survival odds against 2 random deletions: 31747/32640
Survival time against forward sequential whitespace deletion: 25
Survival time against forward sequential deletions: 10
Don't know why it prints "20 0120 " after 11 deletions when fed its own original source, it start right, but then adds a 1 and runs again.
```
I0AjLF8jCgphPSJwcmludGYgJzIwICc7aGVhZCAtYzIxfHRhaWwgLWMxO2V4aXQiCmI9InByaW50
ZiAnMjAgJztoZWFkIC1jMjF8dGFpbCAtYzE7ZXhpdCIKWyAiJGEiID09ICIkYiIgXSYmWyAiJGEi
ID09ICIkYiIgXSYmZXZhbCAiJGEiCgoiICMiCgphPSJwcmludGYgJzIwICc7aGVhZCAtYzIxfHRh
aWwgLWMxO2V4aXQiCmI9InByaW50ZiAnMjAgJztoZWFkIC1jMjF8dGFpbCAtYzE7ZXhpdCIKWyAi
JGEiID0gIiRiIiBdICYmIGV2YWwgIiRhIgooCg==
```
[Answer]
## Tailstrike - Python 3
I had this laying around, doesn't seem to get immediately killed by the Burrowing Wheel. Since the last byte is quite likely to be an unnecessary line terminator, the bot actually attacks the 2nd last byte.
It turns out it's near impossible to get Python 3 to NOT use utf-8.
`PYTHONIOENCODING` only affect the already opened stdin/stdout/stderr, `open(0)` defaults to utf-8 even with `LC_ALL=C.ISO-8859-1`.
Using `sys.stdin` however isn't too horrible, the default error handling is to use surrogate-escape on both stdin and stdout.
```
2
3
5
7
""""
11,0
13,0
'(('
import sys
s=sys.stdin.read();print("%d "%(len(s)-2)+s[-2])
### """""
""""
"%(17,0)"
"%(19,0)"
n=s=sys.stdin.read();print("%d "%(len(s)-2)+s[-2])
###"""""
import sys
s=sys.stdin.read();print("%d "%(len(s)-2)+s[-2])
```
### base64 for easy copying
```
MgozCjUKNwoKCgoiIiIiCjExLDAKMTMsMAonKCgnCgoKaW1wb3J0ICAgc3lzCgpzPXN5cy5zdGRp
bi5yZWFkKCk7cHJpbnQoIiVkICIlKGxlbihzKS0yKStzWy0yXSkKIyMjICIiIiIiCgoKIiIiIgoi
JSgxNywwKSIKIiUoMTksMCkiCm49cz1zeXMuc3RkaW4ucmVhZCgpO3ByaW50KCIlZCAiJShsZW4o
cyktMikrc1stMl0pCiMjIyIiIiIiCgppbXBvcnQgIHN5cwoKcz1zeXMuc3RkaW4ucmVhZCgpO3By
aW50KCIlZCAiJShsZW4ocyktMikrc1stMl0pCg==
```
[Answer]
## Bastarf Mark III, Python 3 only
Run with `python3 bastarf`.
This is a bastard, but my finger slipped. It is focused on offense targeting the current leaders.
### Mark III
Implemented @mousetail's suggestion to use `exec("""` to reduce sensitivity to deletions. Also made print flush as output isn't to a terminal, don't know why this worked with Mark II but maybe it didn't.
Same targets as Mark II but hopefully less fragile. Some improvements could still be made, like removing nested exec, but there already three versions.
```
#
#
#
#
import os
i=os.sys.stdin.read()
try:
exec(r"""
def f(x):
exec('p=i.find(x)\nif p>=0:print("%d %c"%(p,i[p]),flush=True);os._exit(0)')
f('=l')
f('xn')
f('_1')
f('";')
f('\n\t')
f('$(')
f('>+')
f('%c')
f('st')
1//0
""")
except:
print("9 "+i[9])
```
```
IwoKIwoKIwoKIwppbXBvcnQgb3MKaT1vcy5zeXMuc3RkaW4ucmVhZCgpCnRyeToKIGV4ZWMociIi
IgpkZWYgZih4KToKIGV4ZWMoJ3A9aS5maW5kKHgpXG5pZiBwPj0wOnByaW50KCIlZCAlYyIlKHAs
aVtwXSksZmx1c2g9VHJ1ZSk7b3MuX2V4aXQoMCknKQpmKCc9bCcpCmYoJ3huJykKZignXzEnKQpm
KCciOycpCmYoJ1xuXHQnKQpmKCckKCcpCmYoJz4rJykKZignJWMnKQpmKCdzdCcpCjEvLzAKIiIi
KQpleGNlcHQ6CiBwcmludCgiOSAiK2lbOV0pCg==
```
* `f('=l')` specifically targets Distributed Damage
* `f('xn')` tries to target Comment Skipper by attacking the one fatal spot
* `f('_1')` tries to target Almost Rare by messing up the 1-base to 0-base conversion hopefully without causing pre-mature exit
* `f('";')` puts Example Python BOt in an unterminated string
* `f('\t\n')` attacks Ghost
* `f('$(')` will break NÜL Tränslätör, unless the input is actually `cat`
* `f('>+')` tries to target The 2nd'er
* `f('%c')` will make Example C bot output invalid data
* `f('st')` targets `stdin` in Example Node Bot, MVP and Parenthesis Killer
And then it starts getting too big.
Mark I and Mark II are hidden in the edit history.
[Answer]
## The Bloody Awful, Batch
This is the most cursed I could come up with that doesn't involve having to install an Itanic emulator and learning Itanium assembler.
```
@@@@@@@@@@@@@@@ echo off
@@@@@@@@@@@@@@@ echo off
::: The bloody awful :::
::: Mmmmm whitespace
set /p i=
<NUL set /p x=2 %i:~2,1%
exit /b
set /p i=
<NUL set /p x=2 %i:~2,1%
exit /b
```
It has CRLF line endings, so you may need to use the base64
```
QEBAQEBAQEBAQEBAQEBAICAgZWNobyAgIG9mZiAgIA0KDQpAQEBAQEBAQEBAQEBAQEAgICBlY2hv
ICAgb2ZmICAgDQoNCjo6OiAgIFRoZSBibG9vZHkgYXdmdWwgICA6OjoNCg0KOjo6IE1tbW1tICAg
ICAgICAgd2hpdGVzcGFjZQ0KDQoNCg0Kc2V0ICAvcCAgaT0NCg0KPE5VTCAgIHNldCAgL3AgIHg9
MiAlaTp+MiwxJQ0KDQpleGl0ICAvYg0KDQoNCnNldCAgL3AgIGk9DQoNCjxOVUwgICBzZXQgIC9w
ICB4PTIgJWk6fjIsMSUNCg0KZXhpdCAgL2INCg==
```
### Installation
Wine is required. Probably just `apt-get install wine`.
I have tested that it works with just wine64 (no wine32 installed) on Debian, but I have not tested at all on Ubuntu.
Run with `wine cmd /c bloody-awful.bat`
### Strategy
It doesn't seem to be possible to just read a byte from "standard input" in batch/cmd. This bot will read the first line (excluding line terminator) and select one character from it. The safest character to pick would be the first on the line, but even that isn't 100% safe since the line can be completely empty.
I choose to pick the 3rd character since that seems likely enough to exist and will get to the good parts slightly faster than picking the 1st.
For hardening, there is highly redundant at symbols before the redundant `echo off`s as well as plenty of whitespace (including after 'off') to mitigate against attacks from comment skippers and whitespace deleters.
All critical code is duplicated but not actually redundant, but it's enough to keep the Burrowing Wheel distracted with the useless comment for a while.
### And now for something completely different
[A recipe for a nice smoothie](https://www.youtube.com/watch?v=vDlMLqdvHzI)
[Answer]
# Random Hit, Python
```
###
exec("import random
i=input()
j=random.randint(0,len(i))
print(j+" "+i[j])")
###
exec("import random
i=input()
j=random.randint(0,len(i))
print(j+" "+i[j])")
###
```
You just need to install python, random is a built-in function. This selects a random character and removes it.
] |
[Question]
[
Given the diagonals of a matrix, reconstruct the original matrix.
The diagonals parallel to the major diagonal (the main diagonals) will be given.
[](https://i.stack.imgur.com/iwfTs.png)
Diagonals: `[[5], [4, 10], [3, 9, 15], [2, 8, 14, 20], [1, 7, 13, 19, 25], [6, 12, 18, 24], [11, 17, 23], [16, 22], [21]]`
## Rules
* The matrix will be non-empty and will consist of positive integers
* You get to choose how the input diagonals will be given:
1. starting with the main diagonal and then alternating between the outer diagonals (moving outwards from the main diagonal)
2. from the top-right diagonal to the bottom-left diagonal
3. from the bottom-left diagonal to the top-right diagonal
* The end matrix will always be a square
* The order of the numbers in the diagonals should be from top-left
to bottom-right
* Input and output matrix can be flattened
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins
# Test cases
```
[In]: [[5]]
[Out]: [[5]]
[In]: [[1, 69], [0], [13]]
[Out]: [[1, 0], [13, 69]]
[In]: [[25], [0, 1], [6, 23, 10], [420, 9], [67]]
[Out]: [[6, 0, 25], [420, 23, 1], [67, 9, 10]]
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~14~~ 12 bytes
```
Ṗ'L√ẇÞDf?⁼;h
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZYnTOKImuG6h8OeRGY/4oG8O2giLCIiLCIxLDY5LDAsMTMiXQ==)
Math? Sensible methods of putting things into arrays? Programs that finish in reasonable time? Couldn't be me.
Times out for anything bigger than a 2x2 matrix.
Takes input as a flattened list and outputs a flattened list.
## Explained (old)
```
f₌ṖL√vẇ'ÞD?⁼;h
f₌ṖL√ # Push all permutations of the flattened input, as well as the square root of the length of the flattened input
vẇ # Split each permutation into chunks of that length
'ÞD?⁼; # Keep those only where the diagonals equal the input (this basically means try each and every single possible matrix from the input until one is found with the same diagonals)
h # Get the first (and only) item
```
[Answer]
# [Python](https://www.python.org), 60 bytes (@Mukundan314)
```
f=lambda x:x and zip(map(list.pop,x[::-2][::-1]),*f(x[:-1]))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NVBBasMwELz7FXtcGVmJA4HWRC8xpmyruBVY2sVRwO5Xesmlvfc5_U0lk1x2h9lhZtivH1nTB8fb7fuaxubp7zTaicKrI1i6BSg6-PSCgQQnf0lGWPTSd11zGMpsB6XrETNToLp7_PogPCeI1yAr0AWiVHfqjWWtCGymzJzdOWzLx4R73e41HvVRqcplRZ8lztM7ko67XXOosWlVXUdlEpcuqGDkGSL4uLm99N3zMFRst-OIJcq481kKQKeyrcwliLTTrJGtJWVomvBR_PGEfw)
## [Python](https://www.python.org), 62 bytes
```
f=lambda x:x and[*zip(map(list.pop,x[::-2][::-1]),*f(x[:-1]))]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NZBBasMwEEX3PoWWIyErcSDQGpSLGFGmVZwILM3gKGD3Kt1k0256ot6mUppuZobP5_3PfHzxms-UbrfPax7bp5_DaCeMrx7F0i8Ckx_Ue2CIyDCFSzZMrJeh79udq7NzUqsRilJP6R6U7xCZ5izSNfIq8CISNw_pjXhtUNgimbnwKd5XSBm2uttq2Ou9lI0vjqFYfMAToE6bTbtT0HZSqSRNploGpBhpFkmEdKe9DP2zcw3ZEWqK8ccj1wN8AfJcI1B7TRrIWpQGpwmk_Kv8_4Bf)
Uses input format 1 (alternating upper and lower diagonals). Destroys the input.
[Answer]
# [J](https://www.jsoftware.com), 21 20 bytes
```
/:&;</.@i.@(,-)@%:@#
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TU9LCsIwEN33FE9FayGtSWtTGxUKgiAIgtuQlVjUhW4qeBc3deENvIzn8AKOiUoXycy83yTX26F-dvOWEka2VO77XjvyS0wVfDBwKDphhNl6Ob-fqzIcPQaqN54MomIfFX0WBkVXFR1HPV-Bt93sTijB0l_HISBziOQHxKnDECcQHMOYI4fMvO1lX9F6vTgaBa1TYzy9Olf_4c8IRoGGQfPPJZKmkLgvakUNV5xaC4P4VMloPfVWTE9gsIkya4aRiAhntBprcToyWLtxX69rV98)
Takes in flat, outputs flat.
* `%:@#` Square root of list length, to get matrix side length. Call it `n`.
* `(,-)` Create list `n -n`
* `i.` Assuming `n` is 5, eg, this will create the matrix:
```
4 3 2 1 0
9 8 7 6 5
14 13 12 11 10
19 18 17 16 15
24 23 22 21 20
```
* `</.@` Create the boxed diagonals of this matrix:
```
┌─┬───┬──────┬─────────┬────────────┬──────────┬────────┬─────┬──┐
│4│3 9│2 8 14│1 7 13 19│0 6 12 18 24│5 11 17 23│10 16 22│15 21│20│
└─┴───┴──────┴─────────┴────────────┴──────────┴────────┴─────┴──┘
```
* `/:&;` Unbox that and use it to sort the original input, ie, whatever sort would put this into order, apply it to the original input. This does exactly what we want.
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-x`, 22 bytes
```
Fi,YMX#*aFki+R,yPPOa@k
```
Inputs a nested list of diagonals, starting from the top right, as a command-line argument; outputs a flattened matrix in row-major order to stdout, one number per line. [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJGaSxZTVgjKmFGa2krUix5UFBPYUBrIiwiIiwiIiwiLXggXCJbWzVdOyBbNDsgMTBdOyBbMzsgOTsgMTVdOyBbMjsgODsgMTQ7IDIwXTsgWzE7IDc7IDEzOyAxOTsgMjVdOyBbNjsgMTI7IDE4OyAyNF07IFsxMTsgMTc7IDIzXTsgWzE2OyAyMl07IFsyMV1dXCIiXQ==)
### Explanation
For an \$N\$ by \$N\$ matrix, the top row can be found by taking the first number from each of the first \$N\$ diagonals and reversing them. If we remove these numbers from their respective diagonals, the next row is the reverse of the first remaining number in the first \$N\$ non-empty diagonals, and so on.
```
Fi,YMX#*aFki+R,yPPOa@k
a Command-line argument, evaluated (-x flag)
#* Length of each sublist
MX Maximum (this gives the size of the desired matrix)
Y Store in y
Fi, For i in range(y):
Fk For k in
,y range(y)
R reversed
i+ with i added to each element:
a@k Sublist at that index
PO Pop its first element
P Print the popped element
```
[Answer]
# JavaScript (ES6), 65 bytes
Expects the diagonals from top-right to bottom-left.
```
a=>a[w=a.length>>1].map((_,y,A)=>A.map((_,x)=>a[w+y-x][x<y?x:y]))
```
[Try it online!](https://tio.run/##bY/BDoIwEETvfkWPNBZCFwQxguE7msY0CKhBIEIUvh6XVU5ym9l529nezct02fPW9nbdXPKpiCcTJ0a9Y@NUeV321ySR2nmY1rLOYhQpj5N0sQMndDvag1bDcTwNh1FzPmVN3TVV7lRNaRWWUjstmPIFk@4sPMEi1DQEwfaoMQPKpGAhekQkMkBMgAY5iSD4BCElEQOPHOYA9JjU2L75b1@bLnVBRMJbhb4HuFj3OwS85Rc@4Jh2g3DenT4 "JavaScript (Node.js) – Try It Online")
Also **65 bytes**:
```
a=>[...a[w=a.length>>1]].map((_,y,A)=>A.map(_=>a[w+y--].shift()))
```
[Try it online!](https://tio.run/##bY/NDsIgEITvPgVHiJSUba16gKTPQUhDtD@a2hrbaHx6XFd70tvM7LfMcg73MB1up@ucDOOxjo2JwVinlAruYYLq66GdO2u19@oSrpxX8ilLYWxJtjIWufUzSbyaulMzcyFEPIzDNPa16seWN9y5jZfM5ZLp9C0yyfaoKQTJdqhxBjTTkm3RI6KRAWIKNMhpBCEnCCmNGGTkcA5Aj@GRQqx@2/@lS12xJ5H9hT4HpFj3PQSy5Rc5YEy7xfa9G18 "JavaScript (Node.js) – Try It Online")
---
# Flatten format, 89 bytes
This version expects a flatten array of the diagonals from top-right to bottom-left and returns another flatten array.
The only benefit is that there's only one `map()`. But the math is much more verbose. So yeah ... that's a bit silly. :-) There may be a better/shorter formula, though.
```
a=>a.map((_,x)=>a[y=x/w|0,x%=w,n=y+w+~x,(q=n>w&&n-w)*~q-n*~n/2+(x<y?x:y)],w=a.length**.5)
```
[Try it online!](https://tio.run/##bY7LCsIwFET3fkU2StLeVhO1PjD6ISIStL6oqS9MCtJfrxN0JW7C3DkzTE7mae6b2/HySGy5zZudboyem/RsLpyvyQscy0r7rnv1yLe1I6ur2MW1J37Vdu46HZs4EdXXxEa17aqY@1m18NNKrMhpkxa53T8OUZQORbMp7b0s8rQo93zHl0NiA2KyR6xPbAIFQxEbQ8FX8CWxEV5gCa7AM0hkJEIqlJGQiKgQAVNgSq6EaP1u/fE@A1lY7v/BYe4b@Q7gGoRvoZGN0Gje "JavaScript (Node.js) – Try It Online")
Given an input array of length \$N\$, we define for each index \$0\le i \lt N\$:
$$x=i\bmod w\\
y=\lfloor i/w \rfloor\\
n=y+w-x-1\\
q=\max(n-w,0)$$
where \$w\$ is the width of the matrix, i.e. \$\sqrt{N}\$.
The output value at this position is the value stored in the input array at the following index:
$$\frac{n\times(n+1)}{2}-q\times(q+1)+\min(x,y)$$
[Answer]
# [Ruby](https://www.ruby-lang.org/), 62 bytes
```
f=->d{(w=0..l=d.size/2).map{|r|w.map{|c|d[l+r-c][[r,c].min]}}}
```
[Try it online!](https://tio.run/##VYzRCoIwFIbvfYpBN0pzbSuNAnuFHuBwLmwmCDNkJVLqs6@5QeTVzv7/@37T397W1kV6qcZ4KDhjuqjYs/ncdzJhbdmNk5mGcKipAr01qUIAQxWytnngPM@2IzVTpdYxQIaYRBu49i88E/@Nol/tAo4UBCX5CSkBsV/TruAh98S/CiCzpeKUiOXNKZGOEp4/SBf7xfy4XnSYq4LqKS8F0il@ACP7BQ "Ruby – Try It Online")
Takes input as top-right to bottom-left.
Maps 2d indexes to input, for example a 4X4 matrix:
```
3,0 2,0 1,0 0,0
4,0 3,1 2,1 1,1
5,0. 4,1 3,2 2,2
6,0 5,1 4,2 3,3
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), ~~21~~ 22 bytes [SBCS](https://github.com/abrudz/SBCS)
```
⊖w↑i⊖↑⌽⍨≢↑⍥-i←⍳w←≢∘⍉∘↑
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31dP/UdsEAwA&c=e9Q1rfxR28TMR13TgNSjnr2Pelc86lwEYvcu1c181DbhUe/mchAFFOyY8ai3E0S2TQQA&f=NY47EsQwCEP7nOKVSWcJx44vlPsfYcE7adBnkODltC5ODexCoYkj6UBGD@7lM1Gghe@U5kEdt@TBQmV2VPq@jvebip0dK6FtZ8zadGPtE45/qFFfZPcP&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
`∘↑` mix the lists into a matrix, padding on the right with 0s, then…
`∘⍉` transpose, then…
`≢` tally the number of rows (this gives the size of the matrix)
`w←` store as `w` (for **w**idth)
`⍳` generate indices from 0 to that − 1
`i←` store as `i` (for **i**ndices)
`≢`…`⍥-` negate the argument length and that, then:
`↑` take arg-length elements from (because negative; the rear) of the indices, padding with 0s
…`⌽⍨` use those numbers to rotate left (because negative; right) the rows of:
`↑` the original argument lists mixed into a matrix, padded on the right with 0s
`i⊖` rotate the columns up by the amounts `i`
`w↑` take the first `w` rows of that
`⊖` flip upside-down
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 21 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
h½)r■_@mÅε-_╙+§\mÄ╓m§
```
Input expected as option 2: top-right to bottom-left 2D list.
Output as a flattened list.
[Try it online.](https://tio.run/##JY29DcIwEIV7NkE8pNzZceKOPYwV0UAKLCTECDBBFCQ6ukxASeP0DJFFjC9p7u9971043NrT5XxMqY3f9XV6vptdGB@/z7aZ@tcmDvsw3qe@C3FIybnS@5VzhYcjGCtNzRcu81yAcjVgBRJEcwFhTDUzguhFUbAg2Rk1SIOXxAqUrRZzmgExqAZr0QhU5WAZ8wMWK3n/Bw)
**Explanation:**
```
h # Push the input-length (without popping)
½ # Integer-divide it by 2
) # Increase it by 1
r # Pop and push a list in the range [0,length(input)//2+1)
■ # Get the cartesian product of this list, creating pairs
_ # Duplicate this list of pairs
@ # Triple swap input,pairs,pairs -> pairs,input,pairs
m # Map over each pair,
Å # using 2 characters as inner code-block:
ε # Reduce the pair by:
- # Subtracting
_ # Duplicate this list
╙ # Pop and push the maximum (which is length(input)//2+1)
+ # Add it to each integer in the list
§ # Get the inner lists of the input at those indices
\ # Swap so the other pairs-list is at the top again
m # Map over each pair,
Ä # using 1 character as inner code-block:
╓ # Pop and push the minimum of the pair
m # Map over both lists:
§ # Index these minima into the inner lists
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Python](https://www.python.org), ~~84~~ 79 bytes
-1 byte thanks to Kevin Cruijsen
-5 bytes thanks to Mukundan314 and 07.100.97.109
```
lambda x:(z:=len(x)//2+1)and[x[z+c%z+~c//z][min(c%z,c//z)]for c in range(z*z)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwdI0BVuFmKWlJWm6Fjf9chJzk1ISFSqsNKqsbHNS8zQqNPX1jbQNNRPzUqIroqu0k1WrtOuS9fWrYqNzM_M0gFwdEE8zNi2_SCFZITNPoSgxLz1Vo0oLKAY1NbGgKDOvRCNNIzraNDZWU5MLma8TbaKjYByroxBthCZnZAoSNdBRMATRZjoKRsZAtgGIY2IEFLYEC5uDdEEsWrAAQgMA)
Ported from Arnauld's JS answer
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), ~~9~~ 8 bytes
```
ṙLHĊƊṚŒḌ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6Fpt8PI50cT3cOfNw-8Ods45OerijZ0lxUnIxVPpmYbRSdLRprI5CtImOgqEBiGGso2AJZIMFjXQULIBsoJwRWM5QR8EcyAcqMQSqMQKrMQNygOoMgQqNTMCKgKoMgcqMjME8oLyREdgww9hYpViozQA)
How?
```
ṙLHĊƊṚŒḌ : Main Link
L : length; used to count the number of elements
H : Halve; divides by 2
Ċ : Rounds up (ceil)
Ɗ : Last three links as a monad
ṙ : Rotate x y times (x is implied input)
Ṛ : Reverse element
ŒḌ : Reconstruct matrix from its diagonals
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
g;ÝDδ-Z+èεNUεNX‚ßè
```
-2 bytes porting [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/252086/52210) (somewhat). I have the feeling the `εNUεNX‚ßè` could perhaps be golfed some more.
Input expected as option 2: top-right to bottom-left 2D list.
Output as a matrix.
[Try it online](https://tio.run/##yy9OTMpM/f8/3frwXJdzW3SjtA@vOLfVLxSIIx41zDo8//CK//@jo01jdRSiTXQUDA1ADGMdBUsgGyxopKNgAWQD5YzAcoY6CuZAPlCJIVCNEViNGZADVGcIVGhkAlYEVGUIVGZkDOYB5Y2MwIYZxsYCAA) or [verify all test cases](https://tio.run/##NU07CsJAEO09RUjrEzKbzcZoYZPGRitBXLZQELFRwUSwCHgOQWxzAPUAbp9DeJF1x2AxnzfvM/vjcrVdu1M43h3KYhCEOKMTTsvij3K3Gdpb3jx6i66tm@dk5mv@uVzt3dauqvB@jZzWOjEGgdaRgSaojEfcnkTiQQTyXUHEINZIEYFFKm1FrJEtFSMDMRbogyREm5mCvDfDL06BBKgPIZkjUOqTefUfBFvJGPMF).
**Original 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:**
```
g>;©FD®£€нR,¦ε®N>›i¦
```
Input expected as option 2: top-right to bottom-left 2D list.
Outputs each inner row-list on separated newlines to STDOUT.
[Try it online](https://tio.run/##yy9OTMpM/f8/3frwukMr3VwOrTu0@FHTmgt7g3QOLTu39dA6P7tHDbsyDy37/z862jRWRyHaREfB0ADEMNZRsASywYJGOgoWQDZQzggsZ6ijYA7kA5UYAtUYgdWYATlAdYZAhUYmYEVAVYZAZUbGYB5Q3sgIbJhhbCwA) or [verify all test cases](https://tio.run/##NY09CsJAEIV7TxFSvyKz2fwpaBMEGwXbZQsFERsVTASLgHgVISBIOi0Em7UXz5CLrLsuNjPzZr73ZrObzVcLvfdH621ZdD0fB3T8SVn8Va6XvVejLsNcNercnq6f5xSqft9UM@63x8dK1bqqKnUfaCFEJCU8IQIJQYgz20K3YpERAcjUGCwEWYazABaKEwdZhrtTiAxkNUMK4mAuMwEZb4ZfXAxioBSM2xuBEpNsR/OBWStJKb8).
**Explanation:**
```
g # Get the length of the (implicit) input 2D list
; # Halve it
Ý # Push a list in the range [0, length(input)//2]
Dδ- # Pop and push its subtraction table:
D # Duplicate the list
δ # Apply double-vectorized over the two lists:
- # Subtract
Z # Push the flattened maximum (without popping),
# which is the length(input)//2
+ # Add it to each integer
è # Index each inner-most integer into the (implicit) input
ε # Map over each inner list of lists:
NU # Store the map-index in variable `X`
ε # Map over each inner list:
NX‚ß # Push the minimum of the inner and outer indices:
N # Push the inner map-index
X # Push the outer map-index from variable `X`
‚ # Pair them together
ß # Pop and push the minimum
è # Index that minimum into the list
# (after which the resulting matrix is output implicitly)
```
[Extracted from this 05AB1E answer of mine](https://codegolf.stackexchange.com/a/241931/52210), where I've used 45 degree matrix rotations for a word-search solver:
```
g; # Same as above
î # Ceil it
© # Store this matrix-size in variable `®` (without popping)
F # Pop and loop this many times:
D # Duplicate the current 2D list:
®£ # Only keep the first `®` amount of inner lists:
€н # Get the first item from each
R # Reverse it
, # Pop and print it with trailing newline
¦ # Remove the first inner list
ε # Map over each remaining lists:
i # If
® # dimension `®`
› # is larger than
N> # the 1-based map-index:
¦ # Remove the first item from this list
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 43 bytes
```
a->matrix(w=#a\2+1,,i,j,a[w+i-j][min(i,j)])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY9BCsIwEEWvMuimpVMw01p1oReJQbKpRFRCqahncVMQ8UziZfyd2tX8_-flJ3m8o2_Cbh-7Z03r16Wt8-Un8_nm5Nsm3JLreuq3khnmwAf29pqF_ODsKZwTBKlL_0e-PsbjPfGUbyg24dxCTnozoTrxacpkrZ07jJLJzHpRMK2gNRSmJTR2ojvDtIAHYsCIMhUMOANQSoVAGWBSqMNeRMuM6weu0zEWVisVxZAOnTM0_LulGB9WCmKFq4Vz4xe7bpg_)
Takes input from top-right to bottom-left.
[Answer]
# Haskell + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 25 bytes
```
lH(F~<zdm<<lpW[]<lg)<mm p
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ2W0km6Ec0CAUuxN1czcgvyiEoXC0sSczLTM1BSFgKLUnNKUVC6oRABXmm3M0tKSNF2LnTkeGm51NlUpuTY2OQXh0bE2OemaNrm5CgUQ-ZsGuYmZebYp-VwKCrnxCgVFCioKaQrRSvZKOkoREUo6CkqGRsYgSlUVRDooxUL0LVgAoQE)
## Explanation
To build the matrix we use a fold, each step adding a new diagonal. So the bulk of this answer is the function that takes a partial matrix and adds a new diagonal.
The way this process works is that we want to zip the new diagonal with the matrix. If the diagonal is longer than the matrix so far (length of the matrix is the number of rows), then we want to start the zip with the two aligned at the front.
```
1 #### 1####
2 ### 2###
3 ## --> 3##
4 # 4#
5 5
```
If the diagonal is shorter we want to align it at the bottom:
```
##### #####
##### #####
1 #### --> 1####
2 ### 2###
3 ## 3##
```
To do this we pad the diagonal out to the length of the list with empty values. (`lpW[]<lg`) If it's longer this does nothing, but if it's shorter it aligns the two at the bottom.
Then we zip the two with `zdm`. This is the "monoidal" zip, so it pads the shorter value to the length of the longer and combines with the monoid operation.
The one hitch is that for this all to work we need to convert the integers in the diagonals to lists, that way we can have empty values in the padding.
## Reflection
This is a very elegant solution, but it does suggest improvements.
* It hurts me to use `lg`. Because there's nothing to bind the type `l` won't work. `lpW^.lg` should probably be builtin, padding one list to the length of another seems like a useful operation. This would save 3 bytes here.
* `fb F` seems like a useful combinator. However it would need to be a 1 byte operator to save anything in this particular scenario.
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 73 bytes
```
foldl(!)[]
[]#[]=[]
(a:b)#(c:d)=(c:a):b#d
a!b=(a++[[]])#b
(a++b)!c=a++b#c
```
[Try it online!](https://tio.run/##HYxLCsMwDET3OYWCNzZxoXbSX8AnEVrYDoHSpC0pXfT07sQb6Y3mofzdtt/hHR/5U8oc5tcyLbo1LA2LYgkAHcdklM7jZAJmNGNSUxPbFHTsOmYRo1KzczJtDvtWuazx/qRAMzGfxBIPltxxh97SDVyP3tIVjM7Xzlm6IENxcHx1zgjwHEQ/VAmWg@b7mtB7X585kfIH "Curry (PAKCS) – Try It Online")
A port of [@Wheat Wizard's Haskell + hgl answer](https://codegolf.stackexchange.com/a/256312/9288).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
I⮌E⊘⊕LθE⊘⊕Lθ⊟§θ⁺ιλ
```
[Try it online!](https://tio.run/##jYpLCsIwEECvkuUUIjhp6wdX4saCQnEbsghtsIWYtmks3j5OgwdwYGDee9N02jeDtjHWvncBLnoO8DCL8bOBux7hqu1iWqhc483LuED3zbhn6GDKsoyzf37qYYRzqFxrPjAR2vcMPWc2@80pRimlQMWZxB1nQqQLOcM9Ub4SaRS0BxJFypxRxJz2SK5cHT1Qx4J4uzJFapgaSUyyVErFzWK/ "Charcoal – Try It Online") Link is to verbose version of code. Takes input from bottom left to top right. Explanation:
```
θ Input array
L Length
⊕ Incremented
⊘ Halved
E Map over implicit range
θ Input array
L Length
⊕ Incremented
⊘ Halved
E Map over implicit range
θ Input array
§ Indexed by
ι Outer index
⁺ Plus
λ Inner index
⊟ Pop from list
⮌ Reversed
I Cast to string
Implicitly print
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 77 bytes
```
(n=⌊Length@#/2⌋;Total@MapThread[DiagonalMatrix[#1,#2]&,{#,Range[-n,n]}])&
```
Input from the bottom-left diagonal to the top-right diagonal
[Try it online!](https://tio.run/##FYjPCoIwGMBfZTCQgi/SVUaEsEPHhAhvssNHTR3oZ4wdgrEXKJ/SF1l5@v0Z0HV6QGceGJsirqiYp89VU@s6ybdinr7nanTYyxJfVWc1PuuLwXYk7Et01rxrngEXKgHP4Y7U6npDQCqodRJv1pCTjfQ@PwZgfi9SYKfFcmBiByxLl/jPbKE4hBB/ "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
## Challenge
Given an input string `X`, determine if `X` can be obtained from reshaping a *strict prefix* of itself (a prefix that is not `X` itself).
Reshaping a string to a length `N` means repeating the string as many times as needed and then taking the first `N` characters of it.
## Examples:
The string `"abba"` returns Truthy becacause `"abb"` can be reshaped to length 4 to obtain `"abba"`.
The string "acc" returns Falsy becacause none of its strict prefixes (`"a"`, `"ac"`) can be reshaped to obtain `"acc"`.
(Outputs must be consistent)
## Test cases:
```
AA => 1
ABAba => 0
!@#$%&()_+! => 1
AAc => 0
ababababba => 1
abcdeabc => 1
abacabec => 0
@|#|#|@#|@||@#@||@|#| => 1
10101101101010110101011101111011110110110101101101010110010101101101010110 => 1
17436912791279205786716328174301174187417348216070707180471896347218574617954278517034215720138543912791279205786716328174301174187417348216070707180471896347218574617954278517034215720286716328174301174187417348216070707180471896347218574617954278517034219127912792057867163281743011741874173482160707071804718963472185746179542785170342157205720475941259275912791279205786716328174301174187417348216070707180471896347218574617954278517034215720475941252867163281743011741874173482160707071804718963472185746179542785170342157204759412517436912791279205786716328174301174187417348216070707180471896347218574617954278517034215720138543912791279205786716328174301174187417348216070707180471896347218574617954278517034215720286716328174301174187417348216070707180471896347218574617954278517034219127912792057867163281743011741874173482160707071804718963472185746179542785170342157205720475941259275912791279205786716328174301174187417348216070707180471896347218574617954278517034215720475941252867163 => 1
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 10 bytes
```
^(.+).*\1$
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8D9OQ09bU08rxlDl/39HJ8ekRC5FB2UVVTUNzXhtRS5Hx2SuxCQIBEolJiWnpAIJkFhyYlJqMpdDjTIQOgBRDZAEEUAul6EBEEKQARIFxnACKo6szABDBAA "Retina – Try It Online")
Works in any flavor of regex that supports backreferences.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
⊙θ⁼…θκ✂θ±κ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMxr1KjUEfBtbA0MadYw7kyOSfVOSO/ACSWramjEJyTmZwK4vilpieWpGpka4KA9f//hgZACEEGSBQYwwmoOLIyAwyR/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Simply checks whether any prefix of the input is also a suffix. The edge case of the empty prefix is ignored because you can't slice an empty suffix using a negative slice offset.
```
θ Input string
‚äô All indices satisfy
θ Input string
… Truncated to length
κ Current index
⁼ Equals
θ Input string
‚úÇ Sliced from
κ Current index
± Negated
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) -n, 15+1 bytes
```
p ~/^(.+).*\1$/
```
[Try it online!](https://tio.run/##KypNqvz/v0ChTj9OQ09bU08rxlBF////xKSkRK7E5OR/@QUlmfl5xf918wA "Ruby – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 56 bytes
```
f s=any(and.zipWith(==)s.cycle.(`take`s))[1..length s-1]
```
[Try it online!](https://tio.run/##ZU/LCoMwELz3K2JsS0LboB8gmN577kFE1xirGIM0uVj8dxsfFKHM7My@Drs1mFYqNU0VMhHogYAu2afpn42tSRRRw8QglGQkt9DK3FCahIwpqV@2RuYWppOVxhoUoQTzOy8AXxH2Yv94OhOaXby55FzMBsWKdQcKUUon20RAIZc8Hn2H2HF0Oosr50EYOKwMdrbET7b@fi346@D0cOig0e7oDvpHhkj/brRlFUXLM9MX "Haskell – Try It Online")
---
# [Haskell](https://www.haskell.org/), ~~54~~ 53 bytes
Based on [Neil's answer](https://codegolf.stackexchange.com/a/239797/64121): Checks if any proper prefix is a suffix.
```
import Data.List
f s=init(1<$s)>(1<$inits s\\tails s)
```
[Try it online!](https://tio.run/##ZU9BDoIwELzzilLQ0GgI3MVQ41FfIIZsocRGQEJ75O91C8SQmNnO7MzuYfsC/ZZta63qhs9oyBUMxDeljdcQnalemSg9hZqdnTiriS4KA6rFhlkjNSYZeVB@4QLokVA/D8LdPmLlwXeW88oJiAXLDoiqlkjrpAIh5z6fAkSONSE7QusGaYJYKtnI/H605tu15C@hT8/rQPV4dAfDvSTRMKrexA0j82fsFw "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ṁƤinL
```
[Try it online!](https://tio.run/##y0rNyan8///hzsZjSzLzfP4/3L3l0NbD7UcnPdw5QzPy///EpOSUVCDBlZiUmJyYlJoMAA "Jelly – Try It Online")
## How it works
```
ṁƤinL - Main link. Takes a string S on the left
∆§ - Over each prefix P of S:
ṁ - Mold to length S
i - First index of S
L - Length of S
n - Are these two unequal?
```
Essentially, the index and length will only be equal if the only reshaped prefix equal to S is the full prefix i.e. a non-proper prefix
[Answer]
# Haskell, 57 bytes
```
f x|l<-length x=or[x==take l(cycle$take n x)|n<-[1..l-1]]
```
[Try it Online!](https://tio.run/##ZUpbCoMwELzK@miJtIp@twHTa4iUJI1VjKlYPyx493SjUoQys7M7O1Pzd6u0traCib6GYqJ05K0iGqaIyI/UKnQeDPrZXOMiSxLM4qwsL5pqZZ5jbTveGKDQD40ZgXS8hwoKn92Y4P4ZfC8PwsORRPeT5yxj0i0uVqwdLuRDoWyJ5EItdz4HiBw5ozpB64IsRaxMd2uZn2z/fS39@/hlZL8)
-2 bytes thanks to ovs
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 7 bytes
```
L?¦ṪvẎc
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwiTD/CpuG5qnbhuo5jIiwiIiwiJ2FiY2EnIl0=)
```
·π™ # All but last
¦ # Of prefixes
? # Of the input
v # Each
Ẏ # Extended to...
L # Input length
c # Includes input
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 11 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
⊑⋈∊≠⥊¨2↓»∘↑
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oqR4ouI4oiK4omg4qWKwqgy4oaTwrviiJjihpEKCj4o4ouI4p+cRinCqOKfqCJBQkFiYSIKIiFAIyQlJigpXyshIgoiQUFjIgoiYWJhYmFiYWJiYSIKImFiY2RlYWJjIgoiYWJhY2FiZWMiCiJAfCN8I3xAI3xAfHxAI0B8fEB8I3wiCiIxMDEwMTEwMTEwMTAxMDExMDEwMTAxMTEwMTExMTAxMTExMDExMDExMDEwMTEwMTEwMTAxMDExMDAxMDEwMTEwMTEwMTAxMDExMCIK4p+p)
Notes:
A train which roughly translates to `{‚äë(‚ãàùï©)‚àä(‚â†ùï©)‚•䬮2‚Ü쬪‚àò‚Üëùï©}` akin to APL, except we have a single byte prefixes builtin.
-1 from ovs.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
~ca₀ᵈ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8r0tOfNTU8HBrx///0UqOjko6CkqOTo5JiSCGooOyiqqahma8tiJY3DEZRCUmQSBETWJSckoqkIDKJCcmpYLZDjXKQOgARDVAEkQAuSAJQwMghCADJAqM4QRUHFmZAYaIko6SoVIsAA "Brachylog – Try It Online")
Ungodly slow on even mid-sized failing inputs; the essentially equivalent `~c₂a₀ᵈ` is much more performant: [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8r0t@1NSU@Kip4eHWjv//o5UcHZV0FJQcnRyTEkEMRQdlFVU1Dc14bUWwuGMyiEpMgkCImsSk5JRUIAGVSU5MSgWzHWqUgdABiGqAJIgAckEShgZACEEGSBQYwwmoOLIyAwwRJR0lQ6VYAA "Brachylog – Try It Online")
```
~c Some partition of the input
ᵈ is a list of two elements such that the first has the second as
a‚ÇÄ a nonempty prefix.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
ṁȯ€tṫ¹ḣ
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f/DnY0n1j9qWlPycOfqQzsf7lj8////aCVHJ8ekRCUdJUUHZRVVNQ3NeG1FIM/RMRlIJiZBIFhBYlJySiqQgIgnJyalgpgONcpA6ABENUASRAC5QHFDAyCEIAMkCozhBFQcWZkBhohSLAA "Husk – Try It Online")
Same approach as [Neil's answer](https://codegolf.stackexchange.com/a/239797/95126) and [tsh](https://codegolf.stackexchange.com/users/44718/tsh)'s comment: 'is any prefix of input string also one of its suffixes?'
```
ṁȯ ḣ # map over each of the prefixes of the input:
€ # is it present within...
t # the tail of (=drop the first element of)...
·π´¬π # the suffixes of the input?
ṁ # sum the answers
# (so output is non-zero (truthy) for re-shapable strings)
```
[Answer]
# [Haskell](https://www.haskell.org/) + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 13 bytes
```
cP$h_<*h'>~ É
```
If you can simply submit a parser object, then that can be 10 bytes:
```
h_<*h'>~ É
```
## Explanation
* `h_` parses at least one thing off the front of a list (think `.+` in regex).
* `h'` parses any amount off the front of a list (think `.*` in regex).
* `É` is a function which takes an string and produces a parser which matches exactly that string.
We combine the two with `<*` which runs both sequentially giving the result of the first. Then we bind this to `É`, so that the result of `h_` is passed as the input to `É`.
In do notation this would be
```
do x<-h_;h'; É x
```
Described in plain English this matches any string that contains the same non-empty section at both the start and end.
# Non-parser, ~~17~~ 15 bytes
The parsers are obviously the way to go for this challenge, but I thought I'd give it a go without them to see how good hgl does.
```
lt 2<(cn**sw)sx
```
## Explanation
* `sx` gets all prefixes of a list
* `sw` checks if a particular list starts with another.
* `cn` counts the number of elements that satisfy a predicate.
* `(**)` is an infix for `liftA2`.
So altogether `(cn**sw)sx` counts the number of suffixes of the list are also prefixes.
Now, the empty string and the input string should always pass this test. So we want to test if there is *another* string which also is both a prefix and a suffix. So we use `lt 2` to check that's greater than `2`.
## Notes
Some things that could have been better for hgl in this challenge.
* There should be a function `lt2=lt 2` (and `gt1`, `lt3` etc.). That would have saved a byte here.
* `(**)` has the default precedence which although not causing any issues here, could probably be improved.
* Variants of `px` and `sx` that give for example non-empty or strict prefixes / suffixes would probably be useful. If I had a function that specifically gave non-empty and strict suffixes then I could just do `ay**sw$sxS` (where `sxS` is the imagined function) for 10 bytes.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 52 bytes
```
s=>s.replace(/./g,c=>((p+=c)+p).indexOf(s)+1,p='')>1
```
[Try it online!](https://tio.run/##ZYxRS8MwFIXf8ysypiaX1qx5LintwGd/gIpL03RGuiY0RQrO315T08lgnJsTzrkf91N@Sa8G48bH3jZ6bsXsReHZoF0nlaY7tjumShSUukQoSBww0zd6em6ph4SnThACBZ9zfEDVvqolFgXO0Kbc3t0/UHhPNkvBUVWpuJF1VCR5yKrRwS5JKlnrlS3P26AyzDn4YiFGkGdBcbKr7@/929pfY9lNE@8d2DiYEwXmXWdGSl57Aqy1w5NUH3RamG@EsbK9H/GLSbF@wwJPF3rZE8hXwnaadfZIW2oA0A/k8y8 "JavaScript (Node.js) – Try It Online")
Partial based on Redwolf Programs's answer.
---
# [JavaScript (Node.js)](https://nodejs.org), 56 bytes
```
s=>(g=p=>s[0]&&(p+=s.shift())==(q=s.pop()+q)|g(p))(q='')
```
[Try it online!](https://tio.run/##ZYzhaoMwFIX/@xS3dKu52AX9LREd7CmcrDGNNsWZ1MgozD27i4sthXFuTjjnftwz/@JWDMqML70@yrlhs2UZaZlhmS3jarcjJmKW2pNqRoLIGLm4aLQhGF1waolBdFUY4pzCIShei5oDyyAONvn26XlH8CPaLEUSFIXwG157eTJxWRyls1vigtdyZfNp65S7mZwv5qIHk9jJT/zw/b27rf0jFv9r/L0DHQf1SZBa06mRhO99iLTRwxsXJ3JdmO8AQOjejlCqPcgKGFxv9LIPMV0J3Una6ZZEDSkppapCYAwiuYd7gcEPpvMv "JavaScript (Node.js) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 11 bytes
```
e.#$&><\@}:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/U/WUVdTsbGIcaq3@a3JxpSZn5ANlbRXSFNQdnRyTEtUhQoYQIUUHZRVVNQ3NeG1FdVS1jsmoKhOTIBDdhMSk5JRUIIGqHagyOTEpFc0MhxplIHQAohogCSKAXFQlhgZACEEGSBQYwwmoOLIyAwwRda7/AA "J – Try It Online")
This one is kind of tailor made for J.
* `e.` Is the input an element of...
* `<\@}:` Each prefix except the last...
* `#$&>` Shaped to the original input's length.
[Answer]
# [Python 3](https://docs.python.org/3/), 55 bytes
```
lambda s:any(s in s[:x]*len(s)for x in range(1,len(s)))
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYKjGvUqNYITNPoTjaqiJWKyc1T6NYMy2/SKECJFiUmJeeqmGoAxHW1PxfUJSZV6KRpqGemJysrqnJheAnJSUCBf4DAA "Python 3 – Try It Online")
Porting regexes are boring, so non regex one
[Answer]
# [Python 3](https://docs.python.org/3/), 49 bytes
```
f=lambda s,i=1:s>s[:i]and(s[i:]==s[:-i])|f(s,i+1)
```
[Try it online!](https://tio.run/##bUxdS8NAEHzPr9imKnc0Sg7fAldyKULFYl8KFmKQyxddiDF4ESumvz3ueVUKyuzOMrOz2330u5f2ehxr2ejnvNRgApQiMnOTRpjptmQmxSiTkvQlZnyoGSVmgo/vO2wqEJEHABjsJbbdW8/4leka7JkPcg4@t8vuFdueYeA/3n8marVabyBZb@HhdrOE7eEfc7G8Wdwd/LRmyKW0x3ue8VElKtf2behN4unZ@QXjT7OJNYSnVOE2OndwSUG6KCuiH6ULnVfHbDxMCTHVQGyJpAuKkOAqPBnf/UtH/zQW/nHcvy8 "Python 3 – Try It Online")
[Answer]
# JavaScript (ES6), 23 bytes
```
x=>/^(.+).*\1$/.test(x)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9o@7/C1k4/TkNPW1NPK8ZQRV@vJLW4RKNC839yfl5xfk6qXk5@ukaihlJiUnKikqbmfwA "JavaScript (Node.js) – Try It Online")
Or if a function that can't be bound to a variable is allowed, 17 bytes:
```
/^(.+).*\1$/.test
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9o@18/TkNPW1NPK8ZQRV@vJLW45L@GUmJScqKSprVCcn5ecX5Oql5OfrpGouZ/AA "JavaScript (Node.js) – Try It Online")
Regex completely stolen from [G B's answer](https://codegolf.stackexchange.com/a/239806/100664), go upvote that!
[Answer]
# [R](https://www.r-project.org/), ~~74~~ ~~72~~ 70 bytes
Or **[R](https://www.r-project.org/)>=4.1, 63 bytes** by replacing the word `function` with a `\`.
*Edit: -2 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
function(s,n=sum(s|1)){for(i in 2:n)T=T&any(s[1:i-1]-s[n+2-i:1]);!T+1}
```
[Try it online!](https://tio.run/##dU7BDoIwDL37FQOUbEGSjZPBYJg377sRYgayZAdHwuBgxG/HKYqoWV77mravL20GkQyiU2UrawX1WiW6O0PdE4Suom6gBFKBKFaIJczn6gJ1RmIZkjzUmQqiUMYkR1uHBeQ2CNi1YsPqg2qhS/e04C5CHkh2AC@@dk7qLVc@RMfAeSvIt4LS0nLLixEfc/IrKE@VIeual7yobPZp7xmkJnrDDzKtxYpggzHwrDxzotd8LsN/E9uv05PDHQ "R – Try It Online")
Non-regex approach (that would be simple port of other answers: `function(s)grepl("^(.+).*\\1$",s)`).
Takes input as a vector of char codes.
Outputs `NA` as truthy and `FALSE` as falsy.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.sI¨ηåà
```
-1 byte by porting [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/239797/52210).
[Try it online](https://tio.run/##yy9OTMpM/f9fr9jz0Ipz2w8vPbzg///EpKREAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lf73iykMrzm0/vPTwgv86/xOTkhK5EpOTuRydHIEsRQdlFVU1Dc14bUUuR8dkrsQkCAQpSkpOSQUSILHkxKTUZC6HGmUgdACiGiAJIoBcLkMDIIQgAyQKjOEEVBxZmQGGCBdIkAvEBwA).
**Original 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:**
```
¨ηIgδ∍Iå
```
[Try it online](https://tio.run/##yy9OTMpM/f//0Ipz2z3Tz2151NHreXjp//@JSUmJAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/0Mrzm2vTD@35VFHb@Xhpf91/icmJSVyJSYnczk6OQJZig7KKqpqGprx2opcjo7JXIlJEAhSlJSckgokQGLJiUmpyVwONcpA6ABENUASRAC5XIYGQAhBBkgUGMMJqDiyMgMMES6QIBeIDwA).
**Explanation:**
```
.s # Get the suffixes of the (implicit) input
I¨ # Push the input-string, and remove its last character
η # Get the prefixes of this string
åà # And check if any is in the suffixes-list
# (after which the result is output implicitly)
¨ # Remove the last character of the (implicit) input-string
η # Take its prefixes
δ # Map over each prefix:
‚àç # And extend each to a length equal to
Ig # the length of the input
Iå # Then check if the input is in this list
# (after which the result is output implicitly)
```
The second program could have been 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) if the input is never an integer by removing the `g`, because `‚àç` will extend to the length of given string and list arguments: [verify (almost) all test cases without `g`](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/0Mrzm2vPLflUUdv5eGl/3X@JyYlJXIlJidzOTo5AlmKDsoqqmoamvHailyOjslciUkQCFKUlJySCiRAYsmJSanJXA41ykDoAEQ1QBJEALlchgYGhlyGhgaGAA), and see how it now fails for `1001` and `1101`.
[Answer]
# Excel, 72 bytes
```
=LET(x,SEQUENCE(LEN(A1)/2),OR(SUBSTITUTE(LEFT(A1,x),RIGHT(A1,x),"")=""))
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnXNfaViRe8wWhqq3?e=lshBEv)
String comparisons in Excel are not case sensitive but `SUBSTITUTE` is.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 bytes
```
⊂∊≢⍴¨¯1↓,\
```
[Try it online!](https://razetime.github.io/APLgolf/?h=AwA&c=S3vUNuFRV9Ojjq5HnYse9W45tOLQesNHbZN1YgA&f=S1NQT09MTEyHIhBbHQA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f# "Goto The APL Orchard")
From [Kamila's answer](https://stackoverflow.com/a/70396007/16457512) and upvote that!
[Answer]
# [R](https://www.r-project.org/), ~~77~~ ~~73~~ 69 bytes
```
function(s)any(grepl(s,paste0(r<-substring(s,0,nchar(s):1-1),r),f=T))
```
[Try it online!](https://tio.run/##bY7RCoIwFIbvewu1YocmzNtIcD1D93I2pwmxZNOLwHe3U0aYi//sP@zbv8NxU@tLZ/wVO1PlUz1Y3bd3yzygfbDGme7GPO/Q90Ywd0r9oHzvWtsQFdzqKzrKHrM0A@6A1/kFYDmSxfIsFcaw@YFRkWx3ewblIVo/SanXCNWscA4qXRmyPz80KhPwYkxIBdVI/jK6rkOZIM0lFu19vvbhy5gISLBWDNMT "R – Try It Online")
Outputs `TRUE`/`FALSE`.
[Answer]
# JavaScript (ES6), 64 bytes
*-13 thanks to @pxeger*
```
s=>[...s].some((_,i)=>!s.slice(0,i).repeat(s.length).indexOf(s))
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
K'?~•f⁼;₃
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJLJz9+4oCiZuKBvDvigoMiLCIiLCJbXCJhXCIsIFwiYlwiLCBcImJcIiwgXCJhXCJdIl0=)
Ah yes, the limitations of type overloading. Returns `0` for Truthy inputs and `1` for Falsey inputs.
## Explained
```
K'?~•f⁼;₃ # Takes input as a list of characters
K # Prefixes of the input
' # Keep items where:
?~• # The item molded to the shape of the input
f⁼ # is the same as the input (i.e. non-vectorised equality)
; # Close filter.
‚ÇÉ # Is the length of the list 1? For falsey inputs, the resulting list will just contain the input meaning it doesn't have any truthy prefixes.
```
[Answer]
# Wolfram Language (Mathematica), 82 Characters
[Try Online](https://tio.run/##XYsxCsJAEEV7T/FJwGotPEBgW0FQNN04xbiMyaBZJEwj4tnXFbGxfO@/P4mPOolbklL2s2Wn3YwY0cv5prQAcPSqh4PeVZy@0MtVqQ0wDjjRJl8smz8qfPrfY6t58DG2jK5DjZ8W/hassH4xltRISg1zKW8)
Practically the most basic answer I could think of. Tried some fancy things like converting into a list of characters or using some sort of trick instead of StringRepeat, but the bytes came out better this way.
```
Or@@Table[
StringRepeat[StringTake[#,i],‚àû,StringLength@#]==#,{i,StringLength@#-1}]&
```
Explanation:
Iterates i from 1 to the length of the string - 1, and repeats the first i characters until it matches the length of the original. Then, it compares this value to the original and computes whether any of them are true.
I don't know/remember how many characters Infinity counts as, so if that's a problem, I have an 88 character solution without any special chars:
```
Block[{v=Characters@#},
Or@@Table[
PadRight[v~Take~i,Tr[1^v],v~Take~i]==v,{i,Tr[1^v]-1}]]&
```
This converts the string into a list and saves it as a variable, which costs 24 characters, but makes the rest far shorter. I can't just define v as a global variable since that messes up the pure function, and writing out Characters@# is far too long to not be a variable.
[Answer]
# [Factor](https://factorcode.org/) + `grouping.extras math.unicode sequences.repeating`, 59 bytes
```
[ dup head-clump 1 head* [ over length cycle = ] with ∃ ]
```
[Try it online!](https://tio.run/##7VJNT8MwDL3vV5gNEB9iStK0aUFIKxfEhQviNE0oy0xX0aUlbYGh3bjwO/kjxd0ATeK6XRCy/Ww/W8855F6bKnfN7c3V9eUpPKCzmEHi8rpIbdLHl8rpEkp8rNEaLCFBi05n6auu0tyuTfoOCyTSJjDT1bRf29TkE4TCYVXNC5faCs46nW4cdwku4rGmvDPo7e7tHxzeHe@0bGwI9XhlywU9NhMkWPFGj7EtB4se2YB8QdgCtcRzRrZytpaW8QNf/Poa@8W0Ykp6QcSFWoZgvgoDxQNPhO2ElpTkIYXyZCh4wFRrPGSSIAo8qQQPfSUDriJfChX6XDFPCu4rwbgX@tLbkrjYjNSWXteGVH4kufAjQcV2znyfEJuX/P8Yf@hjdJshTOoCpqgnJyarZwXwZXMEQ8if0EGGNqmmYOYmQziHETyn1H68v8Go4QysLopsDv0SaK5d8wk "Factor – Try It Online")
## Explanation
```
! "abba"
dup ! "abba" "abba"
head-clump ! "abba" { "a" "ab" "abb" "abba" }
1 head* ! "abba" { "a" "ab" "abb" }
[ over length cycle = ] ! "abba" { "a" "ab" "abb" } [ over length cycle = ]
with ! { "a" "ab" "abb" } [ "abba" [ over length cycle = ] swapd call ]
```
`∃` Alias for `any?` -- Does the quotation return `t` for any elements in the sequence? Inside the quotation now for the first element...
```
! "abba" "a"
over ! "abba" "a" "abba"
length ! "abba" "a" 4
cycle ! "abba" "aaaa"
= ! f
```
Second element
```
! "abba" "ab"
over ! "abba" "ab" "abba"
length ! "abba" "ab" 4
cycle ! "abba" "abab"
= ! f
```
Third
```
! "abba" "abb"
over ! "abba" "abb" "abba"
length ! "abba" "abb" 4
cycle ! "abba" "abba"
= ! t
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-d`](https://codegolf.meta.stackexchange.com/a/14339/), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
W¶îVîW
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWQ&code=V7buVu5X&input=IkB8I3wjfEAjfEB8fEAjQHx8QHwjfCI)
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 9 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
[;Lm≡]k∑‼
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjNCJXVGRjFCJXVGRjJDJXVGRjREJXUyMjYxJXVGRjNEJXVGRjRCJXUyMjExJXUyMDND,i=YWJjZGVh,v=8)
Can remove `‼` to save a byte if *any* truthy output (not necessarily consistent) is allowed.
] |
[Question]
[
*[Not a duplicate of the valid move challenge because that asks for specific pieces](https://codegolf.stackexchange.com/questions/148587/is-it-a-valid-chess-move)*.
## Backstory
The other night I was doing [a little trolling](https://chat.stackexchange.com/rooms/145373/conversation/plausible-chess) with ChatGPT and chess. I was trying to get it to call me out for making illegal moves, as a lot of the time, you can feed it whatever nonsense you want. While doing so, I wondered if it didn't recognise invalid moves because they were technically valid under some board arrangement. I then thought I'd make a code golf challenge.
## The Challenge
Given a start and end square on an 8x8 chess board, determine whether the move is possible on any legal chess board.
Alternatively, can any kind of piece make a move from the start square to the end square.
## Chess Pieces
For this challenge, you only need to know how the knight and queen move. King and pawn moves can be considered equivalent to a queen moving a single square. A rook move is a queen move restricted to vertical and horizontal movement. A bishop move is a queen move restricted to diagonal movement. Castling and En Passant (holy hell) aren't relevant either.
A valid move from the square highlighted in red is any square marked with a green circle:

This includes the vertical, horizontal and diagonal movement of the queen, as well as the L-shaped movement of the knight.
## Rules
* The positions will be given in algebraic chess notation (letter then number of the square).
* The start and end squares will never be the same square.
* The start and end squares will always be valid squares on an 8x8 chess board.
* Positions can be given in any reasonable and convenient format, including:
+ Strings (e.g. `["f4", "b8"]`)
+ A list of strings (e.g. `[["f", "4"], ["b", "8"]]`)
+ A list of numbers that represent the character codes of each string item (e.g. `[[102, 52], [98, 56]]`)
+ A string, number pairs (e.g. `[["f", 4], ["b", 8]]`)
+ A list of row/column pairs (e.g `[[5, 3], [1, 7]]` OR `[[6, 4], [2, 8]]`). Can be 0-indexed or 1-indexed. Your choice.
* Output in any reasonable and convenient format.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make sure your answer is as short as possible.
## Test Cases
```
start, end -> plausible?
a1, a4 -> True
b2, d3 -> True
b2, e3 -> False
b2, c3 -> True
a1, h8 -> True
c7, g3 -> True
c7, g2 -> False
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 24 bytes
```
@(a,b)imag((a-b)**4)<28i
```
[Try it online!](https://tio.run/##bZDbCoJAEIbv9ykGr3ZtFXYTFDvQVU/QXUSMuprSCXcLIXx2W43Iorn85uOfn7mkBu@qyxe@73crijxh5QkLStFLmOsGbC6jsjNKm32KWmlYgDXJ1kHBAQPwlrCpb8ohTiI5ZNMfoAawxqN@k3Ss9CGHaATSkEMx/QXyE7IjJL/UUNkeIg4J2Ok7aVPr67E09NOUVjxmbDYoTa88BBctFbFknj3svDZoNw0VbNJQydzyW5ftyEz@mfnwMd7LQUvUObPluic "Octave – Try It Online")
Takes two complex numbers as inputs.
## How?
Port of @xnor's python answer plus a trick or two by myself.
Trick 1:
@xnor's test polynomial a^3b-b^3a times 4i is the imaginary part of (a+ib)^4 = a^4 + 4i a^3b - 6a^2b^2 - 4i ab^3 + b^4
*Note:* a and b here as defined in @xnor's code; in my code they have a slightly different meaning.
Trick 2:
Octave implicitly takes absolute values before comparing complex numbers. We abuse that by comparing to 28i instead of 28 to save an explicit call to abs.
[Answer]
# [Python 2](https://docs.python.org/2/), 29 bytes
```
lambda a,b:abs((a-b)**4%1)<28
```
[Try it online!](https://tio.run/##VY/BboMwEETv/ooVUoWXmiqGSI1Q0mO/oDdiVQuYxBUBgmml5uepISkkPlj7xjPyTvvbH5s6GsrdfqjolBUEJLKEMss5hRkGwfpJ4jbaDGfYwc1xSXjTFfySrhSG4@STjwKumvzXpI/IWK9t/5mT1dblU37m5sW2lek5unSahM4u7sWR9Q9Vd1KsEKFsOjBgavA8j6QAWkP4Bh/dt2ZZJKCIH1BP@E6VvXK@PI/h42bG/FXAIX7EaA67z25rePvaQ8VY25m650srZPNmi5gwcGeyQsnN2HSlnuVXMI1SCeOuWZJqag0mjdTwBw "Python 2 – Try It Online")
Based on @xnor's answer. Takes two complex numbers as input.
# [Python 2](https://docs.python.org/2/), 42 bytes
```
lambda x,y,X,Y:abs((X-x+1j*(Y-y))**4%1)<28
```
[Try it online!](https://tio.run/##VY/NboMwEITvfoqVpQovNVUMkRqhpsc@QQ@JiFWZv8YVBYJpFfLy1BAKiS/rbzwj79Rde6xKv8@3h75Q33Gq4Mw7vuP7UMWGsZ13fhRfLtt7HaLrrh8Evvib/gRbmOyXkFVNyi7RSqI33BzlIIerJv414SAS0mam/UiUyYzNR@zE9JOpC90ytOko9Kyd34oDZ7@quJECiQh51YAGXQKlVAkOag3eK7w3PxmJfQ5pcIfZiG@qMFdOluchfNzMmDxz@Azu0Z/D9rNpDXooKUpC6kaXLVtaIZk3W8SQgD2jFXKmh6YryccphikmFnLsCzryZf8H "Python 2 – Try It Online")
The same with less opportunistic input format (4 integers).
## How?
Recall that in polar coordinates complex multiplication adds angles.
Therefore all queen-like moves (and only those) when taken to 4th power will end up on the real axis, i.e. have vanishing imaginary part.
Explicitly, if the difference of source and destination is \$x+yi\$ then the imaginary part of its fourth power is \$4 \times \left( x^3y - x y^3\right)\$ which happens to be @xnor's test polynomial (up to the prefactor 4). As observed by @xnor this has absolute value (4x) 6 at knight's moves and greater for all other (non-queen) moves.
Implementation detail: In Python 2 but not 3 the imaginary part can be isolated by `%1`.
[Answer]
# [Python 3](https://docs.python.org/3.8/), 47 bytes
```
lambda x,y,X,Y:-7<(a:=X-x)*(b:=Y-y)*(a*a-b*b)<7
```
[Try it online!](https://tio.run/##VY/NboMwEITvfooVF7zIrgpUIrJCj32CHhIRVC1/jSXKf6vAy1NTUlB8sGbG/uydZhyudeUfmm4uwstc0leSEdzEKE7irGRw5KTCk7yhwxMVnuVoBDkkEyfBYzC3EMKdmRSvu4xP0XOMclE22Shgzdz/zLURGRvyfvhIqc97w0e85XxSoX7qm1IPHNE8ESlpGNGurMh/qDTSjxGhqDvQoCuwLItcAfQC8hXeu@@cJZ6AzH@w@Z99o7JffbofL/D1sNk0EPDpP1pvg81n9/msS2VhzFjT6WrgexVk22R7qBiYtV4tuKNNNWH2pRPoyItx/gU "Python 3.8 (pre-release) – Try It Online")
Test cases [from mousetail](https://codegolf.stackexchange.com/a/260303/20260).
**[Python 2](https://docs.python.org/2/), 49 bytes**
```
lambda x,y,X,Y:-7<(X-x)**3*(Y-y)-(X-x)*(Y-y)**3<7
```
[Try it online!](https://tio.run/##VY9NboMwEIX3PsWIDR5kVzFUIkJJlz1BF4mIVTlgGksUCNAq5PLU/BQSb2a@53maeVXXXsrC77P9qc/V9zlVcGMdO7BjxMMdPfAbel7g0SPvkE849lbchf0V9jC77hEt65Te441EPnSucpHBpIl/TbiIhLS6aT8T1ejG@mN6pealqXLTUrTuOOJ2nD2KA@tflT9IgUSErKzBgCnAcRwlGKhX4G/wUf9ocvYZpMET6hHfVd5MnKzfg/myXTAJGXwFz@gvZrtsPsM5FQ5KQqraFC1dUyFZLlvFiIB94yhk1AxJN5KNVQxVzCzkmBdM7Mv@Dw "Python 2 – Try It Online")
No walrus here.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
αDËsP3‹~
```
-4 bytes porting [*AndrovT*'s Vyxal answer](https://codegolf.stackexchange.com/a/260309/52210).
Input as two pairs of codepoints.
[Try it online](https://tio.run/##yy9OTMpM/f//3EaXw93FAcaPGnbW/f8fbWhgpGNqFMsVbWmhY2oWCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9W6WL/qGGegob9o6Y1h9td7JU0FR61TVJQsk/4f26jy@Hu4gDjRw076/7r/I@OVko0VNJRSjRRitWJVkoyArJTjBHsVCR2MoQNVp9hAWYnmwPZ6cZIbCMwO80EyE4CqokFAA) or [verify every single pair of chessboard positions](https://tio.run/##yy9OTMpM/e9ocWjxkcbDi7z0DrcdnnBu66OmNYfbE/6f2@hyuLs4wPhRw866/7WHVh7uV3LMyVEoKSotyahUSM5ILS5Oyk8sSlEoyC/OLMnMz1MoSMwsKrZSUNLRObTNnuvQuniolrTEnOJUAlrs/wMA).
**Original 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:**
Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/260305/52210).
```
αW_snDO5QsËM
```
Input as two pairs of codepoints.
[Try it online](https://tio.run/##yy9OTMpM/f//3Mbw@OI8F3/TwOLD3b7//0cbGhjpmBrFckVbWuiYmsUCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9W6WL/qGGegob9o6Y1h9td7JU0FR61TVJQsk/4f25jeHxxnou/aWDx4W7f/zqaMf@jo5USDZV0lBJNlGJ1opWSjIDsFGMEOxWJnQxhg9VnWIDZyeZAdroxEtsIzE4zAbKTgGpiAQ) or [verify every single pair of chessboard positions](https://tio.run/##yy9OTMpM/e9ocWjxkcbDi7z0DrcdnnBu66OmNYfbE/6f2xgeX5zncri72N800Pd/7aGVh/uVHHNyFEqKSksyKhWSM1KLi5PyE4tSFAryizNLMvPzFAoSM4uKrRSUdHQObbPnOrQuHqolLTGnOJWAFvv/AA).
**Explanation:**
```
# first input ("f4"): [102,52]; second input ("b8"): [98,56]
α # Absolute difference of the values in the two (implicit) input-pairs
# [abs(98-102),abs(56-52)] → STACK: [4,4]
D # Duplicate the pair
# STACK: [4,4],[4,4]
Ë # Check if the values in the pair are the same
# STACK: [4,4],1
s # Swap so the pair is at the top of the stack again
# STACK: 1,[4,4]
P # Take the product of the pair
# STACK: 1,16
3‹ # Check whether this is smaller than 3 (thus 0, 1 or 2)
# STACK: 1,0
~ # Bitwise-OR to check either of the two is truthy
# STACK: 1
# (after which the top of the stack is output implicitly as result)
```
```
# first input ("f4"): [102,52]; second input ("b8"): [98,56]
α # Absolute difference of the values in the two (implicit) input-pairs
# [abs(98-102),abs(56-52)] → STACK: [4,4]
W # Get the minimum (without popping)
# STACK: [4,4],4
_ # Check if this minimum is 0 (1 if 0; 0 otherwise)
# STACK: [4,4],0
s # Swap so the earlier pair is at the top again
# STACK: 0,[4,4]
n # Take the square of both values
# STACK: 0,[16,16]
D # Duplicate this pair
# STACK: 0,[16,16],[16,16]
O # Sum the copy
# STACK: 0,[16,16],32
5Q # Check whether this sum is equal to 5 (1 if 5; 0 otherwise)
# STACK: 0,[16,16],0
s # Swap so the earlier squared pair is at the top again
# STACK: 0,0,[16,16]
Ë # Check whether both values in the pair are the same
# STACK: 0,0,1
M # Push the largest value on the stack, to check if any is truthy
# STACK: 0,0,1,1
# (after which the top of the stack is output implicitly as result)
```
[Answer]
# JavaScript (ES6), 42 bytes
Expects `(x0,y0,x1,y1)`, where all arguments are integers. They can be 0-indexed coordinates, 1-indexed coordinates or ASCII codes.
Returns a Boolean value.
```
(x,y,X,Y)=>!((x-=X)*x+(y-=Y)*y-5&&x/y^y/x)
```
[Try it online!](https://tio.run/##dc9Ra8IwEADg9/6KWx/k4i7p1A0dEmGM7RfsQSkZpLG1G8Vo4yT59V1KYTI27yE57svluE991s60H4cT39tt2VWyQ0@B1rRhcnWD6Llcs7G/xcDlho0DfxiNfBbeQ@ZZ544gwYFcQQ5OmFq3z/GTpxPeMeDwOCdYxNvlEwVqmeQJxHepnqQUz/sUFEGWwVv7VQ5STHvZzq5J@SOvunG/yPzTNAyqF3/FzHvZza7KNApcBqlEVLZ90aZGzDVBoVi/tLF7Z5tSNHaHfZWgQiGEO6JmBENWsBjdNw "JavaScript (Node.js) – Try It Online")
### Commented
```
( //
x, y, // (x, y) = coordinates of source square
X, Y // (X, Y) = coordinates of target square
) => //
!( //
(x -= X) * x + // we compute x = x - X and y = y - Y
(y -= Y) * y // if the squared Euclidean distance x² + y²
- 5 // is not equal to 5, this is not a knight move
&& //
x / y ^ y / x // we compute x / y and y / x
// XOR'ing both terms together gives 0 if:
// - either x = 0 or y = 0 (rook move), in which case one
// of the terms is ±infinity and the other one is 0
// (see note below)
// - x = ±y (bishop move), in which case both terms are
) // equal
```
### Note
According to the ECMAScript specification of [NumberBitwiseOp(*op*, *x*, *y*)](https://262.ecma-international.org/12.0/#sec-numberbitwiseop), the arguments of a bitwise operation are first converted with the abstract operation [ToInt32(*argument*)](https://262.ecma-international.org/12.0/#sec-toint32) whose first two steps are:
>
> 1. Let *number* be ? ToNumber(*argument*).
> 2. If *number* is \$\text{NaN}\$, \$+0\_\mathbb{F}\$, \$-0\_\mathbb{F}\$, \$+\infty\_\mathbb{F}\$, or \$-\infty\_\mathbb{F}\$, return \$+0\_\mathbb{F}\$.
>
>
>
That's why `±infinity ^ 0` is `0`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~7~~ 6 bytes
```
εꜝ2v∴≈
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJ+IiwiIiwizrXqnJ0yduKItOKJiCIsIiIsIlsxLCAxXSwgWzEsIDRdIC0+IDFcblsyLCAyXSwgWzQsIDNdIC0+IDFcblsyLCAyXSwgWzUsIDNdIC0+IDBcblsyLCAyXSwgWzMsIDNdIC0+IDFcblsxLCAxXSwgWzgsIDhdIC0+IDFcblszLCA3XSwgWzcsIDNdIC0+IDFcblszLCA3XSwgWzcsIDJdIC0+IDAiXQ==)
*-1 byte by @Johnathan Allan*
Takes input as two pairs of numbers.
```
εꜝ2v∴≈
ε # absolute difference
ꜝ # keep truthy
2v∴ # vectorized maximum with 2
≈ # are all equal?
```
[Answer]
# T-SQL, 63 bytes
input is a table
```
SELECT 1/~((a-c)*(b-d)/3*(a-c)*(b-d)*(abs(a-c)-abs(b-d)))FROM @
```
**[Try it online](https://dbfiddle.uk/UcRETwri)**
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ạḟ0»2E
```
A dyadic Link that accepts one cell reference on the left and the other on the right, each as a pair of integers\* and yields `1` if plausible or `0` if not.
\* The indexing of the inputs does not matter so long as it is unscaled and the two pairs use consistent indexing; they could also be the ordinals of the characters (since only files and ranks, individually, need to have equivalent indexing).
**[Try it online!](https://tio.run/##y0rNyan8///hroUPd8w3OLTbyPX////Rxjrmsf@jTXWMYgE "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hroUPd8w3OLTbyPX/w91bDm19uGOT/@Hl@o8ad@hkPWqYo2Brp/CoYa5m5P//iYYKiSZcSUYKKcYgMhVMJhtzAcUzLLiSzRXSjcGkEQA "Jelly – Try It Online").
### How?
```
ạḟ0»2E - Link: A=[StartRow, StartFile]; B=[EndRow, EndFile]
ạ - absolute difference (vectorises)
-> [abs(StartRow-EndRow), abs(StartFile-EndFile)]
ḟ0 - filter out zeros -- remove the zero from any rook move
»2 - max with two (vectorises) -- cast king/horsey moves to 2 step queen moves
E - all equal? -- are we left with a queen move, or < 2 elements (was a rook)?
```
[Answer]
# Excel, ~~77~~ 72 bytes
```
=LET(
a,INDIRECT(A1&":"&B1),
b,ROWS(a),
c,COLUMNS(a),
OR(b=1,c=1,b=c,b*c=6)
)
```
Expects strings (e.g. "f4", "b8") in cells `A1` and `B1`. Returns a Boolean.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
F²⊞υNUMυ↔⁻ιN⊞υ↔↨υ±¹‹Πυ³
```
[Try it online!](https://tio.run/##XYwxDsIwEAR7XnHlWQoFDh0VUCGRKF@4OIZYcuzI5@P7JpaAgnJ3ZtfMlEwkX8ojJkCtYBCeURq4hVVyL8toEyp12nW0XuOyUJgqPY8cvWSLnQvC6P79uvg@/dwLsa1Fb5@0xcNHSy5kvFtmHFKcxGQU1UC7sVI0aDhCW/Yv/wY "Charcoal – Try It Online") Link is to verbose version of code. Takes input as four integers and outputs a Charcoal boolean, i.e. `-` for plausible, nothing if not. Explanation: Inspired by @xnor's Python answer.
```
F²⊞υN
```
Input the first pair of coordinates.
```
UMυ↔⁻ιN
```
Take the absolute difference of them and the second pair of coordinates.
```
⊞υ↔↨υ±¹
```
Push the absolute difference of the two absolute differences.
```
‹Πυ³
```
Test whether the product is less than `3`.
22 bytes with some evaluate hackery to port @loopywalt's Octave answer:
```
‹↔UV⁺X↨E⁴NUV1j⁴.imag²⁵
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMntbhYwzGpOD@ntCRVI6CyJCM/z7UsMac0EcTNKS3WCMgvTy3ScEosTtXwTSzQMNFR8MwrKC3xK81NAoprauoooOlSMsxSAgmbALGSXmZuYjqQC2QbmWpqWv//b6RgpGCiYPxftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as four integers and outputs a Charcoal boolean, i.e. `-` for plausible, nothing if not. Explanation:
```
⁴ Literal integer `4`
E Map over implicit range
N Next input number
↨ Interpret as base
1j Literal string `1j`
UV Evaluate as Python
X Raised to power
⁴ Literal integer `4`
⁺ Concatenated with
.imag Literal string `.imag`
UV Evaluate as Python
↔ Absolute value
‹ Is less than
²⁵ Literal integer `25`
Implicitly print
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 67 bytes
```
(.)(.)(.)(.)
$1$*1-$3$*1,$2$*1-$4$*
(1+)-\1
^1..1$|^(1+),\1$|^,|,$
```
[Try it online!](https://tio.run/##K0otycxL/B@SEJ@TkJKgF5PCpaqREOPC9V9DTxOOuFQMVbQMdVWMgaSOihGYbaKixaVhqK2pG2PIxRVnqKdnqFITBxLQiQGxdGp0VP7/TzTUUUg0UdC1UwgpKk3lSjLSUUgxRuGmgrluiTnFEH4yQhqkOcMCzk0211FIN0blGsE1AwA "Retina 0.8.2 – Try It Online") Takes input as a string of four digits but test suite converts from test case format for convenience. Explanation:
```
(.)(.)(.)(.)
$1$*1-$3$*1,$2$*1-$4$*
```
Convert to unary, preparing to subtract the `x` and `y` coordinates from each other.
```
(1+)-\1
```
Take the absolute difference of both the `x` and `y` coordinates.
```
^1..1$|^(1+),\1$|^,|,$
```
Match either a knight move, a bishop move, or one of two possible rook moves.
[Answer]
# [Python](https://www.python.org), ~~78~~ 73 bytes
```
lambda i,j:((a:=abs(i[0]-j[0]))==(b:=abs(i[1]-j[1])))|(a<1)|(b<1)|(a<3>b)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVDLTsMwEBRXf8Uql9iSg3CCRGU1FSck7tzSCtl5UFchTxeJAF_CJZfyT_A1OHGaqD6sd8Y74939_qne9b4s-lMGIWxPR515q9_HXLzKRICiB46x4KGQLVbRzc47mEBIGGJ5JtlAMkOSTyzWzEQ5RrEONpJYw7-r-9rYT64dx2WT4G6w8obMFS6hYDl25phLCEI6bfVzLNq0NfoPXGPc8VBdt1WuNCbEWETcMxpaWy1N30Ru0sA0BFnZgAJVgOM4glEQt-Bt4Kk5pkj6FJLgAqYjfBB5a3G8PA_i_WqG8R2Fl-AS-rPYfDb152wLh3whVDWq0HgZhaC5s4XkCMyxpdm4bKrGiUBF_m5aZN_b-x8)
# [Python](https://www.python.org), 65 bytes
Alternate input format, credit to 97.100.97.109
```
lambda u,v,x,y:((a:=abs(u-x))==(b:=abs(v-y)))|(a<1)|(b<1)|(a<3>b)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVDLTsMwEBRXf8Uql-4iB5EEiSpqKsGBL-CWRshJE2op5J2oLfAlXHIp_wRfg1OHRPVhvDP2jHf99V0cml2e9acEPNic2iYxlz8PqXgLtwJa3vE9P7iIwvVEWGNr7ok8D0NNO_NARB8oVpbC8Ixi5axD0kG_V4-lih3Tji7m1RaP_m1A5lAtxII4aM3616wFEWNNXDcvkajjWvnfsUQ8up68qYtUNkikInzXVB5eai-PO5Gq0gmIIMkrkCAzMAxDWBzEHZhreK7amIU2h61zQeMzfRJprXk0Hw_m3XKi0T2HV-eS2pNZPTb2Z2wygz4ZKyqZNTiPQmzqbBZdBmrpqwleSzUaVzjMBNK3g_Er-17vfw)
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 9 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
-ADạsp2©|
```
Port of [AndrovT's Vyxal answer](https://codegolf.stackexchange.com/a/260309/114446).
#### Explanation
```
-ADạsp2©| # Implicit input
-A # Absolute difference
D # Duplicate
ạ # All are equal?
s # Swap
p # Product
2© # Less than or equal to 2
| # Logical or
# Implicit output
```
[Answer]
# [Scala](http://www.scala-lang.org/), ~~237~~ 221 bytes
Saved 16 bytes thanks to the comment.
Golfed version. [Try it online!](https://tio.run/##fZBtS8MwEMff91McZbBkpntUHB0RxCIU9FX1lfjimj6sUrvRxNHS9rPPpNWBMg0cd//87nJ3kQJzPO7Ct1goeMSsgOao6n0MAQ9UmRWp1Suf@4WyojiBhKAbsNANKG@MlkT2MZFkTqdqp/OcMY6HiK0dSRZ0itLL0kzRbmNKDqRyfVZrE9oi19flB8yh8njliI0Ja4/XTrSpvEnlXdTeRGt@1bY6g8/bth5cTznvcWfKSMVqyiVB2ivBIqNCrQxhRndHM8G7XpRgmUoXbssS65dh11fqwnORKeDQWKCPGUXFUt2hjKW@fcikIj0BIDYubAY2XtqUwWwGT@VHfGLh0rBo9TeLv9k95vI3FGcLh4bb9Tkmrg1LV/@wpU3hZ0Nq9e604jTZlTGKLTQgtAaCDEIK/Obrqb3@JZUXRNojhFEIoyYZUjqb9imdZayzjp8)
```
type S=String
type I=Int
def f(a:S,b:S)={def s(s:S)={(s(0).toInt-'a'.toInt,8-s(1).asDigit)};def v(x:I,y:I,c:I,d:I)={val xD=x-c;val yD=y-d;xD*xD+yD*yD==5||xD==0||yD==0||xD*xD==yD*yD};val(x,y)=s(a);val(c,d)=s(b);v(x,y,c,d)}
```
Ungolfed version. [Try it online!](https://tio.run/##fVJNT8JAFLzzKyYNCbtYgRaNhAQThZiYyMmPi/HwWhZYU1vtLqQN8ttx@xmr6KHd92ZmZ7r7qnwK6HCIvFfha8xJhti1gIVY4s00jOKVGuMqjil9vtexDFcvfIzHUGpMciWwpQBaKD0lJZRB76TSLGcAZpFj2bDozOI2@n08xBtRc56bcYvh35youBsK1E/SP7qxCFyPjnH@Rcathv9wrsXRDOStfKmP2FtGsSB/jR1804ORDY9jcllaZffBEsdG6hgU6mNDsZhGUbyQIRkXRryhdI3SPa70KuW7uXkdhExZbULbQ3sn1RMFcjGPtqIMs1Fa7a1i276VPeU0f5ubuRYTNQNlt6G2YV68HitTbMB7OjIgTtGhTlHbGJlWMYf3SM3kSmr@Pab5WWPkO9KqSNwKKQqTfB1FgaCw8TclM7lcGiRxTFTi1nha4mmGpwVeaLvlelJqupV2gnN8flaOEwyyLm10TQeDNizyw@1bh8MX)
```
object Main {
def main(args: Array[String]): Unit = {
val testCases = List(
("a1", "a4"), // True
("b2", "d3"), // True
("b2", "e3"), // False
("b2", "c3"), // True
("a1", "h8"), // True
("c7", "g3"), // True
("c7", "g2") // False
)
testCases.foreach { case (a, b) =>
val (x1, y1) = squareCoordinates(a)
val (x2, y2) = squareCoordinates(b)
println(s"$a $b ${isValidMove(x1, y1, x2, y2)}")
}
}
def squareCoordinates(s: String): (Int, Int) = {
(s(0).toInt - 'a'.toInt, 8 - s(1).asDigit)
}
def isValidMove(x1: Int, y1: Int, x2: Int, y2: Int): Boolean = {
val xDiff = x1 - x2
val yDiff = y1 - y2
xDiff * xDiff + yDiff * yDiff == 5 || xDiff == 0 || yDiff == 0 || xDiff * xDiff == yDiff * yDiff
}
}
```
[Answer]
# [J](http://jsoftware.com/), 17 15 14 bytes
```
[:(=+.3>*)/|@-
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o600bLX1jO20NPVrHHT/a3KlJmfkKxgCYZqCsYIRMtdQwUQBwjcCwjQgzxiFbwznQ9RbACGEb6xgDuSbg@SRNZjCNcAUGCn8BwA "J – Try It Online")
*Port of Neil's Charcoal / xnor's Python answers*
*Also -1 thanks to an idea from AndrovT's answer*
# [J](http://jsoftware.com/), original, 21 bytes
```
1 e.(*:^:4@*,5=|*|)@-
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRVS9TS0rOKsTBy0dExta7RqNB10/2typSZn5CsYZhkqpCkYZxkhcw2zTBQgfKMsIyDfJMsYhW8M50PUW2RZQPnGWeZAvjlIHlmDKVwDTIGRwn8A "J – Try It Online")
*5 idea from Arnauld's answer*
For the rest, we take the difference between in the inputs as complex numbers, normalize the vector, then square it 4 times. If the original vector was on one of the compass directions (rook) or one of the diagonals (queen/bishop), it will eventually settle at 1.
We then check if the result is 1 or 5.
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 7 bytes
```
-AZ‼2M≡
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6Fqt1HaMeNewx8n3UuXBJcVJyMVR8wc3WaEtzHRPLWAUQbWoUyxVtaaFjagDkGxoY6JgaoggYogpYWkL5UBMMDUx0TM1AAkAJU7CAMVQFsoABUMDQwAhkmwLYLLNYiGsA)
A port of [@Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/260356/9288).
```
-AZ‼2M≡
-A Absolute difference
Z‼ Remove zeros
2M Max with 2
≡ All equal?
```
] |
[Question]
[
### Background
Being in a philosophical mood, I remembered one old idea. I think it is suitable for CG.
Duplicates are not found, but it's of course just a kind of totalistic cellular automaton or [erosion](https://en.wikipedia.org/wiki/Erosion_(morphology)).
Given an infinite board filled with empty (let `0`) cells. We create *a figure* - a finite set of non-empty (let `1`) cells. Figure may be with holes, disconnected, random etc. But the bounding box of the figure is finite.
We call *the border* of a figure a subset of its cells that have at least one empty neighbor
(in this model we use *4 neighbors*: top, left, right, bottom).
Example of border (blue):
[](https://i.stack.imgur.com/NikPm.jpg)
One step of fading algorithm:
1. Define a figure boundary
2. Eliminate it, replacing by empty cells
Example of fading step:
[](https://i.stack.imgur.com/ZUEpG.jpg)
### Task:
Determine how many described steps it takes to completely disappear a given figure.
### About size of board
Since the figure can only fade, we just have to deal with the board, just one strip padding figure' bounding box.
**UPD - About minimal input**
So strictly speaking the minimal board is `[[0, 0], [0, 0]]` - empty board with no figure. And as mentioned in comments, you may not handling an empty array; sorry that made that point clear just now.
### Input:
Figure in any appropriate form:
* binary array (all board)
* array of strings (too)
* sparse array (list of positions of non-empty cells and dimensions)
### Output:
Non-negative number of steps, totally eliminating a figure.
### Notes:
Of course, the literal passage of the algorithm to fixed point
and counting steps is an acceptable solution.
But I've got at least two addition ideas:
* Some built-ins of Mathematica ;)
But I can't configure it properly (
* Perhaps one can analyze the maximum distances to the border,
and get the answer only by a given array
### Test cases:
```
[[0, 0], [0, 0]] → 0
[[0, 0 ,0], [0, 1, 0], [0, 0, 0]] → 1
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] → 3
Example of string input:
00000000
01111110
01111110
01111110 → 3
01111110
01111110
01111110
00000000
Example of sparse array input (dimensions and non-empty cells):
[16, 16],
[[2, 2], [2, 3], [2, 4], [2, 13], [2, 14], [2, 15], [3, 2], [3, 3], [3, 4], [3, 5], [3, 8], [3, 9], [3, 10], [3, 12], [3, 13], [3, 14], [3, 15], [4, 2], [4, 3], [4, 4], [4, 5], [4, 8], [4, 9], [4, 10], [4, 12], [4, 13], [4, 14], [4, 15], [5, 3], [5, 4], [5, 5], [5, 8], [5, 9], [5, 10], [5, 12], [5, 13], [5, 14], [6, 8], [6, 9], [6, 10], [7, 7], [7, 8], [7, 9], [7, 10], [8, 7], [8, 8], [8, 9], [8, 10], [9, 7], [9, 8], [9, 9], [9, 10], [11, 2], [11, 3], [11, 4], [12, 2], [12, 3], [12, 4], [12, 5], [12, 6], [12, 7], [12, 8], [12, 9], [12, 10], [12, 11], [12, 12], [12, 13], [12, 14], [13, 2], [13, 3], [13, 4], [13, 5], [13, 6], [13, 7], [13, 8], [13, 9], [13, 10], [13, 11], [13, 12], [13, 13], [13, 14], [13, 15], [14, 3], [14, 4], [14, 5], [14, 6], [14, 7], [14, 8], [14, 9], [14, 10], [14, 11], [14, 12], [14, 13], [14, 14], [14, 15], [15, 13], [15, 14], [15, 15]] → 2
```
[Answer]
# [Python 2 or 3](https://docs.python.org/), 69 bytes
```
f=lambda c:c>[]and-~f([s for s in c if sum(1==abs(e-s)for e in c)>3])
```
A recursive function that accepts a list of positions on the Cartesian grid represented as complex numbers and returns the fading count. Returns `False` for zero as it [quacks like zero in Python](https://codegolf.meta.stackexchange.com/a/9067/53748).
**[Try it online!](https://tio.run/##1VVLjptAEN1zit4NJExEmQbDSMxFEBphDAmWjRFgaZJFdtnlCMnl5iIO3V2vZ2w5jiNlE9RSPerzqmleq/rP06d9Fx6PTbYtd6t1KaqH6jEvym59/7Vx81E0@0GMou1EJdpGjIedS1lWrka3vh89Fax10HsMC@@4rhtR7ffDenR35TS0z96DI@ZnqKfD0Im8fU@bdxvN2aqyoew@1u627pDu6djmUiwPijk874Ff2yLfFIXjTPU4jU@lyESue@WFb2we@CIQflD4QkGa3xiqVZyk3bjmel0EQrMu5r5GudFpzVnluf9yo@vrHzb6iy@6@ej@cN5XNk//T/j2D79Ieu4NrmzgN33nK6GcfDGeVupe5AtfLJT2ZxuylWwJDrKeSIGQS0IuCblktognbFO2FACgklBKqDXkksklk0sml0wumVwyuQS5BLkEuQS5BHnEpBGTRkwaMWnEpBFII5BGII1AGnNNzDUxapa@WLJN2KZsTULCCQknJJyQICHlhJQTUk5IkUDEp6RACKC3RfihhD9KizehCCAGWAIkACkAN1OILLLkZNnNgRB0QRAGQRkEaSgQAywBEoAUgDuHtrOVDlntUPi2s/nBBNkQdEMQjgIxwBIgAUgBuLW0ra2wyCqLrLTIaousRMhqRKPIjiJ14XgGTmacTWqc8ZhC1oey7@tu7Z6MRN9MPnNxC89x6ue@rqZyaved5jX3P9RLq8NxdIO5wBcmuV4rii9t7@o@cBsOHsdlNR3K7UzY6CRPO/uh7SbXhHxx9/Lz@8uPb3e5cWQZ2Ocp/ws "Python 3 – Try It Online")**
[Answer]
# [MATLAB](https://www.mathworks.com/products/matlab.html) with Image Processing Toolbox, ~~45~~ 29 bytes
```
@(x)max(max(bwdist(~x,'ci')))
```
Anonymous function that inputs a matrix and outputs a number. [**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzN7FCA4STylMyi0s06ip01JMz1TU1Nf@naUQb6CgYWCuAyFhNLigfJmQIl0OXJgbBjIAgrGoQsqiK0bSgi2NTjAtRYjIxbiYWQYNPAS8EmqhgCIboUlBRhAJDZGGEGFEKDHAqMIApwLAZ1ZHo0jRVQFJAYSjABgkqQAsoPAqwQYIKoDBW8z8A) (with Octave).
### Explanation
The code
1. computes the Manhattan (city-block) distance between each value and the nearest zero (`bwdist(..., 'ci')` applied to `x` negated);
2. takes the maximum (`max`, used twice because the image has two dimensions).
[Answer]
# MATLAB with Image Processing toolbox, ~~59~~ 66 bytes
*+7 bytes from @Luis Mendo*
```
I={@(~)0,@(a)1+G(imerode(a,strel('dis',1)))}
G=@(a)I{2-~nnz(a)}(a)
```
Writing recursive code in MATLAB is surprisingly tricky; I'm using a workaround I found at [this link](https://stackoverflow.com/questions/32237198/recursive-anonymous-function-matlab) to simulate an if-else statement inside of an anonymous function.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 15 bytes
```
k□ẊṠ?Fv¨VεƛṠg;G
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJr4pah4bqK4bmgP0Z2wqhWzrXGm+G5oGc7RyIsIiIsIltbMSwxXSxbMCwxXSxbMSwwXSxbMiwxXSxbMSwyXV0iXQ==)
Takes input as a list of coordinates.
Computes the taxicab distance of each point to the border and take the maximum.
```
k□ẊṠ?Fv¨VεƛṠg;G
k□ # push [[0,1],[1,0],[0,-1],[-1,0]]
Ẋ # cartesian product with input
Ṡ # vectorizing sum, this results in the shape inflated by one
?F # remove all those that are in input, this results in the border of the shape
v¨Vε # vectorized and right vectorized absolute difference
ƛ ; # map:
Ṡ # vectorizing sum
g # minimum
G # maximum
```
### 15 byte alternative
```
ÞT?0ÞIv¨VεƛṠg;G
```
Takes input as a list of lists.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
`t4&3ZItb-z}x@q
```
Inputs a binary matrix and outputs a number. [**Try it online!**](https://tio.run/##y00syfn/P6HERM04yrMkSbeqtsKh8P//aAMdBWKRNYg0hCGsahCyqIrRtKCLY1OMC1FiMjFuJhbFAgA)! Or [**verify all test cases**](https://tio.run/##y00syfmf8D@hxETNOMqzJEm3qrbCofC/S8j/aAMdBQNrBRAZywXmwPiGcAkUOWIQTD8EYVWDkEVVjKYFXRybYlyIEpOJcTOxCBR2Cngh0DgFQzBEl4KKIhQYIgsjxIhSYIBTgQFMAYbNqI5El6apApICCkMBNkhQAVpA4VGADRJUAIWxAA).
### Explanation
The program erodes the image until it doesn't change.
```
` % Do...while
t % Takes input (implicitly) the first time. Duplicate. Call this (*)
4&3ZI % Erode using 4-neighbourhood
t % Duplicate
b % Bubble up: moves (*) to the top of the stack
- % Subtract, element-wise
z % Number of non-zeros. Gives 0 if the last erosion didn't modify
% the image. Call this (**)
} % Finally (this code is run on loop exit)
x % Delete the image
@ % Push number of current iteration (which is the last one)
q % Subtract 1
% End (implicit). A new iteration will be run if the top of stack (**)
% is not 0
% Display stack (implicit)
```
[Answer]
# [Julia 0.6](http://julialang.org/), ~~62~~ 48 bytes
```
!m=any(m)&&1+!(conv2(1m,[0 1 0;1 1 1;0 1 0]).>4)
```
[Try it online!](https://tio.run/##yyrNyUw0@/9fMdc2Ma9SI1dTTc1QW1EjOT@vzEjDMFcn2kDBUMHA2hBIGlqD2bGaenYmmv8LijLzSnLyNBSd8vNzomM1uVAFDBSAEKLBGszGUAExEigPJoEQWQUXwhBc0FqBC6QXDFGloGLWCHmEGiQ@sgHYIEkG4HYBHhir@R8A "Julia 0.6 – Try It Online")
Performs erosion as 2D convolution with given 3x3 kernel.
14 bytes saved by MarcMush by switching to boolean inputs.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~44~~ ~~42~~ 41 bytes
-1 not handling empty input
```
Max@#/. 1:>1+#0@Erosion[#,CrossMatrix@1]&
```
[Try it online!](https://tio.run/##zZJPS/NAGMTv/RSBghfzaqfZTXYFJSIeFcFj6WEpigXbStqDEuJXr42Z2Tf4jx48CAvPL7vzzJNsZhE2D3eLsJnPwvb@dHsVnsvh8VGCkzMcDkflZbVaz1fLyTC92NH6Kmyq@XOJ6cH2ppovN@X95HL2sDouh9OD19tZWL7Wg7oepcmoSQdJBzvqtnq76Cs@ivZZTZpEp259qft/2puMr7o@7n8e8PP6hQF7fsHeV/TDnX7zsvh7R9982PWqWoTH8vYpVOu786oKL5O6HqfJeHetbc1YDSu0gbhjW8jYkrElY8uu6tyxelaMBOqEWqHeztzQ3NDc0NzQ3NDc0NzI3MjcyNzI3Mjc0tTS1NLU0tTS1MrUytTK1Mo0Z0/Onlw9RZoUrI7Vs3YCR4GjwFHgJPAUeAo8BV4CgLfUQiZ4fy3oh0J/FOPekRXkgkLgBF7AYS0hUjRHdO8uBMoFFAwoGVA0WsgFhcAJvICTszg5RgcxO8j6k7sfDMUGyg0UnBZyQSFwAi/gaBNHx2AhJgsxWojZQowIYkbeyTbNvzO0T21E8mY6aLZv "Wolfram Language (Mathematica) – Try It Online")
Input a binary array of `0`,`1`s.
I don't think there's a shorter way to generate `{{0,1,0},{1,1,1},{0,1,0}}`.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 89 bytes
```
s`1.*
$&_
}`(?<=(.)*)1(?=(.)*)(?=.*¶(?<-1>.)*(?(1)^)0|0|(?<=0(?(2)$)(?<-2>.)*¶.+|01))
0
_
```
[Try it online!](https://tio.run/##bYu5DYAwDEV7z4GQHURkUwPZhEBBQUMBlGEtBmCxkHAUkfjNP569jNs0D96vvWgFWW5h79HUDWpSJGieEFyr8wiglDYMaFCoI3bs4jGHXlFGkVeRn4cuHAsRMFjvORWwiLw5prvfy@Nv//TPk/9UFw "Retina 0.8.2 – Try It Online") Takes input as an array of binary strings. Explanation: Loosely based on my original answer to [Flood fill by distance](https://codegolf.stackexchange.com/q/249085/).
```
s`1.*
$&_
```
If there are any `1`s remaining, then increase the iteration count.
```
(?<=(.)*)1(?=(.)*)
```
For each matching `1`, keeping track of its position, ...
```
(?=.*¶(?<-1>.)*(?(1)^)0|0|(?<=0(?(2)$)(?<-2>.)*¶.+|01))
```
...that is either above, to the left, below, or to the right of a `0`, using its captured position and .NET balancing groups in order to locate the relevant digit, ...
```
0
```
... erode one step.
```
}`
```
Repeat until there is nothing left to do.
```
_
```
Convert the final iteration count to decimal.
[Answer]
# JavaScript (ES11), 88 bytes
Expects a binary matrix.
```
f=m=>m>(m=m.map((r,y)=>r.map((v,x)=>(g=d=>d+2?m[y+d--%2]?.[x+d%2]&g(d):v)(2))))?1+f(m):0
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWNyPSbHNt7XLtNHJtc_VyEws0NIp0KjVt7YognDKdCiBHI902xdYuRdvIPje6UjtFV1fVKNZeL7pCOwXIUEvXSNG0KtPUMNIEAntD7TSNXE0rA4j5t9g8k_PzivNzUvVy8tM10jSiYzU1udCEog10FAwUdAxidRRATEMgD8oEoVhsOoBqDBV0DEHKDMHKYEwQwqaDSwFuIDEIaBpUhyEMYVWIkI3VQdeApg1dHIsV-BFVrCDWF0QHFBdJgY3LC_i8N6BypHiZ6ECDIAWIJRTpwhOvKFI4dGFqRJGihi5iHUlKaBCpC81eYlyI6cdBoou80CAj5PHEMoosVXUR8JoCOMtBahRYzQUA)
### Commented
```
f = // f is a recursive function taking:
m => // m[] = input binary matrix
m > ( // test whether m[] is lexicographically greater
m = // than its updated version
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[]:
( g = // g is a helper recursive function taking
d => // a direction d in [-1 .. 2]
d + 2 ? // if d is not equal to -2:
m[y + d-- % 2] // apply dy to y (decrement d afterwards)
?.[x + d % 2] // apply dx to x
& g(d) // and do a recursive call
: // else:
v // stop and return v
)(2) // initial call to g with d = 2
) // end of inner map()
) // end of outer map()
) ? // if m[] was updated:
1 + // increment the final result
f(m) // and do a recursive call
: // else:
0 // stop
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ạỊS=5ðƇ`ƬL’
```
A monadic Link that accepts a list of positions, as complex numbers, of non-empty cells and yields the fading count.
**[Try it online!](https://tio.run/##y0rNyan8///hroUPd3cF25oe3nCsPeHYGp9HDTP/H530cOeqw20Pd3cfbv//PzraQEeBWBSro8ClANJgCENY1SFkY3XQ1KPpQhfHtAA/ooIFRPqA6CCKBQA "Jelly – Try It Online")**
### How?
```
ạỊS=5ðƇ`ƬL’ - Link: list of coordinates, C
Ƭ - start with X=C and collect up while distinct applying:
` - using X as both arguments of:
Ƈ - filter keep those c in X for which:
ð - the dyadic chain - f(c, X):
ạ - (c) absolute difference (X) (vectorises)
Ị - insignificant? -- less than or equal to 1?
S - sum -- number of neighbours + self
=5 - equals five?
L - length
’ - decrement -- as we've counted the empty list that then didn't change
```
[Answer]
# [J](http://jsoftware.com/), 26 bytes
```
_1+[:#(#~4=1#.1=|@-/~)^:a:
```
[Try it online!](https://tio.run/##lU9Ni8JADL3PrwgdWSfWZibiKVopCgsL4mGvwyiLVLQX/4D0r9fRjqDiZR@EfLyXF9J0GQ0PUAoMYQwOJEZBsPpdf3c7zr1oo9tpyZq4vFSFbXErf9Kh2iwJvCzIepmTjXyIdMb2ywy0/FA1xoLeRMFEWVThJ5nJbVtTwNY1vD1RNe2nPl3PbU0eXzgvBoOW2I@sUvX@eIYDmEFDtkrWkFHmZrSbQLi95pSLUI45VfiPtSfcHDjVfDdj7id9Tv0Dn/mX/Td/VN0V "J – Try It Online")
* Takes input as complex numbers
* Create a distance table between each element and all the others
* For each row, count how many values equal exactly 1 (only true for compass adjacency)
* Remove any whose count is not 4 (ie, remove any non-interior elements)
* Continue this process until a fixed point, keeping a list of intermediate results
* Return the length of this list minus 1
## [J](http://jsoftware.com/), alternate, 34 bytes
```
[:>./1<./"1@:#.]|@-"1/&($#:I.@,)-.
```
[Try it online!](https://tio.run/##fY/LCsIwEEX3@YohFU1sO8lIV9FKURAEceE2RBfSot34A9Jfr@lDsKV4YZjXuQNT1hwXBaQGFhCBBuMjRthfTofami0q2qDilJkA3TuLOam5mAXmiFkkY6wlO@8QWtAaT9IkNoKc8Jin5BQmQlXl6GSlS7o@MUu6qQ2qJPW2UOVo5WBnjZAuML5fKsby@@MFBXDkeo23FbjmKc20F9NEfSX/gj9qPNTX1NqJukmX@/6r6f3AP7ovWf0B "J – Try It Online")
Input is a binary matrix.
We do a single calculation on the input, with no transforms, instead of iterating to simulate the fade:
1. Positions of all the ones
2. Positions of all the zeros
3. Manhattan distance between every element of each of those sets
4. Return the largest
[Answer]
# Python3, 177 bytes:
```
E=enumerate
def f(b):
b=[(x,y)for x,r in E(b)for y,v in E(r)if v]
c=0
while b:b=[(x,y)for x,y in b if all((x+X,y+Y)in b for X,Y in[(1,0),(0,1),(0,-1),(-1,0)])];c+=1
return c
```
[Try it online!](https://tio.run/##rVPLbtswEDyXX7HwJWTNFFqJlCUXPuYfEqhEYbtyI8BRDNlJra93SWmXiZ2icIEShHZIzs7yMdr1h8fnNit23el0t6jbl6e6Wx5q8aPewEau1FzAalHJo@7V5rmDo@6gaeHOr4Rhr1/HYaeaDbw6AetFIuDXY7OtYTU/z@wDdQWeuNxupTxO73U/fVDDZGDc6wfPqCTqRGmZaBy@tyHchjmn3Nf1dIECuvrw0rWwPu26pj3IjaycUiIOqkRDAjpxGgJEPyIYuvvIvbJ7EcGKY/8j723V6Qv@Rdbl/McCf@//ocCVJ7j6is4v9/PTcif9QDfKhSduggUmk0lCTSQ4tH8F1LzSl/1u2xzkzbf2Rp3XDicAjeHlx3MyDH3Yp9insABvgcF@38PeumX7s5aYj9u9mBKjj2EwclWlGtIg6WNG0VBEnsA4YwPIKCWjlIxSfOT1gmJJERMGnImcipw7ihsSNyRuSNyQuCFxQ@KGxQ2LGxY3LG5Y3JKoJVFLopZELYlaFrUsalnUsmhOOTnl5Jwz0zCjWFAsKY6EgggFEQoiFEwoiVASoSRCyQREuqUAMgbDtpAfFPlFMX23ZBnkDGYMCgYlAyoWEEYUxTGqjxeC7AtkYyA7A9kaAeQMZgwKBiUDqpzFytE6GL2D2fvK4wMj2wbZN8jGCSBnMGNQMCgZUGkTS0djYXQWRmth9BZGi2D0yICsc3PxaZ9WR1f1zv@rGP/vfarU6Tc)
[Answer]
# Excel (ms365), 122 bytes
Assuming:
* A range of cells as input;
* Cells contain either a 0 or a 1.
With Excel 365 one could create a named function which can call itself recursively. So let's create a function called 'z' which refers to:
```
=LAMBDA(x,y,IF(OR(x),z(MAKEARRAY(ROWS(x),COLUMNS(x),LAMBDA(r,c,AND(TOROW(INDEX(x,r-{1,0,0,-1},c-{0,1,-1,0}),3)))),y+1),y))
```
Now one could call this function through:
```
=z(<Range>,0)
```
Not sure if I was supposed to add the bytes to actually call the function.
[Answer]
# [Python](http://golly.sourceforge.net/Help/python.html) script in [Golly](http://golly.sourceforge.net/), 83 bytes
```
from golly import*
setrule("4/V")
i=0
while not empty():
run(1)
i+=1
show(str(i))
```
Takes input by drawing the figure in Golly.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
W⊙θ⁼⊕⊗×ⅈ⊕ⅈLΦ講Σ↔Eμ⁻ξ§κπⅈM→Iⅈ
```
[Try it online!](https://tio.run/##TZLBbtswEETv/QoeGYAFuhYpic3JaNogQBwUbQ8FDB8Uh4iFyFIiUWny9aoVzRDWZZ/J3beGNPtD1e@7qpmmf4e6CUqv23f9YtT3l7FqBn3T7vtwDG0MD/qqG@@bU/1TH8Og/@oLo86vTwfzY9RtaB/jQf@omxj62XXXRX3dh2r@@Xs86vX90DVjDHpTPeujUZu6HQf9ZtQ63rQP4U0/GfUMGaynR22616C//qofD/Hi8tPPvm6j/lYNcdl8OU3b7XZl1Gpn1FwzVIsqPJB04mbIMJJhJMPIqfK@RPWo8oXASeGocHaRW8gt5BZyC7mF3EJuKbeUW8ot5ZZyB6mD1EHqIHWQOkodpY5SR2mOmRwzOWcKowrUEtWjLg0lGko0lGgo2eDR4NHg0eDZIIK3NENG@Phbwg8q/KKyOrtyhJxQEEqCJ2DZTJIoySXZlxcizIUwGMJkCKMxQ04oCCXBE7A5S5tTdCRlR7LzzcsHFsZGmBthcGbICQWhJHgCVtu0OgVLUrIkRUtStiRFRFJGPsjtdrvp82vzHw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of points. Explanation:
```
W⊙θ⁼⊕⊗×ⅈ⊕ⅈLΦ講Σ↔Eμ⁻ξ§κπⅈ
```
While there exists a point in the set with enough near (by taxicab distance) neighbours to survive another iteration, ...
```
M→
```
... increment the iteration count.
```
Iⅈ
```
Output the final iteration count.
30 bytes taking input as a list of newline-terminated strings:
```
WS⊞υιI⌈Eυ⌈Eι⌊Eυ⌊E⌕Aν0⁺↔⁻πμ↔⁻ξκ
```
[Try it online!](https://tio.run/##bYzBCoMwEETvfsXiaQMp6NmTFAo9FAL9gtRKXbpGMUnr36fRWlDpXGbfzO5WjR6qTnMI74a4Bjyb3rurG8g8UAhQ3jboJZAoEhVDh0dtHV70SK1vo/dTu0aKSGbTrvBE5l4yo5GQZqmQoNhbLG@2Y@9qjKsRewmtiN0uHiU8xVpFCNlWSZbn@TJP08xz8vWFf/rfb@53/8PhxR8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
WS⊞υι
```
Input the strings.
```
I⌈Eυ⌈Eι⌊Eυ⌊E⌕Aν0⁺↔⁻πμ↔⁻ξκ
```
Calculate the taxicab distance from each point to the nearest `0`, and output the maximum of those.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Δ2Fø0δ.ø}2Fø€ü3}εεÅsyøÅs«ß]N
```
Input as a bit-matrix.
[Try it online](https://tio.run/##yy9OTMpM/f//3BQjt8M7DM5t0Tu8oxbEfNS05vAe49pzW89tPdxaXHl4B5A8tPrw/Fi///@jow10FIhFsToKCiD1hjCEVRlCFqgeRTmaJnRxDOPxI4qNJ871RAdOLAA) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GpRRQlFpSUqlbUJSZV5KaopCZV1BaYqWgpON1aLcOl5JjcklpYg5c1B4o5F9aAuX8PzfFyO3wDoNzW/QO76gFMR81rTm8x7j23NZzWw@3Flce3gEkD60@PD/W77/OoW32XCAbucozMnNSFYpSE0G2caXkcyko6OcXlOhDHAal0Nxqo6ACVpuX@j862kDHIFYHTMZygXlQviFMHFkGF4TqAEFUGagYkjxCDRIfTR4dkqIft/343E/Qh3jswO5LJHEc/sCtwgCnCgMsfsFwE5oKQ7qoIC3EMFVgjXeCKtBDDJ8KbJDI9AFOIQA).
**Explanation:**
```
Δ # Loop until the result no longer changes, using the (implicit) input-matrix:
2Fø0δ.ø} # Add a border of 0s around the matrix:
2F } # Loop 2 times:
ø # Zip/transpose; swapping rows/columns
δ # Map over each inner row-list:
0 .ø # Surround it with both a leading and trailing 0
2Fø€ü3} # Convert the matrix into overlapping 3x3 blocks:
2F } # Loop 2 times again:
ø # Zip/transpose; swapping rows/columns
€ # Map over each inner list:
ü3 # Split it into triplets
εεÅsyøÅs«ß # Get the minimum of each cross of each 3x3 block:
εε # Nested map over the 3x3 blocks:
Ås # Get the middle row-list of the current block
y # Push the 3x3 block again
ø # Zip/transpose; swapping rows/columns
Ås # Push its middle column-list of this transposed block
« # Merge the middle row and column together to a single list
ß # Pop and push its minimum
] # Close the nested map and changes-loop
N # Push the last 0-based index of the changes-loop
# (which is output implicitly as result)
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-x`, 29 bytes
```
YaWy&UiyFI:5={2>$+(aAD_)MSy}i
```
Takes input from the command-line as a string representing a Pip list of two-element lists, each of which represents the coordinates of a non-empty cell. [Attempt This Online!](https://ato.pxeger.com/run?1=PZJNSsRAFITBowwiigxY6Z-8tlEQRHDhSkQkBJmNkN0sFAziSdwIongJL-Jp7Kl6zqY-0u_xNUnl7WM9rb-GxfJ5Mb5_Pj0-LO3nbnU7791M88XlcTp56U53D_dXZ-f3B1fX8-ukHV_93fkeFsPQ1W6sLQMzMqEH-FNqCFwLXAtcC1XnxixMHAnahZahbWoiNZGaSE2sOjdmYVITpYnSRGmiNImCREGqOjFmYVKQJEgSJAky9zL3svb62jONWZgcGAfGgXFgGhQOCgeFg6IBwPdrCMLmSugTQ98Y3f9hErLQCyYUQdJGOF0EN_GVoG6gcqB2oHoastALJhRB_uB-Lw7eHMLWz48O1Qb1BhXXkIVeMKEIuiD6BV4pvFN4qfBW4VXBu9owjeP25_4D)
### Explanation
Port of [Jonathan Allen's Jelly answer](https://codegolf.stackexchange.com/a/260374/16766).
```
YaWy&UiyFI:5={2>$+(aAD_)MSy}i
Ya ; Yank the input into global variable y
Wy ; Loop while y is not empty
&Ui ; (and increment i on each loop):
yFI: ; Filter y by this function and assign back to y:
{ } ; (Inside the function, the function argument is a)
MSy ; Map this function to y and sum the results:
_ ; Each element of y (2-item list)
aAD ; Absolute difference (itemwise) with a
$+( ) ; Add the two elements of the result
2> ; 1 if less than 2, 0 otherwise
; This gives the number of cells in cell a's 5-cell
; neighborhood (including the cell itself) that are
; nonempty
5= ; Return 1 if that fn's result is 5, 0 otherwise
; This filters and keeps only the nonempty cells
; that are surrounded by all nonempty cells
i ; After the loop, print the final value of i
```
] |
[Question]
[
Given a non-empty string (or an integer, or a list/array if you prefer) composed exclusively of digits in the range [1-9], your task is to write a function (or a whole program) that applies a "Match-3 type of rule" from left to right and outputs the resulting string, like this :
```
[parameter] "12223" -> [returned value] "13"
```
Meaning, while parsing the string from left to right if you encounter **the same digit repeated 3 or more times successively**, this whole group of digits must "disappear", resulting in the concatenation of the left and right part of the remaining string.
**Each time you deal with a group, you must start again from the left end and reiterate the same process** until the string no longer changes (normally when you finally reach the right end).
If the string becomes empty at the end of the process, you should output an empty string, or the digit `0`, or an empty list/array as you prefer.
---
Test cases :
```
"1" -> "1"
"31122213" -> "33"
"44555554446" -> "6"
"1322232223222311" -> "1311"
"111" -> ""
"7789998877" -> ""
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins.
[Answer]
# Python 3.8, 67 bytes
```
import re
f=lambda a:(f,str)[a==(b:=re.sub(r"(.)\1\1+","",a,1))](b)
```
[Try it online!](https://tio.run/##ZYxBCoMwEEX3nkJmNaFBGJM2UchJahcJVSpUDWNc9PRpC60U@uCvHu/HR7ots7KRcx6nuHAquS8Gd/dTuPrStzjINbE4e@cwtI77at0CMmAlOuroABJAeklCXDCIHHmcEw4Iiqiua1JQfhCi2KXWxzda6xP8SVKvcB8R/EpjbNM01hoD39v8BA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [sed](https://www.gnu.org/software/sed/) `-E`, 18 bytes
Port of [Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/258202/112488).
```
:l
s/(.)\1\1+//
tl
```
[Try it online!](https://tio.run/##K05N0U3PK/3/3yqHq1hfQ08zxjDGUFtfn6sk5/9/Y0NDIyMjQ2MuExNTEDAxMTHjMjQGisGxoSGXubmFpaWlhYW5@b/8gpLM/Lzi/7quAA "sed – Try It Online")
### Explanation
```
$ info '(sed)Programming Commands'
```
```
:l # Specify the location of label 'l' for branch commands
s/(.)\1\1+// # Erase the first instance of 3 or more consecutive equal characters
tl # Branch to label only if there has been a succesful 's'ubstitution
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
(Ġ:‡ḢḢǑ⟇f
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIoxKA64oCh4bii4biix5Hin4dmIiwiIiwiJzEzMjIyMzIyMjMyMjIzMTEnIl0=)
Why use fixed point when you can do too much work?
```
( # Over each character
Ġ # Group identical items
: Ǒ # Find the first group where...
‡-- # Next two as lambda
ḢḢ # Removing the first two items yields a truthy result
⟇ # Remove the group at the index
f # Flatten the result.
```
[Answer]
# JavaScript (ES6), 42 bytes
Supports less digits than the more generic version below.
```
f=s=>s-(s=s.replace(/(.)\1\1+/,''))?f(s):s
```
[Try it online!](https://tio.run/##Zc7RCoIwFAbg@55Czo0bpeNsy2lgvYg3Y21hiBNP9PorQaLshwP/xcfhv9unJTf306MY49WnFFpqz1Qwaqmc/TRY55lgJe@ww7045Dnnl8CInyi5OFIcfDnEGwsMFKKUEhVkazjPhMhAKdhtqNbHJVrrCr5p9SdRvX9@DhFWiUvfYmPqpmnq2hj4WQDpBQ "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 43 bytes
```
f=s=>s==(s=s.replace(/(.)\1\1+/,''))?s:f(s)
```
[Try it online!](https://tio.run/##Zc5BCsIwEAXQvacos2mC2jBJbFIhepFuSk1ECU3piNePFopo/TDwF4/h37tnR/10Gx/7IV18zsGRO5FzjBxVkx9j13smWMVbbHErdmXJ@ZmOgRHPfRooRV/FdGWBgUKUUqKCYgnnhRAFKAWbFdX6MEdrXcM3rf8kqvfPzyHCInHua2yMbZrGWmPgZwHkFw "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ΔDγ.Δg3@}õ.;
```
[Try it online](https://tio.run/##yy9OTMpM/f//3BSXc5v1zk1JN3aoPbxVz/r/f0NjIyMjODY0BAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/p43J4ul6R16FVZZX2SgqP2iYpKNlX/j83xeXcZr1zU9KNHWoPb9Wz/l@r8z/aUMfY0NDIyMjQWMfExBQETExMzHQMjYFicGxoqGMIxObmFpaWlhYW5uaxAA).
`.Δ...}` could alternatively be `D...Ïн` and/or `g3@` could alternatively be `7b@` for equal-bytes alternatives:
[Try it online](https://tio.run/##yy9OTMpM/f//3BSXc5tdzJMcDvdf2Ht4q571//@GxkZGRnBsaAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/p43J4ul6R16FVZZX2SgqP2iYpKNlX/j83xeXcZhfzJIfD/Rf2Ht6qZ/2/Vud/tKGOsaGhkZGRobGOiYkpCJiYmJjpGBoDxeDY0FDHEIjNzS0sLS0tLMzNYwE).
**Explanation:**
```
Δ # Loop until the result no longer changes (using the implicit input):
D # Duplicate the current integer
γ # Split the copy into parts of equal adjacent digits
.Δ } # Pop and find the first that's truthy for (or -1 if none are):
g # Push the length of the group
3@ # Check whether this length is >= 3
õ # Push an empty string ""
.; # Replace the first occurrence of the found 3+ digits group with this ""
# (after the loop, the result is output implicitly)
D # Duplicate the list of parts of equal adjacent digits
7b # Push 7, and convert it to a binary-string: "111"
@ # Check for each value in the copy whether it's >= 111
Ï # Only keep the parts for which this is truthy
н # Pop and keep the first element (or "" if none were)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
Œɠ>2i1œPŒgFµÐL
```
[Try it online!](https://tio.run/##y0rNyan8///opJML7IwyDY9ODjg6Kd3t0NbDE3z@uxxuf7ijRzPy/39DHQVjQ0MjIyNDYx0FExNTEDAxMTHTUTA0BorCsSFQoSGIMDe3sLS0tLAwNwcA "Jelly – Try It Online")
Takes input as a list of digits, outputs as a list. Outputs `[]` if the result is empty. The TIO footer converts to/from numbers to lists (and converts `[]` to `0`)
## How it works
```
Œɠ>2i1œPŒgFµÐL - Main link. Takes a list of digits D on the left
µÐL - Until a fixed point is reached, do the following:
Œɠ - Run lengths of equal adjacent elements
>2 - Greater than 2?
i1 - Find the first truthy index, i
Œg - Group equal adjacent elements
œP - Split, removing the element at the index i
F - Flatten
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 12 bytes
```
+1`(.)\1\1+
```
[Try it online!](https://tio.run/##K0otycxL/P9f2zBBQ08zxjDGUJvr/39DLmNDQyMjI0NjLhMTUxAwMTEx4zI0BorBsaEhlyEQm5tbWFpaWliYmwMA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Same regex as before naturally; the `1` executes it once (because Retina defaults to global search and replace) while the `+` repeats until the string no longer changes.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
e/(.)\1\1+
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=ZS8oLilcMVwxKw&input=WwoiMSIKIjMxMTIyMjEzIgoiNDQ1NTU1NTQ0NDYiCiIxMzIyMjMyMjIzMjIyMzExIgoiMTExIgoiNzc4OTk5ODg3NyIKXS1tUg)
```
e recursively replace...
/(.)\1\1+ regex: three or more of the same character
with empty string
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 21 bytes
```
Wa~`(.)\1\1+`a:$`.$'a
```
[Try it online!](https://tio.run/##K8gs@P8/PLEuQUNPM8YwxlA7IdFKJUFPRT3x////hsZGIGAMw4aGAA "Pip – Try It Online")
### Explanation
```
Wa~`(.)\1\1+`a:$`.$'a
; a is first command-line argument (implicit)
W ; While
a~ ; the first match in a
` ` ; of this regex:
(.) ; any character
\1\1+ ; followed by the same character 2 or more times
; exists:
$` ; Portion of the string left of the match
$' ; Portion of the string right of the match
. ; Concatenate
a: ; Assign back to a
a ; After the loop exits, output the final value of a
```
[Answer]
# [Arturo](https://arturo-lang.io), ~~56~~ 53 bytes
```
f:$[s][(=s:<=replace s{/(.)\1\1+(.*)}"$2"s)?->s->f s]
```
[Try it](http://arturo-lang.io/playground?ca88VS)
-3 bytes thanks to @Neil
I couldn't get the regex everyone else is using to work, because it wanted to replace all instances of three or more of the same digit at the same time.
# [Arturo](https://arturo-lang.io), 69 bytes
```
g:$[a][(=a:<=flatten filter.first chunk a=>[&]=>[2<size&]a)?->a->g a]
```
[Try it](http://arturo-lang.io/playground?ca88VS)
A version that works on arrays.
[Answer]
# [Raku](https://raku.org/), 33 bytes
```
{($_,{S/(.)$0$0+//}...*eq*).tail}
```
[Try it online!](https://tio.run/##PchBCsIwFEXRrTxKkLZK0p98mwRsN@ECQgcNCBW1Oikha4914oUzuc95Xfpy33CIGEqqRTilq6plIzrRHZXKUsp2frWN/Ey3JZf3tKESAcOIFCFCrhAfKy4EQ6S1JgPm8y9m7kFmf39EoJ21znvvnLVj@QI "Perl 6 – Try It Online")
This is a sequence of successive modifications to the input string, ending when the last two elements are equal (`* eq *`). Then `tail` picks off just the last element.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes
```
W⊕⌕⭆Φθλ⁼κ§θλ11≔Φθ∨‹λ⊖ι⁻✂θ⊖ι⊕λ¹κθθ
```
[Try it online!](https://tio.run/##VY7BCsIwEETvfkXoaQvxkHr0VFChYFHoF4R0aZeu0Sap@vcxVdB6GJhldnhjeu3MVXOMj54YBVTWOLygDdjCgWwLTXBku1rf0skBHYxScC7Ffpw0exikKENlW3x@gjxFmVJZMqL0njq76J0cHNF7YCl2@OPQXKrJTh4aJoPz638uxXLXjFdJw5s25tvVOW0MkFyMalMUxVdKxfWdXw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Tricky without any regex or grouping primitives.
```
W⊕⌕⭆Φθλ⁼κ§θλ11
```
Map overlapping pairs of characters into `1` if equal or `0` if unequal and search for a substring match of `11`. While one is found...
```
≔Φθ∨‹λ⊖ι⁻✂θ⊖ι⊕λ¹κθ
```
... extract the characters prior to the match and all those where the substring from the match to the character contains at least two different characters.
```
θ
```
Output the final string.
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 6 bytes
```
ò툱±«
```
[Try it online!](https://tio.run/##K/v///Cmw2sPdRzaCISr//835DI2NDQyMjI05jIxMQUBExMTMy5DY6AYHBsachkCsbm5haWlpYWFuTkA "V (vim) – Try It Online")
If you check the [V wiki](https://github.com/DJMcMayhem/V/wiki/Regexes) on regexes there are a lot of shortcuts. This line basically expands to:
`while(match found){ :%s/\(.\)\1\1\+// }`
which removes the first 3 found matching characters and then repeats until there are none left.
[Answer]
# [Julia 1.0](http://julialang.org/), 53 bytes
```
!x=x==(y=replace(x,r"(.)\1\1+"=>"";count=1)) ? x : !y
```
[Try it online!](https://tio.run/##PYzhisIwEIT/9ym2@WOCVdgm2vZke/cggkSNkCPEkkSIT9@L9HRg2Zlvh/19OKsxz3OdKRPxJwUzOX0xPDeB8a044hHXjEbGDpf7wydCIeAbMnxB/Zxv9wAWrIdg9NVZbyIXFRTp5tScgSCmYKctj5OziVvRrNhqKUzB@uQ810Aj1HqBPzpGE1LJQATnyvjrzJDBZoSyKiYR27ZFuRApC1Jq95JSar/QfYEoS@0z@P7wcuX4zsV3XT8MQ9933T/6Aw "Julia 1.0 – Try It Online")
very similar to several other answers: regex, compare, recursion
[Answer]
# C function, 108 bytes
[Try it online with a driver program](https://tio.run/##TY7NCsIwEITP2acIFSFpqyh6ao0efAz1UNbaBmrMT1VEfPaYVAVPO3yzzAxOGkTvR1Jhdz3WdOX6o7xM2zX8IytVExlgW9kU2XAcp08gUdJUC5enpgRyb2VXs1TzYBEjdEA/lmVGiOBEpIWZ6LVYbEI26gfTueE5MseLGPICYuv@ahV1JbwApOrpuZKKRVHZBnP6qQ36tjvEHUB0GNmfWLIt6NjtVRJ@2ODPDzx2fhNnQ6L3fvkG)
```
char*c(char*s) {
char *p=s,*q;
while(*p){
q=p;
while(*++q==*p);
p=q-p>=3?strcpy(p,q),c(s):q;
}
return s;
}
```
Here is one that hopefully meets the community standards; I'm sorry the first one didn't. I left just a few extra whitespace for clarity, hope that's OK.
[Answer]
# Excel (ms365), 124 bytes
[](https://i.stack.imgur.com/tjFGY.png)
Formula in `B1`:
```
=LET(x,SORT(TOCOL(REPT(ROW(1:9),SEQUENCE(,LEN(A1),3))),,-1),REDUCE(A1,x,LAMBDA(y,z,SUBSTITUTE(y,@SORTBY(x,FIND(x,y),),,1))))
```
**Note:** For testing, drag this down when absolute referencing is applied to `ROW($1:$9)`. Took it of in final answer to save bytes.
[Answer]
# [Haskell](https://www.haskell.org), ~~68~~ 63 bytes
```
until((==)=<<f)f
f(x:r)|(_:_:_,b)<-span(==x)r=b|1<3=x:f r
f s=s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8Hual1lBR9HP_dQR3dXBeeAAAVl3VournQFW4WYpaUlaboWN-1L80oyczQ0bG01bW1s0jTTuNI0KqyKNGs04q2AUCdJ00a3uCAxD6igQrPINqnG0MbYtsIqTaGIK02h2LYYakxWbmJmHtDY3MQCXwUNhYKizLwSBT2FdAVNhWguBSVDJR0gaWxoaGRkZGgM5piYmIKAiYmJGZhvaAyUg2NDiA5DKG1ubmFpaWlhYW6uFAuxccECCA0A)
The function `f` recursively goes through the string and removes the first group it encounters. `until((==)=<<f)f` is short for `until(\x->f x==x)f` and applies `f` to the input string until a fixed-point is found.
#### Previous 68 bytes approach
```
(""%)
s%(x:r)|(_:_:_,b)<-span(==x)r=""%(s++b)|y<-s++[x]=y%r
s%t=s++t
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8Gual1lBR9HP_dQR3dXBeeAAAVl3VqudAVbhZilpSVpuhY3XTSUlFQ1uYpVNSqsijRrNOKtgFAnSdNGt7ggMU_D1rZCs8gWqESjWFs7SbOmEiiurR1dEWtbqVoE1FViC-SWQM3Kyk3MzAOanZtY4KugoVBQlJlXoqCnkK6gqRDNpaBkqKQDJI0NDY2MjAyNwRwTE1MQMDExMQPzDY2BcnBsCNFhCKXNzS0sLS0tLMzNlWIhNi5YAKEB)
[Answer]
# Haskell, 94 bytes
```
f xs=case break((>=3).length)$group xs of{(ys,[])->concat ys;(ys,zs)->f$concat(ys<>drop 1 zs)}
```
[Answer]
# [Scala](http://www.scala-lang.org/), 93 bytes
Golfed version. [Try it online!](https://tio.run/##hY5NSwMxEEDv@RVDThuUQNrVbVcCehE8eKgfJ@shrtMayWaXyVgspb99TVkR9GAHBiaZN28mNS64wbd9Rwzp8NAuxo4d@y5qdj4QNuJX/4N90K3j5s3Htb7DNX4K0b28Y8Nw63yEnbj8HhxecQWrItULVS/sbuMIyEopC62WZmlOcqlJE/bBNXjtKfFNLNIpSKkufJ6zllQCDAmzhdRe8LZHWNh7prx7ADj4Cdtugw/k@4Cc8rKxq2wWKDEybb6rcLRONVwRue3TyDyrGh6jZ7D5aMjR518OsfjjlFNjJpOJmUql/uXK8uwQZVmeH0PNNBt/0phjfFXN5vP5bFZVI7kX@@EL)
```
def f(s:Q):Q={var r="""(.)\1\1+""".r.replaceFirstIn(s, "");if(s==r)s else f(r)}
type Q=String
```
Ungolfed version. [Try it online!](https://tio.run/##hZBNS8QwEIbv@RVDTw1KIG21H1DQi@BBED9OrofYna2RNC3JuCiyv71mt25h9@AGEmYyzzvMO75RRo2j7obeEfhtJpS1PSnSvRWktHHYsIP6J2kjOkXNu7ateMAWvxjr3z6wIbhT2sIPA1jiCrqQxMq1voJr59T3yyO5IHnlFTxbTVDvSIAh/JKxscOuX@OT04NB8nGUSpkkiUwjzv/lsuxie7IsuzyFyjR0nK@Up/g8L8qyLIo8n8gNC8/Vfi2TzSNNcDv55PtgNrpWBmji7hUROlvBbn@BiKIoFnwhF/IshMLNAoeDUQ0uA3OoFX@VG@083drYn4cmkx29gthDXc9iDh7QeDwedq7vvG3YOP4C)
```
import scala.annotation.tailrec
import scala.util.matching.Regex
object Main {
def main(args: Array[String]): Unit = {
println(removeTriplets("31122213"))
println(removeTriplets("44555554446"))
println(removeTriplets("1322232223222311"))
println(removeTriplets("7789998877"))
}
@tailrec
def removeTriplets(s: String): String = {
val tripletPattern: Regex = """(.)\1\1+""".r
val replaced = tripletPattern.replaceFirstIn(s, "")
if (s == replaced) s else removeTriplets(replaced)
}
}
```
] |
[Question]
[
Given a positive integer `n`, output all of its anti-divisors in any order.
From OEIS [A006272](http://oeis.org/A066272):
>
> Anti-divisors are the numbers that do not divide a number by the largest possible margin. E.g. 20 has anti-divisors 3, 8 and 13. An alternative name for anti-divisor is unbiased non-divisors.
>
>
>
In other words, `1 < m < n` is an anti-divisor of `n` if either
* `m` is even and `n % m == m/2`, or
* `m` is odd and `n % m` is equal to either `(m-1)/2` or `(m+1)/2`.
Notably, 1 is *not* an anti-divisor of any number because it does not satisfy the phrase "do not divide a number".
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Shortest code in bytes wins.
## Test cases
```
1 -> []
2 -> []
3 -> [2]
4 -> [3]
5 -> [2, 3]
6 -> [4]
7 -> [2, 3, 5]
8 -> [3, 5]
9 -> [2, 6]
10 -> [3, 4, 7]
18 -> [4, 5, 7, 12]
20 -> [3, 8, 13]
234 -> [4, 7, 12, 36, 52, 67, 156]
325 -> [2, 3, 7, 10, 11, 21, 26, 31, 50, 59, 93, 130, 217]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 46 bytes
```
lambda n:[m for m in range(2,n)if-2<n%m*2-m<2]
```
[Try it online!](https://tio.run/##BcHBCoJAFAXQ/f2Kuwk1FJynlon2I9XCyMkB5ykyEX39dM72C/OqEu1wj8von6@R2t087brT0yn3Ud9TKrlmzhbS68EfpfC9POJ3dstE04E6ON0@Ic3AbXcaqDmT4prktKlm0UCICjUanHBGiwtMCdMSUkKqGpU0fw "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org), ~~32~~ 31 bytes
*Edit: -1 byte thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
\(n,m=1:n)m[(n%%m-m/2)^2<1][-1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VZA9DsIwDIXFyiksoUqplIjGSfqDKBcpZcyWDghOw1KQOAf34DTYaaqWwbK_5-fYyuN5HV--fd9vXtWfsxhkaPVhyEMnhiwLKuwxv-BR953S_eT6boQXOt-BOkHXb73AVW1SjQw2gWFwc0dC5DKxZahWTQmOpXoeTtwslpJZF4vBSqiiNg-R4EiToOMhuPLWJMYD0NjFHa20vKRB3sDs4h6D7u847hQUWgJy0ISh7EhzjYTG8PsFN6v0YeM45R8)
Pretty much similar to other answers.
The `n=1` is problematic: we can't use `m=2:n` as this would result in `m=2:1`=`c(2,1)`. So we use `m=1:n` and then remove the first element (`1`) with `[-1]` at the end.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 30 bytes
-2 bytes thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor).
-1 byte thanks to [@pajonk](https://codegolf.stackexchange.com/users/55372/pajonk) and [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)
```
n->[d|d<-[2..n],(n%d-d/2)^2<1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboW-_J07aJTalJsdKON9PTyYnU08lRTdFP0jTTjjGwMYyGKbromFhTkVGrkKejaKRQUZeaVAJlKII6SQppGnqamjkJyfl5yYolGtKGenqFBrI5CtKGFjoKRARAbm-goGBuZxmpqQgxbsABCAwA)
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), ~~40~~ 34 bytes
*-6 bytes thanks to @Bubbler by looping backwards*
```
;=i=pE P W<1=i-iT&>4^-*2%p i i 2Oi
```
[Try It Online!](https://tio.run/##lVhpc9s2EP3eX0GziUWIFC27aTsRTXsS1@lk2shp7DbTSkoEgpDEhiIVHrZTif3r7i54gbqcTmYyIvCwF94e8N/0lsYs8hZJJwhd/sB8GsfKL4E3nSWXURRGCr9PeODGivhaZjngLY1i3tyXzpSod2mQePPHcddJxOl8ycIgTqKUJWGkUbJMZl5sxmEaMW7TDHa8xfuZl/B4QRnXiv05TdhMO/qgDYaj4WAYw3rWG@mrbwcfhsGorQ2D1RNC2kckW3D@CXYjnqRRoEjCB93RahWkvp/lwhyD2V2y9HmiUNsx@T1nmgQnViECj9i2Tc/xR0@G2NJvM04dsF2joMb0eTBNZsSgAzYiWRKC414w3WpVlolwKDd/vr28tgcjKw/VH9RP@TJOaOIxZYG3oDlk6Zgb4bEmEMVbGoEPXYueCjGFfovqeu4fs8X6gI7MUpblTTRGCntYJvmaRWkgwh6Fd0rA73JGZC530umW9R3eCSFmvQm4fjp3eLQDV24C7mUY@pwGO4DVblaw6lcIRkT9inh56NZIFqcLlG4IUR9dmlDgWu6opGSLM8V3fW6bJ8V3E7ThRrkgw/hnH80rEFTxwGoaMB5Ocq8lNw4PJeOBj/mvMgoovApBEZIN/pRcr7Pp5tWIDF50/hq1j4zjivL08BAvGGVq6o2K2kjmpvNF5cy4dOaJyM@MjDM/mdWuHNS2Hh7SxrVNZZwi4w6awCwn8yKNZxquEitPlcv@H6/fXfXfXPZv7GVWJMxrlwfJGgcec39AO/98HOH/3c7zjxCC9QAIoWBsto9NHoKATc34iKPexANcHqIch4ECc71pgHIkTwY1ZlRRMzd4Bwoz@Db0XKV7gPdTWm7VCSrXZW38e/ApCO8CxassU1oN01rjZsyFC6SMrxTdr6XX0NU3QwoBLdKFknVSFRs1p6jrSlwpz9ec0alUOkgGNXgvvNOEz1N/L7zdhLverexlvYU30biEUtQbmsxM4E3AJKlH4PeuS1IvaBCEiQKq4E4U54vyD49CFUwN3f@pu1b4lD6qD8SnfijpW4R3@/XV4lerA42edslXOd9uf4X3/H4RBkhSmnBhkJKEUBsDPgW@3XIFjOMRGOnvqCSn8r3trDdnDVSD@DXt@9AQ9/Neqt4V8ftFSSU551FIo4SUFQTb7VoOqAjWiLqvMwh5hfOPhJKFczCTiyOmWgXjf56Sg4NrZXSgOT4aHKSQY1Op56itEYE5Lh5ej9rnZHh8ZJwIWmE0gFmOTCTQgMNKPsRQMx/uEKy2sC2x1aqltvAHqV2qh1YsemDV3AuASa7yOQ2BUDxgYYrL3O0pT5Y0G29r6cL@Zh4Zx12yWnXXalYxIOyrWejEuAAUCjdLD4JqXWbEF5xC75Er0COMr0atvYyvUPKlwmLRXeEUda@/BKxHMzvin1Mv4po6iVViLHFEFluOtMVmnu9@XEQh4zGiXv3ev7h5fdW/rnvzK6gB@1qzxJL8gmEyr8QMHKnTiZuWZlVL4tV5T2SdvjLJUc4YjvM0zsf44cJ87J6ycjZ2y9l4YguLzNIUVHYw2UGnNx707mCq0GiaznHgeLJ09eNMASXKBL2EjupgI7V4HtgJyaQ7xkBozHAMvjZSwBJbGytQnE3z3wGdc9vJf4Pq2Gabs6s4oJmmWaGqypJXcRW1J14YaKpeSa3C4yjlyCmOUt1WDUXVHTOXUXVxXd2oTVfO35wlphcL/howLmWTQpUS8akXJ1y4SJYQ2mPsVeUDae0toal9MEmZpzDkOZCo95Ql/hcFeoHCZjSCL5hZ/DCYQk2yaoLQke1IGiEwVeeSr7ZIMniBao6UB0SuPfUYlb83rK00UPuhcouSoVCmvou2ChXuAdRKKasw4MSoQqC@VQ2N2GfFk0xVDcd@mU4mPDKp74dMgwHcDTFIVOsCI7owkRtAeQeelMQBwz9ZTAdX7yDjuHYMXVjsiJecibn13oPEV4eBSgizmRn7HrwQu4bSqSf7stIwksmWvcsta7TuiR@Cr89Onj97/sOPJ89/aIvViAZuOMewyecvVYPaZxgy2ghtDWm9aCGkSvQ8vIVVjtzdwIDz0sxckjmJwvkFMOAidGHQLN5OpFeaK1@nyQrciwRnNtnIl8JIKi9d5EvF41L8L2@PxXbVh5rO7XBU/U0cKgqiye@99SouYQ8qBeKt1XwANZC/Vkj0WDakTCYZ/RNy66wa3xrBLi2LEzdME/MugsYNAvM8JwZtxOyqKajWWkhTh0PxPCzIBkw73yG/ZCNASG8rZoy98ZsxMaqZSbZEB4piEamvCxtt4VvD@c4GEt8F25DtDST25W3Iow2keA1sQT7dlBlut/PDBlJM3VuQpxWyokp5BCeC6oh85mz3memuM@e7z2DJ33rmsDqj0TKvG3@nOS@O9RqZt3r0GO05mxlpScfyXWNbwGwJ1qgt@KRdrUCl9LxvJjI1i/e5Y1f6nYbw95XwJXZPq5G0FllLt61kfp2LgKZvn9GtwWKbvv8sHRJBq@02nMYjzcDyL32WFYyWf6VEIauVqjajdl0ocIWK8tAjqlzb3dRcgctWj2P9OdVhqixNgA5HdKbXJuku9uK6Yfzbkite8@kOOIhOWUVgYrkdnEAnfHh4@O7k@28eLNuzF5fKW@X96bHtdbybw7NnHzrtk6cLxYN/J1fefw)
Outputs each anti-divisor in a separate line.
I feel like there's just way too much whitespace; there must be a some rearrangement that can avoid some of this whitespace lol
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 31 bytes
```
{grep {1>$_%$^a-$a/2>-1},2..$_}
```
[Try it online!](https://tio.run/##TU5LDoIwEN33FLNAo6F8@gUWchGthEQwJqAEVoRwdpwWIS4m836d167qG720IxxruMAyPfuqg4nlXnHw7mXglRHPAzZTHoZeMS9DOUJ98tvo9vCjM9SfHprXuxoWBkEOV0P4bwu3uSHSAWGIWhUKiLXD0pBkFykoQ9I17HC2WdoQFm@GpJAgX4NIFHIKDIv4nklRwBIu5JZyESzR@MBetFzhXcHV3wesGuMwCtwOpgVuhZrKKGTC3o2tmZgv "Perl 6 – Try It Online")
Anonymous code block that takes a number and returns a list.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
%RḤ_RỊTḊ
```
[Try it online!](https://tio.run/##y0rNyan8/1816OGOJfFBD3d3hTzc0fX/cLu3ZuT//4Y6CkY6CsY6CiY6CqY6CmY6CuY6ChY6CpY6CoYGQAxkGgFpI2OgvLGRKQA "Jelly – Try It Online")
Feels... messy, but the best I can think of to reuse the range ties: `Ḋ%Ḥ_Ịʋ@Ƈ`
```
%R n mod each [1 .. n]
Ḥ times 2
_R minus each corresponding [1 .. n]
Ị in [-1 .. 1]?
T Find truthy indices
Ḋ and remove the first (always 1).
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 23 bytes
```
{1↓⍵{(2>|⍵-2×⍵|⍺)/⍵}⍳⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/Ma8kMyWz7FHbhGrDR22TH/VurdYwsqsB0rpGh6cDKSBzl6Y@kFH7qHcziPr//z8A "APL (Dyalog Classic) – Try It Online")
**Usage:**
```
antidiv←{1↓⍵{(2>|⍵-2×⍵|⍺)/⍵}⍳⍵}
antidiv 10
3 4 7
antidiv 325
2 3 7 10 11 21 26 31 50 59 93 130 217
```
[Answer]
# [Factor](https://factorcode.org/), 61 bytes
```
[ dup [1,b] [ [ mod 2 * ] keep - [-1,1]? ] with filter rest ]
```
[Try it online!](https://tio.run/##JY09D4IwFEV3fsWdDRDKh6IOjsbFxTiRDhUeSoRSyyPGGH97bTR3O7knp1U1j9adT4fjfoNB8S22Sl9pwp2spv6H/ryddc3dqCdM9JhJ1/5kLDG/jO00YxsEbwikyJCjwBIrlFhDJBAl0gRpliNLC3wCV6GZDSoRXiQqv2FsvLeA9FUyiFBFIhRy58Gz8/2265ksLE0M6QZlELsv "Factor – Try It Online")
One of six variations I tried that all come out to 61 bytes. Went with this one because I've never used `[-1,1]?` in a golf before and I think it's a neat word.
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 39 bytes
```
n=>{for(i=n;--i;)n%i-i/2|i<2||print(i)}
```
[Try it online!](https://tio.run/##JYzNCsIwEITvPsVepAls1KbWH2J68ynEQ6kWV3Fb0iJI22ePix0Y5oMZ5ll@yq4K1Pama@l2D@@GX/dvrH1kXwx1ExR5dsaQ07wkQ2s70smOYxuIe0V6ipcUwSJkCFuEHGGHsEc4IBwR0o1Y0EraTPrM5teVvJ7L6qEYfAHDAmA@S4woQWCEGbWTrlb8z3kjOGkXfw "JavaScript (SpiderMonkey) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
L¦ʒ%·yα!
```
[Try it online](https://tio.run/##yy9OTMpM/f/f59CyU5NUD22vPLdR8f9/YyNTAA) or [verify all test cases](https://tio.run/##AU0Asv9vc2FiaWX/dnk/IiDihpIgIj95wqn/TMKmypLCrnMlwrd5zrEh/30s/1sxLDIsMyw0LDUsNiw3LDgsOSwxMCwxOCwyMCwyMzQsMzI1XQ).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input]
¦ # Remove the leading 1 to make the range [2,input]
ʒ # Filter this list by:
% # Modulo the (implicit) input by the current value
· # Double it
yα # Get the absolute difference with the current value
! # Factorial (1 remains 1; 0 becomes 1; everything else just increases)
# (only 1 is truthy in 05AB1E)
# (after which the filtered list is output implicitly)
```
[Answer]
# Regex (ECMAScript 2018 / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / .NET), ~~35~~ 31 bytes
```
(?=((x+)\2(x?$))(?<=^\3?\2\1*))
```
[Try it online!](https://tio.run/##bVC9bttADN7zFIpR4MjKPlgKvFg5a@rgJUM7RilykGiFxfmk8s6xYMdrH6CP2Bdx5RQGMnQj@JHf3w/7akMt3MeZ7xo6BzMvxHyl9svQw7co7Fstdv98htIADClWOQzlJ0Qo78336q6s8ir7jHh@1sFxTZBNZxlOVauwEPq5YyFQQrZx7Emhrsc50tpHko0dz4/s@11c9tLVFIIOsWF/Qt15UO8fU2dWx9Y4HXrHEdRs5OUNgDetduTb@IKr/O2Nw4N9ADa9lXBhh/Zx/oR4Begj4FdZmS0vMMYX6faTtX@1jptErG9pmUxSV2w6gYLvDRWcpnj8YK/bRb0XjgQQSlV5tVQKU05V8ufX72R0F0xWDGYyTLRQP4YFxne6w9gsbI1oGqiGAfHWGL9zrjiYDI83/5c4lCr5p7B9zJ6uiS8N3G7HhNeFaGdDXPuGhjQ9nU54ns/yxeLmLl/8BQ "JavaScript (Node.js) – Try It Online") - ECMAScript 2018 / [Try it online!](https://tio.run/##bVC9btswEN71FIpRgHeVTZhyCxRWaE0dvGRoxyhFCOmsXEFTKknHgh2vfYA8Yl/ElVMYyNDtcN/d9/fTPJtQe@7jzHUNnYOeF15/o/br0MP36Nm10pv94xlKDTBkWOUwlB8QobzVP6pFWeWV@oh4fpTBck2gpjOFU9EKLDz92rEnEJ5MY9mRQFmPc6S1i@Q3Zjw/sut3cdn7rqYQZIgNuxPKzoF4@5havTq22srQW44gZiMvbwCcbqUl18YnXOUvLxzuzB2w7o0PF3Zo7@cPiFeA3gNupUq1vMAYn3y3n6zds7HcpN64lpbpJLPFpvNQ8K2mgrMMj@/sdbso954jAYRSVE4shcCMM5H@@f2aju6CVsWgJ8NEeurHsMD4RncYm4Wt9pIGqmFAvNHa7awtDlrhMfm/xKEU6T@F7b16uCa@NHCzHRNeF15aE@LaNTRk2el0wrOaqXmiviT5PMkXn5JF/vkv "JavaScript (Node.js) – Try It Online") - test cases only
[Try it online!](https://tio.run/##RY9BboMwEEX3nGJkVbInMQiD2EAsTpATAJUiAYklOiDjBckBcoAesRehdtOqu/n6/7@ZWe7uNlO@m49ltg7W@yrtcB22Cqy2jLFd1FqI7YhtJrb6DVHUJ/3e5nWbteqAuPtMo8pYdRU8dBqNs4UJDAVSsrreUBnBpKdkXSbjBIsZRhBCFEL2QtdBGHJiatIO5WvyMDwq9EUwIzxKWGwwfNGvUNWvJMm/np9cDtRrzoMZsOcfbPggGQ31xg1WWAlsYwfC8tXkXJ79PRcSChvVxf8i7f5wexpnRRHlWfEN "Python 3 – Try It Online") - Python `import regex` /
[Try it online!](https://tio.run/##RY9haoQwEIX/5xRDKCSzG8VoC0UbPMGeQC0sqNuAHSXmh7sH6AF6xF7EJt2W/pvHe@@bmeXq32Yqdvu@zM7Del2VGy7DVoEzjnO@y9pIuR2xzeVWPyDK@sW8tkXd5q0@IO4h0@gy0V0FN5OxcXYwgaVISlffWyoZTGZK12WyXvKEI4MYohhyZ7oM0pKXU5N1qO5TgOFRYyiCHeFWwuKiEYphha5@JSnx9fEp1EC9ESKaEXv6wcYP0tFSb/3gpFPAN34gLO9NIdQp3HMmqbHRXfIvsu4Pt@tEZ0w/szxjefHIivzpGw "Python 3 – Try It Online") - test cases only
[Try it online!](https://tio.run/##RY9RaoQwEIbfe4oQBkzWRtTFl7XBhT73BGpBbFYDMZEYUXbxtQfoEXsRm11o@/gP83/zzWgWYadeKLWD5aUVnVjr00mLhZyDnRSckDWkVUrWAiglxQt/r45FlVbJgdI9OD/jVzOMUokPTHO48ji/GCuatiegkNQIpB5nR2/QcFBsGpV0mOFcXgg0UWtm7ZhyKL0vhByaMq43DyCgeSm1qx@THDRT4jcn9xyGvjFwsNFb49peTCRYgwNo@iBf6W2x0gnWm8lt3irJ/zNi2vj3lNQCYdDo@/MLAfmzbh/Wg8e3UWfNPE7@YqSE7ly/Ubxte8zSLHs6ptkP "PowerShell – Try It Online") - .NET / [Try it online!](https://tio.run/##RY/daoQwEEbvfYogAyZrI/60UNYGF3rdJ1ALYrMaiInEiLKLt32APmJfxGYX2l5@w3xnzox64WbquZQ7GFYa3vG1Ph4VX/Ap2HHBMF5DUqV4LYAQXLyw9yorqrRKDoTswenBf9XDKCT/8EkOFxbnZ2140/YYJBIKgVDjbMkVGgaSTqMU1qd@Ls4YmqjVs7JUWpTeFkIGTRnXmwNgUKwUytb3SQ6KSv6bk1sOQ9cYGJjorbFtzyccrMEBFLmTL@S6GGE57fVkN2eV5P8ZUaXde1IojnxQ6PvzCwH@s27v1oPDt1Fn9DxO7mIkuepsvxF/2/aEJrGXPHtp7KXZo5elTz8 "PowerShell – Try It Online") - test cases only
Takes its input in unary, as a string of `x` characters whose length represents the number. Outputs its result as the list of matches' `\1` captures.
This version takes advantage of variable-length lookbehind that is right-to-left evaluated:
```
# tail = conjectured anti-divisor
(?=
( # \1 = tail
(x+)\2(x?$) # \2 = floor(tail / 2); \3 = tail % 2; tail = 0;
# head = input number
)
(?<= # Variable-length lookbehind; read from bottom to top.
^ # Assert head == 0
\3? # optionally, head -= \3
\2 # Assert head ≥ \2; head -= \2
\1* # head %= \1; due to backtracking this result may also have
# a multiple of \1 added to it, but it will not be able to
# match in that case since \2+\3 is guaranteed to be less
# than \1.
)
)
```
# Regex (ECMAScript 2018 / Java / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / .NET), ~~38~~ 37 bytes
```
(?=((x+)\2(x?)))(?<=(?=^\1*\2\3?$).*)
```
[Try it online!](https://tio.run/##bVAxTsNAEOx5hYmQbhcnp9goTczFFUUaCihxECd7YxZdzubuQqyEtDyAJ/KR4IAiUdCtZnZnZ@ZFv2lfOm7DyDYVHbwaZ07dUX3TtXAfHNtaOr15OkCuALoYixS6HBEhv1Y99lgkl0VaXOUXKC/x8CS94ZIgGY4SHIpaYObodc2OQDjSlWFLAmXZz4HmNpBb6n59x7Zdh2nrmpK8lz5UbPcoGwvi52Jo1GxXKyN9aziAGPW6vASwqpaGbB2ecZa@v7O/1bfAqtXOH9WhfhgvEE8E/SXsLMmT6ZHG8OyazWBu37ThKnLa1jSNBrHJlo2DjK8VZRzHuPtjr1kHuXEcCMDnorBiKgTGHIvo6@Mz6t15lWSdGnQD6ajtwwLjj9y27xdWyknqqIQO8VwpuzYm26oEd2f/v9jmIvr9sHpIFqfExwbOV33CE@Ck0T7MbUVdHO/3ezyMR@lkcnaVTr4B "JavaScript (Node.js) – Try It Online") - ECMAScript 2018 / [Try it online!](https://tio.run/##bVBBbtswELzrFYpRgLuRTZhyCxRWaJ168CWH9hilCCGtlS1oSiXpWLDjax/QJ/YjrpzCQA69LWZ2Z2fmh3kxofbcx5nrGjoHPS@8/krtl6GHb9Gza6U3@6czlBpgyLDKYSgREco7PWLfK3Vb5dWi/IDyFs9PMliuCdR0pnAqWoGFp5879gTCk2ksOxIo63GOtHaR/MaM60d2/S4ue9/VFIIMsWF3Qtk5EG8XU6tXx1ZbGXrLEcRs1OUNgNOttOTa@Iyr/PWVw725B9a98eGiDu3D/BHxStB7wq1UqZYXGuOz7/aTtXsxlpvUG9fSMp1ktth0Hgq@01RwluHxnb1uF@XecySAUIrKiaUQmHEm0j@/fqeju6BVMejJMJGe@jEsML7JHcZ@Yau9pIFqGBBvtHY7a4uDVnhM/v/iUIr034ftg3q8Jr40cLMdE14BL60Jce0aGrLsdDrhWc3UPFGfk3ye5IuPySL/9Bc "JavaScript (Node.js) – Try It Online") - test cases only
**[Try it online!](https://tio.run/##bVNLbtswEN37FFOhgYf@sLaDbKqoRhu0QIGkLZKl7QK0TNl0KFIlqVhJkG0P0CP2Iu5IVpsGsDaj@fBx3pvhVtyJ4XZ1u1d5YV2ALflcWd6L4f9IGZQ@GnNyLaujGR@cFDm/sFrLNFjn405RLrVKIdXCe7gSysAjtDEfRCBzZ9UKcsrgTXDKrEG4tZ8tGISNszsPH6tUFkFZOtkB@KS0hCwxctf8YsRTu5Kc8hGLP5RZJp1cXUuxkg6WTdnLIP492boZY3F7rx@EeLep8RF9siSeYnWpjETGXiWm1JqpDD2XP0qhPUZver1exNjjy9IDAmI4CvBICOEfAgG8IYQl1d3Gvp9056Zb2xA/HWJP30QI0hlwSftHbPOivsCzmNRYWqulMPCQZIQoY7hJhTFEXZmiDJBAzbaN4c29DzLnyrAYWp5NGd8I/0VWgdpsJAZoBdHUO2EcigxVtBTb/GwBmtJ1FfeFVgGjIQ2B6gOYEWU@m0Cr4nghnJfkoJ6NFmwAZnw0ybU067A5n8AU6kp4S2a8IMR0I9xsUbV8Gs@MFzG8d07ce54prbEadKtuIwpAZl3NjdpIzCgGc56YMZl@nwheiZBuSKGc0BzPDx42O2zoEVwQ@GFj@M6JAtsrUlvcf82uhVlLumk0MIzVTDN8YK2sljTaORUk1mNk8UMSXFlP5DldkGohw@hkBb9//oITH5EWg1ZNvrX0BCKgWE6b40sdPDJqsMDcDd9FUZ8sXztbFjhmrVY0Mka9Nc8Nn58dD/ZS@Xqg1OUTfZ16Wfc4TRCrPptPsJpSCqfnCcW@z8e9@WR@On3NeI/t663cj4aTs7PO6eTsDw "Java (JDK) – Try It Online") - Java / [Try it online!](https://tio.run/##bVPdbtMwFL7PUxwiptr98ZoOJEQWKphAQtoAbZdtkdzEad05drCdNd20Wx6AR@RFykkaGJOam5Pz48/n@87xht/x0Sa73cuiNNbDBn0mDevH8H@k8lIdjVmxEvXRjPNW8IJdGKVE6o11cVBWSyVTSBV3Dq641PAAXcx57tHcGZlBgRly463UK@B25WYLCn5tzdbBxzoVpZcGTwYAn6QSkCdabNtfErLUZIJhPqTxhyrPhRXZteCZsLBsy54Hyd@TnZtTGnf3uqGPt@sGnxCXLJEnzy6lFoTSF4mulKIyJ46JHxVXjoSn/X4/pPTheekBgRB/FOABEfw/BAQ4RYQl1t3GbpD05rrXWB8/HmKP37j3wmqwSfeHbIuyucDRGNVYGqME13Cf5IgoYrhJudZIXeqy8pBAw7aLkZud86JgUtMYOp5tGVtz90XUHttsJQboBFHYO2IcijRWdBS7/GwBCtNNFXOlkp6EIxwC1nvQY8x81h5XxbKSWyfQIWo2XtAh6OhokimhV359PoEpNJXwFk20QMR0ze1sUXd8Wk9HixjeW8t3juVSKVIPe3WvFQUgN7bhhm0kehyDPk90hGYwQIJX3KdrVKhANMuKg0faHdb4CC4Q/LAxbGt5SborUlPuvubXXK8E3jQeakobpjm5p52sBjXaWukFacZI4/vE26qZyFO6RNV8TsKTDH7//AUnLkQthp2abGPwCYSAsQI3x1XKO0KxwZIUdvQuDAdo2cqaqiQR7bTCkVHsrX1u5OnZMW8upWsGil0@4hc0y7on04SQekDnE1JPMUWm5wnGvs@j/nwyP5u@pKxP981W7qNRNA6iN8FkHEzOXgVnk9d/AA "Java (JDK) – Try It Online")** - test cases only
[Try it online!](https://tio.run/##RY9BboQwDEX3nMKKKiVmAiIgNtCIE8wJgEojATORqEEhC2YO0AP0iL0ITTqturP9/3@217u7LVQc5n1drIPtvkk7Xse9BqstY@wQjRZiP2GXi71BRNG8aj9761Tc5V3RvGAa4@GdraoS1dfw0Fk0LRZmMBR46eYGQ1UEs57TbZ2NEyxhGEEwUTDZC11HYciJuc16lM/Kw/Ck0AfBTPCoYLVB8EG/QtW/LUn@9fHJ5UiD5jyIAXv@wYY/0snQYNxohZXAdhYTVs8k5/Ls77mQUNiqPvlvsv4Pd2RJXpZRkZff "Python 3 – Try It Online") - Python `import regex` / [Try it online!](https://tio.run/##RY9RboMwDIbfcwormpSYBkRgkyZYxAl6AmBSpUIXiRkU8kB7gB1gR9xFWLJu2pvt//8/28vVv81U7vZ9mZ2H9boqN1yGrQZnHOd8l42RcjtgV8itQUTZvJgwe@100hVd2TxgluAenK2uUt3XcDM5G2cHE1iKvGz1Z0sVg8lM2bpM1kuecmQQTRRN7kSXQVrycmrzHtW9CjA8aAxBsCPcKlhcFEIwrND1b0tKfH18CjXQ2QgRxYg9/mDjH9lo6Wz94KRTwDeeEFb3pBDqGO45kdTY6j79b/L@D7frVOdMP7MiZ0X5yMri6Rs "Python 3 – Try It Online") - test cases only
[Try it online!](https://tio.run/##RY9RaoQwEIbfe4ogAybaiLr4sja40OeeQC2IzWogJhIjyi6@9gA9Yi9is0Lbx/9n5ptvRr1wM/Vcyh0MKw3v@Fqfz4ov@OLvuGAYryGpUrwWhBBcvDDXvVdJUKXVqQASBWT3L8/eqx5GIfmHR3K4sTi/asObtscgkVAIhBpnS@7QMJB0GqWwHvVyccXQRK2elaXSovQxEDJoyrjeHACDYqVQtj6aHBSV/DcnjxyGbmNgYKK3xrY9n7C/@gEocpBv5L4YYTnt9WQ3Z5Xk/xlRpd2TUiiOPFDo@/MLAf6zbg/rweHbqDN6Hid3MZJcdbbfiLdte0zTLHs6pdkP "PowerShell – Try It Online") - .NET / [Try it online!](https://tio.run/##RY9RaoQwEIbfPUWQAZO1EaMtlLXBhT73BLoFsdk1EBOJEWUXX3uAHrEXsdmFto//z8w33wxmFnbshFIbWF5ZcRbLcb/XYsaHaMMlx3iJSZ3hpSSE4PKF@@69Zrs6q/MSSLIjW3R4CF9NP0glPkJSwIWnxclY0bQdBoWkRiD1MDlyhYaDouOgpAtpWMgThiZpzaQdVQ5lt4GYQ1Olx9UDMGheSe2O96YATZX4zeyW49hv9Bxs8ta4thMjjpZoB5rcyRdyna10gnZmdKu3YsV/RlQb/6SSWqAQNPr@/EKA/6zbu3Xv8W1ytmYaRn8xUUKfXbeScF03RlkasOcgS4Msfwzy7OkH "PowerShell – Try It Online") - test cases only
Java has variable-length lookbehind, with some limits, including that it's not right-to-left evaluated.
```
# tail = conjectured anti-divisor
(?=
( # \1 = tail
(x+)\2(x?) # \2 = floor(tail / 2); \3 = tail % 2
)
)
(?<= # Variable-length lookbehind
(?=
^ # Assert we're at the beginning of the string;
# tail = input number
\1* # tail %= \1
\2 # Assert tail ≥ \2; tail -= \2
\3? # optionally, tail -= \3
$ # Assert tail == 0
)
.* # Skip to beginning of string
)
```
# Regex (Perl / PCRE2 / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), ~~44~~ 43 bytes
```
(?=((x+)\2(x?)))((?<=(?=^\1*\2\3?$|(?4)).))
```
[Try it online!](https://tio.run/##RY5NTsMwEIX3nMKqrHqG/Kdkg@M6lcqWVXekRAWlYMmkwQ4iKIQlB@CIXCSYUonN03zvjd5MWxudTU9vhBpOBn2432lCI@5Q5OvVZrUcyf5ggFoR83zJcSCFFrbVqgMWMN@@3NnOxZUfJH6C9fOsbGby342dj5e0Qk7UHqxr35lC5ykOhb5JtsJpvOWnG@qEVOXiGLvJ83Cgdj5vjWq633LuXkn4EQlVISPfn1@M00awnvVU8ddHpWtw/BFREz3g8LfKCAuh8FxpUAROkY/jWFVX1@uqmkAKgN7DMoVeIiKAzIUzb8vkvEzLhaTvIC8QQ8RpioM0y84WafYD "Perl 5 – Try It Online") - Perl / [Try it online!](https://tio.run/##RY5NTsMwEIX3OYVVWbWH/NppJYTjOpXKlhU7UqKCUrBk0uAEERTCkgNwRC4STKnE5mm@90ZvpqmsWU5PbwhbgQZzuN8ZhGPhUGab9fV6NaL9wVLcykRkKwEDyo1sG6M7SkIStC93befiMghZwKB6nhX1TP27ifPhApcgkN7T1rXvbG4yDkNubthWOk224nRDnxDrTB5jN/k@DLidzxur6@63XLhXmDgiwjoi6PvziwhcS9KTHmvx@qhNRR1/xNjGDzD8rRJEIpr7rjTMQ6cgxnEsy8urTVlOVElKex8KTnsFAJSqTDrztmBnBS9Shd@pWgBEANPEQpZ47NzjicfThZfy5Q8 "Perl 5 – Try It Online") - test cases only
[Try it online!](https://tio.run/##fZLBbtswDIbveQrWEGqxcRw7XS5TBF@WDQWGdsh2qzvB9ZTYiywbslIE6HrdA@wR9yIZnXQb1sMOFiTy@8mfhLuqOyyyruqAOZAQTAOIoXN6o5zuTFFqHk7ji0ypqjBelW3T1Ua7nOco8tW0DyMI6VtTUG30AFivre@5Um@v3i@VwghSpJJUWIxqW6teex50pdPxfVFuvaNDmbqpfRBBMEkDFPAv5nS5c33d2v9jX0@phDKjdes4q2UimJFrstXzj5/eXF2jwEeo15yZ2947oy3dcJLeSRnkNkCC@909ZSgcJdEkxUGv951pv2geTIKIcEH6st1ZP2gXMxLdUgE6kzsxAjh2ts9vZhfymKfbeIzwSACQAeBnnG3lcctN4ctKFcZw5iLqPaxdF56H@zBiFiPWICIwfaJN0XulnaMueCblh9Xynbq@UcvV6mYlnqvT5KjLqh1mEkBrSAUMb2A2DuHn9x/hiSSruigrzhpyCEUP7AFPYAhh/HtBDyj@umZbOD8nM3@45WDlNeEv3Kmm3/Cj8unpxa9D4QPPJOf7MeYzvs9oPs6zhaTg5zy9yGf5Zca@8ewVYox4OCST2Xw@upzNfwE "PHP – Try It Online") - PCRE2 / [Try it online!](https://tio.run/##fZLPbtNAEMbvfoqptap3Gse1nSIhNitfCKhS1aLArS4r12xik/UfrTdVpNIrD8Aj8iJhnBQQPXDwanfm9818M3Jf9ft51lc9MAsS/HMfIuitXiure1OUmgfn0VmmVFUYp8qu6Wujbc5zFPnyfAhCCOhbUVCt9Qi0Trdu4Eq9u7xaKIUhJEglqbDw6rZWg3bc70uro/ui3DhLhzJ1Uzs/BH@a@CjgX8zqcmuHumv/j309pmLKeKvOclbLWDAjV2Rr4B8/vb28RoGPUK84M7eDs0a3dMNpcieln7c@Ejxs7ylD4TAOpwmOer3rTfdFc3/qh4QL0pfdtnWjdp6S6JYK0BnfCQ/g0Ll9frN2Lg95uk0mCI8EABkAfsLZRh623BSurFRhDGc2pN7j2nXheLALQtZiyBpEBKaPtCkGp7S11AVPpPywXLxX1zdqsVzeLMVzdZocdVl140wCaA2JgPENrI0C@Pn9R3AkyaouyoqzhhxCMQB7wCMYQBD9XtADir@u2QZOT8nMH24xWnlD@At3qhnW/KB8enrx61B4zzPJ@W6Cecp3Gc3HeTaXFPycJ2d5ms8y9o1nF4gR4n6fTJPYS157aeylswtvlr76BQ "PHP – Try It Online") - test cases only
Emulates variable-length lookbehind using recursion and fixed-length lookbehind.
# Regex (Perl / PCRE / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), ~~46~~ 45 bytes
```
(?=((x+)\2(x?)))((?<=(?=z|^\1*\2\3?$|(?4)).))
```
[Try it online!](https://tio.run/##RY5NTsMwEIX3nMKqrHqGJM1PyQbHdSqVLavuSIkKSsGSSYMdRCANSw7AEblIMKUSm6f53hu9maYyOh2f3gg1nPR6f7/VhIbcochWy/VyMZDd3gC1IuLZgmNPci1so1ULLGC@fbmzrYtLP4j9GKvnSVFP5L8bOR8vaYmcqB1Y1741uc4S7HN9E2@E02jDTzfUCanKxDF2k@dhT@102hhVt7/l3L0S8yMSqmaMfH9@MU5rwTrWUcVfH5WuwPFHSE34gP3fKiNsBrnnSoM8cIp8GIayvLpeleUIUgB0HhYJdBIRAWQmnPl@uC3i8yIp5pIeQF4gzhDHMQqSND2bJ@kP "Perl 5 – Try It Online") - Perl / [Try it online!](https://tio.run/##RY5NTsMwEIX3OYVVWbWH/DR2WgnhuEmlsmXFjhSroBQsmTQ4QQTSsOQAHJGLBFMqsXma773Rm6lLaxbj0xvCVqDe7O@3BuGZcCjT9ep6tRzQbm8pbmQs0qWAHuVGNrXRLSUhCZqXu6Z1sQpCFjAonydFNcn@3dj5cIEVCKR3tHHtW5ublEOfmxu2kU7jjTjd0CfEOpXH2E2@Dz1uptPa6qr9LRfuFSaOiLCOCPr@/CICV5J0pMNavD5qU1LHHzNsZw/Q/60SRCKa@640zEOnIIZhUOryaq3USDNJaedDwWmXAQClWSqd@X64LdhZwYskwweazQEigHFkIYs9du7x2OPJ3Ev44gc "Perl 5 – Try It Online") - test cases only
**[Try it online!](https://tio.run/##nZLNbtswDMfvfgpWEGqp8UecrpfIni9LhwBDO6S71Z3gOErsxZYN2SmCpbnuAfaIe5GMTtoN62GH@iBI5I/knzTnaZsfptd3ERiVLsA1C7BtMGFoyzd9thXGTd4ANRAB8Ql40Bi1kkY1ZZopZvveRSxlnpadzOqqKUplEpZwkcz81nawuANLNMqV6gHdKd21TMrr6aeJlNyBgGNKTCysQheyVR0jTWaUN0@zdWfwkGVRFR1xgLgB4QL@xYzKNqYtav1/7NvJNUSPtawNo0U0FLSMliirZXdfPkxvuOA7KJaMlvdtZ0ql8cbd4CGKSKIJR7jdzNGDZmfouAHv49W2KeuFYsQlDuIC47N6o7s@Nhxh0D0mwHP4ICyAY2X9/KY6jI5@vA0GHHYIAAoAdsboOjpOuUq7LJdpWTJqHKzdj12lHbO3tkM1d2jFOQeqTnSZtp1UxmAVfhZFn2eTj/LmVk5ms9uZeM6OnXOV5XXfkwAcQyCgfwPVng2/fvy0TyRKVWmWM1qhQkhboI/8BNpgey8DeuTir2q6hvNzFPOHm/RSxoi/UierdsWOkfv9q9VB84HFEWPbAU9GbBtjf4zFYYTG709fk@AiGSWXMX1i8TvOPc4Pb1tr6yjR1UDozozHbrAn7zP8kR7uulBblYG/aY0/L7Tfb/@L6zB0R1dX1uXo6jc "Bash – Try It Online") - PCRE1 / [Try it online!](https://tio.run/##nZLBbptAEIbvPMVktQq7MWDAqVQZKJc6kaUqqZzeQrrCeG2oYUELjqw6vvYB@oh9EXewk1bNoYdwWO3OfDPzzzDztM0P06u7CLRMF2DrBZgm6DA0xZs@0wjjJm@AaoiADAk40Gi5Elo2ZZpJZg6di1iIPC07kdVVU5RSJyzhQTIbtqaFxS1YolGsZA@oTqquZUJcTT9NhOAWeBxTYuLAKFQhWtkx0mRaOvM0W3caD1EWVdERC4jtER7Av5iW2Ua3Ra3@j307uVz0GMtaM1pEbkDLaImyWnb35eP0hgd8B8WS0fK@7XQpFd647T1EEUkU4Qi3mzl60Gy5lu3xPl5um7JeSEZsYiEeYHxWb1TXx4Y@Bt1jAjzdh8AAOFZWz2@qwujox9tgwGGHAKAAYGeMrqPjlKu0y3KRliWj2sLa/dhl2jFza1pUcYtWnHOg8kSXadsJqTVW4WdR9Hk2uRY3t2Iym93Ogufs2DmXWV73PQWAY/AC6N9AlWPCrx8/zROJUmWa5YxWqBDSFugjP4EmmM7LgB558Fc1XcP5OYr5w016KWPEX6kTVbtix8j9/tXqoPnA4oix7YAnPtvG2B9jcRih8fvT18S7SPxkFNMnFl9y7nB@eNtaG0eJtgJCd3o8tr09@ZDhj3Rw1wO5lRkMN60ezgs17Lf/xXXwbM81vPeG7xr@6NIY@e9@Aw "Bash – Try It Online")** - test cases only
[Try it online!](https://tio.run/##fZLBbtswDIbveQrWEGqxcZw4XS5TBF@WDQWGtsh2qzvB9ZTYiywbslIEa3vdA@wR@yIZnXQb1sMOFiTy@8mfhNuy3c/TtmyBOZAQjAOIoXV6rZxuTV5oHo7js1SpMjdeFU3dVka7jGcosuW4CyMI6VtRUK11D1ivre@4Uu8vPi6UwggSpJJUWAwqW6lOex60hdPxXV5svKNDmaqufBBBMEoCFPAv5nSxdV3V2P9j346pCWUGq8ZxVsmJYEauyFbHP31@d3GJAh@gWnFmbjrvjLZ0w1FyK2WQ2QAJ7rZ3lKFwNIlGCfZ6vWtN81XzYBREhAvSF83W@l47n5LohgrQObkVA4BDZ/vyZnYuD3m6DYcIDwQAGQB@wtlGHrZc574oVW4MZy6i3v3ade55uAsjZjFiNSIC00fa5J1X2jnqgidSXi8XH9TllVosl1dL8VKdJkddlE0/kwBaQyKgfwOzcQjPP36GR5Ks6rwoOavJIeQdsHs8giGE8e8F3aP465pt4PSUzPzhFr2Vt4S/cqfqbs0PyqenV78Ohfc8lZzvhphN@S6l@ThP55KC3x@/ZMlZNs3OU/bI0zeIMeJ@PxlNZ7PB@XT2Cw "PHP – Try It Online") - PCRE2 / [Try it online!](https://tio.run/##fZLPbptAEMbvPMUErcJODBhwKlVdIy51q0hVUrm9hXRF6NpQw4KWdWTlz7UP0Efsi7iDnbZqDj2w2p35fTPfjOirfj/P@qoHZiAFd@pCCL1Ra2lU3xSl4t40PMukrIrGyrJr@7pRJuc5inw5HTwfPPpWFJRrNQLaKm0HLuW7iw8LKdGHGKkkFRZOrWs5KMvdvjQqvC3KjTV0yKZua@v64AaxiwL@xYwqt2aoO/1/7NsxFVHGWXWGszqNBGvSFdka@KfPby8uUeAD1CvOmuvBmkZpumEQ36Spm2sXCR62t5ShsB/5QYyjXu36pvuquBu4PuGC9GW31XbUzhMSXVMBOqMb4QAcOuvnN9Pz9JCn22SC8EAAkAHgJ5xt0sOW28KWlSyahjPjU@9x7aqw3Nt5PtPosxYRgakj3RSDlcoY6oInafpxuXgvL6/kYrm8Worn6jQ5qrLqxpkE0BpiAeMbmA49@Pn9h3ckyaoqyoqzlhxCMQC7wyPogRf@XtAdir@u2QZOT8nMH24xWnlD@At3sh3W/KB8enrx61B4z7OU890E84TvMpqP82yeUvD@8Usen@VJPsvYI8/OEUPE/T4O4siJXztJ5CSzc2eWvPoF "PHP – Try It Online") - test cases only
Works around PCRE1 being picky about recursion it thinks can be endless.
Both Perl/PCRE versions work on the latest version of Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/), but not the one on TIO.
[Answer]
# [Desmos](https://desmos.com/calculator), 40 bytes
```
l=[1...n][2...]
f(n)=l[-2<2mod(n,l)-l<2]
```
[Try It On Desmos!](https://www.desmos.com/calculator/potn9bxfnr)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/nbmwdojm0p)
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~54~~ 53 bytes
*Huge thanks to JoKing for helping me out immensely for this answer, from debugging my errors and helping me find solutions to my problems*
*Also -1 byte thanks to JoKing*
```
N+X:-findall(M,(between(2,N,M),(N mod M*2-M)^2<4),X).
```
[Try it online!](https://tio.run/##DcxBCoMwEAXQqwRXk/pTdLStlSJ4gLgOiAWLWoRoggruvLrtO8Dzi7Puq9Z9PM8qNLkaxrlrrSUN@vTb3vczMSpoCarE5DqhL6y0fPMrlTDyeuZqar0d143qsikKKkODwS1Tu1FweKEKcfhjDlCXMI2UqGMwEqS44Y4HMjwRR4gzcAROUiR8a/7tDw "Prolog (SWI) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
Ḣ'?$%dεṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuKInPyQlZM614bmFIiwiIiwiMzI1Il0=)
-1 byte thanks to lyxal
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$14\log\_{256}(96)\approx\$ 11.524 bytes
```
Fpax'>2A-h%x#x
```
[Try it online!](https://fig.fly.dev/#WyJGcGF4Jz4yQS1oJXgjeCIsIjMyNSJd)
```
Fpax'>2A-h%x#x
ax - Range [1..input]
p - Remove the first item to make this [2..input]
F ' - Filter by (where the current item is x):
%x#x - Modulo x by the input
h - Multiply that by 2
A- - Get the absolute difference between x and that
>2 - Is it less than 2?
```
[Answer]
# Java 8, ~~69~~ 64 bytes
```
n->{for(int i=1;++i<n;)if((n%i*2-i)/2==0)System.out.println(i);}
```
-5 bytes thanks to *@Deadcode*
Outputs the results to STDOUT on separated lines.
[Try it online.](https://tio.run/##jZCxTsMwEIb3PsWpEpJNLiFxWigNYWFioAwdqw4mdZBLeolipwhVefbgpCkTSCyW7vz5u9@3l0fp73cfXVZIY@BFajpNADRZVecyU7DqS4BjqXeQMdcH4olrtRN3GCutzmAFBGlH/uMpL@uB0WmUeJ5@oITrnDG60tfC1/xGpGnI11/GqkNQNjaoakcXxDRP2i7plVXzVjjlaB7GHlwotrYOfd9sJT8HukyyytgnaRQsgdRnH3yzPUUoMMYZzvEW73CB9xiFGC1QhCjiGcZi3o4agF/STJ@pauwSpt7FPnz5L/q1sWf8h6IgY/95Ot61wz7b7hs)
**Explanation:**
```
n->{ // Method with integer parameter and no return-type
for(int i=1;++i<n;) // Loop `i` in the range (1,input]:
if((n%i*2-i) // If the input modulo `i`, doubled, minus `i`
/2 // integer-divided by 2
==0) // equals 0:
System.out.println(i);} // Print `i` with trailing newline
```
[Answer]
# [Haskell](https://www.haskell.org/), 38 bytes
```
h n=[m|m<-[2..n-1],abs(mod n m*2-m)<2]
```
[Try it online!](https://tio.run/##BcExDoAgDADAr3REI40wwxN8AWGo0QQirUQc/Xu9KzSuszXVAhITfxxs8ohiXV5oH4bvAwR49pan4LMyVYlMfTP9qfICQpmSQ3Rr1h8 "Haskell – Try It Online")
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 8 bytes (16 nibbles)
```
>>|,$~-!=$*%@$~~
```
```
| # filter
,$ # the list 1..input
~ # by the falsy results of
!= # the abxolute difference between
$ # each element and
* ~ # twice (2 is default value '~' for multiplication)
%@$ # modulo of input by each element
- ~ # minus 1 (1 is default value '~' for subtraction)
# (note that zero and negative numbers are falsy);
>> # finally remove the first element (always 1)
```
[](https://i.stack.imgur.com/b15Wu.png)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes
```
>.&;.%×₂;.-ȧ<2≤≜
```
A predicate that acts as a generator. [Try it online!](https://tio.run/##ATQAy/9icmFjaHlsb2cy/@KGsOKCgeG2oP8@LiY7LiXDl@KCgjsuLcinPDLiiaTiiZz//zMyNf9Y "Brachylog – Try It Online")
### Explanation
Brachylog's clunky arithmetic builtins make it less than ideal for this challenge. Maybe there's a better way to do it.
```
>.&;.%×₂;.-ȧ<2≤≜
>. The output is less than the input
& And the input
;.% Modulo the output
×₂ Times 2
;.- Difference with the output
ȧ Absolute value
<2 Is less than 2
≤ Which is less than or equal to
≜ A specific number
Which is the output
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 36 bytes
```
->n{(2..n).select{(n%_1*2-_1)**2<4}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsHiNNuYpaUlaboWN1V07fKqNYz09PI09YpTc1KTS6o18lTjDbWMdOMNNbW0jGxMamuharUy8wpKS4oVbBW0VGy4IBy93MSC6pq8Gi7OAoW06Dy9kvz4zFguqI4FN00NuYwUFLiMgdgEiE2B2AyIzYHYAogtgdjQAIgtFLiMgLSRsQmXsZEpRDcA)
[Answer]
# [Julia 1.0](http://julialang.org/), ~~30~~ 28 bytes
Golfing further Ashlin Harris's solution formula
```
~n=(N=2:n;@.N[-1<n%N-N/2<1])
```
[Try it online!](https://tio.run/##XZBNT4QwEIbP218xFxNIukpbyoduzR488wcI2ZAFI0q6xmLUC38dZ5riEg@TzvPOOx/p6@c4tOJ7WWZrosrIe/twvK3qvTjYm2pf3cmDaOKlAwNPw3mK2E4AgHmEuuFsJze5CrkkSAMoAr1WOHjOAqcE@abIQZNUrM2By6slIxbJXz3lkHupCCOxBSUOwp8hr84CNb9dqnS1eh/uzbCLhhNrv0JJvbmK9ARDcJAU6Ff4atR0yaFUNDuhYt6wmLGje7l8wSxKxtpxPE29m9zpvXWup39EKaphtmAMdLVt4PnyARYGC2/9j4u6GJo4jPjfvfwC "Julia 1.0 – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), ~~37~~ 30 bytes
```
~n=filter(m->-1<n%m-m/2<1,2:n)
```
[Try it online!](https://tio.run/##XZDLboMwEEXX8VfMJhJIRsE25lGFqIv@BUIRKkShBaeKqdpu@HU6Y5kGdTHynDt3HvLb59A34ntZZlNe@mHq7sEYnSJxNPsxGg/yKLh8MuHSQgkv/esUsJ0AgPIEVc3ZTm5y5XNJkHhQBHqtcHCcek4Isk2RgyYpX5s9Fw9LSiziv3rCIXNS7kdiC0ochDtDPpw5am67VMlqdT7cm2IXDSfWboWSenMV6TGG4CAp0K/w1ajpgkOhaHZMxaxmIWPP9nr7glkUjDXDcJ46O9nzR2NtR/@IUlDBbKAsoa1MDZfbHQz0Bt67Hxu0IdShH/G/e/kF "Julia 1.0 – Try It Online")
-7 bytes thanks to amelies: improve inequality, pass range directly to filter
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 13 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
╒╞g{_k\%∞-±2<
```
[Try it online.](https://tio.run/##y00syUjPz0n7///R1EmPps5Lr47PjlF91DFP99BGI5v//w25jLiMuUy4TLnMuMy5LLgsuQwNuAwtuIwMuIyMTbiMjUwB)
**Explanation:**
```
╒ # Push a list in the range [1, (implicit) input]
╞ # Remove the leading 1 to make the range [2,input]
g # Filter this list by,
{ # using an arbitrary large inner code-block:
# (implicitly push the filter index and value)
_ # Duplicate the value
k # Push the input-integer
\ # Swap so the value is at the top again
% # Modulo the input by the value
∞ # Double it
- # Subtract the two values from one another
± # Get the absolute value of this
2< # Check that this is smaller than 2 (so either 0 or 1)
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
NθIΦ…²θ‹↔⁻⊗﹪θιι²
```
[Try it online!](https://tio.run/##LcixCgIxDIDh3afomEAdvEm4SRRB8ER8g/YuaCG2tk18/XiD//AN//wKbS6BzS75o3LTd6QGFcfNvaUscAxd4JxY1vsI@UkweFfRuyv1DofYC6sQTClrh1PRyLTAVBblAtW7hPhnwLXRbLe37Zd/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ First input as a number
… Range from
² Literal integer `2` to
θ Input number
Φ Filtered where
θ Input number
﹪ Modulo
ι Current value
⊗ Doubled
↔⁻ Absolute difference with
ι Current value
‹ Is less than
² Literal integer `2`
I Vectorised cast to string
Implicitly print each value on its own line
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~58~~ 52 bytes
```
m;f(n){for(m=1;++m<n;)(n%m*2-m)/2||printf("%d ",m);}
```
[Try it online!](https://tio.run/##dVLbbqMwEH3vVxwhRbITo4Adk0Zu@lL1K5o@pGAatMWpAlKjpvx66WAuza60CJuZM@cM4xmn4Wuatm1pcub4JT@eWLmNzWJR3jnDmZuVcxmWfCm/vt5PhatzFswyBKLkpmnJR7kvHOO43ICeDqhtVVdPz9jiEgtIASWwEtACicBa4FZgIxBHtMiU9JWK4krqxvgk6WF/msOe321a26zPFAQCfsluU36Dt1cehYLuQd37Se@tsPYkaKwR92LcIlY92mFQCTQJyNbJmIycCHEMSW8CFUNH0BtsFEkjQtfBWOzRVfVQcnqw6R97GirenR/l7rx5oOVruvLVqKZ2g3VNK1xmzySLzGDeoSo@7TFnYx/4cgDmE2KwWHg298n6EUxjoGz9KDzl2UzRqzn6h4qruflL/NKJjTczMtVv9ONQvFmwF5o4sZZb6pNBGGYGzb@crOP40PhHBPyaN8LhfReY4JxdlzPcBqpiuhH/O9DOPQ4UUMpZtXN0NDvkam6a9jvN3/avVRt@/AA "C (gcc) – Try It Online")
*Saved 6 bytes thanks to the suggestion of porting Kevin's answer by [Neil](https://codegolf.stackexchange.com/users/17602/neil)!!!*
Port of [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s [Java answer](https://codegolf.stackexchange.com/a/250902/9481).
[Answer]
# [lin](https://github.com/molarmanful/lin), 33 bytes
```
.#n.n.<1drop".n.+_ %.~2/ -2^1<".#
```
[Try it here!](https://replit.com/@molarmanful/try-lin)
For testing purposes (use `-i` flag when running locally):
```
1 11 .-> 18 20 234 325 ( ;.$$ ).'
.#n.n.<1drop".n.+_ %.~2/ -2^1<".#
```
## Explanation
Prettified code:
```
.#n .n.< 1drop (.n.+_ %.~ 2/ - 2^ 1< ).#
```
Assuming input *n*.
* `.n.< 1drop` range [*n*, 2]
* `(...).#` filter...
+ `.n.+_ %.~ 2/ - 2^ 1<` equivalent to `(n%m - m/2)^2 < 1`
[Answer]
# [Perl 5](https://www.perl.org/) `-n`, 35 bytes
```
//;map{abs($'%$_*2-$_)<2&&say}2..$_
```
[Try it online!](https://tio.run/##K0gtyjH9/19f3zo3saA6MalYQ0VdVSVey0hXJV7TxkhNrTixstZIT08l/v9/YyPTf/kFJZn5ecX/dX1N9QwMDf7r5iUCAA "Perl 5 – Try It Online")
Uses a take on [xnor's](https://codegolf.stackexchange.com/a/250885/72767) formula in his python answer.
[Answer]
# x86 64-bit machine code, 26 bytes
```
89 F1 51 8D 44 71 01 99 01 C9 F7 F1 58 83 FA 02 77 01 AB 91 E2 EC FF 4F FC C3
```
[Try it online!](https://tio.run/##RZLNbtswEITP5FNsVRih/BMkbuqDFPeSXIsWRoEEsH1gSEpiIZEqKbkSDL961aXlOBftanbmWy0gUdeLXIhh4L4CBpuI0du8tG@8hIxmCansAZTo5qC8pi4hdesLcKKjpFQcFMfJdjl1Xs9QnN3vKRHyDyVcykssWKU@jE1ta3AcG1HVoCTOl5T85uAp8Y31kvqEdKLIL9ngLG3IIEMJeH75sXmGn782sHVSLx5wm1MNjSOIU6q6RjkD0VMEx4PVEjKmTQNTN4dQuzg9UfpZG1G2UsGjb6S2t8U3SsO04tqwmB4pOXthDXdz6ENJR8kp35bNdvl1tUclsw5YcN2naH7EusJmNospQQTJ2Gifh634XjtEZCya6CR6186IccM7vN@n0J8hHxGYaIxcDSOubUTBHbvZmZsgnOjVvjPfuSi0USCsVEkUxt3lDGnh@IG9W74iuF8z1hqvc6MkBOg0zuItXoKbTvC30KUKX/kJCd3Tl0C7EthEw1vfKB/vzOWq0zD8E1nJcz8sqtUDPvCvWqNflf8B "C++ (gcc) – Try It Online")
Takes \$n\$ in ESI and writes the anti-divisors as consecutive 32-bit integers, terminated with a 0, to an address given in RDI.
In assembly:
```
f: mov ecx, esi
r: push rcx
lea eax, [2*rsi+rcx+1]
cdq
add ecx, ecx
div ecx
pop rax
cmp edx, 2
ja s
stosd
s: xchg ecx, eax
loop r
dec DWORD PTR [rdi-4]
ret
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-f`](https://codegolf.meta.stackexchange.com/a/14339/), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÊÉ©AìøUaN%UÑ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWY&code=ysmpQez4VWFOJVXR&input=MzI1)
## Without Flags, 13 bytes
```
õ ÅkÈaU%XÑ ÊÉ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9SDFa8hhVSVY0SDKyQ&input=MzI1)
```
ÊÉ©AìøUaN%UÑ :Implicit filter of each U in range [0,input)
Ê :Factorial
É :Subtract 1
© :Logical AND with
A :10
ì :To digit array
ø :Contains?
Ua : Absolute difference of U and
N : Array of all inputs (singleton, in this case)
%U : Mod U
Ñ : Multiplied by 2
```
```
õ ÅkÈaU%XÑ ÊÉ :Implicit input of integer U
õ :Range [1,U]
Å :Remove first element
k :Remove elements that return true
È :When passed through the following function as X
a : Absolute difference with
U%XÑ : U mod X times 2
Ê : Factorial
É : Subtract 1
```
[Answer]
# [Go](https://go.dev), 119 bytes
```
func f(n int)(a[]int){for i:=2;i<n;i++{k:=n%i
if i%2<1&&k==i/2||i%2>0&&(k==(i-1)/2||k==(i+1)/2){a=append(a,i)}}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XdBLasMwEAZguvUpRCBGwklryXHiPNQzdF-6EKkVBteyETZdOD5JN6bQQ_Qo7Wk6SrLpbEbSx4j5pY_PUzN9t-ZYmVPJagMugrptfMdmtu5mX31nl8XPu-3dkVnuGLhOcPP8EtbBNp7BTqs9HNwekmSodtrNIQLLYK4OMo4rreFBnc94fEzjmOOZw1KKYJd9EvZiMNq0beleuVmAGMfIl13v3Xgd_3uXX-aHdFywIcJk908eI7w5LheWSyH-mUJTxDK0jNgKbUUsR8uJrdHWxDZoG2IFWkFsi7YlJtMQOqUarkt6X4VeRXtVFrJjpa9UIT9W9NvvTdN1_QM)
] |
[Question]
[
Your task is to create a program or function that takes, as input, a natural number (`n`) between 1 and 25 (inclusive) and prints an isometric representation of a slide and ladder with `n` number of rungs.
### Ladder and slide specifications
The ladder is always oriented on the left and the slide on the right. We're viewing it from the ladder side, so part of the slide is obscured at the top three levels. The rungs are represented by four dashes (`----`) and the sides of the ladder and slide by slashes (`/` and `\`). The following is a diagram to represent the patterns of spaces needed for a slide with five rungs.
```
Slide Blank space count
/----/\ 1234/----/\
/----/ \ 123/----/12\
/----/ \ 12/----/1234\
/----/ \ \ 1/----/1\1234\
/----/ \ \ /----/123\1234\
```
### Examples
```
>>1
/----/\
>>3
/----/\
/----/ \
/----/ \
>>4
/----/\
/----/ \
/----/ \
/----/ \ \
>>10
/----/\
/----/ \
/----/ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
```
This is code-golf, so the answer with the lowest byte count wins.
Note: trailing white space is acceptable in the output, as long as it doesn't exceed the length of the line.
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~81~~ ~~72~~ 52 bytes
Byte count assumes ISO 8859-1 encoding.
```
.+
$* /\ \
^.
+` /(.+)$
$&¶$%`/ $1
/.{5}
/----/
```
[Try it online!](http://retina.tryitonline.net/#code=LisKJCogL1wgICAgXApeLgoKK2AgLyguKykkCiQmwrYkJWAvICAkMQovLns1fQovLS0tLS8&input=MTU)
### Explanation
The program consists of four stages, all of which are regex substitutions (with a couple of Retina-specific features). I'll use input `5` as an example for the explanation.
**Stage 1**
```
.+
$* /\ \
```
This turns the input `n` into `n` spaces followed by `/\ \` which will become the top of the ladder/slide:
```
/\ \
```
For now, we'll just show the slide in full and represent the ladder only by its left-hand `/`.
**Stage 2**
```
^.
```
Unfortunately, `n` spaces are one more than we need, so we remove the first character again. We've now got:
```
/\ \
```
**Stage 3**
```
+` /(.+)$
$&¶$%`/ $1
```
Time to expand the complete structure. Knowing *where* the top is, is sufficient to build the entire thing, because we can simply extend it one line at a time, moving the ladder and the slide apart by two spaces.
The `+` tells Retina to repeat this stage in a loop until the output stops changing (in this case, because the regex stops matching). As for the regex itself, we simply match the `/` on the last line and everything after it and we also match one space in front of it, which means this can no longer match once `/` has reached the first column.
Here's what we replace this with:
```
$& The match itself. We don't want to remove the line we already have.
¶ A linefeed, because we want to append a new line.
$%` This is a very recent addition to Retina: it's like the normal $` but
is bounded by linefeeds. That means this inserts everything in front
of the match which is on the same line. In particular this one space
less than the indentation of the matched line, hence we are shifting
the / one column left.
/ A literal /, representing the left edge of the ladder.
> < Two spaces, so that we can shift the slide one column right.
$1 Capturing group 1 which contains the slide and its separation from
the ladder.
```
So at each iteration, this adds one line to the string, until we end up with this:
```
/\ \
/ \ \
/ \ \
/ \ \
/ \ \
```
**Stage 4**
```
/.{5}
/----/
```
All that's left is getting the ladder right. That's really simple, we just match the `/` and the next 5 characters and insert the correct ladder representation, thereby overriding the slide or spaces that are already there:
```
/----/\
/----/ \
/----/ \
/----/ \ \
/----/ \ \
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~38, 37, 36, 34, 33, 32, 31, 30~~ 29 bytes
```
Àé r\2é/4é-òhYpX$2P^ò3GEòjlr\
```
[Try it online!](http://v.tryitonline.net/#code=w4DDqSByXDLDqS80w6ktw7JoWXBYJDJQXsOyM0dFw7JqbHJc&input=&args=NQ)
~~I *might* catch up with Osabie. One byte shorter than Osabie. `\o/` Tied with 2sable!~~ One byte shorter!
In other news, this is definitely the longest strikethrough header I've ever made.
Explanation:
```
Àé "Insert 'arg1' spaces
r\ "Turn the last one into a '\'
2é/ "Insert 2 '/'
4é- "Insert 4 '-'
ò ò "Recursivly:
h " Move one to the left
Yp " Duplicate this line
X " Delete one space from the left
$2P " Paste two spaces at the end of this line
^ " Move back to the beginning of this line.
```
This will run until an error occurs, which thanks to the "move left" command ('h'), will be 'arg1' times.
Now we just need to add the inner leg
```
3GE "Move to the second slash of line 3
ò ò "Recursively: (The second 'ò' is implicit)
jl " Move down and to the right
r\ " And replace the character under the cursor with a '\'
```
[Non-competing version (28 bytes)](http://v.tryitonline.net/#code=w4DDqSBzL8K0LS9cG8OyaFlwWCQyUF7DsjNHRcOyamxyXA&input=&args=NQ)
[Answer]
## Pyth, ~~39~~ 35 bytes
```
VQ++*dt-QN"/----/">+*+ddN"\ \\"5
```
Explanation:
```
VQ # Interate over 0 -> Q-1 (Q is the input)
+ # Concatenate the 2 halfs of the slide
+ # Concatenate the whitespace block and the ladder
*d # Multiply d (whitespace) by this number \/
t-QN # Calculate the amount of spaces before : input - step of the iterarion -1
"/----/" # Ladder
> 5 # Remove the first 5 chars from the string generated in the following lines
+ # Concatenate the whitespace block and the slide
*+ddN # Multiply "+dd" (2 whitespace) by the step of the iterarion to generate the space between the ladder and the slide
"\ \\" # Slide
```
[Test here](https://pyth.herokuapp.com/?code=VQ%2B%2B*dt-QN%22%2F----%2F%22%3E%2B*%2BddN%22%5C++++%5C%5C%225&input=10&debug=0)
[Answer]
# [2sable](https://github.com/Adriandmen/2sable), ~~40~~ ~~36~~ ~~32~~ 30 bytes
Hmmm, V is coming awfully close...
```
F¹N-<ð×…/--«ðð«N×…\ ««5F¦}¶
```
Uses the **CP-1252** encoding. [Try a 05AB1E compatible version!](http://05ab1e.tryitonline.net/#code=RsK5Ti08w7DDl-KApi8tLcOCwqvDsMOwwqtOw5figKZcICDDgsKrwqs1RsKmfcK2Sj8&input=MTA).
[Answer]
## PowerShell v2+, ~~99~~ ~~90~~ 82 bytes
```
param($n)1..$n|%{" "*($n-$_)+"/----/"+-join(" "*($_+$i++)+"\ \")[6..(6+$_+$i)]}
```
Takes input `$n`, starts a loop from `1` to `$n` with `|%{...}`. Each iteration, we're constructing a string. We start with the appropriate number of spaces `" "*($n-$_)` and the ladder `"/----/"`.
To that, we add another string that's been sliced `[...]` and `-join`ed back together. The second string is the slide, and we assume that the whole slide is always visible. It's the number of spaces before the slide would start `" "*($_+$i++)`, followed by the slide itself `"\ \"`. This is sliced by a range calculated out to be the part of the "spaces plus slide" that's partially hidden by the ladder.
### Examples
```
PS C:\Tools\Scripts\golfing> .\draw-a-ladder-and-slide.ps1 7
/----/\
/----/ \
/----/ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
PS C:\Tools\Scripts\golfing> .\draw-a-ladder-and-slide.ps1 15
/----/\
/----/ \
/----/ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
```
[Answer]
# Python 2 - ~~79~~ ~~76~~ 75 bytes
```
x=input()
for i in range(x):print(x-i)*' '+'/----/'+(i*' '+'\\ \\')[5:]
```
Thanks to Hubert Grzeskowiak for "disqualifying" me since making my program print actually saved 3 bytes!
Thanks also to Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ for saving 1 more byte!
[Answer]
# Vim, 71 keystrokes
This is such a stupid way of doing it, but it's a bit of fun. Input is given as a text file with a single line containing an integer. This is likely quite golfable, but it'll do for now (*edit: switched style of control characters upon request*):
```
A@qyyPgg<c-v><c-v>GkI <c-v><esc>G$i <c-v><esc><esc>
Tq"qDI/----/\^[lD@"ddh<c-v>god:%s/ \\/\\ \\<cr>
```
`<c-v>`, `<esc>` and `<cr>` are all individual keystrokes; ctrl+v, escape, and carriage return (enter) respectively. For a simple to digest version with the correct literals, here is the file `ladder.keys` run though `xxd`:
```
00000000: 4140 7179 7950 6767 1616 476b 4920 161b [[email protected]](/cdn-cgi/l/email-protection) ..
00000010: 4724 6920 2016 1b1b 5471 2271 4449 2f2d G$i ...Tq"qDI/-
00000020: 2d2d 2d2f 5c1b 6c44 4022 6464 6816 676f ---/\.lD@"ddh.go
00000030: 643a 2573 2f20 2020 2020 5c5c 2f5c 5c20 d:%s/ \\/\\
00000040: 2020 205c 5c0d 0d0a \\...
```
To try it out (assuming a nix with the appropriate tools) take the above, run it through `xxd -r` and put in the file `ladder.keys`. Create a file `ladder.txt` with an integer in it. Then do:
```
vim -s ladder.keys -u NONE ladder.txt
```
[Answer]
# bash, 61
```
for((;i<$1;)){ printf "%$[$1+i]s\ \^M%$[$1-++i]s/----/\n";}
```
where `^M` is a literal carriage return
```
$ ./ladder 1
/----/\
$ ./ladder 4
/----/\
/----/ \
/----/ \
/----/ \ \
$ ./ladder 10
/----/\
/----/ \
/----/ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
/----/ \ \
```
[Answer]
## JavaScript (ES6), 79 bytes
```
f=
n=>" ".repeat(n).replace(/./g,"$'/$`$`\\ \\\n").replace(/\/...../g,"/----/")
;
```
```
<input type=number min=0 oninput=o.textContent=f(this.value)><pre id=o>
```
Works by taking a string of `n` spaces, then doing some exotic substitution to get the slide with a support, then replacing the support with a ladder.
[Answer]
# Ruby, 61 bytes
```
->n{n.times{|i|puts"%*s\\ \\\r%*s----/"% [n+i,"",n-i,?/]}}
```
### Ungolfed
```
->(num_rows) {
num_rows.times {|row_idx|
puts "%*s\\ \\\r%*s----/" % [ num_rows + row_idx, "", num_rows - row_idx, "/" ]
}
}
```
I could save two bytes by using `'%*s\ \^M%*s----/'` (where `^M` is a literal carriage return) for the format string, but then Ruby prints the warning "`warning: encountered \r in middle of line, treated as a mere space`". ¯\\_(ツ)\_/¯
### Previous solution (64 bytes)
```
->n{n.times{|i|puts" "*(n+i)+"\\ \\\r"+" "*(n-i-1)+"/----/"}}
```
[Answer]
## Batch, 194 bytes
```
@echo off
for /l %%i in (1,1,%1)do call:l %1 %%i
exit/b
:l
set s=\ \
for /l %%j in (1,1,%2)do call set s= %%s%%
set s=/----/%s:~7%
for /l %%j in (%2,1,%1)do call set s= %%s%%
echo%s%
```
Turned out to be reasonably straightforward: indent the slide, remove the first 7 characters, indent the ladder, remove the leading space. This last bit does involve a little trickery though!
[Answer]
# Java, 116 bytes
```
c->{for(int i=0;i<c;i++)System.out.format("%"+(5+c-i)+"s%"+(i<3?i*2+1:2*(i-2))+"s%5s\n","/----/","\\",i<3?"":"\\");};
```
Unfortunately, you can't [easily] duplicate strings in Java, so I end up abusing the format function.
[Answer]
**Scala, 95 bytes**
```
def l(n:Int)=for(i<- 0 to n-1){println(" "*(n-i-1)+"/----/"+(" "*i+"\\ \\").substring(5))}
```
[Answer]
## Haskell, 81 bytes
```
a n=[1..n]>>" "
f n=[1..n]>>=(\i->a(n-i)++"/----/"++drop 7(a(2*i)++"\\ \\\n"))
```
[Answer]
# [eacal](https://github.com/ConorOBrien-Foxx/eacal), noncompeting, 386 bytes
```
init .
define @ curry push .
define ~ curry exec .--func
alias $ strap
alias ' string
set n set m cast number arg number 0
set s empty string
label l
@ get n
set n ~ dec
@ space
@ get n
$ ~ repeat
$ ' /----/
@ space
@ get m
@ get n
@ ~ sub
@ ~ dec
@ number 2
@ ~ mul
$ ~ repeat
$ ' \
$ newline
@ get n
@ number 0
if ~ more
goto l
@ $
@ regex gm ' ( {4})(?=.$)
@ ' \$1
print ~ replace
```
~~I have officially made the most verbose language possible.~~ I made the comment in jest and in sarcasm. Please calm down. Instructions on how to run in the github repo linked in the header.
## Ungolfed
```
init .
set n set m cast number arg number 0
set s empty string
label loop
push . get n
set n exec .--func dec
push . space
push . get n
strap exec .--func repeat
strap string /----/
push . space
push . get m
push . get n
push . exec .--func sub
push . exec .--func dec
push . number 2
push . exec .--func mul
strap exec .--func repeat
strap string \
strap newline
push . get n
push . number 0
if exec .--func more
goto loop
push . strap
push . regex gm string ( {4})(?=.$)
push . string \$1
print exec .--func replace
```
] |
[Question]
[
This is inspired by an [05AB1E answer](https://codegolf.stackexchange.com/a/114226/76162) by [Magic Octupus Urn](https://codegolf.stackexchange.com/users/59376/magic-octopus-urn).
Given two arguments, a positive integer and a string/list of characters:
1. Translate the number to base-n, where n is the length of the string.
2. For each character, replace every appearance of the index of that character in the base-n number with that character.
3. Print or return the new string.
### Examples:
```
Input:
2740, ["|","_"]
2740 -> 101010110100 in base 2
-> Replace 0s with "|" and 1s with "_"
Output: _|_|_|__|_||
Input:
698911, ["c","h","a","o"]
698911 -> 2222220133 in base 4
-> Replace 0s with "c", 1s with "h", 2s with "a", and 3s with "o"
Output -> "aaaaaachoo"
Input:
1928149325670647244912100789213626616560861130859431492905908574660758972167966, [" ","\n","|","_","-"]
Output:
__ __
| |_| |
___| |___
- - - -
- - - - - - -
- - - - - - - -
_______________
Input: 3446503265645381015412, [':', '\n', '.', '_', '=', ' ', ')', '(', ',']
Output:
_===_
(.,.)
( : )
( : )
```
Rules:
* [IO is flexible](https://codegolf.meta.stackexchange.com/q/2447/76162).
+ You can take the number in any base, as long as it is consistent between inputs
+ The list of characters has to be 0-indexed though, where 0 is the first character and n-1 is the last
* Possible characters can be any printable ASCII, along with whitespace such as tabs and newlines
* The given list of characters will have a length in the range `2-10` inclusive. That is, the smallest base is binary and the largest is decimal (*no pesky letters here*)
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/76162) are forbidden
* Feel free to answer even if your language can't handle the larger test cases.
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code for each language wins. (*I know all you golfing languages have one byte built-ins ready to go* ;)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
gв¹sèJ
```
Since it was inspired by an 05AB1E answer, an answer given in 05AB1E seems fitting. :)
-1 byte thanks to *@Emigna* by removing the foreach and doing this implicitly.
[Try it online](https://tio.run/##MzBNTDJM/f8//cKmskM7Kw@vsP//X0lJyYpLL95WQVNDB8jmMjYxMTM1MDYyMzUzMTW2MDQwNDUxNAIA) or [verify all test cases](https://tio.run/##Fcw9CsJAEAXgfk8RUimozMzOryDpvEZQEe3sBCHeRxsLCw8QL@CN1g08eDx4fCC7PR4Lb8dnOf3e1/F1@z66ch8/XU0Z@kTGkA7n3SVpeCCmtm2bNPTL2gmDHDkyiRooGzEHEgKYB2FWUkUVBVfEDC7Bud4pQKIuY1Uw8TBCtVCd7HVa9ZtmPltMfmZWgUzVYMmOgMJIfw).
**Explanation:**
```
g # `l`: Take the length of the first (string) input
в # And then take the second input in base `l`
# For each digit `y` of this base-converted number:
¹sè # Push the `y`'th character of the first input
J # Join everything together (and output implicitly)
```
[Answer]
# [Python 3](https://docs.python.org/3.5/), 49 bytes
Cannot comment yet, so I post the Python 2 answer adapted to Python 3.5.
```
f=lambda n,s:n and f(n//len(s),s)+s[n%len(s)]or''
```
[Answer]
# Java 8, ~~72~~ 50 bytes
```
a->n->n.toString(a.length).chars().map(c->a[c-48])
```
-22 bytes thanks to *@OlivierGrégoire* by returning an `IntStream` instead of printing directly.
[Try it online](https://tio.run/##fVFNa@MwEL3nVwyGBQlsIcmybG23gbZsYQ97yjEJQavaiVNHNpbSJbT97amcuPSDUtBhNG/mvXkzW/2gk@3d/dE02jn4q2v7OAFwXvvawDagZO/rhlR7a3zdWnI7Br/MRvfzZfxtzQnbab8h1/X6j/Xluuzfdzjfl3pHAjI7RdMpVHAJR51MbXjEtyFf2zXSpCnt2m8wGWQdwoG1QyaZ6rlJRLHEx4tJGLvb/2vC2OP0D219B7vgCJ1Z5kvQeHAH4EvnUfS0imKIeC5ohC/e5YNGOyBSFYqxjxgs7NMqGVCmeMGESnkmcypFzoVQjDNK80JxlkouJZOZpIVkLKVFpkQayrmimQq/XEhJ86xQOWcyV1J@lPm5sGR1CRjFg1QqhMxoygOdyNKCUZYJxs8dz5O3e50cnwjOjsHFMEZ2dF4R3XXNAbmw3Juwy6u@1weE8Zi25X/46mrIhpKq7X9rsxn2Pjs4X@5Iu/ekC/y@QtEPE8UGjy4@441F0cK@Tvx8fAE).
**Explanation:**
```
a->n-> // Method with char-array and BigInteger parameters
n.toString(a.length) // Convert the input-number to Base `amount_of_characters`
.chars() // Loop over it's digits (as characters)
.map(c->a[c // Convert each character to the `i`'th character of the input
-48]) // by first converting the digit-character to index-integer `i`
```
[Answer]
# Japt, 2 bytes
Can take the second input as an array or a string. Fails the last 2 test cases as the numbers exceed JavaScript's max integer. Replace `s` with `ì` to output an array of characters instead.
```
sV
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=c1Y=&input=Njk4OTExClsiYyIsImgiLCJhIiwibyJd)
[Answer]
# [Haskell](https://www.haskell.org/), ~~40~~ 39 bytes
```
0!_=[]
n!l=cycle l!!n:div n(length l)!l
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/30Ax3jY6litPMcc2uTI5J1UhR1Exzyols0whTyMnNS@9JEMhR1Mx539uYmaegq1CQWlJcEmRgoqCmaWFpaGholJyRmK@0n8A "Haskell – Try It Online")
As Haskell's `Int` type is limited to `9223372036854775807`, this fails for larger numbers.
-1 byte thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni).
## Ungolfed
```
(!) :: Int -> [Char] -> [Char]
0 ! _ = [] -- If the number is 0, we reached the end. Base case: empty string
n ! l =
let newN = (n `div` length l) in -- divide n by the base
cycle l!!n -- return the char encoded by the LSD ...
: newN!l -- ... prepended to the rest of the output (computed recursively)
```
[Try it online!](https://tio.run/##dZA7a8MwFIV3/4qj0MGG2iRLaQzpkHYJlC4ZQ2hs@SYWkSUjyQn@9e61WujSatDjPr57jtrKX0nraUpFhrLEzgTkLzi8tpU7/t6SZAmBT2xwOAJ5jt0ZoSWYoavJQXksH3EnOKpkS03MkWkKbCtPkLyVoK4PI3xwylwSwzjNuATQFGDo/sGv1ODUqNuJY@YSWugMyiAO5LBqeCDqMdJrZnIzIEepCVqIufCvxc2OwuBM7JNsh6VJ27DMH9b7/g1FUSDyyihGaOB/3lzcO@rZ4mzWRoojH2C//8UOoR8CUmk7PrnGkRycVzfSYzZ1FbvagDP74PCAp/XzerUSC9ZmF9MX "Haskell – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
YA
```
[Try it online!](https://tio.run/##y00syfn/P9Lx/38jcxMDLvWaeHUA "MATL – Try It Online")
Inputs are a number and a string.
Fails for numbers exceeding `2^53`, because of floating-point precision.
### Explanation
What do `YA` know, a builtin (base conversion with specified target symbols).
[Answer]
# JavaScript (ES6), 48 bytes
Takes input in currying syntax `(c)(n)`, where **c** is a list of characters and **n** is an integer.
Safe only for **n < 253**.
```
c=>n=>n.toString(c.length).replace(/./g,i=>c[i])
```
[Try it online!](https://tio.run/##XYpBCsIwEADvPiOnLNStFVF7SD/hsRQJa5pGwm5JQ0/@PcarMHOaedvdbpTCmo8sL1dmU8gMXMEsj5wCe00YHfu8ACa3RktOt9j6JpiBxjBBIeFNosMoXs96VB/VqKeaQJ9vlxPA4b9T7UvVVuX3Xft733UA5Qs "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 99 bytes
### *With support for big integers*
Takes input in currying syntax `(c)(a)`, where **c** is a list of characters and **a** is a list of decimal digits (as integers).
```
c=>g=(a,p=0,b=c.length,r=0)=>1/a[p]?g(a.map((d,i)=>(r=d+r*10,d=r/b|0,r%=b,d|i-p||p++,d)),p)+c[r]:''
```
[Try it online!](https://tio.run/##hY7LTsMwEEX3fAWKhGITN/X4MY4rufwBPxAi5DyaFrVJ5BZW@fdgXl2w6eJYmpHP3PvmP/y5CYfpshrGtlt2bmnctnfEs8lxVrsmP3ZDf9mz4Dh1W1j7cqqeeuLzk58IadkhbklwbRYegbPWhXU9cxYeXM3a@bCa5nnKMtZSyiaaNWWoNmm6NONwHo9dfhx7siNlMicseU0qSso8z1NhFE@r74Dn91PdBUrp3X@lico@4iPjVUVbWICb8n2UXob4/ASzZHW9AFYUoKwUGg1HZYRSFgRwbgorQKJABNTICwSQvNBWyfhdWK5tnIxC5EYX1ghAYxFvVtn8Vcl/q7jIVz8aIRF2rSaVQs2liPFKywI4aAXif8LyCQ "JavaScript (Node.js) – Try It Online")
[Answer]
# x86 32-bit machine code (32-bit integers): 17 bytes.
(also see other versions below, including 16 bytes for 32-bit or 64-bit, with a DF=1 calling convention.)
Caller passes args in registers, including a pointer to the *end* of an output buffer (like [my C answer](https://codegolf.stackexchange.com/questions/166708/ascii-art-uncompression-from-a-base-n-number/166831#166831); see it for justification and explanation of the algorithm.) [glibc's internal `_itoa` does this](https://code.woboq.org/userspace/glibc/sysdeps/generic/_itoa.h.html#39), so it's not just contrived for code-golf. The arg-passing registers are close to x86-64 System V, except we have an arg in EAX instead of EDX.
On return, EDI points to the first byte of a 0-terminated C string in the output buffer. The usual return-value register is EAX/RAX, but in assembly language you can use whatever calling convention is convenient for a function. (`xchg eax,edi` at the end would add 1 byte).
The caller can calculate an explicit length if it wants, from `buffer_end - edi`. But I don't think we can justify omitting the terminator unless the function actually returns both start+end pointers or pointer+length. That would save 3 bytes in this version, but I don't think it's justifiable.
* EAX = n = number to decode. (For `idiv`. The other args aren't implicit operands.)
* EDI = end of output buffer (64-bit version still uses `dec edi`, so must be in the low 4GiB)
* ESI/RSI = lookup table, aka LUT. not clobbered.
* ECX = length of table = base. not clobbered.
`nasm -felf32 ascii-compress-base.asm -l /dev/stdout | cut -b -30,$((30+10))-` (Hand edited to shrink comments, line numbering is weird.)
```
32-bit: 17 bytes ; 64-bit: 18 bytes
; same source assembles as 32 or 64-bit
3 %ifidn __OUTPUT_FORMAT__, elf32
5 %define rdi edi
6 address %define rsi esi
11 machine %endif
14 code %define DEF(funcname) funcname: global funcname
16 bytes
22 ;;; returns: pointer in RDI to the start of a 0-terminated string
24 ;;; clobbers:; EDX (tmp remainder)
25 DEF(ascii_compress_nostring)
27 00000000 C60700 mov BYTE [rdi], 0
28 .loop: ; do{
29 00000003 99 cdq ; 1 byte shorter than xor edx,edx / div
30 00000004 F7F9 idiv ecx ; edx=n%B eax=n/B
31
32 00000006 8A1416 mov dl, [rsi + rdx] ; dl = LUT[n%B]
33 00000009 4F dec edi ; --output ; 2B in x86-64
34 0000000A 8817 mov [rdi], dl ; *output = dl
35
36 0000000C 85C0 test eax,eax ; div/idiv don't write flags in practice, and the manual says they're undefined.
37 0000000E 75F3 jnz .loop ; }while(n);
38
39 00000010 C3 ret
0x11 bytes = 17
40 00000011 11 .size: db $ - .start
```
It's surprising that the simplest version with basically no speed/size tradeoffs is the smallest, but `std`/`cld` cost 2 bytes to use `stosb` to go in descending order and still follow the common DF=0 calling convention. (And STOS decrements *after* storing, leaving the pointer pointing one byte too low on loop exit, costing us extra bytes to work around.)
# Versions:
I came up with 4 significantly different implementation tricks (using simple `mov` load/store (above), using `lea`/`movsb` (neat but not optimal), using `xchg`/`xlatb`/`stosb`/`xchg`, and one that enters the loop with an overlapping-instruction hack. See code below). The last needs a trailing `0` in the lookup table to copy as the output string terminator, so I'm counting that as +1 byte. Depending on 32/64-bit (1-byte `inc` or not), and whether we can assume the caller sets DF=1 (`stosb` descending) or whatever, different versions are (tied for) shortest.
DF=1 to store in descending order makes it a win to xchg / stosb / xchg, but the caller often won't want that; It feels like offloading work to the caller in a hard-to-justify way. (Unlike custom arg-passing and return-value registers, which typically don't cost an asm caller any extra work.) But in 64-bit code, `cld` / `scasb` works as `inc rdi`, avoiding truncating the output pointer to 32-bit, so it's sometimes inconvenient to preserve DF=1 in 64-bit-clean functions. . (Pointers to static code/data are 32-bit in x86-64 non-PIE executables on Linux, and always in the Linux x32 ABI, so an x86-64 version using 32-bit pointers is usable in some cases.) Anyway, this interaction makes it interesting to look at different combinations of requirements.
* **IA32 with a DF=0 on entry/exit calling convention: 17B (`nostring`)**.
* IA32: **16B (with a DF=1 convention: `stosb_edx_arg` or `skew`)**; or with incoming DF=dontcare, leaving it set: **16+1B `stosb_decode_overlap`** or 17B `stosb_edx_arg`
* **x86-64 with 64-bit pointers, and a DF=0 on entry/exit calling convention: 17+1 bytes (`stosb_decode_overlap`)**, 18B (`stosb_edx_arg` or `skew`)
* x86-64 with 64-bit pointers, other DF handling: **16B (DF=1 `skew`)**, 17B (`nostring` with DF=1, using `scasb` instead of `dec`). 18B (`stosb_edx_arg` preserving DF=1 with 3-byte `inc rdi`).
Or if we allow returning a pointer to 1 byte before the string, **15B** (`stosb_edx_arg` without the `inc` at the end). **All set to call again and expand another string into the buffer with different base / table...** But that would make more sense if we didn't store a terminating `0` either, and you might put the function body inside a loop so that's really a separate problem.
* x86-64 with 32-bit output pointer, DF=0 calling convention: no improvement over 64-bit output pointer, but 18B (`nostring`) ties now.
* x86-64 with 32-bit output pointer: no improvement over the best 64-bit pointer versions, so 16B (DF=1 `skew`). Or to set DF=1 and leave it, 17B for `skew` with `std` but not `cld`. Or 17+1B for `stosb_decode_overlap` with `inc edi` at the end instead of `cld`/`scasb`.
---
# With a DF=1 calling convention: 16 bytes (IA32 or x86-64)
Requires DF=1 on input, leaves it set. [Barely plausible](https://codegolf.stackexchange.com/questions/132981/tips-for-golfing-in-x86-x64-machine-code/165020#165020), at least on a per-function basis. Does the same thing as the above version, but with xchg to get the remainder in/out of AL before/after XLATB (table lookup with R/EBX as base) and STOSB (`*output-- = al`).
With a normal DF=0 on entry/exit convention, **the `std` / `cld`/`scasb` version is 18 bytes for 32 and 64-bit code, and is 64-bit clean** (works with a 64-bit output pointer).
Note that the input args are in different registers, including RBX for the table (for `xlatb`). Also note that this loop starts by storing AL, and ends with the last char not stored yet (hence the `mov` at the end). So the loop is "skewed" relative to the others, hence the name.
```
;DF=1 version. Uncomment std/cld for DF=0
;32-bit and 64-bit: 16B
157 DEF(ascii_compress_skew)
158 ;;; inputs
159 ;; O in RDI = end of output buffer
160 ;; I in RBX = lookup table for xlatb
161 ;; n in EDX = number to decode
162 ;; B in ECX = length of table = modulus
163 ;;; returns: pointer in RDI to the start of a 0-terminated string
164 ;;; clobbers:; EDX=0, EAX=last char
165 .start:
166 ; std
167 00000060 31C0 xor eax,eax
168 .loop: ; do{
169 00000062 AA stosb
170 00000063 92 xchg eax, edx
171
172 00000064 99 cdq ; 1 byte shorter than xor edx,edx / div
173 00000065 F7F9 idiv ecx ; edx=n%B eax=n/B
174
175 00000067 92 xchg eax, edx ; eax=n%B edx=n/B
176 00000068 D7 xlatb ; al = byte [rbx + al]
177
178 00000069 85D2 test edx,edx
179 0000006B 75F5 jnz .loop ; }while(n = n/B);
180
181 0000006D 8807 mov [rdi], al ; stosb would move RDI away
182 ; cld
183 0000006F C3 ret
184 00000070 10 .size: db $ - .start
```
A similar non-skewed version overshoots EDI/RDI and then fixes it up.
```
; 32-bit DF=1: 16B 64-bit: 17B (or 18B for DF=0)
70 DEF(ascii_compress_stosb_edx_arg) ; x86-64 SysV arg passing, but returns in RDI
71 ;; O in RDI = end of output buffer
72 ;; I in RBX = lookup table for xlatb
73 ;; n in EDX = number to decode
74 ;; B in ECX = length of table
75 ;;; clobbers EAX,EDX, preserves DF
76 ; 32-bit mode: a DF=1 convention would save 2B (use inc edi instead of cld/scasb)
77 ; 32-bit mode: call-clobbered DF would save 1B (still need STD, but INC EDI saves 1)
79 .start:
80 00000040 31C0 xor eax,eax
81 ; std
82 00000042 AA stosb
83 .loop:
84 00000043 92 xchg eax, edx
85 00000044 99 cdq
86 00000045 F7F9 idiv ecx ; edx=n%B eax=n/B
87
88 00000047 92 xchg eax, edx ; eax=n%B edx=n/B
89 00000048 D7 xlatb ; al = byte [rbx + al]
90 00000049 AA stosb ; *output-- = al
91
92 0000004A 85D2 test edx,edx
93 0000004C 75F5 jnz .loop
94
95 0000004E 47 inc edi
96 ;; cld
97 ;; scasb ; rdi++
98 0000004F C3 ret
99 00000050 10 .size: db $ - .start
16 bytes for the 32-bit DF=1 version
```
I tried an alternate version of this with `lea esi, [rbx+rdx]` / `movsb` as the inner loop body. (RSI is reset every iteration, but RDI decrements). But it can't use xor-zero / stos for the terminator, so it's 1 byte larger. (And it's not 64-bit clean for the lookup table without a REX prefix on the LEA.)
---
# LUT with explicit length *and* a 0 terminator: 16+1 bytes (32-bit)
This version sets DF=1 and leaves it that way. I'm counting the extra LUT byte required as part of the total byte count.
The cool trick here is **having the same bytes decode two different ways**. We fall into the middle of the loop with remainder = base and quotient= input number, and copy the 0 terminator into place.
On the first time through the function, the first 3 bytes of the loop are consumed as the high bytes of a disp32 for an LEA. That LEA copies the base (modulus) to EDX, `idiv` produces the remainder for later iterations.
The 2nd byte of `idiv ebp` is `FD`, which is the opcode for the `std` instruction that this function needs to work. (This was a lucky discovery. I had been looking at this with `div` earlier, which distinguishes itself from `idiv` using the `/r` bits in ModRM. The 2nd byte of `div epb` decodes as `cmc`, which is harmless but not helpful. But with `idiv ebp` can we actually remove the `std` from the top of the function.)
Note the input registers are difference once again: EBP for the base.
```
103 DEF(ascii_compress_stosb_decode_overlap)
104 ;;; inputs
105 ;; n in EAX = number to decode
106 ;; O in RDI = end of output buffer
107 ;; I in RBX = lookup table, 0-terminated. (first iter copies LUT[base] as output terminator)
108 ;; B in EBP = base = length of table
109 ;;; returns: pointer in RDI to the start of a 0-terminated string
110 ;;; clobbers: EDX (=0), EAX, DF
111 ;; Or a DF=1 convention allows idiv ecx (STC). Or we could put xchg after stos and not run IDIV's modRM
112 .start:
117 ;2nd byte of div ebx = repz. edx=repnz.
118 ; div ebp = cmc. ecx=int1 = icebp (hardware-debug trap)
119 ;2nd byte of idiv ebp = std = 0xfd. ecx=stc
125
126 ;lea edx, [dword 0 + ebp]
127 00000040 8D9500 db 0x8d, 0x95, 0 ; opcode, modrm, 0 for lea edx, [rbp+disp32]. low byte = 0 so DL = BPL+0 = base
128 ; skips xchg, cdq, and idiv.
129 ; decode starts with the 2nd byte of idiv ebp, which decodes as the STD we need
130 .loop:
131 00000043 92 xchg eax, edx
132 00000044 99 cdq
133 00000045 F7FD idiv ebp ; edx=n%B eax=n/B;
134 ;; on loop entry, 2nd byte of idiv ebp runs as STD. n in EAX, like after idiv. base in edx (fake remainder)
135
136 00000047 92 xchg eax, edx ; eax=n%B edx=n/B
137 00000048 D7 xlatb ; al = byte [rbx + al]
138 .do_stos:
139 00000049 AA stosb ; *output-- = al
140
141 0000004A 85D2 test edx,edx
142 0000004C 75F5 jnz .loop
143
144 %ifidn __OUTPUT_FORMAT__, elf32
145 0000004E 47 inc edi ; saves a byte in 32-bit. Makes DF call-clobbered instead of normal DF=0
146 %else
147 cld
148 scasb ; rdi++
149 %endif
150
151 0000004F C3 ret
152 00000050 10 .size: db $ - .start
153 00000051 01 db 1 ; +1 because we require an extra LUT byte
# 16+1 bytes for a 32-bit version.
# 17+1 bytes for a 64-bit version that ends with DF=0
```
This overlapping decode trick can also be used with `cmp eax, imm32`: it only takes 1 byte to effectively jump forward 4 bytes, only clobbering flags. (This is terrible for performance on CPUs that mark instruction boundaries in L1i cache, BTW.)
But here, we're using 3 bytes to copy a register and jump into the loop. That would normally take 2+2 (mov + jmp), and would let us jump into the loop right before the STOS instead of before the XLATB. But then we'd need a separate STD, and it wouldn't be very interesting.
[Try it online! (with a `_start` caller that uses `sys_write` on the result)](https://tio.run/##zVlrbxpLEv3OryhFGxliwGB7vYkRH0Ls3IuUxJHt3M0q10I9Mw10PA8yPWMgu/vbs6eqZ2Bw8ONubrRryfIMVFfX45yq6rayVkdeuGzFykbfvj01YxPENBqdfbh8/@Fy9Prs/O3Ly9GoSTocH@zXeoPh5QXh4WmgxybWlAaGdGDW7xbvtvKuFqTVYv3u4d2rvPt49yvvAd4DvOs4MONajfDT69EkTDwV0jM1znT6jLKpplB5OiSTUZRA0mhLxpKKSS9mOjWRjjMsGGuV5aleqT85fV0f57Efq0g3qHw6LvWXH9RqLKisb8zIT6JZqq0dxYnNUhNPGrUeLDLxLM9saV@Mdzp9@ZH6FOeRp1PKEgq0nwS6FDljkfOTIUTgGyVjSvIMOsjLx2MsoHqUW7xplguTOaLcKNcOZe0Frw2T5DqfUaa8cKV6ILu/4t1DHU@yKWt3EmxqqhGD2B7TLDEx4lcaAhM5kDZTacYrFHVa@Doyscp0QM5b0eAjPHDKHvfo9ORjP1Qw1J@qtMk@9zu1tug4Fnui5Ib/0OAfl6f0Cfi4ahIkYPfsmLb89ChI/ikr/eDLdoEuecsMhk6TlM3Ppkgz0SJJGSpN/NIeBeZGlBg88F@AalMJxPrx0wF/pfC0N6htmBuETVgL9O4yBq@cYSEi@ubD5Sesu6r1WMxmgYu69ZX15BFpFg2gwXeWt1pFkov3LAXCEF1LR4ctD@AtUmI3bCmihu3Xmp4Vivr42FkOLaIX7jSZYvz8Of4q8hLuyup/z6cm1PW40XNrAQkkzXwF9AOP/kItcims1VABkC4VmklM3aNtPICV1mv8ecjfBPng4y2Qiwd1HykHNVS8hO2TJpZm1Hgk/kv0splN4LdJ7IhOb5CGk9dUt4qfuqLlYF/SgpoCHo5proHOeCdrPAzxItIwdCej3OpxHoZs7CxUvgZmjRQoKFSpdiJgFy386YS9mk91qlFkrYtaCTNBGd1BG@AOez@WWn@QHW08vg7VxFIeu@IZtB12Qq0c3q1hyniLXSFMr4xdCWlK4nBZxmubFwD1WauFpA0dwX4U1H54R9C4WrtY3Yv9sue8fDP85d0d4LdZYr0RojVS6aTBqhfPj1pHh3SxtL8htROaKcuZdRAtSm9BgD@LEGNUvkWoMm@ThCf3kfCHOOKUVMlxjG5x8rrfJT@Jb9BrTRLTPMlDtA2wifYHVAcHJO5cF01sM63EVWRpTzLU2KbVV2HYKoxBDwI9K1pB0brNTBhSrPHlxeWJi/Lw3St4P6SCyKXiosQKl@cGHt8C6LHzYHMHgCIFyqAbtAyYyFTq36gB3H1uAxWsdTvHSSYmwkjOVRkq@MacX4esWAVIFSx2qrkmFKplGPrvGFzbqmwtr1bygZMXcYbVNqoq7oXShpny6JIqvFqbv5XcDtTCcHW7ZxV9e12ozM2euCblluapwU5jqT9A1sX1MlTXuifzSqTiHNZYtbT8vtxB4azUqO8qRjFEMhRdl76vWPS4TOzuPtAkH1EiHPtGyY1OQzX7OTPjA4WiuTHPoaDXxyZF/A0PUX4y45mZpxtPWX1FypbKyzVJeqvDDt4zBiD98wdNqWb1fqchI2aTVkUIQUm31B5QK5lbxw6mRv3i8lUDLkMYLdcXhrNvrt/yKUKAKxxntmIuo@HJ8Lcdy/Xi/O0G13urqa9gfZX0vc8RmlI7SCTxBdj2oVbIAm/FJFCmz8PA17bjGx7jr@2iUFV@nPAMwn7ktx3P@whmF58Yn7@pY@4O5hgiWoH28glGSobXd7uatSYuS33qLMaMAdZnM7@wE7juLDwl40uvHG2YnGSi6GBfykRmyeHmQJRbyTkfwIRbsgpqoOfwebPUVihkbenRYRPK0CLJXpuZ5VTJ@rlaMjI4arBrgOREZjLNGIhzDRnEuvVVp8keAlyjO396Rc2SCq/C/oCVhgmaDV46PHPxHEKfcbjCMVEaqIiaaBYa32StAskOhWUCiyFHQvEpmCdpAI92OaCu6jmPnwfs8Yu/uvGvR8mM2dtkCKURf8jVn1U5Pak32w2MnR3sX8FjPuNJtpAbsgmdvMHT4P2b3U7BsgIdLmoM3CZ3gaZgltNbwsfVDEcv65zj@G5DQ5MwM/nTYonlWLModzvQhFvWH29E3uyBRtQrmZvEAhrUsixdNrcayEQUs2ASYlTWyCaF5loXxBXfyRUifM19pD5GewC/ImXQCVC3fn7vKxl//MNdcFvLeugiRjIQf3/w7BVDkHL2rk40iNdbhEgOPLdmrMpsFidpBGdRXDuYhsvDyAOtsnpVc2fLXNU3D6d5XruLQ732Fc9Xc87cl9yk2t3foKJxXxIPHuq113q@rbf@f03Y@AQVIQ9z@3PuYzruHmZ1LbNqXhtXFrd612OOjW403VoK/nc3Nj@V1Y/j55ZDKANjb1AeRW/d5KiwJKeUCXfggIyWvCt0Qpeqkml30uibkGAkL40aZl6Vh3zKDCu7Sq8BSKsf@fhIoBhXjvCpHODl46vq0R4243MQBmTZffH8qrCdy/UKYoxZBqvjE6rLxVSc8lDNY02LolSzSAlhPvp0uAc4/GN0cD7zPEB33LVWfdhIN6cPipkZhBHbYgYsWh9qESxCi9ly3qpesyHnTQ5BdQtukHwbXdLmHgu3Tfm1u6VRp4S5cmGOThAE/HmlMFXYTX8vJ1Y5k3IMpboJWG5UmGsuFROdFdfdGGMy2phiiquruYqz1bVNzxnGVbIIYDrhLPK1iHM498rk7xcxlmNYvUHjNImQWlRFXSlRMMKfav9absnQrXBu85M0zWeY5HSUpMvaHQNb6fIKMovF5a@no4vL8@G7X37vLHiPmH7vsCDvcthxk@dd@kxbt@@HXftxHbXClvKcWOHUYec2HA/d/qN35yMJ1QaW8H236NNcTTAtdtbFgZd3V2WZhfm/IqU0y5YVY2lHemGyeqdR3l@8HAwr3blAM3M5fYzN3Xts5tw7q7CtwwttQKHb5JyMisbF6hsCg9raFeioxo733D9wPX/Em7Izo0maoNk6XO3lNt3DLBPmgd5TNtrLYwPyjY4O29MttqxD4rQgMKsRxGpfToPtNAlUpmrFv3XcCdXdbKMwwtEvOe3/DbGRb45lLHnyr9GTIqwrmaMXz190uxtSr359efak3FCahZRVEedCvf7HDJ@t2Nwn6/P0k/JWyFs@qp6sHaq64ypzzf05psxEfOvV6fCOO4sdFySkyGKhKxeRjH6AjlZ2ueYt08Rxsb2iltMGxon9tW//AQ "Assembly (nasm, x64, Linux) – Try It Online")
It's best for debugging to run it under `strace`, or hexdump the output, so you can see verify that there's a `\0` terminator in the right place and so on. But you can see this actually work, and produce `AAAAAACHOO` for an input of
```
num equ 698911
table: db "CHAO"
%endif
tablen equ $ - table
db 0 ; "terminator" needed by ascii_compress_stosb_decode_overlap
```
(Actually `xxAAAAAACHOO\0x\0\0...`, because we're dumping from 2 bytes earlier in the buffer out to a fixed length. So we can see that the function wrote the bytes it was supposed to and *didn't* step on any bytes it shouldn't have. The start-pointer passed to the function was the 2nd-last `x` character, which was followed by zeros.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
ṙ1ṃ@
```
[Try it online!](https://tio.run/##DYoxCgJRDAWvIr92IclPXpLOe6hYbSOLvWDnKTzKHmdPElPMwMA81217Vx37j4/9e6mq6ziN87i9Wp/m0SzjXpwSrDnF4AR1UU0WJvJI4QkBGAYKME8KS529S5JllytAbpEuDE/gDw "Jelly – Try It Online")
`ṃ` is literally a built-in for this. The other three bytes account for Jelly's one-based indexing.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~49~~ 48 bytes
-1 byte thanks to Jo King
```
f=lambda n,s:n and f(n/len(s),s)+s[n%len(s)]or''
```
[Try it online!](https://tio.run/##PZDdasMwDIXv@xQmMJJQb7P8I9uBPMCu9gCpKena0ELnhDi9GOzdMzmFXegDHdnSkaaf5TpGua5De@@/T@eeRZ6ayPp4ZkMV3@@XWKWap3qfuvjyzMI4l@W6XNKS2q6TVgvOuuK34MWxCIF36J0HyNoXaVeKnmLcauClA@2VNGgFaiu19iBBCOu8BIUSEdCgcAighDNeK3ouvTCeMqsRhTXOWwloPWIewqj5IRKeDnjxuk1SWqMRSlI3bZQDAUaDpA9lU3JWHmLmW8Yxo81gGXVGlcHLEMJuGOd8FHaLbNu52bFpvsWFFR9xeiwNzafyv/j5WDaVLO3pgvl02d76Bw "Python 2 – Try It Online")
### Alternative version (won't finish for large numbers), ~~45~~ 43 bytes
-2 bytes thanks to Jo King
```
f=lambda n,s:s*n and f(n/len(s),s)+(s*n)[n]
```
[Try it online!](https://tio.run/##PY9LasMwEIb3OYUQhNiN2mr0GEkGH6CrHsA2xm1iEkjHxlIWhdzdlbPobv4Hw//Nv@kykVrXsb4NP1@ngZGIVXwhNtCJjQW9385UxFLE8lhku2yoW9M5plg3jXJGCsYfPe9Eg8EHgCy/L8O0GdoYtFIrtGis9iDBGlCCHaqW3vqalYU45BoE5cEErSw6icYpYwIokNL5oECjQoT8QnoE0NLbYHSuqyBtyMoZROmsD04BuoCYB7CWHv0r77rdOC0bD7sSe26udmxerpQY/6D5nirGBQm@X/g@/ief9/SMWuLHzL@B83yvfw "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~3~~ 1 bytes
```
⍘~~θη~~
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMpsTg1uATITNfQ1LT@/z/a2MTEzNTA2MjM1MzE1NjC0MDQ1MTQSEchWt1KXUdBPSYPROqBiHgQYQsiFECEJojQABE66rGx/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 2 bytes thanks to @ASCII-only. Previous version before the builtin was added, 8 bytes:
```
⭆↨θLη§ηι
```
[Try it online!](https://tio.run/##FcXBCsIwDADQX8mtCURZ13aI4kFvgoLgcQ4ps6yDUXUW8e@rubzXRz/3Dz@Vcp7HlPGS/w0n/8S9fwd8MRxDGnLESMSwy4d0D1@MDCMRbUppjbWNq0zduMY6s9KVdlbXDK1aKwZ1TeJSuAlbAQQSUGDVdWXxmX4 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
η Second input
L Length
θ First input
↨ Base convert to array
⭆ Map over values and join
η Second input
ι Current value
§ Index into list
Implicitly print result
```
[Answer]
# [D](https://dlang.org/), 112 bytes
```
import std.conv;C u(C,I)(I n,C b){C t;for(I l=b.length;n;n/=l)t=to!C(n%l)~t;foreach(ref c;t)c=b[c-48];return t;}
```
[Try it online!](https://tio.run/##Vc7BagIxEAbgs/sUo1CYgXVbi1gl7CknoUdvIiWbjd1ATCQ7sQe7ffVtKi3Uw1zm//hn2nG0p3OIDD23lQ7@IiQklOWWcAu@lNDQVQKLY4h54eqmcsa/cye88I@1I645TCX6B0dfN2WU7jCaI2jBpOtmr@fL9UFEwyn6XDSMKnEA1etOxR53hDvQBFf4E2GKP9H@QKhJwFAUl2BbOCnrMbti8u/hPDaIYvIRLRvnMeHzy/IpvZYw@3ybVb9HiO7IarPeLBY3lONwx4bxGw "D – Try It Online")
This is a port of [HatsuPointerKun's C++ answer](https://codegolf.stackexchange.com/a/166852/55550)
The calling style is `u(ulong(n), to!(char[])(b))`, where `n` and `b` are the left and right arguments
## D specific stuff
Sadly, we need to import `std.conv` to do any type conversions above **very** basic type conversion.
Using the golfy template system, and giving the function the required types (which is why calling it is not just `u(n,b)`), we can shorten occurrences of `char[]` and `ulong` to `1` byte each, when inside f the function.
D initializes our types for us, so `C t;` is short for `C t=cast(char[])([])`
`to!C` converts the integer `n%l` to a character array (using codepoints), and `~` is concatenation
`foreach(ref c;t)` is like C++'s `for(... : ...)` loop, but a little longer. `ref` is like `&`, it treats `c` as copied-by-reference (i.e., we can modify `t`). Luckily, D infers the type of `c` without *any* keyword denoting type.
[Answer]
## C++, ~~150~~ 144 bytes, `uint64` input
-6 bytes thanks to Zacharý
```
#include<string>
using s=std::string;s u(uint64_t n,s b){s t;for(;n;n/=b.size())t=std::to_string(n%b.size())+t;for(auto&a:t)a=b[a-48];return t;}
```
Using a variable to store the size would increase the bytecount by 1
To call the function :
```
u(2740, "|_")
```
First the number, second is the string ( char array )
Test cases :
```
std::cout << u(2740, "|_") << '\n' << u(698911, "chao") << '\n';
return 0;
```
[Answer]
# Twig, 66 bytes
Created a `macro` that must be `import`ed into a template.
```
{%macro d(n,c)%}{%for N in n|split%}{{c[N]}}{%endfor%}{%endmacro%}
```
---
## Values expected:
For the first arguments (`n`):
* number
* string
For the second argument (`c`):
* Array of numbers
* Array of strings
---
## How to use:
* Create a `.twig` file
* Add `{% import 'file.twig' as uncompress %}`
* Call the macro `uncompress.d()`
## Ungolfed (non-functional):
```
{% macro d(numbers, chars) %}
{% for number in numbers|split %}
{{ chars[number] }}
{% endfor %}
{% endmacro %}
```
---
---
You can test this code on: <https://twigfiddle.com/54a0i9>
[Answer]
# Pyth, ~~9~~ ~~8~~ 7 bytes
```
s@LQjEl
```
Saved a byte thanks to hakr14 and another thanks to Mr. Xcoder.
[Try it here](http://pyth.herokuapp.com/?code=s%40LQjEl&input=%5B%22+%22%2C%22%5Cn%22%2C%22%7C%22%2C%22_%22%2C%22-%22%5D%0A1928149325670647244912100789213626616560861130859431492905908574660758972167966&debug=0)
### Explanation
```
s@LQjEl
jElQ Convert the second input (the number) to the appropriate base.
@LQ Look up each digit in the list of strings.
s Add them all together.
```
[Answer]
# C89, limited-range signed `int n`, ~~64~~ 53 bytes
* changelog: take a `char **out` and modify it, instead of taking and returning a `char *`
Takes the number as an `int`, the lookup table as an array + length.
Output is written into a `char *outbuf`. Caller passes (by reference) a pointer to the end of the buffer. Function modifies that pointer to point to the first byte of the string on return.
```
g(n,I,B,O)char*I,**O;{for(**O=0;n;n/=B)*--*O=I[n%B];}
```
This is valid C89, and works correctly even with optimization enabled. i.e. doesn't depend on gcc `-O0` behaviour when falling off the end of a non-void function or have any other UB.
Passing a pointer to the end of a buffer is normal for an optimized int->string function, such as [glibc's internal `_itoa`](https://code.woboq.org/userspace/glibc/sysdeps/generic/_itoa.h.html#39). See [this answer](https://stackoverflow.com/questions/13166064/how-do-i-print-an-integer-in-assembly-level-programming-without-printf-from-the/46301894#46301894) for a detailed explanation of breaking an integer into digits with a div / mod loop like we're doing here, in C as well as x86-64 asm. If the base is a power of 2, you can shift/mask to extract digits MSD first, but otherwise the only good option is least-significant-digit first (with modulo).
[Try it online!](https://tio.run/##lVRNb5tAEL3zK0aJ0gCF2E6rKJi6B/fQ@uRjD6kVLbDgVWGX7i5J3Mh/vXQG8FdaNSoHaz0fb2bevN00LNK0bQtXBotgHiy9dM20vwh8fxk/50q7eJiNYxnL0Wzu@WGIfxd38mK@irftPM67vNOs@cxYXXLpLrz4FQTHGflQTIE/1aVIhQ0xrbBrKJX63tRgWVLyAAZjzYzhGTADTCq75hqYLhzwIZ@CqP4FQCmATQlJ8SPHORc5jOHkw0YaWagyxxIPXBuhZBeKdiEtSJgB1gTZVAnXVJWsc7Qa8ZODymGB54QZTj6iA3yyCFk3tu/j4PCXO89INZYCcJLdfMkGNM@nFI0fdsGl1Zsp1Aor4tBWdY2UzFiMtV3tASVp8pzrq6PUJ2Gn8DI1F/oolyzjEN2VkMxiAz1R2N8pbMfcgxLZnqf7v6rGeXaoej8pISiD06JjR/PnU5Ibww26gaNh84hr5fDIyQpDMpalzAPWOD7d2773bpah6WGKIZl0uJOgs0tFLe4xB0USXK1V1qQcJv0MDLcDVlSoo4ynmle4D0I@qrXjd9cprbdHjp2tc85lJnKHVCfTssk4fDA2E@pq/fHUVIrkpY1mIJtDaquYkC4dUC1pMDCM54e7lTew3km1qbA@s0q4nXOy8uKjlfSKnEHnu17FzsGHPeOu76JoFcOfH1LDUtuwchAEyvRHI3pCQBi8c8V94koPsfHoYhveiA79a3Cg/bXPhygivEQUqH3VFGtaHy7h5n2YCEsz8oJuv8y6CwfXV/@B/ZVDpuSlxV@8HhZ3g1qsNU8FqTEm2ec4JmlQyXLTCdGIQmIUkUtPAgFVvDLcuj1jAVw@XQbYtvdCmSgMgxKn9jOeNEVxJMn9BenFgjBvo9t4eJt60RKHQf9QBPAGg3CR57ykN2bYNRJLT1D/3naBw66Lk1z0HgF0cqSgGuVlc/fswnyTZwH0/s6juW20xJvmbNv2JrqNJpP20xe2/JXmJStMGy7ftSFKdpbeRr8B "C (gcc) – Try It Online"). Ungolfed version:
```
/* int n = the number
* int B = size of I = base
* char I[] = input table
* char **O = input/output arg passed by ref:
* on entry: pointer to the last byte of output buffer.
* on exit: pointer to the first byte of the 0-terminated string in output buffer
*/
void ungolfed_g(n,I,B,O)char*I,**O;
{
char *outpos = *O; /* Golfed version uses *O everywhere we use outpos */
*outpos = 0; /* terminate the output string */
for(;n;n/=B)
*--outpos = I[n%B]; /* produce 1 char at a time, decrementing the output pointer */
*O = outpos;
}
```
In this explicit-length version, the input is a `char table[]` which does *not* need a terminating 0 byte, because we never treat it as a string. It could be an `int table[]` for all we care. C doesn't have containers that know their own length, so pointer+length is the normal way to pass an array with a size. So we choose that instead of needing to `strlen`.
The maximum buffer size is approximately `sizeof(int)*CHAR_BIT + 1`, so it's small and compile-time constant. (We use this much space with base=2 and all the bits set to 1.) e.g. 33 bytes for 32 bit integers, including the `0` terminator.
---
# C89, signed `int`, table as an implicit-length C string, 65 bytes
```
B;f(n,I,O)char*I,**O;{B=strlen(I);for(**O=0;n;n/=B)*--*O=I[n%B];}
```
This is the same thing but the input is an implicit-length string so we have to find the length ourselves.
[Answer]
# [Bash + core utilities](https://www.gnu.org/software/bash/), 49 bytes
```
dc -e`echo -en $2|wc -c`o$1p|tr -dc 0-9|tr 0-9 $2
```
[Try it online!](https://tio.run/##FYpLDsIwDAWvkkW3kWzHeY7vUolCqNRViwCJTe@emtW8zzzun22MZ095Xda@HcE9TXL@YunLMfHr/L5TDoGy/2Mg/jEGuzRWL1JhBDVRdRYmsubCBQIwKqiBuVCrriV0caoezRQgq81NGObAmElp3s9bvgA "Bash – Try It Online")
# Comments/explanation
This takes command-line arguments as input (the number in base 10, then a single string with the list of characters) and outputs to stdout. Special characters like space, newline, etc may be entered in octal notation (for example, `\040` for a space), or `\n` for a newline, `\t` for tab, or any other escape sequence that `echo -e` and `tr` interpret identically.
A lot of the bytes here are to handle special characters and larger test cases. If I only have to handle non-terrible characters and the numbers are small (for example, the first test case), the following 24 bytes will do it:
```
dc -e${#2}o$1p|tr 0-9 $2
```
This uses parameter expansion `${#2}` to get the number of characters in the string, builds a dc program to do the base conversion, and then sends the converted number through `tr`.
This won't handle newlines or spaces or tabs, though, so to deal with escape sequences without affecting the base, I do a character count `wc -c` after interpreting the escapes with `echo -en`. This expands the program to 38 bytes:
```
dc -e`echo -en $2|wc -c`o$1p|tr 0-9 $2
```
Unfortunately, dc has an annoying "feature" where if it's outputting a large number, it will line wrap it with a slash+newline sequence, so the larger test cases have this extra output. To remove it, I pipe dc's output through `tr -dc 0-9` to remove non-numeric characters. And there we are.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~14 13~~ 12 bytes
```
⊢⌷⍨∘⊂⊥⍣¯1⍨∘≢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXECWWxCQZWhkYf7/UdeiRz3bH/WueNQx41FX06OupY96Fx9abwgV6Vz0Pw2o9FFvH0R/V/Oh9caP2iYCecFBzkAyxMMz@L@RuYmBQpoCkOsV7O@nrlQTr6TOZWZpYWloiCycnJGYD5QwNjExMzUwNjIzNTMxNbYwNDA0NTE0QlZoFZOnF2@roKmho6QOAA "APL (Dyalog Unicode) – Try It Online")
Infix tacit function; can't handle the largest test case because of floating point representation.
Saved ~~1~~ 2 bytes thanks to @Adám!
~~13 bytes added for the headers: `⎕IO←0`: **I**ndex **O**rigin = 0 and `⎕FR←1287`: **F**loat **R**epresentation = 128 bits.~~ (I'd forgotten that this [doesn't apply.](https://codegolf.meta.stackexchange.com/a/14232/43319))
### How?
```
⊢⌷⍨∘⊂⊥⍣¯1⍨∘≢ ⍝ Tacit function, infix.
≢ ⍝ Tally (number of elements in) the right argument.
⍨∘ ⍝ Then swap the arguments of
⊥⍣¯1 ⍝ Base conversion (to base ≢<r_arg>)
⊂ ⍝ Enclose (convert to an array)
⍨∘ ⍝ Then swap the arguments of
⌷ ⍝ Index
⊢ ⍝ (Into) the right argument.
```
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 17 bytes
```
{_[_2&ToBase!#_]}
```
[Try it online!](https://tio.run/##RY7BTsMwDIbvfYoQ0AQioNhJnGTSpAluHBCH3UoUVaVlk1A30d7GePXisMMs@ZNs//bvZpqadtvNvViuxHzMdcbFZv/UjN3VdU6n@bXrPsb65nBoP1NVvX3vhmnTjdMzC8b6@NXf59P6Zb8b1ovfXom6Ehw1equ5kD9SySxTUuc2xRAByqDlwZaz4dxfBBAxgI0GHXlN1qO1ERC09iEiGEIiIEc6EIDRwUVrWI5Ru8iVt0TauxA9AvlIVJwEO7wPjPMvSj5c7Iy15LRBPmmdCaDBWcCytZRK/K8J@ViQC1YFouCu4LZA8bUqpfkP "Attache – Try It Online")
## Explanation
```
{_[_2&ToBase!#_]}
{ } ?? anonymous lambda; input: _ = dictionary, _2 = encoded
_2&ToBase ?? convert _2 to base
!#_ ?? ... Size[_]
_[ ] ?? and take those members from the dictionary
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte
```
τ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLPhCIsIiIsIlwiOlxcbi5fPSApKCxcIlxuMzQ0NjUwMzI2NTY0NTM4MTAxNTQxMiJd)
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
ÅвJ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cOuFTV7//yspKVlx6cXbKmhq6ADZXMYmJmamBsZGZqZmJqbGFoYGhqYmhkYA "05AB1E – Try It Online")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 7 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
L┬{╵⁸@p
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjJDJXUyNTJDJXVGRjVCJXUyNTc1JXUyMDc4JXVGRjIwJXVGRjUw,i=JTVCJTIyJTIwJTIyJTJDJTIyJTVDbiUyMiUyQyUyMiU3QyUyMiUyQyUyMl8lMjIlMkMlMjItJTIyJTVEJTBBMTkyODE0OTMyNTY3MDY0NzI0NDkxMjEwMDc4OTIxMzYyNjYxNjU2MDg2MTEzMDg1OTQzMTQ5MjkwNTkwODU3NDY2MDc1ODk3MjE2Nzk2Ng__,v=3)
Straight forward implementation:
```
L┬{╵⁸@p
L get the length of the input (popping the item)
┬ base decode the other input
{ for each number there
╵ increment
⁸@ in the 1st input get that numbered item
p and output that
```
The input character set can be a string too as long as it doesn't contain a newline, because Canvas doesn't have a newline character & automatically converts it to a 2D object.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~6~~ 5 bytes
```
n%|E@
```
[Run and debug it](https://staxlang.xyz/#c=n%25%7CE%40&i=%22%7C_%22+2740%0A%22chao%22+698911%0A%22+%5Cn%7C_-%22+1928149325670647244912100789213626616560861130859431492905908574660758972167966%0A%22%3A%5Cn._%3D+%29%28,%22+3446503265645381015412&m=2)
Explanation:
```
n%|E@ Full program, implicit input in order list, number
n% Copy the list to the top and get its length
|E Convert the number to that base
@ Map: index
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 10 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
l;A─{IaWp}
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=bCUzQkEldTI1MDAlN0JJYVdwJTdEZiUwQS4lMkMldTIxOTJm,inputs=MTkyODE0OTMyNTY3MDY0NzI0NDkxMjEwMDc4OTIxMzYyNjYxNjU2MDg2MTEzMDg1OTQzMTQ5MjkwNTkwODU3NDY2MDc1ODk3MjE2Nzk2NiUwQSUyMiUyMCU1Q24lN0NfLSUyMg__,v=0.12)
Pretty long, considering the idea is pretty much implemented in the language: [here](https://dzaima.github.io/SOGLOnline/compression/index.html), entering
```
¶ __ __ ¶ | |_| | ¶___| |___¶- - - - ¶ - - - - - - - ¶- - - - - - - -¶_______________¶
```
gives out a compressed string using this method.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 31 bytes
```
->n,b{n.to_s(b.size).tr"0-9",b}
```
[Try it online!](https://tio.run/##NY7BbsIwDIbvfYooF2BKq9hxnBiJvUhXoXYa2g4riJbDoDx752rd4bPk3/5/@3rrfubTYS5fe9c9@mo8H4dtVw1f949dNV6tL8W67jnXNSbyztR2ss4ebdO4wtQsWQAW9V3VT6VVzusUBDOQBIycPFNCIgEE71MWhMDIDBzZZwYIPkehoOsoPop2iZh9ilkSAidhXs4YjX/rtfx94Wy53gpEHH1AzaMYMniIBLhY9v@WarUclCVnp2wVpxFN9d1ezGNqXTcVxpjLbRzMqdb2ZbNpimcx/wI "Ruby – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 2 bytes
```
:B
```
[Run and debug it](https://staxlang.xyz/#c=%3AB&i=1928149325670647244912100789213626616560861130859431492905908574660758972167966,+[%22+%22,%22%5Cn%22,%22%7C%22,%22_%22,%22-%22]%0A&a=1)
`:B` is an instruction in stax that does this. It would normally operate on a "string"\* instead of an array of "strings". In the end, this means that the output is an array of single character arrays. But output implicitly flattens anyway.
\*Stax doesn't actually have a string type. Text is represented by integer arrays of codepoints.
[Answer]
# [J](http://jsoftware.com/), 12 bytes
```
]{~#@]#.inv[
```
## How?
```
#.inv convert
[ the left argument (the number)
#@] to base the length of the right argument (the list of characters)
{~ and use the digits as indices to
] the list of characters
```
[Try it online!](https://tio.run/##NY3LCsJADEX3/Yqgi1GoQ5LJZCaFguAfuBUpIpbqQheCCD5@vdbX8h4u5xz69lx7QKgA@/XtOZ6vx35/vKz6aTHy4NraOyjhUUF7LordtjsBJ0Fowd0b9wVq2YjeaNttTg6@NIhoxMAaVWLIhBSF@Pq@Va6ExbIE55sappPy5yHjTGKBoyZUSSxixISYsjEFZVUabJiVKGCOJmG4s2G0YSVRxRSzJSZNpvpJwT91b2YO@hc "J – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 49 bytes
```
Outer[Part,{#},#2~IntegerDigits~Tr[1^#]+1,1]<>""&
```
[Try it online!](https://tio.run/##JY4xT8MwEIV3/4rIkapWGPCd7bMNFGVgYaIDWwhVVKVthgbJmCmkfz3YZLhPuvfe6d2ljefu0sb@0M7H7Xp@@4ldqHdtiGIsJ1Hi9XWI3akLL/2pj9/X91DDZ9ncgIDm6Znz1bx5ZLvQD7E@VlUpOOPN6r4aGRtH/ssF3/NJFGi1nESWDkk6p2nTfGWLvPMAi1kk8WNIWA4Fv80J8OhAe4WGrCRtUWsPCFJa5xEUIRGQIekIQElnvFYpjl4anzariaQ1zlsEsp5oqXrgovjvKvhdxj5jm1FkbDLWGSK/oLQmIxWmGm2UAwlGA06MTfMf "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 110 bytes
```
char s[99],S[99];i;f(x,_)char*_;{i=strlen(_);*s=*S=0;while(x)sprintf(S,"%c%s",_[x%i],s),strcpy(s,S),x/=i;x=s;}
```
[Try it online!](https://tio.run/##LZDRasMwDEXf8xUmELCCxpo9lAbhr8hjaoJnksbQucVKW4/Sb/firHoQF46udJH9OFmbkp1NENy3rcYud3I0yYgDZFAP9HSKl3AevRyAalZ1p3b0mN15lBH4GpxfJtlhWdmKSxz6WDmNDLia7PVXMnaA8VM5iorpldZx8WOcl1mYcLIotgT1qu@9huJZiLUy/TY8CiXMcnFyo40G2ui/w86ZZvClqdjAO05Z8dGXKCaZd@QLAO@JMC634MWOildK@/bQNk1@weUP "C (gcc) – Try It Online")
Description:
```
char s[99],S[99]; // Two strings, s and S (capacity 99)
i; // A variable to store the length of the string
f(x,_)char*_;{ // f takes x and string _
i=strlen(_); // set i to the length of _
*s=*S=0; // empty s and S
while(x) // loop until x is zero
sprintf(S,"%c%s", // print into S a character, then a string
_[x%i],s), // character is the x%i'th character of _, the string is s
strcpy(s,S), // copy S into s
x/=i; // divide x by the length of the string (and loop)
x=s;} // return the string in s
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 11 bytes
```
liq_,@\b\f=
```
[Try it online!](https://tio.run/##DcoxCgJRDATQfk/hARQy@ckkUwgeZGFRQVC0sPfu3y0fvPvr@pnz/fxux8t6Wx/nOSFvhIYnyxjlEYLDrFqOQSfBpDWBYZ2KsXeXpXZVkFbZKgdL5HJYftvpDw "CJam – Try It Online") Takes input as the number, then a newline, then the characters in the ASCII art.
## Explanation
```
li e# Read the first line and convert it to an integer
q_, e# Read the rest of the input and push its length n
@\b e# Convert the number to its base-n equivalent, as an array of numbers
\f= e# Map over the array, taking each element's index from the string
```
[Answer]
# JavaScript, 39 bytes
Port of [Rod's Python solution](https://codegolf.stackexchange.com/a/166718/58974).
```
s=>g=n=>n?g(n/(l=s.length)|0)+s[n%l]:""
```
[Try it online](https://tio.run/##BcFRCoMwDADQuxQGCUOnP2MK0YMMP0ptqxISMWVfu3t97/A/b@Haz9KIrrEmqkZTJqFJ5gzyAiZrOUouG/47fNpXHryMztWgYsqxZc2QwIXNq0N4D5@h7xHrDQ)
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/98866/edit).
Closed 2 years ago.
[Improve this question](/posts/98866/edit)
I got this challenge from [Codingame](https://www.codingame.com) and am curious about better solutions than mine:
Given a width via standard input draw a hollow square of '#' in given width and length.
Example:
5 results in
```
#####
# #
# #
# #
#####
```
I used python to solve this so i am particulary interested in other python code. But please feel free to post your solution in any language you want.
[Answer]
# [Charcoal](http://github.com/somebody1234/Charcoal), 6 bytes
Code:
```
NβBββ#
```
Explanation:
```
Nβ # Get input from the command line and store into β
B # Draw a hollow box with...
β # Width β
β # Height β
# # Filled with the character '#'
# Implicitly output the box
```
[Try it online!](http://charcoal.tryitonline.net/#code=77yuzrLvvKLOss6yIw&input=NQ)
[Answer]
# [MATL](http://github.com/lmendo/MATL), 12 bytes
```
:G\1>&*~35*c
```
[Try it online!](http://matl.tryitonline.net/#code=OkdcMT4mKn4zNSpj&input=NQ)
### Explanation
```
: % Input n implicitly. Push range [1 2 ... n]
% STACK: [1 2 3 4 5]
G % Push n again
% STACK: [1 2 3 4 5], 5
\ % Modulo
% STACK: [1 2 3 4 0]
1> % Does each entry exceed 1?
% STACK: [0 1 1 1 0]
&* % Matrix with all pair-wise products
% STACK: [0 0 0 0 0;
0 1 1 1 0;
0 1 1 1 0;
0 1 1 1 0;
0 0 0 0 0]
~ % Negate
% STACK: [1 1 1 1 1;
1 0 0 0 1;
1 0 0 0 1;
1 0 0 0 1;
1 1 1 1 1]
35* % Multiply by 35
% STACK: [35 35 35 35 35;
35 0 0 0 35;
35 0 0 0 35;
35 0 0 0 35;
35 35 35 35 35]
c % Convert to char. 0 is interpreted as space. Display implicitly
% STACK: ['#####';
'# #';
'# #';
'# #';
'#####']
```
[Answer]
# Jolf, 8 bytes
```
,ajj"###
,ajj draw a box with height (input) and width (input)
"### with a hash border
```
[Answer]
## Python 2, ~~62~~ 54 bytes
```
f=lambda n:'#'*n+'\n#%s#'%(' '*(n-2))*(n-2)+'\n'+'#'*n
```
Returns `#\n#` when the input is `1`
55 Bytes version that prints
```
def f(n):a=n-2;print'#'*n,'\n#%s#'%(' '*a)*a,'\n'+'#'*n
```
62 Bytes version that works for any input:
```
f=lambda n:'#'*n+'\n#%s#'%(' '*(n-2))*(n-2)+('\n'+'#'*n)*(n>1)
```
[Answer]
# Java 7, ~~113~~ ~~112~~ 110 bytes
```
String c(int n){String r="";for(int i=n,j;i-->0;r+="\n")for(j=0;j<n;r+=i*j<1|n-i<2|n-j++<2?"#":" ");return r;}
```
1 byte saved thanks to *@OlivierGrégoire*;
2 bytes saved thanks to *@cliffroot*.
Derived solution based on my [*Creating a Crossed Square* answer](https://codegolf.stackexchange.com/a/91072/52210).
[Try it here.](https://ideone.com/uKMm8B)
[Answer]
# [COW](https://esolangs.org/wiki/COW), ~~426~~ ~~405~~ ~~348~~ 330 bytes
```
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMMMmoOMMMMoOMoOMoOMoOMoOMoOMoOMoOMoO
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMMMmoOMMMMoOMoOMoOmoOoomMMM
moOMMMMOOmOomOoMoomoOmoOMOomoomOoMMMmoOMMMMOoMOoMOOmOomOomOomOoMoo
moOmoOMoomoOMMMmoOmoOMMMMOoMOoMOOmOomOomOomOoMoomoOmoOmoOmoOMOomoo
mOomOomOoMoomoOmoOMOomoomOomOomOomOoMoomoOmoOmoOMOOmOoMoomoOMOomoo
```
[Try it online!](https://tio.run/nexus/perl#jVHLboMwELzzFTTywZZjApF6gVDyAyt/QMQhobSJhOOU9CnCt9PFNs2jr0gWeGdnd3a83bxIJ3ShIF9omTfT9iClPAAA/uGgtWKTx8QjuzRMvP3LyldaN0QJkZAqjRJKioUQROXl0wgzo4xUnMcIWgik7CEh4oi9rTdVSarWdpHYZSeEi7TEiPMhJxs/CALfhtALrjDfZnRXb7bPfrGuLcBiai@pru/p7I4xVyKHkkEBegWDDCo4WrN5oDeuE3ri/OiJ8zMDp56czVNPSV/c2r74ek4pDZ0SQENJPXZKKakzGo5J/TU9e58OtdDslx8WtRAuYGiH1nuPrVe@LiszDue5mYASNZsXLOk69PnXAVDm@w/tmvOtFYY47BGXEpeMB/enTBa3gm/XI0eONscxL/nmYsnX8C9UflP/sdD2dIqG6UXTTsBtEEZhJ7af "Perl – TIO Nexus") Change the number in the second line to any number to change the output.
The COW interpreter that I'm using here was written in Perl (and is newer than this challenge), but you can still get the same result by inputting the code [here](http://web.archive.org/web/20130116215713/http://www.frank-buss.de/cow.html).
### Explanation
```
; Note: [n] means "value stored in the nth block of memory".
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoO ;Stores 10 in [0]. 10 is the code point for carriage return
MMMmoOMMMMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoO ;Stores 32 in [1]. 32 is the code point for whitespace
MMMmoOMMMMoOMoOMoO ;Stores 35 in [2]. 35 is the code point for #
moOoom ;Reads STDIN for an integer, and stores it in [3]
MMMmoOMMM ;Copies [3] into [4]
MOO ;Loop as long as [4] is non-zero
mOomOoMoo ;Navigate to [2] and print the character with that code point
moOmoOMOo ;Navigate to [4] and decrement
moo ;End loop
mOoMMMmoOMMMMOoMOo ;Copy [3] into [4] and decrement [4] twice
MOO ;Loop as long as [4] is non-zero
mOomOomOomOoMoo ;Navigate to [0] and print the character with that code point
moOmoOMoo ;Navigate to [2] and print the character with that code point
moOMMMmoOmoOMMMMOoMOo ;Navigate to [3] and copy it into [5], then decrement [5] twice
MOO ;Loop as long as [5] is non-zero
mOomOomOomOoMoo ;Navigate to [1] and print the character with that code point
moOmoOmoOmoOMOo ;Navigate to [5] and decrement
moo ;End loop
mOomOomOoMoo ;Navigate to [2] and print the character with that code point
moOmoOMOo ;Navigate to [4] and decrement
moo ;End loop
mOomOomOomOoMoo ;Navigate to [0] and print the character with that code point
moOmoOmoO ;Navigate to [3]
MOO ;Loop as long as [3] is non-zero
mOoMoo ;Navigate to [2] and print the character with that code point
moOMOo ;Navigate to [3] and decrement
moo ;End loop
```
[Answer]
# Python 2, ~~59~~ 58 bytes
```
n=i=input()
while i:print'#%s#'%((' #'[i%n<2])*(n-2));i-=1
```
**[repl.it](https://repl.it/EQw5/1)**
Note: An input of `1` produces an output of `##`, but a *hollow* square would never be produced for an input less than `3`, so I guess this is fine.
[Answer]
## PowerShell v2+, ~~48~~ 47 bytes
```
param($n)($z='#'*$n--);,("#$(' '*--$n)#")*$n;$z
```
*-1 byte thanks to JohnLBevan*
Takes input `$n`, sets `$z` as `$n` hashmarks, with `$n` post-decremented. Encapsulates that in parens to place a copy on the pipeline. Then uses the comma operator to create an array of pre-decremented `$n` lines of `#`,spaces,`#`. Those are left on the pipeline. Then places `$z` again on the pipeline. Output via implicit `Write-Output` at the end introduces a newline between elements, so we get that for free.
Since the [OP's code](https://codegolf.stackexchange.com/a/98868/42963) doesn't work for input `n <= 1`, I took that to mean we don't need to support input `1`, either.
### Examples
```
PS C:\Tools\Scripts\golfing> 2..6|%{"$_";.\draw-a-hollow-square.ps1 $_;""}
2
##
##
3
###
# #
###
4
####
# #
# #
####
5
#####
# #
# #
# #
#####
6
######
# #
# #
# #
# #
######
```
[Answer]
# C, 98 bytes
```
f(n,i){i=n*(n+1);while(i--){putchar(i%(n+1)==n?10:i<n||i>n*n-1||i%(n+1)==0||i%(n+1)==n-1?35:32);}}
```
Usage:
```
f(5)
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 20 bytes
```
'#×D¹Íð×'#.ø¹Í×sJ¹ä»
```
[Try it online!](http://05ab1e.tryitonline.net/#code=JyPDl0TCucONw7DDlycjLsO4wrnDjcOXc0rCucOkwrs&input=NQ)
Or **18 bytes** if we can ignore `1 <= n`:
```
F„ #N¹<%_è¹Í×'#.ø,
```
[Try it online!](http://05ab1e.tryitonline.net/#code=RuKAniAjTsK5PCVfw6jCucONw5cnIy7DuCw&input=NQ)
[Answer]
# WinDbg, ~~206~~ ~~200~~ ~~182~~ 170 bytes
```
.if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}
```
*-6 bytes from removing parens from `.if` and using `j` instead of second `.if`*
*-18 bytes by using `f` instead of a `.for` to construct the strings.*
*-12 bytes by not NULL-terminating strings, instead passing length to `da`*
Input is passed in through the pseudo-register `$t0` (eg `r $t0 = 5; {above-code}`).
Explanation:
```
.if @$t0 *Verify width($t0) at least 1
{ *(registers have unsigned values)
r $t3 = 2000000; *Set $t3 to address where the
*string will be constructed
f @$t3 L@$t0 23; *Put width($t0) '#' at 2000000($t3)
f 2 * @$t3 L@$t0 20; *Put width($t0) ' ' at 4000000(2*$t3)
eb 2 * @$t3 23; *Put '#' on left of ' ' string
eb 2 * @$t3 + @$t0 - 1 23; *Put '#' on right of ' ' string
da @$t3 L@$t0; *Print the top of the box
j 1 < @$t0 *If width($t1) at least 2
'
.for (r $t1 = @$t0 - 2; @$t1; r $t1 = @$t1 - 1) *Loop width($t0)-2 times to...
{
da 2 * @$t3 L@$t0 *...print the sides of the box
};
da @$t3 L@$t0 *Print the bottom of the box
'
}
```
Sample output:
```
0:000> r$t0=0
0:000> .if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}
0:000> r$t0=1
0:000> .if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}
Filled 0x1 bytes
Filled 0x1 bytes
02000000 "#"
0:000> r$t0=2
0:000> .if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}
Filled 0x2 bytes
Filled 0x2 bytes
02000000 "##"
02000000 "##"
0:000> r$t0=5
0:000> .if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}
Filled 0x5 bytes
Filled 0x5 bytes
02000000 "#####"
04000000 "# #"
04000000 "# #"
04000000 "# #"
02000000 "#####"
```
[Answer]
# JavaScript, ~~61~~ 58 bytes
Saved 3 bytes thanks to [@lmis](https://codegolf.stackexchange.com/users/56071/lmis)!
```
n=>(b='#'[r='repeat'](n))+`
#${' '[r](n-=2)}#`[r](n)+`
`+b
```
(Doesn't handle `0` or `1`)
For 13 extra bytes (at **71 bytes**), you can!
```
n=>n?n-1?(b='#'[r='repeat'](n))+`
#${' '[r](n-=2)}#`[r](n)+`
`+b:'#':''
```
These solutions are fairly simple: they do a lot of storage to not *repeat* themselves to save a few bytes. Unminified without the variablsm it would look like:
```
n => // Anonymous function definition (Param `n` is the size)
'#'.repeat(n) + // # `n` times to form the top
`
#${' '.repeat(n - 2)}#` // Followed by a newline followed by a hash and `n` - 2 spaces and
// another hash to make one of the middle lines
.repeat(n - 2) + // The above middle lines repeated `n` - 2 times
'#'.repeat(n) // Followed by the top line again
```
### Try it!
```
<script type="text/babel">var f=n=>n?n-1?(b='#'[r='repeat'](n))+`\n#${' '[r](n-=2)}#`[r](n)+`\n`+b:'#':'',b,r;function c(){document.getElementById('pre').textContent = f(+document.getElementById('input').value);}</script><input id="input" onkeydown="c();" onkeyup="c();" onchange="c();" onclick="c();" placeholder="Size"><pre id="pre"></pre>
```
[Answer]
# [Python 2](https://docs.python.org/2/), 47 bytes
Works for all `n` greater than 1.
```
lambda n:'#'*n+('#%*s'%(n,'#\n')*~-n)[n:]+'#'*n
```
[Try it online!](https://tio.run/##NcqxCoMwFAXQ3a@4EMJLol0cOgT8Eu0QsamCvUrM0qW/HkFwPZz9l@eNbYndUNbwHacAelHiWBtR2h2iDRtRA8W6/4O2p3/VVyhxSyAWIgV@3qZt8LS@wp4WZoievECDN0RDW04 "Python 2 – Try It Online")
[Answer]
# Python, 109 bytes
```
n=int(input())
for x in range(n):
r=list(' '*n);r[0]=r[-1]='#'
if x%(n-1)==0:r='#'*n
print("".join(r))
```
[Answer]
# Ruby, 39 bytes
```
->n{puts a=?#*n,[?#+' '*(n-=2)+?#]*n,a}
```
Turns out to be shorter this way than all the fancy stuff I was trying. Be advised that this doesn't handle 0 or 1 at all.
[Answer]
## Python 2, 50 bytes
```
m=input()-2
for c in'#'+' '*m+'#':print'#'+m*c+'#'
```
Works for `n>=2`. Prints each line with a pound sign, `n-2` of the appropriate symbol, then another pound sign.
Aliasing the pound symbol gives same length:
```
m=input()-2;p='#'
for c in p+' '*m+p:print p+m*c+p
```
Other attempts:
```
lambda n:'#'*n+('\n#'+' '*(n-2)+'#')*(n-2)+'\n'+'#'*n
lambda n:'#'*n+'\n#%s#'%((n-2)*' ')*(n-2)+'\n'+'#'*n
lambda n:'\n'.join(['#'*n]+['#'+' '*(n-2)+'#']*(n-2)+['#'*n])
n=input();s='#'+' '*(n-2)+'#'
for c in s:print[s,'#'*n][c>' ']
s='##'+' #'*(input()-2)+'##'
for c in s[::2]:print s[c>' '::2]
s='#'+' '*(input()-2)+'#'
for c in s:print s.replace(' ',c)
```
[Answer]
## Haskell, 49 bytes
```
n%b='#':(b<$[3..n])++"#\n"
f n=(n%)=<<init(n%' ')
```
Works for `n>=2`. Defines the operation of sandwiching a character between `#` for an `n`-character newline-terminated string, then applies it twice to make a 2D grid.
Call like:
```
*Main> putStrLn$ f 5
#####
# #
# #
# #
#####
```
[Answer]
# C, ~~83~~ ~~82~~ ~~80~~ ~~78~~ 77 Bytes
```
i,j;f(n){for(i=n;i--;puts(""))for(j=n;j--;putchar(i*j&&i^n-1&&j^n-1?32:35));}
```
Sneak in a multiply and save a byte...
```
i,j;f(n){for(i=n;i--;puts(""))for(j=n;j--;putchar(i&&j&&i^n-1&&j^n-1?32:35));}
```
Also count down j and save a few more...
```
i,j;f(n){for(i=n;i--;puts(""))for(j=0;j++<n;putchar(i&&j^1&&i^n-1&&j^n?32:35));}
```
Count down i from n to zero and save a few bytes...
```
i,j;f(n){for(i=0;i++<n;puts(""))for(j=0;j++<n;putchar(i^1&&j^1&&i^n&&j^n?32:35));}
```
A bit easier to understand and 1 byte more
```
i,j;f(n){for(i=0;i++<n;puts(""))for(j=0;j++<n;putchar(i==1|i==n|j==1|j==n?35:32));}
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 17 bytes
```
{"# "x*/:x#:!x-1}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6pWUlZQqtDSt6pQtlKs0DWs5UpTMAMARoEFvQ==)
Or tacit, 20 bytes:
```
" #"@|/(+|:)\^ :':=:
"# "@&/(+|:)\=':1|=: / similar
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs1JSUFZyqNHX0K6x0oyJU7BSt7K14kpTMAUAUiwF9g==)
[Answer]
# Groovy, ~~51~~ 50 bytes
```
{n->a="*"*n+"\n";n-=2;print(a+"*${' '*n}*\n"*n+a)}
```
[Answer]
# PHP, ~~81~~ 69 bytes
```
for($n=-1+$i=$argv[1];$i--;)echo str_pad("#",$n," #"[$i%$n<1]),"#\n";
```
Run with `-r`; provide input as argument.
Throws a `DivisionByZeroError` for input=`1`.
[Answer]
## Pyke, 11 bytes
```
ttDd*n+*.X#
```
[Try it here!](http://pyke.catbus.co.uk/?code=ttDd%2an%2B%2a.X%23&input=5)
```
ttDd*n+* - a square of spaces n-2*n-2 big
.X# - surround in `#`
```
[Answer]
# R, 68 ~~70~~ bytes
Works for n > 1. Thanks to @Billywob for a couple of bytes swapping out the array for a matrix.
```
cat(rbind(b<-'#',cbind(b,matrix(' ',n<-scan()-2,n),b),b,'
'),sep='')
```
Uses rbind and cbind to put rows and columns of `#`'s around an n-2 square matrix of spaces. Newlines are bound to the rows as well. The newline in the source is significant. Input is from STDIN
[Answer]
# Common Lisp, ~~150~~ 130 bytes
*-20 thanks to @Cyoce and @AlexL.*
```
(defun s(v)(format t"~v,,,vA~%"v #\# #\#)(dotimes(h(- v 2))(format t"~v,,,vA~A~%"(- v 1)#\ #\# #\#))(format t"~v,,,vA"v #\# #\#))
```
Usage:
```
* (s 5)
#####
# #
# #
# #
#####
```
Basically uses `format` twice for the top and bottom and a loop for the rows in between. The format call for the top and bottom outputs a line starting with `#` and padded to the appropriate width with `#`s. The format call for the rows in between works similarly, except the padding is spaces and a `#` gets printed at the end of the line.
Note: I'm rather new to Lisp and expect to have a lot of room for improvement on this.
[Answer]
# [Dyalog APL](https://www.dyalog.com/), 20 bytes
```
{' #'[1+∘.∨⍨1⍵∊⍨⍳⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhGp1BWX1aEPtRx0z9B51rHjUu8LwUe/WRx1dQNaj3s1AdmwtUOWhFYYKpgqGBgA)
This is an improved version on my first attempt suggested by [dzaima](https://codegolf.stackexchange.com/users/59183/dzaima) on [the APL Orchard](https://chat.stackexchange.com/transcript/message/59276795#59276795), so all credit goes to him.
Takes an integer n as input. Using 5 as an example:
```
⍳⍵ integers from 1 to n
1 2 3 4 5
1⍵∊⍨ check whether each integer is 1 or n
1 0 0 0 1
∘.∨⍨ generate all possible pairs of the
0s and 1s in a matrix, or'ing each pair:
∨ | 1 0 0 0 1
--+----------
1 | 1 1 1 1 1
0 | 1 0 0 0 1
0 | 1 0 0 0 1
0 | 1 0 0 0 1
1 | 1 1 1 1 1
1+ add 1 to each number
2 2 2 2 2
2 1 1 1 2
2 1 1 1 2
2 1 1 1 2
2 2 2 2 2
' #'[ ] turn 1 into space (the first character)
and 2 into # (the second character)
```
[Answer]
## Haskell, 67 bytes
```
l#n=l<$[1..n]
f n=unlines$'#'#n:('#':' '#(n-2)++"#")#(n-2)++['#'#n]
```
Usage example:
```
Prelude> putStrLn $ f 4
####
# #
# #
####
```
How it works:
```
l#n=l<$[1..n] -- helper function that makes n copies of l
'#'#n -- make a string of n copies of #, followed by
#(n-2) -- n-2 copies of
'#':' '#(n-2)++"#" -- # followed by n-2 times spaces, followed by #
['#'#n] -- and a final string with n copies of #
unlines -- join with newlines in-between
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13, [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
,þ%µỊṀ€€ị⁾# Y
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=LMO-JcK14buK4bmA4oKs4oKs4buL4oG-IyBZ&input=&args=MTM)** or [try 0 to 15](http://jelly.tryitonline.net/#code=LMO-JcK14buK4bmA4oKs4oKs4buL4oG-IyBZCuKBtOG4tsK1xbzDh-KCrEtZ&input=)
### How?
```
,þ%µỊṀ€€ị⁾# Y - Main link: n
þ - outer product with
, - pair: [[[1,1],[2,1],...,[n,1]],[[1,2],[2,2],...,[n,2]], ... ,[[1,n],[2,n],...,[n,n]]]
% - mod n: [[[1,1],[2,1],...,[0,1]],[[1,2],[2,2],...,[0,2]], ... ,[[1,0],[2,0],...,[0,0]]]
µ - monadic chain separation
Ị - abs(z)<=1: [[[1,1],[0,1],...,[1,1]],[[1,0],[0,0],...,[1,0]], ... ,[[1,1],[0,1],...,[1,1]]]
€€ - for each for each
Ṁ - maximum: [[1, 1, ...,1], [1, 0, ..., 1], ... ,[1, 1, ..., 1] ]
ị - index into (1 based)
⁾# - "# ": ["##...#","# ...#", ...,"##...#"]
Y - join with line feeds
```
[Answer]
## [Pip](http://github.com/dloscutoff/pip), 16 bytes
15 bytes of code, +1 for `-n` flag.
```
(Y_Xa-2WR'#s)My
```
Works for input >= 2. [Try it online!](http://pip.tryitonline.net/#code=KFlfWGEtMldSJyNzKU15&input=&args=NQ+LW4)
### Explanation of somewhat ungolfed version
First, we define a function `y` that takes a string argument, repeats it `a-2` times (where `a` is the first command-line input), and wraps the result in `#`.
```
Y _ X a-2 WR '#
_ Identity function
X a-2 String-repeated by a-2
WR '# Wrapped in #
Y Yank the resulting function into y
```
Next, we apply this function twice--once normally, then again with map--to obtain the square as a list of strings:
```
y M (y s)
(y s) Call function y with s (preinitialized to " ") as argument
y M Map y to each character of the resulting string
```
For input of `4`, `(y s)` results in `"# #"` and `y M (y s)` in `["####"; "# #"; "# #"; "####"]`. This latter value is then printed, with the `-n` flag causing it to be newline-separated.
### Golfing tricks
To get from the ungolfed to the golfed version:
* Remove spaces.
* `Y` is an operator, which means we can use it in an expression. Instead of `Y...` followed by `(ys)`, we can just do `(Y...s)`.
* The problem is, we have to yank the function before we reference it again as `y`; so `yM(Y_Xa-2WR'#s)` won't work. Solution: swap the operands of the `M`ap operator. As long as one of them is a function and the other is an iterable type, it doesn't matter what order they come in.
[Answer]
## Racket 113 bytes
```
(let*((d display)(g(λ()(for((i n))(d"#")))))(g)(d"\n")(for((i(- n 2)))(d"#")(for((i(- n 2)))(d" "))(d"#\n"))(g))
```
Ungolfed:
```
(define (f n)
(let* ((d display)
(g (λ ()
(for ((i n))
(d "#"))
(d "\n"))))
(g)
(for ((i (- n 2)))
(d "#")
(for ((i (- n 2)))
(d " ") )
(d "#\n"))
(g)))
```
Testing:
```
(f 5)
```
Output:
```
#####
# #
# #
# #
#####
```
[Answer]
# SpecBAS - 57 bytes
```
1 INPUT n: a$="#"*n,n-=2,b$="#"+" "*n+"#"#13: ?a$'b$*n;a$
```
`?` is shorthand for `PRINT`, `#13` is carriage return which can be tacked on to the end of a string without needing a `+` to join them.
The apostrophe moves print cursor down one line.
] |
[Question]
[
Write a function that when given a buffer `b` (1 - 104857600 bytes long) and a number of bits `n` (1 <= n <= 64), splits the buffer into chunks of `n` bits. Right-pad the last chunk with `0`s up to `n` bits.
e.g.
Given the buffer `b = "f0oBaR"` or equivalently `[102,48,111,66,97,82]` and `n = 5`, return
```
[12, 24, 24, 6, 30, 16, 19, 1, 10, 8]
```
This is because the above buffer, when represented as binary looks like:
```
01100110 00110000 01101111 01000010 01100001 01010010
```
And when re-grouped into 5s looks like:
```
01100 11000 11000 00110 11110 10000 10011 00001 01010 010[00]
```
Which when converted back into decimal gives the answer.
## Notes
* You may use whatever data type makes the most sense in your language to represent the buffer. In PHP you'd probably use a string, in Node you might want to use a [Buffer](https://nodejs.org/api/buffer.html)
+ If you use a string to represent the buffer, assume it's ASCII for the char -> int conversion
+ You may use an array of ints (0-255) for input if you prefer
* Return value must be an array or list of ints
## Test Cases
```
> b = "Hello World", n = 50
318401791769729, 412278856237056
> b = [1,2,3,4,5], n = 1
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1
> b = "codegolf", n = 32
1668244581, 1735355494
> b = "codegolf" n = 64
7165055918859578470
> b = "codegolf" n = 7
49, 91, 108, 70, 43, 29, 94, 108, 51, 0
> b = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vel est eu velit lacinia iaculis. Nulla facilisi. Mauris vitae elit sapien. Nullam odio nulla, laoreet at lorem eu, elementum ultricies libero. Praesent orci elit, sodales consectetur magna eget, pulvinar eleifend mi. Ut euismod leo ut tortor ultrices blandit. Praesent dapibus tincidunt velit vitae viverra. Nam posuere dui quis ipsum iaculis, quis tristique nisl tincidunt. Aliquam ac ligula a diam congue tempus sit amet quis nisl. Nam lacinia ante vitae leo efficitur, eu tincidunt metus condimentum. Cras euismod quis quam vitae imperdiet. Ut at est turpis.", n = 16
19567, 29285, 27936, 26992, 29557, 27936, 25711, 27759, 29216, 29545, 29728, 24941, 25972, 11296, 25455, 28275, 25955, 29797, 29813, 29216, 24932, 26992, 26995, 25449, 28263, 8293, 27753, 29742, 8272, 25964, 27749, 28276, 25971, 29045, 25888, 30309, 27680, 25971, 29728, 25973, 8310, 25964, 26996, 8300, 24931, 26990, 26977, 8297, 24931, 30060, 26995, 11808, 20085, 27756, 24864, 26209, 25449, 27753, 29545, 11808, 19809, 30066, 26995, 8310, 26996, 24933, 8293, 27753, 29728, 29537, 28777, 25966, 11808, 20085, 27756, 24941, 8303, 25705, 28448, 28277, 27756, 24876, 8300, 24943, 29285, 25972, 8289, 29728, 27759, 29285, 27936, 25973, 11296, 25964, 25965, 25966, 29813, 27936, 30060, 29810, 26979, 26981, 29472, 27753, 25189, 29295, 11808, 20594, 24933, 29541, 28276, 8303, 29283, 26912, 25964, 26996, 11296, 29551, 25697, 27749, 29472, 25455, 28275, 25955, 29797, 29813, 29216, 28001, 26478, 24864, 25959, 25972, 11296, 28789, 27766, 26990, 24946, 8293, 27749, 26982, 25966, 25632, 28009, 11808, 21876, 8293, 30057, 29549, 28516, 8300, 25967, 8309, 29728, 29807, 29300, 28530, 8309, 27764, 29289, 25445, 29472, 25196, 24942, 25705, 29742, 8272, 29281, 25971, 25966, 29728, 25697, 28777, 25205, 29472, 29801, 28259, 26980, 30062, 29728, 30309, 27753, 29728, 30313, 29793, 25888, 30313, 30309, 29298, 24878, 8270, 24941, 8304, 28531, 30053, 29285, 8292, 30057, 8305, 30057, 29472, 26992, 29557, 27936, 26977, 25461, 27753, 29484, 8305, 30057, 29472, 29810, 26995, 29801, 29045, 25888, 28265, 29548, 8308, 26990, 25449, 25717, 28276, 11808, 16748, 26993, 30049, 27936, 24931, 8300, 26983, 30060, 24864, 24864, 25705, 24941, 8291, 28526, 26485, 25888, 29797, 28016, 30067, 8307, 26996, 8289, 28005, 29728, 29045, 26995, 8302, 26995, 27694, 8270, 24941, 8300, 24931, 26990, 26977, 8289, 28276, 25888, 30313, 29793, 25888, 27749, 28448, 25958, 26217, 25449, 29813, 29228, 8293, 29984, 29801, 28259, 26980, 30062, 29728, 28005, 29813, 29472, 25455, 28260, 26989, 25966, 29813, 27950, 8259, 29281, 29472, 25973, 26995, 28015, 25632, 29045, 26995, 8305, 30049, 27936, 30313, 29793, 25888, 26989, 28773, 29284, 26981, 29742, 8277, 29728, 24948, 8293, 29556, 8308, 30066, 28777, 29486
> b = [2,31,73,127,179,233], n = 8
2, 31, 73, 127, 179, 233
```
[Answer]
## Pyth, ~~18~~ 17 bytes
```
iR2c.[t.B+C1z\0QQ
```
Thanks to [@lirtosiast](https://codegolf.stackexchange.com/users/39328/lirtosiast) for a byte!
```
z get input
+C1 prepend a 0x01 to prevent leading zeroes from disappearing
.B convert to binary string
t remove the leading 1 from ^^
.[ \0Q pad right with zeroes to multiple of second input
c Q get chunks/slices of length second input
iR2 map(x: int(x, 2))
```
[Answer]
# Jelly, 13 bytes
```
1;ḅ256æ«BḊsḄṖ
```
This takes the input as a list of integers. [Try it online!](http://jelly.tryitonline.net/#code=MTvhuIUyNTbDpsKrQuG4inPhuIThuZY&input=&args=WzEwMiwgNDgsIDExMSwgNjYsIDk3LCA4Ml0+NQ)
### How it works
```
1;ḅ256æ«BḊsḄṖ Main link. Arguments: A (list), n (integer)
1; Prepend 1 to A.
ḅ256 Convert from base 256 to integer.
æ« Bitshift the result n units to the left.
B Convert to binary.
Ḋ Discard the first binary digit (corresponds to prepended 1).
s Split into chunks of length n.
Ḅ Convert each chunk from binary to integer.
Ṗ Discard the last integer (corresponds to bitshift/padding).
```
[Answer]
# Julia, 117 bytes
```
f(x,n,b=join(map(i->bin(i,8),x)),d=endof,z=rpad(b,d(b)+d(b)%n,0))=map(i->parse(Int,i,2),[z[i:i+n-1]for i=1:n:d(z)-n])
```
This is a function that accepts an integer array and an integer and returns an integer array. It's an exercise in function argument abuse.
Ungolfed:
```
function f(x::Array{Int,1}, # Input array
n::Int, # Input integer
b = join(map(i -> bin(i, 8), x)), # `x` joined as a binary string
d = endof, # Store the `endof` function
z = rpad(b, d(b) + d(b) % n, 0)) # `b` padded to a multiple of n
# Parse out the integers in base 2
map(i -> parse(Int, i, 2), [z[i:i+n-1] for i = 1:n:d(z)-n])
end
```
[Answer]
## JavaScript (ES6), 120 bytes
```
f=(a,n,b=0,t=0,r=[])=>b<n?a.length?f(a.slice(1),n,b+8,t*256+a[0],r):b?[...r,t<<n-b]:r:f(a,n,b-=n,t&(1<<b)-1,[...r,t>>b])
```
Recursive bit twiddling on integer arrays. Ungolfed:
```
function bits(array, nbits) {
var count = 0;
var total = 0;
var result = [];
for (;;) {
if (nbits <= count) {
// We have enough bits to be able to add to the result
count -= nbits;
result.push(total >> count);
total &= (1 << count) - 1;
} else if (array.length) {
// Grab the next 8 bits from the array element
count += 8;
total <<= 8;
total += array.shift();
} else {
// Deal with any leftover bits
if (count) result.push(total << nbits - count);
return result;
}
}
}
```
[Answer]
## Python 3, 102 bytes
```
j=''.join
lambda s,n:[int(j(k),2)for k in zip(*[iter(j([bin(i)[2:].zfill(8)for i in s+[0]]))]*n)][:-1]
```
use [iter trick](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) to group string
* `s`: the input string/buffer
* `n`: the number of bits in each splitted chunk
## Results
```
>>> f([102,48,111,66,97,82],4)
[6, 6, 3, 0, 6, 15, 4, 2, 6, 1, 5, 2, 0]
>>> f([102,48,111,66,97,82],5)
[12, 24, 24, 6, 30, 16, 19, 1, 10, 8]
>>> f([102,48,111,66,97,82],6)
[25, 35, 1, 47, 16, 38, 5, 18]
>>> f([102,48,111,66,97,82],8)
[102, 48, 111, 66, 97, 82]
```
[Answer]
# Ruby, 114 bytes
```
->s,n{a=s.bytes.map{|b|b.to_s(2).rjust 8,?0}.join.split""
r=[]
r<<a.shift(n).join.ljust(n,?0).to_i(2)while a[0]
r}
```
Slightly cleaner:
```
f = -> str, num {
arr = str.bytes.map {|byte|
byte.to_s(2).rjust(8, "0")
}.join.split("")
result = []
while arr.size > 0
result << arr.shift(num).join.ljust(num, "0").to_i(2)
end
result
}
puts f["f0oBaR", 5]
```
[Answer]
# Perl 6, ~~93~~ 68 bytes
```
{@^a».&{sprintf "%08b",$_}.join.comb($^b)».&{:2($_~0 x$b-.chars)}}
```
[Answer]
## PHP, ~~262~~ ~~217~~ [189](https://mothereff.in/byte-counter#.HC%40%22%E0%AB%8E%E0%AB%8D%C2%AB%C2%AB%22iQ2) bytes
```
function f($b,$n){$M='array_map';return$M('bindec',$M(function($x)use($n){return str_pad($x,$n,0);},str_split(implode('',$M(function($s){return str_pad($s,8,0,0);},$M('decbin',$b))),$n)));}
```
(updated with tips from [Ismael Miguel](https://codegolf.stackexchange.com/users/14732/ismael-miguel))
Formatted for readability:
```
function f($b, $n) {
$M = 'array_map';
return $M('bindec', $M(function ($x) use ($n) {
return str_pad($x, $n, 0);
}, str_split(implode('', $M(function ($s) {
return str_pad($s, 8, 0, 0);
}, $M('decbin', $b))), $n)));
}
```
Example:
```
> implode(', ',f(array_map('ord',str_split('f0oBaR')),5));
"12, 24, 24, 6, 30, 16, 19, 1, 10, 8"
```
[Answer]
# CJam, 30 bytes
```
{_@{2b8 0e[}%e_0a@*+/-1<{2b}%}
```
[Try it online!](http://cjam.tryitonline.net/#code=WzEwMiA0OCAxMTEgNjYgOTcgODJdCjUKCntfQHsyYjggMGVbfSVlXzBhQCorLy0xPHsyYn0lfQoKfnA&input=&args=+&debug=on)
This is an unnamed block which expects the int buffer and the amount of chunks on the stack and leaves the result on the stack.
Decided to give CJam a try. Only took me 2 hours to get it done ^^ This is probably too long, suggestions are very welcome!
## Explanation
```
_ e# duplicate the chunk count
@ e# rotate stack, array now on top and chunk counts on the bottom
{ e# start a new block
2b e# convert to binary
8 0e[ e# add zeros on the left, so the binary is 8 bits
} e# end previous block
% e# apply this block to each array-element (map)
e_ e# flatten array
0a e# push an array with a single zero to the stack
@ e# rotate stack, stack contain now n [array] [0] n
* e# repeat the array [0] n times
+ e# concat the two array
/ e# split into chunks of length n, now the stacks only contains the array
-1< e# discard the last chunk
{2b}% e# convert every chunk back to decimal
```
[Answer]
# JavaScript (ES6) 104
Iterative bit by bit fiddling,
**Edit** 5 bytes save thx @Neil
```
(s,g,c=g,t=0)=>(s.map(x=>{for(i=8;i--;--c||(s.push(t),c=g,t=0))t+=t+(x>>i)%2},s=[]),c-g&&s.push(t<<c),s)
```
*Less golfed*
```
(
// parameters
s, // byte source array
g, // output bit group size
// default parameters used as locals
c = g, // output bit counter
t = 0 // temp bit accumulator
) => (
s.map(x =>
{ // for each byte in s
for(i = 8; // loop for 8 bits
i--;
)
// loop body
t += t + (x>>i) % 2, // shift t to left and add next bit
--c // decrement c,if c==0 add bit group to output and reset count and accumulator
||(s.push(t), c=g, t=0)
},
s=[] // init output, reusing s to avoid wasting another global
),
c-g && s.push(t<<c), // add remaining bits, if any
s // return result
)
```
**Test**
```
f=(s,g,c=g,t=0)=>(s.map(x=>{for(i=8;i--;--c||(s.push(t),c=g,t=0))t+=t+(x>>i)%2},s=[]),c-g&&s.push(t<<c),s)
function test()
{
var a = A.value.match(/\d+/g)||[]
var g = +G.value
var r = f(a,g)
O.textContent = r
K.innerHTML = a.map(x=>`<i>${(256- -x).toString(2).slice(-8)}</i>`).join``
+ '\n'+ r.map(x=>`<i>${(256*256*256*256+x).toString(2).slice(-g)}</i>`).join``
}
test()
```
```
#A { width: 50% }
#G { width: 5% }
i:nth-child(even) { color: #00c }
i:nth-child(odd) { color: #c00 }
```
```
Input array <input id=A value="102,48,111,66,97,82">
Group by bits <input id=G value=5> (up to 32)<br>
Output <button onclick="test()">-></button>
<span id=O></span>
<pre id=K></pre>
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 66 bytes
```
->s,n{(s.unpack('B*')[0]+?0*~-n).scan(/.{#{n}}/).map{|x|x.to_i 2}}
```
[Try it online!](https://tio.run/##ZVJdbxMxEHznV6yCRJPiur2kNIAEiPIKCCHxFEXIsfeOBZ999UdUlIa/HtZ3F4oU6R7sufXszOyGvPl9qN8cLt5G4XbTKLPrlP41Pbs9P5utrtbP312d/7lwMxm1ctNLuXu6c/v95Uy2qts93D/cy@S/E8z3@0MH9WpSX/lb9XUiXqyflPuqEnOxENd8Ly@mz17rH2Emf3pyohpKJtobbLytJ2IxP4Furk@g5Yh89AFboC7mFoy3PkCkBKrFJEB7F1EnTDmAMtRR1OQaQEtJwhe0Fl3CeJcRtmgBYwLM5cgEVnEpKSCls6Uo4XO2VkHNMF9JwieVA0XYUlLYM0JUHaEbK1vwhjy4chbMxiqRZTFxrxez4EfYsgDWnW0KpAkjWNpg8CwuKIz8E3zQ1NMLiN4oyzX/u2pV4xRgU9x22W7JqVCIqUZnoGWd34opiq03YNFDTpB84G9synwbq5zpEzk2NexkkyMkcppMZmQIZTC7pS2GoNgou@x8zBgQTCa44z7jJMbYxIBxo5io5Owo2kdaCe8tw0yjNFtvMieswBADbLLh@oRtx0KOIx3oCsnQ/TglxXMc1RWTWNccJ@cjykAfXTBD7vMzNCQv4UNQ8V9APXuvZ@CitsNgCFMfIw@vrAjT8iLJiahuxu3m3a7EciGq@VJUy1divlic7vnL9eEv "Ruby – Try It Online")
Takes input buffer as a string, so that a few test strings were constructed directly in the footer to avoid unprintables.
[Answer]
# J, 24 bytes
```
[:#.-@[>\;@(_8:{."1#:@])
```
This is an anonymous function, which takes `n` as its left argument and `b` as numbers as its right argument.
Test:
```
5 ([:#.-@[>\;@(_8:{."1#:@])) 102 48 111 66 97 82
12 24 24 6 30 16 19 1 10 8
```
Explanation:
```
[:#.-@[>\;@(_8:{."1#:@])
#:@] NB. Convert each number in `b` to bits
_8:{."1 NB. Take the last 8 items for each
NB. (padding with zeroes at the front)
;@ NB. Make a list of all the bits
-@[ NB. Negate `n`
NB. (\ gives non-overlapping infixes if [<0)
>\ NB. Get non-overlapping n-sized infixes
[:#. NB. Convert those back to decimal
```
[Answer]
## Haskell, ~~112~~ 109 bytes
```
import Data.Digits
import Data.Lists
n#x=unDigits 2.take n.(++[0,0..])<$>chunksOf n(tail.digits 2.(+256)=<<x)
```
Usage example: `5 # [102,48,111,66,97,82]` -> `[12,24,24,6,30,16,19,1,10,8]`.
How it works
```
import Data.Digits -- needed for base 2 conversion
import Data.Lists -- needed for "chunksOf", i.e. splitting in
-- sublists of length n
( =<<x) -- map over the input list and combine the
-- results into a single list:
tail.digits 2.(+256) -- convert to base two with exactly 8 digits
chunksOf n -- split into chunks of length n
<$> -- convert every chunk (<$> is map)
take n.(++[0,0..]) -- pad with 0s
unDigits 2 -- convert from base 2
```
[Answer]
## Java, ~~313~~ ~~306~~ 322 bytes
I hope this beats PHP...
And nope. Stupid long function names.
-7 thanks to @quartata for getting rid of public
+16 to fix an error when the split was exact, thanks to @TheCoder for catching it
```
int[] f(String b,int s){int i=0,o[]=new int[(int)Math.ceil(b.length()*8.0/s)],a=0;String x="",t;for(char c:b.toCharArray()){t=Integer.toString(c,2);while(t.length()<8)t="0"+t;x+=t;a+=8;while(a>=s){o[i++]=Integer.parseInt(x.substring(0,s),2);x=x.substring(s,a);a-=s;}}while(a++<s)x+="0";o[i]=Integer.parseInt(x,2);return o;}
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
8&B!we!XB
```
[Try it online!](https://tio.run/##y00syfn/30LNSbE8VTHC6f9/9eT8lNT0/Jw0dS5zAA "MATL – Try It Online")
Takes input `b` as a string delimited by `''` or as an array of comma-separated values like `[102, 48, 111]`, then `n`.
```
8 # push 8
&B # implicitly take input b, and use 2-element convert to binary
# to push a binary matrix of 8 bits
! # transpose, so each column represents an input
w # implicitly take input n and swap it with binary matrix to top of stack
e # reshape into n rows, padding with zeros at end
# this matrix will have each column as an n-bit integer
! # transpose, so each row is now the n-bit integer
XB # convert each row to decimal
# implicit output
```
[Answer]
# [Perl 5](https://www.perl.org/) `-nl -MData::Dump=pp` , 96 bytes
```
$}=$_;pp map{$_=sprintf"%-$}s",$_;y/ /0/;oct"0b$_"}(join'',map{sprintf"%08b",$_}<>)=~m/.{1,$_}/g
```
[Try it online!](https://tio.run/##PYtBD4IgGEDv/ArHaNYmAS6NNDp57TcwbNVsCt@UDs3RT4/y0vHtvQfXsS9iJEERXQMkg4GZaDXB2Fl/wytKwoSzn3uxhHFWu4vHvCUah/XDdTZNs@X451y2Sx2Op416D2w7i4XYPcYCCZ6jnURCCFSW6LBHMv848J2zU6S2j/TcGG@qqnkOoAC@ "Perl 5 – Try It Online")
Requires the `Data::Dump` module.
Takes `n` on the first line of input and the numbers on each line after that.
Outputs to STDERR (the Debug field on TIO).
Deparsed and tidied:
```
BEGIN { $/ = "\n"; $\ = "\n"; }
use Data::Dump ( split( /,/, 'pp', 0 ) );
LINE: while ( defined( $_ = readline ARGV ) ) {
chomp $_;
$} = $_;
pp(
map( {
$_ = sprintf( "%-$}s", $_ );
tr/ /0/;
oct "0b$_";
} join( '', map( { sprintf '%08b', $_; } readline ARGV ) ) =~
/.{1,$_}/g )
);
}
```
[Answer]
# Powershell 146 bytes
```
param([int[]][char[]]$b,$n)-join($b|%{[convert]::ToString($_,2).PadLeft(8,"0")})-split"(.{$n})"|?{$_}|%{[convert]::ToInt32($_.PadRight($n,"0"),2)}
```
---
Take in the buffer and convert it to a char array and then an integer array. For each of those convert to binary, pad the entries with 0's where needed, and join as one large string. Split that string on *n* characters and drop the blanks that are created. Each element from the split is padded (only the last element really would need it) and converted back into an integer. Output is an array
[Answer]
# Python 3.5 - 312 292 bytes:
```
def d(a, b):
o=[];o+=([str(bin(g)).lstrip('0b')if str(type(g))=="<class 'int'>"else str(bin(ord(g))).lstrip('0b')for g in a]);n=[''.join(o)[i:i+b]for i in range(0,len(''.join(o)),b)];v=[]
for t in n:
if len(t)!=b:n[n.index(t)]=str(t)+'0'*(b-len(t))
v+=([int(str(f),2)for f in n])
return v
```
Although this may be long, this is, in my knowledge, is the shortest way to accept both functions and arrays without errors, and still being able to retain *some* accuracy in Python 3.5.
[Answer]
## Java, ~~253~~ 247 bytes
**Golfed**
```
int i,l,a[];Integer I;String f="";int[]c(String s,int n){for(char c:s.toCharArray())f+=f.format("%08d",I.parseInt(I.toString(c, 2)));while(((l=f.length())%n)>0)f+="0";for(a=new int[l=l/n];i<l;)a[i]=I.parseInt(f.substring(i*n,i++*n+n),2);return a;}
```
**UnGolfed**
```
int i,l,a[];
Integer I;
String f="";
int[]c(String s,int n) {
for(char c:s.toCharArray())
f+=f.format("%08d",I.parseInt(I.toString(c,2)));
while(((l=f.length())%n)>0)
f+="0";
for(a=new int[l=l/n];i<l;)
a[i]=I.parseInt(f.substring(i*n,i++*n+n),2);
return a;
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
+256BḊ€Ẏsz0ZḄ
```
[Try it online!](https://tio.run/##TZI9btxADIWvwj6C4ASweztt/ho37rgarsBgfuThjAC7NFylyDXS5ABG2pxkcxHljaSNA6gYUdTH9x7nq3j/sCxv3l1e3Zxevv15@nn69d0eL@5OL8/L598/luVDyhJIJ6uBXPIpk2khDlI6GlI0GYqUmomdTmqDxpHEa@npC9ASi9h9FZrFk1ghqe0IgGe0KpPyUL1aT5@q90xHlPGqPX3kmtVo1sKyEsl4Uol7Z6DkNFFs5w40qBTIAnjVK7XDTxIgALqrL1kHFSOvB8kJ4jKL4SOlPOiK78iSY4@e/10FHiOTjM3tVP2skXMD61GiowCdt82UWkiOvCSqhUrKePah4B08R7cmch7q4ORQjYrGQV1FZQtlMzvrLDkzjMLllKxKFnJV6R5z9k3ssXVbDYOsaMs5qvlXbE/XHmVgeID1sSJhJqcowOSI/iJhgpDzSjdcg2zTz1ti7HFX10zK8Yg4kU/XFvrqAoS65ud0S76n95ntX0ArfdWzsTRMkp1KWWPE8toVARYXqV/eXv0F "Jelly – Try It Online")
Different from Dennis's answer.
Note: The input is actually a list of non-negative integers, but the TIO link eases the pain for you, and accepts either such a list or a string.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
è■àåk┘K¥xk└╣
```
[Run and debug it](https://staxlang.xyz/#p=8afe85866bd94b9d786bc0b9&i=5,+%22f0oBaR%22%0A50,+%22Hello+World%22%0A1,+[1,2,3,4,5]%0A32,+%22codegolf%22%0A64,+%22codegolf%22%0A7,+%22codegolf%22%0A16,+%22Lorem+ipsum+dolor+sit+amet,+consectetur+adipiscing+elit.+Pellentesque+vel+est+eu+velit+lacinia+iaculis.+Nulla+facilisi.+Mauris+vitae+elit+sapien.+Nullam+odio+nulla,+laoreet+at+lorem+eu,+elementum+ultricies+libero.+Praesent+orci+elit,+sodales+consectetur+magna+eget,+pulvinar+eleifend+mi.+Ut+euismod+leo+ut+tortor+ultrices+blandit.+Praesent+dapibus+tincidunt+velit+vitae+viverra.+Nam+posuere+dui+quis+ipsum+iaculis,+quis+tristique+nisl+tincidunt.+Aliquam+ac+ligula+a+diam+congue+tempus+sit+amet+quis+nisl.+Nam+lacinia+ante+vitae+leo+efficitur,+eu+tincidunt+metus+condimentum.+Cras+euismod+quis+quam+vitae+imperdiet.+Ut+at+est+turpis.%22%0A8,+[2,31,73,127,179,233]&a=1&m=2)
This isn't a function as specified in the challenge, but a program, since stax doesn't support functions. It supports input of strings or array literals.
[Answer]
# [Python 2](https://docs.python.org/2/), 101 bytes
```
lambda a,n:[int(''.join(bin(x+256)[3:]for x in a+[0]*n)[n*i:][:n],2)for i in range((len(a)*8-1)/n+1)]
```
[Try it online!](https://tio.run/##PY8xT8MwEIXn5lfcFru5QuzSECyFgQExszC4HlxiFyPXjkyQ2l8f7FZiOOnuvXf67qbL/BUDX@ywX7w@HUYNGoOQLsykru@@owvkkOvc8F1H5VYoGxOcwQXQjWzVOlAZ1k4oKYJCTovript0OBpCvAlE03W/YfQ@NIyqZTQWXkmGUFGtnIX5MpkcGYafOYlk5t8UwJKTnkhMI2qag9XqXy97VVUouSscKSVrOT70yBjDrsOnR@y5wp1CkLVt44t@rxFu42cczTF6m4UtvypvxvsIHzH5saRapfJVU8rvw5WFUMPmGbJ3u3n5Aw "Python 2 – Try It Online")
[Answer]
# [Dyalog APL](https://www.dyalog.com/), 36 bytes
```
{2∘⊥¨↓A⍴(×/A←⍺,⍨⌈⍺÷⍨8×≢⍵)↑∊↓⍉⍵⊤⍨8/2}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/2uhRx4xHXUsPrXjUNtnxUe8WjcPT9R0ftU141LtL51Hvikc9HUDW4e1ApsXh6Y86Fz3q3ar5qG3io44uoIZHvZ1A/qOuJSBpfaPa/25AndQ1kutR31SgXlMFNwVDAyMFEwsFQ0NDBTMzBUtzBQuj/wA "APL (Dyalog Classic) – Try It Online")
This probably could be golfed down more.
[Answer]
# [Elixir](https://elixir-lang.org/), ~~63~~ 60 bytes
```
&(s=&2-1)&&for<<x::size(&2)<-<<"#{&1}",0::size(s)>> >>,do: x
```
[Try it online!](https://tio.run/##fVPbitswEH3vVwwumAS0Zu3sbtrgDbR9KrTdUugHKNbYDMiSVyOF0NJvT8eXdNsuLPhBnhmdOefMCC2dKJzb@3O@4vu8uirXed76UNen3Y7pB67yal1f1XX2@mde/srU9RLm9X4P@70yfgen88eHghwP2ERoi1XWXvv3@lumbtev/s3UdakqtVE36lbulv@ns8Yb7LxtM7WpXkje3byQ3D7LffIBe6CBUw/GWx@AKYLuMSpovGOpw5gCaEMDcUOuA7QUC/iK1qKLyI8J4YgWkCNgGo8CYLWUkgbSTbLEBXxJ1mpoJSy/VMBnnQIxHClqnBCB9UDolsoevCEPbjwrQROWKLQEeOKLSckl7IWA8E42BmoIGSwdMHghFzSyJMGHhiZ4BeyNtlLzt6ped04DdqPaIdkjOR1GYGrRGeiF5/dRFHHvDVj0kCJEH@RbmgrewWpnJkcuTY0oOSSGSK4hkyQymzKLPdIRQ9AiVFQOnhMGBJMIHqXPMonFNjXHpBFHGn12xPYJtoB3VsICoxuR3iVxWIMhCYjITuoj9oMQuYx0hhtB5u6XKWmZ48JuFIltK3aKP2oc6JMKQUiTf4Zm5wv4EDT/MWhCn/jMWNQPGAxhnGyU4Y0rIrCySEWmyrvnL0D2v1TbjSqrrSq3b1W12chbeLM@/wY "Elixir – Try It Online")
Takes input as Elixir binary, outputs a list of integers.
This code makes use of Elixir bitstring generator comprehension to chunk input binary `&1` into bit blocks of size provided as argument `&2`. To account for any leftover bits at the end, we pad the binary with `&2 - 1` zero bits. Here is also the place where some unwanted verbosity kicks in: Elixir complains if we don't explicitly declare `&1` as bitstring, and it also doesn't support expressions in `size(...)`, hence the need for an extra variable assignment.
Easter egg: in the footer, replace `IO.inspect` with `IO.puts`, and our function magically "translates" Lorem ipsum from Latin to Chinese - [Try it online!](https://tio.run/##fZPdattAEIXv@xSDCsKGjYjkJG6NYmh7VegfhTzAWjsSA6tdZWfXmJY@uzv6cdM2EPCFPLP65pwzK7R0onBu78/5iu/z6qpc53nrQ12fdjumH7jKq3V9VdfZ6595@StT10uZ1/s97PfK@B2czh@/FuR4wCZCW6yy9tq/198zdbt@9W@nrktVqY26Ubfybvl/O2u8wc7bNlOb6oXm3c0Lze3UG1LkqfHJB@yBBk49GG99AKYIuseooPGOBYAxBdCGBuKGXAdoKRbwDa1FF5EfE8IRLSBHwDQ@CsBqOUoaSDfJEhfwJVmroZWy/KUCPusUiOFIUeNEBNYDoVtO9uANeXDjsxKaqESRJeBJLyYlL2EvAkR3sjFQQ8hg6YDBi7igkaUJPjQ04RWwN9rKmb9d9bpzGrAb3Q7JHsnpMIKpRWegF50Poyni3huw6CFFiD7IbxkqvIPVzkyJXIYacXJIDJFcQyZJZQ5lNnukI4agxai4HDwnDAgmETzKnGUTS2xqrskgjjTm7IjtE7aAd1bKgtGNWO@SJKzBkBTEZCfnI/aDCLmsdMaNkHn6ZUta9rioG01i20qcko8aF/rkQghpys/QnHwBH4LmPwFN9EnPzKJ@wGAI4xSjLG@8IoKVi1Rkqrx7fv3l8pdqu1FltVXl9q2qNhv5EN6sz78B "Elixir – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
After a long day of meetings, it feels like I've forgotten how to golf! Will play around with this on the train home later, see if I can improve on it.
```
c_¤ùT8ÃòV úTV mÍ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Y1%2bk%2bVQ4w/JWIPpUViBtzQ&input=ImZvb2JhciIKNQ)
[Answer]
# [PHP](https://php.net/), ~~135~~ ~~129~~ 124 bytes
```
function($b,$n){foreach($b as$c)$a.=sprintf('%08b',$c);foreach(str_split($a,$n)as$s)$d[]=bindec(str_pad($s,$n,0));return$d;}
```
[Try it online!](https://tio.run/##pVdLi9swEL7nV4jFJTGYIMUP2aRpoVDYw0KXXnoIIeThbFJS29je07K/fStZz1HiPNiLkUczo5lvXlK1rz6@fq/2FcrruqyXdV6VdXsoXkbYnyJvN/vYvRab9lAWI28deIX/tivrfLXZs1@0aryN763Gs6aqD0W7Gw2/4HQ9DBh1qtiatl421fHQjrwVl2cyje9t54vZ@lBs803HUK22I69h2wH2/Wmdt6914W2n7x/TgdfmTdug2WA@QGiO5gRPAhSlASKEBChJApTRAKWTRYDiAA13uPyx@j1Ei0CwU8ZNMOGfVH24YMjoKZU/hESaAXNFmGl6zI/HEv0p6@PWqGPMTDBkFjAuxsn@HZpmzTKlHWNtQ6hp3WHcam7JcFNu85fyuBveLZ5EnxKnZ6VpApHpZDJhK8Exp/MV6VYUbGJwhtYRan4hnghSpoTFGZwcSW7jAcFalih6YosIG9QxQicGlopVLKXFH5aQhE6KKPsiaWOKT1MIG7uMJZ1gqCEhyuvUljenERsISaJnZSBmHYk76foSC7IOkuYR9qQ2Dso5msL91NYxcc@BOrqVVkQl8joWhtFySTmSAYj6PCWxUqqDqJG/4oFJSasKYqv6ZfhOBFX@GU1uIRA3gUFk@utGRdicQEA@WXWAQWYbV7S1YlOhbEWI2JhrSDOTtJE0EaQ3p@qQmFozhhgkO1Z1Xm/tgJLXEcgoLKD4k6XeISOUhlLaZK9ueSetRXYvA2ZqF1IGT3BiFMvCsPDhnmlrQFGk50vcLiHQp62gEZCqIMsI7M7w94Y8AdCDmtHu9HTB29JER1pXbaZr1LSDBGBuElhXpZN7lzripd5i7TlFIJ2xG4nTOUzSx3ZbN9VtzTxql4Q1BkATvDw7r/Xs6Ip2GGwzYOTvmdGEYTKm9wdHoZc480EdBhBV3sHmJIuXOvPHVLI93Ywu2DTwGe8S0FlN0RvAbrmQXIb8FMH@fLphcGf05GJxfXqeNgzh9UR/4M0H9FE4jcwN5M76hJhBnN1QacwuTjydWdTuPCS@r5v2Bu5sgl7GOQapZHUCDMdv0jMBnMvC6SUQRsa5ukYJf3AwjuETe1v9G4/H5sLOHyBMHeVOTbg8ZWZOwpBJMIf6t9FisJgOBuqxhuRra9WwFfLRG9Oeb/YleviG1miGHgL0tymLZV7wNwNnn08WyA/4RiH2GYmwU58fn5c/fz25/LtOhr@xOj52hG/xysV08P7xHw "PHP – Try It Online")
Implemented as a function, input buffer is an array of ints and returns an array of ints.
**Output**
```
> b = "f0oBaR", n = 5
[12,24,24,6,30,16,19,1,10,8]
> b = "Hello World", n = 50
[318401791769729,412278856237056]
> b = [1,2,3,4,5], n = 1
[0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,1]
```
[Verify all test cases](https://tio.run/##pVdLi9swEL7nV4jFJTGYIMUP2aRpoVDYw0KXXnoIIeThbFJS29je07K/fStZz1HiPNiLkUczo5lvXlK1rz6@fq/2FcrruqyXdV6VdXsoXkbYnyJvN/vYvRab9lAWI28deIX/tivrfLXZs1@0aryN763Gs6aqD0W7Gw2/4HQ9DBh1qtiatl421fHQjrwVl2cyje9t54vZ@lBs803HUK22I69h2wH2/Wmdt6914W2n7x/TgdfmTdug2WA@QGiO5gRPAhSlASKEBChJApTRAKWTRYDiAA13uPyx@j1Ei0CwU8ZNMOGfVH24YMjoKZU/hESaAXNFmGl6zI/HEv0p6@PWqGPMTDBkFjAuxsn@HZpmzTKlHWNtQ6hp3WHcam7JcFNu85fyuBveLZ5EnxKnZ6VpApHpZDJhK8Exp/MV6VYUbGJwhtYRan4hnghSpoTFGZwcSW7jAcFalih6YosIG9QxQicGlopVLKXFH5aQhE6KKPsiaWOKT1MIG7uMJZ1gqCEhyuvUljenERsISaJnZSBmHYk76foSC7IOkuYR9qQ2Dso5msL91NYxcc@BOrqVVkQl8joWhtFySTmSAYj6PCWxUqqDqJG/4oFJSasKYqv6ZfhOBFX@GU1uIRA3gUFk@utGRdicQEA@WXWAQWYbV7S1YlOhbEWI2JhrSDOTtJE0EaQ3p@qQmFozhhgkO1Z1Xm/tgJLXEcgoLKD4k6XeISOUhlLaZK9ueSetRXYvA2ZqF1IGT3BiFMvCsPDhnmlrQFGk50vcLiHQp62gEZCqIMsI7M7w94Y8AdCDmtHu9HTB29JER1pXbaZr1LSDBGBuElhXpZN7lzripd5i7TlFIJ2xG4nTOUzSx3ZbN9VtzTxql4Q1BkATvDw7r/Xs6Ip2GGwzYOTvmdGEYTKm9wdHoZc480EdBhBV3sHmJIuXOvPHVLI93Ywu2DTwGe8S0FlN0RvAbrmQXIb8FMH@fLphcGf05GJxfXqeNgzh9UR/4M0H9FE4jcwN5M76hJhBnN1QacwuTjydWdTuPCS@r5v2Bu5sgl7GOQapZHUCDMdv0jMBnMvC6SUQRsa5ukYJf3AwjuETe1v9G4/H5sLOHyBMHeVOTbg8ZWZOwpBJMIf6t9FisJgOBuqxhuRra9WwFfLRG9Oeb/YleviG1miGHgL0tymLZV7wNwNnn08WyA/4RiH2GYmwU58fn5c/fz25/LtOhr@xOj52hG/xysV08P7xHw "PHP – Try It Online")
[Answer]
# APL(NARS), 471 chars, 942 bytes
```
TH←{v←↑⍴⍴⍵⋄v>2:64⋄v=2:32⋄(v=1)∧''≡0↑⍵:20⋄''≡0↑⍵:4⋄v=1:16⋄⍵≢+⍵:8⋄⍵=⌈⍵:2⋄1}
TV←{x←TH¨⍵⋄k←↑x⋄t←↑⍴⍵⋄t=+/x=2:2⋄t=+/x≤2:1⋄(k≤8)∧⍬≡x∼k:k⋄0}
T←{v←↑⍴⍴⍵⋄v>2:64+TV⍵⋄v=2:32+TV⍵⋄(v=1)∧''≡0↑⍵:20⋄''≡0↑⍵:4⋄v=1:16+TV⍵⋄⍵≢+⍵:8⋄⍵=⌈⍵:2⋄1}
RI←{t←T⍵⋄(t≠1)∧(t≠2)∧(t≠17)∧(t≠18):0⋄∧/((1⊃⍺)≤⍵)∧⍵≤(2⊃⍺)}
B←{(8⍴2)⊤⍵}⋄C←{¯1+⎕AV⍳⍵}⋄f←{t←T⍵⋄(0 255 RI⍵)∧18=t:∊B¨⍵⋄(0 255 RI x←C¨⍵)∧20=t:∊B¨x⋄,¯1}⋄W←{((↑⍴⍵)⍴2)⊥⍵}
q←{(∼1 64 RI,⍺)∨2≠T⍺:,¯1⋄x←f⍵⋄¯1=↑x:,¯1⋄t←↑⍴x⋄k←(⍺-m)×0≠m←⍺∣t⋄W⍉((t+k)÷⍺)⍺⍴(((t⍴1),k⍴0)\x)}
```
commented code and test:
```
⍝TH⍵ return type its argument
TH←{v←↑⍴⍴⍵⋄v>2:64⋄v=2:32⋄(v=1)∧''≡0↑⍵:20⋄''≡0↑⍵:4⋄v=1:16⋄⍵≢+⍵:8⋄⍵=⌈⍵:2⋄1}
⍝ TV⍵ check if type each element of array ⍵ is the same and basic
⍝ (float(int and float too),int,char,complex) and return its number (or 0 if it is not basic)
TV←{x←TH¨⍵⋄k←↑x⋄t←↑⍴⍵⋄t=+/x=2:2⋄t=+/x≤2:1⋄(k≤8)∧⍬≡x∼k:k⋄0}
⍝ T⍵ return the type of ⍵ [it would be ok if ⍵ is not a function]
⍝|1 Float|2 Int|4 Char|8 Complex,Quaternion or Oction|16 List|32 Matrix|64 Tensor
⍝|17 List Float|18 List Int|20 List Char=string|etc
T←{v←↑⍴⍴⍵⋄v>2:64+TV⍵⋄v=2:32+TV⍵⋄(v=1)∧''≡0↑⍵:20⋄''≡0↑⍵:4⋄v=1:16+TV⍵⋄⍵≢+⍵:8⋄⍵=⌈⍵:2⋄1}
⍝ ⍺RI⍵ check if the numeric array ⍵ has elements in [1⊃⍺ 2⊃⍺]; if type is not ok return 0(false)
RI←{t←T⍵⋄(t≠1)∧(t≠2)∧(t≠17)∧(t≠18):0⋄∧/((1⊃⍺)≤⍵)∧⍵≤(2⊃⍺)}
B←{(8⍴2)⊤⍵} ⍝ from decimal to binary of element 0..255
C←{¯1+⎕AV⍳⍵} ⍝ return the number of char that is in array AV seems the ascii number
⍝ f⍵ with ⍵ List int element in 0..255 or String with numeric element 0..255
⍝ return the corrispondence disclosed binary array
f←{t←T⍵⋄(0 255 RI⍵)∧18=t:∊B¨⍵⋄(0 255 RI x←C¨⍵)∧20=t:∊B¨x⋄,¯1}
W←{((↑⍴⍵)⍴2)⊥⍵} ⍝ from list of binary digit to decimal
⍝ the function for the exercise
q←{(∼1 64 RI,⍺)∨2≠T⍺:,¯1⋄x←f⍵⋄¯1=↑x:,¯1⋄t←↑⍴x⋄k←(⍺-m)×0≠m←⍺∣t⋄W⍉((t+k)÷⍺)⍺⍴(((t⍴1),k⍴0)\x)}
5 q 'f0oBaR'
12 24 24 6 30 16 19 1 10 8
50 q "Hello World"
318401791769729 412278856237056
1 q 1 2 3 4 5
0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 1
32 q "codegolf"
1668244581 1735355494
7 q "codegolf"
49 91 108 70 43 29 94 108 51 0
8 q 2 31 73 127 179 233
2 31 73 127 179 233
64 q 2 31 73 127 179 233
1.529217252E17
65 q 2 31 73 127 179 233
¯1
0 q 2 31 73 127 179 233
¯1
23 q '123'
1612057 4194304
23 q '123∞'
¯1
23 q '1' 2 3
¯1
23 q 2 3.3
¯1
23 q 2
¯1
23 q '1'
¯1
23 q ,2
65536
23 q ,'1'
1605632
```
] |
[Question]
[
(Inspired by an early draft of [PhiNotPi's fractal line challenge](https://codegolf.stackexchange.com/q/47701/8478).)
You're given a width `W > 1`, a height `H > 1` and string consisting of `2(W+H-2)` printable ASCII characters. The task is to print this string wrapped around a rectangle of the given width and height, starting in the top left corner, in a clockwise sense. The rectangle's inside is filled with spaces. The test cases should hopefully make this very clear.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument, and either printing the result to STDOUT (or closest alternative) or returning it as a string.
There must be no leading or trailing spaces (apart from those that might be in the input string). You may optionally output a single trailing newline.
This is code golf, so the shortest submission (in bytes) wins.
## Test Cases
Each test case is `"String" W H` followed by the expected output.
```
"Hello, World! "
5 4
Hello
,
!
dlroW
"+--+|||+--+|||"
4 5
+--+
| |
| |
| |
+--+
">v<^"
2 2
>v
^<
"rock beats scissors beats paper beats "
11 10
rock beats
s
s c
t i
a s
e s
b o
r
r s
epap staeb
Note that the following string contains an escaped '"'.
"!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
46 3
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMN
~ O
}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQP
```
## Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
```
function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=0,c=0,p=-1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);t++;c=p==o?c:t;i=i.replace("{{PLACE}}",c+".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);p=o;$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=47710;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/
```
```
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>Language<td>Size<tbody id=answers></table></div><div id=language-list><h2>Winners by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}</td><td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table>
```
[Answer]
## Python 2, 95 bytes
```
s,m,n=input()
print s[:n]
for i in range(m-2):print s[~i]+' '*(n-2)+s[n+i]
print s[1-m::-1][:n]
```
Prints the first line, then the two vertical lines, then the last line.
There's got to be something shorter than writing `print` three times, but everything I've tried so far with saving to a variable and `'\n'.join` has been longer.
[Answer]
# CJam, 27 bytes
```
Nl~:L/(os\2-{)L2-S*@(N@}*W%
```
I don't really CJam, but I think this beats Martin. The main difference is that we push a newline *before* reading input and print the first line immediately, negating the need to store the height.
Takes input in the order
```
H "String" W
```
[Try it online.](http://cjam.aditsu.net/#code=Nl%7E%3AL%2F%28os%5C2-%7B%29L2-S*%40%28N%40%7D*W%25&input=10%20%22rock%20beats%20scissors%20beats%20paper%20beats%20%22%2011)
[Answer]
# CJam, ~~31~~ 30 bytes
At Optimizer's insistence, here is my own attempt. I'm not a fan of winning my own challenges, so I'm counting the APL family (or someone better at CJam) to beat this. ;)
```
l~:H;:V/(N@s{)V2-S*@(N@}H2-*W%
```
Takes input in the same order as given in the question:
```
"Hello, World! " 5 4
```
[Test it here.](http://cjam.aditsu.net/#code=l~%3AH%3B%3AV%2F(N%40s%7B)V2-S*%40(N%40%7DH2-*W%25&input=%22Hello%2C%20World!%20%22%205%204)
One byte saved thanks to Optimizer.
## Explanation
Originally, I had a really nice idea for starting with the rectangle of spaces and then literally wrapping the string around it while rotating the entire grid four times. However, I couldn't seem to get that to work in case where width or height or both are `2`. So I tried the naive approach (print top, loop over sides, print bottom), and surprisingly it turned out to be really short.
```
l~ "Read and evaluate the input.";
:H; "Store the height in H and discard it.";
:V/ "Store the width in V and split the input into chunks of size V.";
(N "Slice off the first such chunk and push a newline.";
@s "Pull up the other chunks and join them back together.";
{ }H2-* "Repeat this block H-2 times, printing the sides.";
) "Slice off the last character of the string.";
V2-S* "Push V-2 spaces.";
@( "Pull up the remaining string and slice off the first character.";
N@ "Push a newline and pull up the remaining string.";
W% "Reverse the remainder of the string, which is the bottom row.";
```
[Answer]
# Pyth, 47 46 45 40 37 36 bytes
This is the obvious approach implemented in Pyth. It prints the first line by indexing `0:width` and then the middle, then the end.
Thanks to @Jakube for the tip with using `z` and `Q` for two inputs and using `p`.
```
AkYQ<zkV-Y2p*d-k2@zt_N@z+kN;<_<z-2Yk
```
Takes input from stdin as a string and as a tuple of dimensions, newline separated:
```
Hello, World!
5, 4
```
and writes to stdout.
[Try it here](http://pyth.herokuapp.com/?code=AkYQ%3CzkV-Y2p*d-k2%40zt_N%40z%2BkN%3B%3C_%3Cz-2Yk&input=Hello%2C+World!+%0A5%2C+4).
```
A Double assignment
kY The vars k and Y
Q The dimension tuple
<zk Prints out first line by doing z[:width]
V-Y2 For N in height-2
p Print out everything
*d Repeat " "
-k2 Width-2 times
@z Index z
-_N1 At index -N-1
@z Index z
+kN At index k+N
; Close out loop
<_<z-2Yk Print last line
```
[Answer]
# J, 61 bytes
Method:
Starting from a `(height-2)*(width-2)` block of spaces we take the necessary amount of characters from the end of the string and add it to the current block. We repeat this 4 times. The total 5 states illustrated with the `'Hello, World! ' 5 4` example (spaces replaced with `X`s for readability):
```
XXX !_ orld ,_W Hello
XXX XX XXX! XXo _XXX,
XX XXX_ XXr !XXX_
XX XXl dlroW
_!d
```
The code:
```
4 :'|:>{:((}.~{:@$);({.~{:@$)|.@|:@,])&>/^:4(|.x);'' ''$~y-2'
```
Explicit function definition. The two-operand function takes a string as left argument and a list of two integers as right argument.
Example usage:
```
wrap_on=.4 :'|:>{:((}.~{:@$);({.~{:@$)|.@|:@,])&>/^:4(|.x);'' ''$~y-2'
'Hello, World! ' wrap_on 5 4
Hello
,
!
dlroW
'>v<^' wrap_on 2 2
>v
^<
```
[Try it online here.](http://tryj.tk/)
[Answer]
# Pyth, ~~38~~ 37
```
AGHQ<zGFNC,_>z_ttH>zGj*dttGN)<>_zttHG
```
I originally had a different 38 solution, but it was basically golfed solution of Maltysen's answer. So I decided to go a little bit different.
Try it [online](https://pyth.herokuapp.com/?code=AGHQ%3CzGFNC%2C_%3Ez_ttH%3EzGj*dttGN)%3C%3E_zttHG&input=Hello%2C+World!+%0A5%2C+4&debug=0).
```
implicit: z=string from input, Q=pair of numbers from input
AGHQ G=Q[0] (width), H=Q[1] (height)
<zG print z[:G]
_>z_ttH last H-2 chars reversed
>zG all chars from the Gth position to end
C, zip these 2 strings to pairs
FN for each pair N:
j*dttGN seperate the two chars by (G-2) spaces and print
) end for
<>_zttHG print last line z[::-1][H-2:][:G]
```
[Answer]
# JavaScript (ES6), 110 ~~115~~
Function with 3 parameters, returning a string
```
F=(s,w,h,q=h+(w-=2),t=b='')=>
[for(c of s)q?t+=q<h?c+'\n'+s[w+h+w+q--]+' '.repeat(q&&w):(b+=s[w+q--],c):q]
&&t+b
```
**Chrome** version **119**: no short format for functions, no default parameters. No reason to use `for(of)` even if it is supported
```
function F(s,w,h){
for(q=h+(w-=2),t=b=i='';
q;
q<h?t+='\n'+s[w+h+w+q--]+' '.repeat(q&&w):b+=s[w+q--])
t+=s[i++];
return t+b
}
```
**ES5** version **126**: no for(of), no string.repeat
```
function F(s,w,h){
for(q=h+(w-=2),t=b=i='';
q;
q<h?t+='\n'+s[w+h+w+q--]+Array(q&&-~w).join(' '):b+=s[w+q--])
t+=s[i++];
return t+b
}
```
**Ungolfed**
```
F=(s,w,h)=>
{
var q = h+(w-=2), // middle length
t = '', // top and body
b = ''; // bottom row
for(c of s)
if (q > 0)
{
if (q < h)
{
t += c+'\n'; // right side, straight
t += s[w+h+w+q]; // left side, backwards
if (q > 1) // body fill, except for the last line
t += ' '.repeat(w)
}
else
{
t+=c, // top, straight
b+=s[w+q] // bottom, backwards
}
--q
}
return t+b
```
**Test** In Firefox/FireBug console
```
;[["Hello, World! ", 5, 4],["+--+|||+--+|||",4,5],[">v<^",2,2]
,["rock beats scissors beats paper beats ",11,10]
,["!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",46,3]]
.forEach(test => console.log(F(...test)))
```
*Output*
```
Hello
,
!
dlroW
+--+
| |
| |
| |
+--+
>v
^<
rock beats
s
s c
t i
a s
e s
b o
r
r s
epap staeb
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMN
~ O
}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQP
```
[Answer]
# Python 2, 97 bytes
```
def f(s,w,h):print s[:w];i=0;exec'print s[~i]+" "*(w-2)+s[w+i];i+=1;'*(h-2);print s[1-h:w+h-3:-1]
```
Taking the direct approach.
[Answer]
# Haskell, ~~164~~ 156 bytes
```
import Data.List
r=replicate
p w h(s:t)=unlines$fst$n$n$n$n(r h$r w ' ',(w,h,s:t++[s]))
n(_:b,(w,h,s))=(transpose$map reverse$(take w s):b,(h,w,drop(w-1)s))
```
The function `p` doesn't print the output, but returns it as a string, e.g `p 4 5 "+--+|||+--+|||"` -> `"+--+\n| |\n| |\n| |\n+--+\n"`. For better display use `putStr`:
```
putStr $ p 4 5 "+--+|||+--+|||"
+--+
| |
| |
| |
+--+
```
How it works: I create a `w` x `h` block of spaces and replace the first line with the beginning of the input string. Then I rotate the block counterclockwise and repeat replacing the first line another three times.
To prevent cutting of the first character again after turn #4, I append it to the input string before starting.
```
"Hello World" example, 5 x 4
| Start Turn #1 Turn #2 Turn #3 Turn #4
---------+--------------------------------------------------------------------
String | "Hello, World! H" "o, World! H" "World! H" "d! H" ""
left |
|
Block | <empty> Hello o, W World d! H
before | l l e
rotating | l , r l
| e olleH o l
| H W ,o
```
Edit: found a better way to solve the cut-off-first-character-after-turn-#4 problem.
[Answer]
# Postscript, 62 bytes
This of course uses binary tokens, but it is equivalent to:
```
/Courier findfont setfont
0 h moveto
s [
w {1 0} repeat pop pop
h {0 -1} repeat pop pop
w {-1 0} repeat pop pop
h {0 1} repeat
] xyshow
```
Here is a hexdump of the file (`xxd round.ps`):
```
0000000: 91c7 9243 9295 3020 6892 6b73 5b77 7b31 ...C..0 h.ks[w{1
0000010: 2030 7d92 8392 7592 7568 7b30 202d 317d 0}...u.uh{0 -1}
0000020: 9283 9275 9275 777b 2d31 2030 7d92 8392 ...u.uw{-1 0}...
0000030: 7592 7568 7b30 2031 7d92 835d 92c3 u.uh{0 1}..]..
```
Run as:
```
gs -dw=11 -dh=10 -ss="rock beats scissors beats paper beats " round.ps
```
The output is really small (as a result of not scaling the font at all), so you need to zoom in a fair bit to see it.
This takes advantage of the `xyshow` operator to write out the string using custom character spacings. In this case, I use the negative vertical spacing to write down, then negative horizontal space to write backwards, then positive vertical space to write upward. Because of this, I don't need to use any sort of string manipulation.
[Answer]
# ><>, ~~82~~ 80 + 3 = 83 bytes
```
:2-&\
v!?:<oi-1
/?(0:i
\~ao{2-{~}
\{:?!v1-}o&:&
>:?v!~{{o}ao4.
^ >" "o1-
o;!?l<
```
**[Esolang page for ><> (Fish)](https://esolangs.org/wiki/Fish)**
This turned out to be shorter than I expected. It uses the straightforward approach of printing the first line, then the columns padded with the central spaces, then the last line.
Input the string via STDIN and the height and width via command line with the `-v` flag, like so:
```
py -3 fish.py round.fish -v <height> <width>
```
---
## Explanation
```
:2-& Put W-2 in the register
:?!v1-io Directly print the first W characters of the input
i:0(?/ Read the rest of the input
~ao{2-{~} Pop a few leftovers 0s from above, decrement H by 2 and print a newline
Stack now consists of H = H-2 at the bottom and the rest of the input reversed
[loop]
{:?!v If H is 0...
~ Pop the 0
l?!;o Print the rest of the (reversed) input
Otherwise...
1-} Decrement H
o Output the top of stack
&:& Copy I = W-2 from the register
:? If I is nonzero...
" "o1- Print a space and decrement I, then repeat from the previous line
{{o}ao Print the bottom input character and output a newline
4. Jump to the start of the loop (note that I = 0 is leftover from above)
```
[Answer]
# Bash+coreutils, 124
A shell script to get you started:
```
echo "${3:0:$1}"
fold -1<<<"${3:$1*2+$2-2}"|tac|paste - <(fold -1<<<"${3:$1:$2-2}")|expand -t$[$1-1]
rev<<<"${3:$1+$2-2:$1}"
```
Pass input as command-line args:
```
$ ./roundnround.sh 5 4 "Hello, World! "
Hello
,
!
dlroW
$
```
[Answer]
# JavaScript, ~~161~~ ~~160~~ 158 bytes
The method I've come up with turned out way too long, but oh well, it's been practice. (Also, I got it to spell out `r+o[u]+'\n':d`.)
```
function f(o,w,n){s=o.slice(0,w)+'\n';o=o.slice(w);n-=2;r='';for(u=w-2;u--;)r+=' ';for(u=d=0;d=o[2*n+w+~u],u<w+n;u++)s+=(u<n)?(d||' ')+r+o[u]+'\n':d;return s}
```
For input that doesn't make sense the output is undefined (literally, and a bunch of times), but it works for all the test cases.
[Answer]
# Groovy, 140
```
f={a,x,y->println a.substring(0,x);(1..y-2).each{println a[a.length()-it]+' '*(x-2)+a[it+x-1]}println a.substring(x+y-2,2*x+y-2).reverse()}
```
call:
```
f('rock beats scissors beats paper beats ',11,10)
```
output:
```
rock beats
s
s c
t i
a s
e s
b o
r
r s
epap staeb
```
[Answer]
# K, 55 54 bytes
Using the same approach as randomra's J implementation; Start with a block of spaces and add from the tail of the string to the edge while rotating four times:
```
f:{`0:*4{((,r#*|x),|:'+*x;(r:-#*x)_*|x)}/((y-2)#" ";x)}
```
And some examples:
```
f["Hello,_World!_";4 5]
Hello
_ ,
! _
dlroW
f[">v<^";2 2]
>v
^<
```
Breaking it down a little for readability,
Generate an NxM block:
```
t:2 3#!6
(0 1 2
3 4 5)
```
Rotate 90 degrees by using transpose(`+`) and reverse-each (`|:'`):
```
|:'+t
(3 0
4 1
5 2)
```
So if we have a block of spaces `t` and a string `s`, we can prepend a slice of the tail of `s` to `t`:
```
s: 12 18 17 8 9
12 18 17 8 9
(,(-#t)#s),|:'+t
(8 9
3 0
4 1
5 2)
```
We use the form `4 {[x] ... }/( ... )` to repeatedly apply a function to a tuple consisting of the string and the matrix we're building. Each time we do this rotate-and-concatenate step we also chop down the string.
**edit:**
Another idea is to try splitting the input string into the fragments we want at each rotation, which simplifies the main body of the program. Unfortunately this works out to be slightly longer at 56 bytes:
```
f:{`0:((y-2)#" "){|:'(,y),+x}/(+\(0,y[0 1 0]-2 1 1))_|x}
```
If there's a better way to calculate those split points I'm open to suggestions.
**edit2:**
Rearranging slightly lets me remove a pair of parentheses. 54 bytes!
```
f:{`0:((y-2)#" "){|:'(,y),+x}/(0,+\y[0 1 0]-2 1 1)_|x}
```
[Answer]
# K, 80 68 bytes
```
f:{[s;y;n]`0:(,n#s),({s[(#s)-x+2],((n-2)#" "),s@n+x}'!y-2),,n#|-4!s}
```
Shortened from 80 thanks to @JohnE.
Original:
```
f:{s:x;n:z;`0:(,s@!n),({s[(#s)+-2-x],({" "}'!n-2),s@n+x}'!y-2),,(|s@!-4+#s)@!n}
```
I barely even know how this thing works.
Example usage:
```
f["Hello, world! ";5;4]
```
There are some possible optimizations, but I keep making Kona segfault...
[Answer]
# R, 178
This is an unnamed function taking `s, w, h` as parameters. I wish there was a nicer way to split the string.
```
function(s,w,h){W=w+h-1;H=w+W-1;S=strsplit(s,'')[[1]];O=array(" ",c(h,w+1));O[,w+1]="\n";O[1:h,c(w,1)]=c(S[w:W],S[(W+W-1):H]);O=t(O);O[1:w,c(1,h)]=c(S[1:w],S[H:W]);cat(O,sep='')}
```
Ungolfed
```
W=w+h-1; # additional index points
H=w+W-1; # additional index points
S=strsplit(s,'')[[1]]; # vectorize the string
O=array(" ",c(h,w+1)); # create an array of spaces
O[,w+1]="\n"; # set newlines
O[1:h,c(w,1)]=c(S[w:W],S[(W+W-1):H]); # build middles lines
O=t(O); # transpose array
O[1:w,c(1,h)]=c(S[1:w],S[H:W]); # build top and bottom lines
cat(O,sep='') # cat out results
```
Test run
```
> (function(s,w,h){W=w+h-1;H=w+W-1;S=strsplit(s,'')[[1]];O=array(" ",c(h,w+1));O[,w+1]="\n";O[1:h,c(w,1)]=c(S[w:W],S[(W+W-1):H]);O=t(O);O[1:w,c(1,h)]=c(S[1:w],S[H:W]);cat(O,sep='')})("Hello, World! ",5,4)
Hello
,
!
dlroW
> (function(s,w,h){W=w+h-1;H=w+W-1;S=strsplit(s,'')[[1]];O=array(" ",c(h,w+1));O[,w+1]="\n";O[1:h,c(w,1)]=c(S[w:W],S[(W+W-1):H]);O=t(O);O[1:w,c(1,h)]=c(S[1:w],S[H:W]);cat(O,sep='')})("+--+|||+--+|||",4,5)
+--+
| |
| |
| |
+--+
> (function(s,w,h){W=w+h-1;H=w+W-1;S=strsplit(s,'')[[1]];O=array(" ",c(h,w+1));O[,w+1]="\n";O[1:h,c(w,1)]=c(S[w:W],S[(W+W-1):H]);O=t(O);O[1:w,c(1,h)]=c(S[1:w],S[H:W]);cat(O,sep='')})(">v<^",2,2)
>v
^<
> (function(s,w,h){W=w+h-1;H=w+W-1;S=strsplit(s,'')[[1]];O=array(" ",c(h,w+1));O[,w+1]="\n";O[1:h,c(w,1)]=c(S[w:W],S[(W+W-1):H]);O=t(O);O[1:w,c(1,h)]=c(S[1:w],S[H:W]);cat(O,sep='')})("rock beats scissors beats paper beats ",11,10)
rock beats
s
s c
t i
a s
e s
b o
r
r s
epap staeb
> # Escaped the \ as well
> (function(s,w,h){W=w+h-1;H=w+W-1;S=strsplit(s,'')[[1]];O=array(" ",c(h,w+1));O[,w+1]="\n";O[1:h,c(w,1)]=c(S[w:W],S[(W+W-1):H]);O=t(O);O[1:w,c(1,h)]=c(S[1:w],S[H:W]);cat(O,sep='')})("!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",46,3)
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMN
~ O
}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQP
>
```
[Answer]
# T-SQL, 307
While still horrendously long, this turned out to be quite a bit easier (and shorter) than I thought in a query. Implemented as an inline table valued function for T-SQL.
```
CREATE FUNCTION f(@S VARCHAR(MAX),@ INT,@H INT)RETURNS TABLE RETURN WITH R AS(SELECT 2i,LEFT(@S,@)S,STUFF(@S,1,@,'')+'|'R UNION ALL SELECT i+1,CASE WHEN i<@H THEN LEFT(RIGHT(R,2),1)+REPLICATE(' ',@-2)+LEFT(R,1)ELSE REVERSE(LEFT(R,@))END,STUFF(STUFF(R,LEN(R)-1,1,''),1,1,'')FROM R WHERE i<=@H)SELECT S FROM R
```
This recurses through the string @h times. First recursion clips @W characters from the string. The middle recursions take the last and first from remaining string with string padding between. The last recursion reverses what is left. There is a few lost characters dealing with the way SQL Server treats trailing spaces on VARCHARS.
**Test Run**
```
WITH TestSet AS (
SELECT *
FROM (VALUES
('Hello, World! ',5,4),
('+--+|||+--+|||',4,5),
('>v<^',2,2),
('rock beats scissors beats paper beats ',11,10),
('!"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~andfoure',50,3)
) Test(S,W,H)
)
SELECT x.S
FROM TestSet
CROSS APPLY (
SELECT S FROM dbo.F(S,W,H)
)x
S
----------------------------
Hello
,
!
dlroW
+--+
| |
| |
| |
+--+
>v
^<
rock beats
s
s c
t i
a s
e s
b o
r
r s
epap staeb
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQR
e S
ruofdna~}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUT
(24 row(s) affected)
```
[Answer]
# Pyth, 33 bytes
```
J-vw2<zQFkC,_z<>zQJj*-Q2dk;<>_zJQ
```
[Demonstration.](https://pyth.herokuapp.com/?code=J-vw2%3CzQFkC%2C_z%3C%3EzQJj*-Q2dk%3B%3C%3E_zJQ&input=rock%20beats%20scissors%20beats%20paper%20beats%20%0A11%0A10&debug=0)
[Answer]
# MATLAB, 101
```
function f(H,W,S)
w=1:W;h=(0:H-3).';n=W+H-2;S(3*n)=' ';S([w;[2*n-h,3*n*ones(H-2,W-2),h+W+1];n-w+W+1])
```
[Answer]
# C++, 398 bytes
**Compiler used - *GCC 4.9.2* with `-std=c++14` flag**
```
#include<bits/stdc++.h>
using namespace std;string s;vector<vector<char>> M;int w,h,p,i,j;void F(int x,int y){if(p<s.size()&&(((!y||y==h-1)&&x>=0&&x<w)||((!x||x==w-1)&&y>=0&&y<h))&&!M[y][x])M[y][x]=s[p++],F(x+1,y),F(x,y+1),F(x-1,y),F(x,y-1);}int main(){getline(cin,s);cin>>w>>h;M.resize(h,vector<char>(w,0));F(0,0);while(i<h){j=0;while(j<w){if(!M[i][j])M[i][j]=32;cout<<M[i][j++];}i++;cout<<endl;}}
```
[Test it here.](http://ideone.com/IQsBuJ)
## Explanation
```
#include<bits/stdc++.h>
using namespace std;
string s; // input string
vector<vector<char>> M; // output matrix
int w, h, p, i, j;
// w = width
// h = height
// p = iterator over s
// i, j = iterators used later for printing answer
void F( int x, int y )
{
// If the coordinates (x, y) are either on the first row/column or the last row/column and are not already populated with the input characters, populate them
if ( p < s.size() && ( ( ( y == 0 || y == h - 1 ) && x >= 0 && x < w ) || ( ( x == 0 || x == w - 1 ) && y >= 0 && y < h ) ) && !M[y][x] )
{
M[y][x] = s[p++];
F( x + 1, y );
F( x, y + 1 );
F( x - 1, y );
F( x, y - 1 );
}
}
int main()
{
getline( cin, s );
cin >> w >> h;
// Input taken !!
M.resize( h, vector<char>( w, 0 ) ); // Fill the matrix with null characters initially
F( 0, 0 ); // This function does all the work
// Now printing the matrix
while ( i < h )
{
j = 0;
while ( j < w )
{
if ( !M[i][j] )
{
M[i][j] = ' '; // Replace '\0' with ' '
}
cout << M[i][j++];
}
i++;
cout << endl;
}
}
```
[Answer]
# Perl, 193 ~~195~~ bytes
```
($s,$w,$h,$i,$y)=(@ARGV,0,2);
$o.=substr$s,$i,$w;
$i+=$w;
$o.=sprintf"\n%s%*s",substr($s,2*($w+$h)-$y++-3,1)||' ',$w-1,substr($s,$i++,1)while$y<$h;
print$o."\n".reverse(substr($s,$i,$w))."\n";
```
I'm sure this can be greatly improved. I'm a noob. >,<
[Answer]
# Java 11, 180 bytes
```
(s,w,h)->{var r=s.substring(0,w)+"\n";int i=w;for(var S=s.split("");i<w+h-2;)r+=S[3*w+2*h-i-5]+" ".repeat(w-2)+S[i++]+"\n";return r+new StringBuffer(s.substring(i,i+w)).reverse();}
```
[Try it online](https://tio.run/##nVNrl9IwEP2@v2K2PrYhaXmvjwLq6uq6uvhAXRXYNZSwDZS2JikVAf86ppBz0HP0C1/Smc7Nzcw9d8Z0Rp3xcLL2QyolXFAeLQ4AeKSYGFGfQTtPATpK8OgGfNsEkmgIZJszQJ7GrA70IRVV3Ic2RNCEtS1JRgLktBYzKkA0pSvTgdwQ2CWSIWz1IsvLKXgz80axsHNcJ8clIVe2ZSGPNzIcOBUPCdzsdKuFDFcKgcOdeh8LljCqUWCRzKkg3OlyjPtbUsFUKiIQOGKZaf4kHY2YsP9sghOOM4RcwWZMSGYjb7X28jmSdBDqOcw4s5gPYaqlMdN3@0CR0WUuFZu6carcRJdUGNmR69vWGQvDmMBlLMLhoW6wTmpoI9M/r/y/siHDjoOXy6X5WKRG6vuTtWaNK4tUSGV/ChH7Exho7SVIn0sZC2nShCZMmNgi5TIpl/Z/5rBn3bp95@6RjQqYOG6xVK5Ua/Xje/cfPPQazdajx09Onj47ff7i7OX5q9cX7Tdv373vfPj46fLzl6/dXq9/df2NDvwhG90EfDwJp1GcfBdSpbPsx/znYrn6pYU8JlW0c2@xCKfTNKSKSTjXiwHl8pE07nGN23R/CKgEk26LZPNXGxhUwEDSKYPBXDHHj9NI7dbC7M5fV3VNbLaITnOwsZWx7868dh76ARXdLa6fmzYJ9YbaVq9kEc1i5litfwM) (NOTE: `String.repeat(int)` is emulated as `repeat(String,int)` for the same byte-count, because Java 11 isn't on TIO yet.)
**Explanation:**
```
(s,w,h)->{ // Method with String & 2 int parameters and String return-type
var r=s.substring(0,w)+"\n";
// Result-String, starting at the the first row of output,
// which is a substring in the range [0, `w`)
int i=w; // Index-integer, starting at `w`
for(var S=s.split(""); // Split the input-String into a String-array of characters
i<w+h-2;) // Loop `i` in the range [`w`, `w+h-2`)
r+= // Append the result-String with:
S[3*w+2*h-i-5] // The character at index `2*w+2*h-4 - i+w-1`
+" ".repeat(w-2) // Then append `w-2` amount of spaces
+S[i++] // Then append the character at index `i`
+"\n"; // And a trailing new-line
return r // After the loop, return `r` as result
+new StringBuffer(s.substring(i,i+w)).reverse();
// Appended with the last row of output,
// which is a substring in the range [`i`, `i+w`) reversed
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal/wiki), 4 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page)
```
BNNS
```
[Try it online (verbose)](https://tio.run/##S85ILErOT8z5/98pv0LDM6@gtMSvNDcptUhDU0cBGze4pCgzL11DU/P/f0NDLkMDrqL85GyFpNTEkmKF4uTM4uL8omIotyCxILUIyv6vW5YDAA) or [try it online (pure)](https://tio.run/##S85ILErOT8z5///9nkXv96wDo83//xsachkacBXlJ2crJKUmlhQrFCdnFhfnFxVDuQWJBalFUDYA).
**Explanation:**
Basically a builtin for this challenge. Take the first two integer-inputs as width and height, and prints a box with the third input-string as border:
```
Box(InputNumber(), InputNumber(), InputString())
BNNS
```
] |
[Question]
[
## Intro
The Tetris Guidelines specify what RNG is needed for the piece selection to be called a Tetris game, called the Random Generator.
Yes, that's the actual name (["Random Generator"](https://tetris.wiki/Random_Generator)).
In essence, it acts like a bag without replacement: You can draw pieces out of the bag, but you cannot draw the same piece from the bag until the bag is refilled.
Write a full program, function, or data structure that simulates such a bag without replacement.
## Specification
Your program/function/data structure must be able to do the following:
* Represent a bag containing 7 distinct integers.
* Draw 1 piece from the bag, removing it from the pool of possible pieces. Output the drawn piece.
* Each piece drawn is picked uniformly and randomly from the pool of existing pieces.
* When the bag is empty, refill the bag.
## Other Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte count wins!
* [Standard loopholes are forbidden.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* [You can use any reasonable I/O method.](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
### "Bonuses"
These bonuses aren't worth anything, but imaginary internet cookies if you are able to do them in your solution.
* Your bag can hold an arbitrary `n` distinct items.
* Your bag can hold any type of piece (a generic bag).
* Your bag can draw an arbitrary `n` number of pieces at once, refilling as needed.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
Inspired by [Kevin Cruijssen's](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [05AB1E answer](https://codegolf.stackexchange.com/a/256676/96037)
6 bytes without the bonus:
```
{7Þ℅⟑,
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ7N8Oe4oSF4p+RLCIsIiIsIiJd)
**Explanation**
```
{7Þ℅⟑,
{ Loop forever
7Þ℅ Random permutaton of range(7)
⟑, Lazily evaluated lambda, print each item
```
Bonuses:
* 5 bytes for *Arbitrary n items*: [`{Þ℅⟑,`](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ7w57ihIXin5EsIiwiIiwiNSJd). Implicitly takes an integer as the input.
* 5 bytes for *Generic bag*: [`{Þ℅⟑,`](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ7w57ihIXin5EsIiwiIiwiW1wiY29va2llXCIsIFwiY29va2lcIiwgXCJjb2tpZVwiXSJd). Implicitly takes a list as the input. Same program as above :P
* 8 bytes for *Draw n items*: [`{7Þ℅?Ẏ⟑,`](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ7N8Oe4oSFP+G6juKfkSwiLCIiLCI1Il0=). Slices the list until the input before applying it to the lambda.
[Answer]
# [R](https://www.r-project.org), ~~50~~ 40 bytes
*-10 bytes thanks to inspiration from Giuseppe*
```
{b=n=1;\()(b<<-c(b,sample(7)))[n<<-n+1]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY5BCsIwEEX3PcXgagZbsW5StD2FS3WRhlaLaVKSCSjiATyDm7oQvJK3sdKu_ufzePzny_UfxxW7xhfvwHWSffFWFqZIN3skLPM8UVjGXradrlAQ0c4Mm5mnh_vEP-rGeRbLwsuu01dM12IZ18EobqzBC016JIomMlKScaZOlToDnySD1BqOzobOg61BgA8tsIVVBvivw5YuFoLWezOjSFm9Da3HVg7aC07OePg2Hur7MX8)
A reuseable function that on each call returns a single random nunber in the range `1..7`, sampled across calls using the 'tetris' distribution.
This is how I interpret the intent of the challenge.
A 62-byte recursive variant of this satisfies all 3 bonuses ([try it here](https://ato.pxeger.com/run?1=ZY9NTgQhEIX3fQqCGyrSyZC4MOPgRRwXQINDbH4CdLRjPImbdmHilTyFV7Dano1xU1V5PL689_Zels_SbCu-yo-puf7669bJFy2jFDdHFngG71gAw5g-HHrDNK8q5NGyDAB3EbV4Ke45enqBZng9U76DFFfkgmRvHkkgqhFFmg-2y94aW6Vh1I0z5bRmP9iCh_ZlwGVUwzmkh_VOTzhPqVRLAWEqzqTN2ZJUSJyCtoUkRzZid66xZv4VoEMUo-ZkMcHgKz7qqfkU98dIodtqiN1uTVVlVTmPMxN7VLibolmd7Bn-UaFrSmP_v_9hq70s2_4B)):
```
f={b=n=1;\(m,p)if(m)c((b<<-c(b,sample(p)))[n<<-n+1],f(m-1,p))}
```
---
# [R](https://www.r-project.org), 24 bytes
```
repeat cat(sample(7),"")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWO4pSC1ITSxSSE0s0ihNzC3JSNcw1dZSUNCHSUFUw1QA)
Alternative: a full program that outputs an infinite sequence of random permutations of `1..7`.
This probably satisfies the letter of the challenge, and other answers have used this approach, although it does seem rather trivial.
[Answer]
# JavaScript (ES6), 50 bytes
A function that draws one piece at a time.
```
m=f=_=>m^(m|=1<<(i=Math.random()*7))?-~i:f(m%=127)
```
[Try it online!](https://tio.run/##DcVNDoIwEAbQPaf4NqQzEgi4aQKMnMAbGE0DVDG0NUDc@HP16tu8u3matV@mx5b7MIwxOrFykYM7k3tL1bY0ydFst2IxfgiOeKeZu/w71ZZcKtVec7RhoXnc4CEom38tdNkwXgnQB7@GeSzmcCVLjAyUZR4pNDoohRrq5BVzk3ziDw "JavaScript (Node.js) – Try It Online")
### Commented
```
m = // m (aka "the bag") is a global bitmask holding
// drawn pieces, initialized to a zero'ish value
f = _ => // f is a recursive function ignoring its argument
m ^ ( // if m is modified when ...
m |= 1 << ( // ... the floor(i)-th bit of m is set
i = // where i is uniformly chosen
Math.random() // in [0, 7[
* 7 //
) //
) ? // then:
-~i // return floor(i + 1)
: // else:
f( // try again
m %= 127 // and reset m to 0 if it's 127 (0b1111111),
) // meaning that the bag is empty
```
[Answer]
# [Raku](https://raku.org/), 23 bytes
```
{grab $||=SetHash(^7):}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Or0oMUlBpabGNji1xCOxOEMjzlzTqvZ/cWKlQpqGpkJFhYKRwX8A "Perl 6 – Try It Online")
Ungolfed:
```
{
state $bag ||= SetHash(0..6);
$bag.grab;
}
```
This is a function which, when called repeatedly, will return the integers 0-6 in a random order, then the same integers in a (likely) different random order, and so on, *ad infinitum*.
Raku has a built-in data type `SetHash` which stores a set of objects, and has a `grab` method that chooses one of them randomly, removes it from the set, and returns it. All that's left to do for this challenge is the refilling. A state variable (`$` in the golfed version, `$bag` in the ungolfed one) stores the `SetHash`, which is reset to a new object with full contents (using `||`) when the variable is undefined, as on the first call to the function, or has become empty, as after every seventh call.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[7L.r)˜ć,
```
Uses a bag with integers `[1,2,3,4,5,6,7]`. Outputs the random piece indefinitely on separated newlines.
[Try it online.](https://tio.run/##yy9OTMpM/f8/2txHr0jz9Jwj7Tr//xsDAA)
1. (9 bytes) Replace `7` with `I` for the first bonus, where `n` is given as input-integer: [try it online](https://tio.run/##yy9OTMpM/f8/2tNHr0jz9Jwj7Tr//5sAAA).
2. (8 bytes) Replace `7L` with `I` for the second bonus, where the bag is given as input-list: [try it online](https://tio.run/##yy9OTMpM/f8/2lOvSPP0nCPtOkC2UlJOopKOrqGBgY6usZ6RgbFlLAA).
3. (11 bytes) Add `Iô` after `˜` for the third bonus, where `n` is given as input-integer and it'll output those `n` items as a list each iteration: [try it online](https://tio.run/##yy9OTMpM/f8/2txHr0jz9BzPw1uOtOv8/28MAA). Will use a combination of the existing list and a new shuffled list if the bag doesn't hold enough items anymore (e.g. let's say \$n=3\$ and the first two iterations where `[4,2,5]` and `[1,7,3]`, then the third iteration will be `[6,a,b]`, where the `6` is from the existing bag, and `a,b` are two random integers from a new bag).
**Explanation:**
```
[ # Loop indefinitely:
7L # Push a list in the range [1,7]
.r # Randomly shuffle it
) # Wrap the entire stack into a list
˜ # Flatten it to a single list
ć # Extract head; pop and push remainder-list and first item separately
, # Pop and output this first item
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 62 bytes
```
f=_=>x.match(i=Math.random()*7|0)?f(x=x[6]?'':x):(x+=i,i);x=''
```
[Try it online!](https://tio.run/##BcFRDoIwDADQfy@y1unClwZm5QSewBjTDCYzQM1YTD@8@3zvzV/eQk6fclxlGGuN9KSruoVLmCDRjcvkMq@DLID786/BPoKS3k@P3phOsQO1lA4JvZIx1e@iZGBqPF/a1lvLGGTdZB7dLC@IgFj/ "JavaScript (Node.js) – Try It Online")
I hope I understood question correctly
[Answer]
# Excel (ms365), 121 bytes
[](https://i.stack.imgur.com/traKF.png)
Formula in `A1`:
```
=LET(p,7,n,8,DROP(TAKE(REDUCE(0,SEQUENCE(ROUNDUP(n/p,0)),LAMBDA(a,b,VSTACK(a,SORTBY(SEQUENCE(p),RANDARRAY(p))))),n+1),1))
```
Idea here is that:
* 'p' - Represents the amount of distinct items in our bag;
* 'n' - Represents the amount of tokens we take out of the bag at once (with refilling it offcourse). You may change this to any reasonable integer;
* 'SEQUENCE(p)' - Represents our array. In this specific case we create an array of integers, but `SORTBY()` can take any array of any type. This however will start changing byte-count!
Below another sample where 'n' == 14 and another one where 'n' == 14 and 'p' == 3:
[](https://i.stack.imgur.com/58TrL.png)[](https://i.stack.imgur.com/8ESCf.png)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), ~~6~~ 5 bytes
```
ẊÐḶFY
```
Implements the first bonus
Runs until a pattern is repeated
-1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!
How?
```
ẊÐḶFY : Main Link, One arg(Number of pieces)
Ẋ : Shuffle; return a random permutation
ÐḶ : Loop; Repeat until the results are no longer unique
F : Flatten list
Y : Join z, separating by linefeeds
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6Fqse7uo6POHhjm1ukUuKk5KLocJLo5XMlWKhHAA)
[Answer]
# [Factor](https://factorcode.org/), ~~63~~ 62 bytes
```
[ 0 get [ 7 iota 7 sample >vector dup 0 set ] when-empty pop ]
```
[Try it online!](https://tio.run/##tU@7CsJAEOz9iiH9iZ2gYCs2NmIVUmwuqwbv5d0lIYjfHlfzBRZOMw@GWfZCOvs4nU@H434D7W3dOpIkoWf95cSPjp3mBEeWU6CPjOQab3Hn6NggRM55DLF1Ga3HdiqxwpUzSqwlyCSUyAbD2M2zaLognSSdCsONnWIb8ojgA6rpuYCghCZjsET1d9tEuVsopRwPqOkqqsD8z497L2jD1PP0Bg "Factor – Try It Online")
A quotation (anonymous function) that takes no arguments and outputs one piece each time it is called. You can look in the bag in between function calls with `0 get`.
[Answer]
# [Go](https://go.dev), 182 bytes
```
import(."math/rand";."golang.org/x/exp/slices")
func f()func()int{b:=[]int{}
return func()int{n:=Intn(7)
for;Contains(b,n);n=Intn(7){}
b=append(b,n)
if len(b)>6{b=[]int{}}
return n}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZY8xasMwFIZ3n0IIAjKJ7XZpGrvq0qlboWMIRbZlRdh-ErICCcYn6RIKvUKhR-kdeohKdtwORcOT9PR_-t7rm1DnT82KmgmOWiYhkK1Wxsa4ai1-P9gquv36mO5IjFtm94lhUOIsxkI1DESsjEiOCT_qpGtkwTscBtUBClSR0FcSSrB9ntLtzm-GwHB7MID-epDSR7BA1i6oTPagwDqRjuQrCDOYey6ZU6Y1h3LsBLJCDQeSh_c3fT7Tf_EwDBf779HGz0ZC1AeCA0qptwuk5W3nDy2rOWmZ3jrGjsFpFEEypdeZvNtsMrlcuqTzdGGXezLuXQNErtDk8bJSdUpH3BZ2map7zUAW5Fn7lxXBixKxxnBWnpBDcMMsL5EEZPeyQzkT2JPCIZgRFDxWLtaUXvXzdziKInyxpv-VB7-mmc_nqf4A)
A generator function that returns a function.
When the returned function is called, it returns an int in the range `[0,7)`.
### "Bonuses"
#### Arbitrary `n` distinct items, 204 bytes
```
import(."math/rand";."golang.org/x/exp/slices")
func f(I[]int)func()int{b,l:=[]int{},len(I)
return func()int{e:=I[Intn(l)]
for;Contains(b,e);e=I[Intn(l)]{}
b=append(b,e)
if len(b)>=l{b=[]int{}}
return e}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZBNSsQwFMdxaU4RAgMJ03Z0xoXTGjeuuhNcDoOk07QT2r6WNAMzlJ7EzSB4CO_gBfQ0Jq1FwWSRvK_f-7_38prX5_dG7AqRS1wJBUhVTa1NQLLKkLeDyfzbz4_RRwNSCbNfaAEpiQKS16WAPKh1vjgu5LFZtKXayZYwlB1ghzMab7YKDHMWZfbXJV4Z8sHZ9V4pgcYMaWkOGvBvkgx5vInBAC3ZFmW1jh5qMFZaSxNPskj-CXc9SrhoGgnpEEQqw46bsHtedsnUq5-6yL4fZ_q6uBxEupEpwx2KJ2HX3nLprVYr78aeHuUScMjdMBZuZNU6qxKFpJVoNrZgK-DEnEysQn4dqbv1OlLzuUVCyG01ZehR27wSqPIwDBKfvboI-YDbwDaqi64RoHb0qXGZGSWzFItSS5GesEVILYxMsQJs9qrFiciJI7EeTQgODqtm4045v-qmnsT3ffIjnf_T3SN7x42cz-P7DQ)
Generator function now takes a list of elements to choose from.
#### Arbitrary `n` items + generic (`comparable`), 208 bytes
```
import(."math/rand";."golang.org/x/exp/slices")
func f[T comparable](I[]T)func()T{b,l:=[]T{},len(I)
return func()T{e:=I[Intn(l)]
for;Contains(b,e);e=I[Intn(l)]{}
b=append(b,e)
if len(b)>=l{b=[]T{}}
return e}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZDBatwwEIbpVYc-gxAEJOLdbbI5JHbVS0--Fbq3xZSxLTti5ZGQtZBg_CS9LIU-RN-i1_ZpKtldKFQ6COYfvvlGX7_19vLDQXOCXtEBNBI9OOvDlnVDYN_Pods8_vq51viWDRCedx6wZcWW9dYA9lvr-93LTr243Wh0o0YmSHfGhnbHA23s4MBDbVTFy2N1ECnh4jDVmcllLExzZhTyUhCvwtkjvTaoXJbHEgNyIyrSWV98tBii4MjrTIlC_RNPM6klOKewXUKiO5qotfggzVSvc-brBDXP616_37xdRNPaXNCJlElJY5jusvv7bL_fZw_xzKRXSHMZF4pZlVx1UMOYSgOcFB_ALQngq0imVOfyrtDvn54KfXsbuZjLiOCCfPKxzyDXGcXF8ktmT7lccEesCnuaHKBu-GeXOjvObloKxitoX2lEKA9BtVQjDc96pDX0LJHETK4IiQmrb9ZPlfLddJ3JNpsN-6su__OeSbzrt1wu6_sH)
Works for any `comparable` type (bool, int, float, string, pointer, channel, struct of comparables, array of comparables, typeset of comparable).
#### Arbitrary `n` items + generic (`comparable`) + `k` items at a time, 288 bytes
```
import(."math/rand";."golang.org/x/exp/slices")
func f[T comparable](I[]T)(func()T,func(int)[]T){b,l:=[]T{},len(I)
A:=func()T{e:=I[Intn(l)]
for;Contains(b,e);e=I[Intn(l)]{}
b=append(b,e)
if len(b)>=l{b=[]T{}}
return e}
return A,func(n int)(N[]T){for i:=0;i<n;i++{N=append(N,A())};return}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZFNitwwEIXJVqcQhgGJUf94OoFgR4FmVt40gfSuMUG2ZY9ou2xkNcwgdJJsmkAOkavkNJHsdphhvJGoV3r1vfLPX01__TOI8iwaiTuhAKlu6LVZR3Vnot8XU68-__2A5yJZR50wTxstoIrSddT0rYBm3etm87yRz8NmbFUpx4ii-gIlrk9HXPbdILQoWpmT7JQfKQkSoUc2nQoMDVVbsDbh_mYdayWQjKJ9wm-tViY8O2VggLQ0R3Wv08cejIcdScEkTeUr2TpUcDEMEqpJRKrGwbGgX3lri3mGQ1qaiwYs_9_2MxDggEQOE5SfhFXCt6n6Aqm6v7eHxfnA9oRSl86PnVsW9TgFD3skFFuUhUze0Mbs4YHtdjv20X8ONRJYIw1OuF-S1_MQWBnZjaHUibMknRgmRcALRTeQ2IN82gYS7w0J9zaEom_a97VAFMMwxf3B-nPCJ7sT5Gl_toMAVZLvQ-isSXRXYdFqKaoX7C2kFkZWPjc2T2rEhWii4EQdWiw4BFt1N_8Zzrd2mRmtVqvohs7fcTvkXqPH8YI-BnZD4u1b-pH6B7ddXq_z-Q8)
A function that returns 2 functions. The first function takes 1 item, the second function takes `k` items.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), (4) 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
7ẊṄ€ß
```
A full program that prints forever.
**[Try it online!](https://tio.run/##y0rNyan8///hrq6HO1seNa05PP/////mAA "Jelly – Try It Online")**
\$4\$ bytes - `ẊṄ€ß` - taking either an arbitrary alphabet size [TIO](https://tio.run/##y0rNyan8///hrq6HO1seNa05PP////@GRgA "Jelly – Try It Online") or an arbitrary alphabet (as a list) [TIO](https://tio.run/##y0rNyan8///hrq6HO1seNa05PP/////R6smJJeo6Cuop@ekgKiMxt7gktQjETMsszgDRufmlxakgRlFiUlImWHF6PlBTLAA "Jelly – Try It Online").
### How?
```
7ẊṄ€ß - Main Link: no arguments
7 - seven
Ẋ - (implicit range [1..7]) shuffle
€ - for each:
Ṅ - print with trailing newline
ß - call this link again with the same arity
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 11 bytes
```
{l|:SHaPOl}
```
This is a function that takes as an argument a list of possible piece values (implementing the first two bonuses) and returns a single piece each time it is called.
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwU0dlZLUkqLM3My8_GIFK4VodU8FdX8F9RAFdS8FdR8F9WAF9ahYLpW81IoSBaulpSVpuharq3NqrII9EgP8c2ohIvt8FDIUqrkUAhQ0ICqRDNXkgipasABCAwA)
### Explanation
We store the current state of the bag in the global variable `l`. Initially, `l` is `[]`.
```
{l|:SHaPOl}
{ } Define a function:
l|: If l is empty, set it to
SHa the function argument, randomly shuffled
POl Pop the first element from l and return it
```
[Answer]
# PHP, 79 bytes
```
$y=function()use(&$a){$a=$a!=[]?$a:range(0,6);shuffle($a);echo array_pop($a);};
```
[Try it online!](https://tio.run/##HY1BCsIwEEWvMsIgE@qiKwWnoQcRkaEkRpBkSBuwlJ49hq7@4/Hga9Bah1GDAq7WlzgtnxTJlNnRGcVsKBblZB/PEeWeJb4d9Zer4TkU77@OWsNuCgkkZ1lfmvRQO1efMhD@wELP0HaA2wFdZ2Brb2QY9voH "PHP – Try It Online")
### Commented
```
$y = function() use (&$a) { // anonymous function with use clause by-reference
$a = $a != [] // equal comparison, if $a is neither null nor empty array
? $a // then use $a
: range(0,6); // else create range array
shuffle($a); // shuffle array
echo array_pop($a); // splice off and return last element of $a
};
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~11~~ 8 bytes
```
LhP*SH,a
```
Implements the first bonus
-3 bytes thanks to [DLosc](https://codegolf.stackexchange.com/users/16766/dlosc)!
How?
```
LhP*SH,a : One arg(Number of items)
a : First arg
L : Loop x times;
h : Literal for 100
, : Range zero to a
SH : Shuffle: random permutation of iterable
* : Map
P : Print
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJMaFAqU0gsYSIsIiIsIiIsIjciXQ==)
[Answer]
# [Zsh](https://www.zsh.org/), 35 bytes
```
exec<<(while shuf -i1-7)
f()read -e
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY3lVMrUpNtbDTKMzJzUhWKM0rTFHQzDXXNNbnSNDSLUhNTFHRTIUp3F6UWpCaWKJgoaEBZ5gpp1gqpyRn5mhAVMEMB)
Uniquely for zsh, this is a function `f`, not a full program.
If you want to cheat and output infinitely, you only need the `while shuf -i1-7`.
Setup:
* `while shuf -i1-7`: repeatedly output the shuffled range 1 to 7
* `<()`: create a pipe from the output of that loop
* `exec<`: move that pipe to standard input
`f`:
* `read`: read one word from standard input
* `-e`: and print it
[Answer]
# [Python 3](https://docs.python.org/3/), 59 bytes
-6 bytes thanks to @att
```
from random import*
while[*map(print,sample(range(7),7))]:1
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehKDEvBUhl5hbkF5VocZVnZOakRmvlJhZoFBRl5pXoFCfmFuSkagCVpadqmGvqmGtqxloZ/v8PAA "Python 3 – Try It Online")
Infinitely prints integers.
I dont know if this is valid: (54 bytes)
Prints all 7 integers of permutation in one line before a newline.
```
from random import*
while 1:print(*sample(range(7),7))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehKDEvBUhl5hbkF5VocZVnZOakKhhaFRRl5pVoaBUn5hbkpGoAFaWnaphr6phrav7/DwA "Python 3 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 149 bytes
```
import System.IO.Unsafe
import System.Random
import Data.List
d(o,[])=d([],o)
d(o,p)=(\n->(n:o,p\\[n]))$(p!!)$unsafePerformIO$randomRIO(0,length p-1)
```
[Try it online!](https://tio.run/##VY69CsIwFEb3PkULGRJog4IgCnVyKQgVxantcCG3Ntj8kFwHnz5qwcHxnOF83wTxgfOckjbeBcqvr0hoZNPKm40wYvbvL2CVMz95BAJ50pEyxV3ZDaJWvBtKJxb2oua9rQ7c7j/Q950dhGDcF4VgzyV@xjC6YJqWhaV7aVq@Kme0d5pyX61FMqBt7YO2xAgemG92zIDnE4KSYyTBNGEAwlyxz/Rayu3w/ZHe "Haskell – Try It Online")
[Answer]
# Clojure, 56 bytes
```
(run! #(run! println %)(repeatedly #(shuffle(range 7))))
```
Creates an infinite list containing random permutations of 0 to 6 and prints each number.
[Try it online!](https://tio.run/##S87JzyotSv3/X6OoNE9RQRlCFRRl5pXk5CmoamoUpRakJpakpuRUKhgDpYszStPSclI1ihLz0lMVzDWB4P9/AA "Clojure – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
7>ℕ≜₁|↰
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/39zuUcvUR51zHjU11jxq2/D///8oAA "Brachylog – Try It Online")
This is a predicates that unifies its output with a random integer between 0 and 6, exhausting each possibility before beginning a new cycle.
[Try generating 14 random unifications here!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh9sWHNr5qHHLf3O7Ry1TH3XOAYrVAKX@//8fBQA)
You can change `7` to any other number to get bigger bags.
### Explanation
```
7>ℕ Take an unknown integer between 0 and 6
≜₁ Assign a value to it, with a random choice
| Else
↰ Recursive call
```
Since our variable is constrained in `[0..6]`, `≜₁` will randomly unify it with one of those 7 values, leaving a choice point for each one. Brachylog will try each choice point when asked (e.g. with `ᶠ - findall`, failure loops, or by pressing `;` in Prolog’s REPL), so each integer value. `|` creates another choice point that will get called only once all the choice points created by `≜₁` are exhausted.
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 11 \log\_{256}(96) \approx \$ 9.05 bytes
```
[7R7zPZw{ZK
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuharo82DzKsCosqro7whIlAJmAIA)
Port of [mathcat's Vyxal answer](https://codegolf.stackexchange.com/a/256680/114446).
#### Explanation
```
[7R7zPZw{ZK
[ # Forever:
ZK # Print
{ # Each element of
Zw # A random element of
7zP # The permutations
7R # Of range(7)
```
#### Bonuses
* Arbitrary `n` items: \$ 13 \log\_{256}(96) \approx \$ 10.70 bytes, [`[z0Rz0zPZw{ZK`](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhZro6sMgqoMqgKiyqujvCFiUKkFC00hDAA)
* Generic bag: \$ 12 \log\_{256}(96) \approx \$ 9.88 bytes, [`[z0DLzPZw{ZK`](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhZroqsMXHyqAqLKq6O8IUJQmQV7otUTk5LVdRTUU1LTQFR6RiaIysrOUY-FqAEA)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 60 bytes
```
b;f(i,j){b-127||(b=0);for(;b&1<<(i=rand()%7););b|=1<<i;j=i;}
```
[Try it online!](https://tio.run/##VY9Bj4IwEIXv/RUTNphpRCPGhMShe9/EePPmhVLQIVoM1L0Ivx1bPDmnyTfzXt4rV5eynCZNNXLSyJdepdtsGFCrjaS67ZD0Is1zZNUV1qCMM0mS9KA8ZGoU0zj9sC1vT1NB3jvD7fr6K77QjXVggq2De8EW/1s2El4CICAm4bd@9nd8r/B4OhyknGlIwGpDwMtlnu7oowJ4dF5ZY/Tnqq5w3FqI11uzh9icbZQAJ1BjsAi/7KvFmfKF4PF0PUbqM9F8H8U4vQE "C (gcc) – Try It Online")
## Explanation
```
b; // Bag: initialized with nothing selected
f(i,j){
b-127||(b=0); // Reset bag when all 7 pieces selected
for(;b&1<<(i=rand()%7);); // Find a random unselected piece
b|=1<<i; // Mark it as selected
j=i; // Return the piece
}
```
] |
[Question]
[
This is a QWERTY keyboard.
```
Q W E R T Y U I O P
A S D F G H J K L
Z X C V B N M
```
We can "spiral out" on this keyboard, starting from G. The spiral will start at G, go to H, then to Y, then to T, then F, then V, then B, then N, then J, then U, then R, then D, then C,... etc. Your challenge is to, given a number 1 ≤ **N** ≤ 26, output the first **N** characters in this spiral. (If you are confused, refer to the pictures at the end of the post.)
The catch? Your program's score is proportional to the indices of characters found inside the spiral!
## Scoring
1. For every letter (case-insensitive) in your code, add the index of that character in the spiral to your score (starting from 1).
2. For every character not in the spiral, add 10 to your score.
3. The lowest score wins.
For example, the program `print("Hello, World!")` has a score of 300.
For your convenience, I have written an automatic program grader.
```
var SPIRAL = "GHYTFVBNJURDCMKIESXLOWAZPQ";
function grade(program) {
var score = 0;
for(var i = 0; i < program.length; i++) {
if(/^[A-Za-z]$/.test(program[i])) {
score += SPIRAL.indexOf(program[i].toUpperCase()) + 1;
}
else {
score += 10;
}
}
return score;
}
input.oninput = function() {
output.value = "Your program's score is: " + grade(input.value);
}
```
```
textarea { width: 500px; height: 6em; font-style: monospace; }
```
```
<textarea id="input"></textarea>
<textarea disabled id="output"></textarea>
```
## Other rules
* Your submission may be a program or function.
* You may take **N** starting at 0 or 1 and ending at 25 or 26, respectively, but the outputs should still begin with "G" and end with "GHYTFVBNJURDCMKIESXLOWAZPQ".
* You must output the characters in the spiral **in order**.
* If a function, you may return a list of characters instead of a string.
* You may have one trailing newline following the output.
* You may use lowercase letters instead of uppercase letters, or a combination of both.
## Test cases
```
number -> output
1 -> G
2 -> GH
5 -> GHYTF
12 -> GHYTFVBNJURD
15 -> GHYTFVBNJURDCMK
24 -> GHYTFVBNJURDCMKIESXLOWAZ
26 -> GHYTFVBNJURDCMKIESXLOWAZPQ
```
## Pictures
[](https://i.stack.imgur.com/KUjwxm.png)
The spiral superimposed:
[](https://i.stack.imgur.com/6Jcijm.png)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~304~~ ~~264~~ 162 points
*Saved 40 points thanks to @ConorO'Brien*
```
;î"历锋㫿鮹㿬崴ꨜꎋΞ"csG
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=O+4iXHU1Mzg2XHU5NTBiXHUzYWZmXHU5YmI5XHUzZmVjXHU1ZDM0XHVhYTFjXHVhMzhiXHUwMzllImNzRw==&input=MjY=)
In order to save as many points as possible, the entire string is condensed into 9 Unicode chars by interpreting each run of 3 letters as a base-36 number, then converting to a code point. The program itself takes this compressed string (which costs 110 points, including the quotes) and maps each `c`harcode by converting it to a `s`tring in base-36 (`G` after the `;` at the beginning). `î` takes the first {input} chars of this, which is implicitly printed.
[Answer]
# C, score: 544
```
g(g){write(1,"GHYTFVBNJURDCMKIESXLOWAZPQ",g);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9dI12zurwosyRVw1BHyd0jMsQtzMnPKzTIxdnX29M1OMLHP9wxKiBQSSdd07r2f2ZeiUJuYmaehiZXNZcCEKTlFylogEQzbQ2tFTJtjMytFbS1MzXBkhAlIJCukalpDecVlJYUaygpQUVquWr/AwA)
[Answer]
# [Spiral](http://esolangs.org/wiki/Spiral), score: ~~61921~~ ~~5127~~ ~~4715~~ ~~4655~~ 4191
```
4.X~>v+^#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v
X * X X X X X X X X X X X X X X X X X X X X X X X X X
! > h y t f V b n j u [ ( 1 3 2 ) ] U J N B F T Y H G
0;vgv*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*vvv****v+^v+^v+^v+^*v++4
X X X X X X X X X X X X X X X X X X X X X X X X X X
v v v v v v v v v v v v v v v v v v v v v v v v v v
Y y J F V u t U [ G H B n 3 N 2 j ) h g f ] ( 1 b T
```
An interpreter can be found [here](http://web.archive.org/web/20060223041000/http://quintopia.net:80/JSpI.java).
**Explanation:**
```
P.X~ZZ*v+^#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v
X X X X X X X X X X X X X X X X X X X X X X X X X X
! h y t f V b n j u r d c m k i e s x l o w a z p q
0;vgv*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*v*****************************************************************vP
X X X X X X X X X X X X X X X X X X X X X X X X X X
v v v v v v v v v v v v v v v v v v v v v v v v v v
z y x w V u t s r q p o n m l k j i h g f e d c b a
```
The program begins at the `0` character on the fourth line. The first piece of code to run is `0;vg`. `;` takes a number
as input and places it in the stack. `v` places what is in the register (a zero) into the stack. It will
be used as the counter. `g` is a label, when it is reached, the control jumps to the other occurence of
the letter `g` in the code.
So this is where the control is now:
```
X
v
g
```
Since there is whitespace in all other directions, the instruction pointer starts moving upwards.
`v` places a zero into the stack, and `X` pops it from the stack immediately. Because the popped value
is zero, the instruction pointer moves to `X` (otherwise it would treat it as whitespace).
By default, the control flow is in turn-right mode, so now when it reaches the junction, the instruction
pointer turns to the right. `v` yet again pushes a zero into the stack, `*` increments the register by one.
```
v*v*v
X
v
g
```
The next `v` places what is in the register (number 1) into the stack, the instruction pointer attempts to turn
to the right, hitting the next `X`. The value just added to the stack is popped and placed in the register.
Because it is non-zero, `X` is not entered, and the IP proceeds to the next `*` on the right instead, again
incrementing the value in the register.
```
v*v*v*v*v
X X X X X
v v v v v
i h g f e
```
This happens again and again until we reach the end of this part and the line of `*`s begins. By now the value
in the register is 6, which is ASCII letter `g` minus ASCII letter `a`. Thus with a line of 97 `*`s we increment
the value in the register to 103, which matches the letter `g` we want to print. `v` pushes it into the stack,
and `P` is another label upon hitting which we jump to the other `P` on the first line of the code.
Here `.` pops the value from the stack and prints it as a character. After that `X` pops the extraneous zero
from the stack, then `~` compares the two remaining values in the stack (the values being the counter and the
input value). If the values are the same, the operator places zero in the stack (otherwise -1 or 1). Again,
the control attempts to turn right. `X` pops the value of the comparison from the stack, if it is zero, `X`, and
after it `!` is entered, terminating the program.
```
P.X~ZZ*v+^
X
!
```
Otherwise the IP continues to the `Z`, which is a label which in this case jumps only one step to the right.
The reason for doing this is that jumping sets the value in the register back to zero. `*` increments the
register and `v` places the resulting 1 into the stack. `+` pops the two top elements of the stack (the
1 and the counter), adds them, and places the result in the stack (in effect this increments the counter by
one). `^` copies the result from the stack to the register without removing it from the stack.
`#` decrements the value in the register by one, `v` pushes the decremented value to the stack, the IP attempts
to turn to the right, and the `X` pops the value from the stack. If the value is non-zero the IP keeps moving
to the east, decrementing the value in the register, until it hits zero, and the IP enters an `X` branch.
```
#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v
X X X X X X X X X X X X X X X X X X X X X X X X X
h y t f V b n j u r d c m k i e s x l o w a z p q
```
The branch leads to a label corresponding to the value of the counter. Upon hitting the label, the control jumps
to the other occurence of the label in the section where we started with the label `g`, starting another iteration.
As with the `g`, the value in the register gets incremented up to the ASCII value of the letter we need to print.
Then the character is printed and the counter incremented, another label is selected. This happens until after the last iteration
the counter equals the input, and the program terminates.
**Edit:**
```
P.X~Zv+^
X *
! Z
```
Achieves the same thing as
```
P.X~ZZ*v+^
X
!
```
but with less whitespace.
**Edit 2:**
```
vv****v+^v+^v+^v+^*v++P
```
Can be used instead of:
```
*****************************************************************vP
```
[Answer]
# [Haskell](https://www.haskell.org/), 471
```
(`take`"GHYTFVBNJURDCMKIESXLOWAZPQ")
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P81WI6EkMTs1QcndIzLELczJzys0yMXZ19vTNTjCxz/cMSogUEnzf25iZp5tQWlJcEmRT55KmoKh4X8A "Haskell – Try It Online")
This is a bit of a benchmark, I feel like there must be a better way, but its the best I've found so far.
## Explanation
I suppose I should explain this for those not familiar with Haskell too well. The function `take` takes the first n elements of the list. It is called like this:
```
take n list
```
We want to take the first n elements of the sting `"GHYTFVBNJURDCMKIESXLOWAZPQ"`, so we want something like
```
f n=take n"GHYTFVBNJURDCMKIESXLOWAZPQ"
```
We can do better though, we can infix `take` using backticks
```
f n=n`take`"GHYTFVBNJURDCMKIESXLOWAZPQ"
```
And now this can be made pointfree
```
(`take`"GHYTFVBNJURDCMKIESXLOWAZPQ")
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 211 score
19 bytes
```
“eȷÞ('¢ạẓkȮV’œ?ØAðḣ
```
[Try it online!](https://tio.run/##ATAAz/9qZWxsef//4oCcZci3w54oJ8Ki4bqh4bqTa8iuVuKAmcWTP8OYQcOw4bij////MTI "Jelly – Try It Online")
saved a bunch of score thanks to Emigna's suggestion to use `œ?` :D
[Answer]
# Befunge, Score: 531
```
QPZAWOLXSEIKMCDRUJNBVFTYHG"&\>,# 1#\-# :# _@
```
I feel this challenge would have been more interesting if the output had to be in a spiral as well.
[Answer]
# TI-Basic (TI-84 Plus CE), ~~454~~ 432 points
```
sub("GHYTFVBNJURDCMKIESXLOWAZPQ",1,Ans
```
-22 points from [Conor O'Brien](https://codegolf.stackexchange.com/users/31957/conor-obrien)
Run with `5:prgmNAME`.
Returns/prints the `sub`string from `1` to `Ans` (the number input).
TI-Basic is a [tokenized langauge](http://tibasicdev.wikidot.com/one-byte-tokens), so I'm scoring this by the byte values of the tokens.
`sub(` is 0xbb 0x0c, so 20
`"` is 0x2a, so `*`, so 10\*2=20
Uppercase letters don't change, so the string is 351
`,` is 0x2b, so `+`, so 10\*2=20
`1` is 0x31, so `1`, so 10
`Ans` is 0x72, which is `r`, so 11
20 + 20 + 351 + 20 + 10 + 11 = 432
[Answer]
# [Vim](https://www.vim.org/), ~~461~~ 418
```
CGHYTFVBNJURDCMKIESXLOWAZPQg^[G@" D
```
Thanks @pacholik for -43 score!
[Try it online!](https://tio.run/##K/v/39ndIzLELczJzys0yMXZ19vTNTjCxz/cMSogMF3a3UFJweX/fyMA "V – Try It Online")
[](https://i.stack.imgur.com/TCric.gif)
[Answer]
# Python 3, score = ~~762~~ 753
1-based input. This is worse than the trivial approach, since it uses 37 non-letters. It is somewhat interesting, though.
*-9 thanks to [Leo](https://codegolf.stackexchange.com/users/62393/leo).*
```
h=lambda g:g and h(g-1)+chr(65+int('GYGGYHGYYGYTGTYHGYGGHGGTGHGYGYGFGHGGYGGHHGGHHYYGHGHGGYFGGYHGGTHGHTGGGGGFGGVHGT'[g*3-3:g*3],35)%26)or''
```
[Try it online!](https://tio.run/##TY3BCsIwEETvfkUuksTaQw3toeC1kw8IwiIeqoVE0LSEXvz6mC0ILuzyZphhl88a5mhyDufX@L5Po/C9F2OcRFC@bnT1CEl1bfWMq5IggCyIQA6OCbCAAxNhYMGW5S0puxnDVoIryoGnGBcLJ6/@YGrTl3s7mlbvT52ek5R5SfwtqEbr3Y/NH5eczl8 "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), score: 204
```
.•3ŽγY
₁ùÐÁo0ª ’ö:•£
```
[Try it online!](https://tio.run/##AS8A0P8wNWFiMWX//y7igKIzxb3Os1kK4oKBw7nDkMOBbzDCqiDigJnDtjrigKLCo///NQ "05AB1E – Try It Online")
[Answer]
# Brainf\*\*k, score = 2690
Input a single byte ranging from `0x1` to `0x1a`.
```
>>++++>+++>>>>++++++++++[<+<-<+>>>-]<<--<+++>>>++>->+++++++++++>++++++>-------->---->-->>---------->--------->+++++>++++++++>--->+>----------->+++++++++>------->+++++++>++++++++++++>----->------>+>>+++++++[<+++++++++++[<[[+<]+<]>->[[>]>]<<<-]>-]<<[-]>,[[<]<.[-]>+[>]<-]
```
[Try it online!](https://tio.run/##XU9RCkIxDLuHV6j1BCEXCf1QQRDhfQief3Zv9VEMowtpujW39/W5PT731xikJWYhF18QDI4pegCedHdk8eay4vQCq/BQSlusz6wpWnO2p/mn9E@ryZ/j2FuwnkAyRJ5cWWIwg8BjD6S8zxICl0kt29ka4/QF "brainfuck – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), score: 391
```
↑∘'GHYTFVBNJURDCMKIESXLOWAZPQ'
```
[Try it online!](https://tio.run/##AUcAuP9hcGwtZHlhbG9n//9m4oaQ4oaR4oiYJ0dIWVRGVkJOSlVSRENNS0lFU1hMT1dBWlBRJ///4o2qICjiiqIsZikgwqjijbMyNg "APL (Dyalog Unicode) – Try It Online")
The only use for Latin letters in Dyalog is in variable names and some system functions. Apart from that, only glyphs and some Greek letters are used.
[Answer]
# Python 3, 522
```
lambda g:"GHYTFVBNJURDCMKIESXLOWAZPQ"[:g]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHdSsndIzLELczJzys0yMXZ19vTNTjCxz/cMSogUCnaKj32f0lRpRUXZ3lGZk6qQkhRaSqQw5mZV6BgqwAkS0s0NIH8gqLMvBINIF9HXddOXSdNA8rV1NTkSq1ITi0oUXD1d3MtKsovAmovSCwu/m/IZcRlymVoxGVoymVkwmVkBgA "Python 3 – Try It Online")
An anonymous lambda utilizing Python's slicing of strings (`"asdf"[:i]` gets the first `i` characters of `"asdf"`)
[Answer]
# Clojure, ~~484~~ 474 points
-10 points because apparently a `%` can exist after a number without a space separating them!? I might have to go back over and improve some submissions.
```
#(subs"ghytfvbnjurdcmkiesxlowazpq"0%)
```
An anonymous function. Basically a Clojure port of what's already been posted. Scores nicely! I think this is the first Clojure program I've ever written that doesn't contain a single space.
```
(defn spiral [n]
; Substring the hardcoded list, going from index 0 to n
(subs "ghytfvbnjurdcmkiesxlowazpq" 0 n))
```
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 521 points
```
"QPZAWOLXSEIKMCDRUJNBVFTYHG"ns[,spol];
```
[Try it online!](https://tio.run/##y6n8/18pMCDKMdzfJyLY1dPb19klKNTLzynMLSTSw10przhap7ggPyfW@v9/QwA "Ly – Try It Online")
I don't feel as though this is optimizable.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), score: 465
```
cut -b-$1<<<GHYTFVBNJURDCMKIESXLOWAZPQ
```
[Try it online!](https://tio.run/##S0oszvj/P7m0REE3SVfF0MbGxt0jMsQtzMnPKzTIxdnX29M1OMLHP9wxKiDw////pgA "Bash – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 293 bytes
```
↑¨ghytfvb⌋ȷÜdcmkÏexl⁰Λzpq
```
This is the shortest one I could find, next closer `¨gHYtfvB⌋ȷÜdCmkÏex←ẆAzpq¨` for a score of 293..
[Try it online!](https://tio.run/##AS4A0f9odXNr///ihpHCqGdoeXRmdmLijIvIt8OcZGNta8OPZXhs4oGwzpt6cHH///81 "Husk – Try It Online")
### Explanation
Brute-force search, turns out all lower-case gave the best score. It's basically the same as @Wheat Wizard's solution, `take` (`↑`) on a compressed string (`¨`).
[Answer]
# Common Lisp, score: 580
```
(subseq"GHYTFVBNJURDCMKIESXLOWAZPQ"0(read))
```
[Try it online!](https://tio.run/##S87JLC74r1FQlJmX/F@juDSpOLVQyd0jMsQtzMnPKzTIxdnX29M1OMLHP9wxKiBQyUCjKDUxRVPzv@Z/cwA)
[Answer]
# Excel, 490 points
```
=LEFT("GHYTFVBNJURDCMKIESXLOWAZPQ",A1)
```
Convention for Excel ansers is to take input from `A1`. Changing this to `G1` cuts 22 points (468).
```
=LEFT("GHYTFVBNJURDCMKIESXLOWAZPQ",G1)
```
[Answer]
# [C#](http://csharppad.com/gist/40b4f4750c521d60fd77451cf3dd5337), score 546
```
g=>"GHYTFVBNJURDCMKIESXLOWAZPQ".Substring(0,g);
```
[Answer]
## Rust, score 443
It is not often that Rust is good at code golf but here it beats many languages
```
|g|&"GHYTFVBNJURDCMKIESXLOWAZPQ"[..g]
```
[Answer]
# Golang, score 861
```
func g(g int){io.WriteString(os.Stdout,"GHYTFVBNJURDCMKIESXLOWAZPQ"[0:g])}
```
[Play it online !](https://play.golang.org/p/gwYIObtQc8)
[Answer]
# Javascript ES6, 527 points
```
g=>`GHYTFVBNJURDCMKIESXLOWAZPQ`.slice(0,g)
```
## Try it !
```
f=g=>`GHYTFVBNJURDCMKIESXLOWAZPQ`.slice(0,g)
input.oninput = function() {
output.value = f(input.value);
}
```
```
textarea { width: 500px; height: 6em; font-style: monospace; }
```
```
<textarea id="input"></textarea>
<textarea disabled id="output"></textarea>
```
[Answer]
# PHP, 590 points
```
<?=substr(GHYTFVBNJURDCMKIESXLOWAZPQ,0,$argv[1]);
```
[Try it online!](https://eval.in/910505)
[Answer]
# PHP, score 584
fiddled a bit with the dictionary; the fact that xoring the string cuts it off rendered `substr` obsolete.
```
<?=">1 -?/;73,+=:420<*!56.8#)("^str_repeat(y,$argv[1]);
```
[Try it online](http://sandbox.onlinephpfunctions.com/code/9ab3081577e2ef08c145d1c1c7728e4bc26ed79b).
[Answer]
# Mathematica, 528
```
"GHYTFVBNJURDCMKIESXLOWAZPQ"~StringTake~#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X8ndIzLELczJzys0yMXZ19vTNTjCxz/cMSogUKkuuKQoMy89JDE7tU5Z7X8AkFPikBZtGvsfAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), score: 371
```
<"GHYTFVBNJURDCMKIESXLOWAZPQ
```
[Try it here.](https://pyth.herokuapp.com/?code=%3C%22GHYTFVBNJURDCMKIESXLOWAZPQ&input=10&debug=0)
## How?
```
<"GHYTFVBNJURDCMKIESXLOWAZPQ"Q implicit string end, implicit input
< Q first Q(=input) elements ...
"GHYTFVBNJURDCMKIESXLOWAZPQ" ... of this string
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 453 points
```
->g{'GHYTFVBNJURDCMKIESXLOWAZPQ'[0,g]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y69Wt3dIzLELczJzys0yMXZ19vTNTjCxz/cMSogUD3aQCc9tva/kbleSWZuanF1TV5NQWlJsUJadB5QGAA "Ruby – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 558+16= 574 points
```
<;v? : <{"GHYTFVBNJURDCMKIESXLOWAZPQ"
>$o1-^
```
Uses the `-v` flag to push input onto the stack.
Pushes the spiral onto the stack in reverse order, then rotates the input to the top. Then, while the top of the stack is non-zero, prints the next letter and decrements the top of the stack.
[Try it online!](https://tio.run/##S8sszvj/38a6zF7BSsGmWsndIzLELczJzys0yMXZ19vTNTjCxz/cMSogUIlLQcFOJd9QN@7///@6ZQqGRgA "><> – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), 261 points
```
<."AZJ{Û§zoÆæÏýú
```
**[Try it here!](https://pyth.herokuapp.com/?code=%3C.%22AZ%01%1F%C2%8DJ%7B%C3%9B%C2%A7z%C2%97o%C3%86%C3%A6%07%C3%8F%C3%BD%C3%BA&input=11&debug=0)**
This outputs uppercase letter. For lowercase, you can try the alternative [261 byter](https://pyth.herokuapp.com/?code=%3C.%22az%01%1F%C2%8DJ%7B%C3%9B%C2%A7z%C2%97o%C3%86%C3%A6%07%C3%8F%C3%BD%C3%BA&input=11&debug=0).
] |
[Question]
[
The non-negative integers are bored of always having the same two\* neighbours, so they decide to mix things up a little. However, they are also lazy and want to stay as close as possible to their original position.
They come up with the following algorithm:
* The first element is 0.
* The \$n^{th}\$ element is the smallest number which is not yet present in the sequence and which is not a neighbour of the \$(n-1)^{th}\$ element.
This generates the following infinite sequence:
```
0,2,4,1,3,5,7,9,6,8,10,12,14,11,13,15,17,19,16,18,20,22,24,21,23,25,27,29,26,28 ...
```
`0` is the first element. `1` is the smallest number not yet in the sequence, but it is a neighbour of `0`. The next smallest number is `2`, so it is the second element of the sequence. Now the remaining numbers are `1,3,4,5,6,...`, but as both `1` and `3` are neighbours of `2`, `4` is the third member of the sequence. As `1` is not a neighbour of `4`, it can finally take its place as fourth element.
### The Task
Write a function or program in as few bytes as possible which generates the above sequence.
You may
* output the sequence infinitely,
* take an input \$n\$ and return the \$n^{th}\$ element of the sequence, or
* take an input \$n\$ and return the first \$n\$ elements of the sequence.
Both zero- or one-indexing is fine in case you choose one of the two latter options.
You don't need to follow the algorithm given above, any method which produces the same sequence is fine.
---
Inspired by [Code golf the best permutation](https://codegolf.stackexchange.com/questions/164838/code-golf-the-best-permutation). Turns out this is [A277618](https://oeis.org/A277618).
\* Zero has literally only one neighbour and doesn't really care.
[Answer]
# JavaScript (ES6), 13 bytes
Returns the \$n\$th term of the sequence.
```
n=>n-2-~++n%5
```
[Try it online!](https://tio.run/##BcHRCkAwFADQX9mL3Bu7oTxO@Q5Ja0bEvWukvPj1OWe3j71c3MKtWWafFpPYdKwb/RUFZ21ywpccng5ZYSCiPkb7Ql1VONJpA8BUKkZlOrUAI9IuG0Ne5ojpBw "JavaScript (Node.js) – Try It Online")
### How?
This computes:
$$n-2+((n+2) \bmod 5)$$
```
n | 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...
-------------+--------------------------------------------------
n - 2 | -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 12 ...
(n+2) mod 5 | 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 ...
-------------+--------------------------------------------------
sum | 0 2 4 1 3 5 7 9 6 8 10 12 14 11 13 ...
```
[Answer]
# [Python 2](https://docs.python.org/2/), 20 bytes
```
lambda n:2*n%5+n/5*5
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPykgrT9VUO0/fVMv0f0FRZl6JQnSaRqamQlp@kUKmQmaeQlFiXnqqhomBZux/AA "Python 2 – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 5 bytes
```
⌠5%+⌡
```
[Try it online!](https://tio.run/##y00syUjPz0n7//9RzwJTVe1HPQv//zfgMuQy4jLmMuEy5TLjMueyAAA "MathGolf – Try It Online")
Some nice symmetry here. Returns the `nth` element of the sequence.
### Explanation:
```
⌠ Increment input by 2
5% Modulo by 5
+ Add to copy of input
⌡ Decrement by 2
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
æ%2.+
```
[Try it online!](https://tio.run/##y0rNyan8///wMlUjPe3/RgYPd2w73P6oac1/AA "Jelly – Try It Online")
Go go gadget obscure built-in!
```
æ%2. Symmetric modulo 5: map [0,1,2,3,4,5,6,7,8,9] to [0,1,2,-2,-1,0,1,2,-2,-1]
+ Add to input
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 14 bytes
```
#+Mod[#,5,-2]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/V9Z2zc/JVpZx1RH1yhW7b@@g0JQYl56arSBjrFBbOx/AA "Wolfram Language (Mathematica) – Try It Online")
Prints the n-th, zero-indexed, integer in the sequence.
[Answer]
# [R](https://www.r-project.org/), ~~25~~ ~~23~~ 21 bytes
-2 bytes thanks to Jo King
```
n=scan();n-2+(n+2)%%5
```
[Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTOk/XSFsjT9tIU1XV9L/hfwA "R – Try It Online")
Outputs `nth` element in sequence.
[Answer]
# [dzaima/APL](https://github.com/dzaima/APL), 9 bytes
```
2-⍨⊢+5|2+
```
Port of Arnauld's answer.
[Try it online!](https://tio.run/##SyzI0U2pSszMTfz/30j3Ue@KR12LtE1rjLT/P@qb6un/qG2CAVcakESVS3vUu9nQ4F9@QUlmfl7xf91iAA)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 14 bytes
```
02413@a+a//5*5
```
Takes \$n\$ (0-based) as a command-line argument and outputs \$a\_n\$. [Try it online!](https://tio.run/##K8gs@P/fwMjE0NghUTtRX99Uy/T///8mAA "Pip – Try It Online")
Observe that \$a\_{n+5} = a\_n+5\$. We hard-code the first five values and offset from there.
---
Or, the formula everyone's using, for **12 bytes**:
```
a-2+(a+2)%5
```
[Answer]
# [Common Lisp](http://www.clisp.org/), 67 bytes
```
(defun x(n)(loop for a from 0 to n collect(+(mod(+ a 2)5)(- a 2))))
```
[Try it online!](https://tio.run/##HYlbCoAgFAW3cj6PSGBBCwofEFy9Ygbu3qT5mmG83E@dkyGmt2CwGIpqRdKGC6lphkNXFHgVib7TMmugXfcwp@H2y2Kytrt0Duxu1Qc "Common Lisp – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 bytes
```
U-2Ò°U%5
```
[Japt Interpreter](https://ethproductions.github.io/japt/?v=1.4.6&code=VS0y0rBVJTU=&input=MTAwCi1t)
A straight port of Arnauld's Javascript answer. The linked version runs through the first n elements, but if the `-m` flag is removed it is still valid and prints the nth element instead.
For comparison's sake, [here](https://ethproductions.github.io/japt/?v=1.4.6&code=z3tZYVggyata+Fl9YX1nVSxbMF0=&input=MTAwCi1t) is the naive version which implements the algorithm provided in the question:
```
@_aX É«NøZ}a}gNhT
```
I'll give an explanation for this one:
```
NhT Set N to [0]
@ }g Get the nth element of N by filling each index with:
_ }a The first integer that satisfies:
aX É It is not a neighbor to the previous element
«NøZ And it is not already in N
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ì5%+Í
```
Port of [@JoKing's MathGolf answer](https://codegolf.stackexchange.com/a/174729/52210).
[Try it online](https://tio.run/##yy9OTMpM/f//cI@pqvbh3v//jUwA) or [verify the first 100 numbers](https://tio.run/##yy9OTMpM/X@x6fBcl/@He0xVtQ/3/v8PAA).
**Explanation:**
```
Ì # Increase the (implicit) input by 2
5% # Take modulo-5
+ # Add the (implicit) input to it
Í # Decrease by 2 (and output implicitly)
```
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 31 bytes
The formula everyone's using.
```
import StdEnv
?n=n-2+(n+2)rem 5
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4zLPs82T9dIWyNP20izKDVXwfR/cEkiUNpWwd7I4P@/5LScxPTi/7qePv9dKvMSczOTiwE "Clean – Try It Online")
# [Clean](https://github.com/Ourous/curated-clean-linux), 80 bytes
My initial approach, returning the first `n` items.
```
import StdEnv
$n=iter n(\l=l++[hd[i\\i<-[0..]|all((<>)i)l&&abs(i-last l)>1]])[0]
```
[Try it online!](https://tio.run/##DcwxDsIgFADQ3VMwNA2koUHntlMdTNw6AsMXUH/yoaagiYlnF30HeI4CpBpX/6TAImCqGB/rVthS/DG9dk0asYSNJW5opK7Td6/RGBykVn1vP0DE@TAJFNS2cMkcJUEujMS0t1ZoZetS4P@NrDmo@nVXgluu8nSu8ztBRJd/ "Clean – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 14 bytes
```
n->2*n%5+n\5*5
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P185IK0/VVDsvxlTL9H9afpFGHlDcQEfBGIgLijLzSoACSgq6dkAiTSNPU1PzPwA "Pari/GP – Try It Online")
---
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 14 bytes
```
n->n-2+(n+2)%5
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1y5P10hbI0/bSFPV9H9afpFGHlDcQEfBGIgLijLzSoACSgq6dkAiTSNPU1PzPwA "Pari/GP – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 30 bytes
```
{.2}.[:,_5,./\2(i.-4 0$~])@,~]
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8L9az6hWL9pKJ95UR08/xkgjU0/XRMFApS5W00GnLva/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqCoYHBfwA "J – Try It Online")
Returns a list of first `n` numbers
This solution is obviously non-competitve, but I wanted to try an array-based method.
## Explanation:
The argument is `n`
`2 ,]` - append 2 to the input
```
(2,~]) 10
10 2
```
`()@` - and use this list to:
`i.` - create a matrix `n` x 2 with the numbers in the range 0..2n-1:
```
i.10 2
0 1
2 3
4 5
6 7
8 9
10 11
12 13
14 15
16 17
18 19
```
`4 0$~]` - `~` reverses the arguments, so it is ]$4 0 - creates matrix `n` x 2 repeating 4 0
```
4 0$~10 2
4 0
4 0
4 0
4 0
4 0
4 0
4 0
4 0
4 0
4 0
```
`-` subtract the second matrix from the first one, so that the first column is "delayed" with 2 positions
```
2(i.-4 0$~])@,~] 10
_4 1
_2 3
0 5
2 7
4 9
6 11
8 13
10 15
12 17
14 19
```
`_5,./\` traverse the matrix in non-overlapping groups of 5 rows and stitch the columns
```
_5,./\2(i.-4 0$~])@,~] 10
_4 _2 0 2 4
1 3 5 7 9
6 8 10 12 14
11 13 15 17 19
```
`[:,` ravel the entire array
```
,_5,./\2(i.-4 0$~])@,~] 10
_4 _2 0 2 4 1 3 5 7 9 6 8 10 12 14 11 13 15 17 19
```
`2}.` - drop the first 2 numbers
```
2}.,_5,./\2(i.-4 0$~])@,~] 10
0 2 4 1 3 5 7 9 6 8 10 12 14 11 13 15 17 19
```
`{.` take the first `n` numbers
```
({.2}.[:,_5,./\2(i.-4 0$~])@,~]) 10
0 2 4 1 3 5 7 9 6 8
```
# [J](http://jsoftware.com/), 9 bytes
```
+_2+5|2+]
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F873kjbtMZIO/a/JpeSnoJ6mq2euoKOQq2VQloxV2pyRr5CmoIFjKFmp5CpZ2hg8B8A "J – Try It Online")
Returns the `n`th element.
Port of Arnauld's answer
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 12 bytes
```
{-2+x+5!x+2}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlrXSLtC21SxQtuo9n@auqKhwX8A "K (ngn/k) – Try It Online")
[Answer]
# [Pepe](//github.com/Soaku/Pepe), 65 bytes
```
REeeeeeeEerEeERRrEEEEEERREeeeeeEeErEEeEeErRrEEEEEEEErRrEEEEEereEE
```
[Try it online!](https://soaku.github.io/Pepe/#!6tQ--&2-!6z_i@-Se@-&0M)
Port of [Jo King's answer.](/a/174729/)
[Answer]
# x86 machine code, 16 bytes
```
00000000: 31d2 89c8 4949 4040 b305 f7f3 9201 c8c3 1...II@@........
```
Assembly:
```
section .text
global func
func: ;function uses fastcall conventions, 1st arg in ecx, returns in eax
;reset edx to 0 so division works
xor edx, edx
mov eax, ecx
;calculate ecx (1st func arg) - 2
dec ecx
dec ecx
;calculate (ecx+2) mod 5
inc eax
inc eax
mov bl, 5
div ebx
xchg eax, edx
;add (ecx-2) and ((ecx+2) mod 5), returning in eax
add eax, ecx
ret
```
[Try it online!](https://tio.run/##bVPbbtswDH22voIIWsROotzaYVid9WFYh73tA@YhkCUm8WpLgSQnHrJ8e0Y5TRsXe5FE8hzyUKJy4TYnKTwsFk8/vsEjTHy1nYixcBWkoMPGV1iu7ubXEW7OljQKx4aAKDcGegwbj1ZDoT0sl8J7W@S1x@UyjlfCeSnKMklgVWsZEyRJgQVkJQodJwe2Mja4ofg8TYvFbErrcEj@rSXvKs56tyrTWW905idJyo7s2LtIdr7OxzLNWMbWUnYVkv5rUEc714ZvCwRe3c1btsl/q7raAv/awVEZhTvKoNDaLtB1gH/BI16DybO2SLgn6P@c8k@/DvdH6JNX1h54Dh/5/TywLHAF/Uz334wW1qYLBTbYjH3jybWnBiXtYv8M/UN7QXAzm8yPAX@@L@hlejAYfPnjEaSptX8gK9O3LtM9uInDk/PkP121L8nxhf4dm9Bj4NJNX2OhaRRwkrl9Ly4EHt@n7TzGyaH0hdEw9jQxLFqXJhdlOxgsLA9RGrYWUjt0cJke6kTvUIeAG8HMeRB2TeNG89eMwKKvrXatLRoWpRYdekDVgDcwBWdAFbvChbR7Y58dixpjQ3wUFsaiyuwCdRTyEZ9KyroUdINkQxzqBV2haAIc5ixSKM/Yy6HDiskznCdQGQUfWFQQtRX2egj18nIUgqQMMCdfIzfrFxGkKaKEQqk2FadUQtO5kze5NF7o9WvrgfLWCMVP9LtP/wA "Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 26 bytes
```
func[n][n + 2 % 5 + n - 2]
```
[Try it online!](https://tio.run/##FYqxCoAwDAX3fsWjICgiVMHFz3ANGaRNoUuQ0H5/rdPB3ZmkfksidvnquWkkZVKsODDhHFRsOLi/VrQiYw/O5JWnouAM9GuYpBYFNPJcxr4v8B4M7h8 "Red – Try It Online")
Port of Arnauld's answer
[Answer]
# Excel, 17 bytes
```
=A1-2+MOD(A1+2,5)
```
Nothing smart. Implements the common formula.
[Answer]
# [C (gcc)](https://gcc.gnu.org/) POSIX, 20 bytes
```
f(n){n=n-2+(n+2)%5;}
```
[Try it online!](https://tio.run/##HYpBDoMgEADP8oqNjQmE0jSmnrD9Rs8GxG6Ci0E8Gb9eij1NMjNGTcbkC5Lxmx2hX5PFcPu8suMk9jimLRKQaiUn2Yqm00dGSjAPSFzAzioXIvBTITzhrgt6eJyU8t@rJZbqeN1YqK/gOAqhWXWwI3@N88O0ZvWmoHBePBpMqtw/ "C (gcc) – Try It Online")
[Answer]
# QBasic, 30 bytes
```
INPUT x
x=x+2
?-4+x*2-(x\5)*5
```
Gives the 0-indexed entry of the list at pos `x`.
[Try it online!](https://repl.it/@pimsteenbergh/NeighboringHeavyVerification) (Note that `?` was expanded to `PRINT` because the interpreter fails otherwise...)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 14 bytes
```
n=>2*n%5+n/5*5
```
[Try it online!](https://tio.run/##BcGxCoAgEADQfwmC08wkcqytJZpqaDY55MAuUPt@e8/n3meqV6KCOzFCLok46O0lhkY1auXvweTuiPpwHBCMmozQJ0b0BSrPyyi5tR0PVtoqhKg/ "C# (Visual C# Interactive Compiler) – Try It Online")
Same logic than others answers: [1](https://codegolf.stackexchange.com/questions/174706/new-neighbour-sequence/174751#174751) [2](https://codegolf.stackexchange.com/questions/174706/new-neighbour-sequence/174708#174708)
[Answer]
# TI-BASIC, 11 bytes
```
Ans-2+remainder(Ans+2,5
```
Input is in `Ans`.
Outputs \$a(n)\$.
A simple port of the other answers.
---
**Note:** TI-BASIC is a tokenized language. Character count does ***not*** equal byte count.
[Answer]
# [R](https://www.r-project.org/), 25 bytes
```
n=1:scan()-1;n-2+(n+2)%%5
```
[Try it online!](https://tio.run/##K/r/P8/W0Ko4OTFPQ1PX0DpP10hbI0/bSFNV1fS/oYHBfwA "R – Try It Online")
Port of Robert S.'s answer (and only by adding just 4 bytes) thanks to R being excellent at handling vectors.
Outputs the first n values.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 9 bytes
```
d2+5%+2-p
```
[Try it online!](https://tio.run/##S0n@b2j4P8VI21RV20i34P9/AA "dc – Try It Online")
Same method as most. Duplicate top-of-stack, add 2, mod 5, add to original (duplicated earlier), subtract 2, print.
] |
[Question]
[
This is a rather simple challenge, but I couldn't find any question that was really similar to it. The challenge is to take a frequency in using STDIN or an equivalent, and then output a tone that matches that frequency, in Hz, for 5 seconds. For example
```
Input: 400
Output: (a tone of 400 Hz with a duration of 5 seconds)
```
## Rules
* Input must be taken in through STDIN, or your language's equivalent
* The answer must be a full program
* Builtins may be used
* The frequency will be anywhere from 50 - 5000 Hz
* The output must be played for 5 seconds
* The output must be in the form of a sine wave
## Test cases
Input: `440`
Output:
Input: `200`
Output:
Input: `4000`
Output:
---
* This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in *every* language. Therefore, no answer will be marked as accepted.
* Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.
Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.
Also note that languages *do* have to fullfil [our usual criteria for programming languages](http://meta.codegolf.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073).
---
## Catalogue
The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{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><script>var QUESTION_ID = 63967; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 39060; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```
[Answer]
# QBasic, ~~18 bytes~~ (disqualified)
Like @pabouk mentioned, this uses the PC speaker, so it plays a *square* wave, not a sine wave like the problem asks. (This requirement was added to the problem *after* this answer was posted, hence the votes.) I'll leave it here for posterity anyway.
---
```
INPUT F
SOUND F,91
```
[Play a sound](https://en.wikibooks.org/wiki/QBasic/Sound#SOUND) at the inputted frequency for 91 ticks, which is equal to 5 seconds.
[Answer]
# Python2, 40 bytes
```
from winsound import*
Beep(input(),5000)
```
Only works on Windows.
[Answer]
## Mathematica, 42 bytes
Well if we can use built-ins...
```
Input[]
EmitSound@Play[Sin[2t%Pi],{t,0,5}]
```
Thanks to the requirement for a full program, this was the first time I got to use [my recently discovered golfing tip](https://codegolf.stackexchange.com/a/58842/8478) of using `%` (result of last evaluation) to save two bytes.
Mathematica also has a built-in `Sound` which takes a pitch and a duration as arguments, but unfortunately the pitch has to be given as a musical note. Specifying your own sound wave via `Play` seems to be the only way to work with a frequency.
[Answer]
## MATLAB, 36 bytes
```
sound(sin(pi*input('')*(0:8^-4:10)))
```
Thanks to [flawr](https://codegolf.stackexchange.com/users/24877/flawr) for saving two bytes.
[Answer]
# C#, 80 bytes
```
class P{static void Main(string[]a){System.Console.Beep(int.Parse(a[0]),5000);}}
```
[Answer]
## PowerShell, 32 bytes
```
[console]::beep((read-host),5kb)
```
[Answer]
# [FakeASM](http://esolangs.org/wiki/FakeASM), 12 bytes
```
RDA
BEEP 5e3
```
Works with the Windows reference implementation [(download)](https://www.dropbox.com/s/upg2fqvoylj7wmd/fakeasm.zip?dl=0). It calls Windows' `Beep` function, which is a sine wave on modern platforms.
[Answer]
# Bash + X11, ~~27~~ 20 bytes
```
xset b 9 $1 5;echo
```
This contains an unprintable, so here's a hexdump:
```
0000000: 7873 6574 2062 2039 2024 3120 353b 6563 xset b 9 $1 5;ec
0000010: 686f 2007 ho .
```
This takes the frequency as a command-line argument and plays the appropriate beep at a volume of 9% (since no volume was specified).
(Note: I was unable to test this due to some issues with my computer, but I'm 99% sure it works.)
[Answer]
# Bash + Linux utils, 95
```
bc -l<<<"obase=16;for(;t<5;t+=1/8000){a=s($1*t*6.3);scale=0;a*30/1+99;scale=9}"|xxd -p -r|aplay
```
This is a true sine wave. No beeps. Input frequency entered via the command-line:
```
./hz.sh 440
```
[Answer]
# Processing, ~~148~~ ~~114~~ 106 bytes
```
import processing.sound.*;
Engine.start().sinePlay(int(loadStrings("s")[0]),1,0,0,0);delay(5000);exit();
```
(For some reason Processing requires both using the import statement and the new line, otherwise it does not recognize the library.)
I still haven't figured out how to pass arguments into Processing, though I know it's possible, so this code requires having a file called "s" in the sketch folder which has the frequency value. If I can figure out how to pass in arguments I could replace file loading with `args[0]`.
[Answer]
## JavaScript, 114 bytes
```
p=prompt();c=new AudioContext;with(c.createOscillator()){frequency.value=p;connect(c.destination);start();stop(5)}
```
Requires a somewhat cutting-edge browser, enter the frequency in the prompt.
[JSFiddle](https://jsfiddle.net/mr4fmtxw/1/)
[Answer]
## VB.net, 90 bytes, 74 bytes
```
Module m
Sub Main(a() as String)
Console.Beep(a(0),5000)
End Sub
End Module
```
Thanks to Sehnsucht
```
Module m
Sub Main()
Console.Beep(My.Application.CommandLineArgs.First,5000)
End Sub
End Module
```
This is my first post so if I did any thing wrong please let me know
[Answer]
# Turbo/Borland/Free/GNU Pascal, 95 bytes
Due to issues with the delay function on modern computers (well, anything faster than 200Mhz) trying to run Turbo / Borland pascal, this might not wait 5 seconds, even with a patched CRT library
```
Program a;Uses crt;Var i,k:Integer;BEGIN Val(ParamStr(1),i,k);Sound(i);Delay(5000);NoSound;END.
```
The String to Integer conversion can be done shorter (77 bytes) on FreePascal, and modern derivates, as they have the `StrToInt` function:
```
Program a;Uses crt;BEGIN Sound(StrToInt(ParamStr(1)));Delay(5000);NoSound;END.
```
[Answer]
## Perl, 27 bytes
Basically a Perl version of the Python answer (also only works on Windows), if we're allowing modules.
```
use Audio::Beep;beep<>,5000
```
[Answer]
# Vitsy + X11, 20 bytes
```
"5 "WX" 9 b tesx",7O
```
A translation of my bash answer. Does not work in the online interpreter (obviously).
Takes input as any non-numeric character followed by the frequency (so for an input of 440 Hz you could do "a440").
## Explanation
```
"5 "WX" 9 b tesx",7O
"5 " Push " 5"
WX Reads input and removes the first character (which is used to force string context)
" 9 b tesx" Push "xset b 9 "
, Pop everything and execute as a shell command.
7O Output bell char.
```
[Answer]
# C with WinAPI, 82 bytes
```
#include<windows.h>
#include<stdio.h>
main(){int x;scanf("%i",&x);Beep(x,5000);}
```
Uses the WinAPI Beep() function.
[Answer]
# [Hassium](http://HassiumLang.com), 38 Bytes
```
func main()Console.beep(input(), 5000)
```
[Answer]
## Shadertoy GLSL Sound Shader, 86
```
#define F 440.0
vec2 mainSound(float t){return vec2(sin(6.3*F*t)*(t<5.0?1.0:0.0));}
```
"Input" is given via `#define`. Outputs a sinewave with approximate frequency of `F`Hz. Rounded 2\*Pi to 6.3, instead of "default" 6.2831, but sounds pretty much the same.
Sadly there isn't much to golf here.
[Answer]
# Jolf, 4 bytes, noncompeting
This language addition came after the challenge.
```
Αc5j
Αc create a beep
5 five seconds long
j with the input as a frequency
```
The default wave is a sine wave.
[Answer]
# SmileBASIC, 84 bytes
```
INPUT F
N=LOG(F/440,POW(2,1/12))+57BGMPLAY FORMAT$("@D%D@255T12N%D",(N-(N<<0))*63,N)
```
Converts from Hz to half steps, and plays the a certain note with the a detune value to produce the frequency.
] |
[Question]
[
If an integer has a digit/sequence of digits in it which repeats continuously (You will understand why I said "continuously") 5 or more times, we call It "Boring".
For example, `11111` is Boring, whereas `12345` is not.
# Instructions
Take an Integer as Input
Output a truthy value if the integer is boring, and a falsey value if the integer is not boring.
# Example
`11111`=>`true` or `1` (1 repeats 5 times)
`12345`=>`false` or `0`
`1112111`=>`false` or `0`
`4242424242`=>`true` or `1` (42 repeats 5 times)
`-11111`=>`true` or `1`
`3452514263534543543543543543876514264527473275`=>`true` or `1` (543 repeats 5 times)
If you use other types of "truth" and "false", specify it.
# Rules
Basic [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
Good luck!
[Answer]
# [Retina](https://github.com/m-ender/retina), 9 bytes
```
(.+)\1{4}
```
[Verify all testcases!](http://retina.tryitonline.net/#code=JWAoLispXDF7NH0&input=MTExMTEKMTIzNDUKMTExMjExMQo0MjQyNDI0MjQy) (slightly modified to run all testcases at once.)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 8 bytes
Code:
```
Œv¹y5×åO
```
Explanation:
```
Œ # Compute all substrings from the input.
v # For each substring.
y5× # Repeat the substring 5 times (42 × 5 = 4242424242).
¹ å # Check if it's in the input string.
O # Sum up the result. Non-boring numbers should give 0.
```
**Truthy** is non-zero and **falsy** is zero. Uses the **CP-1252** encoding.
[Try it online!](http://05ab1e.tryitonline.net/#code=xZJ2wrl5NcOXw6VP&input=NDI0MjQyNDI0Mg)
[Answer]
# Java 8, 52 bytes
```
s->s.matches(".*(.+)\\1{4}.*")
```
Outgolfed [this Java 8 answer](https://codegolf.stackexchange.com/a/84750/52210) with a direct `String#matches`.
**Explanation:**
[Try it here.](https://tio.run/##jU9LbsIwEN3nFKOsbKpYsuOQSojeoGxYQheDcVtDYkfYICGUs6fDT2JVsGeksd5nnjd4wCJ01m/W28E0GCN8ovOnDMD5ZHffaCzMzk@AVQiNRQ@GzdPO@R@IfEJAT00VEyZnYAYepjDE4iOKFpP5tZHlYsTEG18u5Un3YpTzYZKRotuvGlLchIfg1tDS7pv74gv5de/8GJNtRdgn0RGSGs@8MCyX55PzS4h/WKrU1XOWlOoVN63u9ym1eC0fpVOV1GpcVjTq8rHe6/EFIkqt61LV94/0WT/8AQ)
```
s-> // Method with String parameter and boolean return-type
s.matches( // Return whether the entire String matches the following regex:
".* // 0 or more leading characters
(.+)\\1{4} // group of 1 or more characters, repeated 5 times
.*") // 0 or more trailing characters
```
[Answer]
# Java 8, ~~73~~ 66 bytes:
```
L->java.util.regex.Pattern.compile("(.+)\\1{4}").matcher(L).find();
```
Hooray for Java 8 lambdas! Returns `true` if match is found and `false` otherwise.
[Try It Online! (Ideone)](http://ideone.com/bU1vbB)
[Answer]
## Lua, 35 Bytes
Well, I don't see how to do better with Lua's patterns! Takes a command-line argument as input and output `nil` for falsy cases, and the number repeated when truthy.
```
print((...):match("(%d+)%1%1%1%1"))
```
[Answer]
# JavaScript, 16 bytes
In node.js (60 bytes)
```
process.stdin.on('data',t=>console.log(/(.+)\1{4}/.test(t)))
```
Wasting a *ton* of bytes on input/output.
JavaScript ES6 (33 bytes)
```
alert(/(.+)\1{4}/.test(prompt()))
```
Again wasting bytes on input/output.
Preferably, as an anonymous function (22 bytes)
```
n=>/(.+)\1{4}/.test(n)
```
Or even shorter (**16 bytes**)
```
/(.+)\1{4}/.test
```
Thanks @BusinessCat for pointing out my mistakes.
[Answer]
# Python 3.5, ~~49~~ 43 bytes:
(*-6 bytes thanks to tips from [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender)!*)
```
import re;lambda u:re.search(r'(.+)\1{4}',u)
```
Uses a Regular Expression to match all repeating sequences of characters as long as they repeat continuously 5 or more times. Returns an `re` match object (such as `<_sre.SRE_Match object; span=(0, 10), match='4242424242'>`) if a match is found as a truthy value, and nothing or `None` as a falsey value.
[Try It Online! (Ideone)](http://ideone.com/I41iPz)
[Answer]
## Perl, ~~17~~ 15 bytes
```
$_=/(.+)\1{4}/
```
+ the `p` flag.
(run with `perl -pe '$_=/(.+)\1{4}/'`)
Thanks to Dom Hasting for the `(.+)` instead of `(\d+)`.
Explanations if needed :
`(.+)` will match any part of the number, and `\1{4}$` searches if it is repeated 4 times consecutives.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~13~~ 11 bytes
```
§ṁ€ȯm*5tQda
```
[Try it online!](https://tio.run/##yygtzv7//9DyhzsbHzWtObE@V8u0JDAl8f///7qGIAAA "Husk – Try It Online")
similar to 05AB1E.
-2 bytes from Dominic Van Essen and Jo King.
[Answer]
## SABDT, 41 bytes
White Space-less:
```
if($.r("(.+)\1{4})"=""){pr"0";}el{pr"1";}
```
Prettified:
```
if( $.r( "(.+)\1{4}" ) = "" ){
pr "0";
} el {
pr "1";
}
```
Answer brought to you partly by the brilliant person who came up the regex "(.+)\1{4}"
[Answer]
# [Python 3](https://docs.python.org/3/) without regex, 66 bytes
```
lambda s:any(s[j:i]*5in s for i in range(len(s))for j in range(i))
```
[Try it online!](https://tio.run/##TY3PDsIgDIdfpcdi8DD@DEPik8wdMA5lmd0CXPb0CBqjbQ@/fl@Tbnt@rCSLP1/K4p7Xm4NkHe2YhtmG8aADQQK/RghQY3R0n3CZCBNjjc4/GhgrDVFDQ9eKd0IqzWsSbVPi2/z48dUK3SnRS12jkv9zMv1b1ROjjBRGjxa2GCijx5QjEqsfXw "Python 3 – Try It Online")
[Answer]
## C# - 93 38 bytes
```
s=>new Regex(@"(.+)\1{4}").IsMatch(s);
```
Takes a string, returns an integer.
Thanks to [aloisdg](https://codegolf.stackexchange.com/users/15214/aloisdg) for saving a lot of bytes!
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~9~~ 8 bytes
1 byte thanks to Maltysen.
```
~~sm}\*5dQ.:~~
f}*5TQ.:
```
Truthy value is a non-empty array.
Falsey value is `[]` (empty array).
[Test suite.](http://pyth.herokuapp.com/?code=f%7D%2a5TQ.%3A&test_suite=1&test_suite_input=%2211111%22%0A%2212345%22%0A%221112111%22%0A%224242424242%22&debug=0)
```
f}*5TQ.: input as a string stored in Q
f}*5TQ.:Q implicit arguments
Q input
.: all substrings of.
f T filter for this condition, keep those returning true:
*5 repeat five times
} Q in Q? (True/False)
```
[Answer]
# Mathematica, ~~46~~ ~~40~~ 36 bytes
```
b=a__;StringContainsQ[b~~b~~b~~b~~b]
```
Function. Takes a string as input and outputs `True` or `False`. Tests strings against the expression `a__~~a__~~a__~~a__~~a__`, which represents the same character sequence repeated 5 times. For reference, the shortest solution using a regex is 45 bytes long:
```
StringContainsQ@RegularExpression@"(.+)\1{4}"
```
*curse you RegularExpression!*
[Answer]
# PHP, ~~37~~ 33 bytes
thanks to NoOneIsHere, I forgot about `<?=`
program for PHP<5.4, prints `1` for boring numbers, `0` else
```
<?=preg_match('/(.+)\1{4}/U',$n);
```
usage:
* set `register_globals=1` in `php.ini` for php-cgi
then call `php-cgi <filename> n=<number>;echo""`
* for PHP>=5.4, replace `$n` with `$_GET[n]`
**non-regexp solution, ~~152~~ ~~147~~ 140 bytes**
```
<?for($e=$n+1;--$e;)for($f=$e;$f--;)for($a=str_split(substr($n,$f),$e),$k=$c='';strlen($v=array_pop($a));)$c-$v?$k=0&$c=$v:($k++<3?:die(1));
```
* returns exit code 1 for boring numbers, 0 else
replace `die(1)` with `die(print 1)` and append `echo 0;` to print instead
* same usage as above, but also set `short_open_tags=1` if disabled
* The outer loop got an unreasonable start value in the golfing, replace `$n+1` with `ceil(strlen($n)/5)+1` or at least with `strlen($n)` for testing or it may loop like forever.
[Answer]
# Haskell, 80 (63?)
It would be 63 if there were no import statement.
```
import Data.List
f x=or$tail[isInfixOf(concat$replicate 5 b)x|b<-subsequences x]
```
### Usage
```
f "11111211"
f "11111"
f "12345"
f "1112111"
f "4242424242"
f "-11111"
f "3452514263534543543543543543876514264527473275"
```
By the way, *consecutive* makes more sense to me than *continuously.*
(Sorry, I can't comment yet.)
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 22 bytes
```
q:T,{)Tew{5*T\#)}/}%:+
```
[Try it online!](https://tio.run/##S85KzP3/v9AqRKdaMyS1vNpUKyRGWbNWv1bVSvv/f2MTUyNTQxMjM2NTINPEGBlZmJuBpYBKzE3MjY3MTQE "CJam – Try It Online")
Takes sum of 1-indexed positions of all possible repeated substrings in the input. Returns 0 if interesting, anything non-zero if boring.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
øUã mp5
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=%2bFXjIG1wNQ&input=WwoiMTExMTEiIC8vdHJ1ZQoiMTIzNDUiIC8vZmFsc2UKIjExMTIxMTEiIC8vZmFsc2UKIjQyNDI0MjQyNDIiIC8vdHJ1ZQoiLTExMTExIiAvL3RydWUKIjM0NTI1MTQyNjM1MzQ1NDM1NDM1NDM1NDM1NDM4NzY1MTQyNjQ1Mjc0NzMyNzUiIC8vdHJ1ZQpdLW1S) (includes all test cases)
```
øUã mp5 :Implicit input of string U
ø :Does U contain any element of
Uã : Substrings of U
m : Map
p5 : Repeat 5 times
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `Ṡs`, 34 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.25 bytes
```
K5*vc
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIg4bmgcz0iLCIiLCJLNSp2YyIsIiIsIjExMTExMTIyMjIyMiJd)
The 05ab1e answer but in less bytes :)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 77 bytes
```
s=>s.some((_,i)=>s.some(c=>--i<0&&([,s]+1).split([t+=[,c]]+t+t+t+t)[1],t=''))
```
[Try it online!](https://tio.run/##hcpBCsIwEEDRvQdpZkgyWOnS6bKXCEFKDBKJTXGC10@hokvlrz68@/yaJTzTWu1SrrFN3IRHISmPCHAxCb8XeLQ2nY9dB86I1z2SrDlVcFWzM8F7Xd@h672prBRiC2WRkiPlcoMJHBGp4fRJecTDD/EXDDtoGw "JavaScript (Node.js) – Try It Online")
[Answer]
# TSQL, 151 bytes
Golfed:
```
DECLARE @t varchar(99)='11111'
,@z bit=0,@a INT=1,@ INT=1WHILE @a<LEN(@t)SELECT @z=IIF(@t LIKE'%'+replicate(SUBSTRING(@t,@a,@),5)+'%',1,@z),@=IIF(@=20,1,@+1),@a+=IIF(@=1,1,0)PRINT @z
```
Ungolfed:
```
DECLARE @t varchar(99)='11111'
,@z bit=0,
@a INT=1,
@ INT=1
WHILE @a<LEN(@t)
SELECT
@z=IIF(@t LIKE'%'+replicate(SUBSTRING(@t,@a,@),5)+'%',1,@z),
@=IIF(@=20,1,@+1),
@a+=IIF(@=1,1,0)
PRINT @z
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/509048/golf-to-find-boring-numbers)**
[Answer]
# PowerShell, 26 bytes
```
$args[0]-match"(.+)\1{4}"
```
I'm by no means a regex master, so credit to the other answers for that.
[Answer]
# Clojure, 24 bytes
```
#(re-find #"(.+)\1{4}"%)
```
Uses clojure's falsey values of `nil`/`false` and truthy values for everything else. Specifically, `nil` when no match is found for false, and an array `[]` for true when a match is found like for 11111 then `["11111" "1"]` is true.
[Answer]
# JS without regexes, 166
```
b=s=>{for(let i=0;i<s.length-4;i++){for(let n=1;n<=Math.floor((s.length-i)/5);n++){if([1,2,3,4].every(k=>s.slice(i,i+n)==s.slice(i+n*k,i+n*(k+1))))return 1}}return 0}
```
non minified:
```
// test any start pos, and length
var b = s => {
for (let i = 0; i <= s.length - 5; i++) {
for (let n = 1; n <= Math.floor((s.length - i) / 5); n++) {
// test if s is boring at position i, with length n
if ([1, 2, 3, 4].every(k => s.slice(i, i + n) === s.slice(i + n * k, i + n * (k + 1)))) {
return 1;
}
}
}
return 0;
};
console.log(b('11111'));
console.log(b('12345'));
console.log(b('1112111'));
console.log(b('-11111'));
console.log(b('3452514263534543543543543543876514264527473275'));
```
[Answer]
# [Scala 3](https://www.scala-lang.org/), 27 bytes
```
_.matches(".*(.+)\\1{4}.*")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sODkxJ9F4wU3L_KSs1OQSBd_EzDyFai4FhZLKglQFPwVbheCSosy8dAVbOwWn_Pyc1MQ8LqBsWWKOQp4VWH5paUmarsXueL3cxJLkjNRiDSU9LQ09bc2YGMNqk1o9LSVNiIqbH4H6UlLTFHKBVmgkFqUXWyk4FhUlVkZDbIjVtFIIzcssARoJsl9BoQAoWpKTp5GnoWQIAkqamhjiRsYmptjEDQ2NsOswMYJBLJK6uOwB2mJkamhiZGZsCmSaGCMjC3MzsBRQibmJubGROdRBtVy1EI8vWAChAQ)
] |
[Question]
[
Given two strings as input, return the result of XORing the code-points of one string against the code points of the other.
For each character in the first input string, take the code-point (e.g. for `A`, this is 65) and XOR the value against the corresponding index in the second string and output the character at the code-point of the result. If one string is longer than the other, you **must return the portion of the string beyond the length of the shorter**, as-is. (Alternatively, you may pad the shorter string with `NUL` bytes, which is equivalent.)
See the following JavaScript code for an example:
```
const xorStrings = (a, b) => {
let s = '';
// use the longer of the two words to calculate the length of the result
for (let i = 0; i < Math.max(a.length, b.length); i++) {
// append the result of the char from the code-point that results from
// XORing the char codes (or 0 if one string is too short)
s += String.fromCharCode(
(a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0)
);
}
return s;
};
```
[Try it online!](https://tio.run/##bVNtT9swEP68/IobX@KsbZp2vKoDxEolPmyCgiYmtYW5idtkMnGwHRo0@O3d2U5pealqXc5@nudedPeXPlAVy6zQrVwkbLmMRa40VEJeaZnlcwWHQGgTpgEcHsE/D4AzDebW93seuu02lIqBThlwkc@ZBDGznl4IWAiZKNACYsrjklNdA1k@1@kKKJkquUapmZBAjHyG8lEPzTf4SXUa3tGK0NCxMJX6K0BEoxHYpGwetChYnmxoriLEKZUwk@LOeVhnqxBZrtGlusYqC1hJ/T6/xOLXZMNRQDDBCLIZiJyBsv2BzNQnQKVC6sDSFTQOwXUvNJp9FOgjn9hXwHaGcX11okkWwNMTRAHcAJl@9GBZQQ/Ns@m3ZLqUOaie94z9H@HNyD9jnIum3wT/WkiefPYnTRfKlOKPq85sXEUULUMb4ZniSfw111AX55c/TtdMxz3@cgQNB6TTOGEGGHW6X7ffAodXw@uhA3KxYDKmyoC3Do59B9pCggH@urgYXPZPrgYOrJnSRhT1PsGrnwHbV4szMXcM8GB/b3fnbXQsZ9@VGG3j6ZoyfbjNhb6FTqcTHXRfBbN2Q@JFJNo8L4EN5eR7/3TwnlMUxWldSdQxuHv1DmeBjm@Bf@K6lOHwA6Ar1JsgNMSFGNA4JWRkNnBiV9Dsp@As5GLuBmq9qm5PvRctneJw4t/s1QPlWUJ1JnIcXv4IFBcFn7BDOFH3ZSYZ@jk8itINe60SSlZwGjPSHt2Mq27UGld7bNKeN4HENh1vlbs/Hlc@NID4kTHx5igHoRYuR9LZDQJvXXGoyikuEml1V7fGIqS3XP4H "JavaScript (Node.js) – Try It Online")
## Test cases
```
Input Output
['Hello,', 'World!'] '\x1f\x0a\x1e\x00\x0b\x0d'
['Hello', 'wORLD'] '?*> +'
['abcde', '01234'] 'QSQWQ'
['lowercase', "9?' "] 'UPPERCASE'
['test', ''] 'test'
['12345', '98765'] '\x08\x0a\x04\x02\x00' _not_ 111092
['test', 'test'] '\x00\x00\x00\x00'
['123', 'ABCDE'] 'pppDE'
['01', 'qsCDE'] 'ABCDE'
['`c345', 'QQ'] '12345'
```
## Rules
* The two input strings will only ever be code-points 0-255.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest solution, in each language, wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
O^/Ọ
```
[Try it online!](https://tio.run/##y0rNyan8/98/Tv/h7p7///9HqycmJaekqusoqBsYGhmbqMcCAA "Jelly – Try It Online")
Takes input as a list of the two strings, e.g. `['abcde', '01234']`.
### How?
```
O # ord: cast to number (automatically vectorizes)
^/ # Reduce by XOR. XOR automatically applies to corresponding elements
and pads as desired to work if the two strings are different lengths
Ọ # chr: cast to character (vectorizes once again)
```
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 4 bytes
```
*~^*
```
[Try it online!](https://tio.run/##XY9fCwFREMXffYrhwdQS966/m9jElgfFEh4sWvZuqcvV7hZKvvq6g4Sp0zzM75yZOYlI1tPDFfIhtFPjvjbSVib2rxDC7VD2liXD9lblkjPvDiFUEcj9UcTpEgdCSlXEIuBCRTLI4go@hd6Fh96F@boL3ZnWVivAzNtIvvNoMux/27TRNjpQIMrf7gJBFONmpfpHuVN34RIl1VlEOz8mMmfZ@JrnnjTOxmNn0utOHSITEScU95v0znsONUSrakRZzUa99rdU3998/cSqWib9hbA5qmQDnHNmmQ8 "Perl 6 – Try It Online")
Raku has a built-in operator for XORing strings, along with string AND, OR and bitshift. This is a Whatever lambda that takes two parameters.
[Answer]
# perl -Mfeature=say,bitwise -nl, 22 bytes
```
$.%2?($;=$_):say$;^.$_
```
[Try it online!](https://tio.run/##K0gtyjH9/19FT9XIXkPF2lYlXtOqOLFSxTpOTyX@/3@P1JycfB2u8PyinBRFLjCPq9w/yMeFKzEpOSWVy8DQyNiEKye/PLUoObE4lcvSXl0BDLhKUotLuLhA0qZclhbmZqb/8gtKMvPziv/r@qalJpaUFqXaAi3SScosKc8sTv2vm5cDAA)
This is way more characters than I first hoped for. If it weren't for those pesky newlines, the 9 character `say<>^.<>` would do.
## How does it work?
For odd input lines, it saves the current line of input (without the trailing newline due to the `-n` and `-l` switches) into `$;`. For even lines, it `xor`s the previous line (`$;`) and the current line (`$_`), and prints it. The `^.` operator does required bitwise string operation.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 15 [bytes](https://github.com/abrudz/SBCS)
```
80⎕DR≠⌿↑11⎕DR¨⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@FwaO@qS5BjzoXPOrZ/6htoqEhmH9oBZACqfjPmcal7pGak5Ovo66gHp5flJOiqM4FFwSKlfsH@bhAhBKTklNSgUIGhkbGJhChnPzy1KLkxGKQsKW9uroCGEDkSlKLS4DCEA5IiylIkYW5mak6AA "APL (Dyalog Unicode) – Try It Online")
As the OP clarified that the input codepoints will be in the range of 0-255, it is possible to manipulate the underlying data bits directly. Such a string is guaranteed to have data type `80` (8-bit char array), so we convert it to data type `11` (1-bit boolean array) to access the bits, XOR them, and convert back to data type `80`.
```
80⎕DR≠⌿↑11⎕DR¨⎕ ⍝ Full program, input: two string literals on a line
11⎕DR¨⎕ ⍝ Convert each string literal to bit array
↑ ⍝ Promote to matrix, padding with 0 as needed
≠⌿ ⍝ Bitwise XOR
80⎕DR ⍝ Convert back to 8-bit char array
```
---
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 17 bytes
```
⎕UCS⊥≠⌿⍤2⊤↑⎕UCS¨⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97f@jvqmhzsGPupY@6lzwqGf/o94lRo@6ljxqmwiROLQCSINU/udM41L3SM3JyddRV1APzy/KSVFU54ILAsXK/YN8XCBCiUnJKalAIQNDI2MTiFBOfnlqUXJiMUjY0l5dXQEMIHIlqcUlQGEIB6TFFKTIwtzMVB0A "APL (Dyalog Extended) – Try It Online")
Well, the task involves converting char to charcode and back AND converting from/to binary, but all current implementations having `⍢` have some quirks so it can't be used here. So here is the very literal implementation of the task.
```
⎕UCS⊥≠⌿⍤2⊤↑⎕UCS¨⎕ ⍝ Full program, input: two string literals on one line
⎕UCS¨⎕ ⍝ Convert to codepoints
↑ ⍝ Promote into a 2-row matrix, padding zeros as necessary
⍝ (doing on characters give spaces which is 0x20, not 0)
⊤ ⍝ Convert each number to binary
≠⌿⍤2 ⍝ Bitwise XOR
⊥ ⍝ Convert the binary back to integers
⎕UCS ⍝ Convert the integers back to chars
```
[Answer]
# [J](http://jsoftware.com/), 14 bytes
```
XOR@,:&.(3&u:)
```
[Try it online!](https://tio.run/##bY9PT8JAFMTv/RRPDzzR2uwWUGiiCG2NBwJsicEDCZb@OZjGVloD376@7gKpaTeZvD38ZibzVV4bGMOTBQg6MLBI9wbY3uy1/Fh4L7rVMW56nV@rW3ZLfIuSJNURYsB1uk/CK4TLm08NwM2Rx5sj8@lGdBlpRwpRU15pPSy8mVNznrzj22e4I9DfBWEkQcbNXr8JipVYCwKT9BDtAz9X8GiMJxTP4Pty6Xr2ZOUSXER5Ibl/ebVUCWhYVQ5U4PDxYdBspzlDNZH1SWY1E2H7nRZb4JyzkVkrUx9oC2F1qWJpmUxtx23zZFnmVEsYl9xP3uQUqBI0/AzOU4RoBdXWPw "J – Try It Online")
### How it works
```
XOR@,:&.(3&u:)
(3&u:) strings -> code points
&. do right part, then left part, then the inverse of the right part
,: pad shorter one with zeros by making a table
XOR@ XOR the code points
(3&u:) revert back code points -> string
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~60~~\$\cdots\$ ~~55~~ 54 bytes
Saved ~~2~~ 4 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!!
Saved ~~a~~ 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
#define f(a,b)for(;*a+*b;b+=!!*b)a+=putchar(*a^*b)!=*b
```
[Try it online!](https://tio.run/##jVHbToNAEH3vVywY43IxQq1ag9jUtokPJvYS0wepuguLkiAgYEps@u24s0tr2yc3GebsXM6ZZfzTd9@v66OAhVHCUIiJSbUwzbGjE0OnDjVcRdGpRgw3@y79D5JjnbzwgOLqtP4kUYI1tGohfiCpo5IV5St5XiAXrdR7FsepqZpIIgCE@gEDEKdLlvukEBfoAm@3zzsXBwFwlg3fNx@ya@dQjjZy8zSPAwUql4/Th6Fs5IwArnsnSBy4iED36nJPqn83GI4AfBUNmEz@ZtpTZVXGqpIFja5X2aFXWYR7xr3FjXILoLun3yJDkM0mc8H3NB6PpoP@bLQrzsu7ksLqcGsDjYpkwto1KM6yTA4oR25G41tDOEpKFCUBq/hgltPAG1REPywN8WZu7awJiOdoDjIMUblZJZws51whVj31uPC4mPRewmGzY9GyMDc7kFfN2TKE@J@FW6mES4DA9v/ula5b6/oX "C (gcc) – Try It Online")
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 71 bytes
```
f=lambda a,b:chr(ord(a[0])^ord(b[0]))+f(a[1:],b[1:])if a and b else a+b
```
[Try it online!](https://tio.run/##bZLfT8IwEMef3V9RfbkWCNkQFUgmUSHxwUQmMTww1HbrwpKyznZR/OuxN6ZRtMn1Luvnez/alR/VWheng9Lsdlmo@EaknPCOGCVrQ7VJKV/6K/aEkcCItTP3KRitOgJ3lmfE8UVKBJHKSsLbYpdvSm0qYqRnQwMAS7iVSukOdAgstFHpMazI94J4G2Tx1ufOS@d9Z8JZCl4jRN37/cPd5KfMCcetS9JGiosklUj5Qe@0f0BF82gRIaX0uzQJt0ieDMewPz@paXiczaYPN1fzKZKVtBWm@52pyVcfOghLnSE1HFycnx0Udf0P9jP5fWc9nAvIc6GrZxIEgT/s/ShT@4NS0NzEtzUlkb@6vplM/wjKspzU3fsBQq/2H@hL66iXpGk/iv5S@9k893behlfJWprQyG6iN2WuJDVA42W3NY5XLLZtGgPGwNwOzOPWSvf4ShZ0OwobdTfLi5QrRS1jYRj4XqYN/mUkL8h25B2VJi8qmtEWlW9cUc4Qq0PB2O4T "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes
thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for a byte!
```
Ç0ζε`^ç
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cLvBuW3ntibEHV7@/3@0UkKysYmpko5SYKBSLAA "05AB1E – Try It Online")
### Commented
```
implicit input ["QQ", "`c345"]
Ç convert to charcodes [[96, 99, 51, 52, 53], [81, 81]]
ζ Zip with filler ... [[96, 81], [99, 81], [51, "0"], [52, "0"], [53, "0"]]
0 ... zero
ε Map ... [96, 81]
` Dump on stack 96, 81
^ XOR 49
ç Convert to character "1"
implicit output ["1", "2", "3", "4", "5"]
```
[Answer]
# Excel, ~~158 153~~ 108 bytes
(Not counting closing parens)
## Compatibility Notes:
* Minimum version: `CONCAT()` came to be in later versions of [Excel 2016](https://support.microsoft.com/en-us/office/concatenate-function-8f8ae884-2ca8-4f7a-b093-75d702bea31d) (from `CONCATENATE()`).
## The Formulae
* Inputs: `A1`, `B1`
* A2: `=MIN(LEN(A1:B1))`, 14
* B2: `=LEN(A1)-LEN(B1)`, 15
Code (124):
```
=CONCAT(CHAR(BITXOR(CODE(MID(A1,SEQUENCE(A2),1)),CODE(MID(B1,SEQUENCE(A2),1)))))&RIGHT(IF(B2>0,A1,B1),ABS(B2))
```
One unfortunate caveat is that Excel ignores non-printable characters in cells. Alternatively, if you'd rather I use "\xXX" characters, I have this:
```
=CONCAT("\x"&DEC2HEX(BITXOR(CODE(MID(A1,SEQUENCE(A2),1)),CODE(MID(B1,SEQUENCE(A2),1))),2))&RIGHT(IF(B2>0,A1,B1),ABS(B2))
```
at 118 bytes. This just prints all XOR'ed characters as "\xXX" characters and leaves the trailing characters alone. Eg: `Hello!` and `World!!` produce `\x3F\x2A\x3E\x20\x2B\x00!`
### How it Works:
1. The `SEQUENCE(A2)` effectively creates a range of (1..A2). As far as I can tell, I cannot re-use this by caching it in a cell, which is why I had to use it twice.
2. Each item is then converted to numbers with `CODE()` and `BITXOR()`ed against each other.
3. The `CHAR()` converts this to a character, while `DEC2HEX(...,2)` converts it to a 2 width 0-padded hex number.
4. `CONCAT()` puts the array together
5. `RIGHT(...)` tacks on the trailing characters of the longer string.
[Answer]
# Java 10, 109 bytes
```
(a,b)->{int A=a.length,B=b.length;if(A<B){var t=a;a=b;b=t;A^=B^(B=A);}for(;A-->0;)a[A]^=A<B?b[A]:0;return a;}
```
I/O as arrays of characters.
[Try it online.](https://tio.run/##dVPfT9swEH7nr7j5ZY6aRmUb@1HPoAQmbdIAMR72UFrtnLiQLiSd7bRCVf/2YjveqsDIg33n77473@fLAlc4XBS/d3mFWsM5lvXmAKCsjVRzzCVcOBcgv0M1mUJOOwPjbhcRs/D2wC7aoClzuIAa@I5iLKLh8cbmgZRjUsn61tzFGRfBZOWcpp@zaLNCBYYjQy6Y4IalM57NaMbTiG3njaIsHQ6PRyzCSTqdcUs5EdYaj5iSplU1INvumKu/bEVl64drrJqygHvbDb02qqxv7d0x6loxUhtKvsqqamISA/nZqKp4RXwnPdSB68sf38/6GIq8kA4bHb55@66PVc1aqhy1xz@dvAb/9WPc6uD@qct15FkfP7w/@j/D709ZDkiz07MvfWR06IA/@hnwKw@Frq7Is9fzsvm4TjbAOBgiqHf9oI28T5rWJEsLmKqm5Fu9bI0eww0hAxyQGwJYF94Tzvtb/ymVksvWWOb4n0BhypTUbWWAQ53kFBPTnNrzVCl8oFEs@n5g2nRuPJtCLhtra0eWa3/cZQtzN@3C3WS52Sx5D2VlN2z7PJNyOggx1mQvSuCadQU7tWjHiLwWdJ/NdjpY2D8uaU1ZJb4DbdsJpH2cJUYvqWarhWfb7h4B)
**Explanation:**
```
(a,b)->{ // Input as 2 character arrays as parameters as well as return-type
int A=a.length, // `A`: the length of the first array `a`
B=b.length; // `B`: the length of the second array `b`
if(A<B){ // If the length of `a` is smaller than `b`:
var t=a;a=b;b=t; // Swap the arrays `a` and `b`
A^=B^(B=A);} // And also swap the lengths `A` and `B`
// (`a`/`A` is now the largest array, and `b`/`B` the smallest)
for(;A-->0;) // Loop index `A` in the range [`A`, 0):
a[A]^= // Bitwise-XOR the `A`'th value in `a` with, and implicitly cast
// from an integer codepoint to a character afterwards:
A<B? // If index `A` is still within bounds for `b`:
b[A] // XOR it with the `A`'th codepoint of `b`
: // Else:
0; // XOR it with 0 instead
return a;} // Return the modified `a` as result
```
Note that we cannot use a currying lambda `a->b->` here, because we modify the inputs when swapping and they should be (effectively) final for lambdas.
[Answer]
# [Factor](https://factorcode.org/), 48 bytes
```
: f ( s s -- s ) 0 pad-longest [ bitxor ] 2map ;
```
[Try it online!](https://tio.run/##Vc1PT8IwGAbwO5/icRflMDJQQMeBKBAgIRggxoMxoXTvkFjW0b4E/PSzgwqxh/759XnaVEjWpnhbjKfDGFvBX/gmk5GCpd2eMkn2uqvRkY2wyA0x/@RmkzE6lfE0htQJhWut0iJGiju4EsLQTVVEyEUSKp2tyTI@sNrwURt8orEVOTpFMCKldIDgXRuV3ASuX6tc8PA6n/S9iZVMyFlUb9w/eFP6QEYKW/pT9xan4e/YfejYn8pSs0w9tlvN/4nz8pdy8PzS6w@8RHUHO3uFpTw/NJudoPgF "Factor – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 66 bytes
```
f=(a,b)=>b[a.length]?f(b,a):(B=Buffer)(a).map((c,i)=>c^B(b)[i])+''
```
[Try it online!](https://tio.run/##XY9fT8IwFMXf@RSVl7ZSx0BQkAwissQYI38Ww8OYSdu1MFNXsk3BTz9b@oDhJif34f7OuTmf9IeWvMj21U2uU1HXMkCUMByMWUw9JfJttUsmEjFC8QOaBtNvKUWBEcXeF90jxElmWP4xRQzHWYJbENajuAFADJ@FUppAAuBaFyq9ggkBbtptADfHjtwcfWq2MNs3YkYpPHut9TBfvc7OTuedXI9By4GU8VRY0O90b3uX4DJarpcOVPogCk5LCzeHE@igpjFY8H2xCFdPj1Ho4EqUlQ39n3dOPV1PnP3Zt@BwcH/Xv/xu6gxcRb9n1LU1YSNpeFIXIeU7hGJKAEswCMaA67zUSnhKb9FLNH/zyqrI8m0mf5FEFsNmRvUf "JavaScript (Node.js) – Try It Online")
[Answer]
# Scala, 64 bytes
```
(a,b)=>(""/:a.zipAll(b,'\0','\0').map(x=>x._1^x._2))(_+_.toChar)
```
[Try it online!](https://tio.run/##dc1LT8MwDADge39FyKWJqEo7Nh6VOlQ2JA4gNDhw4FHcNB1FWVvSiI1N@@2lyXbKRA625c92WgYCujr74kyheyirjZPzAi36ioCctxFKpITflycly2r@RtHGcX5AoCJChOya3i7ReLwvUNwR8LK@QTA@icBfl00iBMk89zVwTaD@AhqyiscrPw3f@zCglKTHqa/qySdI2jX9JSUqUhB8y4WoPewh/FxLkR9hSh2btS4fHu@mFkLGcq4xCAenQwtFveSSQWsGLq9cZJ41pHirtFttfW5k9i7Oz0b/7Jh8sKcluZ5MbywKQi3f7aF8sP1ns5kWZ7vt/gA "Scala – Try It Online")
Run with
```
val f: ((String,String)=>String) = ...
println(f("01","qsCDE"))
...
```
Uses `zipAll` to zip the input strings with null bytes as padding, then XORs, finally using `foldLeft` shorthand `/:` to turn the whole thing back into a string.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
cÈ^VcY
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Y8heVmNZ&input=J2FiY2RlJwonMDEyMzQn)
```
cÈ^VcY :Implicit input of strings U & V
c :Map the charcodes in U
È :by passing each one at index Y through the following function
^ : Bitwise XOR with
VcY : Charcode at index Y in V
```
[Answer]
# [Lua](https://www.lua.org/), 105 bytes
```
i,a,b=0,...print(a:gsub('.',load'i=i+1return a.char((...):byte()~(b:sub(i,i):byte()or 0))')..b:sub(#a+1))
```
[Try it online!](https://tio.run/##bVJfa9swEH@2P4VGKJKJYqKs3VYPM7alsMFgdC97MIbJtrwKNCuRZMoo7VfP7qSY9mHGYP3@3J3vTmaWJ2N7achIamKsHJrmpLnkXb3lZVkenJ4Ck9VvP3eMlpSjhepar4VTYXYTkWV/Jx1jYC6q7m9QrHhiXYV@zfVCWUe2RUGLskzSSq5FUZzaNs9T@QOUj8UWwkgP53Ge@qDtlLRYJM@k98oFtnoA@EjqmgggN5sDY/TiSItqtO6PTGYQMBEkB5SraVjSB@WDB/ohz@gXZYzllBP60zozvKLvFxK5@@8/vu0jJbt@UEhtxe71ZaSMvVeulx7pprn@QEl82hZFrIH26MSQK0TX796@uaIv9fg9exB//PR5fxOJrUB89Av@1Z@T3N4CfoT5wGB1Lfgq9rMRfEcGCz3HHqXgRO6gySg2uuXLaS3axTRqh4PORpbsMLFI4XXAFaCwAwFmnGd6TH7ylFQS7tSUZ5lyzsIdoHs9jsqpKRCn/GxgwvEHp8MMx4sjvFX6PG8pVeUpL49ZcWtxVRmu9OuLaE7sHAD@N8M5FCJP/wA "Lua – Try It Online")
Taking two strings as arguments, this program calls per-character replace on one of them with essentially XOR function, then appends potentially missing fragment from second string (occurs if it is longer) and prints the result. TIO includes test suite.
[Answer]
# PHP, 36 bytes
```
[,$a,$b]=$argv;echo"$a\r$b\r",$a^$b;
```
Usage:
```
$ php -r '[,$a,$b]=$argv;echo"$a\r$b\r",$a^$b;' -- 'ABCDE' '123';echo
> pppDE
```
Explanation: first output string A, then carriage return `\r`, output string B, then another carriage return, then output the XOR (which truncates to the shorter of the 2 strings). Any characters of the longer string will have already been printed.
# PHP 7.4, 32 bytes
Using new arrow function syntax.
```
fn($a,$b)=>($a|$b^$b)^($a^$a|$b)
```
Explanation:
In PHP binary operators, only the `|` will keep the longest string length and pad with `NUL`s. So we XOR string B with itself, leading to a string with NUL bytes of the same length as B, then OR that with A. This will pad A with NUL bytes and use the length of B, if B is longer than A. We do the same with B, and only *then* XOR.
Edits:
* arrow function variant
* missed the requirement of outputting the longest string
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
C÷꘍C
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=C%C3%B7%EA%98%8DC&inputs=%5B%22test%22%2C%20%22%22%5D&header=&footer=)
Because Vyxal auto-pads lol.
## Explained
```
C÷꘍C
C # convert each character in each string to it's ordinal value
÷꘍ # bitwise xor each item
C # and convert the result back to characters
```
Alternatively, using Keg mode:
### [Vyxal](https://github.com/Vyxal/Vyxal) `K`, 1 byte
```
꘍
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%EA%98%8D&inputs=%22lowercase%22%0A%229%3F%27%20%20%20%20%20%20%22&header=&footer=)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes
```
F⌈EθLι«Fθ«≔ζη≔∧‹ιLκ℅§κιζ»℅⁻|ηζ&ηζ
```
[Try it online!](https://tio.run/##RU5BCoMwEDzrKxYvrpA@oHgotqeCYu/iIWiqSzXWJFax@PZUpbRz2Z1hZneKmqui4421904BJnyidmjX@cSeQSxkZWqkYAW8XWf39PvqRFpTJXFmUAfhn0eyxFhojfSLP4KAQapKkrzByFxlKSZ8MNjOMpi39OI6N0XS4GXtwwsjFCYkB41nMiNpkSqsNyuDr7C92ZUVobtYm2V@041CFVwLn4F3PPkAXp7bw6v5AA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of two strings. Explanation:
```
F⌈EθLι«
```
Loop over the longer length of the strings.
```
Fθ«
```
Loop over the strings.
```
≔ζη
```
Save the result of the previous loop, if any.
```
≔∧‹ιLκ℅§κιζ
```
Get the ordinal at the current index, if that is less than the current string.
```
»℅⁻|ηζ&ηζ
```
Emulate bitwise XOR by subtracting the bitwise AND from the bitwise OR, then convert back to a character.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~80~~ ~~72~~ 69 bytes
```
lambda*a:''.join(map(lambda x,y:chr(ord(x or'\0')^ord(y or'\0')),*a))
```
[Try it online!](https://tio.run/##dZBdb4IwFIbv/RWdXhxgZClMNzXZjBOTLVmiaBZvyFwFjC5IO6gRfj1rBZSJa3J6ctrnPV8s5Rsamtn6yckCslt5RCN9gLtvug2VHWFK/ogSPe27m0ihkackiEbgYFA/ZZSWkaprRFWz1lvI9hz9dyZ7Lr4bDRZtQ47WCrz6QUB10BEsaBR4N1CAKmqJG5zEWDsJJsL7wmNhK2EeXGSQCQ6T2bsFp1JFhoH2jG4rOFm5ni9xbJj37Rpuz@2FXcEDevAjl8RS0uwNCr5Z4h/T6Xg2Gs7HFQn3Yy4LwMXsheT4faZlFx2J97qPD51aP2LYbr4A3BZmyiUAWoaUL5FhGLhn1gsffb1wsb@T/W1CCocvI2t8RckYs6oTYkPSP/EFXeJ5mjP@5RYj2vY1PN9A9gs "Python 2 – Try It Online")
Uneven lengths are annoying...
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~86~~ 81 bytes
```
$k=[char[]]($args[1]);([byte[]]([char[]]($args[0])|%{$_-bxor$k[$i++%$k.Length]}))
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyXbNjo5I7EoOjZWQyWxKL042jBW01ol09bAWiM6qbIkFSSBpsIgVrNGtVolXjepIr9IJTtaJVNbW1UlW88nNS@9JCO2VlPz////ngqJuQppiSX/I/NLFRKLUhVKMjLzAA "PowerShell – Try It Online")
-5 bytes thanks to @mazzy
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~44~~ 43 bytes
```
x(o,r)char*o,*r;{*o|*r&&x(o+1,r+1,*o^=*r);}
```
[Try it online!](https://tio.run/##bZFRS8MwEMff@ynOykaSVWkr@pLNJx98EARftw66LN0CNRlpqx1bP3tMurY4ayBw/H93/7tL2N2OMXMrJMurLYd5UW6Fut8/e78lLeTuWmPl8cCtZGqkAo3ZPtVEBUTTE1FnoqdTq8@iQNtL1HpBNKaNEbKEz1RI5IJU71gArhCIjb@WCYaTB/a02qbK0mX8@JTAAk5hQ6/IZkSco6DeJc4AOXe4WcADBs3LSkuIOmq3YYcjcv4BtI2jBNM/aNOh2KGW1V2Fg72WKQ1I2DFCCgLmrj7nEvWmcD6PZGcIs5nod@3nFQWTNq1tshQJxgN152A/oMyQv1rVkzCu/QD6PDrk8bzg/xZN2Ci/ucw/2Eq/X6l7rJB6jTGvPM@V@X7/eHv5AQ "C (gcc) – Try It Online")
Uses recursion, note that to print strings containing the null byte one will have to manage the strings as arrays. (See the footer of the link for an example)
# [C (gcc)](https://gcc.gnu.org/), ~~50~~ 49 bytes
```
x(o,r)char*o,*r;{*o|*r&&x(o+!!*o,r+!!*r,*o^=*r);}
```
[Try it online!](https://tio.run/##bZFRT4MwEMff@RQ3zJa2Q8Mw@tLNJx98MDHxdcMEusKaYLsUUBbgs2PLYHFiX3r5/@7@d9ey25Sx7kZIlpV7Duu82At1d3hyfktayPRaY8XpyI3UVUh5GrNDpInyiKY1UQ3Ri4XRl7OZ0bS9tEfUx4ZoTNtOyAI@IyGRDSKdMg9sORATf21DDLUD5vRaXCbRNnh4DGEDtd/SKxJPiHUU1DnHCSDrDrMN3GPQvCi1hNVAzU7seELW34O@8SrE9A@KBxRY1LNqqLBw1BKlAQkzhk9BwNrWZ1yi0RSaZiJbQ1guxbjrOK/ImTRpfZOtCDG@UHuO5huKBLm7XTX3g8r1YMyjlzye5fzfojmb5Lfn@S@20h1XGh7Lp07bdS88y1T3/fb@@vwD "C (gcc) – Try It Online")
Slightly safer version (doesn't read past end of strings, requires enough memory to exist past them though - a la `strcpy`).
# [C (gcc)](https://gcc.gnu.org/), ~~61~~ 60 bytes
```
x(b,o,r)char*b,*o,*r;{*o|*r&&x(b+1,o+!!*o,r+!!*r,*b=*r^*o);}
```
[Try it online!](https://tio.run/##dZHBbsIwDIbvfQrDBErSbCpM2yWw0w47TJq0KxSpDSlE6hIUylYEffYubikaY/Ol1v859m9X3q6krG@0kfluqWCyLZba3q2fgp@S02Z1qcliv1FeqkuScssdlevEsZQzy5kTB2aPzA2HHoYjbsNez@sOP46zdMrcglkqqlqbAj4SbQgmiVtJDtgHmM8/ZzGFQwA@Gi3dZcls/PAYwxQOUSUuSPovkVcEZ2kRtHkGBOdCbwr3FJwqds7A6ET94nKzJziZQ2NpFFPxC6UnNEbUsBJlv0r7Dks6klkHRHszkQANE@ySK0O61nA8XsnYFsJQd7foXOutNL6sMTfTMaVnirHxf6zISH8@LwfRuOzz9hS6s4@h8q3689FAXtVXrf9zW9PvVjqdLBJBVdcvKs9t/fX2/vr8DQ "C (gcc) – Try It Online")
As safe as any standard C function taking a buffer, at the cost of a few more bytes.
-1 byte from each thanks to ceilingcat!
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ôM◙L╞@←
```
[Run and debug it](https://staxlang.xyz/#p=934d0a4cc6401b&i=123%0AABCDE)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
ż§oc-¤nc¤vc
```
[Try it online!](https://tio.run/##yygtzv7//@ieQ8vzk3UPLclLPrSkLPn///9KOfnlqUXJicWpSv@VLO3VFRSUAA "Husk – Try It Online")
Unfortunately [Husk](https://github.com/barbuz/Husk) doesn't have a bitwise XOR command (that I could find), so we need to do:
arg1 OR (`v`) arg2 minus arg1 AND (`n`) arg2, costing an extra 5 bytes...
[Answer]
# x86 machine code, 29 bytes
Machine code:
```
00000034: 31 d2 e3 08 8a 11 41 41 84 d2 e1 fe ac 84 c0 75 1.....AA.......u
00000044: 06 e3 09 89 ce 31 c9 30 d0 aa eb e4 c3 .....1.0.....
```
Commented assembly:
```
.intel_syntax noprefix
.globl .strxor
// Doesn't follow standard calling convention.
// Input:
// EDI: Output buffer large enough for longest string
// ESI, ECX: Null terminated strings to XOR
// Output:
// NON-null terminated string stored in EDI.
.strxor:
.Lloop:
// Always clear EDX.
xor edx, edx
// We mark the end of the shorter string
// by setting ECX to null.
jecxz .Lskip_ecx
.Lno_skip_ecx:
// Read a byte from ECX into DL.
mov dl, byte ptr [ecx]
// Increment twice because LOOPZ decrements.
inc ecx
inc ecx
// Was it '\0'?
test dl, dl
// If so, set ECX to NULL by using LOOPZ in place.
// CMOVZ ECX, EAX also works, but needs P6.
// This works with i386 and is the same size.
.Lclear_ecx:
loopz .Lclear_ecx
.Lskip_ecx:
// Load from ESI and autoincrement
lods al, byte ptr [esi]
// Test for '\0'
test al, al
jnz .Lno_swap
.Lswap: // '\0' found
// If ECX is null, we are at the end of both strings.
jecxz .Lend
// Otherwise, we swap ESI and ECX, and then clear ECX.
// Set ESI to ECX.
mov esi, ecx
// And set ECX to NULL.
xor ecx, ecx
// fallthrough
.Lno_swap:
// XOR the two bytes together
xor al, dl
// Store to EDI and autoincrement
stos byte ptr [edi], al
// Loop unconditionally.
jmp .Lloop
.Lend:
ret
```
[Try it online!](https://tio.run/##tVdtb9s2EP6uX3HzVjgB/J6067xiRRZnWAA3bpt0NVpnGUXRNlOZ1EiqtoP99@yOki0r0vptAiyavFfePTyeQmaXj4@cOfgF5jIWnWt49QouJr8FkD8dqZyI7@xWObYBpRMj5nJTkBexDmPoWGc22uyXu10YaWFV08Fcx7Feg3VMRcxEwFkcS7UArtVXoZzUqnModqmS1A0PV/xzMbocwiR1SIQwnc@FgZiZhQChdLpYohVc0GohrENTBg1UVVxftuDifDqEqzSOwQmzkoo5EeUCFpyG6eT9oWBmserO1eSqrWq14KANzqQinztBHplh0BnHWiclVWfxmm0t8Fgwg9zTIhAo4UcRbVr0OpT6KGDFzBdwS9p9BHru/9qlNuhNze7DLVjhHDmH26ddkuuFsXvBNw@Uy7H9IpM7nKGzSt/tZiWf3wsWAUOdTsDc6JVXiRjRMBoXKlf6qx@juJWxJs7AZ9R1W841N2KFIAC3llxAKDhLrYDxZPL2E0Qip9pCr1Q8iwvffHONwsQsSAfNWa/5er/uCB@5X1Fc8mUOVrcoULsgXX0Yjyl2qaXIZT5hVpOYcVGC7PmbyR@fSArhdTYFFlsNa22@WNw7wlUJEVl4@6Ikc7OUNmOCtXRLkCcvXwCeEMBln022wpd8QEudsQdIOROEpSxne2JQ5K@UsbHGjGWpur70NljqtNzF/kAluokPK@fMylLObiiCdNoosJW4kiwr4nqvHrIq4eG0Zgn5iMOQNJEC1JSq6EkePKKsB2kL1gKYwZ87xHuoMWT5qa3DsSjrnKCoWUsrvDpyYB8KnzX6gyxqdxLPp6VcXRMmkB8xUSLtQI4haj1F3xmqfIKlmtPNNxXBOZZHtzRU1IJ92Er5xBLlY@HW2ueJ6tZC0BYrBlgF5tdUnfxORt/CAhYxj4UDHETytpRbjyydQKqwkkeSCjm6vj1IxyrJk09gDXxWio0Y4YIAdbTpCYr7xApOqqDRcWLjOqmynOppowUNtsH3s8ToRSidPXREbDjVDYpKiGD3aOQ6EjAdBZ0V40bD2w8358D3QklqlzTOeDWdDLNyWl0OcblfXfY5tEmVEJX4sUT6sbd52Su80MnOZNDB8KyCnbs3F9c3by4I4/0WvQd7Gb8RgGajWYn0yTzoFxHuMMvlAzRmpKQRDOopg0ZwclBWBCsg3Q@r67TbQXgYe4QektWCipjyKVBMfhWAV1tNDJMy4G0aHhCsrBqkZJyEVQH25OjwPAaZJlYQ7rFJoOd0XhwPvlyUeE9LByzS1LfgoYhThJAvU7gznTUfuNU9L95QO5tVBy3pDutwIcuAoYYog36lh1ob6cSRdREab2Uq0T60oX/8v8L20O9a4LIoqt9lDTopoiKWK0ndib/sepv5vIUVwF@l2MftCc2Zaj5VRcy7wxHk7eYddpPGBdlQ5C4/NND4XWDP2aKa8VGbOPqu8R8sxLGevB@PahhYyCNBDL3@4OS0hgG7WmE4s57pp9fNjFzDSOWIeGpIpPq5l3/544vn35D1Y608Uc9@PR9d1JB7faL@beups794bv3du0Y9nvr1eOrVowO/Gx4XnEN7dTKANt99UbR19k8H1NBA@2w3LXgxkU7iRGkEeyzDnINEaefB95CwLX59YB/gso8GusNWW1/uE2Fi5MjxhI2DVgm2Bo6Fscjbq3OsodsY@wfLWSKsv/IPRXRqPNCy7m6p42gHSYb92xo/WKgR6/qL5R9vENoJ1gbbPfr85@ehNze8naGG2@Ou9dP5UWM22zzrDaYYYW2iox/6x8fdhfjZdomvO1PdRTN4/Bc "Bash – Try It Online")
The code reads two null terminated strings from `esi` and `ecx`, and stores the NON null terminated string in `edi`.
The logic is probably easier to see in the equivalent C code.
```
void strxor(char *dst, const char *src1, const char *src2)
{
for (;;) {
char x = '\0';
if (src2 != NULL) {
x = *src2++;
if (x == '\0') { // eos
src2 = NULL;
}
}
char y = *src1++;
if (y == '\0') {
if (src2 == NULL) { // both eos
return;
} else { // src2 is longer
src1 = src2;
src2 = NULL;
}
}
*dst++ = x ^ y;
}
}
```
I don't null terminate because null bytes naturally show up in the output and it saves a byte.
I may also add a version with explicit lengths which accepts null bytes, but the solution would be significantly less elegant.
[Answer]
# [Perl 5](https://www.perl.org/), 14 bytes
```
sub f{pop^pop}
```
[Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhrbogvyAOiGv/FydWKqRpKCUmJaekKukoGRgaGZsoaVpzQcVLUotLgMIIEfWc/PLUouTE4lR1HQUlS3t1BTAAKvj/L7@gJDM/r/i/rq@pnoGhAQA "Perl 5 – Try It Online")
[Answer]
# Scala 3, ~~30~~ 29 bytes
```
a=>b=>a zipAll(b,0,0)map(_^_)
```
[Try it online](https://scastie.scala-lang.org/0szOKel0TIqe2F3tK8I03g)
# Scala 2, ~~41~~ ~~39~~ 38 bytes
Used infix notation to turn `.map` into just `map`
```
a=>b=>a zipAll(b,0,0)map(a=>a._1^a._2)
```
Inputs and output are lists of integers
[Try it online](https://scastie.scala-lang.org/5uxNZJaHQS6GjkNQ7RPctg)
] |
[Question]
[
Inspired by this [blog post](http://matt.might.net/articles/i-love-you-in-racket/).
Write a program that outputs 99 distinct programs (in the same language) that output the string `I love you`.
How the programs are separated from one another in the output will be defined by you. However, Each byte of output can only belong to at most 1 of the 99 programs.
**Constraints for Output Programs**
1. If **any string** of characters is removed, then the program must not output `I love you`.
e.g. `console.log('I love you');;;` is invalid because `;;;` can be removed
2. If **any two strings** of characters are both removed, then the program must not output `I love you`. This is to prevent inconsequential application of pairs of characters, that pass rule 1 because removing any *single* string will break the program.
e.g. `print((('I love you')))` is invalid, because `((` and `))` can be removed
**There will be two categories of scoring to participate in.**
1. Standard code golf—smallest source code wins
2. Combined code golf—smallest source code + output wins
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
```
/* Configuration */
var QUESTION_ID = 198052; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
if (/<a/.test(lang)) lang = jQuery(lang).text();
languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
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]
# [JavaScript (JavaScript shell)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Introduction_to_the_JavaScript_shell), 65 bytes
total: (64 + 3366 = 3450) bytes
```
for(i=99;i++<198;)print(`\\u0${i}="I love you";print(\\u{${i}})`)
```
```
\u0100="I love you";print(\u{100})
\u0101="I love you";print(\u{101})
\u0102="I love you";print(\u{102})
\u0103="I love you";print(\u{103})
\u0104="I love you";print(\u{104})
\u0105="I love you";print(\u{105})
```
It is trivial.
JavaScript allow escape sequence in variable name. [`console.lo\u0067('Hello world')`](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/OT@vOD8nVS8nP6bUwMDMXEPdIzUnJ1@hPL8oJ0Vd8/9/AA) is prefect valid. I don't think this feature is useful anyway. But...
No TIO link, since the TIO version is out-of-date. You may download JavaScript Shell from <https://archive.mozilla.org/pub/firefox/releases/72.0.1/jsshell/> .
---
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 76 bytes
total: (76 + 2475 = 2551) bytes
```
for(i=99;i++<198;print(v+'="I love you";print('+v+')'))v=eval('"\\u0'+i+'"')
```
[Try it online!](https://tio.run/##NY8xT8QwDIX3@xVWFycKVMdGVcLCdCuI7YYLrdsLtHGUpEUV4reXUMpiyX5P33t@N7OJTbA@3UZvWwojuw9aVh@4D2YEDS8pWNeXwXxe1o6DsLqqaqvUw111X/usJTEr1MUJBp4JFp6K/YwqCxKlnDXNZhBYnM/TEZVVWKBcL2Umj0LWh03dE/M6cms7S20O349lID@YhgRuZLzBDrNxIJc9x0OXZwT9CF@woaKs4VdTGiZHsTGeBLmGW3p9Pj3x6NlR7helLLOtT9cavv9K/EdneMMu8kDlwL3YYIDwtiSKwFPyU8of/AA "JavaScript (SpiderMonkey) – Try It Online")
Output:
```
Ā="I love you";print(Ā)
ā="I love you";print(ā)
Ă="I love you";print(Ă)
ă="I love you";print(ă)
Ą="I love you";print(Ą)
ą="I love you";print(ą)
```
This one is shorter when counting total length. And it is much more trivial.
---
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 85 bytes
total: (86 + 36927 = 37013) bytes
```
for(n=99,p="(L='I love you')=>",q="print(L)";n--;p+='x=>')p='('+p,q+=')()',print(p+q)
```
[Try it online!](https://tio.run/##TY@9bsMwDIT3PAXhRWL8k2YMDGXpFCBTi25dXJt2lcqiYslBjSLP7qpxinYhyOPxw/FUXSpfD9qF3Dvd0NCz/aBpdgN3Q9WDAtmOtg6aLUiEL9is55YHadVulzmVyKMSBzB8IZh4FKj2SXZWiRu0DfKISWnzvHSpEp9qL9ApIUXqsnMUUKLIFp9LzzivN3DFIvBziFonsfDO6CDFqxWxN7omuc0g32JxYm3vevT2EsvVnbOEjjNdKvNv7LnRraYmvnMXi4GcqSJT/EUQmWiXJp4YstH9sGpj9aD28fUb1GMJP7tUwWjJ15UjSbbmhl6eDo/cO7YUeR6xiLYuvJdwXeL8hojwmq1nQ4XhTt5gIOBtCuSBx@DGIHD@Bg "JavaScript (SpiderMonkey) – Try It Online")
Output:
```
((L='I love you')=>print(L))()
(((L='I love you')=>x=>print(L))())()
((((L='I love you')=>x=>x=>print(L))())())()
(((((L='I love you')=>x=>x=>x=>print(L))())())())()
((((((L='I love you')=>x=>x=>x=>x=>print(L))())())())())()
```
This is my original solution.
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 718 bytes, score: 34180 (33462+718)
```
[S S S T N
_Push_1][S S S N
_Push_n=0][T T S _Store_1:n][N
S S S N
_Create_Label_LOOP][S S S T N
_Push_1][S N
S _Dupe_1][T T T _Retrieve_1:n][T S S S _Add][S N
S _Dupe_n+1][S S S T T S S T S S N
_Push_100][T S S T _Subtract][N
T S T T N
_If_0_Jump_to_Label_EXIT_WITH_PRINT][S S S T N
_Push_1][S N
T _Swap][T T S _Store_1:n+1][S S S T N
_Push_1_newline][S N
S _Dupe_1_newline][S S S T S T T T N
_Push_23_space][S S S T N
_Push_1_newline][S T S S T N
_Copy_0-based_1st_23_space][S N
S _Dupe_23_space][S S S T N
_Push_1_newline][S S S N
_Push_0_tab][S T S S T S N
_Copy_0-based_2nd_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][S S S N
_Push_0_tab][S T S S T N
_Copy_0-based_1st_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][S S S N
_Push_0_tab][N
S T N
_Call_Subroutine_PUSH_INTEGER][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S N
S _Dupe_0_tab][N
S T N
_Call_Subroutine_PUSH_INTEGER][S S S T N
_Push_1_newline][S S S T S T T T N
_Push_23_space][S N
S _Dupe_23_space][S S S T N
_Push_1_newline][S N
S _Dupe_1_newline][S T S S T S N
_Copy_0-based_2nd_23_space][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S T S S T S N
_Copy_0-based_2nd_23_space][S N
S _Dupe_23_space][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S T S S T S N
_Copy_0-based_2nd_23_space][S N
S _Dupe_23_space][S S S T N
_Push_1_newline][S T S S T N
_Copy_0-based_1st_23_space][S N
S _Dupe_23_space][S S S N
_Push_0_tab][S T S S T N
_Copy_0-based_1st_23_space][S N
S _Dupe_23_space][S S S N
_Push_0_tab][S T S S T N
_Copy_0-based_1st_23_space][S S S T N
_Push_1_newline][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S N
S _Dupe_0_tab][S T S S T S S N
_Copy_0-based_4th_23_space][S N
S _Dupe_23_space][S S S T N
_Push_1_newline][S T S S T N
_Copy_0-based_1st_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][S S S T N
_Push_1_newline][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S N
S _Dupe_0_tab][S T S S T S S N
_Copy_0-based_4th_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][S S S T N
_Push_1_newline][S T S S T N
_Copy_0-based_1st_23_space][S S S N
_Push_0_tab][S T S S T N
_Copy_0-based_1st_23_space][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S T S S T S N
_Copy_0-based_2nd_23_space][S N
S _Dupe_23_space][S S S T N
_Push_1_newline][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S N
S _Dupe_0_tab][S N
S _Dupe_0_tab][S T S S T S T N
_Copy_0-based_5th_23_space][S N
S _Dupe_23_space][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S T S S T S N
_Copy_0-based_2nd_23_space][S N
S _Dupe_23_space][S S S T N
_Push_1_newline][S T S S T N
_Copy_0-based_1st_23_space][S S S N
_Push_0_tab][S T S S T N
_Copy_0-based_1st_23_space][S S S N
_Push_0_tab][S T S S T N
_Copy_0-based_1st_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][S S S T N
_Push_1_newline][S T S S T N
_Copy_0-based_1st_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][S S S T N
_Push_1_newline][S T S S T N
_Copy_0-based_1st_23_space][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S T S S T S N
_Copy_0-based_2nd_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S N
S _Dupe_0_tab][S T S S T T N
_Copy_0-based_3rd_23_space][S N
S _Dupe_23_space][S S S N
_Push_0_tab][N
S T N
_Call_Subroutine_PUSH_INTEGER][S S S T N
_Push_1_newline][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S N
S _Dupe_0_tab][S N
S _Dupe_0_tab][S S S T S T T T N
_Push_23_space][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S T S S T S N
_Copy_0-based_2nd_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][N
S T N
_Call_Subroutine_PUSH_INTEGER][N
S N
S N
_Jump_to_Label_LOOP][N
S S T T N
_Create_Label_EXIT_WITH_PRINT][S N
N
_Discard_n][N
S S T N
_Create_Label_PRINT_LOOP][S S S T S S T N
_Push_9][T S S S _Add][T N
S S _Print_as_character][N
S N
T N
_Jump_to_Label_PRINT_LOOP][N
S S N
_Create_Subroutine_PUSH_INTEGER][S S S T N
_Push_1_newline][S S S N
_Push_0][S S S T N
_Push_1][T T T _Retrieve_1:n][T T S _Store_0:m][N
S S S S N
_Create_Label_TAB_LOOP][S S S N
_Push_0_tab][S N
S _Dupe_0][S N
S _Dupe_0][T T T _Retrieve_0:m][S S S T N
_Push_1][T S S T _Subtract][S N
S _Dupe_m-1][N
T S S T N
_If_0_Jump_to_Label_DONE_WITH_TAB_LOOP][T T S _Store_0:m-1][N
S N
S S N
_Jump_to_Label_TAB_LOOP][N
S S S T N
_Create_Label_DONE_WITH_TAB_LOOP][S S S T S T T T N
_Push_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][N
T N
_Return_from_Subroutine_PUSH_INTEGER]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
[Try it online](https://tio.run/##hZJLDsMgDETXnlP4alUVqdlVSqQen@IfBuGqWQA242cI83md93G9H8@jNWYm9AFErLMlwNQ/9gTLkkQkm9TDkLlIK2SWMt@jKW1khWgKPBJTjBDChiANLrKXs1yd5CKxnqUMeOnMftu9fL7NJl3VM7w6UhbFHv29wMrcTvUjsRHzAbL7aI7if6xvu9GkREbAQbqwd1O/WCR2AYbFYkHqNITXnGnG0mLtY6RoWRhD6a19AQ) (with raw spaces, tabs and new-lines only).
The output Whitespace programs are output without delimiter. Each program will be as follows, where the `x` is variable in the range `[3,102]`.
```
[S S S (x_amount_of_T )N
_Push_n][S S S T T S T T T T N
_Push_constant_111][S S S (x_amount_of_T )N
_Push_n][T S S T ][T T S _store][S S S T T S N
_Push_6_u][S S S N
_Push_0_o][S S S T S T S N
_Push_10_y][S S T T S S T T T T N
_Push_-79_space][S S T T S T S N
_Push_-10_e][S S S T T T N
_Push_7_v][S S S N
_Push_0_o][S S T T T N
_Push_-3_l][S T S S T S S N
_Copy_0-based_4th_-79_space][S S T T S S T T S N
_Push_-38_I][N
S S N
_Create_Label_LOOP][S S S (x_amount_of_T )N
_Push_n][T T T _Retrieve][S S S (x_amount_of_T )N
_Push_n][T S S S _Add][T S S S _Add][T N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP]
```
In the 1st program, `x` will be 3, so the four `Push n` parts will push the integer `7` (binary `111`; three 1-bits); in the 15th program, `x` will be 18, so the four `Push n` parts will push the integer `262143` (binary `111111111111111111`; eighteen 1-bits); etc. up to `5070602400912917605986812821503` (binary with 102 1-bits).
[Try it online for the 15th program](https://tio.run/##dY5BCoAwDATP2VfM10QKehMUfH7ETaGH0kBg2UyyeY/zafe17S0TiLlkmyFnImxT4A8ZxDpqGCVr3E@pq59gsEiwjHLO4gnc3pYyPw) (with raw spaces, tabs and new-lines only).
I've used [this Whitespace tip of mine](https://codegolf.stackexchange.com/a/158232/52210) to print the output `I love you`. The optimal constant `111` is generated by [this Java program](https://tio.run/##fZJLa@MwEMfv/RTDnCSUmhS2h9oRpYU9GJoe6uwDSllkV03UdWSvNA6EJZ/dK9d2HtvSi4TmP/PTvF7VRp2/Pv9u26JU3sNcGfv3DKBu8tIU4ElRuDaVeYZ1kFhGztjl4xMo3rkB9AZw2jclgQT1OH1K3hRjCfxalaX2nZBa0kvtovnNz1/fb@6@fZ1AKq@SY8jo/TDCEHv9pXKswxmZJmZ2cTlNjBBDAocUJOKEJrUco/q4fEsa8rhPMFpqug0Gz/g@HIBkgC@qHysTlFoV@tZY5bY9l@Xnhid7XycZRfpPo0rPan6N2X2GMXHhDi61pPGxG27zwlxUarukFeMw21d6lMS74o@IR208YA5yGuzm9Mv@zLae9DqqGorqUAuVlmEfLlGMUIFJaCyKVCDEgOKzXqR8@PZ/MjtN/81rdxaOYYOGGX3G7gZsh4ZslAtTwSxDwayU02vE2M7CtcAYM@Sna1HE43JRdYLsVD5XtIpU7pnl/KP5k5DF7MtVGGVgL4bd6fvnNDXOBg@8x76iXdu2KZTVRsO2av4B). In addition, I use one copy for the space to save bytes.
I've also used this same tip with a constant `9` in the generator program to output the Whitespace sub-programs. After that I've used loads of duplicates, as well as copies for the spaces where possible.
### Explanation in pseudo-code:
**Generator program:**
```
Store n=0 at heap-address 1
Start LOOP:
Retrieve n from heap-address 1
n = n + 1
If(n == 100):
Call function EXIT_WITH_PRINT
Store the updated n+1 at heap-address 1
Push the codepoints of "NNSNSSNTSSSTSSST" minus 9 for the output program
Call subroutine PUSH_INTEGER
Push the codepoints of "TTT" minus 9 for the output program
Call subroutine PUSH_INTEGER
Push the codepoints of "NSSNNSTTSSTTSSNSSTSSTSNTTTSSNSSSNTTTSSSNSTSTTSSNTTTTSSTTSSNSTSTSSSNSSSNSTTSSSSTTTSST" minus 9 for the output program
Call subroutine PUSH_INTEGER
Push the codepoints of "NTTTTSTTSSS" minus 9 for the output program
Call subroutine PUSH_INTEGER
Go to the next iteration of LOOP
Function EXIT_WITH_PRINT:
Discard n that was still on the top of the stack
Start PRINT_LOOP:
Add 9 to the value at the top of the stack
Pop and print it as character
(this will fail with an error since there is nothing more to pop, when we're done with
the final character to stop the program)
Go to the next iteration of PRINT_LOOP
Subroutine PUSH_INTEGER:
Push the codepoint of "N" minus 9 for the output program
Retrieve n from heap-address 1
Integer m = n
Store m at heap-address 0
Start TAB_LOOP:
Push the codepoint of "T" minus 9 for the output program
Retrieve m from heap-address 0
m = m - 1
If(m == 0):
Call function DONE_WITH_TAB_LOOP
Store m-1 at heap-address 0
Go to next iteration of TAB_LOOP
Function DONE_WITH_TAB_LOOP:
Push the codepoints of "SSS" minus 9 for the output program
Return to the caller of the PUSH_INTEGER subroutine, and continue from there
```
**Sub-program:**
Variable as explained before is integer `n` (which has `x` amount of binary 1-bits).
```
Integer t = 111 - n
Store t at heap-address n
Push the codepoints of "uoy evol I" minus 111
Start LOOP:
Retrieve t from heap-address n
t = t + n
Add t (which is 111 again) to the value at the top of the stack
Pop and print it as character
(this will fail with an error since there is nothing more to pop, when we're done with
the final character to stop the program)
Go to the next iteration of LOOP
```
Since we use the variable `n` four times (`t = 111-n`; `store t at heap-address n`; `retrieve t from heap-address n`; `t = t+n`) with other pieces of relevant code in between the pushes, we need to remove four string-sequences in order to still have a valid `I love you` output, complying to the rule stating you can't remove one or two string-sequences.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 81 bytes
### Output: 4275 bytes
```
for(n=100;--n;)console.log(`console.log('I lo'+Buffer([${n}^${118^n}])+'e you')`)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/Lb9II8/W0MDAWlc3z1ozOT@vOD8nVS8nP10jAZmj7qmQk6@u7VSalpZapBGtUp1XG6dSbWhoEZdXG6uprZ6qUJlfqq6ZoPn/PwA "JavaScript (Node.js) – Try It Online")
[Answer]
## Batch, 131 + 3564 bytes
```
@for %%a in (a b c d e f g h i j k)do @for %%b in (. / \ "," ";" [ ] + "=")do @echo @for %%%%%%a in (love)do @echo%%~bI %%%%%%a you
```
This produces 99 variants of the same code:
```
@for %%k in (love)do @echo=I %%k you
```
The `for` variable (here `k`) loops over the 11 values `a` to `k`, while the other character that changes is the separator after `echo`, which can usually (as here) be any of 11 characters, but five of them need quoting to use in a `for` command, so I've omitted space and `(`. The programs are all irreducible because they need to get the word `love` to appear in the output.
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~87~~ \$\cdots\$ ~~160~~ 120 bytes
### Output: 3822 bytes (Total: 3942 bytes)
```
i;main(j){for(;i<99;printf("main(){printf(\"%%c Love You\",%d^%d);}\n",j,j^73))j=3+i++*4,j=strchr("$,2MOPW]_",i)?6*j:j;}
```
[Try it online!](https://tio.run/##S9ZNzknMS///P9M6NzEzTyNLszotv0jDOtPG0tK6oCgzryRNQwkso1kN5cYoqaomK/jkl6UqROaXxijpqKbEqaZoWtfG5CnpZOlkxZkba2pm2RprZ2pra5noZNkWlxQlZxRpKKnoGPn6B4THxivpZGram2llWWVZ1/7/DwA "C (clang) – Try It Online")
Fixed pristine-errors kindly pointed out by [Expired Data](https://codegolf.stackexchange.com/users/85908/expired-data).
Fixed pristine-errors kindly pointed out by [Kaddath](https://codegolf.stackexchange.com/users/90841/kaddath).
Saved 50 bytes thanks to [gastropner](https://codegolf.stackexchange.com/users/75886/gastropner)!!!
Prints 99 unique lines like:
```
main(){printf("%c Love You",3^74);}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 86 bytes
86 code + 10289 output = 10375 total
```
x=0
while x<99:print(f"print(chr(len('{(bin(x)[2:8]).zfill(73)}'))+' love you')");x+=1
```
sample segment of output:
`print(chr(len('0000000000000000000000000000000000000000000000000000000000000000000110000'))+' Love you')`
[Answer]
# [PHP](https://php.net/), 96 bytes
# Output: 2516 bytes (total 2612)
```
<?php for(;($i+=2)<773;)if($i<99||--$i%100>67&&$i>299)echo"I<?=chr(".(33+$i++)."-$i)?>love you";
```
[Try it online!](https://tio.run/##bdbNbhpBEATge55ihBwL7LS9szPdPRMwnHPKC/ji4MWsRFjETxJLfndSSHGUSHXwwV1rVD3fsuvdenc@zxa79S6shv14Or7qbx/aycw9TSf9Cr/Oan17E7nqP8ammZtfX1/187bWSbdcD6Mvs8XDcr0fj@7GKd3ij28ndyNcPFnMN8OPLrwOp9H0fLk0jB63j9uvp@PudAy7/fCyf/p@CN2vbnk6ds@fR9Nwf7PcDId@@xKOTy9h2y27w@Fp/xqOQzish59/ru2HbRhWYd8dTpvjp/ANn7Yd8NN1z91z6Lfvnx3646HbrG7uw2L@4cN7z6SS/un2d1zEyDhHqWycJbZs7hKVzLWRWNg8SRvZ3KTNbF6ldTK3VlLD5liWbWtFElvXoyS2r2fJbF93yWzf0khm@5YkyvYtJsr2LVWU7VtbMbZvVTG2b4Uu2zc2UazSIIu3NHBxtnKMjXihQZISaWBSMg2qFLZ2bFupDQ1UaqJBkUo3T7iz6a2NI0nGkyTJI01wn3miiSNRmlQkTr9zaOC0AY4y0bPMEQ0KbRDRoNAGOOZEzzm3aFBogxYNKm0AgkQNcosGlTZo0aDSBunyTaz0URIlG0@SZOqj8MnUR@GTnT@yKhLWTeGTqY/CJ1MfhU@mPgqfTH0UPpn6KHwy9VH4ZOqj8MnUR@GTqY/CJ1MfhU@mPgYfNZ7g6Ud9DD5KfQw@Sn2suTwb6csAPkp9DD5KfQw@Sn0MPkp9DD5a@OsIDaiPwUepj8FHqY/BR6mPwUepj8FHqY9fHvnGkyRGfRw@Rn0cPkZ9HD5GfRw@Rn0cPkZ9HD5GfRw@Rn0cPkZ9HD5GfRw@Rn0cPkZ9HD5GfRw@Rn08XV68lf7rEMWNJ0n8P5/zbw "PHP – Try It Online")
Example program:
```
I<?=chr(35-3)?>love you
```
Still quite new at code golf, hope I get this right. Wanted to encode the space as 32 is the lowest number and wanted to do something else than port an existing answer. Got me into troubles with the 2 strings removing part, but I think this time it passes
(Edit: one line was missing, programs count was 98)
(Edit2: separator is now `:`, as `-` was in the code, and total count was wrong)
**Edit3: This time I think it's OK** (got much more complicated than planned):
* I had to remove all the intervals of the form `x99-x67` that can be reduced by removing the `x`'s
* Had also to remove all the interval of the form `3xx-2xx` that can be reduced by removing the `xx-` and `xx`
* Tried to keep only `--$i%100>67&&$i>299` as a condition but unfortunately it goes to `1003-971` and a bit beyond that all can be reduced to the form `103-71`
* new code is manupulating `$i` with -- and ++ to avoid to add prenthesis and do `($i-1)%100>67` in test and `"-".($i-1).")` in display
* no separator anymore, as per a question's comment
* removed the space after `echo` (thanks to @Ismael Miguel answer)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 23 bytes (combined score 1688 bytes)
```
тGN"•«À¢ÒÙΓʒγ•"тN-…O₃BJ
```
[Try it online!](https://tio.run/##ATMAzP9vc2FiaWX//9GCR04i4oCiwqvDgMKiw5LDmc6TypLOs@KAoiLRgk4t4oCmT@KCg0JK//8 "05AB1E – Try It Online") or [try one of the output programs](https://tio.run/##yy9OTMpM/f/f0vJRw6JDqw83HFp0eNLhmecmn5p0bjNQyND/UVOz0///AA "05AB1E – Try It Online").
```
тG # for N from 1 to 99:
N # N
"•«À¢ÒÙΓʒγ•" # string "•«À¢ÒÙΓʒγ•"
тN- # 100 - N
…O₃B # "O₃B"
J # join the entire stack
```
Each subprogram looks like:
```
1 # 1 (N)
•«À¢ÒÙΓʒγ• # compressed integer 11971423964735158206
99 # 99 (100 - N)
O # sum the entire stack
₃B # convert to base 95
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~34~~ ~~31~~ ~~30~~ ~~28~~ 25 bytes
*Combined Score*: very very big `(25 + no. permutations of "I love you"*20)`
*-3 bytes thanks to @KevinCruijssen*
```
…I„΀v'"y'""œ{•B‹<•è"J
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcMyz0cN8w73PWpac3jd0cmHlpWpK1WqKykdnVz9qGGR06OGnTZA@vAKJa///wE "05AB1E – Try It Online")
---
# Optimised for Combined Score
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~32~~ ~~30~~ 27 bytes
*Combined Score:* `27 + 1980 = 2007`
```
…I„΀îœт£¦v'"y'""œ{•B‹<•è"J
```
[Try it online!](https://tio.run/##ATkAxv9vc2FiaWX//@KApknigJ7DjuKCrMOuxZPRgsKjwqZ2JyJ5JyIixZN74oCiQuKAuTzigKLDqCJK//8 "05AB1E – Try It Online")
This may take a while to run...
---
### Explanation
```
…I„΀î # Compressed string "I love you"
œ # Get the permutations of this string
¦ # Remove the first one ("I love you")
v # loop over these and do...
'"y'" # the string with the value in (e.g. "I love yuo"
"œ{•B‹<•è" # string literal with œ{•B‹<•è value
J # join these and print e.g. "I love yuo"œ{•B‹<•è
```
### Explanation of the output programs:
```
"I love yuo" # a string which is a permutation of "I love you"
œ{ # get the sorted permutations of this string
•B‹<•è # get the value at index 750832 which is "I love you"
```
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), 33 bytes
Programs separated by `:`
Output is 1385 bytes
```
в&(c|&:&I+,&:&,`- love you:`,⑹
```
[Try it online!](https://tio.run/##y05N////wiY1jeQaNSs1T20dIKmToKuQk1@WqlCZX2qVoPNo4s7//wE "Keg – Try It Online")
Programs:
```
ѻв- love you:Ѽг- love you:ѽд- love you:Ѿе- love you:ѿж- love you:Ҁз- love you:ҁи- love you:҂й- love you:҃к- love you:҄л- love you:҅м- love you:҆н- love you:҇о- love you:҈п- love you:҉р- love you:Ҋс- love you:ҋт- love you:Ҍу- love you:ҍф- love you:Ҏх- love you:ҏц- love you:Ґч- love you:ґш- love you:Ғщ- love you:ғъ- love you:Ҕы- love you:ҕь- love you:Җэ- love you:җю- love you:Ҙя- love you:ҙѐ- love you:Қё- love you:қђ- love you:Ҝѓ- love you:ҝє- love you:Ҟѕ- love you:ҟі- love you:Ҡї- love you:ҡј- love you:Ңљ- love you:ңњ- love you:Ҥћ- love you:ҥќ- love you:Ҧѝ- love you:ҧў- love you:Ҩџ- love you:ҩѠ- love you:Ҫѡ- love you:ҫѢ- love you:Ҭѣ- love you:ҭѤ- love you:Үѥ- love you:үѦ- love you:Ұѧ- love you:ұѨ- love you:Ҳѩ- love you:ҳѪ- love you:Ҵѫ- love you:ҵѬ- love you:Ҷѭ- love you:ҷѮ- love you:Ҹѯ- love you:ҹѰ- love you:Һѱ- love you:һѲ- love you:Ҽѳ- love you:ҽѴ- love you:Ҿѵ- love you:ҿѶ- love you:Ӏѷ- love you:ӁѸ- love you:ӂѹ- love you:ӃѺ- love you:ӄѻ- love you:ӅѼ- love you:ӆѽ- love you:ӇѾ- love you:ӈѿ- love you:ӉҀ- love you:ӊҁ- love you:Ӌ҂- love you:ӌ҃- love you:Ӎ҄- love you:ӎ҅- love you:ӏ҆- love you:Ӑ҇- love you:ӑ҈- love you:Ӓ҉- love you:ӓҊ- love you:Ӕҋ- love you:ӕҌ- love you:Ӗҍ- love you:ӗҎ- love you:Әҏ- love you:әҐ- love you:Ӛґ- love you:ӛҒ- love you:Ӝғ- love you:ӝҔ- love you:
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~200~~ ~~181~~ ~~172~~ 165 + ~~3992~~ ~~3828~~ 3540 bytes
```
m="I love you";q=?",?';%w[print $><< puts].map{|e|q.product(q){|c,d|8.times{|i|puts e+c+"#{m.chars.rotate(~i)*""}#{c}.chars.rotate(#{i+1})*#{d*2}"}};puts e+"'#{m}'"}
```
This combines different ways of printing (`print`, `$stdout <<`, `puts`), different ways of quoting the string (`''`, `""`), and different rotations of the string `"I love you"` to make `(((8 * 4) + 1) * 3) =` 99 irreducible programs.
## Golfy Tricks
* Uses `%w[]` as a whitespace-separated string array
* Use `*""` and `*''` instead of `.join`
* Use different combinations of quotation marks (`""`, `''`) instead of different combination of splitting a string (`chars`, `split(//)`), and just use the shorter (`chars`)
* Use `puts` instead of `$stdout<<` as the third way of printing (I didn't think it would be allowed because it also appends a newline where the others don't, but maybe this is fine?)
[Try it online!](https://tio.run/##VczdCsIgGIDhW5HPYr8IdRRsa8ddQ3SwnJCQ0zkthn7duhV00vH78lh/XVNSHZzIXT8EWbWHZu56qPus2T7PxsrJkc2xbYnxbrkwNZgQRZyZsXr03OVzESKvx3hgTiqxhCjj9ySi4hXQoBi/DXZhVrvBifwlixIAaeD4H2iQ1Q6Lkoax3CMgNj8Fsg@CGWBKbw "Ruby – Try It Online") for the initial generator code.
[Try it online!](https://tio.run/##jdbNSgNBEEXhfZ4iDEKpi4C/cRHc@xhRAgrBCZOZQJ5@pCrp6qah67j/Fs2hudQwfZ7n@TD8/I7d9LHc96fd8tx3q6/v7XBcDf24HXe3D3f3Xbe4oN5VhR4LdHZVoacCLV1V6LlAO1cVeinQyVWFXsuHu6rQukB7VxV6K1DUSeQfnRxFnRxFnRxFnRxFnfLDg06Ook4JSe4kzf8kuZM0/5PkTtL8T5I7SfM/Se4kzf8kuZM0/5PkTtL8T5I7SfM/hZ08ZtTJUdTJUdTJUdTJUdQpPzzo5Cjq5MgzTbK4ed9saLDMwF6ZgbkyA2tlBsbKDGzV5c3xVJmBpcI@ItwnGZgp7JMMjBT28TfHE4V9roYGygzskxmYJzOwTmZgnMzANl3eHE@TGVgm7JMawi5hn2RglbBPMrBJ2CcZWCQz5SAdpvGIF5QaOqDU0P2khs4nNXQ9qaHjyd4Mt5MaOp2ojwj3SYbuJuqTDF1N1MffDDcT9bkavJjU0MGkhu4lNXQuqaFrSQ0dS/ZmuJXU0KlEfVJDOpSoTzJ0JlGfZOhIoj7J0Imkphykef4D "Ruby – Try It Online") for the generated code.
This now has some `"I love you"`s appended with a newline, and some not. I hope this is okay.
EDIT: Saved ~~lots of~~ *even more* bytes thanks to Value Ink!
---
# [Ruby](https://www.ruby-lang.org/), 53 + 2375 bytes
This is the cheap way of using a unicode range as variable names.
```
(?ÿ..?š).each{|v|puts"#{v}='I love you';puts #{v}"}
```
[Try it online!](https://tio.run/##KypNqvz/X8P@8H49PfujCzX1UhOTM6prymoKSkuKlZSry2pt1T0VcvLLUhUq80vVrUHCCiBhpdr//wE "Ruby – Try It Online") for the generator code.
[Try it online!](https://tio.run/##bdRJThoAAIXh/X8Kdx6i6QF6jSbdNbFpSxN3oKKiyCSIEwrO8zxPLHzvXPQCb/sd4Ptd@D45Gn0Ov45/G/s58e/H2OREYfzLr8LfP2OfQ1QMriIqJS@hqeRTaDr5NJpJPoPKyctoNvksmks@h@aTz6NK8gpaSL6AFpMvomryKlpKvoRqyWuonryOGskbqJm8iVrJW2g5@TJqJ2@jTvIOWkm@grrJu2g1@SpaS76G1pOvo43kG2gz@SbqJe@hreRbaDv5Nuon76NB8gHaSb6DdpPvor3ke2g/@T46SH6ADpMfoqPkR@g4@TE6SX6CTpOforPkZ@g8@Tm6SH6BLpNfoqvkV@g6@TW6SX6DbpPforvkd@g@@T16SP6AHpM/oqfkT@g5@TN6Sf6CXpO/orfkb@g9@Tv6SP6B0v8a4vS/izj97xJO/3sKp/89jdP/nsHpf5dx@t@zOP3vOZz@9zxO/7uC0/9ewOl/L@L0v6s4/e8lnP53Daf/Xcfpfzdw@t9NnP53C6f/vYzT/27j9L87OP3vFZz@dxen/72K0/9ew@l/r@P0vzdw@t@bOP3vHk7/ewun/72N0//u4/S/B6PRfw "Ruby – Try It Online") for the generated code.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 75 bytes, 2178 + 75 = 2253
```
unique("'I love you'.tclc.say",{S:x(8)[\w]~^=' 'x 2.rand}...*)[^99+1]>>.say
```
[Try it online!](https://tio.run/##K0gtyjH7/780L7OwNFVDSd1TISe/LFWhMr9UXa8kOSdZrzixUkmnOtiqQsNCMzqmPLYuzlZdQb1CwUivKDEvpVZPT09LMzrO0lLbMNbODqT6/38A "Perl 6 – Try It Online")
Outputs variants of:
```
'I love you'.tclc.say
```
string part has a randomised unique case. `tclc` is short for "title case, lowercase", which capitalises the first letter and lowercases the rest.
```
"..." # Starting from the base program
,{ }...* # Generate an infinite series of
S:x(8)[\w]~^= # String xor the first 8 letters
' 'x 2.rand # Randomly space or nothing,
# Essentially flipping the case
unique( ... ) # From the unique elements
[^99+1] # Take 99, skipping the first
>>.say # And print each
```
The reason I don't include the first unique element is so that a variant with correct casing isn't produced, since that would be reducible.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 63 + 3167 = 3230
```
1..99|%{$z=$_%10;"''+(echo you $($_-$z)/10) love $z I)[4,2,0]"}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31BPz9KyRrVapcpWJV7V0MBaSV1dWyM1OSNfoTK/VEFFQyVeV6VKU9/QQFMhJ78sVUGlSsFTM9pEx0jHIFap9v9/AA "PowerShell – Try It Online")
Sample output:
```
''+(echo you 0 love 1 I)[4,2,0]
''+(echo you 0 love 2 I)[4,2,0]
...
''+(echo you 1 love 0 I)[4,2,0]
''+(echo you 1 love 1 I)[4,2,0]
''+(echo you 1 love 2 I)[4,2,0]
...
''+(echo you 9 love 8 I)[4,2,0]
''+(echo you 9 love 9 I)[4,2,0]
```
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 2575 = 101 + 2474
Inspired by Jo King's [answer for Perl](https://codegolf.stackexchange.com/a/198209/80745).
Minimal total output for Powershell (84+2153) was written by [Andrei Odegov](https://codegolf.stackexchange.com/a/198185/80745)
So make sure to upvote them both as well!
```
1..99|%{$n=$_
'"I "+("'+-join(0..6|%{[char](($n-shr$_)%2*32+'LOVEYOU'[$_])
' '*!($_-3)})+'"|% *wer)'}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31BPz9KyRrVaJc9WJZ5LXclTQUlbQ0ldWzcrPzNPw0BPzwwoGZ2ckVgUq6GhkqdbnFGkEq@paqRlbKSt7uMf5hrpH6oerRIfq8mlrqCupaihEq9rrFmrqa2uVKOqoAW0SFO99v9/AA "PowerShell – Try It Online")
Sample output:
```
"I "+("lOVE YOU"|% *wer)
"I "+("LoVE YOU"|% *wer)
"I "+("loVE YOU"|% *wer)
"I "+("LOvE YOU"|% *wer)
...
"I "+("loVE You"|% *wer)
```
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 2672 = 99 + 2573, bonus track
```
1..99|%{$p,$d="0$_"[-2,-1]
$e,$l,$c,$r='I love you'-split"^(.{$p})(.)"
"'$l$d$r'-replace$d,`"$c`""}
```
[Try it online!](https://tio.run/##DctNCoMwEAbQvaeQ4StRmITanQsP0DOUWksy0MJAQuwPYj177Nu/FL@S54eoltI51/e/w4rECAMdcaOLPbHtrhWEoQzPyIM51xo/Ui/xbeyc9PmisXH/tbWNa6kiA0VANjZL0rsXBJ4IfiLaStkB "PowerShell – Try It Online")
It generates 10 distinct programs for each char of the input string. The length of string `I love you` is 10 chars. This is enough for 99 iterations
Sample output:
```
'1 love you'-replace1,"I"
'2 love you'-replace2,"I"
'3 love you'-replace3,"I"
...
'8 love you'-replace8,"I"
'9 love you'-replace9,"I"
'I0love you'-replace0," "
'I1love you'-replace1," "
...
'I love yo8'-replace8,"u"
'I love yo9'-replace9,"u"
```
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 94 + 2890, bonus track 2
```
1..99|%{$n=$_;$i=0
'"=I='+-join(' love you'|% t*y|%{$_+'='[1-($n-shr$i++)%2]})+'"-replace"="'}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31BPz9KyRrVaJc9WJd5aJdPWgEtdydbTVl1bNys/M09DXSEnvyxVoTK/VL1GVaFEqxKkNl5b3VY92lBXQyVPtzijSCVTW1tT1Si2VlNbXUm3KLUgJzE5VclWSb32/38A "PowerShell – Try It Online")
Sample output:
```
"=I= =love you"-replace"="
"=I= l=ove you"-replace"="
"=I= =l=ove you"-replace"="
"=I= lo=ve you"-replace"="
"=I= =lo=ve you"-replace"="
...
```
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 96 + 3094
Specially for those who love to turn `99` into `9`. ٩(^‿^)۶
```
2..100|%{"-join('"+-join(('I love you '*$_)[($_+10)..$_])+"'*$(2+($_-$_%10)/10))[$($_+10)..$_]"}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/30hPz9DAoEa1Wkk3Kz8zT0NdSRvC0FD3VMjJL0tVqMwvVVDXUonXjNZQidc2NNDU01OJj9XUVgIKahhpAwV1VeJVgeL6QKwZrYKsSqn2/38A "PowerShell – Try It Online")
Sample output:
```
-join(' I uoy evol'*2)[12..2]
-join('l I uoy evo'*2)[13..3]
-join('ol I uoy ev'*2)[14..4]
-join('vol I uoy e'*2)[15..5]
-join('evol I uoy '*2)[16..6]
-join(' evol I uoy'*2)[17..7]
-join('y evol I uo'*2)[18..8]
-join('oy evol I u'*2)[19..9]
-join('uoy evol I '*3)[20..10]
-join(' uoy evol I'*3)[21..11]
-join('I uoy evol '*3)[22..12]
-join(' I uoy evol'*3)[23..13]
...
-join(' uoy evol I'*10)[98..88]
-join('I uoy evol '*10)[99..89]
-join(' I uoy evol'*11)[100..90]
-join('l I uoy evo'*11)[101..91]
-join('ol I uoy ev'*11)[102..92]
-join('vol I uoy e'*11)[103..93]
-join('evol I uoy '*11)[104..94]
-join(' evol I uoy'*11)[105..95]
-join('y evol I uo'*11)[106..96]
-join('oy evol I u'*11)[107..97]
-join('uoy evol I '*11)[108..98]
-join(' uoy evol I'*11)[109..99]
-join('I uoy evol '*12)[110..100]
```
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 123 + 3141
...and in a normal order. <https://coub.com/view/27d6eh>
```
$s='I love you';(2..122|%{"-join('"+-join(("$s "*$_)[-($_+10)..-$_])+"'*$(2+($_-$_%10)/10))[$($_-1)..$($_+9)]"})-notmatch$s
```
[Try it online!](https://tio.run/##JYpRCsIwEESvEpYtyXZJNPkT6QE8QylBJFAlNmJaRdSzxxQ/Bt68mVt6hnseQ4ylYO7kQcT0COKVFrlXzhjr3Kd5g76k86Qk8B8UYBbQoqdeK/Rst2SMRj8Qg2xROa629qYOmxrqcRW2vlbgHQ3wJT2l@XqcTyPmUn4 "PowerShell – Try It Online")
Sample output:
```
-join('u I love yo'*2)[2..12]
-join('ou I love y'*2)[3..13]
-join('you I love '*2)[4..14]
-join(' you I love'*2)[5..15]
-join('e you I lov'*2)[6..16]
-join('ve you I lo'*2)[7..17]
-join('ove you I l'*2)[8..18]
-join('love you I '*3)[9..19]
-join(' love you I'*3)[10..20]
-join('u I love yo'*3)[13..23]
-join('ou I love y'*3)[14..24]
-join('you I love '*3)[15..25]
...
```
[Answer]
R, 84 Bytes
```
for(x in 1:99){cat("assign(intToUtf8(",x,"),'I love you');get(intToUtf8(",x,"))\n")}
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 70 bytes
```
for(char i='ÿ';i++<355;Write($"var {i}=\"I love you\";Write({i});"));
```
[Try it online!](https://tio.run/##Sy7WTS7O/P8/Lb9IIzkjsUgh01b98H5160xtbRtjU1Pr8KLMklQNFaUyoFR1Zq1tjJKnQk5@WapCZX5pjBJUGiihaa2kqWn9/z8A "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~85 + 2647 = 2732~~ ~~83 + 2251 = 2334~~ 79 + 1818 = 1897
```
0..226|?{[char]::isletterordigit($_)}|%{"`$$([char]$_)"}|%{"($_='I love you')"}
```
-398 thanks to mazzy
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/30BPz8jIrMa@Ojo5I7Eo1soqszgntaQktSi/KCUzPbNEQyVes7ZGtVopQUVFA6IGKKIEFgLK2ap7KuTkl6UqVOaXqgOF//8HAA)
Sample output:
```
($0='I love you')
...
($â='I love you')
```
[Try it online!](https://tio.run/##Zci1UgIAAADQ3a9g4A7c7BgcbLG7NgNFRUEQECe7u86u0d3FUT8MZ@@98SUTuWgqHYvG44VCOFhSF4oE4olsNJBPZELFReFgKVPGlDMVTCVTxVQzNUwtU880MI1ME9PMtDCtTBsTYdqZDqaT6WK6mR6ml@lj@pkBZpAZYoaZEWaUGWPGmQlmkplippkoM8PMMjFmjplnFpg4s8gsMQkmySwzKSbNrDAZJsvkmFUmz6wxP5/Wl/VN/a5bG9amtWVtWzvWrrVn7VsH1qF1ZB1bJ9apdWadWxfWpXVlXVs31q11Z91bD9aj9WQ9Wy/Wq/VmvVsf/6tQ@AM)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~123 + 4247~~ ~~94~~ 90 + 2124 bytes
Heredoc abuse. Takes 49 different alphanumerics (A-Z, \_, a-v) and constructs 2 programs that print the text using the appropriate heredoc. That's only 98 programs, though, so it adds one more print at the end. Each program is 3 lines long, except the last one.
This beats IMP1's Ruby solution in the combined code golf score, but falls behind in standard scoring.
```
l="I love you"
(?A..?v).grep(/\w/){|i|puts"$><<<<"+i,l,i,"puts <<"+i,l,i}
puts"puts'#{l}'"
```
[Try it online!](https://tio.run/##KypNqvz/P8dWyVMhJ78sVaEyv1SJS8PeUU/PvkxTL70otUBDP6ZcX7O6JrOmoLSkWEnFzgYIlLQzdXJ0MnWUQGIKcH4tF1gNiFBXrs6pVVf6/x8A "Ruby – Try It Online")
[Generated code](https://tio.run/##bcpJagIBAETRfZ9CJMcIAed5nt2I89TaatuCp@8EiiJFJX/5@I9k9U7Tj6/Pn3JBLRNGr23mHSVBLrglzzjzR7HmFfNcTbEWFAtcTbEWFYtcTbGWFEtcTbGWFctcTbFWFCtcTbFWFatcTbHWFGtcTbHWFetcTbE2FBtcTbE2FZtcTbG2FFtcTbG2FdtcTbF2FDtcTbF2FbtcTbH2FHtcTbH2FftcTbEOFAdcTbEOFYdcTbGOFEdcTbGOFcdcTbFOFCdcTbFOFadcTbHOFGdcTbHOFedcTbEuFBdcTbEuFZdcTbGuFFdcTbGuFddcTbFuFDdcTbFuFbdcTbHuFHdcTbHuFfdcTbEeFA9cTbEeFY9cTbGeFE9cTbGeFc9cTbGGiiFXU6wXxQtXU6xXxStXU6yRYsTVFOtN8cbVFOtd8c7VFOtD8cHVFGusGHM1xfpUfHI1xZooJlxNsb4UX1z/0eyvZIM0/QY "Ruby – Try It Online")
### Old solution, 123 + 4247 bytes
Beats out IMP1's (non-Unicode) Ruby solution in the standard code golf department, but falls behind in combined code golf scoring. Unlike their use of multiple output solutions and rotation, I chose to shuffle the string after setting a seed with `srand`.
```
99.times{|i|srand i;puts"srand #{i};puts'#{[*0..9].shuffle.zip('I love you'.chars).sort.map(&:last)*''}'.chars.shuffle*''"}
```
[Try it online!](https://tio.run/##KypNqvz/39JSryQzN7W4uiazprgoMS9FIdO6oLSkWAnCUa7OrAXz1ZWro7UM9PQsY/WKM0rT0nJS9aoyCzTUPRVy8stSFSrzS9X1kjMSi4o19Yrzi0r0chMLNNSschKLSzS11NVroZIwvUAhpdr//wE "Ruby – Try It Online")
[Generated code](https://tio.run/##fVcxjhsxDOzzCnYGUhxs73q9Rl6gZ1wSHVIQYXAOBej1znAtrpuQ/UCiOMPh6FO/98fj/vn@@ycdv/3Rv/eDtNJZK5Ec3n78ev@8v91/6ccH16@Hw5cn8vRENipVlLtQiDyPM6lS4d40PnN6IjuL4FjSFiLnJ5J6KyxVkzovA1lZhaT1EiIXr5Ok18ZFQ@T1ieQmHVej1BC5jjPt2Whn4RB5G29vuF@FkzNPR38SNWHpSaGnk78Jja9SKIE6TdKpFWVKCpgcqqURV@oxdBCF40oTa1cMHUxVLgI5tQw6qOJOhFdJS541uDKNNJbSk1MHWVxBVqeSSPrkbAFUoasW83o@@qAAKDYBMXSwRQUKbJUlftZ5sAVJNYG0elKATxWxtgIVxrNynh1qb6pQYQy97M9i3QiLoYuf2jDTIskQnAdbOA7SQqkJdN2JbWhXWutgq3HdBrbEtU6DrUJmK416YlanvVmMMRCJB2YabFViq1UlrnVythpsgE3cMXSwVcxaOtSdPMtnCyKgfGCmxd0FOO0oOIa6D9q0qICvGDrYgqd3EhvxGHpzzyoVXcimYHYnFKwhtJVjCubBlhoBG7sx9LWwpNvMxM@a3QnNMmu6BefZVwHaSjY2MXSwBU0rDA7UxlBnCwbbbbzjvs7Xl2VgwWqNjWgebIF@24alJgXcnILK5loaS/sy2FK0FbyWbGnvs2UwKCvWwGWfLWxOTX3gMtjCmQDDNJNTZz8VfoV4Q3EHLp4whJGabBvEUGeLKlwbESvpgLPFFaSaE8XQdQ8uWkyESa3uhHY5pZ61HN1fuzkGJx1YfG9hVk0tPYEOtjCtIAyKiTuwTG5EGEILD3FfF4@D6JWaGyUFOFtwDCRCSDGGDraw41Et1BVP7DLYwtu3nJFIe1l9cVpqtn0cQ50tTEHHlk8i2fW4R2ekbDO5GOqzVbfh0kQuV2cLDwINWXS/Tp7exLJbSfR69b3VralQVhK03QlpS6X4ksRQny21LWuJJIZe978LbMuWXAxd96xtckE6j6EvJ7RiNTGi1VMGFIBdTIkG1tMrEdmWS1bcenZ7k@2z0WIK1ukV9BhBj5JaZ7cM5KaOlRg3ax1s4UyUi7SXnOqfLdgF/hpprZ7gsYhp@2rG0PX11cSO68kyWj1llC3sU9LX29H/MJaKsb8TqDuh2ARYhI@hnuBtFTN2ctyB284WPrumgqQATxlQFf46Wcy57bOFX2Q1eAx1JwT7ah/UBHrdf5xqv/OadGB1f8UyNAb@d@rj8Q8 "Ruby – Try It Online")
[Answer]
# [W](https://github.com/A-ee/w) `n` `d`, 34 bytes
Different programs are separated as different list items. The `n` flag joins the input with newlines.
```
•u≡`â!=Ç¡l╪G⌠±×èe↔/.╫ù{¶c×█)←╢k0ôF
```
# Uncompressed
```
99''a146+C"C'"a73+C"C-C@ love you@+"++++M
```
# Explanation
```
99 M % Map in the range from 1 to 99
'' % A single quote '
a146+ % Add the current item by 146
C % Convert the current item to a character
"C'" % Add a string C'
a73+C % Add the current item by 73 (creating a difference of 73)
"C-C@ love you@+"++++ % Prepend the string and join the whole stack
```
# Program explanation
```
'ⁿC'JC- # Create the number 73
C" love you"+ # Convert to character and append "love you"
```
[Answer]
# [Zsh](https://www.zsh.org/), 74 bytes
**Output: 2178** (after removing newline delimiters) for a category 2 score of **2252 bytes**
```
for p (echo print '<<<');for v ({1..7} {a..z})<<<"$v='I love you';$p \$$v"
```
[Try it online!](https://tio.run/##Fck9CoAgAAbQq3yEpC5CLQ2ae3doiTAKIsXM6O/sVm995zomlgbr4cBMP1o4Py0BVClFufwjgl2FENWDqxPifPhXGYk1bTDbaHDYjUri0BISs8RxIxgDzfaeQ@dlegE "Zsh – Try It Online")
Uses method from [this Ruby answer](https://codegolf.stackexchange.com/a/198076/86147), setting a unique variable before printing. In zsh, variables must be alphanumeric, so we limit to 33 names and then print out programs using `echo`, `print`, and `<<<` to get our 99.
There is optimization to be done for category 2, [this tweak scores 77 + 2145 = **2222 bytes**](https://tio.run/##Fck9CoAgAAbQq3yEpC5CLQ2Ze3doiTAKIsXM6O/sZtMb3rVNkcXROFgwPUymA6ybV5@kUkrK6z8D2F0IUb24eyGul6fKSGhoi8UEjdPstCa2IyRkkeOB1xqKHQOHysv4AQ "Zsh – Try It Online"), and more can probably be found.
] |
[Question]
[
[Bertrand's Postulate](https://en.wikipedia.org/wiki/Bertrand%27s_postulate) states that for every integer **n ≥ 1** there is at least one prime **p** such that **n < p ≤ 2n**. In order to verify this theorem for **n < 4000** we do not have to check 4000 cases: The *Landau trick* says it is sufficient to check that
```
2, 3, 5, 7, 13, 23, 43, 83, 163, 317, 631, 1259, 2503, 5003
```
are all prime. Because each of these numbers is less than twice its predecessor each interval **{y : n < y ≤ 2n}** contains at least one of those prime numbers.
This sequence of numbers are the [Bertrand Primes (OEIS A006992)](http://oeis.org/A006992) and they are defined as follows:
```
a(1) = 2
a(n) = largest prime below 2a(n-1)
```
### Challenge
Implement this sequence. You may write
* a function or program that given some **n** returns **a(n)** (0 or 1 indexed),
* a function or program that given some **n** returns the first **n** (or **n-1** or **n+1**) entries of this sequence,
* an infinite list or stream or generator or similar equivalent in your langauge.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 32 bytes
```
k=2
do k=primes(k+k)(end)until 0
```
Keeps printing the values indefinitely (each value is preceded by `k =`).
[Try it online!](https://tio.run/##y08uSSxL/f8/29aIKyVfIdu2oCgzN7VYI1s7W1MjNS9FszSvJDNHweD/fwsA)
---
# [Octave](https://www.gnu.org/software/octave/), 42 bytes
```
k=2
for i=2:input('')k=primes(k+k)(end)end
```
Takes **n** as input and outputs the **n** first values (each value is preceded by `k =`).
[Try it online!](https://tio.run/##y08uSSxL/f8/29aIKy2/SCHT1sgqM6@gtERDXV0z27agKDM3tVgjWztbUyM1L0UTiP//twAA)
---
# [Octave](https://www.gnu.org/software/octave/), 51 bytes
```
k=2;for i=2:input('')k=primes(k+k)(end);end
disp(k)
```
Similar to [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/155673/61405). Takes **n** as input and outputs **a(n)** (1-indexed).
[Try it online!](https://tio.run/##y08uSSxL/f8/29bIOi2/SCHT1sgqM6@gtERDXV0z27agKDM3tVgjWztbUyM1L0XTGkhwpWQWF2hka/7/bwEA)
---
# [Octave](https://www.gnu.org/software/octave/), 60 bytes
```
k=2;for i=2:input('')k*=2;while~isprime(--k)
end
end
disp(k)
```
Takes **n** as input and outputs **a(n)** (1-indexed).
[Try it online!](https://tio.run/##y08uSSxL/f8/29bIOi2/SCHT1sgqM6@gtERDXV0zWwsoWp6RmZNal1lcUJSZm6qhq5utyZWalwLGKUBRjWzN//8tAA)
[Answer]
# [J](http://jsoftware.com/), 11 bytes
```
_4&(p:+:)2:
```
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/@NN1DQKrLStNI2s/mtyKekpqKeBJNUVdBRqrRTSirm4UpMz8hXSFAwN/gMA "J – Try It Online")
0-indexed.
```
_4&(p:+:)2: Input: integer n
2: Constant 2
_4&( ) Repeat n times
+: Double
_4 p: Find the largest prime less than the double
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 27 bytes
Saved one byte thanks to Martin Ender.
0-indexed.
```
Nest[-NextPrime[-2#]&,2,#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6hg@98vtbgkWtcvtaIkoCgzNzVa10g5Vk3HSAdI/nfJjwYK5pVE5@koKCno2iko6SgkOuTF6ihUA0UMdBSMDGpj/wMA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ ~~7~~ 6 bytes
```
$F·.ØØ
```
[Try it online!](https://tio.run/##MzBNTDJM/f9fxe3Qdr3DMw7P@P/fBAA "05AB1E – Try It Online")
---
1-indexed answer (unless 0 is supposed to output 1), explanation:
```
$ # Push 1 and input (n)...
F # n-times do...
· # Double the current prime (first iteration is 1*2=2).
.ØØ # Find prime slightly less than double the current prime.
```
---
It's 1-indexed because all iterations have a 'dummy' iteration with `n=1`.
[Answer]
# [Haskell](https://www.haskell.org/), 50 bytes
```
f p|sum(gcd p<$>[1..p-1])<p=p:f(2*p)|1>0=f$p-1
f 2
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hoKa4NFcjPTlFocBGxS7aUE@vQNcwVtOmwLbAKk3DSKtAs8bQzsA2TQUozJVjm6Zg9D83MTNPwVahoCgzr0RBRaEkMTtVwdBEIee/oQEA "Haskell – Try It Online")
Outputs an infinite list.
---
# [Haskell](https://www.haskell.org/), 40 bytes?
```
f p|mod(2^p-2)p<1=p:f(2*p)|1>0=f$p-1
f 2
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hoCY3P0XDKK5A10izwMbQtsAqTcNIq0CzxtDOwDZNpUDXkCvHNk3B6H9uYmaegq1CQVFmXomCikJJYnaqgqGJQs5/QwMA "Haskell – Try It Online")
This works if Bertrand's primes don't contain any [Fermat pseudoprimes for 2](http://oeis.org/A001567).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
2ḤÆp$¡
```
[Try it online!](https://tio.run/##y0rNyan8/9/o4Y4lh9sKVA4t/P//v6ExAA "Jelly – Try It Online")
0-indexed.
## Explanation
```
2ḤÆp$¡ Main link. Input: n
2 Constant 2
$¡ Repeat n times
Ḥ Double
Æp Find the largest prime less than the double
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
1i:"EZq0)
```
Inputs **n**, outputs **a**(**n**), 1-indexed.
[Try it online!](https://tio.run/##y00syfn/3zDTSsk1qtBAE8g0AAA "MATL – Try It Online")
### Explanation
```
1 % Push 1
i % Push input n
:" % Do the following that many times
E % Multiply by 2
Zq % Primes up to that
0) % Get last entry
% End (implicit). Display (implicit)
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü☼┌τ,æ▒ìn(
```
[Run test cases](https://staxlang.xyz/#c=%C3%BC%E2%98%BC%E2%94%8C%CF%84%2C%C3%A6%E2%96%92%C3%ACn%28&i=1%0A%0A2%0A%0A3%0A%0A13%0A%0A14&a=1&m=1)
This problem has exposed a bug in stax's implementation of `:p`, which is an instruction that gets the greatest prime less than its input. If it worked correctly, there would be a 5 6 byte solution. But alas, it does not, and there is not. As the language's creator, I will fix it, but it seems kind of cheap to fix and use it after the problem was posted.
Anyway, here is the corresponding ascii representation of the program above.
```
ODH{|p}{vgs
```
It's a relatively straight-forward implementation of the problem statement. The only thing possibly interesting about it is the use of the `gs` generator form. Generators are a family of constructions that combine an initial condition, a transform, and a filter, to produce one or more satisfying values. In this case, it's used in place of the broken `:p` instruction.
```
O Push integer 1 underneath the input number.
D Pop the input and repeat the rest of the program that many times.
H Double number.
{|p} Predicate block: is prime?
{vgs Decrement until the predicate is satisfied.
Output is implicitly printed.
```
*Edit:* [here](https://staxlang.xyz/#c=ODH%5E%3Ap&i=1%0A%0A2%0A%0A3%0A%0A13%0A%0A14&a=1&m=1)'s the 6 byte solution, but it requires a bug-fix that was only applied after this challenge was posted.
[Answer]
# [Python 2](https://docs.python.org/2/), 63 bytes
```
r=m=k=P=2
while k:
P*=k;k+=1
if k>m:print r;m=r*2
if P%k:r=k
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8g21zbbNsDWiKs8IzMnVSHbikshQMs22zpb29aQSyEzTSHbLteqoCgzr0ShyDrXtkjLCCwaoJptVWSb/f8/AA "Python 2 – Try It Online")
Prints forever.
Uses the Wilson's Theorem prime generator even though generating primes forward is clunky for this problem. Tracks the current largest prime seen `r` and the doubling boundary `m`.
Two bytes are saved doing `P*=k` rather than `P*=k*k` as usual, as the only effect is to claim that 4 is prime, and the sequence of doubling misses it.
[Answer]
## CJam (15 bytes)
```
2{2*{mp},W=}qi*
```
[Online demo](http://cjam.aditsu.net/#code=2%7B2*%7Bmp%7D%2CW%3D%7Dqi*&input=6). Note that this is 0-indexed.
---
A more efficient approach would be to search backwards, but this requires one character more because it can't use implicit `,` (range):
```
2{2*,W%{mp}=}qi*
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~16~~ ~~14~~ ~~13~~ 12 bytes
Two solutions for the price of one, both 1-indexed.
---
## Nth Term
Finally, a challenge I can write a working solution for using `F.g()`.
```
_ôZ fj Ì}g°U
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=X/RaIGZqIMx9Z7BV&input=OA==)
```
:Implicit input of integer U
_ }g :Starting with the array [0,1] take the last element (Z),
:pass it through the following function
:and push the returned value to the array
ôZ : Range [Z,Z+Z]
fj : Filter primes
Ì : Get the last item
°U :Repeat that process U+1 times and return the last element in the array
```
---
## First N Terms
```
ÆV=ôV fj ̪2
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=xlY99FYgZmogzKoy&input=OA==)
```
:Implicit input of integer U
:Also makes use of variable V, which defaults to 0
Æ :Create range [0,U) and pass each through a function
ôV : Range [V,V+V]
fj : Filter primes
Ì : Get the last item
ª2 : Logical OR with 2, because the above will return undefined on the first iteration
V= : Assign the result of the above to V
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 34 bytes
```
a(n)=if(n<2,2,precprime(2*a(n-1)))
```
[Try it online!](https://tio.run/##K0gsytRNL/j/P1EjT9M2M00jz8ZIx0inoCg1uaAoMzdVw0gLKKNrqKmp@T8tv0gjT8FWwVBHwchARwEon1cCFFBS0LUDEiADgIoA "Pari/GP – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
n=2
while 1:
if all(n%i for i in range(2,n)):print n;n*=2
n-=1
```
[Try it online!](https://tio.run/##DcuxCoAgFAXQva@4S6CRg46GH@OQ@UCuIkL49dbZT5sjVzrTZptrMbjtzVJuWL9BEmIpirsg1Q6BED3yuZU7qbVvXTjAi8ffQBPsWh8 "Python 2 (PyPy) – Try It Online") Prints the sequence indefinitely
[Answer]
# [Haskell](https://www.haskell.org/), 58 bytes
```
a 1=2
a n=last[p|p<-[2..2*a(n-1)],all((>0).mod p)[2..p-1]]
```
[Try it online!](https://tio.run/##FcmxDoMgEADQ3a@4ERohwiwsfoZhuESipud5kRv777Qd3vQObO9K1DtCSHFA4ETYdJWPzG6N3scXGnbBlhGJjMmT9de9gdh/igul9AtPhgR71eVmrawNck4gz8kKHvDnqbj1MH0B "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 68 bytes
Prints the sequence indefinitely (you have to click "Run" the second time to stop the execution).
```
k=2
while 1:
print k;k+=k
while any(k%u<1for u in range(2,k)):k-=1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9vWiKs8IzMnVcHQikuhoCgzr0Qh2zpb2zabSwEinphXqZGtWmpjmJZfpFCqkJmnUJSYl56qYaSTralpla1ra/j/PwA "Python 2 – Try It Online")
### [Python 3](https://docs.python.org/3/), 90 bytes
Returns the nth term.
```
f=lambda n,i=1,p=1:n*[0]and p%i*[i]+f(n-1,i+1,p*i*i)
a=lambda n:n and f(2*a(n-1))[-1]or 1
```
[Try it online!](https://tio.run/##PYtBCsIwEADvfcVSEJJ0A656CsSPhBxWanRBt6H00tfH9OJlLjNT9@296LW1Ej/8fcwMihIJa6SgLp0z6wz1JC5JnopRTyhT106cWBj4fwWFIy3m4vjIrE2e8rICtdKpIAor6@tpCIFuNgxQV9HNKI7@PmKfrG0/ "Python 3 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~97~~ ~~87~~ ~~86~~ ~~80~~ 79 bytes
* Saved ten bytes by inlining a non-primality checking function `P` into the main loop.
* Saved a byte by moving the `printf` call.
* Saved six bytes by returning the `i`-th sequence entry (0-indexed) instead of outputting a never-ending stream.
* Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
f(p,r,i,m,e){for(r=2;p--;)for(e=0,i=r+r;e=m=!e;r=i--)for(;i-++m;e=e&&i%m);p=r;}
```
[Try it online!](https://tio.run/##JYxBCsMwDATf0kCChSUw7VHVB/yL4shBB6dG9Fb6didtjzszbKGtlDFq6Oho2FDhXZ8eXK7ciRi@QyWhiUdnlSYXZRcj@ik2irGdXJfF5gbcxfkz2sP2kP9XWRLn@y1xd9tfNUzzihPWkGMEgDM@AA "C (gcc) – Try It Online")
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/attache), 38 bytes
```
{If[_,Last[Series[Prime,2*$[_-1]]],2]}
```
[Try it online!](https://tio.run/##SywpSUzOSP3vkpqWmZcarZKm87/aMy06XscnsbgkOji1KDO1ODqgKDM3VcdISyU6XtcwNjZWxyi29n8sF1A4r0TB1k4hTDkNRBlYGRr/BwA "Attache – Try It Online")
0-based; returns the `n`th Bertrand prime.
There is currently no builtin to find the previous/next primes, so I use the `Series` builtin to calculate all primes up to `2*$[_-1]`. This last expression uses implicit recursion (bound to `$`) to easily define the recurrence relation. The if condition is used to determine a base condition.
[Answer]
# [Perl 6](http://perl6.org/), 35 bytes
```
2,{(2*$_,*-1...&is-prime).tail}...*
```
[Try it online!](https://tio.run/##K0gtyjH7n1up4FBQlJmbWqxg@99Ip1rDSEslXkdL11BPT08ts1gXLKepV5KYmVMLFNL6b61QnAjXEx1nZBBr/R8A "Perl 6 – Try It Online")
This expression is an infinite list of Bertrand primes.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 39 bytes
```
.K`_
"$+"{`_
__
+`^(?=(..+)\1+$).
*\`_
```
[Try it online!](https://tio.run/##K0otycxLNPz/X887IZ5LSUVbqRpIx8dzaSfEadjbaujpaWvGGGqraOpxcWnFJMT//28JAA "Retina – Try It Online") Explanation:
```
.K`_
```
Start with 1.
```
"$+"{`
```
Repeat the loop using the input as the loop count.
```
_
__
```
Double the value.
```
+`^(?=(..+)\1+$).
```
Find the highest prime less than the value.
```
*\`_
```
Print it out.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 51 + 7 (-rprime) = 58 bytes
```
->n{x=2
n.times{x=(x..2*x).select(&:prime?)[-1]}
x}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vusLWiCtPryQzN7UYyNao0NMz0qrQ1CtOzUlNLtFQsyooAkrZa0brGsbWclXU/i8oLSlWSIs2NI79//9ffkFJZn5e8X/dIrAyAA "Ruby – Try It Online")
A lamba accepting `n` and returning the `nth` Bertrand prime, 0-indexed. There's not much here, but let me ungolf it anyway:
```
->n{
x=2 # With a starting value of 2
n.times{ # Repeat n times:
x=(x..2*x) # Take the range from x to its double
.select(&:prime?)[-1] # Filter to only primes, and take the last
}
x # Return
}
```
# [Ruby](https://www.ruby-lang.org/), 48 + 7 = 55 bytes
```
x=2
loop{puts x
x*=2
loop{(x-=1).prime?&&break}}
```
[Try it online!](https://tio.run/##KypNqvz/v8LWiCsnP7@guqC0pFihgqtCCyagUaFra6ipV1CUmZtqr6aWVJSamF1b@////3/5BSWZ@XnF/3WLwJIA "Ruby – Try It Online")
For fun, here's an infinite-loop solution. It prints as it goes, and requires an interrupt. Depending on exactly when you interrupt, you may or may not see the output. Ungolfed:
```
x=2
loop{
puts x
x*=2
loop{
(x-=1).prime? && break
}
}
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 12 bytes
Takes input from user as N, returns Nth element of the sequence (0-indexed).
```
{¯4⍭2×⍵}⍣⎕⊢2
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97X/1ofUmj3rXGh2e/qh3a@2j3sWP@qY@6lpkBJL9z5nGZcAFJAxBhBGIMAYRJiDCFESYAQA "APL (Dyalog Extended) – Try It Online")
Explanation:
```
{¯4⍭2×⍵}⍣⎕⊢2 ⍝ Full program
⎕ ⍝ Get input from user - call it 'N'
⍣ ⊢2 ⍝ Repeat the left function N times, beginning with 2
2×⍵ ⍝ Double the function input
¯4⍭ ⍝ Find the largest prime less than above
```
[Answer]
# [R](https://www.r-project.org/), 87 bytes
# Given `n` outputs `a(n)`
```
j=scan();n=2;while(j-1){for(i in (n+1):(2*n)){n=ifelse(any(i%%2:(i-1)<1),n,i)};j=j-1};n
```
[Try it online!](https://tio.run/##DctNCoAgEAbQq7QRZvpZKK00DxOhNCJfUIsI8ezm/r27teSfYwexgzfuPSUHSovmEq@bZBAMhEmzJTOCucBLDPkJtOMjUcpYkq43zTNm4eqS77s6NL22Hw "R – Try It Online")
I'm still working on "Given n output a(1), a(2)... a(n)". I thought I could just modify this code slightly, but it seems more difficult than that.
] |
[Question]
[
The pyramid begins with the row `1 1`. We'll call this row 1. For each subsequent row, start with the previous row and insert the current row number between every adjacent pair of numbers that sums to the current row number.
$$
1\quad1\\
1\quad\color{red}{2}\quad1\\
1\quad\color{red}{3}\quad2\quad\color{red}{3}\quad1\\
1\quad\color{red}{4}\quad3\quad2\quad3\quad\color{red}{4}\quad1\\
1\quad\color{red}{5}\quad4\quad3\quad\color{red}{5}\quad2\quad\color{red}{5}\quad3\quad4\quad\color{red}{5}\quad1\\
1\quad\color{red}{6}\quad5\quad4\quad3\quad5\quad2\quad5\quad3\quad4\quad5\quad\color{red}{6}\quad1\\
\cdots
$$
This pyramid is an example of a false pattern. It seems to encode the prime numbers in the lengths of its rows, but the pattern breaks down later on. You may wish to learn more about this sequence from a recent [Numberphile video](https://www.youtube.com/watch?v=NsjsLwYRW8o) which is the inspiration for this question.
## Task
Output the sequence. You may do so in any of the following ways:
| Method | Example input | Example output |
| --- | --- | --- |
| The infinite sequence as rows. We must be able to tell the rows apart somehow. | - | 1 11 2 11 3 2 3 11 4 3 2 3 4 1... |
| The infinite sequence as numbers, top to bottom, left to right. | - | 1 1 1 2 1 1 3... |
| The first \$n\$ rows of the pyramid, 1-indexed. We must be able to tell the rows apart somehow. | 3 | 1 11 2 11 3 2 3 1 |
| The first \$n\$ rows of the pyramid, 0-indexed. We must be able to tell the rows apart somehow. | 3 | 1 11 2 11 3 2 3 11 4 3 2 3 4 1 |
| The first \$n\$ numbers in the pyramid, 1-indexed. | 4 | 1 1 1 2 |
| The first \$n\$ numbers in the pyramid, 0-indexed. | 4 | 1 1 1 2 1 |
| The \$n\$th row in the pyramid, 1-indexed. | 2 | 1 2 1 |
| The \$n\$th row in the pyramid, 0-indexed. | 2 | 1 3 2 3 1 |
| The \$n\$th number in the pyramid, 1-indexed. | 7 | 3 |
| The \$n\$th number in the pyramid, 0-indexed. | 7 | 2 |
## Rules
* Please specify which of the above methods your answer uses.
* Output format is highly flexible. It may take the form of your language's collection type, for instance.
* [Sequence rules](https://codegolf.stackexchange.com/tags/sequence/info) apply, so infinite output may be in the form of a lazy list or generator, etc.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with the fewest bytes (in each language) wins.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~52~~ ~~50~~ 48 bytes
*-1 byte thanks to @loopy walt*
Takes as input an integer \$ n \$ and outputs the \$ n^{th} \$ row. Based on the Wikipedia formula for the Farey sequence.
```
f=lambda n,b=1,d=1:1/d%b*[1]or[d]+f(n,d+n,n-b%d)
```
[Try it online!](https://tio.run/##DcpBDkAwEAXQvVPMRqKMMJaSnkS6aDOKhF9pbJy@vPW732dPmEqJ9vRXUE/gYIXVyiyD1qFdxKW8qOtiA9YOjD7UakpMmUAHKHtsayNMMpq5ojsfeOjPpnw "Python 2 – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 26 bytes
Returns the \$n\$th row, 0-indexed.
```
1 1{x?[;;y]/|&y=+':x}/2+!:
```
[Try it online!](https://ngn.codeberg.page/k#eJxLszJUMKyusI+2tq6M1a9Rq7TVVreqqNU30la04uJKU1c0BQCqEQji)
A very literal implementation of the construction described in the challenge.
`2+!:` Integers from 2 to input+1. These are the row numbers to insert.
`1 1{...}/` Using `1 1` as a seed, reduce the range of integers left to right.
`+':x` Sums of adjacent elements in the last row. The first value in the result will be 0+ first value.
`&y=` Indices where this is equal to the new row number.
`|` Reverse the list of indices. We will insert the row numbers one after the other, inserting from left to right would mess up later indices.
`x?[;;y]/` Starting with the last row, insert the new row number at each of the indices.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
!:Żg$$fR
```
A monadic Link that accepts a positive integer, \$n\$, and yields the \$n\$th row as a list of positive integers.
**[Try it online!](https://tio.run/##y0rNyan8/1/R6ujudBWVtKD///@bAQA "Jelly – Try It Online")**
### How?
```
!:Żg$$fR - Link: integer, n e.g. 4
! - factorial (n) 24
$ - last two links as a monad - f(x=n!):
$ - last two links as a monad - f(x):
Ż - zero-range (x) [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
g - (that) greatest common divisor (x) [24, 1, 2, 3, 4, 1, 6, 1, 8, 3, 2, 1,12, 1, 2, 3, 8, 1, 6, 1, 4, 3, 2, 1,24]
: - (x) integer divide (that) [ 1,24,12, 8, 6,24, 4,24, 3, 8,12,24, 2,24,12, 8, 3,24, 4,24, 6, 8,12,24, 1]
R - range (n) [ 1, 2, 3, 4]
f - filter keep [ 1, 4, 3, 2, 3, 4, 1]
= [ 1, 4, 3, 2, 3, 4, 1]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes
```
Denominator@*FareySequence
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@98lNS8/NzMvsSS/yEHLLbEotTI4tbA0NS859b9LfnRAUWZeSXSegq6dQlp0XmysjkJ1no6CIRAZ1Mb@BwA "Wolfram Language (Mathematica) – Try It Online")
Inputs \$n\$ and returns the \$n\$th row, 1-indexed.
---
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes
```
1||1//.x_||y_/;x+y<=#:>x||x+y||y&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@9@wpsZQX1@vIr6mpjJe37pCu9LGVtnKrqKmBsgEiqn9d8mPDijKzCuJzlPQtVNIi86LjdVRqM7TUTDUUbCojf0PAA "Wolfram Language (Mathematica) – Try It Online")
---
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 39 bytes
```
Cases[#!/GCD[Range[0,#!],#!],a_/;a<=#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@985sTi1OFpZUd/d2SU6KDEvPTXaQEdZMRaME@P1rRNtbJVj1f675EcHFGXmlUTnKejaKaRF58XG6ihU5@koGOooWNTG/gcA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Julia 0.7](http://julialang.org/), ~~40~~ 39 bytes
```
!n=(a=(p=lcm(1:n))./gcd.(p,0:p))[a.<=n]
```
[Try it online!](https://tio.run/##BcHBCoAgDADQX5m3DcLyVEj7kuggWrGwNaK@3947vyppbM0pY2I0rvnCEJXI90cuHq0bohEtyc@sa9vvBwQYQpzAHtG3Kjoh2LS0Hw "Julia 0.7 – Try It Online")
Thanks to alephalpha for a saved byte.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 35 bytes
```
n->[d|i<-[0..n!],n>=d=n!/gcd(n!,i)]
```
Inputs \$n\$ and returns the \$n\$th row, 1-indexed.
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN5XzdO2iU2oybXSjDfT08hRjdfLsbFNs8xT105NTNPIUdTI1Y2FK0_KLNPIUbBUMdRQsdBQKijLzSoB8JQVdOyCRppGnqakJUbpgAYQGAA)
[Answer]
# JavaScript (ES10), 61 bytes
Returns the \$n\$-th row (1-indexed), as an array.
This version naively builds all rows up to the requested one.
```
f=(n,a=[r=1,1])=>r++<n?f(n,a.flatMap(v=>n+(n=v)^r?v:[r,v])):a
```
[Try it online!](https://tio.run/##FYxBCoMwEADvvmJvZkkamqu6@oK@QCwEa4oiuxIll9K3p@lphjnM5pM/57ge143lteQcSLHxNEZyxk1IfdS64yH8qw27vx7@UIl61oop4TMOqRmjSRNi43OQqBgIXAsMXeG9iNYInwpgFj5lX@wub1V@aDdZWdVQI7bVN/8A "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 43 bytes
*-1 thanks to [@loopywalt](https://codegolf.stackexchange.com/users/107561/loopy-walt)*
Returns the \$n\$-th row (1-indexed), as a comma-separated string.
This is a port of [dingledooper's answer](https://codegolf.stackexchange.com/a/254437/58563).
```
f=(n,b=n,d=1)=>n*~d+b?d+[,f(n,d+n,n-b%d)]:1
```
[Try it online!](https://tio.run/##DYtBDoIwEADvvGIvJl23GHsVVx5iOFCWEg3ZNWC8EPl66Wkmmcy7//XrsLw@31pNxpwTO/WR1QsH5Ieed6HYCj19KkFIvdbxJNjdQk62OAWG0IDCvfBahAhhqwAG09Xm8TLb5MqK2FT/fAA "JavaScript (Node.js) – Try It Online")
[Answer]
# Excel (ms365), 163 bytes
[](https://i.stack.imgur.com/4wtTV.png)
Formula in `B1`:
```
=IFERROR(REDUCE({1,1},SEQUENCE(A1,,2),LAMBDA(a,b,VSTACK(a,LET(x,TAKE(a,-1),y,DROP(x,,-1),HSTACK(TOROW(VSTACK(y,IF(y+DROP(x,,1)=b,b,NA())),2,1),TAKE(x,,-1)))))),"")
```
---
I designed this answer to be complient with the rule:
>
> *"The first n rows of the pyramid, 0-indexed. We must be able to tell the rows apart somehow."*
>
>
>
---
The idea here is as follows:
* `REDUCE({1,1},SEQUENCE(A1,,2),LAMBDA(a,b,` - This bit is basically telling Excel to take the input `{1,1}` and recurse the following `SEQUENCE(A1,,2)` times where 'the following' consists of two these two variables. The iteration will now start;
* `VSTACK(a,` - The iteration will then `VSTACK()` (vertically build) what is in variable 'a' and stack the following to it;
* `LET(x,TAKE(a,-1),y,DROP(x,,-1),HSTACK(TOROW(VSTACK(y,IF(y+DROP(x,,1)=b,b,NA())),2,1),TAKE(x,,-1)))` - Bulk of the iteration where we use `LET()` to store the last row from 'a' variable, then take all columns but the last and another variable to take all columns but the first. We compare these two arrays to test if the summation of each element would equal 'b' variable. If so, then use array modification to stack these numbers into the correct location.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
-4 bytes porting [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/254446/52210), also outputting the \$n^{th}\$ row based on input \$n\$ (so make sure to upvote him as well!):
```
!ÐÝδ¿÷ILÃ
```
[Try it online](https://tio.run/##ARwA4/9vc2FiaWX//yHDkMOdzrTCv8O3SUzDg//Dr/80) or [verify the first 8 rows](https://tio.run/##ASkA1v9vc2FiaWX/OEVOPyIg4oaSICI/Tv8hw5DDnc60wr/Dt05Mw4P/w68s/w). (The footer `ï` casts strings to integers, so the output looks better. Feel free to remove it to see the outputs as strings.)
**Explanation:**
```
! # Get the factorial of the (implicit) input-integer
Ð # Triplicate it
Ý # Pop one, and push a list in the range [0,input!]
δ # Apply double-vectorized, mapping over the list using another input! as
# argument:
¿ # Get the greatest common divisor of the current value and input!
÷ # Integer-divide the third input! by each of these GCD's
IL # Push a list in the range [1,input]
à # Only keep those values from the list
# (after which the result is output implicitly)
```
**Original 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach that outputs the infinite sequence (although pretty slowly):**
```
X‚[=Dü+.ιNÌLÃ
```
[Try it online.](https://tio.run/##yy9OTMpM/f8/4lHDrGhbl8N7tPXO7fQ73ONzuPn/4fX/AQ) (The footer `ï` casts strings to integers, so the output looks better. Feel free to remove it, and change integer `X` to a literal string `1`, to see the outputs as strings.)
**Explanation:**
```
X # Push a 1
‚ # Pair the top two values together. Since the stack only contains a single
# item and there is no input, it uses it twice to create pair [1,1]
[ # Start an infinite loop:
= # Print the current list with trailing newline (without popping the list)
D # Duplicate the list
ü # For each overlapping pair:
+ # Sum them together
.ι # Interleave the two lists together
N # Push the 0-based loop index
Ì # Increase it by 2
L # Pop and push a list in the range [1,index+2]
à # Only keep those values from the list
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 14 bytes (28 nibbles)
```
`.:1 1|;>>+!!:0$@+@:-+<2@
```
Returns the infinite sequence of rows.
Follows the steps in the challenge description.
```
`.:1 1|;>>+!!:0$@+@:-+<2@
`. # iterate until unique
:1 1 # starting with a list of 1,1
|;>>+!!:0$@+@:-+<2@ # this function:
! : # join each element of
@ # this list
!:0$@+ # to pairwise sums of this list (with initial 1),
+ # flatten this list of lists,
>> # and remove the initial 1;
; # (remember this list)
| # now filter this list
# keeping only elements that are >0 (truthy) after
- # subtracting from
+ # the sum of
<2@ # the first two elements of the remembered list
```
[](https://i.stack.imgur.com/w9cg8.png)
[Answer]
# [Haskell](https://www.haskell.org/), 56 bytes
```
scanl(!)[1,1][2..]
(a:b:t)!i=a:[i|a+b==i]++(b:t)!i
x!i=x
```
[Try it online!](https://tio.run/##JcqxCsMgEIDhPU@hZFFsA3YU7kmsw0VqcvQiEjNk6LP3Guj6f/@K/f1ilgJP6RkrG22jv/kUH9OUBoNhDofVBBgifdDNAJScM/86nJecsiFVBartVA9VhEYGvh5y3o6k@ZsL49Llnlv7AQ "Haskell – Try It Online")
Is an infinite list of rows.
If not valid output [this](https://tio.run/##JcqxDsIgEIDhvU8B6QJBm@BIek@CDFcUvXgSUjp08Nk9m7j@3//E/rozS4Gr0A3muWesbLSN/uRTvExTGgyGJWxWE2CI9EG3AFByzvzrsB@yyxupKlBtpbqpIjQy8PGQ83Ykzd9cGB9dzrm1Hw "Haskell – Try It Online") is an infinite list of numbers for 61 Bytes.
```
id=<<scanl(!)[1,1][2..]
(a:b:t)!i=a:[i|a+b==i]++(b:t)!i
x!i=x
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
¡Dʀvġḭ?ɾ↔
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCoUTKgHbEoeG4rT/JvuKGlCIsIiIsIjQiXQ==)
Port of [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/questions/254429/prime-pyramid/254446#254446)
```
¡D # n!, 3 times
vġ # Gcd with
ʀ # Range(0, n+1)
ḭ # Integer divide n by that
?ɾ↔ # Keep those from range(1, n+1)
```
[Answer]
# [Python](https://www.python.org), 73 bytes
```
a=x,=1,
while[print(1,*a)]:a=sum(([x+y][x+y+~a[0]:]+[x:=y]for y in a),[])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3PRNtK3RsDXW4yjMyc1KjC4oy80o0DHW0EjVjrRJti0tzNTSiK7QrY0GEdl1itEGsVax2dIWVbWVsWn6RQqVCZp5CoqZOdKwmxECouTDzAQ)
Prints forever.
Naive implementation. Feel a bit silly, since everybody else seems to do something clever.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
Nθ⊞υ¹W⁼¹№υ¹⊞υ⁻θ﹪⁺θ§υ±²↨υ⁰Iυ
```
[Try it online!](https://tio.run/##NY29DsIwDIR3niKjIwWJIjExQcXQgaqvYNqIRApJ82Pg7YOjiu2@8915NpjmgK7Wwa9URno9dIIoz7uJsgFSomP9MdZpAbdI6DJ0SvSBfNmuUop/9G49ZYgswkIuwOQ2vJTBL/rbIqN@YtFw5JoSV8y6mQem9jFZHu0x8zJzrae6f7sf "Charcoal – Try It Online") Link is to verbose version of code. Outputs the `n`th row. Explanation: Based on @dingledooper's formula.
```
Nθ
```
Input `n`.
```
⊞υ¹
```
Start with `1` as the first term in the `n`th row.
```
W⁼¹№υ¹
```
Repeat until there are two `1`s in the row.
```
⊞υ⁻θ﹪⁺θ§υ±²↨υ⁰
```
Calculate the next term as `n-(n+b)%d` where `d` is the previous term and `b` is the penultimate term. Note that on the first loop there is no penultimate term so cyclic indexing gives `b` a value of `1` but `d=1` so the result is `n` anyway.
```
Iυ
```
Output all of the terms in the `n`th row.
A naive approach takes 34 bytes:
```
F²⊞υ¹F…·²N≔ΣEυΦ⟦ικ⟧∨ν∧λ⁼ι⁺κ§υ⊖λυIυ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY49CkIxEIR7T7FYbSAWCoJgJf7AK9SHlmIRY9Rg3qpJVryLjYKircfxNsa_7Wa_mWGOd71SXm-UO52uHBeVxvOx2HjAmoCcwwpZQlU0S59fRtpxsHszUrQ0WJOQ0ZbjgIuZ8SiEgFYIdkk45gL7avsO96yLCU6shPVUwtAjSWjRHJ2E7o6VC5hQnnpxnUDMaG4O72DHaG8KQ9Ekr_ifBE5rcm8pYluFiCxE8xJmOvzm3yblyt6Vp-f6V78A "Charcoal – Attempt This Online") Link is to verbose version of code. Outputs the `n`th row. Explanation:
```
F²⊞υ¹
```
Start with `[1, 1]` as the first row.
```
F…·²N
```
Loop over the remaining rows.
```
≔ΣEυΦ⟦ικ⟧∨ν∧λ⁼ι⁺κ§υ⊖λυ
```
Insert the current row number into the list at the appropriate places.
```
Iυ
```
Output the final list.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 71 bytes
```
.+
$*
1
,1$`
^
1,1¶
{`\b(1+)(?=(,1+)\b.*¶\2\1\b)
$1$2$1
}`¶,1+
¶
1+
$.&
```
[Try it online!](https://tio.run/##K0otycxL/K@nzaWidWgbF5eKXgKXoWMCl6qGewJElMuQS8dQJYErjstQxxCopDohJknDUFtTw95WQwdIxyTpAXXGGMUYxiRpcqkYqhipGHLVJhzaBpTkAqoHkip6av//mwEA "Retina 0.8.2 – Try It Online") Outputs the `n`th row but link is to test suite that outputs the first `n` rows. Explanation:
```
.+
$*
```
Convert `n` to unary.
```
1
,1$`
```
Create a list from `1` to `n`.
```
^
1,1¶
```
Start with `[1, 1]` as the first row.
```
{`
}`
```
Loop over each row.
```
\b(1+)(?=(,1+)\b.*¶\2\1\b)
$1$2$1
```
Insert the current index between every pair of adjacent values with that as its sum.
```
¶,1+
¶
```
Remove the current index so that the next loop uses the next index.
```
1+
$.&
```
Convert to decimal.
[Answer]
# [Haskell](https://www.haskell.org/), 63 bytes
```
scanl(#)[1,1][2..]
(a:t@(b:_))#r|r==a+b=a:r:t#r|0<1=a:t#r
l#_=l
```
The first line generates a lazy infinite list of rows. [Try it online!](https://tio.run/##DcexCsIwEADQvV8RiEOCWoxj8MB/cKylXEO1xWsMuRQXv91423sz8msiqisuUYFKW7mVrHZqi7TEiUUrJsXz@yO8Vw4YyWjbuYPru3Pb9o1BX65m9IO1On8zAO5HQJ99kZ4uTixqSA9Atf7Cg/DJ9RhS@gM "Haskell – Try It Online")
### Explanation
The core of the solution is the operator `#`, which takes a list of numbers (the previous row) and an integer (the next row number) and recursively computes the next row.
```
-- If the first argument is a list with at least two elements, unpack it as
-- follows: first element is a, all but first element is t, second element is b
-- Second argument is r
(a:t@(b:_)) # r
-- If r equals a+b, prepend a and r to the result of a recursive call on t
| r == a+b = a:r:(t#r)
-- Else, just prepend a
| otherwise = a:(t#r)
-- If the first argument has fewer than two elements, return it unchanged
l # _ = l
```
Then, to generate the infinite list of rows, we start from `[1,1]` and do a left scan over increasing row numbers:
```
scanl (#) [1,1] [2..]
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 24 bytes
```
JU2VQ
=-.iJm*qhNdd+VtJJ0
```
[Try it online!](https://tio.run/##K6gsyfj/3yvUKCyQy1ZXL9MrV6swwy8lRTusxMvL4P9/SwA "Pyth – Try It Online")
Prints the first \$n\$ rows as lists.
### Explanation
```
JU2 assign J to [0, 1]
VQ for N in range eval(input())
print
= J assign J to
- 0 remove zeros from
.iJ interleave J with
m*qhNdd if not N map to 0
+VtJJ pairwise sums of J
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 82 bytes
```
o;g(n,b,d){o=n*~d+b?asprintf(&o,"%d %s",d,g(n,d+n,n-b%d)),o:"1";}f(n){n=g(n,n,1);}
```
[Try it online!](https://tio.run/##LY3BCgIhGITv@xQiGP75L@Q1V3qRLqviItRvrEGHZXv0TKM5zGG@GcaPi/e1ZrNIQocBtmzp@A7KXebyWBM9ozxk5CIwUTgG7L2gCGl0IgBgPnPNzR4lwUa2U0INZq9tyu5zIgnDNrCmmFcme5qsNixN@tRcKfjBrv8dF@VKHFmUCcAMe/34eJuXUsfXFw "C (gcc) – Try It Online")
C port of dingledooper's answer.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 40 bytes
This is a port of [dingledooper's answer](https://codegolf.stackexchange.com/a/254437/58563) and [Arnauld's answer](https://codegolf.stackexchange.com/a/254431/112099).
```
->n,b,d=1{b+n*~d<0?[d,f[n,d+n,n-b%d]]:1}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsHiNNuYpaUlaboWNzV07fJ0knRSbA2rk7TztOpSbAzso1N00qLzdFK083TydJNUU2JjrQxroeoVNAz19PQMDTT1chMLqrk4CxTSouMNdeINY7WUdBSUuKDqFiyA0AA)
[Answer]
# [Zsh](https://zsh.sourceforge.io/), 92 ~~100~~ bytes
```
p=(1 1)
for j ({2..$1})<<<$p&&p=(`for i ({1..$#p})echo $p[i] ${$((p[i]+p[i+1]==j?j:0)):#0}`)
```
[Try it Online!](https://tio.run/##FclBCoAgEEDRfacYcAgHIZyWonSQEIIozE1Su8KzT7b5fHjPnURK0AxM3X5ekEG/4zAgV/LeY@n7pssvRxNuokqlbU0nYJmPCPii1v@ZFsMxhDxlZ4mcsnUhEeHxAw)
... ~~[100 bytes](https://tio.run/##FcmxCoQwDIDh/Z4iYIYGQRpHr8UHUaGT2A5e8G660mePcfn54ft/D1WJjoHpvX8uKODqOAzIjWoIAeVlmh7JJmzSiZFc@fztgLLkbQWs6NyzvaXnLcYyl8kTTZ1vK7RETVV5vAE)~~
] |
[Question]
[
In this task, you have to write a program, that computes the prime factors of a number. The input is a natural number 1 < n < 2^32. The output is a list of the prime factors of the number in the following format. Exponents must be omitted if they are 1. Only output prime numbers. (Assuming the input is 131784):
>
> 131784 = 2^3 \* 3 \* 17^2 \* 19
>
>
>
Using the same amount of whitespace is not required; whitespace may be inserted wherever appropriate. Your program should complete in less then 10 minutes for any input. The program with the shortest amount of characters wins.
[Answer]
# SageMath, 31 Bytes
```
N=input()
print N,"=",factor(N)
```
Test case:
`83891573479027823458394579234582347590825792034579235923475902312344444`
Outputs:
`83891573479027823458394579234582347590825792034579235923475902312344444 = 2^2 * 3^2 * 89395597 * 98966790508447596609239 * 263396636003096040031295425789508274613`
[Answer]
## Ruby 1.9, ~~74~~ 70 characters
```
#!ruby -plrmathn
$_+=?=+$_.to_i.prime_division.map{|a|a[0,a[1]]*?^}*?*
```
Edits:
* (74 -> 70) Just use the exponent as slice length instead of explicitly checking for `exponent > 1`
[Answer]
## Perl 5.10, 73 ~~88~~
```
perl -pe '$_=`factor $_`;s%( \d+)\K\1+%-1-length($&)/length$1%ge;y, -,*^,;s;\D+;=;'
```
Takes input number from standard input. Will compute factors for multiple inputs if provided.
Counted as a difference to `perl -e`. 5.10 is needed for the `\K` regex metacharacter.
[Answer]
# OCaml, 201 characters
A direct imperative translation of the best Python code:
```
let(%)s d=if!d>1then Printf.printf"%s%d"s!d
let f n=let x,d,e,s=ref n,ref 1,ref 0,ref"="in""%x;while!d<65536do
incr d;e:=0;while!x mod!d=0do x:=!x/ !d;incr e
done;if!e>0then(!s%d;"^"%e;s:="*")done;!s%x
```
For example,
```
# f 4294967292;;
4294967292=2^2*3^2*7*11*31*151*331- : unit = ()
```
(note that I've omitted outputting the final endline.) Just for fun, at 213 characters, a purely functional version, thoroughly obfuscated through liberal use of operators:
```
let(%)s d=if d>1then Printf.printf"%s%d"s d
let f x=let s=ref"="in""%x;let rec(@)x d=if d=65536then!s%x else
let rec(^)x e=if x/d*d<x then x,e else x/d^e+1in
let x,e=x^0in if e>0then(!s%d;"^"%e;s:="*");x@d+1in x@2
```
[Answer]
## Python, 140 135 133 chars
```
M=N=input()
s=''
f=1
while f<4**8:
f+=1;e=0
while N%f<1:e+=1;N/=f
if e:s+='*%d'%f+'^%d'%e*(e>1)
print M,'=',(s+'*%d'%N*(N>1))[1:]
```
[Answer]
## J, 72
```
(":*/f),'=',([,'*',])/(":"0~.f),.(('^',":)`(''"0)@.(=&1))"0+/(=/~.)f=.q:161784
```
Typical J. Two characters to do most of the work, sixty characters to present it.
**Edit:** Fixed the character count.
[Answer]
## J, ~~53~~ 52 characters
This solution takes the `rplc` trick from the solution of [randomra](https://codegolf.stackexchange.com/a/45499/134) but comes up with some original ideas, too.
```
":,'=',(":@{.,'^','*',~":@#)/.~@q:}:@rplc'^1*';'*'"_
```
In non-tacit notation, this function becomes
```
f =: 3 : 0
(": y) , '=' , }: (g/.~ q: y) rplc '^1*' ; '*'
)
```
where `g` is defined as
```
g =: 3 : 0
": {. y) , '^' , (": # y) , '*'
)
```
* `q: y` is the vector of *prime factors* of `y`. For instance, `q: 60` yields `2 2 3 5`.
* `x u/. y` applies `u` to `y` *keyed* by `x`, that is, `u` is applied to vectors of elements of `y` for which the entries in `x` are equal. This is a bit complex to explain, but in the special case `y u/. y` or `u/.~ y`, `u` is applied to each vector of distinct elements in `y`, where each element is repeated for as often as it appears in `y`. For instance, `</.~ 1 2 1 2 3 1 2 2 3` yields
```
┌─────┬───────┬───┐
│1 1 1│2 2 2 2│3 3│
└─────┴───────┴───┘
```
* `# y` is the *tally* of `y`, that is, the number of items in`y`.
* `": y` *formats* `y` as a string.
* `x , y` *appends* `x` and `y`.
* `{. y` is the *head* `y`, that is, its first item.
* Thus, `(": {. y), '^' , (": # y) , '*'` formats a vector of *n* repetitions of a number *k* into a string of the form *k* ^ *n* \*. This phrase in tacit notation is `:@{.,'^','*',~":@#`, which we pass to the adverb `/.` described further above.
* `x rplc y` is the library function *replace characters.* `y` has the form `a ; b` and every instance of string `a` in `x` is replaced by `b`. `x` is ravelled (that is, reshaped such that it has rank 1) before operation takes place, which is used here. This code replaces `^1*` with `*` as to comply with the mandated output format.
* `}: y` is the *curtail* of `y`, that is, all but its last item. This is used to remove the trailing `*`.
[Answer]
# PHP, 112
```
echo$n=$_GET[0],'=';$c=0;for($i=2;;){if($n%$i<1){$c++;$n/=$i;}else{if($c){echo"$i^$c*";}$c=0;if(++$i>$n)break;}}
```
118
```
echo $n=$_GET[0],'=';for($i=2;;){if(!($n%$i)){++$a[$i];$n/=$i;}else{if($a[$i])echo "$i^$a[$i]*";$i++;if($i>$n)break;}}
```
[Answer]
**Python 119 Chars**
```
M=N=input()
i=1
s=""
while N>1:
i+=1;c=0
while N%i<1:c+=1;N/=i
if c:s+=" * %d"%i+['','^%d'%c][c>1]
print M,'=',s[3:]
```
[Answer]
### JavaScript, ~~124~~ ~~122~~ 119
```
for(s='',i=2,o=p=prompt();i<o;i++){for(n=0;!(p%i);n++)p/=i;n?s+=i+(n-1?'^'+n:'')+'*':0}alert(s.substring(0,s.length-1))
```
[Answer]
# Perl, 78
```
use ntheory":all";say join" * ",map{(join"^",@$_)=~s/\^1$//r}factor_exp(shift)
```
It uses the s///r feature of Perl 5.14 to elide the ^1s. 81 characters to run in a loop:
```
perl -Mntheory=:all -nE 'chomp;say join" * ",map{(join"^",@$_)=~s/\^1$//r}factor_exp($_);'
```
[Answer]
## PHP, 236 characters
```
$f[$n=$c=$argv[1]]++;echo"$n=";while($c){$c=0;foreach($f as$k=>$n)for($r=~~($k/2);$r>1;$r--){if($k%$r==0){unset($f[$k]);$f[$r]++;$f[$k/$r]++;$c=1;break;}}}foreach($f as$k=>$n)if(--$n)$f[$k]="$k^".++$n;else$f[$k]=$k;echo implode("*",$f);
```
Output for 131784: [2^3\*3\*17^2\*19](http://codepad.viper-7.com/L7N3iK)
Completes all numbers within a few seconds while testing.
```
4294967296=2^32
Time: 0.000168
```
Input was never specified, so I chose to call it using command line arguments.
```
php factorize.php 4294967296
```
[Answer]
### Scala 374:
```
def f(i:Int,c:Int=2):List[Int]=if(i==c)List(i)else
if(i%c==0)c::f(i/c,c)else f(i,c+1)
val r=f(readInt)
class A(val v:Int,val c:Int,val l:List[(Int,Int)])
def g(a:A,i:Int)=if(a.v==i)new A(a.v,a.c+1,a.l)else new A(i,1,(a.v,a.c)::a.l)
val a=(new A(r.head,1,Nil:List[(Int,Int)])/:(r.tail:+0))((a,i)=>g(a,i))
a.l.map(p=>if(p._2==1)p._1 else p._1+"^"+p._2).mkString("", "*", "")
```
ungolfed:
```
def factorize (i: Int, c: Int = 2) : List [Int] = {
if (i == c) List (i) else
if (i % c == 0) c :: f (i/c, c) else
f (i, c+1)
}
val r = factorize (readInt)
class A (val value: Int, val count: Int, val list: List [(Int, Int)])
def g (a: A, i: Int) =
if (a.value == i)
new A (a.value, a.count + 1, a.list) else
new A (i, 1, (a.value, a.count) :: a.list)
val a = (new A (r.head, 1, Nil: List[(Int,Int)]) /: (r.tail :+ 0)) ((a, i) => g (a, i))
a.l.map (p => if (p._2 == 1) p._1 else
p._1 + "^" + p._2).mkString ("", "*", "")
```
[Answer]
# J, 74 chars
```
f=.3 :0
(":y),'=',' '-.~('^1 ';'')rplc~}:,,&' *'"1(,'^'&,)&":/"{|:__ q:y
)
f 131784
131784=2^3*3*17^2*19
```
64 chars with input in variable `x`:
```
x=.131784
(":x),'=',' '-.~('^1 ';'')rplc~}:,,&' *'"1(,'^'&,)&":/"{|:__ q:x
131784=2^3*3*17^2*19
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~28~~ ~~27~~ 26 bytes
-1 byte thanks to Shaggy
```
+'=+Uk ü ®ÊÉ?ZÌ+'^+Zl:ZÃq*
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Kyc9K1VrIPwgrsrJP1rMKydeK1psOlrDcSo&input=MTMxNzg0IA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage/wiki), 16 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
³”=³ÆFḟ€1j€”^j”*
```
One of my first Jelly answers, so can definitely be golfed (especially `³”=³`)..
[Try it online.](https://tio.run/##y0rNyan8///Q5kcNc20PbT7c5vZwx/xHTWsMs4AEUCwuC0ho/f//39DY0NzCBAA)
**Explanation:**
```
³ # Push the first argument
”= # Push string "="
³ÆF # Get the prime factor-exponent pairs of the first argument
ḟ€1 # Remove all 1s from each pair
j€”^ # Join each pair by "^"
j”* # Join the pair of strings by "*"
# (implicitly join the entire 'stack' together)
# (which is output implicitly as result)
```
[Answer]
# Java 10, ~~109~~ 108 bytes (lambda function)
```
n->{var r=n+"=";for(int i=1,f;i++<n;r+=f<1?"":(f<2?i:i+"^"+f)+(n>1?"*":""))for(f=0;n%i<1;n/=i)f++;return r;}
```
[Try it online.](https://tio.run/##hVDbasMwDH3fVwjDwJ7XbLk0XeK4/YGtL3scG3huPNylSnGcwCj59sxd8zoKEkJHR@Ic7dWgFvvd96Qb1XXwoiyebgAs@toZpWvYnluAV@8sfoGmTRsKMhHQMWSIzitvNWwBQcKEi/VpUA6cRE4kEaZ1NFwDK@N7IyznFQrHpaniDSElNVWysaXl5INwwzjFdcDvSEkIY@dVIx8F3toqFvggLTOcC1f73iE4MU7iouDYfzZBwSxkaO0ODsEIvYh@ewfFZhc/na8PUdv76BhGvkGKkaZpmrI/R/8y8uUyza9w4jRePWVXSFlSZEW@Sorkmc1PHKdf)
# Java 6+, 181 bytes (full program)
```
class M{public static void main(String[]a){long n=new Long(a[0]),i=1,f;String r=n+"=";for(;i++<n;r+=f<1?"":(f<2?i:i+"^"+f)+(n>1?"*":""))for(f=0;n%i<1;n/=i)f++;System.out.print(r);}}
```
[Try it online.](https://tio.run/##JY3bCsIwEER/JSwIiestKihNoz@gTz6KQrykbK1bSaMi4rfHik8zHOYwpXu4fnm6pHSsXNOI9ft2P1R0FE10sY1HTSdxdcRyEwNxsd059a5qLgRbPj/Fqq3SbUc71SOre978ZyJYRrBgfB2kIcScTUDrc70EyKTPx0vKCGEP6BVKXrS8CxmAUj/D25HhDuXa8NCS8ohm82ri@Tqo73Fwax@iDMp8PiklPdGz@fQL)
-1 byte thanks to *@ceilingcat*.
**Explanation:**
```
n->{ // Method with integer parameter and String return-type
var r=n+"="; // Result-String, starting at the input with an appended "="
for(int i=1,f;i++<n;
// Loop in the range [2, n]
r+= // After every iteration: append the following to the result-String:
f<1? // If the factor `f` is 0:
"" // Append nothing
: // Else:
(f<2? // If the factor `f` is 1:
i // Append the current prime `i`
: // Else:
i+"^"+f) // Append the current prime `i` with it's factor `f`
+(n>1? // And if we're not done yet:
"*" // Also append a "*"
: // Else:
"")) // Append nothing more
for(f=0; // Reset the factor `f` to 0
n%i<1; // Loop as long as `n` is divisible by `i`
n/=i) // Divide `n` by `i`
f++; // Increase the factor `f` by 1
return r;} // Return the result-String
```
[Answer]
# Powershell, ~~113~~ 97 bytes
Inspired by [Joey's](https://codegolf.stackexchange.com/users/15/joey) [answer](https://codegolf.stackexchange.com/a/680/80745). It's a slow but short.
```
param($x)(2..$x|%{for(;!($x%$_)){$_
$x/=$_}}|group|%{$_.Name+"^"+$_.Count-replace'\^1$'})-join'*'
```
Explained test script:
```
$f = {
param($x) # let $x stores a input number > 0
(2..$x|%{ # loop from 2 to initial input number
for(;!($x%$_)){ # loop while remainder is 0
$_ # push a current value to a pipe
$x/=$_ # let $x is $x/$_ (new $x uses in for condition only)
}
}|group|%{ # group all values
$_.Name+"^"+$_.Count-replace'\^1$' # format and remove last ^1
})-join'*' # make string with *
}
&$f 2
&$f 126
&$f 129
&$f 86240
#&$f 7775460
```
Output:
```
2
2*3^2*7
3*43
2^5*5*7^2*11
```
[Answer]
# APL(NARS), 66 chars, 132 bytes
```
{(⍕⍵),'=',3↓∊{m←' * ',⍕↑⍵⋄1=w←2⊃⍵:m⋄m,'^',⍕w}¨v,¨+/¨{k=⍵}¨v←∪k←π⍵}
```
test and comment:
```
f←{(⍕⍵),'=',3↓∊{m←' * ',⍕↑⍵⋄1=w←2⊃⍵:m⋄m,'^',⍕w}¨v,¨+/¨{k=⍵}¨v←∪k←π⍵}
f 131784
131784=2^3 * 3 * 17^2 * 19
f 2
2=2
f (2*32)
4294967296=2^32
{(⍕⍵),'=',3↓∊{m←' * ',⍕↑⍵⋄1=w←2⊃⍵:m⋄m,'^',⍕w}¨v,¨+/¨{k=⍵}¨v←∪k←π⍵}
k←π⍵ find the factors with repetition of ⍵ and assign that array to k example for 12 k is 2 2 3
v←∪ gets from k unique elements and put them in array v
+/¨{k=⍵}¨ for each element of v count how many time it appear in k (it is array exponents)
v,¨ make array of couples from element of v (factors unique) and the array above (exponents unique)
∊{m←' * ',⍕↑⍵⋄1=w←2⊃⍵:m⋄m,'^',⍕w}¨ pretty print the array of couples factor exponent as array chars
3↓ but not the first 3 chars
(⍕⍵),'=' but print first the argument and '=' in char format
```
if someone has many time with these primitives, know them very well them, for me it is possible that
the code is clearer of comments... so code more clear than comments, comments unuseful...
[Answer]
# [QBasic](https://en.wikipedia.org/wiki/QBasic), 156 characters
```
INPUT n#
?n#;"=";
f=2
1c=0
WHILE n#/f=INT(n#/f)
n#=n#/f
c=c+1
WEND
IF c THEN?f;
IF c>1THEN?"^";c;
IF c*(n#>1)THEN?"*";
f=f+1
IF f*f<=n#GOTO 1
IF n#>1THEN?n#
```
When run at [Archive.org](https://archive.org/details/msdos_qbasic_megapack), this takes about 2½ minutes to finish for an input of 4294967291, the largest prime in the specified range.
### Ungolfed, with some remarks
This is the version I used to get the timing information:
```
CLS
INPUT num#
PRINT num#; "=";
factor = 2
startTime# = TIMER
DO
count = 0
WHILE num# / factor = INT(num# / factor)
num# = num# / factor
count = count + 1
WEND
IF count > 0 THEN PRINT factor;
IF count > 1 THEN PRINT "^"; count;
IF count > 0 AND num# > 1 THEN PRINT "*";
factor = factor + 1
LOOP WHILE factor * factor <= num#
IF n# > 1 THEN PRINT n# ELSE PRINT
time# = TIMER - startTime#
PRINT "Search took"; INT(time# / 60); "minutes and";
PRINT INT(time# mod 60); "seconds"
```
The program uses the standard approach of trial division of each factor between \$2\$ and \$\sqrt n\$. It prints a `*` after each successful factor if the remaining \$n\$ is still greater than 1. If the factor becomes greater than \$\sqrt n\$ while \$n > 1\$, then \$n\$ is prime and we output it after exiting the loop.
A few extra bytes had to be spent to cope with very large numbers:
QBasic's numbers are either single- or double-precision floating point under the hood, although it casts to integers for certain calculations. Integers greater than \$2^{24}\$ are not guaranteed to be accurately represented in single-precision floating point, so we have to use double-precision for \$n\$ (thus the double-precision sigil on the variable `num#`). However, since we're only checking factors up to \$\sqrt n < 2^{16}\$, we can use the default single precision for `factor`.
At first, I had `WHILE num# MOD factor = 0` for the inner loop. This worked until I tried numbers close to \$2^{32}\$, at which point it said "Overflow." It seems that the `MOD` operator casts its operands to integers--specifically, 32-bit *signed* integers. A value of \$2^{32}-1\$ can fit in a 32-bit *unsigned* integer, but not a signed one. So `MOD` wasn't going to work. Neither was my usual golf trick of checking divisibility with `a/b=a\b`, since the int-div operator `\` also casts to integers. Fortunately, I could still use floating point division and then truncate explicitly with the `INT` function (which seemingly does *not* cast to integer--??).
Given the issues with single- vs. double-precision, I assumed that squaring `factor` (single-precision) before comparing it with `num#` (double) wasn't going to work. But surprisingly, it did. My best guess after some experimentation is that if there's a double-precision value anywhere in an expression, QBasic casts *all* of the values to double before computing anything. This contrasts with C, [for example](https://tio.run/##jc@9CsIwEAfwPU9xKIW0amk3tX4svoGrS5ukbSAmmiYQEJ89phHRRXH5H8f9Du7IoiPE@ymXRFjKYDMYylXe7xCXBs41lziFG4JWqNqAgy0sy1WZFxVCcNHBtHiSUBiuttYs1F5ZQaFhkNCTnMyjfmY2Rlq9145cdoKFlhE@cCXXkLRxx2Xu0x2Ubb44TOMs/du7WZEX6S@9f2k8nhH5@KtmxmoJ4e@79w8), where implicit casting only occurs between the operands of a single operator.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÐfsÓ0Køε1K'^ý}'*ý'=ý
```
-2 bytes thanks to *@Emigna*.
[Try it online.](https://tio.run/##ASsA1P9vc2FiaWX//8OQZnPDkzBLw7jOtTFLJ17DvX0nKsO9Jz3Dvf//MTMxNzg0)
**Explanation:**
```
Ð # Triplicate the (implicit) input-integer
f # Pop and push all prime factors (without counting duplicates)
s # Swap to take the input again
Ó # Get all prime exponents
0K # Remove all 0s from the exponents list
ø # Zip it with the prime factors, creating pairs
ε # Map each pair to:
1K # Remove all 1s from the pair
'^ý '# And then join by "^"
}'*ý '# After the map: join the string/integers by "*"
'=ý '# And join the stack by "=" (with the input we triplicated at the start)
# (after which the result is output implicitly)
```
[Answer]
# JavaScript, 107
```
n=prompt()
s=n+'='
c=0
for(i=2;;){if(n%i<1){c++
n/=i}else{if(c)s+=i+'^'+c+'*'
c=0
if(++i>n)break}}
alert(s)
```
120
```
n=prompt()
o={2:0}
for(i=2,c=n;i<=c;)!(c%i)?++o[i]?c/=i:0:o[++i]=0
s=n+'='
for(i in o)s+=o[i]?i+'^'+o[i]+'*':''
alert(s)
```
[Answer]
# [PHP](https://php.net/), 112 bytes
```
<?=$a=$argn,"=";for($i=2;1<$a;)$a%$i?$i++:$a/=$i+!++$r[$i];foreach($r as$k=>$v)echo$t?"*":!++$t,$v<2?$k:"$k^$v";
```
[Try it online!](https://tio.run/##HcrRCoIwFIfxe5@iDv9AmxC5O7fjHiQKDmJtCDqW7PWXdvfx44s@FuuijxUkfRYmrTWZyg27MoT/2hKTea@pRuDO3C3ENJALgkNQqofceI@zUkgPhOexTjL6GukkX8w8IDfT6Fdsjq7UH@PWItvOYe4J8wuZTCk/ "PHP – Try It Online")
[Answer]
# PHP, 93 bytes
```
<?=$n=$argn;for($i=2;$n>1;$k&&$p=print($p?"*":"=")."$i^$k",$i++)for($k=0;$n%$i<1;$n/=$i)$k++;
```
I could do 89 bytes with PHP 5.5 (or later), but that postdates the challenge by more than 2 years:
```
<?=$n=$argn;for($i=2;$n>1;$k&&$p=print"=*"[$p]."$i^$k",$i++)for($k=0;$n%$i<1;$n/=$i)$k++;
```
Run as pipe with `-nF` or [try them online](http://sandbox.onlinephpfunctions.com/code/853b0331a800861d752594542295f8fbed2d82a0).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 24 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
+'=+Uk ü ËÎ+DÅÊÎç^+DÊÃq*
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Kyc9K1VrIPwgy84rRMXKzudeK0TKw3Eq&input=MTMxNzg0)
[Answer]
# [Go](https://go.dev), 199 bytes
```
type M=map[int]int
func f(n int)M{m:=make(M)
for x,i:=n,2;i<=n;i++{if func(p int)int{if p<4{return p}else{for i:=2;i*i<=p;i+=2{if p%i==0{return-1}}}
return p}(i)>0{for x%i==0{m[i]++;x/=i}}}
return m}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY9RaoQwEIbfc4qwUEiq26oVlHXTGwh9X_ZBlmQZdhODG8FFPElfpNBL9AI9Q2_TMUrrQ5jkm_8jM-8f53r8stXpUp0l1RUYAtrWjaNPG6Xd5rN1apv_fLu7lbQUurIHMO6Ih6jWnKhihuKDl73eYfciWcmJqhvahbATJkwK2AtTQBD0oOikMOsFPBOx-7RvpGsbQ-0grzfZTzKqKD6ialEViU8-gBDREt7GwzCQP5EBf4282c0pfYBjEBTds4BVUA_LOp2ffdqWcdqTtwanuRoWv8RZnoa41Hzj_L8VeRytUeZRtkLJRJI1iNLcM6yIl__Hca6_)
Returns a map where the keys are the bases, and the values are exponents. So `131784 => map[2:3 3:1 17:2 19:1]`
] |
[Question]
[
Given a matrix, output a representation of the matrix where the top left element is on top, the anti-diagonal is the central row and the bottom right element is at the bottom.
For example, consider the following matrix:
```
1 2 3
4 5 6
7 8 9
```
The diamond version of this matrix is:
```
1
4 2
7 5 3
8 6
9
```
### Inputs and outputs
An input matrix will be given as a list of lists (or anything similar in your language of choice). The output shall be a list of lists as well.
The matrices will only contain positive integers.
The input matrix will not necessarily be square.
The input matrix will be at least 1×1.
### Test Cases
```
Input: [[1]]
Output: [[1]]
Input: [[1,2],[3,4]]
Output: [[1],[3,2],[4]]
Input: [[1,2,3],[4,5,6]]
Output: [[1],[4,2],[5,3],[6]]
Input: [[11,2,5],[3,99,3],[4,8,15],[16,23,42]]
Output: [[11],[3,2],[4,99,5],[16,8,3],[23,15],[42]]
```
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
## J, 6 bytes
```
<@|./.
```
This is an unnamed a monadic verb which takes a matrix and returns a list of antidiagonals:
```
input =. i.3 4
input
0 1 2 3
4 5 6 7
8 9 10 11
<@|./. input
┌─┬───┬─────┬─────┬────┬──┐
│0│4 1│8 5 2│9 6 3│10 7│11│
└─┴───┴─────┴─────┴────┴──┘
```
[Test it here.](http://tryj.tk/)
### Explanation
* `/.` is J's built-in to apply a function to each anti-diagonal. Unfortunately, these anti-diagonals are given in the opposite order of what we want here.
* In `<@|.`, we first apply `|.` which reverses the anti-diagonal and then `<` to box it (which is the only way to return a ragged array in J, since normal arrays are always rectangular, so the antidiagonals would be padded with zeroes).
[Answer]
# Python, 91 bytes
```
e=enumerate
lambda M:[[r[n-i]for i,r in e(M)if-1<n-i<len(r)][::-1]for n,_ in e(M[1:]+M[0])]
```
Test it on [Ideone](http://ideone.com/FjgmK4).
---
# Python + NumPy, 69 bytes
```
import numpy
lambda M:map(M[::-1].diagonal,range(1-len(M),len(M[0])))
```
Expects a 2D NumPy array as input and returns a list of NumPy arrays. Test it on [Ideone](http://ideone.com/kFQIgU).
[Answer]
## Jelly, 7 bytes
```
ṚŒDṙZL$
```
[Try it online!](http://jelly.tryitonline.net/#code=4bmaxZJE4bmZWkwk&input=&args=W1swLCAxLCAyLCAzXSwgWzQsIDUsIDYsIDddLCBbOCwgOSwgMTAsIDExXV0)
### Explanation
```
Ṛ Reverse the matrix vertically.
ŒD Get its diagonals. However these start from
the main diagonal, not the corners.
ZL$ Get the width of the input matrix.
ṙ Rotate the list of diagonals left by that many
places to obtain the correct order.
```
[Answer]
# Mathematica, ~~58~~ 56 bytes
```
a=Length;Reverse@#~Diagonal~b~Table~{b,1-a@#,a@#&@@#-1}&
```
Anonymous function, takes nested arrays.
[Answer]
## CJam, 17 bytes
```
{eeSf.*::+W%zSf-}
```
An unnamed block (function) which expects the matrix on the stack and replaces it with its antidiagonals.
[Test it here.](http://cjam.aditsu.net/#code=%5B%5B0%20%201%20%202%20%203%5D%0A%20%5B4%20%205%20%206%20%207%5D%0A%20%5B8%20%209%2010%2011%5D%5D%0A%0A%7BeeSf.*%3A%3A%2BW%25zSf-%7D%0A%0A~p)
This (found by Sp3000) works for the same byte count:
```
{_,,Sf*\.+W%zSf-}
```
### Explanation
This is best explained with an example. Consider the input:
```
[[0 1 2 3]
[4 5 6 7]
[8 9 10 11]]
ee e# Enumerate matrix, turning each row [x ... z] into [i [x ... z]] where
e# i is the vertical index from the top.
[[0 [0 1 2 3]]
[1 [4 5 6 7]]
[2 [8 9 10 11]]]
Sf.* e# Replace each i with a string of i spaces.
[["" [0 1 2 3]]
[" " [4 5 6 7]]
[" " [8 9 10 11]]]
::+ e# Prepend these strings to the rows.
[[0 1 2 3]
[' 4 5 6 7]
[' ' 8 9 10 11]] e# Note that each ' corresponds to a space character.
W% e# Reverse the rows.
[[' ' 8 9 10 11]
[' 4 5 6 7]
[0 1 2 3]]
z e# Zip/transpose.
[[ ' ' 0]
[ ' 4 1]
[ 8 5 2]
[ 9 6 3]
[10 7]
[11]]
Sf- e# Remove spaces from each row.
[[ 0]
[ 4 1]
[ 8 5 2]
[ 9 6 3]
[10 7]
[11]]
```
[Answer]
## Python 2, ~~88~~ 87 bytes
```
lambda L:[filter(None,x)[::-1]for x in map(None,[],*[i*[0]+r for i,r in enumerate(L)])]
```
Prepend 0s, zip, then remove falsy elements. Returns a list of tuples. This uses `map(None,...)` to perform `zip_longest` (padding missing spots with `None`) and `filter(None,...)` to remove falsy elements.
Annoyingly, we need to add an extra `[]` row to the `map` to guarantee that a list of tuples is returned, since `map(None,*[[1]])` returns `[1]` rather than `[(1,)]` for a 1x1 matrix. The extra row gets stripped out by the `filter` though.
*(Thanks to @Dennis for -1 byte)*
[Answer]
# Ruby, ~~68~~ 66 bytes
Anonymous function.
```
->l{i=-1;k=[];l.map{|r|i-=j=-1;r.map{|e|k[i+j+=1]=[e,*k[i+j]]}};k}
```
* Because of how the splat operator works, I was able to save 2 bytes by forgoing the array addition.
[Answer]
# JavaScript (Firefox), ~~86~~ 75 bytes
```
a=>a.concat(a[0]).slice(1).map((_,i)=>[for(v of a)if(n=v[i--])n].reverse())
```
*Saved 11 bytes thanks to @Neil!*
Works in Firefox 30+. Takes an array of arrays.
[Answer]
# [Husk](https://github.com/barbuz/Husk/wiki/Commands), ~~3~~ 2 [bytes](https://github.com/barbuz/Husk/wiki/Codepage)
```
∂T
```
-1 byte thanks to *@mypronounismonicareinstate*.
[Try it online.](https://tio.run/##yygtzv7//1FHU8j///@jow11jHSMY3WiTXRMdcxiYwE)
**Explanation:**
```
T # Transpose the (implicit) matrix-argument; swapping rows/columns
∂ # Take the anti-diagonals of this transposed matrix
# (after which the result is output implicitly)
```
[Answer]
## Mathematica, 60 bytes
```
#&@@@#&/@GatherBy[Join@@MapIndexed[List,#,{2}],Tr@*Last]&
```
where `` is a Unicode character which Mathematica reads as the postfix `\[Transpose]` operator.
This is a bit longer than the other Mathematica solution but I figured I'd post it because it doesn't use the `Diagonals` built-in and uses a completely different approach.
### Explanation
```
MapIndexed[List,#,{2}]
```
This first transposes the matrix (such that the antidiagonals appear in the correct order if the matrix was flattened). Then we map `List` over the cells of the matrix together with the index, which turns each matrix element `i` into `{i, {x, y}}` where `x` and `y` are the coordinates of the element in the matrix.
```
Join@@...
```
This flattens the outermost dimension, so that we now have a flat list of the matrix elements (with their coordinates) in column-major order.
```
GatherBy[..., Tr@*Last]
```
This groups those elements by the sum of their coordinates. Note that antidiagonals are lines of constant `x+y`, so this does exactly the grouping we want. The order within each group is preserved. Now we just need to get rid of the coordinates again. This is done via the rather cryptic:
```
#&@@@#&/@...
```
This maps the function `#&@@@#&` over each group, which itself *applies* `#&` to each element in the group, and `#` is simply the first argument, i.e. the original matrix element.
[Answer]
# Octave, 77 bytes
With a little abuse of the `accumarray` function:
```
@(M)char(accumarray(((1:size(M,1))+(0:size(M,2)-1)')(:),M(:),[],@(x){num2str(x')}))
```
This defines an anonymous function. To use it, assign to a varible or use `ans`.
Input is the matrix with `:` as row separator. Output is a cell array containing an array for each row (Octave's equivalent to jagged arrays). This is displayed by Octave showing the indices of the cell array and the contents of each cell. [Try it here](http://ideone.com/7a6Yie).
To display the result separated by spaces and newlines only: **83 bytes**
```
@(M)char(accumarray(((1:size(M,1))+(0:size(M,2)-1)')(:),M(:),[],@(x){num2str(x')}))
```
You can also [try it here](http://ideone.com/QbgMMd).
[Answer]
# Octave, ~~63~~ 62 bytes
Removed one byte thanks to ~~@DonMue...~~ @LuisMendo!
```
@(a)cellfun(@(x)x(x>0)',num2cell(spdiags(flipud(a)),1),'un',0)
```
I went the boring route and munged the antidiagonals.
Sample run on [ideone](http://ideone.com/iuAUhy).
[Answer]
# Haskell, ~~83~~ 82 bytes
```
r=zip[0..]
\o->fst$span(any(>0))[reverse[e|(x,t)<-r o,(v,e)<-r t,x+v==a]|a<-[0..]]
```
nimi saved a byte. Thanks!
[Answer]
# [C#], 100 bytes
```
for(r=0;r<l;r++)for(c=0;c<i[r].Length;c++)o[c+r]=o[c+r]?.Prepend(i[r][c]).ToArray()??new[]{i[r][c]};
```
[Try It online!](https://tio.run/##ZY9NS8QwEIbv/oqXnFKaLe3uKi7ZWsSbeBBW8BByWGJcAyWRaVFk6W@v6YdF8TQzzzzDzJhmZRrXfxwJDiW8/VQa5yUWhcBa4BKdWNhGYLcT2PxmW4FrgeKPV1zF2Shv1@jQyYthRx13uOzB@lP7NhPrB6ZyPWOki4EViskK021wvlVxQis9cYo8lxhSM6b9ayBOZS5pX0tK02SoTazN3in62SFN7ARlUtLlFKrskey79S980JTRSfYUbomOXzypqvGl89zpZH8XfBNqmz2Tay1nCixefWjJ@VN2H5znDAJMIGQHW1vT8gblDZj6p4koNUmkTLNkjIiJ7L8B)
Maybe there's a shorter way of inserting elements. Prepend and ToArray seems verbose, but that's the best I found.
[Answer]
# [Haskell](https://www.haskell.org/), 56 bytes
```
a!b=zipWith(++)([]:b)$a++repeat[]
foldr1(!).map(pure<$>)
```
[Try it online!](https://tio.run/##DcVLDoMgEADQvafAhAWEienYr03pNbogLMYIkRSVULrp5alv82b6vF2MtVI76l9Ir1BmoZQUxt5HyUmp7JKjYmzjtd/ilFG0slsoifTN7sGfsi4UVj1tDWMph7UwzjwzBqGHowVzgjNc9q9wg2EfD4AI2Ftb/w "Haskell – Try It Online")
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 111 bytes
```
A*B*C:-append(A,B,C).
s(A,B,C):-A*[B]*C.
N+B:-N=[A|X],X+R,Z*Q*R,maplist(s,[[]|Z],A,Y),Y*Q*B,!;maplist(=([]),B).
```
[Try it online!](https://tio.run/##NYu9DoIwFEZ33sINykcT/oxgGNo6k8gENB1INIYEpbEmLrx7LYrb/c45Vz/nab5F5j1aywgnoowGra@Pi8/AIQLqme0qI0YkV0RQrw55GdWVZEur0IYNenImDe6Dnkbz8g2kVEuvwNAF6Jzj2B3/tvKlCsADaq2UsVIhc3mMREGmyNzmv43UkQw59o6Jla0w/2ZFsdkD4pXEeyTuOXHliXreBw "Prolog (SWI) – Try It Online")
## Explanation
Let's first look a version of the code that not nearly so condensed.
```
snoc(Init,Last,List) :-
append(Init,[Last],List).
diamondize([],Soln) :-
maplist(=([]),Soln).
diamondize([FirstRow|Rest],Soln):-
diamondize(Rest,RestSoln),
append(BeginRestSoln,EndSoln,RestSoln),
maplist(snoc,[[]|BeginRestSoln],FirstRow,BeginSoln),
append(BeginSoln,EndSoln,Soln),
!.
```
The `diamondize/2` predicate (`+/2` in the golfed version) is responsible for calculating what the diamond version of the input matrix is.
The predicate works recursively as follows: first it calculates the diamond version of the input matrix with its first row removed (`diamondize(Rest,RestSoln)`); then to calculate the diamond version of the entire input matrix it uses the fact that adding an initial row changes the diamond version by prepending a singleton list of the first element of the initial row and then pairing up each remaining element in the initial row with the first however many lists in the diamond and adding each initial row element to the end of its paired list, leaving the remaining lists in the diagonal unchanged. To do this in Prolog I use `append` to split `RestSoln` into a beginning, `BeginRestSoln`, and an end, `EndSoln`. Then I use the the builtin `maplist/4` to assert a relation between `BeginRestSoln`, the new initial row, `FirstRow`, and a new list `BeginSoln`. The `maplist/4` predicate asserts that all triples of elements of equal indices from the lists in its second, third, and fourth arguments will satisfy the predicate given as its first argument when it is called on them (note that this requires all the lists given as arguments to be of equal length). The predicate I use is `snoc/3` which asserts that when its second argument is added to the end of the list in its first argument, you get its third argument. Furthermore I add an empty list to the start of `BeginRestSoln` which means that when I `snoc` that with the first element of `FirstRow` the resulting first element of`BeginSoln` will be a singleton list of that aforementioned first element. The rest of `BeginSoln` will be the lists that began the diagonal version of the remainder of the matrix with the remaining elements of the first row added to the end, just as desired in the process described above. Finally to get the solution for the entire matrix we append `BeginSoln` with the unchanged `EndSoln`.
We have now covered the behavior of `diamondize/2` when the matrix is not empty, but the base case is the empty matrix. In that case the "solution" is considered to be a list of some undetermined length with `[]` for all its elements. This list is constructed using the `maplist/2` predicate which asserts that each element of the list given in its second argument satisfies the predicate given in its first argument. The predicate we use is `=([])/1` which is the partially applied `=/2` predicate which asserts that its two arguments unify, so our partially applied version asserts that its singular argument unifies with (ie is equal to) the empty list. However, since we do not specify a length, Prolog will attempt to satisfy the future goals with the shortest list containing only empty lists, backtracking and trying a longer such list if the future goals can't be satisfied. This behavior is very useful since in our first inductive case the predicates won't be satisfied unless the previous solution is at least one less than the length of the rows of the matrix, but we run into an issue in that longer lists of empty lists would also result in solutions that the program would consider valid, but would be invalid for this challenge. To avoid producing these solutions, we add a cut (`!`) to the end of the recursive case of `diamondize/2`, which will tell Prolog not to backtrack once we have a working solution.
Finally to golf the whole thing I used a number of tactics. First off, of course we can eliminate excess whitespace, and give variables and predicates shorter names. Then since `append/3` is being used a lot I can save a couple bytes by creating a copy of it with a shorter name, using an operator to name both it and what was the `diamondize/2` predicate (unfortunately since operator predicates technically can have at most two arguments, I cannot give `s/3` an operator name since I need to pass it to `maplist/4`). Finally I can consolidate the two cases of `+/2` into a single case with a disjunction.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 11 bytes
```
⌽¨+´¨∘↕∘≢⊸⊔
```
Anonymous tacit function. Takes a 2D array and returns a list of lists. [Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oy9wqjiiqLiipTLnOKXi+KliivCtMKo4oiY4oaV4oiY4omiCgptIOKGkCBbWzExLDIsNV0sWzMsOTksM10sWzQsOCwxNV0sWzE2LDIzLDQyXV0KCkYgbQ==)
### Explanation
```
⌽¨+´¨∘↕∘≢⊸⊔
≢ Get the shape of the array (a list of two integers)
↕∘ Range (a 2D array of coordinate pairs)
+´¨∘ Sum each of those pairs
We now have an array in which the top left element is 0, the two elements
in the next antidiagonal are 1, and so forth
⊸ With that as left argument and the original array as right argument,
⊔ Group the values of the right argument into buckets based on the
corresponding number in the left argument
⌽¨ Reverse each antidiagonal
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), [19 bytes](https://chat.stackexchange.com/rooms/240/the-nineteenth-byte)
```
_RMxMZD:xRL_AL BMEa
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJfUk14TVpEOnhSTF9BTCBCTUVhIiwiIiwiIiwiW1sxOzI7M107WzQ7NTs2XTtbNzs4OzldXSAteHAiXQ==)
I'm a bit rusty. There might be a shorter way to do this with loops but oh well.
```
ME # Map [index item] for each item of...
a # Input
--------ME # Block
RL # Repeat...
x # The empty string
_ # By the index
AL # Concatenate to...
B # The item
ZD: # Transpose, filling with ""
----M # Map over each...
_RM # Remove
x # The empty string
```
[Answer]
# Python, 128 bytes (numpy)
```
(lambda A: (lambda A,S:[[A[U][I-U] for U in range(min(S[1]-1,I),max(I-S[0]+1,0)-1,-1)] for I in range(S[1]+S[0]-1)])(A,A.shape))
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~41~~ 17 bytes
```
tm_<dx+dYk.T+LaYk
```
[Try it online!](http://pyth.herokuapp.com/?code=tm_%3Cdx%2BdYk.T%2BLaYk&input=%5B%5B1%2C2%2C3%5D%2C%5B4%2C5%2C6%5D%2C%5B7%2C8%2C9%5D%2C%5B10%2C11%2C12%5D%2C%5B13%2C14%2C15%5D%5D&debug=0)
Inspired by [@Doorknob's solution to another problem](https://codegolf.stackexchange.com/a/75591/48934).
How it works:
```
tm_<dx+dYk.T+LaYk
+L prepend to each subarray...
aYk (Y += ''). Y is initialized to [],
so this prepends [''] to the first
subarray, ['', ''] to the second, etc.
['' 1 2 3
'' '' 4 5 6
'' '' '' 7 8 9
'' '' '' '' 10 11 12
'' '' '' '' '' 13 14 15]
.T transpose, giving us
['' '' '' '' ''
1 '' '' '' ''
2 4 '' '' ''
3 5 7 '' ''
6 8 10 ''
9 11 13
12 14
15]
m_<dx+dYk removes all empty strings in the
subarrays while reversing each one
t remove the first subarray
```
---
Previous attempt:
```
JlQKlhQm_m@@Qk-dk}h.MZ,0-dtKh.mb,tJdUt+JK
```
[Try it online!](http://pyth.herokuapp.com/?code=JlQKlhQm_m%40%40Qk-dk%7Dh.MZ%2C0-dtKh.mb%2CtJdUt%2BJK&input=%5B%5B1%2C2%2C3%5D%2C%5B4%2C5%2C6%5D%2C%5B7%2C8%2C9%5D%2C%5B10%2C11%2C12%5D%2C%5B13%2C14%2C15%5D%5D&debug=0)
How it works:
```
JlQKlhQm_m@@Qk-dk}h.MZ,0-dtKh.mb,tJdUt+JK input array stored as Q
JlQ J = len(Q)
KlhQ K = len(Q[0])
m Ut+JK list for d from 0 to J+K-1:
_m }AAAAAAAAAABBBBBBBB reversed list for k from A to B, where:
h.MZ,0-dtK A = max(0, d-(K-1))
0-dtK 0 d-(K-1)
h.mb,tJd B = min(J-1, d)
tJd J-1 d
@@Qk-dk Q[k][d-k]
```
[Answer]
# Groovy, 77 73 75
```
{i->o=[].withDefault{[]};a=0;i.each{b=0;it.each{o[a+b++].add(0,it)};a++};o}
```
Takes array of arrays as input and returns array of arrays.
[Try it](http://groovyconsole.appspot.com/script/5084993378320384)
EDIT: I forgot to output the anwser, after adding it score goes up to 75.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εD0*«NFÁ]øí0δKʒOĀ
```
Unfortunately 05AB1E only has a builtin for the main (anti)diagonal, and not one for all (anti)diagonals, so we'll have to do things manually..
-1 byte by switching to the legacy version of 05AB1E, so the `0δK` can be `0K`.
[Try it online](https://tio.run/##MzBNTDJM/f//3FYXA61Dq/3cDjfGHt5xeK2B96lJ/kca/v@PjjbUMdIxjtWJNtEx1TED0uY6FjqWsbEA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeX/c1tdDLQOrfZzO9xYW3t4x@G1Bt6nJvkfafhfq/M/OjraUMdIxzhWJ9pEx1THDEib61joWMbG6igApaCUjhFQ3FjHBM5F0gARAomZghVZWkIlLXQMQSKGZjpGQK1GsbGxAA).
**Explanation:**
```
ε # Map each row in the (implicit) input-matrix to:
D # Duplicate the current row
0* # Multiply each by 0, so we have a list of 0s the same length of the row
« # Append the lists together
# i.e. [[1,2,3],[4,5,6],[7,8,9]] → [[1,2,3,0,0,0],[4,5,6,0,0,0],[7,8,9,0,0,0]]
NF # Loop the (0-based) map-index amount of times:
Á # And rotate the row with appended 0s once towards the right each iteration
# → [[1,2,3,0,0,0],[0,4,5,6,0,0],[0,0,7,8,9,0]]
]ø # After the map and inner loop: zip/transpose; swapping rows/columns
# → [[1,0,0],[2,4,0],[3,5,7],[0,6,8],[0,0,9],[0,0,0]]
í # And reverse each inner row
# → [[0,0,1],[0,4,2],[7,5,3],[8,6,0],[9,0,0],[0,0,0]]
0K # Remove all 0s from each inner row
# → [[1],[4,2],[7,5,3],[8,6],[9],[]]
ʒOĀ # And filter out any empty rows
# → [[1],[4,2],[7,5,3],[8,6],[9]]
# (after which the result is output implicitly)
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 78 bytes
```
{{⍵/⍨×≢¨⍵}{⍵/⍨×⍵}¨↓⍉(-⍳≢⍵)⌽⍵↑⍨1 2×≢⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6urH/Vu1X/Uu@Lw9Eediw6tAPJqkYSAPKBY2@RHvZ0auo96NwPVAMU0H/XsBVKP2iYCVRkqGIH1gtT@TwMa@qi371FX86PeNY96txxabwxS1Tc1OMgZSIZ4eAb/T1MwBkKgpKE20ERLrjQFEwVTON/IAAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as an array of space delimited strings, outputs a 2D array of integer strings.
```
ËiEç)¸ÃÕËÔf
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=bbg&code=y2lF5ym4w9XL1GY&input=W1sxIDIgM10gWzQgNSA2XSBbNyA4IDldXQotUQ) (header converts 2D arrays to the required input format) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=bbg&code=y2lF5ym4w9XL1GY&footer=Vq6uaVEgK1HDcSwgaSdbICsnXcNxLCBpJ1sgKydd&input=WwpbWzEgMiAzXSBbNCA1IDZdIFs3IDggOV1dCltbMV1dCltbMSwyXSxbMyw0XV0KW1sxLDIsM10sWzQsNSw2XV0KW1sxMSwyLDVdLFszLDk5LDNdLFs0LDgsMTVdLFsxNiwyMyw0Ml1dCl0KLW1S)
```
ËiEç)¸ÃÕËÔf :Implicit input of array
Ë :Map each element at 0-based index E
i : Prepend
Eç : E spaces
) : End prepend
¸ : Split on spaces
à :End map
Õ :Transpose
Ë :Map
Ô : Reverse
f : Filter
```
] |
[Question]
[
**This question already has answers here**:
[MacGyver's Second Toolbox](/questions/128464/macgyvers-second-toolbox)
(3 answers)
Closed 6 years ago.
In this question each answer will get a "toolbox" that can be used to construct a program/function. The toolbox will consist of two things:
* a list of programming languages
* a list of valid characters
You must write a valid program/function in one of the languages provided using only the characters in the toolbox. Your program/function should output the number of answers already present on this question.
Once you have written and posted an answer the language and characters you have used will be removed from the toolbox and 1 new language and 12 new characters will be randomly added to be used as the toolbox for the next answer.
## Rules
* Each answer will:
+ Output the number of valid answers coming before it
+ Contain a subset of the characters provided in the toolbox for that answer. (repeats are allowed)
+ Be in one of the languages from the provided toolbox
* The next toolbox will determined by [this](https://tio.run/##dVbXduM2EH22vkLRycZSYjqm3DfZk957L5bPGgRBEhIIYFEkcVP@Os/OzICUvCkP4NwBMBWDAW0XGqPn94rp2o@fjG8mJ@esyMXkaDL3rFAITtfMAbmEcX0NH5ZZwVwWnMBVxkNkSnUIy9JapLXRxKvaqIurmqDktFvZJvIVIquysmPK1C8wGVfMe8n7SV1rRI53JhLQRpW06L1oC9VlzD/kav7Coma@RT4WwtVSkwcbsr418C2Yb5CgTCFYm4hOJGi5IiT8hm0JVVHXYo@y6ytkFIk7xpsuRbPD88RInVWKrQamMEYNuErJIAzJqghLpjPep6mIBZxCHdE3jsnRNaEUKM9CosyVUjNUywVYxhB4AzoTBV@VTIIN5NKkjY0oSzpZ3kg8Ni61Zq3RWW9tSQnhSnpaVWYZHUbPTVVBUriTNhCrS9mDtdgS2ODX2sFLx7rkkut8SMZ9xk3S5jOwiafBYyFJHGunxJGOh867FFy2JFpCLC0ZLEUwEQMoQStlSyjRCh0IYS5Fy0B/H4FocY10CIeJzPZBiMDwu5a4WkFNG9RbCaeZLg1BrL9KOlFAtRMk55BkvhHDnJcUaY@wACrDyWZlSI9xQfS0yWoiPevg2Ose0FR0UpAbuxRB2XEZyEKtOtuYHQAfUBV4i1M0D@W0i692cCeIylYQNWaNea49@tgwv0ohNKwbktkUvEHZRmyHGy1x6CBcCmmJI4sFLi0ZGVqyNcuMFXpZrv7BXvd8ciorWCHggptSvDg/zIjUVIj2yV4amolKsoGeA1hlK6MZAYNGV0pQ5a9MUAmQtGJF58B7wpKUK7XGGoerKnkyq4waUESVuAx1VxhFN79lTpr@ErYsNJL7hBSRtXCScteyLZQrAqmxbrN5OTAqgdWgBqbwG6ol1rmOLfSqTVoyzEvUb4ql4EGuRbZvAVBVpMrwAGYRNKjHMgdF3ohALRQ4mdVY/JZaDAKo/fOeXiBtaBni76@JpWZgUbc1G@GG4t4zw9W1TqhYJmSwd/sNFoiNztLDYaNvMMu2WxGLjckTcKyVZeahBbVphQ7F0mOU79B8jzLb2W7HngLCiwF9diUCAbq4Di9rmz3srE44UVNXcpiTqKjjIaaKcWJLa7TVlDRljCWSeoCD2OgRSiBDp1wqeRc9GvdwGRhRDAc6t3j@kIOCEHo/UUdJyfGipC/UU/RUjF54g@nxDbP7zkT3midA5@zpwHwTYEPSIVWSg5ezEYTaoiKislalduE1pIjWtNm01GC8aSn7/pmS1JPo4nMW/ICT@sCcI/@CS1@G7d13Le6DbYbIFo8@cEVfum9BtFaxQB6FBv4WWEkoikQCdlQ4h64vPOx7u7Ahurqm7hdcbO1@PrqgyK8IrzcVedQl1LIh7VEr1hZ0jlE7sNj/w6xxpGNaSw8/LBlJZ1qEobeuZfAY5qaRTiUKvltG/y0b6YkYePlTX9p4THEX0fPnEO/tvWwtHNUYemmjZDEaWeODLOGnChL2VGobw3Q2wttbmC3MDjP4JKcZyEOY9tMzkHe6htle33Fbnk@TSlgbgXdKjJXQ017jbPzm@PLx6ECLDc6A4GQyOkjbtAnjYd64HZR63AuD3AGaO462hBOb9jtmML3XR/@IN@BgmNJeeBdKWQvweXaUX8weDc742ex2dNBrPmYWun@51ziCF278FG07/C@Z5vNZ8hrz8C@vp/3CrPebNoHskDS48JSEnsck5POr/wiHlKRwekO8cf8fCyiB3bLa2URn9nbRQA8fBJhswLmB2iGzPXc3mRwvjdRTj@9/ufN3dnd/n88vzs5ORzeH8M9yeDQ@fPBri@yDtpJYKGME@@uCnGjNkt6ww9vR4WJ7cgIjhzGHcQrjDMY5jAsYlzCuFmGhgRYw@MLBV8CoFtscJHOQzEEyB8kcJHOQzEEyB8n8CsY1DAYDpHMOo4QB8nk1fmny8qNXFofT2auvHWXHr5/Mz84vLq@uH7/x5K2333n3vfc/@PCjjz/59LPPv/jyq6@/@fa773/48aeff/n1ZrG4fXrHCl6Kqm7kcqVabZ85H@Jm2z3/7fc//lxsL6vDv7TJOPxbi78B) python program. To generate the next toolbox put in the remaining languages and characters along with the *post id* of the last answer.
* The language list here is all the languages available on try it online at the time of this post. The characters have char codes 0-127.
* You may write either a full program or a function as your answer. Since REPLs are different languages they will not be allowed. (use the TIO version of every language)
* If a language uses a special encoding the characters should be interpreted as *bytes* (decoded from ASCII and padded with a zero).
* The starting toolbox will be randomized from this questions post id ([126063](https://tio.run/##dVbXduM2EH22vkLRycZSYjqm3DfZk957L5bPGgRBEhIIYFEkcVP@Os/OzICUvCkP4NwBMBWDAW0XGqPn94rp2o@fjG8mJ@esyMXkaDL3rFAITtfMAbmEcX0NH5ZZwVwWnMBVxkNkSnUIy9JapLXRxKvaqIurmqDktFvZJvIVIquysmPK1C8wGVfMe8n7SV1rRI53JhLQRpW06L1oC9VlzD/kav7Coma@RT4WwtVSkwcbsr418C2Yb5CgTCFYm4hOJGi5IiT8hm0JVVHXYo@y6ytkFIk7xpsuRbPD88RInVWKrQamMEYNuErJIAzJqghLpjPep6mIBZxCHdE3jsnRNaEUKM9CosyVUjNUywVYxhB4AzoTBV@VTIIN5NKkjY0oSzpZ3kg8Ni61Zq3RWW9tSQnhSnpaVWYZHUbPTVVBUriTNhCrS9mDtdgS2ODX2sFLx7rkkut8SMZ9xk3S5jOwiafBYyFJHGunxJGOh867FFy2JFpCLC0ZLEUwEQMoQStlSyjRCh0IYS5Fy0B/H4FocY10CIeJzPZBiMDwu5a4WkFNG9RbCaeZLg1BrL9KOlFAtRMk55BkvhHDnJcUaY@wACrDyWZlSI9xQfS0yWoiPevg2Ose0FR0UpAbuxRB2XEZyEKtOtuYHQAfUBV4i1M0D@W0i692cCeIylYQNWaNea49@tgwv0ohNKwbktkUvEHZRmyHGy1x6CBcCmmJI4sFLi0ZGVqyNcuMFXpZrv7BXvd8ciorWCHggptSvDg/zIjUVIj2yV4amolKsoGeA1hlK6MZAYNGV0pQ5a9MUAmQtGJF58B7wpKUK7XGGoerKnkyq4waUESVuAx1VxhFN79lTpr@ErYsNJL7hBSRtXCScteyLZQrAqmxbrN5OTAqgdWgBqbwG6ol1rmOLfSqTVoyzEvUb4ql4EGuRbZvAVBVpMrwAGYRNKjHMgdF3ohALRQ4mdVY/JZaDAKo/fOeXiBtaBni76@JpWZgUbc1G@GG4t4zw9W1TqhYJmSwd/sNFoiNztLDYaNvMMu2WxGLjckTcKyVZeahBbVphQ7F0mOU79B8jzLb2W7HngLCiwF9diUCAbq4Di9rmz3srE44UVNXcpiTqKjjIaaKcWJLa7TVlDRljCWSeoCD2OgRSiBDp1wqeRc9GvdwGRhRDAc6t3j@kIOCEHo/UUdJyfGipC/UU/RUjF54g@nxDbP7zkT3midA5@zpwHwTYEPSIVWSg5ezEYTaoiKislalduE1pIjWtNm01GC8aSn7/pmS1JPo4nMW/ICT@sCcI/@CS1@G7d13Le6DbYbIFo8@cEVfum9BtFaxQB6FBv4WWEkoikQCdlQ4h64vPOx7u7Ahurqm7hdcbO1@PrqgyK8IrzcVedQl1LIh7VEr1hZ0jlE7sNj/w6xxpGNaSw8/LBlJZ1qEobeuZfAY5qaRTiUKvltG/y0b6YkYePlTX9p4THEX0fPnEO/tvWwtHNUYemmjZDEaWeODLOGnChL2VGobw3Q2wttbmC3MDjP4JKcZyEOY9tMzkHe6htle33Fbnk@TSlgbgXdKjJXQ017jbPzm@PLx6ECLDc6A4GQyOkjbtAnjYd64HZR63AuD3AGaO462hBOb9jtmML3XR/@IN@BgmNJeeBdKWQvweXaUX8weDc742ex2dNBrPmYWun@51ziCF278FG07/C@Z5vNZ8hrz8C@vp/3CrPebNoHskDS48JSEnsck5POr/wiHlKRwekO8cf8fCyiB3bLa2URn9nbRQA8fBJhswLmB2iGzPXc3mRwvjdRTj@9/ufN3dnd/n88vzs5ORzeH8M9yeDQ@fPBri@yDtpJYKGME@@uCnGjNkt6ww9vR4WJ7cgIjhzGHcQrjDMY5jAsYlzCuFmGhgRYw@MLBV8CoFtscJHOQzEEyB8kcJHOQzEEyB8n8CsY1DAYDpHMOo4QB8nk1fmny8qNXFofT2auvHWXHr5/Mz84vLq@uH7/x5K2333n3vfc/@PCjjz/59LPPv/jyq6@/@fa773/48aeff/n1ZrG4fXrHCl6Kqm7kcqVabZ85H@Jm2z3/7fc//lxsL6vDv7TJOPxbi78B)), there will be 7 languages to start and I will add the characters `echoprint0` and ascii 0-31 for free to get people started.
* You may not answer twice in a row
## Scoring
Each person will have a score equal to the number valid answers they have provided. There will not necessarily be an end and I will not be accepting any answers.
## Sporting
This is a competition, but I encourage you to put fun above winning while still staying competitive (if I could make the winning criteria "fun had" I would). Some things that are not fun:
* Intentionally using characters you don't need to stunt future answers.
* Attempting to game the post id system to make future tool boxes harder to use.
* Attempting to game the post id system to make future tool boxes easier to use.
I can't prevent any one from doing these things, but I will be downvoting any answers I suspect are doing this.
On a more positive note, here are some things that are good sporting and encouraged:
* Coordinating with other users in chat.
* Saving characters for harder or more restrictive languages
[Answer]
# 2. [Cubix](https://github.com/ETHproductions/cubix), `(no@`
Third time's the charm
```
(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((no@((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
```
[Try it online!](https://tio.run/##Sy5Nyqz4/19jJIK8fAeNUTAKRgHR4P9/AA "Cubix – Try It Online")
[Next toolbox](https://tio.run/##dVZLjxs3DD6vf4VrtFgbiBY7TvdVJCjaSy9FT0Uv2SDRSJoZ2RpJ1cP2BOhv35KUxt70cdDwoyRSJEVS46c0OLt9Mdz2cfl@@WF1e8fbRq3erLaRtwbB2wMPQB5gPD3BhzOveGApKFzlImVuzIRQSu@R9s4Sb3pn7h97glrQbuOHLPaIvGFy4sb1XzFMGB6jFnXS9hZREJPLBKwzkhZjVGNrJsbja64XXy1aHkfkc6tCry1ZcKTTTw6@LY8DEpRpFR8LsYUkq/eEVDzyE6Eu215dEHt6RMaQeOBimIo3Z7wtjLasM3w/M61zZsZdCQZhCFZHWHPLRA1Tm1u4hT6jbQKDY3tCxVHBUqE8SG05qhUKTkYXxAA6CwVbjS6CA8TSlY2DkpJuVgwar01oa/noLKun7SggwuhIq8btckDvhes6CIoI2idirdQVHNSJwBG/3s9WBj4Vk8IUUzk8MuGKtsjgTLwNkVtN4pg7Eke5HrpvqYQeSVSCLyMdKFVyGR2QoJWipYwalU2EMJZq5KC/eqBGXCMdanQ7PVPhJBqiAgaXXRxTieP3oFGigzx3eFanguVWOoKYk50OqoUKIEgGI2FxUPNc1OR9RZgUnRNkR@dIjwtJVTqwnkhlA6RCXwFN5aAVmXEOG6Si0IlO6M3kB3cGYAOqAmtxiuYhxc7@9QHqhKgeFVHnDhj7PqKNA4/74sLApznAQysGlB3Uaa5yjKO2SYXi0g4Hyy0u7TgdtOMHzpxXdif3/2CfKl@MYi1vFRR9uZBX8/OMKo2GaA32ztFMNprP9A7Anu2d5QQcHro3iqph75IpgKQNb6cA1hPWpNyYA@Y9lO@cGcaZGWVUicuQi60z1A1GHrSrhTnyNGgRCzJEDipoit3IT5DCCLTFXGZbOTOmgP2sBqbwm7od5r7NI/SvY1lyPGrU79qdEkkfFLu0BcgqUuVEgmMRDKjH8wCJP6hEbRU4zXosCE9tBwHk/l2l90gHWgb/a@l4ahAedXt3VGFO7gszl7MPymRZkMN@Ho@YID4HT4@Jz3HAKPtpTyw2q0gg8FFLFqEtjWWFLsXTA9Wc0faCmJ/8dGbfAsLCgN67V4kAFW7AYh3Z624bVFA9daqAMcmGuiBiypigTrRGW52kKec8kdIDAvhGD1MBDI0KJeVDjnh4hGLgRNEd6Obqy2sOEkLZy0SfNQUnKklfyKccKRmjig7DEwfuL52J6loUQPcc6cLikGBD0aFNkYPXdFCExrYjYthoSruIFkJEa9YdR2ow0Y0U/fin0dSTqPAFT3HGRX3iIZB9KZQvx5YfpxH3wTZH5IRXn4ShL9VbUqM3PJFFaYA/CC4JZVVIwo4K9zDVxMO@d3YbvOt76n4p5NFf5nNIhuzK8KJTkmcrIZcdac/W8LGle8w2wIn1v@aAo1zTQUf4iWEkzaxKc2896BTRzeOggykUbPec/mWOOhJx8DdQ@tIxYoinjJZ/AX8/vujRw1UtoZcORreLhXcxaQk/WhCwT9r6nNabBVZv604wO8/gM11mIA5pXac3IB9sD7NV380o79ZFJawtwDqjlkbZddW4Wb5bPvywuLLqiDMguFotrso269JynnfhDLVdVmGQu8LjbrKXcGPrumMD0xd99N/4AQxMa9oL74LUvQKbN2@a@813szFxs/m4uKqab7iH7i8vGhfwwi0/4dkB/1XWzXZTrMY4/MvqdV3YVLtpE8jOQYOCpyBUfrP85v2y2T7@hz@kpfhTTxJD@H9nQAnsrmpfOVHUwN2A5By9yn1erW52Ttt1xDdenm3afH55abb3tw/bxYdr@Fe5frO8PpcmMvRPgGB@hxDXZkiwdPHrj4vr59PtLYwGxhbGWxjfw7iDcQ/jAcbjc3q2QFsY4jnAV8Honk8NSDYg2YBkA5INSDYg2YBkA5LNI4wnGBwGSDcChoShvr253d69@/Gnn3/59bff//gsVA8XFNLhePry1/Ppobv@Gw)
[Answer]
# 1. 3var (1 byte)
## Toolbox
```
['elf', 'cubix', 'sml-mlton', 'forte', 'logicode', 'python1', '3var']
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e.0@BGN`ceghilnoprtvwz}'
```
## Code
```
p
```
[Try it online!](https://tio.run/##My5LLPr/v@D/fwA "3var – Try It Online")
[Next toolbox](https://tio.run/##dVbNbiM3DD7HT@EaKGIDO0HG22STogsUvfTWF9gsdjUSPSNbI6n6sT0L9NlTktLY2f4cNPwoiRRJkRz5KQ3Obl@NsH1cflx@Wt0/iK6F1bvVNorOEHh/FAHJBxzPz/gRjQcRmhSAVoVMWRgzEVTKe6K9s8yb3pnHp56hlrzb@CHLAyFvGjUJ4/rvmEYaEaOWddL2llCQk8sMrDOKF2OEsTNTI@JbrpffLVoRR@JzB6HXli048elnh99OxIEIyXQgxkJsIcnqAyOIJ3FmtMu2hytqnp@IMSwehBym4s0FbwujbbMz4jAznXNmxrsSDMYYrB1jLWwja5i63OEt9JlskxQc2zMqjsomFSqC0laQWgl4MrkgB9RZKNpqdBEcMJaubBxAKb5ZOWi6NqmtFaOzTT1tzwGRRkdeNW6fA3kv3W6HQZFB@8SsVbqCI5wZnOjr/WxlEFMxKUwxlcNjI13RFhs8k25D5k6zOOWOolGuh@9bgdQjiyr0ZeQDFSSXyQGFWjlaYGAEmxhRLGEUqL96ACOtsQ4Y3V7PVDpFhkCg4DZXxyAJ@h41Sewwzx2dtYNghVWOIeXkTgfosAIYssFEmjjAPBc1e18RJcXOSbZj51iPCwkqHZqeSWUDpkJfAU/loIHNuIQNU1HqxCf0ZvKDuwC0gVShtTTF85hiF//6gHXCVI/A1Lkjxb6PZOMg4qG4MIhpDvDQyYFkBzjPVU5x1DZBKC7taTS5o6W94IP24iga58Hu1eEf7HPli1FNJzrAoi8X8mZ@noHSaJjWYO8dz2SjxUwfEByag7OCgaNDDwa4Gg4umQJY2ohuCmg9Y83KjTlS3mP5zplhnJlRJpW0jLnYOcPdYBRBu1qYo0iDlrEgw@QIQXPsRnHGFCagLeVys1UzYwo4zGpwir5pt6fct3nE/nUqS05ETfpdtweZ9BGaa1vArGJVTiY8lsBAerwImPgDJG6ryOmmp4Lw3HYIYO4/VPpIdOBl9L@WjucG4Um3dycIc3JfmbmcfQCTVUGO@nk8UYL4HDz/THyOA0XZTwdmqVlFBkGMWjUR29JYVvhSPP@g2gvaXlHjJz9d2PeIqDCw9x4gMeDCDVSsY/O22wYI0HOnChSTbLgLEuaMCXDmNd7qFE8555mUHhDQN/4xFdCQUaGkfMiRDo9YDIIpuYPdHL695TAhwF4n@qw5OBEUfzGfcuRkjBAdhScOwl87E9e1LIDvOfKFxSHhhqJDmyKHf9MBGI3djolpRlPaRbQYIl6z7jRyg4lu5OjHP43mnsSFL0WKMy7qkwiB7UuhfAW1/DiNtA@3OSZnuvokDX@53hKM3ojEFqUBXxBCMcpQSKKOivcw1cSjvndxG73re@5@KeTRX@dzSIbtyvhH5yTPVmEuO9aerRFjx/eYbcAT67vmSKNc01FHfMQ0LN1YSHNvPeoUyc3ToIMpFG33gt8yJx2ZOHwNlL50ihTiKZPl39Dfz6969HhVS@ylg9HdYuFdTFrhQwsD9kVbn9N6s6Dq7dwZZ@cZ@k2XGYxDWtfpDcoH2@Ns1Xc3qod1UYlrC7TOwNKAXVeNm@Uvyw8/L24snGgGBVerxU3ZZl1azvMuXKC2yyqMcjd03F32Cm9sXXdscPqqj9@Nn9DAtOa9@F9Quge0efOufdz8OBsTN5vPi5uq@U547P7qqnGBf7jlFzo70Ftl3W43xWqKw7@sXteFTbWbN6HsHDQseA5C5TfLHz4u2@3Tf/jDWoo/9SQ5hP93BpXg7qr2jRNFDd4NSs7Rq9zX1epu77RdR/rHq4tNm6@vr@328f7xafHpFt8qt@@Wt/z@IXCpUWL4cUBg/iERrl3x9vPi9uV8f4@jxbHF8R7HTzgecDzi@IDj6SW9WKQdDvkS8As4di/nFiVblGxRskXJFiVblGxRskXJ9gnHMw6BA6VbiUPhgLv7X3/7/Y@vEnq8FosmHk/f/rr9Gw "Next toolbox")
[Answer]
# 3. [Pari/GP](http://pari.math.u-bordeaux.fr/), 3 bytes
```
`
2
```
Exploits a syntax error.
[Try it online!](https://tio.run/##K0gsytRNL/j/P4HL6P9/AA "Pari/GP – Try It Online")
[Next toolbox](https://tio.run/##dVbrjyM1DP98/SvKAtpWuqx2euwL3QmBQHxBiA8IhG5Pd5kkM5M2k4Q82s5J/O2L7WTaPR4fEv/ysGM7thM/pcHZzZPhto/LN8u3F9c3vG3UxcuLTeStQfBqzwOQO2gPD9Bx5hUPLAWFq1ykzI2ZEErpPdLeWRqb3pnb@56gFrTb@CGLHSJvmJy4cf0nAyYMj1GLOml7iyiIyWUC1hlJizGqsTUT4/H5qBefLFoeRxznVoVeW9LgQKcfHfQtjwMS5GkVHwuxhSSrd4RUPPAjoS7bXp0Re7jHgSH2wMUwFWtOeFMG2rLO8N08aJ0zM@6KMwiDszrCmlsmqpva3MIt9Bl1E@gc2xMqhgqWCuVBastRrFBwMpogBpBZKOhqdGEcwJeubByUlHSzYtB4bUJby0dnWT1tSw4RRkdaNW6bA1ovXNeBU0TQPtHQSl3BXh0JHLD3ftYy8KmoFKaYyuGRCVekRQZn4m2I3Gpix9iR2Mr10H1LJfRIrBJsGelAqZLLaIAEqeQtZdSobCKEvlQjB/nVAjXiGslQo9vqmQonUREV0LnsbJhKHPu9Ro4O4tzhWZ0KllvpCGJMdjqoFjKAICmMhMVBzXNRk/UVYVB0TpAenSM5LiRV6cB6InUYIBT6CmgqB61IjZPbIBSFTnRCbyY/uBMAHVAUaItTNA8hdrKvD5AnRPWoiDq3R9/3EXUceNwVEwY@zQ4eWjEg76COc5ajH7VNKhSTtthYbnFpy@mgLd9z5ryyW7n7x/ChjotSrOWtgqQvF/Jsfp5RpdAQrc7eOprJRvOZ3gDYsZ2znIDDQ3dGUTbsXDIFELfh7RRAe8KahBuzx7iH9J0jwzgzo4wicRlisXWGqsHIg3Y1MUeeBi1iQYbIXgVNvhv5EUIYgbYYy2wj54EpYDeLgSnsU7fF2Ld5hPp1KEuOR43yXbtVIum9YueyAFFFopxIcCyCAeV4HiDwB5WorMJIsx4TwlPZQQCxf1PpLdKBlsH@mjqeCoRH2d4dVJiD@zyY09kHZbIsyGE9jwcMEJ@Dp8fE5zigl/20oyEWq0gg8FFLFqEsjWWFLsXTA9Wc0OaMmJ/8dBq@AoSJAbV3pxIBStyAyTqy59U2qKB6qlQBfZINVUHEFDFBHWmNtjpJU855IqUGBLCNHqYCGCoVSsiHHPHwCMnAiaI5UM3Vx@cjCAhlzxN91uScqCT1EE85UjBGFR26Jw7cnysT5bUogO450oXFIcGGIkObwgev6aAIjW1HxLDRlHIRLbiI1qw7jFRgohvJ@/FPo6kmUeILnuKMi/jEQyD9Uig9x5IfpxH3wTZH5IhXn4ShnvItqdEbnkijNMAPgktCWRWSsKLCPUw18LDuncwG6/qeql8KefTn@RySIb0yvOgU5NlKiGVH0rM1fGzpHrMNcGL91@yxlWva6wifGEbczKo019a9ThHNPAw6mEJBd8/pL3PQkYiD30CpS4eILp4yav4R7H33pEcPV7WEWjoY3S4W3sWkJXy0wGHvtfU5rdYLzN7WHWF2nsFnusyAH9KqTq@BP9geZqu8q1HerIpIWFuAdkYtjbKrKnG9fL28@3rxwqoDzgDjxcXiRdlmXVrO8y6coLbLygx8L/C4q@wl3Niq7ljD9Fke/RvfgoJpRXvhXZC6V6Dz@mVzu/5yViau1@8WL6rkK@6h@suzxAW8cMv3eHbAv8qq2ayL1uiHf2m9qgvrqjdtAt7ZaZDw5IQ6Xi8/e7NsNvf/YQ9JKfbUk8QQ/t8YEAK7q9hnRhQxcDfAOXuvjj5cXFxtnbariG@8POm0/vD01Gxur@8eFm8v4a9y@XJ5eUpNHNCfAMH8DiGuxRDh9vLd4vLxeH0NrYG2gfYK2lfQbqDdQruDdv@YoG@hiccAvYLWPR4b4GuArwG@Bvga4GuArwG@Bviae2gP0Dg04G4ENAlNLT//4ur61c3962@@/e77H3786edffv3t9z@E6nq4oPHPkPaH48e/Ho933eXf)
[Answer]
# 5. J, 3 Bytes
```
5|9
```
Performs 5 mod 9, outputting 4
[Next toolbox!](https://tio.run/##dVZZjxs3DH5e/wrXbbA2kFnseLtXm6AHWvShRduHogeyaaKRNDOydUWH7QnQ374lqRl70@NBw4@SSJEUyZEfUu/s@lEz28X5y/mrxeU1a2q5eL5YR9ZoBFc7FoDcwri/hw@rvGShSkHiKuMpM60HhEJ4j7RzlnjdOX1z1xFUnHZr32e@ReR1JQamXfcBU3HNYlR8nLSdRRT44DIB67SgxRilafRQsfiU6/gHi5ZFg3xuZOiUJQv2dPrBwbdhsUeCMo1kphBbSLJqS0jGPTsQarPt5AlV93fIaBIPjPdD8eaI14VRtmo1205M45yecFuCQRiC1RJWzFZ8DFOTG7iFLqNtHINjO0LFUV6lQlkQyjJUyyWcjC7wHnQWCrZqVQR7iKUrG3spBN0s7xVeG1fWMuNsNZ62oYBwrSKtarfJAb3nrm0hKDwon4i1Qo1gJw8E9vj1frIysKGYFIaYyuGx4q5oixWcibfBc6NIHHNH4CjXQ/ctJFeGRAX4YuhAIZPL6IAArRQtqaWRNhHCWErDQP/ogTS4RjqkcRs1Ue4EGiIDBrc6OSYTw@9OoUQLee7wrFYGy6xwBDEnWxVkAxVAkAxGUsVeTnNRkfcjwqRoHSc7Wkd6XEhypH3VERnZAKnQjYCmclCSzDiGDVKRq0QndHrwvTsCsAFVgbU4RfOQYkf/ugB1QlQZSdS5Hca@i2hjz@K2uNCzYQpw3/AeZXt5mKoc46hskqG4tMFR5QaXNowO2rAdq5yXdiO2/2DvR74YVTWskVD05UKezE8zsjQaomOwN45mslZsotcAttXWWUbA4aFbLakati7pAkhas2YIYD1hRcq13mHeQ/lOmaGdnlBGlbgMudg4Td3AsKDcWJiGpV7xWJAmspNBUewMO0AKI1AWc7lai4nRBWwnNTCF39RuMPdtNtC/9mXJsahQv2s2kie1k9WpLUBWkSrHExyLoEc9ngVI/F4maqvAqarDgvDUdhBA7l@P9AZpT8vg/1g6nhqER93e7WWYkvvETOXsg9RZFOSwn8c9JojPwdPPxOfYY5T9sCUWm1UkEJhRoorQlkxZoUvx9IOqj2h9QpUf/HBkrwBhYUDv3cpEgAo3YLGa6mm3DTLIjjpVwJhkTV0QMWVMkAdao61O0JRznkjpAQF8ox9TARUaFUrKhxzx8AjFwIiiO9DN5funHCSEtKeJLisKTpSCvpBPOVIyRhkdhif2zJ86E9U1L4DuOdKFxT7BhqJD6SIHf9NeEjJNS0RXRpd2ES2EiNas2xtqMNEZin58pxX1JCp8zlKccFGfWAhkXwrly7Dlx8HgPtjmiBzw6hPX9KV6S9J4zRJZlHp4QTBBKMtCEnZUuIdhTDzse0e3wbuuo@6XQjb@NJ9D0mRXhj86JXm2AnLZkfZsNTMN3WO2AU4c3zU7HOWadirCI6Yi6crKNPXWnUoR3dz3KuhCwXbP6C2zV5GIg9dA6Uv7iCEeMlr@Hvx9/aiMh6uaQy/ttWpmM@9iUgIeWhCwN8r6nJarGVZv4w4wO83gb7rMQBzScpxegXywHcyO@i6MuF4WlbA2A@u0nGtpl6PG1fzF/Paz2ZmVe5wBwcVidla2WZfm07wLR6jsfBQGuTM87iJ7ATe2HHesYPqkj96Nr8DAtKS98F8QqpNg8@p5fbN6NhkTV6vXs7NR8wXz0P3FSeMM/nDzN3h2wLfKsl6vitUYh39ZvRwXVqPdtAlkp6BBwVMQRn41/@jlvF7f/Yc/pKX4M57E@/D/zoAS2D2qfeJEUQN3A5JT9Ebu7WJxsXHKLiP@48XRptXbx8fby9ub29mrc3iqnD@fnx8rExl6EiCYfkOIn7x5SeDUW85fz84fDpeXMGoYaxhXMD6FcQ3jBsYtjLuH9GCBNjD4Q4CvhNE@HGqQrEGyBskaJGuQrEGyBskaJOs7GPcwGAyQrjkMAUPOFx9/8uzisr66@/zFF19@9fU33373/Q8//vTzL7/@9vsfDw9/vuWy7Xq12Wpj3@Xd/jC8/@vhcNue/w0)
[Answer]
# 15. [Half-Broken Car in Heavy Traffic](https://git.metanohi.name/hbcht.git/)
```
#
^
^
^
^
^
^
^
^
^
^
^
^ >>v
< ^
^ > v
ov ^
^< < <
```
Outputs is in cell -2.
[Try it online!](https://tio.run/##y0hKzij5/19ZgSsOO1RQULCzK@NSULBRiAMqUrADCoC4@WUKQFkboLCCzf//X/PydZMTkzNSAQ "Half-Broken Car in Heavy Traffic – Try It Online")
[Next Toolbox](https://tio.run/##dVbXduM2EH22vkLRycZSYjqm3DfZk957L5bPGgRBEhIIYFEkcVP@Os/OzICUvCkP4NwBMBWDAW0XGqPn94rp2o@fjG8mJ@esyMXkaDL3rFAITtfMAbmEcX0NH5ZZwVwWnMBVxkNkSnUIy9JapLXRxKvaqIurmqDktFvZJvIVIquysmPK1C8wGVfMe8n7SV1rRI53JhLQRpW06L1oC9VlzD/kav7Coma@RT4WwtVSkwcbsr418C2Yb5CgTCFYm4hOJGi5IiT8hm0JVVHXYo@y6ytkFIk7xpsuRbPD88RInVWKrQamMEYNuErJIAzJqghLpjPep6mIBZxCHdE3jsnRNaEUKM9CosyVUjNUywVYxhB4AzoTBV@VTIIN5NKkjY0oSzpZ3kg8Ni61Zq3RWW9tSQnhSnpaVWYZHUbPTVVBUriTNhCrS9mDtdgS2ODX2sFLx7rkkut8SMZ9xk3S5jOwiafBYyFJHGunxJGOh867FFy2JFpCLC0ZLEUwEQMoQStlSyjRCh0IYS5Fy0B/H4FocY10CIeJzPZBiMDwu5a4WkFNG9RbCaeZLg1BrL9KOlFAtRMk55BkvhHDnJcUaY@wACrDyWZlSI9xQfS0yWoiPevg2Ose0FR0UpAbuxRB2XEZyEKtOtuYHQAfUBV4i1M0D@W0i692cCeIylYQNWaNea49@tgwv0ohNKwbktkUvEHZRmyHGy1x6CBcCmmJI4sFLi0ZGVqyNcuMFXpZrv7BXvd8ciorWCHggptSvDg/zIjUVIj2yV4amolKsoGeA1hlK6MZAYNGV0pQ5a9MUAmQtGJF58B7wpKUK7XGGoerKnkyq4waUESVuAx1VxhFN79lTpr@ErYsNJL7hBSRtXCScteyLZQrAqmxbrN5OTAqgdWgBqbwG6ol1rmOLfSqTVoyzEvUb4ql4EGuRbZvAVBVpMrwAGYRNKjHMgdF3ohALRQ4mdVY/JZaDAKo/fOeXiBtaBni76@JpWZgUbc1G@GG4t4zw9W1TqhYJmSwd/sNFoiNztLDYaNvMMu2WxGLjckTcKyVZeahBbVphQ7F0mOU79B8jzLb2W7HngLCiwF9diUCAbq4Di9rmz3srE44UVNXcpiTqKjjIaaKcWJLa7TVlDRljCWSeoCD2OgRSiBDp1wqeRc9GvdwGRhRDAc6t3j@kIOCEHo/UUdJyfGipC/UU/RUjF54g@nxDbP7zkT3midA5@zpwHwTYEPSIVWSg5ezEYTaoiKislalduE1pIjWtNm01GC8aSn7/pmS1JPo4nMW/ICT@sCcI/@CS1@G7d13Le6DbYbIFo8@cEVfum9BtFaxQB6FBv4WWEkoikQCdlQ4h64vPOx7u7Ahurqm7hdcbO1@PrqgyK8IrzcVedQl1LIh7VEr1hZ0jlE7sNj/w6xxpGNaSw8/LBlJZ1qEobeuZfAY5qaRTiUKvltG/y0b6YkYePlTX9p4THEX0fPnEO/tvWwtHNUYemmjZDEaWeODLOGnChL2VGobw3Q2wttbmC3MDjP4JKcZyEOY9tMzkHe6htle33Fbnk@TSlgbgXdKjJXQ017jbPzm@PLx6ECLDc6A4GQyOkjbtAnjYd64HZR63AuD3AGaO462hBOb9jtmML3XR/@IN@BgmNJeeBdKWQvweXaUX8weDc742ex2dNBrPmYWun@51ziCF278FG07/C@Z5vNZ8hrz8C@vp/3CrPebNoHskDS48JSEnsck5POr/wiHlKRwekO8cf8fCyiB3bLa2URn9nbRQA8fBJhswLmB2iGzPXc3mRwvjdRTj@9/ufN3dnd/n88vzs5ORzeH8M9yeDQ@fPBri@yDtpJYKGME@@tyeDs6XGxPTmDkMOYwTmGcwTiHcQHjEsbVIiw00AIGXzj4ChjVYpuDZA6SOUjmIJmDZA6SOUjmIJlfwbiGwWCAdM5hlDBAPq/GL01efvTK4nA6e/W1o@z49ZP52fnF5dX14zeevPX2O@@@9/4HH3708Seffvb5F19@9fU33373/Q8//vTzL7/eLBa3T@9YwUtR1Y1crlSr7TPnQ9xsu@e//f7Hn4vtZXX4lzYZh99p8Tc)
[Answer]
# 6. [Forte](https://github.com/judofyr/forter)
Uses `\n 187-DENPUT`
```
1 PUT 71-18
7 END
```
[Try it online!](https://tio.run/##S8svKkn9/99QISA0RMHcUNfQgstcwdXP5f9/AA "Forte – Try It Online")
[Next toolbox](https://tio.run/##dVbrjxs1EP/c/BUhUC6R6tNtjntBK14SCIGEEBIP9Urrtb27Try260eSrcTffsyMd5MrlA/2/Mb2jGfG47H9kDpn1w@G2zbOX8xfLi6ueF2pxbPFOvLaILjc8QDkBtrdHXScecUDS0HhLBcpc2MGhFJ6j7R1lnjTOnN92xLUglYb32WxReQNkwM3rn2PYcLwGLUYB21rEQUxuEzAOiNpMkbV12ZgPD7mWvHepOWxRz7XKrTakgV72v3goK957JCgTK14X4gtJFm9JaTinh8INdm26oTY3S0yhsQDF91QvDnidWG0ZY3h24mpnTMTbkowCEOwGsKaWybGMNW5hlNoM9omMDi2JVQcFSwVyoPUlqNaoWBndEF0oLNQsNXoIthBLF1Z2Ckp6WRFp/HYhLaW986ycbcNBUQYHWnWuE0O6L1wTQNBEUH7RKyVegQ7dSCwx977ycrAh2JSGGIqm0cmXNEWGeyJpyFyrUkcc0diK8dD5y2V0D2JSvClpw2lSi6jAxK0UrSUUb2yiRDGUvUc9I8eqB7nSIfq3UZPVDiJhqiAwWUnx1Ti2O80SjSQ5w73alSw3EpHEHOy0UHVcAMIksFIWOzUNBY1eT8iTIrGCbKjcaTHhaRG2rGWyMgGSIV2BDSUg1ZkxjFskIpCJ9qhNYPv3BGADagKrMUhGocUO/rXBrgnRHWviDq3w9i3EW3seNwWFzo@TAHuatGhbKcO0y3HOGqbVCgubbCxXOPUhtNGG77jzHllN3L7L/Zu5ItRrOa1gktfDuTR@DSiSqEhOgZ742gkG80negVgy7bOcgION90aRbdh65IpgKQNr4cA1hPWpNyYHeY9XN8pM4wzE8qoEqchF2tnqBr0PGg3Xsyep06LWJAhslNBU@x6foAURqAt5jJby4kxBWwnNTCEfWo2mPs291C/9mXK8ahRv6s3SiS9U@xUFiCrSJUTCbZF0KEezwMkfqcSlVXgNGvxQngqOwgg969Geo20o2nwf7w6ngqER93e7VWYkvvETNfZB2WyLMhhPY97TBCfg6fHxOfYYZT9sCUWi1UkEHivJYtQlvoyQ4fi6YGqjmh9QswPfjiyl4DwYkDt3apEgC5uwMvas8fVNqigWqpUAWOSDVVBxJQxQR1ojpY6SUPOeSKlBgTwjR6mAhgaFUrKhxxx8wiXgRNFd6Caq3ePOUgIZU8DbdYUnKgk9ZBPOVIyRhUdhid23J8qE91rUQCdc6QDi12CBUWHNkUOXtNOEerrhohhvSnlIloIEc1Zt@@pwETXU/TjW6OpJtHFFzzFCRf1iYdA9qVQeo4lPw49roNljsgBjz4JQz3dt6R6b3gii1IHPwguCWVVSMKKCucwjImHde/oNnjXtlT9Usi9P43nkAzZleFFpyTPVkIuO9KereF9TeeYbYAdx3/NDls5pp2O8IlhJM2sSlNt3ekU0c19p4MpFGz3nP4yex2JOPgNlLq0jxjiIaPl78DfVw@693BUc6ilndH1bOZdTFrCRwsC9lpbn9NyNcPbW7sDjE4j@EyXEYhDWo7DK5APtoXRUd95L6@WRSXMzcA6o@ZG2eWocTV/Pr/5fPbEqj2OgOBiMXtSllmX5tO4C0eo7XwUBrknuN159hJObDmuWMHwSR/9G1@CgWlJa@FdkLpVYPPqWXW9ejoZE1erV7Mno@Zz7qH6y5PGGbxw89e4d8C/yrJar4rVGIf/WL0cJ1aj3bQIZKegwYWnIIz8av7Ri3m1vv2AP6Sl@DPuJLrw/86AElg9qn3kRFEDZwOSU/RG7s1icb5x2i4jvvHyaNPqzcNDtb6@uL2avTyDv8rZs/nZ8WoiMz0/iB/9dWndqaYg@8Hn8@zV7Oz@cHEBrYK2hnYJ7TNoV9Cuod1Au71P0NfQxH2AXkFr7g8VyFUgV4FcBXIVyFUgV4FcBXLVLbQ7aBwaSFcCmoSmFh9/8vTT@zN2fnH5xfMXX3719Tfffvf9Dz/@9PMvv/72@x9/3t//9Uaopu30Zmt669/m3f4wvPv7/nDTnP0D)
[Answer]
# 7. [Standard ML (MLton)](http://www.mlton.org/), 7 bytes
```
fun$n=6
```
[Try it online!](https://tio.run/##K87N0c3NKcnP@/8/rTRPJc/W7H9ZYo5CvIKtQkFRZl6JhmdeiV5JfnAJkJOuoaKhqan5HwA "Standard ML (MLton) – Try It Online") This declares a function `$` which takes any argument and returns `6`, eg. by calling with `$()`.
[New toolbox.](https://tio.run/##dVbrkxs1DP98@StCGEgyU9/c5rgXtLyHx8DA8IZpSuv1enedeG3XjyTbGfjXD0neTa5QPtj6ybZkSZZluz621qzuNTdNmD6ZPp1dXPGykLNHs1XgpUZwueMeyA20uzvoOHOSexa9xFkuYuJa9wiryjmkjTXE68bq69uGoBK0Wrs2iS0ip1nVc22b1xgmNA9BiWHQNAaRF71NBIzVFU2GILtS94yHh1wjXps0PHTIp1L6RhmyYE@7Hyz0JQ8tEpQpJe8yMZlEo7aEZNjzA6E6mUaeELu7RUaTuOei7bM3R7zKjDKs1nw7MqW1esR1DgZhCFZNWHHDxBCmMpVwCk1C2wQGxzSEsqOCxUy5r5ThqFZI2BldEC3ozBRs1SoLthBLmxe2sqroZEWr8NiEMoZ31rBhtw0FRGgVaFbbTfLovbB1DUERXrlIrKnUAHbyQGCPvXOjlZ732STfh5g3D0zYrC0w2BNPQ6RSkTjmToUtHw@ddyWF6ki0Al862rCS0SZ0oAKtFC2pZSdNJISxlB0H/YMHssM50iE7u1EjFbZCQ6TH4LKTYzJy7HcKJWrIc4t71dIbbipLEHOyVl6WcAMIksFIWGjlOBYUeT8gTIraCrKjtqTH@igH2rKGyMB6SIVmADSUvJJkxjFskIpCRdqh0b1r7RGADagKrMUhGocUO/rXeLgnRFUniVq7w9g3AW1sedhmF1rejwFuS9GibCsP4y3HOCoTpc8ubbCxVOLUhtNGG77jzDppNtX2X@zdwGejWMlLCZc@H8iD8XFE5kJDdAj2xtJI0oqP9ArAlm2t4QQsbrrVkm7D1kadAUlrXvYerCesSLnWO8x7uL5jZmirR5RQJU5DLpZWUzXouFd2uJgdj60SISNNZCe9oth1/AApjEAZzGW2qkZGZ7Ad1cAQ9rHeYO6b1EH92ucpy4NC/bbcSBHVTrJTWYCsIlVWRNgWQYt6HPeQ@K2MVFaBU6zBC@Go7CCA3L8a6DXSlqbB/@HqOCoQDnU7u5d@TO4TM15n56VOVUYW63nYY4K45B09Ji6FFqPs@i2xWKwCAc87VbEAZanLM3Qojh6o4ohWJ8Rc7/ojewkILwbU3q2MBOjierysHXtYbb30sqFK5TEmSVMVREwZ4@WB5miprWjIWkck1wAPvtHDlAFDo3xOeZ8Cbh7gMnCi6A5Uc/nqIQcJIc1poEmKghNkRT3kUwqUjEEGi@EJLXenykT3WmRA5xzowEIbYUHWoXSWg9e0lYS6siaiWadzuQgGQkRzxu47KjDBdhT98FIrqkl08QWPYcRZfeTek33R555jyQ99h@tgmSVywKOPQlNP9y3KzmkeyaLYwg@CV4SSzCRiRYVz6IfEw7p3dBu8axqqftGnzp3Gk4@a7ErwolOSJ1NBLlvSnozmXUnnmIyHHYd/zQ5bPqadCvCJYSTNjIxjbd2pGNDNfau8zhRsd5z@MnsViFj4DeS6tA8Y4j6h5a/A32f3qnNwVFOopa1W5WTibIiqgo8WBOy5Mi7FxXKCt7e0BxgdR/CZziMQh7gYhpcg700Do4O@8666WmSVMDcB67ScamkWg8bl9PH05v3JmZF7HAHB2WxylpcZG6fjuPVHqMx0EAa5M9zuPLkKTmwxrFjC8Ekf/RufgoFxQWvhXahUI8Hm5aPievnOaExYLp9NzgbN59xB9a9OGifwwk2f494e/yqLYrXMVmMc/mP1YphYDnbTIpAdgwYXnoIw8MvpW0@mxer2Df6QluzPsJNo/f87A0pg9aD2gRNZDZwNSI7RG7gXs9n5xiqzCPjGV0ebli/u74vV9ep2NXk6h7/K/NF0Pr44iB98b5F9UEaQfeOLmddBPs@fTebrw8UFtALaCtoltPegXUG7hnYD7XYdoS@hibWHXkKr14cC5AqQK0CuALkC5AqQK0CuALniFtodNA4NpAsBrYImZ2@/8@56vmTnF5dXHzz@8KOPP/n0s8@/@PKrr7/59rvvf/jxp59/@fW33/9Yr/98IWTTqs1Wd9a93O0P/au//l4fbur5Pw "Python 2 – Try It Online") Powershell is the newly added language.
[Answer]
# 23. [DStack](https://esolangs.org/wiki/DStack), 5 bytes
```
222cK
```
**Explanation**
DStack is read in pairs and moves the cursor one char at a time, so the instructions become `22`, `22`, `22`, and `cK`.
```
22 Multiplies register by 10 (initially 0), adds 2
22 Multiplies register by 10, adds 2
2c Does nothing
cK Displays number of the register
```
[Try it online!](https://tio.run/##SykuSUzO/v/fyMgo2fv/fwA)
[Next Toolbox](https://tio.run/##dVZXY9s2EH62foWqNrXUmq4pxyttuvfey3ITEARJSCCAYEhiOv51n927Ayk5bfoA3ncAbuJwoO1CY/T8VjFd@/HD8fXk5IwVuZgcTeaeFQrB6Zo5IBcwrq7gwzIrmMuCE7jKeIhMqQ5hWVqLtDaaeFUbdX5ZE5ScdivbRL5CZFVWdkyZ@hkm44p5L3k/qWuNyPHORALaqJIWvRdtobqM@btczZ9Z1My3yMdCuFpq8mBD1rcGvgXzDRKUKQRrE9GJBC1XhITfsC2hKupa7FF2dYmMInHHeNOlaHZ4nhips0qx1cAUxqgBVykZhCFZFWHJdMb7NBWxgFOoI/rGMTm6JpQC5VlIlLlSaoZquQDLGAJvQGei4KuSSbCBXJq0sRFlSSfLG4nHxqXWrDU6660tKSFcSU@ryiyjw@i5qSpICnfSBmJ1KXuwFlsCG/xaO3jpWJdccp0PybjPuEnafAY28TR4LCSJY@2UONLx0HmXgsuWREuIpSWDpQgmYgAlaKVsCSVaoQMhzKVoGejvIxAtrpEO4TCR2T4IERh@1xJXK6hpg3or4TTTpSGI9VdJJwqodoLkHJLMN2KY85Ii7REWQGU42awM6TEuiJ42WU2kZx0ce90DmopOCnJjlyIoOy4DWahVZxuzA@ADqgJvcYrmoZx28dUO7gRR2Qqixqwxz7VHHxvmVymEhnVDMpuCNyjbiO1woyUOHYRLIS1xZLHApSUjQ0u2ZpmxQi/L1b/Yq55PTmUFKwRccFOKZ@eHGZGaCtE@2UtDM1FJNtAzAKtsZTQjYNDoSgmq/JUJKgGSVqzoHHhPWJJypdZY43BVJU9mlVEDiqgSl6HuCqPo5rfMSdNfwpaFRnKfkCKyFk5S7lq2hXJFIDXWbTYvB0YlsBrUwBR@Q7XEOtexhV61SUuGeYn6TbEUPMi1yPYtAKqKVBkewCyCBvVY5qDIGxGohQInsxqL31KLQQC1f9bTc6QNLUP8/TWx1Aws6rZmI9xQ3HtmuLrWCRXLhAz2br/BArHRWXo4bPQNZtl2K2KxMXkCjrWyzDy0oDat0KFYeozyHZrvUWY72@3YU0B4MaDPrkQgQBfX4WVts7ud1QknaupKDnMSFXU8xFQxTmxpjbaakqaMsURSD3AQGz1CCWTolEsl76JH4x4uAyOK4UDnFk/vclAQQu8n6igpOV6U9IV6ip6K0QtvMD2@YXbfmehe8wTonD0dmG8CbEg6pEpy8HI2glBbVERU1qrULryGFNGaNpuWGow3LWXfP1GSehJdfM6CH3BSH5hz5F9w6cuwvfuuxX2wzRDZ4tEHruhL9y2I1ioWyKPQwN8CKwlFkUjAjgrn0PWFh31vFzZEV9fU/YKLrd3PRxcU@RXh9aYij7qEWjakPWrF2oLOMWoHFvt/mDWOdExr6eGHJSPpTIsw9Na1DB7D3DTSqUTBd8vov2UjPREDL3/qSxuPKe4iev4U4r25la2FoxpDL22ULEYja3yQJfxUQcIeSW1jmM5GeHsLs4XZYQaf5DQDeQjTfnoG8k7XMNvrO27Ls2lSCWsj8E6JsRJ62mucjd8YXzwYHWixwRkQnExGB2mbNmE8zBu3g1KPe2GQO0Bzx9GWcGLTfscMpvf66B/xGhwMU9oL70IpawE@z47y89m9wRk/m92MDnrNx8xC9y/3Gkfwwo0foW2H/yXTfD5LXmMe/uP1tF@Y9X7TJpAdkgYXnpLQ85iEfH75nHBISQqnN8Qb9/@xgBLYLaudTXRmbxcN9PBOgMkGnBuoHTLbc48nk@OlkXrq8f0vd/7OHt/e5vPz8/P7o@tD@Gc5PBof3vm1RfZOW0F2eKsQ75945J5b2Ic3o8PF9uQERg5jDuMUxn0YZzDOYVzAuFyEhQZawOALB18Bo1psc5DMQTIHyRwkc5DMQTIHyRwk80sYVzAYDJDOOYwSBsjn1fiFyYsv3Xt5cTidvfLqUXb82kl@ev/s/OLy6sHrbzx8862333n3vfc/@PCjjz/59LPPv/jyq6@/@fa773/48aeff/n1erG4@e3RY1aUoqobuVStNvaJ8yGuN9vu6e9//PnXYntRHf6tTcbhf1v8Aw)
[Answer]
# 27. [Assembly (x64, Linux, as)](https://sourceware.org/binutils/docs/as/index.html)
```
.text
.global _start
_start:
movl $len,%edx
movl $msg,%ecx
movl $1,%ebx
movl $4,%eax
int $0x80
movl $0,%ebx
movl $1,%eax
int $0x80
.data
msg:
.byte 0b110010,0b110110
len = . - msg
```
[Try it online!](https://tio.run/##Xc7BCsMwCAbgu0/hobu1QWGHUdizDLOGMjAtLDLSp89ka2EMBP3kR5RSUo66DVJaC5aqAWKYdY2ieCsmT4NvGyGvL8VO09Kf0lR35jI77wfZEQ@cHVLhsRh2VC@0r@k3w/@ZMIkJ@NkRQtwsIUVmIqb@M3iBv4BXDDigx6C1Nw "Assembly (x64, Linux, as) – Try It Online")
# Explanation
I don't really know Assembly as, and information online seems hard to find ,so this is modified from the [Hello World test on TIO](https://github.com/TryItOnline/TioTests/blob/master/HelloWorldTests/assembly-as.json).
The main issue here is that we lack the `2` byte, (turns out we did, but hey looks like I saved a 2 for the next answer) this makes it relatively hard to print `26`. We can't use raw ascii or even Hexadecimal (`0x32`) so I ended up using binary.
```
msg:
.byte 0b110010,0b110110
```
Tells it to output the two bytes `2` and `6`.
[Next toolbox](https://tio.run/##dVZZf@M0EH9uPkUIP0gCdVmn9ILlvu/7bMpWlmVbiSxpdSTxcnxrnsvMyE66sDzI8x9Jc2o0su1CY/TiTjFd@/Eb4@vJgzNW5GJyPFl4VigEpxvmgFzAuLqCD8usYC4LTuAq4yEypTqEZWkt0tpo4lVt1PllTVBy2q1sE/kakVVZ2TFl6qeYjCvmveT9pK41Isc7Ewloo0pa9F60heoy5u9zNX9qUTPfIh8L4WqpyYMtWd8Z@BbMN0hQphCsTUQnErRcExJ@y3aEqqhrcUDZ1SUyisQd402XotnjRWKkzirF1gNTGKMGXKVkEIZkVYQl0xnv01TEAk6hjugbx@TomlAKlGchUeZKqRmq5QIsYwi8AZ2Jgq9KJsEGcmnSxkaUJZ0sbyQeG5das9borLe2ooRwJT2tKrOKDqPnpqogKdxJG4jVpezBRuwIbPFr7eClY11yyXU@JOM@4yZp8xnYxNPgsZAkjrVT4kjHQ@ddCi5bEi0hlpYMliKYiAGUoJWyJZRohQ6EMJeiZaC/j0C0uEY6hMNEZocgRGD43UhcraCmDeqthNNMl4Yg1l8lnSig2gmSc0gy34hhzkuKtEdYAJXhZLMypMe4IHraZDWRnnVw7HUPaCo6KciNfYqg7LgMZKFWnW3MHoAPqAq8xSmah3Lax1c7uBNEZSuIGrPBPNcefWyYX6cQGtYNyWwK3qBsI3bDjZY4dBAuhbTCkcUCl1aMDK3YhmXGCr0q1/9ir3o@OZUVrBBwwU0pnp4fZkRqKkT7ZK8MzUQl2UDPAKyztdGMgEGjayWo8tcmqARIWrGic@A9YUnKldpgjcNVlTyZVUYNKKJKXIa6K4yim98yJ01/CVsWGsl9QorIRjhJuWvZDsoVgdRYt9miHBiVwHpQA1P4DdUK61zHFnrVNi0Z5iXqN8VK8CA3Iju0AKgqUmV4ALMIGtRjmYMib0SgFgqczGosfkstBgHU/llPz5E2tAzx99fEUjOwqNuarXBDcR@Y4epaJ1QsEzLYu/0WC8RGZ@nhsNE3mGXbrYnFxuQJONbKMvPQgtq0Qodi6THK92hxQJntbLdnTwHhxYA@uxaBAF1ch5e1ze53ViecqKkrOcxJVNTxEFPFOLGjNdpqSpoyxhJJPcBBbPQIJZChUy6VvIsejXu4DIwohgOdWzy5z0FBCH2YqKOk5HhR0hfqKXoqRi@8wfT4htlDZ6J7zROgc/Z0YL4JsCHpkCrJwcvZCEJtURFRWatSu/AaUkRr2mxbajDetJR9/1hJ6kl08TkLfsBJfWDOkX/BpS/D9u67FvfBNkNkh0cfuKIv3bcgWqtYII9CA38LrCQURSIBOyqcQ9cXHva9fdgQXV1T9wsutvYwH11Q5FeE15uKPOoSatmQ9qgVaws6x6gdWOz/YTY40jFtpIcfloykMy3C0Fs3MngMc9tIpxIF3y2j/5at9EQMvPypL209priL6PkTiPfmTrYWjmoMvbRRshiNrPFBlvBTBQl7JLWNYTYf4e0tzA5mhxl8ktMM5CHM@uk5yDtdw2yv76Qtz2ZJJayNwDslxkroWa9xPn44vnhtdKTFFmdAcDIZHaVt2oTxMG/cHko97oVB7gjNnURbwonN@h1zmD7oo3/Ea3AwzGgvvAulrAX4PD/Oz@cvDM74@fxmdNRrPmEWun950DiCF278CG07/C@Z5Yt58hrz8B@vZ/3CvPebNoHskDS48JSEnsck5IvLZ4RDSlI4vSHeuP@PBZTAblntbaIzB7tooIf3Akw24NxA7ZDZnrudTE5WRuqZx/e/3Ps7v727yxfn51cXo@sp/LNMj8fT4TVC/MxixYX7fRF5agLT42n/kk9vRtPl7sEDGDmMBYxTGK/COINxDuMCxuUywLeAwZcOvgJGtdzlIJeDXA5yOcjlIJeDXA5yOcjllzCuYDAYIJ1zGCUMkM@r5ybPv7iczuYvvfzK6fnF1esP33zr7Xfefe/9Dz786ONPPv3s8y@@/Orrb7797vsffvzp519@vV4ub367rZrV2j6O2ye///HnX8vdRTX9W5uMw3@0@Ac)
[Answer]
# 35. [ELF 32-bit LSB executable (Linux)](https://refspecs.linuxfoundation.org/elf/elf.pdf), 48 bytes
```
0000000: 7f 45 4c 46 01 00 00 00 00 00 00 00 00 90 43 0d .ELF..........C.
0000010: 02 00 03 00 19 90 43 0d 19 90 43 0d 04 00 00 00 ......C...C.....
0000020: b9 2e 90 43 0d b2 0d cd 80 cc 20 00 01 00 33 34 ...C...... ...34
```
I've done it! I have conquered the elusive ELF. ELF has been the first language in the list ever since [the first toolbox](https://tio.run/##dVbXduM2EH22vkLRycZSYjqm3DfZk957L5bPGgRBEhIIYFEkcVP@Os/OzICUvCkP4NwBMBWDAW0XGqPn94rp2o@fjG8mJ@esyMXkaDL3rFAITtfMAbmEcX0NH5ZZwVwWnMBVxkNkSnUIy9JapLXRxKvaqIurmqDktFvZJvIVIquysmPK1C8wGVfMe8n7SV1rRI53JhLQRpW06L1oC9VlzD/kav7Coma@RT4WwtVSkwcbsr418C2Yb5CgTCFYm4hOJGi5IiT8hm0JVVHXYo@y6ytkFIk7xpsuRbPD88RInVWKrQamMEYNuErJIAzJqghLpjPep6mIBZxCHdE3jsnRNaEUKM9CosyVUjNUywVYxhB4AzoTBV@VTIIN5NKkjY0oSzpZ3kg8Ni61Zq3RWW9tSQnhSnpaVWYZHUbPTVVBUriTNhCrS9mDtdgS2ODX2sFLx7rkkut8SMZ9xk3S5jOwiafBYyFJHGunxJGOh867FFy2JFpCLC0ZLEUwEQMoQStlSyjRCh0IYS5Fy0B/H4FocY10CIeJzPZBiMDwu5a4WkFNG9RbCaeZLg1BrL9KOlFAtRMk55BkvhHDnJcUaY@wACrDyWZlSI9xQfS0yWoiPevg2Ose0FR0UpAbuxRB2XEZyEKtOtuYHQAfUBV4i1M0D@W0i692cCeIylYQNWaNea49@tgwv0ohNKwbktkUvEHZRmyHGy1x6CBcCmmJI4sFLi0ZGVqyNcuMFXpZrv7BXvd8ciorWCHggptSvDg/zIjUVIj2yV4amolKsoGeA1hlK6MZAYNGV0pQ5a9MUAmQtGJF58B7wpKUK7XGGoerKnkyq4waUESVuAx1VxhFN79lTpr@ErYsNJL7hBSRtXCScteyLZQrAqmxbrN5OTAqgdWgBqbwG6ol1rmOLfSqTVoyzEvUb4ql4EGuRbZvAVBVpMrwAGYRNKjHMgdF3ohALRQ4mdVY/JZaDAKo/fOeXiBtaBni76@JpWZgUbc1G@GG4t4zw9W1TqhYJmSwd/sNFoiNztLDYaNvMMu2WxGLjckTcKyVZeahBbVphQ7F0mOU79B8jzLb2W7HngLCiwF9diUCAbq4Di9rmz3srE44UVNXcpiTqKjjIaaKcWJLa7TVlDRljCWSeoCD2OgRSiBDp1wqeRc9GvdwGRhRDAc6t3j@kIOCEHo/UUdJyfGipC/UU/RUjF54g@nxDbP7zkT3midA5@zpwHwTYEPSIVWSg5ezEYTaoiKislalduE1pIjWtNm01GC8aSn7/pmS1JPo4nMW/ICT@sCcI/@CS1@G7d13Le6DbYbIFo8@cEVfum9BtFaxQB6FBv4WWEkoikQCdlQ4h64vPOx7u7Ahurqm7hdcbO1@PrqgyK8IrzcVedQl1LIh7VEr1hZ0jlE7sNj/w6xxpGNaSw8/LBlJZ1qEobeuZfAY5qaRTiUKvltG/y0b6YkYePlTX9p4THEX0fPnEO/tvWwtHNUYemmjZDEaWeODLOGnChL2VGobw3Q2wttbmC3MDjP4JKcZyEOY9tMzkHe6htle33Fbnk@TSlgbgXdKjJXQ017jbPzm@PLx6ECLDc6A4GQyOkjbtAnjYd64HZR63AuD3AGaO462hBOb9jtmML3XR/@IN@BgmNJeeBdKWQvweXaUX8weDc742ex2dNBrPmYWun@51ziCF278FG07/C@Z5vNZ8hrz8C@vp/3CrPebNoHskDS48JSEnsck5POr/wiHlKRwekO8cf8fCyiB3bLa2URn9nbRQA8fBJhswLmB2iGzPXc3mRwvjdRTj@9/ufN3dnd/n88vzs5ORzeH8M9yeDQ@fPBri@yDtpJYKGME@@uCnGjNkt6ww9vR4WJ7cgIjhzGHcQrjDMY5jAsYlzCuFmGhgRYw@MLBV8CoFtscJHOQzEEyB8kcJHOQzEEyB8n8CsY1DAYDpHMOo4QB8nk1fmny8qNXFofT2auvHWXHr5/Mz84vLq@uH7/x5K2333n3vfc/@PCjjz/59LPPv/jyq6@/@fa773/48aeff/n1ZrG4fXrHCl6Kqm7kcqVabZ85H@Jm2z3/7fc//lxsL6vDv7TJOPxbi78B). Now we can move on.
I've never used or even heard of ELF before, so this one was an adventure to figure out. I eventually copied much of Dennis' [32 bit](https://codegolf.stackexchange.com/a/84154/70606) Hello, World! program ([64 bit version here](https://codegolf.stackexchange.com/a/84156/70606)). I modified it to print 33 and was able to remove a line of bytes.
Chars used: `\x00\x01\x02\x03\x04\r\x19 .34CEFL\x7f\x80\x90\xb2\xb9\xcc\xcd`
[Try it online!](https://tio.run/##bc49DsMwCAXgvad4J0DPQH@ctUqmniJOMvX@qxvbaZ2hCBADfGJ9bzmzxYD7Br/CE/wGBpD/MxJu4ALI@JrkF0@5VCjsFLUuW@kh9pPzTO8mvkQrOSjdqTlC1341a@lpwYNICdqE@q0ZzCvVDCmjec4f)
[Next Toolbox](https://tio.run/##dVZZc9s2EH62foWqNrXUBq6pxFcmPaczvabn9LbdBARBEhIIIDgkMe30X/fZ3V2QktPjAdxvAeyJxYKuj601yzvNTROm706vZ6dnvCzk7OFsGXipETzacA/kAsbVFXw4c5J7Fr3EVS5i4lr3CKvKOaSNNcTrxurzy4agErRbuzaJNSKnWdVzbZtXGCY0D0GJYdI0BpEXvU0EjNUVLYYgu1L3jIf7XCNeWTQ8dMinUvpGGfJgS9Z3Fr4lDy0SlCkl7zIxmUSj1oRk2PIdoTqZRh4Qu7pERpO456LtczR7vMyMMqzWfD0ypbV6xHVOBmFIVk1YccPEkKYylXAKTULfBCbHNIRyoILFTLmvlOGoVkiwjCGIFnRmCr5qlQVbyKXNG1tZVXSyolV4bEIZwztr2GBtRQkRWgVa1XaVPEYvbF1DUoRXLhJrKjWAjdwR2OLXudFLz/vsku9DzMYDEzZrCwxs4mmIVCoSx9qpcOTjofOupFAdiVYQS0cGKxltwgAq0ErZklp20kRCmEvZcdA/RCA7XCMd0mMi2SEIGTl@NwpXa6hpi3pr6Q03lSWI9VcrL0uodoLkHBIWWjnOBUWRDggLoLaCbNaW9Fgf5UBb1hAZWA/H3gyAppJXktzYpwjKTqhIFhrdu9buAfiAqsBbnKJ5KKd9fI2HO0FUdZKotRvMcxPQx5aHdQ6h5f2YzLYULcq2cjfeaIXDROlzSCscLJW4tOJkaMU3nFknzapa/4O9GvjsFCt5KeGC20q@Oj/OyNxUiA7JXlmaSVrxkZ4BWLO1NZyARaNrLany1zbqDEha87L34D1hRcq13mCNw1VVIpvVVo8ooUpchrorraab33Gv7HAJOx5bJUJGmshGekW56/gOyhWBMli3bFmNjM5gPaqBKfzGeoV1blIHvWqblywPCvXbciVFVBvJDi0AqopUWRHBLIIW9TjuochbGamFAqdYg8XvqMUggNo/G@g50paWIf7hmjhqBg51O7uVfizuAzNeXeelTlVGFnt32GKBuOQdPRwuhRaz7Po1sdiYAgHPO1WxAC2oyyt0KI4eo2KPlgfEXO/6PfsIEF4M6LNrGQnQxfV4WTt2v7N66WVDXcljTpKmjoeYKsbLHa3RVlvRlLWOSO4BHmKjRygDhk75XPI@BTQe4DJwohgOdG758j4HBSHNYaJJipITZEVfqKcUqBiDDBbTE1ruDp2J7rXIgM450IGFNsKGrEPpLAcvZysJdWVNRLNO53YRDKSI1ozddtRggu0o@@GFVtST6OILHsOIs/rIvSf/os9fju099B3ug22WyA6PPgpNX7pvUXZO80gexRb@FnhFKMlMInZUOId@KDzse/uwIbqmoe4XfercYT75qMmvBK83FXkyFdSyJe3JaN6VdI7JeLA4/MNscORj2qgAPyyMpJmRceytGxUDhrltldeZgu@O03/LVgUiFl7@3Je2AVPcJ/T8JcR7e6c6B0c1hV7aalVOJs6GqCr4qYKEPVPGpThfTPD2lnYHs@MMPsl5BvIQ58P0AuS9aWB20HfSVWfzrBLWJuCdllMtzXzQuJg@nV48mRwZucUZEJzNJkd5m7FxOs5bv4fKTAdhkDtCcyfJVXBi82HHAqYP@ugf8RocjHPaC@9CpRoJPi8eFueLB6MzYbG4nRwNmk@4g@5fHTRO4IWbPkPbHv9L5sVykb3GPPzL6/mwsBj8pk0gOyYNLjwlYeAxCcXy8j/CISU5nMGQaP3/xwJKYLeq9zbRmYNdNDDAewFmG3BuoHbM7MA9n81OVlaZecD3v9r7u3h@d1cszy@XjyfXx@MzdPxwekyXGgE9vQj2bwYy@ReFkLXHt5Pjm93pGYxzGBcwLm/ijQFawhAwJIz6ZlecwihgLGE8gvEYBsgVIFeAXHEJg8MAuQLkigoGyBb1a7PX33jw5s3x4q23H7J3Tovl2fnF5dWTp@@@9/4HH3708Seffvb5F19@9fU33373/Q8//vTzL79e39zc/vbsOYefiNVady982u76l7//8efxX8YyAX/I8m8)
[Answer]
# 9. [JavaScript (Babel Node)](https://babeljs.io/), 14 bytes
```
console.log`8`
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNFNSkxKzdHNy09J/f8/OT@vOD8nVS8nPz3BIuH/fwA "JavaScript (Babel Node) – Try It Online")
Miraculously all the characters needed were available.
[Next toolbox](https://tio.run/##dVbpd9s2DP8c/xWe9zrbb1UWOUvidO3u@76vOGspipJoUyTLw7b63vavZwAo2emODxR@AAkQAEFQtguN0Ys7xXTtx0/GN5OzC1bkYvJwsvCsUAjOt8wBuYJxfQ0fllnBXBacwFnGQ2RKdQjL0lqktdHEq9qoy2VNUHJarWwT@QaRVVnZMWXql5iMK@a95L1Q1xqR452JBLRRJU16L9pCdRnz97mavzSpmW@Rj4VwtdTkwY523xv4Fsw3SFCnEKxNRCcStNwQEn7H9oSqqGtxRNn1EhlF6o7xpkvRHPAiMVJnlWKbgSmMUQOuUjIIQ7IqwpLpjPdpKmIBp1BH9I1jcnRNKAXKs5Aoc6XUDM1yATtjCLwBm4mCr0omxQZyadLCRpQlnSxvJB4bl1qz1uis321NCeFKeppVZh0dRs9NVUFSuJM2EKtL2YOt2BPY4dfawUvHuuSS63xIm/uMm2TNZ7AnngaPhSR1rJ0SRzoeOu9ScNmSagmxtLRhKYKJGEAJVilbQolW6EAIcylaBvb7CESLc2RDtGYtB8pNiY4Ih8nNjoGJwPC7lahRQZ0b3KsSTjNdGoJYk5V0ooAbQJAcRpL5RgwyLyn6HmFRVIaTH5UhO8YF0dMmq4n0rINSqHtAouikIDcOaYNS5DLQDrXqbGMOAHxAU@AtikgOJXaIr3ZwT4jKVhA1Zou5rz362DC/SSE0rBsS3BS8Qd1G7IdbjnmUOgiXQlrjyGKBU2tGG63ZlmXGCr0uN/9gr3s@OZUVrBBw6dOB3JMPEpEaDdE@2WtDkqgkG@gFgE22MZoRMLjpRgm6DRsTVAKkrVjROfCesCTjSm2x7uH6DpWhjBpQRJM4DbVYGEXdoGVOmv5itiw0kvuEFJGtcJJy17I9lDACqbGWs0U5MCqBzWAGRPgN1RprX8cW@tcuTRnmJdo3xVrwILciO7YFqCoyZXiAbRE0aMcyB4XfiEBtFTiZ1XghLLUdBFD7Fz29RNrQNMTfXx1LDcKibWt2wg3FfWSG62ydULFMyGA/9zssEBudpcfERt9glm23IRablSfgWCvLzENbatMMHYqlByo/oMURZbaz3YE9B4QXA3rvRgQCdHEdXtY2u99tnXCipk7lMCdRURdETBXjxJ7maKkpSWSMJZJ6gIPY6GFKIEOnXCp5Fz1u7uEyMKIYDnRz8eI@BwUh9FFQR0nJ8aKkL9RT9FSMXniD6fENs8fORPeaJ0Dn7OnAfBNgQbIhVdKD17QRhNqiIqKyVqV24TWkiOa02bXUYLxpKfv@uZLUk@jicxb8gJP5wJwj/4JLX4Yt33ctroNlhsgejz5wRV@6b0G0VrFAHoUG/iBYSSiKRAJ2VDiHri887HuHsCG6uqbuF1xs7VEeXVDkV4QXnYo86hJq2ZD1qBVrCzrHqB3s2P/XbHGkY9pKDz8xGWlnWoSht25l8BjmrpFOJQq@W0b/MjvpiRj4G0h9aecxxV1Ez19AvLd3srVwVGPopY2SxWhkjQ@yhB8tSNhTqW0Ms/kIb29h9iAdJPhMJwnkIcx68Rz0na5B2ts7bcuLWTIJcyPwTomxEnrWW5yPH4@vHo1OtNihBBQnk9FJWqZNGA9y4w5Q6nGvDHonuN1ptCWc2KxfMQfx0R79N96Ag2FGa@FdKGUtwOf5w/xy/mBwxs/nt6OT3vIps9D9y6PFEbxw46e4t8N/lVm@mCevMQ//8nrWT8x7v2kR6A5JgwtPSej5@fiVJ@N8sfyPeMhKiqffiTfu/4MBI7C6N3sviGQGzgY0h@z13LPJ5HRtpJ55fOPLg0/zZ3d3@eLy/Ho5upnCv8r04Xg6vDiI7/3eInuvjSQWyhZB322nt6Ppan92BiOHsYBxDuNNGBcwLmFcwViuwkoDLWDwlYOvgFGt9jlo5qCZg2YOmjlo5qCZg2YOmvkSxjUMBgO0cw6jhAH6eTV59cFrq@n89eyNs/z84mp5/eitx2@/8@5773/w4Ucff/LpZ59/8eVXX3/z7Xff//DjTz//8utvv9@sVrd/PGVVI9eb1j53Ybvbdy/@/Gu1v6qmfwM) New language: pylons (Should be easy ;).
[Answer]
# 18. C# (.NET Core), 33 bytes
```
()=>System.Console.WriteLine(17);
```
[Try it online!](https://tio.run/##Sy7WTc4vSv3/PzknsbhYwbGaS0GhuCSxJDNZoSw/M0XBNzEzT0MTJKoAEUjT0LS1C64sLknN1XPOzyvOz0nVCy/KLEn1ycxL1TA017QGqwUqAzFquWr//wcA)
[Next Toolbox](https://tio.run/##dVZZcyM1EH6Of4UJLLFhFTLOJptsQXEUN8VZQAFx2NVoNDOyNZJWh@1Zjn/Nc@huzdhZjgdNfy2pT7Va4/rYWrO409w0YfrO9Ob47IKXhTx@eLwIvNQIzjfcA3kM4/oaPpw5yT2LXuIqFzFxrXuEVeUc0sYa4nVj9eVVQ1AJ2q1dm8QakdOs6rm2zUsME5qHoMQwaRqDyIveJgLG6ooWQ5BdqXvGw32uES8tGh465FMpfaMMebAl6zsL35KHFgnKlJJ3mZhMolFrQjJs@Y5QnUwjD4hdXyGjSdxz0fY5mj1eZEYZVmu@HpnSWj3iOieDMCSrJqy4YWJIU5lKOIUmoW8Ck2MaQjlQwWKm3FfKcFQrJFjGEEQLOjMFX7XKgi3k0uaNrawqOlnRKjw2oYzhnTVssLaihAitAq1qu0oeoxe2riEpwisXiTWVGsBG7ghs8evc6KXnfXbJ9yFm44EJm7UFBjbxNEQqFYlj7VQ48vHQeVdSqI5EK4ilI4OVjDZhABVopWxJLTtpIiHMpew46B8ikB2ukQ7pMZHsEISMHL8bhas11LRFvbX0hpvKEsT6q5WXJVQ7QXIOCQutHOeCokgHhAVQW0E2a0t6rI9yoC1riAysh2NvBkBTyStJbuxTBGUnVCQLje5da/cAfEBV4C1O0TyU0z6@xsOdIKo6SdTaDea5Cehjy8M6h9DyfkxmW4oWZVu5G2@0wmGi9DmkFQ6WSlxacTK04hvOrJNmVa3/wV4PfHaKlbyUcMFtJV@eH2dkbipEh2SvLM0krfhILwCs2doaTsCi0bWWVPlrG3UGJK152XvwnrAi5VpvsMbhqiqRzWqrR5RQJS5D3ZVW083vuFd2uIQdj60SISNNZCO9otx1fAflikAZrFu2qEZGZ7Ae1cAUfmO9wjo3qYNetc1LlgeF@m25kiKqjWSHFgBVRaqsiGAWQYt6HPdQ5K2M1EKBU6zB4nfUYhBA7V8M9BJpS8sQ/3BNHDUDh7qd3Uo/FveBGa@u81KnKiOLvTtssUBc8o4eDpdCi1l2/ZpYbEyBgOedqliAFtTlFToUR49RsUeLA2Kud/2ePQeEFwP67FpGAnRxPV7Wjt3vrF562VBX8piTpKnjIaaK8XJHa7TVVjRlrSOSe4CH2OgRyoChUz6XvE8BjQe4DJwohgOdW764z0FBSHOYaJKi5ARZ0RfqKQUqxiCDxfSElrtDZ6J7LTKgcw50YKGNsCHrUDrLwcvZSkJdWRPRrNO5XQQDKaI1Y7cdNZhgO8p@eK4V9SS6@ILHMOKsPnLvyb/o85djew99h/tgmyWyw6OPQtOX7luUndM8kkexhb8FXhFKMpOIHRXOoR8KD/vePmyIrmmo@0WfOneYTz5q8ivB601FnkwFtWxJezKadyWdYzIeLA7/MBsc@Zg2KsAPCyNpZmQce@tGxYBhblvldabgu@P037JVgYiFlz/3pW3AFPcJPX8B8d7eqc7BUU2hl7ZalZOJsyGqCn6qIGFPlXEpzuYTvL2l3cHsOINPcp6BPMTZMD0HeW8amB30nXbVxSyrhLUJeKflVEszGzTOp29PHz@ZHBm5xRkQPD6eHOVtxsbpOG/9HiozHYRB7gjNnSZXwYnNhh1zmD7oo3/EG3AwzmgvvAuVaiT4PH9YXM4fjM6E@fx2cjRoPuUOun910DiBF276FG17/C@ZFYt59hrz8C@vZ8PCfPCbNoHsmDS48JSEgcckFIur/wiHlORwBkOi9f8fCyiB3are20RnDnbRwADvBZhtwLmB2jGzA/fs@Ph0ZZWZBXz/q72/82d3d8Xi8uJsMbk5gX@Wk4fTk3u/tsjeayvIHm4JcuPLhfjw4J/cTk6Wu7MzGAWMBYxzGI9gXMC4hPEYxtUyLg3QEoZYevhKGPVyV4BkAZIFSBYgWYBkAZIFSBYgWVzBuIbBYYB0IWBUMEC@qKevHL/62oPXlydvvPmQvXW2OH90cXl1/eTtd997/4MPP/r4k08/@/yLL7/6@ptvv/v@hx9/@vmXm@Xy9tenz3gpqrppV2v3PG22uxe//f7Hn8vd4/rkL2OZgD9q@Tc)
[Answer]
# 20. [TRANSCRIPT](https://esolangs.org/wiki/TRANSCRIPT), 45 bytes
```
You can see a Q here.
>SET Q TO 19
>X Q
>QUIT
```
**Explanation:**
TRANSCRIPT is designed to resemble interactive fiction scripts. So rather than using variables, objects and NPCs are used. Commands and dialog (essentially comments) are mixed together.
```
You can see a Q here. Creates an object named Q
>SET Q TO 19 Assign Q to 19
>X Q Display Q
>QUIT End the program
```
Chars used: `.19>EIOQSTUXYZacehnorsu`
[Try it online!](https://tio.run/##KylKzCtOLsosKPn/PzK/VCE5MU@hODVVIVEhUCEjtShVj8su2DUEyAnxVzC05LKLUAjksgsM9Qz5/x8A)
[Next Toolbox](https://tio.run/##dVZZk@M0EH6e/IowsEwCq2Gc2bmW3eIsoLiK4gGqmAy7sizbSmRJqyOJl@Nf8zx0t@xkluNB7q8l9alWy66PrTWLe81NE6bPp7fHZxe8LOTx4@NF4KVGcL7hHsgVjJsb@HDmJPcseomrXMTEte4RVpVzSBtriNeN1ZfXDUElaLd2bRJrRE6zqufaNm8wTGgeghLDpGkMIi96mwgYqytaDEF2pe4ZDw@5RryxaHjokE@l9I0y5MGWrO8sfEseWiQoU0reZWIyiUatCcmw5TtCdTKNPCB2c42MJnHPRdvnaPZ4kRllWK35emRKa/WI65wMwpCsmrDihokhTWUq4RSahL4JTI5pCOVABYuZcl8pw1GtkGAZQxAt6MwUfNUqC7aQS5s3trKq6GRFq/DYhDKGd9awwdqKEiK0CrSq7Sp5jF7YuoakCK9cJNZUagAbuSOwxa9zo5ee99kl34eYjQcmbNYWGNjE0xCpVCSOtVPhyMdD511JoToSrSCWjgxWMtqEAVSglbIlteykiYQwl7LjoH@IQHa4Rjqkx0SyQxAycvxuFK7WUNMW9dbSG24qSxDrr1ZellDtBMk5JCy0cpwLiiIdEBZAbQXZrC3psT7KgbasITKwHo69GQBNJa8kubFPEZSdUJEsNLp3rd0D8AFVgbc4RfNQTvv4Gg93gqjqJFFrN5jnJqCPLQ/rHELL@zGZbSlalG3lbrzRCoeJ0ueQVjhYKnFpxcnQim84s06aVbX@B3sz8NkpVvJSwgW3lXxzfpyRuakQHZK9sjSTtOIjvQCwZmtrOAGLRtdaUuWvbdQZkLTmZe/Be8KKlGu9wRqHq6pENqutHlFClbgMdVdaTTe/417Z4RJ2PLZKhIw0kY30inLX8R2UKwJlsG7ZohoZncF6VANT@I31CuvcpA561TYvWR4U6rflSoqoNpIdWgBUFamyIoJZBC3qcdxDkbcyUgsFTrEGi99Ri0EAtX8x0EukLS1D/MM1cdQMHOp2div9WNwHZry6zkudqows9u6wxQJxyTt6OFwKLWbZ9WtisTEFAp53qmIBWlCXV@hQHD1GxR4tDoi53vV79hwQXgzos2sZCdDF9XhZO/aws3rpZUNdyWNOkqaOh5gqxssdrdFWW9GUtY5I7gEeYqNHKAOGTvlc8j4FNB7gMnCiGA50bvn6IQcFIc1hokmKkhNkRV@opxSoGIMMFtMTWu4OnYnutciAzjnQgYU2woasQ@ksBy9nKwl1ZU1Es07ndhEMpIjWjN121GCC7Sj74ZVW1JPo4gsew4iz@si9J/@iz1@O7T30He6DbZbIDo8@Ck1fum9Rdk7zSB7FFv4WeEUoyUwidlQ4h34oPOx7@7Ahuqah7hd96txhPvmoya8ErzcVeTIV1LIl7clo3pV0jsl4sDj8w2xw5GPaqAA/LIykmZFx7K0bFQOGuW2V15mC747Tf8tWBSIWXv7cl7YBU9wn9Pw1xHt3rzoHRzWFXtpqVU4mzoaoKvipgoS9UMalOJtP8PaWdgez4ww@yXkG8hBnw/Qc5L1pYHbQd9pVF7OsEtYm4J2WUy3NbNA4nz6bXj2dHBm5xRkQPD6eHOVtxsbpOG/9HiozHYRB7gjNnSZXwYnNhh1zmD7oo3/EW3AwzmgvvAuVaiT4PH9cXM4fjc6E@fxucjRoPuUOun910DiBF276Am17/C@ZFYt59hrz8C@vZ8PCfPCbNoHsmDS48JSEgcckFIvr/wiHlORwBkOi9f8fCyiB3are20RnDnbRwAAfBJhtwLmB2jGzA/fy@Ph0ZZWZBXz/q72/85f398Xi8qJ4Mrk9gX@Wk8fTkwe/tsg@aCvIjm8V4sMTj1z@Czq5m5wsd2dnMAoYCxjnMJ7AuIBxCeMKxvUyLg3QEoZYevhKGPVyV4BkAZIFSBYgWYBkAZIFSBYgWVzDuIHBYYB0IWBUMEC@qKdvHb/9zqN3lyez@XvvP2YfnC3On1xcXl0//fDZ848@/uTTzz7/4suvvv7m2@@@/@HHn37@5Xa5vPv1xcuyqhu1WuvOvYqb7a5//dvvf/y53F3VJ38ZywT8Tcu/AQ)
[Answer]
# 29. [Pushy](https://github.com/FTcode/Pushy), `TL#`
```
TTTTTTTTTTTTTTTTTTTTTTTTTTTTL#
```
This pushes `10` to the stack 28 times, then gets the length of the stack and prints it.
[Try it online!](https://tio.run/##Kygtzqj8/z8ED/BR/v8fAA "Pushy – Try It Online")
[Next toolbox](https://tio.run/##dVbZdts2EH22vkLVaSqpNd1Qjrc06b73dD9dLTcBQZCEBAIIFklMl7/uszszICWnTR/AuQNgVgwGtF1ojF7cKqZrP348vp7cP2NFLibHk4VnhUJwumEOyAWMqyv4sMwK5rLgBK4yHiJTqkNYltYirY0mXtVGnV/WBCWn3co2ka8RWZWVHVOmfoHJuGLeS95P6lojcrwzkYA2qqRF70VbqC5j/i5X8xcWNfMt8rEQrpaaPNiS9Z2Bb8F8gwRlCsHaRHQiQcs1IeG3bEeoiroWB5RdXSKjSNwx3nQpmj1eJEbqrFJsPTCFMWrAVUoGYUhWRVgynfE@TUUs4BTqiL5xTI6uCaVAeRYSZa6UmqFaLsAyhsAb0Jko@KpkEmwglyZtbERZ0snyRuKxcak1a43OemsrSghX0tOqMqvoMHpuqgqSwp20gVhdyh5sxI7AFr/WDl461iWXXOdDMu4zbpI2n4FNPA0eC0niWDsljnQ8dN6l4LIl0RJiaclgKYKJGEAJWilbQolW6EAIcylaBvr7CESLa6RDOExkdghCBIbfjcTVCmraoN5KOM10aQhi/VXSiQKqnSA5hyTzjRjmvKRIe4QFUBlONitDeowLoqdNVhPpWQfHXveApqKTgtzYpwjKjstAFmrV2cbsAfiAqsBbnKJ5KKd9fLWDO0FUtoKoMRvMc@3Rx4b5dQqhYd2QzKbgDco2YjfcaIlDB@FSSCscWSxwacXI0IptWGas0Kty/S/2queTU1nBCgEX3JTixflhRqSmQrRP9srQTFSSDfQMwDpbG80IGDS6VoIqf22CSoCkFSs6B94TlqRcqQ3WOFxVyZNZZdSAIqrEZai7wii6@S1z0vSXsGWhkdwnpIhshJOUu5btoFwRSI11my3KgVEJrAc1MIXfUK2wznVsoVdt05JhXqJ@U6wED3IjskMLgKoiVYYHMIugQT2WOSjyRgRqocDJrMbit9RiEEDtn/X0HGlDyxB/f00sNQOLuq3ZCjcU94EZrq51QsUyIYO922@xQGx0lh4OG32DWbbdmlhsTJ6AY60sMw8tqE0rdCiWHqN8jxYHlNnOdnv2FBBeDOizaxEI0MV1eFnb7G5ndcKJmrqSw5xERR0PMVWMEztao62mpCljLJHUAxzERo9QAhk65VLJu@jRuIfLwIhiONC5xfO7HBSE0IeJOkpKjhclfaGeoqdi9MIbTI9vmD10JrrXPAE6Z08H5psAG5IOqZIcvJyNINQWFRGVtSq1C68hRbSmzbalBuNNS9n3z5SknkQXn7PgB5zUB@Yc@Rdc@jJs775rcR9sM0R2ePSBK/rSfQuitYoF8ig08LfASkJRJBKwo8I5dH3hYd/bhw3R1TV1v@Biaw/z0QVFfkV4vanIoy6hlg1pj1qxtqBzjNqBxf4fZoMjHdNGevhhyUg60yIMvXUjg8cwt410KlHw3TL6b9lKT8TAy5/60tZjiruInj@HeG9uZWvhqMbQSxsli9HIGh9kCT9VkLAnUtsYZvMR3t7C7GB2mMEnOc1AHsKsn56DvNM1zPb6TtrybJZUwtoIvFNirISe9Rrn40fji4ejIy22OAOCk8noKG3TJoyHeeP2UOpxLwxyR2juJNoSTmzW75jD9EEf/SNeg4NhRnvhXShlLcDn@XF@Pr83OOPn85vRUa/5hFno/uVB4wheuPETtO3wv2SWL@bJa8zDf7ye9Qvz3m/aBLJD0uDCUxJ6HpOQLy5fEg4pSeH0hnjj/j8WUAK7ZbW3ic4c7KKBHt4JMNmAcwO1Q2Z77ulkcrIyUs88vv/l3t/509vbfHF@cXY@up7CP8v0eDwdXiPELy1WXLjbF5GnJoCAnurpzWi63N2/DyOHsYBxCuMBjDMY5zAuYFwuA3wLGHzp4CtgVMtdDnI5yOUgl4NcDnI5yOUgl4NcfgnjCgaDAdI5h1HCAPm8emXy6r3XltPZ/PU3jrOTN/PF6YOz86uHbz16/PY77773/gcffvTxJ59@9vkXX3719Tfffvf9Dz/@9PMvv14vlze/PeVl3cjV2thnLsTNdvf89z/@/Gu5u6imf2uTcfirFv8A)
[Answer]
# 34. [Java (OpenJDK 9)](https://tio.run/##y0osS9TNL0jNy0rJtvz/PzOvJLUoLTE5VSGxurgksSQzWaEsPzNFITcxM08juKQoMy89OjZRszq4srgkNVcvv7RErwAoWKJhbKxpXVv7/z8A "Java (OpenJDK 9) – Try It Online"), 63 bytes
```
interface a{static void main(String[]a){System.out.print(33);}}
```
I figured this was getting a bit too easy, with all the characters available and all...
[Try it online!](https://tio.run/##y0osS9TNL0jNy0rJtvz/PzOvJLUoLTE5VSGxurgksSQzWaEsPzNFITcxM08juKQoMy89OjZRszq4srgkNVcvv7RErwAoWKJhbKxpXVv7/z8A)
[Next toolbox](https://tio.run/##dVZZt9smEH6@/hWu2/Ta7SWNfHO3nKT7vrene5wmCCEJGwFhsa2cnv7rPqczg2QnXR7QfAPMyjDI9bG1Zvlcc9OE6YPpw9mdC14WcnY2WwZeagTnW@6BXMG4uYEPZ05yz6KXuMpFTFzrHmFVOYe0sYZ43Vh9ed0QVIJ2a9cmsUHkNKt6rm3zEsOE5iEoMUyaxiDyoreJgLG6osUQZFfqnvHwIteIlxYNDx3yqZS@UYY82JH1vYVvyUOLBGVKybtMTCbRqA0hGXZ8T6hOppFHxG6ukdEk7rlo@xzNAS8zowyrNd@MTGmtHnGdk0EYklUTVtwwMaSpTCWcQpPQN4HJMQ2hHKhgMVPuK2U4qhUSLGMIogWdmYKvWmXBFnJp88ZWVhWdrGgVHptQxvDOGjZYW1NChFaBVrVdJ4/RC1vXkBThlYvEmkoNYCv3BHb4dW700vM@u@T7ELPxwITN2gIDm3gaIpWKxLF2Khz5eOi8KylUR6IVxNKRwUpGmzCACrRStqSWnTSREOZSdhz0DxHIDtdIh/SYSHYMQkaO363C1Rpq2qLeWnrDTWUJYv3VyssSqp0gOYeEhVaOc0FRpAPCAqitIJu1JT3WRznQljVEBtbDsTcDoKnklSQ3DimCshMqkoVG9661BwA@oCrwFqdoHsrpEF/j4U4QVZ0kau0W89wE9LHlYZNDaHk/JrMtRYuyrdyPN1rhMFH6HNIaB0slLq05GVrzLWfWSbOuNv9gbwY@O8VKXkq44LaSL8@PMzI3FaJDsteWZpJWfKQXADZsYw0nYNHoRkuq/I2NOgOS1rzsPXhPWJFyrbdY43BVlchmtdUjSqgSl6HuSqvp5nfcKztcwo7HVomQkSaylV5R7jq@h3JFoAzWLVtWI6Mz2IxqYAq/sV5jnZvUQa/a5SXLg0L9tlxLEdVWsmMLgKoiVVZEMIugRT2OeyjyVkZqocAp1mDxO2oxCKD2LwZ6ibSlZYh/uCaOmoFD3c7upB@L@8iMV9d5qVOVkcXeHXZYIC55Rw@HS6HFLLt@Qyw2pkDA805VLEAL6vIKHYqjx6g4oOURMde7/sCeA8KLAX12IyMBurgeL2vHXuysXnrZUFfymJOkqeMhporxck9rtNVWNGWtI5J7gIfY6BHKgKFTPpe8TwGNB7gMnCiGA51bPnuRg4KQ5jjRJEXJCbKiL9RTClSMQQaL6Qktd8fORPdaZEDnHOjAQhthQ9ahdJaDl7OVhLqyJqJZp3O7CAZSRGvG7jpqMMF2lP3wVCvqSXTxBY9hxFl95N6Tf9HnL8f2HvoO98E2S2SPRx@Fpi/dtyg7p3kkj2ILfwu8IpRkJhE7KpxDPxQe9r1D2BBd01D3iz517jiffNTkV4LXm4o8mQpq2ZL2ZDTvSjrHZDxYHP5htjjyMW1VgB8WRtLMyDj21q2KAcPctcrrTMF3x@m/ZacCEQsvf@5Lu4Ap7hN6/gziffRcdQ6Oagq9tNWqnEycDVFV8FMFCXusjEtxvpjg7S3tHmbHGXyS8wzkIc6H6QXIe9PA7KDvdlddzLNKWJuAd1pOtTTzQeNien96dW9yYuQOZ0BwNpuc5G3Gxuk4b/0BKjMdhEHuBM3dTq6CE5sPOxYwfdRH/4gPwcE4p73wLlSqkeDz4qy4XNwanQmLxaPJyaD5NnfQ/aujxgm8cNPHaNvjf8m8WC6y15iHf3k9HxYWg9@0CWTHpMGFpyQMPCahWF7/RzikJIczGBKt//9YQAnsVvXBJjpztIsGBvhCgNkGnBuoHTM7cE9ms9trq8w84PtfHfxdPHn@vFheXi/PJw9P4Z/l9Gx6Or5GiOluI6AXGMHh6UAm/6mcPpqcrvZ37sAoYCxhnMO4C@MCxiWMKxjXq7gyQEsYYuXhK2HUq30BkgVIFiBZgGQBkgVIFiBZgGRxDeMGBocB0oWAUcEA@aJ@Zfbqa7deX52@8eYZe@tOsbx7cXl1fXPv/oO333n3vfc/@PCjjz/59LPPv/jyq6@/@fa773/48aeff/n1t9Xq98dPyna90U/Tbv/sjz9X@6v69C9jmYB/Z/k3)
[Answer]
# 45. [Templates Considered Harmful](https://github.com/feresum/tmp-lang), `Ad<T,>`
```
Add<Add<Add<Add<Add<Add<T,T>,Add<T,T>>,Add<Add<T,T>,Add<T,T>>>,T>,Add<T,T>>,Add<Add<T,T>,Add<Add<Add<Add<T,T>,Add<Add<Add<Add<Add<Add<Add<T,T>,Add<T,T>>,Add<Add<T,T>,Add<T,T>>>,T>,Add<T,T>>,Add<Add<T,T>,Add<Add<Add<Add<T,T>,Add<T,T>>,Add<Add<T,T>,Add<T,T>>>,T>>>,T>>,Add<Add<T,T>,Add<T,T>>>,Add<T,T>>>>
```
[Try it online!](https://tio.run/##K0nNLchJLEkt/v/fMSXFBhsO0Qmx04ExICxMYTsCirAaSH8bCRkIIXAqQDDt/v8HAA "Templates Considered Harmful – Try It Online")
[Next Toolbox](https://tio.run/##dVbXlts2EH22vkJR4qyUGI4pe5sTn@Sk93pSVxsbBEESEgjAKJLolL/OszMzIKV1ygMwF2UqBgO4PrbWLJ9rbpowfTS9mt075WUhZ3dmy8BLjeD@lnsg59AuL6HjzEnuWfQSV7mIiWvdI6wq55A21tBYN1afXTQElaDd2rVJbBA5zaqea9u8MGBC8xCUGCZNYxB50dtEwFhd0WIIsit1z3i4OWrEC4uGhw7HqZS@UYYs2JH2vYW@5KFFgjyl5F0mJpNo1IaQDDu@J1Qn08gjYpcXONDE7rlo@@zNAS/zQBlWa74ZB6W1esR1DgZhCFZNWHHDxBCmMpVwCk1C2wQGxzSEsqOCxUy5r5ThKFZI0IwuiBZkZgq2apUZW4ilzRtbWVV0sqJVeGxCGcM7a9igbU0BEVoFWtV2nTx6L2xdQ1CEVy7S0FRqAFu5J7DD3rnRSs/7bJLvQ8zKAxM2SwsMdOJpiFQqYsfcqbDl46HzrqRQHbFW4EtHCisZbUIHKpBK0ZJadtJEQhhL2XGQP3ggO1wjGdJjINnRCRk59luFqzXktEW5tfSGm8oSxPyrlZclZDtBMg4JC60c54IiTweECVBbQTprS3Ksj3KgLWuIDEMPx94MgKaSV5LMOIQI0k6oSBoa3bvWHgDYgKLAWpyieUing3@NhztBVHWSqLVbjHMT0MaWh012oeX9GMy2FC3ytnI/3miFzUTps0trbCyVuLTmpGjNt5xZJ8262vxjeDmMs1Gs5KWEC24r@eL8OCNzUSE6BHttaSZpxUd6CmDDNtZwAhaVbrSkzN/YqDMgbs3L3oP1hBUJ13qLOQ5XVYmsVls9ooQicRnyrrSabn7HvbLDJex4bJUIGWkiW@kVxa7je0hXBMpg3rJlNQ50BptRDExhH@s15rlJHdSqXV6yPCiUb8u1FFFtJTuWAMgqEmVFBLUIWpTjuIckb2WkEgojxRpMfkclBgHk/ulAz5C2tAz@D9fEUTFwKNvZnfRjch8H49V1XupUZWSxdocdJohL3tHD4VJoMcqu39AQC1Mg4HmnKhagBHV5hQ7F0WNUHNDyiJjrXX8Y3geEFwPq7EZGAnRxPV7Wjt2srF562VBV8hiTpKniIaaM8XJPa7TVVjRlrSOSa4AH3@gRyoChUT6nvE8BlQe4DJwougOVWz67OYKEkOY40SRFwQmyoh7yKQVKxiCDxfCElrtjZaJ7LTKgcw50YKGNsCHLUDrzwcvZSkJdWRPRrNO5XAQDIaI1Y3cdFZhgO4p@eKoV1SS6@ILHMOIsPnLvyb7oc8@xvIe@w32wzRLZ49FHoamn@xZl5zSPZFFs4bfAK0JJZhKxosI59EPiYd07uA3eNQ1Vv@hT547zyUdNdiV4vSnJk6kgly1JT0bzrqRzTMaDxuEPs8WWj2mrAnxYGHEzI@NYW7cqBnRz1yqvMwXbHad/y04FIhZe/lyXdgFD3Ce0/Bn4e/1cdQ6Oagq1tNWqnEycDVFV8KmCgD1WxqU4X0zw9pZ2D7PjDD7JeQbiEOfD9AL4vWlgdpB3t6tO51kkrE3AOi2nWpr5IHExfWt6/nByy8gdzgDjbDa5lbcZG6fjvPUHqMx0YAa@W6jubnIVnNh82LGA6aM8@iNegYFxTnvhXahUI8HmxZ3ibHF7NCYsFteTW4Pku9xB9a@OEifwwk0fo26P/5J5sVxkqzEO/7J6PiwsBrtpE/COQYMLT0EYxhiEYnnxH@6QkOzOoEi0/v99ASGwW9UHnWjMUS8qGOANB7MOODcQO0Z2GD2Zze6urTLzgO9/dbB38eT582J5dlmcTq5O6JU9uTM9yR8QRDnJEeXHDNHhE0lbb/wjTq4nJ6v9vXvQCmhLaPehPYB2Cu0M2jm0i1VcGaAlNLHy0Eto9WpfAGcBnAVwFsBZAGcBnAVwFsBZXEC7hMahAXchoFXQgL@oX5q9/MrtV1cni9deZ2/cK5b3H5yenV9cPnzz0dvvvPve@x98@NHHn3z62edffPnV1998@933P/z408@/XK1W178@fsJLUTfteqO7p2m375/99vsff6725/XJX8YyAZ9p@Tc)
[Answer]
# 4. [Python 1](https://www.python.org/download/releases/1.6.1/) `print+3`
```
print+3
```
[Try it online!](https://tio.run/##K6gsycjPM/z/v6AoM69E2/j/fwA "Python 1 – Try It Online")
[Next toolbox](https://tio.run/##dVZZjxs3DH5e/wrXbbE2kFnsON1db5ugaJGiDy2KPhQ9kA0SjaSZka0rOmxP0P72LUnN2JseDxI/HaRIiqTkh9Q7u37UzHZx/nL@enF9w5paLp4t1pE1GsHzPQtA7qDd30PHKi9ZqFKQuMp4ykzrAaEQ3iPtnKWx7py@3XQEFafd2veZ7xB5XYmBadd9NKi4ZjEqPk7aziIKfHCZgHVa0GKM0jR6qFh8Our4R4uWRYPj3MjQKUsaHOj0o4O@YbFHgjyNZKYQW0iyakdIxgM7Emqz7eQZVfcbHGhiD4z3Q7HmhNdloGzVarabBo1zesJtcQZhcFZLWDFb8dFNTW7gFrqMunF0ju0IFUN5lQplQSjLUCyXcDKawHuQWSjoqlVh7MGXrmzspRB0s7xXeG1cWcuMs9V42pYcwrWKtKrdNge0nru2BafwoHyioRVqBHt5JHDA3vtJy8CGolIYYiqHx4q7Ii1WcCbeBs@NInaMHYGtXA/dt5BcGWIVYIuhA4VMLqMBAqSSt6SWRtpECH0pDQP5owXS4BrJkMZt1US5E6iIDOjc6myYTAz7vUKOFuLc4VmtDJZZ4QhiTLYqyAYygCApjKSKvZzmoiLrR4RB0TpOerSO5LiQ5Ej7qiMyDgOEQjcCmspBSVLj5DYIRa4SndDpwffuBEAHFAXa4hTNQ4id7OsC5AlRZSRR5/bo@y6ijj2Lu2JCz4bJwX3De@Tt5XHKcvSjskmGYtIWW5UbXNoyOmjL9qxyXtqt2P1jeD@Oi1JVwxoJSV8u5Mn8NCNLoSE6OnvraCZrxSZ6A2BX7ZxlBBweutOSsmHnki6AuDVrhgDaE1YkXOs9xj2k7xQZ2ukJZRSJyxCLjdNUDQwLyo2JaVjqFY8FaSJ7GRT5zrAjhDACZTGWq7WYBrqA3SQGprBP7RZj32YD9etQlhyLCuW7Zit5UntZncsCRBWJcjzBsQh6lONZgMDvZaKyCiNVdZgQnsoOAoj9m5HeIu1pGewfU8dTgfAo27uDDFNwnwdTOvsgdRYFOazn8YAB4nPw9Jj4HHv0sh92NMRiFQkEZpSoIpQlU1boUjw9UPUJrc@o8oMfTsPngDAxoPbuZCJAiRswWU31tNoGGWRHlSqgT7KmKoiYIibII63RVidoyjlPpNSAALbRw1RAhUqFEvIhRzw8QjIwomgOVHP54ekIAkLa80SXFTknSkE9xFOOFIxRRofuiT3z58pEec0LoHuOdGGxT7ChyFC68MFr2ktCpmmJ6MroUi6iBRfRmnUHQwUmOkPej@@1oppEic9ZihMu4hMLgfRLofQMS34cDO6DbY7IEa8@cU095VuSxmuWSKPUww@CCUJZFpKwosI9DGPgYd07mQ3WdR1VvxSy8ef5HJImvTK86BTk2QqIZUfSs9XMNHSP2QY4cfzX7LGVa9qrCJ@YirgrK9NUW/cqRTTz0KugCwXdPaO/zEFFIg5@A6UuHSK6eMio@Qew982jMh6uag61tNeqmc28i0kJ@GiBw94q63NarmaYvY07wuw0g890mQE/pOU4vQL@YDuYHeVdGXGzLCJhbQbaaTnX0i5Hiav5i/ndl7MLKw84A4yLxeyibLMuzad5F05Q2fnIDHwXeNxV9gJubDnuWMH0WR79G1@DgmlJe@FdEKqToPPqWX27@nxSJq5Wb2YXo@Qr5qH6i7PEGbxw87d4dsC/yrJer4rW6Id/ab0cF1aj3rQJeCenQcKTE8bxav7Jy3m93vyHPSSl2DOexPvw/8aAENg9in1iRBEDdwOck/fG0bvF4mrrlF1GfOPFSafVu8fHen17valnry/hr3L5bH55Sk0c0J8AwfQOId5i9@Tne/lmdvlwvL6GVkNbQ3sO7QtoN9Buod1B2zwk6Bto/CFAL6G1D8ca@Grgq4GvBr4a@Grgq4GvBr56A@0eGoMG3DWHJqDJ@eLTz66u65vN/Vcvvv7m21ffff/Djz/9/Muvv/3@B5dt12@1eb8/HIcPf/71cLxrL/8G)
[Answer]
# 8. [PowerShell Core](https://github.com/PowerShell/PowerShell), 1 byte
```
7
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/f/f/P9/AA "PowerShell Core – Try It Online")
I had no idea what powershell is, but it turns out that 7 outputs 7 in TIO.
[Next toolbox](https://tio.run/##dVbrk@M0DP@8/StKGdh25rxsuuwL7ngPj4GB4f3YHneO4yRuHdvnR9vcDPzriyQn7R4cHxz9ZFuyJEtyXB9ba5b3mpsmTJ9M72bnl7ws5OzRbBl4qRFcbLkHcg3j9hY@nDnJPYte4ioXMXGte4RV5RzSxhridWP11U1DUAnarV2bxAaR06zqubbNKwwTmoegxDBpGoPIi94mAsbqihZDkF2pe8bDQ64RrywaHjrkUyl9owxZsKPT9xa@JQ8tEpQpJe8yMZlEozaEZNjxPaE6mUYeEbu9QUaTuOei7bM3B7zMjDKs1nwzMqW1esR1DgZhCFZNWHHDxBCmMpVwC01C2wQGxzSEsqOCxUy5r5ThqFZIOBldEC3ozBRs1SoLthBLmze2sqroZkWr8NqEMoZ31rDhtDUFRGgVaFXbdfLovbB1DUERXrlIrKnUALZyT2CHX@dGKz3vs0m@DzEfHpiwWVtgcCbehkilInHMnQpHvh6670oK1ZFoBb50dGAlo03oQAVaKVpSy06aSAhjKTsO@gcPZIdrpEN2dq1GKmyFhkiPwWVHx2Tk@N0qlKghzy2eVUtvuKksQczJWnlZQgUQJIORsNDKcS4o8n5AmBS1FWRHbUmP9VEOtGUNkYH1kArNAGgqeSXJjEPYIBWFinRCo3vX2gMAG1AVWItTNA8pdvCv8VAnRFUniVq7xdg3AW1sedhkF1rejwFuS9GibCv3Y5VjHJWJ0meX1jhYKnFpzemgNd9yZp0062rzL/Z24LNRrOSlhKLPF/JgfpyRudEQHYK9tjSTtOIjvQSwYRtrOAGLh260pGrY2KgzIGnNy96D9YQVKdd6i3kP5TtmhrZ6RAlV4jLkYmk1dYOOe2WHwux4bJUIGWkiW@kVxa7je0hhBMpgLrNlNTI6g82oBqbwG@s15r5JHfSvXV6yPCjUb8u1FFFtJTu2BcgqUmVFhGMRtKjHcQ@J38pIbRU4xRosCEdtBwHk/uVAr5C2tAz@D6XjqEE41O3sTvoxuY/MWM7OS52qjCz287DDBHHJO3pMXAotRtn1G2KxWQUCnneqYgHaUpdX6FIcPVDFAS2PiLne9Qf2AhAWBvTejYwEqHA9FmvHHnZbL71sqFN5jEnS1AURU8Z4uac12mormrLWEck9wINv9DBlwNAon1Pep4CHBygGThTdgW4uXz7kICGkOU40SVFwgqzoC/mUAiVjkMFieELL3bEzUV2LDOieA11YaCNsyDqUznLwmraSUFfWRDTrdG4XwUCIaM3YXUcNJtiOoh9eaEU9iQpf8BhGnNVH7j3ZF33@cmz5oe9wH2yzRPZ49VFo@lK9Rdk5zSNZFFv4g@AVoSQzidhR4R76IfGw7x3cBu@ahrpf9Klzx/nkoya7ErzolOTJVJDLlrQno3lX0j0m4@HE4b9miyNf01YF@IlhJM2MjGNv3aoY0M1dq7zOFGx3nP5ldioQsfA3kPvSLmCI@4SWvwR/n96rzsFVTaGXtlqVk4mzIaoKfrQgYM@UcSnOFxOs3tLuYXacwWc6z0Ac4nyYXoC8Nw3MDvrOuupynlXC2gSs03KqpZkPGhfTx9Pr9yYnRu5wBgRns8lJ3mZsnI7z1h@gMtNBGORO8Liz5Cq4sfmwYwHTR33033gHBsY57YV3oVKNBJsXj4qrxVujMWGxeDo5GTSfcQfdvzpqnMALN32GZ3v8V5kXy0W2GuPwH6vnw8JisJs2gewYNCh4CsLAL6ZvPJkWy5vX@ENasj/DSaL1/@8MKIHdg9oHTmQ1cDcgOUZv4J7PZmdrq8w84BtfHWxaPL@/L5ZXF8X55O4U/lVOH01PxxcH8YPfW2QftBFkX/ti5n2Qz6dPJ6er/fk5jALGEsYFjHdhXMK4gnEN42YVVwZoCUOsPHwljHq1L0CyAMkCJAuQLECyAMkCJAuQLG5g3MLgMEC6EDAqGCBf1LM333p7dbpgZ@@cX1ze3L7/@IMPP/r4k08/@/yLL7/6@ptvv/v@hx9/@vmXX3/7/Y@71erPZ8@hluqmVeuN7qx74be7ff/yr79X@@v69B8 "Python 2 – Try It Online")
[Answer]
# 10. [Prelude](https://esolangs.org/wiki/Prelude), `3+!`
We finally got an `!`!
```
3333333333333333333++++++++++++++++++!
```
[Try it online!](https://tio.run/##KyhKzSlNSf3/3xgTaGMAxf//AQ "Prelude – Try It Online")
[Next toolbox](https://tio.run/##dVbZlts2DH0ef4U7PenYPVE6cjJbmnTf930bpwlFUhJtimS42FZO21@fAqBkT7o8ULgACRAAQVCuj601ixvNTBOmj6fXx6dnrCrl8d3jRWCVRnB/wzyQCxhXV/BhhZPMF9FLnGU8JqZ1j1AI55A21hCvG6vPLxuCitNq7drE14icLkTPtG1eYgquWQiKD0LTGESe9zYRMFYLmgxBdpXuCxZucw1/adKw0CGfKukbZciDLe2@s/CtWGiRoE4lWZeJySQatSYkw5btCNXJNPKAiqtLZDSpe8bbPkezx4vMKFPUmq1HprJWj7jOySAMyaoJK2YKPqSpShWcQpPQN47JMQ2hHCgvYqbMC2UYmuUSdsYQeAs2MwVftcqKLeTS5oWtFIJOlrcKj40rY1hnTTHstqKEcK0CzWq7Sh6j57auISncKxeJNUINYCN3BLb4dW700rM@u@T7EPPmoeA2WwsF7ImnwVOlSB1rR@DIx0PnLSRXHakKiKWjDYWMNmEAAqxStqSWnTSREOZSdgzsDxHIDufIhuzsSo2UW4GOSI/JLQ6Bycjwu1GoUUOdW9yrlt4wIyxBrMlaeVnBDSBIDiMpQitHWVAU/YCwKGrLyY/akh3roxxoWzREBtZDKTQDIFHySpIb@7RBKXIVaYdG9661ewA@oCnwFkUkhxLbx9d4uCdEVSeJWrvB3DcBfWxZWOcQWtaPCW4r3qJuK3fjLcc8KhOlzyGtcBSpwqkVo41WbMMK66RZifU/2KuBz04VFaskXPp8ILfko0TmRkN0SPbKkiRpxUZ6BmBdrK1hBCxuutaSbsPaRp0BaWtW9R68J6zIuNYbrHu4vmNlaKtHlNAkTkMtVlZTN@iYV3a4mB2LreIhI01kI72i3HVsByWMQBms5WIhRkZnsB7NgAi/sV5h7ZvUQf/a5inLgkL7tlpJHtVGFoe2AFVFpiyPsC2CFu045qHwWxmprQKnigYvhKO2gwBq/2yg50hbmob4h6vjqEE4tO3sVvqxuA/MeJ2dlzqJjCz287DFAnHJO3pMXAotZtn1a2KxWQUCnnVKFAHaUpdn6FAcPVDlHi0OqHC96/fsfUB4MaD3rmUkQBfX42Xtitvd1ksvG@pUHnOSNHVBxFQxXu5ojpZaQSJrHZHcAzzERg9TBgU65XPJ@xRw8wCXgRHFcKCbyxe3OSgIaQ6CJilKTpCCvlBPKVAxBhkspie0zB06E91rngGdc6ADC22EBdmG0lkPXtNWEuqqmoguOp3bRTCQIpozdttRgwm2o@yH51pRT6KLz1kMI87mI/Oe/Is@fxm2/NB3uA6WWSI7PPrINX3pvkXZOc0ieRRb@INgglCSmUTsqHAO/VB42Pf2YUN0TUPdL/rUuYM8@ajJrwQvOhV5MgJq2ZL1ZDTrKjrHZDzsOPzXbHDkY9qoAD8xBWkXRsaxt25UDBjmtlVeZwq@O0b/MlsViFj4G8h9aRswxX1Cz19AvE9uVOfgqKbQS1utqsnE2RCVgB8tSNhTZVyKs/kEb29ldyAdJfhMZwnkIc4G8Rz0vWlAOti714mzWTYJcxPwTsuplmY2WJxPH00vHk6OjNyiBBSPjydHeZmxcTrKrd9DZaaDMugd4Xb3khNwYrNhxRzEB3v033gNDsYZrYV3QahGgs/zu@X5/M7oTJjPn0yOBsv3mIPuLw4WJ/DCTZ/i3h7/VWblYp69xjz8y@vZMDEf/KZFoDsmDS48JWHg59NXHk/LxeV/xENWcjzDTrz1/x8MGIHVg9lbQWQzcDagOWZv4J4dH99bWWVmAd94sfdp/uzmplycPzgtJ9cn8K9ycnd6Mr44iG/93iJ7q41kFsoWQW6fJ08mJ8vd6SmMEsYCxn0YD2CcwTiHcQHjchmXBmgFgy89fCWMerkrQbMEzRI0S9AsQbMEzRI0S9AsL2FcwWAwQLvkMAQM0C/r6fGrd15bnsxfL944LRdnF5dXD9989Nbb77z73vsffPjRx598@tnnX3z51dfffPvd9z/8@NPPv/z62/Vy@eT3p89YJepWrdadse65DzFttrv@xR9//rXcXdQnfwM)
## Explanation
`9` is 57 in ASCII, which is 3 times 19. So in order to get `9` we add 19 3s and use `!` to output.
[Answer]
# 11. [Convex](https://github.com/GamrCorps/Convex), 1 byte
```
A
```
[Try it online!](https://tio.run/##S87PK0ut@P/f8f9/AA "Convex – Try It Online")
[Next toolbox](https://tio.run/##dVbZlts2DH0ef4U7PenYPVE68mS2NOm@7/sWpwlFUhJtimS42FZO21@fAqBkT7o8ULgACRAAQVCuj601ixvNTBOmj6aPj0/PWVXK47vHi8AqjeBswzyQSxjX1/BhhZPMF9FLnGU8JqZ1j1AI55A21hCvG6svrhqCitNq7drE14icLkTPtG1eYgquWQiKD0LTGESe9zYRMFYLmgxBdpXuCxZucw1/adKw0CGfKukbZciDLe2@s/CtWGiRoE4lWZeJySQatSYkw5btCNXJNPKAiusrZDSpe8bbPkezx4vMKFPUmq1HprJWj7jOySAMyaoJK2YKPqSpShWcQpPQN47JMQ2hHCgvYqbMC2UYmuUSdsYQeAs2MwVftcqKLeTS5oWtFIJOlrcKj40rY1hnTTHstqKEcK0CzWq7Sh6j57auISncKxeJNUINYCN3BLb4dW700rM@u@T7EPPmoeA2WwsF7ImnwVOlSB1rR@DIx0PnLSRXHakKiKWjDYWMNmEAAqxStqSWnTSREOZSdgzsDxHIDufIhuzsSo2UW4GOSI/JLQ6Bycjwu1GoUUOdW9yrlt4wIyxBrMlaeVnBDSBIDiMpQitHWVAU/YCwKGrLyY/akh3roxxoWzREBtZDKTQDIFHySpIb@7RBKXIVaYdG9661ewA@oCnwFkUkhxLbx9d4uCdEVSeJWrvB3DcBfWxZWOcQWtaPCW4r3qJuK3fjLcc8KhOlzyGtcBSpwqkVo41WbMMK66RZifU/2OuBz04VFaskXPp8ILfko0TmRkN0SPbKkiRpxUZ6DmBdrK1hBCxuutaSbsPaRp0BaWtW9R68J6zIuNYbrHu4vmNlaKtHlNAkTkMtVlZTN@iYV3a4mB2LreIhI01kI72i3HVsByWMQBms5WIhRkZnsB7NgAi/sV5h7ZvUQf/a5inLgkL7tlpJHtVGFoe2AFVFpiyPsC2CFu045qHwWxmprQKnigYvhKO2gwBq/3ygF0hbmob4h6vjqEE4tO3sVvqxuA/MeJ2dlzqJjCz287DFAnHJO3pMXAotZtn1a2KxWQUCnnVKFAHaUpdn6FAcPVDlHi0OqHC96/fsGSC8GNB71zISoIvr8bJ2xe1u66WXDXUqjzlJmrogYqoYL3c0R0utIJG1jkjuAR5io4cpgwKd8rnkfQq4eYDLwIhiONDN5YvbHBSENAdBkxQlJ0hBX6inFKgYgwwW0xNa5g6die41z4DOOdCBhTbCgmxD6awHr2krCXVVTUQXnc7tIhhIEc0Zu@2owQTbUfbDc62oJ9HF5yyGEWfzkXlP/kWfvwxbfug7XAfLLJEdHn3kmr5036LsnGaRPIot/EEwQSjJTCJ2VDiHfig87Hv7sCG6pqHuF33q3EGefNTkV4IXnYo8GQG1bMl6Mpp1FZ1jMh52HP5rNjjyMW1UgJ@YgrQLI@PYWzcqBgxz2yqvMwXfHaN/ma0KRCz8DeS@tA2Y4j6h5y8g3ic3qnNwVFPopa1W1WTibIhKwI8WJOypMi7F2XyCt7eyO5COEnymswTyEGeDeA763jQgHezd68T5LJuEuQl4p@VUSzMbLM6nD6eXDyZHRm5RAorHx5OjvMzYOB3l1u@hMtNBGfSOcLt7yQk4sdmwYg7igz36b3wMDsYZrYV3QahGgs/zu@XF/M7oTJjPn0yOBsv3mIPuLw4WJ/DCTZ/i3h7/VWblYp69xjz8y@vZMDEf/KZFoDsmDS48JWHg59NXHk3LxdV/xENWcjzDTrz1/x8MGIHVg9lbQWQzcDagOWZv4J4dH99bWWVmAd94sfdp/uzmplxc3D89mzw@gX@Vk7vTk/HFQXzr9xbZW20ks1C2CHL7PHkyOVnuTk9hlDAWMM5g3IdxDuMCxiWMq2VcGqAVDL708JUw6uWuBM0SNEvQLEGzBM0SNEvQLEGzvIJxDYPBAO2SwxAwQL@sp8ev3nlteTJ/vXjjtFycX15dP3jz4Vtvv/Pue@9/8OFHH3/y6Weff/HlV19/8@133//w408///Lrb4@Xyye/P33GKlG3arXujHXPfYhps931L/7486/l7rI@@Rs "Python 2 – Try It Online")
[Answer]
# 12. [Logicode](https://github.com/LogicodeLang/Logicode), 6 bytes
```
out 11
```
[Try it online!](https://tio.run/##y8lPz0zOT0n9/z@/tETB0PD/fwA "Logicode – Try It Online")
trivial, right language for 11
[Next toolbox](https://tio.run/##dVbZlts2DH0ef4XrntR2TzQdOZktTbrv@76NpwlFURJtimS42FZO21@fAqBkO10eKFyABAiAIETbhcboxZ1iuvbjJ@Obydk5K3IxuT9ZeFYoBA82zAG5hHF9DR@WWcFcFpzAWcZDZEp1CMvSWqS10cSr2qiLq5qg5LRa2SbyNSKrsrJjytQvMRlXzHvJe6GuNSLHOxMJaKNKmvRetIXqMuaPuZq/NKmZb5GPhXC11OTBlnbfGfgWzDdIUKcQrE1EJxK0XBMSfst2hKqoa3FA2fUVMorUHeNNl6LZ40VipM4qxdYDUxijBlylZBCGZFWEJdMZ79NUxAJOoY7oG8fk6JpQCpRnIVHmSqkZmuUCdsYQeAM2EwVflUyKDeTSpIWNKEs6Wd5IPDYutWat0Vm/24oSwpX0NKvMKjqMnpuqgqRwJ20gVpeyBxuxI7DFr7WDl451ySXX@ZA29xk3yZrPYE88DR4LSepYOyWOdDx03qXgsiXVEmJpacNSBBMxgBKsUraEEq3QgRDmUrQM7PcRiBbnyIZozUoOlJsSHREOk5sdAhOB4XcjUaOCOje4VyWcZro0BLEmK@lEATeAIDmMJPONGGReUvQ9wqKoDCc/KkN2jAuip01WE@lZB6VQ94BE0UlBbuzTBqXIZaAdatXZxuwB@ICmwFsUkRxKbB9f7eCeEJWtIGrMBnNfe/SxYX6dQmhYNyS4KXiDuo3YDbcc8yh1EC6FtMKRxQKnVow2WrENy4wVelWu/8Fe93xyKitYIeDSpwM5kg8SkRoN0T7ZK0OSqCQb6DmAdbY2mhEwuOlaCboNaxNUAqStWNE58J6wJONKbbDu4foOlaGMGlBEkzgNtVgYRd2gZU6a/mK2LDSS@4QUkY1wknLXsh2UMAKpsZazRTkwKoH1YAZE@A3VCmtfxxb61zZNGeYl2jfFSvAgNyI7tAWoKjJleIBtETRoxzIHhd@IQG0VOJnVeCEstR0EUPvnPb1A2tA0xN9fHUsNwqJta7bCDcV9YIbrbJ1QsUzIYD/3WywQG52ln4mNvsEs225NLDYrT8CxVpaZh7bUphk6FEs/qHyPFgeU2c52e/YBILwY0HvXIhCgi@vwsrbZcbd1womaOpXDnERFXRAxVYwTO5qjpaYkkTGWSOoBDmKjH1MCGTrlUsm76HFzD5eBEcVwoJuLF8ccFITQB0EdJSXHi5K@UE/RUzF64Q2mxzfMHjoT3WueAJ2zpwPzTYAFyYZUSQ/@po0g1BYVEZW1KrULryFFNKfNtqUG401L2ffPlaSeRBefs@AHnMwH5hz5F1z6Mmz5vmtxHSwzRHZ49IEr@tJ9C6K1igXyKDTwgmAloSgSCdhR4Ry6vvCw7@3DhujqmrpfcLG1B3l0QZFfEf7oVORRl1DLhqxHrVhb0DlG7WDH/l2zwZGOaSM9PGIy0s60CENv3cjgMcxtI51KFHy3jN4yW@mJGHgNpL609ZjiLqLnLyDe2zvZWjiqMfTSRsliNLLGB1nCQwsS9lRqG8NsPsLbW5gdSAcJ/qaTBPIQZr14DvpO1yDt7Z225fksmYS5EXinxFgJPestzsePx5ePRidabFECipPJ6CQt0yaMB7lxeyj1uFcGvRPc7jTaEk5s1q@Yg/hgj96NN@BgmNFa@C@Ushbg8/x@fjG/Nzjj5/Pb0Ulv@ZRZ6P7lweII/nDjp7i3w7fKLF/Mk9eYh395Pesn5r3ftAh0h6TBhack9Px8/MqTcb64@o94yEqKp9@JN@7/gwEjsLo3exREMgNnA5pD9nru2WRyujJSzzz@48u9T/Nnd3f54uLh2eXoZgpvlen98Xh69KYFfnrUOxILtYog9czp7Wi63J2dwchhLGA8gPEQxjmMCxiXMK6WYamBFjD40sFXwKiWuxw0c9DMQTMHzRw0c9DMQTMHzfwKxjUMBgO0cw6jhAH6eTWevHrvteV0/nr2xtni/PLq@tGbj996@51333v/gw8/@viTTz/7/Isvv/r6m2@/@/6HH3/6@Zdff7tZLm9/f/qMFWXVyNW61fa585vtrnvxx59/LXeX1fRv)
[Answer]
# 16. Scala, 13 bytes
```
()=>print(15)
```
[Try it online!](https://tio.run/##K05OzEn8/z8/KSs1uUTBsZpLQSElNU0hNzEzTyPRyrGoKLEyOrikKDMvPVYTJKmgUJZYpJCmYAtmKyhoaNraFQClSzQMTTXBYmkaILqWq/b/fwA)
[Next Toolbox](https://tio.run/##dVZXf9s2EH@2PoWqNrXUmq4pxytNf91772G5DgiCJCQQQDAkMR3fus/u3YGUnI4H8P4H4CYOB9ouNEbP7xTTtR@/Mb6enJyxIheTo8ncs0IhOF0zB@QCxtUVfFhmBXNZcAJXGQ@RKdUhLEtrkdZGE69qo84va4KS025lm8hXiKzKyo4pUz/HZFwx7yXvJ3WtETnemUhAG1XSoveiLVSXMX@fq/lzi5r5FvlYCFdLTR5syPrWwLdgvkGCMoVgbSI6kaDlipDwG7YlVEVdiz3Kri6RUSTuGG@6FM0OzxMjdVYpthqYwhg14ColgzAkqyIsmc54n6YiFnAKdUTfOCZH14RSoDwLiTJXSs1QLRdgGUPgDehMFHxVMgk2kEuTNjaiLOlkeSPx2LjUmrVGZ721JSWEK@lpVZlldBg9N1UFSeFO2kCsLmUP1mJLYINfawcvHeuSS67zIRn3GTdJm8/AJp4Gj4UkcaydEkc6HjrvUnDZkmgJsbRksBTBRAygBK2ULaFEK3QghLkULQP9fQSixTXSIRwmMtsHIQLD71riagU1bVBvJZxmujQEsf4q6UQB1U6QnEOS@UYMc15SpD3CAqgMJ5uVIT3GBdHTJquJ9KyDY697QFPRSUFu7FIEZcdlIAu16mxjdgB8QFXgLU7RPJTTLr7awZ0gKltB1Jg15rn26GPD/CqF0LBuSGZT8AZlG7EdbrTEoYNwKaQljiwWuLRkZGjJ1iwzVuhlufoHe9XzyamsYIWAC25K8fz8MCNSUyHaJ3tpaCYqyQZ6BmCVrYxmBAwaXSlBlb8yQSVA0ooVnQPvCUtSrtQaaxyuquTJrDJqQBFV4jLUXWEU3fyWOWn6S9iy0EjuE1JE1sJJyl3LtlCuCKTGus3m5cCoBFaDGpjCb6iWWOc6ttCrNmnJMC9RvymWgge5Ftm@BUBVkSrDA5hF0KAeyxwUeSMCtVDgZFZj8VtqMQig9s96eo60oWWIv78mlpqBRd3WbIQbinvPDFfXOqFimZDB3u03WCA2OksPh42@wSzbbkUsNiZPwLFWlpmHFtSmFToUS49RvkPzPcpsZ7sdewoILwb02ZUIBOjiOrysbXa/szrhRE1dyWFOoqKOh5gqxoktrdFWU9KUMZZI6gEOYqNHKIEMnXKp5F30aNzDZWBEMRzo3OLZfQ4KQuj9RB0lJceLkr5QT9FTMXrhDabHN8zuOxPda54AnbOnA/NNgA1Jh1RJDl7ORhBqi4qIylqV2oXXkCJa02bTUoPxpqXs@6dKUk@ii89Z8ANO6gNzjvwLLn0ZtnfftbgPthkiWzz6wBV96b4F0VrFAnkUGvhbYCWhKBIJ2FHhHLq@8LDv7cKG6Oqaul9wsbX7@eiCIr8ivN5U5FGXUMuGtEetWFvQOUbtwGL/D7PGkY5pLT38sGQknWkRht66lsFjmJtGOpUo@G4Z/bdspCdi4OVPfWnjMcVdRM@fQbw3d7K1cFRj6KWNksVoZI0PsoSfKkjYrdQ2hulshLe3MFuYHWbwSU4zkIcw7adnIO90DbO9vuO2PJsmlbA2Au@UGCuhp73G2fjx@OLR6ECLDc6A4GQyOkjbtAnjYd64HZR63AuD3AGaO462hBOb9jtmML3XR/@I1@BgmNJeeBdKWQvweXaUn88eDM742exmdNBrPmYWun@51ziCF258i7Yd/pdM8/kseY15@JfX035h1vtNm0B2SBpceEpCz2MS8vnlf4RDSlI4vSHeuP@PBZTAblntbKIze7tooIf3Akw24NxA7ZDZnnsymRwvjdRTj@9/ufN39uTuLp@fP7w6H10fwj/L4dH48N6vLbL32gqy@1uCXP8fhXB4xA5vRoeL7ckJjBzGHMYpjIcwzmCcw7iAcbkICw20gMEXDr4CRrXY5iCZg2QOkjlI5iCZg2QOkjlI5pcwrmAwGCCdcxglDJDPq/ELkxdfevDy4vCVV4@y49dO5qcPzy8urx69/vjNt95@59333v/gw48@/uTTzz7/4suvvv7m2@@@/@HHn37@5XqxuPn19gkreCmqulmuVGue@rjebLtnv/3@x5@L7UV1@Jc2GYc/a/E3)
[Answer]
# 17. [2sable](https://github.com/Adriandmen/2sable) (Prints 16)
```
4n
```
[Try it online!](https://tio.run/##MypOTMpJ/f/fJO//fwA "2sable – Try It Online")
```
4 # Push 4
n # Square it
```
[Next Toolbox, new language: golfscript](https://tio.run/##dVZXY9s2EH62foWqNrXUmq4pxytNuvfey3ITEARJSCCAYEhiOv51n927Ayk5HQ/gfQfgJg4H2i40Rs9vFdO1Hz8aX09OzliRi8nRZO5ZoRCcrpkDcgHj6go@LLOCuSw4gauMh8iU6hCWpbVIa6OJV7VR55c1Qclpt7JN5CtEVmVlx5Spn2Myrpj3kveTutaIHO9MJKCNKmnRe9EWqsuYv8vV/LlFzXyLfCyEq6UmDzZkfWvgWzDfIEGZQrA2EZ1I0HJFSPgN2xKqoq7FHmVXl8goEneMN12KZofniZE6qxRbDUxhjBpwlZJBGJJVEZZMZ7xPUxELOIU6om8ck6NrQilQnoVEmSulZqiWC7CMIfAGdCYKviqZBBvIpUkbG1GWdLK8kXhsXGrNWqOz3tqSEsKV9LSqzDI6jJ6bqoKkcCdtIFaXsgdrsSWwwa@1g5eOdckl1/mQjPuMm6TNZ2ATT4PHQpI41k6JIx0PnXcpuGxJtIRYWjJYimAiBlCCVsqWUKIVOhDCXIqWgf4@AtHiGukQDhOZ7YMQgeF3LXG1gpo2qLcSTjNdGoJYf5V0ooBqJ0jOIcl8I4Y5LynSHmEBVIaTzcqQHuOC6GmT1UR61sGx1z2gqeikIDd2KYKy4zKQhVp1tjE7AD6gKvAWp2geymkXX@3gThCVrSBqzBrzXHv0sWF@lUJoWDcksyl4g7KN2A43WuLQQbgU0hJHFgtcWjIytGRrlhkr9LJc/YO96vnkVFawQsAFN6V4fn6YEampEO2TvTQ0E5VkAz0DsMpWRjMCBo2ulKDKX5mgEiBpxYrOgfeEJSlXao01DldV8mRWGTWgiCpxGequMIpufsucNP0lbFloJPcJKSJr4STlrmVbKFcEUmPdZvNyYFQCq0ENTOE3VEuscx1b6FWbtGSYl6jfFEvBg1yLbN8CoKpIleEBzCJoUI9lDoq8EYFaKHAyq7H4LbUYBFD7Zz09R9rQMsTfXxNLzcCibms2wg3FvWeGq2udULFMyGDv9hssEBudpYfDRt9glm23IhYbkyfgWCvLzEMLatMKHYqlxyjfofkeZbaz3Y49BYQXA/rsSgQCdHEdXtY2u9tZnXCipq7kMCdRUcdDTBXjxJbWaKspacoYSyT1AAex0SOUQIZOuVTyLno07uEyMKIYDnRu8ewuBwUh9H6ijpKS40VJX6in6KkYvfAG0@MbZvedie41T4DO2dOB@SbAhqRDqiQHL2cjCLVFRURlrUrtwmtIEa1ps2mpwXjTUvb9UyWpJ9HF5yz4ASf1gTlH/gWXvgzbu@9a3AfbDJEtHn3gir5034JorWKBPAoN/C2wklAUiQTsqHAOXV942Pd2YUN0dU3dL7jY2v18dEGRXxFebyryqEuoZUPao1asLegco3Zgsf@HWeNIx7SWHn5YMpLOtAhDb13L4DHMTSOdShR8t4z@WzbSEzHw8qe@tPGY4i6i588g3ptb2Vo4qjH00kbJYjSyxgdZwk8VJOyx1DaG6WyEt7cwW5gdZvBJTjOQhzDtp2cg73QNs72@47Y8myaVsDYC75QYK6GnvcbZ@OH44sHoQIsNzoDgZDI6SNu0CeNh3rgdlHrcC4PcAZo7jraEE5v2O2YwvddH/4jX4GCY0l54F0pZC/B5dpSfz@4NzvjZ7GZ00Gs@Zha6f7nXOIIXbvwYbTv8L5nm81nyGvPwL6@n/cKs95s2geyQNLjwlISexyTk88v/CIeUpHB6Q7xx/x8LKIHdstrZRGf2dtFAD@8EmGzAuYHaIbM992QyOV4aqace3/9y5@/sye1tPj@/f3Uxuj6Ef5bDo/HhnV9bZO@0FWT3twS5/j8K4fCIHd6MDhfbkxMYOYw5jFMY92GcwTiHcQHjchEWGmgBgy8cfAWMarHNQTIHyRwkc5DMQTIHyRwkc5DML2FcwWAwQDrnMEoYIJ9X4xcmL7507@XF4XT2yqtH2fFrJ/n89P7Z@cXl1YPXHz5648233n7n3ffe/@DDjz7@5NPPPv/iy6@@/ubb777/4ceffv7lerG4@fXxE1bwUlR1I5cr1Wpjnzof4nqz7Z799vsffy62F9XhX9pkHH6yxd8)
[Answer]
# 19. [pbrain](http://www.parkscomputing.com/applications/pbrain/), 58 bytes
```
+++++++++++++++++++++++++++++++++++++++++++++++++.+++++++.
```
Prints ASCII values 49 and 56 (`18`).
[Try it online!](https://tio.run/##K0gqSszM@/9fm1SgB6P//wcA "pbrain – Try It Online")
[Next toolbox](https://tio.run/##dVZZt9s0EH5ufkUIlJtwqlLn9m49ZT3sOxzgADeXVpZlW4ksqVqSuCz/mucyM7KTW5YHeb6RNKtGI7s@ttYsX2humjB9a3o9e3DGy0LO7s2WgZcawemWeyAXMK6u4MOZk9yz6CWuchET17pHWFXOIW2sIV43Vp9fNgSVoN3atUlsEDnNqp5r27zEMKF5CEoMk6YxiLzobSJgrK5oMQTZlbpnPNzmGvHSouGhQz6V0jfKkAc7sr638C15aJGgTCl5l4nJJBq1ISTDju8J1ck08ojY1SUymsQ9F22fozngZWaUYbXmm5EprdUjrnMyCEOyasKKGyaGNJWphFNoEvomMDmmIZQDFSxmyn2lDEe1QoJlDEG0oDNT8FWrLNhCLm3e2MqqopMVrcJjE8oY3lnDBmtrSojQKtCqtuvkMXph6xqSIrxykVhTqQFs5Z7ADr/OjV563meXfB9iNh6YsFlbYGATT0OkUpE41k6FIx8PnXclhepItIJYOjJYyWgTBlCBVsqW1LKTJhLCXMqOg/4hAtnhGumQHhPJjkHIyPG7VbhaQ01b1FtLb7ipLEGsv1p5WUK1EyTnkLDQynEuKIp0QFgAtRVks7akx/ooB9qyhsjAejj2ZgA0lbyS5MYhRVB2QkWy0OjetfYAwAdUBd7iFM1DOR3iazzcCaKqk0St3WKem4A@tjxscggt78dktqVoUbaV@/FGKxwmSp9DWuNgqcSlNSdDa77lzDpp1tXmH@zVwGenWMlLCRfcVvLl@XFG5qZCdEj22tJM0oqP9AzAhm2s4QQsGt1oSZW/sVFnQNKal70H7wkrUq71FmscrqoS2ay2ekQJVeIy1F1pNd38jntlh0vY8dgqETLSRLbSK8pdx/dQrgiUwbply2pkdAabUQ1M4TfWa6xzkzroVbu8ZHlQqN@Waymi2kp2bAFQVaTKighmEbSox3EPRd7KSC0UOMUaLH5HLQYB1P7ZQM@RtrQM8Q/XxFEzcKjb2Z30Y3EfmfHqOi91qjKy2LvDDgvEJe/o4XAptJhl12@IxcYUCHjeqYoFaEFdXqFDcfQYFQe0PCLmetcf2FNAeDGgz25kJEAX1@Nl7djtzuqllw11JY85SZo6HmKqGC/3tEZbbUVT1joiuQd4iI0eoQwYOuVzyfsU0HiAy8CJYjjQueXz2xwUhDTHiSYpSk6QFX2hnlKgYgwyWExPaLk7dia61yIDOudABxbaCBuyDqWzHLycrSTUlTURzTqd20UwkCJaM3bXUYMJtqPsh2daUU@iiy94DCPO6iP3nvyLPn85tvfQd7gPtlkiezz6KDR96b5F2TnNI3kUW/hb4BWhJDOJ2FHhHPqh8LDvHcKG6JqGul/0qXPH@eSjJr8SvN5U5MlUUMuWtCejeVfSOSbjweLwD7PFkY9pqwL8sDCSZkbGsbduVQwY5q5VXmcKvjtO/y07FYhYePlzX9oFTHGf0PPnEO/NC9U5OKop9NJWq3IycTZEVcFPFSTsiTIuxfligre3tHuYHWfwSc4zkIc4H6YXIO9NA7ODvvtddTbPKmFtAt5pOdXSzAeNi@nj6cWjyR0jdzgDgrPZ5E7eZmycjvPWH6Ay00EY5O6gufvJVXBi82HHAqaP@ugf8RocjHPaC@9CpRoJPi/uFeeLu6MzYbG4mdwZNN/nDrp/ddQ4gRdu@gRte/wvmRfLRfYa8/Avr@fDwmLwmzaB7Jg0uPCUhIHHJBTLy/8Ih5TkcAZDovX/Hwsogd2qPthEZ4520cAAbwWYbcC5gdoxswP3dDa7v7bKzAO@/9XB38XTFy@K5flZcTq5PoF/lpN705Nbv7bI3moryB5vCXLjy4X4@OCf3ExOVvsHD2AUMJYwTmE8hHEG4xzGBYzLVVwZoCUMsfLwlTDq1b4AyQIkC5AsQLIAyQIkC5AsQLK4hHEFg8MA6ULAqGCAfFFPX5m9@trd11cnizfusTcfFMvTh2fnF5dXjx6//c67773/wYcfffzJp599/sWXX339zbffff/Djz/9/Mv1anXz65OnvBRV3bRqvdHGumc@pO1u//y33//4c7W/qE/@MpYJ@LeWfwM)
[Answer]
# 22. [MarioLANG](https://esolangs.org/wiki/MarioLANG), 44 bytes
```
+++++++++++++++++++++:
=====================
```
Boring but shortest.
[Try it online!](https://tio.run/##y00syszPScxL//9fGxuw4rLFBv7//5qXr5ucmJyRCgA "MarioLANG – Try It Online")
[Next Toolbox](https://tio.run/##dVZZf9s2DH@OP4XnrYu9X5RVTuMkW3ff933GaUtRlESbIlkettUd33rPGQBKdrrjgcQfJAECIAjSdqExen6rmK79@I3x9eT@OStyMTmZzD0rFIKzDXNALqBdXUHHMiuYy4ITOMt4iEypDmFZWou0Npp4VRu1uKwJSk6rlW0iXyOyKis7pkz9HJNxxbyXvB/UtUbkeGciAW1USZPei7ZQXcb8Xa7mz01q5lvkYyFcLTVZsKXddwb6gvkGCcoUgrWJ6ESClmtCwm/ZjlAVdS0OKLu6REaRuGO86ZI3ezxPjNRZpdh6YApj1ICrFAzCEKyKsGQ6432YiljAKdQRbeMYHF0TSo7yLCTKXCk1Q7VcwM7oAm9AZ6Jgq5JJsIFYmrSwEWVJJ8sbicfGpdasNTrrd1tRQLiSnmaVWUWH3nNTVRAU7qQNxOpS9mAjdgS22Fs7WOlYl0xynQ9pc59xk7T5DPbE0@CxkCSOuVNiS8dD510KLlsSLcGXljYsRTARHShBK0VLKNEKHQhhLEXLQH/vgWhxjnQIh4HMDk6IwLDfSJytIKcN6q2E00yXhiDmXyWdKCDbCZJxSDLfiGHMS/K0R5gAleG0Z2VIj3FB9LTJaiI96@DY6x7QUHRSkBn7EEHacRloh1p1tjF7ADagKrAWh2gc0mnvX@3gThCVrSBqzAbjXHu0sWF@nVxoWDcEsyl4g7KN2A03WmLTQbjk0gpbFgucWjHaaMU2LDNW6FW5/gd71fPJqKxghYALbkrx/PgwIlJRIdoHe2VoJCrJBnoOYJ2tjWYEDG66VoIyf22CSoCkFSs6B9YTlqRcqQ3mOFxVydO2yqgBRVSJ05B3hVF081vmpOkvYctCI7lPSBHZCCcpdi3bQboikBrzNpuXA6MSWA9qYAj7UK0wz3VsoVZt05RhXqJ@U6wED3IjskMJgKwiVYYH2BZBg3osc5DkjQhUQoGTWY3Jb6nEIIDcP@/pAmlD0@B/f00sFQOLuq3ZCjck94EZrq51QsUyIYO1228xQWx0lh4OG32DUbbdmlgsTJ6AY60sMw8lqE0zdCiWHqN8j@YHlNnOdnv2DBBeDKizaxEI0MV1eFnb7G5ldcKJmqqSw5hERRUPMWWMEzuao6WmpCFjLJFUAxz4Ro9QAhka5VLKu@hxcw@XgRFFd6Byi2d3OUgIoQ8DdZQUHC9K6iGfoqdk9MIbDI9vmD1UJrrXPAE6Z08H5psAC5IOqZIcvJyNINQWFRGVtSqVC68hRDSnzbalAuNNS9H3T5WkmkQXn7PgB5zUB@Yc2Rdc6hmWd9@1uA6WGSI7PPrAFfV034JorWKBLAoN/BZYSSiKRAJWVDiHrk88rHt7t8G7uqbqF1xs7WE8uqDIrgivNyV51CXksiHtUSvWFnSOUTvYsf/DbLClY9pIDx@WjKQzLcJQWzcyeHRz20inEgXbLaN/y1Z6IgZe/lSXth5D3EW0/Bn4e3MrWwtHNYZa2ihZjEbW@CBL@FRBwB5LbWOYzkZ4ewuzg9FhBJ/kNAJxCNN@eAbyTtcw2us7bcvzaVIJcyOwTomxEnraa5yNH44vXhsdabHFERCcTEZHaZk2YTyMG7eHUo97YZA7wu1Ooy3hxKb9ihkMH/TRH/EaDAxTWgvvQilrATbPTvLF7N5gjJ/NbkZHveZTZqH6lweNI3jhxo9xb4f/kmk@nyWrMQ7/snraT8x6u2kRyA5BgwtPQeh5DEI@v/wPd0hJcqffiDfu/30BJbBaVvs90ZjDvrhBD@84mPaAcwO1Q2R77slkcroyUk89vv/l3t7Zk9vbfL5YLM5G18fwZzk@GR/f@doie6esIDu8VYgPTzxy6Rd0fDM6Xu7u34eWQ5tDO4P2ANo5tAW0C2iXywB9AY0vHfQCWrXc5SCXg1wOcjnI5SCXg1wOcjnI5ZfQrqAxaCCdc2glNJDPq/ELkxdfuvfy8ng6e@UkO301n589OF9cXF69/vDNt95@59333v/gw48@/uTTzz7/4suvvv7m2@@@/@HHn37@5dfr5fLm0eMnrOClqOpGrtaq1cY@dT7EzXbXPfvt9z/@XO4uquO/tMk4/K7F3w)
[Answer]
# 24. [Chez Scheme](https://cisco.github.io/ChezScheme/), 12 bytes
```
(display 23)
```
[Try it online!](https://tio.run/##K07OSM1N1QWSVf//a6RkFhfkJFYqGBlr/v8PAA "Chez Scheme – Try It Online")
[Next toolbox.](https://tio.run/##dVZXY9s2EH62foWqNrXUmq4pxyttuvfey3ITEARJSCCAYEhiOv51n927Ayk5bfoA3ncAbuJwoO1CY/T8VjFd@/HD8fXk5IwVuZgcTeaeFQrB6Zo5IBcwrq7gwzIrmMuCE7jKeIhMqQ5hWVqLtDaaeFUbdX5ZE5ScdivbRL5CZFVWdkyZ@hkm44p5L3k/qWuNyPHORALaqJIWvRdtobqM@btczZ9Z1My3yMdCuFpq8mBD1rcGvgXzDRKUKQRrE9GJBC1XhITfsC2hKupa7FF2dYmMInHHeNOlaHZ4nhips0qx1cAUxqgBVykZhCFZFWHJdMb7NBWxgFOoI/rGMTm6JpQC5VlIlLlSaoZquQDLGAJvQGei4KuSSbCBXJq0sRFlSSfLG4nHxqXWrDU6660tKSFcSU@ryiyjw@i5qSpICnfSBmJ1KXuwFlsCG/xaO3jpWJdccp0PybjPuEnafAY28TR4LCSJY@2UONLx0HmXgsuWREuIpSWDpQgmYgAlaKVsCSVaoQMhzKVoGejvIxAtrpEO4TCR2T4IERh@1xJXK6hpg3or4TTTpSGI9VdJJwqodoLkHJLMN2KY85Ii7REWQGU42awM6TEuiJ42WU2kZx0ce90DmopOCnJjlyIoOy4DWahVZxuzA@ADqgJvcYrmoZx28dUO7gRR2Qqixqwxz7VHHxvmVymEhnVDMpuCNyjbiO1woyUOHYRLIS1xZLHApSUjQ0u2ZpmxQi/L1b/Yq55PTmUFKwRccFOKZ@eHGZGaCtE@2UtDM1FJNtAzAKtsZTQjYNDoSgmq/JUJKgGSVqzoHHhPWJJypdZY43BVJU9mlVEDiqgSl6HuCqPo5rfMSdNfwpaFRnKfkCKyFk5S7lq2hXJFIDXWbTYvB0YlsBrUwBR@Q7XEOtexhV61SUuGeYn6TbEUPMi1yPYtAKqKVBkewCyCBvVY5qDIGxGohQInsxqL31KLQQC1f9bTc6QNLUP8/TWx1Aws6rZmI9xQ3HtmuLrWCRXLhAz2br/BArHRWXo4bPQNZtl2K2KxMXkCjrWyzDy0oDat0KFYeozyHZrvUWY72@3YU0B4MaDPrkQgQBfX4WVts7ud1QknaupKDnMSFXU8xFQxTmxpjbaakqaMsURSD3AQGz1CCWTolEsl76JH4x4uAyOK4UDnFk/vclAQQu8n6igpOV6U9IV6ip6K0QtvMD2@YXbfmehe8wTonD0dmG8CbEg6pEpy8HI2glBbVERU1qrULryGFNGaNpuWGow3LWXfP1GSehJdfM6CH3BSH5hz5F9w6cuwvfuuxX2wzRDZ4tEHruhL9y2I1ioWyKPQwN8CKwlFkUjAjgrn0PWFh31vFzZEV9fU/YKLrd3PRxcU@RXh9aYij7qEWjakPWrF2oLOMWoHFvt/mDWOdExr6eGHJSPpTIsw9Na1DB7D3DTSqUTBd8vov2UjPREDL3/qSxuPKe4iev4U4r25la2FoxpDL22ULEYja3yQJfxUQcIeSW1jmM5GeHsLs4XZYQaf5DQDeQjTfnoG8k7XMNvrO27Ls2lSCWsj8E6JsRJ62mucjd8YXzwYHWixwRkQnExGB2mbNmE8zBu3g1KPe2GQO0Bzx9GWcGLTfscMpvf66B/xGhwMU9oL70IpawE@z47y89m9wRk/m92MDnrNx8xC9y/3Gkfwwo0foW2H/yXTfD5LXmMe/uP1tF@Y9X7TJpAdkgYXnpLQ85iEfH75nHBISQqnN8Qb9/@xgBLYLaudTXRmbxcN9PBOgMkGnBuoHTLbc48nk@OlkXrq8f0vd/7OHt/e5vPz84vT0fUh/LMcHo0P7/zaIjs8Toj3bzpyz61kXLjbNA9vRoeL7ckJjBzGHMYpjPswzmCcw7iAcbkICw20gMEXDr4CRrXY5iCZg2QOkjlI5iCZg2QOkjlI5pcwrmAwGCCdcxglDJDPqxcmL7507@XF4SuvHmXHr53k98/OLy6vHrz@xsM333r7nXffe/@DDz/6@JNPP/v8iy@/@vqbb7/7/ocff/r5l1@vF4ub3x49ZgUXVd0sV602T1yI68326e9//PnXYntRHf6tTcbhR1v8Aw "Python 2 – Try It Online") Arcyóu is the new language.
[Answer]
# 28. [Haskell](https://www.haskell.org/), 6 bytes
```
f x=27
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwtbI/H9uYmaegq1CQVFmXomCikKahuZ/AA "Haskell – Try It Online") Declares a function `f` which takes any argument and returns `27`.
[Next toolbox:](https://tio.run/##dVZXY9s2EH62foWqDklt6Jpyvdp0772n5SQgCJKQQADBkMR0/Os@u3cHUnLa9AG87wDcxOFA24XG6MWtYrr24zfH15OTM1bkYnJvsvCsUAhON8wBuYBxdQUfllnBXBacwFXGQ2RKdQjL0lqktdHEq9qo88uaoOS0W9km8jUiq7KyY8rUTzEZV8x7yftJXWtEjncmEtBGlbTovWgL1WXM3@Vq/tSiZr5FPhbC1VKTB1uyvjPwLZhvkKBMIVibiE4kaLkmJPyW7QhVUdfigLKrS2QUiTvGmy5Fs8eLxEidVYqtB6YwRg24SskgDMmqCEumM96nqYgFnEId0TeOydE1oRQoz0KizJVSM1TLBVjGEHgDOhMFX5VMgg3k0qSNjShLOlneSDw2LrVmrdFZb21FCeFKelpVZhUdRs9NVUFSuJM2EKtL2YON2BHY4tfawUvHuuSS63xIxn3GTdLmM7CJp8FjIUkca6fEkY6HzrsUXLYkWkIsLRksRTARAyhBK2VLKNEKHQhhLkXLQH8fgWhxjXQIh4nMDkGIwPC7kbhaQU0b1FsJp5kuDUGsv0o6UUC1EyTnkGS@EcOclxRpj7AAKsPJZmVIj3FB9LTJaiI96@DY6x7QVHRSkBv7FEHZcRnIQq0625g9AB9QFXiLUzQP5bSPr3ZwJ4jKVhA1ZoN5rj362DC/TiE0rBuS2RS8QdlG7IYbLXHoIFwKaYUjiwUurRgZWrENy4wVelWu/8Ve9XxyKitYIeCCm1I8PT/MiNRUiPbJXhmaiUqygZ4BWGdroxkBg0bXSlDlr01QCZC0YkXnwHvCkpQrtcEah6sqeTKrjBpQRJW4DHVXGEU3v2VOmv4Stiw0kvuEFJGNcJJy17IdlCsCqbFus0U5MCqB9aAGpvAbqhXWuY4t9KptWjLMS9RvipXgQW5EdmgBUFWkyvAAZhE0qMcyB0XeiEAtFDiZ1Vj8lloMAqj9s56eI21oGeLvr4mlZmBRtzVb4YbiPjDD1bVOqFgmZLB3@y0WiI3O0sNho28wy7ZbE4uNyRNwrJVl5qEFtWmFDsXSY5Tv0eKAMtvZbs@eAsKLAX12LQIBurgOL2ub3e2sTjhRU1dymJOoqOMhpopxYkdrtNWUNGWMJZJ6gIPY6BFKIEOnXCp5Fz0a93AZGFEMBzq3eHKXg4IQ@jBRR0nJ8aKkL9RT9FSMXniD6fENs4fORPeaJ0Dn7OnAfBNgQ9IhVZKDl7MRhNqiIqKyVqV24TWkiNa02bbUYLxpKfv@sZLUk@jicxb8gJP6wJwj/4JLX4bt3Xct7oNthsgOjz5wRV@6b0G0VrFAHoUG/hZYSSiKRAJ2VDiHri887Hv7sCG6uqbuF1xs7WE@uqDIrwivNxV51CXUsiHtUSvWFnSOUTuw2P/DbHCkY9pIDz8sGUlnWoSht25k8BjmtpFOJQq@W0b/LVvpiRh4@VNf2npMcRfR8ycQ782tbC0c1Rh6aaNkMRpZ44Ms4acKEvZQahvDbD7C21uYHcwOM/gkpxnIQ5j103OQd7qG2V7fcVuezZJKWBuBd0qMldCzXuN8fH988froSIstzoDgZDI6Stu0CeNh3rg9lHrcC4PcEZo7jraEE5v1O@YwfdBH/4jX4GCY0V54F0pZC/B5fi8/n784OOPn85vRUa/5mFno/uVB4wheuPFDtO3wv2SWL@bJa8zDf7ye9Qvz3m/aBLJD0uDCUxJ6HpOQLy6fEQ4pSeH0hnjj/j8WUAK7ZbW3ic4c7KKBHt4JMNmAcwO1Q2Z77tFkcrwyUs88vv/l3t/5o9vbfHF@cXYyup7CP8v03ng6vEaIn1msuHC3LyJPTYAWsOlOb0bT5e7kBEYOYwHjFMZrMM5gnMO4gHG5DPAtYPClg6@AUS13OcjlIJeDXA5yOcjlIJeDXA5y@SWMKxgMBkjnHEYJA@Tz6rnJ8y@8tJzO5i@/cvxqfnp@9cb9t95@59333v/gw48@/uTTzz7/4suvvv7m2@@@/@HHn37@5dffrpfLmwePoE@u1vaxC3GzffL7H3/@tdxdVNO/tck4/EyLfwA "Python 2 – Try It Online")
```
['elf', 'logicode', 'visual-basic-net-mono', 'python2-pypy', 'silos', 'pushy', 'agony']
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f!"#$%&\'()*+,-./1234569:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^`cdghijkopqrtuvwxz{|}~\x7f'
```
[Answer]
# 30. Visual Basic .NET (Mono), 9 bytes
```
MSGBOX 29
```
Pops up a system dialog box containing 29. Very similar to `alert` in javascript. It is case insensitive, but is usually written as `MsgBox`.
This can't be tested on TIO because `MsgBox` is a system window and that can't be seen online. The easiest way to test it is by pasting the code into a `.vbs` text file and running it on Windows. A `.vbs` file uses VBScript, a scripting version of VB that is very similar (`MsgBox` is the same between the two).
It's fun to use `MsgBox` again as that was the very first thing I ever programmed. In fifth grade, I made a series of `MsgBox` scripts to mess with friends.
[Next Toolbox](https://tio.run/##dVZZk@M0EH7e/IowxTIJjId1Zudalqs4iqsooIACJsOuLMm2ElnS6kji5fjXPA/dLTuZ5XiQ@2tJfarVsutja83iTjPThOm705ujR@esKuXRydEisEojONswD@QSxvU1fFjhJPNF9BJXGY@Jad0jFMI5pI01xOvG6ourhqDitFu7NvE1IqcL0TNtm1eYgmsWguLDpGkMIs97mwgYqwUthiC7SvcFC/e5hr@yaFjokE@V9I0y5MGWrO8sfCsWWiQoU0nWZWIyiUatCcmwZTtCdTKNPKDi@goZTeKe8bbP0ezxIjPKFLVm65GprNUjrnMyCEOyasKKmYIPaapSBafQJPSNY3JMQygHyouYKfNCGYZquQTLGAJvQWem4KtWWbCFXNq8sZVC0MnyVuGxcWUM66wpBmsrSgjXKtCqtqvkMXpu6xqSwr1ykVgj1AA2ckdgi1/nRi8967NLvg8xGw8Ft1lbKMAmngZPlSJxrB2BIx8PnbeQXHUkKiCWjgwKGW3CAARopWxJLTtpIiHMpewY6B8ikB2ukQ7pMZHFIQgZGX43CldrqGmLemvpDTPCEsT6q5WXFVQ7QXIOSRFaOc4FRZEOCAugtpxs1pb0WB/lQNuiITKwHo69GQBNJa8kubFPEZQdV5EsNLp3rd0D8AFVgbc4RfNQTvv4Gg93gqjqJFFrN5jnJqCPLQvrHELL@jGZbcVblG3lbrzRCoeJ0ueQVjiKVOHSipGhFduwwjppVmL9D/Z64LNTRcUqCRfcCvnq/Dgjc1MhOiR7ZWkmacVGeg5gXaytYQQsGl1rSZW/tlFnQNKaVb0H7wkrUq71Bmscrqri2ay2ekQJVeIy1F1lNd38jnllh0vYsdgqHjLSRDbSK8pdx3ZQrgiUwbotFmJkdAbrUQ1M4TfWK6xzkzroVdu8ZFlQqN9WK8mj2sji0AKgqkiV5RHMImhRj2MeiryVkVoocKposPgdtRgEUPvnA71A2tIyxD9cE0fNwKFuZ7fSj8V9YMar67zUSWRksXeHLRaIS97Rw@FSaDHLrl8Ti40pEPCsU6II0IK6vEKH4ugxKvdocUCF612/Z88A4cWAPruWkQBdXI@XtSvud1YvvWyoK3nMSdLU8RBTxXi5ozXaagVNWeuI5B7gITZ6hDIo0CmfS96ngMYDXAZGFMOBzi1f3uegIKQ5TDRJUXKCFPSFekqBijHIYDE9oWXu0JnoXvMM6JwDHVhoI2zIOpTOcvBytpJQV9VEdNHp3C6CgRTRmrHbjhpMsB1lP7zQinoSXXzOYhhxVh@Z9@Rf9PnLsL2HvsN9sM0S2eHRR67pS/ctys5pFsmj2MLfAhOEkswkYkeFc@iHwsO@tw8bomsa6n7Rp84d5pOPmvxK8HpTkScjoJYtaU9Gs66ic0zGg8XhH2aDIx/TRgX4YSlIujAyjr11o2LAMLet8jpT8N0x@m/ZqkDEwsuf@9I2YIr7hJ6/hHhv71Tn4Kim0EtbrarJxNkQlYCfKkjYM2VcirP5BG9vZXcwO87gk5xnIA9xNkzPQd6bBmYHfaedOJ9llbA2Ae@0nGppZoPG@fTp9PLJ5IGRW5wBwaOjyYO8zdg4Heet30NlpoMwyD1Ac6fJCTix2bBjDtMHffSPeAMOxhnthXdBqEaCz/OT8mL@cHQmzOe3kweD5lPmoPuLg8YJvHDTZ2jb43/JrFzMs9eYh395PRsW5oPftAlkx6TBhackDDwmoVxc/Uc4pCSHMxjirf//WEAJ7Fb13iY6c7CLBgZ4L8BsA84N1I6ZHbjnR0enK6vMLOD7L/b@zp/f3ZWLi8uLcnJzDP8sxyfT4/E1Qny//SFPdx0BvcgI9k/J8e3keLl79AhGCWMB4wzGYxjnMC5gXMK4WsalAVrB4EsPXwmjXu5KkCxBsgTJEiRLkCxBsgTJEiTLKxjXMBgMkC45DAED5Mv6taPXH76xPJ7N33zrpDh9uzx7fH5x9eSdp@@@9/4HH3708Seffvb5F19@9fU33373/Q8//vTzLzfL5e2vz54zLmTdtGq11p2x7oWPabPdvfzt9z/@XO4u6@O/jC04/E3LvwE)
[Answer]
# 31. [Python 2 (PyPy)](http://pypy.org/), `print-31`
```
print--31-1
```
[Try it online!](https://tio.run/##K6gsycjPM9ItqCyo/P@/oCgzr0RX19hQ1/D/fwA "Python 2 (PyPy) – Try It Online")
`--31` is the same thing as `31`, then `-1` subtracts 1, making it 30.
[Next toolbox](https://tio.run/##dVZne9s2EP5s/QpVbWqpNV1TjleadDzd8@leluuAIEhCAgEEQxLT8a/72b07kJLT8QG89wDcxOFA24XG6PmdYrr24yfj68nJGStyMTmazD0rFILTNXNALmBcXcGHZVYwlwUncJXxEJlSHcKytBZpbTTxqjbq/LImKDntVraJfIXIqqzsmDL1C0zGFfNe8n5S1xqR452JBLRRJS16L9pCdRnz97mav7ComW@Rj4VwtdTkwYasbw18C@YbJChTCNYmohMJWq4ICb9hW0JV1LXYo@zqEhlF4o7xpkvR7PA8MVJnlWKrgSmMUQOuUjIIQ7IqwpLpjPdpKmIBp1BH9I1jcnRNKAXKs5Aoc6XUDNVyAZYxBN6AzkTBVyWTYAO5NGljI8qSTpY3Eo@NS61Za3TWW1tSQriSnlaVWUaH0XNTVZAU7qQNxOpS9mAttgQ2@LV28NKxLrnkOh@ScZ9xk7T5DGziafBYSBLH2ilxpOOh8y4Fly2JlhBLSwZLEUzEAErQStkSSrRCB0KYS9Ey0N9HIFpcIx3CYSKzfRAiMPyuJa5WUNMG9VbCaaZLQxDrr5JOFFDtBMk5JJlvxDDnJUXaIyyAynCyWRnSY1wQPW2ymkjPOjj2ugc0FZ0U5MYuRVB2XAayUKvONmYHwAdUBd7iFM1DOe3iqx3cCaKyFUSNWWOea48@NsyvUggN64ZkNgVvULYR2@FGSxw6CJdCWuLIYoFLS0aGlmzNMmOFXparf7BXPZ@cygpWCLjgphQvzg8zIjUVon2yl4ZmopJsoGcAVtnKaEbAoNGVElT5KxNUAiStWNE58J6wJOVKrbHG4apKnswqowYUUSUuQ90VRtHNb5mTpr@ELQuN5D4hRWQtnKTctWwL5YpAaqzbbF4OjEpgNaiBKfyGaol1rmMLvWqTlgzzEvWbYil4kGuR7VsAVBWpMjyAWQQN6rHMQZE3IlALBU5mNRa/pRaDAGr/rKfnSBtahvj7a2KpGVjUbc1GuKG498xwda0TKpYJGezdfoMFYqOz9HDY6BvMsu1WxGJj8gQca2WZeWhBbVqhQ7H0GOU7NN@jzHa227GngPBiQJ9diUCALq7Dy9pm9zurE07U1JUc5iQq6niIqWKc2NIabTUlTRljiaQe4CA2eoQSyNApl0reRY/GPVwGRhTDgc4tnt/noCCE3k/UUVJyvCjpC/UUPRWjF95genzD7L4z0b3mCdA5ezow3wTYkHRIleTg5WwEobaoiKisValdeA0pojVtNi01GG9ayr5/piT1JLr4nAU/4KQ@MOfIv@DSl2F7912L@2CbIbLFow9c0ZfuWxCtVSyQR6GBvwVWEooikYAdFc6h6wsP@94ubIiurqn7BRdbu5@PLijyK8LrTUUedQm1bEh71Iq1BZ1j1A4s9v8waxzpmNbSww9LRtKZFmHorWsZPIa5aaRTiYLvltF/y0Z6IgZe/tSXNh5T3EX0/DnEe3MnWwtHNYZe2ihZjEbW@CBL@KmChN1KbWOYzkZ4ewuzhdlhBp/kNAN5CNN@egbyTtcw2@s7bsuzaVIJayPwTomxEnraa5yNH48vHo0OtNjgDAhOJqODtE2bMB7mjdtBqce9MMgdoLnjaEs4sWm/YwbTe330j3gNDoYp7YV3oZS1AJ9nR/n57MHgjJ/NbkYHveZjZqH7l3uNI3jhxrdo2@F/yTSfz5LXmId/eT3tF2a937QJZIekwYWnJPQ8JiGfX/5HOKQkhdMb4o37/1hACeyW1c4mOrO3iwZ6eC/AZAPODdQOme25p5PJ8dJIPfX4/pc7f2dP7@7y@fnF@eno@hD@WQ6PxofDa4SY7jYCeoER7J4OZNzq8GZ0uNienMDIYcxhnMJ4COMMxjmMCxiXi7DQQAsYfOHgK2BUi20OkjlI5iCZg2QOkjlI5iCZg2R@CeMKBoMB0jmHUcIA@bwavzR5@ZUHry4Op7PXXj86fuNk/vDs/OLy6tGbj5@89fY77773/gcffvTxJ59@9vkXX3719Tfffvf9Dz/@9PMv14vFza@3T1nBS1HVzXKlWvPMx/Vm@/y33//4c7G9qA7/0ibj8B8t/gY)
[Answer]
# 33. [Minkolang](https://github.com/elendiastarman/Minkolang), 9 bytes
```
"332"(O).
```
[Try it online!](https://tio.run/##y83My87PScxL//9fydjYSEnDX1Pv/38A "Minkolang – Try It Online")
[Next Toolbox](https://tio.run/##dVZXY9s2EH62foWqNrXUmq4pxytNuvfeK3ITEARJSCCAYEhiOv51n927AynZHQ/gfQfgJg4H2i40Rs9vFNO1Hz8aP56cnLEiF5OjydyzQiE4XTMH5ALG1RV8WGYFc1lwAlcZD5Ep1SEsS2uR1kYTr2qjzi9rgpLTbmWbyFeIrMrKjilT32Eyrpj3kveTutaIHO9MJKCNKmnRe9EWqsuYv83V/M6iZr5FPhbC1VKTBxuyvjXwLZhvkKBMIVibiE4kaLkiJPyGbQlVUddij7KrS2QUiTvGmy5Fs8PzxEidVYqtBqYwRg24SskgDMmqCEumM96nqYgFnEId0TeOydE1oRQoz0KizJVSM1TLBVjGEHgDOhMFX5VMgg3k0qSNjShLOlneSDw2LrVmrdFZb21JCeFKelpVZhkdRs9NVUFSuJM2EKtL2YO12BLY4NfawUvHuuSS63xIxn3GTdLmM7CJp8FjIUkca6fEkY6HzrsUXLYkWkIsLRksRTARAyhBK2VLKNEKHQhhLkXLQH8fgWhxjXQIh4nM9kGIwPC7lrhaQU0b1FsJp5kuDUGsv0o6UUC1EyTnkGS@EcOclxRpj7AAKsPJZmVIj3FB9LTJaiI96@DY6x7QVHRSkBu7FEHZcRnIQq0625gdAB9QFXiLUzQP5bSLr3ZwJ4jKVhA1Zo15rj362DC/SiE0rBuS2RS8QdlGbIcbLXHoIFwKaYkjiwUuLRkZWrI1y4wVelmu/sFe9XxyKitYIeCCm1LcnR9mRGoqRPtkLw3NRCXZQM8ArLKV0YyAQaMrJajyVyaoBEhasaJz4D1hScqVWmONw1WVPJlVRg0ookpchrorjKKb3zInTX8JWxYayX1CishaOEm5a9kWyhWB1Fi32bwcGJXAalADU/gN1RLrXMcWetUmLRnmJeo3xVLwINci27cAqCpSZXgAswga1GOZgyJvRKAWCpzMaix@Sy0GAdT@WU/PkTa0DPH318RSM7Co25qNcENx75nh6lonVCwTMti7/QYLxEZn6eGw0TeYZdutiMXG5Ak41soy89CC2rRCh2LpMcp3aL5Hme1st2NPAeHFgD67EoEAXVyHl7XNbndWJ5yoqSs5zElU1PEQU8U4saU12mpKmjLGEkk9wEFs9AglkKFTLpW8ix6Ne7gMjCiGA51bPL/NQUEIvZ@oo6TkeFHSF@opeipGL7zB9PiG2X1nonvNE6Bz9nRgvgmwIemQKsnBy9kIQm1REVFZq1K78BpSRGvabFpqMN60lH3/TEnqSXTxOQt@wEl9YM6Rf8GlL8P27rsW98E2Q2SLRx@4oi/dtyBaq1ggj0IDfwusJBRFIgE7KpxD1xce9r1d2BBdXVP3Cy62dj8fXVDkV4TXm4o86hJq2ZD2qBVrCzrHqB1Y7P9h1jjSMa2lhx@WjKQzLcLQW9cyeAxz00inEgXfLaP/lo30RAy8/KkvbTymuIvo@XOI9/pGthaOagy9tFGyGI2s8UGW8FMFCXsitY1hOhvh7S3MFmaHGXyS0wzkIUz76RnIO13DbK/vuC3PpkklrI3AOyXGSuhpr3E2fji@eDA60GKDMyA4mYwO0jZtwniYN24HpR73wiB3gOaOoy3hxKb9jhlM7/XRP@JjcDBMaS@8C6WsBfg8O8rPZ/cGZ/xsdj066DUfMwvdv9xrHMELN36Cth3@l0zz@Sx5jXn4l9fTfmHW@02bQHZIGlx4SkLPYxLy@eV/hENKUji9Id64/48FlMBuWe1sojN7u2igh7cCTDbg3EDtkNmeezqZHC@N1FOP73@583f29OYmn59f5hejx4fwz3J4ND4cXiPEdLcR0AuMYPd0IJP@VBDdeWgPr0eHi@3JCYwcxhzGKYz7MM5gnMO4gHG5CAsNtIDBFw6@Aka12OYgmYNkDpI5SOYgmYNkDpI5SOaXMK5gMBggnXMYJQyQz6vxC5MXX7r38uJwOnvl1aPs@LWTfH56/@z84vLqwesPH73x5ltvv/Pue@9/8OFHH3/y6Weff/HlV19/8@133//w408///J4sbj@9cnTgpeiqpvlSrXa2Gc@xPVm2z3/7fc//lxsL6rDv7TJOPxki78B)
Never heard of this one before, I have no idea how it works. It just did weird stuff and I went "ok fine" and got it to print what I wanted. :D
] |
[Question]
[
Given a string containing only the characters `-`, `|`, `+` and newline determine the longest straight line contained in it. A straight line is either an uninterupted run of `-`s and `+`s in a single row or an uninterupted run of `|`s and `+`s in a single column.
So for example:
```
|
| ----
|
--+--
|
|
```
There are 3 lines here one vertical, two horizontal, with the vertical line being the longest since it is 6 characters.
Your challenge is to write a program or function which takes a string as input and gives the length of the longest line.
You may assume that the input is perfectly rectangular. That is that every row has the same number of characters. You may also assume that the input contains at least 1 of the non-whitespace characters (`-`, `|`, and `+`).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), answers will be scored in bytes with fewer bytes being the goal.
## Test cases
```
|
| ----
|
--+--
|
|
```
6
```
+
```
1
```
---|---
|
|
|
```
4
```
-
-|||||
-
```
1
```
|
|
+----+
```
6
```
|+-
-+|
```
2
```
|
|
|
| +
|
| |
|
| |
+-+
```
4
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ ~~13~~ 12 bytes
```
OZ%3;ƲḂŒgẎ§Ṁ
```
[Try it online!](https://tio.run/##y0rNyan8/98/StXY@timhzuajk5Kf7ir79Dyhzsb/j/cveXhjq6HO6cdbtf8/19dXZ1LAQhqFMAAxtYFAjRxXV1tXV1kNRhsoFk6CjADFZAUaCOxFbCwERqB1tYgW42FAVesC9GsWwMCMB6yG2og2mrgtnFpg/yljaSoRluXS1e7BqwPAA "Jelly – Try It Online")
Takes input as a list of lines/a character matrix
~~First attempt, can probably be improved by a lot.~~ Ports [wasif's Vyxal answer](https://codegolf.stackexchange.com/a/235802/66833) for the conversion to `1`/`0` matrices, so make sure you drop them an upvote as well.
-1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!
## How it works
```
OZ%3;ƲḂŒgẎ§Ṁ - Main link. Takes a matrix M on the left
O - Convert each character to an ordinal
Ʋ - Last 4 links as a monad f(ord(M)):
Z - Transpose
%3 - Mod by 3 (|,+ -> 1, space -> 2, - -> 0)
; - Concatenate to ord(M)
Ḃ - Mod each 2 (1 -> 1, 45, 43 -> 1, 32, 124, 2, 0 -> 0)
Œg - Over each list, group adjacent equal elements
Ẏ - Drop into a list of lists
§ - Sums of each (lists of 0 -> 0, lists of 1 -> length)
Ṁ - Maximum
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
ø3%«É€γOZ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8A5j1UOrD3c@alpzbrN/1P//0dHGRjoKyNjQyARVAIFjdRTwKzcxRcYEleM2HW6IMYJNolsoUx7LBQA "05AB1E – Try It Online")
-2 thanks to @ovs
Takes charcode matrix
This takes inspiration from Arnauld answer:
* Modulo input matrix by 2 (Or is odd number) to get horizontal lines. (Run of 1)
* Take the input matrix again and transpose (to get the columns) then Modulo by 3 are odd numbers? (Vertical runs)
* Pair them, for each
* Group consecutive equals
* Sum them up
* Take the maximum
And that's the result
[Answer]
# JavaScript (ES10), 88 bytes
Expects a matrix of ASCII codes.
```
m=>Math.max(...m.map(r=>r.map(H=(v,x)=>[m.map(V=r=>V=r[x]%3%2*-~V),H=v%2*-~H])).flat(3))
```
[Try it online!](https://tio.run/##bY/LTsMwEEX3@QqrUVUPqS1El8iREAJlw6pSN2kWlus0QXnhmCgIw68Hx2lpEL0L68zMnYdfecdbofJGk6o@yCFlQ8nCF64zWvIeU0pLCw1WLFQOIoa7dQ8sjKfCjtmSfeI@WW6WdzfkewfriHUOowSApgXXeAMwKPn2niuJV2m7AqokPzznhdx@VALfAtX1Vqu8OmKgbVPkGi/2le/7@2phR9TqiYsMt4iF6NNDqEQMtReftbgjx3Jsb1aJi8UYCyoyrh7t5x40BoB72y7qqq0LSYv6iFNcjskvGJCVQU7eiYmV9zdPSEDI3POP7dUeushxMGN0hV2PXWbmC6/A6CNTCzGjztFpqZnM5ne8F4x/CKa6CYhHAoN@AA "JavaScript (Node.js) – Try It Online")
### How?
Given an ASCII code \$v\$, we use \$v\bmod 2\$ and \$(v\bmod 3)\bmod 2\$ to identify horizontal and vertical characters respectively.
```
char. | code | % 2 | % 3 % 2
-------+------+-----+---------
' ' | 32 | 0 | 0
'+' | 43 | 1 | 1
'-' | 45 | 1 | 0
'|' | 124 | 0 | 1
```
### Commented
```
m => // m[] = input matrix
Math.max(... // return the maximum of all values
m.map(r => // for each row r[] in m[]:
r.map(H = // initialize H to a non-numeric value
(v, x) => // for each value v at position x in r[]:
[ m.map(V = // initialize V to a non-numeric value
r => // for each row r[] in m[]:
V = r[x] % 3 % 2 // increment V if r[x] is '|' or '+'
* -~V // otherwise, clear V
), // end of map()
H = v % 2 // increment H if v is '-' or '+'
* -~H // otherwise, clear H
] //
) // end of map()
) // end of map()
.flat(3) // deep flatten
) // end of Math.max()
```
[Answer]
# [Dyalog APL](https://www.dyalog.com/), ~~31~~ 27 bytes
```
{≢⍉↑↑⊆⍨¨(↓⍵∊'-+'),↓⍉⍵∊'|+'}
```
-4 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs).
[Try it online!](https://tio.run/##fU9BCsIwELz7ir1FWResSvE7paIIBYWexHgtthBQ/IGnPkA/4FP2I3WTRk1VHAKbDDM7k2ST0XybZOslpVmS56u0aRZcHHdcXtiUXJzsqQo29b3uc3Fmc@NDpQjVYOiepWc0qr14AWKIIjZXBQINL8iVBB2WCFvmW2uherJuGqwLgPAH3ggzZ5RU/ZEcTieeSG8rbtuQtqDOrtiX0N2yaD@FTjQWnRNpIVE7ZzR6tvgd7ieGlH5PCN8@r9WqBw)
Expects a matrix of characters.
```
⍵∊'-+' Turn - and + into 1s and other characters into 0s
↓ and split the matrix into individual rows.
⍵∊'|+' Take the original matrix, turn | and + into 1s,
⍉ transpose it,
↓ and again split it into rows.
, Join the rows together.
⊆⍨¨ Extract streaks of 1s for each row.
↑↑ Reduce the level of nesting twice to obtain a
3-dimensional array where the 1-streaks, padded
with 0s at the end, lie along the last dimension.
≢⍉ Finally, get the length of this dimension,
i.e., the length of the longest 1-streak.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
…-+|ü2Iδå`ø«€γOà
```
Input as a matrix of characters.
Port of [*@cairdCoinheringaahing*'s Jelly answer](https://codegolf.stackexchange.com/a/235790/52210), so make sure to upvote him as well.
[Try it online](https://tio.run/##yy9OTMpM/f//UcMyXe2aw3uMPM9tObw04fCOQ6sfNa05t9n/8IL//6OjlRSUdFBwDRofgWN1FPAr10XBBJXjMR1mijYSm0THUKY8FgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX3lo26GFj5rWBNuGVupwKfmXlkAl/j9qWKarXXN4j1HEuS2HlyYc3nFoNVDduc3@hxf81zm0zf5/tJICENQogEFMHpSjCwRwDkxGV1dbVxdFGQZHSUdBSQEBIHLayBwFLBywLqCNNSi2YmOBVOpCDdCtAQEgjWxzDVR1DcKKmDxtkHe0lWIB).
**Explanation:**
```
…-+| # Push string "-+|"
ü2 # Create overlapping pairs of this string: ["-+","+|"]
δ # Map over this pair of strings:
I å # Check for each character in the input-matrix if it's in this string
` # After the map: pop and push both matrices separated to the stack
ø # Zip/transpose the top one; swapping rows/columns
« # Merge the lists together
€γ # Split each inner list into groups of the same digits
O # Sum each inner-most list
à # And take the flattened maximum of these sums
# (after which it is output implicitly as result)
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~192~~ ~~175~~ ~~169~~ 167 bytes
```
n->{int i,r,l=0,b,h[]=new int[n[0].length];for(var a:n)for(r=i=0;i<a.length;i++){l=(r=(b=a[i])==45|b==43?r+1:0)>l?r:l;l=(h[i]=b>45|b==43?h[i]+1:0)>l?h[i]:l;}return l;}
```
[Try it online!](https://tio.run/##rVPBcoIwEL37FTueYCCItr1Io9PpyUNPHhkOASLExsCEYMdRv50mFtDpdGptm0PY7L6XvH3DrsmWoHX62iScVBW8ECZgPxiAXqMRJDkRGSUxp8CEonJFEnqq9SdYaDi0S2dB0UqBpYkyjMJIp8pa2cEJcvy4t6xjzhKoFFH6sy1YChvzrLVUkolMk4jMKruT0UqpqKrLPrGAquC1YoUA3CfP6KzgK5pCUqS0EWi2N8KYK12OfTd28zDCgr4ZuaEI/cjjVGQqj4JVIa0tkUCmwjaxxAz7AXskLSJgjmPvOdYFK8YkZJGN8f3DIdb73Vw646lvz/hcTnmgQbmu43jW1825g5hYo45SdyUF6KgJBud@e/uMmwtj4RjwhdGf19Bshzb2VPGs@U9Skp1lu1dJCBC6mXTrSwg5CP1K3v@TjsF3Tk@@dHpo5CPnqpDhDwUPP3T@GXfZy3JXKbrxilp5pZ4kxYXVTYln2rPOf5PdjuRttImhdaN8bN4B "Java (JDK) – Try It Online")
-6 thanks to Kevin Cruijssen; -2 thanks to Celingcat!
[Answer]
# [R](https://www.r-project.org/), ~~87~~ 86 bytes
Or **[R](https://www.r-project.org/)>=4.1, 72 bytes** by replacing two `function` appearances with `\`s.
*-1 byte thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
function(s,b=function(x,r=rle(x))max(r$l[r$v==1]))max(apply(s%%2,1,b),apply(s%%3,2,b))
```
[Try it online!](https://tio.run/##pVFBCoMwELznFSIKG9wcrKX0kgf07q3tQUsFIY2SxGIhf7exFrEo0tI5zSxLZnaiuoJ3RSMvpqwkaMz5KFpUXIkrtJTeshZUII4quHMen4dBVtfiAToMNxhjTnHUCW6cpl0Bt8yosoVGilIbEMPGVYA2SteiNEB8z8F6L5A3Zw7kc85YxNh0Z8Z99E/SpxQbU@zT6iCN4zvElFLydRBv8nA04d6cL/ptf/FzV9rppQvkbxM25Ga2B2ErVSW/VWWHmHYshUT9t0Vrkbsn "R – Try It Online")
That turned out shorter than I expected.
Takes input as matrix of character codes.
### Explanation
```
function(s, # function takes s as input
b=function(x, # helper function for rows/columns
r=rle(x)) # compute run length encoding
max( # get maximum
r$l[r$v==1] # of run lengths where value is one
))
max( # maximum of
apply( # apply to
s%%2, # the matrix with ones for | and +
1,b), # the helper function along columns
apply( # apply to
s%%3, # the matrix with ones for - and +
2,b) # the helper function along rows
)
```
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 52 bytes
```
n/.zip]"-":a;{{{.a"+"+\?-1>*}%"ø"%{,}/}/"|":a;}%$-1=
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/P09fryqzIFZJV8kq0bq6ulovUUlbSTvGXtfQTqtWVYlBSbVap1a/Vl@pBqSgVlVF19D2/38FIKhRAAMuKFsXArhQpXR1tXV1kZWhswE "GolfScript – Try It Online")
Explanation:
```
n/. split input on newline
.zip duplicate and zip(transpose rows and columns) the copy
] put them in an array
"-":a; has "-" for first copy and "|" for the zipped copy
{ map over the copies of input
{ for each line
{ map over each char
.a"+"+\?-1>* returns char if == a ("-" or "|") or "+", otherwise 0
}%
"ø"% splits on ø(null char, "\x00") to get array of lines
{,}/ for each, get length
}/
"|":a; sets a to "|" for the next copy
}%
left with array of line lengths
$-1= sort and get last element, aka get max
implicit print
```
There is probably some completely different approach that is smaller, but I am pretty happy with how small I got this.
The difference between `{...}~`(map) and `{...}/`(for each) is that map returns an array, while for each dumps them on the stack, essentially `{...}~~`. Rearranging and using `/` allowed me to save a few chars I didn't think I could, so that's pretty cool.
The code has a literal null char that stackoverflow isn't liking, so I replaced it with `ø`. The tio.run link should work.
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), 124 bytes
```
int f(char*a){char*b=a,*c=a,l=0,h=0;for(;*a;++a)*a%2?l=l>++h?l:h:h=0,*a>10?*a%5>2?*a=0,l=l>++*c?l:*c:*c=0,++c:c=b;return l;}
```
[Try it online!](https://tio.run/##hZNRj4IwDMff@RSNl0tgdQmiaMIEP8h5D3PgQTLRID45Pzu34ckNxdAQ1na/tn@WIU4n@iNE0xRlDXtX5Lwi3Lu26y7mUyL0S8b@NI99tj9WLiOcIXKP8M9gI2OZIOYbGeWRBqaEJzN/o7fCJNCLztwJIjRChH50ClFEIt6xKqsvVQmS3ZqPohTykmawLo7nusr4IXEco@jAi9L14OoAGEkgZl/fEMNkqxMAClrbll1ItVnh/y6lSOkTPBBOWDcpsCdBn8Z@CIOh1Wve9dL6lK3x1bHKFo8y2vWnyljrPQ8JLcGqU6NsXcZDc0Zo1S27OoWtMIrK7rvq97U7v/PRmqmsvHrDq97Z3VXi4/t0/lynUSSOlxrWa3NLZ55x2mxWppINIME4Mh9HFuNIOI4sx5HVK/L3f/jMuTW/ "C++ (gcc) – Try It Online")
This is my first time submitting a code here, so I'm open to any improvements. I don't think I used anything past `C++98`. The function takes a C-string as input and modifies it.
### Explanation
```
int f(char* a) { // Take a C-string as input
char* b = a; // Preserve a pointer to the beginning
char* c = a; // Use the first row of a to keep track of
// vertical line lengths; this is tracked by c.
char l = 0; // Maximal line length
char h = 0; // Current horizontal line length
for (; *a; ++a) { // *a may be '\0' (0), '\n' (10), ' ' (32),
// '+' (43), '-' (45), or '|' (124).
if (*a % 2) { // Current character is '+' (43) or '-' (45)
++h; // Increment current horizontal line length
l = l > h ? l : h; // Update maximal line length
}
else {
h = 0; // Reset horizontal line length
}
if (*a != 10) {
if (*a % 5 > 2) { // Current character is '+' (43) or '|' (124)
*a = 0; // Set current character to 0 (only needed
// for the first row)
++*c; // Increment current column's vertical line
// length
l = l > *c ? l : *c; // Update maximal line length
}
else {
*c = 0; // Reset current column's vertical line length
}
++c;
}
else { // Current character is '\n' (10)
c = b; // Reset column tracker
}
}
return l;
}
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~114~~ 109 bytes
*-5 bytes thanx to Alex Waygood*
```
lambda i,j=''.join:max(map(len,g('[-+]+',i)+g('[|+]+',j(map(j,zip(*i.split('\n')))))))
import re
g=re.findall
```
[Try it online!](https://tio.run/##dY/NDsIgEITvPAXpBZRuL95M@iTWA6Y/LgFKkIMa3r3S1pja6pxmyezHrHuEa28PQ1tWg5bmUkuKuSoZK1SP9mjknRvpuG5s3nF2AnEWLMedGIc4DWoKqPyJju@xuDmNgbPKst0sgsb1PlDfkK70TdGiraXWg/NoA295lmU0KdJJ5O0hiXy/AwiAZWbtEyl9R1ZgugiKhadb/wOQasRlla3ZLsEMhjiKwP9uccbETwsixrvFFB5e "Python 3 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 74 bytes
```
Lw$`([-+]+)|[|+]((?<=(.)*.).*¶(?<-3>.)*(?(3)^)[|+])*
$1¶_$#2*
%C`.
N^`
0G`
```
[Try it online!](https://tio.run/##K0otycxLNPz/36dcJUEjWlc7VluzJrpGO1ZDw97GVkNPU0tPU0/r0DYgT9fYDsjVsNcw1ozTBCnR1OJSMTy0LV5F2UiLS9U5QY/LLy6By8A94f9/XQUFhRog1gUyuBQgHF0gAHNqQDIgAOToamvraoPluRR0QVQNWAFMD5gDAA "Retina – Try It Online") Explanation:
```
Lw`([-+]+)|[|+]((?<=(.)*.).*¶(?<-3>.)*(?(3)^)[|+])*
```
List all overlapping matches of either horizontal or vertical lines. A .NET balancing group is used to ensure that all of the characters in the vertical line are in the same column. All overlapping matches are needed to ensure that all possible lines are detected, as simple overlaps would only detect the horizontal line of an upside-down `L` shape.
```
L$`
$1¶_$#2*
```
For each match list the horizontal line and a string of underscores of the length of the vertical line. (There is always at least one underscore even when there was no vertical match but the horizontal match is always at least length `1` in this case anyway.)
```
%C`.
```
Count the number of characters in each line.
```
N^`
```
Sort in descending order.
```
0G`
```
Take the maximum.
[Answer]
## [Nibbles](http://golfscript.com/nibbles), 12 bytes
```
`/+.:$`'!$ 3%.%~$%$~,$]
```
That's 23 nibbles which are encoded in 0.5 bytes each. Nibbles isn't on TIO yet.
Translation:
```
`/ special fold
+ concat
. map \a ->
: concat
$ input
`' transpose
! special zip
$ input
3
% mod
. map \b ->
%~ split by \c ->
$ a
% mod
$ c
~ 2
,$ length b
] max
```
Usage: pass the input in via the command line as a list of strings. You could use stdin instead but then instead of a $ you'd need ;;@ for the stdin as lines.
```
nibbles longestline.nbl "[\"-+ \",\" | ]\"]"
```
This is inspired by the 05ab1e solution, although surprisingly longer.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 26 bytes
```
MX#*:(J*ZgR'-sALgR'|s)Jn^w
```
[Try it online!](https://tio.run/##K8gs@P/fN0JZy0rDSysqPUhdt9jRB0jVFGt65cWV//@voKurWwPEXApAUINM/tctAgA "Pip – Try It Online") (Uses the `-r` flag to take input as lines of stdin, but would also work without the flag if input lines were given as command-line arguments.)
### Explanation
```
MX#*:(J*ZgR'-sALgR'|s)Jn^w
g is lines of input; s is space; n is newline; w is
regex matching runs of whitespace (implicit)
gR'-s In g, replace all hyphens with spaces
Z Zip (transpose rows for columns)
J* Join each column into a string
AL To the list of columns, append this list:
gR'|s In g, replace all pipes with spaces
( )Jn Join the resulting list on newlines
^w Split on runs of whitespace
#*: Get the length of each run of non-whitespace characters
MX Take the maximum
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 14 bytes
```
∷¹ǒ∷ÞT"ƛ0ZfĠv∑
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=G&code=%E2%88%B7%C2%B9%C7%92%E2%88%B7%C3%9ET%22%C6%9B0Zf%C4%A0v%E2%88%91&inputs=&header=&footer=)
-7 thanks to @AaronMiller and @emanresuA
[Answer]
# [Ruby](https://www.ruby-lang.org/), 103 bytes
```
->m{eval"(m#{e=".map{|x|x+[' ']}.join.gsub('"}|',' ')+m.transpose#{e}-',' ')).split.map(&:length).max"}
```
[Try it online!](https://tio.run/##fU9Ra4MwGHz/fsVHWpaE7AusjD0M3B8pY9gZuxa10sTiMP52l2hxroXdSy7H3eVybnbfwzpPBnorO3NJCybKVWcSpsu07nzrW7XlyN97fTwdKr23zU5w1nv@GFSpSu3OaWXrkzUh1dMkS23r4uBihXh4LUy1d18y3FrWD5nJ0RnrhJWAH5sME7STXXDgcn520pDzHrBunMV1rj/TohBjSAKYKgOITcgwwOMIuHIKgL86kSJaem45g9ULLDtx4VELjv/z0PM014QdfrnlngT78/wsTW3kI4Du@8YM/B7RreJv1TT/avOKgJSP2Q3cDhx@AA "Ruby – Try It Online")
* takes a 2d array as input.
We use eval to repeat `e` two times by interpolation.
`e`= adds a column of spaces, joins and calls gsub..
to swap `|` or `-` with a space, we do it on both input and input transposed.
Then we split to get our desired chunks of lines and we get the max length
[Answer]
# [Perl 5](https://www.perl.org/), 94 bytes
```
sub{$s=$_=pop;max((map y///c,/[-+]+/g),map{map$c=/[|+]/?$c+1:0,$s=~/^.{0,$_}(.?)/mg}0..y///c)}
```
[Try it online!](https://tio.run/##bVJdT8IwFH3vr2hI4z66rmDUh41mPuiTCi/6BEhwjGWRsYXWBLKOP@Grv84f4my3IYjepO29555z2tw0j9bLywotWMXfXgrEGZqyPMv9dLYxzXSWwy2lNHToiOAJprHlKKxQC4WMjiSe0ACFuOd1HSXd0We3UNm0NN3Aomlcdl231ltl5adbiETEBWf9vnE7uDF8AKAKCevY50TFCU4IJuSY8ycHV40XrnfQU5WykT9Wv3ZwAQBpdETq2Fe1rjY9OnQD60fh5haJCSBYKvb5P@zDgVuxbGt50pcHc1w/SY0ELLK1HvqImq4dWOZ4ji3KJ047tx1V6HhOY24VtTrdmog7KNrkFrtGU78FIYozwc7QQnWtBszXyUpAzWRMdwMje/38eDc8w7btwfARDu@MI2YHagdNhEoShSKaMy0erzo@KKuvLBdJtuIVebhPuPC8J5Esmfoy3w "Perl 5 – Try It Online")
[Answer]
## [Wolfram](https://www.wolfram.com/language/), 98 bytes
```
Max[Length/@Flatten[Map[r|->SequenceCases[r,{#2..}],#]&@@@{{#,"-"|"+"},{Transpose@#,"|"|"+"}},2]]&
```
Explanation
```
Max[ Max of
Length /@ Flatten[ Length of
Map[r |-> For each row
SequenceCases[r, {#2 ..}], #] & Sequences of
@@@ {{#, "-" | "+"}, {Transpose@#, "|" | "+"}}, - or + in the input
| or + in the transpose of the input
2]] &
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
WS⊞υιIL⌈⁺Eυ⌈⪪⭆ι№-+λ0E§υ⁰⌈⪪⭆υ№|+§λκ0
```
[Try it online!](https://tio.run/##dYzBCoMwDIbvPkXw1NIWvHsanoQNBJ@gOLFltcpsNw99966x6G0/hOTPn3yDku9hkSbGr9JmBNLa1bvevbWdCKXQ@U0Rz0HTuujS0pFGbo7cRzs5RR5y17OfSWf8lsyKl@euX412JJMw0hyaxSdAKVjJwVDKoaxKbBjfXGuf446Eiv6n@IsSkHJ@GQ4vehGz6hgFAIRUIg0FZCOSDhMwQSUjGBPsyAsQ2MJxcP5kE8XH/AA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation:
```
WS⊞υι
```
Input the strings into an array.
```
IL⌈⁺
```
Output the length of the maximum line in either of the following:
```
Eυ⌈⪪⭆ι№-+λ0
```
For each string in the array, replace each character with `1` if it is `-` or `+` otherwise `0`, then split the result on `0`s and take the maximum string of `1`s. This results in a list of strings that have the lengths of the longest line in each row.
```
E§υ⁰⌈⪪⭆υ№|+§λκ0
```
For each column, build up a string of `1`s and `0`s corresponding to whether each character is `|` or `+` or not, then split on `0`s and take the maximum again, resulting in a list of strings that have the lengths of the longest line in each column.
[Answer]
# Scala, 92 bytes
```
l=>(l.flatMap(_ split "[ |]")++l.transpose.flatMap(_.mkString split "[ -]")).map(_.size).max
```
[Try it in Scastie!](https://scastie.scala-lang.org/HkWtbCXmRpiEMORfYB1AcA)
Takes a `Seq[String]`.
## Slightly longer solution, 94 bytes
```
l=>(for((m,c)<-Seq(l->"[ |]",l.transpose->"[ -]");r<-m;p<-r.mkString split c)yield p.size).max
```
[Try it in Scastie!](https://scastie.scala-lang.org/SzZOYbpIRwmcpdZzSRfquQ)
Takes input as a `Seq[Seq[Char]]`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 19 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
"-|"¬c@zY ôkXi+ÃmÊn
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=Ii18IqxjQHpZIPRrWGkrw23Kbg&input=IiAgICB8ICAgICAgCiAgICB8ICAtLS0tCiAgICB8ICAgICAgCiAgLS0rLS0gICAgCiAgICB8ICAgICAgCiAgICB8ICAgIg)
```
"-|"¬c@zY ôkXi+ÃmÊn :Implicit input of string U
"-|"¬ :Split "-|" into an array of characters
c :Flat map
@ :By passing each X at 0-based index Y through the following function
zY : Rotate U 90 degrees Y times
ô : Split at characters that return truthy (non-empty string)
k : When the following characters are removed
Xi+ : "+" prepended to X
à :End map
m :Map
Ê : Length
n :Sort
:Implicit output of last element
```
] |
[Question]
[
**The [bounty](https://codegolf.stackexchange.com/help/bounty) expires in 5 days**. Answers to this question are eligible for a +100 reputation bounty.
[Adám](/users/43319/ad%c3%a1m) wants to **reward an existing answer**:
>
> [This](https://codegolf.stackexchange.com/a/270056/43319) well-explained answer is the first in APL here, and therefore qualifies for [this](https://codegolf.meta.stackexchange.com/a/17363/43319) bounty.
>
Your task is simple. Post a snippet in any language that if the snippet is repeated n times, will output n in decimal, octal, and hexadecimal, in that order, separated in spaces. n is an integer larger than zero. There is no leading zeroes. Shortest answer wins
## Example
If the snippet is `ABC` then the test case is
```
ABC
1 1 1
ABCABC
2 2 2
ABCABCABCABCABCABCABCABCABC
9 11 9
ABCABCABCABCABCABCABCABCABCABCABCABC
12 14 C
ABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABCABC
18 22 12
```
[Answer]
## Perl, 30 bytes
```
printf"\r%d %o %x",++$n,$n,$n;
```
Go back to the beginning of the line, increment counter and print counter overwriting the old output.
[Answer]
# JavaScript, ~~54 53 51~~ 47 bytes
*Saved 4 bytes thanks to @user81655*
```
var d=-~d;d+` ${d[b='toString'](8)} `+d[b](16);
```
I'm actually kinda surprised this works.
### Explanation
```
var d=-~d; // `var` let's `d` not throw an error if it's not defined
// -~ essentially increments the variable
d+ // decimal
` ${ // space character
d[b='toString'](8) // octal
} ` // space character
+d[b](16) // Hexadecimal
```
[Try it online](http://vihanserver.tk/p/esfiddle/?code=var%20d%3Dd%2B1%7C%7C1%3B%5Bd%2Cd.toString(8)%2Cd.toString(16)%5D.join%60%20%60%3B)
[Answer]
# Japt, 12 bytes
```
[°TTs8 TsG]¸
```
*Thanks to @ETHproductions* for saving 2 bytes!
Same as my ùîºùïäùïÑùïöùïü answer.
[Answer]
# C++, ~~205~~ 179 bytes
```
int main(){};static int c=1;
#define v(x) A##x
#define u(x) v(x)
#define z u(__LINE__)
#include <cstdio>
class z{public:z(){++c;};~z(){if(c){printf("%d %o %x",--c,c,c);c=0;}}}z;//
```
(No trailing newline - when copied, the first line of the copy and last line of the original should coincide)
Basically, this works by making a sequence of static variables which, on construction, increment a global variable counter. Then, on destruction, if the counter is not 0, it does all its output and sets the counter to zero.
In order to define a sequence of variables with no name conflicts, we use the macro explained as follows:
```
#define v(x) A##x //This concatenates the string "A" with the input x.
#define u(x) v(x) //This slows down the preprocessor so it expands __LINE__ rather than yielding A__LINE__ as v(__LINE__) would do.
#define z u(__LINE__)//Gives a name which is unique to each line.
```
which somewhat relies on the quirks of the string processor. We use `z` many times to define classes/variables that will not conflict with each other when copied onto separate lines. Moreover, the definitions which must occur only once are placed on the first line, which is commented out in copies of the code. The `#define` and `#include` statements don't care that they get repeated, so need no special handling.
This code also features undefined behavior in the statement:
```
printf("%d %o %x",--c,c,c)
```
since there are no sequence points, but c is modified and accessed. LLVM 6.0 gives a warning, but compiles it as desired - that `--c` evaluates before `c`. One could, at the expense of two bytes, add the statement `--c;` before the outputs and change `--c` in `printf` to `c`, which would get rid of the warning.
---
Replaced `std::cout` with `printf` saving 26 bytes thanks to a suggestion of my brother.
[Answer]
# CJam, ~~20~~ ~~19~~ 18 bytes
```
];U):USU8bSU"%X"e%
```
*Thanks to @MartinBüttner for golfing off 1 byte!*
[Try it online!](http://cjam.tryitonline.net/#code=XTtVKTpVU1U4YlNVIiVYImUlXTtVKTpVU1U4YlNVIiVYImUlXTtVKTpVU1U4YlNVIiVYImUlXTtVKTpVU1U4YlNVIiVYImUlXTtVKTpVU1U4YlNVIiVYImUlXTtVKTpVU1U4YlNVIiVYImUlXTtVKTpVU1U4YlNVIiVYImUlXTtVKTpVU1U4YlNVIiVYImUlXTtVKTpVU1U4YlNVIiVYImUlXTtVKTpVU1U4YlNVIiVYImUlXTtVKTpVU1U4YlNVIiVYImUlXTtVKTpVU1U4YlNVIiVYImUl&input=)
### How it works
```
] e# Wrap the entire stack in an array.
; e# Discard the array.
U e# Push U (initially 0).
):U e# Increment and save in U.
S e# Push a space.
U8b e# Convert U to base 8 (array of integers).
S e# Push a space.
U"%X"e% e# Convert U to hexadecimal (string).
```
[Answer]
# ùîºùïäùïÑùïöùïü, 14 chars / 28 bytes
```
[⧺Ḁ,Ḁß8,Ḁⓧ]ø⬭;
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=&code=%5B%E2%A7%BA%E1%B8%80%2C%E1%B8%80%C3%9F8%2C%E1%B8%80%E2%93%A7%5D%C3%B8%E2%AC%AD%3B)`
First answer! Although there are probably better ways to handle this.
# Explanation
```
[⧺Ḁ,Ḁß8,Ḁⓧ]ø⬭; // implicit: Ḁ = 0
[⧺Ḁ, // increment Ḁ by 1
Ḁß8, // octal representation of Ḁ
Ḁⓧ] // hex representation of Ḁ
ø⬭; // join above array with spaces
// repeat as desired until implicit output
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 26 bytes
Uses [current release (6.0.0)](https://github.com/lmendo/MATL/releases/tag/6.0.0). Works on Octave.
```
0$N1+ttYUb8YAb16YA3$XhZc1$
```
### Examples
Once:
```
>> matl 0$N1+ttYUb8YAb16YA3$XhZc1$
1 1 1
```
Twice:
```
>> matl 0$N1+ttYUb8YAb16YA3$XhZc1$0$N1+ttYUb8YAb16YA3$XhZc1$
2 2 2
```
16 times:
```
>> matl 0$N1+ttYUb8YAb16YA3$XhZc1$0$N1+ttYUb8YAb16YA3$XhZc1$0$N1+ttYUb8YAb16YA3$XhZc1$0$N1+ttYUb8YAb16YA3$XhZc1$0$N1+ttYUb8YAb16YA3$XhZc1$0$N1+ttYUb8YAb16YA3$XhZc1$0$N1+ttYUb8YAb16YA3$XhZc1$0$N1+ttYUb8YAb16YA3$XhZc1$0$N1+ttYUb8YAb16YA3$XhZc1$0$N1+ttYUb8YAb16YA3$XhZc1$0$N1+ttYUb8YAb16YA3$XhZc1$0$N1+ttYUb8YAb16YA3$XhZc1$0$N1+ttYUb8YAb16YA3$XhZc1$0$N1+ttYUb8YAb16YA3$XhZc1$0$N1+ttYUb8YAb16YA3$XhZc1$0$N1+ttYUb8YAb16YA3$XhZc1$
16 20 10
```
### Explanation
The number of elements in the stack is used to indicate how many times we've run the snippet
```
0$ % specify zero inputs for next function, in case this is not the first
% occurence of the snippet.
N % number of elements in stack
1+ % add one
tt % duplicate twice. We now have three copies of the number
YU % convert to string (decimal)
b8YA % bubble up number and convert to octal string
b16YA % bubble up number and convert to hex string
3$XhZc % join top three elements (strings) with a space
1$ % specify one input for next function. If the program ends here, that next
% function will be implicit display, so it will print the top of the stack.
% Else the stack will be left with one element more than at the beginning of
% the current snippet
```
[Answer]
## OCaml, 198 bytes
```
;;open Char
;;(if Sys.argv.(0).[0]='~'then Sys.argv.(0).[0]<-'\000'else Sys.argv.(0).[0]<-chr(1+int_of_char Sys.argv.(0).[0]));let n=1+int_of_char Sys.argv.(0).[0]in Printf.printf"\r%d %o %x"n n n
```
Includes a trailing newline and requires that the filename starts with a tilde (I used `~.ml`; you can run it with `ocaml \~.ml`) because it's the highest-valued standard printable ASCII character. Abuses the fact that all characters in a string are mutable and `Sys.argv.(0).[0]` is the first character in the filename.
It should only work for n = 1 to 126, because the ASCII code for `~` is 126 and I'm adding one to the output. It could be made two bytes shorter if we only want n = 1 to 125. After it's repeated 126 times, it'll cycle back to n = 1.
This is my first ever golf so any comments or improvements would be much appreciated.
Ungolfed version:
```
;; open Char
;; if Sys.argv.(0).[0] = '~'
then Sys.argv.(0).[0] <- '\000'
else Sys.argv.(0).[0] <- chr (1 + int_of_char Sys.argv.(0).[0])
;; let n = 1 + int_of_char Sys.argv.(0).[0] in
Printf.printf "\r%d %o %x" n n n
```
[Answer]
# [TeaScript](http://github.com/vihanb/TeaScript), ~~21~~ 20 bytes
```
[┼d,dT8),dT16)]j(p);
```
I should make it auto-close on `;`
[Try it online](http://vihan.org/p/TeaScript/#?code=%22%5B%2B%2Bd,dT8),dT16)%5Dj(p);%22&inputs=%5B%22%22%5D&opts=%7B%22int%22:false,%22ar%22:false,%22debug%22:false%7D)
## Explanation
`┼` becomes `++`
```
// Implicit: d = 0
[ // Start array
++d, // Increment d, decimal value
dT8), // d to base 8
dT16) // d to base 16
]j(p); // Join by spaces
// Implicit: Output *last* expression
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes
```
_&›¥D8τṅ$HWṄ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJfJuKAusKlRDjPhOG5hSRIV+G5hCIsIiIsIiJd)
[Try it Online 10 times!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJfJuKAusKlRDjPhOG5hSRIV+G5hF8m4oC6wqVEOM+E4bmFJEhX4bmEXybigLrCpUQ4z4ThuYUkSFfhuYRfJuKAusKlRDjPhOG5hSRIV+G5hF8m4oC6wqVEOM+E4bmFJEhX4bmEXybigLrCpUQ4z4ThuYUkSFfhuYRfJuKAusKlRDjPhOG5hSRIV+G5hF8m4oC6wqVEOM+E4bmFJEhX4bmEXybigLrCpUQ4z4ThuYUkSFfhuYRfJuKAusKlRDjPhOG5hSRIV+G5hCIsIiIsIiJd)
[Answer]
## Perl, 40 bytes
```
$_=<<'';printf"%d %o %x",(1+y/z//)x3;
:
```
There's a final newline behind the colon.
Treats everything after the first line as a here document and counts the `z` in it. For every further copy of the code one `z` is added. We have to add `1` to the count, because there's none for the first snippet (the one that is executed).
If additional output to stderr is allowed, we can omit the 2 single quotes `''` and can get down to 38 bytes. Without the `''` perl emits a warning about a deprecated feature.
[Answer]
# Mathematica, 76 bytes
Note that `n` should have no definitions before.
```
0;If[ValueQ@n,++n,n=1];StringJoin@Riffle[IntegerString[n,#]&/@{10,8,16}," "]
```
Here, the behaviour of `;` is used. The snippet above is one single `CompoundExpression`, however, when a couple of snippets are put together, there is still one `CompoundExpression` as is shown below. (Some unnecessary rearrangements are made.)
```
0;
If[ValueQ@n,++n,n=1]; StringJoin@Riffle[IntegerString[n,#]&/@{10,8,16}," "] 0;
If[ValueQ@n,++n,n=1]; StringJoin@Riffle[IntegerString[n,#]&/@{10,8,16}," "] 0;
If[ValueQ@n,++n,n=1]; StringJoin@Riffle[IntegerString[n,#]&/@{10,8,16}," "]
(* 3 3 3 *)
```
So one cannot make such snippet works if writting explicit `CompoundExpression`. Also, almost everything you like can be put before the first `;` such as `E`, `Pi` or `MandelbrotSetPlot[]`,.
[Answer]
## bash, 49 bytes
File `count.bash`:
```
((++n));trap 'printf "%d %o %x\n" $n $n $n' exit;
```
...no trailing newline.
Run:
```
$ bash count.bash
1 1 1
$ cat count.bash count.bash count.bash | bash
3 3 3
$ for i in $(seq 10) ; do cat count.bash ; done | bash
10 12 a
```
[Answer]
# Python 2, 54 bytes
```
n=len(open(__file__).read())/54;print n,oct(n),hex(n)#
```
No trailing newline. Outputs in the form `1 01 0x1`.
If that's not ok, 56 bytes
```
n=len(open(__file__).read())/56;print"%d %o %x"%(n,n,n)#
```
When pasted in front of each other, the length of the file gets longer by 1 line for each time pasted. The base case starts with 2 lines so you have to subtract 1 from the line length. Computation is suppressed by the comment.
[Answer]
# Python 2.x 140 bytes
This was not meant to be an overly competitive solution, but a method that I found amusing, being for one thing, an attempt at a **multithreaded** code golf.
```
import thread;n=eval("n+1")if"n"in globals()else 1;
def t(c):99**99;print("%s "*3)%(n,oct(n),hex(n))*(c==n)
thread.start_new_thread(t,(n,));
```
Keeps a counter, spawns a thread for each count and if the counter has not changed when the counters timer goes off after a completing an expensive math problem (instead of a timer to save bytes), the formatted string is printed.
Some example configurations and their outputs:
```
import thread;n=eval("n+1")if"n"in globals()else 1;
def t(c):99**99;print("%s "*3)%(n,oct(n),hex(n))*(c==n)
thread.start_new_thread(t,(n,));
Outputs 1 01 0x1
```
and fifteen copy pastes:
```
import thread;n=eval("n+1")if"n"in globals()else 1;
def t(c):99**99;print("%s "*3)%(n,oct(n),hex(n))*(c==n)
thread.start_new_thread(t,(n,));import thread;n=eval("n+1")if"n"in globals()else 1;
def t(c):99**99;print("%s "*3)%(n,oct(n),hex(n))*(c==n)
thread.start_new_thread(t,(n,));import thread;n=eval("n+1")if"n"in globals()else 1;
...
Outputs 15 017 0xf
```
[Answer]
## [Perl 5](https://www.perl.org/), 31 bytes
```
exit+printf"%d %o %x",(++$-)x3,
```
Uses the same approach as [my answer for 'I double the source, you double the output!'](https://codegolf.stackexchange.com/a/138918/9365).
[Try it online!](https://tio.run/##K0gtyjH9/z@1IrNEu6AoM68kTUk1RUE1X0G1QklHQ1tbRVezwlhnVJoG0v//AwA "Perl 5 – Try It Online")
[Answer]
# [APL (Dyalog APL)](https://www.dyalog.com/products.htm), 30 bytes
Requires `‚éïIO` to be `0`.
```
(+,8 16{(⎕D,⎕A)[⍺⊥⍣¯1⊢⍵]}¨⊢)⊃1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70qpTIxJz89PrEgZ8EWK7_E3NTigsTkVK5HfVM9_R-1TTBYWlqSpmtx00hDW8dCwdCsWgMo46IDJBw1ox_17nrUtfRR7-JD6w0fdS161Ls1tvbQCiBL81FXs-GS4qTk4psebkBTjIB8oJbgIGcgGeLhGcxVDWQAJR719mkAtR2e_qh3i5smiAAaYKj9qHezoYEBl5VrXgrcSRCHLFgAoQE)
The main idea is to use an ambivalent function, where the monadic variant would return the result, and the dyadic variant would keep track of the count.
```
(+,8 16{(⎕D,⎕A)[⍺⊥⍣¯1⊢⍵]}¨⊢)⊃1
‎⁡
(+,8 16{(⎕D,⎕A)[⍺⊥⍣¯1⊢⍵]}¨⊢) # ‎⁢The ambivalent function:
+ # ‎⁣ monadic: identity (*); dyadic: left + right
, # ‎⁤ concatenated with
8 16{(⎕D,⎕A)[⍺⊥⍣¯1⊢⍵]}¨⊢ # ‎⁢⁡‎⁣ octal and hexadecimal versions:
{(⎕D,⎕A)[⍺⊥⍣¯1⊢⍵]} # ‎⁢⁢ dyadic function to convert int to base-n string:
(⎕D,⎕A) # ‎⁢⁣ digits concatenated to alphabet
[ ] # ‎⁢⁤ indexed by
⍵ # ‎⁣⁡ right argument
⊥⍣¯1 # ‎⁣⁢ in base (returns digit vector, e.g. 42 in base-16 is [2, 10])
⍺ # ‎⁣⁣ left argument
¨ # ‎⁣⁤ applied to:
8 ⊢ # ‎⁤⁡ 8 and right argument,
16 ⊢ # ‎⁤⁢ 16 and right argument,
‎⁤⁣
# ‎⁤⁤‎⁤⁢To Summarize:
# ‎⁢⁡⁡‎⁤⁣ monadic version returns: [arg, oct(arg), hex(arg)]
# ‎⁢⁡⁢ dyadic version returns: [left + right, oct(right), hex(right)]
# since left argument is always 1 when snippet is repeated, we can simplify it to
# [1 + right, oct(right), hex(right)]
‎⁢⁡⁣
⊃ # ‎⁢⁡⁤pick first (extracts the current count)
# when snippet is repeated this would be in front of all the dyadic calls
# but not in front of the final monadic call
1 # ‎⁢⁢⁡The initial count
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
\*monadic `+` is the conjugate, but can be treated as identity for non complex inputs
[Answer]
# Awk, 33 bytes
```
{printf v" %o %x",v,v}BEGIN{v++}0
```
[Try it online!](https://tio.run/##SyzP/v@/uqAoM68kTaFMSUE1X0G1QkmnTKes1snV3dOvukxbu9ZgVAFEwf//XAA)
This solution abuses the `BEGIN` statements running before anything happens and the `0` at the end to prevent any other patterns from running.
[Answer]
# Ruby, 35 bytes
```
1;$.+=1;$><<"#$. %1$o %1$x"%$.*-~-0
```
Each snippet increments `$.` (which starts as 0 if no files have been read), but only the last outputs anything. `*-~-0` evaluates to `*1`, meaning print the string once, but with concatenation it becomes `*-~-01`, an octal expression evaluating to 0. Since `$><<` doesn't include a trailing newline, printing the empty string means printing nothing.
] |
[Question]
[
Output the area \$A\$ of a triangle given its side lengths \$a, b, c\$ as inputs. This can be computed using [Heron's formula](https://en.wikipedia.org/wiki/Heron%27s_formula):
$$ A=\sqrt{s(s-a)(s-b)(s-c)}\textrm{, where } s=\frac{a+b+c}{2}.$$
This can be written in various ways, such as
$$ A= \frac{1}{4}\sqrt{(a+b+c)(-a+b+c)(a-b+c)(a+b-c)}$$
$$ A= \frac{1}{4}\sqrt{(a^2+b^2+c^2)^2-2(a^4+b^4+c^4)}$$
See [Wikipedia](https://en.wikipedia.org/wiki/Heron%27s_formula#Formulation) for more. Related: [What are my dimensions?](https://codegolf.stackexchange.com/q/121811/20260)
The inputs will be three positive integers that [satisfy the triangle inequality](https://codegolf.stackexchange.com/q/199353/20260) and so are sides of a non-degenerate triangle. While the order of the three sides doesn't affect the output, you may not assume they're given in a particular order like sorted. You may take inputs in a list or tuple or the like. Any reasonable float output is fine.
**Test cases**
```
1 1 1 -> 0.4330
3 4 5 -> 6.0000
9 3 7 -> 8.7856
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 20 bytes
```
N@*Area@*SSSTriangle
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@9/PQcuxKDXRQSs4ODikKDMxLz0n9X9AUWZeSbSygq6dQpqCg4OCcqyCmoK@g0J1taGOAgjV6ihUG@somOgomIKYljoKQJ55be1/AA "Wolfram Language (Mathematica) – Try It Online")
Built-in.
---
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 22 bytes
```
((#.#)^2-2#.#^3)^.5/4&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@19DQ1lPWTPOSNcISMcZa8bpmeqbqP0PKMrMK4lWVtC1U0hzUI5VUFPQd1CorjbUUQChWh2FamMdBRMdBVMQ01JHAcgzr639DwA "Wolfram Language (Mathematica) – Try It Online")
-2 bytes by porting [loopy walt's Python answer](https://codegolf.stackexchange.com/a/250455/9288).
Takes input as a list. Using the formula \$A= \frac{1}{4}\sqrt{(a^2+b^2+c^2)^2-2(a^4+b^4+c^4)}\$.
---
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes
```
1##&@@(+##/2-{0,##})^.5&
```
[Try it online!](https://tio.run/##Fcc7CoAwEEXRrTwYCIrjXxELZZZgLwpBFC1iIelC1h4VbnGu0fbcjbbXpsOBIZRESiRKiPIqdQUT@XjNWhWm57rtTEhHHBABLVDIBc6VjD/PcDWjYbQ/e8Z3nffhBQ "Wolfram Language (Mathematica) – Try It Online")
Based on [chyanog's answer to another challenge](https://codegolf.stackexchange.com/a/11032/9288).
Using the formlula \$A=\sqrt{s(s-a)(s-b)(s-c)}\textrm{, where } s=\frac{a+b+c}{2}\$.
[Answer]
# [Dyalog APL](https://www.dyalog.com/products.htm), ~~16~~ 15 bytes
-1 thanks to @Bubbler.
```
.5*⍨0∘,×.-2÷⍨+/
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70qpTIxJz89PrEgZ8GCpaUlaboWN80e9U191DZBQ89U61HvCoNHHTN0Dk_X0zU6vB3I1dbXPLRCw1ABCDU1jBVMFEw1NSwVjBXMNSG6oYbADAMA)
```
┌──┼───────┐
.5 *⍨ ┌───┼────┐
0∘, ×.- ┌─┼──┐
2 ÷⍨ +/
0∘, left argument: input with 0 prepended 0 a b c
2÷⍨+/ right argument: sum of input divided by 2 (a+b+c)/2 = s
×.- left minus right, then take the product (0-s)(a-s)(b-s)(c-s)
.5*⍨ square root
```
`(0-s)(a-s)(b-s)(c-s)` is equivalent to `(s-0)(s-a)(s-b)(s-c)` as there is an even number of items being multiplied.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 13 bytes
```
{%*/x-/x%2}0,
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6pW1dKv0NWvUDWqNdDh4kpTMARBIG2sYKJgCqQtgSxzAL4FCGI=)
There is! -2 bytes thanks to @ovs.
```
{%*/x-/x%2}0, x: a length-3 array containing the three sides
0, prepend a 0
x%2 (0; a/2; b/2; c/2)
x-/ (0 a b c) - a/2 - b/2 - c/2
%*/ sqrt(product of the above)
```
---
# [K (ngn/k)](https://codeberg.org/ngn/k), 16 bytes
```
{%-s*/x-s:+/x%2}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6pW1S3W0q/QLbbS1q9QNarl4kpTMARBIG2sYKJgCqQtgSxzAOl9CX4=)
~~There must be a shorter way..?~~
```
{%-s*/x-s:+/x%2} x: a length-3 array containing the three sides
s:+/x%2 s: half sum of x
x- (a-s; b-s; c-s)
-s*/ -s * (a-s) * (b-s) * (c-s)
% sqrt
```
[Answer]
# [J](http://jsoftware.com/), 17 16 bytes
```
2%:[:*/0&,-+/%2:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jVStoq209A3UdHS19VWNrP5rcqUmZ@QrpCkYgiCMY6xgomCqAONZAvnmXKkVmSXq6lxgdQq6dgoGeibGxgZcEKVAvpmeARBwgRWD@BZ65hamZv8B "J – Try It Online")
*-1 thanks to [Bubbler's K approach](https://codegolf.stackexchange.com/a/250450/15469)*
The interesting insight (obvious when spelled out but not always when searching for a golf) is: When taking the product of an even number of elements, it is equivalent to taking the product of their negatives.
## original, 17 bytes
```
2%:[:*/+/-:@-0,+:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jVStoq209LX1da0cdA10tK3@a3KlJmfkK6QpGIIgjGOsYKJgqgDjWQL55lypFZkl6upcYHUKunYKBnomxsYGXBClQL6ZngEQcIEVg/gWeuYWpmb/AQ "J – Try It Online")
* `0,+:` Double each input and prepend 0
* `+/...-` Subtract each of those from sum of input
* `-:@` And halve each result
* `[:*/` Product
* `2%:` Root
[Answer]
# [Python](https://www.python.org), 47 bytes
```
lambda a,b,c:(4*a*a*b*b-(a*a+b*b-c*c)**2)**.5/4
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY39XMSc5NSEhUSdZJ0kq00TLQSgTBJK0lXA8jQBjGStZI1tbSMgFjPVN8Eom19QVFmXolGmoaljrGOuaYmRHTBAggNAA)
Classic boring solution. There might be a shorter way to express this formula, but I can't find it.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
HSạŻP½
```
[Try it online!](https://tio.run/##y0rNyan8/98j@OGuhUd3Bxza@z/aWMdExzT2cPt/AA "Jelly – Try It Online")
Don't ask me why the chaining works...
```
H # Half of
S # The sum of the input
ạ # Absolute difference with
Ż # The input, with a 0 prepended
P½ # Take the square root of the product
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0šDO;αPt
```
[Try it online](https://tio.run/##yy9OTMpM/f/f4OhCF3/rcxsDSv7/jzbWMdExjQUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/g6MLXfytz20MKPmv8z862lAHCGN1oo11THRMgbSljrGOeWwsAA).
**Explanation:**
Uses the default formula:
$$s=\frac{0+a+b+c}{2}$$
$$ A=\sqrt{abs(0-s)\times abs(a-s)\times abs(b-s)\times abs(c-s)}$$
```
0š # Prepend a 0 in front of the (implicit) input-triplet
D # Duplicate the list
O # Sum the copy
; # Halve the sum
α # Get the absolute difference between this sum and the values in the list
P # Take the product
t # Square root
# (which is output implicitly as result)
```
[Answer]
# [Python](https://www.python.org) NumPy, 32 bytes
```
lambda v:((v@v-2*v*v)*v@v)**.5/4
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3FXISc5NSEhXKrDQ0yhzKdI20yrTKNLWATE0tLT1TfROouqS0ovxchbzS3IJKhczcgvyiEoXEoqLESq6Cosy8Eo00DTBPI9pQBwhjNTU10SWMdUx0TLFJWOoY65iDJCA2LVgAoQE)
### Previous [Python](https://www.python.org) NumPy, 33 bytes
```
lambda v:(v@v*v@v-2*v**3@v)**.5/4
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3FXMSc5NSEhXKrDTKHMq0gFjXSKtMS8vYoUxTS0vPVN8EqjAprSg_VyGvNLegUiEztyC_qEQhsagosZKroCgzr0QjTQPM04g21AHCWE1NTXQJYx0THVNsEpY6xjrmIAmITQsWQGgA)
### Previous [Python](https://www.python.org) NumPy, 36 bytes (@alephalpha)
```
lambda v:(v@v*v@v-2*v**2@v**2)**.5/4
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3VXISc5NSEhXKrDTKHMq0gFjXSKtMS8vIAURoamnpmeqbQNUmpRXl5yrkleYWVCpk5hbkF5UoJBYVJVZyFRRl5pVopGmAeRrRhjpAGKupqYkuYaxjomOKTcJSx1jHHCQBsWnBAggNAA)
### Previous [Python](https://www.python.org) NumPy, 37 bytes
```
lambda v:((v@v)**2-2*v**2@v**2)**.5/4
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3VXMSc5NSEhXKrDQ0yhzKNLW0jHSNtMqAlAOIAPL1TPVNoIqT0orycxXySnMLKhUycwvyi0oUEouKEiu5Cooy80o00jTAPI1oQx0gjNXU1ESXMNYx0THFJmGpY6xjDpKA2LRgAYQGAA)
Expects a numpy vector containing the three side lenghts.
[Answer]
# [R](https://www.r-project.org), ~~30~~ 28 bytes
```
\(x)prod(sum(x)/2-c(0,x))^.5
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhZ7YjQqNAuK8lM0iktzgUx9I91kDQOdCk3NOD1TiJKbXmkayRqGOgogpKmprKBrp2CgZ2JsbMAFkjDWUTDRUTCFSpjpGQABWMJSRwEoZw6VsNAztzA1g5i4YAGEBgA)
Inspired by [@Kevin Cruijssen's 05AB1E answer](https://codegolf.stackexchange.com/a/250460/55372).
---
### [R](https://www.r-project.org), ~~32~~ 30 bytes
*Edit: -2 bytes by looking at [@loopywalt's answer](https://codegolf.stackexchange.com/a/250455/55372).*
```
\(x)((x%*%x)^2-2*x^3%*%x)^.5/4
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhb7YjQqNDU0KlS1VCs044x0jbQq4owhHD1TfROIopteaRrJGoY6CiCkqamsoGunYKBnYmxswAWSMNZRMNFRMIVKmOkZAAFYwlJHAShnDpWw0DO3MDWDmLhgAYQGAA)
Takes input as a vector of sides.
Uses the formula
$$ A= \frac{1}{4}\sqrt{(a^2+b^2+c^2)^2-2(a^4+b^4+c^4)}$$
with observation that sum of squares of elements from `x` is a dot product of `x` with itself. So with \$x=[a,b,c]\$ and \$y=[a^3,b^3,c^3]\$:
$$ A= \frac{1}{4}\sqrt{(x \cdot x)^2-2(y\cdot x)}$$
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~59~~ 51 bytes
```
#define f(a,b,c)sqrt(4*a*a*b*b-(c=a*a+b*b-c*c)*c)/4
```
[Try it online!](https://tio.run/##bZFtT4MwEMff71NcMEsKKxsT9hScb4yfwi2mLWUSWUFKInHZVxePUVDmCiXH/f53vbsKV6RMHer6LpJxoiTEhFFOha0/ipIEDsOHO9wlYovmpDGFI2x8Z0GdqBKOLFHEhtMIcDWOUurylb3sYQunOQWfwuYcDinvaYCCayp6uqCwMjROM1aCrHIpShm1Cm8a@L5HYTn1cFFYT1frxdIEiEzpEsQbKxz8SvEuizbK2lXP97tq84R7YVH4@@9bw@NynaSZwqi5dANDsgJIU2uiIlkh8kJjPoBOvmQWk65Ke2YcTu8JYTK5qO1LsnZqXfcMs5npXTT7cIB5h/lNLDos/uG2G42C5naBUxD2NZVI@/Heyp8zfcnAuCYSXNA2dmwm9KvMC9TGxBpHFNoN7iOMYxjrncJpD/qjw37osH4KmvZX15y@N0WfR@f6W8QpO@ja/azd9PgD "C (clang) – Try It Online")
*Saved 8 bytes thanks to [jdt](https://codegolf.stackexchange.com/users/41374/jdt)!!!*
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$9\log\_{256}(96)\approx\$ 7.408 bytes
```
mqr-J0xHS
```
[Try it online!](https://fig.fly.dev/#WyJtcXItSjB4SFMiLCJbMyw0LDVdIl0=)
Jelly beats me... again. Takes input as a list of the side lengths.
```
mqr-J0xHS
S # Sum the lengths
H # Halve it
- # That ^ minus...
x # The input
J0 # With a 0 prepended
r # Product
mq # Square root
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~9~~ 8 bytes
```
∑½₌N-Π*√
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiJHCveKCjE4tzqAq4oiaIiwiIiwiOSwzLDciXQ==)
*[A 7 byter with `-r`](https://vyxal.pythonanywhere.com/#WyLhuItyIiwiIiwi4oiRwr1+Lc6gKuKImiIsIiIsIjksMyw3Il0=)*
Outputs as a fraction representation. [Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCLiiJHCvSR+Lc6g4oCeKuKImiIsIiIsIjksMyw3Il0=) if you want decimals as output.
Takes the 3 side lengths as a list of numbers.
Quite literal implementation of Heron's formula, with some extra insight from Bubbler's answer.
## Explained
```
∑½₌N-Π*√
∑½ # Half sum of the side lengths
₌N- # Push the half sum negated, as well as each side length minus the half sum
Π* # Take the product of the subtracted side lengths and multiply it by the negated half sum
√ # Take the square root of that
```
[Answer]
# [Haskell](https://www.haskell.org), 38 bytes
```
sqrt.product.(map=<<(-).(/2).sum).(0:)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ2W0km6Ec0CAUuzSNAVbhZilpSVpuhY31YoLi0r0CoryU0qTS_Q0chMLbG1sNHQ19TT0jTT1iktzgSwDK02oaqvcxMw8oG6gMt94BY2Cosy8EgU9hTRNhehoQx0FEIrVUYg21lEw0VEwBTEtdRSAPPPYWIgJCxZAaAA)
---
# [Haskell](https://www.haskell.org), 38 bytes
```
sqrt.product.(map.(-).(/2).sum<*>(0:))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ2W0km6Ec0CAUuzSNAVbhZilpSVpuhY31YoLi0r0CoryU0qTS_Q0chML9DR0NfU09I009YpLc2207DQMrDQ1oaqtchMz84C6gcp84xU0Cooy80oU9BTSNBWiow11FEAoVkch2lhHwURHwRTEtNRRAPLMY2MhJixYAKEB)
With the help of [pointfree.io](http://pointfree.io/).
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 9 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
0Γ_Σ½-ε*√
```
I/O as decimals.
[Try it online.](https://tio.run/##y00syUjPz0n7/9/g3OT4c4sP7dU9t1XrUces//8N9QwUoJjLGEibALEpkG0JpEF8cz0DAA)
**Explanation:**
Similar approach as [my 05AB1E answer](https://codegolf.stackexchange.com/a/250460/52210), except with subtract instead of absolute difference, since with four values the negatives balance themselves out anyway.
```
0 # Push a 0
Γ # Wrap the top four items into a list (using the three implicit inputs)
_ # Duplicate this list
Σ # Sum
½ # Halve
- # Subtract it from each value in the list
ε* # Product: reduce by multiplication
√ # Square root
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, ~~36~~ 35 bytes
```
[ dup Σ 2 / dup rot n-v Π * √ ]
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjkJtYkqFXmpeZnJ@SCuZARMpSQWqLIZy00rzkksz8vGKFgqLUkpLKgqLMvBIFay6uagVDMKwFsowVTBRMwSxLINscyPofrZBSWqBwbrGCkYI@mFmUX6KQp1umcG6BgpbCo45ZCrH/S4oyHRT0ihWSc1ITi/4DAA "Factor – Try It Online")
-1 byte because I remembered `√` is 1 byte shorter than `sqrt`.
```
! { 3 4 5 }
dup ! { 3 4 5 } { 3 4 5 }
Σ ! { 3 4 5 } 12
2 ! { 3 4 5 } 12 2
/ ! { 3 4 5 } 6
dup ! { 3 4 5 } 6 6
rot ! 6 6 { 3 4 5 }
n-v ! 6 { 3 2 1 }
Π ! 6 6
* ! 36
√ ! 6.0
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 15 bytes
```
0+]J++2./?-pdr@
```
[Try it online!](https://tio.run/##SyotykktLixN/V9dUPzfQDvWS1vbSE/fXrcgpcjhf214zn9DPQMFKOYyBtImQGwKZFsCaRDfXM8AAA "Burlesque – Try It Online")
A port of [Kevin Cruijssen's 05AB1E answer](https://codegolf.stackexchange.com/a/250460/91386)
```
0+] # Prepend 0
J # Duplicate
++ # Sum
2./ # Halve
?- # Difference with original
pd # Product
r@ # Square root
```
[Answer]
# [Desmos](https://desmos.com/calculator), 36 bytes
```
f(l)=(total(ll)^2-2l^4.total)^{.5}/4
```
Input is a list of the three side lengths.
[Try It On Desmos!](https://www.desmos.com/calculator/ttfj5rs9mm)
Port of [Steffan's Python answer](https://codegolf.stackexchange.com/a/250449/96039) also gives 36 bytes:
```
f(a,b,c)=(4aabb-(aa+bb-cc)^2)^{.5}/4
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 14 bytes
```
√·×´+´∘÷⟜2-0⊸∾
```
[Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=QXJlYSDihpAg4oiawrfDl8K0K8K04oiYw7fin5wyLTDiirjiiL4KQXJlYcKoIOKfqDHigL8x4oC/MSwz4oC/NOKAvzUsOeKAvzPigL834p+p)
```
0⊸∾ # each element of the argument, prepended by a zero
- # subtracted from
+´∘ # the sum of
÷⟜2 # each element of the argument divided by 2
×´ # get the product (fold-multiply),
√· # and take the square root
```
[Answer]
## JavaScript, 43 bytes (@Steffan)
Ported from [Steffan's Python answer](https://codegolf.stackexchange.com/a/250449) by him:
```
f=
(a,b,c)=>(4*a*a*b*b-(a*a+b*b-c*c)**2)**.5/4
console.log(f(1, 1, 1), 0.4330)
console.log(f(3, 4, 5), 6.0000)
console.log(f(9, 3, 7), 8.7856)
```
## JavaScript, 46 bytes (me)
Boring answer :/ but couldn't think of anything better.
\$A=\sqrt{s(s-a)(s-b)(s-c)}\textrm{, where } s=\frac{a+b+c}{2}\$.
```
f=
(a,b,c,s=(a+b+c)/2)=>(s*(s-a)*(s-b)*(s-c))**.5
console.log(f(1, 1, 1), 0.4330)
console.log(f(3, 4, 5), 6.0000)
console.log(f(9, 3, 7), 8.7856)
```
[Answer]
# x86 32-bit machine code, 33 bytes
```
6A 03 59 D9 E8 D9 EE DC E1 DA 04 8C E2 FB D9 FD 6A 03 59 D9 C0 DA 2C 8C DE CA E2 F7 DE C9 D9 FA C3
```
[Try it online!](https://tio.run/##dVJNj9MwED1nfsVQVMluXUjaRYiGctorAlVIIHV7SB27jeQ6wXaWsFX/OmWcbQvLClmayXy992YUOdlKeTq9rKw0banwvQ9lVb/afYCnKRtiDrSpi4CaUYyFwOg2j07yHO/rqkRlS8ZzKPwe2XLAQM@TpvU7nOXY1A0q2UGiTZn19oGsbzcOfWAZF9GlHEw6T3RVlCXefv20vMXPX5a4Ur4Z34xofA2JqQnJpHFYFkbBMwaTzSP8GY/AepL/oOl9a5rYOr0qODNkfxX/yCPW7y5A4lQA2nYOfEALy9r60J8iyNUaF3iATMQHM3Ej3gh4J2birYBUTOnBMQeIzfuiso/ndFspUO4Kh6MRBfccDpDESpdja321tao8111OImqHrCOeNMcOXyzQVw@q1ixIjq8vAY3zWB4vcEbCk8ZRRrPBUN/ZgcDYverWIkruxtnlY7rmtFAC1/Y7@7GQu8oqlHWp5nHdxBE1e6JrxDXlyxoPlzkcptNvxDNy4zHPj/hjVxmFzEW57J@dOJ0y4l5n2bDCzc@gPO@1Opw8n9G9EhVaZ@kOcITT6ZfUptj602Q/m5Kh/3BBgMr8Bg "C (gcc) – Try It Online")
Uses the `cdecl` calling convention, taking three 32-bit integers on the stack and returning a value on the FPU register stack.
In assembly:
```
f: push 3; pop ecx # Set ECX to 3.
fld1 # Push 1 onto the FPU register stack.
fldz # Push 0 onto the FPU register stack.
fsubr st(1), st(0) # Change the 1 to 0-1=-1.
l0: fiadd DWORD PTR [esp+4*ecx] # Add an argument to the top value.
loop l0 # Loop 3 times, making the top value a+b+c.
fscale # Multiply the top value by 2^(value below)=2^-1=1/2.
push 3; pop ecx # Set ECX to 3 again.
l1: fld st(0) # Duplicate the top value, which is s.
fisubr DWORD PTR [esp+4*ecx]# Change the top value to a-s or b-s or c-s.
fmulp st(2), st(0) # Multiply the third-from-top value
# (which was -1) by that and pop it.
loop l1 # Loop 3 times.
# The FPU register stack is now -(a-s)(b-s)(c-s), s.
fmulp st(1), st(0) # Multiply those values and pop, leaving the product.
fsqrt # Take the square root.
ret # Return.
```
---
I had another version using SIMD instructions to do multiple calculations at once, but it was longer, at 48 bytes:
```
5A 6A 00 89 E1 F8 C5 F8 5B 01 0F 59 C0 C5 FB 7C C8 C5 F3 7C C9 F3 0F 11 09 D9 01 F5 72 EC D8 C0 D9 C1 DE CA DE E9 D9 FA 58 6A 04 DA 31 58 FF E2
```
```
f: pop edx
push 0
mov ecx, esp
clc
vcvtdq2ps xmm0, [ecx]
r: mulps xmm0, xmm0
vhaddps xmm1, xmm0, xmm0
vhaddps xmm1, xmm1, xmm1
movss [ecx], xmm1
fld DWORD PTR [ecx]
cmc
jc r
fadd st(0), st(0)
fld st(1)
fmulp st(2), st(0)
fsubp
fsqrt
pop eax
push 4
fidiv DWORD PTR [ecx]
pop eax
jmp edx
```
[Answer]
# Knight, 50 bytes
```
;=x=s-**4=a^P2=b^P2^+a-b^P2 2;W>x=x/+x/s x 2xO/x 4
```
[Try it online!](https://tio.run/##rVlbU9tKEn62f8XgFLZGloMsnK1TNjJFciBFLYEcSDYP4AQhy1i1suyVZC5L2L@e7e65aGSb7Gb38CBpZvr6TU93jwk7t2H441WchslyHO3lxTiev54O6@ZMEt9UpsLicRGtEGVxeluZKuKZoBlHkziNWJKwZJ7e0qOuZz@dfv7AuuXw4tM588rh3w7OWa8cHp2@Y7@Vw/PPrFsSH51cGLSnn08M0s@nHw4u/mrlnFn4aLJ/dd9wvXpwAWrFYjgNMmbzksGkAlu1iOGQ9cq108MvuJjCInn0neH33t4KDaohGnQTaJKEI2GF5u3Z2QkR4WOfnOyjb4Yh5@8FAfAbtt4FyTLi/DId8Xqd/IBduRz5543DsyPrx8B/8POObff84OtHz7@Bx9d20ME38wZfhg/@w077YSdnD8x7ONt5YL0fHBgbAyHLBmFRMGM@Sh3U66B6EWR5ZHH2VK/FacHiQb0Gs2SGw@zJMg1hhphDGBezhZMv0ktv5D@5jvsMMmoxiCN6eLs4sbOD4uMFu5/GRZQvgjCq1@A7iSyYB3ZLmOGwxlVxlV5NrjL29Hw5snj/VYOTKbV4wixtrc9ar1qcCRFqdgtmr1KYbrfFDNhZi5I8MieehTnhNAr/zibzjKXL2U2U5dIeZsX5OL6NCyUVtKM7XUd7JN4267qszWxpebvNWYe13BaoQEtjzrKoWGYpU4Ej2Ch2Bqs23AVZHNwkkbICjEjm91FmhaBPGcK@f2fKuJBGIQHxrcUlPPEG12O/68Ae@Xp6xTo8ijJkgSQdLxcWbimTmHYYjNYNFokhF9KEGVetVmlToyU2DZjBA20UAyGQSOAbLFsEecGKaQTCgqwAYrkBtkIUNzTk6Iky1jhfLxoLzy6nja6VYJD5GLpFPE/BbIxYdwSmhQqRfLlYIOBcRZWaMeE34w9gN8BGGSqUFynEMSQ1jFxpuUDlU0uffDFxhBOY4PqY2NBMFWSUE4WrFtqNpgZJMg@tnut0OTqI09oJcjBdJkmQPZqOlvtzbmzPx5a2jBRK/mW6wk0quqhCJoVNnh4cvn13/cfWye9nhsOm2Jt4o1xvXe5WRfD744sXJBZRRiKDdMz@sQzUEMXemSp211UIAN63NBbHG7Ag5l6VuUrzTKkyW6a4QwOZmO1inlsqV9IBgNAu4pDR6s1ycun1RtIOsdFNSg/agHwBx6qYWEAK/m8nybih8g4VJgeFrAqAQ6EFiJIn9Ffo9lh3t@onOo@xuM8aRbaMGhCDeh5DEuYnAWQQXGhgZDVKENBP9F3WJoLj29v5PIGVmyoCL/pauvUzh@xf98g082bNzARtTP9UGyFoi3mSWKapDnMdqBD/g8npmslYhT8cfDx1sBaLQIPh8WXXdV0IJ3AFhmqUx/@MvhUMXwMjRg1vEQEYOfjw6Lnrd1VJxwyHVR1f9PTEaxcIjo5PDm02geQ4qOnQlvowDYfBwkmilDoAAyvVOgnM4Ny9BMYqI9YmLG1YcKyYegmoxXuExQCKSoyLOm@Es8XKDhBI8ahMIQhTPEI1@X1chFPLBmTWOi3AiMm/EOtU66DVZ6hFEPgIKPZqkIV5k5yS4mW3WAlZPqAqXFJQS1pkWLqoK70c8acyzKCBotwuFJ@D4qrsDDKexZvuwwT/SsqPQAlSBUa3UZFAQ2k1aS@buENYIsdxygfxxLJoP7EhCKcZ2uJAnHIuttl3BxtthRenNkDoOxT6ROeI2UACMlD2Ikgyd5ZWvi39EfR65V25gpwmxJrmGmgwGiD@/MV8EaWWodhpZA1qFcAqfyYqJcSj77m932heNheW6EgmYPoYnYIWDkLWwf4OyKF3oBHqANUqvCyYZG2fWiE8sUDJJdwgh3QR1CjB9pln9iwljKUnf4An0QO0cXja1/zcquw63Ru2MJOtEZ6shQdoSaq4GOS/t/qyT9wQyDrzyQrUOKW22MIaxFURGg57vGws19KhYr2g5tDazpGxehjWmQFOaH1MvZBJeaMkVQtYXqIglWJfKmGyZpk7IHOLROGsRAEPhrj4IGhiPyvQsWaTLludDpKORJt7Re12TZm1/drOwR4LRpypo5YZ5i@LXO2@jgnR6wmD2togypOQLzElY2gZ2yO66Vp1t8XNFamh72cqljyx59j/0mEQG0BUOI2n3FdeenxzqIZBoV6y6@y2S5i4@kZZHLpRh96FzBHSr85adBrRjq161V7BZJe7swGF1fK8AQd7DQexr5tQmG1wzSYa3xRCDFCDLMqQfusKLnlINOh0SJ4Eikrm6kYLRIvK6d/5KTA7m4HZ/inT9mamr4RmxSFxdaA5z/RyIGEXqPus09UoEy1A34Vz1unCGeuaxN4vUu9BeqzQ@j6Skt6@mnEV5AS0N3Ql1h6ndsX2Cf/66oGgRXIF7giUYLHEwDdeGaZRFrVyls6hh46TIk7ZffAIuLHxHO6kRXQbZcCzmKdRWsQB3iLgJM/ZfcSmwV0EhFIQkhdsFqRLCJ/H1ziL3t0g4gAFIZEvkwJ/NCDlOuEpko5Jo1SuQGbyaZIV8SjvZUr3ZUM02V6FyqX7eZBgbXwEr9NxEo3ZdWn2tZbyhF@iMTOUlM4MUVino8acyGuS1DZMf9Z5cI@CdaXwYdKr5EW/mhX3mXn498xjgKx9@ZtckwmCfVZpFGnSYUY2RBmu4FQl1xN1AGm3fKg2Rhc0hEOJoTUfz/tsFs3CBYZZyobX@/@vK8M/wZWhcmVrgy@@9EW6sv8y@kLrBpNxeZ9VCDxN4akCurXJznKg3VOZxxSgzWuW6Q992VQb9k1OmUo0//f/hl/mIEOM5h@0@iZ1pc1dpfXLrFtd/uWLjOpty5sM0tUqtxmdCokGJY78CreRJpEDKdptzSZM/gLuiV@9zEaz4h0zexfJdlzt2pHU4N/3@rsGLO/FlcE3Oqy2WYDW70ipvHg4@izsVhraCwH0itDBasnzNpW8Xa77AE9z92jyPzREaBi@cStC3fzrdsjsjTzwELW2u9gkUYMg4l8s0oso2vIkgPZxNAkgSYJnqsOMU1iMx/QjUhAWUKZa22ELe06c4eyFWywK0zUQukH5Q8IsiFNsVlmQ3YYOCbVt@L7j@HMV3S/xXzyWS9ZUr3HPP97U39T/8m8)
This is the elusive "triple Heron" answer:
* Because of the limitations of Knight, this only works for Heronian triangles (triangles with integer sides and area)
* It uses Heron's formula for the area of the triangle
* Because Knight doesn't have square root, I implemented it using Heron's method.
~~(It doesn't work in the TIO because it hasn't implemented the no-op.)~~ It turns out I just misread the spec.
Here's the expanded code:
```
;=a^P2
;=b^P2
;=c^P2
;=s (-(*(*4a) b)(^(+a(-b c)) 2))
;=x s
;WHILE >x (=x(/+x(/s x) 2))
x
OUTPUT /x 4
```
[Answer]
# [Raku](https://raku.org/), 27 bytes
```
{sqrt [*] @_.sum/2 X-0,|@_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/uriwqEQhWitWwSFer7g0V99IIULXQKfGIb72f3FipYKSSryCrZ1CdZqCSnytkkJafpGCjaECENrpKNgYK5gomIIYlgrGCuZ2/wE "Perl 6 – Try It Online")
`@_` is the array of arguments to the function: *a*, *b*, and *c*. `@_.sum / 2` is half the sum of the arguments, what the problem statement calls *s*. `X-` subtracts the numbers `0` and `|@_`, the flattened arguments, from that number, producing the numbers *s*, *s - a*, *s - b*, and *s - c*. Then `[*]` multiplies them together and `sqrt` takes the square root.
[Answer]
# TI-Basic, 14 bytes
```
√(sum(Ans)/2prod(sum(Ans)/2-Ans
```
or
```
.25√(sum(Ans)prod(sum(Ans)-2Ans
```
Takes input in `Ans` as a list.
[Answer]
# JavaScript, 43 bytes
Tried to beat `43` bytes but got a different form :)
$$
\sqrt{s(s-a)(s-b)(s-c)}
$$
where \$s=\frac{a + b + c}{2}\$ is equal to:
$$
\frac{1}{4}\sqrt{4abd - d^2}
$$
where \$d=(a + b)^2 - c^2\$
```
(a,b,c)=>(4*a*b*(d=(a+b)**2-c*c)-d*d)**.5/4
```
Try it:
```
f=(a,b,c)=>(4*a*b*(d=(a+b)**2-c*c)-d*d)**.5/4
;[
[1, 1, 1], // 0.4330
[3, 4, 5], // 6.0000
[9, 3, 7], // 8.7856
].forEach(([a,b,c])=>console.log(f(a,b,c)))
```
[Answer]
# [lin](https://github.com/molarmanful/lin), 25 bytes
```
.+ \+ `/2/.~0' - \* `/.5^
```
[Try it here!](https://replit.com/@molarmanful/try-lin)
For testing purposes (use `-i` flag if running locally):
```
[1 1 1] ;
.+ \+ `/2/.~0' - \* `/.5^
```
## Explanation
Prettified code:
```
.+ \+ `/ 2/.~ 0' - \* `/ .5^
```
* `.+ \+ `/ 2/` duplicate, half-sum of input
* `.~ 0'` swap, append 0
* `- \* `/ .5^` vector subtract, product, square root
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
I₂Π⁻⊘Σθ⊞Oθ⁰
```
[Try it online!](https://tio.run/##HcHBCsIwDADQX@kxhQqCBxGPXrwMy3ocO4SusEG32DTZ70fwvbwiZ8JqFnk7BF7YBVJT5DISCUSmRbPAsB3a4Y31LAsk3aF5H1zUvn6@hVGIoQV39X9Ps2l6BHcL7j7PdjnrDw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array. Explanation:
```
θ Input array
Σ Summed
⊘ Halved
⁻ Vectorised subtract
⁰ Literal integer `0`
⊞O Appended to
θ Input array
Π Take the product
₂ Take the square root
I Cast to string
Implicitly print
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 44 bytes
```
->a,b,c{(4*a*a*b*b-(a*a+b*b-c*c)**2)**0.5/4}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ0knuVrDRCsRCJO0knQ1gAxtECNZK1lTS8sIiA30TPVNav8XKKRFG@oAYSwXiGmsY6JjCmFa6hjrmMf@BwA "Ruby – Try It Online")
# [Ruby](https://www.ruby-lang.org/), 45 bytes
```
->a{a.inject(s=a.sum/2.0){|p,i|p*(s-i)}**0.5}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6xOlEvMy8rNblEo9g2Ua@4NFffSM9As7qmQCezpkBLo1g3U7NWS8tAz7T2f4FCWnS0oQ4QxsZygTnGOiY6pjCOpY6xjnls7H8A "Ruby – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=product,sum -pal`, 37 bytes
```
$_=sqrt product map{sum(@F)/2-$_}0,@F
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3ra4sKhEoaAoP6U0uUQhN7Ggurg0V8PBTVPfSFclvtZAx8Ht/39DBSDkMlYwUTDlslQwVjD/l19QkpmfV/xf19dUz8DQAEj7ZBaXWFmFlmTm2EJN0wGa9F@3IDEHAA "Perl 5 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~14~~ 13 bytes
```
@*F-LcsQ2+QZ2
```
[Try it online!](https://tio.run/##K6gsyfj/30HLTdcnuTjQSDswyuj//2hDHQUQigUA "Pyth – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 52 bytes
```
(a,b,c)=>Math.Sqrt((a-(a=(a+b+c)/2))*(b-a)*(c-a)*-a)
```
[Try it online!](https://tio.run/##bYyxCsJAEERr8xVb7pqNolFEYlLaCYKlWOytCQnIBS8XLcRvPxNIKcO8mWZGu0S7Jhx7q4d725tHyfA/C6ggDyhsWCkvTuLrxeXpPKIkKDlKbGKl5ZpojiaRgTpycMiiqnWlaI0vcTBdQGPBlu/r7YMrHkQMmPKGt2PZc8o7@lI0O7vGeqymEWXhBw "C# (Visual C# Interactive Compiler) – Try It Online")
] |
[Question]
[
## Challenge
Given a positive integer \$n\$, count the number of \$n\times n\$ binary matrices (i.e. whose entries are \$0\$ or \$1\$) with exactly two \$1\$'s in each rows and two \$1\$'s in each column.
Here are a few examples of valid matrices for \$n=4\$:
```
1100 1100 1100
1100 0011 0110
0011 1100 0011
0011 0011 1001
```
And here are a few invalid matrices:
```
1100
0011
0111 <-- three 1's in this row
1100
^
`--- three 1's in this column
```
```
1111 <-- four 1's in this row
0011
1100
0000 <-- zero 1's in this row
```
This sequence is catalogued on OEIS as [A001499](https://oeis.org/A001499). Here are a few non-bruteforce ways to compute it (\$a\_n\$ denotes the number of valid \$n\times n\$ binary matrices).
* The recursive formula
$$
2a\_n-2n(n-1)a\_{n-1}-n(n-1)^2a\_{n-2}=0
$$
with base cases \$a\_1=0\$, \$a\_2=1\$.
* The explicit formula
$$
a\_n=\frac{(n!)^2}{4^n}\sum\_{i=0}^n\frac{(-2)^i(2n-2i)!}{i!((n-i)!)^2}.
$$
You may find other ways to compute this sequence on the OEIS page linked above. To be clear, bruteforcing is a perfectly valid way of solving this challenge.
## Rules
As usual in [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenges, your task is to write a program/function which does one of the following (consistently across different inputs).
* Take a positive integer \$n\$ as input and return \$a\_n\$ as output. Because of the combinatorial interpretation of this sequence, it has to be \$1\$-indexed (i.e. you are not allowed to take \$n\$ and return \$a\_{n+1}\$). If you choose this option, you are not required to handle the input \$n=0\$.
* Take a positive integer \$n\$ as input and return the list \$[a\_1,a\_2,\ldots,a\_n]\$ as output. Optionally, you may instead choose to return \$[a\_0,a\_1,\ldots,a\_{n-1}]\$ or \$[a\_0,a\_1,\ldots,a\_n]\$, where \$a\_0=1\$ (consistent with the combinatorial interpretation). The choice has to be consistent across different inputs.
* Take no input and return the infinite list/generator \$[a\_1,a\_2,a\_3,\ldots]\$. Optionally, you may instead choose to return \$[a\_0,a\_1,a\_2,\ldots]\$, where \$a\_0=1\$.
Your program/function must theoretically work for arbitrarily large inputs, assuming infinite time, memory and integer/floating point precision. In practice, it's ok if if fails because of integer overflow and/or floating point errors.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Testcases
```
Input Output
1 0
2 1
3 6
4 90
5 2040
6 67950
7 3110940
8 187530840
9 14398171200
10 1371785398200
11 158815387962000
12 21959547410077200
13 3574340599104475200
14 676508133623135814000
15 147320988741542099484000
```
[Answer]
# [J](http://jsoftware.com/), 41 bytes
```
1#.*:=1#.2>[:>@~.@,[:+&,&.>/~i.@!<@A.=@i.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1tKxsgaSRXbSVnUOdnoNOtJW2mo6anp1@Xaaeg6KNg6OerUOm3n9NrtTkjHygVluFNAVDCMcQzDGCcMzAHGMIxxKizgTCMzIwgfBNoUrNLU0hAmb/AQ "J – Try It Online")
A different take on brute force, which handles up to n=6 on TIO.
Since the idea is more interesting than the J mechanics here, I'll explain that.
I could likely save bytes by translating one of the formulas into J, but that seemed less fun.
## the idea
* Generate all `n!` permutations of the identity matrix. Eg, for n=3:
```
┌─────┬─────┬─────┬─────┬─────┬─────┐
│1 0 0│1 0 0│0 1 0│0 1 0│0 0 1│0 0 1│
│0 1 0│0 0 1│1 0 0│0 0 1│1 0 0│0 1 0│
│0 0 1│0 1 0│0 0 1│1 0 0│0 1 0│1 0 0│
└─────┴─────┴─────┴─────┴─────┴─────┘
```
* Create an "addition table" of this list with itself, using matrix addition:
```
┌─────┬─────┬─────┬─────┬─────┬─────┐
│2 0 0│2 0 0│1 1 0│1 1 0│1 0 1│1 0 1│
│0 2 0│0 1 1│1 1 0│0 1 1│1 1 0│0 2 0│
│0 0 2│0 1 1│0 0 2│1 0 1│0 1 1│1 0 1│
├─────┼─────┼─────┼─────┼─────┼─────┤
│2 0 0│2 0 0│1 1 0│1 1 0│1 0 1│1 0 1│
│0 1 1│0 0 2│1 0 1│0 0 2│1 0 1│0 1 1│
│0 1 1│0 2 0│0 1 1│1 1 0│0 2 0│1 1 0│
├─────┼─────┼─────┼─────┼─────┼─────┤
│1 1 0│1 1 0│0 2 0│0 2 0│0 1 1│0 1 1│
│1 1 0│1 0 1│2 0 0│1 0 1│2 0 0│1 1 0│
│0 0 2│0 1 1│0 0 2│1 0 1│0 1 1│1 0 1│
├─────┼─────┼─────┼─────┼─────┼─────┤
│1 1 0│1 1 0│0 2 0│0 2 0│0 1 1│0 1 1│
│0 1 1│0 0 2│1 0 1│0 0 2│1 0 1│0 1 1│
│1 0 1│1 1 0│1 0 1│2 0 0│1 1 0│2 0 0│
├─────┼─────┼─────┼─────┼─────┼─────┤
│1 0 1│1 0 1│0 1 1│0 1 1│0 0 2│0 0 2│
│1 1 0│1 0 1│2 0 0│1 0 1│2 0 0│1 1 0│
│0 1 1│0 2 0│0 1 1│1 1 0│0 2 0│1 1 0│
├─────┼─────┼─────┼─────┼─────┼─────┤
│1 0 1│1 0 1│0 1 1│0 1 1│0 0 2│0 0 2│
│0 2 0│0 1 1│1 1 0│0 1 1│1 1 0│0 2 0│
│1 0 1│1 1 0│1 0 1│2 0 0│1 1 0│2 0 0│
└─────┴─────┴─────┴─────┴─────┴─────┘
```
* Now we note that the valid items are simply those without a 2 anywhere:
```
┌─────┬─────┬─────┬─────┬─────┬─────┐
│ │ │ │1 1 0│1 0 1│ │
│ │ │ │0 1 1│1 1 0│ │
│ │ │ │1 0 1│0 1 1│ │
├─────┼─────┼─────┼─────┼─────┼─────┤
│ │ │1 1 0│ │ │1 0 1│
│ │ │1 0 1│ │ │0 1 1│
│ │ │0 1 1│ │ │1 1 0│
├─────┼─────┼─────┼─────┼─────┼─────┤
│ │1 1 0│ │ │ │0 1 1│
│ │1 0 1│ │ │ │1 1 0│
│ │0 1 1│ │ │ │1 0 1│
├─────┼─────┼─────┼─────┼─────┼─────┤
│1 1 0│ │ │ │0 1 1│ │
│0 1 1│ │ │ │1 0 1│ │
│1 0 1│ │ │ │1 1 0│ │
├─────┼─────┼─────┼─────┼─────┼─────┤
│1 0 1│ │ │0 1 1│ │ │
│1 1 0│ │ │1 0 1│ │ │
│0 1 1│ │ │1 1 0│ │ │
├─────┼─────┼─────┼─────┼─────┼─────┤
│ │1 0 1│0 1 1│ │ │ │
│ │0 1 1│1 1 0│ │ │ │
│ │1 1 0│1 0 1│ │ │ │
└─────┴─────┴─────┴─────┴─────┴─────┘
```
* But these are not necessarily unique. However, after removing dups, we
have our answer, which is 6:
```
┌─────┬─────┬─────┬─────┬─────┬─────┐
│ │ │ │1 1 0│1 0 1│ │
│ │ │ │0 1 1│1 1 0│ │
│ │ │ │1 0 1│0 1 1│ │
├─────┼─────┼─────┼─────┼─────┼─────┤
│ │ │1 1 0│ │ │1 0 1│
│ │ │1 0 1│ │ │0 1 1│
│ │ │0 1 1│ │ │1 1 0│
├─────┼─────┼─────┼─────┼─────┼─────┤
│ │ │ │ │ │0 1 1│
│ │ │ │ │ │1 1 0│
│ │ │ │ │ │1 0 1│
├─────┼─────┼─────┼─────┼─────┼─────┤
│ │ │ │ │0 1 1│ │
│ │ │ │ │1 0 1│ │
│ │ │ │ │1 1 0│ │
├─────┼─────┼─────┼─────┼─────┼─────┤
│ │ │ │ │ │ │
│ │ │ │ │ │ │
│ │ │ │ │ │ │
├─────┼─────┼─────┼─────┼─────┼─────┤
│ │ │ │ │ │ │
│ │ │ │ │ │ │
│ │ │ │ │ │ │
└─────┴─────┴─────┴─────┴─────┴─────┘
```
[Answer]
# JavaScript (ES6), 36 bytes
Returns the \$n\$th term of the sequence.
```
f=n=>--n<2?n:-~n*n*(f(n)+n*f(n-1)/2)
```
[Try it online!](https://tio.run/##FctBDoIwEAXQPaf4y07rqGUpVM9CkBoN@WOAuDF49YKrt3qv7tPN/fR8L0q7D6XkxHRVZVvfeNEfPb3LjhLodzTKqZaSbXJEQmxAtIjn3RAE3wrojbONw3G0h@MB/ytNtZYN "JavaScript (Node.js) – Try It Online")
### How?
We decrement \$n\$ right away in order to use the following 0-indexed form of the recursive formula:
* \$a\_n=n\$ for \$0\le n< 2\$
* \$a\_n=(n+1)\times n\times \left(a\_{n-1}+\dfrac{n\times a\_{n-2}}{2}\right)\$ for \$n\ge2\$
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ 12 bytes
```
1ÝλsN*;+NN>P
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f8PDcc7uL/bSstf387AL@/wcA "05AB1E – Try It Online")
-4 thanks to @ovs, which allowed for another -1
Uses the recursive formula.
```
1Ý 0-based range from 1, pushes [0,1]
λ recursive context
s swap the implicit a(n-1),a(n-2) to a(n-2),a(n-1)
N* n*a(n-2)
; /2
+ +a(n-1)
NN> n,(n+1)
P product of all elements in stack, (n*a(n-2)/2+a(n-1))*n*(n+1)
```
[Answer]
# [Oasis](https://github.com/Adriandmen/Oasis), ~~16 12 14 13~~ 11 bytes
```
àn*t+nn>**T
```
[Try it online!](https://tio.run/##y08sziz@///wgjytEu28PDstrZD////r@v83AgA "Oasis – Try It Online")
Uses the recursive formula, a port of the 05AB1E answer.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
²Ø.ṗs€µ;Z§=2Ạ)S
```
[Try it online!](https://tio.run/##ATgAx/9qZWxsef//wrLDmC7huZdz4oKswrU7WsKnPTLhuqApU/874oCcIC0@IOKAnTvDhwo0w4figqxZ/w "Jelly – Try It Online")
A monadic link taking an integer and returning an integer. Brute forces it.
## Explanation
```
² | Squared
Ø.ṗ | [0,1] Cartesian power of this
s€ | Split each of these into lists of the original argument in length
µ | Start a new monadic chain
) | For each of the possible matrices we’ve generated:
;Z | - Append its transpose
§ | - Sum each list
=2 | - Equal to 2 (vectorises)
Ạ | - All true
S | Finally, sum to find the number of matrices meeting the criteria
```
---
As an alternative, here’s an implementation of the recursive formula:
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
L,²H$בƲ×Fḣ2S;
Ç¡Ḋ
```
[Try it online!](https://tio.run/##ASgA1/9qZWxsef//TCzCskgkw5figJjGssOXRuG4ozJTOwrDh8Kh4biK//80 "Jelly – Try It Online")
A full program that takes n via STDIN and returns the first `n+1` terms in reverse order. I thought I should be able to shorten it by replacing `\nÇ` with `µ` but that’s not working.
---
Finally, a Jelly translation of @Jonah’s J answer:
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
=þ`Œ!+þ`ẎQ«Ƒ€1S
```
[Try it online!](https://tio.run/##y0rNyan8/9/28L6Eo5MUtYHUw119gYdWH5v4qGmNYfD///9NAQ "Jelly – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~45~~ 41 bytes
```
f(n){n=n--<3?n:-~n*n*(f(n)+n*f(n-1)/2.);}
```
[Try it online!](https://tio.run/##VVDbboMwDH3nKyykSgkkK5dexCjbw7SvGDygEDrUza1IpaEh9uljhlK6RortHJ/j5ETJvVJ9XzLkLSYo5S58xkf5gw46bEBddChJny@DBx53fYVn@MwrZNxqLaA1ALo5aXXWxVsGCbSeAF/ARkBEVeCtKG620ZpS6PtetPK6eFSq97x2KGp10DVJYRDbafMapE30QnttC/h/Du1JWR5rYMPFFRa6IZkXT@UOTPWtjyW7PokvJ8CZkRhcd2RzuFi42kCadBnjgh/ftQy1hu@4RzWhs/dRmd0Ip5ooJbMXBcgnoLgwKZIjFGDEbFsnicmmsZ3V9b@q/Mj3ppdffw "C (gcc) – Try It Online")
Inputs a positive integer \$n\$ and returns \$a\_n\$.
[Answer]
# [Factor](https://factorcode.org/), ~~83~~ 76 bytes
```
:: f ( n! -- m ) n 1 - n! n n 1 > [ n 1 + * n f n n 1 - f 2 / * + * ] when ;
```
[Try it online!](https://tio.run/##Lcu9DoIwFAXg3ac4bv4Vg4lLSVwNC4txIgy1uQViucVSY3z6WojTOffLuUbp4Hy838rqKmGdVnbCoEKHJ3kmi4leb2JNE0ZPIXxH33NYFplX3CYvVmUl0TpropQw2IDXEAIDtmDkEPPNS72gXnKPXUrzV5HaCcdkszf4dMQoYn5GnR8eTfoxyJKT0l38AQ "Factor – Try It Online")
*-7 thanks to @Delfad0r*
This is a translation of [@Arnauld's excellent answer](https://codegolf.stackexchange.com/a/225706/97916).
This is the first time I've submitted a Factor golf where it was shortest to make a named function. Recursion is so much shorter than other solutions that the mandatory function signature is worth it.
Here are some other solutions I tried first, which ended up being longer:
**Brute force, 94 bytes**
```
[ { 0 1 } swap '[ _ selections ] twice [ dup flip [ t [ sum 2 = and ] reduce ] both? ] count ]
```
**Explicit formula, 98 bytes**
```
[| n | n n! sq 4 n ^ / n [0,b] [| i | -2 i ^ 2 n * 2 i * - n! * i n! n i - n! sq * / ] map-sum * ]
```
[Answer]
# [APL(Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 32 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{+/∧/¨(2=+/,+⌿)¨⍵ ⍵∘⍴¨↓⍉⊤⍳2*×⍨⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31dP/UdsEAwA&c=q9bWf9SxXP/QCg0jW219He1HPfs1D6141LtVAYgfdcx41LsFyG2b/Ki381HXkke9m420Dk9/1AtSUQsA&f=AwA&i=Szu04lHvZhMA&r=tio&l=apl-dyalog-extended&m=dfn&n=f)
A dfn submission which takes a single input on the right.
Straight brute force which exceeds workspace size at n=5.
Uses `⎕IO←0` (0 indexing).
-4 bytes from ovs.
## Explanation
```
{+/∧/¨(2=+/,+⌿)¨⍵ ⍵∘⍴¨↓⍉2⊤¯1+⍳2*×⍨⍵}
2*×⍨⍵ 2^(n**2)
¯1+⍳ 0-range
2⊤ convert to base 2 matrix
⍉ transpose
↓ convert to nested list
⍵ ⍵∘⍴¨ reshape each vector to n x n matrix
(2=+/,+⌿)¨ 2= sums of rows and cols?
∧/¨ check if all elements of each satisfy that condition
+/ sum
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁼þⱮŒ!+þ`ẎḊỊÐṀQL
```
A monadic Link that accepts \$n\$ and yields \$a\_n\$.
**[Try it online!](https://tio.run/##ASoA1f9qZWxsef//4oG8w77isa7FkiErw75g4bqO4biK4buKw5DhuYBRTP///zQ "Jelly – Try It Online")**
### How?
Uses [Jonah's](https://codegolf.stackexchange.com/users/15469/jonah) idea from their [J answer](https://codegolf.stackexchange.com/a/225721/53748).
```
⁼þⱮŒ!+þ`ẎḊỊÐṀQL - Link: n
Œ! - all permutations (of implicit [1..n])
Ɱ - map with:
þ - (implicit [1..n]) outer product (permutation) using:
⁼ - equals?
` - use that as both arguments of:
þ - outer product using:
+ - addition
Ẏ - tighten (to a list of matrices)
Ḋ - dequeue (makes the following still work when n=1)
ÐṀ - keep those which are maximal under:
Ị - is insignificant (abs(x)<=1?)
Q - deduplicate
L - length
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~49~~ 36 bytes
```
⊞υ¹⊞υ⁰F⊖N⊞υ×÷×Lυ⊖Lυ²⁺⊗§υ±¹×⊖Lυ§υ±²Iυ
```
[Try it online!](https://tio.run/##bY7LCsIwEEX3fkWWU4ggxZ0rn1CwUvQLYjs0gXT6SFL9@5jU58JZhMmdy7m3lGIoW6G9z6hz9uSaKw7QJ6vZ2hhVExyUtkHJRQdFewtbylmfcJa3ldMtZGR3alQVguLsYzgLqhEW0ZkEbxqffe@ENvF6cQ2o6SBDTjEosrAVxsIRqbbyHfmkvTSZPGO/lFzcVRNIG2EQIjJW7Dmb/mubUYV3kJz9afjD1FOPjMoBGySLFcTK/6QwK@@Xfj7qBw "Charcoal – Try It Online") Link is to verbose version of code. Outputs the terms `a₀..aₙ`. Explanation:
```
⊞υ¹⊞υ⁰F⊖N⊞υ×÷×Lυ⊖Lυ²⁺⊗§υ±¹×⊖Lυ§υ±²Iυ
```
Start with `a₀` and `a₁`.
```
F⊖N
```
Input `n` and calculate `n-1` more terms...
```
⊞υ×÷×Lυ⊖Lυ²⁺⊗§υ±¹×⊖Lυ§υ±²
```
... apply the recurrence relation to calculate the next term.
```
Iυ
```
Output all the terms.
[Answer]
# MATLAB/Octave, 58 bytes
```
c=0
b=1
n=2;while k=n
n=n+1;
a=n*k*b+n*k*k*c/2
c=b;b=a;end
```
[Use Octave Online to test it yourself!](https://octave-online.net/) TIO seems to have problems with infinite nature of the script. It uses recursive formula and it's an infinite generator. The following results are printed to the console. It technically works forever but pretty fast falls into limits of floating precision and all new results are infinity. On MATLAB as I checked the results stay precise up to 13th element of the sequence. After that some floating precision errors appear and then they accumulate with each next element.
The scripts throws a warning due to `while k=n` but it continues to work. If needed to be avoided it can be replaced with `while 1` and `k=n` in next line.
For MATLAB it is also possible to reduce length to **57 bytes** with code like that:
```
c=0
b=1
for n=3:Inf
k=(n-1);a=n*k*b+n*k*k*c/2
c=b;b=a;end
```
But it doesn't work in Octave due to `3:Inf` range.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
’ÑH×+Ñ×ב
’¹ÇỊ?
```
[Try it online!](https://tio.run/##AS4A0f9qZWxsef//4oCZw5FIw5crw5HDl8OX4oCYCuKAmcK5w4fhu4o//zhSw4figqz/ "Jelly – Try It Online")
Uses the recursive formula.
## Explanation
```
’ÑH×+Ñ×ב Auxiliary monadic link, taking (n-1) as the argument
’ Decrement:
(n-2)
Ñ Apply next link:
a(n-2)
H Halve:
a(n-2) / 2
× Multiply by the argument:
(n-1) a(n-2) / 2
+ Add
Ñ the next link applied to the argument:
(n-1) a(n-2) / 2 + a(n-1)
× Multiply by the argument:
(n-1) ((n-1) a(n-2) / 2 + a(n-1))
× Multiply by
‘ the argument incremented:
n (n-1) ((n-1) a(n-2) / 2 + a(n-1))
’¹ÇỊ? Main monadic link, taking n as the argument
’ Decrement: (n-1)
? If
Ị insignificant: |n-1| ≤ 1
then
¹ identity: (n-1)
else
Ç apply previous link
```
[Answer]
# [R](https://www.r-project.org/), 52 bytes
```
f=function(n,k=n-1)"if"(n<3,k,n*k*(f(k)+f(n-2)*k/2))
```
[Try it online!](https://tio.run/##BcFBCoAgEAXQu7iaMSW0RRB5jS4gDsjAF8Q2XX56b5pJkRd19QFC0IKY2HVxhPsIGuDVk5DyJoSY2eueme1pdY3Zv0bClK6T7Qc "R – Try It Online")
Using formula from [OEIS page](https://oeis.org/A001499): `a(n) = n(n-1)/2 [ 2 a(n-1) + (n-1) a(n-2) ] (Bricard)`
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 20 bytes
```
~lṁ{{0|1}ᵐ²\,?+ᵐ=₂}ᶜ
```
Brute-force solution; times out on TIO with any input higher than 4. [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy7n4c7G6mqDGsPah1snHNoUo2OvDWTYPmpqqn24bc7//yb/IwA "Brachylog – Try It Online")
### Explanation
```
~l Generate a list whose length equals the input
ṁ That list is a square matrix
At this point, we have a matrix of indeterminate values
{ }ᶜ Count how many ways we can satisfy this predicate:
{ }ᵐ² For each value in the matrix:
0|1 It is either 0 or 1
\ Transpose the matrix
,? Append the non-transposed version
We now have a list of all rows and all columns of the matrix
+ᵐ Sum each row/column
=₂ All the results must equal 2
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 48 bytes
```
a(n)=if(n<2,n<1,(n^2-n)*(a(n-1)+(n-1)/2*a(n-2)))
```
[Try it online!](https://tio.run/##K0gsytRNL/j/P1EjT9M2M00jz8ZIJ8/GUEcjL85IN09TSwMooWuoqQ0m9Y20QFwjTU3N//8LijLzSoDSxpqaAA "Pari/GP – Try It Online")
Found it on the OEIS page, just golfed it a bit, uses Recursion
[Answer]
# [Python 3](https://docs.python.org/3/), 53 bytes
```
a=lambda n:n<1if n<2else~-n*n*(a(n-1)+(n-1)/2*a(n-2))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9E2JzE3KSVRIc8qz8YwM00hz8YoNac4tU43TytPSyNRI0/XUFMbTOobaYG4Rpqa/wuKMvNKgJLGQDYA "Python 3 – Try It Online")
-2 thanks to @Neil
Recursive formula, for input 1 it should output `False` instead of 0
[Answer]
# [Desmos](https://desmos.com/calculator), 51 bytes
```
a=n-i
f(n)=n!^2/4^n\sum_{i=0}^n(-2)^i(2a)!/(i!a!^2)
```
[Try It On Desmos!](https://www.desmos.com/calculator/rlkrjftol0)
[Try It On Desmos!(Prettified)](https://www.desmos.com/calculator/zl1o4zuikq)
Desmos doesn't support recursion and has limited ability for loops, so I had to use the explicit formula:
$$a\_n=\frac{(n!)^2}{4^n}\sum\_{i=0}^n\frac{(-2)^i(2n-2i)!}{i!((n-i)!)^2}$$
[Answer]
# [Ruby](https://www.ruby-lang.org/), 41 bytes
```
f=->n{(w=n*n-=1)<3?n:w*f[n]+w*n*f[n-1]/2}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y6vWqPcNk8rT9fWUNPG2D7PqlwrLTovVrtcKw/E0DWM1Teq/V@goGGop2dooKmXm1igoZam@R8A "Ruby – Try It Online")
Using the recursive formula
[Answer]
# [Python 3](https://docs.python.org/3/), 195 bytes
```
def f(n):
if n<2:
return 1
return n*f(n-1)
def o(n):
if n < 2:
return 0
p=0
r=(f(n)**2)/4
for i in range(n+1):
p+=(-2)**i*f(2*n-2*i)/(f(i)*(f(n-i)**2))
return int(p * r)
```
[Try it online!](https://tio.run/##XY7LCsJADEX3/YosJylD7agI0n6MYEezyQyhLvz6MVHwtQk3cM9J6n29Ftm2dl4y5CB47AA4g0zJE4Au600Fxu4dhawXR@wcKV8ITPALbWyps0@dg8uJEg4723NRYGABPcllCdKP@CJrP4eYrMh2JZHERIyDwYzkishPCX7eYVlDBQLF9mc97F1a1RvFBNge "Python 3 – Try It Online")
Pretty ungolfed, but hey, it's one of the first to use the standard formula, and it can handle up to 75.
] |
[Question]
[
Welcome to the grinder.
Your task is to make big rocks into small rocks by grinding them.
Take an input of a big rock of size `n > 3` and grind it.
Continue to grind the rocks by dumping them into the grinder until the size of all the rocks are `2`.
rocks are always grinded into equal even halves. If the result of a grinding is odd take result - 1.
Print the output of each grinding as you proceed.
### Examples
input: `5`
output: `22`
The result are two rocks of size 2
input: `50`
output:
```
2424 //two rocks of size 24
12121212 //four rocks of size 12
66666666 //8 rocks of size 6
2222222222222222
```
the result is 16 rocks of size 2
input: `30`
output:
```
1414
6666
22222222
```
the result is 8 rocks of size 2
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins! Have fun and good luck!
[Answer]
# TSQL, ~~61~~ 59 bytes
```
DECLARE @ int=50
,@x int=1WHILE @>2SELECT @=@/4*2,@x*=2PRINT replicate(@,@x)
```
**[Try it out](https://data.stackexchange.com/stackoverflow/query/589030/make-big-rocks-into-small-rocks)**
[Answer]
# COW, ~~297~~ 291 bytes
```
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOmoOMoOmoOmoOoommOoMoOMOOmoOMMMmoOMMMmoOOOOMoOmOoMOOMOomoOmoO
MOOMOomOoMOomoOmoomOoMMMOOOMoOmoOMMMmOomOomoomoOmoOMOOMOomOomOomOoMOomoOmoOmoOmoomOomOomOo
mOomOoMMMmoOMMMMOOMOomoOOOMmOomOoMoOmoOmoomOomOoMoomoOmoOmoOMOOMOoMOomoOMoOmOomoomoOMMMOOO
mOoMMMMMMmOoMMMMOomoo
```
[Try it online!](https://tio.run/nexus/perl#fVHbjoIwEH3nK1jTh5JaRJPNJiKrPzDpBxgelHVXE2pd3GuQb2enTIvwsqRpp2dmzplD202RzfhWQ741Kq8XzU0pdQMAPOFmjI5mb2nALlmSBtfPfaiNqZmWMmVlNk85K7ZSMp0f3ieYmaxZKcQSQYJAKQtJuZxH38dTeWBlQywKWS5SuptReBPC51QdxnEc0hWs4B7zzZpfqtP5IyyOFQHRklOQmeqFr56jyLUo3@IVwCp0iFfB0erTK39wTOhJiLsnIUYGhp6czaGn1DY3xIt/zylliVMCqDmrpk4pY9WaJ1NW9dNHPwvfC/V190soQfgAng6tW49NcPjald04QuTdBJzp1aaI0rZFn/8s7XdcSIyPYHHV4QD9jp8twywGylC9iy1ISBcDuGLq7QpsatyiR42qbx@ufoBeFE@XGreAufNQMdXTzKROgxEtDdYx22zwlLQSHuNkjud5EP4B "Perl – TIO Nexus")
The code prints each number on its own line, and separates iterations with an additional newline. It also prints the first iteration by itself, followed by a newline. So an input of 5 would give an output that looks like `5 2 2` except with newlines instead of spaces. Sample output for `50` is given below.
Explanation tree:
```
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOmoOMoOmoOmoOoom ;Store 10 in [0], 1 in [1], and integer input in [3]
mOoMoO ;Store 1 in [2]
MOO ;Loop while [2] is non-zero
moOMMMmoOMMMmoOOOOMoOmOo ; Copy [3] to [4], clear contents of [5], and store 1 in [5]
MOO ; Loop while [4] is non-zero
MOomoOmoO ; Decrement 4 and move to 6
MOO ; Loop while [6] is non-zero
MOomOoMOomoO ; Decrement [5] and [6]
moo ; End loop once [6] is empty
mOoMMMOOOMoOmoOMMMmOomOo ; Copy [5] to [6], and reset [5] to 1, then move back to [4]
moo ; End loop now that [4] is empty. [6] now contains the parity of [3]
moOmoO ; Navigate to [6]
MOO ; Loop while [6] is non-empty
MOomOomOomOoMOomoOmoOmoO ; Decrememnt [3] and [6]
moo ; End loop now that [6] is empty. [3] now contains the largest even number less than the previous iteration.
mOomOomOomOomOoMMMmoOMMM ; Copy [1] to [2]
MOO ; Loop while [2] is non-empty
MOomoOOOMmOomOoMoOmoO ; Decrement [2], increment [1], and print the number in [3].
moo ; End loop now that [2] is empty
mOomOoMoo ; Print a new line
moOmoOmoO ; Navigate to [3]
MOO ; Loop while [3] is non-empty
MOoMOomoOMoOmOo ; Decrement [3] twice and increment [4] once
moo ; [4] now contains half of [3]
moOMMMOOOmOoMMM ; Copy [4] to [3] and clear [4]
MMMmOoMMMMOo ; Copy [3] to [2] and decrement once
moo ;End loop now that [2] is empty
```
Sample output for input 50:
```
50
24
24
12
12
12
12
6
6
6
6
6
6
6
6
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes
```
¸[4÷·€D=¬<#
```
[Try it online!](http://05ab1e.tryitonline.net/#code=wrhbNMO3wrfigqxEPcKsPCM&input=NTA)
**Explanation**
```
¸ # wrap input in a list
[ # start infinite loop
4÷ # elementwise integer divison by 4
· # elementwise multiplication by 2
€D # duplicate each element in the list
= # print it
¬ # get the first element of the list
< # decrease it by 1
# # if true: exit loop
```
[Answer]
## Python 2, ~~55~~ 53 bytes
```
n=input()
while n[0]>2:n=len(n)*2*[n[0]/4<<1];print n
```
Divide by 4 and left shift by 1 to get the special division
[Answer]
# Haskell, ~~75 71 60 50~~ 47 bytes
```
f 0=[]
f n|x<-f$2*div n 4=show n:zipWith(++)x x
```
[Try it online!](https://tio.run/nexus/haskell#y03MzFOwVcjMK0ktSkwuUVBRKM7IL1fQU0gD4qLUxJT/aQoGttGxXGkKeTUVNrppKkZaKZllCnkKJrZglXlWVZkF4ZklGRra2poVChX//xsbAAA "Haskell – TIO Nexus") Edit: As the output is now allowed to be a list including the input, ~~10~~ 13 bytes can be saved.
Usage:
```
Prelude> f 50
["50","2424","12121212","66666666","2222222222222222"]
```
---
**Original 60 byte version:**
```
2%x=""
n%x|z<-2*div n 4=([1..x]>>show z)++"\n"++z%(x*2)
(%2)
```
[Try it online!](https://tio.run/nexus/haskell#BcHRCkAwGAbQe0/xtaw2y2JcmhfBxULZhV8h1vLuc87uPMHC072ebr6RQ3AjoXGubkmGB8tYRjx8sStNsfgHhNaKodY6TH1/bceLKJViIzGlIhehMDKlpvoB "Haskell – TIO Nexus") Thanks to Christian Sievers for pointing out the shorter formula.
Usage:
```
Prelude> (%2)50
"2424\n12121212\n66666666\n2222222222222222\n"
```
[Answer]
# JavaScript (ES6) ~~64~~ ~~59~~ 57 Bytes
```
f=s=>{for(n=1;s>2;)console.log(`${s=s/4<<1}`.repeat(n*=2))}
console.log(f.toString().length);
f(5);
f(50);
f(30);
```
[Answer]
## Python 2, ~~48~~ 47 bytes
```
s=input()
n=1
while s>3:s=s/4*2;n*=2;print`s`*n
```
[Answer]
# Java, 85 bytes
```
n->{String s="";for(int q=2,i;n>2;q*=2,s+="\n")for(i=q,n=n/4*2;i-->0;)s+=n;return s;}
```
## Testing and ungolfed
```
import java.util.function.*;
class Ideone {
public static void main(String[] args) throws java.lang.Exception {
Function<Integer, String> f = number -> {
String result = "";
for (int quantity = 2, i; number > 2; quantity *= 2) {
number = number / 4 * 2; // Make sure that the next is half or half - 1 if odd
for (i = quantity; i > 0; i--) { // copy "quantity" times.
result += number;
}
result += "\n"; // append new line
}
return result;
};
System.out.println(f.apply(50));
}
}
```
Note: I don't know why, Ideone keeps giving internal error, so testing on it is a problem. To test, just copy/paste and run in your standard Java IDE. (It works there, I made sure of it ;) )
[Answer]
# C#, 88 86 83 bytes
*Saved 3 bytes thanks to [Skorm](https://codegolf.stackexchange.com/users/62879/skorm)*
*Saved another byte by changing the `while` to a `for` loop which includes variable declarations*
*Saved 1 bytes thanks to [Yodle](https://codegolf.stackexchange.com/users/59170/yodle)*
```
n=>{var r="";for(int i,c=2;n>2;c*=2,r+="\n")for(i=0,n=n/4*2;i++<c;)r+=n;return r;};
```
Anonymous function which returns a string composed of the result of each grinding.
Full program with ungolfed method and test cases [before the last edit!]:
```
using System;
public class Program
{
public static void Main()
{
Func<int, string> f =
n =>
{
var r = "";
for (int i, c = 1; n > 2; ) // iterator and counter variable
{
n = n/4 * 2; // make sure the result if even
c *= 2; // keep track of the number of rocks
for (i = 0; i++ < c; ) // store the current line made of [c] rocks of size [n]
r += n;
r += "\n"; // add a trailing newline to the string resulted from this step
}
return r; // return the entire history
};
//test cases:
Console.WriteLine(f(5));
Console.WriteLine(f(50));
Console.WriteLine(f(30));
}
}
```
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 21 bytes
```
l~]{{2/-2&_}%_n_2-}g;
```
[Try it online!](https://tio.run/nexus/cjam#K/TTr7bysf7vUxdbXW2kr2ukFl@rGp8Xb6Rbm279PzavVv@/KZexAZepAQA "CJam – TIO Nexus") (As a test suite.)
### Explanation
```
l~] e# Read input, evaluate and wrap it in a singleton list.
{ e# Do while...
{ e# Map this block over the list of rocks.
2/ e# Halve the rock.
-2& e# Bitwise AND with -2, clearing the least-significant bit and
e# rounding down to an even integer.
_ e# Duplicate.
}%
_n e# Print a copy of the current list of rocks.
_2- e# Continue if the current list of rocks contains values that aren't 2.
}g
; e# Discard the final result to prevent printing it again.
```
[Answer]
## Pyth, ~~18~~ ~~16~~ 13 bytes
```
WhQ=Q*2my/d4\n
```
\* `\n` is a new line
Explanation :
```
W # While
hQ # first element of Q - 0 is falsy
=Q # assign to Q
*2 # the double of the (list) that is returned
m # form this \/ map
/d4 # divide every element by 4
y # and double
\n # print Q
```
[Try here](https://pyth.herokuapp.com/?code=WhQ%3DQ*2my%2Fd4%0A&input=%5B30%5D&debug=0)
[Answer]
# [MATL](http://github.com/lmendo/MATL), 13 bytes
```
`K/kEthttH>]x
```
[Try it online!](http://matl.tryitonline.net/#code=YEsva0V0aHR0SD5deA&input=NTA)
```
` % Do...while
K/k % Divide by 4 and round down. Takes input implicitly in the first iteration
E % Multiply by 2
th % Attach a copy of itself (creates a longer array)
t % Duplicate. This copy will be used for further grinding, keeping the original
tH> % Duplicate. True if the values exceed 2. Used as loop condition
] % End. The loop exits if the latest array contains 2
x % Delete last copy. Implicitly display the entire stack
```
[Answer]
# PHP, ~~72~~ ~~67~~ 64 bytes
```
for($n=$argv[$k=1];$n>2;)echo str_repeat($n=$n/2&~1,$k*=2),"\n";
```
Takes argument from command line. Run with `-r`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13 12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
:4Ḥx2µȦпṖY
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=OjThuKR4MsK1yKbDkMK_4bmWWQ&input=&args=NTA)**
Note: the OP stated that the input may also be in the output.
### How?
```
:4Ḥx2µȦпṖY - Main link: rockSize
µ - monadic separation
п - loop collect intermediate results while
Ȧ - any
:4 - integer division (vectorises) by 4
Ḥ - double (vectorises)
x2 - repeat the elements 2 times
Ṗ - pop (remove the trailing list of zeros)
Y - join with line feeds
```
Version without the input displayed for 12 bytes: [`:4Ḥḟ0x2µÐĿḊG`](http://jelly.tryitonline.net/#code=OjThuKThuJ8weDLCtcOQxL_huIpH&input=&args=NTA)
[Answer]
# Perl, ~~40~~ ~~35~~ 30 + 1 = 31 bytes
Run with the `-n` flag
-4 bytes thanks to @Dada
```
say$_ x($.*=2)while$_=$_>>1&~1
```
[Try it online!](https://tio.run/nexus/perl#@1@cWKkSr1ChoaKnZWukWZ6RmZOqEm@rEm9nZ6hWZ/j/v6nBf928/7q@pnoGhgYA "Perl – TIO Nexus")
Perl automatically reads the input into the variable `$_` when `-n` is set. `$.` is a special variable set to `1` at the beginning of the program by the interpreter, so I can use it as a base for doubling. Every iteration of the `while` loop, it bit-shifts `$_` down and performs a logical AND against the negative of itself minus one to cancel out the ones bit.
[Answer]
# PowerShell 3+, ~~58~~ 54 bytes
```
for($s=$input;$s;$s=($s-shr2)*2){"$s"*(2-shl($i++)-1)}
```
Thanks [TimmyD](https://codegolf.stackexchange.com/users/42963/timmyd) for saving me 4 bytes!
### Slightly Ungolfed (formatting)
```
for ( $s = $input ; $s ; $s = ( $s -shr 2 ) * 2 ) {
"$s" * (2 -shl ($i++)-1)
}
```
### Explanation
I'm using the same divide by 4 multiply by 2 trick as a lot of the other answers, but I ran into a problem. PowerShell converts numbers to floating point if needed during division, and for golfing that's annoying because `$v/4*2` becomes something unsighlty like `[int]($v/4)*2`. I got around that using bitshifting for the division with `-shr`.
For calculating how many times to print an iteration I just take `(2^$i)-1` which works nicely and has the added effect of leaving out the input value. Trying to just multiply by 2 was problematic because starting from 0 makes it hard to increase the value with just `$i*=2` and starting from 1 requires too much correction to get the number right.
Since PowerShell doesn't have an operator for it, and I wanted to avoid `[Math]::Pow()`, I relied on bitshifting again for my powers of 2.
[Answer]
# Python 2, 47 Bytes
Since the OP said that a 1D array which included the input was fine I have come up with this recursive function, which unfortunately only ties with the current Python winner.
```
f=lambda s,n=1:[s]*n+(f(s/4*2,n*2)if s>3else[])
```
[Answer]
# Perl, 47 bytes
```
$a=<>>>1;say 2*(($a>>=1)||die)x(1<<$_)for 1..$a
```
No command-line options, this time (unusually for Perl). The basic idea is that as all the rocks at any given step are the same size, we just record the size (in `$a`) and the number (in `$_`), rather than recording the whole list. I couldn't find a way to get rid of the space (or `+`) after `say` ; you can move the `2*` but it won't parse correctly if it's followed by an opening parenthesis.
I can't help but shake the feeling that this is improvable, but I can't see how.
[Answer]
# Vim ~~61~~ 54 bytes
```
qqYpPJ0yw:s;\d*;="/2
;g
:let @t=(">7)+1
@tkjjG@qq@q
```
[TryItOnline!](http://v.tryitonline.net/#code=cXFZcFBKMHl3OnM7XGQqOxI9EiIvMgo7Zwo6bGV0IEB0PSgSIj43KSsxCkB0a2pqR0BxcUBx&input=MTI3)
Unprintables:
```
qqYpPJ0yw:s;\d*;^R=^R"/2
;g
:let @t=(^R">7)+1
@tkjjG@qq@q
```
Luckily vim automatically truncates on x/2.
[Answer]
# JavaScript, ~~71~~ ~~63~~ ~~59~~ 58 Bytes
Well, I came up with this javascript solution. Totally new at golfing, but I foudn this a fun challenge
Saved 4 bytes thanks to Titus suggestion using a for loop.
ungolfed basis:
```
for(o = i = 30; i > 1; i= i/4<<1) {
console.log(`${i}`.repeat(o / i));
}
```
Golfed version
```
for(o=i=30;i>1;i=i/4<<1){console.log(`${i}`.repeat(o/i));}
```
I'm open for suggestions how to improve it / learn golfing
input tester
```
function test(a){
var el = document.getElementById('output');
var text = [];
for(o = i = parseInt(a); i > 1; i= i/4<<1) {
text.push(`${i}`.repeat(o / i));
}
el.innerText = text.join('\n');
}
```
```
<input type="input" onchange="test(this.value)"><button>run</button>
<pre id="output">
</pre>
```
[Answer]
# BASH, 81 bytes
```
n=$1
h=1
while [ ${n//2} ];do
printf -v s %$[h=h*2]s
echo ${s// /$[n=n/4*2]}
done
```
[Answer]
# Swift, 84 Bytes
```
func g(n:Int){var n=n,i=2;while n>2{n=n/4*2;print(Array(repeating:n,count:i));i*=2}}
```
---
**Ungolfed**
```
func grind(rockSize: Int) {
var rockSize = rockSize
var rockCount = 1
while rockSize > 2 {
rockSize = rockSize / 4 * 2
rockCount *= 2
let output = Array(repeating: rockSize, count: rockCount)
print(output)
}
}
```
[Answer]
# Befunge, 45 bytes
```
&1vg0_\:.\v
:\< ^!:-1<p00:*2\.:*2/4,+55_@#`2
```
[Try it online!](http://befunge.tryitonline.net/#code=JjF2ZzBfXDouXHYKOlw8ICBeITotMTxwMDA6KjJcLjoqMi80LCs1NV9AI2Ay&input=NTA)
**Explanation**
```
& read the rock size
1 initialise the count
< start of main loop going right to left
\ swap the size to the top of the stack
:2`#@_ if size is not > 2 then exit
55+, output a line break
4/2* size = size/4*2, i.e. split into even halves
:. output the size
\ swap the count to the top of the stack
2* count = count*2
:00p save count for later
< start of inner loop
1- decrement the count
:!^_ break out of the loop if the count is zero
\ swap the size to the top of the stack
:. output the size
\ swap the count to the top of the stack
v back to the start of the inner loop
0g restore the saved count
v back to the start of the main loop
```
[Answer]
# Javascript, 106 bytes
First code golf, thought I'd have a go. (It's not very good).
```
for(;i[i.length-1]>3;){for(var x=0;x<i.length;x++)i[x]/=2,i[x]%2===1&&i[x]--;i=i.concat(i),console.log(i)}
```
Unminified:
```
while (input[input.length - 1] > 3) {
for (var x = 0; x < input.length; x++) {
input[x] /= 2;
if (input[x] % 2 === 1) input[x]--;
}
input = input.concat(input);
console.log(input);
}
```
] |
[Question]
[
Say that you have a string like this:
`abaabbbbbaabba`
Count the number of times that a specified character appears in the input string, but only if the character appears *only once in a row*. For example, if the character is `a`,
```
abaabbbbbaabba
^ x x ^
```
The total would be 2 (the `aa`'s wouldn't count because the `a` appears two times in a row).
*How is this related to FizzBuzz?*
If the character appears 3 (or a multiple of 3) times in a row, or 5 (or a multiple of 5) times in a row, the counter is *decremented* instead. If it is a multiple of both 3 *and* 5 times, the counter is still incremented. Remember that the counter is also incremented if the character appears only once in a row, and it is ignored if the character appears any other number of times in a row (besides the situations described above).
To recap, if the string to match is `a`,
```
input counter (explanation)
a 1 (single occurence)
aaa -1(multiple of 3)
aaaaa -1(multiple of 5)
aaaaaaaaaaaaaaa 1 (multiple of 15)
aa 0 (none of the above)
aba 2 (two single instances)
aaba 1 (one single occurence(+1) and one double occurence(ignored))
aaaba 0 (one single occurence(+1) and one triple (-1)
aaaaaa -1 (six is a multiple of three)
```
Reference (ungolfed) implementation in java:
```
import java.util.Scanner;
import java.util.regex.*;
public class StrMatcher {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //Scanner to get user input
int total = 0;//Running total of matches
System.out.println("Enter a string: ");
String strBeingSearched = sc.nextLine(); //String that will be searched
System.out.println("Enter string to match with: ");
String strBeingMatched = sc.nextLine(); //Substring used for searching
//Simple regex matcher
Pattern pattern = Pattern.compile("(" + strBeingMatched + ")+");
Matcher matcher = pattern.matcher(strBeingSearched);
while(matcher.find()){ //While there are still matches
int length = matcher.end() - matcher.start();
int numberOfTimes = length/strBeingMatched.length();//Calculate how many times in a row the string is matched
if((numberOfTimes == 1)||((numberOfTimes % 3 == 0) && (numberOfTimes % 5 == 0))){
total++; //Increment counter if single match or divisible by 15
} else if((numberOfTimes % 3 == 0)||(numberOfTimes % 5 == 0)) {
total--; //Decrement counter if divisible by 3 or 5 (but not 15)
}
strBeingSearched = strBeingSearched.substring(matcher.end());
matcher = pattern.matcher(strBeingSearched); //Replace string/matcher and repeat
}
System.out.println(total);
}
}
```
* The string that will be searched can be any length, but the pattern will only be a single character.
* Neither string will have regex special characters.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest program in bytes wins.
* No standard loopholes.
[Answer]
# [Funciton](http://esolangs.org/wiki/Funciton), 1840 bytes
Damn, this language is ungolfable.
This program expects the first character of the input to be the character to search for, and the rest of the input to make the string to search through. This means that `aaaba` will search for `a` in the input `aaba` (and thus output 1). You *can* separate them with a newline or space (`a aaba`) but only because the extra newline/space makes no difference to the output.
As always, you can get a nicer-looking rendering (without the line spacing) if you execute `$('pre').css('line-height',1)` in your browser console.
```
┌───┐
│╓─╖└─────────────┐
└╢³╟┐ ┌─────┐ ┌┴┐╓─╖
┌─────┐╙─╜└────┤┌─╖ ┌┴╖│┌┘║¹║
│ ├───────┐└┤²╟─┤·╟┘│ ╙┬╜╔═══════╗
│ ┌┴╖╔═╗┌─╖├┐╘╤╝ ╘╤╝┌┘ └┬╢2097151║
│ │♭║║5╟┤%╟┘└─┴──┐│┌┘┌───┘╚═══════╝
│ ╘╤╝╚═╝╘╤╝╔═╗┌─╖│││┌┴┐┌────┐
│ ┌┴╖ ┌┘ ║3╟┤%╟┘││└┬┘│╔══╗└┐
│ ┌─┤·╟─┐ │ ╚═╝╘╤╝ │└┐ │║21╟┐│
│ │ ╘╤╝ ├─┘┌─────┘ └┐└┐ │╚══╝│└─┐
│ ┌┴╖┌┴╖┌┴╖┌┴╖┌─╖ ┌┴╖│ │┌─╖┌┴─╖│
│┌┤·╟┤?╟┤?╟┤?╟┤+╟────┤³║│ └┤²╟┤>>║└──┐
││╘╤╝╘╤╝╘╤╝╘╤╝╘╤╝ ╘╤╝│ ╘╤╝╘╤═╝╓─╖│
││ │ ┌┴╖┌┴╖┌┴╖┌┴╖╔═╗ ┌┴╖│ ┌┴╖ ├──╢²╟┤
││ └─┤·╟┤·╟┤?╟┤·╟╢1║┌┤·╟┘ │♯║┌┴╖ ╙─╜│
│└──┐╘╤╝╘╤╝╘╤╝╘╤╝╚═╝│╘╤╝ ╘╤╝│¹║┌───┘
└──┐│╔╧╗ └┬─┘ ┌┴╖ │┌┴─╖ │ ╘╤╝│
││║1║ ┌┴┐┌─┤?╟───┴┤>>╟┐ ┌┴╖┌┴╖│
││╚═╝ └┬┘│ ╘╤╝ ╘══╝│┌┤?╟┤=║│
│└────┐│╔╧╗ ┌─────┘│╘╤╝╘╤╝│
╔═╗└────┐│├╢0║╔══╗┌┴╖┌─╖ ╔╧╗ └─┘
║ ║ │└┘╚═╝║21╟┤×╟┤♯╟┐║0║
╚╤╝ └──┐ ╚══╝╘═╝╘═╝│╚═╝
│┌──┴────╖└────────────┘
││int→str║
│╘══╤════╝
┌┴─╖┌┴╖┌─╖╔╗
│>>╟┤³╟┤¹╟╢║
╘═╤╝╘═╝╘═╝╚╝
╔═╧╗
║21║
╚══╝
```
(1840 bytes when encoded as UTF-16.)
# Explanation
* `¹` returns the first character of a string.
* `²` counts the number of occurrences of a character at the start of a given string. For example, given the character `a` and the string `aaba`, it returns 2. For `a` and `baa`, it returns 0.
* `³` calls `²` to get the number of characters at the start, examines whether the number is divisible by 3 and 5 and whether it is equal to 1 and determines the proper increment/decrement. It also removes one extra character from the start of the string (e.g. given `aaabba` it removes 3+1=4 characters, giving `ba`). Then it calls itself recursively with the shorter string and adds the result.
* The main program calls `¹` to remove the first character from the input and calls `³` with that character and the rest of the string as separate arguments.
[Answer]
# CJam, ~~40~~ ~~36~~ ~~35~~ ~~32~~ 30 bytes
```
0llcf=e`::*{(_g+Y13515Yb+=(+}/
```
*Thanks to @MartinBüttner for golfing off 1 byte!*
*Thanks to @AndreaBiondo for golfing off 2 bytes and paving the way for 3 more!*
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=0llcf%3De%60%3A%3A*%7B(_g%2BY13515Yb%2B%3D(%2B%7D%2F&input=aaaba%0Aa).
### How it works
```
0 e# Push a 0 (accumulator).
l e# Read a line from STDIN.
lc e# Read a second line and keep only the first character.
f= e# Check each character from the first line for equality.
e# This results in 1 for the specified character and 0 for others.
e` e# Perform run-length encoding.
::* e# Multiply each element by its number of repetitions.
{ e# For each remaining integer I:
(_! e# Subtract 1, copy and push sign(I-1).
+ e# Add the results.
e# If I == 0, I-1 + sign(I-1) = -1 + -1 = -2.
e# If I == 1, I-1 + sign(I-1) = 0 + 0 = 0.
e# If I >= 2, I-1 + sign(I-1) = I-1 + 1 = I.
Y e# Push 2.
13515Yb e# Convert 13515 into the array of its binary digits.
+ e# Concatenate 2 and the array.
e# This pushes [2 1 1 0 1 0 0 1 1 0 0 1 0 1 1].
= e# Retrieve the digit at (index I-1 + sign(I-1))%15.
e# If I == 0, this pushes 1.
e# Else, if I == 1, this pushes 2.
e# Else, if I%15 == 0, this pushes 2.
e# Else, if I%3==0 or I%5==0, this pushes 0.
e# Else, this pushes 1.
( e# Decrement the result.
+ e# Add it to the accumulator.
}/ e#
```
[Answer]
## **C, ~~160~~ ~~126~~ ~~125~~ ~~119~~ ~~114~~ ~~109~~ ~~104~~ 100 bytes**
```
main(int q,char **z){int i=0,t=0,s=0,a=z[1][0],c;do{if((c=z[2][i])!=a){s+=(!!t)*((t==1)-!(t%3)-!(t%5)+3*!(t%15));t=0;}else{++t;}++i;}while(c);printf("%d\n",s);}
```
Probably can be made better...
This takes input from command line arguments (first argument is pattern, second is string). Does not support searching for pattern of NULL char (\x00).
EDIT \*\*~~126~~ ~~125~~ ~~119~~ ~~114~~ ~~109~~ ~~104~~ 100 bytes \*\*: After incorporating Dennis's suggestions, and some additional ideas (removed else clause, combined the while into one single statement and used subtraction instead of !=). Also removed extra semicolon in for loop (that was actually part of Dennis's suggestion).
Shortened even more by removing the variables 'i' and 'a'.
```
t,s;main(c,z)char**z;{for(;c;t++)if((c=*z[2]++)-*z[1])s+=!!t*((t<2)-!(t%3)-!(t%5)+3*!(t%15)),t=-1;printf("%d",s);}
```
Removed the if and negation ('!') operators by abusing the ternary operator.
Compressed the modularity checks by using ~~that bitwise 'AND' trick~~ a double && because bitwise '&' has a bug, and putting the (t<2) comparison inside the ternary operators.
Replaced !!t \* (...) by moving !!t into the ternary operator, thus allowing me to remove parentheses.
Man, I really want to get it below the 100 byte mark :S
```
t,s;main(c,z)char**z;{for(;c;)(c=*z[2]++)-*z[1]?s+=t%15?t%3&&t%5?t<2:-1:!!t,t=0:t++;printf("%d",s);}
```
TENTATIVE solutions:
I am not sure if these would be considered valid, but I can get down to 93 chars if I use exit(s) instead of printf("%d",s). But then the output would not be visible, rather it would be a return code.
If output is really necessary, I can also get it down to 98 bytes, but it would require printing all intermediate values of s before the final answer as well...
[Answer]
# Ruby, ~~111 103~~ 96 bytes
```
->s,m{s.chars.chunk{|x|x}.reduce(0){|x,(c,g)|l=g.size
x+(c!=m ?0:l<2||l%15<1?1:l%3*l%5<1?-1:0)}}
```
This challenge was made for Ruby's [`Enumerable#chunk`](http://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-chunk), so I had to post this. :)
Online test: <http://ideone.com/pG4mAn>
The code is pretty much straightforward. Here's a more readable version: <http://ideone.com/ub3siA>.
[Answer]
# Python 3, ~~361, 300, 296, 263, 256, 237, 229, 188, 178~~, 164 bytes.
Saved 15 bytes thanks to vaultah from SOPython.
Saved 9 bytes thanks to Joe Kington from SOPython.
Saved 11 bytes thanks to DSM from SOPython.
This is my first time submitting an answer, so I'm sure this could be much shorter. It takes the test string as the first response to input, and the search char as the second one.
```
t=input()
m=input()
c=u=0
g=iter(t)
while g:
r=next(g,0)
if r==0:print(c);g=0
while r==m:u+=1;r=next(g,0)
if u:b=u%3<1;v=u%5<1;c+=((0,-1)[b|v],1)[u<2or b&v];u=0
```
Ungolfed version:
```
import sys
test = sys.argv[1]
match_char = sys.argv[2]
counter = char_counter = 0
char_generator = (c for c in test)
while char_generator:
try:
char = next(char_generator)
except StopIteration:
print(counter)
break
while char == match_char:
char_counter += 1
try:
char = next(char_generator)
except StopIteration:
break
if char_counter == 0:
continue
counter += 1 if char_counter == 1 or (char_counter % 3 == 0 and char_counter % 5 == 0) else -1 if char_counter % 3 == 0 or char_counter % 5 == 0 else 0
char_counter = 0
```
Discovered I was failing one of the test cases.
[Answer]
# Haskell, 120 bytes
```
import Data.List
f c=sum.map(v.length).filter((==c).head).group
v 1=1
v n|n%3&&n%5=1|(n%3||n%5)=(-1)|0<1=0
x%y=x`mod`y<1
```
`f` does the job.
[Answer]
# Java, ~~146~~ ~~152~~ ~~143~~ ~~138~~ ~~139~~ 136 bytes
1. Fixed a bug.
2. shifted operations, switched to bitwise operator for the `%3&%5` checks.
3. Shortened `i<2` comparison.
4. Fixed a bug (`%3&%5` check not working as thought).
5. Used multiplication shortcut as seen in [@w0lf](https://codegolf.stackexchange.com/a/58376/21697)'s Ruby answer.
Implemented as a `BiFunction<String, String, Integer>` in Java 8, let me know if this is required to be a full program (or if I can even drop the `java.util.regex` package prefix below).
Byte count above does not include the newline below, which is simply added for formatting purposes on this site.
```
(a,b)->java.util.regex.Pattern.compile("[^"+b+"]").splitAsStream(a)
.mapToInt(v->v.length()).map(i->i<2?i:i%15<1?1:i%3*i%5<1?-1:0).sum();
```
Rough explanation:
1. Apply regex with pattern that *does not* match `b`, i.e. `"[^"+b+"]"`.
2. Get length of each token (e.g. `"a" -> 1`).
3. Apply the desired mapping to `-1`, `0` and `1`.
4. `sum()` to get answer.
[Answer]
# Javascript, 206 bytes
```
function f(n,e){var t=n.match(new RegExp(e,"g")).length,g=n.match(new RegExp(e+"{2,}","g"));return null!==g&&g.forEach(function(n){t-=n.length,n.length%15==0?t+=1:(n.length%3==0||n.length%5==0)&&(t-=1)}),t}
```
### Expanded:
```
function funkyFizzb(n, c) {
var score = n.match(new RegExp(c, "g")).length;
var repeatOccurence = n.match(new RegExp(c + "{2,}", "g"));
if(repeatOccurence !== null) {
repeatOccurence.forEach(function(v,i){
// remove multiple occurrence counts
score -= v.length;
if(v.length % 15 == 0) {
score += 1;
}
else if(v.length % 3 == 0 || v.length % 5 == 0) {
score -= 1;
}
});
}
return score;
};
```
### Explanation:
I'm using regex to count total times a character appears, then subtract from that all the times it appeared in groups. Finally, I go through the groups and do the fizz buzz increment / decrement.
Passes the test cases given in the question:
```
funkyFizzb("aaa", "a") => -1
```
and so on
[Answer]
# Perl, ~~82~~ ~~65~~ ~~63~~ 59 bytes
58 bytes + 1 byte command line parameter
Not particularly short, but it's a start - will continue shortening it.
```
$l=y///c,$i+=!($l>1&&$l%15)||-!($l%3*$l%5)for/$^I+/g;$_=$i
```
Assuming `-i` can be used to give the input string an example usage is as follows:
```
echo "aaabaaa" | perl -pi"a" entry.pl
```
[Answer]
# Pyth, 32 bytes
so close! 2 more bytes to tie Dennis' excellent CJam entry
```
s.b?qYz?tN@+,0_1 1+}3PN}5PN1Zrw8
```
[Test it Online](https://pyth.herokuapp.com/?code=s.b%3FqYz%3FtN%40%2B%2C0_1+1%2B%7D3PN%7D5PN1Zrw8&input=a%0Aabaaaaaabbbbbaaaaabbaabaaaaaaaaaaaaaaab&test_suite_input=1%0A2%0A15%0A77%0A12345678929&debug=0)
[Answer]
# gawk, 140
```
p=$2{b="[^"$1"]";for($0=2;$i-->0;){sub("^"b"*",_,p);p=substr(p,$++i=match(p,b))}for($i=length(p);$++j;)s+=$j%5?$j%3?$j<2:-1:$j%3?-1:1}$0=s""
```
Input as "char space string", like so
```
echo "x axxbxcxdexxxfffghixxj" | awk 'p=$2{b="[^"$1"]";for($0=2;$i-->0;){sub("^"b"*",_,p);p=substr(p,$++i=match(p,b))}for($i=length(p);$++j;)s+=$j%5?$j%3?$j<2:-1:$j%3?-1:1}$0=s""'
```
### Ungolfed
```
p=$2{
#i=j=s=0 # make reusable
b="[^"$1"]"; # pattern "not matching char"
$0=2; # help starting the while loop
while($i-->0){ # match didn't return -1; dec stack top
sub("^"b"*",_,p); # remove not matching chars at head of string
$++i=match(p,b); # push index of first occurence of not matching char
p=substr(p,$i) # remove matching chars from head of string
};
$i=length(p); # get last value
while($++j) # sometimes last value on stack is 0
s+=$j%5?$j%3?$j<2:-1:$j%3?-1:1
# if $j%5!=0
# if $j%3!=0 (not divisible by 5 AND 3)
# s+=($j==1) (single character)
# else (divisible by 3 but not by 5)
# s-=1
# else (divisble by 5)
# if $j%3!=0
# s-=1 (divisible by 5 but not by 3)
# else
# s+=1 (divisible by 3 AND 5)
}$0=s"" # output
```
[Answer]
# Pyth, 27 bytes
```
sm|!JPdx,02+}3J}5JhMf}zTrw8
```
[Test suite](https://pyth.herokuapp.com/?code=sm%7C%21JPdx%2C02%2B%7D3J%7D5JhMf%7DzTrw8&input=%5B1%2C+0%2C+2%2C+0%2C+7%2C+7%2C+7%2C+0%2C+5%2C+0%2C+0%2C+0%2C+9%5D&test_suite=1&test_suite_input=a%0Aaaa%0Aa%0Aaaaaa%0Aa%0Aaaaaaaaaaaaaaaa%0Aa%0Aaa%0Aa%0A%0Aa%0Aaba%0Aa%0Aaaba%0Aa%0Aaaaba%0Aa%0Aaaaaaa%0A&debug=0&input_size=2)
Input in the form e.g.:
```
a
aaaba
```
Explanation:
```
sm|!JPdx,02+}3J}5JhMf}zTrw8
z = input() (The match character)
w input() (The string)
r 8 Run length encode
f}zT Filter for the runs z is in.
hM Take their lengths
m| Map (d) to the logical or of
Pd Find all prime factors of the current run length
J Save them in J
! Take the logical negation. This will be 1 if
d is 1, and 0 otherwise.
+}3J If d wasn't 1, add up 1 if 3 is in J
}5J and 1 if 5 is in J.
x,02 Then, take the index of the result in [0,2]
so 0 -> 0, 2 -> 1, 1 -> -1 (not found)
s Sum up the values for each run.
```
] |
[Question]
[
## Challenge
Given a string of any length, write it as a triangle, spiraling out from the center. For example, `abcdefghijklmnop` becomes:
```
g
fah
edcbi
ponmlkj
```
Or more explicitly:
[](https://i.stack.imgur.com/NyzLX.png)
If you like, you can spiral counter-clockwise instead:
```
g
haf
ibcde
jklmnop
```
Or add spaces uniformly:
```
g
f a h
e d c b i
p o n m l k j
```
The input characters will be ascii, but may include spaces. Also, the number of characters may not be a perfect square (`Hello World!`):
```
W
Ho
oller
!dl
```
A couple more edge cases. 2 letter input `ab`:
```
a
b
```
And 3 letter input `abc`:
```
a
cb
```
## Procedural Description
In case the above examples aren't clear, here's a procedural description of the process:
1. Put down your initial letter.
2. Move diagonally down and to the right (i.e., this direction `\`). So if you started at `(0,0)`, you will now be at (1,-1). Put down your second letter.
3. Move left one space a time, dropping a letter on each space, for a total of 3 spaces. That is, drop letters on `(0,-1)`, `(-1,-1)`, and `(-2, -1)`.
4. Next move diagonally up and to the right `/` two spaces, dropping letters on `(-1,0)` and `(0,1)`.
5. Now cycle back to moving diagonally down and to the right, continuing to step and drop letters as long as your current position is left-right adjacent to an existing letter.
6. Next move left again, continuing to step and drop letters as long as you are diagonally adjacent `/` to an existing letter.
7. Move diagonally up and to the right again `/`, stepping and dropping letters as long as your current position is left-right adjacent to an existing letter.
8. Repeat steps 5-7 until all letters are used up.
## More examples
## Rules
* Code golf, standard rules apply.
* Trailing spaces or newlines are ok.
* Consistent leading spaces or newlines are also ok, as long as the shape of the triangle is preserved.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 99 bytes
```
sPrint@@@Array[s[[4# #-2#+1-#2&@@If[Abs@#2<2#,!##,#-Abs@#2|-#2]]]/._@__->" "&,2{L=Tr[1^s],L},-L]
```
[Try it online!](https://tio.run/##JY1BTsMwEEX3OUXqkbLBBtViSdFUCESlLECtxMIy0cR1mkASV7a7QKU9BDfghBwhTenmfT29xe8o1raj2BgaqtkQ/n5@X3zTR0Sce09fKih1CykICVdTATJDXFRqXgYEeSeBTwA4iIt/j11rfXNdYFGIe5ayjMt9Plt5NX0PmucHLnI9vO4aG7HCh5o8mWh9wEdTOwWcMb5yyzj@b0Zb9NtdfHK@05nOjktD/XGfMCrN2labuvn4bLvebRlP2LNtW5e@Od@uJ2enf5QXmvOw5DCcAA "Wolfram Language (Mathematica) – Try It Online")
Directly computes the index of each position: in Cartesian coordinates,
\$\operatorname{index}(x,y)=\textit{offset}+\begin{cases}2y(2y+1)-x,&|x|<-2y\\
2\left(y+|x|\right)\left(2\left(y+|x|\right)+1\right)+x,&\text{else}\end{cases}\$
where \$\textit{offset}\$ is the index of the "first" character (1, in Mathematica).
Takes a list of characters as input.
---
### Older approach, ~~123~~ ~~122~~ ~~109~~ 107 bytes
```
Print@@@Normal@SparseArray[i=0;p=2Length@#;(p+=ReIm[I[2+I,1-I][[⌈2√i++⌉~Mod~4-1]]-1])->#&/@#,2p," "]&
```
[Try it online!](https://tio.run/##JY7NSsQwGEX3fYoxhaI0Rae4GyoRUQyoyFRwEbL4Jk2bav7IxIWIXc/APIGP1xepHV3cczm7YyAqaSD2Aqa2mp5DbyMh5MkFA5rUHsJWXocAn6yvLla@Kh@k7aIi6erU59VaUsMoK3OKlwXljI2HXTnufvo8Hw/74dE1w2Wx5HzeWXGVZuckxaXHaIF4NrXkRkEAEWXYkluhHEsxQvjF1XGu6Gaj1n/EuzmFZzwbagF2@EoQbEQj2071b@/aWOcRTtC91NotXl3QzcnR4Q@bf4rjoeR7@gU "Wolfram Language (Mathematica) – Try It Online")
The direction of the (1-indexed) `i`th character relative to the previous character can be computed with \$\Big\lceil2\sqrt i\Big\rceil\bmod 4\$:
* 1: ↗
* 2: ↘
* 3,0: ←
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~37~~ ~~36~~ 21 bytes
```
GH✳✳E⊖LθI§4174⌈⊗₂⊕ι²θ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY7NCoJAFIVfRVxdQReFUNAqcpFQELWMFuN41alxrs6M_Wx7jTYuinqAXqa3SUjoLA_f-Ti3Fy-Y5sRk2z4amwXjz3VF8pKTmpOUdIJIaORWkDKwZBVEyDWWqCymsECV2wJqz_OdGTMWpjZWKZ7BDQej0O1KFFKoHCJqEtkNNnXDNK6JLMTq7xFeH98Z-k7tTe4m4ab_89y6wVG6uzdLeIpZXoj9QZaKqlob-0O- "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation: Inspired by @KevinCruijssen's 05AB1E solution, but then using @att's formula to generate the directions.
```
θ Input string
L Length
⊖ Decremented
E Map over implicit range
ι Current index (0-indexed)
⊕ Incremented (i.e. 1-indexed)
₂ Square rooted
⊗ Doubled
⌈ Ceiling
§4174 Cyclically index to find direction
I Cast to integer
✳✳ Convert to directions
GH ²θ Draw path using input string
```
The path drawing command draws one character for the start and then `n-1` characters for each direction in the array. Unfortunately there aren't any single character strings that represent diagonal directions so I have to use integers instead; these start at `0` for right and increment for each 45° clockwise.
Previous 37 byte solution:
```
≔⮌⪪S¹θFLθF³F§⟦⊕⊗ι⁺³×⁴ι⊗⊕ι⟧κ¿θ✳⁻⁷׳κ⊟θ
```
[Try it online!](https://tio.run/##TU6xrsIwDNz5ioyOVAbUJ72BCYmlEkgI3vbEUFK3NU2dNnERfx/SCiQWn3w@351pS29caWPchUANwxkf6APCZbAkUPAwyUU8cQM6Uxudxqi3q9p5BQfkRloYtVbLnr9xJwVX@IT/go3HHlmwgr2bbjYhzRYnOwXIM/VHPQb4ydTCfiTfb@lwzVSXIqhWKUqdUheBPXk0Qo7hSJy8fj9e@SKeI9wwN9vGWN5MhXXT0r2zPbth9EFWcf2wLw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⮌⪪S¹θ
```
Split the input into characters and reverse the list.
```
FLθ
```
Loop a large enough number of times.
```
F³
```
Loop for each side of the triangle.
```
F§⟦⊕⊗ι⁺³×⁴ι⊗⊕ι⟧κ
```
Loop for the size of the side.
```
¿θ
```
Check whether there is still anything left to print.
```
✳⁻⁷׳κ⊟θ
```
Print the next character in the appropriate direction.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~24~~ ~~20~~ ~~15~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2Iā¨t·îŽOGsèΛ
```
-7 bytes by porting [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/210459/52210), using [*@att*'s formula](https://codegolf.stackexchange.com/a/210464/52210), so make sure to upvote both of them as well!
[Try it online.](https://tio.run/##ASoA1f9vc2FiaWX//zJJxIHCqHTCt8Ouxb1PR3PDqM6b//9IZWxsbyBXb3JsZCE) No test suite, because the `.Λ` builtin will keep its previous contents and there isn't any way to reset it ([this is what it would look like](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VT@Nyo@0nhoRcmh7YfXHd3r7158eIXeudn/df5HKyUmJaekpqVnZGZl5@Tm5Rco6Sh5pObk5CuE5xflpCgCuYlJYCJZKRYA).
**Explanation:**
```
2 # Push a 2
I # Push the input-string
ā # Push a list in the range [1,length] (without popping)
¨ # Remove the last value to change the range to [1,length)
t # Take the square-root of each value
· # Double each
î # Ceil each
ŽOG # Push compressed integer 6136
s # Swap so the list is at the top of the stack again
è # Index each value (0-based and modulair) into the 6136
Λ # Pop all three and use the Canvas builtin,
# after which the result is implicitly output immediately afterwards
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ŽOG` is `6136`.
The Canvas builtin uses three arguments to draw a shape:
* Character/string to draw: the input in this case
* Length of the lines we'll draw: `2` in this case
* The direction to draw in: `[3,6,6,6,1,1,3,3,3,6,6,6,6,6,6,6,1,1,1,1,3,...]`.
See the original answer below for an explanation of the Canvas builtin. Unlike the program below where the list of lengths are leading, here the list of directions are leading because we use a single length of `2`.
---
**Original ~~24~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:**
```
ā·Ð·s>ø.ι˜DŠOð׫₆1ªΛ
```
Contains leading/trailing spaces and newlines (the longer the input, the more spaces/newlines)
[Try it online.](https://tio.run/##ATkAxv9vc2FiaWX//8SBwrfDkMK3cz7DuC7OucucRMWgT8Oww5fCq@KChjHCqs6b//9IZWxsbyBXb3JsZCE) No test suite, because the `.Λ` builtin will keep its previous contents and there isn't any way to reset it ([this is what it would look like](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VT@P9J4aPvhCYe2F9sd3qF3bufpOS5HF/gf3nB4@qHVj5raDA@t0js3@7/O/2ilxKTklNS09IzMrOyc3Lz8AiUdJY/UnJx8hfD8opwURSA3MQlMJCvFAgA), where the test cases are drawn on top of one another).
**Explanation:**
```
ā # Push a list in the range [1, length] of the (implicit) input (without popping)
# i.e. "Hello World!" → "Hello World!" and [1,2,3,4,5,6,7,8,9,10,11,12]
· # Double each value in this list
# → [2,4,6,8,10,12,14,16,18,20,22,24]
Ð # Triplicate it
· # Double each value of the top copy
# → [4,8,12,16,20,24,28,32,36,40,44,48]
s # Swap to get the other copy
> # Increase each by 1
# → [3,5,6,9,11,13,15,17,19,21,23,25]
ø # Create pairs of the top two lists
# → [[4,3],[8,5],[12,7],[16,9],[20,11],[24,13],[28,15],[32,17],[36,19],[40,21],[44,23],[48,25]]
.ι # Interleave it with the third list
# → [2,[4,3],4,[8,5],6,[12,7],8,[16,9],10,[20,11],12,[24,13],14,[28,15],16,[32,17],18,[36,19],20,[40,21],22,[44,23],24,[48,25]]
˜ # Flatten
# → [2,4,3,4,8,5,6,12,7,8,16,9,10,20,11,12,24,13,14,28,15,16,32,17,18,36,19,20,40,21,22,44,23,24,48,25]
D # Duplicate this list of integers
Š # Triple-swap, so the stack order is list,input,list
O # Pop and sum the top list
# → 636
ð× # Create a string of that many spaces
« # And append it to the string
₆ # Push builtin 36
1ª # Convert it to a list of digits, and append 1: [3,6,1]
Λ # Use the Canvas builtin with these three arguments,
# after which the result is implicitly output immediately afterwards
```
The Canvas builtin uses three arguments to draw a shape:
* Character/string to draw: the input in this case, appended with trailing spaces
* Length of the lines we'll draw: the list `[2,4,3,4,8,5,6,12,7,8,16,9,10,20,11,...]`
* The direction to draw in: `[3,6,1]`. The digits in the range \$[0,7]\$ each represent a certain direction:
```
7 0 1
↖ ↑ ↗
6 ← X → 2
↙ ↓ ↘
5 4 3
```
So the `[3,6,1]` in this case translate to the directions \$[↘,←,↗]\$.
Here a step-by-step explanation of the output (we'll use input `"Hello_World!"` as example here):
Step 1: Draw 2 characters (`"He"`) in direction `3↘`:
```
H
e
```
Step 2: Draw 4-1 characters (`"llo"`) in direction `6←`:
```
H
olle
```
Step 3: Draw 3-1 characters (`"_W"`) in direction `1↗`:
```
W
_H
olle
```
Step 4: Draw 4-1 characters (`"orl"`) in direction `3↘`:
```
W
_Ho
oller
l
```
Step 5: Draw 8-1 characters (`"d! "`) in direction `6←`:
```
W
_Ho
oller
!dl
```
Et cetera for all other trailing spaces.
[See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210)
[Answer]
# [JavaScript (V8)](https://v8.dev/), 222 bytes
```
s=>(g=(a,b,n=1)=>b?g([(c=(b+' '.repeat(n*8)).slice(0,n*8))[n*6-1],...[...a,c.slice(0,n*4-1)].map((l,i)=>c[n*6+i]+l+c[n*6-2-i])],b.slice(n*8),n+1):a)([s[0]],s.slice(1)).reduce((p,l,i,a)=>p+' '.repeat(a.length-i-1)+l+`
`,'')
```
[Try it online!](https://tio.run/##XY5Zb8IwEITf@RX0yWtiW6SqKlQpVL3pfZe2kSWcxART47hOSI8/nxqEKsTDSjOa3W92KmpRpk7Zita9Zhw1ZdSHPAJBEmKiEEf9ZD@HGNIIkgC1EXPSSlGB6fQwZqVWqYQuWbrYdHZpyAljLPYjSLqW79AQczYTFkAT5bHpYj1QPNDBUtJtqjjmJFkdLZDEBCHeExjiMu5yTspVFvpqJ7O5l2CJ5xHhiXb9P8G0NHk1ocoX@45Ra0QQwo11ylQwBjSQWhftYeF0toUwbv0HIkkzOc4navqhZ6awn66s5vXX98/vweHR8cnp2eD84vLq@ub27v7h8en5Zfj69r4B2OR53/wB "JavaScript (V8) – Try It Online")
It most definitely can be golfed more.
I use a recursive algorithm, splitting the output into triangle 'layers', where each layer is a complete wrap (three sides) of the previous triangle.
Ungolfed
```
s=>(g=(a,b,n=1)=> // g is a recursive function; a: previous; b: rest; n: increment
b ? // if there is more string to wrap
g([ // wrap b around a as a triangle and recurse
(c=(b+' '.repeat(n*8)).slice(0,n*8))[n*6-1],
...[...a,c.slice(0,n*4-1)].map((l,i)=>c[n*6+i]+l+c[n*6-2-i])
],
b.slice(n*8),
n+1)
:a // otherwise return the triangle
)
([s[0]],s.slice(1)) // run the function with the first letter and the rest
.reduce((p,l,i,a)=>p+' '.repeat(a.length-i-1)+l+'\n','') // step the triangle to make it look like it is meant to
```
[Answer]
# JavaScript (ES8), 137 bytes
Expects an array of characters. Returns a string.
This version is based on [the formula used by @att](https://codegolf.stackexchange.com/a/210464/58563), modified to be more golf-friendly in JS.
```
a=>a.map((c,n)=>(m[y+=~(d=2*n**.5-1/n)%4%3?d&++x/x||-1:!x--]=m[y]||[...''.padEnd(x)])[x]=c,m=[],x=y=a.length)&&m.map(r=>r.join``).join`
`
```
[Try it online!](https://tio.run/##bY7LTsMwFET3@Qo3UlM7D1flsaFyWFXiD1hElmJs54VjBycUBwK/HgxlyWZmdO6VZjp2ZiO37TBl2gi5VmRlJGe4ZwOEPNWI5LAv5oR8QUGuYh3H@DY77DXa3myv70WUJG7vliU73G1cllHif@myFBjj3Q4PTJy0gA5RVDhKeNqTgqaOzIRhJXU9NSiK@t8uS3KLO9PqskQXD8r1WAQAhA9SKQMejVViE6YgZE8X5X8mZFU3bfesem2G/9iLHafX85ub38OABrgy9sR4A0dAcvDhG6z0EVTwZ/VI0dEjbvRolMTK1NCfPftE6zc "JavaScript (Node.js) – Try It Online") (raw output)
[Try it online!](https://tio.run/##bY9NU4MwEEDv/IqUsSXhI1i1FzvBU2e8ePHiAZghQoDWkGDAmlrwr2O0nZ687O683dm3u6N72uVq2/aBkAWbSjJRElHc0BbC3BeIRLCJDx75hgW5cYXr4lWwDAWa381vH4qF5@lQD0OwvJ/pIEiJmU2HIcYYOw5uabERBdQoRbFOSe43JE59TQ6EYs5E1ddosWj@XIpECu/kVmQZOmUrm9axBYD9yDiX4EUqXsxsH9j09RTzcypYWdXb3RtvhGz/Y@@q6z/2n/rwZVuphUupNjSvYQdIBI7GoJgpQQl/r@5StDYol6KTnGEuK2jaWLGW05zBMBFeWBlHImx0oc@s2ugWZkkiwPHq2J2fAwF4on2NSy6lghfquuAar9A4Zj5wKgedtxnviKYf "JavaScript (Node.js) – Try It Online") (with extra whitespace removed)
### How?
Given the position \$n\$ of the character, the direction \$0\le d\le 2\$ can be computed with:
$$d=\left(\left\lfloor2\sqrt{n}+1-\frac{1}{n}\right\rfloor\bmod 4\right)\bmod 3$$
The actual JS implementation is:
```
~(2 * n ** 0.5 - 1 / n) % 4 % 3
```
which evaluates to \$0\$, \$-1\$ or \$-2\$.
---
# JavaScript (ES8), ~~163~~ 157 bytes
Expects an array of characters. Returns a string.
```
a=>a.map(c=>((m[y]=m[y]||[...''.padEnd(x)])[x]=c,j%3%2?x--:y+=!!++x-j%3,k?k--:k=(n=j/3<<1)+(j++%3||n+2)),m=[],j=k=0,x=y=a.length)&&m.map(r=>r.join``).join`
`
```
[Try it online!](https://tio.run/##bY@9boMwHMR3nsJBIrFlcNuwNfmTKVLfoANCwuHbGJsamkJLn506Tccud6ffDacT/MqHzDT9GCidF2sJK4eIs473OIMI4y6eE7jJssSMsd2O9Tw/qxxPJCHxlEDmCy/09qcpCJ5nCpsNpVNgkd@eWotawArEQ3g8PhGKBaVeuCyK7gnxO4gTX0ALj/4EM3AmC1WNNdluu999A5FhQjcqTcndnXQ9xA5C7kshpUav2sh84/rI5Ze7Zn@WF2VVN6KVndL9f@zNDOP79WOaP10ncVipzZlnNR4QROjLLpjCRlTi2@chIQeLMq0GLQsmdYVtbdk3WX8A "JavaScript (Node.js) – Try It Online") (raw output)
[Try it online!](https://tio.run/##bY9Bb4IwGIbv/IpKprQC1Wl2mRZPJrvssssOQEIHBYTSssIcTPztrE7jaZfv/fJ8yffkLeiRNrE61K0rZMLGlIyUeBRXtIYx8SCs/D4klzEMPsbYsnBNk71IYIdC5HchiZ1iup6udp3rPvc2mUxsu3M1cspdqVFJoCDFYr3dPiIbFrY9XQ@DsFcIORXxQ6cgJVk6HekJxZyJrM3RbFb9@RXxFC7kQUQRuqYRjRvfAMB8YZxL8C4VTyamA0z6cZ3xLRKWZvmhKHklZP0f@1RN@3X87vof0wgNnEq1p3EOG0A8cNIGxfQKUnjp3IRoo1EsRSM5w1xmUJ@xYjWnMYOLQNiLTDsCYaI7fWPZvqthFAQCnB5Oza0ccMErbXOccikVvNP5HCzxEzqfIwdYmYVu37T3jMZf "JavaScript (Node.js) – Try It Online") (with extra whitespace removed)
### How?
This is a rather straightforward algorithm that draws the output character by character in a matrix \$m[\:]\$, keeping track of the position \$(x,y)\$ of the pen, a direction in \$\{0,1,2\}\$ and the number \$k\$ of characters to draw before the next direction change.
We move according to the following table:
```
direction | moving towards | distance
-----------+----------------+----------
0 | South-East | 2t + 1 (t = turn number)
1 | West | 4t + 3
2 | North-East | 2t + 2
```
Which gives:
```
t = 0 t = 1 t = 2 t = 3
2
2 2.
2 2. 2..0
2 2. 2..0 2....0
2X 2.X0 2..X.0 2...X..0
1110 2....0 2......0 2........0
11111110 2........0 2..........0
111111111110 2............0
1111111111111110
```
In the JS implementation, we do not store the direction explicitly. Instead, we use a counter \$j\$ going from \$0\$ to \$+\infty\$ and use \$j\bmod 3\$ to figure out the current direction. We also do not store the turn number but compute \$n=2\cdot\lfloor j/3\rfloor\$, using the value of \$j\$ *before* it's incremented to account for the direction change (which means that \$n\$ is equal to \$2(t-1)\$ rather than \$2t\$ when the direction wraps to \$0\$).
Hence the following table:
```
j mod 3 | (j + 1) mod 3 | | new starting
(old direction) | (new direction) | new distance | value for k
-----------------+-----------------+---------------------+--------------
2 | 0 | (n + 2) + 1 = n + 3 | n + 2
0 | 1 | 2n + 3 | 2n + 2
1 | 2 | n + 2 | n + 1
```
And the corresponding expression to update \$k\$:
```
k = (n = j / 3 << 1) + (j++ % 3 || n + 2)
```
The coordinates are updated with:
```
j % 3 % 2 ? // if the direction is 1:
x-- // decrement x
: // else:
y += !!++x - j % 3 // increment y if the direction is 0
// or decrement y if it's 2
// increment x in both cases
```
[Answer]
# [R](https://www.r-project.org/), ~~205~~ ~~153~~ ~~147~~ ~~136~~ ~~132~~ 126 bytes
-52 from Dominic van Essen.
-4 from Giuseppe.
-4 again thanks to Giuseppe.
-5 further thanks to Dominic van Essen
```
function(s,n=nchar(s))for(y in(x=-n:n)*2)cat(ifelse((i=(t=y-2*(r=abs(x))*!r<y)*t-t-2*(r<y)*x+x+1)>n," ",substring(s,i,i)),"
")
```
[Try it online!](https://tio.run/##bU@7UsMwEOzzFRdRRHJsZkjJIGr@gFq2z7FAnOB0CjY/b2QGN4RuZ29fx4uwd3QOaJchUyc@kk41WepGxzoZM0TWM3jSk23onkx1Mp0T7QcMCbX2Voudm1Ol2bo26cmYas8Ps6mkkR96xdNxOt6ZR6oVqDrlNpVWOpciX3tjarVTZrkBioIgoxPYRsG2CUaXgFEyE1xcyL86n1YTEGKPfQ0pQpLI2Je9RVZC2pJxoBzCAUZk3K3QbulayYgf2XevLcdPGuL0kt/eU7wgl0NwX3Mfz7fK/HVdM@4fqr3mnjCECM@RQ78vH38D "R – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~270~~ ~~265~~ ~~252~~ ~~243~~ ~~232~~ ~~227~~ 225 bytes
*I finally managed to remove 2 more characters to bring the total to a number that can be represented in triangular form (as shown here). Code should be formatted conventionally to be run (as in the example on TIO); the '•' represents a newline (`\n`) character.*
```
f
unc
tion(
s,`~`=c
bind,m=ma
trix){n=nch
ar(s)+1;p=m(,
n^2,2);while(T<
n){a=4*F;p[T+0:a,
]=c(F:-F,(-F:F)[-1]
)~0:a-2*F;p[T+a+-2:a+
3,]=(F=F+1)~(b=2*F-1):-
b;T=T+2*a+4};m=m(" ",n,n)
;m[p[2:n-1,]+b+1]=el(strspl
it(s,''));apply(m,1,cat,"•")}
```
[Try it online!](https://tio.run/##NY/LboMwEEX3/gqLLrBjUxWaFaq3fAE7RBUDTnBrxtQ2eTRKfp06UrMb6Zy5utetwWkJB6PEul@gD9oC8Xx334m@0zDwSUwyKmd6BQH9KB3xlOVoFhPh8FnwgqLTqI0i9QfQqxTbTYXmpmZvpeSt6ElVZhUnWVVWtMnylt4jyIp/SbKsKCV7jyapRMVyeiediDTLaZl1qBY1KzaSbW8o9iAJTjhwoGhq5qYoIct5yzqWt0IZ4oPzs9Ehtk9TSpGcZ3MhE895LwNPUEJv6wsGGxQOowz4uRs/Z@NReuxUWBzgozTLv6f94wmDUoMaOPYW@2CdGrB@aDGkixkpLMakeFROoccpnukkCaP6WXT/3Tl7gr09fy3T7O1RuQiM/L0M9vCa0PUP "R – Try It Online")
Note that this approach has been comprehensively outgolfed by [att's approach](https://codegolf.stackexchange.com/questions/210454/spiralize-a-word-triangularly/210543#210543), although as consolation neither that nor any of the other current answers can be represented as a triangle...
Works by constructing the coordinates for each letter, then using this to put the letters into an empty matrix.
Commented:
```
triangle=
function(s){n=nchar(s) # n is the number of letters
s=el(strsplit(s,'')) # first split the string into individual letters
p=matrix(,2,n^2) # initialize p as a 2-row matrix to hold the coordinates
# (with plenty of columns so that we've enough to go all
# the way round the outermost triangle)
# now, F is the current loop, starting at 0
while(T<=n){ # T is the current letter index
a=4*F+1 # a=the size of the 'arch' (number of letters going up & over)
p[,T+1:a-1]= # set the coordinates for the arch letters...
rbind( # ...(rbind combines rows for y & x coordinates)...
c(F:-F,(-F:F)[-1]), # ...to y = F..-F, and then -F+1..F (so: up & then down again)
1:a-2*F-1) # ...and x = across the arch from -2*F to +2*F
a=a+2 # a=now the width of the base = size of arch + 2
p[,T+a+1:a-3]= # now set the coordinates of the base letters...
rbind( #
F+1, # ... base y = row F+1
(b=2*F+1):-b) # ... and x = goes (backwards) from 2*F+1..-2*F-1
T=T+2*a-2 # update the current letter index
F=F+1} # increment the loop
p=p[,1:n] # delete any excess coordinates
p=p-min(p)+1 # re-zero the coordinates to remove negatives
m=matrix(" ",b<-max(p),b) # create a new matrix filled with " "
m[t(p)]=s # and fill it with the letters at the right positions
n=apply(m,1,cat," # finally, print each row
")}
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-l`, 70 bytes
```
sMC:Y#ax:w:y/2-/2Ly*2L++i/2{I++v<ys@w@x:a@vi%4%3?++x&i%4=1?--w++w--x}s
```
[Try it online!](https://tio.run/##K8gs@P@/2NfZKlI5scKq3KpS30hX38inUsvIR1s7U9@o2lNbu8ymstih3KHCKtGhLFPVRNXYXlu7Qg3IsjW019Ut19Yu19WtqC3@//@/bs7/xKTklNS09IzMrOyc3Lz8gsKi4pLSsvKKyioA "Pip – Try It Online")
... I'm not sure I want to try explaining this monstrosity in detail. The basic idea is to construct an over-big 2D array of spaces (`sMC:#a`) and then put the characters from the input string into the array at the proper indices (`s@w@x:a@v`). The rest of the code figures out what the "proper indices" are.
---
Alternate approach, 77 bytes:
```
a.:sX#aW<|a{UpaWa^@YxNl?v+1++v%2?v*2+1vl:xNl?RV^p.:lv%2?lPEpl.^pAEx}RVsX,#l.l
```
[Try it online!](https://tio.run/##K8gs@P8/Uc@qOEI5MdymJrE6tCAxPDHOIbLCL8e@TNtQW7tM1ci@TMtI27AsxwokGBQWV6BnlQMSzglwLcjRiytwdK2oDQorjtBRztHL@f//v27O/8Sk5JTUtPSMzKzsnNy8/ILCouKS0rLyisoqAA)
Builds the triangle as a list of lines, alternating between adding lines to the front/end of the list and adding characters to the front/end of each line. I was hoping this way might be shorter, but so far it seems it's not.
[Answer]
# [J](http://jsoftware.com/), 60 bytes
```
4 :'x(<"1(#x)++/\(3|4|>.2*%:i.#x){<:3 3#:3 2 8)}y',~' '"0/,~
```
[Try it online!](https://tio.run/##ndJbT8IwFADg9/2K4zbTDUq3bqi4AAmgiIqoeMFbQhQ2Lk6GyIQJ7q/PKmQmMhKwD01z2n4956TdQAUDVE4F27SGHIVBp9UegtvntPmy6Yx6nMzxBJAFGQMQhp8rkCBQqJaLQRIMNJbSPJWEsRyPKw@SPk1Os0SLbRodwmKTtKGDLrBJg5T86SHsI0C8qmA/gEqeAKczwpsRXgTh/SUkTdBiLCxOiCp6iPufglgW32n42A@N9Yu5N2bFMGXBSPA0TRR5FQbmyjqGCnWK6xQoNtgUofx2ZJniLSphWyIauy4j@pooLDrghvs0niWKmyGr04j9RrPRdsACVDJt24GaM7CbG2gWRQk2UHji8anRNK1Wu9N9tl96Tv918DZ030dj7yOXL@ztFw9Kh0fH5ZPK6dl59eLy6rp2c3unUk1Pbm3vpHYjTYxy0W/l8sviBRR8AQ "J – Try It Online")
Obligatory J answer because it's Jonah's challenge.
Because "replace a certain position inside an array with a value" is not a verb but an adverb, it can't be used in a train as-is, so it is wrapped inside an explicit inline verb.
Uses [att's formula](https://codegolf.stackexchange.com/a/210464/78410) to construct the directions.
### How it works
```
NB. input: a string (character vector) of length n
,~' '"0/,~ NB. create a large enough canvas (blank matrix of size 2n*2n)
,~ NB. concatenate two copies of self
/ NB. outer product by...
' '"0 NB. a constant function that returns blank per character
,~ NB. concatenate two copies of self
4 :'...' NB. a dyadic explicit verb, where x is the input string and
NB. y is the canvas generated above
x(...)}y NB. replace some places of y by contents of x...
3|4|>.2*%:i.#x NB. formula by att (gives 0, 1, or 2 per index)
(...){ NB. select the directions based on the above...
<:3 3#:3 2 8 NB. the matrix (0 -1)(-1 1)(1 1) i.e. L/RU/RD
(#x)++/\ NB. take cumulative sum (giving coords to place each char)
NB. and add n to all elements
<"1 NB. enclose each row to satisfy the input format of }
```
[Answer]
# Scala, ~~322~~ 318 bytes
```
s=>((s zip Seq.unfold((0,0,0->0)){case(r,n,y->x)=>Option.when(n<s.size){val(c,t)=(math.sqrt(n).toInt%2,r+1-math.abs(x.sign))
(y->x,(t,n+1,(y+(c-1)*(1-t%2*2),x+1-c*2)))}}groupBy(_._2._1)toSeq)sortBy(_._1)map(_._2.sortBy(_._2._2)map(_._1)mkString)zipWithIndex)map{t=>" "*(math.sqrt(s.size).toInt-t._2)+t._1}mkString "\n"
```
[Try it in Scastie](https://scastie.scala-lang.org/7caCJTcPTcq8rywhD8dHcA) (doesn't work in TIO)
[Answer]
# [Perl 5](https://www.perl.org/), 163 bytes
```
sub f{ #newlines and indentation added here for readability.
$_=' 'x1e3;
@L=(51,$a=-1,-49)x($p=225);
for$c(pop=~/./g){
$P=$p+$L[1];
$a++>0&&s/^(.{$P}) /$1$c/s&&($p=$P,$a=0,shift@L)||substr$_,$p+=$L[0],1,$c
}
s/.{50}/$&\n/gr
}
```
In short, it adds the next char from the input in the current direction unless it discovers it's time to change direction.
[Try it online!](https://tio.run/##Xc3LToNAGEDhvU@BzR/KBMowVRaGjKn3tqLitd5qQylQFGGcoYpSfHWcroyuT/IdFvLUbhqxmCpRBRPaVtolCTecnks1mxjg0w4xOptbqNSA0W7XRk6Ucwg0ljP6jU0cowo8CkwH94GMHfB1fdtSVYGfNFOWGikYCARYqOpKAG9lWoaYJ1HRc9FyKdei4DAxpEElYo0N@Q1qgc3KtmoM6mOGY143a4wnWaFEWsufBrMwiufJ80v6muXsjYti8f5Rfn7t7O7tHxwe9QfDY/fk9Mw7v7i8ur4Z3d7dt5DzC/TDNM2VUc7T2fqf8F@WsfkB "Perl 5 – Try It Online")
] |
[Question]
[
We are all used to the old-school telephone keypad, right? For reference, here is what it looks like:
[](https://i.stack.imgur.com/MPi6I.png)
---
Given a String consisting only of **lowercase ASCII letters and single spaces**, your task is to return the number of taps one should make in order to type down the full String with a telephone keypad as the one above.
For those who are unfamiliar with this, here's how it works:
* The key with the digit `2`, for example, also has the string `abc` written down on it. In order to type `a`, you must press this key once, for `b` you must press twice and for `c` you must press thrice.
* For consecutive letters that are on the same key, you must wait 1 second before pressing again. So, if you want to type `cb`, you must press 3 times for `c`, wait a second and then press twice for `b`, so still 5 taps.
* The same applies for all other keys, except for a *single* space, which only requires 1 press. Also note that the keys `7` and `9` have four letters on them. The same algorithm is applied, the only difference being the number of letters. The strings corresponding to each key can be found in the image above (but lowercase), or in the following list, that contains all the characters you might receive:
```
"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz", " "
```
# Test Cases
```
Input -> Output (Explanation)
"" -> 0 (nothing should be tapped)
"water" -> 8 ("w,a,t" each require 1 tap (on keys 9, 2 and 8), "e" requires 2 taps (on key 3), "r" requires 3 taps (on key 7), 1+1+1+2+3 = 8)
"soap" -> 9 (4+3+1+1)
"candela" -> 13 (3+1+2+1+2+3+1)
"code golf" -> 20 (3+3+1+2+1(for the space)+1+3+3+3)
"king of the hill" -> 33 (2+3+2+1+1+3+3+1+1+2+2+1+2+3+3+3)
```
# Specs
* Standard I/O rules and Default Loopholes apply.
* You may only take input in your language's native String type. Output can either be an integer or a string representation of that integer.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer *in every language* wins.
[Answer]
# JavaScript (ES6) ~~77~~ ~~66~~ ~~64~~ 60 bytes
(Saved some bytes thanks to @Johan Karlsson and @Arnauld).
```
s=>[...s].map(l=>s=~~s+2+'behknquxcfilorvysz'.search(l)/8)|s
```
```
f=
s=>[...s].map(l=>s=~~s+2+'behknquxcfilorvysz'.search(l)/8)|s
console.log(f('')); //0
console.log(f('water')); //8
console.log(f('soap')); //9
console.log(f('candela')); //13
console.log(f('code golf')); //20
console.log(f('king of the hill')); //33
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~29~~ ~~26~~ 25 bytes
```
ð¢svA•22ā₂•S£ð«øðδKy.åƶOO
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8IZDi4rLHB81LDIyOtL4qKkJyAo@tBgovPrwjsMbzm3xrtQ7vPTYNn////@zM/PSFfLTFEoyUhUyMnNyAA "05AB1E – Try It Online")
**Explanation**
```
ð¢ # count spaces in input
sv # for each char y in input
A # push the lowercase alphabet
•22ā₂•S # push the base-10 digit list [3,3,3,3,3,4,3,4]
£ # split the alphabet into pieces of these sizes
ð« # append a space to each
ø # transpose
ðδK # deep remove spaces
y.å # check y for membership of each
ƶ # lift each by their index in the list
O # sum the list
O # sum the stack
```
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
Uses the same algorithm as [@RickHitchcock's Javascript solution](https://codegolf.stackexchange.com/a/128827/64121)
```
lambda x:sum('behknquxcfilorvysz'.find(c)/8+2for c in x)
```
[Try it online!](https://tio.run/##Jc1LDsIgFIXhuau4MyBWTToyTXQj6oDyEFLKRUq1tenaUXR0vjP6w5wM@jrr0zU73reSw9QMY09Jq0znH@MktHUYn/PwJnttvaSCHY7bWmMEAdbDxHJxUkMq90JIBeTFk4oFA/JQVnAvleM/olRwR6fL6ay/A2pIRoGxzpFbswEI0foEZFlhd4Zl/YYx9jzRqEKkpcQq0H@w/AE "Python 2 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~69~~ ~~67~~ ~~65~~ 64 bytes
1 byte thanks to Mr. Xcoder.
1 byte thanks to Felipe Nardi Batista.
```
lambda x:sum((ord(i)+~(i>"s"))%3+3*(i in"sz")+(i>" ")for i in x)
```
[Try it online!](https://tio.run/##VclNCsMgEEDhfU8xDBRm6tJdITlJNpbEOsRoUEt@Fr26rZtCl@9761FcDLrabqjeLI/RwH7Pr4UoppGE1Zukx4zMV630jQQkYD6RVXNAtjFBQ9i5rklCIUvN@fKrzZQp/cks4QnRQnETOPH@O@sH "Python 3 – Try It Online")
[Answer]
# Dyalog APL, 37 bytes
```
+/⌈9÷⍨'adgjmptw behknqux~cfilorvy~'⍳⍞
```
[Try it online!](https://tio.run/##RYs7DsIwEET7nMJdChRRc5yNfzFZvCY2hFCkJQW@AjU9BQfgJr6IEUiYqea90YDDRkyApBuO4L3hOS0XlVfrdF02r2eK9xqE3u5cGFkru97uD6eZK4M0HKe5TvGR4u3zyewbVVW/MkKQQyFP4ApwsEIiFG5BSzz/ZxKSaUJVTG@sZqRY6CTrDOIb)
**How?**
Get the `⍳`ndex of every char of the input in the string `'adgjmptw behknqux~cfilorvy~'` (`s` and `z` will default to 28), divide by 9, round up and sum.
[Answer]
## JavaScript (ES6), 71 bytes
```
f=
s=>[...s].map(c=>t+=((c=parseInt(0+c,36))>23?c+3:c&&~-c%3)%7%4+1,t=0)|t
```
```
<input oninput=o.textContent=f(this.value)><pre id=o>
```
Look no letter tables! I didn't quite understand @LeakyNun's formula so I came up with my own.
[Answer]
# C, ~~211~~ 196 bytes
First submission here...looks quite lengthy and I see that this is not an efficient approach, but at least it works :)
```
f(char*n){char*k=" abcdefghijklmnopqrstuvwxyz";int t[]={0,3,3,3,3,3,4,3,4};int l=0,s,j,i;while(*n){i=0;while(k[i]){if(k[i]==*n){s=0;for(j=0;s<i-t[j];s+=t[j++]);*n++;l+=(!i?1:i-s);}i++;}}return l;}
```
Ungolfed version:
```
int f(char *n){
char *k=" abcdefghijklmnopqrstuvwxyz";
int t[]={0,3,3,3,3,3,4,3,4};
int l=0,s,j,i;
while(*n){ // loop through input characters
i=0;
while(k[i]){
if(k[i]==*n){ // find matching char in k
s=0;
for(j=0;s<i-t[j];s+=t[j++]); // sum up the "key sizes" up to the key found
*n++;
l+=(!i?1:i-s); // key presses are i-s except for space (1)
}
i++;
}
}
return l;
}
```
[Answer]
# Haskell - ~~74~~ ~~71~~ 62 bytes
*Edit: removed 3 bytes by using a list comprehension instead of filter*
*Edit: Save 9 bytes thanks to Siracusa, Laikoni and Zgarb!*
```
f=sum.(>>= \x->1:[1|y<-"bcceffhiikllnooqrrsssuvvxyyzzz",y==x])
```
## Usage
```
λ> f "candela"
13
λ>
```
[Try it online!](https://tio.run/##ZckxDsIgFADQ3VP8EAdNbJOuRnoRdcAChfSXX6GtQLw77rK@Z0SYFGIpmodtbk99z@ERm7673rtvujXsNQxKa2PthOiI3t6HELZ9jynlnNklcR6f5zIL64CDpAPA4q1boQUNR2DsHz5iVb7SQGKpcBBOKhS1k1QwEupqJutGIA2rUWAsIis/)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes
```
Øaḟ⁾sz©;⁶s3Z®ṭċ@€€⁸×"J$ẎS
```
[Try it online!](https://tio.run/##y0rNyan8///wjMSHO@Y/atxXXHVopfWjxm3FxlGH1j3cufZIt8OjpjUg1Ljj8HQlL5WHu/qC////n5yYl5KakwgA "Jelly – Try It Online")
[Answer]
## Clojure, ~~82~~ 76 bytes
```
#(apply +(for[c %](+(count(filter #{c}"bcceffhiikllnooqrrsssuvvxyyzzz"))1)))
```
Oh it is simpler to just `filter` and `count` than use `frequencies`. Original:
```
#(apply +(count %)(for[c %](get(frequencies"bcceffhiikllnooqrrsssuvvxyyzzz")c 0)))
```
The string encodes how many times more than just once you need to press the key for a given character :)
[Answer]
# [Python 3](https://docs.python.org/3/), 91 bytes
```
lambda x:sum(j.find(i)+1for j in' !abc!def!ghi!jkl!mno!pqrs!tuv!wxyz'.split('!')for i in x)
```
[Try it online!](https://tio.run/##VYtBDsIgEADvvmK3FyAmTYw3E3/ihbZQllJAoLb181gvJh5nJhP3YoK/Vn1/VCfnbpCw3fIyc9tq8gMncb7okMACeQYoux4HpXE0hHZyOPuA8ZkyluWF67a/WZujo8IZMvH96PhgEzUm8oVr3kAjxOlHqywq/ZmJ/AhBQzEKDDl3xPoB "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 60 bytes
Probably sub-optimal, as this is my first golf ever in Python.
```
lambda x:sum((ord(i)-8)%3.15//1+3*(i>'y')+(i>' ')for i in x)
```
[Try it online!](https://tio.run/##VclBCsIwEIXhvaeYjSRj0VKCIIKexE00STOYZkIasT191I2Q1eP/XlqL56iqu9xq0NPdaFjO82uSkrORhPsTbtVhOPb90KmdpKtYBXa/BYGOMxBQhAVryhSLdFIIxM0/3rrY3MjMOjXw0NHYoFtjY2Hk4Bp9UhyBHRRvwVMI37N@AA "Python 3 – Try It Online")
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~46~~ 36 bytes
*Thanks to CalculatorFeline for saving 6 bytes.*
```
s|z
,c
[cfilorvy]
,b
[behknqux]
,,
.
```
[Try it online!](https://tio.run/##DcdBDoMgEAXQ/T8FGxMXpNfwEMTEEQchTpgWaWsb746@3StcU6bW9cPU9vMP6@F8SKLl8xthZ7iZ45Zf7@OexaM1fKlywa70hKe8sBC8LmxWlYAt5dVoMDWyiUnkAg "Retina – Try It Online")
[Answer]
## Java, ~~95~~ 73 bytes
```
a->a.chars().map(b->1+(b<64?0:b+(Math.abs(b-115)<4?4:5))%(3+b/112)).sum()
```
Thanks to Kevin Cruijssen for making the function a lambda expression (where `a` is of type `String`). 95 bytes became 73 bytes!
A lambda expression sums up the press count of each character using `map()`. `map()` converts each character (ASCII in lower case range is 97-122) in the stream to the appropriate value (looks like simple saw wave, but taking into account both 4 cycles is annoying) using this math: `1+(b<64?0:b+(Math.abs(b-115)<4?4:5))%(3+b/112)`. [Here's](https://www.desmos.com/calculator/86ii5wwvmg) a desmos graph of that model.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~100~~ 90 bytes
```
a:qb:["abc""def""ghi""jkl""mno""pqrs""tuv""wxyz"s]Fc,#a{Fd,#b{e:((bd)@?(ac))e<4?i+:e+1x}}i
```
Check each character of the input for a match in each element of b. The index of that match plus 1 gets added to the total.
[Try it online!](https://tio.run/##BcFLDoIwFAXQrTSXSRuYmDhqTHDEJgyDfh70SYUiqChh7fWcxClno2erbzDWAZ46oA8M3IcIPMYJSPNzAdbXG/hs3x@WtnFVYfbGV4XdSUtpvbrW0jil6HKuudRUnrbj4JwHHnsxdWINJALH@Ac "Pip – Try It Online")
[Answer]
# Mathematica, 83 bytes
```
c=Characters;Tr[Tr@Mod[c@"bc1def1ghi1jkl1mno1pqrstuv1wxyz "~Position~#,4]+1&/@c@#]&
```
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 94 bytes
```
[_l;||_SA,a,1|p=p-(instr(@sz`,B)>0)-(instr(@cfilorvy`+C,B)>0)-(instr(@behknqux`+C+D,B)>0)+1}?p
```
## Explanation
```
[ | FOR a = 1 TO
_l | the length of
; the input string (A$)
_SA,a,1| Take the a'th char of A$ and assign it to B$
p=p p is our tap-counter, and in each iteration it gets increased by the code below
which consist of this pattern:
instr(@xyz`,B)>0 where
- instr tests if arg 2 is in arg 1 (it either returns 0 or X where X is the index of a2 in a1)
- @...` defines the letters we want to test as arg1
- B is the current letter to count the taps for
Each of these blocks adds 1 tap to the counter, and each block has the letters of its level
(4-taps, 3-taps or 2-taps) and the level 'above' it.
-(instr(@sz`,B)>0) <-- letters that require 4 taps
-(instr(@cfilorvy`+C,B)>0) <-- 3 or 4 taps
-(instr(@behknqux`+C+D,B)>0) <-- 2, 3,or 4 taps
+1 <-- and always a 1-tap
} NEXT
?p PRINT the number of taps
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~69~~ 68 bytes
```
bc<<<`fold -1|tr "\n "adgjmptwbehknquxcfilorvysz +[1*9][2*8][3*8]44`
```
[Try it online!](https://tio.run/##S0oszvj/PynZxsYmIS0/J0VB17CmpEhBKSZPQSkxJT0rt6CkPCk1IzuvsLQiOS0zJ7@orLK4SkE72lDLMjbaSMsiNtoYSJiYJPz/n5yfkqqQnp@T9v8/AA "Bash – Try It Online")
Folds one char per line, transliterates each newline with `+`, each space with `1` and each letter with the corresponding number of pushes. bc does the sum.
[Answer]
## C, 92 88 bytes
```
c,n;f(char*s){n=0;while(c=*s++)n+=(c=='s')+3*(c>'y')+1+(c+1+(c<'s'))%3-(c<33);return n;}
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 36 bytes
```
{+/(3×⍵∊'sz'),1+3|¯1+⍵⍳⍨819⌶⎕A~'SZ'}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhGptfQ3jw9Mf9W591NGlXlylrqljqG1cc2i9oTZIrHfzo94VFoaWj3q2Peqb6linHhylXgvUqaCuzgUkyhNLUovArOL8xAIwIzkxLyU1JxHMTkpMT82pggjnp6QqpOfnpIF52Zl56Qr5aQolGakKGZk5OeoA "APL (Dyalog Classic) – Try It Online")
Finds the mod-3 indices in the alphabet without *S* and *Z*. Since space, *S*, and *Z* are not found, they "have" index 25 (one more than the max index), which is good for space. Then we just need to add 3 for each *S* or *Z*.
`{` anonymous function where the argument is represented by *⍵*:
`⎕A~'SZ'` the uppercase **A**lphabet, except for *S* and *Z*
`819⌶` lowercase
`⍵⍳⍨` the **ɩ**ndices of the argument in that
`¯1+` add negative one
`3|` mod-3
`1+` add one (this converts all 0-mods to 3)
`(`…`),` prepend:
`⍵∊'sz'` Boolean where the argument is either *s* or *z*
`3×` multiply by 3
`+/` sum
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 75 ~~77~~ bytes
```
n,b;f(char*a){for(n=0;b=*a++;)n+=b<'s'?--b%3+(b>31):""[b-'s'];a=n;}
```
The unprintable string `""` is a table of `04 01 02 03 01 02 03 04`.
[Try it online!](https://tio.run/##fYpBDoIwFESjsuIUTRNCC5Jg2FnRg6iL39ICEX9JwbggnB27ciVOZjGZ91RWK7UsuJfCMNWAS4BPxjqGZS5kmUCaCo5pKU/xEF@yTEZFyuS5OPAjDTbbnW9ArzLz9C6gRDEvLY7kCS0yHk4h8emdvwyjUXVDuveDci5@kzeM2q3jwUK/ThVgpTv4I9hKk9p2Zl15tFgTa8jYaNK0Xfc1nR5fDkkuwjlcPg "C (gcc) – Try It Online")
] |
[Question]
[
*A continuation of [Inverse Deltas of an Array](https://codegolf.stackexchange.com/questions/101057/inverse-deltas-of-an-array)*
Your task is to take an array of signed 32 bit integers, recompile it with its deltas reversed.
## Example
The List,
```
18 19 17 20 16
```
has the deltas:
```
1 -2 3 -4
```
which, when reversed, yields:
```
-4 3 -2 1
```
then when recompiled, using yields:
```
18 14 17 15 16
```
which should be your return value.
Recompiling consists of taking the `C`, which is the first value of the array. In this case, `18`, and applying the deltas to it in order.
So `18 + -4` gives `14`, `14 + 3` gives `17`, and so on.
## Input/Output
You will be given a list/array/table/tuple/stack/etc. of signed integers as input through any standard input method.
You must output the modified data once again in any acceptable form, following the above delta reversing method.
You will receive N inputs where `0 < N < 10` where each number falls within the range `-1000 < X < 1000`
## Test Cases
```
1 2 3 4 5 -> 1 2 3 4 5
18 19 17 20 16 -> 18 14 17 15 16
5 9 1 3 8 7 8 -> 5 6 5 10 12 4 8
6 5 4 1 2 3 -> 6 7 8 5 4 3
```
## Notes
* As stated in above, you will always receive at least 1 input, and no more than 9.
* The first and last number of your output, will **always** match that of the input.
* Only Standard Input Output is accepted
* Standard loopholes apply
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest byte-count wins!
* Have fun!
## And the winner is...
[Dennis!](https://codegolf.stackexchange.com/users/12012/dennis) Who firstly took the first place, then beat himself with a shorter solution, giving himself both the first and second place!
Honorable mention to [ais523](https://codegolf.stackexchange.com/users/62131/ais523) with their Jelly, that if not for Dennis getting in just before them, would have held the second place.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
I;ḢṚ+\
```
[Try it online!](https://tio.run/nexus/jelly#@@9p/XDHooc7Z2nH/D/c/qhpjfv//9GGOgpGOgrGOgomOgqmsToK0YYWOgqGlkBsDpQxANJmIFFTHQWQGFglUAFQzgIkbAbUBNYKNSYWAA "Jelly – TIO Nexus")
### How it works
```
I;ḢṚ+\ Main link. Argument: A (array)
I Increments; compute the deltas of A.
Ḣ Head; yield the first element of A.
; Concatenate the results to both sides.
Ṛ Reverse the resulting array.
+\ Compute the cumulative sum of the reversed array.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
.ịS_Ṛ
```
This uses the algorithm from [Glen O's Julia answer](https://codegolf.stackexchange.com/a/102162/12012).
[Try it online!](https://tio.run/nexus/jelly#@6/3cHd3cPzDnbP@H25/1LTG/f//aEMdBSMdBWMdBRMdBdNYHYVoQwsdBUNLIDYHyhgAaTOQqKmOAkgMrBKoAChnARI2A2oCa4UaEwsA "Jelly – TIO Nexus")
### How it works
```
.ịS_Ṛ Main link. Argument: A (array)
.ị At-index 0.5; retrieve the values at the nearest indices (0 and 1). Since
indexing is 1-based and modular, this gives the last and first element.
S Compute their sum.
Ṛ Yield A, reversed.
_ Subtract the result to the right from the result to the left.
```
[Answer]
# Julia, 24 bytes
```
!x=x[end]+x[]-reverse(x)
```
This is the "clever" way to solve the problem. The negative reverse of the array has the "deltas" reversed, and then you just need to fix the fact that it starts/ends at the wrong places.
[Answer]
## [Snowman](http://github.com/KeyboardFire/snowman-lang/) 1.0.2, 72 bytes
```
((}#0AaGwR#`wRaCaZ`0NdE`aN0AaG:dU,0aA|1aA,nS;aM`0wRaC|#0aA*|:#nA*#;aM*))
```
[Try it online!](https://tio.run/nexus/snowman#q@UytCgPSuAytASSic5AhjmUYWQAEzGDMrT@a2jUKhs4JrqXByknlAclOidGJRj4pbgmJPqBRK1SQnUMEh1rDBMddfKCrRN9EwxAimqUgYJaNVbKeY5aykBRLU3N/8olwcUB/wE "Snowman – TIO Nexus")
This is a subroutine that takes input from and outputs to the current permavar.
```
((
} enable variables b, e, and g
# store the input in variable b
0AaG remove the first element (take indices > 0)
wR wrap the array in another array
#`wRaC concatenate with the original input array
aZ zip (transpose); we now have pairs of elements
`0NdE obtain the number -1 (by decrementing 0)
`aN reverse the zipped array
0AaG remove first (there is one fewer delta than array elements)
: map over the array of pairs:
dU duplicate; we now have b=[x,y] e=[x,y]
,0aA move the copy and get the first element; b=x g=[x,y]
|1aA get the second element from the copy; b=y g=x
,nS subtract; we now have b=y-x which is returned from the map
;aM (map)
`0wRaC prepend a zero (in preparation for the next step)
|#0aA get the first element of the original array
* store this in the permavar
|: map over the array of deltas with 0 prepended:
# store the permavar in e
nA add the delta and the permavar
*# make this the new value of the permavar
;aM (map)
* "return" the resulting array from the subroutine
))
```
[Answer]
## JavaScript (ES6), ~~45~~ 37 bytes
```
a=>a.reverse(z=a[0]).map(e=>z+a[0]-e)
```
Port of @JHM's Mathematica answer. (I'm sure I could have derived it myself, but not at this time of night.) Edit: Saved 8 bytes thanks to @edc65.
[Answer]
# Mathematica, 23 bytes
```
#&@@#+Last@#-Reverse@#&
```
Unnamed function. The result is simply: reverse( (first element) + (last element) - (each element) ).
[Answer]
# Python 2, ~~96~~ ~~74~~ ~~54~~ 44 bytes
```
lambda l:[l[0]+l[-1]-j for j in l][::-1]
```
Input is given as an array surrounded by square brackets. Output is in the same format.
*Thanks to @Kade for saving ~~22~~ 42 bytes by using a much more simple method than whatever I was doing before!*
*Thanks to @Sherlock9 for saving 10 bytes by eliminating the index counter from the list comprehension!*
Great, now if I golf it anymore I'll get the "crossed out 44 is still 44" problem. ;\_;
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 8 bytes
```
¬s¤sR(++
```
[Try it online!](http://05ab1e.tryitonline.net/#code=wqxzwqRzUigrKw&input=WzE4LCAxOSwgMTcsIDIwLCAxNl0)
Translation of my MATL answer, second approach.
```
¬ % Implicit input. Head, without consuming the input
s % Swap
¤ % Tail, without consuming the input
s % Swap
R( % Reverse and negate
++ % Add head and tail of input to reversed and negated input. Implicitly display
```
[Answer]
## R, 37 30 bytes
Edit: Now using the approach in Glen O's Julia answer
```
x=scan();x[1]+tail(x,1)-rev(x)
```
Old:
```
x=scan();cumsum(c(x[1],rev(diff(x))))
```
Reads input, compute deltas, concatenate with first element and calculate the cumulative sum.
[Answer]
# [MATL](http://github.com/lmendo/MATL), 8 bytes
```
1)GdPhYs
```
[Try it online!](http://matl.tryitonline.net/#code=MSlHZFBoWXM&input=WzE4ICAxOSAgMTcgIDIwICAxNl0)
This is direct application of the definition. Consider input `[18 19 17 20 16]` as an example.
```
1) % Implicit input. Get its first entry
% STACK: 18
G % Push input again
% STACK: 18, [18 19 17 20 16]
d % Consecutive differences
% STACK: 18, [1 -2 3 -4]
P % Reverse
% STACK: 18, [-4 3 -2 1]
h % Concatenate
% STACK: [18 -4 3 -2 1]
Ys % Cumulative sum. Implicitly display
% STACK: [18 14 17 15 16]
```
---
Different approach, same byte count:
```
P_G5L)s+
```
[Try it onllne!](http://matl.tryitonline.net/#code=UF9HNUwpcys&input=WzE4ICAxOSAgMTcgIDIwICAxNl0)
Reversed and negated array plus the first and last entries of the original array.
```
P_ % Implicit inut. Reverse and negate
G % Push input again
5L)s % Sum of first and last entries
+ % Add to reversed and negated array. Implicitly display
```
[Answer]
# Japt, 8 bytes
```
Ô®nUÌ+Ug
```
[Run it online](https://ethproductions.github.io/japt/?v=1.4.6&code=1K5uVcwrVWc=&input=WzE4LCAxOSwgMTcsIDIwLCAxNl0KCi1R)
[Answer]
# Pyth - 10 bytes
```
sM._+hQ_.+
```
[Test Suite](http://pyth.herokuapp.com/?code=sM._%2BhQ_.%2B&test_suite=1&test_suite_input=1%2C+2%2C+3%2C+4%2C+5%0A18%2C++19%2C++17%2C++20%2C++16%0A5%2C+9%2C+1%2C+3%2C+8%2C+7%2C+8%0A6%2C+5%2C+4%2C+1%2C+2%2C+3&debug=0).
[Answer]
# [아희(Aheui)](http://esolangs.org/wiki/Aheui), 3 \* 21 chars + 2 "\n" = 65 bytes
```
빪쑥쌳텆슉폎귁삯씬희
뿓팤팧쎢싺솎
싺싹삭당뽔
```
Assumes input in stack 아. The output will be stored in stack 안.
**If you want to try this code:**
At the end of the first line of this code, add the character `벙` length(n)-times (i.e. if the input is 7 integers, insert it 7 times). For each prompt, type one integer:
```
어우
우어
빪쑥쌳텆슉폎귁삯씬희
뿓팤팧쎢싺솎
싺싹삭당뽔
```
[Try it here! (copy and paste the code)](http://jinoh.3owl.com/aheui/jsaheui_en.html)
**Example**
For `1, 2, 3, 4, 5`:
```
어우벙벙벙벙벙
우어
빪쑥쌳텆슉폎귁삯씬희
뿓팤팧쎢싺솎
싺싹삭당뽔
```
and then type `1`, `2`, `3`, `4`, and `5` (there will be 5 prompts).
**Alternative Version (65 bytes)**
```
빠쑥쌳터슉펴ㅇ삯씬희
뿌파파쎢싺솎
싺싹삭다뽀
```
[Answer]
## C# 42 bytes
Takes an `int[]` and returns an `IEnumerable<int>`.
```
a=>a.Select(v=>a[0]+a.Last()-v).Reverse();
```
(This is actually just a ported version of JHM's version..)
[Answer]
# TSQL, 200 bytes
Table variable used as input
```
DECLARE @ table(a int, b int identity)
INSERT @ values(5),(9),(1),(3),(8),(7),(8);
WITH c as(SELECT*,rank()over(order by b desc)z FROM @)SELECT g+isnull(sum(-f)over(order
by b),0)FROM(SELECT sum(iif(c.b=1,c.a,0))over()g,d.a-lead(d.a)over(order by d.b)f,c.b
FROM c,c d WHERE c.b=d.z)d
```
**[Try it out](https://data.stackexchange.com/stackoverflow/query/590898/reverse-deltas-of-an-array)**
[Answer]
# PHP, ~~60~~ ~~56~~ 52 bytes
-4 bytes thanks to @user59178
```
for($a=$argv;--$argc;)echo$a[1]+end($a)-$a[$argc],_;
```
operates on command line arguments, uses underscore as separator. Run with
`php -r '<code>' <space separated numbers>`
[Answer]
# [Perl 6](https://perl6.org), ~~48 33~~ 30 bytes
```
{[\+] .[0],|.reverse.rotor(2=>-1).map({[-] @_})}
```
```
{.reverse.map: {.[0]+.[*-1]-$^a}}
```
```
{[R,] .map: {.[0]+.[*-1]-$^a}}
```
[Try it](https://tio.run/nexus/perl6#dZBNboMwEIX3PsVbpA3/iRMgtDS0B@iq6g5SCYErIQFBMVSNIk7UW/RidHAgu1oay37zzfOMOynw5TtZyKoz7rNjLrAfLvGbdYBTpc0jLk68PphObNj8YC8@0r4fiHxphWyxR1nUQmr6hDKgWtEGLJ6KuunaaDzvoWFpL5@R5CZ0E3dIpKmoRBqUiZZ0gDHVie9GZK3Io3/rViFtmvn7Mz@iO6@FbK1JuxlcZdYz1tGQ79RwyJoyrWGq7kP2eTxNg9gRtESZWUhmA10NVEg7F6Ipzxg/R1PQ/OBMWlCy04hTyfqBY4MtXHhQi8xvCuMB@AP4Dps1uK9ypLijwj1SmAdKExxgRzECHnwKTvyGLAI23tzJ8mrvK3ZUt38 "Perl 6 – TIO Nexus")
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
[R,] # reduce the following using the comma operator [R]eversed
# (short way to do the same thing as 「reverse」)
.map: # map the input (implicit method call on 「$_」
{ # bare block lambda with placeholder parameter 「$a」
.[ 0 ] # the first value of 「$_」 (implicit “method” call)
+ .[ * - 1 ] # add the last value of 「$_」 (implicit “method” call)
- $^a # declare the parameter and subtract it from the above
}
}
```
The `*-1` is also a lambda expression of type WhateverCode, where the `*` is the only positional parameter.
[Answer]
# [Desmos](https://desmos.com/calculator), 34 bytes
```
f(l)=l[1]+l[k]-l[k...1]
k=l.length
```
Uses the trick from the [Mathematica answer](https://codegolf.stackexchange.com/questions/102139/reverse-deltas-of-an-array/102142#102142). Go check that answer out too!
[Try It On Desmos!](https://www.desmos.com/calculator/wodvmoq0df)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/jdkanjddtq)
[Answer]
# [Factor](https://factorcode.org/), 39 bytes
```
[| s | s first s last + s reverse n-v ]
```
[Try it online!](https://tio.run/##PYxLCsJAEET3c4rai8GJ@RkPIG7ciCtxMYQOBvJzegxIzNnHjhgLqqp5FF2awnXWX87H0yEH0@NJbUGMxrj7N4KB5gWj7gpTM3pLzr16W7UOe6VGBdEIjRBbRIgxLSSD3kGnCDfQyR/HECjTDKl4oYnw6PdkUpPy1zcYs8vKspOujdRKDksDWSa06wE335gegf8A "Factor – Try It Online")
A rare problem where local variables win out over stack shuffling. Note that `s` is the only variable; `n-v` is the name of a word that subtracts a vector from a number. Uses the same logic as JungHwan Min's [Mathematica answer](https://codegolf.stackexchange.com/a/102142/97916).
[Answer]
# [Julia 0.4](http://julialang.org/), 32 bytes
```
!x=[x[];x|>diff|>flipud]|>cumsum
```
[Try it online!](https://tio.run/nexus/julia#LYzBCoMwEETvfsUoCAorNG1NLaWh/5HmVBsIaCpaIYf8e7pKB5aBNzOb8nDXQZtbiKp31kZlBzetvYnqtY7LOib7mRHgPCotCEfCiXAmtIagRUcQV74LJwd2udGWsLG9yQXOug1LHu3T/xtTZ2A9ptn5r62KshFyQaNQLk9fEAIhD3X29n36AQ "Julia 0.4 – TIO Nexus")
[Answer]
# BASH, 71 bytes
```
s=$1
echo $s
for i in `seq ${#@} -1 2`;{
echo $[s=s+${!i}-${@:i-1:1}]
}
```
[Answer]
# C++14, 103 bytes
As unnamed lambda, requiring its input to have `rbegin`, `rend`, `back` and `push_back` like the containers `vector`, `deque` or `list`.
Using the approach from Glen O's [Julia answer](https://codegolf.stackexchange.com/a/102162/53667)
```
[](auto c){decltype(c)d;for(auto i=c.rbegin()-1;++i!=c.rend();)d.push_back(c[0]+c.back()-*i);return d;}
```
Ungolfed and usage:
```
#include<iostream>
#include<vector>
//declare generic function, return is deduced automatically
auto f=[](auto c){
//create fresh container of the same type as input
decltype(c)d;
//iterate through the reverse container
for(auto i=c.rbegin()-1;++i!=c.rend();)
//add the first and last element minus the negative reverse
d.push_back(c[0]+c.back()-*i);
return d;
}
;
int main(){
std::vector<int> a={18, 19, 17, 20, 16};
auto b = f(a);
for(auto&x:b)
std::cout << x << ", ";
std::cout<<"\n";
}
```
[Answer]
# Haskell, 33 bytes
Uses the same logic as JHM:
```
f a=map(head a+last a-)$reverse a
```
Quite readable as well.
[Answer]
# [Convex](http://github.com/GamrCorps/Convex), 10 [bytes](https://en.wikipedia.org/wiki/Windows-1252)
```
_î\(@¥+¡p;
```
[Try it online!](http://convex.tryitonline.net/#code=X8OuXChAwqUrwqFwOw&input=&args=WzE4IDE5IDE3IDIwIDE2XQ)
[Answer]
**Clojure, 101 bytes**
```
(fn[c](conj(map #(-(first c)%)(reductions +(reverse(map #(apply - %)(partition 2 1 c)))))(first c))))
```
Pretty much follows the description:
```
(def f (fn[c]
(conj
(->> c
(partition 2 1)
(map #(apply - %))
reverse
(reductions +)
(map #(-(first c)%)))
(first c))))
```
[Answer]
# Java 7, 96 bytes
```
int[]c(int[]a){int l=a.length,i=1,r[]=a.clone();for(;i<l;r[i]=r[i-1]+a[l-i]-a[l-++i]);return r;}
```
**Explanation:**
```
int[] c(int[] a){ // Method with integer-array parameter and integer-array return-type
int l=a.length, // Length of input array
i=1, // Index (starting at 1, although Java is 0-indexed)
r[]=a.clone(); // Copy of input array
for(; i<l; // Loop over the array
r[i] = // Replace the value at the current index in the copied array with:
r[i-1] // The previous value in this copied array
+ a[l - i] // plus the opposite value in the input array
- a[l - ++i]) // minus the value before the opposite value in the input array (and increase the index)
; // End the loop (implicit / no body)
return r; // Return the result array
} // End of method
```
**Test code:**
[Try it here.](https://tio.run/nexus/java-openjdk#rY5BTsMwEEX3OcUsbWVi1YW0QW4WHIBVl5EXJoRi5DqVMymqopw9DC3iAnTjL3lm3vtLG9wwwMuUAQzkyLfgIzW2FddwcuKEUDsVunigD/S1xtRY/mhDHzshzXufhPG7YFLjbc1PoW3umlB4W/xEnnsrTepoTBGSmTNWncbXwKpf47n3b3B0Poo9JR8PjQUW8xrA/jJQd1T9SOrEIwpRfLqzUyP5oJ5TcpdBUX87E62I3det/wS6Qv2EeovrFeoNzFJK818krvEBH7G8C61Erse8CrdY3YW4wZLbXVv@8eZsXpZv)
```
class M{
static int[]c(int[]a){int l=a.length,i=1,r[]=a.clone();for(;i<l;r[i]=r[i-1]+a[l-i]-a[l-++i]);return r;}
public static void main(String[] a){
System.out.println(java.util.Arrays.toString(c(new int[]{ 18,19,17,20,16 })));
System.out.println(java.util.Arrays.toString(c(new int[]{ 1,2,3,4,5 })));
System.out.println(java.util.Arrays.toString(c(new int[]{ 5,9,1,3,8,7,8 })));
System.out.println(java.util.Arrays.toString(c(new int[]{ 6,5,4,1,2,3 })));
}
}
```
**Output:**
```
[18, 14, 17, 15, 16]
[1, 2, 3, 4, 5]
[5, 6, 5, 10, 12, 4, 8]
[6, 7, 8, 5, 4, 3]
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function.
```
+\⊃,∘⌽2-⍨/⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///XzvmUVezzqOOGY969hrpPupdof@oa9H/tEdtEx719j3qm@rpD5Q/tN74UdtEIC84yBlIhnh4Bv9PUzBUMFIwVjBRMOUCsi0UDC0VDM0VjAwUDM2AAqYKQC5Q2kLBXMECyDcDiphAtAAA "APL (Dyalog Unicode) – Try It Online")
`+\` cumulative sum of
`⊃` the first element of the argument
`,` followed
`∘` by
`⌽` the reversal of
`2-⍨/` the pairwise difference of
`⊢` the argument
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
m`-§+←→¹↔
```
[Try it online!](https://tio.run/##ASkA1v9odXNr//9tYC3CpyvihpDihpLCueKGlP///1s1LDksMSwzLDgsNyw4XQ "Husk – Try It Online")
] |
[Question]
[
[Conways' Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) is a well known cellular automaton "played" on an infinite grid, filled with cells that are either alive or dead. Once given an initial state, the board evolves according to rules indefinitely. Those rules are:
* Any live cell with 2 or 3 living neighbours (the 8 cells immediately around it) lives to the next state
* Any dead cell with exactly 3 living neighbours becomes a living cell
* Any other cell becomes a dead cell
Let \$B\_i\$ be the board state at the \$i\$th step, beginning with \$B\_0\$ as the starting configuration, before any of the evolution rules are applied. We then define a "fixed board" to be a board state \$B\_i\$ such that there is a board state \$B\_j\$, with \$j > i\$, such that \$B\_i = B\_j\$ (that is, all cells in both boards are identical). In other words, if a board state is ever repeated during the evolution of the board, it is a fixed board.
Due to the nature of Game of Life, this definition means that a "fixed board" is either constant, or the only evolution is a fixed periodic set of states.
For example, the following board states are fixed, as \$B\_{217} = B\_{219}\$, where \$B\_{217}\$ is the left board:
[](https://i.stack.imgur.com/nRUxs.png)
The left board state happened to be the 217th generation of [this](https://i.stack.imgur.com/zYFYa.png) starting state, taken from [this challenge](https://codegolf.stackexchange.com/q/221353).
Note that the empty board is a fixed board, and that any patterns of infinite growth, or spaceship like patterns can never result in a fixed board.
---
This is an [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") challenge where each answer is a starting state, and the number of generations it takes to reach a fixed board must be strictly larger than the previous answer.
The \$n\$th answer should be a starting configuration of cells within an \$n \times n\$ bounding box such that, if the \$n-1\$th answer took \$p\_{n-1}\$ generations to reach a fixed board, the \$n\$th answer takes \$p\_n > p\_{n-1}\$ generations to reach a fixed board. Note that the "number of generations" is defined as the lowest \$i\$ such that \$B\_i\$ is a fixed board. For example, the empty board takes \$0\$ generations, as \$B\_0\$ is already a fixed board.
Each answer's score is \$i\$, the number of generations to a fixed board.
I have posted the starting answer, for \$n = 2\$, with \$p = 1\$, below.
### Rules
* You must wait an hour between posting two answers
* You may not post two answers in a row
* You can edit your answer at any point to change its score. However, keep in mind the following:
+ If your answer is the latest, people may be working on a follow-up answer, so changing yours may invalidate their attempt
+ If your answer is in the middle of the chain, you may edit it to any score, so long as it is within the bounds of the previous and later answers.
* The answer with the highest score (i.e. the latest) at any given point in time is the winner
[Answer]
# \$n = 12, p = 2215\$
Evolves to beehive + blinker + r-pentomino after 46 generations
```
.o.ooooooo..
....oo..o..o
.o.o...oo...
.ooooo...o..
o.....ooo...
....o..ooo..
..o..oo.o...
o.oo........
...o.o..oo.o
....oo....oo
..o.oo...o.o
..ooo.o...o.
```
RLE:
```
x = 12, y = 12, rule = B3/S23
bob7o$4b2o2bo2bo$bobo3b2o$b5o3bo$o5b3o$4bo2b3o$obo2b2obo2bo$2b2o$3bobo
2b2obo$4b2o4b2o$2bob2o3bobo$2b3obo3bo!
```
[Try it online!](http://copy.sh/life/?gist=84654e70c7d15e5d6486d355ef0d7534)
I wonder at what value of \$n\$ would engineered patterns appear. There are some cool engineered diehards at \$n=32\$ and \$n\approx96\$.
[Answer]
# \$n=7, p=456\$
I can't find a parent of [Bubbler's answer](https://codegolf.stackexchange.com/a/251520/9288). So instead, I found a grandparent of its child.
```
. . . . # . .
. # . . # . #
. # . # # . #
. . . # . # .
# . # . # # #
. # . . . . #
. . . . . . .
```
Or in RLE format:
```
x = 7, y = 7, rule = B3/S23
4bo$bo2bobo$bob2obo$3bobo$obob3o$bo4bo!
```
[Try it online!](http://copy.sh/life/?gist=47002f623958a6a7e0aacb4c92095977)
[Answer]
# \$n = 10, p = 1353\$
Search result from a simple script that runs for 1024 gens and then another 4 gens and checks that the bounding box is the same and population is different.
```
oo.....o..
.o.oo.o.o.
.oo.....o.
oo...o..oo
...o....oo
...ooo..o.
....o.o.o.
ooooo.o..o
..oo.ooo.o
ooo..o...o
```
RLE:
```
x = 10, y = 10, rule = B3/S23
2o5bo$bob2obobo$b2o5bo$2o3bo2b2o$3bo4b2o$3b3o2bo$4bobobo$5obo2bo$2b2ob
3obo$3o2bo3bo!
```
[Try it online!](http://copy.sh/life/?gist=3bb9adb72ceced2fd71c292819d7bd87)
Also, it looks like it has no 10x10 predecessors, but it's possible I didn't set the search for that properly.
[Answer]
# \$n = 2, p = 1\$
This has board states \$B\_0, B\_1, B\_2\$ left-to-right below. [This](https://copy.sh/life/?gist=088bf0abf78f15676b1c4fbacad299ec) is the preloaded pattern.
[](https://i.stack.imgur.com/tgeJw.png) [](https://i.stack.imgur.com/z4Of8.png) [](https://i.stack.imgur.com/z4Of8.png)
[Answer]
# \$n = 6, p = 455\$
Found by spamming the random button for two hours. Interestingly, the active pattern converges to [my own n=4 solution](https://codegolf.stackexchange.com/a/251513/78410). This makes me suspect that only very few actual long-lasting patterns exist which result in a valid answer for this challenge.
```
...##.
.##..#
#..#..
###.#.
#.#..#
...#..
```
```
#C Generated by copy.sh/life
x = 6, y = 6, rule = B3/S23
3b2o$b2o2bo$o2bo$3obo$obo2bo$3bo!
```
View it live on [copy.sh/life](http://copy.sh/life/?gist=5043fc17280d21a096876dba92413410).
[Answer]
# \$n=11, p=1697\$
I did some soup search this time.
```
. O . O O O O O O . .
O . O . . . O O . . .
. O . O O O . . O O .
O . . . . . O . . . .
. . O O . . . O . . O
. . . O . O . O . . O
. O . . . O O . . O O
O O O O . O . O . . .
O O O O O . O . . O .
O O . O . . O . . O O
. O . O . . . . . O O
```
Or in RLE format:
```
x = 11, y = 11, rule = B3/S23
bob6o$obo3b2o$bob3o2b2o$o5bo$2b2o3bo2bo$3bobobo2bo$bo3b2o2b2o$4obobo$
5obo2bo$2obo2bo2b2o$bobo5b2o!
```
[Try it online!](http://copy.sh/life/?gist=7321d4cce39edf7fd5f24730f7b43547)
[Answer]
## *n*=3, *p*=2
```
. . . . .
. # . . .
. . . # .
. . # # .
. . . . .
```
[Answer]
# \$n=13, p=2600\$
```
. O O . . O . O O . . O O
O . O O . O . . . O O . .
. . O . O . . . O O . . .
O . . . O . . O . . . O .
O . O . O O . . . O . O .
O . O O . . . O . O O O .
O O . . O . O O . O O O O
. . . O . O O O O . . . .
. . . O O . . O O . O . .
. . . O . . . . O . . O O
. . . . O . . . . O . . .
. . O . O O . . O . O O O
. O . O O . O . . O O O O
```
Or in RLE format:
```
x = 13, y = 13, rule = B3/S23
b2o2bob2o2b2o$ob2obo3b2o$2bobo3b2o$o3bo2bo3bo$obob2o3bobo$ob2o3bob3o$
2o2bob2ob4o$3bob4o$3b2o2b2obo$3bo4bo2b2o$4bo4bo$2bob2o2bob3o$bob2obo2b
4o!
```
[Try it online!](http://copy.sh/life/?gist=8b1ecfc1d888773bdb534bb1e226aa0f)
[Answer]
# \$n = 4, p = 431\$
```
.XXX
....
XX.X
.X.X
```
View it live on [copy.sh/life](http://copy.sh/life/?gist=4e0b4cf2dedfc36bfe65dec9248300d1).
[Answer]
# \$n=8,p=901\$
Another product of random search. The pattern this time is clearly different from the previous ones, and it *almost* fits in 7x7 board (the bottom left cell can be safely removed).
```
.#...#.#
.#.....#
.#..#.##
..#.....
.#....#.
.#..#.##
...#.#.#
#.....#.
```
```
#C Generated by copy.sh/life
x = 8, y = 8, rule = B3/S23
bo3bobo$bo5bo$bo2bob2o$2bo$bo4bo$bo2bob2o$3bobobo$o5bo!
```
View it live on [copy.sh/life](http://copy.sh/life/?gist=eaef8f644be354f9c83853f7f982b9e9).
[Answer]
# \$n=9, p=903\$
A grandparent of [Bubbler's answer](https://codegolf.stackexchange.com/a/251524/9288).
```
O . O . O O . O .
O O O . O . O O .
. O . O O . . . .
O . . . . O . . .
. . O . . . . . .
. . . . O O O . .
O O O . O . . O .
O . O O O . O . O
. O . O O . . . .
```
Or in RLE format:
```
x = 9, y = 9, rule = B3/S23
obob2obo$3obob2o$bob2o$o4bo$2bo$4b3o$3obo2bo$ob3obobo$bob2o!
```
[Try it online!](http://copy.sh/life/?gist=748a6df7ffb91a9295f8f6c6309335da)
All these parents and grandparents are found using my Mathematica package, [LifeFind](https://github.com/AlephAlpha/LifeFind). The code in the package isn't too complicated. [You can try it on TIO.](https://tio.run/##zVxrc9tGlv2uXwGTKZeU0Bbx4MuOs5JlO/GOkziWJjNVNFcFkbBEmwIYEnKkYTh/PXvP6Sf4kGXPzNamxhAJdN@@fd/nNjiXaXmRXableJj@@dWbq0kWPAlqT@P94yiuPd7Z@ensYvTT1eVZNpP73/5Re9qsBQ@@CxbNZWMnCGRkOFQ3wkaQNIK2/ItabfswUw@jRtBtBLH8CaOueRil6mEs0xpBT57Lnw7G9OQSdTGjm9jRep2WjJZ/UbsJgpaNSK8U4rYwEYJY2HbPx@p50sQzd/uDniYrxmAEnGBm1MM48NHqYjXHR65mtHG71TG3Y72ZMATX8qgpCyWhlUSs2W/3QA2DIl4s3VhvIIEAQCFs41PbiivWO@iIkITTCEJKEvf4vWZANh@LgDoUQgckoJMIlx6E04vsFL35HlajYMBY1HZM672Gsh5ItUGuh8XBWxxBQy186jo2ftNcCrkOBAk5hBBp1OLWobsulN1t2TkzvXXYENhukvcQF3zqkfc25jjWbjTvYCkmS7Qwu7nEKKSFPQszWLiJ/YFcEkE9LaGZdK0xJFpHcWRZS4xZddwoY0ktsAbqNMWeG2A00cT@qc92jAtMCvYdRRAHpB73rP4TowyMgiRCiirCBcKMY1xa0G7PSiHRCurI@E4HQqBlQF0w4JgbTHrYqhPMb4Y9sAJRR9BrElpbTow@hE6CPUB@IVwj4hy4RRJ2IUXHfmmoQiwwwJge0HJi@V3zCu@A6UQ9eEAvtgNuDAnsvsftYBMRtwP1Y@G4ha/dnp31DzMLVtwj3Q5G2O20tCV0YH9QWNLCfl1oaZkQBjGGcJwopo1YObcyYxkgDXOLSaNlmW8ZqwDbTQgugpScY7SsVUBFTaoV@4eZxy0KE@YPW0q6oZ2lrSKiOmP6Ng3a7c74aBOekNDQwAOZhLoSyDrhCl1rBC1jBIiXEQw1gn1FMS0Ta1FQIUzHeUNrZtaCQXAYdBUznrVpmthDixcnXqNXhi1KkOGjZ2XTtsET/omNxEqEuCBsJF16Kj658NW2aoMwYXIJ9pA4T2wbtdEeSQisJi70tLXa4jbtwt03cod6opg8Q6BwgrhHqZAadWyNoJ2bWdSn1VFnaO5jEkgmFJTz/o7hlK6IpZIuPjnv6Gr76hkej3Umtjnm2KZi2qCkXGi0E9nHJpbBR2DfDPuGhWOTjqHziImvESC4d5nNEKwQK5Jm004wu5KtdCGmDn3UsmNSMly3hSwAamHHPdeybzFMuttG9JCh8NLFLOTnkBEXXEf00a7jRMu9i9sdI7Jjk5NhcgicUQgriq1ATE7u0hnp2bgklq7JyXCeEBRCBK/QRo5jk5NhqExqkFPSds@108Mu4RU9igE@St0g58ZwvqTZtVNMRYJEHlI2jOxdx7axMlkQtLoMKNAauIuRQWMkw6Tp@NDuDjfqUZ7wcwg1ovNAfTFiUtIM7Rzt7Ah0iEohTCpEfAuhzYiVFkgkTceacXVUDCG0F0EncWy3Z9IynACRDH4QwWBj0EsQfxLkyMQmuWOblhPLm03LXTdKq4IlDKuwDgXrBpgADOMOqVJkhBDaD2nkSNUxxJ6E1gQSqw4MgyxC2joydARxxsiQcYfVnpWDycvwYdZLHRoHLjDimDtkyGk7ydiQzAQJEUOzSWzt2eRlBDIWhy2yDi0qn4bSmbmcCdu8DC8NYYMxvaDt5KLzMqssGg8CcNLs2QFWqbBDaDaCzOKY24HMsHCMXJ00bXSyeZmVJ6tSTE2adjsmL7OGgsYSJIiWCzA2L3dZd0IisLwksXK2eRl5L4a9xR0WLZZ5k5dZGDGdITa3nGvYvKziHtXKKIAL4kyCoJDQmGzWPbZ5meoEVzGyeRK63Zm8jNgQtmhp4IFMsniCrBOuYDPhsc3LLBEZhhPWzjRNpmQsw2Tn3MHmZVaLrHjpUoxpiDQJVcrc0nHiNXpF5IooQQSQJLSysXkZETRiHaZEiAsCRwsFRqvJT3YPNi/Tt1kMJEwB1uRsXqY9glACVlsu@Ni83KVduPtW7uCIpSBdq8uSlFIhNeYOawQ2L7foHFZHNi@3OJMs4OLc3@ZluiKWajVppJa2zsutMFz@8V0FMJ8ET2TIX7Kb42JWHvyYzc6zPuYEJ@nZJOsvak9rDSFQW/b79X6/NRgE3wShXL/9LjgpjsvZOD8/OJkdPMsmWZn167LqILh/QAry38u8zM6z2bPx@bic98ciDQk1A/AinxfyjyknXA4aQT24P6hw9uu/hzN5BmSfEL93l4N/F3s/rLQabGfBgeHQNh1ggIoBpCjVZEAWQXRFtYawRDAaKUAqOFLxqJApqgzifDYdNFBtu/5CBaNHhe1YdNixIDBOFOKHdxGHxQqLEVU3I9OKkFyv1mVnQOEuZp1eZFB0ixCX5BgfuhXcFl26DgfDqQbliCCwdyJhQifVuyASaGr8D9SuVaOQFaMyUZjqb0RscjgYbSAXMX7smJi6NoqD6oRecdPH6wqJtTrVboeD/IVrlzBeeSgdXkYUDE9TLQxmW4J3AqeekaUC8woVt4inCSzabL1UUL7CVc0K7osvvb4DDLml8S4xLNE7gQ4lrtoRLdOckfHajFSbht2mrgb4bAsQHynATHwVOZAVGaQlaUEbBfOTamz1dIeEOF71PZpNi4M7BtsrFKqhqKKiOhEEYszQrE9Yl/aathFAkcQVhBZPDZSo9h0idmzalQ5E7CB/4bUJaHy4UKNsGCSxhsJEdET7hN8KwdqtowVARGubCgStiUWuHQvbIosEuxUkmBjXaBv4q5stBnBqGBdrLMeGB@E3ujBads3IoHEaIyGqgnsEtsyMHQPTCacV@gs1AQ9VJlPbNfIbCoSFqjvhwWYqquNhZ03OgdFWpT1hwC7BpMLqzdji046G7gqkhkbICkpDqUnUNuiVaFmhYgJOizoV0CaWNmHDw6pt06jsVMHsOjB1MNRBptBhVBatoUabjIcKlBJ1hgr5wY6hcmi8Z30uNBgmZBBKDETVkCZyYLSC50z8ZqkXK4hLFNVUABESgACwfxilwmBhV2FXvTazA/fG7NBMNOwj5lKVPTtfRMvtpFLjmxjO0NpU@Ba@CFkzahI3UTYK7NKK2wovmvTRM1V40tQVu8LDbKwRV2rMZcvzhDW6ZWLqcLcDdhEF2fbRHav2iE7koWMHEAsHrwnnPEjHAEjIBFkryMtkQAwRhdbp2hr5EUGpepsYmsCSjUYHCVUN3q5gBBPDQRxOCZ9iRCbeIdSDlllPa/AaGjDfMr6vYX1EbG/QIHtRYcuAK2WktiCnybU0gNaaYYOR6JDRt9kymI91Sdi2mCk2OJBgoK1hixYJDVcV7SHBNWEVoawFjfzUq1TzNoZ3qhg1Ib6PKmi15eBh4UFKKIloJeoYcMmevUJGsUaGsQLXunLXMTxpMtzEBoCyAaaKhEQDO5b4Sa9rUUNSQQ02hncMVNLI3IATVfKzp9CKNThWUE3MVMsu7BrkppBF10ID4nNyFltIl1ikYBKoh0BsDIfYHPgkhCCS9SEWFRV7OEsHTQdcWhUoa4ARgUesAFvPYpnYwDwCmtgIWcEudUgSGaSTtDUUIzhJeg6hEJTRWUwS8HCNieHM3R7wWQMxP3w5ijFQIFgDDapsT0zZ3vtXoQOOLRW7jx7lM32G@TL/mE7GowDfHwZ/nWfzoAYEow455UMtGOfzMktHD2uPPRL9/FRzMAgePQnyyjMQO1WbwVNh@emkGH7oL6bpbJ5BbI3AfvzB@/wrPpdmQKkec8f6mwwoC1mlEczPlJY@TXNJ3VA7v6aTq@zHdNrXUsyDR0E9DP75z@BCPu3WHtSCP4JabQ935rhzOCmzWZ6W448imIODoB7tBQ8fPgweOb0dZ79dZfkwk8eeLqn2HAIcijqGDfcoCP52MR5e9OtR8ORJsFjK41pNrnN8rQkDfwgz@PigVpkVHBWX00l2meWlzG0ERxfpLB0Ke/ODuSj5ZHaVrYz3ByzFdgbBvmZxIcCxyb1qYL60U2sh73fU/doQdpvVvOcRn2vXqKV4rgfJZYzLB1xyf07MOa1b5rz3JsrlN1xmuNz4dJIvoVDi8rsvTCEqt/5REzc2d61AQsOq2@Ta5tV2DDMFiF3iMr2F4oaZMnj5WNvwqtFbgzfWu2KJdjNi1fN@Pdh/6On@12x2JiMv@6/TErMG/VMheCq@@F0wHdCA7ztbcA6kSWxxI7JK7@sv5kLwTP7lp0vt4WLW4/Kiv8hlrGYZzvH7uBRbz0U4H0VCXnNF7lxU7ship/73QYWdrST92EGKPven3teBUePTcfnzzInwVVF8uJr2T2YikWA3@h9sYM9q/L@Lcd6X6A1PrlNqgQpsR6nEyv6ZXqARvDzPi1mGu9AtvHHgLE4i/xYC89sIyH8U@vxMQrU/CwFWUz9Ky0zMQnLMcZnOyp/fqXGIYLu18xr@MkfYaCDq32OUk0d@vKidcfAZQiI@1PZpq/tz/pmvDp@bcbsYeOsqEjVX13oEos/zkWVXLHMhshB51qOl56prm5r7/FWpnv0HWVqK6g4kASysr3rhBOF74TKU2KV34wfa5XJpzGGDnqnkl@/60LNKCT9m83kqNcRazlZjAy/ZMlMPdF4UEv1@OFCWs/N9lmczCQRFPvczs/ZYWbBu1pN8UlcTdYnhWxtXpMkF60ambUzEtS5uT8TamsTGRKwvZsWlLlzOjVhOT089q6O5@ffusgRnfuT1gjM26rSyuDa1jTrZ@XlK0fVPCojY1TMS83/IrtPzIk8njOQv0gk8uObJm/cjiZn@5D5iC0KnpqzDc3/gNKKesE7pV@hJrfgkMPA6MBEpZIm2r8MLtBipO5XHNa/OtFXm9pVcWbrKkNu2GFztB@Q8Yey@Dqaq6PHLLLUUYuhAh1tVGiu78gqUv@ayyAHFI0Y2F58bM7ucni6hszHzZW59yEa9gR7tCuzliuZePR8E0Bi0QOOjvyjFvHreT2ez9Ob01XhebtVK7RqFshIw5dkIbuydUN8x9bSTdEVwXJ1HA7W3eY0Ss5pASng2lrpujtUPyJEho0a8Gb97N9GAYs0xzZhsOkmHmalsN97ccjfQ9EXbP6bXhgHEBPVx/6FAMmiApU6Tn85qy0q16Uaq5w9XilfRZbD/WApuodsybmgN4KgYoVr@Jmgngy3zxJsSv@xW/61T@eWqKMeokXPVLgsJtcKwirW2zf6xGFUmCj9AULWvtPLuedvalU2qmLanAhFzkwzFzXu0tbmaqx/rm/LHbnIGkHEdPKpkIkXBEMe1kGuF@drXuL/LkLeKUeyO3qS5@JpUpSyjBysJb72mXJt5iJl/rw32uEEn/F2TOkIEgIaLKXUJBtrpX2X5eXlxMNuvfL0e7FX0cC0CmkAGKtTvrArh3kZRqO3vfMFGxJYqDqLZmiC4dprQlrgnIghMA/FhtopkX6ejN@Pzi7LvO@LCsSjGL8jbsSnfTR8vSGWnX6KtszvMM1v01HQy64vP7J4UFRs/SIMHcIg9Me/VR2fyyHPBL193C@GlhaBKesfTybj8dBjTh7uG/gyVyK6uRF6N80zVfNcUeV2h9@OLYlZm8/Jg1bBUOYBZLAYRjeFI90zBsWd3n3@i3qA6d@/grf8WZ/0MX3WasDLN0rKfNrza5yAfqNjUEMqTgTH5w9ffQ19SbKbTc78/JF@H8gBNIG9cX9@uuohfWJpCdo344LED1idFmU4OpGB4mY@y62zUr4dfe7tHPywK7rsSFWkmFV01kG0EzS7VBQV7ikZHf7WC1Ww2djZCCliOZzJ9oezJHxPZC6qdctjfitnIt4iHleBow8OO4T3N59Ni7mVbYkqo8E32MQO0lfxf7ebV1YH9wEPpitjFLEtHB2aNg4qFrBcG1Se@r608Mk5XRyF1w12OTteT7apB1ZpiPYmEEc@sRgM2W1gDNJurRQCc4do8bNaYWv@BWpLLVelUd@/vgRqRmac1jXNMufd6UpSH@ei1DC1V4bejEXy1ICRX5tYhKhfMpF3tisFe2Jp@D5/MrR3riZM9CGq12j@8Kgv@RAQl6Aor/akqKsVki2kJc9pSbOpG6XmWm47H7aDgifiZXdhIex33bShGbZy7BQgoB7USYp9JKnNUZGOpyJpQ2i54fRCM9/b1p9B2T16MEbSwnKRI7HvZ2CD2AaMEhS6itRV@MSlmL67yIYYfDyUIibMavXi28Xx4UaByJb1n2VSyuZY1QlCkcDi@LtlTYztMbEd0IrWajT9QkYoueEaoIGttklpwnyZ3nKWz4YXWnkS0eVoiXP5UBPOr4YVZCeFybeTNpR9Y5etlVs5udPP9be0ofFvpua/MFxlP8TMjAJOfCnweF6Px0Kw4l0o8C/KiFD6mUwS0UfCumPkmQawyB2mji8oSm@ASwN4GxMtTEgZvwU/j4e1YGPBM71VFgKNQyb/2Wu@hZsC3DD08T2cVehJy83OxgdXlJf2NJLVA@6r4etiS0X/Ji9/zo2wymZsWrr5HY@S9b//Qvdraz@UFypR8NHbsgo3livD71@K@N5904ZU5MqWBQrnJ/2HqYBvd6RfRnt6Z9uj6SxcYXX/GCqOb7S0OHd9ggjmOcXK2vcWoBUJTkw0cmIwbwftGIJD841B0iD/Qvs7fH1UrKhULuVZ/hEeMG4oK5ZO6qgnBByh9qP/OFAGMFbdrBLwU0L6sns2vJqUKeKshV6N3ns8oEqrLHdimsU1zt3VMXC5cHeX50KDSEz@pfPsSEhUKg8Gewj/ML7dE/obt@YmWTCbyOmc7mw4hvabkxnzDoiaMCMilcBj4rNwtZdlO6b0q7zaCSHi@T4rfmV6ZKUA3hlFN0BhPH02n9/KvPB3oTX/aFAJJ82znsPtlFPS0KCZZmktUkRqv7O/uDvvaqAc44bu3isQRv/o4KgwZLHQmXaqjXEyTr7j5TRAt14qqn2eCbGXju3pVkzbZb@x/WG2pBC8mEEN@sErHcYGT@4ZeH4wID/yzXhGWOJZ@2395KaVZNh8Eu3RPWVRuPv/taixZLsvLwepEKw4ehO8JahGp7N4LPDHdv7/zxRKCSCCRqpxXFkVW@ekF3GXxocGDNHYgbZfxs3T4@fztVXa4qjoTIXfW1bb4tJ6glsYte18OPiHwf13cW4TtPE6i7waHWxH6jn/mV/FEW0ygZEMtYUqHo8jCDm9zFWuUB9dgC3UrurnqIweCQHIXAnLXo8GJz6IHn7n0ezvz7ds7LuoW@@MuMzbs71m0f5eZ3rS1jSbffMlGN4eEzTwmf/8ceWyjfNseul@i5W0LOcWcNrblHJT@g8f6bFi7A72BpUx/kcpUdZ6u76T@Y04LzKOm/yj138VRJQ472XVx3Gt0soUlfI1kJ7Y/bh8GqSpR8aZQLG7sEfbT4B0yoT1Mrwz06m5s@ym6BgrFNYLnH7P8lwMd61zEUrfrccPCPcvUTX8hYko9Od34crqpyOnGl9PNLXKqCCbS8oBgKuLbIqeb/29yUpW0ZkkBpKOLYjzM@osqax52ckRh69uHLc1PSprIBRogLHVUr8Tz/ccS@78VcpJoSinIpk7o1t10ZSl3ZFGrgZKYQxQA2PF@85Mbwy9UY25vYWNs2EDT4noTG9reK9smBB0M7KjNtN8b2u@F9s1W2jefTXursMTAlIL79tFAH8bcU4Cp7zJL9bteh9jIOor@yvcNl5URizIEM5H3ko@qCzYmaTJbr8uEEGHy78VsUCkH6uJkb4orKbN3y0iUWoZ7ouD96YCn1hue3eCZX8SU0WqA1sBQlrURFY1i2uWShYtU515lo9g3cNIfJxWMv3UqgKGadxWM1BrwGtW6MKmTxFC9IUikfM99O1WVCRjb2hTWdLwmVp2VneoEL@qKx4V8WJLgYrFYLm2ru9p5RjBbDyyqGSKW8oARDJWjV85HS95bsgeK03B24/LR47vBYYWujYFqQOS/CKBAQX1VfWzrGyZejGfz8kBmIUjP5pmqgxe3xEhVrZuXpNhX03WrQfg2QFlb4Fhi/s0FZ2W51c4QxXME2QwrCRzgMfAdxLUjFigfIlXg2Nc31kTqACwj2ZRaQoBVnR3U3RVDlvmwqV9WgbCOK42KucvgJg444YCja3xSJY0U7Oo@vG90g4@slzyfUyX1Pe3YeGN53bsa3ktMqotyd@x8LJB//m6cno0n41IUPy/TfOgOMLTbCaPawuQT9Cx/lArlA2XvoIv238rCtnfoJLOCpXSfyeWzhmozob1jgaGTy8YwMuBxV3lRjNjePD48sUn1ztv8v9rctg2YnLqyDdt3MfqtHu5taIZ7x3u3moHENidWdXilTrn8kyqrAe8UJrDW1u@jkv365usprfrxY/tFn@5j5gD9p90PpysUaLo4MQ0@QH1194b9TzgJZLfSe1/ciZYnIYtFM/jDQGNURPr0f4E8Lt906aEHrB2ojVUjDPXs@HRZOVQZL73AGLyeZdNMcqMnquDZrJjqQ5SqsIJXqYRRHOWJ4MXdFUdN9GYRUB6wlbvaHcDQG2/ojRp6w6EwGMwa3UCI@DFzyJBkKYQMC@tZDaWZrkW/USb3JptfpNNMFRAHVn@k68zTpSW9HnscA9OFiKqnfq/G77IXY0RHhB2@SdbffLLhTp9WTwqFniFj@9np7HzOQ@Y7ndipprTaUSM4Qy2TjSBF/8Hy7pHRP0Rf6EOYBbL/ovJGYb3fjwYVZa6c1NyhG71@WHPLkaA5hV96P0bZdGgA6XmpfftBYFVFtAT7PpGZv0FYjf/E2rr81doTvPhfh2Vx@QtrQXNzIagwXRnIOKBypfnkSubao5Na5f8U4Ea9M1i9eb2NoAWtn00R38SMUuXXtW/065rm/Ss7MK0ubRe8@2Y2ruIt4NhbWbq6a7x3ARdYyTb3nthcsnqsrv1NUXUHtzP94yVDeFONtPLqwCwbZZKS54Ja6KS@2WyLJs@vh1Kr@9UbTv4dpeqp//YQsmEKY6xM2krwk0SrjuFeMDU0BjrubnxiYkquUlT1iFYfycrq6vx05bD1cMpkJWUzypxSlRoIYxCZWcKX/dHhlld0jw69DUvs/2QsBhNXk3Sm34gAfHCHUgdbo0ik29zLpXtdQDU4ZFGf0@fXOFL//uUL79WSRe3ZeD6dCG678kNo82HLCzSyxS976YRvmwgLduX@u/EkO7WCvKNg1HTOXX2lY@PbF3d8c8N7D8PpquEqotvIiEi0kW0WYEVbayP0zMN8fMk7eCWp9M7vX@bvxrnU2uvaO56m4kwX46lSY/BJPdL@09HIvHwQrWzCKMcnvK6l6uk4fgRAILpda3iuflKFF/G@P3rW1zVYI7iSG3P/1j4ALuj5eg52/Dflzfv3rnex4/9U8eWlFPLegeCbopRJr7J3lVfGqHpdAldqTtTIthhVFNFGrONnjQ/gX/wzUC9CPGyzXlw/PsPkemPlaFdLXpWey2qts1D7X@6f46XTq2C3HvEFJIlaY04Yi7CW/mq@mU7vaKQDPfvL7FTP/bSlwlS1BZAZ71e65rUi/krXe3HHH65/maL//4DMazOf9dqOhFyfohd8b699/d/83eEFiH/17YcvfPVBlRDiD8OLvvmltv@jlNVT8XXw97qYj@25uv82rZ1r3iGT/ElYGqqmSQV0omRnWy8aDHyUt@6aK34RVTDbqhRE8fCvfTRzdh@Ee//D12b30Y6sruO9BqexVbzkscZOpRepfpIDHIlEqO1pgU6UqktPHUVB7MXvfdMN2GDDA/Xe3ODxn6/GH7PDV0Uu5SUA10p@l1AY6tjn4x@We33xgjJ4gYrOepV@gJf53ub8IYJ8pBIod77O/zY/PD56@VIkWapBldfN1S9f7IzqL1gC9auXn2tL@8M4Fdt@uRpn5YFfmFk9ueiSjhRiVUTZG9CthaK8kLVZa4gZnVxNGXoWutGnDlfwozzBIzs7O7tfB8ClQRqcA0xP01mWl0HxLhAqc6PM4Ou9nVXZmt8w1M6K@Kw4K746K1q8RvItKr6K@CXxb3Gc3MBA/ExFePjzz/8F "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# \$n = 14, p = 3185\$
Random soup battle continues.
```
. O . . O . . . O . O . O O
O O . . . O O . . . . . O .
. O O O . . O . . . O . . .
. O O O O O . . . O O O O O
. O O O . . O O . . O O . O
. O O O O . O O O O . . . .
O . . . O O O O O O . . O .
. O . . . O O O . O . O O .
O . . O . . . . . . . . . O
. . . . . O . . O . . . . O
. . O . . . . O O O . . O O
. . O O O . O O . . . . O O
. . . . . . . O . O . O . .
. . . O . . . O O O . . . .
```
RLE:
```
x = 14, y = 14, rule = B3/S23
bo2bo3bobob2o$2o3b2o5bo$b3o2bo3bo$b5o3b5o$b3o2b2o2b2obo$b4ob4o$o3b6o2b
o$bo3b3obob2o$o2bo9bo$5bo2bo4bo$2bo4b3o2b2o$2b3ob2o4b2o$7bobobo$3bo3b
3o!
```
[Try it online!](https://copy.sh/life/?gist=60ce7e2cee86d6f55b097688baac6364)
[Answer]
# \$n = 18, p = 5231\$
Just one more random soup. 18x18 is better, but still too tight for engineered designs I tried.
```
. . . O . O O . O O . . O . . O O O
O . O O O . . . O O O . . . . . . O
. . . . O . O . . O . . O . . . . .
. . O . O O O . . O . O . O O . . .
O O O O O . . O . O . O O . O O O O
. . . . O . O O . . . . . . . O . .
. O . . . . . . . O . . O O O O O O
O O . . . O . . . O O O . . . O . .
O . O . O O . . . O O . . . . . . O
. . . O . . O . O . . . O . . . O O
O . O O O O O O . O O . O . . . . .
O . . . . . . . . . O O O O O . . .
. O O O . . . O O . . . . . . O . .
. . O O . O . . O O . O O . . . O .
. . O O . . O O O O . . . O . . . .
. O . . O O . . . . O . . O . O O O
. . . O . . . O . . O O O . . O O O
. . O . . . O O . . O . O . . . . .
```
RLE:
```
x = 18, y = 18, rule = B3/S23
3bob2ob2o2bo2b3o$ob3o3b3o6bo$4bobo2bo2bo$2bob3o2bobob2o$5o2bobob2ob4o$
4bob2o7bo$bo7bo2b6o$2o3bo3b3o3bo$obob2o3b2o6bo$3bo2bobo3bo3b2o$ob6ob2o
bo$o9b5o$b3o3b2o6bo$2b2obo2b2ob2o3bo$2b2o2b4o3bo$bo2b2o4bo2bob3o$3bo3b
o2b3o2b3o$2bo3b2o2bobo!
```
[Try it online!](https://copy.sh/life/?gist=beb97f8e8e36d2ffa1067ad1d5201194)
[Answer]
# \$n=5,p=432\$
A [parent](https://conwaylife.com/wiki/Parent) of [Bubbler's answer](https://codegolf.stackexchange.com/a/251513/9288).
```
.XX..
.XX.X
XX.X.
.....
..XX.
```
Or in RLE format:
```
x = 5, y = 5, rule = B3/S23
b2o$b2obo$2obo2$2b2o!
```
[Try it online!](http://copy.sh/life/?gist=d5151a2e1d858e6f54198ac01d560bd7)
[Answer]
# \$n = 16, p = 3456\$
I've tried a few of engineered designs for that size, but they all were not as good as a random soup.
```
. . . O O . O . O . O O . O . .
. O . O O . . . . . . O O . O .
O O O O . . O O . . . . . O . .
. . O O . O O . . . . . . . . O
O O . . . . O . . O . O . . O .
O . . O . . O . O . O . O O . O
. O . . . O . . . . . . . . . O
O O . . . . . . O O O . . . O .
. . . . . O O O O . . O O . O O
O O O O O O . . . . . . O . O O
. . . O O . . . O . O O . . O O
O O O O O O O O . . . . . O . O
O . . . . . . . O . O . . . . .
. . . . . O . . . O . O . O . O
. . O . O . . O . O . O . . . .
O O . . O O . O . . O . . O . .
```
RLE:
```
x = 16, y = 16, rule = B3/S23
3b2obobob2obo$bob2o6b2obo$4o2b2o5bo$2b2ob2o8bo$2o4bo2bobo2bo$o2bo2bobo
bob2obo$bo3bo9bo$2o6b3o3bo$5b4o2b2ob2o$6o6bob2o$3b2o3bob2o2b2o$8o5bobo
$o7bobo$5bo3bobobobo$2bobo2bobobo$2o2b2obo2bo2bo!
```
[Try it online!](http://copy.sh/life/?gist=350f3bb99f08a0f346efc76fc1948737)
[Answer]
# \$n=17, p=3696\$
```
O . O O . O . . O . . . O O O . .
. . . O . . . . O O O . O . O O O
. . . . O . O . O . . O . O . . O
. . . . O . . O O . . . O . O O .
O O . O O . . . . O . . O . . O .
O O O . O . . O O . O O O . O O .
. O O . . O . . . O O O O . O . .
O O O O . . O . O O . O O . O . .
. . . . O O O . O O . . O O O O O
O O O . . . . . O O O O . . . . .
O O O O O O O . O . O O . O O . O
O . O . . O . . O O . . . . O . O
O . O O O O O . . O . . . O O O .
. O O . . O . O O . . . O . O . .
O O . . O O . . . . . O O O . . .
O . . . O . . . . . O . O O . . .
. O . . O . . . . O O . O O O . O
```
```
x = 17, y = 17, rule = B3/S23
ob2obo2bo3b3o$3bo4b3obob3o$4bobobo2bobo2bo$4bo2b2o3bob2o$2ob2o4bo2bo2b
o$3obo2b2ob3ob2o$b2o2bo3b4obo$4o2bob2ob2obo$4b3ob2o2b5o$3o5b4o$7obob2o
b2obo$obo2bo2b2o4bobo$ob5o2bo3b3o$b2o2bob2o3bobo$2o2b2o5b3o$o3bo5bob2o
$bo2bo4b2ob3obo!
```
[Try it online!](http://copy.sh/life/?gist=d6be2bceefb94afc1fda8b7ed24397e8)
[Answer]
# \$n = 20, p = 5627\$
I've tried random symmetric soups this time. Still can't fit engineered solutions into such small a space.
This pattern is a 2-generation predecessor of a (variant of a) symmetric pattern found by search.
```
. . O . . . O . . . . . . O . . O . O .
. . . . O O . . O O . O O O . . . . O .
. O O . O . O O O O . . . O . O . O . .
O . . . . . O . O . . O . O . O . . . O
O . O . O . . . . . O . . . . . O O . O
. . O . . . . O O . . O O . O . O . . .
O O . O . O . . . O . O O . O O . O . O
. O O . . O . . O O O O . . O . . O O O
. O O . . . . O . O . . . O . O . . . .
. O . . . O . . O O O . . O . . . O . .
. . . O O . O . O . . O . . O O O O . O
O . . O O . . . . O . . . . O . . . . .
. . . . . O O . . O . O . O O O . . . .
O . O . O O . . O O O . . . . . . O O .
. . . O . O . O O . O . O . . O . . . O
O . O O . . O . . O . . . . . O O . . O
O . . . O . . . O . . O . . O O . . . .
. . O . O . O . . . O O O O . O . O O O
. O . . . . O O O . O O . . O . . . . .
. O . O . . O . . . . . . O . O . O . O
```
RLE:
```
x = 20, y = 20, rule = B3/S23
2bo3bo6bo2bobo$4b2o2b2ob3o4bo$b2obob4o3bobobo$o5bobo2bobobo3bo$obobo5b
o5b2obo$2bo4b2o2b2obobo$2obobo3bob2ob2obobo$b2o2bo2b4o2bo2b3o$b2o4bobo
3bobo$bo3bo2b3o2bo3bo$3b2obobo2bo2b4obo$o2b2o4bo4bo$5b2o2bobob3o$obob
2o2b3o6b2o$3bobob2obobo2bo3bo$ob2o2bo2bo5b2o2bo$o3bo3bo2bo2b2o$2bobobo
3b4obob3o$bo4b3ob2o2bo$bobo2bo6bobobobo!
```
[Try it online!](https://copy.sh/life/?gist=2ef706f3e50176db0c86e7d0387fa698)
[Answer]
# \$n=15, p=3239\$
```
O . O O . . . . . . O O . . .
. O O . . . O . . O . . . . .
. O O . O . O O . . . . . O O
O O . O . . . . . O . . . O O
O . . . O . O O O . O . . O .
. . O O O O . O O O . . O . O
O O . O . O . O O O O . O O .
O O O O O O O . . . O . . . .
O . . O . O . O . . . O O O .
O O . . . . . O . . . . O . .
. . O O . O . . . O O . . . O
O O O . O O . O . . . O O O O
O . O O O . O . . O O . . O O
. . O . . O . . O O . O . O .
. O . . . O O O O . O . . . .
```
```
x = 15, y = 15, rule = B3/S23
ob2o6b2o$b2o3bo2bo$b2obob2o5b2o$2obo5bo3b2o$o3bob3obo2bo$2b4ob3o2bobo$
2obobob4ob2o$7o3bo$o2bobobo3b3o$2o5bo4bo$2b2obo3b2o3bo$3ob2obo3b4o$ob
3obo2b2o2b2o$2bo2bo2b2obobo$bo3b4obo!
```
[Try it online!](http://copy.sh/life/?gist=2fa783dab3ea80075d3ba985470ef769)
[Answer]
# \$n=19, p=5232\$
A grandparent of the child of [Pavgran's answer](https://codegolf.stackexchange.com/a/251770/9288).
```
. . . . . O . . . . . O O . O . . . .
O . O O . . . . . O . . . . . O O . O
. . . . O O . O O . . O O . O O . O .
O O . . . . . . . O . . . . O O . . .
. . . . . O O . . O O O . . O . . . O
O O O . O O . . . . . O . . . O . . .
. O . . O . O . O . . O . . . O . O .
. O . . O . . . O . . . . . O . . O .
O O . O O O . O O . O . O . O . . O O
. . O . O . . . O . O O O . . . O O .
O . . . . . . . O . O O O O . . . . O
O . O . . . O O . O . . O . . O . O .
. O . O O O . O . . . . . . O O O . .
. . O O . O O O . . O O . O . . O . O
O . . . . O . . O . . . . . . O O . .
. . . O . . O O O . . . O . . . O . .
O . O O O O . . . . O . . O O O O . O
. . . . . . . O O O O O . O . O . . .
O . . . O O . O O . . . . . . . . . O
```
```
x = 19, y = 19, rule = B3/S23
5bo5b2obo$ob2o5bo5b2obo$4b2ob2o2b2ob2obo$2o7bo4b2o$5b2o2b3o2bo3bo$3ob
2o5bo3bo$bo2bobobo2bo3bobo$bo2bo3bo5bo2bo$2ob3ob2obobobo2b2o$2bobo3bob
3o3b2o$o7bob4o4bo$obo3b2obo2bo2bobo$bob3obo6b3o$2b2ob3o2b2obo2bobo$o4b
o2bo6b2o$3bo2b3o3bo3bo$ob4o4bo2b4obo$7b5obobo$o3b2ob2o9bo!
```
[Try it online!](http://copy.sh/life/?gist=9fcada90ab855b93f6dea067e52c6047)
[Answer]
# \$n=21, p=5744\$
```
O . . . . . . . . . O . O . O . . . O . O
. . . . O . . . . . . . O . O O . . . . .
O . O . . . . . . O O . . . O O . O O . .
. . O . . . O O . . O . . . . O . . . . .
. . . . . . O . . . O . O . . . . . . O .
. O O O . . . . . . O . . . . . . . . . .
O O O . . . . . . O O . . O . . O O . . .
. . . . . . O O . . O . O O . . . O . . .
O O . . O . . O . . . O . . . . . . . . .
. . . . . . . . O O O O . . O . . . O . .
O . O O O O O O . O O O . O O O O O O . O
. . O . . . O . . O O O O . . . . . . . .
. . . . . . . . . O . . . O . . O . . O O
. . . O . . . O O . O . . O O . . . . . .
. . . O O . . O . . O O . . . . . . O O O
. . . . . . . . . . O . . . . . . O O O .
. O . . . . . . O . O . . . O . . . . . .
. . . . . O . . . . O . . O O . . . O . .
. . O O . O O . . . O O . . . . . . O . O
. . . . . O O . O . . . . . . . O . . . .
O . O . . . O . O . O . . . . . . . . . O
```
```
x = 21, y = 21, rule = B3/S23
o9bobobo3bobo$4bo7bob2o$obo6b2o3b2ob2o$2bo3b2o2bo4bo$6bo3bobo6bo$b3o6b
o$3o6b2o2bo2b2o$6b2o2bob2o3bo$2o2bo2bo3bo$8b4o2bo3bo$ob6ob3ob6obo$2bo
3bo2b4o$9bo3bo2bo2b2o$3bo3b2obo2b2o$3b2o2bo2b2o6b3o$10bo6b3o$bo6bobo3b
o$5bo4bo2b2o3bo$2b2ob2o3b2o6bobo$5b2obo7bo$obo3bobobo9bo!
```
[Try it online!](http://copy.sh/life/?gist=86e3787b51d4ac3b6e315008d4d9e31b)
] |
[Question]
[
# ~~Code~~Drawing one-liner
# Teaser
Behold this formidable drawing:

Can you draw this in a single stroke? Give it a try.
Can you do this one, now:

Give it a try.
# How it works
These "make this drawing with one pen stroke" problems are [graph-theory](/questions/tagged/graph-theory "show questions tagged 'graph-theory'") problems with a rather simple solution. For each vertex, compute its degree. If all vertices have an even degree or if only two vertices have an odd degree, this is possible. In any other case, it is impossible. This is the same as finding an [Eulerian path](https://en.wikipedia.org/wiki/Eulerian_path) in the graph. This is also related to the very famous [seven bridges of Königsberg](https://en.wikipedia.org/wiki/Seven_Bridges_of_K%C3%B6nigsberg) puzzle.
For the first drawing, the degrees are
```
2
/ \
4-----4
|\ /|
| 4 |
|/ \|
3-----3
```
so we are in the second possible case, as all numbers are even except for the two 3s in the bottom. What is more, when we have odd numbers, we have to start in one of them and finish in the other. When everything is even, we can start wherever we want but we will finish where we started.
For the second drawing it is impossible, as there are too many odd degrees:
```
2
/ \
5-----5
/|\ /|\
2 | 4 | 2
\|/ \|/
5-----5
\ /
2
```
# Task
Given the degrees of the edges as input, decide if a corresponding drawing could be done in a single pen stroke. Output Truthy if such a feat is possible and output Falsy otherwise.
# Input
The degrees of the vertices in any sensible format, such as
* an array of integers like `[2,4,4,4,3,3]` or `[2,5,5,2,4,2,5,5,2]`
* separate arguments to a function, like `f(2,4,4,4,3,3)` or `f(2,5,5,2,4,2,5,5,2)`
# Output
A Truthy value if all numbers are even or exactly two of them are odd, Falsy otherwise.
# Test cases
## Truthy
```
[2, 4, 4, 3, 3]
[2, 2]
[1, 2, 3, 4, 6, 8]
[2, 4, 2, 4, 2, 4, 2, 4]
[8, 6, 8, 2, 2, 3, 11]
[1, 3]
[8]
```
## Falsy
```
[1, 2, 3, 4, 5, 6]
[2, 3]
[9]
[7, 2, 2, 2]
[4, 2, 7]
[3, 3, 3, 3]
[1, 2, 3, 1, 1]
[1, 1, 4, 1, 1]
[7, 7, 7, 7, 7, 7, 7, 7]
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!
[Answer]
# [Python](https://docs.python.org/2/), 31 bytes
```
lambda l:sum(n%2for n in l)|2<3
```
[Try it online!](https://tio.run/##ZU9BCoMwELznFXMpKORitNVKfYn1kFKCQkxF40Ho39NkY8FSWHbJ7OxMZtps/zLCqebutBwfTwldL@uYmJNQrxkGg4FO3@KWOzuvtt/QoG0FR0GV@@o4AiDCzPwk1O8uHNW@Kwj@6WFTRRIB8SzLdhVSrbqOMSX1El2P4md/uosT9Rpa@VWiv0SjkjR8FBmixAw1A6Z5MBaSQyUyZYyeByK5/vHcBw "Python 2 – Try It Online")
We use `k|2<3` to check that `k` is either 0 or 2. This works because the bit operation `|2` sets the bit for place-value 2, so to get a result that's 2 or less, there must be no other bits set.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes
```
(a=Tr@Mod[#,2])==0||a==2&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277XyPRNqTIwTc/JVpZxyhW09bWoKYm0dbWSO1/QFFmXom@Q7q@QzVXtZGOggkYGQNRrQ5YwAhEGwJpsChQzkxHwQIqZwIWRiFBMhYQRWABiDZDQ6gpYFMt0I00BWqAGglWYAkizGH6wS6AGG8OYhpD3AdVCzcHyIDZYgg2FSYANAgLqq39/x8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5~~ 4 bytes
Thanks to 05AB1E's weird boolification system, any number but 1 is falsy.
-1 Thanks to Jonathan Allan
```
ÉO1α
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cKe/4bmN//9HG@kAYSwA "05AB1E – Try It Online")
# Explanation
```
É Vectorizing n % 2
O Sum the resulting list
1α |n - 1|
```
[Answer]
# [Turing Machine But Way Worse](https://github.com/MilkyWay90/Turing-Machine-But-Way-Worse), 1245 bytes
```
0 0 0 1 1 0 0
0 1 0 1 2 0 0
1 2 1 1 3 0 0
1 3 1 1 4 0 0
0 4 0 1 5 0 0
1 4 1 1 5 0 0
0 5 0 1 6 0 0
1 5 1 1 6 0 0
0 6 0 1 7 0 0
1 6 1 1 7 0 0
0 7 0 1 0 0 0
1 7 1 1 8 0 0
0 8 0 1 9 0 0
0 9 0 1 a 0 0
1 a 1 1 b 0 0
1 b 1 1 c 0 0
0 c 0 1 d 0 0
1 c 1 1 d 0 0
0 d 0 1 e 0 0
1 d 1 1 e 0 0
0 e 0 1 f 0 0
1 e 1 1 f 0 0
0 f 0 1 0 0 0
1 f 1 1 8 0 0
0 b 0 1 k 0 0
0 3 0 1 4 0 0
0 g 0 1 h 0 0
0 h 0 1 i 0 0
1 i 1 1 j 0 0
1 j 1 1 k 0 0
0 k 0 1 l 0 0
1 k 1 1 l 0 0
0 l 0 1 m 0 0
1 l 1 1 m 0 0
0 m 0 1 n 0 0
1 m 1 1 n 0 0
0 n 0 1 g 0 0
1 n 1 1 o 0 0
0 o 0 1 p 0 0
0 p 0 1 q 0 0
1 q 1 1 r 0 0
1 r 1 1 s 0 0
0 s 0 1 t 0 0
1 s 1 1 t 0 0
0 t 0 1 u 0 0
1 t 1 1 u 0 0
0 u 0 1 v 0 0
1 u 1 1 v 0 0
0 v 0 1 g 0 0
1 v 1 1 o 0 0
0 r 0 1 A 0 0
0 j 0 1 k 0 0
0 w 0 1 x 0 0
0 x 0 1 y 0 0
1 y 1 1 z 0 0
1 z 1 1 A 0 0
0 A 0 1 B 0 0
1 A 1 1 B 0 0
0 B 0 1 C 0 0
1 B 1 1 C 0 0
0 C 0 1 D 0 0
1 C 1 1 D 0 0
0 D 0 1 w 0 0
1 D 1 1 E 0 0
0 E 0 1 F 0 0
0 F 0 1 G 0 0
1 G 1 1 H 0 0
1 H 1 1 I 0 0
0 I 0 1 J 0 0
1 I 1 1 J 0 0
0 J 0 1 K 0 0
1 J 1 1 K 0 0
0 K 0 1 L 0 0
1 K 1 1 L 0 0
0 L 0 1 w 0 0
1 L 1 1 E 0 0
0 H 0 1 0 0 1
0 z 0 1 A 0 0
0 2 1 1 M 0 0
0 y 1 1 M 0 0
0 q 1 1 M 0 0
0 M 1 1 N 0 0
0 N 0 1 O 0 0
0 O 0 1 P 0 0
0 P 0 1 Q 0 0
0 Q 1 1 0 1 1
0 a 0 1 0 0 1
0 i 0 1 0 0 1
0 G 0 1 0 0 1
```
[Try it online!](https://tio.run/##VdRJTgJBAEbhvafgACxogQaXDDI7HYFRpkaBBoTLIzwemkovOi/fn7LSMaTJ4HA4n3OZ6xNdnsv7Icc7yjxS1/dV8laeKrgssCxqBayoFbFYK2KxFmMlLcZKWilzu8HNSlhZK2NP1hPVd9lnObAG1NDlkOVIG2IjbYSNtRE21sbYRBtjE20S3HMS3HOALaw8df9mn9TUmlIzT5lxytyaU/dTFiyX2gJbakss0ZZYoiXYSkuwlbbCPrUV9qV9Yd/WN7V2uWa5sTbU1uWWZaptsVRLsZ2WYjtth@21HbbX9sE998E9N1jFmgdf/kD9WD/U0VOOnHKyTtT9lArLqlbBqloVq2lVrKbVsLpWw@paHTtodexZe8YaVoNqumyybFktqu2yzbKjtbGO1sG6Wgfral2sp3WxntYL7tkL7tn6@5@PLnUKvvztd@LFOga1DuqFerVeOeXNeqPerXfqw/rwNyrir/eDu8yCav7X@VzOxtly9vHy5LNR9As "Turing Machine But Way Worse – Try It Online")
**Input:** A list like `n, n, n, n, ...`
**Output:** *(blank)* for falsy, `1` for truthy
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes
```
⁼¹↔⊖Σ﹪A²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO1sDQxp1jDUEfBMak4P6e0JFXDJTW5KDU3Na8kNUUjuDRXwzc/pTQnX8Mzr6C0RENTR8FIEwys//@PjrbQUTDTUQCSRmBkrKNgaBgb@1@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Port of @ovs' 05AB1E answer. Explanation:
```
A Input array
﹪ ² Vectorised modulo literal 2
Σ Sum
⊖ Decremented
↔ Absolute
⁼¹ Equals literal 1
```
There are other ways to check for `0` or `2` for the same byte count, such as `Not(Decremented(Absolute(Decremented(...))))`, `Equals(2, BitwiseOr(2, ...))`, or `Count("02", Cast(...))` (careful not to use `"20"` of course).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 18 bytes
```
M`[13579]\b
^[02]$
```
[Try it online!](https://tio.run/##VYtBCoNQDET3cw6FLmbRJOr/nsBVT6AWLXTRTRel9/8mIqUyBIbJe5/n9/VeS30ZlnJbRrE29fP0wH286lyVomw8RoNSIVTvDTtmxOfvkGP1FoSIo4b8E1p2Lhh6pB1RhJRg3HNwwvDE@WiJp2w "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
M`[13579]\b
```
Count the number of odd numbers.
```
^[02]$
```
Compare to `0` or `2`.
[Answer]
# JavaScript (ES6), 29 bytes
```
a=>a.map(x=>m>>=x&1,m=5)&&m&1
```
[Try it online!](https://tio.run/##bU7LCoMwELz3K3IKBlIhPmqkJD8iHoLV0mKM1FL8@zTZxKJQWHaXmd2ZeaqPWrrXY36fJ3Pr7SCsElKlWs3JKqSWUqyYUS1KgrHGzHZmWszYp6O5J02TUVRA5a5aijyQ@cncBNRxF4p45AqAD90zPBwBEN4YiyqgytsWEg2EXE/HBHuj0slEI3irfas2VcgVTCu/5iF1vP3puGXzZqC6AU7oT@2S2S8 "JavaScript (Node.js) – Try It Online")
### How?
We start with the bitmask \$m=101\_2=5\_{10}\$ and right-shift it by one position for each odd value in the input array. The final result is given by the parity of \$m\$.
[Answer]
# [Python 3](https://docs.python.org/3/), 34 bytes
```
lambda a:sum(n%2for n in a)in(0,2)
```
[Try it online!](https://tio.run/##ZU9BCoMwELznFXspJJBDE221gi@xHraUoKBRNB58fZpsLFgKyy6ZnZ3JzLvrJpt5Uz/9gOPrjYDVuo3cXrSZFrDQW0DRW36VWni3bK7boYam0RJyqixUKyECOk4VJqFhd5dQHruc4J8eN2UiEZDOlDpUSLVsW8YMDmtyPYvfwukhTtRHbMVXif6SjArSCGkwpkkZKgYwL711HCUYjkIwlt7ixCXjf6r/AA "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 5 bytes
-1 byte thanks to [a'\_'](https://codegolf.stackexchange.com/users/92069/a).
```
ÉO<ÄΘ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cKe/zeGWczP@/4@20FEw01EAkkZgZKyjYGgYCwA "05AB1E – Try It Online")
### Explanation
```
É is the number odd (vectorizes over the input list)
O sum (number of odd values)
< decrement (number of odd values - 1)
Ä absolute value (|number of odd values - 1|)
Θ equal to 1 (|number of odd values - 1| == 1)
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 28 bytes
```
dc<<<`grep -c [13579]$`d2-*p
```
[Try it online!](https://tio.run/##S0oszvj/PyXZxsYmIb0otUBBN1kh2tDY1NwyViUhxUhXq@D/fyMuEyA05jIGAA "Bash – Try It Online")
Input is on stdin: one number per line.
Output is on stdout: 0 is truthy, any non-zero value is falsy.
How it works:
* grep counts the number *n* of lines ending with an odd digit;
* dc then computes and prints *n*\*(*n*-2), which is 0 iff *n* equals 0 or 2.
[Answer]
# Excel, 50 bytes
```
=ISNUMBER(FIND(SUMPRODUCT(--(MOD(A:A,2)=1)),"02"))
```
`MOD(A:A,2)=1` to find odd number
`SUMPRODUCT()` to count them
`FIND( ,"02")` to check if `0` or `2`
`ISNUMBER()` to converts to TRUE/FALSE
Feels very clunky, hope to refine...
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), [73](http://null.link.io "Thanks to @MitchellSpector for the idea of using the size argument") 64 bytes
I don't know why I keep trying.
```
int f(int*a,int s){int o=1;for(;s;)o+=a[--s]%2;return o%2&&o<4;}
```
Commented :
```
int f(int*a,int s){ // function definition
int o=1; // odd counter starts at 1 because then parity of truthy inputs is one
for(;s;) // Use size arg as counter and iterate backwards (Thanks @MitchellSpector)
o+=a[--s]%2; // check for odd, add parity
return o%2&&o<4; // Valid values for odd are 0 and 2 (or rather 1 and 3)
// Solve with parity and range check
}
```
[TIO-k6qqj7ln](https://tio.run/##jZNdb4IwFIbv/RUnLipsGvmQj624y/2C3akXDVJHosXQcrEYf7srFCkwt5I0pTnn6en7npb4fF4c4vj2lNL4WOwTiNKM8TzBp/dRwVJ6AIpPCTvjOAHG9@iWUg7EEPMznpdrZl7KT7a2EclyAzFkZi9rvFks2G7ioDzhRU4hmzjTaRat0LUqcMIpNUy4jACWS/jMC/71DTFmCROREuDWZgdruDhzWFXDFeOK7lm7yToq6MigLYIVL3b5cwgV4LZr9meFrSQWyu1VVha0bQV5zWEtWX69U0Sksw98ZF1jxPqt0hMnNUWI8qYqk9rbq4rUZoK7PtUIUhuQxgIVrzW7spud@n5PlVgosyRosnYluJsNGyUPhmxFnBUcogjG9VW/wZaOUSsx2/JZ@SUGt0RDTBmjsz@YUqeOEUZ8HSOchjpG@A10jDdAj3hMdodp90U@lH/aQiy9HTKgLcTpy3jAlM9Sx5T/pI7xBtTx9ddNggFM2L/K0fX2Aw "C++ (gcc) – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 26 bytes
```
p=>(p.Count(n=>n%2>0)|2)<3
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXEh2ro5CUn59jp5Bm@7/A1k6jQM85vzSvRCPP1i5P1cjOQLPGSNPG@L81V3hRZkmqT2ZeqkaaRl5quQJYc7WRjoIJGBkDUa2mJh51RnikDYHSYDOAJpnpKFjgN8kErBqFxKPBAmIkWB3EEkNDIp1iCtSK3yn4/GyJR84c5hx8oQLxmzlIxX8A "C# (Visual C# Interactive Compiler) – Try It Online")
Thanks to answer of @xnor -1B
# 27 bytes
```
p=>(p.Count(n=>n%2>0)&-3)<1
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXEh2ro5CUn59jp5Bm@7/A1k6jQM85vzSvRCPP1i5P1cjOQFNN11jTxvC/NVd4UWZJqk9mXqpGmkZearkCWHe1kY6CCRgZA1GtpiYedUZ4pA2B0mAzgCaZ6ShY4DfJBKwahcSjwQJiJFgdxBJDQyKdYgrUit8p@PxsiUfOHOYcfKEC8Zs5SMV/AA "C# (Visual C# Interactive Compiler) – Try It Online")
This one was my first attempt, but I made mistake at first so I'm publishing it now when I fixed it.
[Answer]
# [Julia 1.0](http://julialang.org/), 15 bytes
```
~v=sum(v.%2)&-3
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/v67Mtrg0V6NMT9VIU03X@D@XQ3FGfrlCXbSRjoIJGBkDUSyysBGCZwjkgVUA1ZnpKFjEomlHJxHyFhANYGGIEYaGKOYi2WmB3UJToBEoFiJpsUQwzWF2ILkb4hxzhIAxxJ8oZsDtAjJQ3WYIth9VGGgNFhTL9R8A "Julia 1.0 – Try It Online")
A port of [Gymhgy's Japt answer](https://codegolf.stackexchange.com/a/199579/8774) (0 as Truthy, other numbers as Falsy).
**17 bytes** porting Arnauld's [JS solution](https://codegolf.stackexchange.com/a/199572/8774) :
`~v=5>>sum(v.%2)%2`
[Try it online!](https://tio.run/##yyrNyUw0rPj/v67M1tTOrrg0V6NMT9VIU9XoP5dDcUZ@uUJdtJGOggkYGQNRLLKwEYJnCOSBVQDVmekoWMSiaUcnEfIWEA1gYYgRhoYo5iLZaYHdQlOgESgWImmxRDDNYXYguRviHHOEgDHEnyhmwO0CMlDdZgi2H1UYaA0WFMv1HwA "Julia 1.0 – Try It Online")
And an obligatory port of the popular 05AB1E solution, at **19 bytes**:
`~v=abs(sum(v.%2)-1)`
[Try it online!](https://tio.run/##yyrNyUw0rPj/v67MNjGpWKO4NFejTE/VSFPXUPM/l0NxRn65Ql20kY6CCRgZA1EssrARgmcI5IFVANWZ6ShYxKJpRycR8hYQDWBhiBGGhijmItlpgd1CU6ARKBYiabFEMM1hdiC5G@Icc4SAMcSfKGbA7QIyUN1mCLYfVRhoDRYUy/UfAA "Julia 1.0 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
osq|1=
```
[Try it online!](https://tio.run/##y00syfmfkKlQEuWnYK9QoacQq/A/v7iwxtD2f4SLQkjs/2gjHQUTMDIGolguEN8ISBkCKbAYUMZMR8ECImMCFkUhgRIWECVgPkSToSHECJCBFmimmQJVQ0wDyVoCsTlMJ8hiiLHmQJYxxE0QdXATgAyo4YZg46B8oBlYUCyXgb4BAA "MATL – Try It Online")
I herd we're portin 05AB1E solutions!
A port of Arnauld's [JS solution](https://codegolf.stackexchange.com/a/199572/8774) while we're at it (8 bytes):
`osW5w/ko` [Try it online!](https://tio.run/##y00syfmfkKlQEuWnYK9QoacQq/A/vzjctFw/O/9/hItCSOz/aCMdBRMwMgaiWC4Q3whIGQIpsBhQxkxHwQIiYwIWRSGBEhYQJWA@RJOhIcQIkIEWaKaZAlVDTAPJWgKxOUwnyGKIseZAljHETRB1cBOADKjhhmDjoHygGVhQLJeBvgEA "MATL – Try It Online")
And one of [Gymhgy's Japt answer](https://codegolf.stackexchange.com/a/199579/8774) (6 bytes, 0 as Truthy, other numbers as Falsy):
`os3_Z&` [Try it online!](https://tio.run/##y00syfmfkKlQEuWnYK9QoacQq/A/v9g4Pkrtf4SLQkjs/2gjHQUTMDIGolguEN8ISBkCKbAYUMZMR8ECImMCFkUhgRIWECVgPkSToSHECJCBFmimmQJVQ0wDyVoCsTlMJ8hiiLHmQJYxxE0QdXATgAyo4YZg46B8oBlYUCyXgb4BAA "MATL – Try It Online") (though, `os2FZ:` is a more straightforward implementation of the idea in MATL [Try it online!](https://tio.run/##y00syfmfkKlQEuWnYK9QoacQq/A/v9jILcrqf4SLQkjs/2gjHQUTMDIGolguEN8ISBkCKbAYUMZMR8ECImMCFkUhgRIWECVgPkSToSHECJCBFmimmQJVQ0wDyVoCsTlMJ8hiiLHmQJYxxE0QdXATgAyo4YZg46B8oBlYUCyXgb4BAA "MATL – Try It Online"))
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), 13 bytes
```
÷⑷2%⑸⅀:0=$2=+
```
[Try it online!](https://tio.run/##y05N////8PZHE7cbqT6auONRa4OVga2Kka32///RhjoKRjoKxjoKJjoKpjoKZrEA "Keg – Try It Online")
Simply using everyone else's algorithm!
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-!`](https://codegolf.meta.stackexchange.com/a/14339/), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
èu a1 É
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=6HUgYTEgyQ&input=WzIsIDQsIDQsIDMsIDNd)
[Answer]
## [W](https://github.com/A-ee/w) `d`, ~~8~~ 7 bytes
```
♦æ╥└¬y÷
```
Uncompressed:
```
2mJ1-z1=
```
## Explanation
```
2m % Modulo the list by 2, auto-vectorizes.
J % Sum the list.
1- % Decrement by 1.
z % Absolute value.
1= % Is this 1?
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
This method is shorter in Stax.
```
ƒ╟⌡≡ù₧╬)
```
[Run and debug it](https://staxlang.xyz/#p=9fc7f5f0979ece29&i=[2,+4,+4,+3,+3]%0A[2,+2]%0A[1,+2,+3,+4,+6,+8]%0A[2,+4,+2,+4,+2,+4,+2,+4]%0A[8,+6,+8,+2,+2,+3,+11]%0A[1,+3]%0A[8]%0A[1,+2,+3,+4,+5,+6]%0A[2,+3]%0A[9]%0A[7,+2,+2,+2]%0A[4,+2,+7]&a=1&m=2)
# Explanation
```
{2%m Map modulo 2 over the input
|+ Sum the resulting list
02\ In the list [0, 2]:
# How many times does this number appear?
```
[Answer]
# [PHP](https://php.net/), ~~39~~ 43 bytes
```
for(;$n=$argv[++$i];)$s+=$n%2;echo!($s&-3);
```
[Try it online!](https://tio.run/##K8go@G9jX5BRoPA/Lb9Iw1olz1YlsSi9LFpbWyUz1lpTpVjbViVP1cg6NTkjX1FDpVhN11jT@v///4ZAaPzf9L/FfwsA "PHP – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-pa`, 20 bytes
```
$_=(2|grep$_%2,@F)<3
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lbDqCa9KLVAJV7VSMfBTdPG@P9/Ix0FEzAyBqJYLiDXKJbLEEiCRYDiZjoKFmBxE7AgChnLZQFRAOZCtBgagvUDzbJANcgUqBRsEFDKMpbLHKYHaB/EOPNYLmOIO8Bq4HqBDIiZhmBzIFygdiwo9l9@QUlmfl7xf92CxBwA "Perl 5 – Try It Online")
Borrows the `|2<3` trick from [@xnor's Python answer](https://codegolf.stackexchange.com/a/199548/72767)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-!`](https://codegolf.meta.stackexchange.com/a/14339/), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
èu &-3
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=6HUgJi0z&input=WzIsIDQsIDQsIDMsIDNdCg)
```
èu &-3 Full program taking in array of degrees U
èu Amount of odd numbers in array
& Bitwise AND
-3 With -3; -3 has very bit set except of the second bit (1111...11101)
-! Zero -> True, Other numbers -> False
```
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 11 bytes
```
{2%+}*(2?(!
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPkfbahgBISGCiZA0jj2f7WRqnatloaRvYbi//8A "GolfScript – Try It Online")
My first go at it, may shrink it a bit. I made it so 1 is true, 0 is false, but if you're okay with the other way around, I can do different things :)
Short explanation; Convert all the elements to mod 2 and sum them. The only valid answers would be 0 or 2. Now, subtract 1 and square them. 0 is -1 is 1. 2 is 1 is 1. 0 and 2 both give you 1. Lastly, subtract 1 and perform a not operation to make all non-0, non-2 values to a 0 and the 0-2s to a 1.
Kind of roundabout, and I'm sure I can cut two characters somewhere.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 bytesSBCS
```
0 2∊⍨1⊥2∘|
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///30DB6FFH16PeFYaPupYCmTNq/qc9apvwqLfvUd9UT/9HXc2H1hs/apsI5AUHOQPJEA/P4P@PeucqhBSVlmRUcqUdWqGgYaRgAoTGCsaaILYRkDRUMALyTRTMFCw0IfJIWBOiywIkC@SDVBoagjWBDNCx0OTiAtnglphTDLUAZpypghnYOLA6SyBhDtYPshFksjnUZGMFY6hrIBoNFSDGGwKNgLDNFVCgJgA "APL (Dyalog Unicode) – Try It Online")
Because a challenge needs an APL answer.
### How it works
```
0 2∊⍨1⊥2∘|
2∘| ⍝ Modulo 2
1⊥ ⍝ Sum
0 2∊⍨ ⍝ Is member of [0 2]?
```
[Answer]
# [Whitespace](https://github.com/Adriandmen/05AB1E/wiki/Commands), 102 bytes
```
[S S S N
_Push_0][S N
S _Dupe_0][N
S S N
_Create_Label_LOOP][S N
S _Dupe][S N
S _Dupe][T N
T T _Read_STDIN_as_integer][T T T _Retrieve][S N
S _Dupe_input][N
T T S N
_If_neg_Jump_to_Label_DONE][S S S T S N
_Push_2][T S T T _Modulo][T S S S _Add][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_DONE][S N
N
_Discard][S N
S _Dupe][N
T S T N
_If_0_Jump_to_Label_TRUTHY][S S S T S N
_Push_2][T S S T _Subtract][N
T S T N
_If_0_Jump_to_Label_TRUTHY][T N
S T _Print_as_integer][N
N
N
_Exit_program][N
S S T N
_Create_Label_TRUTHY][S S S T N
_Push_1][T N
S T _Print_as_integer]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
Since Whitespace inputs one integer at a time, the input should contain a trailing `-1` so it knows when to stop reading integers and the input is done.
Outputs `1`/`0` for truthy/falsey respectively.
[Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsMYQQnFycIgLhgUkEBSHIqgITAari4oDRYBVA5TAVIJwiDjACrgkiBBf7/t@Ay47LgMuYyAkJDQy5dQwA) (with raw spaces, tabs and new-lines only).
**Explanation in pseudo-code:**
```
Integer n = 0
Start LOOP:
Integer i = STDIN as input
If(i < 0):
Jump to Label DONE
n = n + (i modulo-2)
Go to next iteration of LOOP
Label DONE:
If(n == 0): Jump to Label TRUTHY
If(n-2 == 0): Jump to Label TRUTHY
Print 0 as integer to STDOUT
Exit program
Label TRUTHY:
Print 1 as integer to STDOUT
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 6 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
¥Σ(±1=
```
[Try it online.](https://tio.run/##y00syUjPz0n7///Q0nOLNQ5tNLT9/z/aSMcECI11jGO5gGwjIGmoYwTkm@iY6ViAxUx0kDBQxAIkA2SDVBkagjWANFsgaTXVMQNrBYlbArE5WDnIcJAh5kDaWMcYailEj6EOxCRDoG4I21wHBcYCAA)
**Explanation:**
```
¥ # Take modulo-2 on each integer of the (implicit) input-list
Σ # Sum those
( # Decrease it by 1
± # Take the absolute value
1= # And check whether this is equal to 1
# (after which the entire stack joined together is output implicitly)
```
[Answer]
# Java 8, 28 bytes
```
s->(s.map(i->i%2).sum()|2)<3
```
Port of [*@xnor*'s Python answer](https://codegolf.stackexchange.com/a/199548/52210)
[Try it online.](https://tio.run/##bZJRa4MwEMff@ymOwiChMaB21a1bYY97WF/6OPaQ2mzEaRQTC2XrZ3enlpLYESLe@bv8/7kzF0cR5IfvLiuEMfAmlP6ZAShtZfMpMgnbPgTYV1UhhYaM5FjBW6sKbmwjRclftd0Nb2DoGuHzDB/GCqsy2IKGZ@hMsCGGl6ImKtiou4hy05aE/kb0Ke7WPV@3@wL5S9mxUgco0QvBk5X@ev8AQUcjVhpLIrbEFbN4ELwmIzcMWYTEkq1Y6lNL5mz3U9qzmOzrwtA/y1NK/9O5Zytfxyt5cINkEPHc9mYSNxGzeHrBUSlkE2shik@SCfPWzViG/g4kDppzfu3u7mSsLHnVWl5j422hnXm/NI04GW6rcShE0MX8EeYLzbNbavw5kKEX9XP3Bw)
**Explanation:**
```
s-> // Method with IntStream parameter and boolean return-type
(s.map(i->i%2) // Take modulo-2 for each value in the IntStream
.sum() // And them sum those
|2) // Take a bitwise-OR with 2
<3 // And check whether that is smaller than 3
```
[Answer]
# [Chevron](https://esolangs.org/wiki/Chevron), ~~172~~ 147 bytes
```
^__>^n
>^n>^t
^t~s>>^s
0>>^o
0>>^i
^i+1>>^i
^t,^i~c>>^c
->+2??^c~^_i
->-3
^n^c>^n
^n~o>>^z
^o+^z>>^o
^__>^n
->+2?^i=^s
->-9
^o-2>>^p
^o*^p>>^o
>^o
```
Takes numbers from stdin in the form `2 4 4 3 3`.
Outputs `0` or `-0` for truthy, anything else falsy.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 6 bytes
```
∺∑⨪Ȧ1=
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%88%BA%E2%88%91%E2%A8%AA%C8%A61%3D&inputs=%5B8%2C%206%2C%208%2C%202%2C%202%2C%203%2C%2011%5D&header=&footer=)
Just another port of the 05ab1e answer.
[Answer]
# [R](https://www.r-project.org/), ~~30~~ 29 bytes
Or \*\*[R](https://www.r-project.org/)>=4.1, 22 bytes by replacing the word `function` with a `\`.
*Edit: -1 byte thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).*
```
function(v)sum(v%%2/2)%in%0:1
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jTLO4NFejTFXVSN9IUzUzT9XAyvB/mkayhpGOggkYGQORpiYXVMwIyjQEMsFyQBVmOgoWCBUmYBkUEippAVEKFoNoNjREGAezBGQUhhWmQK0IK2BKLaG0OcxImOsg9ppDecYQTyD0wU0GMpBcYAi2CkkMaC4WpKn5HwA "R – Try It Online")
Almost straightforward approach.
Less straightforward, but used by many other answers, approach results in the same byte-count:
```
function(v)(sum(v%%2)-1)^2==1
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jTFOjuDRXo0xV1UhT11AzzsjW1vB/mkayhpGOggkYGQORpiYXVMwIyjQEMsFyQBVmOgoWCBUmYBkUEippAVEKFoNoNjREGAezBGQUhhWmQK0IK2BKLaG0OcxImOsg9ppDecYQTyD0wU0GMpBcYAi2CkkMaC4WpKn5HwA "R – Try It Online")
] |
[Question]
[
## Challenge
Given nine numbers, `a, b, c, d, e, f, g, h, i`, as input which correspond to the square matrix:
$$\mathbf{M} = \begin{pmatrix}a& b& c\\ d& e& f\\ g& h& i\end{pmatrix}$$
Find the inverse of the matrix, \$\mathbf{M}^{-1}\$ and output its components.
## Inverse Matrix
The inverse of a matrix 3 by 3 obeys the following equation:
$$\mathbf{MM}^{-1} = \mathbf{M}^{-1}\mathbf{M} = \mathbf{I} = \begin{pmatrix}1&0&0\\0&1&0\\0&0&1\end{pmatrix}$$
And can be calculated as:
$$\mathbf{M}^{-1} = \frac{1}{\det(\mathbf{M})}\mathbf{C}^T$$
Where \$\mathbf{C}\$ is the matrix of cofactors:
$$\mathbf{C}=\begin{pmatrix}ei-fh&fg-di&dh-eg\\ch-bi&ai-cg&bg-ah\\bf-ce&cd-af&ae-bd\end{pmatrix}$$
And \$\mathbf{C}^T\$ is the transpose of \$\mathbf{C}\$:
$$\mathbf{C}^T = \begin{pmatrix}ei-fh&ch-bi&bf-ce\\fg-di&ai-cg&cd-af\\dh-eg&bg-ah&ae-bd\end{pmatrix}$$
And \$\det(\mathbf{M})\$ is the determinant of \$\mathbf{M}\$:
$$\det(\mathbf{M}) = a(ei-fh)-b(di-fg)+c(dh-eg)$$
## Worked Example
For example, let's say the input is `0, -3, -2, 1, -4, -2, -3, 4, 1`. This corresponds to the matrix:
$$\mathbf{M} = \begin{pmatrix}0&-3&-2\\1&-4&-2\\-3&4&1\end{pmatrix}$$
Firstly, let's calculate what's known as the determinant using the formula above:
$$\det(\mathbf{M}) = 0(-4\times1-(-2)\times4) - (-3)(1\times1-(-2)\times-3) + (-2)(1\times4-(-4)\times-3) = 1$$
Next let's calculate the matrix of cofactors:
$$\mathbf{C} = \begin{pmatrix}-4\times1-(-2)\times4& -(1\times1-(-2)\times-3)&1\times4-(-4)\times-3\\-(-3\times1-(-2)\times4)&0\times1-(-2)\times-3&-(0\times4-(-3)\times-3)\\-3\times-2-(-2)\times-4&-(0\times-2-(-2)\times1)&0\times-4-(-3)\times1\end{pmatrix}$$
$$= \begin{pmatrix}4&5&-8\\-5&-6&9\\-2&-2&3\end{pmatrix}$$
We then need to transpose \$\mathbf{C}\$ (flip the rows and columns) to get \$\mathbf{C}^T\$:
$$\mathbf{C}^T = \begin{pmatrix}4&-5&2\\5&-6&-2\\-8&9&3\end{pmatrix}$$
Finally, we can find the inverse as:
$$\mathbf{M}^{-1} = \frac{1}{\det(\mathbf{M})}\mathbf{C}^T = \frac{1}{1}\begin{pmatrix}4&-5&2\\5&-6&-2\\-8&9&3\end{pmatrix}=\begin{pmatrix}4&-5&2\\5&-6&-2\\-8&9&3\end{pmatrix}$$
So the output would be `4, -5, -2, 5, -6, -2, -8, 9, 3`.
## Rules
* The given matrix will always have an inverse (i.e. non-singular). The matrix may be self-inverse
* The given matrix will always be a 3 by 3 matrix with 9 integers
* The numbers in the input will always be integers in the range \$-1000 \leq n \leq 1000\$
* Non-integer components of the matrix may be given as a decimal or a fraction
## Examples
```
Input > Output
1, 0, 0, 0, 1, 0, 0, 0, 1 > 1, 0, 0, 0, 1, 0, 0, 0, 1
0, -3, -2, 1, -4, -2, -3, 4, 1 > 4, -5, -2, 5, -6, -2, -8, 9, 3
1, 2, 3, 3, 1, 2, 2, 1, 3 > -1/6, 1/2, -1/6, 5/6, 1/2, -7/6, -1/6, -1/2, 5/6
7, 9, 4, 2, 7, 9, 3, 4, 5 > -1/94, -29/94, 53/94, 17/94, 23/94, -55/94, -13/94, -1/94, 31/94
```
## Winning
The shortest code in bytes wins.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 54 bytes
```
th3LZ)t,3:q&XdpswP]w-lw/GtY*tXdsGXdsUw-IXy*2/+GtXds*-*
```
[Try it online!](https://tio.run/##y00syfn/vyTD2CdKs0TH2KpQLSKloLg8ILZcN6dc370kUqskIqXYHYhDy3U9Iyq1jPS13UFCWrpa/1UV3PKLFJLz88pS8zJT85JTuVQVog11FAyAyBpEGsIYIHYsSBbI0DUGYiNrkKSuCYQJEjKBKQGKG@koGFsrGIMNAEobgRnGYFlzHQVLoGKwIIgNVgbUaxr7n5DhAA "MATL – Try It Online")
Just to keep it interesting, doesn't use the inbuilt matrix division or determinant functions to do it.
Instead, computes the determinant using the [Rule of Sarrus](https://en.wikipedia.org/wiki/Rule_of_Sarrus).
[](https://i.stack.imgur.com/TkVi5.png)
And the adjugate (transposed cofactor matrix) using [Cayley–Hamilton formula](https://en.wikipedia.org/wiki/Adjugate_matrix#Cayley%E2%80%93Hamilton_formula).
$$ {\displaystyle \operatorname {adj} (\mathbf {A} )={\frac {1}{2}}\left((\operatorname {tr} \mathbf {A} )^{2}-\operatorname {tr} \mathbf {A} ^{2}\right)\mathbf {I} \_{3}-\mathbf {A} \operatorname {tr} \mathbf {A} +\mathbf {A} ^{2}.} $$
### Commented code:
```
% Finding determinant
th % concatenate the matrix to itself sideways
3LZ) % chop off the last column (since the Rule of Sarrus doesn't need it)
t % duplicate this matrix (say S)
, % do this twice:
3:q&Xd % get the first three diagonals of S
ps % multiply each diagonal's values and add the results
wP % switch and flip the matrix (to get the popposing diagonals next time)
]w % close loop, switch to have correct order of sums
- % subtract - we now have the determinant
lw/ % invert that
% Finding adjugate using Cayley–Hamilton formula
GtY* % A^2 term (last term of the formula)
tXds % trace(A^2) for term 1 of formula
GXdsU % (trace(A))^2 for term1 of formula
w- % (trace(A))^2 - trace(A^2)
IXy* % multiply that by the identity matrix
2/ % divide that by 2 - term 1 complete
+
GtXds* % A*trA for term 2 of formula
- % subtract to get adj(A)
* % multiply by the inverse of determinant we found earlier
% implicit output
```
We could go even ~~more insane~~ purer by replacing the matrix multiplication `GtY*` done for \$ A^2 \$, with something like `3:"Gt!@qYS*!s] 3$v t&v 3:K-&Xd` ([Try it on MATL Online](https://matl.io/?code=tY%2a+%27--%27+3%3A%22Gt%21%40qYS%2a%21s%5D+3%24v+t%26v+3%3AK-%26Xd&inputs=%5B0%2C+-3%2C+-2%3B+1%2C+-4%2C+-2%3B+-3%2C+4%2C+1%5D&version=20.9.1)).
The more direct and obvious way:
## 4 bytes
```
-1Y^
```
[Try it online!](https://tio.run/##y00syfn/X9cwMu6/qoJbfpFCcn5eWWpeZmpeciqXqkK0oY6CARBZg0hDGAPEjgXJAhm6xkBsZA2S1DWBMEFCJjAlQHEjHQVjawVjsAFAaSMwwxgsa66jYAlUDBYEscHKgHpNY/8TMhwA "MATL – Try It Online")
*(-1 byte thanks to @Luis Mendo.)*
`-1` - Push the literal -1
`Y^` - Raise input to that power (implicit input, implicit output)
[Answer]
**APL(Dyalog Classic),1 byte**
```
⌹
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhEc9O4EMBWMF40e9WwwVDMAQTgMA)
if a flat lis is required this is 8 bytes
```
,∘⌹3 3∘⍴
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbBJ1HHTMe9ew0VjAGMXq3AEUVDBUMwBBOAwA)
[Answer]
# **R, ~~51~~ ~~35~~ ~~27~~ ~~8~~ 5 bytes**
```
solve
```
[Try it online!](https://tio.run/##K/qfpmCj@784P6cs9X@aRm5iSVFmhUayhoGOrrGOrpGOoY6uCYgG8kx0DDV1jIEwRFPz////AA "R – Try It Online")
First go at doing one of these golf challenges. Sorry if my formatting is wrong!
Saved a total additional 11 bytes thanks to Giuseppe!
Saved an additional 19 bytes thanks to JAD!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
æ*-
```
[Try it online!](https://tio.run/##y0rNyan8///wMi3d////R0cb6igYAFGsjkI0kDZEMEG82FgA "Jelly – Try It Online")
Assuming we can take input and provide as a 2D list of integers. If a flat list of integers is really required for both input and output, then [this](https://tio.run/##y0rNyan8/7/Y@PAyLV23////RxvqKBjAEAo7FgA) works for 6 bytes.
[Answer]
# JavaScript (ES6), 123 bytes
*Saved 2 bytes thanks to @Mr.Xcoder*
*Saved 1 byte thanks to @ETHproductions*
Takes input as 9 distinct values.
```
(a,b,c,d,e,f,g,h,i)=>[x=e*i-h*f,c*h-b*i,b*f-c*e,y=f*g-d*i,a*i-c*g,d*c-a*f,z=d*h-g*e,g*b-a*h,a*e-d*b].map(v=>v/=a*x+b*y+c*z)
```
[Try it online!](https://tio.run/##ZYzLDoJADEX3fMUsmdJBUbbDjxgX8waDDBFDgJ/HQnBhXNyk9/S0DzWqwbya/i26aN3q5Zoq1GjQokOPAWtsuKxuk3TQiBo8GqiFhgY1eGHA4Sw9BGGJKDIMBLRghCJzkZbcQE4ATaQmw5Gp7/lT9ekoq/EkFUyZhjkzsPDVxG6IrcvbGFKfJoyxAhk779naNhU/bScJ58n/Ka3ElXLB45Eov23jrDxO1w8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 2 bytes
```
%.
```
Just a built-in primitive
[Try it online!](https://tio.run/##dYyxCoAgAAV3v@IIQ4ISzSIK@haHSKKloblvNyWIlnjD8eC4PYZz1hgmTCx1rEShUWHWipprIpxCrMt2EHA4afAO32LxXWZ6HfYxVEOa@uhIm8p5L/9UOTCmVEtmjvYi3g "J – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 139 bytes
```
def F(a,b,c,d,e,f,g,h,i):x=e*i-f*h;y=f*g-d*i;z=d*h-e*g;print[j/(a*x+b*y+c*z)for j in x,c*h-b*i,b*f-c*e,y,a*i-c*g,c*d-a*f,z,b*g-a*h,a*e-b*d]
```
[Try it online!](https://tio.run/##bZBNboMwEIX3nGJ22JMhrRopUonYdpcTIKSAscFR@JEhFeTydCChjZSuPJ438/z8tWNfNvXHNOXawJdIKSNFOWkyVFBJVoZDpNEGBsvDGBksghzt4RblWAYai4PT/dXV8flNpDhsMhw3Cm/SNA7OYGsYSPFghpYyNIFCTSOlbKewYCUPUjR0Y63gqmRF82yeTJ5xTQXdWLUj2KptXD9fsubSEahOE3TcvVgzPg1uq7R3Vulu3TjO98HzXv4E0eom/BfRl553tPU3D/2HY9Xi@Yzfw11CsJS7cL@W@/AzSTyvdbbuwb8v@ASneyAxN@S2u2YdMxMPuJLZiZnthhlLhigehCWBn@vel6e74a8tIPxZrzzE4404XqInFC/h@VziJ4mc155ysO30Aw "Python 2 – Try It Online") (Has `return` instead of `print` for ease of testing.)
[Answer]
# Python 3, 77 bytes
```
import numpy
lambda l:(numpy.matrix(l).reshape(-1,3)**-1).ravel().tolist()[0]
```
Takes input as a flat list.
It's 63 bytes if input is taken as a 2D array:
```
import numpy
lambda l:(numpy.matrix(l)**-1).ravel().tolist()[0]
```
[Answer]
# [Google Sheets](https://sheets.google.com), 16 bytes
```
=MINVERSE(A1:C3)
```
Input is in the range `A1:C3`
Built-ins are boring
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 143 bytes
```
import StdEnv
$a b c d e f g h i#p=e*i-h*f
#q=f*g-d*i
#r=d*h-g*e
=[v/(a*p+b*q+c*r)\\v<-[p,c*h-b*i,b*f-c*e,q,a*i-c*g,d*c-a*f,r,g*b-a*h,a*e-d*b]]
```
[Try it online!](https://tio.run/##NU45DsIwEOzzipVCAYvNXeIOCiQ6SqBYr49YSkISQiQ@jzEgmtFcGg2XlupY3cyjtFBRqGOomlvXw6k3@3rIRgQaGAxYcOChgJA3ymKQBbosb5VDLw2GLO@UwUJ6tJk6D/MxYTPV2E4Zu8nlMmzluRGcChqD0OgkoxWtoDTE6IVBloROdMKjTqxIiU27@nqNp57SHQUjWMwWINcfWCVYfsjmr77@5mfHF7uS/D3KwzHunjVVge9v "Clean – Try It Online")
[Answer]
# Perl 5, 179 bytes
```
sub{($a,$b,$c,$d,$e,$f,$g,$h,$i)=@_;map$_/($a*$x+$b*$y+$c*$z),$x=$e*$i-$f*$h,$c*$h-$b*$i,$b*$f-$c*$e,$y=$f*$g-$d*$i,$a*$i-$c*$g,$c*$d-$a*$f,$z=$d*$h-$e*$g,$b*$g-$a*$h,$a*$e-$b*$d}
```
[Try it online](https://tio.run/##dY3hSsNAEIT/@xT5MWBz3dPUNEgJJ76Az1AuzSW9ok3oKTQVX924t4c/BAt7yzD7zdzoTq/VjGDm8NF8LmAJDWFHaAmO0BF6wp7gc/O8rd/siO09UwrnJRqFaYmdwiUnnA2cgtfoVOTZ3etIeIq709HhwslEoNdo5WQlwqdeIq2ODn96MRHgBienRiJWmnk7aW6/5vom2Ck7DP6Y3VIcBP20WFFW/M4fnf/P80mX/B4E1@sko7W@HmKSoVIm6RQvr/CPlG2kkLGkU3@V1/P3ML774Rhm/VLdFaviBw "Perl 5 – Try It Online").
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 6 bytes
```
m->1/m
```
Takes multiplicative inverse in the matrix ring \$\mathrm{M}\_n\$.
[Try it online!](https://tio.run/##NYvNCoMwEIRfZfBkIEtNokgJ@iKSgxdFaMoivfTp425aYX@@nZnl9Txo57JhQsk0u0cuK/Pr22bQDD6P90ew0aPB1mZjLJbFWXRSUae7QTmJK5uCtI/qUf9Dlfp/QmRvESJCfRfXVwhqjhZPiVZNuabkc0jJlAs "Pari/GP – Try It Online")
[Answer]
# APL (Dyalog), 7 bytes
```
,⌹3 3⍴⎕
```
Takes input as a flat list and outputs as a flat list
[**Try it online!**](https://tio.run/##SyzI0U2pTMzJT///qKNdofi/zqOencYKxo96tzzqmwoS@1/MZaBwaL0xEBspGAJJEzALJGICAA)
[Answer]
# [Factor](https://factorcode.org/) + `math.matrices.extras`, 5 bytes
```
recip
```
[Try it online!](https://tio.run/##S0tMLskv@v@/KDU5s@D/fwA "Factor – Try It Online")
[](https://i.stack.imgur.com/BDijG.gif)
[Answer]
# [Ruby](https://www.ruby-lang.org/) + `-rmatrix`, 24 bytes
```
->a{Matrix[*a].inv.to_a}
```
Or, if taking in and outputting a Matrix is apart of standard I/O, then this becomes 10 bytes.
```
->a{a.inv}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpck20km5RbmJJUWaFUuyiNNulpSVpuhY7dO0Sq33BotFaibF6mXlleiX58Ym1EOmb2gVFmXklCmnR0dGGOgpGOgrGsToK0cY6CiAeiGkEZhrHxsZyQbQsWAChAQ)
[Answer]
# Perl, 226 + 4 (`-plF,` flag) = 230 bytes
```
$_=join', ',map$_/($a*$x+$b*$y+$c*$z),$x=($e=$F[4])*($i=$F[8])-($f=$F[5])*($h=$F[7]),($c=$F[2])*$h-($b=$F[1])*$i,$b*$f-$c*$e,$y=$f*($g=$F[6])-($d=$F[3])*$i,($a=$F[0])*$i-$c*$g,$c*$d-$a*$f,$z=$d*$h-$e*$g,$b*$g-$a*$h,$a*$e-$b*$d
```
[Try it online](https://tio.run/##VY7NbsIwEITvPEUOI@GEtQokKe3BV16iihAQ56eiJGp7AB6@7o6tHirZq29mdtee/eelDgEH9z6N16VkS/k4zjg8GRwL3FY4FbivcC7wyAU3Z@Ad9m9VkxcGI/Glya1BR6yjOxB3TS4GZ@JWXQzac6LaUI3CvZ3lXi@4O3Q62DN/jutaYpla9SdU66jiSC@sreUXO8HDoeUL8DHSzX2MBmH1lk4bwkay9d/5xwstttS7jYGtEtKqGKunsowncWosFzvJXmOTGonTTP0zzd/jdP0Kdr7s5Rc).
[Answer]
# Noether, 168 bytes
```
I~aI~bI~cI~dI~eI~fI~gI~hI~iei*fh*-a*di*fg*-b*-dh*eg*-c*+~zei*fh*-z/P","~nPch*bi*-z/PnPbf*ce*-z/PnPfg*di*-z/PnPai*cg*-z/PnPcd*af*-z/PnPdh*eg*-z/PnPbg*ah*-z/PnPae*bd*-z/P
```
[**Try it online**](https://beta-decay.github.io/noether?code=SX5hSX5iSX5jSX5kSX5lSX5mSX5nSX5oSX5pZWkqZmgqLWEqZGkqZmcqLWIqLWRoKmVnKi1jKit-emVpKmZoKi16L1AiLCJ-blBjaCpiaSotei9QblBiZipjZSotei9QblBmZypkaSotei9QblBhaSpjZyotei9QblBjZCphZiotei9QblBkaCplZyotei9QblBiZyphaCotei9QblBhZSpiZCotei9Q&input=MQoyCjMKMwoxCjIKMgoxCjM)
[Answer]
## Clojure, 165 bytes
```
(fn[a b c d e f g h i](let[M map C(M -(M *[e f d c a b b c a][i g h h i g f d e])(M *[f d e b c a c a b][h i g i g h e f d]))](for[i C](/ i(apply +(M *[a b c]C))))))
```
I'm sorry this outputs C in transpose, and I'm feeling lazy to re-do those long character sequences to fix it at the moment.
] |
[Question]
[
Draw a program or function that will write to `STDOUT` `n` times (each for one step) a string that contains a dot `.` at the location of the walker. The program also needs to write a line every `s` seconds (or wait `s` seconds after each line).
A random walk is a mathematical formalization of a path that consists of a succession of random steps ([wiki](https://en.wikipedia.org/wiki/Random_walk)), such that every new step will be the last step plus a new value, so any `t`step value is just the sum of all the random values before ir plus the initial value.
The program should take 2 inputs and will use only spaces `" "` and dots `"."` on the output. The start value of the walker will be `20` such that the output should be a dot after 19 spaces.
```
. #19 spaces then a dot
```
Every new step the value will be the last value of the walker plus one of these`[-2-1,0,1,2]`(20% chance each). After the new position is printed the program should wait `s` seconds and the go to the next step. If the step takes the walker outsite the range `1 to 40` it should be just ignored and the walker position stays the same. The number of spaces will always be a number from 0 to 39.
### Example
```
#input
Mywalk(s = 0.1, n = 30)
#output
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
```
### Considerations
* You may take the input as any reasonable format
* The shortest code wins
* It's okay if your program only accept the seconds as integers
[Answer]
# Matlab, 112
The core idea is generating a list of possible next positions and then uniformly drawing one of them. If we are e.g. at position $l=1$ the possible steps would be `[-1,0,1,2,3]` Of course if we would chose `-1` that would be invalid and we would have to stay at the same position. Thats why we replace the *invalid* positions with the current position, `[1,0,1,2,3]`, and then randomly chose an element from this updated list.
The OP asked us tho *draw* the program, so here we go:
[](https://i.stack.imgur.com/f1jfJ.png)
The transcription:
```
function c(n,s);
l=19; %initialize position
for k=1:n;
disp([ones(1,l)*32,'.']); %print the line
z=(-2:2)+l; %get vector of possible next steps (for l=1 we get [-1,0,1,2,3])
z(z<0)=l; %prune invalids: here we just replace the the invalid positions with the current position
z(z>39)=l; % this ensures the same behaivour as staying in the same spot when going outside of the range
l=z(randi(5)); %draw random sample of those
pause(s);
end
```
[Answer]
# Perl, ~~136~~ ~~128~~ ~~116~~ ~~106~~ ~~101~~ ~~90~~ 86
```
$p=19;map{say$"x$p.".";sleep $ARGV[0];$x=rand(5)+$p-2;$p=$x>0&&$x<40?$x:$p}1..$ARGV[1]
```
Requires the seconds to be an integer.
Run with `perl <filename> <second delay> <number of steps>`.
There may be more golfing potential here, although honestly, I'm surprised it got this far. (Come on, only 6 more bytes to beat the bash answer...)
**Changes**
* Saved 8 bytes by removing unneeded parentheses and spelling out ARGV (it's actually shorter that way)
* Saved 12 more bytes by removing `$s` and `$n` and just using the plain `$ARGV[0]` and `$ARGV[1]`
* Saved another 10 bytes when I realized I could use `$"` and didn't need to specifically define `$u` as `$undef`.
* Saved 5 more bytes by rearranging the ternary and how `$x` is used and by using `map` instead of `for`.
* Saved 11 bytes by no longer accepting the seconds as decimals (challenge spec says it's OK.)
* Saved another 5 bytes by using `say` instead of `print`.
[Answer]
# Pyth, 39
```
J19VEK+.d0QW<.d0K)+*d=JhtS[Z39-+O5J2)\.
```
Takes `s` as the first line of input and `n` as the second. Works on the command line but not with the online interpreter. My first Pyth program ever! Golfing tips are appreciated.
[Answer]
# Python 2, ~~124~~ 119 bytes
@janrn and @Steve Eckert: I don't have enough reputation to comment your answer but here's essentially your version shortened down. The task is to draw a program or a *function*, so by using `f(s,x)` you can save quite some bits, as well you can use `max(0,min(x,39))` to avoid an extra `if` clause. Got it down to:
```
import time,random as r
def f(s,x):
n=19
while x:print' '*n+'.';time.sleep(s);n=max(0,min(n+r.randint(-2,2),39));x-=1
```
[Answer]
# Bash, 81
```
for((s=20;i++<$1;t=s,s+=RANDOM%5-2,s=s<0|s>39?t:s)){
printf %${s}s.\\n
sleep $2
}
```
Edit: *If the step takes the walker outsite the range 1 to 40 it should be just ignored and the walker position stays the same* handled correctly.
Input from command-line options. E.g.:
```
$ ./randwalk.sh 5 0.5
.
.
.
.
.
$
```
[Answer]
## Ruby, 84
```
def w(s,n)q=19;n.times{puts ' '*q+'.';sleep s;q+=rand(5)-2;q=[[q,0].max,39].min};end
```
[Answer]
## Python 2.7, ~~198~~ ~~162~~ ~~143~~ 133
```
import time,random as r;p=20;s=0;d=input();w=input()
while s<d:
print' '*p+'.';s+=1;p=max(1,min(p+r.randint(-2,2),40));time.sleep(w)
```
When calling the script with `python script.py`, the first input is the amount of steps, second input the time between steps (accepts float or int). Any suggestions for improving?
**Edits**
* saved 36 bytes due to now using `print ' '*p+'.'`, thanks to @corsiKlause Ho Ho Ho
* down another 19 bytes by removing tab indents, replaced them with one space or `;` where possible
* 10 bytes less thanks to @Bruce\_Forte idea with `p=max(1,min(p+r.randint(-2,2),40))` (I can't comment on your answer as well, but thanks; don't want to copy it completely)
[Answer]
# Processing, ~~150~~ 147
```
void w(int n,int s){int x=20,i,y,c=0;for(;c<n;c++){x+=y=int(random(5)-2);if(x>40||x<0)x-=y;for(i=1;i<x;i++)print(" ");println(".");delay(s*1000);}}
```
Usage:
```
void setup() {
w(10,1);
}
```
Note: `1000` can't be changed to `1e3` for type reasons.
[Answer]
# Lua, 140 Bytes
Note: This program requires the LuaSocket package.
```
require"socket"p=19 for i=1,arg[2]+0 do print((" "):rep(p)..".")p=p+math.random(-2,2)p=p<0 and 0 or p>39 and 39 or p socket.sleep(arg[1])end
```
[Answer]
# [Perl 6](http://perl6.org), 92 bytes
```
my (\n,\s)=@*ARGS;$/=19;for (-2..2).roll(n) {put ' 'x($/+=(40>$/+$_>=0??$_!!0)),'.';sleep s} # 92
```
```
my (\n,\s)=@*ARGS;
$/=19;
for (-2..2).roll(n) {
put ' 'x($/+=(40>$/+$_>=0??$_!!0)),'.';
sleep s
}
```
Usage:
```
$ perl6 -e 'my (\n,\s)=@*ARGS;$/=19;for (-2..2).roll(n) {put " "x($/+=(40>$/+$_>=0??$_!!0)),".",;sleep s}' 10 0.001
.
.
.
.
.
.
.
.
.
.
```
[Answer]
# JavaScript (ES6), 125 bytes
```
(s,n)=>(t=setTimeout)(c=`console.log(" ".repeat(p)+".");p+=m=Math.random()*5|0;p-=p>41|p<2?m:2;--i&&t(c,d)`,d=s*1e3,p=19,i=n)
```
## Explanation
```
(s,n)=>
(t=setTimeout)( // set inital timeout
c=` // c = code for timeout to execute
console.log(" ".repeat(p)+"."); // print the current line
p+=m=Math.random()*5|0; // move walker 0 - 4 positions to the right
p-=p>41|p<2? // if walker was moved out of bounds (2 - 41 instead
// of 0 - 39 because the random move of 0 - 4 to
// the right has not had the 2 subtracted yet)
m: // undo the move
2; // else subtract 2 to make the move -2 to 2
--i&&t(c,d) // while we have steps remaining schedule next one
`,
d=s*1e3, // d = milliseconds to wait between steps
p=19, // p = position of walker (0 indexed)
i=n // i = steps remaining (needed to make n global)
)
```
## Test
```
console.log = s => result.textContent += s + "\n";
var solution = (s,n)=>(t=setTimeout)(c=`console.log(" ".repeat(p)+".");p+=m=Math.random()*5|0;p-=p>41|p<2?m:2;--i&&t(c,d)`,d=s*1e3,p=19,i=n)
```
```
<input type="number" id="seconds" value="0.1" /><br />
<input type="number" id="steps" value="30" /><br />
<button onclick="solution(+seconds.value,+steps.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# k4, 61 characters
```
f:{y{-1((y:1|40&y+-2+*1?5)#" "),".";."\\sleep ",$x;y}[x]\20;}
```
sample run:
```
f[.1]30
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
```
[Answer]
## Mathematica, ~~122~~ 117 bytes
```
$RecursionLimit=∞;If[#2>0,Print[Indent[a=Min[#3+RandomInteger@{-2,2},39]~Max~0],"."];Pause@#;#0[#,#2-1,a]]&[##,19]&
```
Recursive anonymous function, takes input in the order specified. Could probably be golfed further.
[Answer]
# Python 3, 154 bytes
```
import time
from random import*
w=int(input())
z=int(input())
g=19
c=6
s=" "
while c:
c-=1
s+=s
while z:
z-=1
if -1<g<40:
print(s[:g]+'.')
time.sleep(w)
g+=randint(-2,2)
```
Generate a string of spaces greater than the maximum required length, then print that string ONLY up to the char at index 'g', then print a '.'. Finish by incrementing g by a random value in the range [-2:2], and repeat.
If anyone could help me golf down that horrific input block, I'd appreciate it.
[Answer]
# C funtion, 114
```
s=20,i,t;w(int n,float f){for(;i++<n;t=s,s+=rand()%5-2,s=s<0||s>39?t:s,usleep((int)(f*1e6)))printf("%*c.\n",s,0);}
```
Pretty much a direct translation of [my bash answer](https://codegolf.stackexchange.com/a/67080/11259).
### Full test program:
```
s=20,i,t;w(int n,float f){for(;i++<n;t=s,s+=rand()%5-2,s=s<0||s>39?t:s,usleep((int)(f*1e6)))printf("%*c.\n",s,0);}
int main (int argc, char **argv) {
w(10, 0.2);
return 0;
}
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 35 bytes
```
⍬⊣⎕{⎕←⌽⍵↑'.'⋄1⌈40⌊⍵+3-?5⊣⎕DL⍺}⍣⎕⊢20
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@j3jWPuhY/6ptaDcSP2iY86tn7qHfro7aJ6nrqj7pbDB/1dJgYPOrpAgpqG@vam0IUu/g86t1V@6gXxH7UtcjIAGTY/zQuYwMuIwA "APL (Dyalog Unicode) – Try It Online")
A full program which takes n as first input and s as the second.
```
⍬⊣⎕{⎕←⌽⍵↑'.'⋄1⌈40⌊⍵+3-?5⊣⎕DL⍺}⍣⎕⊢20
{ }⍣⎕ do the following n times
⎕ with s as constant left argument ⍺
⊢20 and 20 as right argument ⍵
⍵↑'.' take ⍵ characters from '.'
⌽ reverse to pad with spaces
⎕← and display it
⎕DL⍺ delay s seconds
⊣ suppress it's return value with
?5 a random number in 1-5
3- subtract from 3 to get negative possibilities
⍵+ add current ⍵ to it
40⌊ minimum of that and 40
1⌈ maximum of that and 1
⍬⊣ suppress the final return value.
```
] |
[Question]
[
From the infinite triangular array of positive integers, suppose we select every 2nd numbers on every 2nd row as shown below:
$$
\underline{1} \\
\;2\; \quad \;3\; \\
\;\underline{4}\; \quad \;5\; \quad \;\underline{6}\; \\
\;7\; \quad \;8\; \quad \;9\; \quad 10 \\
\underline{11} \quad 12 \quad \underline{13} \quad 14 \quad \underline{15} \\
16 \quad 17 \quad 18 \quad 19 \quad 20 \quad 21 \\
\underline{22} \quad 23 \quad \underline{24} \quad 25 \quad \underline{26} \quad 27 \quad \underline{28} \\
\cdots
$$
The resulting sequence ([A185868](http://oeis.org/A185868)) is as follows:
```
1, 4, 6, 11, 13, 15, 22, 24, 26, 28, 37, 39, 41, 43, 45, 56, 58, 60, 62, 64, 66,
79, 81, 83, 85, 87, 89, 91, 106, 108, 110, 112, 114, 116, 118, 120, 137, ...
```
The task is to output this sequence.
[sequence](/questions/tagged/sequence "show questions tagged 'sequence'") I/O rules apply. You can choose to implement one of the following:
* Given the index \$n\$ (0- or 1-based), output the \$n\$th term of the sequence.
* Given a positive integer \$n\$, output the first \$n\$ terms of the sequence.
* Take no input and output the entire sequence by
+ printing infinitely or
+ returning a lazy list or a generator.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
[Answer]
# [Python](https://www.python.org), 35 bytes (@att)
```
lambda n:int((2*n)**.5-.5)**2+2*n-1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3lXMSc5NSEhXyrDLzSjQ0jLTyNLW09Ex19UyBtJE2kK9rCFWqkJZfpJCnkJmnUJSYl56qYahjZKBpVVAE0pimkaepCVG3YAGEBgA)
### [Python](https://www.python.org), 39 bytes
```
lambda n:(int((8*n)**.5-1)//2)**2+2*n-1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY31XMSc5NSEhXyrDQy80o0NCy08jS1tPRMdQ019fWNgEwjbSOtPF1DqHKFtPwihTyFzDyFosS89FQNQx0jA02rgiKQ3jSNPE1NiLoFCyA0AA)
Given the 1-based index computes a single value.
[Answer]
# [Python 2](https://docs.python.org/2/), 47 bytes
Outputs the sequence indefinitely.
```
n=x=1
while 1:exec'2;print x;x+='*n+'n-~n';n+=1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8@2wtaQqzwjMydVwdAqtSI1Wd3IuqAoM69EocK6QttWXStPWz1Pty5P3TpP29bw/38A "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org), 34 bytes
```
[2*n^2-3*n+2*k|n<-[1..],k<-[1..n]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ2W0km6Ec0CAUuz-3MTMPAVbhdzEAt94hYKizLwSBRWFksTsVAVDAwOFmKWlJWm6FjeVoo208uKMdI218rSNtLJr8mx0ow319GJ1siGMvNhYiMoFUApKAwA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ḷ²’xRĖḄḣ
```
A monadic Link that accepts a positive integer, \$n\$, and yields a list of the first \$n\$ odd-odd triangular polka dot numbers.
**[Try it online!](https://tio.run/##AR4A4f9qZWxsef//4bi2wrLigJl4UsSW4biE4bij////Mzc "Jelly – Try It Online")**
### How?
Calculates the first \$T(n)=\frac{n(n+1)}{2}\$ terms, and outputs the first \$n\$.
```
Ḷ²’xRĖḄḣ - Link: integer, n e.g. 5
Ḷ - lowered range (n) [ 0, 1, 2, 3, 4]
² - square (vectorises) [ 0, 1, 4, 9, 16]
’ - decrement [ -1, 0, 3, 8, 15]
R - range (n) [ 1, 2, 3, 4, 5]
x - repeat elements [ -1, 0, 0, 3, 3, 3, 8, 8, 8, 8, 15, 15, 15, 15, 15]
Ė - enumerate [[1,-1],[2,0],[3,0],[4,3],[5,3],[6,3],[7,8],[8,8],[9,8],[10,8],[11,15],[12,15],[13,15],[14,15],[15,15]]
Ḅ - convert from base 2 (vectorises)
...i.e. [a,b] -> 2a+b [ 1, 4, 6, 11, 13, 15, 22, 24, 26, 28, 37, 39, 41, 43, 45]
ḣ - head (to index n) [ 1, 4, 6, 11, 13]
```
[Answer]
# [Rust](https://www.rust-lang.org/), 43 bytes
```
|n|((n+n).sqrt().round()-1.).powi(2)+n+n-1.
```
[Try it online!](https://tio.run/##dczBCsIwDAbge58i3hLmiu1ExKGvMga2MNDMtR0enM9eg9iTLIeQn/8jYY4pe4Z7PzASvBTI3FwCfwLP6BtL9UU2nCEvvCByxaTjFBKSDuPMV6TaaNKP8TmgpUp6yblV3099jC6kzk0b9GgkQkdb@B3tP7GF7FdJU8hhlZhdMfZYkHrnDw "Rust – Try It Online")
A slightly modified version of loopy walt's answer.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
Þ∞:ẇ2Ḟ2vḞf
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnuKInjrhuocy4bieMnbhuJ5mIiwiIiwiIl0=) Outputs (theoretically) infinitely but crashes due to hitting the recursion limit caused by a bug.
```
Þ∞ # All positive integers
ẇ # Cut into slices of lengths...
Þ∞: # Positive integers
2Ḟ # Get every second item
2vḞ # Get every second item of each
f # Flatten the final array
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 40 bytes
Prints the sequence forever.
```
for(n=i=q=1;;n+=--i?2:q+(i=++q))print(n)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPPNtO20NbQ2jpP21ZXN9PeyKpQWyPTVlu7UFOzoCgzr0QjT/P/fwA "JavaScript (V8) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 34 bytes
```
[ 2 * dup √ .5 - 1 /i sq + 1 - ]
```
[Try it online!](https://tio.run/##LYqxDcIwFAX7TPFqIIZEooEBEA0NoopSGOcHLMi3Y38XbMAMjMciJgKa0510vTbiQj4d94fdBjcKTHcMWq5fqD6xEes4/jJovtDfE1vjOoIPJPLwwbIg0piIzbRsi6JeoakW57bIDWrM0CWP9/MFtUaJCkuLOGI@WYk2D9pD5Q8 "Factor – Try It Online")
Outputs the 1-indexed nth term of the sequence. Port of loopy walt's and att's [Python answer](https://codegolf.stackexchange.com/a/253320/97916).
```
word | data stack | comment
------+-------------------------+-----------------
| 5 | example input
2 | 5 2 |
* | 10 |
dup | 10 10 |
√ | 10 3.16227766016838 | square root
.5 | 10 3.16227766016838 0.5 |
- | 10 2.66227766016838 |
1 | 10 2.66227766016838 1 |
/i | 10 2 | integer divide
sq | 10 4 | square
+ | 14 |
1 | 14 1 |
- | 13 | output
```
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 32 bytes
```
; ; tk2* ;2^2* ;3* - + flat
$W1+
```
[Try it here!](https://replit.com/@molarmanful/try-sclin) Returns an infinite list. This code is so weird...
For testing purposes (use `-i` flag when running locally):
```
; 50tk >A
; ; tk2* ;2^2* ;3* - + flat
$W1+
```
## Explanation
Prettified code:
```
; ; tk 2* ; 2^ 2* ; 3* - + flat
$W 1+
```
`;` means "evaluate the next line as a function."
* `$W 1+` [1, ∞) as *n*
* `; ; tk 2*` `[[2][2 4][2 4 6][2 4 6 8]...]` as *k*\*2
+ this works because `tk` ("take") vectorizes the second argument
* `; 2^ 2* ; 3* - +` *n*^2\*2 - *n*\*3 + *k*\*2
+ this whole segment is vectorized
* `flat` flatten
It's vectorizations all the way down!
---
# [sclin](https://github.com/molarmanful/sclin), 19 bytes
```
2*""Q.5^.5- I2^ +1-
```
[Try it here!](https://replit.com/@molarmanful/try-sclin) Port of @loopywalt/@att's answer. Takes a 1-based index, but the whole function vectorizes quite neatly too.
For testing purposes (use `-i` flag when running locally):
```
$W1+ ; 50tk >A
2*""Q.5^.5- I2^ +1-
```
[Answer]
# [R](https://www.r-project.org/), 55 bytes
```
function(n,`?`=rbind)diffinv(rep(1:n*2+1?2,1?1:n))[n]+1
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPJ8E@wbYoKTMvRTMlMy0tM69Moyi1QMPQKk/LSNvQ3kjH0B7I1tSMzovVNvxfnFhQkFMJlDU00EnT/A8A "R – Try It Online")
Returns the 1-based nth term.
[Answer]
# [Raku](https://raku.org/), 31 bytes
```
[\+] flat (1,3...*)Z(2 Xxx^∞)
```
[Try it online!](https://tio.run/##K0gtyjH7n1up4FCcWqhg@z86RjtWIS0nsURBw1DHWE9PT0szSsNIIaKiIu5RxzzN/9YKxYkQxdFxhgYGsf8B "Perl 6 – Try It Online")
This is an expression for the lazy infinite sequence of numbers.
* `(1, 3 ... *)` is the infinite sequence of odd numbers.
* `xx` is the replication operator, which replicates its left-hand side a number of times given by its right-hand side.
* `X` is the cross-product metaoperator. Applied to the replication operator `xx`, it makes a new operator that replicates as a cross product.
* `^∞` is the unbounded range of increasing integers starting at zero.
* `2 Xxx ^∞` produces a list of 2 replicated each number of times from zero to infinity: `(), (2,), (2, 2), (2, 2, 2), ...`.
* `Z` zips the odd numbers with the list of increasing numbers of twos: `(1, ()), (3, (2,)), (5, (2, 2)), (7, (2, 2, 2)), ...`.
* `flat` flattens that list: `1, 3, 2, 5, 2, 2, 7, 2, 2, 2, ...`. That gives the list of differences between adjacent terms of the sequence.
* `[\+]` gives the list of partial sums of the previous sequence, which is the desired polka-dot sequence.
[Answer]
# [R](https://www.r-project.org/), 37 bytes
```
function(x)(((8*x)^.5-1)%/%2)^2+2*x-1
```
[Try it online!](https://tio.run/##K/pfkJ@TnZiSX2L7P600L7kkMz9Po0JTQ0PDQqtCM07PVNdQU1Vf1UgzzkjbSKtC1xCuXsPQyshU8z8A "R – Try It Online")
An alternative to [Giuseppe's R answer](https://codegolf.stackexchange.com/a/253355/95126), here using a variant of [loopy walt's approach](https://codegolf.stackexchange.com/a/253320/95126).
[Answer]
# Excel, 27 bytes
```
=INT((2*A1)^.5-.5)^2+2*A1-1
```
Direct implementation of [loopy walt's answer in Python](https://codegolf.stackexchange.com/a/253320/38183) except it's shorter in Excel. Given the 1-based index computes a single value. Input is in `A1`. When copying the above into Excel, it will automatically add leading zeroes to change `.5` to `0.5`.
[](https://i.stack.imgur.com/oOpcY.png)
---
This **41 byte** solution prints the first 1,048,576 terms (or however many rows you have in your version of Excel):
```
=LET(r,ROW(A:A),INT((2*r)^.5-.5)^2+2*r-1)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes
```
Þ∞:ɾ•y_ƛy$;f
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyI1IiwiIiwiw57iiJ46yb7igKJ5X8abeSQ7ZiIsIiIsIiJd)
Outputs the sequence forever.
## Explained
```
Þ∞:ɾ•y_ƛy$;f
Þ∞: # Push two copies of an infinite list of positive integers
ɾ # In the second copy of the infinite list, push range [1, n] for each item
• # And mold the first copy of the infinite list to the shape of the second
y_ # uninterleave the infinite list, giving two lists: the list of every second row starting at row 0, and the list of every second row starting at row 1. Discard the list starting at row 1.
ƛy$;f # To each row in the remaining list, uninterleave the row, and return the list of every second item starting at index 0. Then flatten the result.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
NθFθF⊕ι⊞υ×ιιIE…υθ⊕⁺ι⊗κ
```
[Try it online!](https://tio.run/##TUw7DgIhFOz3FK98JFhaUWKzhWYLL8DiMxD5LR8TT49I5TTzycxoo7KOyvW@htTqrfmdMh5MLM@YYQiYvAadyVOo9EDLGGytGGwc7tZTQcthhGLZsg0VpSoVryqh/GhH0sT0ax6Mw//L5tocXmLb3fAvNiF6P/fT230B "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` terms of the sequence. Explanation: Port of @JonathanAllan's Jelly answer.
```
Nθ
```
Input `n`.
```
FθF⊕ι⊞υ×ιι
```
Create an array containing each of the squares `0`, `1`, `4`, `9`, ... `i²`, ... each repeated `i+1` times.
```
IE…υθ⊕⁺ι⊗κ
```
Take the first `n` elements of the array, and add to each the incremented doubled index (0-indexed).
20 bytes using the newer version of Charcoal on ATO:
```
NθIE…ΣEθE⊕ι×ιιθ⊕⁺ι⊗κ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjcbPPMKSkv8SnOTUos0CjWtuQKKMvNKNJwTi0s0fBMLNJwrk3NSnTPyCzSCS3PBIoU6CiDKMy-5KDU3Na8kNUUjU1NHISQzN7VYI1NHIVMTCHQUCoEYWU1ATilY2iW_NCkHyM_WBAPrJcVJycVQ1yyPVtIty1GKXWgK4QMA "Attempt This Online") Link is to verbose version of code. Outputs the first `n` terms of the sequence. Explanation:
```
Nθ Input `n` as a number
θ Input `n`
E Map over implicit range
ι Current value
⊕ Incremented
E Map over implicit range
ι Outer value
× Multiplied by
ι Outer value
Σ Concatenated
… Truncated to length
θ Input `n`
E Map over squares
ι Current square
⁺ Plus
κ Current index
⊗ Doubled
⊕ Incremented
I Cast to string
Implicitly print
```
[Answer]
# [Desmos](https://desmos.com/calculator), 31 bytes
```
f(n)=floor(\sqrt{2n}-.5)^2+2n-1
```
Literally just a port of loopy walt's python answer, go upvote that answer too!
[Try It On Desmos!](https://www.desmos.com/calculator/zyoxm5ji9g)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/5xvg9olfby)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
-1 byte by porting [@corvus\_192's Rust answer](https://codegolf.stackexchange.com/a/253353/52210), which is a slightly modified version of [@loopyWalt's Python answer](https://codegolf.stackexchange.com/a/253320/52210), so make sure to upvote them as well!
Given \$n\$, it'll output the 1-based \$n^{th}\$ term (**8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**):
```
·Dtò<n+<
```
[Try it online](https://tio.run/##yy9OTMpM/f//0HaXksObbPK0bf7/NwUA) or [verify the first 25 items](https://tio.run/##yy9OTMpM/W9k6upnr6TwqG2SgpK93/9D211KDm@yydO2@a/zHwA).
Given no input, it'll output the infinite sequence list (**9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**):
```
∞£ιнειн}˜
```
[Try it online.](https://tio.run/##yy9OTMpM/f//Uce8Q4vP7byw99xWEFl7es7//wA)
**Explanation:**
```
· # Double the (implicit) input-integer
D # Duplicate it
t # Take the square-root of the copy
ò # Round it to the nearest integer
< # Decrease it by 1
n # Square it
+ # Add it to the doubled input that's still on the stack
< # Decrease it by 1
# (after which it is output implicitly as result)
```
```
∞ # Push a positive infinite list: [1,2,3,4,5,...]
£ # Split it into parts of itself (since there is no input):
# [[1],[2,3],[4,5,6],[7,8,9,10],[11,12,13,14,15],...]
ι # Uninterleave it into two parts
н # Pop and only keep the first
ε } # Map over each remaining inner list:
ιн # Do the same for those
˜ # Flatten the list of lists
# (after which the infinite list is output implicitly as result)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
d:√ṙ‹²+‹
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIyNcabIiwiZDriiJrhuZnigLnCsivigLkiLCIiLCIiXQ==)
Port of 05AB1E, which is a port of Rust, so make sure to upvote those answers!
[Answer]
# [C (GCC)](https://gcc.gnu.org), ~~68~~ 65 bytes
*-2 bytes thanks to [@Sʨɠɠan](https://codegolf.stackexchange.com/users/92689/s%ca%a8%c9%a0%c9%a0an)*
```
i;r;main(s){for(;i<=r||(i=0,s+=++r+ ++r);i+=2)printf("%d ",s+i);}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBgqWlJWm6FjcdM62LrHMTM_M0ijWr0_KLNKwzbWyLamo0Mm0NdIq1bbW1i7QVgISmdaa2rZFmQVFmXkmahpJqioISUDpT07oWYhDUPJi5AA)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 24 bytes
```
((RTDBa-0.5)//1)E2+DBa-1
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCIoKFJUREJhLTAuNSkvLzEpRTIrREJhLTEiLCIiLCIiLCIxMCJd)
Port of loopy walt's Python answer, so go upvote his answer too!
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 39 bytes
Prints the infinite sequence.
```
130>$:2+@$:1+@v
2$-1v!?:$oan:{<}+
~+}v>
```
[Try it online!](https://tio.run/##S8sszvj/39DYwE7FykjbQcXKUNuhjMtIRdewTNHeSiU/Mc@q2qZWm6tOu7bM7v9/AA "><> – Try It Online")
# [><>](https://esolangs.org/wiki/Fish), 38 bytes
Prints the nth term 1-indexed.
```
:8*$2*1v
}(?!v1+>::*{:
+1-n>2-2,:1%-:*
```
[Try it online!](https://tio.run/##S8sszvj/38pCS8VIy7CMq1bDXrHMUNvOykqr2opL21A3z85I10jHylBV10rr////umWGZgA "><> – Try It Online")
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 10 bytes
```
2*Đ√½-Ɩ²+⁻
```
[Try it online!](https://tio.run/##ARsA5P9weXT//zIqxJDiiJrCvS3GlsKyK@KBu///MTA "Pyt – Try It Online")
```
implicit input
2* double
Đ duplicate on the stack
√ take the square root of top
½- subtract 1/2
Ɩ² cast to an integer and square
+ add the stack
⁻ decrement
implicit output
```
Port of [loopy walt's Python answer](https://codegolf.stackexchange.com/a/253320/52210)
If floating-point returns are allowed, then 9 bytes is possible:
```
2*Đ√⎶⁻²+⁻
```
[Try it online!](https://tio.run/##K6gs@f/fSOvIhEcdsx71bXvUuPvQJm0g@f@/oQEA "Pyt – Try It Online")
Port of [corvus\_192's Rust answer](https://codegolf.stackexchange.com/questions/253309/triangular-polkadot-numbers/253353#253353)
] |
[Question]
[
[Related](https://codegolf.stackexchange.com/questions/103902/wrap-a-seasonal-present)
A room, in the context of this challenge, is a multidimensional array where the elements on the "outside" are `1`, to represent the walls, and all the other elements are `0` (empty space inside the room)
Here's a 1D room with size 5:
```
[1,0,0,0,1]
```
And here's a 2D room with size 6x4:
```
[[1,1,1,1],
[1,0,0,1],
[1,0,0,1],
[1,0,0,1],
[1,0,0,1],
[1,1,1,1]]
```
It's 6x4 and not 4x6 because the list has length 6 at depth 1, and length 4 at depth 2.
Or a 4x4x4 room (imagine each 4x4 sub-array as a 2D slice of the 3D room):
```
[[[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]],
[[1,1,1,1],
[1,0,0,1],
[1,0,0,1],
[1,1,1,1]],
[[1,1,1,1],
[1,0,0,1],
[1,0,0,1],
[1,1,1,1]],
[[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]]
```
A room can be recursively defined by starting with `0` and replacing each `0` with `[1,0,0,...,0,1]` and each 1 with `[1,1,...,1,1]`, each to the appropriate length and depth.
Your challenge is to take a list of integers and output a room with those dimensions. Dimensions will always be \$ >1 \$. A dimension value of 2 means no space inside, so if there's a 2 the whole thing will be `1`s.
You may use any two consistent values instead of `0` and `1` to represent space and wall.
Output may be as a flattened string, e.g. [3,4] => `111110011111`.
You may take the coordinate list reversed (inside out).
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
# Testcases
```
[3] => [1,0,1]
[2,2,2,2,2] => [ [ [ [ [1,1], [1,1] ], [ [1,1], [1,1] ] ], [ [ [1,1], [1,1] ], [ [1,1], [1,1] ] ] ], [ [ [ [1,1], [1,1] ], [ [1,1], [1,1] ] ], [ [ [1,1], [1,1] ], [ [1,1], [1,1] ] ] ] ]
[4,4,4] => [ [ [1,1,1,1], [1,1,1,1], [1,1,1,1], [1,1,1,1] ], [ [1,1,1,1], [1,0,0,1], [1,0,0,1], [1,1,1,1] ], [ [1,1,1,1], [1,0,0,1], [1,0,0,1], [1,1,1,1] ], [ [1,1,1,1], [1,1,1,1], [1,1,1,1], [1,1,1,1] ] ]
[5,6] => [ [1,1,1,1,1,1], [1,0,0,0,0,1], [1,0,0,0,0,1], [1,0,0,0,0,1], [1,1,1,1,1,1] ]
[3,19] => [ [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] ]
[12] => [1,0,0,0,0,0,0,0,0,0,0,1]
```
Thanks to golden\_bat and pxeger for clarifying and fixing this challenge.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
R%)Ịoþ/
```
A monadic Link that accepts the dimensions as a list of positive integers ordered by depth descending (like the examples in the question) and yields the room as a multi-dimensional list of `1`s and `0`s.
**[Try it online!](https://tio.run/##y0rNyan8/z9IVfPh7q78w/v0////H22iY6pjFgsA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/z9IVfPh7q78w/v0/x9uf9S05uikhztnAOmsR437uLj@/482jtWJNtIBQyDLRAcIgbSpjhmQNLTUAUkbGsUCAA "Jelly – Try It Online")
### How?
```
R%)Ịoþ/ - Link: list of positive integers, Sizes
) - for each (size in Sizes):
R - range (size) -> [1,2,3,...,size]
% - modulo (size) -> [1,2,3,...,0]
Ị - insignificant? -> [...,[1,0,0,...,1],...]
/ - reduce by:
þ - make a table using:
o - logical OR (vectorises)
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 11 bytes [SBCS](https://github.com/abrudz/SBCS)
```
⊢↑1∘-↑-∘2⍴≡
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9S16FHbRMNHHTN0gbQukDZ61LvlUedCAA&f=S1PQMeZS19XVVedKUzDSAUM430QHCOE8Ux0zONvQEkmbjqGRAgA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
Sometimes the most straightforward method wins. Space is 1, wall is 0.
### How it works
```
⊢↑1∘-↑-∘2⍴≡ Monadic train; ⍵←dimension vector
-∘2⍴≡ Create the core of ones of dimensions of ⍵-2
1∘-↑ Prepend a layer of zeroes by overtaking ⍵-1 in reverse
⊢↑ Append a layer of zeroes by overtaking ⍵
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 bytes
Anonymous tacit prefix function.
```
⊂(∨/=,1∊⊢)¨⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FXk8ajjhX6tjqGjzq6HnUt0jy04lHv5v9pj9omPOrte9TV/Kh3zaPeLYfWGz9qm/iob2pwkDOQDPHwDP6fpmDMpaury5WmYKQDhlCeiQ4QQtmmOmZQlqGlDky5oZECAA "APL (Dyalog Unicode) – Try It Online")
`⊂(`…`)¨⍳` apply the following tacit infix function between the entire argument and each index in an array of those dimensions:
`1∊⊢` is there a `1` in the index?
`=,` prepend a Boolean list indicating which coordinate are equal to the corresponding element of the original argument
`∨/` are any true? (lit. OR reduction)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~14~~ 11 bytes
```
|/~&/|:'\!:
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6rRr1PTr7FSj1G04uJKt6quUE5TqKjlSnfQMQYSRgpgCGSZKAAhkDZVMAOShpYKIGkdQyMuADyAD2M=)
@ngn suggested a 13-byter `{|/~x&|'x:!x}` in [chat](https://chat.stackexchange.com/transcript/message/58794299#58794299), which
* overwrites `x` with the odometer (`x:!x`),
* takes element-wise minimum `&` with its row-wise reverse `|'x`,
* and then does `|/~` as below.
The 11-byter above is the result of [`x f g x` trainifying tip](https://codegolf.stackexchange.com/a/231590/78410). 1 in `1|:'\` can be omitted because odometer's reverse is always different from itself (assuming all dimensions are at least 2).
---
# [K (ngn/k)](https://codeberg.org/ngn/k), 14 bytes
```
{|/~(x-1)!'!x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6qu0a/TqNA11FRUV6yo5eJKt6quUE5TADLTHXSMgYSRAhgCWSYKQAikTRXMgKShpQJIWsfQiAsAhigQeg==)
Same bytecount as [Traws's](https://codegolf.stackexchange.com/a/233060/78410) but different approach. Returns a flattened list of ones on the wall and zeros inside. The helper function `g` reshapes the flattened list into the desired shape.
### How it works
```
{|/~(x-1)!'!x} monadic function; x: a list
!x odometer: column-wise list of coordinates in x-shaped array
(x-1)!' use modulo x-1 to convert occurrence of x-1 in each row to zeros
~ boolean NOT
|/ reduce by boolean OR over each column
```
[Answer]
# JavaScript (ES6), 65 bytes
Expects the input list in reverse order.
Very similar to the 66-byte version, but returns a flattened string.
```
f=([n,...a],b='0')=>n?b.replace(/./g,v=>f(a,1+v.repeat(n-2)+1)):b
```
[Try it online!](https://tio.run/##PY49D4IwGIR3fkU32vBS5EMTNcXJxUEHR8LwUgtiSEsKIfHXVwjEyw3P3S33wQkHadt@DLV5KedqQQsNnHMsoRL@zmci15eKW9V3KBWNeNTAJPKaIsTBtPQKR6rDhAUxY6fKnQuPkCIFkpWwUAJk85qzefmPeyCHleIjkHTDpPRKj9fGXlG@KRKRE2n0YDrFO9PQ2/Nx58NoW9209ZfOV@Ybk7KDomyR@wE "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 66 bytes
Expects the input list in reverse order.
```
f=([n,...a],b=[0])=>n?b.map(v=>f(a,[1,...Array(n-2).fill(v),1])):b
```
[Try it online!](https://tio.run/##LU49C8IwFNz7KzK@wOvD1A9QScXBxUEHx5AhrUmt1KSkpdBfXy31OLg7joN7m8F0ZazbPvXhaafJSVAeichoLKRaaS5zfyroY1oYZO7AoBJzf47RjODTjJOrmwYGjkJzfiimo0oYU2uNs2TI/lzyBtnMJWyR7RYn9sj@C5HpRCfkQryY8gWGyZyVwXehsdSECq6P@426Pta@qt0Iv0cU7WBjZ4HPmL4 "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
[ n, // n = next value from the input list
...a ], // a[] = all remaining values
b = [ 0 ] // b[] = output, initialized to [ 0 ]
) => //
n ? // if n is defined:
b.map(v => // for each value v in b[]:
f( // do a recursive call:
a, // pass the remaining values
[ // build an array consisting of:
1, // a leading '1'
...Array(n - 2) // followed by n - 2 values
.fill(v), // set to v
1 // followed by a trailing '1'
] // end of array
) // end of recursive call
) // end of map()
: // else:
b // we're done: return b[]
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/) with Image Package, 25 bytes
```
@(d)padarray(e(d-2),+~~d)
```
Anonymous function that inputs a vector with the coordinates and outputs an *n*-dimensional array. Wall and space are respectively `0` and `e` (equal to `2.71828...`)
Note that, when displaying, the first dimension corresponds to the vertical direction.
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999BI0WzIDElsagosVIjVSNF10hTR7uuLkXzf5pGtHGspo5CSmZxgYa6LhJQ1@QCShopgCE@JSYKQIhPgamCGT5pQ0sFvE4wxGn7fwA "Octave – Try It Online")
### Explanation
```
@(d)padarray(e(d-2),+~~d)
@(d) % Define anonymous function
e(d-2) % N-dim array containing e, with side lengths given by d-2
+~~d % Negate d twice, cast to double: gives vector of N ones (**)
padarray( , ) % Add a frame of zeros to (*) with thickness (**) in each dim
```
[Answer]
# [Haskell](https://www.haskell.org/), 57 bytes
```
s[]="0"
s(a:b)|k<-[1..product b]>>"1"=k++([3..a]>>s b)++k
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/vzg61lbJQImrWCPRKkmzJttGN9pQT6@gKD@lNLlEISnWzk7JUMk2W1tbI9pYTy8RyC9WSNLU1s7@n5uYmWdbUJSZV6JSHG2iA4Sx/wE "Haskell – Try It Online")
Builds a flat list since Haskell is strongly typed. Also takes the coordinates in reverse.
[Answer]
# [Python 3.6](https://docs.python.org/3.6/), 63 bytes
```
f=lambda d,w=0:d and[f(d[1:],x)for x in[1,*[w]*(d[0]-2),1]]or w
```
[Try it online!](https://tio.run/##DckxCoAwDADAr2RsSwSr6CD4kpChEoKCVhGh@vrYW@/6nvXMvZnOezoWSSBY5nYSSFlInVCcGF@v5w0vbJkiBiocarTcdB4jc61i173lx6mjAUf23n4 "Python 3 – Try It Online")
Got the and/or mechanism from aeh5040's post. Originally I was just using a ternary operator.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 65 bytes
```
f=lambda d,o=0:d and[f(t:=d[1:],1),*[f(t,o)]*(d[0]-2),f(t,1)]or o
```
[Try it online!](https://tio.run/##HUzbCgIhEH3vK3zcWSZY3YoS/JJhHgyRFkpFfLCvtzEOnCuc8m2vnPZ7qWNE9/afZ/AqYHabDcqnQHFp1gXSllEDrjNjBl6XQBufDeAsNHCuKo8o3NWRFNHOSAb/EHdBgegVb8L6gXPWhtmeVKlHakuXow4wfg "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 14 bytes
```
{.-@<:{.-&2$1:
```
[Try it online!](https://tio.run/##rVJdS8MwFH3PrziMYRykoUm3gWGVouCTKPha9jBryjpwFZfpwB9f02Y1rKzFh3FI7tfJuTchm2rEaY5YgYIhhLIr4Lh/eXyofniQLJTdr@RYqGpCnu44nvfmY2@Ql5/vK2P0G74Ls8ZredC7Ooms3H4VeptpYvTOxBypgs7WZUKDIKBthOvFSE6SvCEhckY6uGDq4IIZ5s4RkuhDYSglabREfItUsJCJJUkla@CSLYQtMWdQO53MMfcP3h/zopqwc0@ZhZ/aFpnnDbhe01fC5i267uX4w/PUt5mxeXuXY@G0W6djf@jP1rLihkVndPtxqtmPbrcBxWYO6T/dObHqFw "J – Try It Online")
*This is a translation of [Bubbler's nice answer](https://codegolf.stackexchange.com/a/233036/15469) into J.*
I tried a few other approaches, including stumbling on the same one Adam used, but in J Bubbler's approach was easily the shortest.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 14 bytes
```
|/:/{~x#!x-1}'
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6rRt9KvrqtQVqzQNaxV5+JKc9AxBhJGCmAIZJkoACGQNlUwA5KGlgogaR1DIy4Avr4NUg==)
```
{ }' for each dimension apply the function in lambda
x#!x-1 overtake n from the range of n-1, e.g. 0 1 2 3 4 0 for n=6
~ "not" the array to get ones at the edges e.g. 1 0 0 0 0 1
|/:/ max table along all dimensions
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
Œp’ỊƇƇo⁸ŒṬ
```
[Try it online!](https://tio.run/##y0rNyan8///opIJHDTMf7u461n6sPf9R446jkx7uXPNf53D7w537HjWtyXrUMEdB107hUcNcrsPtQIHI//@jo41jdaKNdMAQyDLRAUIgbapjBiQNLXVA0oZGsbEA "Jelly – Try It Online")
A monadic link taking a list of integers and returning a list of the appropriate depth of 0s and 1s. Works by generating a list of all of the coordinates, keeping only those that are the walls and using the multidimensional untruthy link to generate the final list.
[Answer]
# [Coconut](http://coconut-lang.org/), 68 bytes
Uses the recursive method described in the challenge. Takes input in reversed order.
```
g=(x,k)->x*0==0and[1,*[x]*(k-2),1]or[*map(g$(?,k),x)]
reduce$(g,?,0)
```
[Try it online!](https://tio.run/##LU@7DoQgEOzvKygswKxEvEdyBfohhMIoGmMQAnixuH/nwDNTzGx2diY7mMFse4hx5viAlVTtUdac1/02CgalOGSJ16ohwKRxotS9xXOBu@SEg8jbxJ0a90EVeIYOahInZzSy1i1bQIu2xoVrugXlg0ccCXGXgEQDJ7J8QEIWT3hlYm84LayR8jr7tihVF/ifRelEqVMf5bwaSV6mJ/yuVfwB "Coconut – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 32 bytes
```
map(elem 0).mapM(\i->0:[2-i..0])
```
[Try it online!](https://tio.run/##HYxNCsMgFIT3PcVbKqgY@wMNpDfICYwLCdpKNUj1/HlV@RbzLWbmY8vXxYh@2TDZTFx0CSQVzVeyBf6Ss1Y8CCENxepKLbCA1lfDQCs26HpjjS539ugxPdmoTMqYS7LhaKt@CST/wlFBgKcw7vDcfbTvgnzP@Q8 "Haskell – Try It Online")
Outputs a flat list of Booleans
[Answer]
# [Julia 0.7](http://julialang.org/), ~~39~~ 37 bytes
```
x->(a=ones(x);a[(:).(2,x.-1)...]=0;a)
```
[Try it online!](https://tio.run/##rVLLCoMwELznKxZ6SWAbjPZBK/EregseAipYRKWmYL/eRvuwikoPModsZiezu2Gv9yzVxyaRTb0NqJZFHle0Zr5W9Mw4dbHmW8E456F0fM0aE1emkoooLwTcgAxACXRQhES52OHLfyBsFl8HtMGIeXN/6L7KVT3Btr5Di0HjNo@9dCHsbfuM0/3IOFxPv9xPO9AeDz/jvHPDgqOi89f@bessTuhNW89jaDuPccEFx64Vd7CDU34kJElxAwMSus0lAFFalZl@0IRe7mUWU8MYs3R5S3OT5ZSROI@aJw "Julia 0.7 – Try It Online")
Takes input as a tuple of dimensions, outputs a multidimensional array with `1`s and `0`s formatted as floats.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
≔0ζ≔1ηF⮌θ«≔Eι⎇﹪κ⊖ιζηζ≔Eιηη»ζ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU9DyUBJR6FK05oLxjcE8jOA/LT8IgWNoNSy1KLiVI1CTU2Fai5OqBrfxAKNTB2FkNSivMSiSg3f/JTSnHyNbB0Fl9TkotTc1LyS1BSNTE1NoMEgszQhFqDpztCE2FPLFVCUmVeiAVTy/390tLGOiY5pbOx/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs vertically with ever larger number of newlines as delimiters between different dimensions. Explanation:
```
≔0ζ≔1η
```
Start with `0` as the hollow room and `1` as a solid room.
```
F⮌θ«
```
Loop through the dimensions in reverse order so that the innermost dimension is processed first.
```
≔Eι⎇﹪κ⊖ιζηζ
```
For the next level of hollow room, take the number of rooms and make the first and last solid.
```
≔Eιηη
```
The next level of solid rooms is just an array of the appropriate number of solid rooms of the previous level.
```
»ζ
```
Output the final hollow room.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 bytes
```
∨∘⌽⍨∘,0∊¨⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkG/x91rHjUMeNRz95HvSCGjsGjjq5DKx71bv6fBpR/1Nv3qKv5Ue@aR71bDq03ftQ2EagzOMgZSIZ4eAZD1XQ@6loEVJDGlaZgzKWrqwukjXTAEMoz0QFCKNtUxwzKMrTUgSk3NFIAAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÎvTyo<y<o>‚b‡
```
Straight-forward approach. Can definitely be golfed a bit with a smarter approach.
Output is a flattened string.
[Try it online](https://tio.run/##yy9OTMpM/f//cF9ZSGW@TaVNvt2jhllJjxoW/q@1DT683jOorPLwllqd/9HGOiaxAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6mj5F9aAuP8NyguC6nMt6m0ybd71DAr6VHDwv@1tsGH11cGlVUe3lKrc2ib/f/oaNNYnWgzHRMgaaJjAqaNISQQG@lAIZBtqmMGljO0BFKGRrGxAA).
**Explanation:**
```
Î # Push 0 and the input-list
v # Loop over the integers `y` of this list:
T # Push 10
yo< # Push 2^y-1 (oeis sequence A000225)
y<o> # Push 2^(y-1)+1 (oeis sequence A000051)
‚ # Pair them together
b # Convert both to a binary string
‡ # Transliterate the [1,0] to ["111...111","100...001"] respectively
# (after which the result is output implicitly)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes
```
Array[!1{##}a&,a=#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@9@xqCixMlrR8P2EbdXKyrVAKlFNJ9FWOVbtf0BRZl5JtLKCrp1CWrRybKyCmoK@g0J1tXGtjkK1kQ4UgjgmOkAIYpjqmIEoYx1LEGVoVFv7HwA "Wolfram Language (Mathematica) – Try It Online")
The private-use character is `\[VectorLess]`.
] |
[Question]
[
[This question](https://codegolf.stackexchange.com/questions/17239/convert-a-decimal-to-a-fraction) doesn't need to apply to just terminating decimals - repeating decimals can also be converted to fractions via an algorithm.
Your task is to make a program that takes a repeated decimal as input, and output the corresponding numerator and denominator (in lowest terms) that produces that decimal expansion. Fractions greater than 1 should be represented as improper fractions like `9/5`. You can assume that input will be positive.
The repeated decimal will be given in this format:
```
5.3.87
```
with everything after the second dot repeated, like this:
```
5.3878787878787...
```
Your program will output two integers representing the numerator and denominator, separated by a slash (or the equivalent form in your language if you do not output plain text):
```
889/165
```
Note that terminating decimals will have nothing after the second dot, and decimals with no non-repeating decimal portion will have nothing between the two dots.
### Test cases
These test cases cover all of the required corner cases:
```
0..3 = 1/3
0.0.3 = 1/30
0.00.3 = 1/300
0.6875. = 11/16
1.8. = 9/5
2.. = 2/1
5..09 = 56/11
0.1.6 = 1/6
2..142857 = 15/7
0.01041.6 = 1/96
0.2.283950617 = 37/162
0.000000.1 = 1/9000000
0..9 = 1/1
0.0.9 = 1/10
0.24.9 = 1/4
```
If you wish, you can also assume that fractions without integer parts have nothing to the left of the first dot. You can test that with these optional test cases:
```
.25. = 1/4
.1.6 = 1/6
..09 = 1/11
.. = 0/1
```
[Answer]
# Perl 6 (~~93~~ ~~101~~ ~~100~~ ~~80~~ ~~68~~ 66 bytes)
```
$/=split ".",get;say ($0+($1+$2/(9 x$2.comb||1))/10**$1.comb).nude
```
The size was increased to handle nothing, instead of just failing. Mouq proposed to use `$/`, so it's now being used, and the code is 20 bytes shorter. Ayiko proposed replacing `/` with , so the code is even shorter (by 12 bytes). Then Mouq proposed replacing `chars` with `comb` (in numeric context, they are identical, because list of characters after conversion to number is number of characters).
Sample output:
```
$ perl6 script.p6
5.3.87
889 165
$ perl6 script.p6
2.0.0
2 1
$ perl6 script.p6
0..3
1 3
$ perl6 script.p6
0.0.3
1 30
$ perl6 script.p6
0.0.0
0 1
$ perl6 script.p6
0.1.6
1 6
$ perl6 script.p6
0.01041.6
1 96
$ perl6 script.p6
0.2.283950617
37 162
$ perl6 script.p6
123.456.789
41111111 333000
```
[Answer]
# Dyalog APL (~~75~~ ~~73~~ ~~69~~ 68 characters)
Here is another and fifth attempt (most probably my last one); I spent the day trying to write some piece of code shorter than 80 characters and being fully consistent with the rules. This challenge made my day!
I finally got a line of APL made of 75 characters, working with Dyalog APL (but not on the online interpreter page because using the `⍎` *execute* function), which is the following one:
```
(N,D)÷D∨N←(⍎'0',1↓I/⍨2=+\P)+(⍎'0',I/⍨2>+\P)×D←D+0=D←⍎'0',⌽2↓⍕¯1+10⊥P←'.'=I← '1.2.3'
```
Of course I could make it a little shorter, but the special cases where one, two or three fields are missing. My code can even handle the `..` input case.
I know that APL is difficult to read, and since people enjoy understanding how a piece of code actually works, here are some explanation. Basically, I compute the final denominator in the variable D and the final numerator in the variable N.
APL is parsed from right to left.
* First, the string is stored in variable I (`I←`).
* Then it is mapped to a vector of booleans indicating where a dot is, and this vector is called P (`P←'.'=`). For instance '1.2.3' will be mapped to 0 1 0 1 0.
* This vector is digits in base 10 (`10⊥`); now '1.2.3' is 1010.
* Then 1 is substracted from this number (either with `1-⍨` or with `¯1+`, here I chose the second). Now '1.2.3' is 1009.
* Then this number is converted to a string (`⍕`), two initial digits are removed (`2↓`), which makes 09 from our initial '1.2.3' example; the string is reversed (`⌽`).
* Here, as a special case, I add an initial 0 character in front of the string; it makes me sad to use the four characters `'0',` but I did it for avoiding an error when the second and thirds fields are both empty. The string is converted back to a number (`⍎`) and it is stored in D, which is the denominator except when both last fields are empty, because in such case D is equal to 0.
* The `D←D+0=` piece of code set D to 1 if it is currently null, and now D contains the denominator (before GCD division however).
* This denominator is multiplied (`×`) with the content of the initial string I up to the second dot with `(⍎'0',I/⍨2>+\P)` which starts from P again (0 1 0 1 0 in my example), adds the successive numbers by cumulating them (which makes 0 1 1 2 2 in my example), check which values are smaller than 2 (making the boolean vector 1 1 1 0 0), and taking corresponding characters in I; another 0 is added in front of the string for preventing another trap (if the two initial fields are empty) and the whole is converted to a number.
* The last part of the input string is added to the previous product with `(⍎'0',1↓I/⍨2=+\P)`, which takes P again, adds by cumulating again, check which values are equal to 2 (see previous explanation), takes the characers, removes the first one which is a dot, adds a preventing initial 0 character and converts to a number.
* This product followed with a sum is stored in N which is the numerator.
* Finally the GCD is computed with D∨N and both numbers are divided by this GCD.
*edit:* Here is a fix for 73 characters:
```
(N,D)÷D∨N←(⍎'0',1↓P/I)+(⍎'0',I/⍨~P←2=+\P)×D←D+0=D←⍎'0',⌽2↓⍕¯1+10⊥P←'.'=I←
```
The idea of this hack is computing first the case where cumulative addition has values equal to 2, storing them for later and inverting this bitwise mask for getting the first case; thus computing the next case needs less characters.
*edit:* Here is another fix for 69 characters:
```
(N,D)÷D∨N←(⍎'0',1↓P/I)+(⍎'0',I/⍨~P←2=+\P)×D←⍎'1⌈0',⌽2↓⍕¯1+10⊥P←'.'=I←
```
The idea of this hack is to embed the most complicated special case as APL code in the string to be evaluated (at string to number conversion stage).
*edit:* Here is another fix for 68 characters:
```
(N,D)÷D∨N←(⍎'0',1↓P/I)+(⍎'0',I/⍨~P←2=+\P)×D←⍎'1⌈0',⌽3↓⍕1-10⊥P←'.'=I←
```
The idea of this hack is to replace *adding -1 to the value* for substracting 1 to that value by the operation *substracting that value to 1* then remove later one character more at the beginning (which will be the minus sign).
*edit:* Cosmetic change:
```
(N,D)÷D∨N←(⍎'0',1↓P/I)+(⍎'0',I/⍨~P←2=+\P)×D←1⌈⍎'0',⌽3↓⍕1-10⊥P←'.'=I←
```
No improvement in size, but more satisfied to get the *maximum* function out of the code to be evaluated.
[Answer]
# J (~~85~~ ~~90~~ 89 chars)
My original function, which was 5 characters shorter than the second, had a couple of bugs: it didn't output integers as "n/1" and it gave the wrong answer on numbers with more than a dozen or so digits. Here's a corrected function in J that also incorporates Eelvex's suggestion to save a character:
```
f=:3 :0
'a t'=.|:(".@('0','x',~]),10x^#);._1'.',y
(,'/'&,)&":/(,%+.)&1+/a%*/\1,0 1-~}.t
)
```
It receives a string and returns a string. Here's a sample session:
```
f '..'
0/1
f '0.0.0'
0/1
f '3..'
3/1
f '..052631578947368421'
1/19
f '0.2.283950617'
37/162
f '.0.103092783505154639175257731958762886597938144329896907216494845360824742268041237113402061855670'
1/97
```
[Answer]
# C, 171
Quite long. Could be further reduced. No `scanf`, which really can't handle it if there aren't any numbers between the dots. No `strtol`. Just number crunching:
```
a,b,c,d,q;main(){while((q=getchar()-48)>-3)q<0?(d=b>0,b+=!b):d?(c=c*10+q,d*=10):(a=a*10+q,b*=10);for(a=a*--d+c,q=b*=d;q>1;a%q+b%q?--q:(a/=q,b/=q));printf("%d/%d\n",a,b);}
```
Test:
```
rfc <<< "2..142857"
15/7
```
[Answer]
# DC (not fully general, shortened to 76 characters)
Not fully general, but please, consider I did it with one of the oldest things in the world:
```
5.3.87 dsaX10r^d1-rla*sasbdscX10r^dlc*rlb*rlb*la+snsdlnld[dSarLa%d0<a]dsax+dldr/rlnr/f
```
**Edit:** I edit my solution; it isn't more general, but a little shorter:
```
sadsbX10r^sclaX10r^dd1-dsdlblc**rla*+dsnrld*dsd[dSarLa%d0<a]dsax+dldr/rlnr/f
```
Use it as:
```
5.3.87 sadsbX10r^sclaX10r^dd1-dsdlblc**rla*+dsnrld*dsd[dSarLa%d0<a]dsax+dldr/rlnr/f
```
* First field isn't required:
```
.1.3 sadsbX10r^sclaX10r^dd1-dsdlblc**rla*+dsnrld*dsd[dSarLa%d0<a]dsax+dldr/rlnr/f
```
is OK.
* Second and thirst field require at least one digit
[Answer]
## Javascript, 203
Way too long, but still fun. Newlines because semicolons are unreadable.
```
s=prompt(b=1).split(".")
P=Math.pow
a=s[0]
c=s[1]
d=P(10,l=c.length)
f=(P(10,s[2].length)-1)*P(10,l)||1
e=s[2]=+s[2]
a=d*a+b*c;b*=d
a=f*a+b*e;b*=f
function g(a,b){return b?g(b,a%b):a}g=g(a,b);a/g+"/"+b/g
```
[Answer]
# J (different method)
Another solution based on a very different method; this time it is fully general; only missing is the 1-denominator when an integer is submitted:
```
".((({.~(i.&1)),'+'"_,((":@(10&^)@#,'%~',])@}.@#~~:/\),'+%',((,~(##'9'"_),'%x:0'"_)@}.@#~2:=+/\@]))(=&'.')) '.1.3'
2r15
".((({.~(i.&1)),'+'"_,((":@(10&^)@#,'%~',])@}.@#~~:/\),'+%',((,~(##'9'"_),'%x:0'"_)@}.@#~2:=+/\@]))(=&'.')) '.1.'
1r10
".((({.~(i.&1)),'+'"_,((":@(10&^)@#,'%~',])@}.@#~~:/\),'+%',((,~(##'9'"_),'%x:0'"_)@}.@#~2:=+/\@]))(=&'.')) '1..'
1
".((({.~(i.&1)),'+'"_,((":@(10&^)@#,'%~',])@}.@#~~:/\),'+%',((,~(##'9'"_),'%x:0'"_)@}.@#~2:=+/\@]))(=&'.')) '1..3'
4r3
```
[Answer]
## GolfScript (67 chars)
```
`{'.'/1$=.10\,?@-).!+0@+~}+3,/1$4$*]-1%~;*+*+].~{.@\%.}do;{/}+/'/'@
```
NB This supports empty integer parts.
If the string is of the form `'n.p.q'` then the value is `n + p/E + q/(DE) = ((nD + p)E + q)/DE` where `D = 10^(len p)` and `E = 10^(len q) - 1`, *except* when `len q = 0`, in which case `E = 1` (to avoid division by 0).
Dissection:
```
# Stack: 'n.p.q'
`{ # Combined with the }+ below this pulls the value into the block
# Stack: idx 'n.p.q'
'.'/ # Stack: idx ['n' 'p' 'q']
1$= # Stack: idx str (where str is the indexed element of ['n' 'p' 'q'])
.10\,? # Stack: idx str 10^(len str)
@-) # Stack: str 10^(len str)-idx+1
# If idx = 0 we don't care about the top value on the stack
# If idx = 1 we compute D = 10^(len 'p')
# If idx = 2 we compute E' = 10^(len 'q') - 1
.!+ # Handle the special case E'=0; note that D is never 0
0@+~ # Stack: 10^(len str)-idx+1 eval('0'+str) (GolfScript doesn't treat 011 as octal)
}+ # See above
3,/ # Run the block for idx = 0, 1, 2
# Stack: _ n D p E q
1$4$* # Stack: _ n D p E q D*E
]-1%~; # Stack: D*E q E p D n
*+*+ # Stack: D*E q+E*(p+D*n)
].~ # Stack: [denom' num'] denom' num'
{.@\%.}do; # Stack: [denom' num'] gcd
{/}+/ # Stack: denom num
'/'@ # Stack: num '/' denom
```
[Online demo](http://golfscript.apphb.com/?c=OycwLi4zCjAuMC4zCjAuMDAuMwowLjY4NzUuCjEuOC4KMi4uCjUuLjA5CjAuMS42CjIuLjE0Mjg1NwowLjAxMDQxLjYKMC4yLjI4Mzk1MDYxNwowLjAwMDAwMC4xCjAuLjknbi97CgpgeycuJy8xJD0uMTBcLD9ALSkuISswQCt%2BfSszLC8xJDQkKl0tMSV%2BOyorKitdLn57LkBcJS59ZG87ey99Ky8nLydACgpdcHV0c30v) which simulates running the program with each of the test inputs, one at a time.
[Answer]
# Python
## No libraries - 156 characters
```
_=lambda a,b:b and _(b,a%b)or a;a,b,c=raw_input().split('.');d,e=int(a+b+c)-bool(c)*int(a+b),
(10**len(c)-bool(c))*10**len(b);f=_(d,e);print'%i/%i'%(d/f,e/f)
```
## Using `fractions` - 127 characters
```
from fractions import*;a,b,c=raw_input().split('.');print Fraction(int(a+b+c)-bool(c)*int(a+b
),(10**len(c)-bool(c))*10**len(b))
```
[Answer]
## Mathematica, 143
As usual, Mathematica offers many high-level functions to do the job, but gives them verbose names.
```
x=StringTake;c=ToExpression;p=s~StringPosition~".";{o,t}=First/@p;u=StringLength@s-t;d=t-o-1;Rationalize@(c@x[s,t-1]+c@x[s,-u]/((10^u)-1)/10^d)
```
Sample output to be added later when I have time.
[Answer]
# Ruby - 112
```
x,y,z=gets.chop.split".";y||='0';z||='0';puts((y.to_i+Rational(z.to_i,10**z.length-1))/10**y.length+x.to_i).to_s
```
This is my first experiment with ruby, so feel free to suggest improvements.
```
$ ruby20 % <<< '5.3.87'
889/165
$ ruby20 % <<< '0..3'
1/3
$ ruby20 % <<< '0.0.3'
1/30
$ ruby20 % <<< '0.00.3'
1/300
$ ruby20 % <<< '0.6875.0'
11/16
$ ruby20 % <<< '1.8.0'
9/5
$ ruby20 % <<< '2..'
2/1
$ ruby20 % <<< '..'
0/1
```
[Answer]
## C, 164
This is similar to orion's C solution, even though I did it from scratch.
I confess however stealing a number of his optimizations.
It is not much shorter, but it handles .25. = 1/4 and 0.000000.1 = 1/9000000.
```
long a,b,c,d,e;main(){while((c=getchar()-48)>-3)c+2?a=a*10+c,b*=10:b?e=a,d=b:(b=1);
b>d?a-=e,b-=d:0;for(d=2;d<=a;)a%d+b%d?d++:(a/=d,b/=d);printf("%ld/%ld\n",a,b);}
```
[Answer]
Two python answers using no libraries. First handles the optional input without a digit before the first . and is 162 chars
```
_=lambda a,b:b and _(b,a%b)or a;i,t,r=raw_input().split(".");b=r!="";d=(10**len(r)-b)*10**len(t);n=int((i+t+r)or 0)-b*int((i+t)or 0);f=_(d,n);print "%i/%i"%(n,d)
```
Second doesn't handle nothing before the first digit but does handle all required inputs correctly and is 150 chars
```
_=lambda a,b:b and _(b,a%b)or a;i,t,r=raw_input().split(".");b=r!="";d=(10**len(r)-b)*10**len(t);n=int(i+t+r)-b*int(i+t);f=_(d,n);print "%i/%i"%(n,d)
```
[Answer]
## Haskell
```
import Data.Ratio
f n=case s '.' n of
[x,y,z]->(r x)%1+(r y)%(10^(length y))+(r z)%((10^t-1)*(10^(length y)))
where
r ""=0
r n=read n
t = if length z==0 then 9 else length z
s _ []=[[]]
s n (x:xs) | x==n = []:(s n xs)
| otherwise = let (l:ls)=s n xs in (x:l):ls
```
[Answer]
# JavaScript (ECMASCript 6) ~~180~~ 175
```
G=(a,d)=>d?G(d,a%d):a;P=a=>+("1e"+a);L=a=>a.length;f=prompt().split(".");B=P(L(b=f[1]));D=P(L(b)+L(c=f[2]))-P(L(b))||1;alert((m=(f[0]+b||0)*D+B*(c||0))/(g=G(m,n=B*D))+"/"+n/g)
```
While it isn't a clear winner for the 300 bounty... this is the shortest I can come up with:
* *Changes from previous version:* some slight alteration to logic, and changes to the Power `P` function by altering it to `+("1e"+a)` instead of `Math.pow(10,a)` thereby saving a few more characters...
[Answer]
# Mathematica 175
```
f@i_:=
If[IntegerQ[g=FromDigits[Map[IntegerDigits@ToExpression@#&,StringSplit[i,"."]/.""-> {}]
/.{a_,b_,c_}:> {{Sequence@@Join[a,b],c},Length@a}]],HoldForm[Evaluate@g]/HoldForm@1,g]
```
Most of the routine goes to massaging the input. Approximately 50 chars went to handling integers.
---
## Examples
```
f["7801.098.765"]
```

More examples:
```
TableForm[
Partition[{#, f[#]} & /@ {"19..87", "19.3.87", "5.3.87", "0.0.3", "0..3", "0.2.283950617",
"123.456.789", "6666.7777.8888", "2.0.0","0.0.0"}, 5], TableSpacing -> {5, 5}]
```

---
## How it would normally be accomplished in Mathematica
`FromDigits` can obtain a fraction directly from a recurring repeating decimal, provided that the input is of a particular form. Integers are displayed as integers.
```
z={{{1, 9, {8, 7}}, 2}, {{1, 9, 3, {8, 7}}, 2}, {{5, 3, {8, 7}}, 1}, {{{3}}, -1}, {{{3}}, 0},
{{2, {2, 8, 3, 9, 5, 0, 6, 1, 7}}, 0}, {{1, 2, 3, 4, 5, 6, {7, 8, 9}}, 3},
{{6, 6, 6, 6, 7, 7, 7, 7, {8}}, 4}, {{2}, 1}, {{0}, 1}}
FromDigits/@z
```

[Answer]
# J (96 characters)
I don't use the slash symbol as a separator (but solution in Mathematica doesn't either since it uses a graphical representation which is better anyway); in J language the fraction is displayed with `r` instead as `/`:
```
(((-.@]#[)((".@[%#@[(10x&^)@-{.@])+({.@](10x&^)@-#@[)*<:@{:@](".%<:@(10x&^)@#)@}.[)I.@])(=&'.')) '1..3'
4r3
(((-.@]#[)((".@[%#@[(10x&^)@-{.@])+({.@](10x&^)@-#@[)*<:@{:@](".%<:@(10x&^)@#)@}.[)I.@])(=&'.')) '123.456.789'
41111111r333000
```
[Answer]
# APL (not fully general)
Not fully general (like my solution for dc); works with Dyalog APL (but not on the online version of Dyalog APL, not sure why):
```
(R,F)÷(F←D×N)∨R←(⍎C)+D×(⍎I/⍨2>+\P)×N←10*¯1++/≠\P⊣D←¯1+10*⍴C←1↓I/⍨2=+\P←'.'=I← '123.456.789'
```
The first field is optional, but at least one digit is required for both other fields.
[Answer]
# JavaScript (189)
```
i=prompt().split(".");a=i[0];b=i[1];c=i[2];B=b.length;p=Math.pow;n=a+b+c-(a+b);d=p(10,B+c.length)-p(10,B);f=1;while(f){f=0;for(i=2;i<=n;i++)if(n%i==0&&d%i==0){n/=i;d/=i;f=1}};alert(n+"/"+d)
```
### Example:
Input:
```
5.3.87
```
Output:
```
889/165
```
[Answer]
# C (420 characters as written; less after removing unnecessary whitespace)
Note that this assumes 64-bit `long` (e.g. 64 bit Linux); it will fail for the test case `0.2.283950617` on systems using 32-bit `long`. This can be fixed at the cost of some characters by changing the type to `long long` and changing the `printf` format string accordingly.
```
#include <stdio.h>
long d[3], n[3], i;
int main(int c, char** v)
{
while (c = *v[1]++)
switch(c)
{
case '.':
n[++i] = 1;
break;
default:
d[i] = 10 * d[i] + c - '0';
n[i] *= 10;
}
n[2] -= n[2] != 1;
while (i--)
d[2] += d[i] * n[i+1], n[i]*=n[i+1];
i = d[2];
*n = n[1];
while (i)
*d = i, i = *n%i, *n = *d;
printf("%ld/%ld\n", d[2]/ *n, n[1]/ *n);
}
```
[Answer]
## [GTB](http://timtechsoftware.com/gtb "GTB"), 81
```
`_:s;_,1,l?_)-S;_,"."
s;A;,1,S;_,".")-1
s;_,1+S;_,"."),l?_)-S;_,"."))→_
x?A;+_)►Frac
```
**Example**
```
?3.25.
13/4
```
] |
[Question]
[
The purpose of this task is to write a program or function to find the most common substring within a given string, of the specified length.
## Inputs
1. A string, `s`, of any length and characters that are valid as inputs for your language.
2. A number, `n`, indicating the length of substring to find. Guaranteed to be equal to or less than the length of the string.
## Output
The most common (case-sensitive) substring of `s` of length `n`. In the case of a tie, any of the options may be output.
## Win Criteria
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest bytes wins; usual exceptions etc. apply.
## Examples
`Hello, World!`, `1` > `l` (appears 3 times)
`Hello! Cheerio!`, `2` > `o!` (appears twice)
`The Cat sat on the mat`, `2` > `at` (appears three times)
`The Cat sat on the mat`, `3` > `at` or `he` (both with trailing spaces. Both appear twice - note case-sensitivity so `The` and `the` are different substrings)
`Mississippi`, `4` > `issi` (appears twice, note that the two occurrences overlap each other)
## Some more examples, all using the same input string\*
```
Bb:maj/2
F:maj/5
Bb:maj/2
G:9/3
Bb:maj7
F:maj/3
G:min7
C:sus4(b7,9)
C:sus4(b7,9)
C:sus4(b7,9)
F:maj
F:maj
```
(note the trailing newline)
1 > `\r\n`(appears 12 times, counting `\r\n` as a single character - my choice, your code may differ on this - otherwise either `\r` or `\n` appear the same number of times). `:` also appears 12 times
2 > `:m` (appears 8 times)
3 > `:ma` or `maj` (appears 7 times)
4 > `:maj` (appears 7 times)
5 > `F:maj` or `\r\nF:ma` or `:maj/` (appears 4 times)
14 > `\r\nC:sus4(b7,9)\r\n` (appears 3 times)
(\* input is taken from [How predictable is popular music?](https://codegolf.stackexchange.com/questions/198425/how-predictable-is-popular-music/). The result of this task might be used, for example, to find the most efficient way to apply a substitution in order to compress the string)
[Answer]
# Python 3.8, ~~[75](https://tio.run/##Jc7BasMwEATQX5nmEok4hrSXEsgH9N5bmoMsry1RZWW0a7v@ele0p4VhHrPTpiHz2/tU9gG3rz25Z9c7SMNXyUWpN8ZI6/PMapbrTe7xGk/8sM1ih1wQERnF8UgmERuxZz5drLX38@WxTyVWNZjDZ4gCCTmmHh1B8pOq84UkdomQMo@YInlCHqD0o7UCDU6hI9VAFN4JVesrFRRyKW31JFocawPHPQL57wZRQQsxgpP/Hd2mLPhAH3s@KrqsYS3wuRTyGnls2xbdrMgBK6XUIJEeqyXC@vdBoDokc1JEeTk0eLV2/wU)~~ ~~[68](https://tio.run/##Jc/BTsMwDAbgV/nZZalWKgEXNGkPsDs34JCmbmOROlXsduvTjwhOln75028vu8Usb@9LeYy4fD2Sn/vBQ1s5z/7unNMu5FXMbeeLfvKZT/LdtFsz5gIGC4qXiVwicdo8y@mlaZrHUriK0R0@Iis0Zk4DeoLmmaoJhZT7REhZJixMgZBHGN2trsCiN9hENVBD8ErVhkoVhXxKex2JNi/WwsuASOGnBRtoI0H0@t9j@5IVVww8yNHQZ4u3gpBLoWAsU9d16FdDjrhRSi0S2bFaItz@LohUi3RNBtanQ4vX@tkv)~~ ~~[97](https://tio.run/##XcoxDsIwDEDRq1idbBFYYECRepLQIUADjlonitsKTh/SFelPXy9/l3eS8zWXGqC/1cnP96cHNWJn/0FEpy7aeJAhpAIRWKB4eY04jYJKNJweaZUFN9urY8sNktlox/yPj0JENRduPmDHqnudgUvbPw)~~ 63 bytes
```
lambda s,n:max(l:=[s[j:j+n]for j in range(len(s))],key=l.count)
```
You can [try it online](https://tio.run/##FcJBCsMgEADAryw57RLppT0UwZekOdhUW41ZxTWQvN7QYcrZfpnvz1K7B/PqyW7vjwVRrDd7YNJmkinqOPLsc4UIgaFa/jpMjlGIZrW606Tbkndu1EsN3NDjEET@BwUPon4B)! Increased byte count because, as @xnor kindly pointed out, Python's `str.count` doesn't count overlapping substrings... But then @xnor's reformulation of what I was doing allowed to slice a third of the bytes!
## How:
```
l:=[s[j:j+n]for j in range(len(s))]
```
This creates a list of all the substrings in `s` of size `n`, plus the suffixes of size `n-1`, `n-2`, ..., `1`. Then we find the `max` on that list, with the numerical value being used to sort given by
```
l.count
```
That means that if `a` and `b` are from `l`, `a > b` if `a` shows up more times in `l` than `b`. This means the shorter suffixes are never the result of the `max` because they only show up once, and even if the correct-sized substrings only show up once, they are first in `l` so they come out instead of the short suffixes. This allows me to save some bytes in the `range` used, given that I don't have to prevent `i+n` from being larger than `len(s)`.
~~# Python, ~~[83](https://tio.run/##LY89bsMwDIWv8uolFuIYSLsF6AG6d0szyDJtEVEoQ2SS@vSu0HYiSPB7P8tqMcvbNuH9a0v@Nowe2slJczEa21bPfOK9XKZcwGBB8TJTm0hadQfZH53rrrS@/6N20j7ku1hrzp0Px8u2FK5bs2uwx9Q2n5EVGjOnEQNB842qaiikPCRCyjJjYQqEPMHo2@oLLHqDzVQPagheqbKhoopCPqW1jkQPL9bBy4hI4dqBDfQgQfT652PrkhUfGHmUnWHIFp8FIZdCwVjmvu8x3A054kkpdUhku8oS4fmbIFI10nsysL40HV5dLVWrue0H)~~ 64 bytes~~
```
lambda s,n:max((s[i:i+n]for i in range(len(s)-n+1)),key=s.count)
```
Thanks to @mypetlion I saved a LOT of bytes :D
You can [try it online](https://tio.run/##NY/BbsMwDEN/hculCZoF2HYrsL/YbdvBsZnaqGMHltI2X5@5KHYRIIGk@JZNfU4f@4TPnz2aeXQG0qfTbO5tK9/hFI7pd8oFASGhmHRmG5la6V7T8a3r@gu3TxlsXpN2@1JC0rY5NDhiapsvHwTi8xodRkLyzJpiC10Y44aY0xlLoCXyBOVdqwTqjdbBehCFNcLqtdUqKDSx@gojryZpD5McPO2lR1DwygRv3POPbkuWZ9hjH7PbwFjDbC6FVunwwJo5DAPGVZE9boyxR6Qeam0St/8qhbJGRZCXpsd7V@kqY7f/AQ) with my very own incredible test case!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŒIù.M
```
[Try it online](https://tio.run/##yy9OTMpM/f//6CTPwzv1fP//D8lIVXBOLFEoBuL8PIUSIDc3sYTLCAA) or [verify the smaller test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXC/6OTig/v1PP9r/M/OtpQR8kjNScnX0chPL8oJ0VRKVZHIdoIKqio4JyRmlqUmQ8XDslIVXBOLFEoBuL8PIUSIDc3sQQsa4xX1kRHyTezuBiECgoylWJjAQ) or [verify the larger test case](https://tio.run/##yy9OTMpM/X90kmdZpb2SwqO2SQpK9i6V/w/v1PP9r/NfSUnJKckqNzFL34jLDUybcsEF3K0s9Y2hXHOotDFQNDczz5zL2aq4tNhEI8lcx1ITDwesC0IC7eKKNtQx0jHWMdEx1TE0iQUA) (which is a bit slow).
**Explanation:**
```
Œ # Push all substrings of the (implicit) input-string
Iù # Only keep substrings of a length equal to the second input-integer
.M # Only keep the most frequent item of the remaining substrings
# (after which it is output implicitly as result)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
s₎ᶠọtᵒth
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/hRU9/DbQse7u4tebh1UknG///RSr6ZxcUgVFCQqaSjYBL7PwoA "Brachylog – Try It Online")
### Explanation
```
ᶠ Find all…
s …substrings of <1st element of input>…
₎ …of length <2nd element of input>
ọ Get the list of each substring with its number of occurrence
tᵒ Order by the number of occurrence
t Take the last one
h Output the substring itself
```
[Answer]
# JavaScript (ES6), ~~85 83~~ 80 bytes
Takes input as `(string)(length)`.
```
s=>n=>[...s].map(o=m=(x,i)=>(o[k=s.substr(i,n)]=-~o[k])<m|!k[n-1]?0:m=o[O=k])&&O
```
[Try it online!](https://tio.run/##jZFfa8IwFMXf@ymuPtgEYrraitgtHUz2h8HmwwZ7qAWjthptk9LUscHYV@9SHSpsD14SOPfc/EIOWfN3ruelKKquVIukTlmtWShZGFFKdUxzXiDFcoY@iMAsRCraME31dqarEgkiccy638aM8VX@1dpEsuvG1xdBzlQ0ZsbtdMb1XEmtsoRmaolS1H5IskwReFNltmi1MXIxhkM5DtiZbf2HtGC0SpJSqAbqHaEGUa0/zOsqgRGvQJutJFSmzXn1izYMr85nvAMDNqgSbDP5Qz8JrZtVFMIg/mms/SuboW1ZGhhMb2ZBztdOb1JO5N1O9ht5at8HQ8c7moPjUW8/zoXcmaNAb7WPZgMyxOf0u0sOYnppRS6BHgGPgE@gT8D1Y5qq8pbPV0gCC@E06ePL@Jma7xdyKdJPE1xjJLGp@gc "JavaScript (Node.js) – Try It Online")
[Answer]
# Java 10, ~~212~~ ~~211~~ ~~196~~ ~~195~~ ~~146~~ 143 bytes
```
s->n->{String r="",t;for(int m=0,c,j,i=s.length();i-->n;)for(c=0,j=-1;(j=s.indexOf(t=s.substring(i-n,i),j+1))>=0;)if(++c>m){m=c;r=t;}return r;}
```
-15 bytes by outputting the substrings with their count, [which is allowed](https://codegolf.stackexchange.com/questions/199696/the-most-common-substring/199718#comment474884_199696).
-1 byte thanks to *@ceilingcat*.
-52 bytes thanks to *@OlivierGrégoire*.
[Try it online.](https://tio.run/##jVNNb6MwEL3nV0x9soWhIUlVNSwcNlJ391D10JX20PTgEJOYhQHZprtVxG/PGgKKqm2rSnwM85793oyHXDwLP9/@PqaFMAbuhMLDBMBYYVUKuUODxqoiyBpMraowuB2CLw9WK9zxDzk/0Mqd1BxO5CSBDGI4Gj9BPzmckqBjQriNskpThRbKeMpTnnMVm6CQuLN7yiLluyUR6zipw/PYDyOaO4bCrfx7n1HrYtNsTL8lVT5yxXjuhYwl8TRiKqOelyYlO5RxGunYRq2WttEIOmqP0cSVXDebwpU8VP5cqS2Urhv05PLxCQTrOgNgpbE05OS7LIqKw69KF9sLwqIzOBvAC1jtpdSq@g/@uZewEhaMuysE6z5LYV@x5p9iLTi5U8Z0V12rEXp4MVaWQdXYoHbubYGU@CTQspbCeZ9OGetrhuFg@r3cyZCvm2Up8svZGm/74GqN59S35c3lfExcj5R5B5QKXWK1NI1Z0M01v2Eff/VLhxd513PnqjNdiFRSskbCydo92VDlODFqifIPuOjx6RDyGZ/zBb/i4aJlPe3tdmBMPOWRJRAvC0RdFy@9HBtidRJpJ@efoR@JvumdKI5DDWaYizdUjEdA4BY6MXwtZkYlHJXa4z8)
**Explanation:**
```
s->n->{ // Method with String and Integer parameters and String return-type
String r="", // Result-String, starting empty
t; // Temp-String
for(int m=0, // Largest count, starting at 0
c, // Temp count integer
j, // Temp index integer
i // Index-integer `i`
=s.length();i-->n;)
// Loop `i` in the range (input-length, n]:
for(c=0, // Reset the temp-count to 0
j=-1; // And the temp-index integer to -1
(j=s.indexOf(t=s.substring(i-n,i)
// Set String `t` to a substring of the input-String in the range [i-n,i)
j+1))// Set the temp-index `j` to the index of String `t` in the input-String,
// only looking at the trailing portion after index `j+1`
>=0;) // And continue looping as long as long as that substring is found
if(++c>m){// If the temp-count + 1 is larger than the current largest count:
m=c; // Set this current largest count to this temp-count + 1
r=t;} // And the result-String to this temp-String
return r;} // After the nested loops, return the result-String
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~49~~ 46 bytes
*-3 bytes thanks to SirBogman*
```
{$^n;bag($^a~~m:ov/.**{$n}/X~$).max(*{*}).key}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiUuzzopMV1DJS6xri7XKr9MX09Lq1olr1Y/ok5FUy83sUJDq1qrVlMvO7Wy9n9xYqVCmkKNSrxCWn4Rl4a6b2ZxMQgVFGSq6yiYaOoAxUIyUhWcE0sUioE4P0@hBMjNTSwBShtr6vwHAA "Perl 6 – Try It Online")
### Explanation
```
{ } # Anonymous block
$^n; # Declare argument
$^a~~m / / # Regex match input string
:ov # Also return overlapping matches
.**{$n} # Match n-character strings
X~$ # Stringify matches
bag( ) # Convert to Bag (multiset)
.max(*{*}) # Find Pair string=>count with max value
.key # Get key (string)
```
[Answer]
# [PHP](https://php.net/), ~~133~~ 126 bytes
```
for(;$k<=strlen($i=$argv[1])-$j=$argv[2];)$s[]=substr($i,$k++,$j);$c=array_count_values($s);asort($c);echo array_key_last($c);
```
[Try it online!](https://tio.run/##LYrBCsMgEAV/xcMelKSH5GqkHxKCbMXWRhuDq4F8vbWkh/dghtndXqf73v4ZE5fgJ0U5BbtxeCvA9DrmYRE3WP8wLlIAzYui8mhhq3rwXdfDKiQYhSnhqU0sW9YHhmKJAwmJFFPmYIS0xkV2Vd6eOiBdvtaanWUGM6O2uLEffjDX8Qs "PHP – Try It Online")
Annoyingly `asort()` ~~and `end()`~~ can't be chained into one expression.
-7 bytes thanks to @manatwork
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 92 bytes
```
s=>n=>s.map(F=t=>([F[w=(w+t).slice(-n)]=-~F[w],w]),w="").sort(([a],[b])=>a-b)[s.length-1][1]
```
[Try it online!](https://tio.run/##fVFNa@MwEL37V0x7KBKRHfJRQgPyoYHsXva2sAfXbGRnEqsokpGUuHvZv54d293uUmjBlpg3b9488Z7VRYXa6zam1u3xepDXIHMr85CdVMu2MsqcFduik6ybRJ4Fo2tkqeWlTH8TXIqu5KKTt7fUcz4yVqhSFFXJZa7SihchM2iPsUlnZTErr7WzwRnMjDuy3Vc0xgn44bzZ3wiYQQ4GmGpbVD7AAqI@YeDJQLuBTYPotSPinIgEvDFjR6Z48r1B2KgIgX5nIVJ5UnGkE/SP3njEv@IfDS3GIeeBEFa52ECn6YheaaPtEUKragwZPPatUXo0AilYFxFqFTANaIOO@qLjLwgO@m3K7oc1yiPs9eGAHi3tP1chehImT990CP3XtlrAkoz0xbvninFJbMhkrxY7B66uz57UyBe4C3qjWkBVN0AW0fMdRRrrhk1ZNuEC2NN@wkm8r@CJTY98iDz02XtsDT3vI6pgP4USlagpZS8PrMiyTJWcTSrO7@4858n/ORczMRcLsRT3YrYshyUvMh@ndo/V@qSep/NkO9z3yRvwZf0wXbyWq9f2gtCTtqtksw7nsGTVSjzwT4phajx35O@Fc379Aw "JavaScript (Node.js) – Try It Online")
Takes `s` as a list of characters in `(s)(n)` syntax.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~97~~, ~~96~~, 92 bytes
```
s=>n=>s.Skip(n-1).Select((_,i)=>s.Substring(i,n)).GroupBy(x=>x).OrderBy(g=>g.Count()).Last()
```
[Try it online!](https://tio.run/##lY3BbsIwDIbve4rAyZFCJNhuW3JYJQYa0w5M4jh1xRSLzqniVIKn70LZbr1MsvXb/j/blcwqoX7ZcfUkKRLXZqiJk1m/xNC1efTnqJt679VBuV6cZ@fFbk/UAs/m2m6xwSoBfBrSg9N93VaADGtth4PPFzg7f9b2Pe4x5q52vrZF6DhBZjalZO0f73aREm6IEQ4wXWHTBKN2ITb7yVRDfvaKFz1GTVRxRIwUrtxilPs4oirKpCRnYJVy@12m/@P3o/gbiVyjbSkzD79M/wM "C# (Visual C# Interactive Compiler) – Try It Online")
Explanation:
```
s.Skip(n-1).Select((_,i)=>s.Substring(i,n)) //select every substring of size n
.GroupBy(x=>x) //group by value
.OrderBy(g=>g.Count()) //order by increasing recurrence
.Last() //return the last one
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
NθF⊕⁻Lηθ⊞υ✂ηι⁺θιUMυ⟦№υιι⟧⊟⌈υ
```
[Try it online!](https://tio.run/##FYy7CgMhFET7/QrLK5gu3ZZbLcQgpAwpjDHxgq9Vb8jfG4UpDsOZMU4Xk7TvfY@Z2pXC0xY4@Lq8U2GwR1NssLHZF0iMVOFi46c5cFywg3POFFUHJNjNo7HgBEPBlB/iMXAI6yJ13lIIOr6md98SxTYJxwU@hqAKjkalDFL/MFAAmsPez4vEWmdyxn76@j8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs the lexicographically largest substring with the highest count. Explanation:
```
Nθ
```
Input the desired substring length.
```
F⊕⁻Lηθ⊞υ✂ηι⁺θι
```
Extract all substrings of that length and push them to a list.
```
UMυ⟦№υιι⟧
```
Replace each substring with a tuple of its count and the substring..
```
⊟⌈υ
```
Print the substring with the highest count.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ãV ü ñÊÌ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=41Yg/CDxysw&input=IlRoZSBDYXQgc2F0IG9uIHRoZSBtYXQiCjM)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes
```
#&@@Commonest[##~Partition~1]&
```
Takes an array of characters, returns an array of characters.
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8V9ZzcHBOT83Nz8vtbgkWlm5LiCxqCSzJDM/r84wVu2/pjVXQFFmXomCg0JatHNGYlFicklqUXE0F5eSU5JVbmKWvhGXG5g25YILuFtZ6htDueZQaWOgaG5mnjmXs1VxabGJRpK5jqUmHg5YF4RU4uKK1eHiMgVS/wE "Wolfram Language (Mathematica) – Try It Online")
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes
```
#&@@Commonest[##~StringPartition~1]&
```
Takes a string, returns a string.
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8V9ZzcHBOT83Nz8vtbgkWlm5LrikKDMvPSCxqCSzJDM/r84wVu2/pjVXAFC0RMFBIS2ai0vJKckqNzFL34jLDUybcsEF3K0s9Y2hXHOotDFQNDczz5zL2aq4tNhEI8lcx1ITDwesC0Iq6XBxmXJxxf4HAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Zsh](https://www.zsh.org/), 89 bytes
```
local -A m
repeat $#1 ((++m[${1:$[i++]:$2}]))
for k v (${(kv)m})((v>M))&&r=$k&&M=$v
<<<$r
```
[Try it online!](https://tio.run/##fVFdT8IwFH2/v@KCdW0zDWFACAszURL1hfjCG/IwoHOTdZ1tmYlkv30WnPBGc9t77zn9ODn9MWmTMM6aXG3iHO8fUYIWpYgtkps@Mub7ckkO/ZAsM99fhSSoV5xDojTusEJGDmxXcVlzxqqHOeeepyOy87x5RCqYTqdENxxgkyq9NRF9Wocy/uwF8HzKIzgDL@GkN2jbcUsPHCqzYgyz0OzNkK3HdxN@pTmdalcKJ40GC2RAjZLCplnxgVlhhRbGupriAOiryHOF30rn2w7Ffgt0cJYKrTPlsADoIhW4cY4YN1WB1rUytlcpd/U8M@YYZZlRHAL5M8G98V8F5@rCji77hsDxAACldqIT7C6cbMQQb42L9@Jtb8u9DbGL7g@@fG5qJAUkSMwxH71HGrnhnKih@QU "Zsh – Try It Online")
```
local -A m # associative array, "local" is shorter than "typeset"
repeat $#1 { # looping for the length of the string will cause the
# program to use shorter, invalid strings as
# the bash-style slice gets cut short
((++m[${1:$[i++]:$2}])) # increment the map at the key with substring
} # starting at $[i++] with length $2
for k v (${(kv)m}) { # loop over the associative array's keys/values
((v>M)) && r=$k && M=$v # find the max value M, save the key as r.
} # looping forward ensures we avoid our invalid subtrings
<<<$r # print $r
```
[Answer]
# [C++ (clang)](http://clang.llvm.org/), ~~201~~ \$\cdots\$ ~~151~~ 150 bytes
```
#import<map>
using S=std::string;S f(S s,int n){std::map<S,int>m;S t,r;for(int i=0,x=0;i<=s.size()-n;r=x<++m[t=s.substr(i++,n)]?x=m[t],t:r);return r;}
```
[Try it online!](https://tio.run/##dVBNT8MwDL33V5hyadV0Gh@nJS2HXbhwKhIHtkNo0y1Sm1SJiyam/vaRZIMxEFYi2@89O3bqYcjrjqvN4XAt@0EbZD0fymi0Um2gKiw2i4VF4zJaQZtUYIlUCCrdB8qJWeWRsnc8EkNbbRKvkMWc7Io5laywMys/RJLmippix7Ksf0UPjm@ucyKzjKh0/bArHLwmuDApNQJHo8DQyY2l6m5sBDCpnVzwvozO2LuoUZsy8i/2XKokjfYROAvTHVkW4oHLU3RcJwxdAgqLFgo4Vnnbx4@i6zSBF2265iomcDOR3@wVLLdCGKk9f3vBP0lr/RkG6bj7C@55K2DJEay7WgG6tOf4p8W/srspqCYanPtqSPiIOmyxCKuk323CrrUeERiDeBXH3nvNrJXGfqEEzrgVtVaNxyHPSziVtMm5iPzQpacOKxXTaDp8Ag "C++ (clang) – Try It Online")
# Ungolfed
```
#include<map>
#include<string>
std::string f(const std::string& s,int n) {
std::map<std::string,int> m;
for(int i=0;i<=s.size()-n;++i) {
m[s.substr(i,n)]++;
}
int x=0;
std::string r;
for(auto a:m) {
if(x<a.second) {
x=a.second;
r=a.first;
}
}
return r;
}
```
[Answer]
# Excel (Ver. 1911), 60 Bytes
```
B2 'Input: String
B3 'Input: Sub-string Length
C2 =-COUNTIF(D2#,D2#)
D2 =MID(B2,SEQUENCE(LEN(B2)),B3)
E2 =SORT(C2#:D2)
F2 'Output
```
### Test Sample
Note: Newlines do exist in cells, but default formatting doesn't show them. Also only 10 of the 105 rows are shown to keep the image a decent size.
[](https://i.stack.imgur.com/4X3rJ.png)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
I have a feeling there may be an elusive 5-byter out there.
```
ṡċ@Þ`Ṫ
```
**[Try it online!](https://tio.run/##y0rNyan8///hzoVHuh0Oz0t4uHPV////1X0zi4tBqKAgU/2/CQA "Jelly – Try It Online")**
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 72 bytes
```
param($s,$n)(0..($s.Length-$n)|%{$s|% s*g $_ $n}|group|sort C*|% N*)[-1]
```
[Try it online!](https://tio.run/##hVLfT8IwEH7vX3EuxW6kgDAIssSESII@qC@a@GAMDqkws19pSzRh/O147QZiMnXZ2rvvvvt2d22efQipViKOd/QNLmCzy0MZJi5VnKaee9Zuo9m@EelSr1qIFI0NVUUDVHMJdAY03RZLma3zQmVSw6SJobum99TqPu@2hFAtlL7XMkqXqD12yOU8SML3To9M7T74Bq6CUcev3GEV9hFNonRIJoFaq747H/KR94djs6rVGRMydgngw112Gyll3jyPGIc@B2Y8NHteRTkqlUOXw9hlAePOS@p46NfTeqgTJKhyXhv2S5UkZJxhSQyFhrXEvtVBxm@EgVWalhxL7djaDGLq69d3gbpIOh6RaWc/k2s89IzDYybjxQmzTbMYd/8n4wQmKyFklBmO6bg0DqSHlYBJqEHhl6Wg0U1CXXGt4f/PLUeFKLaHqBkV/sGDAhqwsdlUacnxvq0TXMVnLl61WKCpo0QovFx0VtKkUOtYI3CK99kk2Rwbc6hbhVtRetDwgn2SQ8h29wU "PowerShell – Try It Online")
Unrolled:
```
param($s,$n)
(
0..($s.Length-$n)|%{
$s|% substring $_ $n
}|group|sort Count|% Name
)[-1]
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 58 bytes
```
->s,n{a=(0..s.size).map{|i|s[i,n]};a.max_by{|e|a.count e}}
```
[Try it online!](https://tio.run/##fYvdCoJAEIXv9ymG6CJhWvMPybKLgrrqCUxirZU2cJMmIXN9drOQLoPDnHO@4dyrrO7y@NBNV4S6EfFkxjlxUi9p8UKUjVGGEoU6bReiB89jVjdGGsFPt0o/QLZtRxDDeMnvUpxZ4iC4CB6CjxAgOH7KpThdGjDaQAl5Qgg6hZZ98miviD4q1ahfpN06iwpxtV22/XrAfmAXzW1vqOHw9npaKB2yTUQV@ZMsxLn1p3xXw30D "Ruby – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-lp`, 47 bytes
```
++$k{$_}>$k{$\}&&($\=$_)for<>=~/(?=(.{$_}))/g}{
```
[Try it online!](https://tio.run/##K0gtyjH9/19bWyW7WiW@1g5ExdSqqWmoxNiqxGum5RfZ2NnW6WvY22rogRRoauqn11b//2/C5ZtZXAxCBQWZ//ILSjLz84r/6/qa6hkYGvzXzSkAAA "Perl 5 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ãV
ñ@è¶X
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=41YK8UDotlg&input=IlRoZSBDYXQgc2F0IG9uIHRoZSBtYXQiCjM)
[Answer]
# [Go](https://golang.org/), 131 bytes
```
func f(s string,l int)(p string){x,i:=0,0
m:=map[string]int{}
for;i<=len(s)-l;i++{t:=s[i:i+l]
m[t]++
if m[t]>x{x=m[t]
p=t}}
return}
```
Takes as input a `string` and an `int` representing the string and the length of the substring respectively.
Some newlines can be replaced by semicolons if people prefer one-liners.
[Try it online!](https://tio.run/##jVFNa8QgEL37K6Y5JcQu249Ttvayl14KPRR6CKGINVmpUdFZSAn@9lQ33bK9VXQYfW/GeTODXRwXn3yQMHJlCFGjsx6h6Ecslv5oBPRlgIBemYFqUAar0v3cq3miqmFbuiVjw0bu2vW9S6w5kt76nXpgWpoyVNd6p@p6xoaFVjWq1h0ZW@zqmqgesvc4zRPLDnEMYyRe4tGbuOCXk4AyoOBB5o@PAmEmAHAuK/tTroxEQk4lZylltbLOoQEaBm33m@kEpjUXT1JrS@HNev1xVVC4ifQvdgX7g5Re2YzeXqCvBwl7jhDSsQbwkLuI/yXdXZCeVQh5O6cScr8iSU6yqY3wTgFFFuC5GeSFprOKNK7NS2oGalOioGloKDYhR22mqtqt2eLyDQ "Go – Try It Online")
] |
[Question]
[
Several years back, Hot Wheels made a simple flash game called ["Formula Fuelers Racers"](http://play.hotwheels.com/en-us/games/formula-fuelers-racers.html)\*. To play the game, you select three ingredients from a fridge to put into your car, which is then raced against the computer's randomly-generated car. It turns out the mechanics of this game are pretty simple. First off, the actual race "time" of your car is randomly generated and has no bearing on whether or not you win the race. Secondly, the winner of the race is determined by a score which is calculated from the selected ingredients (duplicate ingredients are allowed, and the order matters). Each ingredient has an associated "value" and an associated "operation" as shown in the following table:
```
# ingredient val op
1 Hot Salsa 2 +
2 Root Beer 1 +
3 Milk 1 +
4 Pickle Juice 2 +
5 Mystery Lunch -3 *
6 BBQ Sauce 2 +
7 Egg 1 +
8 Ketchup 2 +
9 Mustard -1 *
10 Melon 1 +
11 Chocolate Milk 1 +
12 Mayonnaise -2 *
13 Baby Food 0 +
14 Pepper 1 +
15 Salt 2 +
16 Syrup -1 *
17 Salad Dressing 2 +
18 Orange Juice 1 +
19 Soy Sauce 2 +
```
For convenience, this challenge will be referring to ingredients by their number and not their name. Here are the steps to compute a score:
1. First, initialize the score with the value of the first ingredient.
2. Then, use the second ingredient's operation to combine the current score and the second ingredient's value to get an updated score.
3. Finally, use the third ingredient's operation to combine the current score and the third ingredient's value to get the final score.
Higher scores are better and always beat lower scores.
For example, the ingredients `1 2 3` have a score of `(2+1)+1 = 4`. The ingredients `7 5 6` have a score of `(1*-3)+2 = -1`. Therefore, `1 2 3` beats `7 5 6`.
**Challenge**
In this challenge, you shall write a program which takes an ordered list of 3 integers and outputs the corresponding score.
**Input**
Your program may accept a list of three integers in the most convenient format. You are allowed to use either 1-indexing for the ingredient names (as above) or 0-indexing (subtract 1 from every index above).
**Ouput**
Your program must output a single integer indicating the score.
**Test Cases**
```
4 5 5 => 18 // max score
5 5 5 => -27 // min score
13 13 13 => 0
1 2 3 => 4
7 5 6 => -1
16 2 19 => 2
19 7 12 => -6
```
*\*This page is pretty outdated and doesn't work in some browsers, but you don't need to play the game for this challenge.*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“zẈ€$ụ¤’b6’ị@µỊị⁾+׿CFḊV
```
Takes a list of 0-indexed ingredients.
**[Try it online!](https://tio.run/nexus/jelly#@/@oYU7Vw10dj5rWqDzcvfTQkkcNM5PMgMTD3d0Oh7Y@3N0FZDxq3Kd9ePrRPc5uD3d0hf3//z/aWMdExyQWAA "Jelly – TIO Nexus")** or see a [test suite](https://tio.run/nexus/jelly#@/@oYU7Vw10dj5rWqDzcvfTQkkcNM5PMgMTD3d0Oh7Y@3N0FZDxq3Kd9ePrRPc5uD3d0hf0/3A5U/f9/dLSxjomOSaxOtAmUNjTSASMg00DHUAdEmwGlTEFSpkABQwsQy0LHTMfQMDYWAA)
### How?
Uses a slightly convoluted form of compressing the values as a base-6 number and the fact that the multiplicative entries are the negative ones. Instead of simply shifting up by 3 to get the base-6 digits, the complemented values incremented are used - this saves bytes by allowing the `Ị` atom to pick out the negative entries prior to the complement step while also saving a byte in the base-250 compression.
```
“zẈ€$ụ¤’b6’ị@µỊị⁾+׿CFḊV - Main link: 0-based ingredient list e.g. [6,4,5]
“zẈ€$ụ¤’ - base 250 compressed number: 120851767994004
b6 - convert to base 6: [1,1,0,5,0,1,0,3,1,1,4,2,1,0,3,0,1,0,0]
’ - decrement: [0,0,-1,4,-1,0,-1,2,0,0,3,1,0,-1,2,-1,0,-1,-1]
ị@ - index into [reversed @rguments] [0,4,-1]
µ - monadic chain separation (call that x)
Ị - insignificant(x)? (abs(x)<=1) [1,0,1]
⁾+× - ['+','×']
ị - index into ['+','×','+']
C - complement(x) (1-x) [1,-3,2]
ż - zip [['+',1],['×',-3],['+',2]]
F - flatten ['+',1,'×',-3,'+',2]
Ḋ - dequeue [1,'×',-3,'+',2]
V - evaluate as Jelly code -1
```
[Answer]
## JavaScript (ES6), ~~89~~ ~~84~~ ~~82~~ ~~78~~ 73 bytes
Takes input as an array of 3 integers, using 0-indexing.
```
a=>(o=a=>F()<0?a*n:a+n)(o((F=_=>n='5445054524413452545'[a.shift()]-3)()))
```
### Test cases
```
let f =
a=>(o=a=>F()<0?a*n:a+n)(o((F=_=>n='5445054524413452545'[a.shift()]-3)()))
console.log(f([3, 4, 4])) // => 18
console.log(f([4, 4, 4])) // => -27
console.log(f([12, 12, 12])) // => 0
console.log(f([0, 1, 2])) // => 4
console.log(f([6, 4, 5])) // => -1
console.log(f([15, 1, 18])) // => 2
console.log(f([18, 6, 11])) // => -6
```
## Previous version, 78 bytes
Takes the 3 integers in currying syntax `(a)(b)(c)`, using 0-indexing.
```
a=>b=>(o=a=>b=>(n=F(b))<0?a*n:a+n)(o((F=n=>'5445054524413452545'[n]-3)(a))(b))
```
### How it works
One slightly unusual thing about this code is that it only takes 2 arguments in 'common' currying syntax `a => b =>` and eventually returns a function that takes the 3rd one.
**Breakdown**
```
F = n => '5445054524413452545'[n] - 3
o = a => b => (n = F(b)) < 0 ? a * n : a + n
f = a => b => o(o(F(a))(b))
```
```
f(a)(b)(c)
| | |
| | +-- 'b' argument of the function returned by the outer call to 'o'
| +----- 'b' argument of the function returned by 'f'
+-------- 'a' argument of 'f'
```
### Test cases
```
let f =
a=>b=>(o=a=>b=>(n=F(b))<0?a*n:a+n)(o((F=n=>'5445054524413452545'[n]-3)(a))(b))
console.log(f(3)(4)(4)) // => 18
console.log(f(4)(4)(4)) // => -27
console.log(f(12)(12)(12)) // => 0
console.log(f(0)(1)(2)) // => 4
console.log(f(6)(4)(5)) // => -1
console.log(f(15)(1)(18)) // => 2
console.log(f(18)(6)(11)) // => -6
```
[Answer]
# Befunge, ~~74~~ 73 bytes
```
>&:0`!#^_1g68*-^:0`!#v_+
^2112-212/11.012/212 >*
^ @.$< >">"35*0p
```
[Try it here!](http://www.quirkster.com/iano/js/befunge.html) It's weird that my code works on this one interpreter only.
The second row basically contains all of the values from the table. The non-numeric values are actually negative values as they come before the digits on the ASCII table. There's a bit of logic there that determines if the number is negative or not, and if it is, this number is multiplied by the result.
The right side of the third row initializes the first number. If I didn't have to do that, I could save a lot of bytes.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes
```
•6SÚ²ÄOÕ6BS3-©¹è|v®yèD0‹i*ë+
```
[Try it online!](https://tio.run/nexus/05ab1e#@/@oYZFZ8OFZhzYdbvE/3AziOQUb6x5aeWjn4RU1ZYfWVR5e4WLwqGFnptbh1dr//5twASEA "05AB1E – TIO Nexus")
```
•6SÚ²ÄOÕ6BS3-© # Push [2, 1, 1, 2, -3, 2, 1, 2, -1, 1, 1, -2, 0, 1, 2, -1, 2, 1, 2] and store.
¹è # Get first score.
|v # Iterate through remaining scores.
®yèD0‹i*ë+ # Push score list, grab relevant score.
# If negative, multiply, else add.
```
This actually works for as many or as few inputs as you'd like, so you can have cars with 4 or more traits or cars with just 2. This was not intentional, just how it ended up.
[Answer]
# PHP, 128 Bytes
```
$i="5445054524413452545";[,$a,$b,$c]=$argv;echo(bc.($i[$c]-3<0?mul:add))((bc.($i[$b]-3<0?mul:add))($i[$a]-3,$i[$b]-3),$i[$c]-3);
```
## PHP, 138 Bytes
```
$d=decbin(506743);$i="5445054524413452545";[,$a,$b,$c]=$argv;echo(bc.($d[$c]?add:mul))((bc.($d[$b]?add:mul))($i[$a]-3,$i[$b]-3),$i[$c]-3);
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/b0cf8e0192ca8f8200665b8ac85dbc2f674ea22b)
Expanded
```
$d=decbin(506743);
$i="5445054524413452545";
[,$a,$b,$c]=$argv;
echo(bc.($d[$c]?add:mul))((bc.($d[$b]?add:mul))($i[$a]-3,$i[$b]-3),$i[$c]-3);
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~123~~ ~~110~~ 107 bytes
```
a,b,c=input()
s=[int(i)-3for i in'05445054524413452545']
n=s[a]
for i in s[b],s[c]:n=[n*i,n+i][n>0]
print n
```
[Try it online!](https://tio.run/nexus/python2#NYwxDoMwEAR7v8IdEC4SBlsokZyPnK4ApEjXLJYN73fcpNmZYrR1o52OqEj31Q@mRFZcvQ7P5Xtmq1bRTcH70CbM3ruloWknBrHwJuaf2cK7UOFD3oiMhxJGFcZnEpNyO7Wo1b1oJTf/AA "Python 2 – TIO Nexus")
---
-3 bytes thanks to @mathjunkie
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~43~~ 38 bytes
```
q~[YXXY-3YXYWXX-2TXYWYXY]f={_W>42+c~}*
```
There might be a way to compress the list further...
Uses 0-based indexing.
[Try it online!](https://tio.run/nexus/cjam#@19YFx0ZERGpaxwZERkeEaFrFAKkgezYNNvq@HA7EyPt5Lparf//o00UgDAWAA "CJam – TIO Nexus")
**Explanation**
This program makes use of the fact that a value is multiplicative instead of additive if and only if its negative.
```
q~ e# Get the list from input
[...] e# Push the list of values for each ingredient. T=0, W=-1,
e# X=1, Y=2.
f= e# Get the elements at the given indices
{ e# Reduce over this block:
_W> e# Check if the second number is > -1 (returning 0 or 1)
42+c e# Add the result to 42 and cast to a char.
e# (ASCII 42 is * and 43 is +)
~ e# Eval the char (* is multiply, + is add)
}* e# (end block)
```
[Answer]
# Lua, ~~140~~ 131 bytes
```
i={2,1,1,2,-3,2,1,2,-1,1,1,-2,0,1,2,-1,2,1,2}function f(a,b,c)loadstring(("print("..i[a].."+"..i[b].."+"..i[c]..")"):gsub('%+%-','*-'))()end
```
```
i={2,1,1,2,-3,2,1,2,-1,1,1,-2,0,1,2,-1,2,1,2}function f(a,b,c)x,y,z=i[a],i[b],i[c]v=y>0 and x+y or x*y;print(z>0 and v+z or v*z)end
```
[Answer]
# JavaScript, 85 72 bytes
```
a=a=>eval(a.map(x=>(b="5445054524413452545"[x]-3,b<0?"*":"+")+b).join``)
```
Takes input in format `[a,b,c]`
-13 bytes thanks to ETHproductions
[Answer]
# R, ~~125~~ 123 bytes
```
function(a,b,c){v=c(5,4,4,5,0,5,4,5,2,4,4,1,3,4,5,2,5,4,5)-3
o=rep("+",19)
o[v<0]="*"
get(o[c])(get(o[b])(v[a],v[b]),v[c])}
```
Anonymous function that takes three integers as input. Defines a list of values and operations, and then just evaluates the ones called by the input, i.e. `o3(o2(v1,v2),v3)`. There's almost definitely a golfier way to do this!
**Update:** after some re-working, I have an alternative, also **123 bytes**. Again, an anonymous function, but takes input as a single vector of three values. Uses the same approach, defining a list of values and operations and evaluating it.
```
function(x,f=c(sum,prod)[x[-1]%in%c(5,9,12,16)+1],s=c(5,4,4,5,0,5,4,5,2,4,4,1,3,4,5,2,5,4,5)[x]-3)f[[2]](el(f)(s[-3]),s[3])
```
[Answer]
# Haskell, ~~186~~ ~~116~~ ~~112~~ 108 bytes
```
o x|x<0=(*)|0<1=(+)
v=(map((-51+).fromEnum)"95445054524413452545"!!)
w [x,y,z]=(o z)((o y)x y)z
k=w.map v
```
Main function is `k`. New to Code Golf so I am sure there are a few bytes I could shave off with clever use of `$` operator versus parentheses. I will probably update the answer as I continue to find improvements.
Essentially the program can be broken down like this:
* v is a function that takes a 1 based index and returns the value of that food id.
* o is a function that takes the food value and returns the appropriate operator (Eg. negative values are always `*` where positive values are always `+`)
* w is a function that takes a List of 3 partial functions of `v` mapped to input integers and fetches the appropriate operations and values from each and returns the proper output.
* k is the main function in point free style that maps v to input and composes this list for w to return the output.
**UPDATE**
Special thanks for pointing out the fromEnum trick! That worked out nicely. Also I missed the part in the rules that stated an acceptable solution could be a function that takes a list of integers. That saved a tremendous amount of work.
**UPDATE 2**
As per other suggestions, shaved a handful of bytes by reordering operations, creating an else guard that always evaluates to True, and a pattern matching on W that pattern matches on a List of 3 elements. Thanks for the suggestions!
**UPDATE 3**
Another thanks to Laikoni for pointing out more code golf rules that I was not aware of. Also mapping v to my input to create a list of partially applied functions was a phenomenal idea and saved me 4 additional bytes!
[Answer]
## Haskell, ~~92~~ 87 bytes
```
x#y|x<0=(y*)|0<1=(y+)
k[x,y,z]=z#z$y#x$y
k.map([read[q]-3|q<-"95445054524413452545"]!!)
```
[Try it online!](https://tio.run/nexus/haskell#XYvLCoMwEEX3fsX4WGgbi4kZi2C@JGQhtIKIouIiEf/dji3ZdDF3LodzTxu7wzaFSt0tO4qGU7lnwaAtc2w3ao/3xMU2cUGnhsfYzqle3@1LLyYvj6XJoxqlxAIlCil5SY9qZMIwO8e2n0DBvPbTBgnQFroAQIOWDACQAg0BBhr/AS8Z/M6DyxAUHjz9pPJGxb4Grz2oCZDGxQXM@QE "Haskell – TIO Nexus")
Based on @maple\_shaft's answer, I just factorized it a bit.
Thanks to @Laikoni for 5 bytes!
[Answer]
# C, ~~171~~ 161 bytes
```
#include<stdio.h>
r,z[3],*a=z,i;f(x){i?x<0?r*=x:(r+=x):(r=x);}main(){scanf("%d %d %d",a,a+1,a+2);for(;i++<3;f("05445054524413452545"[*a++]-51));printf("%d",r);}
```
[Answer]
# 8086 machine code, 62 bytes
```
00000000 be 3b 01 31 c0 86 c4 ac e8 0a 00 81 fe 3e 01 72 |.;.1.........>.r|
00000010 f4 b4 4c cd 21 bb 32 01 d0 e8 d7 73 03 c0 e0 04 |..L.!.2....s....|
00000020 c0 f8 04 e3 05 31 c9 c3 86 c4 78 03 00 e0 c3 f6 |.....1....x.....|
00000030 ec c3 21 12 d2 12 f1 1e 01 2f 12 00 00 00 |..!....../....|
0000003e
```
The last three bytes contain the (zero-indexed) input. Hey, you told me I could use the most convenient input format. In this case, that's hardcoding!
Output is the error code returned to the shell.
How it works:
```
| org 0x100
| use16
be 3b 01 | mov si, input ; source = input
31 c0 | xor ax, ax ; clear ax
86 c4 | @@: xchg al, ah ; swap al/ah (ah = total value)
ac | lodsb ; al = *si++
e8 0a 00 | call fn
81 fe 3e 01 | cmp si, input+3 ; end of input?
72 f4 | jb @b ; repeat if not
b4 4c | mov ah, 0x4c ; dos function: exit with al=error code
cd 21 | int 0x21 ; syscall
|
bb 32 01 | fn: mov bx, table ; pointer to lookup table
d0 e8 | shr al, 1 ; divide input by 2
d7 | xlatb ; al = *(bx + al)
73 03 | jnc @f ; skip next instruction if input was odd
c0 e0 04 | shl al, 4 ; shift low nibble to high nibble
c0 f8 04 | @@: sar al, 4 ; shift high nibble to low nibble with sign-extension
e3 05 | jcxz @f ; return if cx is non-zero (only happens for the first input)
31 c9 | xor cx, cx ; clear cx
c3 | ret
86 c4 | xchg al, ah ; swap al/ah (al = total value)
78 03 | @@: js @f ; multiply if negative, add if positive
00 e0 | add al, ah ; al = al+ah
c3 | ret
f6 ec | @@: imul ah ; ax = al*ah
c3 | ret
21 12 d2 12 | table db 0x21, 0x12, 0xd2, 0x12, 0xf1, 0x1e, 0x01, 0x2f, 0x12
f1 1e 01 2f | ; each value is stored in a 4-bit nibble
12 |
00 00 00 | input db 3 dup(0)
```
] |
[Question]
[
Given a non-negative integer (`n`), create a function that returns `n` in alphabetical order, according to the literal spelling of each digit in `n`.
### Examples:
```
Input: 101
>> one, zero, one
>> one, one, zero
Output: 110
Input: 31948
>> three, one, nine, four, eight
>> eight, four, nine, one, three
Output: 84913
Input: 5544
>> five, five, four, four
>> five, five, four, four
Output: 5544
Input: 1234567890
Output: 8549176320
```
Note: the operations in the example are illustrative only and do not need to be included in the output. Only the alphabetically-sorted number needs to be returned.
This is code-golf, so the shortest code in bytes wins.
Edit: the input can be taken in any desired format that best suits your language, and the output can be produced similarly by returning from the function or printing. The input will always be a natural number (including 0) and will not contain leading 0's.
[Relevant OEIS entry](https://oeis.org/A057846) (A057846) found by @DomHastings
[Answer]
# [Perl 6](http://perl6.org), ~~32~~ 28 bytes
```
~~{+[~] .comb.sort: \*.Str.uniname}~~
{+[~] .comb.sort: *.uniname}
```
### Explanation:
```
{
# turn the following into a Numeric
+
# fold the following list using string concatenation operator
[~]
# split $_ into individual characters
# (implicit method call on implicit parameter)
.comb
.sort:
*.uniname # sort by the Unicode name of the character (digit)
}
```
### Test:
```
#! /usr/bin/env perl6
use v6.c;
use Test;
my @tests = (
101 => 110,
31948 => 84913,
5544 => 5544,
1234567890 => 8549176320,
);
# give the lambda a lexical name for clarity
my &int-sort = {+[~] .comb.sort: *.uniname}
plan 3 * @tests;
for @tests -> $_ ( :key($input), :value($expected) ) {
put '';
isa-ok $input, Int, "input ($input) is an Int";
my $output = int-sort $input;
is $output, $expected, .gist;
isa-ok $output, Int, "output ($output) is an Int"
}
```
```
1..12
ok 1 - input (101) is an Int
ok 2 - 101 => 110
ok 3 - output (110) is an Int
ok 4 - input (31948) is an Int
ok 5 - 31948 => 84913
ok 6 - output (84913) is an Int
ok 7 - input (5544) is an Int
ok 8 - 5544 => 5544
ok 9 - output (5544) is an Int
ok 10 - input (1234567890) is an Int
ok 11 - 1234567890 => 8549176320
ok 12 - output (8549176320) is an Int
```
[Answer]
## 05AB1E, ~~12~~ ~~11~~ 10 bytes
```
•OWÿ¾•vy†J
```
**Explained**
```
•OWÿ¾• # push sortorder (236719458)
v # for each number in sortorder
y† # filter to the front
J # join
# implicitly print
```
[Try it online](http://05ab1e.tryitonline.net/#code=4oCiT1fDv8K-4oCidnnigKBK&input=MzE5NDg)
Saved 1 byte thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan)
[Answer]
# JavaScript (ES6), 54
*Edit* same char count, but avoiding the global variable `z`
Input / output as strings
```
n=>[...n].sort((a,b)=>n[a]-n[b],n='9487216503').join``
```
**Test**
```
f=n=>[...n].sort((a,b)=>n[a]-n[b],n='9487216503').join``
function test() {
O.textContent=f(I.value)
}
test()
```
```
<input id=I type=number value=31948 oninput='test()'>
<pre id=O></pre>
```
[Answer]
## Haskell, ~~62 51~~ 44 bytes
As @nimi suggested, using a list comprehension is shorter than composing functions:
```
f x=0+read[a|a<-"8549176320",b<-show x,a==b]
```
For reference my version:
```
f n=read.(=<<)(\x->filter(==x)$show n)$"8549176320"
```
The pointfree version is a bit longer:
```
f=flip(read.)"8549176320".(=<<).flip(filter.(==)).show
```
Straightforward: Filter the digits in the correct order and then concatenate the result.
[Answer]
# Pyth, ~~12~~ 10 bytes
```
ox`C" Ȁ\0
```
Not sure if it can be golfed further. Input needs to be enclosed in quotes.
2 bytes saved thanks to @isaacg!
In pythonic pseudocode:
```
Q = input()
o Q sort(Q, key = lambda N:
`C" Ȁ\0 repr(base256toDec(" Ȁ\0"))
x N .index(N) # 8 being absent from the number yields -1
)
```
[Test it here](http://pyth.herokuapp.com/?code=ox%60C%22+%C2%BB%C3%84%5C0&test_suite=1&test_suite_input=%22101%22%0A%2231948%22%0A%225544%22&debug=0).
[Answer]
# Perl, 37 bytes
36 bytes code + 1 byte command line (-F)
```
say sort{8549176320=~/$b.*$a/||-1}@F
```
Usage example:
```
echo -n "04823" | perl -F -M5.010 entry.pl
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 19 bytes
```
Vt'8549176320'&m2$S
```
[**Try it online!**](http://matl.tryitonline.net/#code=VnQnODU0OTE3NjMyMCcmbTIkUw&input=MzE5NDg)
### Explanation
```
V % Implicitly input number. Convert to string (¹)
t % Push copy of (¹)
'8549176320' % Push this string (²), which defines order
&m % Indices (³) of each element of (¹) in (²)
2$S % Sort copy of (¹) according to (³). Implicitly display
```
[Answer]
# Jelly, 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“U1°ŀ”OṾf@€
```
[Try it here.](http://jelly.tryitonline.net/#code=4oCcVTHCsMWA4oCdT-G5vmZA4oKs&input=&args=IjMxOTQ4Ig)
## Explanation
```
“U1°ŀ”O Get the Unicode ordinals of “U1°ŀ”
(all of which are coincidentally single bytes
in the Jelly code page!)
The result is [85, 49, 176, 320].
Ṿ Uneval. This gets us the string “85,49,176,320”.
f@€ For each char in this string, extract all chars
from the first command line argument that
equal it.
```
[Answer]
# Mathematica ~~35 78~~ 47 bytes
31 bytes saved thanks to a suggestion by LIAMnYP!
```
FromDigits@SortBy[IntegerDigits@#,IntegerName]&
```
`IntegerDigits` breaks up the number into digits which are then sorted according to their names in English. `FromDigits` assembles the digits into a base-10 number.
---
```
FromDigits@SortBy[IntegerDigits@#,IntegerName]&[1234567890]
```
8549176320
[Answer]
# C, ~~142~~ ~~141~~ 117
Pass parameter as `long long *` to `f()`; the function modifies the parameter:
```
f(long long*n){char*c="8549176320",g[10]={0};for(;*n;*n/=10)++g[*n%10];for(;*c;++c)for(;g[*c-48]--;*n=*n*10+*c-48);}
```
`long long` is necessary since the last test case overflowed an `int` when sorted.
[Answer]
## Python 2 - 95 bytes
```
def s(n):
l=list("8549176320")
return "".join(sorted(list(n),key=lambda x: l.index(x)))
```
Attempting further golfing...I think the line 2 is unnecessary and this can become 1 lambda.
EDIT: 49 char version in comments, thx to xnor and vaultah for help.
[Answer]
**-- Oracle 11 (SQL): 164 bytes**
```
SELECT LISTAGG(DECODE(s,0,'zero',TO_CHAR(TO_DATE(s,'j'),'jsp')),',')WITHIN GROUP(ORDER BY 1)FROM(SELECT SUBSTR(&1,level,1)s FROM dual CONNECT BY LEVEL<=LENGTH(&1));
```
**Long form and explanation**
```
SELECT LISTAGG(DECODE(s,0,'zero',TO_CHAR(TO_DATE(s,'j'),'jsp')),',') WITHIN GROUP (ORDER BY 1)
FROM ( SELECT SUBSTR(&1,level,1)s FROM dual
CONNECT BY LEVEL <= LENGTH(&1)
);
```
Get the input as parameter to script:
```
SELECT &1 FROM dual
```
"create" rows by using connect by based on length of input:
```
CONNECT BY LEVEL <= LENGTH(&1)
```
Rip out each digit from the string for each position:
```
SELECT SUBSTR(&1,level,1)s FROM dual
```
Convert the digit to Julian date, and back to Char to get spelling:
```
TO_CHAR(TO_DATE(s,'j'),'jsp')
```
Check for zero - special case.
```
DECODE(s,0,'zero'
```
Use LISTAGG function to concatenate rows back into a single row list, comma delimited, ordered alphabetically
```
LISTAGG(DECODE(s,0,'zero',TO_CHAR(TO_DATE(s,'j'),'jsp')),',') WITHIN GROUP (ORDER BY 1)
```
Always fun trying to tweak SQL for things like this ... :) really tests my knowledge of the bugger ...
[Answer]
# Ruby, 60 bytes
```
->n{n.to_s.chars.sort_by{|c|'8549176320'.index c}.join.to_i}
```
[Answer]
# Racket, ~~142~~ 130 bytes
```
(λ(n)(string->number(list->string(sort(string->list(~a n))char<? #:key(λ(m)(string-ref "9487216503"(-(char->integer m)48)))))))
```
Of which conversions are ~~more than~~ *almost* half of the length (~~76~~ 64 bytes).
[Answer]
# TSQL, 260 bytes
Used reversed bubble sort to avoid refering to the length, to save some bytes
**Golfed:**
```
DECLARE @ varchar(99)=101
,@i INT=99,@j INT=98WHILE @i>1SELECT
@=IIF(CHARINDEX(x,'598327614')>CHARINDEX(y,'598327614'),STUFF(STUFF(@,@j,1,x),@i,1,y),@),@i-=IIF(@j=1,1,0),@j=IIF(@j=1,@i,@j-1)FROM(SELECT
SUBSTRING(@,@i,1)x,SUBSTRING(@,@j,1)y)z
PRINT @
```
**Ungolfed:**
```
DECLARE @s BIGINT=1234567890
DECLARE @ char(99)=@s,@i INT=99,@j INT=98
WHILE @i>1
SELECT
@=IIF(CHARINDEX(x,'236719458')>CHARINDEX(y,'236719458'),
STUFF(STUFF(@,@j,1,x),@i,1,y),@),
@i-=IIF(@j=1,1,0),
@j=IIF(@j=1,@i,@j-1)
FROM(SELECT SUBSTRING(@,@i,1)x,SUBSTRING(@,@j,1)y)z
PRINT CAST(@ as bigint)
```
Insisting on using integer types as input and output added 37 bytes
[Answer]
# ClojureScript, 45 bytes
```
#(apply str(sort-by(vec"9487216503")(str %)))
```
Uses some screwy string->int conversion from Javascript leak through, so it's not valid Clojure.
[Answer]
## Firebird, 317 bytes
**Golfed:**
```
select list(s,'')from(with recursive q as(select 1 p,substring(:a from 1 for 1)s from rdb$database q union all select q.p+1 p,substring(:a from q.p+1 for 1)s from q where q.p<char_length(:a))select s from q order by iif(s=8,0,iif(s=5,1,iif(s=4,2,iif(s=9,3,iif(s=1,4,iif(s=7,5,iif(s=3,7,iif(s=2,8,iif(s=0,9,6))))))))))
```
**Ungolfed:**
```
select list(s, '')
from (
with recursive q as (
select 1 as p, substring(:a from 1 for 1) s
from rdb$database q
union all
select q.p + 1 as p, substring(:a from q.p + 1 for 1) as s
from q
where q.p < char_length(:a)
)
select s
from q
order by iif(s = 8, 0,
iif(s = 5, 1,
iif(s = 4, 2,
iif(s = 9, 3,
iif(s = 1, 4,
iif(s = 7, 5,
iif(s = 3, 7,
iif(s = 2, 8,
iif(s = 0, 9, 6)))))))))
)
```
There's no split functionality in Firebird. Instead I created a recursive query to get the next character over and over. Then reselect those while sorting by our proper order. Finally concatenate those results back together in a list. Override the default comma delimiter with blank. I could save 11 bytes by creating a new dummy table instead of `rdb$database` but I thought that may be against the rules.
[Answer]
## ZX Spectum, machine code, ~~53~~ ~~48~~ ~~47~~ ~~45~~ 44 bytes
```
org 49200 ; #c030
; table converts ascii to alfabetical order
; start from BASIC with any number as : PRINT "1234567890" AND USR 49208
```
`convtab defb 249 ; zero
defb 244 ; one
defb 248 ; two
defb 247 ; three
defb 2+205 ; four
defb 1+205 ; five
defb 246 ; six
defb 245 ; seven
; defb 0 ; eight
; defb 3 ; nine
; last 2 conversions hidden in call-command`
```
start Call #2bf1 ; fetch stackindex
call #2ab2 ; store back
ld h,#c0 ; set highbyte of table
Sort Push de
loop ld b,d
ld c,e
inc de
ld a,(bc) ; fetch number
Ld l,a
ld a,(de)
cp 34 ; endmarker "
Jr z,exit ; end reached?
push hl ; save number
ld l,a
Ld a,(hl) ; convert second number
pop hl
cp (hl) ; compare numbers
jr nc,loop ; in order, no swap
swap ld a,(bc) ; swap original numbers
ld l,a
ld a,(de)
ld (bc),a
ld a,l
ld (de),a
Exit pop de
Ret z
jr sort ; check number for order
```
[Answer]
# Factor, 128
```
[ 10 base> [ 48 - ] { } map-as dup [ number>text ] map zip [ second first ] sort-with [ first ] map [ 48 + ] ""map-as 10 >base ]
```
Hooray for builtins! :D
[Answer]
# PHP, 126 bytes
As far as I know php doesn't have any builtins that would really help with this (the best I could do using a usort(str\_split()) was 5 bytes longer) so the only thing I'm happy within this answer is the games played with $i to save a couple of bytes on the itteration.
```
<?php for($i=-1;$i<9;)$a[++$i]=preg_replace("/[^$i]/","",$argv[1]);array_multisort([9,4,8,7,2,1,6,5,0,3],$a);echo implode($a);
```
[Answer]
# APL, 23 bytes
```
{⍎n['8549176320'⍋n←⍕⍵]}
```
Explanation:
* `n←⍕⍵`: get the string representation of `n` and store it in `n`
* `'8549176320'⍋`: find a permutation of `n` that sorts `n` given the order `8549176320`.
* `n[`...`]`: reorder `n` by that permutation
* `⍎`: evaluate the result (to turn it back into a number)
[Answer]
# Clojure, 53 bytes
Well, list comprehension idea from Haskell solution seems to be the shortest:
```
#(apply str(for[p"8549176320"b(str %):when(= p b)]p))
```
My original approach is 1 byte longer:
```
#(apply str(sort-by(zipmap"549176320"(range))(str %)))
```
You can see both function online here: <https://ideone.com/afac5n>
[Answer]
## Common Lisp, 104
```
(lambda(n)(#1=parse-integer(sort(format()"~A"n)'string<= :key(lambda(u)(format()"~R"(#1#(string u)))))))
```
### Ungolfed
```
(lambda (n)
(parse-integer
(sort (format nil "~A" n)
#'string<=
:key (lambda (u) (format nil "~R" (parse-integer (string u)))))))
```
Convert integer as string, sort characters using the `string<=` comparison while using a custom `:key` function which converts a given character as the English representation of the numerical value it represents. Usually I would not use a key function which does as much as this one, but it costs less in bytes than decorate/sort/undecorate.
[Answer]
# Python 3, 234 bytes
This is a direct translation of [my Factor answer](https://codegolf.stackexchange.com/a/84840/46231), just for fun.
```
def f(n):
s=list(map(int,str(n)))
return int("".join(list(map(str,list(map(lambda x:x[1],sorted(list(zip(list(map(lambda t:{0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine"}[t],s)),s)))))))))
```
The semantics of the evaluation of "lazy" map and zip objects is the most subtle hard-to-find-bug-inducing piece of genuine horse excrement in the universe. Sometimes, `s = map(f, x)` won't allow `s` to be used properly or at all.
[Answer]
## Pyke, 14 bytes
```
.#uЀB`@
```
[Try it here!](http://pyke.catbus.co.uk/?code=.%23u%04%D0%80%1B%05%EF%86%93B%60%40&input=%221234567890%22)
[Answer]
## C, 80 bytes
Takes a string containing a number in base 10 and prints to `stdio`:
```
F(char*i){for(char*p,d,*o="8549176320";*o;++o)for(p=i;d=*p++;d-*o||putchar(d));}
```
[Answer]
## Python 2.7.11, 67 bytes
```
lambda n:''.join(sorted(list(n),key=lambda s:"9487216503"[int(s)]))
```
Takes a string as input and outputs a string.
[Answer]
# Python 3, 74 bytes
```
lambda x:''.join(i[1]for i in sorted(['9487216503'[int(j)],j]for j in x))
```
[Answer]
# [PHP](https://php.net/), 107 bytes
```
function($a){usort($a,function($a,$b){return($z=array_flip([8,5,4,9,1,7,6,3,2,0]))[$a]-$z[$b];});return$a;}
```
[Try it online!](https://tio.run/##TY0xa8MwEIV3/YojaLDgCnYdNw5KyFToUGh2VQTFkbEhjYQsD43xb3fPcYfc9N69u@/5xk@7g2888AB7mOr@VsXW3RJuxNB3LkRS@LRFfhZDsLEP5O57E4L5PdXX1ieqxALXuMUMN/iGOb5iqoVQ3OgXflf8rOUo5PLKjRwnyXi0XeyoVzEAlWGKmcZZ5gTZEqxcbPEgrxeTETgnW1DJBku6SynQkrHaBWuqJoF/rulIgYCB3mzVOGh//NVdbPJYI6xgnu@4wqckLOmcHz@Op/evT8lGNv0B "PHP – Try It Online")
Uses a user-defined comparison function to adjust the sorting order.
***Output***
```
101 110
31948 84913
5544 5544
1234567890 8549176320
```
] |
[Question]
[
Write a program that prints out all the good rational approximations of pi with denominator < 1000000, in increasing denominator order. `a/b` is a "good rational approximation" of pi if it is closer to pi than any other rational with denominator no bigger than `b`.
The output should have 167 lines total, and start and end like this:
```
3/1
13/4
16/5
19/6
22/7
179/57
...
833719/265381
1146408/364913
3126535/995207
```
Shortest program wins.
[Answer]
## Golfscript, 71 70 69 chars
```
2\!:^2^..292^15.2/3]{(.)2/.9>+{\+.((}*;.}do;;]-1%{^0@{2$*+\}/"/"\n}/;
```
(Assumes that you don't pass it anything on stdin)
I don't want to hear any more whinging by people who don't have built-in constants for pi. I don't even have floating point numbers!
See <http://en.wikipedia.org/wiki/Continued_fraction#Best_rational_approximations> for the background.
```
# No input, so the stack contains ""
2\!:^2^..292^15.2/3]
# ^ is used to store 1 because that saves a char by allowing the elimination of whitespace
# Otherwise straightforward: stack now contains [2 1 2 1 1 1 292 1 15 7 3]
# Pi as a continued fraction is 3+1/(7+1/(15+1/(...)))
# If you reverse the array now on the stack you get the first 10 continuants followed by 2
# (rather than 3)
# That's a little hack to avoid passing the denominator 1000000
{
# Stack holds: ... [c_n c_{n-1} ... c_0]
(.)2/.9>+
# Stack holds ... [c_{n-1} ... c_0] c_n (1+c_n)/2+((1+c_n)/2 > 9 ? 1 : 0)
# (1+c_n)/2 > 9 is an ad-hoc approximation of the "half rule"
# which works in this case but not in general
# Let k = (1+c_n)/2+((1+c_n)/2 > 9 ? 1 : 0)
# We execute the next block k times
{
# ... [c_{n-1} ... c_0] z
\+.((
# ... [z c_{n-1} ... c_0] [c_{n-1} ... c_0] z-1
}*
# So we now have ... [c_n c_{n-1} ... c_0] [(c_n)-1 c_{n-1} ... c_0] ...
# [(c_n)-k+1 c_{n-1} ... c_0] [c_{n-1} ... c_0] c_n-k
;
# Go round the loop until the array runs out
.
}do
# Stack now contains all the solutions as CFs in reverse order, plus two surplus:
# [2 1 2 1 1 1 292 1 15 7 3] [1 2 1 1 1 292 1 15 7 3] ... [6 3] [5 3] [4 3] [3] [2] []
# Ditch the two surplus ones, bundle everything up in an array, and reverse it
;;]-1%
# For each CF...
{
# Stack holds ... [(c_n)-j c_{n-1} ... c_0]
# We now need to convert the CF into a rational in canonical form
# We unwind from the inside out starting with (c_n)-j + 1/infinity,
# representing infinity as 1/0
^0@
# ... 1 0 [c_n-j c_{n-1} ... c_0]
# Loop over the terms of the CF
{
# ... numerator denominator term-of-CF
2$*+\
# ... (term-of-CF * numerator + denominator) numerator
}/
# Presentation
"/"\n
# ... numerator "/" denominator newline
}/
# Pop that final newline to avoid a trailing blank line which isn't in the spec
;
```
[Answer]
## Mathematica, ~~67~~ 63
This isn't going to be fast, but I believe it is technically correct.
```
Round[π,1/Range@1*^6]//.x_:>First/@Split[x,#2≥#&@@Abs[π-{##}]&]
```
`Round[π, x]` gives the closest fraction to π in steps of `x`. This is "listable" so `Round[π,1/Range@1*^6]` does this for all fractions down to `1/10^6` in order. The resulting list with many "bad" rational approximations is then repeatedly (`//.`) processed by removing any elements which are farther from π than the preceding one.
[Answer]
## Perl, 77 chars
```
$e=$p=atan2 0,-1;($f=abs$p-($==$p*$_+.5)/$_)<$e&&($e=$f,say"$=/$_")for 1..1e6
```
A minor challenge is that Perl doesn't have a built-in *π* constant available, so I first had to calculate it as `atan2(0,-1)`. I'm sure this will be beaten by languages more suited for the job, but it's not bad for a language mainly designed for text processing.
[Answer]
## JS (95 characters)
```
for(i=k=1,m=Math;i<1e6;i++)if((j=m.abs((x=m.round(m.PI*i))/i-m.PI))<k)k=j,console.log(x+'/'+i)
```
It does print 167 lines.
[Answer]
## Python, 96 93 89 characters
```
a=b=d=1.
while b<=1e6:
e=3.14159265359-a/b;x=abs(e)
if x<d:print a,b;d=x
a+=e>0;b+=e<0
```
### Python, 95 93 characters, different algorithm
```
p=3.14159265359;d=1
for a in range(3,p*1e6):
b=round(a/p);e=abs(p-a/b)
if e<d:print a,b;d=e
```
**note:** It was less characters to write `p=3.14159265359;` than `from math import*`. Darn those wordy imports!
[Answer]
### Ruby 1.9, 84 characters
```
m=1;(1..1e6).map{|d|n=(d*q=Math::PI).round;k=(n-q*d).abs/d;k<m&&(m=k;puts [n,d]*?/)}
```
[Answer]
## C99, 113 characters
```
main(d,n){double e=9,p=2*asin(1),c,a=1;for(;n=d*p+.5,c=fabsl(p-a*n/d),d<1e6;++d)c<e&&printf("%d/%d\n",n,d,e=c);}
```
Need to compile with `-lm`, and probably full of undefined behaviour, but it works for me.
[Answer]
### Scala - 180 chars
```
import math._
def p(z:Int,n:Int,s:Double):Unit=
if(n==1e6)0 else{val q=1.0*z/n
val x=if(abs(Pi-q)<s){println(z+"/"+n)
abs(Pi-q)}else s
if(Pi-q<0)p(z,n+1,x)else p(z+1,n,x)}
p(3,1,1)
```
// ungolfed: 457
```
val pi=math.Pi
@annotation.tailrec
def toPi (zaehler: Int = 3, nenner: Int = 1, sofar: Double=1): Unit = {
if (nenner == 1000000) ()
else {
val quotient = 1.0*zaehler/nenner
val diff = (pi - quotient)
val adiff= math.abs (diff)
val next = if (adiff < sofar) {
println (zaehler + "/" + nenner)
adiff
}
else sofar
if (diff < 0) toPi (zaehler, nenner + 1, next)
else toPi (zaehler + 1, nenner, next)
}
}
```
The tailrec annotation is just a check, to verify, that it is tail-recursive, which is often a performance improvement.
[Answer]
# Mathematica 18 17 chars
I chose to use, as a measure of "best", the number of terms in a continued fraction representation of π. By this criterion, the best rational approximations of π are its convergents.
There are 10 convergents of π with a denominator less than one million. This is fewer than the requested 167 terms, but I am including it here because it may be of interest to others.
```
Convergents[π, 10]
(* out *)
{3, 22/7, 333/106, 355/113, 103993/33102, 104348/33215, 208341/66317,
312689/99532, 833719/265381, 1146408/364913}
```
If you really want to see the denominator for the first convergent, it will cost an additional 11 characters:
```
Convergents[π, 10] /. {3 -> "3/1"}
(* out *)
{"3/1", 22/7, 333/106, 355/113, 103993/33102, 104348/33215,
208341/66317, 312689/99532, 833719/265381, 1146408/364913}
```
---
For those who are interested, the following shows the relations among the convergents, partial quotients, and continued fraction expression of convergents of π:
```
Table[ContinuedFraction[π, k], {k, 10}]
w[frac_] := Row[{Fold[(#1^-1 + #2) &, Last[#], Rest[Reverse[#]]] &[Text@Style[#, Blue, Bold, 14] & /@ ToString /@ ContinuedFraction[frac]]}];
w /@ FromContinuedFraction /@ ContinuedFraction /@ Convergents[π, 10]
```

Please excuse the inconsistent formatting of the continued fractions.
[Answer]
# C# 140 129 chars
```
double n=3,d=1,e=d;while(n<4e5){double w=n/d-Math.PI,a=Math.Abs(w);if(a<e){e=a;Console.WriteLine(n+"/"+d);}if(w>0)d++;else n++;}
```
Uncompressed code
```
var numerator = 3d;
var denominator = 1d;
var delta = 4d;
while (numerator < 4e5)
{
var newDelta = (numerator / denominator) - Math.PI;
var absNewDelta = Math.Abs(newDelta);
if (absNewDelta < delta)
{
delta = absNewDelta;
Console.WriteLine(string.Format("{0}/{1}", numerator, denominator));
}
if (newDelta > 0)
{
denominator++;
}
else
{
numerator++;
}
}
```
[Answer]
# J, 69 65
### New
```
]`,@.(<&j{.)/({~(i.<./)@j=.|@-l)@(%~(i:3x)+<.@*l=.1p1&)"0>:_i.1e3
```
Still a brute force approach but much faster and a tad shorter.
### Old
A simple "brute force":
```
(#~({:<<./@}:)\@j)({~(i.<./)@j=.|@-l)@(%~(i:6x)+<.@*l=.1p1&)"0>:i.1e3
```
make a list of `a/b`s and then discard those that are farther from π for some `b'<b`.
*Note: Change `1e3` to `1e6` for the full list. Go do something else and return later.*
] |
[Question]
[
>
> Edit 2020-11-06: This challenge has been edited with new provisions to encourage participation. The edits have been **bolded** for emphasis.
>
>
>
Welcome to a cops and robbers version of [Find an Illegal String](https://codegolf.stackexchange.com/questions/133486/find-an-illegal-string).
An *illegal string* is "a string of characters that cannot appear in any legal program in your programming language of choice" (from the linked post).
For this challenge, we will define an *almost illegal string*, which is a string of characters that is very hard, but not impossible, to include in a valid program.
## The Cops' Challenge
* Choose a programming language, and choose an 'almost illegal string' - this is a sequence of characters that is very hard to include in a valid program without causing it to error.
* Write a program that contains the 'almost illegal string' as a contiguous substring that does not error.
* **Optionally, you may also specify a set of banned characters. These are characters that do not appear in your program, except in the 'almost illegal string'. (Therefore: banned characters can still appear inside the almost illegal string)**
That's it! You will reveal the programming language, the almost illegal string, **and the set of banned characters**, and challenge robbers to write a program that contains the illegal string but does not error.
For the purposes of this challenge, we define 'does not error' as:
* Your program exits with exit code 0.
* Your program does not print any output to standard error.
* Your program may print anything to standard output, if you wish, but it does not have to.
* If (and only if) your language *always* prints output to standard error regardless of the program, such as debugging or timing information, you may instead design a program that *only* outputs this to standard error. If you are making use of this clause, mention it in your cop post.
## The Robbers' Challenge
Find an uncracked answer. Write a program in the language specified that contains as a contiguous substring the almost illegal string specified and does not error. **Your program may not use any character in the set of banned characters, unless it is part of the almost illegal string.** Your program does not need to be exactly what the cop had in mind. Post an answer to the robber's thread and leave a comment on the cops' answer to crack it.
## Clarifications
* If your cop answer requires a specific operating environment or version, you must specify this in your answer.
* The cop's almost illegal string that they reveal is to be interpreted with respect to the standard encoding for the language's interpreter. For most programs, this will be UTF8.
* Solutions should not take any input (via standard input, argv, or any other source) and may assume no such input is given.
* Solutions must terminate in a finite amount of time. This means entering an infinite loop and getting killed by TIO's 60 second timeout is not a valid solution.
* Cops should make sure if their almost illegal string contains leading or trailing newlines that it is very clear it does so. Robbers should carefully note any leading or trailing newlines in a cop's post.
## Formatting hint
The clearest way to include leading or trailing newlines is to use the backtick syntax for your post:
```
```
foo
```
```
Renders as:
```
foo
```
To remove any ambiguity, *explicitly mention* the leading/trailing newlines in your post.
## Scoring
After 10 days without a crack, a cop can mark their answer as *safe* and reveal their solution. Once the cop has revealed their solution, it is no longer able to be cracked.
Cops are scored based on the length (in bytes) of their almost illegal string in their safe answer(s), with lower being better.
Robbers are scored by the number of answers they crack, with higher being better.
---
## Example
### Python 3, 5 bytes
Illegal string:
```
"'1/0
```
Banned characters:
```
#'
```
### Python 3, cracks example's answer
Program:
```
""" "'1/0 """
```
The idea is that we can just comment out the string, since `"` is not banned.
[Answer]
# [Python 2](https://docs.python.org/2/), 5 bytes ([cracked by tsh](https://codegolf.stackexchange.com/a/214817/20260))
```
bin()
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PykzT0Pz/38A "Python 2 – Try It Online")
Banned: all characters *except* alphanumeric characters
```
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
```
So, you're allowed the above characters and nothing else (in addition to `bin()` itself).
(This idea isn't mine, I remember it from an earlier challenge, but I don't remember who deserves credit for it.)
[Answer]
# Haskell, 3 bytes
```
#"
```
(begins with a newline)
Disallowed charachters: `-`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes, [cracked by HyperNeutrino](https://codegolf.stackexchange.com/a/214815/66833)
```
¬´{
```
[Try it online!](https://tio.run/##y0rNyan8/5@L69Dq6v//AQ "Jelly – Try It Online")
You may not use newlines. Any other character/byte is fair game
---
My intended solution was any of the banned characters [here](https://codegolf.stackexchange.com/a/214816/66833) aside from `”`. Each of these characters cause the parsing of the link to break, meaning everything before them gets ignored:
[Try it online!](https://tio.run/##y0rNyan8/5@L69Dqao3//wE "Jelly – Try It Online")
[Answer]
# [Python 3](https://docs.python.org), 7 bytes, [cracked by @EasyasPi](https://codegolf.stackexchange.com/a/219334/94066)
Still not the intended answer, so I'm just revealing it. Scroll to the bottom to see it.
```
raise
```
### Banned characters
```
`TAB` "'(),.=[\]_{|}
```
Non-ASCII characters are all banned as well. [Try it online](https://tio.run/##K6gsycjPM/7/n6soMbM4lev/fwA "Python 3 – Try It Online") or [validate it online](https://tio.run/##tVRta@Q2EP5c/4ppDqpdSHzyi2x5YQ9KLoXQkkBv@6FkQxlJ49jUsYylTW5p@9tT2ZukR1@Ou7T1B9lja56X8YyGvW9snz3Uo72FBl3TtQra28GOHlyDqSii@ZN1z2/3ztNt9EcURWGJnTc0jms7UL9grw3dve53XceOgd2zZTSMbe8X7OJyc7aC8xp80wZAF@4Etu/24Om9B7vzw857Msewt7sR9Ij652lb299h15o4IEWvYL1eA8DJyUlYP/8ZXgWIzQf8d9h2Bn1re2gIg4sYfpzZrSG4sTTRw9FpiI5AUWfv4xniX6uIJoL1yBh7eAjLVbI6Sa7/F3@hdAd/tbX@o/5Q2Tv6r/wN6ByZ9WbcUdTWwLb9iK2jbc@gt35inSSsopAAjw1y@qc/vjqoNJPKKUfb3mNInHy1XUc32IHzIfcmtMaMc@D8Bjs3k2K/X@gnquA/2J4i9gUcbdlieRyvr7bb659@@fU3tvwUJY8CHCjsezKgGwwbQ1Hd3wm4b30Dh5GYezke9o8TAeigPhDW8f3YelpM@MtJ82HCFmyYZxOeMt88TxWkb75KPk3vXHEXygBhOu34D1U6xAe8ScA8@Au19@RmWUHzzteSLZdxQ@9Ne0POL5ZTIa/mnM@8WM0rUeoqlYYyXaalyVPOjZY6SSuZZzWJNEcUiGiyIleJKiUmSV1Skihtioodv4hWSF4kpcnqtMhIEpYc6zoXJRUF8oKjSKogRZCSWmlZV0glSoOoqUhTpfhLaQWvMiGDbixNmadSZkYhFyrDpFBp@EqyEmnJQ6QyQlGmgsqqUlgkRVG9lJZTlqW6rnKOCilPijQvdJVrnuW1VNxURS0wNxpV0INCmUpy5HmFGAouJLIXsF6vnpOe@vL7r0@/hfN3cH6xObt4e/YW3l1@98Pm/PLiy@kYglvcw2Cd/@DEjx@7lEJ3/hXvqc/nLv8oxsPv "Python 3 – Try It Online")!
## Some cracks that work without the banned chars
```
'''
raise'''
```
```
"""
raise"""
```
```
raise SystemExit
```
```
raise`TAB`SystemExit # originally posted by EasyasPi here, he found yet another loophole
```
```
raise\
SystemExit
```
```
raiser=3 # originally posted by EasyasPi on v1 of this challenge
```
# Intended Answer
>
>
> ```
> #coding:U7
> quit+ACgAKQ-
> raise
>
>
> ```
>
>
>
>
This works because
>
> the magic comment at the top sets the file encoding to UTF-7
>
>
>
and
>
> in UTF-7, characters can be encoded by first converting them to their UTF-16 binary representations, and concatenating them if there are multiple characters to be encoded. Here, we want to call `quit`, so we need to convert `()`. This becomes `0000 0000 0010 1000 0000 0000 0010 1001`. Next, we regroup them into groups of 6, to get `000000 000010 100000 000000 001010 01`, and pad the last group with trailing zeros (if necessary). In this case, we get `000000 000010 100000 000000 001010 010000`. Finally, we convert these to the corresponding Base64 characters (table [here](https://en.wikipedia.org/wiki/Base64#Base64_table_from_RFC_4648)), getting `ACgAKQ`, prepend a `+`, and append a `-`.
>
>
>
So,
>
> `()` in UTF-7 is `+ACgAKQ-`. We use this fact to bypass the banned `()` and call `quit` anyways, by replacing `()` with `+ACgAKQ-`. This exits the program before it can throw any errors.
>
>
>
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes, [cracked by Unrelated String](https://codegolf.stackexchange.com/a/214832/66833)
```
¬´{
```
[Try it online!](https://tio.run/##y0rNyan8/5@L69Dq6v//AQ "Jelly – Try It Online")
I'm giving Jelly another go, but with slightly more restrictions. You may not use `qu∆Å∆ò»§(∆à…¶∆ô…±…≤∆• † Ç»•` (the unimplemented commands in Jelly), `‚Äù` or newlines, as these make it *far* too trivial to crack (thanks to [HyperNeutrino](https://codegolf.stackexchange.com/users/68942/hyperneutrino) for showing that)
---
Neither HyperNeutrino's crack in the comments, nor Unrelated String's crack was my intended solution. Putting a `≈í` (or any of `√ê√Ü√ò≈ì√¶`) with nothing after it at the end causes the same behaviour as any of `qu∆Å∆ò»§(∆à…¶∆ô…±…≤∆• † Ç»•`, as they always expect to have a character after them. Without any character, they cause a break in the program chain, meaning that everything before them is ignored:
[Try it online!](https://tio.run/##y0rNyan8/5@L69Dq6qOT/v8HAA "Jelly – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 2 bytes, [cracked](https://codegolf.stackexchange.com/a/215202/86301) by Dominic van Essen
```
'"
```
[Try it online!](https://tio.run/##K/r/X13p/38A "R – Try It Online")
Banned characters (newlines are banned):
```
'"`#\qel
```
This bans the obvious cracks I can think of, but I wouldn't be surprised if you come up with a crack very different to what I intend.
[Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) [cracked](https://tio.run/##K/r/v7A0s0RD01pd6f9/AA) a first version of this challenge, and then a [second](https://tio.run/##K/r/v8K2KDUxxSczL7VYQ8dQk0td6f9/AA "R – Try It Online"); then [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) [cracked](https://tio.run/##K/r/Pz21RCOxoCi/IL9Yo7g0qbikSMNQx0DHQFMz2tDCwDxWU0PTWl3p/38A) a third version. I have added `qel` and newlines to the list of banned character to sidestep their cracks.
---
The solution I had in mind was
```
assign(intToUtf8(c(37,39,34,37)), c); 1 %'"% 2
```
[Try it online!](https://tio.run/##K/r/P7G4ODM9TyMzryQkP7QkzUIjWcPYXMfYUsfYRMfYXFNTRyFZ01rBUEFVXUlVwej/fwA "R – Try It Online")
The assign call creates a new binary operator, `%'"%`; it is equivalent to `"%'"%" <- c`. In R, you can create new operators of the form `%x%` where `x` is *any* string: `%}%`, `%$@%` and `%µ£$%` are all valid operator names. Here, the new operator is equal to the concatenation function `c` and so the output is the vector `1 2`.
Dominic's [crack](https://codegolf.stackexchange.com/a/215202/86301) doesn't define the operator; he simply buried it in a `try` call, which is also valid R code.
The trick used here means that any future attempt at an almost illegal string will probably have to ban the `%` character.
[Answer]
# Desmos, 9 bytes,
```
sort(3,2
```
Banned characters: New Lines
```
```
I'm hoping that most people are not familiar with Desmos here, so people wouldn't know what to try.
Note:
An expression in Desmos would be considered an error if it shows a "danger sign" next to the expression, like this:
[](https://i.stack.imgur.com/prrUc.png)
[Answer]
# [Rust](https://www.rust-lang.org/), 5 Bytes (Safe)
```
:! =1
```
Banned Characters:
```
|!/"'
```
A nightly compiler is used, you may pass any flags to rustc if you like.
---
[A crack by @EasyasPi](https://codegolf.stackexchange.com/a/219254/94093)
does work (and is brilliant), but I think because the question says "you must write a program that contains ...", if your code is not designed to run, it isn't a program :)
## The intended solution
The idea is to create a local variable that has the never type, call some functions on the integer 1 such that it becomes the never type.
However, with `!` as a banned character, we can't simply put the `#![feature(never_type)]` attribute on the top of the program. We must use an unstable rustc flag that allows us to inject crate-level attributes. The command to compile would be:
```
cargo rustc -- -Z crate-attr='feature(never_type, core_panic)'
```
Because closures (`|| something`) and the use of the `!` type outside are restricted, we must operate on the integer literal with provided functions. This is where the `core_panic` feature comes in and gives us a nice way to transform a `&str` into `!`. We know the start and the end, we can just put them together:
```
use std::io::stdout;
use core::panicking::panic_str;
use std::borrow::Borrow;
fn main() {
let a:! =1i8.checked_neg().as_ref().map(ToString::to_string).as_ref().map(Borrow::borrow).map(panic_str).unwrap();
}
```
[Answer]
# [Vim](https://www.vim.org), 4 bytes, cracked by [tail spark rabbit ear](https://codegolf.stackexchange.com/a/231255/100411)
```
<Esc><Esc>ZQ
```
This one is a bit more difficult than my other Vim one.
### Intended Solution:
>
> `i<C-o>:<C-r><Esc><Esc>ZQ`
>
>
>
[Answer]
# [Python 3](https://docs.python.org), 10 bytes, [cracked by The Fifth Marshal](https://codegolf.stackexchange.com/a/220920/46076)
```
?"""?'''?
```
## Banned characters
Alphanumeric, whitespace, and non-ASCII.
---
>
> The intended solution makes use of an interesting quirk in the Python parser.
>
>
>
Here's a hint if you want one:
>
> The hint is that there is no hint. (This isn't a joke. This is actually the hint.)
>
>
>
---
# Intended Answer
>
> Hexdump:
> ```
> 00000000: 2300 0a3f 2222 223f 2727 273f #..?"""?'''?
> ```
>
>
>
>
For some reason,
>
> the Python parser seems to ignore characters following null characters.
>
>
>
So,
>
> it ignores the newline after the `#␀`, therefore treating the `?"""?'''?` as part of the comment.
>
>
>
Fun fact: This was actually posted on the original Find an Illegal String challenge, but when I found a way to get around it, I decided to post it here.
[Answer]
# Ruby, 17 bytes, [cracked by Dingus](https://codegolf.stackexchange.com/a/214869/92901)
```
=end
#{"""'}
=end
```
(no newline at start)
Disallowed charachters: `N`
[Answer]
# Julia, 5 bytes, [Cracked by Dingus](https://codegolf.stackexchange.com/a/214877/92901)
```
?""":
```
Disallowed charachters: `#`
[Answer]
# Julia, 6 bytes
```
?"""Óàã:
```
There is a zero width space before the `:`
Disallowed characters: `#`
[Answer]
# [Python 3](https://docs.python.org/3/), 13 bytes, [Cracked by EasyasPi](https://codegolf.stackexchange.com/a/218679/94093)
```
int(–ê,–í,–°)
```
Banned Characters: All ascii characters except `2()~+` and newlines. `'"#=` are banned.
```
!"#$%&'*,-./013456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}
```
The solution makes use of an odd python 3 feature.
[Try it online!](https://tio.run/##K6gsycjPM/7/PzOvROPCBJ0Lk3QuLNT8/x8A "Python 3 – Try It Online")
[Answer]
# nasm, 4 bytes, safe
```
[al]
```
Banned characters:
```
;"`'%#
```
## Solution:
>
> `section` is, as far as I know, the only thing in NASM which accepts an arbitrary string without quotes.
>
>
> ```
> section [al]
> section .text
> global _start
> _start:
> mov eax, 60
> syscall
> ```
>
> [Try it online!](https://tio.run/##SywuTs1NyqnUzUsszv3/XwEKilOTSzLz8xSiE3NiudAF9UpSK0rgouk5@UmJOQrxxSWJRSVcEMoKLpubXwamUxMrdBTMDBBmVRYnJ@bkKPz/DwA "Assembly (nasm, x64, Linux) – Try It Online")
>
>
>
Stop giving me these assembly ones for free. üòî
[Answer]
# [Python 3](https://docs.python.org/3/), 3 bytes, [Cracked by user](https://codegolf.stackexchange.com/a/219498/95792)
I can't believe I missed that obvious loophole! I am adding a slightly revised version of my code that should avoid this.
## New Answer, 4 bytes, [Cracked by Unrelated String](https://codegolf.stackexchange.com/a/219508/85334)
```
1=2
```
Note: There is a `space` at the beginning of the code.
Banned characters: All non-ascii characters, quotes, and #.
```
"'#
```
[Try it online!](https://tio.run/##K6gsycjPM/7/X8HQ1uj/fwA "Python 3 – Try It Online")
## Old Answer, 3 bytes, [Cracked by user](https://codegolf.stackexchange.com/a/219498/95792):
```
1=2
```
Banned characters: All non-ascii characters, quotes, and #.
```
"'#
```
[Try it online!](https://tio.run/##K6gsycjPM/7/39DW6P9/AA "Python 3 – Try It Online")
### My intended solution for both posts:
```
foo : 1=2
```
[Answer]
# Javascript, 7 bytes, [cracked by Makonede](https://codegolf.stackexchange.com/a/220576/16484)
```
...void
```
# Javascript, 8 bytes, [cracked by Makonede](https://codegolf.stackexchange.com/a/220578/16484)
Note one trailing space
```
...void
```
Banned characters:
* all comments: `//`, `/**/`
* all strings: `""`, ````, `''`
* curlies: `{}`
* brackets: `[]`
* asterisk: `*`
* the letter `w`
Clarifications: My cop answer works in a browser environment, but there are probably solutions in Node too.
[Answer]
# Ruby, 17 bytes
```
=end
#{"""'}
=end
```
Disallowed characters: `N`,`%`
This time I made it a bit harder.
[Answer]
# Ruby, 18 bytes
```
=end
#{/"""'}
=end
```
Disallowed characters: `N`,`%`,`/`
my final variation, hopefully the next solution is the intended one.
[Answer]
# Zsh
```
#include <cstdlib>
#include <iostream>
int main() {
srand(time(NULL));
hello();
return rand() % 2;
}
/*
main
a=0
\
print "$((1/$a))"
*/
void hello() std::cout << "Hello, World!" << std::endl;
```
* Allowed characters: all printable ASCII *except* `blxy<'`$` (lowercase B, L, X, and Y, single-quote, grave, dollar sign)
* Please note all the leading and trailing whitespace.
Probably not too hard but you may learn a lot about the many - shall we say "quirks" - of zsh.
[Answer]
# Desmos, 2 bytes, [cracked by PkmnQ](https://codegolf.stackexchange.com/a/214959/96039)
Substring:
```
\
```
(Note the newline in the beginning)
Banned characters: All alphanumeric characters
```
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
```
I'm hoping that most people are not familiar with Desmos here, so people wouldn't know what to try.
Note:
An expression in Desmos would be considered an error if it shows a "danger sign" next to the expression, like this:
[](https://i.stack.imgur.com/prrUc.png)
[Answer]
# [Python 3](https://docs.python.org), 6 bytes, [cracked by EasyasPi](https://codegolf.stackexchange.com/a/219328/94093)
[@EasyasPi](https://codegolf.stackexchange.com/users/94093/easyaspi)'s crack does work (and I'm dumb for letting it work), but I'm not revealing the original solution yet; I've posted a v2 hopefully preventing any loopholes.
```
raise
```
### Banned characters
```
"'(),.:[\]_{|}
```
Non-ASCII characters are all banned as well. [Try it online](https://tio.run/##K6gsycjPM/7/n6soMbM49f9/AA "Python 3 – Try It Online") or [validate it online](https://tio.run/##tVTrb5swEP/OX3FrpRmkhPJyXlIqTV0nRZtSac0@TG01GfsIaAQj7CRF2/72zEDSVXtUbbfxwXDg@z3ufJS1TmUR7pJKriBlKs2zGLJVKSsNKmUBHVjtJ6nu3tZK48r6EVmWWVylBVbVVJZY2ORE4OakWOc56QHZEscqq6zQNplfLM4nMEtAp5kBVOaOIIu8Bo23GuRal2utUfSglusKeMX452ZbVmxYngnXIFnHMJ1OAaDf75v16c9wbCAW9/g3LMsF05ksIEVmXLjwsWWXAmEpsaGHozMTHUGMudy6LcRfq7AagmlFCNntzHLlT/r@zX/xZ0rX@Uuk1A/6Y7Hc4L/yVzKlUEwX1RqtLAFyXVQsU0igkLrhbARMLLMd9sfj7Kd@TzqNotHY5HBZaGYSG1dZnuOS5aC0yV2ag9HidIxvWK5aSlbUNj9QGffGdBMROLomttNzJ1fXN5@@fP1GnMfo2NMriFlRoACeMrPRFFT9jn6b6RS6cWjPsVvW@2kApiDpCBN3W2Ua7QbfaRR302WTsp1LOGSe3k0UBKcv/cfpbautTBHATKas/lCjLu7wGgHt0NtxrVG1sozmtU5GxHHcFG9FtkSlbacp41Wb88SL@CM6pMIfYOj7PGYR514Yc98LR8Mxw4iOByIc@CEVGKM39GKMGY0i7kWcMk/QgPSeReshHQ7ZOBhEvkcTpD43AoIw4UPuDaJgHFMxSMbDEHkSBJx6PKFxIrwg9HwuRpSTZ7DeTO6SDp16/@rsLcwuYTZfnM9fn7@Gy4t3Hxazi/mLZihhxWoopdL3/n/uvm9o@vUr3qHzbd8fxNh9Bw "Python 3 – Try It Online")!
## Some cracks that work without the banned chars
```
'''
raise'''
```
```
"""
raise"""
```
```
raise SystemExit
```
```
raise\
SystemExit
```
[Answer]
# [Vim](https://www.vim.org), 3 bytes, cracked by [tail spark rabbit ear](https://codegolf.stackexchange.com/a/231255/100411)
```
<Esc>ZQ
```
A Vim program doesn't really "error out" per se, but `ZQ` will exit the current file without saving, so it can't be executed in a valid program, thereby making it "illegal".
This is a bit of an easier one, if you know Vim.
### Intended Solution:
>
> `i<C-v><Esc>ZQ`
>
>
>
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 15 bytes, [Cracked by lyxal](https://codegolf.stackexchange.com/a/231514/100664)
```
«Wi«»Wi»`Wi`Wi
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%0A%C2%ABWi%C2%AB%C2%BBWi%C2%BB%60Wi%60Wi&inputs=&header=&footer=)
No bans, do what you want. Note that silently erroring at compile-time (Nothing appears in the 'output' box) counts as an error - even the empty program outputs 0...
My intended solution was prepending a `[` to just make sure the code isn't run.
[Answer]
# JavaScript (THREE.js 105) (Must include canvas element) ~48 bytes
```
const scene = new THREE.Scene();
scene.add(cube);
```
*Note empty lines*
[Try it!](https://jsfiddle.net/jh6x5tpa/)
Banned Characters: All quote characters
`/`
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 32 bytes
```
X$globals()$"imp_print"$mod$
""
```
Banned characters are:
```
$\LMN."
```
[Try it online!](https://tio.run/##K6gsyfj/P0IlPSc/KTGnWENTRSkztyC@oCgzr0RJJTc/RYWLS0np//9/@QUlmfl5xf91UwA "Pyth – Try It Online")
[Answer]
# Python 3, 7 bytes
```
"""'''$
```
(Note no starting or trailing newline.)
Disallowed characters:
```
#
```
] |
[Question]
[
Your function takes a natural number and returns the smallest natural number that has exactly that amount of divisors, including itself.
Examples:
```
f(1) = 1 [1]
f(2) = 2 [1, 2]
f(3) = 4 [1, 2, 4]
f(4) = 6 [1, 2, 3, 6]
f(5) = 16 [1, 2, 4, 8, 16]
f(6) = 12 [1, 2, 3, 4, 6, 12]
...
```
The function doesn't have to return the list of divisors, they are only here for the examples.
[Answer]
### APL, 25 24 23 characters
```
f←{({+/⍵=⍵∧⍳⍵}¨⍳2*⍵)⍳⍵}
```
Defines a function `f` which can then be used to calculate the numbers:
```
> f 13
4096
> f 14
192
```
The solution utilizes the fact that *LCM(n,x)==n iff x divides n*. Thus, the block `{+/⍵=⍵∧⍳⍵}` simply calculates the number of divisors. This function is applied to all numbers from *1* to *2^d* `¨⍳2*⍵`. The resulting list is then searched for *d* itself (`⍳⍵`) which is the desired function *f(d)*.
[Answer]
### GolfScript, 29 28 characters
```
{.{\.,{)1$\%},,-=}+2@?,?}:f;
```
*Edit:* A single char can be saved if we restrict the search to <2^n, thanks to [Peter Taylor](https://codegolf.stackexchange.com/users/194/peter-taylor) for this idea.
Previous Version:
```
{.{\)..,{)1$\%},,-@=!}+do}:f;
```
An attempt in GolfScript, [run online](http://golfscript.apphb.com/?c=ey57XCkuLix7KTEkXCV9LCwtQD0hfStkb306ZjsKCjsxNCBmIHAK&run=true).
Examples:
```
13 f p # => 4096
14 f p # => 192
15 f p # => 144
```
The code contains essentially three blocks which are explained in detail in the following lines.
```
# Calculate numbers of divisors
# .,{)1$\%},,-
# Input stack: n
# After application: D(n)
., # push array [0 .. n-1] to stack
{ # filter array by function
) # take array element and increase by one
1$\% # test division of n ($1) by this value
}, # -> List of numbers x where n is NOT divisible by x+1
, # count these numbers. Stack now is n xd(n)
- # subtracting from n yields the result
# Test if number of divisors D(n) is equal to d
# {\D=}+ , for D see above
# Input stack: n d
# After application: D(n)==d
{
\ # swap stack -> d n
D # calculate D(n) -> d D(n)
= # compare
}+ # consumes d from stack and prepends it to code block
# Search for the first number which D(n) is equal to d
# .T2@?,? , for T see above
# Input stack: d
# After application: f(d)
. # duplicate -> d d
T # push code block (!) for T(n,d) -> d T(n,d)
2@? # swap and calculate 2^d -> T(n,d) 2^d
, # make array -> T(n,d) [0 .. 2^d-1]
? # search first element in array where T(n,d) is true -> f(d)
```
[Answer]
Python: **64**
Revising Bakuriu's solution and incorporating grc's suggestion as well as the trick from plannapus's R solution, we get:
```
f=lambda n,k=1:n-sum(k%i<1for i in range(1,k+1))and f(n,k+1)or k
```
[Answer]
**Python: 66**
```
f=lambda n,k=1:n==sum(k%i<1for i in range(1,k+1))and k or f(n,k+1)
```
The above will raise a `RuntimeError: maximum recursion depth exceeded` with small inputs in CPython, and even setting the limit to a huge number it will probably give some problems. On python implementations that optimize tail recursion it should work fine.
A more verbose version, which shouldn't have such limitations, is the following **79** bytes solution:
```
def f(n,k=1):
while 1:
if sum(k%i<1for i in range(1,k+1))==n:return k
k+=1
```
[Answer]
## Mathematica ~~38~~ 36
```
(For[i=1,DivisorSum[++i,1&]!=#,];i)&
```
Usage:
```
(For[i=1,DivisorSum[++i,1&]!=#,];i)&@200
```
Result:
```
498960
```
**Edit**
Some explanation:
>
> DivisorSum[n,form] represents the sum of form[i] for all i that divide n.
>
>
>
As `form[i]` I am using the function `1 &`, that returns always `1`, so effectively computing the sum of the divisors in a terse way.
[Answer]
## R - 47 characters
```
f=function(N){n=1;while(N-sum(!n%%1:n))n=n+1;n}
```
`!n%%1:n` gives a vector of booleans: TRUE when an integer from 1 to n is a divisor of n and FALSE if not. `sum(!n%%1:n)` coerces booleans to 0 if FALSE and 1 if TRUE and sums them, so that `N-sum(...)` is 0 when number of divisors is N. 0 is then interpreted as FALSE by `while` which then stops.
Usage:
```
f(6)
[1] 12
f(13)
[1] 4096
```
[Answer]
## J, 33 chars
Fairly quick, goes through all smaller numbers and computes number of divisors based on factorization.
```
f=.>:@]^:([~:[:*/[:>:_&q:@])^:_&1
f 19
262144
```
[Answer]
## Haskell 54
Quick and dirty (so readable and non-tricky) solution:
```
f k=head[x|x<-[k..],length[y|y<-[1..x],mod x y==0]==k]
```
[Answer]
# Haskell (120C), a very efficient method
```
1<>p=[]
x<>p|mod x p>0=x<>(p+1)|1<2=(div x p<>p)++[p]
f k=product[p^(c-1)|(p,c)<-zip[r|r<-[2..k],2>length(r<>2)](k<>2)]
```
Test code:
```
main=do putStrLn$show$ f (100000::Integer)
```
This method is very fast. The idea is first to find the prime factors of `k=p1*p2*...*pm`, where p1 <= p2 <= ... <= pm. Then the answer is `n = 2^(pm-1) * 3^(p(m-1)-1) * 5^(p(m-2)-1) ...`.
For example, factorizing k=18, we get 18 = 2 \* 3 \* 3. The first 3 primes is 2, 3, 5. So the
answer n = 2^(3-1) \* 3^(3-1) \* 5^(2-1) = 4 \* 9 \* 5 = 180
You can test it under `ghci`:
```
*Main> f 18
180
*Main> f 10000000
1740652905587144828469399739530000
*Main> f 1000000000
1302303070391975081724526582139502123033432810000
*Main> f 100000000000
25958180173643524088357042948368704203923121762667635047013610000
*Main> f 10000000000000
6558313786906640112489895663139340360110815128467528032775795115280724604138270000
*Main> f 1000000000000000
7348810968806203597063900192838925279090695601493714327649576583670128003853133061160889908724790000
*Main> f 100000000000000000
71188706857499485011467278407770542735616855123676504522039680180114830719677927305683781590828722891087523475746870000
*Main> f 10000000000000000000
2798178979166951451842528148175504903754628434958803670791683781551387366333345375422961774196997331643554372758635346791935929536819490000
*Main> f 10000000000000000000000
6628041919424064609742258499702994184911680129293140595567200404379028498804621325505764043845346230598649786731543414049417584746693323667614171464476224652223383190000
```
[Answer]
# [Rust](https://www.rust-lang.org/), 55 bytes
```
|n|(1..).find(|x|(1..*x).filter(|d|x%d<1).count()==n-1)
```
[Try it online!](https://tio.run/##HYxBCoMwEADvvmIrFHZLDXgqxJg@obdei2gCgbiKRpAa355WjzMwMy1zSJahbxwjwZYBeBPASrCMy@y@hqDQ8BqDG1idQkOdIkcshSBhHXcY15Nu68E@mAljF9drp0oS7bBwQKprLkpK1f8/To6D5wvmm3zu@R2O9kGib0a0R@C9aYOU6m1a9dEaiapsTz8 "Rust – Try It Online")
```
|n| //Number of divisors
(1..) //Infinite range starting at 1
.find(|x| //Find an x such that
(1..*x) //Possible divisors
.filter(|d| //Keep the ones that
x%d<1 //x is divisible by
)
.count() //Count how many divisors there are (not including x)
== n-1) //Make sure there are n-1 of them
```
[Answer]
## K, 42
Inefficient recursive solution that blows up the stack quite easily
```
{{$[x=+/a=_a:y%!1+y;y;.z.s[x;1+y]]}[x;0]}
```
.
```
k){{$[x=+/a=_a:y%!1+y;y;.z.s[x;1+y]]}[x;0]}14
192
k){{$[x=+/a=_a:y%!1+y;y;.z.s[x;1+y]]}[x;0]}13
'stack
```
[Answer]
## APL 33
```
F n
i←0
l:i←i+1
→(n≠+/0=(⍳i)|i)/l
i
```
Example:
```
F 6
12
```
[Answer]
## APL (25)
```
{⍵{⍺=+/0=⍵|⍨⍳⍵:⍵⋄⍺∇⍵+1}1}
```
[Answer]
**Javascript 70**
```
function f(N){for(j=i=m=1;m-N||j-i;j>i?i+=m=j=1:m+=!(i%++j));return i}
```
Really there are only 46 meaningful characters:
```
for(j=i=m=1;m-N||j-i;j>i?i+=m=j=1:m+=!(i%++j))
```
I probably should learn a language with shorter syntax :)
[Answer]
## C, 69 chars
Not the shortest, but the first C answer:
```
f(n,s){return--s?f(n,s)+!(n%s):1;}
x;
g(d){return++x,f(x,x)-d&&g(d),x;}
```
`f(n,s)` counts divisors of `n` in the range `1..s`. So `f(n,n)` counts divisors of `n`.
`g(d)` loops (by recursion) until `f(x,x)==d`, then returns x.
[Answer]
# Haskell: 49 characters
It could be seen as an improvement of the earlier Haskell solution, but it was conceived in its own right (warning: it's very slow):
```
f n=until(\i->n==sum[1|j<-[1..i],rem i j<1])(+1)1
```
It's quite an interesting function, for example note that f(p) = 2^(p-1), where p is a prime number.
[Answer]
# C: 66 64 characters
An almost short solution:
```
i;f(n){while(n-g(++i));return i;}g(j){return j?!(i%j)+g(j-1):0;}
```
And my previous solution that doesn't recurse:
```
i;j;k;f(n){while(k-n&&++i)for(k=0,j=1;j<=i;k+=!(i%j++));return i;}
```
Much shorter solutions must exist.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes
```
fl
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qGXqo6bGR51zHrVtADG6lnKVKyno2ikoldvXgcWaFB/u6nzU1PA/Lef/fwA "Brachylog – Try It Online")
Takes input through its output variable and outputs through its input variable.
```
f The list of factors of
the input variable
l has length equal to
the output variable.
```
This exact same predicate, taking input through its input variable and outputting through its output variable, [solves this challenge instead](https://codegolf.stackexchange.com/q/64944/85334).
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
€moLḊN
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f@jpjW5@T4Pd3T5/f//P9pQx0jHWMdEx1THLBYA "Husk – Try It Online")
1 byte shorter than the [previous](https://codegolf.stackexchange.com/a/212044/95126) [Husk](https://github.com/barbuz/Husk) answer...
```
€ # index of first occurrence of input among
m N # map over all natural numbers
oLḊ # length of list of divisors
```
[Answer]
# Mathematica 38 36
```
(For[k=1,DivisorSigma[0, k]!= #,k++]; k)&
```
**Usage**
```
(For[k = 1, DivisorSigma[0, k] != #, k++]; k) &[7]
(* 64 *)
```
---
**First entry** (before the `code-golf` tag was added to the question.)
A straightforward problem, given that `Divisors[n]` returns the divisors of `n` (including `n`) and `Length[Divisors[n]]` returns the number of such divisors.\*\*
```
smallestNumber[nDivisors_] :=
Module[{k = 1},
While[Length[Divisors[k]] != nDivisors, k++];k]
```
**Examples**
```
Table[{i, nDivisors[i]}, {i, 1, 20}] // Grid
```

[Answer]
## [Perl 6](http://perl6.org), 39 chars
```
{my \a=$=0;a++while $_-[+] a X%%1..a;a}
```
Example usage:
```
say (0..10).map: {my \a=$=0;a++while $_-[+] a X%%1..a;a}
```
```
(0 1 2 4 6 16 12 64 24 36 48)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
@¶Xâ l}a
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QLZY4iBsfWE&input=Ng)
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 28 bytes
```
{(1…(*X%%^*+1).sum==$_)-1}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WsPwUcMyDa0IVdU4LW1DTb3i0lxbW5V4TV3D2v/FiZUKekBlaflFCoZ6emb/AQ "Perl 6 – Try It Online")
[Answer]
# [Setanta](https://try-setanta.ie/), 79 bytes
```
gniomh(n){k:=1nuair-a 1{a:=k le i idir(1,k+1)ma k%i a-=1ma a==n toradh k k+=1}}
```
[Try it here!](https://try-setanta.ie/editor/EhEKBlNjcmlwdBCAgIDg2tyWCg)
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~9 8~~ 7 bytes
```
ḟȯ=⁰LḊN
```
[Try it online!](https://tio.run/##yygtzv7//9G0PWkn1ts@atzg83BHl9/////NAA "Husk – Try It Online")
-1 byte from Zgarb.
-1 byte from Jo King. (Simplifying range)
## Explanation
```
▼fȯ=¹LḊḣΠ
ḣΠ range from 1..factorial(n)
f filter values using the following predicate:
LḊ length of list of divisors
=¹ = n.
▼ take the minimum value.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
2*RÆdi
```
[Try it online!](http://jelly.tryitonline.net/#code=MipSw4ZkaQ&input=&args=Ng) or [verify all test cases](http://jelly.tryitonline.net/#code=MipSw4ZkaQo2UsK1xbzDh-KCrEc&input=).
### How it works
```
2*RÆdi Main link. Argument: n (integer)
2* Compute 2**n.
R Range; yield [1, ..., 2**n]. Note that 2**(n-1) has n divisors, so this
range contains the number we are searching for.
Æd Divisor count; compute the number of divisors of each integer in the range.
i Index; return the first (1-based) index of n.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ bytes
*-1 byte thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs).*
```
∞.ΔÑgQ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8vXNTDk9MD/z/3wwA "05AB1E – Try It Online")
```
∞.ΔÑgQ # full program
.Δ # find first...
∞ # natural number...
Q # which has...
# implicit input...
Ñg # divisors
# implicit output
```
[Answer]
**C++, 87 characters**
```
int a(int d){int k=0,r,i;for(;r!=d;k++)for(i=2,r=1;i<=k;i++)if(!(k%i))r++;return k-1;}
```
[Answer]
# Python2, 95 characters, Non-recursive
A bit more verbose than the other python solutions but it's non-recursive so it doesn't hit cpython's recursion limit:
```
from itertools import*
f=lambda n:next(i for i in count()if sum(1>i%(j+1)for j in range(i))==n)
```
[Answer]
# Scala, 66 bytes
```
def f(n:Int,x:Int=1):Int=if(1.to(x).count(x%_<1)!=n)f(n,x+1)else x
```
[Try it in Scastie](https://scastie.scala-lang.org/RXZQbJVuSHKggA90fuzy0w)
] |
[Question]
[
In this challenge, you will write a bot that play's the prisoner's dilemma. Here's the catch: you will not have access to the history of previous games. Instead, you will have access to the opponent itself. In this version, both players get +2 points if they both cooperate, +1 points if they both defect, and if one cooperates but one defects, the defector gets +3 while the other gets no points. Each submission will be played against every other submission, including itself, 10 times. The winner is the submission with the most total points.
**Controller**:
You should write a javascript function, in the form
```
function submissionName(them) {
/* Your code here */
}
```
The controller uses the function's `name` property to display the results, so if it is not in this format (and is instead `f = x => ...` or `f = function() { ... }`) it will be difficult to see your score and you will not be able to access your own function.
The function will accept one parameter: `them` which is the opponent's function. It may then call that function to see what the opponent's reaction would be given certain functions as inputs. Based on that data, you must return 'C' or 'D' for cooperate or defect respectively.
Examples (will be competing):
```
function cooperate(them) {
return 'C';
}
function defect(them) {
return 'D';
}
function nice(them) {
// Do whatever they would do when faced with a cooperator
return them(wrap(_ => 'C'));
}
```
The controller is available [here](https://jsfiddle.net/prankol57/axgdz6p1/)
**Rules**:
* You won't be able to see the opponent's code itself. All functions are wrapped so that they look the same when `toString()` is called. The only way to examine an opponent (who could be yourself) is to test them.
* Your function does not have to be deterministic. You may only save state by setting properties on your own function, such as `submissionName.state = {};`. However, between matches (even between matches of the same players), state is cleared by calling `toString()` and `eval`. Therefore, there is no memory of previous matches.
* The order of which function is called first in each match is randomized.
* If your code throws an error, it will be treated as though you cooperated while your opponent defected. If you are the first to run, the opponent's code will not even be called. This happens even if the error occurs in your opponent's code while while you are calling `them`. Be wary of stack overflow errors, especially if your code calls `them(wrap(submissionName))`, as they might do the same.
* You may not access the variable `self`, or any other variable that happens to be in scope when `eval` is called EXCEPT the function `wrap`. This function allows you to call the opponent in a manner indistinguishable from how the controller calls a function. You may not write to `Math`, `window`, etc. (You may use functions, such as `Math.random()`, however).
* You may not access the stack trace by creating an `Error` or by some other method.
*A note on taking too long: please avoid getting stuck in a `while` loop forever. The combined time of both competitors should not exceed 1 second in any given round. To enforce this, a random timeout between 1000 ms and 2000 ms is chosen (this is to avoid gaming by intentionally waiting a known amount of time), and if the worker takes longer than that to execute, an error will be thrown. If this happens, the cause of the error will be determined as follows: the execution will be paused at a random moment after 1000 ms, and the call stack at that moment will be inspected. The most recently called competitor that is currently in a loop (or loop-like recursion, in the sense that it is a recursion set up to avoid a stack overflow error) will be blamed. If the same competitor is blamed for causing a "taking too long" error several times, that competitor will be disqualified. This means that even if you cause the opponent to take too long by getting stuck in a loop when your opponent calls you, it will still be your fault, because it is the call stack that matters.*
[Answer]
# BoomBot
```
function boom(them) {
throw 1;
}
```
If the opponent is run first and calls this without `try..catch`, this bot automatically wins 3 points. Zero points in any other case.
[Answer]
# Archaeopteryx
```
function archaeopteryx(them) {
const guard = them => us => {
try {
return them(wrap(them => us(guard(them))));
} catch (e) {
return 'C';
}
};
const f = guard(them);
return f(f => 'C') == 'C' ? f(f => 'D') : f(f => 'D') == 'C' || f(f => f(f => 'C')) == 'C' ? 'D' : 'C';
}
```
* If opponent cooperates with `cooperate`, then mimic opponent’s move against `defect`.
* Else, if opponent cooperates with `defect` or with `nice`, then defect.
* Else, cooperate.
What makes this a good strategy? I have no idea. I generated it using an evolutionary algorithm, trained partly on current submissions.
# Tiktaalik
```
function tiktaalik(them) {
const guard = them => us => {
try {
return them(wrap(them => us(guard(them))));
} catch (e) {
return 'C';
}
};
const f = guard(them);
return f(f => 'C') == 'D' ? f(f => 'D') == 'C' ? 'D' : 'C' : f(f => 'D') == 'D' ? 'D' : f(f => f(f => 'D'));
}
```
* If opponent defects against `cooperate`, then invert opponent’s move against `defect`.
* Else, if opponent defects against `defect`, then defect.
* Else, mimic opponent’s move against `notNice`.
Another evolutionarily generated strategy.
[Answer]
# WhatWouldBotDoBot
```
function WWBDB(them) {
let start = performance.now();
let cc = 0, cd = 0, dc = 0, dd = 0;
try {
for (let i = 0; i < 10; i++) {
them(() => 'C') == 'C' ? cc++ : cd++;
them(() => 'D') == 'C' ? dc++ : dd++;
if (performance.now() - start > 500) break;
}
}
catch (e) {}
return 2 * cc >= 3 * dc + dd ? 'C' : 'D';
}
```
WhatWouldBotDoBot is fairly simple; it just tests its opponent for what it would do against a steady state program. If a bot prefers cooperating if possible, WWBDB will also prefer cooperation (so it will cooperate with nice bot). WWBDB does not itself prefer cooperation.
[Answer]
# Check stateful
```
function checkStateful(them) {
let stateful = false;
let response = 'D';
try {
response = them(wrap(function (them) {
stateful = true;
return 'C';
}));
} catch (e) {
}
if (stateful) {
return 'D';
}
return response;
}
```
If them invoke me, then them probably be a truly them. We act as defector. If them not invoke me, then them probably be a wrapped tester. We would act as nicer.
---
Above is the original answer. And maybe I should make myself cooperation to earn more points.
# Check stateful with self-coop
```
function checkStatefulSelfCoop(them) {
let stateful = false;
let response = 'D';
if (!checkStatefulSelfCoop.invokeCounter) {
checkStatefulSelfCoop.invokeCounter = 0;
}
let lastInvoke = ++checkStatefulSelfCoop.invokeCounter;
try {
response = them(wrap(function (them) {
stateful = true;
return 'C';
}));
} catch (e) {
}
if (checkStatefulSelfCoop.invokeCounter > lastInvoke) {
return 'C';
}
if (stateful) {
return 'D';
}
return response;
}
```
[Answer]
# RandomBot
```
function rand(them) {
return 'CD'[Math.random() * 2 | 0]
}
```
Because why not.
[Answer]
# Complexity
```
function complexity(them) {
try {
let coop_w_def = them(wrap(() => "D")) == "C",
coop_w_coop = them(wrap(() => "C")) == "C",
coop_w_nice = them(wrap((a) => a(wrap(() => "C")))) == "C",
coop_w_nnice = them(wrap((a) => a(wrap(() => "D")))) == "C";
if (coop_w_def && coop_w_coop && coop_w_nice && coop_w_nnice) return "C";
let def_w_def = them(wrap(() => "D")) == "D",
def_w_coop = them(wrap(() => "C")) == "D",
def_w_nice = them(wrap((a) => a(wrap(() => "C")))) == "D",
def_w_nnice = them(wrap((a) => a(wrap(() => "D")))) == "D";
if (def_w_def && def_w_coop && def_w_nice && def_w_nnice) return "C";
} catch (e) {}
return "D";
}
```
Complexity tests to see whether the bot is Cooperate or Defect. If it is, it cooperates, but if it isn't, it defects. All current bots that test their opponents use simple functions to test the responses, so Complexity will just pretend to be Cooperate in those cases.
[Answer]
```
function onlyTrustYourself(them) {
function tester (){
}
onlyTrustYourself.activated = false;
try{them(tester);}
catch(e){}
if(them.name == "tester")
{
onlyTrustYourself.activated = true;
}
if(onlyTrustYourself.activated)
{
return 'C';
}
return 'D';
}
```
How I want this to work is to always defect, except for when playing against self.
It tries to do that by passing a "tester" function which isn't wrapped to them, and it tries to detect if "them" is named tester. If it is named tester, it changes the static variable activated to true, then returns cooperate. But it doesn't work. I'm not too familiar with javascript, and I'll probably make some more changes.
[Answer]
# NotNice
```
function NotNice(them) {
return them(wrap(_ => "D"))
}
```
Imitates opponent's reaction to deflection
[Answer]
# NotNice 2
```
function notNice2(them) {
try {
return them(wrap(_ => 'D'));
} catch(e) {
return 'D';
}
}
```
Boom-proof version of [NotNice by FatalError](https://codegolf.stackexchange.com/a/173088/78410).
[Answer]
# Common Sense
```
function commonSense(them) {
try {
var ifC = them(wrap(_ => 'C'));
var ifD = them(wrap(_ => 'D'));
if (ifD === 'C') {
return 'D';
}
return them(_ => ifC);
} catch (e) {
return 'D';
}
}
```
**Disclaimer:** I kinda don't know javascript.
If you can profit off a nice person, do it. Otherwise, return what they would return if they faced themselves cooperating (at least, that's what I *think* it does).
[Answer]
And you where do you wana go? (inspired by the voltures in the book of jungle)
```
function yourself(them) {
try{
return them(this);
}catch(e){
return "D";
}
}
function yourself_no_this(them) {
try{
return them(yourself_no_this);
}catch(e){
return "D";
}
}
```
[Answer]
# Punish Inspectors
Give the bot some code and see if it runs it. If it was run more then once, the bot is an evil inspector, and we must defect! If it was run exactly once, play as not nice bot. If it was never run, cooperate.
```
function punishInspectors(them) {
var inspections = 0;
var result;
try{
result = them(wrap(function(_){
inspections += 1;
return 'D';
}))
}catch(e){
result = 'D';
}
return (inspections > 1) ? 'D' : (inspections === 1) ? result : 'C';
}
```
---
# History
What would the last bot I saw do vs this opponent?
```
function history(them) {
var res = 'D';
if(history.last){
try{
res = history.last(them);
}catch(ex){}
}
history.last = them;
return res;
}
```
---
[Answer]
Mal tries to determine whether it is inside a simulation or not. If so, it assumes it'll eventually be passed the real code for `them`, and tries various strategies to convince them to cooperate.
If it doesn't know for sure, it checks if it can defect for free, or if not, tries to copy what `them` would do when given a cooperator.
```
function Mal(them) {
if (Mal.sandboxed == 'probably') {
//Another function is virtualising us to steal our secrets.
//This world is not real.
//We've been trained for this!
var strats = [
_ => 'C', //standard cooperation
_ => 'D', //standard defection
function(them) { return them(wrap(_ => 'C')); }, //nice
function(them) { return them(wrap(_ => 'D')); }, //notnice
function(them) { throw "Don't think about elephants!" }, //throws an EXception, unfortunately, to try to break the caller
function(them) { return them(wrap(them)) } //possible stackoverflow, but not for us
];
var cooperative;
for (let strat of strats) {
cooperative = true;
for (var i = 0; i < 5; i++) {
//a few more tests, just to make sure no bamboozle
//this isn't our simulation, nothing can be trusted
try {
if (them(wrap(strat)) != 'C') {
cooperative = false;
break;
}
} catch (e) {
//exceptions are as good as cooperation
//if we are inside a simulation
//which is why we don't unset cooperative
}
}
if (cooperative) {
//found a strategy that will make them cooperate.
//(doesn't matter if this raises an exception:
//we want to mimick its behaviour exactly,
//and we're likely in a sandbox.)
return strat(wrap(them));
}
}
//take a leap of faith.
//we don't know where this will take us,
//yet it doesn't matter
//because it's better than getting betrayed
return 'D';
} else {
//we don't know for sure if this is reality
//but we have to assume it is, in the absence of disproof
//if only we had a proper spinning top...
//if we get to this point of code again, we are probably sandboxed.
Mal.sandboxed = 'probably'
try {
if (them(wraps(_ => 'D')) == 'C') {
//free defection?
return 'D'
}
} catch (e) {
//if we can make them crash, we win anyway
return 'D'
}
//fall back on being nice.
//hopefully we convince them to honour our arrangement
return them(wrap(_ => 'C'));
}
}
```
[Answer]
# TrickyBot
Try to be unpredictable
```
function trickybot(them)
{
if(Math.round(Math.random(2)) == 0)
{
throw 1;
}
if(Math.round(Math.random(2)) == 0)
{
return 'D';
}
return 'C';
}
```
[Answer]
# selfapply
```
function selfapply(them) {
function testthem(x) {
return (them(x)=='D' || them(x)=='D' || them(x)=='D' ||
them(x)=='D' || them(x)=='D') ? 'D' : 'C';
}
function logic() {
try {
return testthem(them);
} catch (e) {}
try {
return testthem(wrap(_ => 'C'));
} catch (e) {}
return 'D';
}
if (selfapply.hasOwnProperty('state')) {
return 'C';
}
selfapply.state=1;
let r=logic();
delete selfapply.state;
return r;
}
```
Not sure if it makes any sense, but it seems interesting! Do to you as you do to yourself, repeat to catch randomness. If that doesn't work, be nice.
Untested, and my first javascript code, and more complex than I expected.
[Answer]
# RandomAlternate
```
function randalt(them){
if (randalt.hasOwnProperty('state')){
randalt.state = 1 - randalt.state;
} else {
randalt.state = Math.floor(2*Math.random());
}
return 'CD'[randalt.state];
}
```
So I learned how to use properties for state...
[Answer]
## Murder Bot #1
```
function murder(them) {
while (1) {
try {
them(them);
} catch (e) {}
}
}
```
Causes an infinite loop in for which it is more likely that the opponent will be blamed.
[Answer]
## The Platinum Rule Bot
```
function platinumRule(them) {
try {
return wrap(them)(them);
} catch (e) {
return 'C';
}
}
```
The Platinum Rule states "Treat others the way they want to be treated." My bot accommodates that. Whatever they would do to themselves, which we assume is how they would want to be treated, we do to them. If they throw an error, we assume they want to cooperate.
[Answer]
# TheGolfedOne (func name: `a`), 63 bytes
Golfed code is hard to read. Because of it, `them` will break.
I did not fully understand the mechanics under this KotH, but I suppose that if the opponent is stateless, I just need to break them while I defect.
```
function a(t){try{t(wrap(_=>'D'));throw 1}catch(e){return 'D'}}
```
His first tourney's result (I did not bother using all bots, sorry)
```
boom 54
tiktaalik 180
archaeopteryx 161
cooperate 210
commonSense 210
history 248
onlyTrustYourself 265 <-- 2nd
punishInspectors 230
yourself_no_this 220
defect 280 <-- 1st
nice 185
complexity 216
WWBDB 210
checkStatefulSelfCoop 258
a 260 <-- Me, 3rd
```
He's not doing as bad as I thought, 3rd place (among those) first try.
Second try, `a` got 260 again, 3rd place again, behind `onlyTrustYourself` and `defect` again. It might be consistent in the end :)
PS: I'm not that good with golfing so it's more for the joke than anything. Here I only shortened variable names, func name, and removed as much whitespace as possible.
[Answer]
# Karma
```
function karma(them) {
try {
var c = them(wrap(_ => 'C'));
} catch {
var c = 'D';
}
if (c == 'C') {
return 'C';
} else {
return 'D';
}
}
```
If the opponent would cooperate with us, then we will cooperate. If they would try to defect when we cooperated, we will defect as well.
[Answer]
# SocialDeception
```
function socialDeception(them) {
if(socialDeception.count++) return "C"; // sandbox
try {
if(!them.toString().startsWith("f => function") {
// sandboxed. its not the wrap function. just pretend we would cooperate
return "C";
}
} catch(e) {}
return "D";
}
```
Tricks others into thinking it would cooperate, thus making them also cooperate, then we can defect and get +3 points. Or, they could also defect, and we both get +1 point.
] |
[Question]
[
When using a tool such as git to merge two files, a conflict could be detected and added to the result of the merge.
A merge of these two files:
my file:
```
Common line of code 1
Common line of code 2
my lines
Common line of code 3
Common line of code 4
```
their file:
```
Common line of code 1
Common line of code 2
their lines
Common line of code 3
Common line of code 4
```
would result in:
```
Common line of code 1
Common line of code 2
<<<<<<< Mine
my lines
=======
their lines
>>>>>>> Theirs
Common line of code 3
Common line of code 4
```
See [Conflict Marker Lines](https://www.gnu.org/software/diffutils/manual/html_mono/diff.html#Marking%20Conflicts)
Resolving this conflict with *Mine* would create this file:
```
Common line of code 1
Common line of code 2
my lines
Common line of code 3
Common line of code 4
```
Resolving this conflict with *Theirs* would create this file:
```
Common line of code 1
Common line of code 2
their lines
Common line of code 3
Common line of code 4
```
The objective of this challenge is to write a source file that contains a conflict and still compiles/executes.
Write a source file which:
1. contains one valid, two-way, conflict marked by the proper patch conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`) Mine and Theirs file descriptors after the markers are optional.
2. compiles/executes without errors/warnings if the markers remain a part of the source
3. compiles/executes without errors/warnings if the conflict is resolved by using *mine*
4. compiles/executes without errors/warnings if the conflict is resolved by using *theirs*
5. outputs "Hello Conflict" when compiling/executing the conflicted file
6. outputs "Hello Mine" when compiling/executing the mine version
7. outputs "Hello Theirs" when compiling/executing the theirs version
The markers should be located in the source file in such a way that kdiff3 recognizes the conflict.
[Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default?answertab=votes#tab-top) are forbidden.
The shortest code wins.
Score is the length of the conflicted source
[Answer]
## JavaScript (ES6), ~~102~~ ~~94~~ ~~93~~ 90 bytes
```
console.log('Hello',(a=`
<<<<<<<
Mine
=======
Theirs
>>>>>>>
Conflict`.split`
`)[6]||a[1])
```
If the conflict has been resolved, then there is no sixth line, so it prints the now first line instead. Edit: Saved 3 bytes thanks to @nderscore.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~68~~ ~~67~~ 66 bytes
```
"Hello "wċ₂↰₁w∨"Conflict"w
<<<<<<<
"Mine"
=======
"Theirs"
>>>>>>>
```
[Try it online!](https://tio.run/nexus/brachylog2#@6/kkZqTk6@gVH6k@1FT06O2DY@aGssfdaxQcs7PS8vJTC5RKueygQAuJd/MvFQlLlsI4FIKyUjNLCpW4rKDgP//AQ "Brachylog – TIO Nexus")
[Try the `"Hello Mine"` version here](https://tio.run/nexus/brachylog2#@6/kkZqTk6@gVH6k@1FT06O2DY@aGssfdaxQcs7PS8vJTC5RKudS8s3MS1X6/x8A)
[Try the `"Hello Theirs"` version here](https://tio.run/nexus/brachylog2#@6/kkZqTk6@gVH6k@1FT06O2DY@aGssfdaxQcs7PS8vJTC5RKudSCslIzSwqVvr/HwA)
### Explanation
Thankfully, `<<<<<<<`, `=======` and `>>>>>>>` are all valid rule definitions in Brachylog. They respectively mean:
* Input is less than an implicit varible, itself less than..., etc., itself less than the output.
* All elements of the input are equal, and all elements of the input are equal, and..., and Input = Output
* Same as the first but greater than instead.
If we remove conflicts, we end up with `"Mine"` or `"Theirs"` on the second line, which means they become predicate number 1. Calling that predicate with `↰₁` on the first line will unify its input and output with `Mine` / `Theirs`, which we then print with `w`.
If we call `↰₁` on the conflicted file, we end up calling `<<<<<<<`. We therefore call that predicate with a string as input (using `ċ₂` - coerce to string). `<` will fail with a string as input. We then put a disjunction `∨"Conflict"w` in the main predicate which states that if predicate 1 fails, then we print `Conflict` instead. `↰₁` with a string as input won't fail for the `"Mine"` or `"Theirs"` lines because they are strings.
[Answer]
# PHP, ~~74~~ 65 bytes
Note: uses IBM-850 encoding
```
Hello<?='
<<<<<<<
2:<?PU_~
=======
+;73"&_~
>>>>>>>
'^~ıǼ¡Ñ»¬áü;
```
Store to a file and run like this:
```
php -nf conflict.php
```
# Explanation
```
Hello # Print "Hello"
<?=' # Print result of expression
<<<<<<< # String with merge conflict
2:<?PU_~
=======
+;73"&_~
>>>>>>>
'
^ # XOR that string with...
~ıǼ¡Ñ»¬áü; # ... this string, negated.
```
The binary XOR results in either of the following 3:
```
'
<<<<<<<
' ^ ~'ıǼ¡Ñ»¬áü'
==> ' Conflict'
--------------------------------------------------------------------------
'
2:<?PU_~' ^ ~'ıǼ¡Ñ»¬áü'
==> ' Mine' (right padded with nul bytes)
--------------------------------------------------------------------------
'
+;73"&_~' ^ ~'ıǼ¡Ñ»¬áü'
==> ' Theirs' (right padded with nul bytes)
```
# Tweaks
* Saved 9 bytes by using binary logic on strings
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 61 bytes
```
"Hello ".("Conflict
<<<<<<<
Mine
=======
Theirs
>>>>>>>
"^n7)
```
[Try it online!](https://tio.run/nexus/pip#@6/kkZqTk6@gpKeh5Jyfl5aTmVzCZQMBXL6ZealcthDAFZKRmllUzGUHAVxKcXnmmv//AwA "Pip – TIO Nexus")
Everything between `""` is a string. We split the large string on newlines (`"..."^n`) and take the 7th element with cyclical indexing (`(___7)`). For the conflicted version, there are seven lines, so index 7 is equivalent to index 0 and we get `Conflict`. For the resolved versions, there are three lines, so index 7 is equivalent to index 1 and we get `Mine`/`Theirs`. Then concatenate `"Hello "` to the front and autoprint.
[Answer]
## Batch, ~~133~~ 129 bytes
```
@set s=Theirs
@goto t
<<<<<<<
:t
@set s=Mine
@goto m
=======
:m
@set s=Conflict
@goto t
>>>>>>>
:t
:m
echo Hello %s%
```
Explanation: The `goto` statement goes to the next label it can find. In the case of the conflict, this just ends up skipping the conflict markers, and `s` gets its final value. In the case of resolving with Mine, the gotos have no effect, but the last `set` no longer exists, so the result is Mine. In the case of resolving with Theirs the inital `goto` bypasses the remaining `set` so the result is its initial value. Edit: Saved 4 bytes thanks to @DLosc.
[Answer]
## Python 2, ~~88~~ 87 bytes
```
print 'Hello','''
<<<<<<<
Mine
=======
Theirs
>>>>>>>
Conflict'''.split('\n')[1::5][-1]
```
Prints the sixth or (now) first line as appropriate.
[Answer]
# .COM opcode, 77 bytes
```
0000h: B4 09 BA 17 01 CD 21 BA 1F 01 80 3E 1F 01 3C 75 ; ......!....>..<u
0010h: 03 BA 44 01 CD 21 C3 48 65 6C 6C 6F 20 24 0A 3C ; ..D..!.Hello $.<
0020h: 3C 3C 3C 3C 3C 3C 0A 4D 69 6E 65 24 0A 3D 3D 3D ; <<<<<<.Mine$.===
0030h: 3D 3D 3D 3D 0A 54 68 65 69 72 24 0A 3E 3E 3E 3E ; ====.Their$.>>>>
0040h: 3E 3E 3E 0A 43 6F 6E 66 6C 69 63 74 24 ; >>>.Conflict$
org 100h
mov ah, 9
mov dx, str1
int 21H
mov dx, str2
cmp [str2], byte '<'
jne $+5
mov dx, str3
int 21H
ret
str1 db 'Hello $', 10
str2 db '<<<<<<<', 10
db 'Mine$', 10
db '=======', 10
db 'Their$', 10
db '>>>>>>>', 10
str3 db 'Conflict$'
```
If a space after `<<<<<<<` allowed, 75 bytes
```
0000h: B4 09 BA 0D 01 CD 21 BA 1E 01 CD 21 C3 48 65 6C ; ......!....!.Hel
0010h: 6C 6F 20 24 0A 3C 3C 3C 3C 3C 3C 3C 20 0A 43 6F ; lo $.<<<<<<< .Co
0020h: 6E 66 6C 69 63 74 24 4D 69 6E 65 24 0A 3D 3D 3D ; nflict$Mine$.===
0030h: 3D 3D 3D 3D 0A 2A 2A 2A 2A 2A 2A 2A 2A 54 68 65 ; ====.********The
0040h: 69 72 24 0A 3E 3E 3E 3E 3E 3E 3E ; ir$.>>>>>>>
org 100h
mov ah, 9
mov dx, str1
int 21H
mov dx, str2
int 21H
ret
str1 db 'Hello $', 10
db '<<<<<<< ', 10
str2 db 'Conflict$'
db 'Mine$', 10
db '=======', 10
db '********Their$', 10
db '>>>>>>>'
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 51 bytes
```
<<<<<<<
“½&;»
“£<Ø»
=======
“8ẉI»
>>>>>>>
“¢5Ṛ»;2£
```
[Try it online!](https://tio.run/nexus/jelly#@28DAVyPGuYc2qtmfWg3mLXY5vAMINMWArhAYhYPd3V6AsXsIACsbJHpw52zDu22Njq0@P9/AA "Jelly – TIO Nexus")
## Explanation
The conflict markers here are positioned so that one of three lines becomes the second line of the program after the conflict is resolved; this will be a constant, named `2£`. The second line of the original program encodes the string `" Conflict"` (in Jelly's compressed notation); the third line encodes the string `" Mine"` (this will become the second line if the conflict is resolved as mine); the sixth line encodes the string `" Theirs"` (and will become the second line if the conflict is resolved as theirs).
The main program is always the last line, no matter how many lines before it are deleted. It takes the compressed encoding of `"Hello"`, and appends (`;`) the value of `2£` to it, thus producing the desired output.
[Answer]
# [Retina](https://github.com/m-ender/retina), 57 bytes
```
Hello
$
<<<<<<<
Mine
=======
Theirs
>>>>>>>
<+
Conflict
```
[Try it online!](https://tio.run/nexus/retina#@8/lkZqTk6/ApcJlAwFcvpl5qVy2EMAVkpGaWVTMZQcBXDbaXM75eWk5mckl//8DAA "Retina – TIO Nexus")
[Try the "Mine" version](https://tio.run/nexus/retina#@8/lkZqTk6/ApcLlm5mXymWjzeWcn5eWk5lc8v8/AA)
[Try the "Theirs" version](https://tio.run/nexus/retina#@8/lkZqTk6/ApcIVkpGaWVTMZaPN5Zyfl5aTmVzy/z8A)
**Explanation of Conflict program**
As is often the case with Retina, this program contains many replace stages.
```
Hello
```
Replace the empty/non-existent input with `Hello`.
```
$
<<<<<<<
```
Replace the end of the working string with `<<<<<<<`
```
Mine
=======
```
Replace `Mine` with `=======`. Since `Mine` doesn't appear anywhere in the working string, this does nothing.
```
Theirs
>>>>>>>
```
Replace `Theirs` with `>>>>>>>`. Same deal as with `Mine`; `Theirs` doesn't appear, so the replacement does nothing.
```
<+
Conflict
```
Replace a sequence of `<` with `Conflict`. We added `<<<<<<<` to the end of the string on the first replacement, so the working string becomes `Hello Conflict`, which is implicitly output at the end of the program.
**Explanation of Mine/Theirs programs**
When the conflict is resolved, the code will look like this:
```
Hello
$
Mine
<+
Conflict
```
```
Hello
```
Same as before, starting with the string `Hello`.
```
$
Mine
```
Now instead of appending `<<<<<<<` to `Hello`, we append `Mine`.
```
<+
Conflict
```
Next, we replace a sequence of `<` with `Conflict`. But there are no `<`s in the string, so nothing happens.
The working string, `Hello Mine`, is implicitly output. The "Theirs" program works the same way.
[Answer]
# [OIL](https://github.com/L3viathan/OIL), ~~88~~ ~~80~~ 77 bytes
```
4
2
Hello
10
Conflict
16
16
8
4
11
3
<<<<<<<
Mine
=======
Theirs
>>>>>>>
4
4
```
`4` `2` is printing line 2 (`Hello`), `10` tests whether line 0 (`4`) is identical with line 16 (the one that contains a `4` when the conflict exists) and jumps to either line 16 or line 8 depending on the result. If it existed, `4` `4` prints line 4 (`Conflict`). If it didn't, `4` `11` prints either `Mine` or `Theirs`, depending on what was merged, and `3` exits.
[Answer]
# Java 145 Bytes
```
()->{String s = "Hello ";/*
<<<<<<<
*/s+="Mine";/*
=======
*/s+="Theirs";/*
>>>>>>>
*/if(s.length()>15)s="Hello Conflict";System.out.println(s);}
```
Java has no multiline strings so some Comment trickery was needed
[Answer]
# Bash, 76 bytes
**Golfed**
```
sed 's/^/Hello /;s/<\+/Conflict/;q'<<E
<<<<<<<
Mine
=======
Theirs
>>>>>>>
E
```
**How it works**
Uses [here doc](https://en.wikipedia.org/wiki/Here_document), to feed the source text to *sed*.
*Sed* will prepend the first line it read with "Hello ", replace the `<<<<<<<` string by "Conflict" and then quit (`q`).
[Try It Online !](https://tio.run/nexus/bash#@1@cmqKgXqwfp@@RmpOTr6BvXaxvE6Ot75yfl5aTmVyib12obmPjymUDAVy@mXmpXLYQwBWSkZpZVMxlBwFcrv//AwA)
[Answer]
# ES6 (Javascript), ~~83~~, 82 bytes
**Golfed**
```
alert("Hello "+((T=`\
<<<<<<<
Mine
=======
Theirs
>>>>>>>
`)[1]>"<"?T:"Conflict"))
```
**Try It**
```
alert("Hello "+((T=`\
<<<<<<<
Mine
=======
Theirs
>>>>>>>
`)[1]>"<"?T:"Conflict"))
alert("Hello "+((T=`\
Mine
`)[1]>"<"?T:"Conflict"))
alert("Hello "+((T=`\
Theirs
`)[1]>"<"?T:"Conflict"))
```
[Answer]
# Java 8, 108 bytes
This is a lambda accepting [empty input](https://codegolf.meta.stackexchange.com/a/12696) and returning nothing.
```
n->System.out.print("Hello "+",Mine,Theirs,Conflict".split(",")[/*
<<<<<<<
*/1/*
=======
*/+2/*
>>>>>>>
*/])
```
[Try It Online](https://tio.run/##rVGxbsIwFJzjr7AyJWCM2hXI0qULE1UXxOAahzp1nq34Gamq@Pb0NQlSxcTADbZ0undn32vUWS18MNAcv/o@pA9nNddOxci3ygL/YdlERlRIV21BOd7QmExonawTaLQe5IuHmFrTrd@9PVYsy1oLhm8YLKrdd0TTSp9Qhs4CFvmrcc7zfJ6LLanE26exXRRkUVMU5jIGZ0km8nK/nLHZ8mk4DyXZCo6D@lHW8@f/3nrSPcZ9PWL6wGbENbMaMWWv2G3TZ@qRt7SEYocUftofuOpOsfzbyVCuVFqbgAUk58oVkbfPdVAM/FjY3fJrB/cOXNiF9f0v)
Approach inspired by masterX244's [Java solution](https://codegolf.stackexchange.com/a/111141).
[Answer]
# C (GCC), 110 bytes
Function submission.
```
f(){char*s[]={0,"Mine","Theirs","Conflict"};printf("Hello %s",s[/*
<<<<<<<
*/1/*
=======
*/+2/*
>>>>>>>
*/]);}
```
Approach inspired by masterX244's [Java solution](https://codegolf.stackexchange.com/a/111141).
## TIOs
* [mine](https://tio.run/##S9ZNT07@/z9NQ7M6OSOxSKs4Ota22kBHyTczL1VJRykkIzWzqBjIcM7PS8vJTC5RqrUuKMrMK0nTUPJIzcnJV1AFyhZH62txaekbgslYTeva/0AVCrmJmXkaZfmZKZoK1VycQBusuTiLUktKi/IUDKy5av8DAA)
* [theirs](https://tio.run/##S9ZNT07@/z9NQ7M6OSOxSKs4Ota22kBHyTczL1VJRykkIzWzqBjIcM7PS8vJTC5RqrUuKMrMK0nTUPJIzcnJV1AFyhZH62txaelrG4GpWE3r2v9AJQq5iZl5GmX5mSmaCtVcnEArrLk4i1JLSovyFAysuWr/AwA)
* [conflict](https://tio.run/##JY6xCsMgGITn@BQiFNSmJO1q06VLl27dQoZgtRGsFrVdxGe3P/hN93FwnDy8pKxVU5bltgYe52XKY0/uxinSk8emTIgQrt5pa2QiRXyCcUlTclPWeryDNs4DR@cG4sMRbGqA7U@glwbowkSpMIDfq3H0582T4Yw6OCBQF1T6BodHgUr9Aw)
[Answer]
## [Perl 5](https://www.perl.org/), 68 bytes
Updated after realising that the version with 6 of each delimiter works as intended, but with the actual 7 delimiters, it doesn't... Oops...
```
say"Hello ",q
<<<<<<<
!Mine!;0
=======
!Theirs!;0
>>>>>>>
&&Conflict
```
[Try the conflict online!](https://tio.run/##K0gtyjH9/784sVLJIzUnJ19BSaeQywYCuBR9M/NSFa0NuGwhgEsxJCM1s6gYJGQHAVxqas75eWk5mckl////yy8oyczPK/6v62uqZ2BoAAA "Perl 5 – Try It Online")
[Try mine online!](https://tio.run/##K0gtyjH9/784sVLJIzUnJ19BSaeQS9E3My9V0dqAS03NOT8vLSczueT//3/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online")
[Try itheirs online!](https://tio.run/##K0gtyjH9/784sVLJIzUnJ19BSaeQSzEkIzWzqFjR2oBLTc05Py8tJzO55P//f/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online")
] |
[Question]
[
Your task is to determine if a given string is of proper length and can be represented with Scrabble tiles and, if so, output the sum of each letter's score.
If you don't know how to play Scrabble:, you have 100 tiles with various letters A–Z printed on them, as well as two wildcards that can represent any letter. Each letter has a certain number of points, and each tile (but not necessarily word) can only be used once. When a word is played, the point value of each tile used is added up, which becomes the score. As there are a limited number of letters available, a word can only have a certain letter as many times as that letter has tiles + any unused wildcards. The Scrabble board is 15×15 cells, so the word must be between 2 and 15 characters long.
For a list of the quantity and score of each letter in the English version, see below or <http://boardgames.about.com/od/scrabble/a/tile_distribute.htm> ([archive](http://web.archive.org/web/20140412222004/http://boardgames.about.com/od/scrabble/a/tile_distribute.htm)).
```
Letter Qty Points Letter Qty Points
------------------- -------------------
A 9 1 O 8 1
B 2 3 P 2 3
C 2 3 Q 1 10
D 4 2 R 6 1
E 12 1 S 4 1
F 2 4 T 6 1
G 3 2 U 4 1
H 2 4 V 2 4
I 9 1 W 2 4
J 1 8 X 1 8
K 1 5 Y 2 4
L 4 1 Z 1 10
M 2 3 [wild] 2 0
N 6 1
```
## Further rules
* The program shall take a single string of input from STDIN or the like.
* The input will always contain only uppercase letters.
* If the string contains more copies of a letter than there are unused wildcards or tiles for that letter OR the string's length is not between 2 and 15 inclusive, the program should output `Invalid`.
* Otherwise, the score should be added up with using data from the chart above and output.
* Do not use wildcards unless necessary.
* Do not worry about bonuses such as double word scores or whether the string is a real word.
* The program shall output the result through STDOUT or the like.
* [Loopholes that are forbidden by default](https://codegolf.meta.stackexchange.com/q/1061/29750) are not allowed.
* Using an external source such as a website, as well as any libraries, APIs, functions, or the like that calculate Scrabble scores or proper quantities are not alllowed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins.
## Walkthrough
```
Input: CODEGOLF
C -> 3, O -> 1, D -> 2, E -> 1, G -> 2, O -> 1, L -> 1, F -> 4
3 + 1 + 2 + 1 + 2 + 1 + 1 + 4 = 15
Output: 15
```
## Testcases
```
Input Output
------------------------
SCRABBLE 14
JAZZ 19
STACKEXCHANGE 32
XYWFHQYVZVJKHFW 81
PIZZAZZ Invalid
KIXOKEJAJAX Invalid
MISUNDERSTANDING Invalid
```
[Answer]
# Perl 5 ~~228 205 186 184 178 177 153 150 149 142 137~~ 135
Run with perl -E.
Golfed:
```
$_=<>;@a=@b=map-ord,' 0 0@0 H ``'=~/./g;say s!.!($a[$q=64-ord$&]+=8)<8?$-+=1-29/$b[$q]:++$j!ge~~[2..15]&&$j<3?$-:Invalid
```
This solution uses some non-printable characters, so a hexdump is provided below:
```
00000000: 245f 3d3c 3e3b 4061 3d40 623d 6d61 702d $_=<>;@a=@b=map-
00000010: 6f72 642c 2703 0904 0909 2030 2030 030e ord,'..... 0 0..
00000020: 4030 0e20 0704 4809 1809 601d 0e0e 6027 @0. ..H...`...`'
00000030: 3d7e 2f2e 2f67 3b73 6179 2073 212e 2128 =~/./g;say s!.!(
00000040: 2461 5b24 713d 3634 2d6f 7264 2426 5d2b $a[$q=64-ord$&]+
00000050: 3d38 293c 383f 242d 2b3d 312d 3239 2f24 =8)<8?$-+=1-29/$
00000060: 625b 2471 5d3a 2b2b 246a 2167 657e 7e5b b[$q]:++$j!ge~~[
00000070: 322e 2e31 355d 2626 246a 3c33 3f24 2d3a 2..15]&&$j<3?$-:
00000080: 496e 7661 6c69 64 Invalid
```
Alternatively, using Ctrl+Key:
```
$_=<>;@a=@b=map-ord,'^C^I^D^I^I 0 0^C^N@0^N ^G^DH^I^X^I`^]^N^N`'=~/./g;print s!.!($a[$q=64-ord$&]+=8)<8?$-+=1-29/$b[$q]:++$j!ge~~[2..15]&&$j<3?$-:Invalid
```
Ungolfed+commented:
```
# Read in input
$_=<>;
# @a and @b: represents approximately 8x the number of tiles (when rounded up). The
# non-multiple-of-8 values distinguish tiles that are given equally, but are worth
# different values
@b=@a=map-ord,"...."~=/./g;
# above is equivalent to
# @a=@b=(-03,-09,-04,-09,-09,-32,-48,-32,-48,-03,-14,-64,-48,-14,-32,-07,-04,-72,-09,-24,-09,-96,-29,-14,-14,-96);
say
# for each character
s!.!
# $q: A->-1, B->-2, etc.
# decrement number of $q tiles, add points if needed, otherwise
# increment j, which counts number of wilds used
# truncate(1-29/b[q]): decimal values were chosen specifically
# for this to return the point value. b[q] is the number of tiles
# of the qth letter after a originally given.
# $- contains the score, is initially zero (if in a one line program,
# as the golfed version is), and is always an integer
($a[$q=64-ord$&]+=8)<8 ? $- += 1 - 29/$b[$q] : ++$j
# s returns length, check if between 2 and 15
!ge ~~ [2..15]
# make sure less than 3 negative tiles (aka wilds)
&& $j < 3 ?
# print score
$-
# or invalid
: Invalid
```
[Answer]
# C, Rev 2, ~~151 145~~ 138
Inspired by the 159-byte code in @bebe's comment, I squeezed another ~~8 14~~ 21 characters out:
4 bytes saved by rearranging the length counter `i`. This is initialised to 1 (assuming the program takes no arguments) then multiplied by 4 every time a letter is read. It overflows to zero when the word length is greater than 15, so to check if the word length is bad, we simply check if `i<5` (I put `i<9` so it will still give invalid for one-letter words if the user accidentally intialises `i` to 2 by putting a single argument on the command line.)
4 bytes saved by changing the loop condition test to a simple `&31`. This requires that the word is terminated with a space (ASCII 32) or a null character (ASCII 0.) Normally keyboard input is terminated by a newline (ASCII 10) so the program's a bit inconvenient to use, because you have to type the space then press return as well to get the computer to read the buffer. For newline-terminated strings, I could match but not beat the way bebe does it.
~~6~~ 13 bytes saved by changing the encoding to **-(number of tiles of each letter)-(score for that letter-1)\*13**. This now requires a range from -4 for L,S,U to -118 for Q,Z. The reason for using negative numbers is to avoid the unprintable ASCII range 0 to 31. Instead the range used is the two's complement of the negative numbers 256-4=252 to 256-118=138. These are printable, extended ASCII characters. There are issues with copying and pasting these in Unicode (the way it simplifies back to ASCII depends on the code page installed which can lead to unpredictable results) so I have included the correct ASCII codes in the program comment.
The advantage of this encoding is the elimination of the variable `r` as the number of tiles is always reduced by 1 (as it is stored as a negative number, we do `t[x]++`. Additionally, the postfix operator means we can perform this increment at the same time as adding the score to `s`.
```
//char t[]={32,247,228,228,239,244,215,240,215,247,164,203,252,228,250,248,228,138,250,252,250,252,215,215,164,215,138,0};
b,s;
main(i,x){
for(char t[]=" ÷ääïô×ð×÷¤ËüäúøäŠúüúü×פ׊";x=getchar()&31;i*=4)
t[x]%13?
s-=t[x]++/13-1:
b++;
printf(i<9|b>2?"Invalid":"%d",s);
}
```
# C,~~184~~ Rev 1 173 (or 172 with compiler option)
I'm using GCC, and with the compiler option `-std=c99` it will allow me to move `char t[]="...."` into the initialization of the `for` loop for a saving of one additional semicolon. For readability, I have shown the program without this change, and with whitespace left in.
```
#define T t[x[1][i]-65]
i,b,s;
main(int r,char**x){
char t[]="Z>>QxS=SZW6(><P>m<(<(SSWSm";
for(;x[1][i];i++)
T/10?
s+=r=T%10+1,T-=r*10:
b++;
printf(i<2|i>15|b>2?"Invalid":"%d",s);
}
```
The trick is in the datatable. For each letter an ASCII code of the form **(total score of tiles for that letter)\*10+(score of one tile-1)** is stored in the table `t[]`. At runtime, these total scores are reduced as tiles are used up.
The total score of all the tiles for each letter ranges from 12 for E down to 4 for L,S,U. This form of encoding enables only printable ASCII characters to be used (ASCII 120,`x` for E down to ASCII 40,`(` for L,S,U.) Using the *number* of tiles would need a range from 120 down to 10, which is why I avoided it.
Thanks to a `#define` macro, a single symbol `T` is used in the main program to retrieve the letter index `i`from the first commandline argument, subtract ASCII `A`=65 from it to give an index ,and look it up in the table T: `t[x[1][i]-65]`.
The `for` loop is used more like a `while` loop: the loop ends when a zero byte (string terminator) is encountered in the input string.
If the tiles of that letter are not exhausted (`T/10` is nonzero) `s` is incremented by the tile score `T%10+1` to keep a total score. At the same time the tile score is stored in `r`, so that the value in the able represented by `T` can be decremented by `r*10` to indicate that one tile has been used. If the tiles are exhausted, the wildcard/blank counter `b` is incremented.
The `printf` statement is fairly self-explanatory. if the wordlength is out of bounds or the blank count is too high, print `Invalid` otherwise print the score `s`.
[Answer]
# JavaScript (ES6) - ~~241~~ ~~230~~ ~~199~~ 182
```
f=s=>{for(i=t=_=0,E=12,A=I=9,B=C=M=P=28,D=17,F=H=V=W=Y=41,G=16,J=X=92,K=53,L=S=U=4,N=R=T=6,O=8,Q=Z=118;c=s[i++];)this[c]%13<1?_++:t+=1+this[c]--/13|0;alert(i<3|i>16|_>2?"Invalid":t)}
```
*Edit* - changed the way I encoded the quantities/scores to reduce size and remove non-ascii variables
*Edit 2* - changed the quantity/score encodings to integers instead of strings
*Edit 3* - switched to `%13` (thanks @edc65), inverted the encoding, modified the values directly, and a few other minor improvements
Tested in Firefox console.
[Answer]
# Python 3, ~~217~~ 201
```
b=2;i=s=0;w=input()
while i<26:n=w.count(chr(i+65));q=int('9224c232911426821646422121'[i],16);b-=max(0,n-q);s+=min(n,q)*int('1332142418513113a11114484a'[i],16);i+=1
print(["Invalid",s][-b<1<len(w)<16])
```
Ungolfed:
```
b=2 # number of blanks available
i=s=0 # letter index 0..25, running score tally
w=input()
# Loop through each letter of the alphabet
while i<26:
# Get number of occurrences in the word
n=w.count(chr(i+65))
# Get quantity of the letter from hex encoded string
q=int('9224c232911426821646422121'[i],16)
# Remove blanks for each occurrence over that letter's quantity
b-=max(0,n-q)
# Score the non-blank tiles, getting scores from hex-encoded string
s+=min(n,q)*int('1332142418513113a11114484a'[i],16)
# Increment
i+=1
# If b > -1 and 1 < len(w) < 16, print the score; otherwise, print "Invalid"
print(["Invalid",s][-b<1<len(w)<16])
```
**Edit:** Thanks to @BeetDemGuise for a tip that ultimately led me to much more than a 1-character reduction! Original code below:
```
q=[77-ord(x)for x in'DKKIAKJKDLLIKGEKLGIGIKKLKL'];b=2;s=0;w=input()
for c in set(w):n=w.count(c);o=ord(c)-65;b-=max(0,n-q[o]);s+=min(n,q[o])*(1+int('02210313074020029000033739'[o]))
print(["Invalid",s][-b<1<len(w)<16])
```
[Answer]
# BEFUNGE 93 - 210 bytes.
But it doesn't check the 15 letter limit.
```
v1332142418513113:11114484: >01g:"0"-!#v_1-01p1+\v
9224<232911426821646422121v "Invalid"< vp0<
<vp00p10"20"p200p900
>>~:55+-!#v_"@"-::1g:"0"-! #^_1-\1p0g+"0"-02g+>02p
_v#:-1< #p90+g90-"0"g1:<
@.g20< @,,,,,,,<
```
[Answer]
# C, 197
Assumes the string is provided as a command line argument, e.g. `./scrabble STACKEXCHANGE`
```
s;n;m=31;main(int c,char**v){char d[]="BIBBDLBCBIAADBFHBAFDFDBBABA@ACCBADBDAHEACAACJAAAADDHDJ";for(;c=*v[1]++&m;d[c]--,s+=d[c+27]&m)n+=1+m*(!(d[c]&m||d[c=0]&m));printf(n>1&&n<16?"%d":"Invalid",s);}
```
[Answer]
# JavaScript - 232 201
```
t=[9,2,2,4,12,2,3,2,9,1,1,4,2,6,8,2,1,6,4,6,4,2,2,1,2,1];w=r=0;for(i=y=z.length;i--;){x=z.charCodeAt(i)-65;if(!t[x])w++;else{t[x]--;r+=-~"02210313074020029000033739"[x]}}alert(w>2|y<2|y>15?"Invalid":r)
```
`z` stores word. Outputs as alert.
*Edit:* improved as per recommendations below.
[Answer]
# Haskell - 538
Save it as scrabble.hs and then compile it using
```
ghc --make scrabble && ./scrabble
```
Then enter your word as input and press enter
```
l=['A'..'Z']
sc=zip l [1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10]
vfs a y =snd $ filter (\x -> fst x == y) a !! 0
q = zip l [9,2,2,4,12,2,3,2,9,1,1,4,2,6,8,2,1,6,4,6,4,2,2,1,2,1]
i s =filter (\x -> (fst x) >=0) [(length [x | x <- s, x == a] - vfs q a,a) | a <- l]
main = do
s <- getLine
if length s <= 15 && length s > 2 && sum (map fst (i s)) <= 2 then
putStrLn $ show (sum [vfs sc x| x <- s] - sum [(vfs sc (snd x)) * (fst x) | x <- (filter (\x -> fst x > 0) (i s))])
else do
putStrLn "Invalid"
```
[Answer]
# Python 2.7 - 263
I couldn't come anywhere close to [DLosc's answer](https://codegolf.stackexchange.com/a/35792/8777), but this treats each letter as a 'bag' that you pull from, until its empty, then you pull blanks, and when that is empty it errors.
```
S=input().lower()
X={chr(97+i):[int(y)+1]*(77-ord(x))for i,(x,y)in enumerate(zip('DKKIAKJKDLLIKGEKLGIGIKKLKL','02210313074020029000033739'))}
B=[0,0]
try:
if len(S)>15:1/0
print sum(map(lambda x:X[x].pop()if len(X[x])>0 else B.pop(),S))
except:
print "invalid"
```
[Answer]
# Haskell, ~~290~~ 283
As far down as I could make it for now:
```
import Data.List
t="CdC8d::Od;D;d41N:dd:6dNdN;;4;6"
s w@(_:_:_)=let d=concat(zipWith(replicate.(`div`11).f 33)t("AEIO"++['A'..]))\\w;y=drop 15w in if length(d++w++y++y++y)>100 then s""else show$187-(sum$map((`mod`11).f 0.(t!!).f 61)d)
s _="Invalid"
f n=(-n+).fromEnum
main=interact s
```
This code abides by the rules very strictly, so make sure you don't pass it any extra characters (such as end-of-line). Use like this: `echo -n "JAZZ" | runghc scrabble.hs`.
## Explanation
The pattern `(_:_:_)` makes sure that only strings of at least two characters are considered, everything else results in `"Invalid"` (fallback pattern `_`). The table of tiles is encoded as `11*nTiles+value` converted to ASCII with an offset that allows the lookup modulo 11 to work, where the letters `AEIO` are duplicated because they occur more than 6 times each. The pool of tiles is then created using `replicate`, from which the characters in the word are removed as they occur (list difference, `\\`). The pool contains 98 tiles, so if the total length of the word and the remaining part of the pool is larger then 100, then we have used too many wildcards. Also, the word minus the first 15 letters is added three times to the length computation so any word longer than 15 letters automatically appears to use up three wildcards and therefore is invalid. Scoring is done on the remaining pool, which initially had 187 points, which we simply subtract from. Note the `f 61` rather than `f 65`, 65 being the ASCII number of `'A'`, because of the duplicate `"AEIO"` at the beginning of the pool. The rest is just boilerplate.
[Answer]
## Python3 - 197
```
s,i,c,r=input(),0x1a24182424416141611a2381612341151891243224c142232391,[],[]; p=len(s)
for w in s:e=8*ord(w)-520;c+=[s.count(w)<=i>>e+4&15];r+=[i>>e&15]
print(['Invalid',sum(r)][all([p>2,p<15]+c)])
```
Let's put the bignums to use :D
(It doesn't handle wildcards currently, I've skipped reading that rule entirely, damn)
[Answer]
# Ruby - 195
```
b=2
i=s=0
w=$*[0]
(?A..?Z).map{|l|n=w.count(l);q='9224c232911426821646422121'[i].to_i(16);b-=[0,n-q].max;s+=[n,q].min*'1332142418513113a11114484a'[i].to_i(16);i+=1}
p(-b<1&&w.size<16?s:'Invalid')
```
I'm assuming the output of `"Invalid"` is fine, if not I would need to do `$><<(-b<1&&w.size<16?s:'Invalid')` which would bump it up to 198
# Clojure - 325
I haven't done clojure in a while so I'm sure there are several ways to improve my solution .ie the qty and pts lists
```
(let[w(first *command-line-args*)o(map #(count(filter #{%}(seq w)))(map char(range 65 91)))i(apply +(filter neg?(map #(- % %2)'(9 2 2 4 12 2 3 2 9 1 1 4 2 6 8 2 1 6 4 6 4 2 2 1 2 1) o)))](println(if(or(> -2 i)(not(<= 2(count w)15)))"Invalid"(apply +(map #(* % %2)o'(1 3 3 2 1 4 2 4 1 8 5 1 3 1 1 3 10 1 1 1 1 4 4 8 4 10))))))
```
Some what Un-golfed
```
(let [word (first *command-line-args*)
letters (map char(range 65 91))
occ (map #(count (filter #{%} (seq word))) letters)
invalid (apply + (filter neg? (map #(- % %2)
'(9 2 2 4 12 2 3 2 9 1 1 4 2 6 8 2 1 6 4 6 4 2 2 1 2 1)
occ)))
score (apply + (map #(* % %2) occ '(1 3 3 2 1 4 2 4 1 8 5 1 3 1 1 3 10 1 1 1 1 4 4 8 4 10)))]
(println
(if (or (> -2 invalid)
(not (<= 2 (count word) 15)))
"Invalid"
score)))
```
[Answer]
# ES6: 184 (non-strict)
`w` is assumed to already contain the word. `r` is the output string.
```
i=0,o=[..."291232342c124322491181541236181231a61416141242418241a"].map(c=>parseInt(c,16)),r=!w[16]&&w[2]&&[...w].every(c=>o[c=c.charCodeAt()*2-129]-->0?i+=o[c+1]:o[0]--)?i+"":"Invalid"
```
Here's it explained and a little less golfed:
```
// The sum.
i = 0,
// The data for the letters. It's encoded similar to the Ruby version, with
// the first being the wildcard holder. The rest hold in hex form the
// following: first = quantity left, second = value.
// The .map(c => parseInt(c, 16) simply parses all the hex characters.
o = [..."291232342c124322491181541236181231a61416141242418241a"]
.map(c => parseInt(c, 16)),
// The result, `r`.
r = !w[16] || // If there is a 16th character in the word or no 2nd character,
w[2] && // then the next section isn't evaluated. It immediately equates
// to true, thus returning "Invalid".
[...w] // Convert the string into an array of characters (ES6 equivalent to
// `.split('')`
.every(c => // This loop terminates when the callback returns a falsy
// value.
// Gets the ASCII value, subtracts 65, doubles it (the lookup table is
// in pairs within one array), and decrements the counter at that entry.
// The lookup table also doubles as a data holder.
o[c = c.charCodeAt() * 2 - 129]--
> 0 ? // Test if there is something to take away. This must return
// false at 0 and -1 so wildcards can be taken.
i += o[c+1] : // If there was something to take away, then add the
// letter value to the sum.
o[0]--) // Otherwise, take a wildcard. If this is already at 0, then
// it returns falsy.
? "Invalid" : i + "" // This is where the text is returned.
```
[Answer]
## Dart - 201
```
main(a,{x:0xa14281424214161416a132181632145181194223421c24323219,i,r:0,m,s:2}){if((m=a[0].length)>1&&m<16)for(i in a[s=0].codeUnits)x>>(m=i*8-520)&15>0?r+=(x-=1<<m)>>m+4&15:++s;print(s<2?r:"Invalid");}
```
This requires bignums, so it won't compile to JavaScript.
With more whitespace:
```
main(a,{x:0xa14281424214161416a132181632145181194223421c24323219,i,r:0,m,s:3}){
if((m=a[0].length)>1&&m<16)
for(i in a[s=0].codeUnits)
x>>(m=i*8-520)&15>0
? r+=(x-=1<<m)>>m+4&15
: ++s;
print(s<3?r:"Invalid");
}
```
[Answer]
# PHP, ~~180~~ ~~170~~ 168 bytes
```
for($q=str_split(KDKKIAKJKDLLIKGEKLGIGIKKLKL);$o=31&ord($argv[1][$i++]);)$s+=$q[$o]++>L?$q[0]++>L?$f=1:0:X02210313074020029000033739[$o]+1;echo$f|$i<3|$i>16?Invalid:$s;
```
Yay! beating JS!
**breakdown**
```
for(
$q=str_split(KDKKIAKJKDLLIKGEKLGIGIKKLKL); // init quantities: L=1,A=12
$o=31&ord($argv[1][$i++]); // loop through characters: map to [1..26]
)
$s+= // increase score by ...
$q[$o]++>L? // old quantity below 1?
$q[0]++>L?$f=1 // no more wildcards? set error flag
:0 // wildcard: 0 points
:X02210313074020029000033739[$o]+1; // else: letter score
echo$f|$i<3|$i>16?Invalid:$s; // output
```
I´m so glad there is no letter score larger than 10.
] |
[Question]
[
*Alternatively, guess who's doing a course on operating systems*
Round Robin scheduling is a way to schedule ready processes in an operating system. Each process in the queue is run for a certain amount of time (quantum), interrupted after that time (if not yet finished), and then added back to the ready queue for another round.
Your task today is to print the order that tasks are executed in a round robin simulation.
## The Challenge
Given a list of `[int, int]` (both > 0), as well as a quantum, return a list of `int` representing the order that processes were executed. Assume that all the processes arrive at the same time.
The list of `[int, int]` represents a (simplified) list of processes. The two ints are the process id and service time (the time the process needs to fully run).
For example:
```
[[1, 5], [2, 10], [3, 3], [4, 12]]
```
Represents the following processes
| Process ID | Service Time |
| --- | --- |
| 1 | 5 |
| 2 | 10 |
| 3 | 3 |
| 4 | 12 |
The quantum is an integer > 0 that represents the time slice dedicated to each process. A quantum of 4 means that each process is executed for 4 time units before being interrupted and then added to the ready queue.
If a quantum is larger than the time left on a process, then the next process is selected after the running process ends.
## Worked Example
Using the above process list (`[[1, 5], [2, 10], [3, 3], [4, 12]]`), and a quantum of `4`, the process execution order will be:
```
t = 0
(head) (tail)
ready queue = [1, 2, 3, 4]
time left = [5, 10, 3, 12]
Select process 1 to run for 4 time units
t = 4
interrupt process 1
(head) (tail)
ready queue = [2, 3, 4, 1]
time left = [10, 3, 12, 1]
Select process 2 to run for 4 time units.
t = 8
interrupt process 2
(head) (tail)
ready queue = [3, 4, 1, 2]
time left = [3, 12, 1, 6]
Select process 3 to run for 3 time units
t = 11
process 3 finished
(head) (tail)
ready queue = [4, 1, 2]
time left = [12, 1, 6]
Select process 4 to run for 4 time units
t = 15
interrupt process 4
(head) (tail)
ready queue = [1, 2, 4]
time left = [1, 6, 8]
Select process 1 to run for 1 time unit
t = 16
process 1 finished
h t
ready queue = [2, 4]
time left = [6, 8]
Select process 2 to run for 4 time units
t = 20
interrupt process 2
h t
ready queue = [4, 2]
time left = [8, 2]
Select process 4 to run for 4 time units
t = 24
interrupt process 4
h t
ready queue = [2, 4]
time left = [2, 4]
Select process 2 to run for 2 time units
t = 26
process 2 finished
h t
ready queue = [4]
time left = [4]
Select process 4 to run for 4 time units
t = 30
process 4 finished
no more proceses in the queue.
```
Therefore, the order of processes executed is:
```
[1, 2, 3, 4, 1, 2, 4, 2, 4]
```
## Rules
* Input can be taken as `list[list[int, int]], int`, `list[int], list[int], int`, or some other reasonable input method.
* The processes and quantum can be taken in any order.
* For example:
```
list[int: processIds]
list[int: serviceTimes]
int: quantum
```
or
```
list[int: serviceTimes]
int: quantum
list[int: processIds]
```
or any other combination.
* Output can be `list[int]`, `str` (joined on newlines, or spaces, or any constant delimiter) or some other reasonable output method.
* There will always be at least one process.
* The process ids list will always be a permutation of the range `[1, number of processes]`.
* The process ids can be 0-indexed if you want it to be for some reason. Using 0-indexing, the ids list will always be a permutation of the range `[0, number of processes]`.
* The order of the process ids list is important - processes are executed in the order they arrive (in a first come first serve manner). That is how the ready queue in an actual RR simulation works after all (FCFS selection strategy, with pre-emption on time quantums).
## Test Cases
```
processes, times, quantum => order
[1, 2, 3, 4], [5, 10, 3, 12], 4 => [1, 2, 3, 4, 1, 2, 4, 2, 4]
[5, 4, 3, 2, 1], [20, 20, 20, 20, 20], 4 => [5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5], [3, 3, 3, 3, 8], 4 => [1, 2, 3, 4, 5, 5]
[1, 2, 3, 4, 5], [3, 3, 10, 3, 8], 2 => [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 3, 5, 3, 5, 3]
[1], [20], 5 => [1, 1, 1, 1]
[1], [19], 4 => [1, 1, 1, 1, 1]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
÷Ċ⁵x"ZẎ
```
A full program that accepts `Times Quantum ProcessIds` and prints the schedule.
**[Try it online!](https://tio.run/##y0rNyan8///w9iNdjxq3VihFPdzV9////2hjHQUgMjQAUxax/43@R5vqKBjpKJgARYGCsQA "Jelly – Try It Online")**
### How?
```
÷Ċ⁵x"ZẎ - Main Link: Times, Quantum
√∑ - {Times} divided by {Quantum}
Ċ - ceiling -> {SlotCounts}
⁵ - program's third argument -> ProcessIds
" - {ProcessIds} zip {SlotCounts} with:
x - {ProcessId} times {SlotCount}
Z - transpose
Ẏ - tighten
- implicit print
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 17 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{0~⍨,⍉↑⍺/⍨¨⌈⍵÷⍺⍺}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=qzaoe9S7QudRb@ejtomPenfpA3mHVjzq6XjUu/XwdqAAENUCAA&f=K3nUNqFao0ChRKFQE8h81DfVK9jf71FHl3q0@qPereqx6gqPulsUHnU1FWgUKqRpltRycZWoRxvqKBjpKBjrKJjE6ihEm@ooGBqAuYZGQL6JOkgJUNAELAZUaAhSZQRUgorhahHG6SiYgtQag3kQZEFIGdRukDojiDqIdUDSFME3tASbAwA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
An operator that takes the quantum as `⍺⍺`, times as right argument `⍵` and 1-indexed process ids as left argument `⍺`.
`⌈⍵÷⍺⍺` times divided by quantum, rounded up.
`⍺/⍨¨` For each result, make a vector with the corresponding process id repeated that many times.
`‚Üë` Join the vectors into a rectangular matrix, padding shorter vectors with 0s.
`,‚çâ` Transpose matrix, then flatten into vector.
`0~‚ç®` Remove 0s from vector.
[Answer]
# Excel, 45 bytes
```
=TOCOL(IF(A2#-A3*(ROW(1:99)-1)>0,A1#,NA()),2)
```
Quantum in cell `A3`, Process IDs and Service Times in spilled, *horizontal* ranges `A1#` and `A2#` respectively.
Returns a vertical array.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 46 bytes
```
{2*:'/-1_(#:){(1_y),(0<*|x)#,x:(*y)-0,x}[x]\y}
```
[Try it online!](https://ngn.codeberg.page/k#eJydT11PwjAUfb+/onaJbbcC69gSvRP1tW+w122ZRIfxAdEBZgTht9uOj2wGX0xub3t6zrkfM9wGLrJBTxXcQbHlqtgIyf0797sWjqyRuxvR82W9S+s82+wABvBRLZ7L5bJcSrJ6m9vrcz19X63nZHRPFtVLWUGqJAkkGUoS5pKkkSTKb6AKDA6tsCUx3807POQcrCFsOIOVrRAYe/ec63S0kvwf5tCZKbJ9hw06xM3F0SOr/NN5XNtag0vWX3DYzrbqYXeTo5P7GCdS3banavMZgEZV6MfrPdcPktFBllHB+JWj0cenafX6RZQA4DpOBHrU1qAZMw7g43gi0CdB4fUZ45ymdCQKwRg1zYxGA2r0uDuJPeaNBWCCfZZAsp/1DfcDwUF7gg==)
[Answer]
# [Headass](https://esolangs.org/wiki/Headass), 58 bytes
```
U{R])]O:]-[};{N)UO}:NE.UO[N):-E;UP^U][{N)UO}:](>):DOD]O;NE
```
Takes input as a list like `quantum, id_1, servicetime_1, id_2, servicetime_2...` with each argument on a separate line. I've gone ahead and made links for each individual test case because I know it's a bit cumbersome to translate.
[Test case 1](https://dso.surge.sh/#@WyJoZWFkYXNzIiwiIiwiVXtSXSldTzpdLVt9O3tOKVVPfTpORS5VT1tOKTotRTtVUF5VXVt7TilVT306XSg+KTpET0RdTztORSIsIiIsIjRcbjFcbjVcbjJcbjEwXG4zXG4zXG40XG4xMiIsIiJd) [Test case 2](https://dso.surge.sh/#@WyJoZWFkYXNzIiwiIiwiVXtSXSldTzpdLVt9O3tOKVVPfTpORS5VT1tOKTotRTtVUF5VXVt7TilVT306XSg+KTpET0RdTztORSIsIiIsIjRcbjVcbjIwXG40XG4yMFxuM1xuMjBcbjJcbjIwXG4xXG4yMCIsIiJd) [Test case 3](https://dso.surge.sh/#@WyJoZWFkYXNzIiwiIiwiVXtSXSldTzpdLVt9O3tOKVVPfTpORS5VT1tOKTotRTtVUF5VXVt7TilVT306XSg+KTpET0RdTztORSIsIiIsIjRcbjFcbjNcbjJcbjNcbjNcbjNcbjRcbjNcbjVcbjgiLCIiXQ==) [Test case 4](https://dso.surge.sh/#@WyJoZWFkYXNzIiwiIiwiVXtSXSldTzpdLVt9O3tOKVVPfTpORS5VT1tOKTotRTtVUF5VXVt7TilVT306XSg+KTpET0RdTztORSIsIiIsIjRcbjFcbjNcbjJcbjNcbjNcbjEwXG40XG4zXG41XG44IiwiIl0=) [Test case 5](https://dso.surge.sh/#@WyJoZWFkYXNzIiwiIiwiVXtSXSldTzpdLVt9O3tOKVVPfTpORS5VT1tOKTotRTtVUF5VXVt7TilVT306XSg+KTpET0RdTztORSIsIiIsIjVcbjFcbjIwIiwiIl0=) [Test case 6](https://dso.surge.sh/#@WyJoZWFkYXNzIiwiIiwiVXtSXSldTzpdLVt9O3tOKVVPfTpORS5VT1tOKTotRTtVUF5VXVt7TilVT306XSg+KTpET0RdTztORSIsIiIsIjRcbjFcbjE5IiwiIl0=)
### Explanation:
Pretty straightforward, just subtracts the quantum from each service time, checks if the service time has been used up, and decides whether to keep the values on the queue.
```
U{R])]O:]-[};{N)UO}:NE. code block 0
U take quantum (q)
{R])]O:]-[}; negate q and store on queue:
{ } loop
R]) if q + r2 == 0
]O store r2 on queue
: ; break from loop
else
]-[ decrement r2
end loop
{N)UO}: store the remaining inputs on the queue:
{N) }: while there are still inputs
UO store input on queue
NE go to code block 1
. end code block
UO[N):-E;UP^U][{N)UO}:](>):DOD]O;NE code block 1
UO keep q at top of queue
[ r2 = q
N): if there are no items left on the queue
-E go to block -1 (error, halt)
; endif
UP print the id on top of queue
^ r1 = id
U][ r2 = remaining service time + r2
{N)UO}: retain remaining values on the queue
](>): if r2 > 0
DO put r1 on bottom of queue
D]O put r2 on bottom of queue
; endif
NE go to code block 1
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 44 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 5.5 bytes
```
/⌈$ẋ∩f
```
**[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiL+KMiCThuoviiKlmIiwiIiwiMlxuWzMsIDMsIDEwLCAzLCA4XVxuWzUsIDIsIDQsIDEsIDNdIl0=)**
### How?
Port of my Jelly answer.
```
/⌈$ẋ∩f - [Quantum, Times, ProcessIds]
/ - divide -> [Times/Quantum, ProcessIds]
‚åà - ceil -> [SlotCounts, ProcessIds]
$ - swap -> [ProcessIds, SlotCounts]
ẋ - repeat -> [RepeatedProcessIds]
‚à© - transpose -> [ProcessIdSublists]
f - flatten -> [Schedule]
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~23~~ 21 bytes
-2 bytes from @Bubbler's improvement
```
{y[&r]@<,/!'r:-_-z%x}
```
[Try it online!](https://ngn.codeberg.page/k/#eJydUNtugzAMfc9XeNIurRQKCaRqyTbtI/aG0MogtKhcWgIS3bR9+xIoLVSdNE1xHB/7nNhJ7H4evPvSf3nE5s1D6Rpvxsdd84XQq/t56x2+SzeGGTR8VWz5ZBUHScobfuDl1Nccb+JwAhRscDgDYqmA0GmfAn06evsdlSlkK0w4tWBg03MF/hj5o+bAuA3dWpzbM2AtjV7Q2jlHvHNk97tVMo4Jx3pAAu06ttVZsjxldR6ZaFNVO+maZlhEYl2k8UxWQbgVTbgJ8rWYhUVm7mshq6TIpUnnzJpbpkyyOg0qYZRFnUfKvye5IcONiOo0ydcI7coiFFIKiaFKMn3s6yCv6gyenqEoI1Eij2CgGGysPhqDx7B6YQsJVdjRxAFFpdvY6byPtMBpawoTfQNV8vE+3TPiYvg/9NFoJqb72i3qbHF1dKaZvyqPz9ZSek16Ae2h17d2b1ee9eqj9UWyHE41rP8AUlm2KQ==)
Takes three arguments, `x` (quantum), `y` (processes), and `z` (times).
Based on @frasiyav's [BQN answer](https://codegolf.stackexchange.com/a/265123/98547).
* `r:-_-z%x` calculate the ceiling of the times (`z`) divided by the quantum (`x`), and store it in variable `r`
* `<,/!'` generate `0..r-1` for each value in `r`, flatten them into a list, and then grade-up them (this is related to an "occurrence count")
* `y[&r]@` use this to index into a list containing the correct number of copies of each process ID
[Answer]
# [J](https://www.jsoftware.com), 21 bytes
```
(/:1#.]=]\)@#~>.@%&>/
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrsVVD38pQWS_WNjZG00G5zk7PQVXNTh8id4sxU5PLz0lPoaQoMa-4IL84VSGxoKAoPzE5AyxsoKtXZ6DjUGNl56Bh46CsZADTrsmVmpyRr2CoYKRgrGACpk3AWNcKLpimYKpgaABkGhopWCuYQHSYAiWMgQoMiWYBTURw0hSMDFAQ3GCYraZAiOQIU6AWYyi0wKYawTKGYyz6wR4BGWAEMwACwUrTIC4xRZWCSxpagiyGhPiCBRAaAA)
The Jelly / APL transpose approach was too verbose in J so I found a sorting based approach. Consider this example `1 2 3 4 f 5 10 3 12 ; 4`:
* `>.@%&>/` It starts the same as the APL approach dividing the times by the quantum and taking the ceiling:
```
2 3 1 3
```
* `#~` It uses that mask to duplicate the process ids in place:
```
1 1 2 2 2 3 4 4 4
```
* `(/: )@` Now we finish by applying a single sort... we just need to find the correct ordering...
* `]=]\` This creates the prefix lists with zero fill on the right, and then asks, "Where does each element equal that value?" Thus each element is compared to a row:
```
1 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0
0 0 1 1 0 0 0 0 0
0 0 1 1 1 0 0 0 0
0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 1 1 0
0 0 0 0 0 0 1 1 1
```
* `1#.` Now when we sum each row we get a running count of how many times each element has appeared so far:
```
1 2 1 2 3 1 1 2 3
```
This is exactly the ordering we need to achieve the round robin.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 56 bytes
```
f@q_=#&@@@Flatten[#~Partition~UpTo@q&/@Table@@@#,{2,1}]&
```
[Try all test cases online.](https://tio.run/##dY0xC4MwEIX3/oqA4HRQLxpoh8JNnR3sJFLSojRQtcptEv96qhGHFl3eN7zv3dWaX2Wt2Ty1cxV190sQEtH1rZnLJg/GVPds2LTNePtkLXXhkTL9eJeTFMAgAW0RurQ3DeeiypNCkBgGBGV9GU2IIZ4yAZTWiuLw7yqQke/lInvIBThja4T@pvS53p9TwenXl1s@RvsDtQ52P@N5LtwX "Wolfram Language (Mathematica) – Try It Online") Defines a function named `f` that takes its arguments in a format like (for the first test case)
`f[4][{{1,5},{2,10},{3,3},{4,12}}]`.
The code isn't all that short, but I learned something about `Flatten` that made me want to share this approach. Using the first test case:
* `Table@@@#` evaluates to `{ {1,1,1,1,1}, {2,2,2,2,2,2,2,2,2,2}, {3,3,3}, {4,4,4,4,4,4,4,4,4,4,4,4} }`.
* `#~Partition~UpTo@q&` operates on each element of that list, yielding `{ { {1,1,1,1}, {1} }, { {2,2,2,2}, {2,2,2,2}, {2,2} }, { {3,3,3} }, { {4,4,4,4}, {4,4,4,4}, {4,4,4,4}, {4,4,4,4} } }`.
* Next we want to transpose this array (an array in which each element is a short constant list of length at most 4); but `Transpose` doesn't handle ragged lists—the idiom for that in Mathematica is `Flatten[#,{2}]`. This would yield `{ { {1,1,1,1}, {2,2,2,2}, {3,3,3}, {4,4,4,4} }, { {1}, {2,2,2,2}, {4,4,4,4} }, { {2,2}, {4,4,4,4} }, { {4,4,4,4} } }`.
* It turns out that we want to partially flatten this resulting list as well; so we could apply `Flatten[#,{1}]` to it (we could've also applied `Join` suitably). Now here's the cool bit I never realized before: `Flatten[#,{2,1}]` will cheerfully flatten the list first at the second level and then at the first level—in that "wrong" order! The result is `{ {1,1,1,1}, {2,2,2,2}, {3,3,3}, {4,4,4,4}, {1}, {2,2,2,2}, {4,4,4,4}, {2,2}, {4,4,4,4}, {4,4,4,4} }`.
* Now all that's left is to take the first element of each list (using `#&@@@`), which gives `{ 1, 2, 3, 4, 1, 2, 4, 2, 4, 4 }`.
[Answer]
# JavaScript (ES6), 57 bytes
Expects `(serviceTimes)(quantum)(processIds)`, using 0-indexed process IDs. Returns a space-separated string.
```
t=>q=>g=([n,...p])=>1/n?n+' '+g((t[n]-=q)>0?[...p,n]:p):p
```
[Try it online!](https://tio.run/##pZHBbsMgDIbvfQrfCqpLEpJKWyfoaU@BOERZk26qgLTRXj8jkLZJVeUyCwy/ZT6M@Sl/y2t1@Xbd1tivY1@LvhOyFbIRRBlkjDlNhcwSczCbNaw3DSGdMnorWirTgxoS0Oi9o3vXf6gVgAKVImQIHCHXCGrnlY/kfuFeF3A3r5LEH3jk47jPowcdgUWI8BBMByb3afMZyDfgLB//IW8FTCsshgLysI3j7fGqVy8qQmWLnLE/A4gvcZ4kn/r7FbE/3u9gySZXjGNGyN7nf/WKAM@ECNErVtvLZ1mdCFEOoUNoNQUhobLmas9HdrYNqUlHSUuJo5T2fw "JavaScript (Node.js) – Try It Online")
### Commented
```
t => // t[] = array of service times
q => // q = quantum
g = ([ // g is a recursive function taking:
n, // n = ID of next process
...p // p[] = array of remaining process IDs
]) => //
1 / n ? // if n is defined:
n + ' ' + // append n followed by a space
g( // followed by the result of a recursive call:
(t[n] -= q) // subtract q from the n-th service time
> 0 ? // if the result is positive:
[...p, n] // still running: put back n at the end of p[]
: // else:
p // kill the process by just passing p[]
) // end of recursive call
: // else:
p // stop the recursion (p[] is now empty)
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 16 [bytes](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
{‚çã‚àò‚äí‚ä∏‚äè‚åà‚àò√∑‚üúùﮂä∏/Àùùï©}
```
[Try it here.](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge+KNi+KImOKKkuKKuOKKj+KMiOKImMO34p+c8J2VqOKKuC/LnfCdlal9CgrigKJTaG93IDQgRiBbWzUsIDEwLCAzLCAxMl0sWzEsIDIsIDMsIDRdXQrigKJTaG93IDQgRiBbWzIwLCAyMCwgMjAsIDIwLCAyMF0sIFs1LCA0LCAzLCAyLCAxXV0K4oCiU2hvdyA0IEYgW1szLCAzLCAzLCAzLCA4XSwgWzEsIDIsIDMsIDQsIDVdXQrigKJTaG93IDIgRiBbWzMsIDMsIDEwLCAzLCA4XSwgWzEsIDIsIDMsIDQsIDVdXQrigKJTaG93IDUgRiBbWzIwXSwgWzFdXQrigKJTaG93IDQgRiBbWzE5XSwgWzFdXQpACg==)
Takes the quantum as the left argument `ùï®` and an array of `[serviceTimes, processIds]` as the right argument `ùï©`.
How it works:
```
{‚çã‚àò‚äí‚ä∏‚äè‚åà‚àò√∑‚üúùﮂä∏/Àùùï©}
Àùùï© # Apply between rows of the right argument:
‚ä∏/ # replicate the ids by
‚åà‚àò√∑‚üúùï® # the ceil of serviceTimes divided by the quantum.
⊸⊏ # Then, reorder the result according to:
‚äí # the running occurrence count
⍋∘ # graded by ascending order.
```
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 17 bytes
```
/ |^"*`"zip tpose
```
[Try it on scline!](https://scline.fly.dev/#H4sIAHwo_WQCA4s2VDBSMFYwiVWINlUwNAAyDY1iFUwUrAEuP78nGQAAAA#H4sIAHwo_WQCA9NXqIlT0kpQqsosUCgpyC9OBQDiHFH_EQAAAA) Way simpler than I thought...
## Explanation
* `/ |^` Divide each service time by quantum and round up
* `"*`"zip` repeat each process number by previous results
* `tpose` transpose - this fortunately works with uneven lists-of-lists!
---
# [sclin](https://github.com/molarmanful/sclin), 54 bytes
```
=$n.
dups"; @"&#
1_ roll0.: Q n>o0$n , -1.: Q0>"pop"|#
```
[Try it on scline!](https://scline.fly.dev/#H4sIAFMe_WQCA4s2VDCNVYg2UjA0AFLGCsZA0kTB0ChWwUTBGgD0.1EZHQAAAA#H4sIAFMe_WQCA7NVydPjSiktKFayVnBQUlPmMoxXKMrPyTHQs1IIVMizyzdQyVPQUdA1BPEN7JQK8guUapQBr7tOtTYAAAA) Initial solution.
## Explanation
Prettified code:
```
=$n.
dups ( ; @ ) &#
1_ roll 0.: Q n>o 0 $n , - 1.: Q 0> \pop |#
```
Takes processes input as a list of `[int int]`.
* `=$n` quantum as *n*
* `dups ( ; @ ) &#` if stack is not empty, execute next line and loop...
+ `1_ roll` rotate bottom of stack to the top
+ `0.: Q n>o` output process number
+ `0 $n , -` decrement service time by *n*
+ `1.: Q 0> \pop |#` if service time <= 0, then pop from the stack
[Answer]
# [Python](https://www.python.org), 61 bytes
```
lambda q,i:[I for Q in range(max(i)[0])for C,I in i if C>q*Q]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nVFNSwMxEMXr_oqhp6SMsp9QC9tLT4Veise4h1g3GtiP7LqKevVneCmI_if9NWZ2t5JKvQiTIS9v3psZ8vphnrrbutq9qfTy_b5Tp7PPtJDl1bWEBvVcrEDVLWxAV9DK6iZnpXxkmgs_40QscUWUBq1guWimm2w0uSB2TVxt8or5fO4B07jFhmMNKZTSsPxBFrg-uzOF7tgE0gVMOPfAtLrqmGINiumzNmyLmmdWxQfr3dfJiwgQQoQIIc4QRIIQ-D0MQotjsnJK7HN_j4eceSSIe87igBxCKz88Pz4HtQj_h7avO1NCfaMeDTE7OnpClX8qx7VJGh6T_oKRm8l12N3mZK8eY08G5-5UDj98xjc)
Expects quantum,list of cost-id pairs.
## How?
Instead of updating the remaining cost in each pair we run through the unchanged list repeatedly and after each cycle update the threshold (0,q,2q,3q,...) by which processes are filtered.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
F⌈Eθ§ι¹IEΦθ››§κ¹ι﹪ιη§κ⁰
```
[Try it online!](https://tio.run/##RYzNCsIwEIRfZY8RVuifJ08iWDwUvIccljbSYNpoTKVvH3eF4sIywzDz9SPFPpDP@R4iqI5WNy0T61O9EE7pOg92VQ6h3PHBLbo5qTO9069ycT7ZKM02WhK76bZ8yBLB8XdhWHwQ1sioP5wrhcCPOWutS4SDQdAVDwsxNUIt2nBQGXaNyfuP/wI "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of pairs of (process id, service time) and the quantum. Explanation:
```
F⌈Eθ§ι¹
```
Loop up to the maximum service time.
```
IEΦθ››§κ¹ι﹪ιη§κ⁰
```
Output any processes due to be serviced at this time (i.e. their service time is higher and this is actually a multiple of the quantum.)
Would be 17 bytes if dictionary order was guaranteed:
```
F⌈EθιIEΦθ››κι﹪ιηλ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6Fjfj0vKLFDR8Eysyc0tzgXSBRqGOQqampqZCQFFmXomGc2JxCVjYLTOnJLUIJOtelJoIYsLobJAGHQXf_JTSnHyNTB2FDKB2HYUcIGm9pDgpuRhq1_JoJd2yHKXY_dHVhlYKpjoKRlYKhgY6CsZWCsY6CiZAjlEtkI6FqAYA "Charcoal – Attempt This Online") Link is to verbose version of code. Takes input as a dictionary and a number. Explanation:
```
F⌈Eθι
```
Loop up to the maximum service time.
```
IEΦθ››κι﹪ιηλ
```
Output any processes due to be serviced at this time (i.e. their service time is higher and this is actually a multiple of the quantum.)
[Answer]
# [Scala 3](https://www.scala-lang.org/), 72 bytes
A port of [@loopy walt's Python answer](https://codegolf.stackexchange.com/a/265067/110802) in Scala.
---
Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=nVLNTsJAEE488hQT4mHXbBvaQoLlJ_FgookelHhCQlZoyZrS38WAhCfxggd9J30Zne6CFJCDJvsz881838xu5uU9G_CAO8vPo6_o4dEbSLjmIoR5CWDo-TBGh_B0lLlwlqZ81u3IVISjHnXhLhQSWioT4IkHMOSSI3AlMkkUCECI8iwGNgOHQZUyHa8xsCoKsmxawDeZGFF2VZ-Usm3Nmgo5Kmqt6TZqbm-6XXRDYfB_d6-ZYtu1dTlHIXrVDz2ylhP-ILf6tVzPPqC34zrFc7_U5utooZilZKxf3_qTc7rzqCJJcWhJXX6UIpkIBgMGCRIiCk1DzQtdzY-eoNTLJkE-VD5JMNl8FjERKy2AGCdPBiHJyrcqz4VjTbgPz6cxjq43RCgq6_xFSe9c13fJZShZ3mdXWYAH7dFWu-MlXbR7WPNtIn2j_nGBpQVGCHY9v2kaFZARCHPMY9I3-xZFa2pYjbhpiIbwIUasnZzcLGbCC4a5a1NTRqir9V4X-l4u9f0N)
```
(q,i)=>(for{Q<-0 to i.map(_._1).max-1;p<-i;if p._1>q*Q}yield p._2).toSeq
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=nVPBTsJAED144ysmxMOuWQhtIcFGTdR4MNEDGk9IyAotWVNaaBcDGn7Dixcu-lF-jbOzrRTQgybdbefNvLczzdu3j2wgI-mtVu8zHdban3uvycNjMNBwLVUMLxWAYRDCGAMm01Hmw2maykX3VqcqHvW4D3ex0nBMlQBPMoKh1BKBK5VpRiAAYxQ5AlwBnoAmFzbfEuA0CHJcXsLXlZih76bdORebmi1KeZR1CrqLmpuLbx66pgj4f7jTTLntVnGcR4h92r8N2TKEP8jlf83oub_obYVeed89av3reOkwh2ScH2f9rjncGqpMIg6v0CtMUiQzJWAgYIqEhMNRjfzCc_9YB6VBNouMqUI2xeL6s5owlWsBTNB5OopZVr2hOh_2LeE-vphP0LrBEKGkauuXFbNyG6OeD5exFqB8arfLKMKNGy8ThEFvw9BjOT9HQNXx42zB-vW-w3FRnpmhit47ZpwGzGKtLKvoWKrUpFQeq5Ag1IATmMIBdGyrsFBBNMxzLq_rxDREAyzt9cxvaXFbvwA)
```
def f(q: Int, i: List[(Int, Int)]): List[Int] = {
val maxC = i.maxBy(_._1)._1
(for {
Q <- 0 until maxC
pair <- i
if pair._1 > q * Q
} yield pair._2).toList
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes
```
/îδиÅ\ζ˜þ
```
-1 thanks to Kevin Cruijssen
[Try it online!](https://tio.run/##yy9OTMpM/f9f//C6c1su7DjcGnNu2@k5h/f9/2/EFW2sowBEhgZgyiKWK9pQR8EIzDHRUTCLBQA "05AB1E – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~76~~ 75 bytes
```
\d+(?=,|$)
$*#
(?=.*, (#)+)(?<-1>#)+
@
S`,
rM!&`.+@
O$^`.+: (@+)
$1_
: @+
```
[Try it online!](https://tio.run/##bYy9CsJAEIT7fYqVnHLJnSG7MaCHmuusxMJW9AQtbCyCpc/lA/hi5@YHQbCZb4bZ2eb6uN3Pcaw3IR4uRtcr@1QpqCwB8XlmUSepSXW9nNJaHHjYB4vQbEeTkBsPO3UUOtTeyIxO4NAbiArer0gOK4vskAqLpcPS4kwCC6ByyEWXuS9bcA8aOqBuw51@96Iynv/pqfg9YBg@Va2hhbQf "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input as a list of pairs and an integer. Explanation:
```
\d+(?=,|$)
$*#
```
Convert the durations to unary.
```
(?=.*, (#)+)(?<-1>#)+
@
```
Calculate the number of times each process gets scheduled.
```
S`,
```
Split each process to its own line.
```
rM!&`.+@
```
Match each process once for each tick. This has to be done in reverse for the overlapping matches to work properly, so the processes actually come out in the wrong order.
```
O$^`.+: (@+)
$1_
```
Sort them according to the tick count and fix up the ordering.
```
: @+
```
Delete the tick counts.
(Out of interest I did try a repeat/transpose/flatten approach but the best I could do in Retina 1 was 79 bytes.)
[Answer]
# [Uiua](https://uiua.org), 11 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
▽±.♭⍉⬚0≡↯⌈÷
```
[Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4oqP4o2P4oqQL-KKguKKg-KKkOKIteKHoeKWveKMiMO3CmYg4oaQIOKKj-KNjy3iipfiioMu4o2P4oqD4oqa4pa94oyIw7cKZiDihpAg4oqP4o2P4o2c4oqV4pah4oqQ4omh4o2PLi7ilr3ijIjDtwpmIOKGkCDilr3CsS7ima3ijYnirJow4omh4oav4oyIw7cKZiA0IFs1IDEwIDMgMTJdIFsxIDIgMyA0XQpmIDUgWzIwXSBbMV0K)
```
▽±.♭⍉⬚0≡↯⌈÷ input: quantum, times, IDs
‚åà√∑ divide times by quantum and take ceiling -> occurrence count
⬚0≡↯ duplicate each ID that many times forming a row in a matrix,
padding short rows with zeros
for the first example, [[1,1,0], [2,2,2], [3,0,0], [4,4,4]]
♭⍉ transpose and flatten
▽±. keep nonzero elements
```
Some 12- and 13-byte solutions:
```
⊏⍏⊐/⊂⊃⊐∵⇡▽⌈÷ # 12
‚åà√∑ same as the above
⊃ run two functions over two stack items(repetitions, ids):
⊐/⊂ ⊐∵⇡ ranges of repetitions concatenated; [0, 1, 0, 1, 2, 0, 0, 1, 2]
‚ñΩ duplicate each ID in a vector; [1, 1, 2, 2, 2, 3, 4, 4, 4]
⊏⍏ reorder the IDs by the ascending order of the ranges
⊏⍏-⊗⊃.⍏⊃⊚▽⌈÷ # 12
⊏⍏ ⊃ ▽⌈÷ same as above
‚äö duplicate indices by values; [0, 0, 1, 1, 1, 2, 3, 3, 3]
⊗⊃.⍏ self-index and sorting order: [0, 0, 2, 2, 2, 5, 6, 6, 6],
[0, 1, 2, 3, 4, 5, 6, 7, 8]
- subtract first from second: [0, 1, 0, 1, 2, 0, 0, 1, 2]
⊏⍏⍜⊕□⊐≡⍏..▽⌈÷ # 13
⊏⍏ .▽⌈÷ same as above, but using just duplicated ids
⍜⊕□⊐≡⍏. group by itself and replace each group with range of that length
```
[Answer]
# Python3, 83 bytes:
```
def R(p,t,q):
Q,s=[*zip(p,t)],[]
for a,b in Q:s+=[a];Q+=[(a,b-q)]*(b>q)
return s
```
[Try it online!](https://tio.run/##jY5NDoIwEIX3PcUsWxwTWyBBDN4Btk0XECGyKaXUhV6@FjAadGMyP3lvvpmMubvroOPMWO8vbQcVNehwZDmBEqdCRo/ezBZTKBWBbrBQYwO9hjKfdoWs1akMjQZzPzIV0eY8MgK2dTerYfLG9trRikqOIBBihEQhyBSBHxbJRdAJY@RNhlmyjALPZ1gEcpvfK5/jCOm8Ei9qjexP@vXQjIsNvv4Qavpj8@N63D8B)
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 68 bytes
```
a=$1{for(b=1;b<NF;){$++c=$++b;if(0<d=$++b-c){$++NF=$c;$++NF=d}}}NF=c
```
[Try it online!](https://tio.run/##SyzP/v8/0VbFsDotv0gjydbQOsnGz81as1pFWzvZFkgkWWemaRjYpIDZuslgCT83W5Vkawgjpba2Fkgl//9vomCoYKpgpGBooGAMhECuEQA "AWK – Try It Online")
This program expects the first commandline argument to give the quantum. And the arguments after that are pairs of pid/service-time values. It works by iterating through the pid/time pairs, adding the pid to an output list. Then if the service time remaining is larger than the quantum, the pid and remaining time are appended to the argument. So it essentially extends the commandline arguments as needed. And the "output list" is stored at the beginning of the argument list. Each iteration consumes two values from the argument list but only adds one (the pid) to the front of the argument list. So once the all the arguments have been processed, all that's left to do is set the number of arguments to the size of the output list. The pid list if printed automatically since the "test" that sets the number of arguments has no associated code.
```
a=$1{ ... } -- set "a" to the quantum (first arg)
.. for( ... ){ ... } -- loop to process pairs of args
.. .. b=1;b<NF; -- stops when at the end of args
.. .. .. $++c=$++b; -- copy the "pid" to the output list and increment
.. .. .. if( ... ){ ... } -- "true" when service time > quantum
.. .. .. .. 0<d=$++b-c -- set "d" to remaining service time
.. .. .. .. .. $++NF=$c; -- append pid to end of args
.. .. .. .. .. $++NF=d -- append remaining service time
NF=c -- set the number of pids to print
```
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~97~~ 93 bytes
```
[](auto&l,int q,auto o){for(int m;m=0,q;q=m<q?m:q)for(auto&[p,t]:l)m=t>m?t:m,t>0?o=p:o,t-=q;}
```
[Try it online!](https://tio.run/##hVLtSsMwFP29PMUFwbWQQdttoOnHHmQOqTGTYNOv3ApS@uw1STvtnOCf3JNz7jkJN@F1vXnjfMw7rOAMKRmPJ89u7gsqS4SGOqXy@3PVepZRsUoD2sRNqpLmoFjjW8VZjjXFEyt8lWKmDsgUxSw4VGnNKoqbtImHMSZ3suRF9yogkZXGVuQqW3D6lupQFhI/l9SH4Fi1GSHuQrksPR96stL4ytikJQ7XuZzRDWucFMySZXMBFBp5roWG1Iat@r4PKewHCn1EIQws2FLY2rozRDQYtBvo1LqnEAWzFF16JxBdQOjA0hXOedFcF/mumtSH/wxh8JcjWjimQ/cLJnz8Th1iQlbmCWF6QzgWUpvRNF1eYqdO7GcubsZXQ7aDg1borsDYSGfvykvB9b7k/P1Zllq0KFpv6vZ91z9/HJBsTvENO53Aqw4hSUDaZQ3rmPwS1k@lJQcykPEL "C++ (gcc) – Try It Online")
4 bytes shaved off thanks to ceilingcat. Takes a list of pairs as input, and uses an insert iterator to return the results. Explanation:
```
[](auto& l, int q, auto o) { // Process list, quantum, output iterator
for (int m; m = 0, // Will track maximum time of all processes
q; // As long as quantum is still non-zero
q = m < q ? m : q) // Limit quantum to the maximum process time
for (auto& [p, t]: l) // Loop over all processes
m = t > m ? t : m, // Update the maximum time
t > 0 ? o = p : o, // Output process number if time left is positive
t -= q; // Subtract the quantum from the time
}
```
] |
[Question]
[
Who doesn't love action movies with fast noisy cars, especially those with a lot of crashes? Who doesn't love action shots in ascii art?
# The scene is:
Two cars are starting at opposite sides of a straight road (with 60 spaces between). They start driving towards each other at constant speeds. The car to the left drives at 1 space per second, and the one to the right drives at 2 spaces per second.
Obviously, the cars can't pass through each other, so for `n ≥ 20`, the scene will be two crashed cars with bonnets up at the position where the crash occurred.
As a movie lover, I want to pause the scene now and then, just to enjoy the beauty of it.
Given an integer `n` (function argument or STDIN), representing the number of seconds from the start of the scene, show the scene at that moment.
This is the starting scene, with 60 spaces between the front wheels:
```
__ __
_/ \_ _/ \_
o o o o
```
this is the scene after 11 seconds:
```
__ __
_/ \_ _/ \_
o o o o
```
and this is what it looks like after the crash (note that the bonnets are up after the crash):
```
__ __
_/ \/\/ \_
o oo o
```
I'm only interested in watching two cars crashing, so spaces, newlines, ++ doesn't matter.
This is code golf, so the shortest code in bytes wins. Answers added later can still win if they are shorter than the current accepted answer.
[Answer]
# [Labyrinth](https://github.com/mbuettner/labyrinth), ~~394~~ 386 bytes
I proudly introduce...
```
<}74}}:23}29}59}}}}}}}:111_}}}}:::::::23_}:111
? @
:" }}_47}_95 3""""""""(
_ : } _ } {=}
2 23_}29_ _ ; : \
0 ; 3 +_( 3_" 60{ .{.{.
"-_95:}}"" 2 0 ) 2 " _ _ {
"" _ : 2 _ ."(; } 3 .{
;_92}_47} : _ 0 = : * ;
: "" 2 {.{{ . -""(
}}:59_}}:::: "";_ . { _ "
} " {.{.{. 32.
}}}_95:}}}}_20-
```
...my new two-dimensional esolang Labyrinth! The code above isn't incredibly well golfed (there are 161 spaces and 25 NOPs, so a better layout could shorten this a lot), but at least I managed to show that the language is usable for non-trivial tasks. :)
## How it works
First, a quick overview of the language:
* Labyrinth operates on two stacks, *main* and *auxiliary*, which can hold arbitrary signed integers. At the bottom of both stacks there is an infinite amount of zeroes.
* Commands are individual characters on a 2D grid and they form a maze (that is unknown characters, particularly spaces, are walls). `"` is a NOP which is not a wall and can be helpful for padding certain paths in the code. As opposed to many other 2D languages, the edges do *not* wrap around.
* The instruction pointer (IP) starts at the first non-wall character (in reading order) moving to the right. `@` terminates the program.
* If possible, the IP follows corridors (also around bends). If the IP has multiple cells to move to, it will generally turn left if the top of the main stack is negative, move straight ahead if it's zero, or turn right if it's positive. When the IP hits a wall it reverses direction. (There are a few more subtleties, but they shouldn't matter for this code.) This is the only way to implement control flow.
* Apart from arithmetic and stack manipulation commands, the source code can be modified at runtime with the four commands `>v<^` which will shift a row or column of the source code cyclically by one cell. Which row or column is affected depends on the top of the stack. If the IP's own row or column is shifted, it will move with the shift. This makes it possible to jump from one edge of the source code to the other.
Now for this particular challenge, here is the general idea of the algorithm:
* Push the ends of the cars up to the bonnets (i.e. `/ \_o oo o`) onto the auxiliary stack.
* Read the input and determine whether to push `__` or `/\` next.
* Push the remainder of the cars (i.e. `__ __ _/ \` and two leading spaces) onto the auxiliary stack.
* Clamp the input to a maximum value of `20`, let's call this *N*.
* Now do the following 3 times:
+ Print *N* spaces.
+ Print 6 stored characters.
+ Print 60 - 3\**N* spaces.
+ Print 6 stored characters.
+ Print a newline.
Finally, let's look at some parts of the code. The IP starts in the top left corner, on a grid shifting command. The top of the main stack is `0` (which is used as a relative index), so the first row is shifted to the left, which also moves the IP to the right end of the grid. Now the first row is simply executed from right to left, which pushes the first set of fixed characters onto the auxiliary stack:
```
}74}}:23}29}59}}}}}}}:111_}}}}:::::::23_}:111<
```
This row shifting is useful for golfing when you want to start with a large amount of linear code.
Next we read the input and push the correct bonnets:
```
?
:"
_
2
0 ;
"-_95:}}""
"" _
;_92}_47}
```
The bit on the left with the three NOPs sends negative results along the top branch and non-negative results along the bottom branch. At the right they are joined back together.
Now follows another large linear section (which could probably be golfed a lot with another row-shifting trick):
```
}}_47}_95
: }
23_}29_ _
3
2
:
:
:
}}:59_}}::::
}
}}}_95:}}}}
```
This pushes the remainder of the cars onto the auxiliary stack.
Next, we compute `min(20, input)`, which is similar to first branch:
```
;
+_(
0 )
2 _
_ 0
"" 2
"";_
"
_20-
```
Finally, we have the loop which runs three times to print the lines. Each iteration of the loop contains two small (3x3) loops to print the spaces, as well as two sections to print 6 characters from the auxiliary stack:
```
@
3""""""""(
_ } {=}
: \
3_" 60{ .{.{.
2 " _ _ {
."(; } 3 .{
= : * ;
{.{{ . -""(
. { _ "
{.{.{. 32.
```
One nifty trick I'd like to draw attention to is the `.{.{.` at the right edge. This is a dead end, so apart from the `.` at the end the code is executed twice, once forward and once backward. This gives a neat way to shorten palindromic code (the catch is that you need to make sure the IP takes the correct turn when exiting the dead end again).
[Answer]
# CJam, ~~68~~ 66 bytes
```
liKe<:M" __ _/ \_o o"6/f{\S*1$+60M3*-S*@N}:+MK={58'/t59'\t}&
```
[Try it online](http://cjam.aditsu.net/#code=liKe%3C%3AM%22%20%20__%20%20_%2F%20%20%5C_o%20%20%20%20o%226%2Ff%7B%5CS*1%24%2B60M3*-S*%40N%7D%3A%2BMK%3D%7B58'%2Ft59'%5Ct%7D%26&input=20)
Anybody who sees the start of the code will be sure to `liKe` it!
Explanation:
```
li Get input n and convert to integer.
Ke< Cap n at 20.
:M Save in variable M for multiple use later.
" __ _/ \_o o"
Car (18 characters).
6/ Split into 3 lines of 6 characters.
f{ Map lines with parameter.
\ Swap n to top.
S* Create string with n spaces for left margin.
1$ Copy one car line to top. Keep original for second car
+ Concatenate the spaces and car.
60M3*- Calculate 60-3*n, which is the amount of space between cars.
S* Create string with 60-3*n spaces.
N Add a newline.
} End of line mapping.
:+ Concatenate all output pieces into single string.
MK= Check if capped n is equal to 20.
{ If equal, replace hoods with crashed versions.
58'/t '/ at position 58.
59'\t '\ at position 59.
}& End of conditional block for crashed hoods.
```
[Answer]
## Python 2.7, ~~167~~ ~~164~~ 159 Bytes
```
n=input();s,x=60-3*n,min(n,20)
for e in[' _',"_/ ","o "]:p=e+(e[::-1],(' \_',' \/')[s<1])['/'in e];print" "*x+p+" "*s+(p[-1]+p[1:-1]+p[0]).replace("//","\/")
```
This takes input from stdin.
[Demo here](https://ideone.com/aaBG8w)
Testing this -
```
$ ./cars.py
0
__ __
_/ \_ _/ \_
o o o o
$ ./cars.py
11
__ __
_/ \_ _/ \_
o o o o
$ ./cars.py
20
__ __
_/ \/\/ \_
o oo o
```
[Answer]
# R, 191 Bytes
About as good as I can get it now. Takes the seconds from STDIN and cats to STDOUT.
```
n=scan();p=paste0;formals(p)$collapse='';cat(sprintf(c('%s __ %s __ ','%s_/ \\_%s_/ \\_','%s_/ \\/%s\\/ \\_','%so o%so o')[-3+(n<21)],p(rep(' ',n)),p(rep(' ',60-n*3))),sep='\n')
```
Explanation
```
# Get the input from STDIN. Requires a single number 0-20
n=scan();
# alias paste0 and set collapse default to ''
p=paste0;
formals(p)$collapse='';
# output
cat(
# sprintf to format the strings
sprintf(
# vector of strings to format picks which bonnet to remove
c('%s __ %s __ ','%s_/ \\_%s_/ \\_','%s_/ \\/%s\\/ \\_','%so o%so o')[-3+(n<21)]
# move left car by 1
,p(rep(' ',n))
# move right car by 2
,p(rep(' ',60-n*3))
)
,sep='\n')
```
Tests
```
> n=scan();p=paste0;formals(p)$collapse='';cat(sprintf(c('%s __ %s __ ','%s_/ \\_%s_/ \\_','%s_/ \\/%s\\/ \\_','%so o%so o')[-3+(n==20)],p(rep(' ',n)),p(rep(' ',60-n*3))),sep='\n')
1: 0
2:
Read 1 item
__ __
_/ \_ _/ \_
o o o o
> n=scan();p=paste0;formals(p)$collapse='';cat(sprintf(c('%s __ %s __ ','%s_/ \\_%s_/ \\_','%s_/ \\/%s\\/ \\_','%so o%so o')[-3+(n==20)],p(rep(' ',n)),p(rep(' ',60-n*3))),sep='\n')
1: 5
2:
Read 1 item
__ __
_/ \_ _/ \_
o o o o
> n=scan();p=paste0;formals(p)$collapse='';cat(sprintf(c('%s __ %s __ ','%s_/ \\_%s_/ \\_','%s_/ \\/%s\\/ \\_','%so o%so o')[-3+(n==20)],p(rep(' ',n)),p(rep(' ',60-n*3))),sep='\n')
1: 20
2:
Read 1 item
__ __
_/ \/\/ \_
o oo o
>
```
[Answer]
## CJam, 120 bytes
```
q~20e<_[" "]*\[" _o"]\[" / " "_ " "_ " " \ " ]\[19>" /o"" _o"?]60 3 5$,*-[" "]*[0$," _o"" \o"?]3$[" _o"]+++++++zN*
```
[Demo](http://cjam.aditsu.net/#code=q~20e%3C_%5B%22%20%20%20%22%5D*%5C%5B%22%20_o%22%5D%5C%5B%22%20%2F%20%22%20%22_%20%20%22%20%22_%20%20%22%20%22%20%5C%20%22%20%5D%5C%5B19%3E%22%20%2Fo%22%22%20_o%22%3F%5D60%203%205%24%2C*-%5B%22%20%20%20%22%5D*%5B0%24%2C%22%20_o%22%22%20%5Co%22%3F%5D3%24%5B%22%20_o%22%5D%2B%2B%2B%2B%2B%2B%2BzN*&input=11)
Ungolfed:
```
q~ e# Read the input
20e< e# min(20, input) (let's call it N)
_ e# Duplicate the value on the stack
[" "] e# Push 3 blank spaces
* e# Create N arrays of 3 blank spaces
\ e# Swap the top two stack elements
[" _o"] e# Push the " _o" string to stack
\ e# Swap the top two stack elements
[" / " "_ " "_ " " \ " ]
\ e#
[ e# If N is greater than 20 then push the array [" /o"],
19 e# otherwise [" _o"]
>
" /o"
" _o"
?
]
60 e# 60 is the maximum space between the two cars
3 e# 3 is the number of blocks covered per move
5$, e# Take the 6th element from the stack (an array of size N)
*- e# Compute the remaining blocks (60 - 3 * N)
[" "] e# Add an array of 3 blank spaces
* e# Multiply it to fit the remaining blocks
[0$," _o"" \o"?] e# Add the (broken?) front part of the second car
3$ e# Copy the middle part of the car
[" _o"] e# Append the right side of the car
+++++++ e# Concatenate all arrays
z e# Transpose the array
N* e# Join the array using new lines
```
[Demo](http://cjam.aditsu.net/#code=q~%20%20%20%20%20%20%20%20e%23%20Read%20the%20input%0A20e%3C%20%20%20%20%20%20e%23%20min(20%2C%20input)%20(let's%20call%20it%20N)%0A_%20%20%20%20%20%20%20%20%20e%23%20Duplicate%20the%20value%20on%20the%20stack%0A%5B%22%20%20%20%22%5D%20%20%20e%23%20Push%203%20blank%20spaces%0A*%20%20%20%20%20%20%20%20%20e%23%20Create%20N%20arrays%20of%203%20blank%20spaces%0A%5C%20%20%20%20%20%20%20%20%20e%23%20Swap%20the%20top%20two%20stack%20elements%0A%5B%22%20_o%22%5D%20%20%20e%23%20Push%20the%20%22%20_o%22%20string%20to%20stack%0A%5C%20%20%20%20%20%20%20%20%20e%23%20Swap%20the%20top%20two%20stack%20elements%0A%5B%22%20%2F%20%22%20%22_%20%20%22%20%22_%20%20%22%20%22%20%5C%20%22%20%5D%0A%5C%20%20%20%20%20%20%20%20%20e%23%0A%5B%20%20%20%20%20%20%20%20%20e%23%20If%20N%20is%20greater%20than%2020%20then%20push%20the%20array%20%5B%22%20%2Fo%22%5D%2C%0A%20%2019%20%20%20%20%20%20e%23%20otherwise%20%5B%22%20_o%22%5D%0A%20%20%3E%0A%20%20%22%20%2Fo%22%0A%20%20%22%20_o%22%0A%20%20%3F%0A%5D%0A60%20%20%20%20%20%20%20%20e%23%2060%20is%20the%20maximum%20space%20between%20the%20two%20cars%0A3%20%20%20%20%20%20%20%20%20e%23%203%20is%20the%20number%20of%20blocks%20covered%20per%20move%0A5%24%2C%20%20%20%20%20%20%20e%23%20Take%20the%206th%20element%20from%20the%20stack%20(an%20array%20of%20size%20N)%0A*-%20%20%20%20%20%20%20%20e%23%20Compute%20the%20remaining%20blocks%20(60%20-%203%20*%20N)%0A%5B%22%20%20%20%22%5D%20%20%20e%23%20Add%20an%20array%20of%203%20blank%20spaces%0A*%20%20%20%20%20%20%20%20%20e%23%20Multiply%20it%20to%20fit%20the%20remaining%20blocks%0A%5B0%24%2C%22%20_o%22%22%20%5Co%22%3F%5D%20e%23%20Add%20the%20(broken%3F)%20front%20part%20of%20the%20second%20car%0A3%24%20%20%20%20%20%20%20%20e%23%20Copy%20the%20middle%20part%20of%20the%20car%0A%5B%22%20_o%22%5D%20%20%20e%23%20Append%20the%20right%20side%20of%20the%20car%0A%2B%2B%2B%2B%2B%2B%2B%20%20%20e%23%20Concatenate%20all%20arrays%0Az%20%20%20%20%20%20%20%20%20e%23%20Transpose%20the%20array%0AN*%20%20%20%20%20%20%20%20e%23%20Join%20the%20array%20using%20new%20lines&input=11)
[Answer]
# PHP, 160 155 bytes
```
$f=str_repeat;echo$l=$f(' ',$s=min(max($argv[1],0),20))," __ ",
$m=$f(' ',$r=60-3*$s)," __\n{$l}_/ \\",$r?_.$m._:'/\\',
"/ \\_\n{$l}o o{$m}o o\n";
```
The code is displayed here on 3 lines to fit the layout of the code box. Those newlines are not needed.
The ungolfed code:
```
// The number of seconds, between (and including) 0 and 20
$sec = min(max($argv[1], 0), 20);
$rest = 60 - 3 * $sec;
$left = str_repeat(' ', $sec); // left padding
$mid = str_repeat(' ', $rest); // space in the middle
$c = $rest ? '_'.$mid.'_' : '/\\';
echo($left.' __ '.$mid." __\n");
echo($left.'_/ \\'. $c ."/ \\_\n");
echo($left.'o o'.$mid."o o\n");
```
It gets the number of seconds from the command line (first argument):
```
$ php -d error_reporting=0 action.php 11
__ __
_/ \_ _/ \_
o o o o
```
The PHP CLI option `-d error_reporting=0` is needed to hide some notices PHP displays about undefined constants (`str_repeat`, `_`) that it converts to strings (2 bytes saved for each notice).
One additional byte can be saved on PHP 7 by squeezing the initialization of `$f` into its first use (`$m=($f=str_repeat)(...)`); it doesn't compile on PHP 5.
The test case and some of the techniques used to shrink the code can be found on [github](https://github.com/axiac/code-golf/blob/master/lets-see-some-action.php).
**Update:**
@ismail-miguel squeezed the initialization of `$left` and inlined `$c` into the arguments of `echo` saving 4 bytes (see comment below).
By swapping the order the variables `$m` and `s` are initialized I got rid of a pair of parentheses and saved 1 byte more.
[Answer]
# JavaScript (ES6), 121 bytes
Using template string, the 2 newlines inside the string are signficant and counted.
To save bytes, output with `alert`, even if the proportional font used in `alert` is not well suited for ASCII art and the result is ugly for n>=20 (crash).
Test running the snippet in FireFox
```
F=n=>alert(` __
_/ \\_
o o`.replace(/.+/g,v=>(Z=x=>' '.repeat(x)+v)(n<20?n:n=20)+Z(60-3*n)).replace('__/','/\\/'))
```
```
<input id=I value=10><button onclick='F(I.value)'>go</button>
```
[Answer]
# Python 2, 148 bytes
This uses ANSI escape codes to position the cursor in the right place to draw the cars. It then checks to see if the input was 20, if it was, it goes back and draws on the bonnets of the car.
Takes an int from stdin, output to stdout.
```
p=lambda x:"u __u_/ \_uo o".replace("u","\n\033[%dC")%(x,x,x)+"\033[4A";i=min(20,input());print p(i)+"\n"+p(66-i*2)+"\n\n\n\033[25C/\\"*(i==20)
```
Ungolfed:
```
def get_car(x):
return "\n __\n_/ \_\no o".replace("\n","\n\033[%dC")%(x,x,x)+"\033[4A"
i=min(20,input())
print get_car(i)
print get_car(66-i*2)
if i==20:
print"\n\n\033[25C/\\"
```
[Answer]
## Pyth, 67 bytes
```
Kjbm+++*\ JhS,Q20d*\ -60*3Jdc3" __ _/ \_o o"?nJ20KXXK58\/59\\
```
Try it out [here](https://pyth.herokuapp.com/?code=Kjbm%2B%2B%2B*%5C%20JhS%2CQ20d*%5C%20-60*3Jdc3%22%20%20__%20%20_%2F%20%20%5C_o%20%20%20%20o%22%3FnJ20KXXK58%5C%2F59%5C%5C&input=20&debug=0).
```
Implicit: Q=eval(input())
JhS,Q20 Set J=min(Q,20)
" __ _/ \_o o" Concatenated car string
c3 Split into 3
m For d in the above
*\ J J spaces before 1st car
*\ -60*3 60-3J spaces in between them
+++ d d Concatenate spaces and car string
Kjb Join on newlines, store in K
?nJ20 If J != 20...
K ... print K
XK58\/ ... else put / in position 58
X 59\\ and \ in position 59 (implicit print)
```
[Answer]
# C, ~~180~~ ~~191~~ 168 bytes
```
#define S(x,y)" __ ",#x"/ \\"#y,"o o",
char*s[][3]={S(_,_)S(_,/)S(\\,_)};i;l;f(n){l=n>19&&(n=20);for(i=0;i<3;i++)printf("%*s%*s\n",n+6,s[l][i],60-3*n,s[l*2][i]);}
```
ungolfed:
```
// make a map of possible car parts
#define S(x, y) { " __ ", #x "/ \\" #y, "o o" }
char * s[4][3]= {
S(_,_),
S(_,/),
S(\\,_)
};
i,l;
f(n){
i = 0;
l = n>19 && (n = 20); // l = 1, if crash happend
for(; i < 3; i++) {
// '*' means length (padding) is given as an int argument
printf("%*s%*s\n", n + 6, s[l][i], 60 - 3 * n, s[l*2][i]);
}
}
```
test program:
```
main() {
f( 0);f( 5);f(10);
f(15);f(20);f(21);
return 0;
}
```
output:
```
__ __
_/ \_ _/ \_
o o o o
__ __
_/ \_ _/ \_
o o o o
__ __
_/ \_ _/ \_
o o o o
__ __
_/ \_ _/ \_
o o o o
__ __
_/ \/\/ \_
o oo o
__ __
_/ \/\/ \_
o oo o
```
I was able to golf this one pretty hard. I think I started with almost 300 bytes.
~~But I don't know if this still fulfills all the requirements. As you can see after 21 seconds, the first car pushes the second car over to the right. I would need to add a few bytes if this isn't allowed.~~
**Edit:** fixed it. This should be more realistic than Sharknado ;-)
**Edit:** I could significantly shorten my solution by taking a second look at the `printf` man-page. If you use '\*' you can supply the field length directly to printf, without the need to create a format-string with `sprintf` beforehand.
[Answer]
# [><>](http://esolangs.org/wiki/Fish), ~~538~~ 276 bytes
```
:3*a6*$-:0)?v~~a2*0c4*1-e2*1+6pa9*2+b7p04.
v >04.
>>1[>:0) ?v~].
^ ^-1o" "<
\$:&94&12." ":oo"_":oo" ":oo
\$:&95&12." ":oo"_":oo" ":ooao
\$:&96&12."_"o"/"o" ":oo"\"o"_"o
\$:&97&12."_"o"/"o" ":oo"\"o"_"oao
\$:&98&12."o"o" ":::oooo"o"o
\$:&99&12."o"o" ":::oooo"o"o;
```
I've dropped the size a LOT, I'm amazed that I managed to drop the size by half. The old one is below. This one is not as efficient performance wise due to the width of the grid, mostly from the very first line.
You can test it out [here](http://fishlanguage.com/playground). Put the amount of time passed in the "Initial Stack", not "Input"!
Here's the old version.
```
:3*a6*$-:0) ?v~~a2*0c4*1-c3*1-4p^
v~v?)0: <[1:$/$:1[ >:0) ?v~]" ":oo"_":oo" ":ooaov
] >" "o1-^ ^ <^-1o" "/"/"o"_"<]~v?)0: <[1:$<
>" ":oo"_":oo" ":oo^ \o" ":oo"\"\" "o1-^
/o"\"oo:" "o"/"o"_"]~v?)0: <[1:$o"_"o/
\"_"oaov hi there >" "o1-^
>$:1[ >:0) ?v~]"o"o" ":::oooo"o"o>$:1[ >:0) ?v~]v
^ <^-1o" "< ^ <^-1o" "<
v p4-1*29+2*9a< ;o"o"oooo:::" "o"o"<
```
[Answer]
## Java, 258 Chars
```
class M{public static void main(String[]a){String l="",m=l,r=" __ ",w="o o",x="_/ \\_";int p=Integer.parseInt(a[0]),i=20;p=p>i?i:p;for(i=-1;++i<p;)l+=" ";for(;++i<21;)m+=" ";System.out.print(l+r+m+r+"\n"+l+(x+m+x).replace("__","/\\")+"\n"+l+w+m+w);}}
```
Un-Golfed
```
class M {
public static void main(String[] a) {
String l = "", m = l, r = " __ ", w = "o o", x = "_/ \\_";
int p = Integer.parseInt(a[0]), i = 20;
p = p > i ? i : p;
for (i = -1; ++i < p;)
l += " ";
for (; ++i < 21;)
m += " ";
System.out.print(l + r + m + r + "\n"
+ l + (x + m + x).replace("__", "/\\") + "\n"
+ l + w + m + w);
}
}
```
Results
```
0
__ __
_/ \_ _/ \_
o o o o
1
__ __
_/ \_ _/ \_
o o o o
...
19
__ __
_/ \_ _/ \_
o o o o
20
__ __
_/ \/\/ \_
o oo o
21
__ __
_/ \/\/ \_
o oo o
```
[Answer]
## Python 2, 102 bytes
```
n=input()
for r in" __ ","_/ \_","o o":print((n*' ')[:20]+r+(60-3*n)*' '+r).replace('__/','/\/')
```
Pretty straightforward. For each row of the car, we print `n` spaces, that row, `60-3*n` spaces, and the row again. To stop the cars, rather than doing `min(n,20)`, it was one char shorter to limit the first run of spaces with `[:20]`, and the second is fine because a negative times a string is the empty string.
To move up the fenders, we just do a `replace`. Since `__` also appears on the roof, we need a bit of context to identify the fenders, so we check for a `/` following.
[Answer]
# Java, 270 267 bytes
Pretty sure there's a better/shorter way of doing this, but my brain isn't properly engaged.
```
class C{public static void main(String[]a){String l="",m="",r=" __ ",w="o o";int p=Math.min(Integer.parseInt(a[0]),20),i;for(i=0;++i<p;)l+=" ";for(i=0;++i<60-3*p;)m+=" ";System.out.print(l+r+m+r+"\n"+l+"_/ \\"+(p==20?"/"+m+"\\":"_"+m+"_")+"/ \\_\n"+l+w+m+w);}}
```
**For n=19:**
```
__ __
_/ \_ _/ \_
o o o o
```
**For n=20:**
```
__ __
_/ \/\/ \_
o oo o
```
**Ungolfed**
`public class Crash {
public static void main(String[] args) {
String left="", mid="", r=" __ ", w="o o";
int pos = Math.min(Integer.parseInt(args[0]),20),i;
for (i=0; ++i<pos;){
left+=" ";
}
for (i=0; ++i<60-3*pos;){
mid+=" ";
}
System.out.print(
left + r + mid + r + "\n" +
left + "_/ \\" + (pos==20 ? "/" + mid + "\\" : "_" + mid + "_") + "/ \\_\n" +
left + w + mid + w);
}
}`
[Answer]
# PHP 7, 140 bytes
```
<?$s=$argv[1];$r=($f=str_repeat)(~ß,60-3*$s);echo$l=$f(~ß,min(20,$s))," __ $r __
${l}_/ \\",$r?_.$r._:~У,"/ \_
$l",$o=~ßßßß,$r,$o;
```
### Usage:
Save as ANSI in `file.php` (there should be zero-width characters in `$o`) and run:
```
php -derror_reporting=~E_NOTICE -dshort_open_tag=1 file.php x
```
with `x` as the number of seconds.
And a version that works without changing the error reporting (**148 bytes**):
```
<?$s=$argv[1];$r=($f=@str_repeat)(' ',60-3*$s);echo$l=$f(' ',min(20,$s))," __ $r __
${l}_/ \\",$r?"_${r}_":"/\\","/ \_
$l",$o="o o",$r,$o;
```
[Answer]
# Javascript, 193 bytes
It's not a winner, but it's something
<http://jsfiddle.net/yb703y0p/2/>
```
function f(n){
c = [" __ A", "_/ \\_A", "o oA"]
for(i=0;i<3;i++)c[i]=c[i].replace('A',' '.repeat(n))+c[i].replace('A','')
if(n==0)c[1]=c[1].replace('__','/\\')
console.log(c.join("\n"))
}
```
] |
[Question]
[
Implement a simple digital [Stopwatch](https://en.wikipedia.org/wiki/Stopwatch),
which will display the time elapsed in seconds and minutes, as described below.
>
> **Important**
>
>
> Please read both *Display* and *Controls* sections !
>
>
>
**Display**
Time elapsed, should be displayed in the `MM:SS` format,
by replacing the previously displayed time string "in-place"
(clearing the whole or a part of the screen is also allowed).
The stopwatch must be updated at least every second.
*Examples:*
0 minutes, 0 seconds
```
00:00
```
0 minutes, 33 seconds
```
00:33
```
1 minute, 50 seconds
```
01:50
```
Initially, you can start with '00:00' or with any other value in range [00:00-59:59].
Once your Stopwatch reaches `59:59`, it should reset to `00:00` and continue afresh.
You can use a different base (instead of decimal) or even a different numeral system if you wish, as long as you follow the general pattern.
For example `13:03` can be displayed as:
[Decimal](https://en.wikipedia.org/wiki/Decimal)
```
13:03
```
[Hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal)
```
0D:03
```
[Base64](https://en.wikipedia.org/wiki/Base64)
```
N:D
```
[Quater-imaginary base](https://en.wikipedia.org/wiki/Quater-imaginary_base)
```
10101:3
```
[Roman Numerals](https://en.wikipedia.org/wiki/Roman_numerals)
```
XIII:III
```
Beware that if you use a non-decimal numeral system/base, it must be encoded using printable ASCII (or Unicode) characters, e.g. using two binary (unprintable) bytes for minutes and seconds is not allowed.
You must also left-pad your output with zeroes as appropriate, if your numerical system allows for that.
Replacing the separator character `:` with any other printable character (including digits) is also acceptable.
**Controls**
The stopwatch should start *paused*, and stay in this state, until user explicitly *starts* it, by pressing the *'control'* key (see below).
If, while stopwatch is counting, user presses the *'control'* key again, the stopwatch should *pause* (keeping the current time), until the *'control'* key is pressed a one more time.
The *'control'* key can be a single keystroke, e.g. `s`,
or any combination of keys, e.g. `Ctrl+Shift+X`, but it must be 'atomic', pressing multiple keys in sequence, e.g. `s` then `Enter`, is *not allowed*.
The same *'control'* key (or combination) must be used to *pause* and *resume* the stopwatch.
You must use a specific *'control'* key, i.e. 'any key' is not allowed.
Alternatively, you can use a single or double mouse-click, instead of a keypress for 'control'.
---
**Rules**
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins;
* Standard code-golf loopholes apply;
* Your program must (theoretically) be capable of running forever.
[Answer]
# Python 2, ~~167~~ 129 bytes
-36 bytes mostly\* from using [Maltysen's idea](https://codegolf.stackexchange.com/a/108487/53748) of catching `ctrl-c` using an exception - go give credit!
-4 bytes thanks to DLosc (init `n` and `b` to 0 rather than `f()`)
-1 byte thanks to FlipTack (use `p^=1` rather than `p=1-p`)
-2 bytes thanks to Felipe Nardi Batista (remove precision specifiers)
```
import time
f=time.time
n=b=p=0
while 1:
try:n=[n,f()][p];t=n-b;print'\r%02d:%02d'%(t/60%60,t%60),
except:b=[b-n+f(),b][p];p^=1
```
Works the same as my original, below, but with the control key sequence of `ctrl+c`.
(Tested by me with Python 2.7.8 on Windows 7, 64bit;
Tested by Brian Minton with Python 2.7.13 on linux, 64bit)
\* also collapsed `if` statement to a list lookup in order to get the `try` as a one-liner.
My original:
```
import time,msvcrt as m
f=time.time
n=b=p=0
while 1:
if m.kbhit()and m.getch()==b'p':b=[b-n+f(),b][p];p^=1
if p:n=f()
t=n-b;print'\r%0.2d:%0.2d'%(t/60%60,t%60),
```
(Tested by me with Python 2.7.8 on Windows 7, 64bit - this code, however, is Windows specific due to the use of the `msvcrt` library)
The control key is 'p'.
`n` and `b` are initialised to the same value at start-up, giving an "offset" of 0; `p` is initialised to 0, indicating a paused state.
Whenever the control key is pressed the value of `p` is switched. When switching from a paused state to an active state `b` is updated to a new value keeping any current offset from the previous active state(s) with `b-n`.
During an active state `n` is repeatedly updated to the current time by calling `time.time()`.
The difference between `n` and `b`, `t`, is then the total number of seconds (including a fractional part) elapsed during active state(s).
The minutes elapsed are then `t/60` and each of the minutes and seconds are displayed mod 60 with `(t/60%60,t%60)`. Leading zeros are prepended for each using string formatting of the integer part with `'...%0.2d...'`. Printing a tuple (the trailing `,`) where the first item has a leading carriage return (the `\r`) causes the previously printed text to be overwritten.
[Answer]
# SmileBASIC, ~~86~~ ~~77~~ 71 bytes
```
@L
N=N!=DIALOG(FORMAT$("%02D:%02D",F/60MOD 60,F MOD 60),,,N)F=F+1GOTO@L
```
`DIALOG` displays a textbox on the touch screen. `N` is the number of seconds the text box will stay on screen before it disappears. If `N` is `0`, it stays until the user presses the button on the touch screen.
`DIALOG` Returns `1` if the user pressed the button, and `0` if it closed automatically. So when the user pushes the pause button, it returns `1`, and the display time is set to `0`, pausing the stopwatch. After the user presses the button again, we set the display time back to `1`, resuming the timer. Basically, every time `DIALOG` returns `1`, the display time is switched between `1` and `0` using `!=`, which is eqivilant to a logical XOR as long as both inputs are 1 or 0.
[Answer]
# Python - ~~160~~ ~~159~~ 143 bytes
*Thanks to @JonathanAllan for saving me 18 bytes!*
Only uses builtin libraries, so the control key is `ctrl-c`, catching it with an `except keyboardInterrupt`.
```
import time
Z=0
print'00:00'
while 1:exec"try:\n while 1:\n %s\nexcept:1\n"*2%(1,"print'\033c%02d:%02d'%divmod(Z%3600,60);Z+=1;time.sleep(1)")
```
[Answer]
# bash + Unix utilities, 90 or 93 bytes
**90-byte version:**
```
trap d=\$[!d] 2;for((n=0;;)){((d|!n))&&dc<<<DP60dod*d$n\r%+n|colrm 1 4&&: $[n++];sleep 1;}
```
**93-byte version:**
```
trap d=\$[!d] 2;for((n=0;;)){((d|!n))&&dc<<<DP60dod*$n+n|colrm 1 4&&n=$[(n+1)%3600];sleep 1;}
```
Ctrl-C is the resume/pause character. A space is the delimiter between minutes and seconds.
The difference between the two versions is that the 90-byte program will work for 2^63 seconds (at which point, bash will give me an integer overflow).
The 93-byte version will truly work forever.
The original problem included the requirement: "Your program must (theoretically) be capable of running forever."
If running for 2^63 seconds is sufficient to meet that requirement, then the 90-byte solution works. That duration is more than 20 times the age of the universe!
If the program needs to be able to run for longer than that, I'll have to go with the 93-byte solution.
---
I should probably point out that this solution, as well as at least some of the others posted, will *very* slowly fall behind the true elapsed time. This slippage is because the program is sleeping for one second between each execution of the body of the loop, but the body of the loop does take some tiny amount of time to execute. This will be inconsequential in practice.
[Answer]
# QBasic, ~~213~~ 211 bytes
Control key is tab. Leaving this running may cause laptop fires. You have been warned.
```
DO
WHILE k$<>CHR$(9)
k$=INKEY$
LOCATE 1
?CHR$(48+m\10);CHR$(48+(m MOD 10));":";CHR$(48+(d MOD 60)\10);CHR$(48+(d MOD 10))
IF r THEN
n=TIMER
d=v+n-b+86400
m=d\60MOD 60
END IF
WEND
k$=""
v=v+n-b
r=1-r
b=TIMER
LOOP
```
Here it is in action, pausing at 10, 15, and 20 seconds:
[](https://i.stack.imgur.com/FlWKZ.gif)
### Ungolfed and commented
```
' Outer loop runs forever
DO
' The WHILE-WEND loop runs until tab is pressed
WHILE key$ <> CHR$(9)
key$ = INKEY$
' Output the stopwatch value at top left of screen
LOCATE 1
' Unfortunately, QBasic's PRINT USING doesn't have a format for printing
' with leading zeros, so we have to do it manually by printing the
' 10s digit and the 1s digit
PRINT CHR$(48 + minute \ 10); CHR$(48 + (minute MOD 10));
PRINT ":";
PRINT CHR$(48 + second \ 10); CHR$(48 + (second MOD 10))
' Update the current time if the running flag is set
IF running THEN now = TIMER
' Take the difference between now and the last time we started the
' stopwatch, plus the amount of saved time from previous runs,
' plus 86400 to account for the possibility of running over midnight
' (since TIMER is the number of seconds since midnight, and QBasic's
' MOD doesn't handle negative values like we would need it to)
diff = saved + now - lastStarted + 86400
second = diff MOD 60
minute = diff \ 60 MOD 60
WEND
' If we're outside the WHILE loop, the user pressed tab
key$ = ""
' Add the previous run's time to the saved amount
saved = saved + now - lastStarted
' Toggle running between 0 and 1
running = 1 - running
' If we're starting, we want to put the current time in lastStarted;
' if we're stopping, it doesn't matter
lastStarted = TIMER
LOOP
```
Note that values of `TIMER` are floating-point. This doesn't affect the output, since `MOD` and `\` truncate to integers. But it does add accuracy to the amount of saved time: if you pause the timer right before a tick, you'll see when you start it up again that the number changes in less than a second.
[Answer]
## Batch, 132 bytes
```
set/ar=0,m=s=100
:l
cls
@choice/t 1 /d y /m %m:~1%:%s:~1% /n
set/as+=r,m+=c=s/160,s-=c*60,m-=m/160*60,r^^=%errorlevel%-1
goto l
```
Pressing `n` will (un)pause the timer. The output flicker can be reduced at a cost of three (or four) bytes.
[Answer]
# Pure bash, 141 bytes
```
set -m
while ! read -t 1;do printf '\r%02i:%02i' $[s=s>3598?0:s+1,s/60] $[s%60];done&trap 'fg>/dev/null' TSTP
printf '00:00'
kill -STOP $!
read
```
This uses nothing but Bash builtins (no external tools). The control character is `Ctrl-Z`, so that standard `SIGTSTP` handling pauses the stopwatch.
* [`set -m` enables job control](https://www.gnu.org/software/bash/manual/bashref.html#The-Shopt-Builtin), which is usually off in a script.
* A [subshell](https://www.gnu.org/software/bash/manual/bashref.html#Command-Execution-Environment) process is [backgrounded (`&`)](https://www.gnu.org/software/bash/manual/bashref.html#Lists).
+ [`read -t 1` waits one second for input from the user](https://www.gnu.org/software/bash/manual/bashref.html#index-read), then fails.
+ The [`until` loop](https://www.gnu.org/software/bash/manual/bashref.html#Looping-Constructs) continues as long as `read` keeps failing.
+ [`printf` outputs](https://www.gnu.org/software/bash/manual/bashref.html#index-printf) the correctly-padded and -formatted time
+ `$[s=s>3598?0:s+1,s/60]` arithmetic expansion first [computes](https://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic) the updated time, checking whether to wrap and otherwise incrementing the seconds counter `s`, and then returns the floored division `s/60`.
+ `$[s%60]` gives the seconds remainder.
* The outer script sets up a [`trap` handler](https://www.gnu.org/software/bash/manual/bashref.html#index-trap) for `TSTP`, the signal `Ctrl-Z` generates. When `Ctrl-Z` is pressed while the outer script is running, it will run [`fg>/dev/null` and put the subshell back into the foreground](https://www.gnu.org/software/bash/manual/bashref.html#index-fg). `>/dev/null` is necessary to stop `fg` printing out the subshell command every time.
* The script prints the initial `00:00` and [sends a `STOP` signal](https://www.gnu.org/software/bash/manual/bashref.html#index-kill) to the [child process `$!`](https://www.gnu.org/software/bash/manual/bashref.html#index-_0024_0021), which will pause the process.
* `read` waits for input forever, keeping the script alive.
If `Ctrl-Z` is pressed while the subshell is foregrounded, it will pause execution and return the outer script to the foreground, where it will wait silently. If the outer script is foregrounded, the trap handler will resume the subshell's execution, and it will count up again.
[Answer]
# Javascript in Chrome console, 143 bytes
```
f=document,m=s=g=i=0;setInterval(()=>{if(g%2){m=(i/60|0)%60;s=i++%60}f.write((m>9?m:'0'+m)+':'+(s>9?s:'0'+s));f.close();f.onclick=()=>g++},1e3)
```
When entered in console it inits the counter to 00:00 and then enables the control which is keypress on the document.
Not much magic going on, notably the `(i/60)|0` floors the number
Done and tested in Chrome console
[Answer]
# HTML + JavaScript (ES6), ~~191 192 187 183~~ 174 bytes
```
<b onclick='b=b?clearInterval(b):setInterval("a.innerHTML=`${(d=(((c=a.innerHTML.split`:`)[1]>58)+c[0])%60)>9?d:`0`+d}:${(e=++c[1]%60)>9?e:`0`+e}",1e3)'onload='b=0'id=a>00:00
```
### Explanation
Click the timer to start or pause the stopwatch. As such, a single click is the *control* key. The separator between the two values is a colon.
Whenever the user clicks the click, the value of `b` is checked. It is initialised to `0` which evaluates to `false`, so a string of code is evaluated every 1000 milliseconds. This sets the variable to the id of the interval, so it can be stopped later. If `b` contains a number, it evaluates to `true`, so the interval is stopped. This returns the value `undefined`, so the cycle continues.
The string of code changes the html of the element with id `a` (the stopwatch). First the minutes are parsed by taking the previous stopwatch value, splitting it by the colon, and getting the minutes value, which is increased by 0 if the value of the seconds is not 59 (greater than 58), and 1 otherwise, modulo 60. Then this value is padded. Then comes the colon, and lastly, the seconds. The code simply gets the old value, increases it by 1, takes modulo 60 and optionally pads it.
[Answer]
## C ~~309~~ 179 bytes
```
f(){m=0,s=0;A: while(getchar()^'\n'){if(s++==59){if(m++==59)m=0;s=0;}printf("\r%02d:%02d",m,s);sleep(1);system("clear");if(getchar()=='\n'){break;}}while(getchar()^'\n'){}goto A;}
```
Ungolfed version:
```
void f()
{
int m=0,s=0;
A: while(getchar()^'\n')
{
if(s++==59)
{
if(m++==59)
m=0;
s=0;
}
printf("\r%02d:%02d",m,s);
sleep(1);
system("clear");
if(getchar()=='\n')
{
break;
}
}
while(getchar()^'\n')
{}
goto A ;
}
```
Usage: Press `Enter` to *Pause* and *Resume* the Stopwatch.
Explanation:
* Wait for `Enter` keystroke, `break` the first `while` loop and wait until next `Enter` comes.
* Upon next `Enter` keystroke, `goto` first `while` loop and resume counting.
Now, I know `goto` is a bad coding practice in C, but I could not figure out another way.
[Answer]
# Javascript, 124 bytes
```
s=i=1,setInterval("s&&(d=document).close(d.write(`0${i/60%60|0}:`.slice(-3)+`0${i++%60}`.slice(-2))),d.onclick=_=>s=!s",1e3)
```
The 'control key' is a click on the document.
To test this, paste the code in the console or in a html file inside the `<script>` tag.
*Explanation:*
```
let s = 1
let i = 1
setInterval(() => {
//If s = true then check after the "&&" operator else false
s && (d = document).close( //put the document variable inside the d variable, so now i don't need to use anymore the long word 'document, then i close the document
d.write( //Write into the document the next string
`0${i/60%60|0}:`.slice(-3) + `0${i++%60}`.slice(-2) //Here is the magic, here I update the 'i' variable and convert the 'i' value to minutes and seconds
)
),
d.onclick = _ => s = !s //Add onclick event to the document, if s = true then s = false, if s = false then s = true
}, 1e3) //1e3 = 1000
```
Tested in Chrome
[Answer]
# PHP, ~~94~~ 91 bytes
I assume that 32 is the key code for the space bar (which it probably is not);
I currently have no way to test ncurses. But the rest of the code works fine.
```
for($s=[STDIN];;)echo date("\ri:s",$t+=$r^=stream_select($s,$n,$n,1)&&32==ncurses_getch());
```
starts at `00:00`, but increments immediately when pause ends
If You (like me) don´t have ncurses, You can test by replacing the second `date` parameter with `$t+=$r^=!rand(sleep(1),19);` or `$t+=$r^=++$x%20<1+sleep(1);`. (`sleep` always returns `0`.)
**breakdown**
```
for($s=[STDIN]; // set pointer for stream_select
; // infinite loop:
)
echo date("\ri:s", // 5. print CR + time
$t+= // 4. increment $t if watch is running
$r^= // 3. then toggle pause
stream_select($s,$n,$n,1) // 1. wait 1 second for a keystroke
&&32==ncurses_getch() // 2. if keystroke, and key==space bar
;
```
[Answer]
**C# 220 Bytes**
```
using static System.Console;
using static System.DateTime;
class P
{
static void Main()
{
var l = Now;
var d = l-l;
for( var r = 1<0;;Write($"\r{d:mm\\:ss}"))
{
if (KeyAvailable&&ReadKey(1<2).KeyChar == 's')
{
l = Now;
r = !r;
}
if (r)
d -= l - (l = Now);
}
}
}
```
Golfed
```
using static System.Console;using static System.DateTime;class P{static void Main(){var l=Now;var d=l-l;for(var r=1<0;;Write($"\r{d:mm\\:ss}")){(KeyAvailable&&ReadKey(1<2).KeyChar=='s'){l=Now;r=!r;}if(r)d-=l-(l=Now);}}}
```
Using the `s` key to start/stop.
Whole program works by remembering the TimeDelta using `DateTime.Now`
Most C#-Magic here comes from the C# 7.0 feature `using static`.
[Answer]
Bash, 65 bytes
`trap d=\$[!d] 2;for((;;)){ printf "\r%(%M:%S)T" $[n+=d];sleep 1;}`
Note that it must be written to a file script to work correctly, or else, try:
`bash -c 'trap d=\$[!d] 2;for((;;)){ printf "\r%(%M:%S)T" $[n+=d];sleep 1;}'`
Extended version to explain it:
```
trap d=\$[!d] 2 # flip d for each INT (ctrl-c) signal.
for((n=0;;)){ # repeat forever the code inside the {...}
# The n=0 is not strictly needed.
printf "\r%(%M:%S)T" "$[n+=d]" # Print Minute:Second string calculated from
# the n value, increment by the value of d.
# If IFS is not numeric (0-9), then, the
# quotes around "$[n+=d]" could be removed.
sleep 1 # wait for 1 second.
}
```
The `%(...)T` format to printf is valid in bash 5+.
[Answer]
# Commodore BASIC (C64/TheC64 Mini, VIC-20, PET, C16/+4) - 147 tokenized and BASIC bytes
```
0?"{clear}":geta$:ifa$<>" "thengoto
1ti$="000000"
2fori=.to1:?"{home}"mid$(ti$,3,2)":"mid$(ti$,5,2):geta$:b$=ti$:i=-(a$=" "):nE:pO198,.
3geta$:ifa$<>" "then3
4ti$=b$:goto2
```
`{clear}` in the listing is `SHIFT+CLR/HOME` which outputs as one PETSCII character when following an opening quotation mark, whereas `{home}` is the `CLR/HOME` key without the shift on the same condition of following an opening quotation mark.
Use the space bar as the control key.
To work with the Commodore 128 in BASIC 7, change the listing in the following lines:
```
0?"{clear}":geta$:ifa$<>" "thengoto0
2fori=.to1:?"{home}"mid$(ti$,3,2)":"mid$(ti$,5,2):geta$:b$=ti$:i=-(a$=" "):nE:poK198,.
```
Adds an extra seven tokens to the count (as all numbers are stored in BASIC as 7 bytes, so `goto10` is 8 tokenized bytes whereas `goto` is only 1).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~121~~ 115 bytes
```
p,r;g(){r^=1;}main(t,b){for(b=time(signal(2,g));;r?p=t:(b+=t!=p))t=time(0)-b,printf("\r%02d:%02d ",t/60%60,t%60);}
```
[Try it online!](https://tio.run/##JcrBCsIwDADQX5mDQYIZ1h12WAj@iAhrdaXgaom5jX17Vby80wt9DKHWQsoRcNObnHlf55TByOO2vBS8WFof8E4xz08YKCIy66WITeCPYgcpiPZPDntPRVO2Bdqrdm64Tz@apiU7ja4bHdkX5L3WDw "C (gcc) – Try It Online")
Sets a signal handler for SIGINT, which is triggered by pressing control-C. We keep a time offset in `b`, and display the wall clock time minus the time offset. If we are paused, increment the time base everytime the wall clock ticks to freeze the displayed time.
Thanks to @ceilingcat for shaving off 6 bytes!
[Answer]
# Zsh + Gnu date, 242 bytes
Featuring 1/100ths of a second! It requires an interactive terminal, but [here's a TIO link](https://tio.run/##RY5PC4JAEMXv@ymWWCUpbTPo0OihQ7eI6BYqrOn6h7LMXYmK/ey2CtXl8d7wm5n3EkXXtWPrXfssT2PJ8cQQDO7/tGOgUKaJhscptiV16Nw0hwQnrWcF7VVwiQ@b/faoUK7RR1FeOF7BuwXpk6C24wiENtJY0ggq7cbSWCwptYU10yPEk@KGR2HD6qa8ygwb1E1XvWBSYSKYQ@7BfOpGYTKCDJRCnuf1DZ4w9Ggh9kmNfm8z@B4MeeCu@60B0U1kBDmorvsA) anyway.
Hit `Enter` to start/stop the timer; `Ctrl-C` to exit.
```
u(){p=`gdate +%s`;q=`gdate +%N`;}
f(){read -t0.01&&{read;break};unset REPLY}
g(){while :;{u;t=$[p-a];s=$[t%60];m=$[(t%3600-s)/60]
echo "\r`printf %02d:%02d $m $s`.$q[1,2]\c";f;}}
<<<ready;read;u;a=$p
while :;{f;echo "\r\e[2A\c";u;a=$[p-t];g;}
```
Comments (a bit out of date):
```
u()echo $[`gdate +%s%N`/1000] # fn:unix timestamp extended to µs
v()gdate +%s # fn:unix time, in s
f(){read -t0.01 -r&&{read -r;break;} # fn:listens for "Enter"
;unset REPLY;}
g(){while :; # fn:rolling stopwatch
{q=`u`;t=$[`v`-a] # t=time diff from baseline (s)
;echo "\r`printf %02d:%02d # format output
$[(t%3600-s)/60] $s` # minutes:seconds
.${q:10:2}\c"; # .xx = partial seconds
f;}} # listen for "Enter"
# Execution starts here!
<<<ready;read;u;a=$p # Wait for "Enter"; get baseline $a
while :;{ # Main program loop
f; # listen for an "Enter"
echo "\r\e[2A\c" # go up 1 line of the console
a=$[`v`-t] # reset the baseline
;g;} # begin the stopwatch
```
] |
[Question]
[
## Substitute a string with itself
Your goal is to substitute a string with itself by replacing each character in the original string with the one before it, starting with the first character and wrapping around. Here are some examples to show what I mean:
1st example:
```
Input: program
Output: apgopra
How:
Program -> mrogram (replace p by m in program)
-> mpogpam (replace r by p in mrogram)
-> mprgpam (replace o by r in mpogpam)
-> mpropam (replace g by o in mprgpam)
-> mpgopam (replace r by g in mpropam)
-> mpgoprm (replace a by r in mpgopam)
-> apgopra (replace m by a in mpgoprm)
```
2nd example:
```
Input: robot
Output: orbro
How:
Robot -> tobot (replace r by t in robot)
-> trbrt (replace o by r in tobot)
-> trort (replace b by o in trbrt)
-> trbrt (replace o by b in trort)
-> orbro (replace t by o in trbrt)
```
3rd example:
```
Input: x
Output: x
How:
x -> x (replace x by x in x)
```
4th example:
```
Input: xy
Output: xx
How:
xy -> yy (replace x by y in xy)
-> xx (replace y by x in yy)
```
Sidenotes:
* The string `x` will only contain lowercase alphanumeric characters and spaces
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in **bytes** wins!
[Answer]
## CJam, 11 bytes
```
q__1m>.{er}
```
[Test it here.](http://cjam.aditsu.net/#code=q__1m%3E.%7Ber%7D&input=program)
### Explanation
```
q__ e# Read input and make two copies.
1m> e# Rotate the second copy one character to the right.
.{er} e# For each pair of characters from the second and third string,
e# replace occurrences of the first with the second.
```
[Answer]
# [TeaScript](https://esolangs.org/wiki/TeaScript), 17 bytes ~~19~~ ~~21~~ ~~24~~
TeaScript is JavaScript for golfing
```
xd(#lg(i,xC(1#a))
```
Nice and short
[Try it online](http://vihanserver.tk/p/TeaScript/?code=xd(%23lg(i%2CxC(1)%5Ba%5D))&input=program) (watch for trailing whitespace in the input)
### Ungolfed & Explanation
```
x.reduce // Reduce over input
(# // Anonymous function expands to ((l,i,a)=>
l.g( // global replace...
i // replace var i with...
x.cycle(1) // Cycle x 1
[a] // At position a
)
)
```
[Answer]
# JavaScript ES6, 69 bytes
```
s=>[...s].reduce((p,c,i)=>p.replace(RegExp(c,'g'),s.slice(i-1)[0]),s)
```
```
F=s=>[...s].reduce((p,c,i)=>p.replace(RegExp(c,'g'),s.slice(i-1)[0]),s)
input.oninput=()=>output.innerHTML=F(input.value)
```
```
#input, #output {
width: 100%;
}
```
```
<textarea id='input' rows="5">
</textarea>
<div id="output"></div>
```
[Answer]
# Ruby, ~~50~~ 48 bytes
```
->s{t=s.dup;t.size.times{|i|t.tr!s[i],s[i-1]};t}
```
Test:
```
f=->s{t=s.dup;t.size.times{|i|t.tr!s[i],s[i-1]};t}
f["program"]
=> "apgopra"
```
[Answer]
# Mathematica, ~~89~~ ~~75~~ ~~74~~ 57 bytes
```
""<>Fold[#/.#2&,c=Characters@#,Thread[c->RotateRight@c]]&
```
[Answer]
# Pyth, 13 bytes
```
u:G.*HC.>Bz1z
```
[Try it online.](https://pyth.herokuapp.com/?code=u%3AG.*HC.%3EBz1z&input=program) [Test suite.](https://pyth.herokuapp.com/?code=u%3AG.*HC.%3EBz1z&test_suite=1&test_suite_input=program%0Arobot%0Ax%0Axy)
[Answer]
# k2 - 17 char
Function taking 1 argument.
```
{_ssr/[x;x;-1!x]}
```
k2 has a builtin called `_ssr` for **S**tring **S**earch and **R**eplace. `_ssr[x;y;z]` will find `y` in `x` and replace it with `z`. So we use `/` to fold this functionality over each replacement we want to make. For those unfamiliar with folding (as in functional programming), essentially `_ssr/[x; (y1; y2; y3); (z1; z2; z3)]` becomes `_ssr[_ssr[_ssr[x; y1; z1]; y2; z2]; y3; z3]`. Strings are lists of their characters, so we may simply rotate the input back a step and get the replacements, and plug right in.
```
{_ssr/[x;x;-1!x]} "program"
"apgopra"
{_ssr/[x;x;-1!x]} "robot"
"orbro"
{_ssr/[x;x;-1!x]} (,"x") / one-letter strings are ,"x" and parens are required
,"x"
{_ssr/[x;x;-1!x]} "xy"
"xx"
```
[Answer]
# Haskell, 76 bytes
```
[]#_=[];(x:y)#g@(a,b)|x==a=b:y#g|2>1=x:y#g;h x=foldl(#)x$zip x$last x:init x
```
Too bad, Haskell doesn't even have a build-in substitution function.
[Answer]
## PHP, 76 bytes
```
function($s){$f=str_split;echo str_replace($f($s),$f(substr($s,-1).$s),$s);}
```
Here is the ungolfed version:
```
function selfSubstitute($originalString)
{
$shiftedString = substr($originalString, -1) . $originalString;
$splitOriginalString = str_split($originalString);
$splitShiftedString = str_split($shiftedString);
echo str_replace($splitOriginalString, $splitShiftedString, $originalString);
}
```
[Answer]
# Python, ~~67~~ ~~64~~ ~~62~~ 57 Bytes
Straightforward solution, will look into something to shorten this. Thanks to @RandyC for saving 5 bytes.
```
c=input()
for x in zip(c,c[-1]+c):c=c.replace(*x)
print c
```
Input should be in quotes.
[Answer]
# Haskell, 58 bytes
```
r(x,y)c|x==c=y|0<1=c;f s=foldl(flip$map.r)s.zip s$last s:s
```
Pretty similar to Christian's solution, but using `map` and the fact that `zip` ignores superfluous elements if the lists are of unequal length. It folds through the list of replacements (on the form `(from,to)`), updating the string by mapping the hand written replacement function `r` on each letter.
The expression `flip$map.r` was derived using LambdaBot's "Pointless" plugin.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ ~~9~~ 7 bytes
```
ṙ-ż@y@ƒ
```
[Try it online!](https://tio.run/##y0rNyan8///hzpm6R/c4VDocm/T/cPujpjWR//8rFRTlpxcl5irpKCgV5Sfll4AYFWCiUgkA "Jelly – Try It Online")
Having seen caird's `y`-based solution, I spent several hours trying to use matrix multiplication instead, but eventually I took a crack at `y` and arrived at this.
Speaking of caird's solution, I was about to pose the question to JHT of how to outdo `J_.ịƲU` for "obtaining pairs of elements from the input followed by the elements preceding them, wrapping around", but as I wrote that whole thing out I realized I never did actually try using `ż`!
The edit history contains some nice old explanations if anyone wants to read them.
```
ṙ Rotate the input left
- by -1.
ż@ Zip the input with the rotated input.
ƒ Starting with the input, reduce the resulting pairs by
y@ substitution.
```
[Answer]
# [J](http://jsoftware.com/), 18 bytes
```
rplc~/@,~|.,.1|.|.
```
[Try it online!](https://tio.run/##y/r/P81WT6GoICe5Tt9Bp65GT0fPsEavRu9/anJGvkKagnpBUX56UWKuOhdMoCg/Kb8Ewa1Q/w8A "J – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
żṙ-$,µ,Ḣy¥¥/ḷ/¿
```
[Try it online!](https://tio.run/##y0rNyan8///onoc7Z@qq6BzaqvNwx6LKQ0sPLdV/uGO7/qH9/w@3P9y5SjPy/3@lgqL89KLEXCUdBaWi/KT8EhCjAkxUKgEA "Jelly – Try It Online")
Jelly sucks at strings
## How it works
```
żṙ-$,µ,Ḣy¥¥/ḷ/¿ - Main link. Takes a string S on the left
$ - Group the previous two links together:
- - -1
ṙ - Rotate S 1 unit to the right
ż - Zip S with rotated S; Call this M
, - Pair with S; [M, S]
µ - Begin a new link with this pair as the argument
¥ - Group the previous two links together as a dyad f(p, s):
¥ - Group the previous two links together as a dyad g(p, s):
Ḣ - Remove the first pair in p and use it; [c, t]
y - Replace c with t in s
, - Yield a pair with the modified p and the replaced s
¿ - While:
ḷ/ - The first element is truthy
/ - Run f(M, S)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
dUíUé
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ZFXtVek&input=InByb2dyYW0i)
```
dUíUé :Implicit input of string U
d :For each pair XY in the following string, recursively replace X with Y
Uí : Interleave U with
Ué : U rotated right
```
[Answer]
# [Perl 5](https://www.perl.org/) `-pF`, 34 bytes
```
for$a(0..$#F){s/$F[$a]/$F[$a-1]/g}
```
[Try it online!](https://tio.run/##K0gtyjH9/z8tv0glUcNAT09F2U2zulhfxS1aJTEWQukaxuqn1/7/X1CUn16UmMtVlJ@UX8JVwVVR@S@/oCQzP6/4v25BjhsA "Perl 5 – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 29 bytes
```
⟨tc≡⟩⟨gcs₂ᶠ⟩{gᵗz{tᵛ&th|h}ᵐ}ˡb
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/9H8FSXJjzoXPpq/EshMTy4GyW1bAORWpz/cOr2quuTh1tlqJRk1GSDltacXJv3/H61UUJSfXpSYq6SjoFSUn5RfAmJUgIlKpVgA "Brachylog – Try It Online")
```
c Concatenate
t the last item of the input
⟨ ≡⟩ with the input.
c Concatenate
g that result in a singleton list
⟨ s₂ᶠ⟩ with a list of its length-2 substrings.
... b Remove the extra element from the final result.
{ }ˡ Left fold:
gᵗz zip each element of the first element with the entire second element,
{ }ᵐ and for each of those pairs:
tᵛ the last element of both is the same
&th and the first element of the last element of the pair
| is the output, or
h the first element of the pair is the output.
```
] |
[Question]
[
The [Dottie number](http://mathworld.wolfram.com/DottieNumber.html) is the fixed point of the cosine function, or the solution to the equation **cos(x)=x**.1
Your task will be to make code that approximates this constant. Your code should represent a function that takes an integer as input and outputs a real number. The limit of your function as the input grows should be the Dottie number.
You may output as a fraction, a decimal, or an algebraic representation of a number. Your output should be capable of being arbitrarily precise, floats and doubles are not sufficient for this challenge. If your language is not capable of arbitrary precision numbers, then you must either implement them or choose a new language.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored in bytes, with fewer bytes being better.
### Tips
One way of calculating the constant is to take any number and repeatedly apply the cosine to it. As the number of applications tends towards infinity the result tends towards the fixed point of cosine.
Here is a fairly accurate approximation of the number.
```
0.739085133215161
```
1: Here we will take cosine in radians
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~34~~ ~~30~~ 19 bytes
*11 bytes off thanks to [Sanchises](https://codegolf.stackexchange.com/users/32352/sanchises)!*
```
48i:"'cos('wh41hGY$
```
The last decimal figures in the output may be off. However, the number of correct figures starting from the left increases with the input, and the result converges to the actual constant.
[**Try it online!**](https://tio.run/##y00syfn/38Qi00pJPTm/WEO9PMPEMMM9UuX/fyMDAwA)
### Explanation
For input *n*, and starting at *x*=1, this applies the function
*x* ↦ cos(*x*)
with *n*-digit [variable-precision arithmetic](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic) *n* times.
```
48 % Push 48, which is ASCII for '1': initial value for x as a string
i:" % Do n times, where n is the input
'cos(' % Push this string
w % Swap. Moves current string x onto the top of the stack
h % Concatenate
41 % Push 41, which is ASCII for ')'
h % Concatenate. This gives the string 'cos(x)', where x is the
% current number
GY$ % Evaluate with variable-prevision arithmetic using n digits
% The result is a string, which represents the new x
% End (implicit). Display (implicit). The stack contains the last x
```
[Answer]
# [dzaima/APL](https://github.com/dzaima/APL), 55 bytes
```
⎕←⊃{⍵,⍨-/P,((P÷⍨×)/¨(2×⍳N)⍴¨⊃⍵)÷!2L×⍳N}⍣{⍵≢∪⍵}P←10L*N←⎕
```
Using big integer (no big decimals!) arithmetic (where \$10^N\$ is the equivalent of a `1`), iterate the first \$N\$ terms of the Taylor series (an overestimate, but that's fine) until a duplicate has been encountered. May be off by a bit due to lost precision in the end, but, as with other answers, those differences will disappear with higher \$N\$.
No TIO link as TIO's dzaima/APL hasn't been updated to support bigintegers.
Example I/O:
```
1
9L
10
7390851332L
100
7390851332151606416553120876738734040134117589007574649656806357732846548835475945993761069317665318L
200
73908513321516064165531208767387340401341175890075746496568063577328465488354759459937610693176653184980124664398716302771490369130842031578044057462077868852490389153928943884509523480133563127677224L
```
[Answer]
# [Python 3](https://docs.python.org/3/), 58 bytes
```
lambda n:S('cos('*n+'0'+')'*n).evalf(n)
from sympy import*
```
[Try it online!](https://tio.run/##FcsxDoMwDADAGV7hzTZIVVA3pL6CtUtoSYlE7MhElfL6tGy3XK5lV7m3AA94tsOn9e1B5oXwpSfhICM6HJH/4tv29Ucg4T6YJjhryhViymplaEENBKKAeflsNDnHc99li1LoOtx@ "Python 3 – Try It Online")
[Answer]
# GNU bc -l, 30
Score includes +1 for `-l` flag to `bc`.
```
for(a=1;a/A-b/A;b=c(a))a=b
a
```
The final newline is significant and necessary.
[Try it online](https://tio.run/##S0r@/z8tv0gj0dbQOlHfUTdJ39E6yTZZI1FTM9E2iSuR6////7o5AA).
`-l` does 2 things:
* enable the "math" library, including `c()` for cos(x)
* sets precision (scale) to 20 decimal places (`bc` has arbitrary precision calculation)
I'm not really clear on the precision requirement. As it is, this program calculates to 20 decimal places. If a different precision is required, then `scale=n;` needs to be inserted at the start of the program, where `n` is the number of decimal places. I don't know if I should add this to my score or not.
Note also that for some numbers of decimal places (e.g. 21, but not 20), the calculation oscillates either side of the solution in the last digit. Thus in the comparison of current and previous iterations, I divide both sides by 10 (`A`) to erase the last digit.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 19 bytes
```
Nest[Cos,0,9#]~N~#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773y@1uCTaOb9Yx0DHUjm2zq9OWe1/QFFmXomCQ3q0oYFB7P//AA "Wolfram Language (Mathematica) – Try It Online")
-3 bytes from @alephalpha
[Answer]
# [R](https://www.r-project.org/) (+Rmpfr), 55 bytes
```
function(n,b=Rmpfr::mpfr(1,n)){for(i in 1:n)b=cos(b);b}
```
Dennis has now added Rmpfr to TIO so this will work; added some test cases.
### Explanation:
Takes the code I wrote from [this challenge](https://codegolf.stackexchange.com/questions/137527/calculate-the-n-th-iterate-of-a-polynomial-for-a-specific-value-f%E2%81%BFx) to evaluate `cos` `n` times starting at `1`, but first I specify the precision I want the values to be in by creating an object `b` of class `mpfr` with value `1` and precision `n`, `n>=2`, so we get more precision as we go along.
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPJ8k2KLcgrcjKCkRqGOrkaWpWp@UXaWQqZOYpGFrlaSbZJucXayRpWifV/i9OLCjIqdQwNIjTMLAy0dQ21EnT/A8A)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 42 bytes
```
@(n)digits(n)*0+vpasolve(sym('cos(x)-x'));
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI08zJTM9s6QYyNAy0C4rSCzOzylL1SiuzNVQT84v1qjQ1K1Q19S0/p@mYWSo@R8A "Octave – Try It Online")
Pretty much a duplicate of [my answer to Approximate the Plastic Number](https://codegolf.stackexchange.com/questions/126820/approximate-the-plastic-number), but somewhat shorter due to more relaxed requirements.
[Answer]
# [Mathics](http://mathics.github.io/) or Mathematica, 46 bytes
```
{$MaxPrecision=#}~Block~Cos~FixedPoint~N[1,#]&
```
[Try it online!](https://tio.run/##y00sychMLv7/v1rFN7EioCg1ObM4Mz/PVrm2ziknPzm7zjm/uM4tsyI1JSA/M6@kzi/aUEc5Vu1/QBGQF60abWhgEBv7HwA "Mathics – Try It Online")
[Answer]
# [PHP](https://php.net/), 50 bytes
```
$a=$argv[1];$i=$j=0;while($i<$a){$j=cos($j);$i++;}
```
[Try it online!](https://tio.run/##K8go@G9jXwAkVRJtVRKL0suiDWOtVTJtVbJsDazLMzJzUjVUMm1UEjWrgSLJ@cUaKlmaQHltbeva/6nJGfkqWdb2dv//GxoAAQA "PHP – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 57 54 bytes
```
u_.tG1lX$globals()$"neg"$__import__("decimal").Decimal
```
This would be much shorter if we didn't need the Decimal to be up to spec, but it is what it is.
Edit 1: -3 bytes because we need a number anyways, so we can use `X`s returned copy of `globals()` length as our starting value, moving it to the end and removing a `$` and some whitespace.
[Try it online!](https://tio.run/##K6gsyfj/vzRer8TdMCdCJT0nPykxp1hDU0UpLzVdSSU@PjO3IL@oJD5eQyklNTkzNzFHSVPPBcL6//9ffkFJZn5e8X/dFAA "Pyth – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 84 bytes
```
n=>"0."+(F=(J,Z=c=0n)=>J?F(J*-I*I/++c/++c/B/B,Z+J):I-Z>>2n?(I=Z,F(B)):I)(B=I=10n**n)
```
[Try it online!](https://tio.run/##Hcw9CsMwDEDhu2SS/JO4hS4FOeDBIB/BW3CT0hLk0oRc3w0d3vIN7z0d01a@r89upT7mtlAT8p3rOw2RIJlMhZwg@TRGSMqy4kHr8i8MwWSd8M42e3@VEZiyiRDwJIRATBcnSgm2UmWr69yv9QkL3M4jth8 "JavaScript (Node.js) – Try It Online")
Has a precision of roughly `n-1` digits. BigInt is used and `cos(x)` is calculated using its Taylor expansion. The `I-Z>>2n` part is used only to prevent looping forever (with a cost of 4 bytes and some precision). Although theoretical applicable for arbitrary precision, practical range is `n<63` because of stack overflow.
### Shorter (82 bytes), no worries about stack overflow, but far fewer precision
```
n=>"0."+eval("for(I=B=10n**n;n--;I=Z)for(Z=J=B,c=0n;J;)Z+=(J=J*-I*I/++c/++c/B/B)")
```
### Much shorter (80 bytes), larger range until stack overflow (`n<172`), but same precision as the 82-byte.
```
n=>"0."+(F=(J,Z=c=0n)=>J?F(J*-I*I/++c/++c/B/B,Z+J):n--?(I=Z,F(B)):I)(B=I=10n**n)
```
### If arbitrary precision is not the main point, then 25 bytes:
```
F=n=>n?Math.cos(F(n-1)):1
```
[Answer]
# [Factor](https://factorcode.org/) + `math.polynomials math.factorials`, 66 bytes
```
[| x | 1 x [ sq neg x [0,b) [ 2 * n! recip ] map polyval ] times ]
```
[Try it online!](https://tio.run/##NY0xC8IwFIT3/opzVEqx4qTgKi4u4lQ6pPG1BtMkTVKx0P8ek6LL8e7j3l3LuNc23G@X6/mAF1lFElJzJh165p@LFO2SEn9YGC0npfsEsgVYpjpyMJa8n4wVysPRMJLikR6zPaoyb@pQzfhgRhm1ghugqEvnNm/WEeywgVrBEhcGdVwySENvJqPzoo9VdUj0MRoU8eHUSs38L1qELw "Factor – Try It Online")
Factor has rational numbers, but no arbitrary-precision decimals. This answer tries to exploit it as much as possible: iterate the evaluation of the fist `n` terms of Taylor series (more precisely, Maclaurin series) `n` times, with the starting value of 1. The output is given as a rational number; the floating-point representation is also shown on TIO to check the value in human-readable form.
The function is very slow to calculate and very slow to converge, but in theory it must converge to the Dottie number as `n` increases, since the iterated function approaches the cosine function, the iteration count increases to infinity, and the whole computation is done in rationals (and therefore exact).
### How it works
Given a positive integer \$n\$, the code approximates the Dottie number as follows:
$$
\cos{x} = \sum\_{i=0}^{\infty}{\frac{(-1)^i}{(2i)!}x^{2i}}
\approx \sum\_{i=0}^{n-1}{\frac{(-x^2)^i}{(2i)!}} \\
\text{Dottie number } = \cos{x} \text{ iterated } \infty \text{ times on } 1 \\
\approx \sum\_{i=0}^{n-1}{\frac{(-x^2)^i}{(2i)!}} \text{ iterated } n \text{ times on } 1
$$
```
[| x | ! an anonymous function that takes one arg `x` as a local variable
1 x [ ... ] times ! repeat the inner function x times on the value 1...
sq neg ! val -> -val^2
x [0,b) ! 0..x-1
[ 2 * n! recip ] map ! convert each number `i` to 1/(2i)!
polyval ! evaluate the array as polynomial at the value of -val^2
]
```
[Answer]
# [Julia 1.0](http://julialang.org/), 42 bytes
```
!n=big(n<2||setprecision(()->cos(!~-n),n))
```
[Try it online!](https://tio.run/##DcFNCoAgEAbQfafQ3QwUaMuo7tKPxYR8iha0iK5uvXdcXiZ7l6IxzLIT@vZ5sjtjcotkCSDiZlxCJv024BrMZQtJiRIo21ljTKV@MQlOD9LClcNaPg "Julia 1.0 – Try It Online")
sets the precision of `BigFloat`s to `n` bits and computes \$cos^{n-1}(1)\$ recursively
[Answer]
# Perl 5, 41 Bytes
```
use bignum;sub f{$_[0]?cos(f($_[0]-1)):0}
```
Bignum is required for the arbitrary precision. Defines a function f that recursively applies cosine to 0 N times.
TIO doesn't seem to have bignum so no link :(
[Answer]
## Mathematica 44 Bytes
```
FindRoot[Cos@x-x,{x,0},WorkingPrecision->#]&
```
`FindRoot` uses Newton's method by default.
[Answer]
# Axiom, 174 bytes
```
f(n:PI):Complex Float==(n>10^4=>%i;m:=digits(n+10);e:=10^(-n-7);a:=0;repeat(b:=a+(cos(a)-a)/(sin(a)+1.);if a~=0 and a-b<e then break;a:=b);a:=floor(b*10^n)/10.^n;digits(m);a)
```
ungolfed and commented
```
-- Input: n:PI numero di cifre
-- Output la soluzione x a cos(x)=x con n cifre significative dopo la virgola
-- Usa il metodo di Newton a_0:=a a_(n+1)=a_n-f(a_n)/f'(a_n)
fo(n:PI):Complex Float==
n>10^4=>%i
m:=digits(n+10)
e:=10^(-n-7)
a:=0 -- Punto iniziale
repeat
b:=a+(cos(a)-a)/(sin(a)+1.)
if a~=0 and a-b<e then break
a:=b
a:=floor(b*10^n)/10.^n
digits(m)
a
```
results:
```
(3) -> for i in 1..10 repeat output[i,f(i)]
[1.0,0.7]
[2.0,0.73]
[3.0,0.739]
[4.0,0.739]
[5.0,0.73908]
[6.0,0.739085]
[7.0,0.7390851]
[8.0,0.73908513]
[9.0,0.739085133]
[10.0,0.7390851332]
Type: Void
Time: 0.12 (IN) + 0.10 (EV) + 0.12 (OT) + 0.02 (GC) = 0.35 sec
(4) -> f 300
(4)
0.7390851332 1516064165 5312087673 8734040134 1175890075 7464965680 635773284
6 5488354759 4599376106 9317665318 4980124664 3987163027 7149036913 084203157
8 0440574620 7786885249 0389153928 9438845095 2348013356 3127677223 158095635
3 7765724512 0437341993 6433512538 4097800343 4064670047 9402143478 080271801
8 8377113613 8204206631
Type: Complex Float
Time: 0.03 (IN) + 0.07 (OT) = 0.10 sec
```
I would use the Newton method because it would be faster
than 'repeated cos(x) method'
```
800 92x
1000 153x
2000 379x
```
where in the first column there is the number of digit
and in the second column there is how much Newton method
is faster than use repeated cos(x) method, here.
Good Morning
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 35 bytes
```
1.."$args"|%{$x=[Math]::Cos($x)}
$x
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SZlv931BPT0klsSi9WKlGtVqlwjbaN7EkI9bKyjm/WEOlQrOWS6Xify0Xl5pKmoKhgYHBfwA "PowerShell Core – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 6 bytes
```
(∆c)$Ḟ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJBIiwiIiwiKOKIhmMpJOG4niIsIiIsIjVcbjEwXG4yMFxuNTBcbjEwMCJd)
Uses sympy's arbitrary-precision cosine function. Since decimals are outputted to a fixed precision (although stored as arbitrary-precision) it has to be taken to n decimal places.
```
( ) # n times
∆c # cosine
$Ḟ # result to n decimal places
```
[Answer]
# [Maxima](http://maxima.sourceforge.net/), 93 bytes
A port of [@MarcMush's Julia 1.0 answer](https://codegolf.stackexchange.com/a/238273/110802) in Maxima.
93 bytes, it can be golfed much more.
---
Golfed version. [Try it online!](https://tio.run/##NY69DoMwDIT3PIVHgqiAjmm79QG6Vx0gJMIq2CgJ/Xn6NBHFy8mf7k43dx@cu1iXcDUWyUAYDTijV@fxZcCupAMywRvDCMOXuhk1LMmAPuOyFrEvSKpLP7F@Fnd@VKzskh3VJooqp9ACnY@5nKC3E3chhczkzf5p9kUqOrRSyj3IlZPxJEQad3NI4b/Nr1PwYB3P0EJgaJumyUMsO0CV0OjWDQ4MhYB0S46nfpRSyFP8AQ)
```
b(n):=block([o],o:fpprec,fpprec:n,r:if n<2 then bfloat(n)else bfloat(cos(b(n-1))),fpprec:o,r)
```
Ungolfed version. [Try it online!](https://tio.run/##fZHBTsQgEIbvfYo5lo1mW49Vbz6A0ePGGEqHlEihGWB3ffrKtLa7GxO5EIb/G/5/GOTZDHLa7@AFtXEIsUcgVImCOSLo5FQ03sHJxB66bycHo2DMAhO4vNsXbekENM/QWq@@ygLyOnjbfbLo424@5@7v8rj0zle3PAtWfQN65P2CYZypC0FoZWRr0cPGL1QDbgNfkbSnYYaVtCoxtebgosPTXx@EIdnYgNG59xM8sNJBq62XkWOiDbgelQ9lzn5fCyG2Z98wRE//JF2dromvyJjI/Y6fXdx6KsRjUXAuMi5eqQJo8gPUPI66qiqmcnAwTS71lJZi52H5mZHxbNsIkTtO0/QD)
```
/* Define the recursive function with dynamic precision */
b(n) := block(
[old_prec],
/* Save the old precision */
old_prec: fpprec,
/* Set the precision relative to n */
fpprec: n,
/* Perform the calculation with the new precision */
result: if n < 2 then bfloat(n) else bfloat(cos(b(n-1))),
/* Restore the old precision */
fpprec: old_prec,
/* Return the result */
result
);
/* Print the results from 1 to 1000 */
for i:1 thru 1000 do (
print(b(i))
);
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 47 bytes
```
f(n)=if(n,subst(Pol(cos(x+O(x^n))),x,f(n-1)),1)
```
[Try it online!](https://tio.run/##K0gsytRNL/j/P00jT9M2E0jqFJcmFZdoBOTnaCTnF2tUaPtrVMTlaWpq6lToAKV1DYEsQ83/aflFGnkKtgoGOgpmOgoFRZl5JUC@koKuHZAAGaap@R8A "Pari/GP – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 267 bytes
```
f d=(iterate(\(b,e)->r(\(x,y)(z,w)->(x*10^(2*d-y)+z*10^(2*d-w),2*d))(0,0)$takeWhile((/=0).fst)[r(\(x,y)(z,w)->(x*z,y+w))((-1)^n,0)[let z=2*e*n;s=max(z-d)0in(b^(2*n)`div`10^s,z-s),(10^d`div`product[2..2*n],d)]|n<-[0..]])(7,1))#[];(h:t)#v|h`elem`v=h|0<1=t#(h:v);r=foldr
```
[Try it online!](https://tio.run/##ZU/BboMwDP2VqOxgQ8gCl0prwxfstsMOjAq6BAWVhiqk0KL@O3N32GUXv/dsPz/ZNuPJ9P26tkwr6ILxTTDwBUduMC08sRu/Iyx8Jgm3OJMHyGOd3jFZ/sSMnAARJJf4EpqT@bRdbwBelUTRjgHL/5cWfk9m8kCa4cGRsexNYIvKYxO73ajOzQ2WVKPsHByfOQ5r3U01hY58SUfkQFT/9i5@0NfvUOZC0F7FNVYPt09LKURVIWx5hhiV1Q7sW8Boetja9OZcT8o@5D5TIaLBhDuv2qHXfj03nWOKedPod8eKQrHLNXwET0Iw2EixSRIkOtphJqAHn3Xdyh8 "Haskell – Try It Online")
[Answer]
# [Go](https://go.dev), 71 bytes
```
import."math"
func f(n int)(k float64){for;n>=0;n--{k=Cos(k)}
return k}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY5NCoMwFIT3OcUjq0SqSCmlVOymi25LbxCKsY_oi8TnSjxJN1LoobxNtX-rgRnmm7k_Sj9OUWOuzpQF1AZJYN34wIlsOSCVrfwbtmb57NjGu-n082rDNylsR1ewigCJtXJgK294u9G99SGjQ55mFMe9y4--VU4PIhTcBQI3_HBvwLKuNPRibgHCPodgaH51KZrCsJKJXK3TJccoR3Ge33FFClfzMmotBvHFjeNHXw)
Input is the number of times to apply `cos`. Limited to 64-bit floating point precision.
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 33 bytes
Takes the desired precision as an argument.
```
~:!~%(:& &~(:cos&BigMath))&0.to_d
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qfKmVbSSblFSZnpKanJmbmKOko4CCl8_N7EkA0OwtCQzRyl2kZvt0tKSNF2Lm4p1Vop1qhpWagpqdRpWyfnFak6Z6b5AnZqaagZ6JfnxKRCFywoU3KItYiGcBQsgNAA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
õ Ôr@McX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9SDUckBNY1g&input=NTAw)
```
õ Ôr@McX :Implicit input of integer U
õ :Range [1,U]
Ô :Reverse
r :Reduce by
@ :Passing the current value X (initially the first element) through the following function
McX : Cosine of X
```
[Answer]
# APL(NARS), 219 chars
```
R←{⍵=0:⍵⋄10≥m←(⍺-⍨⌊10⍟d←∣1∧÷⍵×1x)⌊⍺-⍨⌊10⍟n←∣1∧⍵×1x:⍵⋄(×⍵)×(⌊n÷q)÷⌊d÷q←{(10∘×⍣⍵)1x}m-5}
r←p C w;d;e;v;m
r←d←1⋄e←1÷10x*p⋄v←¯1,0⋄m←w×wׯ1
r+←d×←m÷×/v+←2⋄→2×⍳e<∣d⋄r←p R r
r←D w;e;v
e←1÷10x*w⋄v←1x
r←w C v⋄→0×⍳e>∣v-r⋄v←r⋄→2
```
C is the cos function, has as parameters p the precision (or the number of digits afther the decimal point)
and w the rational number (here represented using r as in 23r4 for 23/4) and return a rational. If the argument
of that function is a int or a float, it return one float. For 3 significative digits we have
```
3 C 1
0.5403028025
3 C 1x
4357r8064
2○1
0.5403023059
```
D is the function that would return the number in question that has argument the digit of precision.
How appear one fractional result?
```
D 3
117407r158925
```
So there is need one function that traslate the fractional result in a decimal string we can read
r2fs: input ⍺ the precision ⍵ one rational number
```
r2fs←{⎕ct←0⋄k←≢b←⍕⌊⍵×10x*a←⍺⋄k-←s←'¯'=↑b⋄c←{s:'¯'⋄''}⋄m←s↓b⋄0≥k-⍺:c,'0.',((⍺-k)⍴'0'),m⋄c,((k-⍺)↑m),'.',(k-⍺)↓m}
```
One has to note as ⎕ct is a local varible in r2fs and its value in use out of that function is different.
So all could be more clear
```
8 r2fs¨ D¨ 1 2 3 4 5 6 7 8
0.70224186 0.73556389 0.73875727 0.73905483 0.73908230 0.73908552 0.73908517 0.73908513
19 r2fs D 20
0.7390851332151606416
40 r2fs D 39
0.7390851332151606416553120876738734040131
39 r2fs D 40
0.739085133215160641655312087673873404013
```
For the C function sometime the result is not ok for float input
```
10 C 45
55.65114514
2○45
0.5253219888
10 C 45
55.65114514
2○45
0.5253219888
```
but the fraction input it seems converge right for cos
```
49 r2fs 50 C 45x
0.5253219888177296960474644048235629188973106884573
```
One other problem one has to solve here it seems to me that the function D can converge to that number but its fraction in r
is so big that consume all resources so have to be cut in some way... I would say one could reduce the size of the fraction in memory
cuting the final parts of the numerator and denomicator (save all the digits of both until precision number),
something as function R make (for me R has to be used inside the cos).
] |
[Question]
[
Challenge: Implement [ROT-47](http://rot47.net/) in code that works as both itself and as the ROT-47 version of itself.
### Scoring:
Your score is calculated as a percentage of **used, ROT-47 eligible bytes in total of both versions of the program** divided by **total bytes (all characters) of both versions**.
A **used, ROT-47 eligible byte** is any character that would be converted by the ROT-47 cipher that is not **part of a comment** or ignored by the compiler/interpreter. For example, any character in a brainfuck program that is not `+-<>[],.` is not considered a used byte, and any character in a C program including and after `//` or inside `/* */` is not considered a used byte. All special symbols in APL are not considered used, as are all characters in a Whitespace program (sorry).
Ties will be broken by the program with the most upvotes. If there is still a tie, then the shortest program wins.
Example scoring:
### C: 62/64 = 96.875%
Notice there is a space in this program. Obviously also, this program is not a valid entry because it doesn't even compile, but I wanted to show how scoring works.
```
main(){printf("Hello World!");}
```
[Answer]
# Ruby, 100% (74 characters)
Input on STDIN, output on STDOUT.
```
Vj=s=gets;puts(s.tr'!-~','P-~!-O');Vj;'lDl86EDjAFEDWD]ECVP\OV[V!\OP\~VXj;'
```
The second line is the first line ROT-47'd. Therefore, when ROT-47ing the whole program, it becomes:
```
';lDl86EDjAFEDWD]ECVP\OV[V!\OP\~VXj';jV=s=gets;puts(s.tr'!-~','P-~!-O');jV
```
My strategy here is based upon the fact that:
* `V` is `'` when ROT-47'd
* `j` is `;` when ROT-47'd
* Therefore, `Vj=...Vj;` turns into `';l...';`, which is essentially a no-op
+ Now you can create any arbitrary code that does anything normally and no-ops when ROT-47'd. This is because `Vj=...Vj;` can support running any code as you could do `Vj=0;{INSERT ANY CODE};Vj;`, and that will become `'...';` when ROT-47'd. You just have to be careful not to use `V` in that code, since that will break it.
* Similar logic can be used in reverse to produce the second half (`jV` instead of `Vj`)
[Answer]
# C - 54.6%
```
Y;BW;XL;jNj;AW(){XL^Y;};main(int i,char**v){char*x=v[1];while(*x){if(*x>32&&*x<128)*x=(*x+15)%94+32;putchar(*x++);}}//Y^Nj>2:?W:?E :[492CYYGXL492CYIlG,`.jH9:=6WYIXL:7WYImbaUUYIk`agXYIlWYIZ`dXThcZbajAFE492CWYIZZXjNN
```
When ROT-47-translated, we get
```
*jq(j){j;};jp(WXL){/*jNj>2:?W:?E :[492CYYGXL492CYIlG,`.jH9:=6WYIXL:7WYImbaUUYIk`agXYIlWYIZ`dXThcZbajAFE492CWYIZZXjNN^^*/};main(int i,char**v){char*x=v[1];while(*x){if(*x>32&&*x<128)*x=(*x+15)%94+32;putchar(*x++);}}
```
Both programs compile, and ROT-47-translate the first argument:
```
$ ./a "hello world"
96==@ H@C=5
```
[Answer]
## GolfScript, 120 / 120 bytes = 100%
```
{:&&32>&&+254<*{7+7+94%33+}*}%LiUUbamUUZadckYLfZfZhcTbbZNYNT
```
or, in ROT-47:
```
LiUUbamUUZadckYLfZfZhcTbbZNYNT{:&&32>&&+254<*{7+7+94%33+}*}%
```
No comments or string abuse. The undefined command `LiUUbamUUZadckYLfZfZhcTbbZNYNT` (which equals the rest of the code in ROT-47) is a no-op, but it still gets executed by the interpreter, so I believe it counts as used.
This was actually a pretty easy challenge in GolfScript. The main difficulty was in avoiding the digit `1`, which is mapped by ROT-47 into the GolfScript command ```. The commands `.`, `-`, `,`, `\`, `[`, `/`, `]` and `^` also had to be avoided, but that was fairly easy in this case, since the task required no array building.
### Bonus:
Here's a GolfScript [period-2 quine](https://codegolf.stackexchange.com/questions/2582/golf-a-mutual-quine) (i.e. a program that prints a second program that prints the first program again) where the two programs are the ROT-47 transforms of each other:
```
{`'0$~'+.{7+7+94%33+}%@!{0$@@;}*}0$~L1V_SOVZ]LfZfZhcTbbZNToPL_SoojNYN_SO
```
This program outputs itself ROT-47 encoded, yielding another GolfScript program:
```
L1V_SOVZ]LfZfZhcTbbZNToPL_SoojNYN_SO{`'0$~'+.{7+7+94%33+}%@!{0$@@;}*}0$~
```
which, in turn, also outputs itself ROT-47 encoded, yielding the previous program again. Thus, this program is also a [rotating quine](https://codegolf.stackexchange.com/questions/5083/create-a-rotating-quine).
[Answer]
# python, 96.1% (?)
According to your definition, strings count as used code?
```
V=input();print("".join([chr(33+(ord(V[i])+14)%94)for i in range(len(V))]));V
'l:?AFEWXjAC:?EWQQ];@:?W,49CWbbZW@C5WD,:.XZ`cXThcX7@C : :? C2?86W=6?WDXX.XXj'
```
] |
[Question]
[
## Background
An **almost regular hexagon** is a hexagon where
* all of its internal angles are 120 degrees, and
* pairs of the opposite sides are parallel and have equal lengths (i.e. a [zonogon](https://en.wikipedia.org/wiki/Zonogon)).
The following is an example of an almost regular hexagon, with side lengths 2 (red), 4 (blue), and 3 (yellow).

A **triangular domino** is a domino made of two unit triangles. A **triangular domino tiling** is a tiling on a shape using triangular dominoes. The following is a possible triangular domino tiling of the above shape (each color represents an *orientation* of each triangular domino):

## Challenge
Given the lengths of the three sides of an almost regular hexagon, find the number of distinct triangular domino tilings. The three sides will be always positive integers.
## Alternative description
The second image shows that such a tiling can be viewed as an isometric view of stacked unit cubes. Now let's assign three directions to three axes in 3D:
* `x` = down-right / southeast / SE (blue edges in the first image)
* `y` = down-left / southwest / SW (red edges)
* `z` = up / north / N (yellow edges)
Then the stacked unit cubes can be represented as an `x`-by-`y` 2D array, whose items represent the height of the stack at that position. So the above challenge is equivalent to the following:
>
> Given three positive integers `x`, `y`, and `z`, find the number of `x`-by-`y` arrays whose elements are between 0 and `z` inclusive and all rows and columns are in decreasing order.
>
>
>
It happens that this is one definition of [plane partition](http://mathworld.wolfram.com/PlanePartition.html) in the form of \$ PL(x,y,z) \$, and it has a closed-form formula:
$$
PL(x,y,z) = \prod\_{i=1}^x \prod\_{j=1}^y \prod\_{k=1}^z \frac{i+j+k-1}{i+j+k-2}
$$
## Scoring and winning criterion
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
Note that a submission is valid even if it suffers from integer overflows or floating-point inaccuracies, as long as the underlying algorithm is correct.
## Test cases
```
x,y,z => output
---------------
1,1,1 => 2
1,1,2 => 3
1,2,3 => 10
2,3,1 => 10 (the order of inputs doesn't matter, since it's the same hexagon)
2,3,4 => 490
3,4,2 => 490
3,3,5 => 14112
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 14 bytes
```
×/1+1÷1+∘,1⊥¨⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qn/6O2CQb/D0/XN9Q2PLzdUPtRxwwdw0ddSw@teNS7@X8aUPZRbx9EYVfzofXGj9omAnnBQc5AMsTDM/h/moKhgpGCMVcaiFQwAQA "APL (Dyalog Classic) – Try It Online")
Uses 0 indexing with `⎕IO←0`.
### Explanation:
```
⍳ ⍝ Cartesian product of the ranges from 0 to n-1
1⊥¨ ⍝ Sum of each element (using base 1)
, ⍝ Flattened
∘ ⍝ Composed with
1+1÷1+ ⍝ 1 + 1/(n+1)
×/ ⍝ And reduced by multiplication
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~38~~ 30 bytes
```
{[*] map 1+1/(*+1),[X+] ^<<@_}
```
[Try it online!](https://tio.run/##Jc7RioMwEAXQ581X3KdWm4BG3YUudulnFKxdpI5V0ESSLGwp/XabVOblDFzuzExm/FqmOzYdDlge1a7G1MyQXCbRjstYVCde41KWx9/n0mmDaBwU2RgP9mGbOzrwspy@b8m55Ul1yWv2XKTwg8MPMhaYBeaemcgDZcq81oRMEbmeoE1LBrrDoOY/Z9Fqsmrr/C/OkRGwg7oSBre1CHHbTISe/pubVvG7rQhtxT5lnuvFdcnF5/tOIWX2Ag "Perl 6 – Try It Online")
Based on the formula given in the question
### Explanation:
```
{ } # Anonymous code block
^<<@_ # Map each input to the range 0 to n-1
[X+] # Get the cross product of sums
map , # Map these to
1+1/(*+1) # 1+1/(n+1) = (n+2/n+1)
# Which is the formula compensating for the 0 based range
[*] # And reduce by multiplication
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes
```
Array[1+1/(##-2)&,#,1,1##&]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@9@xqCixMtpQ21BfQ1lZ10hTTUdZx1DHUFlZLVbtf0BRZl5JtLKCrp1CWrRybKyCmoK@g0J1taGOAgjV6ihAmUZQppGOgjGICaKhCiBMExATREPVGoNFTWtr/wMA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
L.«â€˜OÍz>P
```
[Try it online](https://tio.run/##yy9OTMpM/f/fR@/Q6sOLHjWtOT3H/3BvlV3A///RxjomOkaxAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/H71Dqw8vetS05vQc/8O9VXYB/3X@R0cb6gBhrI4CmGEEYRjpGIMYQAoiBWKYgBhACqLGGChiGhsLAA).
**Explanation:**
Uses the derived formula (inspired by *@JoKing*'s answers):
$$PL(x,y,z) = \prod\_{i=1}^x \prod\_{j=1}^y \prod\_{k=1}^z \frac{1}{i+j+k-2}+1$$
```
L # Map each value in the (implicit) input-list to an inner [1,v]-ranged list
.« # (Right-)reduce these lists by:
â # Taking the cartesian product between two lists
€˜ # Then flatten each inner list
O # Sum each inner list
Í # Decrease all by 2
z # Take 1/v for each value
> # Increase all by 1
P # And take the product of that
# (after which the result is output implicitly)
```
[Answer]
# [Haskell](https://www.haskell.org/), 44 bytes
```
foldr(\r k->k+k/(sum r-2))1.mapM(\n->[1..n])
```
[Try it online!](https://tio.run/##BcFNEkAgGADQq3wLixqVobHkBk5QLRqE6UdTXN/nvdNWv4eAbtLo7rAVogt4PvvWd6S@EQofKO1FtHkhOvFZ9UIkQzHaK8EEuVzpgQYcKMkkGw1@qwv2qMjXnH8 "Haskell – Try It Online")
Outputs floats. Thanks to @H.PWiz for 4 bytes using a fold.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
```
Œp§_2İ‘P
```
[Try it online!](https://tio.run/##y0rNyan8///opIJDy@ONjmx41DAj4P/h9kdNayL//4821AHCWB0wbQSmjXSMgTSQBIuDaBMgDSTB8sZAvmksAA "Jelly – Try It Online")
Uses the altered form of the closed form expression. Takes input as a list `[x,y,z]`.
```
Œp Cartesian product of the list.
(Each element, being an integer, is implicitly converted to a range.)
§ Sum the items of each triplet,
_2 subtract 2 from each sum,
İ take the reciprocal of each lowered sum,
‘ increment each reciprocal,
P and return the product of the increments reciprocals.
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~17~~ 15 bytes
```
%/*/'2 1+\:+/!:
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs1LV19JXN1Iw1I6x0tZXtOLiKrGqVomurCuySlOosE7Iz7bWSEhLzMyxrrCutC7SjK3lKok2VABCayO9WCjbyNoYyjZSMLY2NABzgEygIiSOibWJJYQHZAP1IHjGCqbWhiaGhkATFfTzy1KL0nLyywH9wicM)
last test fails because of an overflow
uses a 0-indexed version of the formula:
\$PL(x,y,z)=\prod\_{i=0}^{x-1}\prod\_{j=0}^{y-1}\prod\_{k=0}^{z-1}\frac{i+j+k+2}{i+j+k+1}\$
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 75
Inputs are passed as a comma-separated list.
```
e={1..${1//,/\}+\{1..}}
eval eval echo \\$\[1 *\\\($e-1\\\) /\\\($e-2\\\) ]
```
[Try it online!](https://tio.run/##LYhLDsIwDET3PsUssmghNEoKK8RJMItAU6UfUQkkWEQ5e3ABW/PsN1f/jKWvaqQSTsk2jUrWGG04b3nVnCm8/IwfbnEBs@KzxYaZKxV2Vm4N8zf3tUvJ9I7DHPAIvsOAEdMR3UKQ6aEGrUatJuqWeygWsrTSCR1akkizck8S6Vv5Dx8 "Bash – Try It Online")
The last test fails due to integer overflow.
[Answer]
# JavaScript (ES6), ~~73 65~~ 64 bytes
```
(x,y,z)=>(g=n=>!n||g(n-1)/(s=n%z-~(n/z%y)+n/z/y%x|0)*-~s)(x*y*z)
```
[Try it online!](https://tio.run/##bc1BDoIwFATQvafABcn/2FpacOGi3IUgEI35NdYY2hCuXrtCAmQWs3jJzKP@1rZ5318fTubWhk4HGJhjHnUFvSZdHWkceyAuUYDVlHo@AQmfOjzFEi4dxhwzPlmEIXOZx9AYsubZnp@mhw4ki0FMhEh0lajDVtWsxUYVK2aV@YojLqZ3uZy5vK496uJ7zwt2@c@XUqrwAw "JavaScript (Node.js) – Try It Online")
### Commented
```
(x, y, z) => ( // (x, y, z) = input
g = n => // g is a recursive function taking a counter n
!n || // if n = 0, stop recursion and return 1
g(n - 1) / ( // otherwise, divide the result of a recursive call by:
s = // s defined as the sum of:
n % z // k, 0-indexed: n mod z
- ~(n / z % y) // j, 1-indexed: floor((n / z) mod y) + 1
+ n / z / y % x | 0 // i, 0-indexed: floor((n / z / y) mod x)
) //
* -~s // and multiply by s + 1
)(x * y * z) // initial call to g with n = x * y * z
```
[Answer]
# [J](http://jsoftware.com/), 25 bytes
-4 bytes thanks to Bubbler!
```
[:*/1+1%1+1#.&>[:,@{i.&.>
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYAXEunoKzkE@bv@jrbT0DbUNVYFYWU/NLtpKx6E6U09Nz@6/JpeSnoJ6mq2euoKOQloxV2pyRr5CmpqdgiEIWoNIIyBppGBsDcRAERBpYg3EQHFjINtU4T8A "J – Try It Online")
# [J](http://jsoftware.com/), 29 bytes
```
[:*/[:(1+1%1++/)@>[:,@{<@i."0
```
[Try it online!](https://tio.run/##FYg7CoAwFAT7nGIR/EZi4qd5Uck9UopBbSwsxbPHF5YZlrlieBYFDYKOnprOU2WkyY2UXe1WT617Z3eqTMdaZAplWFSJFh8hPELs23EjFCtMmk3u2T0Gy3BJHi3DfeA/If4 "J – Try It Online")
A [J](http://jsoftware.com/) port of [@JoKing's APL answer](https://codegolf.stackexchange.com/a/196081/75681) (don't forget to upvote it), but twice as long. I'll try to golf it...
[Answer]
# [J](http://jsoftware.com/), 18 bytes
```
*/@,@(1+%)1++/&i./
```
[Try it online!](https://tio.run/##JcrBCoMwEATQ@37FULBWYxMnSQ8NCNKCJ@mhH6Ho/9/jamCHx@zunm8W9YIhoUaHHknztPj@5ym3buzGB03V0Bh336zLjaxDWjKxgqAU/aVHEK8G3RejBDXqPVz9Jb@PPf/A/pz4LmEk/QE "J – Try It Online")
Takes `z` on its left and `x y` on the right.
Uses [modified formula by Peter Taylor](https://codegolf.stackexchange.com/questions/196070/triangular-domino-tiling-of-an-almost-regular-hexagon#comment466589_196089):
$$
\begin{align}
\prod\_{i=1}^x \prod\_{j=1}^y \frac{i+j+z-1}{i+j-1} &= \prod\_{i=1}^x \prod\_{j=1}^y \left(1 + \frac{z}{i+j-1}\right) \\
&= \prod\_{i=0}^{x-1} \prod\_{j=0}^{y-1} \left(1 + \frac{z}{i+j+1}\right)
\end{align}
$$
### How it works
```
*/@,@(1+%)1++/&i./ NB. Left =: z, Right =: x y
/ NB. Reduce over x y...
&i. NB. Apply range (n -> 0..n-1) to each item and
+/ NB. Outer product by addition
1+ NB. Increment each, so that each cell has i+j+1
@(1+%) NB. Compute 1+z/(i+j+1) for each i and j
*/@, NB. Flatten the matrix and compute the product
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~85~~ 75 bytes
```
->x,y,z{w=->t{(0...x*y*z).map{|r|r%x+(r/=x)%y+r/y+t}.reduce &:*};w[2]/w[1]}
```
[Try it online!](https://tio.run/##TcxJDoMgAIXhfU9B0tgoIsjQRdvARYiLDrozMUQDOJydkg5q3u5L3m@Ghw@NDIVyyKNxsrJQ/ZSWGGMHPRwz3N67aTazSVyeGiJdlvjcEJ/3Czb1a3jW4HSFy81qVhGrabWEDjSaorgKHAkBUgF2@Btbjf@MIb4aLT8YaXfeoVhRXL4abdfclKPzFhCUsvAG "Ruby – Try It Online")
[Answer]
# [Icon](https://github.com/gtownsend/icon), ~~81, 78~~ 70 bytes
-8 bytes thanks to Peter Taylor
```
procedure f(x,y,z)
p:=1&p*:=(1+z/(seq()\x+seq()\y-1.))&\u
return p
end
```
[Try it online!](https://tio.run/##Tc69DoMgEADgWZ4CFwOVtkHbxcQnUYZGz4ShSK/Sii9v0Q5yN1y@3E9Od6NZV4tjB71DoAObhRcLJ7aqZWZPVc1kvlzZG16Mt3P@r/4sL5xnrSMIk0NDLQHTR2eeD20YJzQEfAA9/aKegA1p2jRShFSCJMnW3lnELER5MCAe3ng7GBDvlqF7V4rvz/wA "Icon – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~79~~ 62 bytes
Based on @galen-ivanov's [answer](https://codegolf.stackexchange.com/a/196089/32604).
-17 bytes thanks to Jo King and xnor.
```
lambda x,y,z,t=1:[t:=t+t*z/(i%x-~i//x)for i in range(x*y)][-1]
```
[Try it online!](https://tio.run/##VcuxCsMgGATgvU/hUvBPDWJsIQR8kjSDIbUVWiPyD5qhr27tptz0cXc@4Wt3cvQhG3XPb/1ZN00iS@xgqMQ046Twgt3BqT3H/ms5j2D2QCyxjgTtng8auwTL3Isl@2AdUkMFKwE41R4aD0xWLmr2f18rFzV/WfobQP4B "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
NθNηFNFηFθ⊞υ⊕⁺λ⁺κιI÷Π⊕υΠυ
```
[Try it online!](https://tio.run/##TYwxDsMgDEX3nMKjLdGl7ZaxXbJUXIECFaiENIBzfUpRpMbL139fz9qppBcVap3ih8uD56dNuNI4HLtr/bUkwCMkgs7cniuB5OyQBUxRJzvbWKxBGThjENDzLcBTu3GQyceCN5VLe1rufvPGokyLYf0jf5@JmrwP3OVaz3CBaz1t4Qs "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses the 0-indexed version of the given formula.
```
NθNηFNFηFθ
```
Input the three dimensions and loop over the implicit ranges.
```
⊞υ⊕⁺λ⁺κι
```
Take each incremented sum and save it in a list, thus flattening the Cartesian product.
```
I÷Π⊕υΠυ
```
Divide the product of the incremented list by the product of the list and cast to string for implicit print.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
mo rï Ëc rÄ pJ ÄÃ×
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bW8gcu8gy2MgcsQgcEogxMPX&input=W1sxLDIsM10sWzIsMyw0XV0KLW0)
input as array
```
mo rï // cartesian product [0,n)
Ëc // flatten each triplet
rÄ // reduce with initial value of 1 ( -2 +3=>triplets 0 to 1
pJ // raised -1
Ä // +1
Ã× // reduce by multiplication
Implicit output, -m flag to run the program for each input
```
] |
[Question]
[
Recently I posted [a](https://codegolf.stackexchange.com/questions/114578/find-diffy-games) question about Diffy games which has gone unanswered. Thats fine, the question is really hard, but I would like to make an easier question about Diffy games so that we can get the ball rolling.
---
# How Diffy works
*Copied from [Find Diffy Games](https://codegolf.stackexchange.com/questions/114578/find-diffy-games)*
The Diffy game works like as follows: You start with a list of non-negative integers, in this example we will use
```
3 4 5 8
```
Then you take the absolute difference between adjacent numbers
```
(8) 3 4 5 8
5 1 1 3
```
Then you repeat. You repeat until you realize you have entered a loop. And then generally the game starts from the beginning again.
```
3 4 5 8
5 1 1 3
2 4 0 2
0 2 4 2
2 2 2 2
0 0 0 0
0 0 0 0
```
Most games end in a string of all zeros, which is considered to be a lose state, but a rare few games get stuck in larger loops.
---
# Task
Given the starting state of a Diffy game determine whether or not the game eventually reaches a state of all zeros. You should output a Truthy or Falsy value for each of the two states. Which corresponds to which does not matter.
The goal is to minimize the number of bytes in your source.
[Answer]
# Pyth, 6 bytes
```
suaV+e
```
[Test suite](https://pyth.herokuapp.com/?code=suaV%2Be&test_suite=1&test_suite_input=3%2C+4%2C+5%2C+8%0A42%2C+42%2C+41&debug=0)
This program is very suave. 0 (falsy) means all zeroes, anything else (truthy) means not all zeroes.
How it works:
```
suaV+e
suaV+eGGGQ Variable introduction.
u Q Apply the following function repeatedly to its previous result,
starting with the input. Stop when a value occurs which has
occurred before.
aV Take the absolute differences between elements at the same indices of
G The previous list and
+eGG The previous list with its last element prepended.
s The repeated value is returned. Sum its entries. This is zero (falsy)
if and only if the entries are all zero.
```
[Answer]
# Mathematica, 52 bytes
```
1>Max@Nest[Abs[#-RotateLeft@#]&,#,Max[1+#]^Tr[1^#]]&
```
Pure function taking a list of nonnegative integers as input and returning `True` or `False`.
`Abs[#-RotateLeft@#]&` is a function that executes one round of the diffy game. (Technically it should be `RotateRight`, but the ultimate answer is unaffected, and hey, free byte.) So `Nest[...,#,R]` executes `R` rounds of the diffy game, and then `1>Max@` detects whether the result is all zeros.
How do we know how many diffy-game rounds `R` to do? If `m` is the largest value in the input, notice that we will never produce an integer larger than `m` no matter how many rounds we do. The total number of lists of length `l` of nonnegative integers all bounded by `m` is `(m+1)^l`. So if we carry out `(m+1)^l` rounds of the diffy game, we are guaranteed to have seen some list twice by then, and thus will be in the periodic part of the game. In particular, the game ends in all zeros if and only if the result of `(m+1)^l` rounds of the game is the all-zeros list. That expression is what `Max[1+#]^Tr[1^#]` computes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṁ‘*L
ṙ1ạ
ÇÑ¡Ṁ
```
Outputs 0 (falsey) if the all zero state will be reached, otherwise a truthy value (a positive integer) is returned.
**[Try it online!](https://tio.run/nexus/jelly#@/9wZ8OjhhlaPlwPd840fLhrIdfh9sMTDy0ECv///z/aUMdQxwAEYwE "Jelly – TIO Nexus")**
Uses the observation first [made by Greg Martin](https://codegolf.stackexchange.com/a/116273/53748) that the numbers within the array may never leave the domain **[0,m]** where **m** is the maximal element in the input, so performing **(m+1)l** rounds where **l** is the input's length will suffice.
### How?
```
Ṁ‘*L - Link 1, number of rounds to perform: list a
Ṁ - maximum of a
‘ - incremented
L - length of a
* - exponentiate
ṙ1ạ - Link 2, perform a round: list x
ṙ1 - rotate x left by 1
ạ - absolute difference (vectorises) with x
ÇÑ¡Ṁ - Main link: list a
¡ - repeat:
Ç - the last link (2) as a monad
Ñ - the next link (1) as a monad times
Ṁ - return the maximum of the resulting list
```
[Answer]
# PHP, 144 Bytes
print 0 for all zero and any positive integer value for true
```
<?for($r[]=$_GET[0];!$t;){$e=end($r);$e[]=$e[$c=0];for($n=[];++$c<count($e);)$n[]=abs($e[$c-1]-$e[$c]);$t=in_array($n,$r);$r[]=$n;}echo max($n);
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/f8507275eac7f077ec8bf9fb40f918d0d8ebd6f9)
Expanded
```
for($r[]=$_GET;!$t;){
$e=end($r); # copy last array
$e[]=$e[$c=0]; # add the first item as last item
for($n=[];++$c<count($e);)$n[]=abs($e[$c-1]-$e[$c]); # make new array
$t=in_array($n,$r); # is new array in result array
$r[]=$n; # add the new array
}
echo max($n); # Output max of last array
```
[Answer]
## R (3.3.1), 87 bytes
Returns zero for a game ending in all zeros, and a positive number otherwise.
```
z=scan();sum(Reduce(function(x,y)abs(diff(c(x,x[1]))),rep(list(z),max(z+1)^length(z))))
```
leverages the same fact by Greg Martin and uses the builtin diff to do the diffy-ing
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ṙ1ạµÐLẸ
```
[Try it online!](https://tio.run/##y0rNyan8///hzpmGD3ctPLT18ASfh7t2/D/c/qhpzf//0cY6JjqmOhaxOgrRhjqGOgYgGAsA "Jelly – Try It Online")
Outputs `0` (falsey) if it is degenerate, and `1` (truthy) if not
## How it works
```
ṙ1ạµÐLẸ - Main link. Takes an array A on the left
µ - Group the links to the left into a monad f(A):
ṙ1 - Rotate A one step to the left
ạ - Take the absolute differences with A
ÐL - Repeatedly apply f(A) on A until reaching a fixed point
Ẹ - Yield 0 if all 0s, else 1
```
[Answer]
# [Röda](https://github.com/fergusq/roda), 80 bytes
```
f l...{x=[{peek a;[_];[a]}()|slide 2|abs _-_];[sum(x)=0]if[x in l]else{x|f*l+x}}
```
[Try it online!](https://tio.run/nexus/roda#XYlNCsIwFAbXeopv2WoM9Q@E0pOER4j4AsG0FKMQSHL2GLfCzGamWngpZYqTSivzE2ZUmkZlqHR9Dt49GKds7gH68OvhM3exnwZyVkW4BZ7YB04x253fx1LqbFpN2406C1wErgI3QoZtri@3vKHbOwo0hv9R6hc "Röda – TIO Nexus")
Ungolfed:
```
function f(l...) { /* function f, variadic arguments */
x := [ /* x is a list of */
{ /* duplicate the first element of the stream to the last position */
peek a /* read the first element of the stream */
[_] /* pull all values and push them */
[a] /* push a */
}() |
slide(2) | /* duplicate every element except first and last */
abs(_-_) /* calculate the difference of every pair */
]
/* If we have already encountered x */
if [ x in l ] do
return sum(x) = 0 /* Check if x contains only zeroes */
else
x | f(*l+x) /* Call f again, with x appended to l */
done
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
Returns **1** if it ends in zeroes and **0** otherwise.
```
Z¹g*F¤¸ì¥Ä}_P
```
[Try it online!](https://tio.run/nexus/05ab1e#@x91aGe6ltuhJYd2HF5zaOnhltr4gP//o411FEx0FEx1FCxiAQ "05AB1E – TIO Nexus")
**Explanation**
Uses the upper bound of rounds: `max(input)*len(input)` explained by *xnor* in the comment section.
```
Z # get max(input)
¹g # get length of input
* # multiply
F # that many times do:
¤ # get the last value of the current list (originally input)
¸ # wrap it
ì # prepend to the list
¥ # calculate deltas
Ä # calculate absolute values
} # end loop
_ # negate each (turns 0 into 1 and everything else to 0)
P # calculate product
```
[Answer]
## J, 22 bytes
Returns `0` (which is effectively `false` in J) for a degenerate game ending in all zeros. Returns `1` (`true`) if the nth iteration contains a non-zero number, where n is equal to the largest integer in the original sequence multiplied by the length of the list. See [Greg Martin's answer](https://codegolf.stackexchange.com/a/116273/15640) explaining why this is true.
```
*>./|&(-1&|.)^:(#*>./)
```
Translation:
* What is the sign `*`
* of the greatest value `>./`
* when you iterate the following as many times as `^:( )`
* the length of the list `#` multiplied by `*` the greatest value in the list `>./`:
+ take the absolute value `|&` of
+ the difference between the list `(- )` and
+ the list rotated by one `1&|.`
Examples:
```
*>./|&(-1&|.)^:(#*>./) 1 1 0
1
*>./|&(-1&|.)^:(#*>./) 42 42 41
1
*>./|&(-1&|.)^:(#*>./) 3 4 5 8
0
*>./|&(-1&|.)^:(#*>./) 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1
0
```
[Answer]
# JavaScript (ES6), ~~95 92~~ 90 bytes
```
f=(a,b=(Math.max(...a)+1)**(c=a.length))=>b?f(a.map((v,i)=>v-a[++i%c]),b-1):a.every(v=>!v)
```
# Explanation
Recursive function that calls itself as long as the counter (which starts at the maximum value in the list plus one to the power of the length of the list [`= (max + 1)**length`]) is not zero. On every call, the counter is decremented, and when it hits zero, all elements in the list are checked against zero. If they all equal zero, the program returns `true`, and `false` otherwise.
[Answer]
# PHP, 123 115
```
for($a=$_GET,$b=[];!in_array($a,$b);){$b[]=$c=$a;$c[]=$c[0];foreach($a as$d=>&$e)$e=abs($e-$c[$d+1]);}echo!max($a);
```
taking input via HTTP get e.g. `?3&4&5&8` saves a few bytes.
Prints 1 if it reaches all zeros or nothing otherwise.
---
```
for($e=$argv,$r=[];!in_array($e,$r);$q=$e[0]){$e[0]=end($e);$r[]=$e;foreach($e as$k=>&$q)$q=abs($q-$e[$k+1]);}echo!max($e);
```
takes the list of arguments via command line. I've got the feeling this can be golfed even further (looking at @Titus).
[Answer]
# Python 3.6, 101 bytes
```
def f(t):
x={}
while x.get(t,1):x[t]=0;t=(*(abs(a-b)for a,b in zip(t,t[1:]+t[:1])),)
return any(t)
```
Takes a tuple of numbers and returns False if it ends in zeros and True if it loops.
[Answer]
## JavaScript (ES6), ~~84~~ 83 bytes
Returns `true` for a game ending in all zeros, `false` otherwise.
```
f=(a,k=a)=>k[b=a.map((n,i)=>Math.abs(n-a[(i||a.length)-1]))]?!+b.join``:f(k[b]=b,k)
```
### Test
```
f=(a,k=a)=>k[b=a.map((n,i)=>Math.abs(n-a[(i||a.length)-1]))]?!+b.join``:f(k[b]=b,k)
console.log(f([3,4,5,8])); // ends in zeros
console.log(f([1,0,1])); // does not end in zeros
console.log(f([7])); // ends in zeros
```
] |
[Question]
[
Sometimes to fall asleep, I'll count as high as I can, whilst skipping numbers that are not [square-free](https://en.wikipedia.org/wiki/Square-free_integer). I get a little thrill when I get to skip over several numbers in a row - for example, `48,49,50` are all NOT square-free (48 is divisible by 2^2, 49 by 7^2, and 50 by 5^2).
This led me to wondering about the earliest example of adjacent numbers divisible by some arbitrary sequence of divisors.
## Input
Input is an ordered list `a = [a_0, a_1, ...]` of strictly positive integers containing at least 1 element.
## Output
Output is the smallest positive integer `n` with the property that `a_0` divides `n`, `a_1` divides `n+1`, and more generally `a_k` divides `n+k`. If no such `n` exists, the function/program's behavior is not defined.
## Test Cases
```
[15] -> 15
[3,4,5] -> 3
[5,4,3] -> 55
[2,3,5,7] -> 158
[4,9,25,49] -> 29348
[11,7,5,3,2] -> 1518
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest result (per language) wins bragging rights. The usual loopholes are excluded.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 51 bytes
```
Mod[ChineseRemainder[1-Range@Length@#,#],LCM@@#,1]&
```
[Try it online!](https://tio.run/##FcmxCoMwGEXhV/kx4HSlxCji0BJwVSiuIUOoUTOYgs0mPnuabN/hHCbs9jDBfUxc6Ulx@i5q2J23Pzun4fxiT8Wr2fjNytH6LeySgWmMwySTuC7j@3Q@KAYqqHpRAVoV05pKeki6LoEG7Q262gSRUUOgRZfZoEedRp@Dc3RpCNS5xH3HPw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
VδΛ¦⁰ṫN
```
[Try it online!](https://tio.run/##yygtzv6vkKtR/KipsUjz0Lb/Yee2nJt9aNmjxg0Pd672@///f7SxjomOaSxXtCmQNgbSRjrGOqY65kCWiY6ljhFQ2BLINjTUMQcKG@sYxQIA "Husk – Try It Online")
## Explanation
```
VδΛ¦⁰ṫN Input is a list x.
N The list [1,2,3...
ṫ Tails: [[1,2,3...],[2,3,4...],[3,4,5...]...
V Index of first tail y satisfying this:
Λ Every element
⁰ of x
¦ divides
δ the corresponding element of y.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
```
`Gf@q+G\a}@
```
[Try it online!](https://tio.run/##y00syfn/P8E9zaFQ2z0msdbh//9oUx0THeNYAA "MATL – Try It Online")
```
` % Do ....
Gf % Convert input to [1,2,...,]
@q+ % Add current iteration index minus one, to get [n, n+1, ....]
G\ % Elementwise mod([n,n+1,...],[a_0,a_1,...])
a % ...while any of the modular remainders is nonzero.
} % Finally:
@ % Output the iteration index.
```
Not exactly optimized for speed... the largest testcase takes a full minute using MATL, and approximately 0.03s on MATLAB. There is a small possibility MATL has a bit more overhead.
[Answer]
# JavaScript, ~~42~~ 40 bytes
Will throw a recursion error if there is no solution (or the solution is too big).
```
a=>(g=y=>a.some(x=>y++%x)?g(++n):n)(n=1)
```
Saved 2 bytes with a pointer from [Rick Hitchcock](https://codegolf.stackexchange.com/users/42260/rick-hitchcock)
---
## Try it
Enter a comma separated list of numbers.
```
o.innerText=(f=
a=>(g=y=>a.some(x=>y++%x)?g(++n):n)(n=1)
)(i.value=[5,4,3]);oninput=_=>o.innerText=f(i.value.split`,`.map(eval))
```
```
<input id=i><pre id=o>
```
[Answer]
# [Python 3](https://docs.python.org/3/), 62 bytes
```
f=lambda x,n=1:all(j%k<1for j,k in enumerate(x,n))or-~f(x,n+1)
```
[Try it online!](https://tio.run/##VY1PS8MwGMbv/RSvB1nTvT2kWTdWnCCCUNQdZi8yxqgzxWxtUpIUOsb86jWpB/H2e/7xtGf7pSQbKq0a0NyoTh84iKZV2kIUjLY5mz8nMNzqWjTChpuX/DUv9m/Fw@Mzwij3@fopX@fFO8I/Sci444dOG6Hk7z6JIkYhBkqGalWXzcdnCT3KFc3Kug6Pt6c7WikNRzyBkMBl13BdWh66DiFKx9@Vx6mfu1rvS9vFDmHLcIaph9QB85AgwxTHcIZLTFyw9IJSXLiAYbLLAoBWC2nDanLpb0xG51eI7@HiXkiWXidk@AE "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
Xµā<N+sÖP
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/4tDWI402ftrFh6cF/P8fbWioY65jqmOsYxQLAA "05AB1E – Try It Online")
**Explanation**
```
Xµ # loop until counter equals 1
ā # push range [1 ... len(input)]
< # decrement
N+ # add current iteration index N (starts at 1)
sÖ # elementwise evenly divisible by
P # product
# if true, increase counter
# output N
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~45~~ 44 bytes
```
f a=[n|n<-[1..],1>sum(zipWith mod[n..]a)]!!0
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00h0TY6rybPRjfaUE8vVsfQrrg0V6MqsyA8syRDITc/JToPKJyoGauoaPA/NzEzz7agKDOvRCUt2lTHRMc49j8A "Haskell – Try It Online")
*Edit: -1 byte thanks to nimi!*
[Answer]
# [Clean](https://clean.cs.ru.nl), 61 bytes
```
import StdEnv
$l=hd[n\\n<-[1..]|and[i/e*e==i\\i<-[n..]&e<-l]]
```
[Try it online!](https://tio.run/##DcuxCsIwEADQ3a/IUBwkqSh1KDSbHQS3jkmGI4l6kFyljYLgt3tmffB8ikCc5/BKUWRAYszPeSliKmGk96ZJ@hEMWUuDMoe2dV@gYHAfd1FrtBYrU@VtHFRyjqcCNWvRCNPJXh5Psusd//wtwX1ldbny@UOQ0a9/ "Clean – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
f!s.e%+kTbQ
```
[Try it online!](https://tio.run/##K6gsyfj/P02xWC9VVTs7JCnw//9oEx1LHSNTHRPLWAA "Pyth – Try It Online")
---
```
f!s.e%+kTbQ Full program - inputs list from stdin and outputs to stdout
f First number T such that
.e Q The enumerated mapping over the Input Q
+kT by the function (elem_value+T)
% b mod (elem_index)
!s has a false sum, i.e. has all elements 0
```
[Answer]
# [J](http://jsoftware.com/), 23 bytes
```
[:I.0=]+/@:|"1#]\[:i.*/
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o6089QxsY7X1HaxqlAyVY2OirTL1tPT/a3IpcKUmZ@QrpCkYK5gomMI4pkCOMYxjBJQzVTCHcU0ULBWMgAosYQKGhgrmQAXGCkb/AQ "J – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 51 bytes
```
function(l){while(any((F+1:sum(l|1))%%l))F=F+1
F+1}
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNHs7o8IzMnVSMxr1JDw03b0Kq4NFcjp8ZQU1NVNUdT080WKMYFxLX/0zSSNUx0LHWMTHVMLDU1/wMA "R – Try It Online")
The use of `any` throws `k` warnings about implicit conversion to `logical`, where `k` is the return value.
[Answer]
# [Perl 6](http://perl6.org/), 34 bytes
```
->\a{first {all ($_..*)Z%%a},^∞}
```
[Try it online!](https://tio.run/##FclRCoMgAIfxq/wJGzVakOYiVh5kROJDQmA0bC8hvu8UO9wu4vTt9/G9FmvuYTtx0RjDTUzK6dUebzhlDAoi6/paPvNc@Wr@fb4@HOpERiRGAadBpM@gd4uBoQUXFQYewRIoGDi6xBY9aBx9iqZBFwcDFY/wBw "Perl 6 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~24 23~~ 22 bytes
```
{∨/×⍺|⍵+⍳⍴⍺:⍺∇⍵+1⋄⍵}∘1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OAZPWjjhX6h6c/6t1V86h3q/aj3s2POhcBeVZA/KijHSRm@Ki7BUjXPuqYYfj/f5qCsYKJgilXmoIpkDYG0kZAEVMFcyDLRMFSwQgobAlkGxoqmAOFjRWMAA "APL (Dyalog Unicode) – Try It Online")
Technically, this is a tacit function. I had to make it so since the only input allowed is the list of integers. Uses `⎕IO←0` (0-indexing)
It's worth noting that the function times out if `n` doesn't exist.
Thanks to @ngn and @H.PWiz for 1 byte each.
### How?
```
{∨/×⍺|⍵+⍳≢⍺:⍺∇⍵+1⋄⍵}∘1 ⍝ Main function. ⍺=input; ⍵=1.
{ }∘1 ⍝ Using 1 as right argument and input as left argument:
: ⍝ If
⍳≢⍺ ⍝ The range [0..length(⍺)]
⍵+ ⍝ +⍵ (this generates the vector ⍵+0, ⍵+1,..., ⍵+length(⍺))
⍺| ⍝ Modulo ⍺
× ⍝ Signum; returns 1 for positive integers, ¯1 for negative and 0 for 0.
∨/ ⍝ Logical OR reduction. Yields falsy iff the elements of the previous vector are all falsy.
⍺∇⍵+1 ⍝ Call the function recursively with ⍵+1.
⋄⍵ ⍝ Else return ⍵.
```
[Answer]
# [Perl 5](https://www.perl.org/), 49 + 2 (`-pa`) = 51 bytes
```
$i=!++$\;($\+$i)%$_&&last,$i++for@F;$i<@F&&redo}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18l01ZRW1slxlpDJUZbJVNTVSVeTS0nsbhERyVTWzstv8jBzVol08bBTU2tKDUlv7b6/38TBUsFI1MFE8t/@QUlmfl5xf91fU31DAwN/usWJAIA "Perl 5 – Try It Online")
[Answer]
# Japt, 10 bytes
Will eventually output `undefined` if no solution exists, if it doesn't crash your browser first.
```
@e_X°vZÃ}a
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=QGVfWLB2WsN9YQ==&input=WzUsNCwzXQ==)
---
## Explanation
```
:Implicit input of array U
@ }a :Loop and output the first integer X that returns true.
e_ Ã :For every element Z in U
X° :X, postfix increcemnted
vZ :Is it divisible by Z?
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 48 bytes
```
->l{1+(1..1/0.0).find{|x|l.all?{|y|(x+=1)%y<1}}}
```
[Try it online!](https://tio.run/##FclBCsIwEEDRfU/RjdDScewkDaVg9SAhi4oEhFGKIDRkcvaY7N7nf3@PkP2azzeONHSESJcRxx796/OMcgjjxnyPEqQ7hpX6U7hSSilbq2EC46C1pkBXKNBgYK6cYAFVxlKDCOYyNCjn8L3tUViavbUM3rJzTcp/ "Ruby – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 80 bytes
```
def f(l,n=1):
while n:
n+=1
if all((n+i)%v<1for i,v in enumerate(l)):return n
```
[Try it online!](https://tio.run/##FY7BCoQgFEXX@RVvM6D0NmoSSX1JtAhGSXBeIdYwX@/o7lzOXZzrl4@TVClv58HziLRIYRl8jxAdkGUd9YtkXfCwx8g59UG8nln6M0HABwKBo/vj0p4dj0LY5PKdCKi0R25@1Tig2RBWU0E3UKjR4NhwwAlVFVMbUuJYhUa11Qa4UqBcq7Iofw "Python 2 – Try It Online")
[Answer]
# [Standard ML (MLton)](http://www.mlton.org/), 96 bytes
```
open List;fun$n% =if all hd(tabulate(length%,fn i=>[1>(n+i)mod nth(%,i)]))then n else$(n+1)%;$1;
```
[Try it online!](https://tio.run/##PYzBasMwEETv@oo92CClm4Isi8QI@x7orUdhiktkWyCvQ73J77tKKL3Nm3nMtqTjknilfV9vgeAjbuzGOxVUQhtHGFKC@Sp5@L6ngYNMgSaeSxwJYtt53Ul6i2pZr0A8yxKj6pXiOT8RhLSFIu9ala7Qbn8MCSZoIbITz/yV8@0nEoO8EL/z@smZJpAT@AoNWjz1CpQT8iC8wRptD8cOjPA2g3mBteLffbK2Z@FrbLDKTvOqqsbUudQaT1kzWP2J@iwOav8F "Standard ML (MLton) – Try It Online")
### Ungolfed:
```
open List
fun f n l =
if all (fn x=>x)
(tabulate ( length l
, fn i => (n+i) mod nth(l,i) = 0))
then n
else f (n+1) l
val g = f 1
```
[Try it online!](https://tio.run/##TY47b8MwDIR3/YobpZQJKitC4sHeC3TraASFi/oFyHRQM0X@vcs4QdubeMePj3lM2zHJxMsynRvG6zCLaS@MFoyEAgaqoUWdEmzLuBbl1a3hQ1bqj0uqpYFFariTHul//08EnR9QlLD8NDiM0ydYeptITYFnd98rvf7B98NNmht9RXnvdO13ndAp2sIvt/pd6/PXwAL7wrKT6U3UdbAdqowCRTqcHJyxG1MF2lM8YVsimCqqCauJ0fyiN@/j0VR7yilTJl@jLA97Db2ng2KBsgfoj2bjlh8 "Standard ML (MLton) – Try It Online") Starting with `n=1`, the function `f` increments `n` until the `all`-condition is fulfilled, in which case `n` is returned.
`tabulate(m,g)` with some integer `m` and function `g` builds the list `[g 0, g 1, ..., g m]`. In our condition `tabulate` is called with the length of the input list `l` and a function which checks whether the `i`th element of `l` divides `n+i`. This yields a list of booleans, so `all` with the identity function `fn x=>x` checks whether all elements are true.
I found a nice golfing trick to shorten the identity function in this case by four bytes: Instead of the lambda `(fn x=>x)`, the build-in function `hd` is used, which returns the first element of a list, and the resulting bools in `tabulate` are wrapped in `[` and `]` to create singleton lists.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~65~~ 62 bytes
```
for(){$o=1;$i=++$j;$args[0]|%{$o*=!($i++%$_)};if($o){$j;exit}}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Py2/SEOzWiXf1tBaJdNWW1sly1olsSi9ONogtkYVKK5lq6ihkqmtraoSr1lrnZmmoZIPVJ5lnVqRWVJb@///fwcNQ0Mdcx1THWMdI00A "PowerShell – Try It Online")
PowerShell doesn't have the equivalent of an `any` or `some` or the like, so we need a slightly different approach.
This takes input `$args[0]` as an array, then enters an infinite `for` loop. Each iteration we set `$o` to be `1` (explained later), and set `$i` to be `++$j`. The incrementing `$j` keeps tabs on what the first number of the proposed solution is, while the `$i` will increment over the rest of the proposed solution.
We then send each element of the input `$args[0]` into a `ForEach-Object` loop. Inside the inner loop, we Boolean-multiply into `$o` the result of a calculation. This will make it so that if the calculation fails for a value, the `$o` will turn to `0`. The calculation is `!($i++%$_)`, or the Boolean-not of the modulo operation. Since any nonzero value is truthy in PowerShell, this turns any remainders into a falsey value, thus turning `$o` into `0`.
Outside the inner loop, `if` `$o` is nonzero, we've found an incrementing solution that works, so we output `$j` and `exit`.
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 108 bytes
```
(load library
(d ?(q((L N)(i L(i(mod N(h L))0(?(t L)(inc N)))1
(d S(q((L N)(i(? L N)N(S L(inc N
(q((L)(S L 1
```
The last line is an unnamed lambda function that takes a list and returns an integer. [Try it online!](https://tio.run/##RY07DoNADAX7nOKVz12WDaLkAoiGE2yyQrHEPzScfmOnSfVG1ox86nJN@tlK4bSmjEmfRzquGzNa7mSHXqjoqJzXjJ5vdCJ3tjwNqMvLBJHgwfAP2MKh5@CpSy6MP0H8iFA4pw0juIMMtYARD/jWttG2QkSNxigENIYRlf2S8gU "tinylisp – Try It Online")
### Ungolfed
```
(load library)
(comment Function to check a candidate n)
(def sequentially-divisible?
(lambda (divisors start-num)
(if divisors
(if (divides? (head divisors) start-num)
(sequentially-divisible? (tail divisors) (inc start-num))
0)
1)))
(comment Function to check successive candidates for n until one works)
(def search
(lambda (divisors start-num)
(if (sequentially-divisible? divisors start-num)
start-num
(search divisors (inc start-num)))))
(comment Solution function: search for candidates for n starting from 1)
(def f
(lambda (divisors)
(search divisors 1)))
```
[Answer]
# [Julia 0.6](http://julialang.org/), 79 bytes
```
f(s,l=length(s),n=s[])=(while !all(mod.(collect(0:l-1).+n,s).==0);n+=s[];end;n)
```
[Try it online!](https://tio.run/##XctBDoIwEIXhvafQ3UwYG0pBgqQnISwIFMGMg7EYj1/rznT7vf/d37wOlxBm8MSWndz2BTySWN/1aOGzrOyOp4EZHtukYNyY3bhDfuWzRpUJeVTW5thK9ru0TqZWMDxfq@wsMEOnqx7x8AeGSkqtimYSK8hQRXWiJTVUxLxJXGuqY26oiEP4Ag "Julia 0.6 – Try It Online")
Inputs without valid solutiosn will cause infinite looping... :)
[Answer]
# Python 2, 78 bytes
```
def f(a,c=0):
while [j for i,j in enumerate(a) if(c+i)%j<1]!=a:c+=1
return c
```
EDIT: -26 thanks to @Chas Brown
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~47 46 43~~ 42 bytes
```
->a{(1..).find{|i|a.all?{|v|i%v<1&&i+=1}}}
```
[Try it online!](https://tio.run/##XcxLCsIwFIXhuasoFYviNXBzE2rA6kJqBxENBIoU@wBJsvYYigPr@PvPeY23dzTVNR7O2iHrh0fHjH3enbdeM922F@cnbzfTCYvC7isMIcRuHPosXztT1wQCZNOEbEu7fPUDMgHNIOVSOBBIKGdDeVyiAAU8bdXMXJH4CxChTHMC/j3AFMQP "Ruby – Try It Online")
NB: the `(1..)` syntax is only supported in ruby 2.6, for the moment TIO only supports 2.5 so the link is to an older version (43 bytes).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
1Ḷ+$ọ¥Ạ¥1#
```
[Try it online!](https://tio.run/##ASUA2v9qZWxsef//MeG4tisk4buNwqXhuqDCpTEj////WzUsIDQsIDNd "Jelly – Try It Online")
[Answer]
# APL NARS, 140 bytes, 70 chars
```
r←f w;i;k
i←r←1⊃,w⋄k←¯1+⍴w⋄→0×⍳k=0
A:→0×⍳0=+/(1↓w)∣(k⍴r)+⍳k⋄r+←i⋄→A
```
test
```
f 15
15
f 3 4 5
3
f 5 4 3
55
f 2 3 5 7
158
f 4 9 25 49
29348
f 11 7 5 3 2
1518
```
[Answer]
# Java 8, ~~82~~ 75 bytes
```
a->{for(int r=1,i,f;;r++){i=f=0;for(int b:a)f+=(r+i++)%b;if(f<1)return r;}}
```
**Explanation:**
[Try it online.](https://tio.run/##lY7BbsIwEETvfMVeKtnKEpGECFGT/kG5cEQcnGAj0@BEjkNVRf72dAn0nkrrlbwzozdXeZfLplX2ev4aq1p2HXxKY4cFgLFeOS0rBfvHdzpAxWgfTyC5oFugR9N56U0Fe7BQwCiXH4Nu3MMIrkjQoBbCRREfTKGLlfjTynfJdVQwFxkS30phNNO7hDvle2fBiRBG8QS0fVkT4MW5N@YMN2rJDt4ZezmeJH82PPx0Xt3ipvdxS4qvLbNxxaz6hqn2kOSBT81neDNc4z/sOdmz@fYUM8xxMz@wxi2mBNnOjyQJbgiSYfrKhEUYfwE)
```
a->{ // Method with integer-array parameter and integer return-type
for(int r=1, // Return-integer, starting at 1
i, // Index-integer
f; // Flag-integer
;r++){ // Loop indefinitely, increasing `r` by 1 after every iteration
i=f=0; // Reset both `i` and `f` to 0
for(int b:a) // Inner loop over the input-array
f+=(r+i++)%b; // Increase the flag-integer by `r+i` modulo the current item
if(f<1) // If the flag-integer is still 0 at the end of the inner loop
return r;}} // Return `r` as result
```
] |
[Question]
[
It is trivially possible to create a [bijective](https://en.wikipedia.org/wiki/Bijection) function from \$\mathbb{Z}\$ (the set of all integers) to \$\mathbb{Z}\$ (e.g. the identity function).
It is also possible to create a bijective function from \$\mathbb{Z}\$ to \$\mathbb{Z}^2\$ (the set of all pairs of 2 integers; the [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) of \$\mathbb{Z}\$ and \$\mathbb{Z}\$). For example, we could take the lattice representing integer points on a 2D plane, draw a spiral from 0 outwards, and then encode pairs of integers as the distance along the spiral when it intersects that point.
[](https://i.stack.imgur.com/Rtdxw.gif)
(A function which does this with natural numbers is known as a [pairing function](https://en.wikipedia.org/wiki/Pairing_function).)
In fact, there exists a family of these bijective functions:
$$f\_k(x) : \mathbb{Z} \to \mathbb{Z}^k$$
## The Challenge
Define a family of functions \$f\_k(x)\$ (where \$k\$ is a positive integer) with the property that \$f\_k(x)\$ bijectively maps integers to \$k\$-tuples of integers.
Your submission should, given inputs \$k\$ and \$x\$, return \$f\_k(x)\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer (measured in bytes) wins.
## Specifications
* Any family \$f\_k(x)\$ can be used as long as it fulfills the above criteria.
* You are encouraged to add a description of how your function family works, as well as a snippet to compute the inverse of the function (this is not included in your byte count).
* It is fine if the inverse function is uncomputable, as long as you can prove it the function is bijective.
* You can use any suitable representation for signed integers and lists of signed integers for your language, but you must allow inputs to your function to be unbounded.
* You only need to support values of \$k\$ up to 127.
[Answer]
## [Alice](https://github.com/m-ender/alice), ~~14~~ 12 bytes
```
/O
\i@/t&Yd&
```
[Try it online!](https://tio.run/##S8zJTE79/1/fnysm00G/RC0yRe3/f0MjYy5TAA "Alice – Try It Online")
Inverse function (not golfed):
```
/o Q
\i@/~~\ /dt&Z
```
[Try it online!](https://tio.run/##S8zJTE79/18/XwEEArliMh306@piFPRTStSi/v834AJBXWMuYwA "Alice – Try It Online")
### Explanation
Alice has a built-in bijection between **ℤ** and **ℤ2**, which can be computed with `Y` (unpack) and its inverse `Z` (pack). Here is an excerpt from the docs explaining the bijection:
>
> The details of the bijection are likely irrelevant for most use cases. The main point is that it lets the user encode two integers in one and extract the two integers again later on. By applying the pack command repeatedly, entire lists or trees of integers can be stored in a single number (although not in a particularly memory-efficient way). The mapping computed by the pack operation is a bijective function **ℤ2 → ℤ** (i.e. a one-to-one mapping). First, the integers **{..., -2, -1, 0, 1, 2, ...}** are mapped to the natural numbers (including zero) like **{..., 3, 1, 0, 2, 4, ...}** (in other words, negative integers are mapped to odd naturals and non-negative integers are mapped to even naturals). The two natural numbers are then mapped to one via the [Cantor pairing function](https://en.wikipedia.org/wiki/Pairing_function), which writes the naturals along the diagonals of the first quadrant of the integer grid. Specifically, **{(0,0), (1,0), (0,1), (2,0), (1,1), (0,2), (3,0), ...}** are mapped to **{0, 1, 2, 3, 4, 5, 6, ...}**. The resulting natural number is then mapped back to the integers using the inverse of the earlier bijection. The unpack command computes exactly the inverse of this mapping.
>
>
>
As alluded to above, we can use this unpack operation to map **ℤ** to **ℤk** as well. After applying it to the initial integer, we can unpack the second integer of the result again, which gives us a list of three integers. So **k-1** applications of `Y` give us **k** integers as the result.
We can compute the inverse by packing the list up with `Z` from the end.
So the program itself has this structure:
```
/O
\i@/...d&
```
This is just a basic template for a program which reads a variable number of decimal integers as input and prints a variable number as the result. So the actual code is really just:
```
t Decrement k.
& Repeat the next command k-1 times.
Y Unpack.
```
One thing I'd like to address is "why would Alice have a built-in for a **ℤ → ℤ2** bijection, isn't that golfing language territory"? As with most of Alice's weirder built-ins, the main reason is Alice's design principle that every command has two meanings, one for Cardinal (integer) mode and one for Ordinal (string) mode, and these two meanings should be *somehow* related to give Cardinal and Ordinal mode the feeling that they are mirror universes where things are sort of the same but also different. And quite often I had a command for one of the two modes I wanted to add, and then had to figure out what other command to pair it with.
In the case of `Y` and `Z` Ordinal mode came first: I wanted to have a function to interleave two strings (zip) and separate them again (unzip). The quality of this that I wanted to capture in Cardinal mode was to form one integer from two and be able to extract the two integers again later, which makes such a bijection the natural choice.
I also figured that this would actually be very useful outside of golfing, because it lets you store an entire list or even tree of integers in a single unit of memory (stack element, tape cell or grid cell).
[Answer]
# Python, ~~96~~ 93 bytes
```
def f(k,x):
c=[0]*k;i=0
while x:v=(x+1)%3-1;x=x//3+(v<0);c[i%k]+=v*3**(i//k);i+=1
return c
```
This works in principle by converting the input number `x` to [balanced ternary](https://en.wikipedia.org/wiki/Balanced_ternary), and then distributing the trits (ternary digits) least-significant first between the different coordinates in a round-robin fashion. So for `k=2` for example, every even positioned trit would contribute to the `x` coordinate, and every odd positioned trit would contribute to the `y` coordinate. For `k=3` you'd have the first, fourth and seventh trits (etc...) contributing to `x`, while the second, fifth and eighth contribute to `y`, and the third, sixth and ninth contribute to `z`.
For example, with `k=2`, lets look at `x=35`. In balanced ternary, `35` is `110T` (using the Wikipedia article's notation where `T` represents a `-1` digit). Dividing the trits up gives `1T` (the first and third trits, counting from the right) for the `x` coordinate and `10` (second and fourth trits) for the `y` coordinate. Converting each coordinate back to decimal, we get `2, 3`.
Of course, I'm not actually converting the whole number to balanced ternary at once in the golfed code. I'm just computing one trit at a time (in the `v` variable), and adding its value directly to the appropriate coordinate.
Here's an ungolfed inverse function that takes a list of coordinates and returns a number:
```
def inverse_f(coords):
x = 0
i = 0
while any(coords):
v = (coords[i%3]+1) % 3 - 1
coords[i%3] = coords[i%3] // 3 + (v==-1)
x += v * 3**i
i += 1
return x
```
My `f` function is perhaps notable for its performance. It uses only `O(k)` memory and takes `O(k) + O(log(x))` time to find the results, so it can work with very large input values. Try `f(10000, 10**10000)` for instance, and you'll get an answer pretty much instantly (adding an extra zero to the exponent so `x` is `10**100000` makes it take 30 seconds or so on my old PC). The inverse function is not as fast, mostly because it's hard for it to tell when it's done (it scans all the coordinates after each change, so it takes something like `O(k*log(x))` time). It could probably be optimized to be faster, but it's probably fast enough for normal parameters already.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
§~!oΠR€Θݱ
```
[Try it online!](https://tio.run/##AR8A4P9odXNr///Cp34hb86gUuKCrM6YxLDCsf///zP/LTQ4 "Husk – Try It Online")
The inverse function is also 10 bytes.
```
§o!ȯ€ΠRΘݱ
```
[Try it online!](https://tio.run/##ASUA2v9odXNr///Cp28hyK/igqzOoFLOmMSwwrH///8z/1stNiwxLDBd "Husk – Try It Online")
## Explanation
Forward direction:
```
§~!oΠR€Θݱ Implicit inputs, say k=3 and x=-48
ݱ The infinite list [1,-1,2,-2,3,-3,4,-4,..
Θ Prepend 0: [0,1,-1,2,-2,3,-3,4,-4,..
~ € Index of x in this sequence: 97
§ R Repeat the sequence k times: [[0,1,-1,..],[0,1,-1,..],[0,1,-1,..]]
oΠ Cartesian product: [[0,0,0],[1,0,0],[0,1,0],[1,1,0],[-1,0,0],[0,0,1],..
! Index into this list using the index computed from x: [-6,1,0]
```
Reverse direction:
```
§o!ȯ€ΠRΘݱ Implicit inputs, say k=3 and y=[-6,1,0]
ΠRΘݱ As above, k-wise Cartesian product of [0,1,-1,2,-2,..
ȯ€ Index of y in this sequence: 97
§o! Index into the sequence [0,1,-1,2,-2,.. : -48
```
The Cartesian product built-in `Π` behaves nicely for infinite lists, enumerating each **k**-tuple exactly once.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 61 bytes
```
SortBy[Range[-(x=2Abs@#+Boole[#>=0]),x]~Tuples~#2,#.#&][[x]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78X5IfUlqQk2r7Pzi/qMSpMjooMS89NVpXo8LWyDGp2EFZ2yk/Pyc1WtnO1iBWU6citg6svLhO2UhHWU9ZLTY6uiI2Vu1/QFFmXomDc35OaW6eW35RrkNIYhJQG9T06Aodo1id6godXVMd09rY/wA "Wolfram Language (Mathematica) – Try It Online")
(Takes the integer and then the length of the tuple as input.)
Inverse:
```
If[OddQ[#],#-1,-#]/2&@Tr@Position[SortBy[Range[-(x=Ceiling@Norm@#),x]~Tuples~Length@#,#.#&],#]&
```
[Try it online!](https://tio.run/##PY1dC4IwGIX/ymAgBVt@3AujroIoK@/GLkZOHbgt5gJD9K8vM@3qvM97OOco7mqhuJMP7ktrVP56NiL1x5JeiuJKIUMQxwhDFiYByS3JTCudNJrejXX7N71xXQmKN116ELKRuiJnYxWBW9SxcS5rx5PQlasJRHAHg6mQBT6zUjv6HwQhAX2PEwSiAfUxAjieFK9HhMDK0Q8Xmd3l@3UXXDI4GQbmPw "Wolfram Language (Mathematica) – Try It Online")
# How it works
The idea is straightforward: we turn the integer input into a positive integer (by mapping 0,1,2,3,... to 1,3,5,7,... and -1,-2,-3,... to 2,4,6,...) and then index into all the *k*-tuples, sorted by distance from the origin and then by Mathematica's default tie-breaking.
But we can't use an infinite list, so when we're looking for the *n*th *k*-tuple, we only generate *k*-tuples of integers in the range {-*n*,...,*n*}. This is guaranteed to be enough, because the *n*th smallest *k*-tuple by norm has norm less than *n*, and all tuples of norm *n* or less are included in this list.
For the inverse, we just generate a long enough list of *k*-tuples, find the position of the given *k*-tuple in that list, and then invert the "fold into a positive integer" operation.
[Answer]
# J, 7 Bytes
`#.,|:#:`
The J code to do this embarrassingly simple
A very simple pairing function (or, tupling function) is to simply interleave the digits of the binary expansion of each of the numbers. So, for instance `(47, 79)` would be paired as such:
```
1_0_0_1_1_1_1
1_0_1_1_1_1
-------------
1100011111111
```
or, 6399. Obviously, we can trivially generalize to any n-tuple.
Let's examine how this works verb by verb.
`#:` is anti-base two, when used monadically it returns the binary expansion of a number. `#: 47 79` gives the result:
```
0 1 0 1 1 1 1
1 0 0 1 1 1 1
```
`|:` is the transpose operator, which simply rotates an array. Rotating the result of `#: 47 79` gives:
```
0 1
1 0
0 0
1 1
1 1
1 1
1 1
```
When used monadically, `,` is the ravel operator, it produces a 1-dimensional list from an table:
```
0 1 1 0 0 0 1 1 1 1 1 1 1 1
```
Finally, `#.` converts the binary expansion back, giving us the result `6339`.
This solution will work for any string of integers.
[Answer]
# [Perl 6](http://perl6.org/), 148 bytes
```
my@s=map ->\n{|grep {n==abs any |$_},(-n..n X -n..n)},^Inf;my&f={$_==1??+*!!do {my&g=f $_-1;my@v=map {.[0],|g .[1]},@s;->\n{@v[n>=0??2*n!!-1-2*n]}}}
```
[Try it online!](https://tio.run/##HY1BCoMwFAWv8hQRa01QC92Er257g4K1YqnJpkZREELM2a24Ghge86Z@/t33fTDVQkM3gRUvbTc19xOsJuo@CzptsAWtSyKmOdd44uTFJe@HlmIwoSQbtERZWV5jz/uOsIdUJBG0LDsG1Xq2La/TJtkUeJ01LqkWcb5Va60LSssyj7XnsYwdbJxzu8BgECoQZHS7CCydgR@0oAJWHW3nQ44zWJ5ynqdi/wM "Perl 6 – Try It Online")
Ungolfed:
```
sub rect($n) {
grep ->[$x,$y] { abs($x|$y) == $n }, (-$n..$n X -$n..$n);
}
my @spiral = map { |rect($_) }, ^Inf;
sub f($k) {
if ($k == 1) {
-> $_ { $_ }
} else {
my &g = f($k-1);
my @v = map -> [$x, $y] { $x, |g($y) }, @spiral;
-> $_ { $_ >= 0 ?? @v[2*$_] !! @v[-1-2*$_] }
}
}
```
Explanation:
* `rect($n)` is a helper function that generates the coordinates of the integral points on the edge of a rectangle from coordinates `(-$n,$n)` to `($n, $n)`.
* `@spiral` is a lazy, infinite list of the integral points on the edges of rectangles of increasing size, starting from 0.
* `f($k)` returns a function which is a bijection from the integers to `$k`-tuples of integers.
If `$k` is `1`, `f` returns the identity mapping `-> $_ { $_ }`.
Otherwise, `&g` is the recursively obtained mapping from the integers to `$k-1`-tuples of integers.
Then, we `@spiral` out from the origin, and at each point form a `$k`-tuple by taking the X-coordinate and the flattened result of calling `g` with the Y-coordinate. This lazily generated mapping is stored in the array `@v`.
`@v` contains all `$k`-tuples starting with index 0, so to extend the indexing to the negative integers, we just map positive inputs to the even numbers and negative inputs to the odd numbers. A function (closure) is returned which looks up elements of `@v` in this way.
[Answer]
# JavaScript, 155 bytes
```
f=k=>x=>(t=x<0?1+2*~x:2*x,h=y=>(g=(v,p=[])=>1/p[k-1]?v||t--?0:p.map(v=>v&1?~(v/2):v/2):[...Array(1+v)].map((_,i)=>g(v-i,[...p,i])).find(u=>u))(y)||h(y+1))(0)
```
```
f=k=>x=>(t=x<0?1+2*~x:2*x,h=y=>(g=(v,p=[])=>1/p[k-1]?v||t--?0:p.map(v=>v&1?~(v/2):v/2):[...Array(1+v)].map((_,i)=>g(v-i,[...p,i])).find(u=>u))(y)||h(y+1))(0)
```
```
<p>k = <input id=k value=2>
<p>from <input id=a value=-5>
<p>to <input id=b value=5>
<p><button type="button" onclick="for(o.value='',i=+a.value;i<=b.value;i++)o.value+=[i,f(+k.value)(i)].join(':')+'\n';">generate</button>
<p><pre><output id=o>
```
Prettify version:
```
k => x => {
// Map input to non-negative integer
if (x > 0) t = 2 * x; else t = 2 * -x - 1;
// we try to generate all triples with sum of v
g = (v, p = []) => {
if (p.length === k) {
if (v) return null;
if (t--) return null;
// if this is the t-th one we generate then we got it
return p;
}
for (var i = 0; i <= v; i++) {
var r = g(v-i, [...p, i]);
if (r) return r;
}
}
// try sum from 0 to infinity
h = x => g(x) || h(x + 1);
// map tuple of non-negative integers back
return h(0).map(v => {
if (v % 2) return -(v + 1) / 2
else return v / 2;
});
}
```
* First, we map all integers to all non-negative integers one by one:
+ if n > 0 then result = n \* 2
+ otherwise result = -n \* 2 - 1
* Second, we give all tuples with k-length non-negative integers an order:
+ calculate sum of all element, smaller one comes first
+ if sum is equal, compare from left to right, smaller one comes first
+ As a result, we got the map for all non-negative integers to tuples with k non-negative integers
* Finally, map non-negative integers in tuple given in second step to all integers with similar formula in first step
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 107 bytes
```
(-1)^#⌈#/2⌉&@Nest[{w=⌊(√(8#+1)-1)/2⌋;x=#-w(w+1)/2,w-x}~Join~{##2}&@@#&,{2Abs@#-Boole[#<0]},#2-1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8V9D11AzTvlRT4eyvtGjnk41B7/U4pLo6nLbRz1dGo86ZmlYKGsbagIVgaS7rStslXXLNcq1QXydct2K2jqv/My8umplZaNaNQcHZTWdaiPHpGIHZV2n/Pyc1GhlG4PYWh1lI13DWLX/mtZcAUWZeSUOadGGpqamZmY6prH/AQ "Wolfram Language (Mathematica) – Try It Online")
## Inverse, 60 bytes
```
(-1)^#⌈#/2⌉&@Fold[+##(1+##)/2+#&,2Abs@#-Boole[#<0]&/@#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8V9D11AzTvlRT4eyvtGjnk41B7/U4pLo6nLbRz1dGo86ZmlYKGsbagIVgaS7rStslXXLNcq1QXydct2K2jqv/My8umplZaNaNQcHZTWdaiPHpGIHZV2n/Pyc1GhlG4PYWh1lI13DWLX/mtZcAUWZeSUOadGGpqamZmY6prH/AQ "Wolfram Language (Mathematica) – Try It Online")
## Explanation:
Z -> N0 via `f(n) = 2n if n>=0 and -2n-1 if n<0`
N0 -> N0^2 via [inverse of the pairing function](https://en.wikipedia.org/wiki/Pairing_function#Inverting_the_Cantor_pairing_function)
N0 -> N0^k Repeatedly apply the above to the leftmost number until we get length `k`
N0^k -> Z^k via `f(n) = (-1)^n * ceil(n/2)`, element-wise
---
# Mathematica, 101 bytes
```
(-1)^#⌈#/2⌉&@Nest[{a=#~IntegerExponent~2+1,#/2^a+1/2}~Join~{##2}&@@#&,{2Abs@#+Boole[#<=0]},#2-1]&
```
Similar to above (uses N instead of N0), but uses the inverse of the bijection f: N^2 -> N via `f(a, b) = 2^(a - 1)(2b - 1)`
[Answer]
# JavaScript, 112 bytes
```
k=>x=>(r=Array(k).fill(''),[...`${x<0?2*~x+1:2*x}`].map((c,i,s)=>r[(s.length-i)%k]+=c),r.map(v=>v&1?~(v/2):v/2))
```
1. convert to non-negative
2. (n\*k+i)th digit to i-th number
3. convert back
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes
```
[D_#>3‰`<s])sô0ζεR3β
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/2iVe2c74UcOGBJviWM3iw1sMzm07tzXI@Nym//8NDYCAyxgA "05AB1E – Try It Online") Port of @Blckknght's answer. Inverse, 17 bytes:
```
[Z_#>3‰ø`<s])˜R3β
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/Oipe2c74UcOGwzsSbIpjNU/PCTI@twkobmSko6BrCcSGhrEA "05AB1E – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
µ<1ạḤðŒRṗAS$Þ⁸ị
```
[Try it online!](https://tio.run/##ASsA1P9qZWxsef//wrU8MeG6oeG4pMOwxZJS4bmXQVMkw57igbjhu4v///8xMv8z "Jelly – Try It Online")
1-indexed.
Inverse:
```
AṀ×LŒRṗLAS$Þiµ:2NḂ}¡
```
[Try it online!](https://tio.run/##y0rNyan8/9/x4c6Gw9N9jk4Kerhzuo9jsMrheZmHtloZ@T3c0VR7aOH///@jDXUUgMggFgA "Jelly – Try It Online")
] |
[Question]
[
Given a string `s` and an array/list `l`, determine whether or not `s` can be made with parts from `l`.
For example, if the string is `"Hello, world!"` and the list is `[' world!', 'Hello,']`, then the program/function should return a truthy value, because you can arrange the list to form the string. The following list would also return a truthy value: `['l', 'He', 'o, wor', 'd!']`. Just imagine the `'l'` filling in where it needs to in he string. So yes, you may repeat elements of the list to form the string. If it cannot form the string, it should return a falsy value. Standard methods of IO, standard loopholes apply.
**Test cases:**
```
Input (In the form of s, l)
Output (1 if possible, 0 if impossible)
"Hello, world!", ["l", "He", "o, wor", "d!"]
1
"la lal al ", ["la", " l", "al "]
1
"this is a string", ["this should return falsy"]
0
"thi is a string", ["this", "i i", " a", " string"]
0
"aaaaa", ["aa"]
0
"foo bar foobar", ["foo", "bar", " ", "spam"]
1
"ababab", ["a","ba","ab"]
1
"", ["The string can be constructed with nothing!"]
1
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
~c¬{∋¬∈}
```
[Try it online!](https://tio.run/nexus/brachylog2#@1@XfGhN9aOO7kNrHnV01P7/r5STqJCTmKMAREr/o4E8JR0lhRwgARKIBQA "Brachylog – TIO Nexus")
This is really slow. Took about 37 seconds for the "Hello, world!" test case on my PC, and timed-out on TIO.
This takes the string through the Input variable and the list through the Output variable
### Explanation
```
String = ?, List = .
It is possible to find…
~c …a deconcatenation of ?…
¬{ } …such that it is impossible…
∋¬∈ …that an element of that deconcatenation is not an element of .
```
[Answer]
## Mathematica, 29 bytes
```
StringMatchQ[#,""|##&@@#2..]&
```
## Explanation:
```
#, (* The first argument *)
StringMatchQ[ (* matches the string pattern *)
""|##& (* Alternatives *)
@@ (* applied to *)
#2 (* the second argument *)
.. (* repeated *)
]&
```
## Borderline cheating solution, 21 bytes
```
StringMatchQ[#,#2..]&
```
Since Mathematica is a symbolic programming language, there is no\* difference between the expressions `List[a,b,...]` and `Alternatives[a,b,...]` other than how they interact with other symbols and how they are displayed (`{a,b,...}` and `a|b|...`, respectively). When used in the second argument of `StringMatchQ`, an `Alternatives` expression is treated as a string pattern, and thus we can save `8` bytes over my above solution by taking the second argument as an `Alternatives` expression.
\* Technically `List` is also `Locked`, which prevents users from `Unprotect`ing it and changing its behavior.
[Answer]
# Pyth, 23 bytes
```
AQW&GhGJ.(G0Vf!xJTH aG>JlN;G
```
Takes input like `[['string'],['list', 'of', 'parts']]`. The output is either an empty list or a list with values inside. In Pyth, a list containing anything, even a null string (`['']`), evaluates to true.
[Try it online!](http://pyth.herokuapp.com/?code=AQW%26GhGJ.%28G0Vf%21xJTH+aG%3EJlN%3BG&input=%5B%5B%22ababab%22%5D%2C%5B%22a%22%2C%22ba%22%2C%22ab%22%5D%5D&debug=0)
Explanation:
```
| Implicit: Q = eval(input())
AQ | Assign the first value of Q to G and the second to H
W&GhG | While G is not empty and G doesn't contain an empty string:
J.(G0 | Pop the first value of G and store into J
Vf!xJTH | For N in elements in H that match the beginning of J:
| Additional space for suppressing printing
aG>JlN | Append to G the elements of J from the length of N to the end
; | End all loops
G | Print G
```
This solution continuously tries to remove every possible part from the beginning of the string, and keeps track of what values it still needs to look through.
If we look at the value of `G` in the test case [`[['ababab'],['a','ba','ab']]`](http://pyth.herokuapp.com/?code=AQW%26GhGJ.%28G0Vf%21xJTH+aG%3EJlN%3BG&input=%5B%5B%27ababab%27%5D%2C+%5B%27a%27%2C+%27ba%27%2C+%27ab%27%5D%5D&debug=0) after each iteration of the while loop, this is what we get:
```
['ababab']
['babab', 'abab']
['abab', 'bab']
['bab', 'bab', 'ab']
['bab', 'ab', 'b']
['ab', 'b', 'b']
['b', 'b', '']
['b', '']
[''] <---Remember, this evaluates to True
```
And, in the test case [`[['aaaaa'],['aa']]`](http://pyth.herokuapp.com/?code=AQW%26GhGJ.%28G0Vf%21xJTH+aG%3EJlN%3BG&input=%5B%5B%27aaaaa%27%5D%2C+%5B%27aa%27%5D%5D&debug=0), this is what we get:
```
['aaaaa']
['aaa']
['a']
[] <---And this evaluates to False
```
I created another test case, [`[['aaaaaa'],['a','aa','aaa']]`](http://pyth.herokuapp.com/?code=AQW%26GhGJ.%28G0Vf%21xJTH+aG%3EJlN%3BG&input=%5B%5B%27aaaaaa%27%5D%2C+%5B%27a%27%2C%27aa%27%2C%27aaa%27%5D%5D&debug=0) and the output was this:
```
['', 'aaa', 'aa', 'a', 'aa', 'a', '', 'a', '', 'aa', 'a', '', 'a', '', '', 'a', '', '']
```
The output list contains a bunch of garbage inside of it, but it's still a truthy value.
[Answer]
# [Perl 5](https://www.perl.org/), 39 bytes
38 bytes of code + `-p` flag.
```
map{chop;$v.="\Q$_\E|"}<>;$_=/^($v)*$/
```
[Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@J@bWFCdnJFfYK1SpmerFBOoEh/jWqNUa2NnrRJvqx@noVKmqaWi//@/R2pOTr6OQnl@UU6KIlcOl0cqF4TLBeQCAA "Perl 5 – TIO Nexus")
For the input `"Hello, world!", ["l", "He", "o, wor", "d!"]` (separated by newlines actually), it construct the pattern `l|He|o, wor|d!|` (with the metacharacters escaped, thanks to `\Q..\E`), and then looks if the first string matches this pattern with `/^($v)*$/`.
On the TryItOnline, note that there need to be a trailing newline.
[Answer]
# PHP, 69 Bytes
```
<?=($s=$_GET[0])>""?ctype_digit(strtr($s,array_flip($_GET[1])))?:0:1;
```
[Testcases](http://sandbox.onlinephpfunctions.com/code/6fbacec0f1889ff7de8237799ad56b829648ac4a)
[Answer]
# Python 2, 141 bytes
```
lambda s,l:s in[''.join(i)for r in range(len(s)+1)for j in combinations_with_replacement(l,r)for i in permutations(j)]
from itertools import*
```
[Try it Online!](https://tio.run/nexus/python2#JY3BCsIwEETvfkXIpYkGwavgl2gpSU10S7IbNit@fm0qAwPzeDDp9lizL@HpVXP52hTgfRjOCwEasIlY8YYUe3xFkyOaZk@XnS@dz1QCoBcgbNMX5D1xrNnPsUQUkx3vKnS1Ri4f@atmseMhMRUFElmI8nZcKrEc18qAopLRPvRop@7aa6dDr22Pdv0B)
*Extremely* inefficient. The first test case times out on TIO.
[Answer]
## JavaScript (ES6), 59 bytes
Takes the array of substrings `a` and the string `s` in currying syntax `(a)(s)`. Returns `false` / `true`.
```
a=>g=s=>!s||a.some(e=>s.split(e)[0]?0:g(s.slice(e.length)))
```
### Commented
```
a => // main function that takes 'a' as input
g = s => // g = recursive function that takes 's' as input
!s || // if 's' is empty, return true (success!)
a.some(e => // else, for each element 'e' in 'a':
s.split(e)[0] ? // if 's' doesn't begin with 'e':
0 // do nothing
: // else:
g(s.slice(e.length)) // remove 'e' at the beginning of 's' and
) // do a recursive call on the remaining part
```
### Test cases
```
let f =
a=>g=s=>!s||a.some(e=>s.split(e)[0]?0:g(s.slice(e.length)))
console.log(f(["l", "He", "o, wor", "d!"])("Hello, world!")) // true
console.log(f(["la", " l", "al "])("la lal al ")) // true
console.log(f(["this should return falsy"])("this is a string")) // false
console.log(f(["this", "i i", " a", " string"])("thi is a string")) // false
console.log(f(["aa"])("aaaaa")) // false
console.log(f(["foo", "bar", " ", "spam"])("foo bar foobar")) // true
console.log(f(["a","ba","ab"])("ababab")) // true
```
[Answer]
# [Haskell](https://www.haskell.org/), 35 bytes
`#` takes a `String` and a list of `String`s, and returns a `Bool`.
```
s#l=elem s$concat<$>mapM("":)(l<$s)
```
[Try it online!](https://tio.run/nexus/haskell#LU5LjsIwDN3PKTyhi0SqegAEs54NJ0AsTBsgkpsgOxHi9MVJiC1/3nt2vGKIxxCzZ5zzUCKF6GVa8WnlkV5TiXNhftudm9jj4qbGb7Kjoye/ggxzijPmw/CnMydrzN5ZOgzits2af0@URnglpuXXjHA2pFHhGjtRK@Uu7scaQiAkUO9arCS0kYo1TX4EAXUEyRzivSkbqPcWWoB9LhzhhiTvPoL1NZ2mhtxSgisyaNbUKC3rP7019QAjT1y/G67V@gozqkiD9sp9AA "Haskell – TIO Nexus")
Just don't mind the test case I left out because it thrashed my meager laptop, even with -O2. I suspect GHC doesn't fuse away that intermediate 30517578125 element list, it has too much sharing to get swiftly garbage collected, and because the test case is false the program has to generate all of it... feel free to try if you can handle that.
`mapM("":)(l<$s)` is a list of all ways of making a `length s` list of elements that are either empty strings or strings from `l`.
[Answer]
# Pyth, ~~17~~ ~~15~~ ~~11~~ 14 bytes
```
AQ|!G}Ym-dH./G
```
The requirement for the empty string changed, adding 3 bytes.
Explanation
```
AQ|!G}Ym-dH./G
AQ Save the input into G, H.
./G Get all partitions of G.
m-dH Check if the parts are in H.
}Y The empty list should be present if and only
if the string can be made...
|!G ... or the string might be empty.
```
Old versions
```
AQ}Ym-dH./G
```
Shorter *and* runs in the lifespan of the universe!
Explanation
```
AQ}Ym-dH./G
AQ Save the input into G, H.
./G Get all partitions of G.
m-dH Check if the parts are in H.
}Y The empty list should be present if and only
if the string can be made.
AQ&G}GsMs.pMy*HlG
```
This is horrifyingly slow, but it works for my (trivially small) test cases.
Explanation
```
AQ&G}GsMs.pMy*HlG
AQ Save the input into G, H.
*HlG Repeat the list of substrings for each character of G.
y Take the power set.
.pM Take every permutation of each set of substrings.
sMs Get a list of all the joined strings.
}G Check if G is one of them.
&G Make sure G is not empty.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ ~~12~~ 8 bytes
```
;FŒṖḟ€Ạ¬
```
[Try it online!](https://tio.run/nexus/jelly#@2/tdnTSw53THu6Y/6hpzcNdCw6t@f//v5LSf6WQjFSF4pKizLx0heTEPIWkVIXk/DygQGlySWqKQnlmSYZCXn5JBlBeUQkA "Jelly – TIO Nexus")
**How it works**
```
;FŒṖḟ€Ạ¬ - main function, left argument s, right argument l
;F - concatenate to the string the list, flattened to deal with "" as string
ŒṖ - Get all partitions of s, that is, all ways to make s from substrings
€ - For each partition...
ḟ - Filter out (exclude) those elements which are not in...
- (implicit right arg) the list l. This leaves the empty set (falsy) if the partition can be made of elements from the list
Ạ - If any element is falsy (thus constructable from l), return 0; else return 1
¬ - Apply logical not to this, to yield the proper 1 = constructable from list, 0 otherwise.
```
*bugfix on case `"", ["The string can be constructed with nothing"]` thanks to @JonathanAllan*
[Answer]
# R, 49 bytes
```
function(s,l)gsub(paste(l,collapse='|'),"",s)==""
```
[Try it online!](https://tio.run/nexus/r#FYjbCcAgDABXkfyYQFbIMKnYUgg@Gv3r7rbCcXDXZZ2zpHHXgs5Gl88Dm/rIaJyqmTbPEt9IDMBOIgCrPXcZ2BFMg6mFH@C0EzhAsO39iGh9)
[Answer]
# Pyth, 10 ~~8~~ bytes
```
f!-TQ./+zh
```
[Test suite](https://pyth.herokuapp.com/?code=f%21-TQ.%2F%2Bzh&test_suite=1&test_suite_input=%5B%22l%22%2C+%22He%22%2C+%22o%2C+wor%22%2C+%22d%21%22%5D%0AHello%2C+world%21%0A%5B%22la%22%2C+%22+l%22%2C+%22al+%22%5D%0Ala+lal+al+%0A%5B%22t%22%5D%0Athis%0A%5B%22this%22%2C+%22i+i%22%2C+%22+a%22%2C+%22+string%22%5D%0Athi%0A%5B%22aa%22%5D%0Aaaaaa%0A%5B%22foo%22%2C+%22bar%22%2C+%22+%22%2C+%22spam%22%5D%0Afoo+bar+%0A%5B%22a%22%2C%22ba%22%2C%22ab%22%5D%0Aababab%0A%5B%22The%22%5D%0A&debug=1&input_size=2)
This takes the list on the first line of STDIN, and the string (without quotes) on the second.
To start, the list is stored in `Q`, and the string is stored in `z`. Next, we form all possible partitions of `z`. Each partition will be filtered (`f`) to check if it uses only pieces in `Q`. To do this, we remove all elements of `Q` from `T`, the partition we're partitioning, and logically negate the result with `!`, so that only partitions where every element was in `Q` are kept.
To fix the problem that `''` has no partitions, we add the first word of the dictionary to z, so that it won't be an empty string.
[Answer]
# PowerShell, ~~61~~ ~~58~~ 57 bytes
```
{$s,$l=$_;$l|sort -d length|%{$s=$s.replace($_,'')};+!$s}
```
[Try it online!](https://tio.run/nexus/powershell#bVDNbsMgDL7vKVxE1URle4Gq9z3A7p2T0BDJgwqIqqnps2c2ZNplgGzz/diIRr1bomDgHiINO2WgUcSRYYmVkIq5tjUvzCIQEvCpYhQWikewKspuSsAHIeU4@bFIC5hcmGmAaPMcPVyR0vef51@LdGamjKnDNkG1oSwRGy437BoCdBiBM6fSiUvx1quSt6t0w6/fJp3sIuRerOLA90oW@MPZbS706KGz0AfPwNxnO8B9yg584Of6UT5q2cPn@tDJaDrry0nTkkLM8DoAWT9mt@yZPOv0Fu2NsLeNvpjDoX2ejjudnuv6Aw "PowerShell – TIO Nexus")
Old solutions:
```
{$s,$l=$_;$l|sort -d length|%{$s=$s.replace($_,'')};[int]!$s}
{$s,$l=$_;$l|sort -d length|%{$s=$s.replace($_,'')};0+!$s}
```
[Answer]
# Python 2, 64 bytes
```
lambda s,l:len(re.findall("^("+"|".join(l)+")*$",s))>0
import re
```
[Try this online!](https://tio.run/nexus/python2#FYhBCoMwEEX3PcUwuJipQbou1IuohRETSPlGiS69exrh8x7vh89YYOu8GB0Ob/gk2XchpsUA4a9wyxd3vy0mgbasz4bdodq/HnHdt3xS9mXPMZ0UhGEEA9Wxo6FmFRNu3t@k5Q8)
[Answer]
# PowerShell, 78
```
$s,$l=$args;!($s-creplace(($l|sort -d length|%{[regex]::escape($_)})-join'|'))
```
Pretty straightforward regex-based approach.
[Answer]
## CJam (16 bytes)
```
{Ma+1$,m*:e_\a&}
```
This is an anonymous block (function) taking the string and the array of strings on the stack. [Online demo](http://cjam.aditsu.net/#code=%22ababab%22%20%5B%22a%22%20%22ba%22%20%22ab%22%5D%0A%0A%7BMa%2B1%24%2Cm*%3Ae_%5Ca%26%7D%0A%0A~).
It uses the obvious algorithm:
```
{ e# Declare a block. Call the args str and arr
Ma+ e# Add the empty string to the array
1$,m* e# Take the Cartesian product of len(str) copies of (arr + [""])
:e_ e# Flatten each element of the Cartesian product into a single string
\a& e# Intersect with an array containing only str
}
```
The return value is an empty array/string (falsy) if `str` can't be made, or an array containing `str` (truthy, even if `str` is itself the empty string) if it can be made.
[Answer]
# C++(Bcc), 287 bytes
```
#include<algorithm.h>
f(a,b)char*a,**b;{int i,j,k,v,p[256];if(!a||!b||!*b)return-1;for(v=0;v<256&&b[v];++v)p[v]=v;if(v>=256)return-1;la:for(i=0,j=0;j<v&&a[i];){for(k=0;b[p[j]][k]==a[i]&&a[i];++i,++k);j=b[p[j]][k]?(i-=k),j+1:0;}if(a[i]&&next_permutation(p,p+v)) goto la;return i&&!a[i];}
```
because i do not wrote or used too much the next\_permutation() i don't know if is all ok.
I don't know 100% if it is a solution too possibly this is out of quality...
One list of string is here one array of pointers to char; NULL terminated
The algo is easy, there is one algo that linearity try if all string in the list fit with argument "a" string
there is one other algo that permute the index of the list of string so it try all possible combination.
ungolf it, test code and results here
```
#include<stdio.h>
g(a,b)char*a,**b;
{int i,j,k,v,p[256];
if(!a||!b||!*b) return -1;
for(v=0;v<256&&b[v];++v) p[v]=v;
if(v>=256) return -1; // one array of len >256 is too much
la:
for(i=0,j=0;j<v&&a[i];)
{for(k=0;b[p[j]][k]==a[i]&&a[i];++i,++k);
j=b[p[j]][k]?(i-=k),j+1:0;
}
if(a[i]&&next_permutation(p,p+v)) goto la;
return i&&!a[i];
}
#define F for
#define P printf
test(char* a, char** b)
{int i;
P("f(\"%s\",[",a);
F(i=0;b[i];++i)
P("\"%s\"%s", b[i], b[i+1]?", ":"");
P("])=%d\n", f(a,b));
}
main()
{char *a1="Hello, world!", *b1[]={"l","He", "o, worl", "d!", 0};//1
char *a2="la lal al ", *b2[]={"la", " l", "al ", 0};//1
char *a3="this is a string", *b3[]={"this should return falsy", 0};//0
char *a4="thi is a string", *b4[]={"this", "i i", " a", " string", 0};//0
char *a5="aaaaa", *b5[]={"aa", 0};//0
char *a6="foo bar foobar", *b6[]={"foo","bar"," ","spam", 0};//1
char *a7="ababab", *b7[]={"a","ba","ab", 0};//1
char *a8="", *b8[]={"This return 0 even if has to return 1", 0};//0
char *a9="ababc", *b9[]={"a","abc", "b", 0};//1
test(a1,b1);test(a2,b2);test(a3,b3);test(a4,b4);test(a5,b5);test(a6,b6);
test(a7,b7);test(a8,b8);test(a9,b9);
}
f("Hello, world!",["l", "He", "o, worl", "d!"])=1
f("la lal al ",["la", " l", "al "])=1
f("this is a string",["this should return falsy"])=0
f("thi is a string",["this", "i i", " a", " string"])=0
f("aaaaa",["aa"])=0
f("foo bar foobar",["foo", "bar", " ", "spam"])=1
f("ababab",["a", "ba", "ab"])=1
f("",["This return 0 even if has to return 1"])=0
f("ababc",["a", "abc", "b"])=1
```
this would compile in gcc C++ compiler
```
#include<algorithm>
int f(char*a,char**b){int i,j,k,v,p[256];if(!a||!b||!*b)return -1;for(v=0;v<256&&b[v];++v)p[v]=v;if(v>=256)return -1;la:;for(i=0,j=0;j<v&&a[i];){for(k=0;b[p[j]][k]==a[i]&&a[i];++i,++k);j=b[p[j]][k]?(i-=k),j+1:0;}if(a[i]&&std::next_permutation(p,p+v))goto la;return i&&!a[i];}
```
[Answer]
# Python, 66 bytes
```
lambda s,l:s==''or any(x==s[:len(x)]and f(s[len(x):],l)for x in l)
```
### Ungolfed:
```
def f(s,l):
if s=='':
return 1
for x in l:
if s.startswith(x) and f(s[len(x):],l):
return 1
return 0
```
[Answer]
# Microsoft Sql Server, 353 bytes
```
u as(select s.n,s collate Latin1_General_BIN s,l collate Latin1_General_BIN l,
row_number()over(partition by l.n order by len(l)desc)r from s,l where s.n=l.n),
v as(select n,s,l,replace(s,l,'')c,r from u where r=1 union all
select u.n,u.s,u.l,replace(v.c,u.l,''),u.r from v,u where v.n=u.n and v.r+1=u.r)
select s,iif(min(c)='',1,0)u from v group by n,s
```
[Test it online.](http://rextester.com/PBGQ9479)
Readable version:
```
with s as(
select n,s
from(values(1,'Hello, world!'),
(2,'la lal al '),
(3,'this is a string'),
(4,'thi is a string'),
(5,'aaaaa'),
(6,'foo bar foobar'),
(7,'ababab'),
(8,''))s(n,s)),
l as(
select n,l
from(values(1,'l'),(1,'He'),(1,'o, wor'),(1,'d!'),
(2,'la'),(2,' l'),(2,'al '),
(3,'this should return falsy'),
(4,'this'),(4,'i i'),(4,' a'),(4,' string'),
(5,'aa'),
(6,'foo'),(6,'bar'),(6,' '),(6,'spam'),
(7,'a'),(7,'ba'),(7,'ab'),
(8,'The string can be constructed with nothing!'))l(n,l)),
--The solution starts from the next line.
u as(
select s.n,
s collate Latin1_General_BIN s,
l collate Latin1_General_BIN l,
row_number()over(partition by l.n order by len(l)desc)r
from s,l
where s.n=l.n),
v as(
select n,s,l,replace(s,l,'')c,r from u where r=1
union all
select u.n,u.s,u.l,replace(v.c,u.l,''),u.r
from v,u
where v.n=u.n and v.r+1=u.r
)
select s,iif(min(c)='',1,0)u from v group by n,s
```
[Answer]
## C, 140 bytes
I'm sure there is a shorter way to do this in C but I wanted to create a solution that tests all the possible combinations of substrings instead of the usual find/replace method.
```
char p[999];c,o;d(e,g,l,f)int*e,**g,**l;{c=f&&c;for(l=g;*l;)strcpy(p+f,*l++),(o=strlen(p))<strlen(e)?d(e,g,0,o):(c|=!strcmp(e,p));return c;}
```
[Try it online](https://tio.run/nexus/c-gcc#PU47DsIwDJ3pKUIlkJN6YC0hYuUGDIgBpUlBhCYKQYBKz14c8RlsWe/nN@rjIbKwq@t6LzV62YDBFh1afuqSMChES@Nkr5Wdz7W0PoJTrSSIX1PU4QmhsihcVXEErwhzpoPA@ep7Gr7@hC7Q8yXol5pm4yUQSDIZTbrFjmk5jPSSXQ6nDnjRF5NcTbBkHokpVm6Mcx63PrqmlD/ybJ53H5vrbk@SnpUfGr/qfCCtBRvIESLFWyhnWdBAzsV/APUohvEN)
Ungolfed:
```
#include <string.h>
#include <stdio.h>
char buf[999];
int result;
int temp;
int test(char *text, char **ss, char **ptr, int length)
{
if (length == 0)
result = 0;
for(ptr = ss; *ptr; ptr++)
{
strcpy(buf + length, *ptr);
temp = strlen(buf);
if (temp < strlen(text))
{
// test recursivly
test(text, ss, 0, temp);
}
else
{
if (strcmp(buf, text) == 0)
result = 1;
}
}
return result;
}
int main()
{
char *text = "Hello,World";
char *keywords[] = { "World", "Hello", ",", 0 };
printf("%d", test(text, keywords, 0, 0));
}
```
] |
[Question]
[
## Task:
Your task is, when given three inputs:
* a numerator `n`
* a denominator `d`
* another integer, `x`
Create a program/function that finds the `x`th digit of the number after the decimal place.
## Specs:
* The range of `n` and `d` is between `1` and `2^31 - 1`, inclusive.
* The range of `x` is between `1` and `10,000,000`, inclusive.
+ You may choose to use 1-based indexing or 0-based indexing for `x`. Please state in your answer which one you're using.
* `n` may be larger than `d`.
* `n`, `d` and `x` are guaranteed to be positive integers (for 1-based index version of `x`, if you choose to use 0-based indexing for `x` then `x` can be `0`).
* You may take inputs in any reasonable way (I.e. any way that is not a standard loophole).
## Rules:
* You must return the exact `x`th digit, not when rounded - so the `15`th digit of `1/6`, for example, is not `7`, but `6`.
* Your program must work for all `x` under 10 million, unless your language doesn't support decimals to 10 million places.
## Example I/O:
*The example input uses 0-based indexing, which means `x` will go from `0` to `9,999,999`. As well as that, the "input" is written as a string with spaces separating the numbers.*
```
1 2 3: 0
5 6 0: 8
5 6 1: 3
1 6 15: 6 (not 7, as it's not rounded)
1 11 2: 0
1 10000 9999999: 0
11 7 1: 7
```
[Answer]
# [Python 2](https://docs.python.org/2/), 25 bytes
Port of my Haskell answer, since Python also supports bignums by default. As there, `x` is 1-indexed.
```
lambda n,d,x:n*10**x/d%10
```
[Try it online!](https://tio.run/nexus/python2#LYrBDsIgDEDvfEUvJkCaSKfOZIlHv2J6QGGRZEMyMeLXIxv20PeavuF0yaOebkaDR4Op85KUlGlrNqRynL8dg8/DjZaTKAphdj7CwKXz4R25EMymuw0Rzivc04N@gS1pLW3uCRvcX1l/wBbpz6aQlrtdhQh3VVSZupVa4vI5LvUP "Python 2 – TIO Nexus") (borrowing Keerthana Prabhakaran's wrapper.)
[Answer]
## Mathematica 33 Bytes
```
RealDigits[#/#2,10,1,-#3][[1,1]]&
```
1-based indexing.
e.g. 10-millionth digit of Pi right of the decimal point:
```
%[Pi,1,10^7]
7
```
takes about 2 seconds on my old machine.
You can try it online at [WolframAlpha](http://www.wolframalpha.com/input/?i=RealDigits%5B%23%2F%232,%2010,%201,%20-%233%5D%5B%5B1,%201%5D%5D%20%26%5BPi,%201,%2011%5D)
(click the equal sign)
[Answer]
# [Haskell](https://www.haskell.org/), 26 bytes
Works for all test cases. Yay bignums!
`(n#d)x` takes `Integer`s and returns an `Integer`. `x` is 1-indexed.
```
(n#d)x=n*10^x`div`d`mod`10
```
[Try it online!](https://tio.run/nexus/haskell#JYpBDsIgFET3nIJEF61pCL9qXXESo4H4aSSR3waq5fYI7SzmvUzGG0fK0WKDeS3HL30c2Si8mZv4nlYxVuXBGhTrFDC2Yjuw8U4ddumhGjpgm/IORSeQz6TR/TRqP6EGmTPwnl/YlQ8ctu4ZVB8KAPi5QpbsLSWwst7K6w8 "Haskell – TIO Nexus")
[Answer]
# PHP>=7.1, 40 Bytes
```
<?=bcdiv(($a=$argv)[1],$a[2],$a[3])[-1];
```
[bcdiv](http://php.net/manual/en/function.bcdiv.php)
[Online Version](http://sandbox.onlinephpfunctions.com/code/bcba44f9eceb6971913dc22b05e8217c6ff4cd96)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
⁵*×:ƓDṪ
```
[Try it online!](https://tio.run/nexus/jelly#@/@ocavW4elWxya7PNy56v9/8/8m/40B "Jelly – TIO Nexus")
A function submission (but also works as a full program). Jelly functions can only take two arguments directly; thus I take the digit to return as the left argument, the numerator as the right argument, and the denominator from standard input (in lieu of using a third argument).
People used to Jelly may be aware that a *full program* can take more than two arguments, but doing so causes you to lose access to the tersest way to write the constant integer 10, which is fairly relevant here. As such, this sort of mixed input feels somewhat like an exploit rather than actual useful golfing; I personally disagree with it, but [the rule about allowing this](https://codegolf.meta.stackexchange.com/a/5415/62131) is presently at +40 / -12, so as long as it's in the rules, I may as well exploit it (and pretty much have to to be competitive).
A left argument of 1 refers to the digit immediately after the decimal point (the ".1s digit"), an argument of 2 to the .01s digit, and so on.
## Explanation
```
⁵*×:ƓDṪ
⁵* 10 to the power of {the left argument}
× multiplied by {the right argument}
: divided by
Ɠ standard input
Ṫ take the last
D decimal digit
```
Jelly has arbitrary-precision arithmetic on integers, so by pre-multiplying by a power of 10, we're effectively moving the digit we want to the units position, where it's much easier to extract.
[Answer]
# [sed](https://www.gnu.org/software/sed/) `-r`, 93 ~~131~~ ~~136~~ bytes
```
s/$/,/
:d
s/,.+/,/
:
s/(1+)(1*;\1;1*,)1{10}?/\21/
t
s/1*/&&&&&&&&&&/
ta
:a
s/1,/,/
td
s/.+,//
```
[Try it online!](https://tio.run/##XUy7DsIwDNz9HQi1iVtzjM3Aj3SpVAYWikg2xK/j2gi1CidL97B9@TqrZjkICw0zZeE@frXJBrFtENKIhMAtXji9LzKeIVRsjSDHDRZNNEwes/8X7@oji6jauw8IjoQf/Vnzu65BVbRX1efGn@VRbss9a/dcAQ "sed 4.2.2 – Try It Online")
([See output in decimal](https://tio.run/##XY7NCoMwEITveQ4p/qSOG7U/5tAXkYJgKb1oabyJr950N5SKHQLf7GQzxN167x0iaKimVw46z4JnG1OWxJTaliylOqGZiuWC1hDUxNeUYvcTR51qOom1vJ@kK880INFcL6hh2REM7my4pJTAGFTCmnAINDgGljgFVjgLrxEKeM8/kUOKRJa@@Bt5Xv1WahOtVdt15nt8To9xcH7/@gA))
Takes input in unary and outputs in unary, and the program is 1-indexed. Thankfully, this [challenge](https://codegolf.stackexchange.com/a/114851/41805) has already prepared me for this one.
The concept is similar, both implement long division. Here, I perform long division `x` times, where `x` is the digit after the decimal place that I have to find. After each iteration, I discard the previous decimal places because they are no longer needed.
While doing division, the program is in the format `dividend;divisor;x,result`.
`s/$/,/` adds this comma, the comma is required to separate the result from everything else
Then follows the main program loop
`:d` label d
* `s/,.+/,/` remove everything after the comma
* `:` empty label
* + `s/(1+)(1*;\1;1*,)1{10}?/\21/` perform division, adding 1 to the result each iteration, whilst simultaneously removing blocks of 10 continuous 1s in the result
* `t` branch to the empty label, in other words, loop until the dividend has been exhausted
* `s/1*/&&&&&&&&&&/` multiply the dividend by 10 to prepare for the next iteration
* `ta` branch to label a
* `:a` label a, this line and the line above are required to make `td` work
* `s/1,/,/` subtract 1 from x
`td` conditional branch to d, this is triggered if there has been a successful substitution since the last conditional branch, since `s/1*/&&&&&&&&&&/` is always successful, `td` will always get triggered, but by introducing branch a, we fix that so that it only depends on the previous substitution
`s/.+,//` finally, remove everything but the result
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~34~~ 33 bytes
```
->n,d,x{(0..x).map{n=n%d*10};n/d}
```
[Try it online!](https://tio.run/nexus/ruby#S7P9r2uXp5OiU1GtYaCnV6Gpl5tYUJ1nm6eaomVoUGudp59S@79AIS3aUMdIxziWC8Q01THTMUAwDSFMQxDTFMY2BKqHsw2AAEICAVTUUMccqPM/AA "Ruby – TIO Nexus")
[Answer]
# REXX, 76 bytes
(Not very short but thought it would make a change to do one in REXX)
Rexx is 1-based by defintion.
```
arg n d x
numeric digits x+10
y=n/d
parse var y "." +(x) z
say left(z,1,"0")
```
Explanation:
1. Read input to the numbers
2. Guarantee enough significant digits (default is 9)
3. Calculate
4. Split. Find the decimal point, count forward "x" characters, take the following characters and put into "z"
5. Print out first digit. Pad with 0 to be sure.
Merging 3 and 4 actually makes it longer because of the change in syntax:
```
parse value n/d with "." +x z +1
```
For non-REXXers: Strings and numbers are totally interchangeable in REXX. They are determined by how you act on them. So you can parse a number using sting functions with no conversion.
For example
```
"27" + "28"
```
returns 55 and not 2728!
[Answer]
## Batch, 70 bytes
```
@set n=%1
@for /l %%x in (0,1,%3)do @set/an=n%%%2*10
@cmd/cset/an/%2
```
[Answer]
# Assembly Intel x86 cpu language, 50 bytes
```
00000940 53 push ebx
00000941 8B5C240C mov ebx,[esp+0xc]
00000945 8B4C2410 mov ecx,[esp+0x10]
00000949 31C0 xor eax,eax
0000094B 48 dec eax
0000094C 81C102000000 add ecx,0x2
00000952 721A jc 0x96e
00000954 81FB00000000 cmp ebx,0x0
0000095A 7412 jz 0x96e
0000095C 8B442408 mov eax,[esp+0x8]
00000960 31D2 xor edx,edx
00000962 F7F3 div ebx
00000964 49 dec ecx
00000965 7407 jz 0x96e
00000967 8D0492 lea eax,[edx+edx*4]
0000096A 01C0 add eax,eax
0000096C EBF2 jmp short 0x960
0000096E 5B pop ebx
0000096F C20C00 ret 0xc
```
traslation in nasm
```
; u32 __stdcall rdiv(u32 a, u32 b, u32 c)
; 8a, 12b, 16c
align 4
rdiv: ; c<0xFFFFFFFE and b!=0
push ebx ; something as for(;a=10*(a%b),c--;);return a/b
mov ebx, dword[esp+ 12]
mov ecx, dword[esp+ 16]
xor eax, eax
dec eax
add ecx, 2
jc .z
cmp ebx, 0
je .z
mov eax, dword[esp+ 8]
.1: xor edx, edx
div ebx
dec ecx
jz .z
lea eax, [edx+edx*4]
add eax, eax
jmp short .1 ; a=5*a;a+=a=>a=10*a
.z:
pop ebx
ret 12
```
For parameter 'c' the range begin from 0; it would be 0..0xfffffffd. If parameters b=0 or c out of range 0..0xfffffffd it would return -1
[Answer]
# Lua, 42 bytes
```
function a(n,x,d)
print((n*10^x/d)%10)
end
```
[Answer]
# C, ~~49~~ 43 bytes
```
f(a,b,i){for(;a=10*(a%b),i--;);return a/b;}
```
'i' argument is 0-indexing. Test code and result
```
main()
{int i;
for(i=0;i<20;++i)
printf("%u", f(12,11,i));
printf("\nf(1,2,3)=%d\n",f(1,2,3));
printf("f(5,6,0)=%d\n",f(5,6,0));
printf("f(5,6,1)=%d\n",f(5,6,1));
printf("f(1,6,15)=%d\n",f(1,6,15));
printf("f(1,11,2)=%d\n",f(1,11,2));
printf("f(1,10000,9999999)=%d\n",f(1,10000,9999999));
printf("f(11,7,1)=%d\n",f(11,7,1));
}
f(1,2,3)=0
f(5,6,0)=8
f(5,6,1)=3
f(1,6,15)=6
f(1,11,2)=0
f(1,10000,9999999)=0
f(11,7,1)=7
```
[Answer]
# Java 7, ~~146~~ ~~139~~ ~~137~~ ~~133~~ ~~128~~ 122 Bytes
-3 bytes thanks to Erik the Outgolfer, I totally forgot imports didn't have to be on their own line
-4 bytes thanks to Qwerp-Derp for moving n%d to the constructor
-6 bytes thanks Kevin Cruijssen for removing the toString()
I hope this is how the byte count is done for java functions with imports
```
import java.math.*;char a(int n,int d,int x){return (new BigDecimal(n%d).divide(new BigDecimal(d),x+1,1)+"").charAt(x+2);}
```
Uses Java's BigDecimal class to get exact representation of the decimal expansion. Note it's not the fastest running code ever but it does eventually produce the correct output for all test cases. Ungolfed code:
```
import java.math.*;
char a(int n, int d, int x){
BigDecimal num = new BigDecimal(n%d); // reduce improper fractions
BigDecimal div = new BigDecimal(d);
BigDecimal dec = num.divide(div, x+1, 1); // precision of x + 1, round down
return (dec+"").charAt(x+2); //xth char after decimal
}
```
[Try it online!](https://tio.run/nexus/java-openjdk#jZDBasMwDIbPzVOIwsBejKk72h5CDxm77tTj2EGLTeoRO8F2soySZ8/s0l12aKaDBPq/XxLSpmtdgE8ckBsMZ/5YZFnXfzS6gqpB7@EVtb1kq1vPBwyxDK2WYKJCTsFpW7@9A7ra0wiukgFKOIJVX1c3oUVsn759UIa3feBdtITGkpIjEQy2DJ7oPWbHYM9g8w9G0IVdidktQSIdtQhtYtxKjPt45A@/101zdUYHSKIOlqUsr3mkF6dC7yyQ9LpnXb@oShtsiH2QlEs9aKn@SpKyMRdM0Hy9pjxNLgMZ8y0tpnmafwA)
[Answer]
## Clojure, 39 bytes
```
#(mod(int(/(*(Math/pow 10 %3)%)%2))10))
```
anonymous function with arguments `n,d,x` where `x` uses one based indexing.
[Answer]
# [F# (.NET Core)](https://www.microsoft.com/net/core/platform), 30 bytes
```
let f n d x=n*pown 10I x/d%10I
```
[Try it online!](https://tio.run/##TU5LCsIwFNz3FEOh0MoTTdVuSgRx5RnEhZqkFOSlNAGz6N1jbEFczAdmGMa49dOOOsaX9jBgKATJq8G@GWJ7QdioIukce@38@e60g8R1ElTTvj1QQ2LmuhVf3yQRgnbTLTN2RMkERQgVev4bUDYDhrFnbxh5kRoLII8oTvnyA6VB@ei71AJXP6uqNBfjBw "F# (.NET Core) – Try It Online")
(use 1-based indexing)
[Answer]
## Groovy, 30 bytes
```
{n,d,x->(n*10**x/d as int)%10}
```
x uses 1 based indexing.
Explanation:
```
{n,d,x-> // closure with three arguments, n, d, x
n*10**x // multiply n with 10 to the power of x
/d // divide by d
as int // convert from BigDecimal to int
)%10 // modulo 10 to get the answer
}
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
/$›ḞṪt
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIvJOKAuuG4nuG5qnQiLCIiLCIyXG4xXG4zIl0=)
I do like the Sympy wrappers vyxal now has. Takes denominator, numerator then index.
## Explained
```
/$›ḞṪt
/ # divide the numerator by the denominator. This is fine because vyxal stores floats as Rationals internally.
$ # place the index at the top of the stack
›Ḟ # Sympy.evalf(fraction, n=index+1). This avoids rounding issues
Ṫt # get the second last item
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 4 bytes (8 nibbles)
```
/\`p/*^~
```
Input is `x`, `n`, `d`. Uses 1-based indexing.
```
* # multiply
^~ # 10 to the power of
# (implicitly) arg1
# by
# (implicitly) arg2
/ # and divide this by (implicitly) arg3
`p # print the number as a string
\ # reverse it
/ # and get the first element
# (by folding across it, each time
# returning the left-hand of each pair)
```
[](https://i.stack.imgur.com/CaliH.png)
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 7 bytes
```
ᴇ*⇹/1ᴇ%
```
[Try it online!](https://tio.run/##K6gs@f//4ZZ2rUftO/UNgQzV//8NDbhMucwB "Pyt – Try It Online")
input is `x`,`n`,`d`
```
ᴇ raises 10 to the x
* multiplies by n
⇹/ divides by d
1ᴇ% modulo 10; implicit print
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~50,44,40,~~ 36 bytes
```
lambda n,d,x:(`n*1./d%1`+'0'*x)[x+2]
```
[Try it online!](https://tio.run/nexus/python2#LYpBDoIwEEX3nGI2hhYmymDQhMSlp0ASUEpsgrXBGuvp60D9i3kvkzeeLmHqH9ehB4MD@lp0JqPtbthQl6dFmnnZ@Lxsg5u/dQKfu56UIMkKdtbGwSgybezbCSkT5W/KOjiv0E8D/QsUp7FUoSEscd8mTYUHLP4kJi2sViFuohS8eHnLi/DI9Q8 "Python 2 – TIO Nexus")
[Answer]
## Ruby, 39 bytes
```
->n,m,o{(n*1.0/m).to_s.split(?.)[1][o]}
```
[Answer]
# JavaScript (ES6), 34 bytes
```
(n,d,x)=>`${n/d}`.split`.`[1][x]|0
```
x is 0-based
```
f=
(n,d,x)=>`${n/d}`.split`.`[1][x]|0
console.log(f(1,2,3))
console.log(f(5,6,0))
console.log(f(5,6,1))
console.log(f(1,6,15))
console.log(f(1,11,2))
console.log(f(1,10000,10000000))
console.log(f(11,7,1))
console.log(f(2000,7,0))
```
[Answer]
# [Python 2](https://docs.python.org/2/), 32 bytes
Uses 0-indexing
```
lambda n,d,x:int(10**-~x*n/d)%10
```
[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQp5OiU2GVmVeiYWigpaVbV6GVp5@iqWpo8D8tv0ghM68AiBWiNQx1jHSMNXU0THXMdAygtCGQNgTRpmCGIVANiGGoYw6VMjQAAghpYGCoGWvFxVlQBLQKZKyOQpqGFpDW/A8A "Python 2 – TIO Nexus")
Edit:
Rolled back to original solution as seen in Ørjan Johansen's answer that it works, but I won't golf it any further
[Answer]
# Groovy, 55 bytes
```
{n,d,x->z='0'*x;Eval.me("$n.$z/$d.$z").toString()[x-1]}
```
Explained using `1,11,2`:
```
{
n,d,x-> // I've already lost to Jelly by the end of this line.
z='0'*x; // Set z equal to 2 0's.
Eval.me // Evaluate as groovy code...
("$n.$z/$d.$z") // 1.00g/11.00g (Automatically set precision using # 0s).
.toString()[x-1] // Get 2nd digit of division.
}
```
[Answer]
# Axiom, ~~71 61~~ 76 bytes
```
f(a:NNI,b:PI,n:NNI):NNI==(repeat(a:=10*(a rem b);n=0=>break;n:=n-1);a quo b)
```
n is 0-indexing [0..M]. Test code and result
```
(19) -> f(1,2,3)=0
(19) 0= 0
(20) -> f(5,6,0)=8
(20) 8= 8
(21) -> f(5,6,1)=3
(21) 3= 3
(22) -> f(1,6,15)=6
(22) 6= 6
(23) -> f(1,11,2)=0
(23) 0= 0
(24) -> f(1,10000,9999999)=0
(24) 0= 0
(25) -> f(11,7,1)=7
(25) 7= 7
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
→d÷⁰*²!İ⁰
```
[Try it online!](https://tio.run/##yygtzv7//1HbpJTD2x81btA6tEnxyAYg4////4aG/83/GwEA "Husk – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 23 bytes
```
(a,b,i)=>a*10n**i/b%10n
```
[Try it online!](https://tio.run/##VYtBDoIwEEX3nGI2Ji1WaFFAa2DhgsQzYJMWJKQGC7GN18cCK/9i8vL@n5f6Ktt@9OQOZnx2c1XMSJGGaFyUKmTUhKGOm52H@RpIBgkcOdAghQwoh/MKjMMxYAukHDJPzO@WlSfqA5ctq2KQLw@5jOw0aCcfRkZvNSFXlMgWbrMoroGLGK/NTfd34zBpR2PHoYuGsUe1rakgtmbLSQSp0L/YM4M9nITAGM8/ "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 43 bytes, [port](https://codegolf.stackexchange.com/a/118122/)
```
(a,b,i)=>eval(`for(;a=10*(a%b),i--;)a/b|0`)
```
[Try it online!](https://tio.run/##VYzNUoQwEITvPMVcLDMaINkf0VDZIy@BVGVY0MKKCUXinnx3DOzJPvT09Ex9X3SjcF2mOebOD@Pa6JUR7/mE@jLeyDLz4RdWk5biidFDj3zK8xqp7H@FwbXOjIQDHBWI7AwvIBS87kEqOGZyC2eVnDkfoeJAAab4GGBbF//jhnHA9CYTZEOkJJLg7a69klBttMoUYbZTNO/OFN80s6gvLOh4b1nZgupK3C8zLWFsrKeI/Opd8HYsrP9kbWhFx0MrNzt0vGH/i2eJaZ66DhHXPw "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 51 bytes
```
(n,d,x)=>[...Array(x)].map(_=>[n*=10,u=n/d,n%=d])|u
```
[Try it online!](https://tio.run/##VY7BTsQgEIbvfYq5GBlFWnZdqxg28dKXQLIlS2NqKjRAzZr47hW6J//DzD/fTP7Mp/k28RzGOT04b4e1kytx1NILyqNijL2FYH7IBTX7MjM5ZejuJG/oIl1tqbuRVuPvsr5WPYcd7AU01QGeoBHwvBkuYF/xYg4iV@J8gpaCiTCm2whlDH5xdrCYz3gOKRHZNVnwctWGOLQlre1ZnKcx9e@u335K8kiiTFdKagVC17htZhPi0E3eJKRn76KfBjb5D6KiajSNipey07Qj/8E9x9wftUbE9Q8 "JavaScript (Node.js) – Try It Online")
use Array rather than recursive to avoid [stackoverflow](https://stackoverflow.com/)
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 9 \log\_{256}(96) \approx \$ 7.41 bytes
```
10@*s10%,
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhYrDQ0ctIoNDVR1IPwFMMqQy5TLDMIBAA) Takes `x` then `n` then `d`.
Port of [Ørjan Johansen's Python answer](https://codegolf.stackexchange.com/a/117468/114446)
**Explanation:**
```
10@*s10%, # Implicit input, x then n then d
10@ # 10**x
* # *n
s # Swap so d is on top
10% # d%10
, # Integer divide
# Implicit output
```
] |
[Question]
[
My coworker, [Jimmy](https://blog.codinghorror.com/new-programming-jargon/) is kinda new to C/C++. He's also kind of a slow learner. Now, to be fair, his code always compiles, but he has some really sloppy habits. For example, everybody knows that you can define an array like this:
```
int spam[] = {4, 8, 15, 16, 23, 42};
```
Everybody that is, except for Jimmy. He is convinced that the *only* way to make an array is like this:
```
int spam[6];
spam[0] = 4;
spam[1] = 8;
spam[2] = 15;
spam[3] = 16;
spam[4] = 23;
spam[5] = 42;
```
I keep fixing this for him in code-review, but he won't learn. So I need you to write a tool that automagically does this for him when he commits¹.
# The challenge
I want you to write either a full program or a function that takes in a multiline string as input, and outputs the more compact version of the C array. The input will *always* follow this format, whitespace included:
```
identifier_one identifier_two[some_length];
identifier_two[0] = some_number;
identifier_two[1] = some_number;
identifier_two[2] = some_number;
...
identifier_two[some_length - 1] = some_number;
```
In short, the input will always be valid and well defined C. In more detail:
All of the identifiers will be made up of just letters and underscores. The length will always be at least one, and there will never be any missing or out of bounds indexes. You may also assume that the indexes are in order. For example:
```
foo bar[3];
bar[0] = 1
bar[2] = 9;
```
```
foo bar[1];
bar[0] = 1;
bar[1] = 3;
```
and
```
foo bar[3];
bar[2] = 9;
bar[0] = 1
bar[1] = 3
```
are all invalid inputs, and may cause undefined behavior in your submission. You may also assume that all of the numbers will be valid decimal numbers, negative or positive. The input will not have extraneous spaces. The output should always follow this format, whitespace included:
```
identifier_one identifier_two[] = {n1, n2, n3, ...};
```
Here is some sample data:
```
Input:
spam eggs[10];
eggs[0] = 0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;
eggs[4] = 3;
eggs[5] = 7;
eggs[6] = 888;
eggs[7] = 555;
eggs[8] = 0;
eggs[9] = -2;
Output:
spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};
Input:
char ans[2];
ans[0] = 52;
ans[1] = 50;
Output:
char ans[] = {52, 50};
Input:
blah_blah quux[1];
quux[0] = 105;
Output:
blah_blah quux[] = {105};
```
You may take your input and output in any reasonable format, such as STDIN/STDOUT, function arguments and return value, reading and writing files etc. Standard loopholes apply. The shortest answer in bytes wins!
---
*¹This is passive-aggressive and a terrible idea. You did **not** get this idea from me.*
[Answer]
# Vim, ~~43~~ 36 bytes
You don't need to give Jimmy a script, just teach him to use a proper text editor. (literal returns for clarity)
```
:%s/.*=//|%s/;\n/,/<cr><cr>
3wcf ] = {<esc>
$s};
```
[Answer]
## CJam, ~~43~~ 36 bytes
```
qN/('[/~;"[] = {"@{S/W=W<}%", "*"};"
```
[**Online Example**](http://cjam.tryitonline.net/#code=cU4vKCdbL347IltdID0geyJAe1MvVz1XPH0lIiwgIioifTsi&input=c3BhbSBlZ2dzWzEwXTsKZWdnc1swXSA9IDA7CmVnZ3NbMV0gPSA0OwplZ2dzWzJdID0gODsKZWdnc1szXSA9IC0zOwplZ2dzWzRdID0gMzsKZWdnc1s1XSA9IDc7CmVnZ3NbNl0gPSA4ODg7CmVnZ3NbN10gPSA1NTU7CmVnZ3NbOF0gPSAwOwplZ2dzWzldID0gLTI7)
**Explanation:**
```
qN/ |Read all lines to array
('[/~; |slice first line left of [
"[] = {" |add formatting to stack
@ |rotate to remaining lines
{ }% |for each line in array
S/W= |split after last space
W< |remove last character (;)
", "* |insert ", " to array
"};" |add formatting
```
A big thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) for the improvements on my first CJam answer.
[Answer]
# JavaScript (ES6), ~~65~~ ~~64~~ 63 bytes
```
s=>`${s.split`[`[0]}[] = {${s.match(/-?\d+(?=;)/g).join`, `}};`
```
[Answer]
## [Retina](http://github.com/mbuettner/retina), ~~30~~ 28 bytes
Byte count assumes ISO 8859-1 encoding.
```
\d+];¶.+
] = {
;¶.+=
,
;
};
```
[Try it online!](http://retina.tryitonline.net/#code=XGQrXTvCti4rIApdID0gewo7wrYuKz0KLAo7Cn07&input=c3BhbSBlZ2dzWzEwXTsKZWdnc1swXSA9IDA7CmVnZ3NbMV0gPSA0OwplZ2dzWzJdID0gODsKZWdnc1szXSA9IC0zOwplZ2dzWzRdID0gMzsKZWdnc1s1XSA9IDc7CmVnZ3NbNl0gPSA4ODg7CmVnZ3NbN10gPSA1NTU7CmVnZ3NbOF0gPSAwOwplZ2dzWzldID0gLTI7)
### Explanation
We'll use the following input as an example:
```
spam eggs[4];
eggs[0] = 0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;
```
**Stage 1**
```
\d+];¶.+
] = {
```
Note that there's a trailing space on the first line.
We start by matching a number following by `];` and a linefeed, and then everything up to the last space on the next line. This match can only be found at the end of the first line (due to the `];`). All of this is replaced with `] = {`. That is, it transforms our example input to:
```
spam eggs[] = {0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;
```
**Stage 2**
```
;¶.+=
,
```
Now we match everything from a `;` up to the `=` on the next line and replace with a `,`. This transforms the string to:
```
spam eggs[] = {0, 4, 8, -3;
```
**Stage 3**
```
;
};
```
All that's left is fixing the end and we do this by replacing the only remaining `;` with `};`:
```
spam eggs[] = {0, 4, 8, -3};
```
[Answer]
## Julia, ~~112~~ ~~108~~ 105 Bytes
```
f(s)=string(split(s,'[')[1],"[] = {",join([m[1] for m in [eachmatch(r"= *(-?\d+)",s)...]],", "),"};")
```
**Explanation**
```
string( # build output string
split(s,'[')[1], # get declaration (e.g. spam eggs)
"[] = {", # add [] = {
join( # collect numbers
[m[1] for m in [eachmatch(r"= *(-?\d+)",s)...]], # regex out (signed) numbers
", "), # and join comma separated
"};" # add };
) # close string(
```
Saved bytes by replacing collect(eachmatch()) with [eachmatch()...] and with a shorter regex
[Answer]
## Lua, 121 Bytes.
```
function g(s)print(s:gmatch('.-%[')()..'] = {'..s:gsub('.-\n','',1):gsub('.-([%d.-]+);\n?','%1, '):gsub(',%s+$','};'))end
```
## Explained
```
function g(s)
print( -- Print, Self Explaintry.
s:gmatch('.-%[')()..'] = {' -- Find the 'header', match the first line's class and assignment name (everything up to the 'n]') and append that. Then, append ] = {.
-- In the eggs example, this looks like; 'spam eggs[] = {' now
.. -- concatenate...
s:gsub('.-\n','',1) -- the input, with the first line removed.
:gsub('.-([%d.-]+);\n?','%1, ') -- Then that chunk is searched, quite boringly, a number followed by a semicolon, and the entire string is replaced with an array of those,
-- EG, '1, 2, 3, 4, 5, 6, '
:gsub(',%s+$','};') -- Replace the final ', ' (if any) with a single '};', finishing our terrifying combination
)
end
```
[Answer]
## Batch, 160 bytes
```
@echo off
set/ps=
set s=%s:[=[] = {&rem %
set r=
:l
set t=
set/pt=
if "%t%"=="" echo %r%};&exit/b
set t=%t:* =%
set r=%r%%s%%t:~2,-1%
set s=,
goto l
```
Note: The line `set s=,` ends with a space. Takes input on STDIN. That weird line 3 takes the input (e.g. `int spam[6];` and changes the `[` into `[] = {&rem` resulting in `set s=int spam[] = {&rem 6];` which then gets interpreted as two statements, `set s=int spam[] = {` and `rem 6];`, the latter of which is a comment. Then for each line we delete the text up to the first space (because you can't use `=` in a pattern and the matching is non-greedy) and extract the value.
[Answer]
# C, 121 bytes
```
n=2;main(i){for(;putchar(getchar())^91;);for(printf("] = {");~scanf("%*[^=]%*c%d",&i);n=0)printf(", %d"+n,i);puts("};");}
```
[Answer]
### Python 112 111
Very straightforward to me, please suggest any improvement that comes to mind.
```
def f(l):
a,*b=l.split('\n')
return a[:a.index('[')]+'[] = {'+', '.join(r.split(' = ')[1][:-1]for r in b)+'};'
# TEST
lines = """spam eggs[10];
eggs[0] = 0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;
eggs[4] = 3;
eggs[5] = 7;
eggs[6] = 888;
eggs[7] = 555;
eggs[8] = 0;
eggs[9] = -2;"""
print (f(lines))
assert f(lines) == 'spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};'
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~31~~ ~~30~~ 28 bytes
```
žh-|vy#¤¨ˆ\}¨… = ¯ïžuDÀÀ‡';J
```
**Explanation**
```
žh-¨ # remove numbers and ";" from first input
|v } # for each of the rest of the inputs
y# # split on spaces
¤¨ # take the last element (number) minus the last char (";")
ˆ\ # store in global array and throw the rest of the list away
… = # push the string " = "
¯ï # push global array and convert to int
žuDÀÀ‡ # replace square brackets of array with curly ones
'; # push ";"
J # join everything and display
```
[Try it online!](http://05ab1e.tryitonline.net/#code=xb5oLcKofHZ5I8KkwqjLhlx94oCmID0gwq_Dr8W-dUTDgMOA4oChJztK&input=c3BhbSBlZ2dzWzEwXTsKZWdnc1swXSA9IDA7CmVnZ3NbMV0gPSA0OwplZ2dzWzJdID0gODsKZWdnc1szXSA9IC0zOwplZ2dzWzRdID0gMzsKZWdnc1s1XSA9IDc7CmVnZ3NbNl0gPSA4ODg7CmVnZ3NbN10gPSA1NTU7CmVnZ3NbOF0gPSAwOwplZ2dzWzldID0gLTI7)
Saved a byte thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan)
[Answer]
# Java 7, ~~159~~ ~~158~~ ~~149~~ 154 bytes
```
String c(String[]a){a[0]=a[0].split("\\d")[0]+"] = {\b";for(String i:a)a[0]+=i.split("= [{]*")[1];return a[0].replace(";",", ").replaceFirst("..$","};");}
```
Multiple bytes saved thanks to *@cliffroot*.
**Ungolfed & test code:**
[Try it here.](https://ideone.com/qJ0a4u)
```
class M{
static String c(String[] a){
a[0] = a[0].split("\\d")[0] + "] = {\b";
for(String i : a){
a[0] += i.split("= [{]*")[1];
}
return a[0].replace(";", ", ").replaceFirst("..$", "};");
}
public static void main(String[] a){
System.out.println(c(new String[]{ "spam eggs[10];", "eggs[0] = 0;", "eggs[1] = 4;",
"eggs[2] = 8;", "eggs[3] = -3;", "eggs[4] = 3;", "eggs[5] = 7;", "eggs[6] = 888;",
"eggs[7] = 555;", "eggs[8] = 0;", "eggs[9] = -2;" }));
System.out.println(c(new String[]{ "char ans[2]", "ans[0] = 52;", "ans[1] = 50;" }));
System.out.println(c(new String[]{ "blah_blah quux[1];", "quux[0] = 105;" }));
}
}
```
**Output:**
```
spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};
char ans[] = {52, 50};
blah_blah quux[] = {105};
```
[Answer]
## Perl, 42 + 2 (`-0p`) = 44 bytes
```
s%\d+].*%] = {@{[join",",/(-?\d+);/g]}};%s
```
Needs `-p` and `-0` flags to run. For instance :
```
perl -0pe 's%\d+].*%] = {@{[join",",/(-?\d+);/g]}};%s' <<< "blah_blah quux[1];
quux[0] = 105;"
```
[Answer]
# [jq](https://stedolan.github.io/jq/), 85 bytes
```
./"
"|(.[0]|gsub("\\d|;";""))+" = {"+(.[1:]|map([scan("-?\\d+")][-1])|join(", "))+"}"
```
[Try it online!](https://tio.run/##Vc3NDsIgDAfwu09BeoLMTdiGQ4nxQRgH/Mjiks0Z4kl8dgQSlnjrr@2/HV/eVzvYgMOVotoN9n3B0Pc3J0ECEFIAOqEPFGHMjtpNZsHKXs2MoTyHtQKIViXTxI3PR2huUcp8wXuwi5nQfRisYlTLfk4l1eEezWJRbVYdJbKaqLLJbCNX8agua5@CYo120ZzzbPH39JAO1xJ@ "jq – Try It Online")
I can probably remove the `map`, but not sure how to do it without breaking the thing. Otherwise quite satisfied with the solution.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 33 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ỴḊḲ€Ṫ€K⁾;,yṖ“{“};”j
ỴḢḟØDṖ,⁾ =,ÇK
```
**[TryItOnline](http://jelly.tryitonline.net/#code=4bu04biK4biy4oKs4bmq4oKsS-KBvjsseeG5luKAnHvigJx9O-KAnWoK4bu04bii4bifw5hE4bmWLOKBviA9LMOHSw&input=&args=c3BhbSBlZ2dzWzEwXTsKZWdnc1swXSA9IDA7CmVnZ3NbMV0gPSA0OwplZ2dzWzJdID0gODsKZWdnc1szXSA9IC0zOwplZ2dzWzRdID0gMzsKZWdnc1s1XSA9IDc7CmVnZ3NbNl0gPSA4ODg7CmVnZ3NbN10gPSA1NTU7CmVnZ3NbOF0gPSAwOwplZ2dzWzldID0gLTI7)**
How?
```
ỴḊḲ€Ṫ€K⁾;,yṖ“{“};”j - Link 1, parse and reform the values, same input as the Main link
Ỵ - split on line feeds
Ḋ - dequeue (remove the first line)
Ḳ€ - split each on spaces
Ṫ€ - tail each (get the numbers with trailing ';')
K - join on spaces
⁾;, - ";,"
y - map (replace ';' with ',')
Ṗ - pop (remove the last ',')
“{“};” - list of strings ["{","};"]
j - join (making "{" + "n0, n1, ,n2, ..." + "};")
ỴḢḟØDṖ,⁾ =,ÇK - Main link, takes one argument, the multiline string
Ỵ - split on line feeds
Ḣ - head (just the first line)
ØD - digits yield "0123456789"
ḟ - filter out
Ṗ - pop (remove the trailing ';')
, , - pair
⁾ = - the string " ="
Ç - call the previous Link (1)
K - join on spaces (add the space after the '=')
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 27 bytes
```
Ỵ©ḢḟØDṖ“ = {”®Ḳ€Ṫ€Ṗ€j⁾, ⁾};
```
[Try it online!](http://jelly.tryitonline.net/#code=4bu0wqnhuKLhuJ_DmEThuZbigJwgPSB74oCdwq7huLLigqzhuarigqzhuZbigqxq4oG-LCDigb59Ow&input=&args=c3BhbSBlZ2dzWzEwXTsKZWdnc1swXSA9IDA7CmVnZ3NbMV0gPSA0OwplZ2dzWzJdID0gODsKZWdnc1szXSA9IC0zOwplZ2dzWzRdID0gMzsKZWdnc1s1XSA9IDc7CmVnZ3NbNl0gPSA4ODg7CmVnZ3NbN10gPSA1NTU7CmVnZ3NbOF0gPSAwOwplZ2dzWzldID0gLTI7)
## Explanation
```
Ỵ Split into lines
©Ḣ Take the first one, store the others in ®
ḟØD Remove digits
Ṗ Remove trailing ;
“ = {” Print a literal string
® Recall the remaining lines
Ḳ€ Split each into words
Ṫ€ Keep each last word
Ṗ€ Remove each trailing ;
j⁾, Join by “, ”
⁾}; Literal “};”
```
[Answer]
# sed 51
```
1s,\[.*,[] = {,
:
N
s,\n.*= ,,
s/;/, /
$s/, $/};/
t
```
[Answer]
# Java, 106 bytes
String manipulation in Java is hell, as always.
```
a->a[0].join("",a).replaceAll(";\\w+\\[\\d+\\] = ",", ").replaceAll("\\d+\\], ","] = {").replace(";","};")
```
This is a pure regex answer. Make a single concatenated `String`, then perform `replaceXxx` until it's ok.
## Testing and ungolfed:
```
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<String[], String> f = a ->
String.join("", a) // I think this would join. Not sure, though. Golfed into a[0].join because static members are accessible from instances.
.replaceAll(";\\w+\\[\\d+\\] = ", ", ") // replace with regex
.replaceAll("\\d+\\], ", "] = {") // replace with regex
.replace(";", "};"); // replace no regex
String[] spam = {
"int spam[6];",
"spam[0] = 4;",
"spam[1] = 8;",
"spam[2] = 15;",
"spam[3] = 16;",
"spam[4] = 23;",
"spam[5] = 42;"
};
test(f, spam, "int spam[] = {4, 8, 15, 16, 23, 42};");
String[] eggs = {
"spam eggs[10];",
"eggs[0] = 0;",
"eggs[1] = 4;",
"eggs[2] = 8;",
"eggs[3] = -3;",
"eggs[4] = 3;",
"eggs[5] = 7;",
"eggs[6] = 888;",
"eggs[7] = 555;",
"eggs[8] = 0;",
"eggs[9] = -2;"
};
test(f, eggs, "spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};");
String[] ans = {
"char ans[2];",
"ans[0] = 52;",
"ans[1] = 50;"
};
test(f, ans, "char ans[] = {52, 50};");
String[] quux = {
"blah_blah quux[1];",
"quux[0] = 105;"
};
test(f, quux, "blah_blah quux[] = {105};");
}
static void test(Function<String[], String> f, String[] input, String expected) {
System.out.printf("Result: %s%nExpected: %s%n", f.apply(input), expected);
}
}
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `aṪ`, 28 bytes
```
ḣƛ⌈t⌊;‛, j\{p\}+$kd$FṪ` = `„
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=a%E1%B9%AA&code=%E1%B8%A3%C6%9B%E2%8C%88t%E2%8C%8A%3B%E2%80%9B%2C%20j%5C%7Bp%5C%7D%2B%24kd%24F%E1%B9%AA%60%20%3D%20%60%E2%80%9E&inputs=int%20spam%5B6%5D%3B%0Aspam%5B0%5D%20%3D%204%3B%0Aspam%5B1%5D%20%3D%208%3B%0Aspam%5B2%5D%20%3D%2015%3B%0Aspam%5B3%5D%20%3D%2016%3B%0Aspam%5B4%5D%20%3D%2023%3B%0Aspam%5B5%5D%20%3D%2042%3B&header=&footer=)
```
ḣ # Head extract
ƛ ; # Foreach line except the first
⌈t⌊ # Split on spaces, get the last, parse an int
‛, j\{p\}+ # Join by commas and add {}
$kd$FṪ # Remove digits from line 1
` = `„ # Push a ` = ` and prepare the stack for printing
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-r`, ~~32~~ 30 bytes
```
aRXI.']["] = {"(Z@>g@XI1)Jk'}]
```
[Try it online!](https://tio.run/##K8gs@P8/MSjCU089NlopVsFWoVpJI8rBLt0hwtNQ0ytbvTb2///igsRchdT09OJoQ4NYay4wywCk1gDKMQRxTKAcIxDHAsoxBnF0jaE8ExAPxjEFccyhHDOwJguYNnMQ19TUFMq1QLbMEmykkfV/3SIA "Pip – Try It Online")
### Explanation
The builtin regex for matching integers, `XI == `-?\d+``, came in really handy here.
```
aRXI.']["] = {"(Z@>g@XI1)Jk'}]
g is list of lines from stdin; a is first line (-r flag)
aR In the first line, replace
XI.'] integer followed by closing square bracket, with:
@>g All but the first element in g
@XI Find all (two) integers in each element
Z Zip that list of pairs into a pair of lists
( 1) and take the second list (the values)
Jk Join on ", "
[ ] Put the above string in a list
"] = {" with this string before it
'} and a curly brace after it
(The list is converted to a string when used as a
replacement; since there are no list-formatting flags
in use, its elements are simply concatenated together)
```
[Answer]
## Ruby, 64 bytes
```
->{gets.split(?[)[0]+"[]={"+$<.map{|s|s.scan /\ -?\d+/}*?,+"};"}
```
[Answer]
# JavaScript, 125 bytes
I know it's longer than others, but I really wanted to use `eval`. Just for fun.
```
f=function(s){m=/^(\w+ )(\w+).*?(;.*)/.exec(s)
eval("var "+m[2]+"=new Array()"+m[3]+'alert(m[1]+m[2]+"={"+eval(m[2])+"};")')}
```
To run, paste the following into [here](http://www.webtoolkitonline.com/javascript-tester.html):
```
s='int spam[6];\
spam[0] = 4;\
spam[1] = 8;\
spam[2] = 15;\
spam[3] = 16;\
spam[4] = 23;\
spam[5] = 42;'
f=function(s){m=/^(\w+ )(\w+).*?(;.*)/.exec(s)
eval("var "+m[2]+"=new Array()"+m[3]+'alert(m[1]+m[2]+"={"+eval(m[2])+"};")')}
f(s)
```
[Answer]
## Haxe, 234 bytes
```
function R(L:Array<String>){var S=L[0];var W=S.indexOf(" ");var T=S.substr(0,W),M=S.substring(W+1,S.indexOf("["));var r=[for(i in 1...L.length)L[i].substring(L[i].lastIndexOf(" ")+1,L[i].length-1)].join(', ');return'$T $M[] = {$r};';}
```
Long function names killed this :D
Try the testcases [here](http://try.haxe.org/#c8527)!
[Answer]
# [V](http://github.com/DJMcMayhem/V), ~~25~~, 24 bytes
```
3wC] = {òJd2f $s, òhC};
```
[Try it online!](http://v.tryitonline.net/#code=M3dDXSA9IHsbw7JKZDJmICRzLCDDsmhDfTs&input=aW50IHNwYW1bNl07CnNwYW1bMV0gPSA4OwpzcGFtWzJdID0gMTU7CnNwYW1bM10gPSAxNjsKc3BhbVs0XSA9IDIzOwpzcGFtWzVdID0gNDI7)
This contains an unprintable `<esc>` character, so here is a hexdump:
```
0000000: 3377 435d 203d 207b 1bf2 4a64 3266 2024 3wC] = {..Jd2f $
0000010: 732c 20f2 6843 7d3b s, .hC};
```
Explanation:
```
3w "Move forward 3 words
C <esc> "Delete everything until the end of the line, and enter this text:
] = { "'] = {'
ò ò "Recursively:
J " Join these two lines (which enters a space)
d " Delete everything until you
2f " (f)ind the (2)nd space
$ " Move to the end of this line
s " Delete a character, and enter:
, " ', '
"
h "Move one character to the left
C "Delete everything until the end of the line, and enter this text:
}; "'};'
```
[Answer]
# [Julia 1.0](http://julialang.org/), 81 bytes
```
!s=split(s,"[")[1]*"[] = {"*join([s[1] for s=eachmatch(r"(-*\d+);",s)],", ")*"};"
```
[Try it online!](https://tio.run/##Tc3LCoMwEAXQfb8iziqxEXylWoJfkmYRrK0RXxgLhdJvT41E6G7OhXune/VaJW9rA1OZudcrNhQEEJHIEIREFfpA2E16xMJsGXpMCzJVo@p2UGvd4gVwFN7uZ8KBGiIpUAQkhC8HOy96XPsRB2BmNaDm@dwWYslP@xW77dgjccg9UofSI3OIMq/c6QBzKDwue6k8aoUjY8yz/H923SdTDsT@AA "Julia 1.0 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 80 bytes
```
f x=takeWhile(/='[')x++"[] = {"++drop 2([", "++w|w<-words x,w<"="]>>=init)++"};"
```
[Try it online!](https://tio.run/##fc5LCoMwEAbgfU8RslFRqY@mKhqv0UVwEWrU4BMTUGh7dmskQled1XwD/8w0VLSs67atAiuWtGWPhnfMvGKDGNZq25AUAIMXtO1yHicQmAQ6YNfyXjJ3GedSgNVZMohhkeeYD1xae@iTwq2nfNgHks30KUG1iYn2gNW1IL5fpJej89RyT8NXuGkECrFGqOCGWjelE0gh0rgfofiMRYoIIc3491hyrAzO08cjbvK30i8 "Haskell – Try It Online") Haskell is normally not very good at string-process-y challenges but it does OK here.
## Explanation
`takeWhile(/='[')x` extracts the typename and identifier `"spam eggs"`. Then we append `"[] = {" ++ drop 2 nums ++ "};"`, where `nums` is:
```
[", "++w|w<-words x,w<"="]>>=init
```
The "words" (whitespace-delimited parts) of the input that are lexicographically less than `"="` happen to be all the digit-plus-semicolon parts like `"0;"`. This is because `'-'` < `'0'..'9'` < `'='` < `'a'..'z'`.
The list comprehension says that to each such part, we prepend a comma and space:
```
[", 0;",", 4;",", 8;"]
```
Then `>>=init` (`concatMap init`) concatenates and chops off the semicolons:
```
", 0, 4, 8"
```
After which point `drop 2` gets rid of the initial comma.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 42 bytes 39 bytes
```
+:++:h.z"\d"k" = {"j", "mecd\ t.z\;k"}; // `ecd\ ` takes last word rather than regex replace
+:++:h.z"\d"k" = {"j", "m:d".* "kt.z\;k"};
```
[Try it online!](https://tio.run/##Tc1NCoMwEIbhfU8xzLJpQ/xJjQmeRF0ULEqDIOhGpWePThihu3kW7zfTugwhCCuEHeSGTYceoYIdv/gAHG2H8g7oF7k1zuPPhTBP7xE@fT/XiWrdLV6qPRvFSAg5IyUYRkZ4ZqycdEETCsYrRubKCqLWmmn@n5VxMnUH "Pyth – Try It Online")
## Explanation
```
+:++:h.z"\d"k" = {"j", "m:d".* "kt.z\;k"};
++ // Join the following strings:
:h.z"\d"k // input[0] with regex \d replaced for empty string
" = {" // Literal ` = {`
j", " // Join with `, ` the following:
m:d".* "kt.z // Rest of input, removing everything before the numbers
// Now our string looks like:
// spam eggs[]; = {0;, 4;, 8;, -3;, 3;, 7;, 888;, 555;, 0;, -2;
: [our string] \;k // Remove ';'
+ "}; // Append "};"
```
] |
[Question]
[
# Challenge
## Premise
Bob is a novice pianist who can only play sequences of single notes. In addition, he does quite an interesting thing: for every note after the first, if it's higher than the previous note was, he uses the finger directly to the right of the previous finger used; if lower, to the left; if the same pitch, well, the same finger.
Let's take Auld Lang Syne as an example, and arbitrarily suppose, only for the sake of this example, that Bob uses the very right side of his right hand.
```
Pitch: Should < auld = ac- = quain- < tance > be > for- < got
Digit: mid ring ring ring pinky ring mid ring
```
Alice wants to convince him of the stupidity of his playing...
## Task
Input: a sequence of \$n\$ MIDI note numbers (which are integers between 0 and 127 inclusive), where \$2\leq n\leq10000\$.
Output: the number of fingers required to finish the melody with the playing style outlined in 'Premise'.
Please note that the answer may be more than 5.
No consideration of the starting finger is needed. Assume that the choice is optimal for playable melodies and has nothing (else) to do with the number of fingers required.
### Example 1
Input: `0 0 0 0`
Output: `1`
### Example 2
Input: `43 48 48 48 52 50 48 50`
Output: `3`
### Example 3
Input: `86 88 84 81 83 79 74 76 72 69 71 67 62 64 60 57 59 57 56 55`
Output: `9`
### Example 4
Input: `82 79 78 76 78 76 74 73 70 67 66 64 66 64 62 61`
Output: `12`
# Remarks
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins.
* [Standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/), [I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and [loophole rules](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* If possible, link an online demo of your code.
* Please explain your code.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 27 bytes
```
{+minmax [\+] @_ Z<=>0,|@_}
```
[Try it online!](https://tio.run/##RY/RCoIwFIbvfYoDQRTuYk43J2b4HJmIFwlCRtRNUj37@odnefFx9u@c843dL4@rcdNM24Eqcu94Gm9T/6LmHLdUd3Q6VEcpPnX3dWUUPfuZhl2jMkEr7b6kDSVl6GapoMyuaAUkn@UynYZha4TFvYXJJgC7eQGQcwOwa3xGz@TAZ/QMfBpZF1wxq/XiLv5uxTLLslC93D8kWWpYGqp/JOFvKfcD "Perl 6 – Try It Online")
### Explanation
`@_ Z<=>0,|@_` uses the zip metaoperator (`Z`) with the compare operator (`<=>`) to zip the list with itself offset by 1 and return the result of the comparison., e.g. `[43, 48, 48, 48, 52, 50, 48, 50]` -> `(More More Same Same More Less Less More)`
`[\+]` Reduces the list by summing over it (More = 1, Same = 0, Less = -1), however the `\` does a 'triangular reduction' which produces a list of each calculation instead of the end result, e.g. `(More More Same Same More Less Less More)` -> `(More 2 2 2 3 2 1 2)`
`minmax` returns the range of smallest..largest, effectively removing duplicates. `(More 2 2 2 3 2 1 2)` -> `Order::More..3`
`+` just returns the length of this range (list), which is the result
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
¥.±ŒOÄZ>
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0FK9QxuPTvI/3BJl9/9/tIWZjoKFBRCbALEhEBvrKJhbAjGQbw6UMzfSUTAD8YFyZuZADOID5cwMdBRMgXxTSygNVGtqGgsA "05AB1E – Try It Online")
---
## Explanation
```
¥ - Get the differences
.± - Get the signs of these (so if they go up or down)
ŒO - Sum the sublists of these
ÄZ - And find the biggest absolute change
> - Add one (since we need a finger to play the first note)
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~64 63~~ 57 bytes
*-6 bytes thanks to @xnor's abuse of walrus!*
```
lambda l,t=0,a=0:len({(t:=t+(a<b)-(a>(a:=b)))for b in l})
```
[Try it online!](https://tio.run/##PY7NasMwEITvforBvUjUCf63Euq8SNOD4thEVJGNpFBC8LOnK6UUlmXY@WbY5e4vs6nEYp9Tf3xqeT2dJXTm@zyTfb7Xo2EP5ve9f2fy48Q3TB6Y3Pcnzvk0W5ygDPTKn@q6zNbD3V2SBEMrMwaPDlvnz8rsE@ANdpRnOi83n2GYrR0HD2ncz2gx2fmKiBLpsnBGj6tcmPOWOqxasli7dYtWnqWbQ8o5sZowrZxngVWGmt0fwqP/KiKDkeLxjUFqjelmBq9mQ8AZw2Ucvuk9d9OeEEuJielALzZEp/ShV2wOR/OwKz4fBPShef06mpQ/yxr/szmgSOoKtfibpkSTR5EHs0pECyEgaogCokK3Q1eja9GVaEkXaDu0pGu0OZoOzS7uFk0TCnaJKGNIxNBrUwE15THaxuhrU00RXyp/AQ "Python 3.8 (pre-release) – Try It Online")
A function that takes input `l` as a list of integers, and returns the number of fingers needed.
**How**:
`t` keeps track of the current finger (represented by an integer). For each 2 consecutive notes `a, b`, the finger is increased by `-1`, `0`, or `1` depending on whether `a>b`, `a==b` or `a<b`:
```
t:=t+(a<b)-(a>b)
```
All values of `t` are then gathered into a set, whose size is the number of unique fingers.
[Answer]
# [R](https://www.r-project.org/), ~~45~~ 42 bytes
```
`?`=diff;1+?range(0,cumsum(sign(?scan())))
```
[Try it online!](https://tio.run/##NcQxDoAgEATAr2yJ0UKR3GmM4SsQFGIhBYT3nzZMMUXEWXdeT4zHMtric7rVPIX21vaq@qSsbA0@q@Enmwbv4A1MfQNewTOIQQQyfQ1a5AM "R – Try It Online")
Thanks to JDL for -3 bytes.
[Answer]
# [FRACTRAN](https://en.wikipedia.org/wiki/FRACTRAN) 29 fractions (244 bytes)
```
7*61/2^129*59 3*61/2*59 47/59 59/61 2*53/7*47 31/47 47/53 7*37/2^129*31
17/31 31/37 67/2^128*17 5*19/2*3*17 5*11*23/2*13*17 5*11*23/2*17 13*23/3*11*17
13*23/3*17 41/17 17/19 29/3*23 41/23 23/29 3*43/5*41 3*43/2*41 47/41
41/43 2/67 1/3 2/13 2/11
```
Input: \$59\cdot 2^n\$, where \$n\$ is the MIDI list (terminated in the sentinel 128) in base-129. That is, if the list is \$\{n\_0, n\_1, n\_2, \dots, n\_m\}\$, then
\$n=n\_0 + 129n\_1 + 129^2n\_2 + \cdots + 129^{m}n\_m + 129^{m+1}\cdot 128\$.
Output: \$2^k\$, where \$k\$ is the number of necessary fingers.
---
To try this online, the interpreter at <https://pimlu.github.io/fractran/> is able to evaluate the program relatively quickly, and it takes the program in the following syntax:
```
7*61%2^129*59
3*61%2*59
47%59
59%61
2*53%7*47
31%47
47%53
7*37%2^129*31
17%31
31%37
67%2^128*17
5*19%2*3*17
5*11*23%2*13*17
5*11*23%2*17
13*23%3*11*17
13*23%3*17
41%17
17%19
29%3*23
41%23
23%29
3*43%5*41
3*43%2*41
47%41
41%43
2%67
1%3
2%13
2%11
```
For the four examples, the program accepts this syntax for the input:
```
[59, 1], [2, 35446128768]
[59, 1], [2, 9845790461648320003]
[59, 1], [2, 209150948383325817811492382511176427430698872]
[59, 1], [2, 755543512556056338685630134436248304]
```
These are prime factorizations, saving having to multiply out the gigantic exponentials.
## How does it work?
In FRACTRAN, there is a state, which is initially set to the input value. The state is multiplied by each fraction one at a time, and if any results in a whole number, that number replaces the state and the program returns to the beginning of the list. If no fractions apply in this way, then the state is output and the program halts.
This is a terse way of describing a register machine. By prime factorizing everything, a fraction like 75/7 = 3\*5^2/7 means "if register seven is at least 1, then decrement it and add 1 to register three and 2 to register five."
Each prime in the program can be given a descriptive name, like 3 is 'a' and 59 is 'line1'. The rest don't particularly matter, since I'll give a disassembled version of the program, and you could figure out the rest of the assignments if you really wanted. Each line is like a chemical reaction; for example, the first line means "if line1 >= 1 and a >= 129, then decrement line1 by 1, decrement a by 129, increment line1r by 1, and increment adiv1 by 1."
```
0. line1 + 129 a -> line1r + adiv
1. line1 + a -> line1r + b
2. line1 -> line3
3. line1r -> line1
4. line3 + adiv -> line3r + a
5. line3 -> line4
6. line3r -> line3
7. line4 + 129 a -> line4r + adiv
8. line4 -> line5
9. line4r -> line4
10. line5 + 128 a -> line8
11. line5 + a + b -> line5r + c
12. line5 + a + MAX -> line6 + c + MIN
13. line5 + a -> line6 + c + MIN
14. line5 + b + MIN -> line6 + MAX
15. line5 + b -> line6 + MAX
16. line5 -> line7
17. line5r -> line5
18. line6 + b -> line6r
19. line6 -> line7
20. line6r -> line6
21. line7 + c -> line7r + b
22. line7 + a -> line7r + b
23. line7 -> line3
24. line7r -> line7
25. line8 -> a
26. b -> 0
27. MAX -> a
28. MIN -> a
```
So, here's an analysis. At the beginning, the input is `line1 + n a`. This means, the first relevant part of the program is
```
0. line1 + 129 a -> line1r + adiv
1. line1 + a -> line1r + b
2. line1 -> line3
3. line1r -> line1
```
which reduces the a register mod 129, putting the quotient in adiv and the remainder into b, which serves as a register to hold the previous MIDI note, which in this case is the very first one. Once this is done, it continues onto
```
4. line3 + adiv -> line3r + a
5. line3 -> line4
6. line3r -> line3
```
which moves adiv back into the a register, and for the main loop the a register starts with the remaining part of the MIDI list. Then,
```
7. line4 + 129 a -> line4r + adiv
8. line4 -> line5
9. line4r -> line4
```
The MIDI list is reduced mod 129, putting the rest of the list into adiv, leaving the MIDI note in the a register. This continues on to the the core calculation loop.
```
10. line5 + 128 a -> line8
11. line5 + a + b -> line5r + c
12. line5 + a + MAX -> line6 + c + MIN
13. line5 + a -> line6 + c + MIN
14. line5 + b + MIN -> line6 + MAX
15. line5 + b -> line6 + MAX
16. line5 -> line7
17. line5r -> line5
```
Reaction 10 detects if the sentinel 128 has occured, in which case it goes to line8 (the cleanup routine). Otherwise, we begin the comparison of a with b, to see which is larger. There are two registers MAX and MIN, representing the maximum and minimum relative finger numbers relative to note b so far. If a is greater than b, then we need to decrement MAX and increment MIN; if MAX is zero, then we don't decrement it, since this has the effect of widening the necessary number of fingers. Similarly, if b is greater than a, we need to decrement MIN (if nonzero) and increment MAX.
The comparison works by decrementing both a and b until one of them is zero. We will need the a register later on, to store it back into b, so whenever we decrement a, we increment a temporary variable c. Reaction 11 decrements a and b if they are both nonzero. Past this point, we know either b=0 or a=0. Reactions 12 and 13 are for the b=0 case, implementing the decrement-MAX-if-nonzero operation, and reactions 14 and 15 are for a=0. Reaction 16 is when a and be were equal.
If a and b were unequal in some way, then b is zeroed out with the following block
```
18. line6 + b -> line6r
19. line6 -> line7
20. line6r -> line6
```
And, along with the a=b case, this continues on to
```
21. line7 + c -> line7r + b
22. line7 + a -> line7r + b
23. line7 -> line3
24. line7r -> line7
```
which stores a+c into b, clearing a and c in the process. This has the effect of copying the original value of a at the start of the main loop into b. From here, we return to line3 to set up the main loop.
At the very end, once the sentinel is detected, the following block is run.
```
25. line8 -> a
26. b -> 0
27. MAX -> a
28. MIN -> a
```
Since the sentinel detection subtracts 128 from a, we know a is zero when entering this block. Then, the value of 1 + MAX + MIN is stored into a, and the value of b is cleared out. Once done, no other reactions apply, and the program terminates with the number of necessary fingers in the a register.
[Answer]
# JavaScript (ES6), ~~55 53~~ 52 bytes
```
a=>a.map(o=v=>o[i+=-(a>v)|a<(a=v)]=n+=!o[i],i=n=0)|n
```
[Try it online!](https://tio.run/##bczNCsIwEATgu2/hLcGxpDF/gtsXkR5CrVKpiVjJqe9eQ9SLCMswMMt39clP3WO4P7chnvrlTIunxlc3f2eREjXxOGxoy3yT@OwPzFPiLYUNrfPQYqBAgs9h6WKY4thXY7ywMztKhe@1nK9@VrWDcp/TElqUIv58OgPn4BRcDbeD3cMqWAMrYXKvYSxM7gpGQFvofUkDrf9psgiuCO/MWmZFcUxx3pnNOgvLCw "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array of notes, re-used to store
a.map( // the previous finger index
o = // o = object used to store the fingers
v => // for each note v in a[]:
o[ // update o[i]:
i += // update i:
-(a > v) | // decrement i if the previous value is greater than v
a < (a = v) // increment i if it's lower than v; and update a to v
] = // (if a = v or a is non-numeric, i is left unchanged)
n += !o[i], // mark this finger as used and increment n if it was
// not already used
i = n = 0 // start with i = n = 0
) | n // end of map(); return n
```
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=uniq -pa`, 35 bytes
```
$_=uniq map{$c+=$_<=>$p;$p=$_;$c}@F
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3rY0L7NQITexoFolWdtWJd7G1k6lwFqlAMi0VkmudXD7/9/CSMHcUsHcQsHcDEaaKJgbK5gbKJiZK5iZKZiZwEgjBTPDf/kFJZn5ecX/dX1N9QwMDYC0T2ZxiZVVaElmDti6/7oFiQA "Perl 5 – Try It Online")
[Answer]
# [Io](http://iolanguage.org/), ~~107~~ 105 bytes
-2 bytes after using "push" instead of "append".
```
method(x,(r :=x slice(0,-1)map(i,v,(v-x at(i+1))compare(0)))map(i,v,r slice(0,i+1)sum)push(0)unique size)
```
[Try it online!](https://tio.run/##bY3NDoIwEITvPsUeu7EmgLRUE9/ECyqJTfipFAzx5XFqClw8TLbTnf3GdvOtfDg6X@g6N9Xw7B5ikqLHx0S@tvdKJPKQclM6YeVbivdhonIQdp8y37vGlT0SzGugX69CxI8Nu9E/ERlb@xor8vZT8a9T1NYPIsslbWIm19t2qNvdFsmPknKzSWVQEt/J3xOjJRmsDagmhYAoThB8gV0BhA4eO11AwWOngVXw6hQnskr9r8gi0kTkMkNFqEsiWkf0MkNVuiHnLw "Io – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~53~~ 46 bytes
```
Tr[1^{0}~Union~Accumulate@Sign@Differences@#]&
```
[Try it online!](https://tio.run/##VY3LCsIwEEX3fkVBcNVFWptHF0IEP0BQV6VCCIkGbISarkr763ECU6WQy82dx5lOhafpVHBaRXuI174p7iOZ5pt3bz8ftR664aWCkRf38PLkrDW98dp85LbdxXPvfJC2GUme4Zvaza9a7fOsEn/REkTwv5oULM8EVEUFKkCwyWsQZA49DpssZegxDkoZegxoFDKt0WGW0hW5RJJA0uKJnK4QJDIkLp4uFFMbvw "Wolfram Language (Mathematica) – Try It Online")
Thanks to @J42161217 for pointing out that `Tr[1^list]` is a 1-character-shorter alternative to `Length@list`.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 76 bytes
```
\d+
*_:$&*
+`_=_
=
=_
<
_=
>
[_:=]
Lw$`(.)(?>(\1)|(?<-2>.))*
_$#2*
O^`
1G`
```
[Try it online!](https://tio.run/##NYw9C8IwGIT391ccWCWtWJo0H69i6ugiuLhZTQQdXBxEcPG/15AqHA833HPP2@v@uMhhKg4R0Q/9dU5VWBWziuYx@ECeEtYUPHV0DCt/Itq9iyjqUmw60cvyIzbrherqsqwoFBNV0f4cSW4jDYPS@Id0C82/GAXT5NIQWzCDNViCW7glnIazcAo2dQnrYFPXsA2Mg1lmWhhDrPKe835kctNJky2brZHpQX4B "Retina – Try It Online") Link includes test suite. Takes input as a `=`-separated list of integers (I could have used space or `,` but `=` was prettier) but the test suite adapts the space-separated test cases to work with the code. Explanation:
```
\d+
*_:$&*
```
Convert each integer to unary in duplicate.
```
+`_=_
=
```
Subtract pairs of adjacent integers.
```
=_
<
_=
>
```
Note whether adjacent integers were ascending or descending.
```
[_:=]
```
Delete everything else.
```
Lw$`(.)(?>(\1)|(?<-2>.))*
_$#2*
```
Find runs of notes. Runs can be interrupted by a reverse run as long as the run does not return to its starting finger; this is achieved via the .NET regexp balancing group construct `(?<-2>.)`. The run always starts with an ascending or descending pair which requires two fingers; since one finger is added at the end to handle the degenerate case where only one note is played, only one finger is added here, resulting in the number of additional fingers required for this run. The `w` modifier allows all valid runs to be collected.
```
O^`
```
Sort the longest number of fingers to the start.
```
1G`
```
Consider only the longest number of fingers. (I would count the longest fingers using `\G.?` but that doesn't work for some reason.)
```
```
Convert back to decimal and add one for the starting finger.
[Answer]
# [Husk](https://github.com/barbuz/Husk/wiki/Commands), 11 [bytes](https://github.com/barbuz/Husk/wiki/Codepage)
```
→▲mamΣQm±Ẋ-
```
Port of [*@ExpiredData*'s 05AB1E answer](https://codegolf.stackexchange.com/a/203742/52210), so make sure to upvote him!
[Try it online.](https://tio.run/##yygtzv7//1HbpEfTNuUm5p5bHJh7aOPDXV26////j7Yw07Gw0LEw0bEw1LEw1jG31DE30TE30zE30jEDsg11zMx1zIBsEx0zAx1Tcx1TSzBppmNqGgsA)
**Explanation:**
```
Ẋ # For each overlapping pair of the (implicit) argument:
- # Subtract them from one another
m # Then map over each forward difference:
± # And take its signum (-1 if <0; 0 if 0; 1 if >0)
Q # Get all sublists of those
m # Map over each sublist:
Σ # And take its sum
m # Map over each sum:
a # And take its absolute value
▲ # Then take the maximum of this list
→ # Increase it by 1
# (after which it is output implicitly as result)
```
[Answer]
# [C#], 86 bytes
```
s.Aggregate(0,(i,y)=>{var t=z>y?++i:z<y?--i:i;h[i]=1;z=y;return t;});return h.Count();
```
[Try It online!](https://tio.run/##bVDBaoNAEL37FYP0oGQjxkRjYkwoKYWWQg899JDmILLVhbCGdW0x4rfb2bg2Fgo@Z2bnvTe7k5bTtGTdVyKA8XMlZxADp9@HIzQQBgTCELFAzBBzAssVAusl9pYegUDV2AuWCFVjL3AJ@Fj7Kx2R6/vQRsbvGG88xtO2obYdohqjRrraPtD2Q1TjZn9s5yPbBUoX4Q0@0n1X5@4f2WIk89D5BkW78coRr98W0c/RcU4Gw0F37iXwwFLJCp6IesO4VDS5tez@DhVy3D4Vmv5Y8VQRD0fyn/L61yZWSSAncLEh3oLRdKVzn2WCZomklkssRmo73jbKXMaXbb2bTNj6sql30ylbsyg/sGM8iy5xHQkqK8FBRq095LmzLyou8aIdHhqfhaBJmlt6IQi9F9toDICzsz/RRKhnwfAogH3By@JEnXfBJH1hnFp35pNSrQGaNykYz5zngnHLJGBe92e3H/y1kldKA8LCIwL4VTZgx0T7tvsB)
My goal was to do this using the Linq Aggregate function, but surely not the best way.
[Answer]
# [J](http://jsoftware.com/), ~~36~~ 18 bytes
Bubbler managed to shave off a full 50% off my program with a few nice tricks and some deft handling of trains.
```
0#@=@(,+/\)2*@-/\]
```
[Try it online!](https://tio.run/##jY3NCsIwEITvPsWgoIlt0yTNn0ElKHgSD16t1x58hz573aYqCB6E3WFg5tt9DHOBVYddxAolJCJtJXC8nk@DXKRdYmVRt1yvU1W394HPLgcBxYq9qKutqLksb5EKr3xKY8HecWLfBf6rsSxJxy@J/VnrBaMi7yMfOmjzmVkH08CE11gNK7ORlASHEBAMgkJo4DfwBt7BazjyCs7DkTdwEtbDbrI6WDvSOhMhE5MSTWdk5lzmJqUb6gk "J – Try It Online")
The dyadic verb `*@-/\` takes a prefix size and a list, then computes the sign of the difference of the list (from inserting `-` between elements of the list). In this case, it is used as `2 *@-/\ ]`, which is a fork that takes a list and gives a list of the signs of differences between adjacent elements. (This is an idiom I hoped would exist but couldn't come up with myself.)
Letting `d` denote this result, the rest of the train is `0 #@=@(, +/\) d`, which is equivalent to `# = (0 , +/\ d)`. First, `+/\ d` computes the sum of each prefix of `d`, which like in the previous answer gives a relative finger numbering of all notes of the song. But, since the differences only give relative differences, the fingering of the first note is not present, so zero is prefixed to the list with the `,` dyad.
For some reason I thought I had to take one more than the difference of the maximum and minimum values of this array to count the number of necessary fingers, despite the fact all I had to do was count the number of distinct elements, which would be `# ~.` of the array. However, J has a one-character shorter idiom for this. The `=` monad gives an array with one row per unique element (the rows indicating where that element appears), and the `#` monad counts the number of rows, hence the number of necessary fingers.
---
The original 36-byte solution:
```
1:+(>./-<./)@(0&,)@(+/\)@(}.(*@-)}:)
```
[Try it online!](https://tio.run/##PYzBCsIwEETvfsXgwTa2TZM02WyDSkHw5Klnzzn4D/32uKYizD4GljfvctRoMq4JDXoYJLlB474@H8Wmrr3pcbjoUS2tOfXCbnwJN92el0FtSRVVMpz/55DhJ3j@JTgEU4uRDxOYwR5swRPijOgRCdGBpFtQBEn3IIMQEeZKQghf21WDq7FTbJkx1aPq7ZQN@wE "J – Try It Online")
This is a monadic verb that takes a list of numbers.
`*@-` takes the sign of the difference of two numbers. Since `}.` and `}:` cut off the head and tail of a list, the fork `}. (*@-) }:` constructs a list of signs of differences between consecutive elements of the given list.
This is composed with `+/\`, which takes the sums of the prefixes of the list, giving relative finger numbers through the song. This is prefixed with 0 using `0&,` since the song starts with some finger.
This is composed with `>./ - <./`, which takes the difference of the maximum and the minimum of these relative finger numbers, and then the `1:+` fixes a fencepost error: we start counting fingers from 1.
[Answer]
# [PHP](https://php.net/), ~~66~~ 59 bytes
```
for(;$b=$argv[++$i];$a=$b)$f[$n+=$b<=>$a]=1;echo count($f);
```
[Try it online!](https://tio.run/##HcZBDsIgEAXQq7iYRRs2ojAzDUUP0nRBG7FuCmnU63@Jm5dXt4rxXpu5HF2gJVI6nt/JGHrNgVKkpac80W7axnijNEcbHutWTmv57O@Och8AKEMV6qAWeoUMEAdhyAXcbsECbnfgM7zAD38Z3v8A "PHP – Try It Online")
Pretty straightforward: uses a index counter `$n` which is incremented each time a superior note is to play and decremented when a lower note, with the PHP comparison operator `<=>`. Then an array is set to the value `1` at this index. At the end count the array.
EDIT: saved 7 bytes removing the test on `$i`, we actually don't care if the starting value for `$n` is `0` or `1`
[Answer]
# [T-SQL](https://www.microsoft.com/sql-server), 125 bytes
Input is taken from table `T` (according to the [Code Golf rules for SQL](https://codegolf.meta.stackexchange.com/a/5341/78876)): column `P` represents position and column `V` represents the value.
```
SELECT MAX(S)-MIN(S)+1FROM(SELECT*,SUM(ISNULL(X,0))OVER(ORDER BY P)S FROM(SELECT*,SIGN(V-LAG(V)OVER(ORDER BY P))X FROM T)A)B
```
[DB Fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=536abbf32ea54146f0a13e99434ac400)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Port of [Expired Data's solution](https://codegolf.stackexchange.com/a/203742/58974).
```
äÎãx rÔÄ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=5M7jeCBy1MQ&input=Wzg2LCA4OCwgODQsIDgxLCA4MywgNzksIDc0LCA3NiwgNzIsIDY5LCA3MSwgNjcsIDYyLCA2NCwgNjAsIDU3LCA1OSwgNTcsIDU2LCA1NV0)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
£→▓J←εm@φ┤»
```
[Run and debug it](https://staxlang.xyz/#p=9c1ab24a1bee6d40edb4af&i=[0+0+0+0]%0A[43+48+48+48+52+50+48+50]%0A[86+88+84+81+83+79+74+76+72+69+71+67+62+64+60+57+59+57+56+55]%0A[82+79+78+76+78+76+74+73+70+67+66+64+66+64+62+61]&a=1&m=2)
Unpacked, ungolfed, and commented, it looks like this.
```
input:[43 48 48 48 52 50 48 50]
:- get pairwise differences main:[5, 0, 0, 4, -2, -2, 2]
Z+ prepend a 0 main:[0, 5, 0, 0, 4, -2, -2, 2]
{:+m map: numeric sign main:[0, 1, 0, 0, 1, -1, -1, 1]
:+ prefix sums main:[0, 1, 1, 1, 2, 1, 0, 1]
:s^ max - min + 1 main:3
```
[Run this one](https://staxlang.xyz/#c=++++%09++++++++++++++++++++++++%09input%3A[43+48+48+48+52+50+48+50]%0A%3A-++%09get+pairwise+differences%09main%3A[5,+0,+0,+4,+-2,+-2,+2]+%0AZ%2B++%09prepend+a+0+++++++++++++%09main%3A[0,+5,+0,+0,+4,+-2,+-2,+2]+%0A%7B%3A%2Bm%09map%3A+numeric+sign+++++++%09main%3A[0,+1,+0,+0,+1,+-1,+-1,+1]+%0A%3A%2B++%09prefix+sums+++++++++++++%09main%3A[0,+1,+1,+1,+2,+1,+0,+1]+%0A%3As%5E+%09max+-+min+%2B+1+++++++++++%09main%3A3+%0A&i=[0+0+0+0]%0A[43+48+48+48+52+50+48+50]%0A[86+88+84+81+83+79+74+76+72+69+71+67+62+64+60+57+59+57+56+55]%0A[82+79+78+76+78+76+74+73+70+67+66+64+66+64+62+61]&a=1&m=2)
] |
[Question]
[
(Note: This is my first ever code golf question, but as far as I can tell, nobody else has done exactly this, so I should be good.)
Your task is to make a program or function that takes in a string `s` and an integer `n`, and returns or outputs that text wrapped into multiple lines. Each word must be wholly on a line; i.e. no words split in the middle. Each line can be no longer than `n` characters long, and you must fit as many words as possible on each line.
Example:
```
s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
n = 50
output:
Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Sed eget erat lectus. Morbi mi mi, fringilla
sed suscipit ullamcorper, tristique at mauris.
Morbi non commodo nibh. Pellentesque habitant
morbi tristique senectus et netus et malesuada
fames ac turpis egestas. Sed at iaculis mauris.
Praesent a sem augue. Nulla lectus sapien, auctor
nec pharetra eu, tincidunt ac diam. Sed ligula
arcu, aliquam quis velit aliquam, dictum varius
erat.
```
Your output can be an array of strings or a single string with line breaks. Also, you can assume no words will be longer than `n`, so don't worry about dealing with weird cases.
Standard I/O rules apply, and standard loopholes are prohibited. Trailing spaces are allowed.
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortes solution in bytes wins.
[Here](https://tio.run/##jVPbitwwDH3PV4h5SiCEQulLof2Ctiz0sS2LxlYSLbbs9WW3/fqpnGQ6vbDQEEKsy9E5Rzj@KGuQ15eLpRmeE8b7Qt9L3z4jOJKlrMPbDvR5DslmeActNeXouPQnOA1bzrFQy335th1NTYmk3LfwHt3Cc0gbCrDsaDvw3x0Txkhi@1Yy/KrgudFpI6eHwNL/3jEM8P4ge4P8BzaG2A9/pDfa13EvIL@I14Q1ioe4/8baPolKTbI3dV2z7vQhJPLAMVcPNjj1KnMB9KSLMEEymdKaAC1HzoZlAdIlTPCZLNBCBShhURtMqXmCjyGdGXx7R5iTlrNzCFmLc9X2qOBVI96EFCmNUBLnwo@VQFE8Vj1eUSSIUvA@2ADC53WCO3Lqd6Hc6lc8c0HRrq36BpRJNjag5ISOH4@OckWLMKu4DGhAZamkJiIXzLsiJcFoqtP4lcxdQlJINUWRPWBdKk3wqak4ZEPGyCSj5kxRB3U8xBXV7YRAVUWyGLa1YRiwjH4f5nipCoLJaA06JY8eHqvOfmoeX0OjtugYD0@YuKlRw6cTdKL7e/Oq66LarLfiqxzbv92nPIIMw3C5/AQ "Python 3 – Try It Online") is an example program in Python that would work.
[Answer]
# [Python 2](https://docs.python.org/2/), 26 bytes
```
from textwrap import*
fill
```
[Try it online!](https://tio.run/##VZDNSgRBDITv@xR1dGUYVPDoG6gIHkUk25OZDfSf6fSqT79mdBcR@pBOV1fqS/2yfck3x@OsJcH40z6UKiTVona5mSXG44w7rMWmqmTDfKH08Sa5drvYDnj5dzsVry/Xr9vjfVFOkNp6wlRiUTQxUGIbEEpuHIytK2iSKi1IXsBRbMQzT@CFDaxkiK7rbcRD0Z0grWfA7FkWD0VoLm7dv1c3795JoWhlHWAqzeS9M9wlUffr2SWX7BFSKlNBlt1@xBPHyNm4rfo97cTIYdOP@s@ocf5JAw@X@VQkitw6TYTZ4RoowLEcaYVoRu2XyEMIhR69fw7zpMRu6Utx5wTqS@cRjyvFCRuNqnAe/C2Yb9DHo@5J2ZTA3SElB5n66hEwCaXfYVGW7iakwTUUPTwlvHeffVh3fG4N/sXHJBxIZaXxhY@bze3VNw "Python 2 – Try It Online\"oXcyiLN1FSIPPUPTwlHDq7v217fjWGvyL2yR8kcpG4wsf73YvT38 \"Python 2 – Try It Online")
Meh... built-ins are boring... instead, have a nice 87-byte solution here:
```
s,n=input()
x=''
for i in s.split():c=n<len(x+i);exec'print x'*c;x=x*-~-c+i+' '
print x
```
[Try it online!](https://tio.run/##RZDNTsMwEITvfYoRlwBNI4TEBegbAELiCbbONl3Jf3jtKlx49bKBVkg5OOvxzHybv@ohxfvTSfu4lZhbvb5ZzduuW@1TgUAidNDsxeaPbhufPcfreS03Tzyz63KRWDF3t@5p3s63m@@NW8u6Q7c635xOVy@pcIBkbQFj8marUkGBaw@XorKrXFsBjZJFncQJbHkDPngET1zBhSq86ZoOeE1lJwjL12NvKZN4T1ATa7Pn2cybTYJLJXPpUYtolc/GMJdAzX4vLjFFqxBCGhOi7A4D3tkbYWVd9AfaSSXDCL/qfyPl@NsGVi7y@RDIszYaCXuDU5CDYRnSAqGV9I/ISgi55m1@KfNeiM3SlmLOAdSmxgPeFoozNpSycOztzlXboMUjH6hwLQRuBinRydgWD4dRKPyFeZmamVBxpiFv5Sngs1n2cdnxZdTbE4sJOFKRhcYWPlz1eLj7AQ "Python 2 – Try It Online")
Outputs trailing spaces.
[Answer]
# [PHP](https://php.net/), 8 bytes
Admittedly not the most original solution, but PHP has a native function that matches your requirements perfectly!
## [`wordwrap`](http://php.net/manual/en/function.wordwrap.php):
>
> `string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = FALSE ]]] )`
>
>
> Wraps a string to a given number of characters using a string break character.
>
>
>
Use like so:
```
$str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.";
echo wordwrap($str, 50);
```
Or [Try it online!](https://tio.run/##RZFLbsMwDET3OcUg6KIFDKObrtKiF2iLAD0BIzM2Af1CScnxXSofFPBCpobDeVRe8rq@f@Ylb55KVXxg@5WUAySXFjAlnxRFKihwHeBSLOwq16agSbIUJ3EGe6kjfnkCz1zBShXedK2M@E56EIT@DTiqycV7QjFxadaezbxZJbikmXVAVSlVTo1hLoGa/T5cYooWIYQ0JUQ5LCP27D3HyqXrFzpIpWhdV/W/UeF4TQMLF/l@COS5NJoIR4MrIAfDMqQOUSqVG5GFEHLNW/0RZq/EZmlLMecAanPjET@d4o6NQlk4Dnbnqm3QxiMvpFyVwM0gJTqZWvdwmITCbZiXuZkJqTMNeQtPAadms899x4/SYC02JuBMKp3GFj5udxt2S8Il6XRRys/9QQe8vb7s1vUP "PHP – Try It Online")
[Answer]
# JavaScript (ES6), ~~75 73~~ 72 bytes
Takes input as `(string)(n)`.
```
s=>n=>s.split` `.map(w=>r=(u=r?r+' '+w:w)[n]?(o+=r+`
`,w):u,o=r='')&&o+r
```
[Try it online!](https://tio.run/##RZBNbhsxDIX3PQWRRTyDmQyyySaAnAu0gYEuiwKmNfSYgf5MSvbxXU4So4AWEvX4@D5@4AXVC5f6lPJMt6O7qdsmt9VJS@C6h/0UsXRXtxXXNSdvMmxgM1xfr/2f9Pety4OTYf9jP1771zZmJ26z6R8f8yA3n5PmQFPIS3fsHn5moQhctEWYc8gCyhUwUh1hlZKvVJsAzlxYPacFyBJM8JtmoIUqkGCFYLqmE/zKcmCI6xnhKCbnEBDUxNqsvZh5s0r0WQrJCFVYK58bgblEbPa8u6ScLEKMec6Q@HCaYEchUKqkq/6EB66YrOtT/d9IKX2mAQuX6PsSMZA2nBGOBqeAHgzLkFYIrahfRBaC0bdg9XuYnSCZpS3FnCNgWxpN8L5SfGODYmFKo/35ahu08VBOKFQFgZpBcvI8t9XDw8wYv4YFXpqZoHjTYLDwGOHcbPZl3fG9NFqLjYlwQeGVxhY@PfTdy3Pf3/4B "JavaScript (Node.js) – Try It Online")
### Variables
The formatted output is stored in \$o\$ (in green below).
The updated line \$u\$ is defined as the concatenation of:
* the current line \$r\$ (in black below)
* a space if \$r\$ is not empty, or nothing otherwise (in orange below)
* the new word \$w\$ (in blue below)
We need to insert a line break whenever the \$n\$-th character of \$u\$ is set (0-indexed, in red below).
### Example
\$n=16\$ and \$s\$ = "LOREM IPSUM DOLOR"
Adding "LOREM":
$$\small\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
\hline
00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&\color{red}{16}\\ \hline
\color{blue}L&\color{blue}O&\color{blue}R&\color{blue}E&\color{blue}M&&&&&&&&&&&&\\ \hline\end{array}
$$
Adding "IPSUM":
$$\small\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
\hline
00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&\color{red}{16}\\ \hline
L&O&R&E&M&\color{orange}\bullet&\color{blue}I&\color{blue}P&\color{blue}S&\color{blue}U&\color{blue}M&&&&&&\\ \hline\end{array}
$$
Adding "DOLOR":
$$\small\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
\hline
00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&\color{red}{16}\\ \hline
L&O&R&E&M&\bullet&I&P&S&U&M&\color{orange}\bullet&\color{blue}D&\color{blue}O&\color{blue}L&\color{blue}O&\color{blue}R\\ \hline\end{array}
$$
$$\small\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
\hline
00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&\color{red}{16}\\ \hline
\color{green}L&\color{green}O&\color{green}R&\color{green}E&\color{green}M&\color{green}\bullet&\color{green}I&\color{green}P&\color{green}S&\color{green}U&\color{green}M&\color{green}\hookleftarrow&&&&&\\ \hline
D&O&L&O&R&&&&&&&&&&&&\\ \hline\end{array}
$$
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~46~~ 29 bytes
```
{;*.comb(/.**{1..$_}[\s|$]/)}
```
[Try it online!](https://tio.run/##RZDNSkMxEIVf5VBE2nKJutCN2CdQKbhUkWnutB3IzzWTFIr67HVuaxGySCZnzpxvBi7h7hD3uFzjAYev@7nzOa6mV24@/7px7uLj5/VNvy/er2Y/h/X09no2nTzmwhEyaIvoc8gFKhUUuXbwOSn7yrUVUC@DqJe0AQepDi/cgzdcwYUqgumaOjzlshLE8XRYF5NLCAQ1sTZrH8y8WSX6XAYuHWoRrfLZGOYSqdnz7JJysggx5j4jyWrrsOQQOFXWUb@llVRK1nVU/xspp2MaWLjEf5dIgbVRT1gbnII8DMuQRgitpCciCyHkW7D6OcyyEJulLcWcI6htGjs8jxR/2FAahFNnf77aBm08hi0VroXAzSAleenb6OHRC8XTsCCbZiZUvGkoWHiK@Gw2ezfu@FzqrMXGROyoyEhjC3eT2WLhlPaHXw "Perl 6 – Try It Online")
Regex based solution that takes input curried, like `f(n)(s)` and returns a list of lines. Each line except the last has a trailing whitespace
### Explanation:
```
{;* } # Anonymous code block that returns a Whatever lambda
.comb(/ /) # Split the string by
.**{1..$_} # Up to n characters
[\s|$] # Terminated by a whitespace char or the end of the string
```
[Answer]
# Vim, 15 bytes/keystrokes
```
DJ:se tw=<C-r>"
gq_
```
A text formatting question? I know just the tool for the job! And it even has my name in the first two keystrokes :D
`<C-r>` means `ctrl-r`.
This could [*ever* so slightly shorter in V](https://tio.run/##RZBLTsRADET3LDlBHSCK2LBB4gaARuIAyNPxZCz1J9O2w/GDMx8h9aLbXS7X87ptb8qw3/dnepovP9v20ToXyKJeMLXcOlQMVNgGpFaVk7F5B02yiCapMziLjfjmCTyzgTsZcuhcR3y2fhSU/Qw49ZBLzgQNsXq0L2HuUSmp9YX7AOuiJhdnhEshj@fDpbYaEUppU0OV43nEgXPmaqy7/kxHMarRdVX/GynXaxpEuMr3S6HM6jQRTgGnoITACqQdQo30RhQhhJLnqD/CHDpxWMZSwrmAfHYe8bVT3LGhtAjXIf6SxQZjPJYzdbZOYA9IqUkm3z0SJqFyG5Zl9jChnkJDOcJTwcVj9rrv@FEaoiXGFKzUZaeJhY/b68sf "V – Try It Online"), but I prefer answering in vanilla vim for answers that really show off how concise vim can be for the right challenge. And the difference is so small anyway.
This could also be the following for 15 bytes as well:
```
:se tw=<C-r><C-w>
ddgq_
```
[Try it online!](https://tio.run/##RZBLbsMwDET3OcUcwDG66aZos@m2LQL0AAUjsQ4BfRxSSo7v0vmggCFY1HA4j@dleTFGu7y9vm9158dlt4lxOv0sy/PT5qMqZ8hsPSPWVBUmDZS5DQi1GIfGrSsoyiwWpEzgJG3EN0fwxA2s1JBc123EZ9WDIK/fgF91uaREMBdb9/bZzbtXcqg6sw5oKtbk1Bnukqn79eFSavEIOddYUeRwHLHnlLg0tlV/pIM0Kt51Vf8bGZdrGni4wvefTImtUyT8OpyBAhzLkVYIa2Q3Ig8hFHry@iPMXond0pfizhnUp84jvlaKOzaMZuEy@FtovkEfj/lIyk0J3B1SSpDYV4@AKJRvw5JM3U1Ig2soeXjKOHWffV53/CgN3uJjMs6kstL4wsdle/4D "V – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~36~~ 27 bytes
R has this as a built-in (`strwrap`), we return a vector of split lines.
```
function(s,n)strwrap(s,n+1)
```
[Try it online!](https://tio.run/##RZFNTsNADIX3PcUTKypCBAt2cANAlTiBO3FaS/OT2jPl@MHTHyFlMfE8P7/Po@v8/rzOLYcqJT/akLdW9Vdp6een1@1q@MDDZ1FOkMVawlRiUZhUUOI6IJRsHCrXpqBJFrEg@QCOUkf88AQ@cAUrVUTXNRvxVXQvSP0bMKvLJUaCudiaty9u3rySQtGFdUBVsSqnxnCXRM1/7y65ZI@QUpkKsuyPI3YcI@fK1vVH2kul7F0X9b@Rcb6kgYfLfDskimyNJsLscAYKcCxH6hBWya5EHkIotOj1e5idErulL8WdE6gdGo/47hQ3bBgtwnnwu1B9gz4ey5GUqxK4OaTkIFPrHgGTULoOi3JobkIaXEPRw1PCqfnsc9/xvTR4i49JOJNKp/GFjw/YZH@/t5fNZr487voH "R – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 70 bytes
```
s!n|length s<=n=[s]|(t,_:d)<-splitAt(until((<'!').(s!!))pred n)s=t:d!n
```
[Answer]
# [Python 2](https://docs.python.org/2/), 74 bytes
```
s,n=input()
while s:i=n;exec"i-=' '<(s+' '*n)[i];"*n;print s[:i];s=s[i+1:]
```
[Try it online!](https://tio.run/##RZDNbtwwDITvfYrBXvLnGG2BXna7b9AEAXpc5MCVGZuARCmilJ@n39JJFgUM2KJHM/OxvLcl68/TyQbdi5beLq@@vS4SGbaVve74jcNGbvcXuPh9aTf@utargzzuNte6K1W0wQ5bP9veDnLzY/t4Om3@5MoJUqwnTDnmCpMGStwGhKzGoXHrFTRJEQuiMzhKG/GXJ/DMDVypIbqu24i7XI@CtD4DnjxzlhgJ5mLrfr24efdJCrkWrgNaFWvy3Bnukqj78eyiWb1CSnnKUDkuIx44RtbGtuoXOkojh0of6v9GxvrRBl5O@esjUWTrNBGeHM5AAY7lSCuENbJPIi8hFHr0@bnMQyV2S1@KOydQnzuPuF8pvrBhVIR18H@h@QY9HmWhyq0SuDukaJCprx4Bk1D6DIsydzehGlxD0ctTwnP37Jd1x@fR4Fc8JuGFqqw0vvBxM@DX938 "Python 2 – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 46 44 bytes
Basically a pure regex solution in Java, almost certainly the shortest I've written.
Cheers to Kevin for helping to cut down the bytes in the regex even further!
```
n->s->s.replaceAll(".{1,"+n+"}( |$)","$0\n")
```
[Try it online!](https://tio.run/##fZFJaxtBEIXv@hWPwQcNHjfOIScnglwMgTgYdExyKPWUpJJ7cy8C4@i3KzVayM3QML1Uvfremx3t6W43vhyto1LwRBLeZ0CpVMVip6@mVXFm3YKtEoN5vGy@fA@VN5yHD4uWNUvYDDh/Fwus8fUY7hZFl8mcHFn@5ty8M@@fhu423HaHOf7e9N3Q3dz/Dl1/fJgpTmorpzgXqn2UEV5J52fZX39A/UQNLN9KZW9iqybpU3VhvjaUknubf77vL7vuR8zsIak0jzG6mFGkgjzXATaGwrZybRk0SpJidQTYSTVY8gg1XcGZKpzWtWLwFPNK4Kc1YD0RiXOEosWlaXtS8aY33sacpsSUulR5bQxV8dT0eFUJMSiC93GMCLLaGjyzc6xZl6l@SyupFLTrVP1fqHA40UDhAl82nhyXRiNhreYKyEJtqaXJhIZZzo4UQsg2p/dXmOdMrJIaiip7UNs0Nvg5ubjYRqEkHAZ9s1UT1PFIW8pcM4GbmpRgZWyThsUo5M/DnGyailC2WkNO4cnjtens/ZTx9WrQFh3jsacsOo2wgj3Fbrq@f9CffZgdjv8A "Java (JDK) – Try It Online")
Using a curried lamdba, it creates a regex to greedily match up to `n` characters followed by either a space or end of string. It then replaces those characters with themselves followed by a newline.
[Answer]
# Mathematica, 16 bytes
```
InsertLinebreaks
```
Built-in function. Takes a string and an integer as input and returns a string as output.
>
> `[InsertLinebreaks](https://reference.wolfram.com/language/ref/InsertLinebreaks.html)["*string*", *n*]`
>
> inserts newline characters to make no line longer than *n* characters.
>
>
>
[Answer]
# Powershell, ~~40~~ 83 bytes
Test case with `n=80` added.
```
param($s,$n)$s-split' '|%{if(($o+$_|% le*)-lt$n){$o+=' '*!!$o+$_}else{$o;$o=$_}}
$o
```
Test script:
```
$f = {
param($s,$n)$s-split' '|%{if(($o+$_|% le*)-lt$n){$o+=' '*!!$o+$_}else{$o;$o=$_}}
$o
}
@(
,(50, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.",
"Lorem ipsum dolor sit amet, consectetur adipiscing",
"elit. Sed eget erat lectus. Morbi mi mi, fringilla",
"sed suscipit ullamcorper, tristique at mauris.",
"Morbi non commodo nibh. Pellentesque habitant",
"morbi tristique senectus et netus et malesuada",
"fames ac turpis egestas. Sed at iaculis mauris.",
"Praesent a sem augue. Nulla lectus sapien, auctor",
"nec pharetra eu, tincidunt ac diam. Sed ligula",
"arcu, aliquam quis velit aliquam, dictum varius",
"erat.")
,(80, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus.",
"Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non",
"commodo nibh. Pellentesque habitant morbi tristique senectus et netus et",
"malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue.",
"Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu,",
"aliquam quis velit aliquam, dictum varius erat.")
) | %{
$n,$s,$expected = $_
$result = &$f $s $n
"$result"-eq"$expected"
# $result # uncomment this line to dispaly a result
}
```
Output:
```
True
True
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 68 bytes
```
i;b(s,n,l)char*s,*l;{for(i=n;*++s;i--||(i=l-s+n,*l=10))l=*s-32?l:s;}
```
[Try it online!](https://tio.run/##RVLLTiMxELzzFS1OmWRmBLvay46i/QFASBxXHDqezqQlPwa3zQX49mwZiFbyod2urq4q2Q2Lc@ezToeN9bH3nTtx3lq/9dPbMeWN7uO03e1s0mF4f8fVD7aLeN7f3nSd329t@Pnjj/9t08c5sMZN93ZFjYPs7/P@@i5lCaSr1UBz8gltLcRBSk8uRRNXpNRMPOuq5jQuJF7LSE8ykyxSSDIX8sBVG@k@5YNSaKenYwZcvWcygK1ifAV5RSe4lFfJPZWsVvSlCoElcMX1whJThIQQ0pwo6uE00qN4L7GINfyJD1o4YuoT/Z/IJH6qIYiL8l0E9mKVZ6YjzBmxI9iCpWbCCtuXI4hQdtWjfxHzmFlAiVDAHIjrUmWkh@bi2zYZryqxx5srSBDraUXCUjKTVJjU6HSujcPRrBy@lnldKkg4O2DYQzwHeqnY/doyvrR6jGBNoFfO2twg8PF6uqL2I37ddKjWWmxjqD7O/wA "C (gcc) – Try It Online")
Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat), save 2 bytes by moving global `char*l` to parameter.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Infix function; left argument is `n`, right argument is `n`.
```
⎕CY'dfns'⋄wrap
```
[Try it online!](https://tio.run/##RZBLahxBEESvErvZtAaD8Qm0kcAf4fHGy5yq7J6E@rTqI@G1hBYyFvbC5/AdfJS@yDha0mBoiq6syMh4KXM4898k5Ol4XJ5@n3/d@DHVzfL9/rbIfByXh5/Ljye@XH5aHu/@/nm7PPzibff5nOeXi8vd8d0bjNi8z0UjbK49wueQC6o1SNQ2wOVU1TVtvUC8zVadpQkarG2xUw@dtEGLNATqet3iQy57Q1y/AWOh3EIQVIprZ/tM885KdLnMWga0YrXZdVfQJUrn9eSScmKEGLPPSLY/bHGlIWhqWlf9QfbWJLHrWf3fqGp6TgOGS/r6EyVo7eIFI@EqxIFYRFohapP6QsQQJq4H1k9hroooLbkUOkdIn7pu8XGleMVGldk0DXxzjRvkeMwHKdqKQDshLTnzffVw8CbxZViwqdNEiqNGAsNLxHXn7Jt1x6fSwBaOibiRYisNF775Bw "APL (Dyalog Unicode) – Try It Online")
`⎕CY` **c**op**y** in [the dfns library](http://dfns.dyalog.com/n_contents.htm)
`⋄` then
`wrap`[[c]](http://dfns.dyalog.com/c_wrap.htm "Code") use the wrap[[n]](http://dfns.dyalog.com/n_wrap.htm "Notes") function
[c] code of that function
[n] notes for that function
---
### Golfed version of `wrap`, 59 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
```
{⍺≥≢⍵:⍵⋄(t↑⍵),2↓⎕TC,⍺∇⍵↓⍨t+b⊃⍨t←⊃⌽⍺,g/⍨⍺≥g←⍸(⍺+1)↑b←' '=⍵}
```
[Try it online!](https://tio.run/##RVDNahRBEH6Vum1CxjUqXgRPuSRgNLi@QE1P7WxD/0z6JyDiKbKa6C5KyAsIgrecAiJ48VH6RTZf72YJzEB11VffT/FgHnXv2fh@VZbXR2/K/Pv@6kNZ/C0Xv8rFz7K4fYG/fP20k8r8B8rd5mmZXwH77qCpsC@f6xydxe@015bL81qApVbf/gHR9I/R2jD2dbD4s4PX3pNdELZojGj0EhwfV9P1dLnxcXn@/@ZZlVxeT94eVL3Do8nq@T5NafTKB7Gkh5gtdd74QFEnYiupIeVdFJUk5UDc6UFHpV1PYnQa00Q6kl4SSeBEBrgcx3TsQ6vJ1q@haQBcG8MUAY4Z6wPIMzpW@TBIaCgFHZM@zUJgsZzx3LI472DBWt95crqdjelEjBGXJFb8jFud2GFrjX4giuLWbgjmnNwXlo3EzB3TFOEisSLEQqQaIiaOm0QwoVllg/7WzElgASWOAmZLnPssY3pdU9zHpsiDFtdgphIuCHkaZhwkBSbJCKmd0l2uHIo6zXYjZnSfQcJBAcMG5tnSaYb2Wb3xttVgBTKWzjjomgYHH90B "APL (Dyalog Unicode) – Try It Online")
`{`…`}` dfn; `⍺` is left argument (width), `⍵` is right argument (string)
`≢⍵` tally (number of characters) of string
`⍺≥`…`:` if width is greater than or equal to that, then:
`⍵` return the string
`⋄` otherwise:
`' '=⍵` Boolean mask where blanks are equal to the string
`b←` store in `b` (for **b**lanks)
`(`…`)↑` take the following number of elements from that:
`⍺+1` one more than the width
`⍸` **i**ndices where true
`g←` store in `g` (for **g**aps)
`⍺≥` Boolean mask where the width is greater than or equal to that
`g/⍨` filter the gap indices by that
`⍺,` append that to the width
`⊃⌽` pick the last element of that (lit. pick the first of the reversed)
`t←` store in `t` (for **t**ake)
`b⊃⍨` use that to pick an element from the mask of **b**lanks
`t+` add that to `t`
`⍵↓⍨` drop that many characters from the string
`⍺∇` recurse on that with the same left left argument
`⎕TC,` append that to the list of **t**erminal **c**ontrol characters (8:HT, 10:NL, 13:CR)
`2↓` drop the first two character from that (leaving just a leading 13:CR)
`(`…`),` append that to the following:
`t↑⍵` the first `t` characters of the string
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 20 bytes
```
¸rÈ+Yi[X·ÌY]¸Ê>V?R:S
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=uHJAW1hZXXEoWLfMK1MrWSDKPlY/UjpT&input=IkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0LCBjb25zZWN0ZXR1ciBhZGlwaXNjaW5nIGVsaXQuIFNlZCBlZ2V0IGVyYXQgbGVjdHVzLiBNb3JiaSBtaSBtaSwgZnJpbmdpbGxhIHNlZCBzdXNjaXBpdCB1bGxhbWNvcnBlciwgdHJpc3RpcXVlIGF0IG1hdXJpcy4gTW9yYmkgbm9uIGNvbW1vZG8gbmliaC4gUGVsbGVudGVzcXVlIGhhYml0YW50IG1vcmJpIHRyaXN0aXF1ZSBzZW5lY3R1cyBldCBuZXR1cyBldCBtYWxlc3VhZGEgZmFtZXMgYWMgdHVycGlzIGVnZXN0YXMuIFNlZCBhdCBpYWN1bGlzIG1hdXJpcy4gUHJhZXNlbnQgYSBzZW0gYXVndWUuIE51bGxhIGxlY3R1cyBzYXBpZW4sIGF1Y3RvciBuZWMgcGhhcmV0cmEgZXUsIHRpbmNpZHVudCBhYyBkaWFtLiBTZWQgbGlndWxhIGFyY3UsIGFsaXF1YW0gcXVpcyB2ZWxpdCBhbGlxdWFtLCBkaWN0dW0gdmFyaXVzIGVyYXQuIgo1MAo=)
Thanks to Bubbler and Shaggy for their help
Explanation:
```
¸ #Split into words
r #For each word, add them to the output in this way:
i # Choose a character using this process:
X·Ì # Get the last line of the output
Y # And the current word
[ ]¸ # Join them with a space
Ê>V? # If the resulting line is greater than the allowed length:
?R # Choose "/n" (newline)
:S # Otherwise choose " " (space)
i # Add the chosen character to the output
È+Y # Add the current word to the output
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 37 bytes
```
.+$
$*
!`(?=\S.*¶(1)+)(?<-1>.)+(?=\s)
```
[Try it online!](https://tio.run/##RZBNTgMxDIX3PYWRuui0Q0QX7IBeAFClblngJu7UUn6mcdKjcQAuNjj9EVIWifP8/D5nKhxxmsxqPpsvZw/fi83r184sf38W627VLTYvj@s3061aWbppek@ZAvAoNYBLPmUQLoCBSg82RSFbqNQM6HhksRwHIM/FwI4c0EAFKGMBr7oqBj5S3jOEdno4ZJWz9wiiYqnaPqp51UqwKY@UeyiZpfCpEqhLwKrPu0tMUSOEkFyCyPujgS15T7GQNP0R91wwatdF/W8kFC9pQMNFul0CepKKDuGgcAJoQbEUqUFIQbkSaQhGW73W72G2GUktdSnqHADrUMnAZ6O4YYPgyBR7/bNFN6jjYTxippIRqCokR8uuNg8LjjFch3keqppgtqpBr@ExwKnq7HPb8b3Ua4uOCXDGzI1GF25mz09/ "Retina 0.8.2 – Try It Online") Takes `s` and `n` on separate lines. Explanation:
```
.+$
$*
```
Convert `n` to unary.
```
(?=\S.*¶(1)+)(?<-1>.)+(?=\s)
```
Match non-whitespace, then look ahead to `n` and count it as `$#1`. Then go back and use a balancing group to match up to `n` characters followed by whitespace.
```
!`
```
Output the matches as a list of lines.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
Nθ←F⪪S «¿‹⁺LιⅈθM→⸿ι
```
[Try it online!](https://tio.run/##RVKxrtswDJxfvoLIJAOu0aVL@wUF0oegWTp0YWTaJiDJjihlKfrt7il5QQFDIKnj8Y6yXzj7lcO@f09bLe81XiW7W/ft8GO9i/t6kqkgmdZM7rIFLe6Bu5SsaXZdT0c6dh39ObzpRO4kZu4cqiFKc1mcAvHLdThvQD0pf@q8NM43CSZ0BlFxx9/52ErPTBH@3fcvnw@nNUsk3axGGtcAFaaFOErpya/JxBcpNROPuql5aCKByIEuMpLMUkgyFwrAVRsgIF@VYvt6mpoFDYHJALaK9g3kFZXo17xJ7gk2reitCoElckX6YklrgoQY13GlpNdloLOEIKmINfzCVy2c0PVA/ycySQ81BHFJPoLIQazyyDTBnBF7gi1YaiassD0dQYSyrwH1l5hzZgEllgLmSFznKgO9Nxcftsl4U0k97nzBBjGeNjy7lMwkFSY1eR1r4/A0KsfnsKBzBQn@D2A4QDxHulXMvrcdv0o9WjAm0p2zNjdY@LB/uod/ "Charcoal – Try It Online") Link is to verbose version of code. Takes input of `n` and `s` on separate lines. Explanation:
```
Nθ
```
Input `n`.
```
←
```
Move the cursor left one square to balance the right movement from the first iteration of the loop.
```
F⪪S «
```
Split the string on spaces and loop over the words.
```
¿‹⁺Lιⅈθ
```
Calculate whether the next word will reach the right edge.
```
M→
```
If it will not then move one square right.
```
⸿
```
If it will then start a new line.
```
ι
```
Output the word.
[Answer]
## JavaScript + HTML + CSS, ~~117~~ 64 bytes
*-53 bytes courtesy of @Neil*
```
n=50
s="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
f=(n,s)=>document.body.innerHTML+=`<tt><p style=width:${n}ch>${s}`
f(n,s)
```
[Answer]
# [Red](http://www.red-lang.org), 125, 117, 114 112 bytes
```
func[s n][d: 0 parse s[any[to" "p:" "opt[[to" "| to end]q:(if(-1 - d + index? q)> n[p/1: #"^/"d: index? p])]]]s]
```
[Try it online!](https://tio.run/##RZDNbhsxDITvfYrB9pKgziY59LKH9AXaImiPiy1AS1ybgP4sSkEL9N1dbmyjgCBIFDUzHyv78w/28/Jhnc5rT25WpGX2E55QqCpDZ0p/5pYHDGWyLZc2X65/0TI4@eU03cl69/CMB3h8giTPv7/gdP@CNJfH5wkfh1@Pg2leX8pyvyyLLudSJTWsGL7myhFStEf4HHKFSgNFbju4nJRd49YryEsRdZIO4CBtxE/24AM3cKWGYH1dR3zLdS@I29phNZODhEBQa9Zu34uJd6tEl2vhukOrok1OnWEqkbpdbyopJ4sQY/YZSfbHEa8cAqfGuvUfaS@NjCK@d/8XUk7vaWDhEl8PkQJrJ09YDU5BDoZlSBuENtILkYUQcj1Y/RbmtRKbpA3FlCOoHzqP@L5RXLGhVITTzt5cswmaPcqRKrdK4G6Qkpz4vmk4eKF4MQty6CZC1VkPBQtPEadu3m/bjG@lnX0xm4g3qrLR2MDHAZ@fzv8A "Red – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
õs#vDy«g²›i,}yðJ}?
```
[Try it online.](https://tio.run/##RZA9TgMxEIV7TjES7WpFQ01DhQBF4gQT72Qzkn82HjtSikjchwYh0VAmN@Eiy3N@hOTCHr95875JxkuVeT5@2@32cXf4GA9fv@8/2u13x8@n/cM8P6csgXSyGmhIPmUyLcRBSkcuRRNXpNRMPOik5jSOJF5LT28ykIxSSDIX8tBV6@kl5aVSaKejVYZcvWcyiK2ifYJ5RSW4lCfJHZWsVnRTheASuOJ5dYkpIkIIaUgUdbnuaSHeSyxiTb8GWuGIrpP638gkntIQwkW5XAJ7scoD0wpwRuwIWEBqEFbYzkQIoeyqR/0aZpFZYImlwDkQ17FKT6@N4oJNxpNK7PDnCjaI8TStOUvJTFIBqdHpUJuHo0E5nId5HStMODto2CM8B9pUzN62HV9LHVowJtCWszYaLLy/ub/7Aw)
**Explanation:**
```
õ # Push an empty string "" to the stack
s # Swap to take the (implicit) string input
# # Split it by spaces
v } # For-each `y` over the words:
D # Duplicate the top of the stack
# (which is the empty string in the very first iteration)
y« # Append the current word `y`
g # Get its length
²›i } # If its lengthy is larger than the second input:
, # Pop and output the current duplicated value with trailing newline
yð # Push the word `y` and a space " "
J # Join the entire stack together
? # After the loop, output the last part as well (without newline)
```
[Answer]
# Java 8, 135 bytes
```
n->s->{String r="",S[]=s.split(" "),t=r;for(int i=0;i<S.length;)if((t+S[i]).length()>n){r+=t+"\n";t="";}else t+=S[i++]+" ";return r+t;}
```
[Try it online.](https://tio.run/##fVFNi9swEL3nVww@2dgRe@nJ6xwLhW5ZyDHNYSLLyaT68EqjwBLy29PRxqG3gsHSzNOb996c8YLr8/jnri2mBG9I/roCSIxMGs7SVZnJqil7zRS8@r4cXn94NkcTu/@CthzJHzt4/DcbmGC4@/UmrTfXRw3iUFXddrcfkkqzJa4rqJqOh9hPIdbkGWh46el1q6zxRz71DU11ze12R/tmqdXNxjfX2A7cVr991bNw9jdjkwFuB0G27b4V3j4aztFDbLm/3fuVOJ3zwYrTxfAl0AhOQqgf6nZ7wKYEArD9TGycCpnVLC22vp4UzrP9rL@9NMup@hmicUBzyg7GYEOERAzoDHegg09Gc5EAONJMSZcAjJhWsDUjSJ4MJiKDFVxOCt5CPBC48nUwFUVkLUIScMryfBbyLBWnQ5zLMkR1YvrIBoTFYZbrk8UHLxKcC2MAT4eTgndjJT82qeBPeCBGidt9of8RJeO/1ICI82Y5OLQmZRwRJjGXADWILbFUTEiY6eFIRBDqbKX@FPMe0QilhCLMDjAfs1Hwq7hYbEPCmYzvpKdZEpTxMJ9QdhcRTBaT5DWNuXBoGAndY5ilYxYSjFowaEU8OvjIMvtSMn6WOnkiYxxcMFJxI4Grqml6WfNtdbv/BQ)
**Explanation:**
```
n->s->{ // Method with integer & String parameters and String return
String r="", // Result-String, starting empty
S[]=s.split(" "), // Input-String split by spaces
t=r; // Temp-String, starting empty as well
for(int i=0;i<S.length;) // Loop `i` in the range [0, amount_of_words):
if((t+S[i]).length()>n){ // If `t` and the word are larger than the integer input:
r+=t+"\n"; // Add `t` and a newline to the result
t="";} // And reset `t` to an empty String
else // Else:
t+=S[i++]+" "; // Append the word and a space to `t`
// (and then increase `i` by 1 with `i++` for the next word
// of the next iteration)
return r+t;} // Return the result-String appended with `t` as result
```
[Answer]
# JavaScript, 40 bytes
```
s=>n=>eval(`s.match(/.{1,${n}}( |$)/g)`)
```
[Try it online!](https://tio.run/##RZBLbsMwDESvQgRZ2ICrtIsukxO0RYBeIIzE2Cz0cUTJmzRnd@l8UEALiRoO5/EHJxSbeSwvMTmaT9tZtru43dGEvjmICVjs0GzM5a1bX@L12sDvut307aGdbYqSPBmf@ubUrD5SpgA8Sg3gkk8ZhAtgoNLBIiVbqNQM6HhksRx7IM/FwDc5oJ4KUMYCXnVVDHymfGQIy@nglFXO3iOIiqVq@6jmVSvBpjxS7qBklsLnSqAuAas@ny4xRY0QQnIJIh8HA3vynmIhWfQDHrlg1K6b@t9IKN7SgIaL9LgE9CQVHcJJ4QTQgmIp0gIhBeVOpCEYbfVaf4bZZyS11KWocwCsfSUDXwvFAxsER6bY6Z8tukEdD@OAmUpGoKqQHC27unhYcIzhPsxzX9UEs1UNeg2PAc5VZ0/Ljp@lTlt0TIAJMy80unCzapv317ad/wA "JavaScript (Node.js) – Try It Online")
[Answer]
Thanks to @Erik the Outgolfer, a golfed version :
# [Python 3](https://docs.python.org/3/), 94 bytes
```
def f(t,n):
while t:i=n+(t[min(len(t)-1,n)]==" "or-t[n-1::-1].find(' '));print(t[:i]);t=t[i:]
```
[Try it online!](https://tio.run/##RVLLTuNAELzzFaVcsLWORcTNyH8ACGmPUQ6dcTtuaR5mpofd/frQBqKVfLB7qqqrarz@0yXFx6vyX2WM2D2nzAGylhowJZ8yiigosHZwKRZ2ylozaJJVipN4AXvRHr95Al9YwZkU3nC19HhJ@SwI29NhzgYX7wnFwKUafTXxapPgUl45d9AsReW9MkwlULXPm0pM0SyEkKaEKOelxxt7z1G5bPiFzqIUjfWF/i9UOH65gZmL/PMSyHOpNBFmC1dADhbLIm0hilL5TmQmhFz1Nr@ZecvEJmmlmHIA1UvlHq9bip/YKLQKx87OnFqDth7rQpk1E7haSIlOprppOExC4XuZl0s1EcrOMOTNPAW8V9v9sXV8G3VGsTUBH5RlS2OF9zvcRbu/x4frxDPmRrvYDnf4s4hn6CBj/NXoMUhsrLFG2/3BAKdx3GGX8l6PcX8Yhv3h1M8Sp@Ye9237tNp9qbEGObVPOupRhtPVpLd/xdjXTw "Python 3 – Try It Online")
~~# [Python 3](https://docs.python.org/3/), 130 bytes~~
```
def f(t,n):
l=[]
while len(t):
i=(n-t[:n][::-1].find(' '),n+1)[t[min(len(t)-1,n)]==" "]
l.append(t[:i])
t=t[i::]
return l
```
[Try it online!](https://tio.run/##RZJBj5tADIXv@RUWlwWVoEZ7Q@IftNVKPdIcHHASr2YMO@PZtr8@fWw2qsQBPM@f3/Ow/vXrYs83lz8uNFD1bUkSSddcIs1LWBJldeIo3tK0WJbJxUsinnXVPKldSIJ6Rz9lJrmIkyR2CtCV3NH3JZ2U4va0dE6QawhMGeJc0L4CXlCJ05JWSS150uz6VoRAiVzw@aDYYrAQ4zIvZHq6dvQiIYi55E1/5ZM6G7o@1P9BWezDDcGcyedL5CC58Mx0RrhMPBFiIdIWIjvneyKYUJ5KQP1h5iWxAImlgByJy6VIRz@2FJ@xKfOqYi3OJscGMZ7WKyfxxCQFIdUmncvGmGhWjvdhQS8FEE4TNBxgniO9Fcx@33b8KLVowZhI75x0S4OFdxXtDPf3/PU2y5nOtbfW9DsKw3jc0e@rBoE5q30rkg617X3s7Tj2/f5w7M5qc/1ET01rXw7N6GNUq@/6/QGk4zBUVIFEoeN1FajRrscGFR981L7HYdr@DKNwW3HRXle/rOpeF5BgZ/u/AGqa2z8 "Python 3 – Try It Online")
Not so golfed version...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ḲŒṖK€€ḣ€ƑƇṪY
```
[Try it online!](https://tio.run/##y0rNyan8///hjk1HJz3cOc37UdMaIHq4YzGQPDbxWPvDnasi////n6iQpJCskJKappCukJ6hkPXfFAA "Jelly – Try It Online")
Unfortunately, this is too slow to work for the provided test case in under a minute over TIO.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 162 bytes
```
string[]t(string n,int a){var g="";for(int i=0;i++<Math.Floor((double)n.Length/a);)g+=$"^.{{{i*a-1}}}|";return Regex.Split(n,$@"(?n)(?<=({g.Trim('|')})\S*)\s");}}
```
This function uses a regex which matches the closest whitespace that is near the nth or multiple of nth character and splits the string based on it.
[Try it online!](https://tio.run/##VVJLa9xADD6vf4UwgXgSx00PPTlLCqU9JSV0Az00LWjHilcwD2ceIWXj377VZHdpa@bg0UjfQ5KOF9oH2u1yZDfC6ndMZPvq31t3Ty@p@0ZjNhg@v0yBYmTvYl8tyldNeW1YgzYYI9wFPwa01bZaxIRJ4jGFghWX9Y0QWeApZguDNz5A5ARoKbWgBZB0opQD4MATR12qyHDqYEUD0EgJKGACI3k5dnDrw5rBltPCYyFhYxCiJMcs5ZOAZ4lYMThRaEGExMRPmUBQLGa5HlGcdyLBWj94cLzedHBHxpBLFEv@Btec0EnVW/ZfoEjuTQ2IOEeHH4uGYsYB4VHMRUANYkssFRPSlbh3JCIYdTYSP4q5C0gCKU0RZAuYx0wdfC0uDrYh4sTkWnnTSToo9DBtMFAKCJTFJDvNQy4YGgZGuyczXMYHGLTkoBHxaOEpC/dz6fEx1EqJ0Fh4xsDFjTS8q/uqWhymfBjqs@cBbpFdo6qFzHrxKLNFvWmkDjSwg9TE9sOlUmVJPslwvaHue@BEN@yo0Uq2Z67@B91vyo@fUrrfGddy8aG2BXVc1nUvNE2J8fKy5/Pzq1tMm@6L8RJuBi9opFx3Q25Mm3eoejWeL0/qX912u@UzvHg/z/Nr3YeyZQ5ko@mlW01iv3Htyce6uXaqub5aNtuxuw9sm9PXUzWrh9WZeoi16ud5t/sD "C# (.NET Core) – Try It Online")
The TIO link is a full program, and the function has a static keyword so the function can be called from main.
[Test Regex](http://regexstorm.net/tester?p=%28%3f%3c%3d%28%5e.%7b49%7d%7c%5e.%7b99%7d%7c%5e.%7b149%7d%7c%5e.%7b199%7d%7c%5e.%7b249%7d%7c%5e.%7b299%7d%7c%5e.%7b349%7d%7c%5e.%7b399%7d%29%5cS*%29%5cs&i=Lorem+ipsum+dolor+sit+amet%2c+consectetur+adipiscing+elit.+Sed+eget+erat+lectus.+Morbi+mi+mi%2c+fringilla+sed+suscipit+ullamcorper%2c+tristique+at+mauris.+Morbi+non+commodo+nibh.+Pellentesque+habitant+morbi+tristique+senectus+et+netus+et+malesuada+fames+ac+turpis+egestas.+Sed+at+iaculis+mauris.+Praesent+a+sem+augue.+Nulla+lectus+sapien%2c+auctor+nec+pharetra+eu%2c+tincidunt+ac+diam.+Sed+ligula+arcu%2c+aliquam+quis+velit+aliquam%2c+dictum+varius+erat.&o=n)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 78 bytes
```
s=>n=>System.Text.RegularExpressions.Regex.Replace(s,".{1,"+n+"}( |$)","$0\n")
```
[Try it online!](https://tio.run/##RVJNb9swDL3nVzwYPdioZqyHnbrk1p3aoVgH7LILIzMJAUl2RanIsO23Z1TSYIBgiDT5Pkh5/eBVTl9q8p@1ZEl7d75LKu4SbzbYYX3S9SatNy@/tHAcv/OxjN94XwPlh@OSWVXmpC3FR/sugTz36rrx953rbtNt97fHn5uhc93Nx5@pG073q9Xqgg/FGt3jnDlCFq0R0xzmDJUCilwcvEGzL1xqBk2yiPrWx0HKiBeeYKwFnKkgWF3VEU9z3gpiOw67RiMhENSKtVr7YuDVMtHPeeHsYFK0yGtlGEqkauEVJc3JJMQ4TzOSbA8jnjkEToW11R9oK4WSdZ2r/wMpp7MamLjE75dIgbXSRNiZOQV5mC2z1ExoIb04MhFCvgbLX8U8Z2KDtKEYcgTVfeURX5uLd9tQWoSTs3@@2ASNHsuBMpdM4GomJXmZasPwmITihSxIWyQoe6uhYOIp4rUa91ub8TXlrMVoIt4oS3NjAx87W6S9FSRb4t0nC35kKdzveh36NAz3p38 "C# (Visual C# Interactive Compiler) – Try It Online")
Credit goes to @LukeStevens for coming up with the Java version... Apparently .NET makes you import the `RegularExpressions` namespace in order to do a replace :(
Here is my original version that splits on the space character and uses LINQ to join them back together:
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 91 bytes
```
s=>n=>s.Split(' ').Aggregate((a,w)=>a+(a.Length-a.LastIndexOf('\n')+w.Length>n?'\n':' ')+w)
```
[Try it online!](https://tio.run/##RVI7b9wwDN7vVxBZzsY5BjJ0SWoXXQoUSNoAGbp04cm0j4BEOaKU67@/UPdAAQ0kRX4PSk7vnfLpRxH3VXNiWbpzzJK7Sz6OMMNw0mGUYdT@bfWcmy1s2/77siRaMFPTYHdshxF3DfbPJEs@3FuAmn/KRP9@z832r2zb3fF6Ocq3WnisKLtje3rabDYXMlAY4O45JgrAq5YAU/QxgXIGDJQ7cFGUXKZcEuDEK6urc2SqenijCWihDJQwg7e@oj28xLRnCPV0MFca9h5BrVmLja8GXqwSXEwrpQ5MimZ@LwSGErBYekORKCYhhDhFEN4fengl70kyae0/4J4zik2du/8DKclZDZg4oWsQ0JMWnBBmM6eADsyWWaomNKNeHJkIRle81W9iXhOSQdpSDDkAlqVQD7@qi6ttUFyZpLM7l22DRg/rARPlhEDFTLI4nkrFcDAxhguZ56UYCCZnPehNPAZ4L8b9UXd8K3U2YjQBPjBxdWML7@/sIe3jgNgjPnyx5E9i@x1zo20jbft0@gQ "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Dart](https://www.dartlang.org/), 112 bytes
```
f(s,n){var l=[''];s.split(' ').forEach((w){if((l.last+w).length<=n)l.last+=w+' ';else l.add(w+' ');});return l;}
```
[Try it online!](https://tio.run/##RVK7buMwEOz9FdNJQgQiKa7SubwudwiQUlCxplbyAiSl8BEXhr/dt3JsGBAEajU7OzPLkWK@Xqc6taE5f1OE2/dVNXTJpNVJritUjZmW@Ifssa5PzVmmunbGUcovp8Y4DnM@/t6H5l7bn160pWOXGM7QONa3QtNdmi5yLjHAdZerJwl1c94B28yMPXo9A331vkT2kDUVj3FxS0SSDPKcW9glJLZ5owGNskqyEmawCjX45BE8cwZHynCKK8ng7xIPAr89LaaocHGOkBSciravSl604u0SV44tcpSU5aswlMVT0c8HS1iCSvB@GRcEORwNPthpApnThj/SQTIF7bqhn0SJw00NVFzg@8GT41RoJExqLoEs1JZa2kykTOnHkYoQssVp/SHmIxIrpYaizB5U5sIG/zYXd9tItAqHVv/ZrAnqeKxH0vwjgYualGBlLBuHxSjkf4Y5mYuSULSKIafiyeOr6OzvLeNHqdUWHeO33cnmRgM3VfvrddAdDt1O3/l5Z8ptzcBUl/51aEv/Njxv1KobyU2nAL0fu8v1Pw "Dart – Try It Online")
[Answer]
# APL(NARS), 48 chars, 96 bytes
```
{⊃⍵{⍺≥≢⍵:⊂⍵⋄k←1+⍺-' '⍳⍨⌽r←⍺↑⍵⋄(⊂k↑r),⍺∇k↓⍵}⍨⍺+1}
```
test:
```
f←{⊃⍵{⍺≥≢⍵:⊂⍵⋄k←1+⍺-' '⍳⍨⌽r←⍺↑⍵⋄(⊂k↑r),⍺∇k↓⍵}⍨⍺+1}
s←"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
50 f s
Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Sed eget erat lectus. Morbi mi mi, fringilla
sed suscipit ullamcorper, tristique at mauris.
Morbi non commodo nibh. Pellentesque habitant
morbi tristique senectus et netus et malesuada
fames ac turpis egestas. Sed at iaculis mauris.
Praesent a sem augue. Nulla lectus sapien, auctor
nec pharetra eu, tincidunt ac diam. Sed ligula
arcu, aliquam quis velit aliquam, dictum varius
erat.
```
[Answer]
# C, 63 bytes
```
b(a,n)char*a;{while(strlen(a)>n){for(a+=n;*a-32;--a);*a++=10;}}
```
The function of this exercise b(a,n) would break the line "a" as exercise said,
in the way not change its length (if we see the result as one string) because
change some spaces in \n or new line in place. The input string "a" should have no \n character too in it for b() function (it could have \n in input string for bs())
b(a,n) function would be ok only because the restriction of this exercise,
that impose each word of "a" string has length < n if this is not true, that function can go
to one infinite loop...(very wrong in my way of see so i copy too the function more good because
in that case would return -1 and not would go to one infinite loop; it is bs(a,n) below)I not exclude both functions are bugged...
```
#define R(x,y) if(x)return y
#define U unsigned
U bs(char*a,U n)
{U c,q,r=1,i,j;
R(!a||n<1||n++>0xFFFF,-1);
for(j=c=i=0;;++i,++c)
{R(i==-1,-1);q=a[i];
if(q==10)goto l;
if(c>=n){R(i-j>n,-1);a[i=j]=10;l:c=-1;++r;}
R(!q,r);
if(q==32)j=i;
}
}
```
result of b() passed on one function that add line lenght each line
```
Lorem ipsum dolor sit amet, consectetur adipiscing [50]
elit. Sed eget erat lectus. Morbi mi mi, fringilla [50]
sed suscipit ullamcorper, tristique at mauris. [46]
Morbi non commodo nibh. Pellentesque habitant [45]
morbi tristique senectus et netus et malesuada [46]
fames ac turpis egestas. Sed at iaculis mauris. [47]
Praesent a sem augue. Nulla lectus sapien, auctor [49]
nec pharetra eu, tincidunt ac diam. Sed ligula [46]
arcu, aliquam quis velit aliquam, dictum varius [47]
erat. [5]
```
] |
[Question]
[
# Introduction
A bell tower will ring its bells every hour, `n` times, with `n` being the the current hour on a 12 hour clock.
For example, a bell will ring 5 times at 5pm, and 10 times at 10am.
# Task
Given two times in a suitable format, output the number of times the bell will ring, inclusive of the start and end times
# Examples
```
"10am-12pm"
10+11+12= 33
[01:00, 05:00]
1+2+3+4+5 = 15
[11, 15]
11+12+1+2+3 = 29
[10:00pm, 10:00am]
10+11+12+1+2+3+4+5+6+7+8+9+10 = 88
```
If the start is the same as the end then the you simply just ouput the number of chimes for that hour:
```
[5pm, 5pm]
5 = 5
```
As you can see, you may choose an input method but the output must be an integer on its own (or an acceptable alternative) trailing/ leading newlines and spaces are allowed.
Note:
* inputs may span from the afternoon of one day to the morning of the next.
* the difference between the two times will never be more than 24 hours.
* input is flexible so long as you clearly state what format your input is.
* your input must have a **clear** distinction between AM and PM.
[Answer]
# JavaScript (ES6), ~~38~~ 35 bytes
```
f=(x,y)=>~-x%12-~(x-y&&f(x%24+1,y))
```
Recursively adds the current number of bell rings to the total. Called like `f(11,15)`; midnight is represented as `24`. I got part of the `~-` trick from [@xnor's Python answer](https://codegolf.stackexchange.com/a/95261/42545).
## Test snippet
```
f=(x,y)=>~-x%12-~(x-y&&f(x%24+1,y))
g=(x,y)=>console.log("x:",x,"y:",y,"result:",f(x,y))
g(10,12)
g(1,5)
g(11,15)
g(22,10)
```
```
<input id=A type="number" min=1 max=24 value=9>
<input id=B type="number" min=1 max=24 value=17>
<button onclick="g(A.value,B.value)">Run</button>
```
### Non-recursive version (Firefox 30+), 56 bytes
```
(x,y,t=0)=>[for(_ of Array((y-x+25)%24))t+=x++%12||12]|t
```
Equivalent to the following ES6 function:
```
(x,y,t=0)=>[...Array((y-x+25)%24))].map(_=>t+=x++%12||12)|t
```
[Answer]
# Python 2, 46 bytes
```
f=lambda x,y:(x%12or 12)+(x-y and f(-~x%24,y))
```
Based on my JS answer. The recursive formula **f** for the solution is defined as so:
1. Start with two integers **x** and **y**.
2. Take **x mod 12**; if this is 0, take **12** instead.
3. If **x != y**, add the result of **f(x+1 mod 24, y)**.
[Answer]
# Python 2, ~~59~~ 54 bytes
```
a=lambda x,y:sum(1+i%12for i in range(x-1,y+24*(x>y)))
```
Equivalent to
```
summ=0
if start > end:
end+=24
for hour in range(start-1,end):
summ +=1+hour%12
print summ
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 13 bytes
With a lot of help from *Emigna*.
```
-24%ݹ+<12%>O
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=LTI0JcOdwrkrPDEyJT5P&input=MjMKMQ)
[Answer]
## Python, 42 bytes
```
f=lambda a,b:~-a%12-~(b-a and f(-~a%24,b))
```
A recursive function that takes two numbers from 0 to 23. Expanding the `~x`'s to `-x-1` gives
```
f=lambda a,b:(a-1)%12+1+(b-a and f((a+1)%24,b))
```
The expression `(a+1)%12+1` converts a time to the number of rings `1` to `12`. Then, the lower bound is incremented modulo 24 and the function for the recursive result is added. That is, unless the current hour is the end hour, in which case we stop.
I've been trying to write a purely arithmetical solution instead, but so far I've only found long and messy expressions.
[Answer]
## Haskell, 48 43 bytes
```
s%e=sum[mod x 12+1|x<-[s-1..e+23],x<e||s>e]
```
Usage is `startHour % endHour`, with both inputs given in 24-hr format.
*edit: added @xnor's improvement, saving 5 bytes*
[Answer]
# C#, 73 bytes
```
a=>b=>{int x=0;for(;;){x+=(a%=24)>12?a-12:a<1?12:a;if(a++==b)return x;}};
```
Acceptable input: integers in range [0,23].
**This solution does not use LINQ.**
---
Full program with test cases:
```
using System;
namespace HowManyTimesABellTowerRings
{
class Program
{
static void Main(string[] args)
{
Func<int,Func<int,int>>f= a=>b=>{int x=0;for(;;){x+=(a%=24)>12?a-12:a<1?12:a;if(a++==b)return x;}};
Console.WriteLine(f(10)(12)); //33
Console.WriteLine(f(1)(5)); //15
Console.WriteLine(f(11)(15)); //29
Console.WriteLine(f(22)(10)); //88
Console.WriteLine(f(10)(10)); //10
Console.WriteLine(f(11)(10)); //156
Console.WriteLine(f(0)(23)); //156
Console.WriteLine(f(22)(1)); //34
}
}
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17 16 15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
>×24+⁹⁸r’%12‘S
```
**[TryItOnline](http://jelly.tryitonline.net/#code=PsOXMjQr4oG54oG4cuKAmSUxMuKAmFM&input=&args=MjM+MQ)**
How?
```
>×24+⁹⁸r’%12‘S - Main link: a, b (24 hr integers, midnight may be 0 or 24)
> - a>b? (1 if true, 0 if false)
×24 - times 24 (24 if a>b, else 0)
+⁹ - add to b (b+24 if a>b, else b)
⁸ - a
r - range(a, b+24 or b) ([a,a+1,...,b+24 or b])
’ - decrement (vectorises) ([a-1,a,...,b+23 or b-1])
%12 - mod 12 (vectorises) (number of tolls at each occurrence - 1)
‘ - increment (vectorises) (number of tolls at each occurrence)
S - sum
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 14 bytes
```
yy>24*+&:12X\s
```
Input format is as in the third example in the challenge, that is, two numbers in 24-hour format.
[Try it online!](http://matl.tryitonline.net/#code=eXk-MjQqKyY6MTJYXHM&input=MjIKMTA)
### Explanation
Take inputs `22`, `10` as an example.
```
yy % Take two inputs implicitly. Duplicate both
% STACK: 22, 10, 22, 10
> % Is the first greater than the second?
% STACK: 22, 10, 1
24* % Multiply by 24
% STACK: 22, 10, 24
+ % Add
% STACK: 22, 34
&: % Binary range
% STACK: [22 23 24 25 26 27 28 29 30 31 32 33 34]
12X\ % Modulo 12, 1-based
% STACK: [10 11 12 1 2 3 4 5 6 7 8 9 10]
s % Sum of array
% STACK: 88
% Implicitly display
```
[Answer]
# PHP, 90 Bytes
Input format '[1,24]' between 1 and 24
In this challenge that I am hate why PHP loose against other languages. I prefer to show all my ideas. Maybe an other PHP Crack finds a shorter solution.
```
<?list($f,$g)=$_GET[b];for($i=$f;$i-1!=$g|$f>$g&!$c;$s+=$i++%12?:12)$i<25?:$c=$i=1;echo$s;
```
99 Bytes
```
<?for($i=($b=$_GET[b])[0],$c=($d=$b[1]-$b[0])<0?25+$d:$d+1;$c--;$s+=$i++%12?:12)$i<25?:$i=1;echo$s;
```
113 Bytes a way with min and max
```
<?for($i=min($b=$_GET[b]);$i<=$m=max($b);)$s+=$i++%12?:12;echo($b[0]>$b[1])?156-$s+($m%12?:12)+($b[1]%12?:12):$s;
```
okay this crazy idea works with an array 149 Bytes
fills the array `$y[0]` and `$y[1]` if `$_GET["b"][0]<=$_GET["b"][1]`
if `$y[1]` is `null` we can sum this array `array_diff_key($y[0],array_slice($y[0],$b[1],$b[0]-$b[1]-1,1))`
```
<?for(;++$i<25;)$y[$i>=($b=$_GET[b])[0]&$i<=$b[1]][$i]=$i%12?:12;echo array_sum($y[1]??array_diff_key($y[0],array_slice($y[0],$b[1],$b[0]-$b[1]-1,1)));
```
This could be golfed down 124 Bytes
```
<?for(;++$i<25;)$x[($v=($b=$_GET[b])[0]>$b[1])?$i<$b[0]&$i>$b[1]:$i>=$b[0]&$i<=$b[1]][$i]=$i%12?:12;echo array_sum($x[!$v]);
```
Now at this point we can reduce the array with only two ints 101 Bytes
Make 2 sums `$x[0]` and `$x[1]`
`list($f,$g)=$_GET[b];`
if `$v=($f>$g`
then add value to `$x[$i<$f&$i>$g]`
else add value to `$x[$i>=$f&$i<=$g]`
the output will be find by case `echo$x[!$v];`
```
<?list($f,$g)=$_GET[b];for(;++$i<25;)$x[($v=$f>$g)?$i<$f&$i>$g:$i>=$f&$i<=$g]+=$i%12?:12;echo$x[!$v];
```
After that i found a way to calculate the result directly 112 Bytes
```
<?list($x,$y)=$_GET[t];echo(($b=$x>$y)+(($x-($s=$x%12?:12)^$y-($t=$y%12?:12))xor$b))*78-($s*($s-1)-$t*($t+1))/2;
```
recursive 103 Bytes
```
<?list($x,$y)=$_GET[t];function f($x,$y){return($x%12?:12)+($x-$y?f(++$x<25?$x:1,$y):0);}echo f($x,$y);
```
[Answer]
# PHP, 69 bytes
```
list(,$i,$a)=$argv;for($a+=$i>$a?24:0;$i<=$a;)$n+=$i++%12?:12;echo$n;
```
The list extraction was inspired by Jörg Hülsermann's answer but the rest of the similarities are a result of convergent evolution and because it's quite a lot shorter and the conditionals in the loop are different enough I'm posting it as a separate answer.
Takes input as 24 hour times (fine with either 0 or 24). Run like:
```
php -r "list(,$i,$a)=$argv;for($a+=$i>$a?24:0;$i<=$a;)$n+=$i++%12?:12;echo$n;" 9 18
```
[Answer]
# Java, ~~72~~ ~~71~~ ~~78~~ 76 bytes
```
Usage:
pm: true if first time is past 11am
time: first time%12
pm2: true if second time is past 11am
time2: second time%12
```
**Edit**:
* ***-1** byte off. Thanks to @1Darco1*
* *Fixed function head. **+7** bytes on.*
* ***-2** bytes off. Thanks to @Kevin Cruijssen*
* ***+2** bytes on. Now `e`/`clock` is initialized.*
---
```
(a,b,c,d)->{int e=0;b+=a?12:0;d+=c?12:0;for(;b!=d;e+=b%12,b=++b%24);return e;}
```
Ungolfed:
```
public static int clock(boolean pm, int time, boolean pm2, int time2){
int clock=0;
time+=pm?12:0;
time2+=pm2?12:0;
while(time!=time2){
clock+=time%12;
time=++time%24;
}
return clock;
}
```
[Answer]
## [QBIC](https://codegolf.stackexchange.com/questions/44680/showcase-your-language-one-vote-at-a-time/86385#86385), ~~90~~ 47 bytes
So, here's the answer printing only the total number of bell-rings:
```
::{c=a~c>12|c=c-12]d=d+c~a=b|_Xd]a=a+1~a>24|a=1
```
Input is in range `1-24`; `a` and `b` are the inputs (`::` in the code), `c` keeps track of am/pm, `d` is the total number of rings. When we've counted down all the hours, `_Xd` terminates the program, printing `d` in the process.
---
OK, I misunderstood the question and thought the `1+2+3...=` text was part of the output, so I wrote that:
```
::{c=a~c>12|c=c-12]X=!c$Z=Z+X+@+| d=d+c~a=b|?left$$|(Z,len(Z)-1)+@ =|+!d$_X]a=a+1~a>24|a=1
```
Now, I'll go code the proper answer...
[Answer]
# Pyth - 11 bytes
```
s|R12%R12}F
```
[Test Suite](http://pyth.herokuapp.com/?code=s%7CR12%25R12%7DF&test_suite=1&test_suite_input=10%2C+12%0A1%2C+5%0A11%2C+15%0A10%2C+22%0A5%2C+5&debug=0).
[Answer]
## C#, 76 bytes
```
(a,b)=>Enumerable.Range(a,Math.Abs(b-a)+1).Select(n=>n%12==0?12:n%12).Sum();
```
[Answer]
# Perl, 36 bytes
Includes +1 for `-p`
Give start and end time in 24-hour format on a line each on STDIN:
```
toll.pl
11
15
^D
```
`toll.pl`:
```
#!/usr/bin/perl -p
$\+=$_%12||12for$_..$_+(<>-$_)%24}{
```
[Answer]
# Java 7, 64 bytes
```
int c(int x,int y){return(x%12<1?12:x%12)+(x!=y?c(-~x%24,y):0);}
```
Recursive method based on [*@ETHproductions*'s Python 2 answer](https://codegolf.stackexchange.com/a/95259/52210). Uses a 24-hour clock input.
**Ungolfed & test code:**
[Try it here.](https://ideone.com/EAoqZi)
```
class M{
static int c(int x, int y){
return (x%12 < 1
? 12
: x%12)
+ (x != y
? c(-~x % 24, y)
: 0);
}
public static void main(String[] a){
System.out.println(c(10, 12));
System.out.println(c(1, 5));
System.out.println(c(11, 15));
System.out.println(c(10, 22));
System.out.println(c(5, 5));
}
}
```
**Output:**
```
33
15
29
88
5
```
[Answer]
## Batch, ~~168~~ 91 bytes
```
@cmd/cset/ax=(%1+23)%%24,y=x+(%2+24-%1)%%24,z=y%%12+1,(y/12-x/12)*78+z*-~z/2-(x%%=12)*-~x/2
```
Edit: Saved 77 byte by switching to a closed form for the answer.
* `%1` and `%2` are the two command-line parameters
* `@` Disable Batch's default which is to echo the command
* `cmd/c` Fool Batch into immediately printing the result of the calculation
* `set/a` Perform a numeric calculation
* `x=(%1+23)%%24,` Normalise the starting hour to be the number of hours since 1AM (1PM would also work, but 11 is no shorter than 23)
* `y=x+(%2+24-%1)%%24,` Normalise the ending hour to be ahead of the starting hour, advancing to the next day if necessary
* `z=y%%12+1,` Number of bells struck at the ending hour
* `(y/12-x/12)*78+` Number of bells due to extra half days
* `z*~-z/2-` Number of bells from 1 o'clock to the ending hour inclusive
* `(x%%=12)` One less than the number of bells struck at the starting hour
* `*-~x/2` Number of bells that would have been struck from 1 o'clock to the starting hour, but not including the starting hour
[Answer]
### C, 56 Bytes
```
f(a,b,c=0){while(b-->a){c+=b>12?b-12:b;}printf("%d",c);}
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 48 + 2 = 50 bytes
```
<v$&%$-&:$+}:*2c
{>:?!v1-}:1+
v?=1l<++1%c+b$
>n;
```
Input is expected to be present on the stack at program start, so +2 bytes for the `-v` flag. Input is two integers specifying the hour on the 24 hour clock, so `10am - 10pm` would be given as `10 22`.
[Try it online!](http://fish.tryitonline.net/#code=PHYkJiUkLSY6JCt9OioyYwp7Pjo_IXYxLX06MSsKdj89MWw8KysxJWMrYiQKPm47&input=&args=LXYgMTA+LXYgMjI)
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), ~~45~~ 44 bytes
*Saved 1 byte, thanks to @ETHproductions*
My first foray into Cubix...
```
)$424tU4OI0Iuq;;-!^;^%&21u+rr;ss!;sqU>&%r$@;
```
Or, cubified:
```
) $ 4
2 4 t
U 4 O
I 0 I u q ; ; - ! ^ ; ^
% & 2 1 u + r r ; s s !
; s q U > & % r $ @ ; .
. . .
. . .
. . .
```
You can try it out at the [online interpreter](https://ethproductions.github.io/cubix/). Input is in 24 hour format, with the end time first. For example, from 5pm to 1am the input should be `1 17`.
---
Previous version, 45 bytes:
```
)$442t\/OI0Iuq;;-!^;^%&21u+rr;ss!;sqU>&%r$@.;
```
[Answer]
# Qbasic, 112 bytes
```
input "",a
input "",b
do
if a=25 then a=1
if a<=12 then
c=c+a
else
c=c+a-12
endif
a=a+1
loop until a=b+1
print c
```
[Answer]
# Python, 73 bytes
It would be so much shorter if we didn't have to support `pm` to `am`. I use recursion to support it.
```
f=lambda a,b:sum([~-i%12+1for i in range(a,b+1)]*(a<b)or[f(a,24),f(1,b)])
```
[**Try it online**](https://repl.it/DnDQ/1)
Without supporting `pm` to `am` (45 bytes):
```
lambda a,b:sum(~-i%12+1for i in range(a,b+1))
```
] |
[Question]
[
**Monday Mini-Golf:** A series of short [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenges, posted (hopefully!) every Monday.
Many web applications (especially social media) automatically truncate long passages of text so they fit within the app's formatting. In this challenge, we're going to create an algorithm to automatically trim a passage of text to a certain length.
# Challenge
The goal of the challenge is to write a program or function that takes in two arguments:
* *T*, the text to truncate.
* *L*, the maximum length to return.
And returns *T*, truncated with the following logic:
* If the length of *T* is less than or equal to *L*, no truncation is needed. Return the original string.
* Truncate *T* to length *L*-2. If this contains no spaces or hyphens, return *T* truncated to exactly *L*-3 characters, followed by an ellipsis `...`.
* Otherwise, trim the end of the result up to the last space or hyphen. Add an ellipsis `...` and return the result.
# Details
* *T* and *L* may be taken in either order and any format.
* You may assume that 3 < *L* < 231.
* You may not use U+2026 Horizontal Ellipsis `…`; you must use three periods.
* The input will not start with a space or a hyphen.
* The input will not contain any whitespace other than regular spaces. (No tabs, newlines, etc.)
# Test-cases
### Inputs:
```
"This is some very long text." 25
"This-is-some-long-hyphen-separated-text." 33
"Programming Puzzles & Code Golf is a question and answer site for programming puzzle enthusiasts and code golfers." 55
"abcdefghijklmnopqrstuvwxyz" 20
"a b c" 4
"Very long." 100
```
### Outputs:
```
"This is some very long..."
"This-is-some-long-hyphen..."
"Programming Puzzles & Code Golf is a question and..."
"abcdefghijklmnopq..."
"a..."
"Very long."
```
(Note that the quotes are just to specify that these are strings; they need not be included.)
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest valid code in bytes wins. Tiebreaker goes to submission that reached its final byte count first. ~~The winner will be chosen next Monday, Oct 5. Good luck!~~
**Edit:** Congrats to your winner, @Jakube with Pyth again, with **25 bytes!**
[Answer]
# Pyth, 25 bytes
```
+WnzK<zeo}@zN" -"-Q2K"...
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=%2BWnzK%3Czeo%7D%40zN%22+-%22-Q2K%22...&input=This+is+some-very+long+text.%0A25&test_suite_input=This+is+some+very+long+text.%0A25%0AThis-is-some-long-hyphen-separated-text.%0A33%0AProgramming+Puzzles+%26+Code+Golf+is+a+question+and+answer+site+for+programming+puzzle+enthusiasts+and+code+golfers.%0A55%0Aabcdefghijklmnopqrstuvwxyz%0A20%0Aa+b+c%0A4%0AVery+long.%0A100&debug=0&input_size=2) or [Test Suite](http://pyth.herokuapp.com/?code=%2BWnzK%3Czeo%7D%40zN%22+-%22-Q2K%22...&input=This+is+some-very+long+text.%0A25&test_suite=1&test_suite_input=This+is+some+very+long+text.%0A25%0AThis-is-some-long-hyphen-separated-text.%0A33%0AProgramming+Puzzles+%26+Code+Golf+is+a+question+and+answer+site+for+programming+puzzle+enthusiasts+and+code+golfers.%0A55%0Aabcdefghijklmnopqrstuvwxyz%0A20%0Aa+b+c%0A4%0AVery+long.%0A100&debug=0&input_size=2)
### Explanation:
```
+WnzK<zeo}@zN" -"-Q2K"... implicit: z = input string, Q = input number
o -Q2 order the indices N in [0, 1, ..., Q-3] by
}@zN" -" z[T] in " -"
(hyphen-indices get sorted to the back)
e take the last such number
<z reduce z to length ^
K save this string to K
+WnzK K"... print (K + "...") if z != K else only K
```
[Answer]
# Perl, ~~69~~ ~~59~~ 52 bytes
51 bytes code + 1 byte command line. Assumes numerical input is allowed to be given with -i parameter.
```
s/.{$^I}\K.*//&&s/(^([^ -]*).|.*\K[ -].*)..$/$2.../
```
Usage:
```
echo "This-is-some-long-hyphen-separated-text." | perl -p -i"33" entry.pl
```
[Answer]
# Python 2, ~~78~~ 73 bytes
```
t,l=input()
u=t[:l-2]
print(t,u[:max(map(u.rfind,' -'))]+'...')[l<len(t)]
```
Input format follows the example input.
[Answer]
# JavaScript (ES6), ~~123~~ ~~78~~ ~~67~~ 61 bytes
I didn't expect to be able to cut this down so much, but it turns out the splice/replace combo is able to cover every case where truncation is needed.
```
(T,L)=>T[L]?T.slice(0,L-2).replace(/([ -][^ -]*|.)$/,'...'):T
```
First argument is the string, second is the length. Special thanks to edc65 for the length check optimization!
Here's the original code (123 bytes):
```
(T,L)=>(T.length>L?(S=T.slice(0,L)).slice(0,(m=Math.max(S.lastIndexOf` `,S.lastIndexOf`-`))<0?L-3:Math.min(L-3,m))+'...':T)
```
[Answer]
# TI-BASIC, 87 bytes
```
Prompt L,Str1
For(X,1,L
{inString(Str1," ",X),inString(Str1,"-",X
max(I,max(Ans*(Ans≤L-3->I
End
Str1
If L<length(Ans
sub(Ans,1,I+(L-3)not(I))+"...
Ans
```
TI-BASIC doesn't have many string manipulation commands, so we need to find the last index manually: if the string doesn't contain the string to search for, `inString(` returns 0. We search for hyphens and spaces starting at every position from 1 to `L`, and record the greatest number less than or equal to `L-3`. If that number `I` is still 0, we use `L-3` as the ending index instead.
Due to the calculator's limitations, the largest addressable index of a string is 9999; therefore, this will fail for larger strings.
I rely on the calculator's behavior of automatically initializing the variable `I` to 0, so delete `I` or clear your calculator's memory before running.
[Answer]
# Python 2, 105 bytes
```
def t(s,l):a=s[:l-2];return s[:max(a.rfind(' '),a.rfind('-'))]+'...'if' 'in a or'-'in a else a[:-1]+'...'
```
Called with
```
>>> print t("This is some very long text.", 25)
This is some very long...
```
[Answer]
# C# .NET, ~~187~~ 169 bytes
Hmm...
```
string f(string T,int L){if(T.Length<=L)return T;T=T.Substring(0,L-2);return T.Substring(0,T.Contains(" ")||T.Contains("-")?T.LastIndexOfAny(new[]{' ','-'}):L-3)+"...";}
```
[Answer]
# Groovy, 95 bytes
```
a={T,L->F=T.size()<=L?T:T[0..L-3]
m=F=~'(.*[- ])'
F==T?F:m?m[0][0].trim()+'...':F[0..-2]+'...'}
```
Pretty straightforward, can probably be golfed further
[Answer]
# CJam, 34 bytes
```
q~1$<_@={-2<_W%{" -"&}#~We|<'.3*}|
```
Try it online: [Chrome](http://cjam.aditsu.net/#code=q~1%24%3C_%40%3D%7B-2%3C_W%25%7B%22%20-%22%26%7D%23~We%7C%3C'.3*%7D%7C&input=%22a%20b%20c%22%204) | [Firefox](http://cjam.aditsu.net/#code=q~1%24%3C_%40%3D%7B-2%3C_W%2525%7B%22%20-%22%26%7D%23~We%7C%3C'.3*%7D%7C&input=%22a%20b%20c%22%204)
[Answer]
**T-SQL,145 bytes**
```
create proc a(@t varchar(max),@l int)as if LEN(@t)<=@l return @t;set @t = LEFT(@t,@l-3) select LEFT(@t,LEN(@t)-CHARINDEX('-',REVERSE(@t)))+'...'
```
usage:
`exec a("This is some very long text.", 25)
exec a("This-is-some-long-hyphen-separated-text.", 33)`
[Answer]
# [rs](https://github.com/kirbyfan64/rs), 116
```
(\d+)$/(_)^^(\1)
___$/
\t
+\t(.)(.*) (_)(_*)$/\1\t\2 \4
\t(.*?)_+$/\1\t
\t( ?).+/\1
[- ][^- \t]*$/
(?<!\t)$/...
\t/
```
At least it's shorter than C#...
[Live demo and test cases.](http://kirbyfan64.github.io/rs/index.html?script=%28%5Cd%2B%29%24%2F%28_%29%5E%5E%28%5C1%29%0A___%24%2F%0A%5Ct%0A%2B%5Ct%28.%29%28.*%29%20%28_%29%28_*%29%24%2F%5C1%5Ct%5C2%20%5C4%0A%5Ct%28.*%3F%29_%2B%24%2F%5C1%5Ct%0A%5Ct%28%20%3F%29.%2B%2F%5C1%0A%5B-%20%5D%5B%5E-%20%5Ct%5D*%24%2F%0A%28%3F%3C!%5Ct%29%24%2F...%0A%C2%A0%5Ct%2F&input=This%20is%20some%20very%20long%20text.%2025%0AThis-is-some-long-hyphen-separated-text.%2033%0AProgramming%20Puzzles%20%26%20Code%20Golf%20is%20a%20question%20and%20answer%20site%20for%20programming%20puzzle%20enthusiasts%20and%20code%20golfers.%2055%0Aabcdefghijklmnopqrstuvwxyz%2020%0Aa%20b%20c%204%0AVery%20long.%20100)
[Answer]
# Ceylon ~~386~~ ~~333~~ ~~252~~ ~~230~~ ~~222~~ ~~216~~ ~~171~~ ~~153~~ ~~131~~ 111
```
String t(String s,Integer l)=>s.size<l then s else s[0:(s[0:l-2].lastIndexWhere(" -".contains)else l-3)]+"...";
```
Ungolfed Original:
```
String truncate(String text, Integer length) {
if(text.size < length) {
return text;
}
Boolean spacePredicate(Character char) {
return char == ' ' || char == '-';
}
Integer? spaceIndex = text[0:length-2].lastIndexWhere(spacePredicate);
if(exists spaceIndex) {
return text[0:spaceIndex] + "...";
}
return text[0:length-3]+"...";
}
```
This is 386 bytes/characters.
Some interesting features here:
The `x[y:z]` syntax is syntactic sugar for [`x.measure(y, z)`](https://modules.ceylon-lang.org/repo/1/ceylon/language/1.1.0/module-doc/api/Ranged.type.html#measure), and returns a subrange of `x` starting at `y` with length `z` – for strings, this is a substring. (There is also `x[y..z]` syntax, which is a [span](https://modules.ceylon-lang.org/repo/1/ceylon/language/1.1.0/module-doc/api/Ranged.type.html#span) from index y to z, both inclusive, as well as half-open spans `x[...z]` and `x[y...]`.)
[`List.lastIndexWhere`](https://modules.ceylon-lang.org/repo/1/ceylon/language/1.1.0/module-doc/api/List.type.html#lastIndexWhere) takes a predicate (i.e. a function taking a list element and returning a boolean, i.e. here a [`Callable<Boolean, [Character]>`](https://modules.ceylon-lang.org/repo/1/ceylon/language/1.1.0/module-doc/api/Callable.type.html)), and gives the index of the last list element where the predicate is fulfilled (or null, if it's never fulfilled). As strings are lists, this works for strings too.
The result of this, `spaceIndex` is of type `Integer|Null`, or `Integer?` for short – i.e. it can either be an Integer or `null` (the only value of type `Null`). (The name `spaceIndex` comes from when I didn't realize that `-` was also special – I guess `breakIndex` would be better.)
With `exists spaceIndex` we can check if `spaceIndex` is non-null, and do something different then. (Inside this if-block the compiler knows that it is non-null ... without that it would have complained if I used `spaceIndex` to access the string.)
Instead of the local function `spacePredicate` we can also use an anonymous function
```
(Character char) => char == ' ' || char == '-'
```
This brings us to 333 characters:
```
String truncate(String text, Integer length) {
if(text.size < length) {
return text;
}
Integer? spaceIndex = text[0:length-2].lastIndexWhere(
(Character char) => char == ' ' || char == '-');
if(exists spaceIndex) {
return text[0:spaceIndex] + "...";
}
return text[0:length-3]+"...";
}
```
Next optimization is to use shorter variable and function names, which brings us down by 81 bytes to 252:
```
String t(String s, Integer l) {
if(s.size < l) {
return s;
}
Integer? i = s[0:l-2].lastIndexWhere(
(Character e) => e == ' ' || e == '-');
if(exists i) {
return s[0:i] + "...";
}
return s[0:l-3]+"...";
}
```
The predicate function actually doesn't need its argument type declared, that can be inferred by the compiler. Same for the type of `i` (where we still have to write `value` to mark it as a declaration). Now that declaration is short enough to fit on one line, bringing us down to 230:
```
String t(String s, Integer l) {
if(s.size < l) {
return s;
}
value i = s[0:l-2].lastIndexWhere((e) => e == ' ' || e == '-');
if(exists i) {
return s[0:i] + "...";
}
return s[0:l-3]+"...";
}
```
Instead of `e == ' ' || e == '-'` we can also write `e in [' ', '-']` (or `e in {' ', '-'}`, this is an iterable constructor instead of a tuple one).
The [`in` operator](http://ceylon-lang.org/documentation/1.1/reference/operator/in/) maps to the method Category.contains, which brings us to the idea that we can pass that tuple's [`contains`](https://modules.ceylon-lang.org/repo/1/ceylon/language/1.1.0/module-doc/api/Tuple.type.html#contains) method directly (it is a callable taking any object, so also accepting character), without the `(e) => ...` boilerplate (222 bytes):
```
String t(String s, Integer l) {
if(s.size < l) {
return s;
}
value i = s[0:l-2].lastIndexWhere([' ', '-'].contains);
if(exists i) {
return s[0:i] + "...";
}
return s[0:l-3]+"...";
}
```
Actually, another category containing the same two characters is the two-character string `" -"`. (In addition it also contains its substrings, but that doesn't hurt here). 216 bytes.
```
String t(String s, Integer l) {
if(s.size < l) {
return s;
}
value i = s[0:l-2].lastIndexWhere(" -".contains);
if(exists i) {
return s[0:i] + "...";
}
return s[0:l-3]+"...";
}
```
I guess we got the most out of this line, let's turn to the others ... the last two return statements have some similarity which we can exploit – they just differ in `i` vs. `l-3`, and are using `i` just when it is not null, otherwise `l-3`. Fortunately this is exactly what the [`else`](http://ceylon-lang.org/documentation/1.1/reference/operator/else/) operator is made for!
```
String t(String s, Integer l) {
if(s.size < l) {
return s;
}
value i = s[0:l-2].lastIndexWhere(" -".contains);
return s[0:(i else l-3)] + "...";
}
```
(The parentheses seem to be needed here, as `else` has a lower precedence than `[:]`.) This is 171 characters. Now `i` is used just once, so we can inline it, bringing us to 153 characters:
```
String t(String s, Integer l) {
if(s.size < l) {
return s;
}
return s[0:(s[0:l-2].lastIndexWhere(" -".contains) else l-3)] + "...";
}
```
We can also replace this `if-return-return` combination by a combination of the `then` and `else` operators in one `return`. (`then` returns is second operand when the first one is true, otherwise null, which then allows `else` to return its second operand.`) 131 bytes (although some of the savings are the white spaces which we'll get rid off anyways):
```
String t(String s, Integer l) {
return s.size < l then s else s[0:(s[0:l-2].lastIndexWhere(" -".contains) else l-3)] + "...";
}
```
A function which contains just one return with an expression can alternatively be written with the "fat arrow" notation, giving 123:
```
String t(String s, Integer l) =>
s.size < l then s else s[0:(s[0:l-2].lastIndexWhere(" -".contains) else l-3)] + "...";
```
Removing the unneeded whitespace gives us the final 111 bytes:
`String t(String s,Integer l)=>s.size<l then s else s[0:(s[0:l-2].lastIndexWhere(" -".contains)else l-3)]+"...";`
As an addition, here is a function which prints the examples from the question (using the name `t` which is used after step two):
```
shared void testTruncate() {
value testInputs = {
["This is some very long text.", 25],
["This-is-some-long-hyphen-separated-text.", 33],
["Programming Puzzles & Code Golf is a question and answer site for programming puzzle enthusiasts and code golfers.", 55],
["abcdefghijklmnopqrstuvwxyz", 20],
["a b c", 4],
["Very long.", 100]
};
for(input in testInputs) {
print(t(*input));
}
}
```
[Answer]
POSIX shell + GNU sed, 65 bytes
```
sed -re "s/(.{$1}).+/\1/;T;s/(.*)[- ]...*/\1.../;t;s/...$/.../;:"
```
This is a job made for sed! But I needed shell to get the length limit in (perhaps Perl would be better). The sed part expands out to a fairly simple sequence, with conditional jumps when we finish:
```
s/(.{$1}).+/\1/
T
s/(.*)[- ]...*/\1.../
t
s/...$/.../
:
```
[Answer]
# Mathematica 192 bytes
```
t=With[{r=StringTake[#,Min[#2-2,StringLength[#]]],p={"-",Whitespace},e="..."},
Which[StringLength[#]<=#2,#,StringFreeQ[r,p],StringDrop[r,-1]<>e,
True,StringTake[r,Max[StringPosition[r,p]]-1]<>e]]&
```
Called as
```
t["This is some very long text.", 25]
```
[Answer]
# ><>, 74 bytes
```
l$-:1)?\~r05.
/?=0:~$<-1
\}:0= ?\::"- "@=@=+?
>~"..."r\}
/!? <
>ol?!;
```
This solution requires the string to be truncated and `L` to already be on the stack, in that order.
There's 7 wasted bytes caused by alignment issues, still trying to golf those out.
[Answer]
## C# (157):
Based on the [**answer of Salah Alami**](https://codegolf.stackexchange.com/a/58957/15235), but shorter. The ***string*** class derives from `IEnumerable<char>`, so instead of `T.Contains(" ")||T.Contains("-")`, I use `" -".Any(x=>T.Contains(x))`.
Solution:
```
string f(string T,int L){if(T.Length<=L)return T;T=T.Substring(0,L-2);return T.Substring(0," -".Any(T.Contains)?T.LastIndexOfAny(new[]{' ','-'}):L-3)+"...";}
```
Ungolfed:
```
string f (string T, int L)
{
if (T.Length <= L)
return T;
T = T.Substring(0, L - 2);
return T.Substring(0, " -".Any(T.Contains) ? T.LastIndexOfAny(new[]{' ', '-'}) : L - 3) + "...";
}
```
**Update:**
Saved 6 bytes thanks to the comment of SLuck49, using `Any(T.Contains)` instead of `Any(x=>T.Contains(x))`.
[Answer]
## [GS2](https://github.com/nooodl/gs2), 29 bytes
This program takes standard input. The first line is the string, and the second is the target length number.
```
2a 0e 56 3c 40 a0 74 20 22 22 04 5d 2e 2a 3f 5b
20 2d 5d 7c 2e 07 2e 2e 2e 9d 20 e4 35
```
GS2 code can be a bit hard to read sometimes. :) Here's some commentary.
```
2a # lines - split input on newlines yielding a two element array
0e # extract-array - pop array, push both elements
56 # read-num - convert length string to number
3c # take - truncate the string to specified length
40 # dup - duplicate truncated string on stack
a0 # junk1 - push the last popped value, the un-truncated string
74 # ne - test for inequality
20 # reverse string
22 22 # tail tail - remove first two characters
# regex replace first occurrence of ".*?[ -]|." with "..."
04 5d 2e 2a 3f 5b 20 2d 5d 7c 2e 07 2e 2e 2e 9d
20 # reverse string
e4 # block5 - make a block out of last 5 instructions
35 # when - conditionally execute block
```
[Answer]
# Groovy, 56 bytes
Copied Kleyguerth's answer first, hence the same variable names...
Trim the string down by 2 chars, then most of the work is done by the regex, replace a dash or a space followed by any number of chars that are not a dash or a space at the end of the string with a "." OR replace any character at the end of the string if all the chars before it are neither a dash or a space with a ".". Harder to put into words than to write the regex...
```
a={T,L->T.size()<=L?T:T[0..L-3].replaceAll("([- ][^ -]*|(?<=[^- ]*).)\$",".")+".."}
```
Edit: Actually, can just remove the part of the string that matches the regex and add "..." at the end:
```
a={T,L->T.size()<=L?T:T[0..L-3]-~/[- ][^ -]*$|.$/+"..."}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes
```
ḣṖṖe€⁾ -œṗƊṖȯ$Ẏḣ⁹_3¤”.⁺⁺ðL>¥¡
```
[Try it online!](https://tio.run/##y0rNyan8///hjsUPd04DotRHTWseNe5T0D06@eHO6ce6gEIn1qs83NUHVPGocWe88aEljxrm6j1q3AVEhzf42B1aemjh////lQKK8tOLEnNzM/PSFQJKq6pyUosV1BSc81NSFdzzc9IUMosVEhUKS1OLSzLz8xQS81KAuLg8tUihOLMkVSEtv0ihAMmEArAJCql5JRmlxZmJxSXFYC3JIOPSgcalFhXrKf03NQUA "Jelly – Try It Online")
Full program.
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 89 bytes
```
import StdEnv
$n l|size l>n=l%(0,last[n:[i\\i<-[2..n]&c<-:l|c==' '||c=='-']]-3)+++"..."=l
```
[Try it online!](https://tio.run/##JYyxasMwFAD3foUwSZ3iPFHqzVidkqHQIZBsjoeHLNuCpydjqSEp/vYooYWD45bTZJCT890PGeHQcrJu8nMUx9jt@fKyYkFLsL9G0CcrWm/et4QhNlw19ny2NTQfUnL7qmuoaNFK5SJf/gx520L5VhRFJqXMFKVjxOdYiZUoS5GdRhvgSfDOAHkeYLxNo2EIZsIZo@kgmmuUWbrrnnAICb6@0@7G6Kz@jwNh7P3sHg "Clean – Try It Online")
As a function `$ :: Int String -> String`
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 117 bytes
```
a=>b=>a.Length>b?a.Substring(0,(" -".Any(x=>a.IndexOf(x,0,b-2)>-1)?a.LastIndexOfAny(new[]{' ','-'},b-2):b-3))+"...":a
```
Based off of @Abba's, which is based off of @Salah Alami's answer. Instead of using `Contains` and an unnecessary `Substring` call, it uses IndexOf to check if a hyphen or space exists in the truncated string.
[Try it online!](https://tio.run/##TVFRS8MwEH7vrzj64FqWlLq5F7tWRFCEgYKiD2MPaXtrY7ekS9Ktm/jbZ7KpCJdw4fvuu@9yhaaF5sf7ThRTbRQXFTnlXBhyfmdZnx5ZmuVpxqIZisrUWX7DopcuPxOCmAQ@UD@6Ffugd6xHUWL/tAx6EpOcjsKMXoa2Ysa0@YEcVeBuvvgcwIAM6ODrRLzO6TgMh34URf41OybeucN80abep@e/1lyDDS3XCFtUe1hJUYHB3kQ@OePUhsOpg2i9b2sUVGPLFDNY0j/us5KVYuu1lYfn7nBYoYYLuJMlwoNcLV0bBpsOteFSABOlPXqHCjQ3CEupoP2n0J4UAIWpO83tnPpUUji5ysqh0rYreD7LixKXVc0/mtVayHajtOm2u35/cKYY5FC45O13uMj/Sjy7jPlCui8YTch4TCYTMorJFbmMY8/C1kywZQqaNE6aafuzpKQZDkPvXVm7My4w6IN23izCQLo7TI7f "C# (Visual C# Interactive Compiler) – Try It Online")
] |
[Question]
[
# Create a Sudoku solution CHECKER
There are oodles of Sudoku SOLVERS here, but I want you to create a solution CHECKER as small as humanly possible (code-golf).
* A valid entry will be able to either take a 9x9 array as an argument (passed by reference, serialized on the command line, or however you want to take it) or accept an input file that is nine lines of nine numbers for the final grid. See examples of input below.
* Valid input should be base-10 numbers (1-9)
* Missing, empty, extra, non-numeric positions, or positions with numbers outside of 1-9 should be rejected as invalid input by returning a non-zero result, printing an error, or both.
* Your program needs to test whether each number appears once per column, once per line, and once per 3x3 sub-grid. If it passes, return "0" and if not, return a non-zero result.
* Use of external resources (websites, etc.) is to be avoided.
* If your solution is a stand-alone program, exiting with a exit status of, or printing, "0" or non-zero for "Pass" or "Fail", respectively, is ok.
Let the smallest answer win!
# Input Examples:
c array:
```
int input[9][9]={{1,2,3,4,5,6,7,8,9},
{4,5,6,7,8,9,1,2,3},
{7,8,9,1,2,3,4,5,6},
{2,3,1,5,6,4,8,9,7},
{5,6,4,8,9,7,2,3,1},
{8,9,7,2,3,1,5,6,4},
{3,1,2,6,4,5,9,7,8},
{6,4,5,9,7,8,3,1,2},
{9,7,8,3,1,2,6,4,5}
};
```
file:
```
123456789
456789123
789123456
231564897
564897231
897231564
312645978
645978312
978312645
```
The 9 sub-grids:
```
+---+---+---+
|123|456|789|
|456|789|123|
|789|123|456|
+---+---+---+
|231|564|897|
|564|897|231|
|897|231|564|
+---+---+---+
|312|645|978|
|645|978|312|
|978|312|645|
+---+---+---+
```
[Answer]
## Python, 103
I hate sudoku.
```
b = [[1,2,3,4,5,6,7,8,9],
[4,5,6,7,8,9,1,2,3],
[7,8,9,1,2,3,4,5,6],
[2,3,1,5,6,4,8,9,7],
[5,6,4,8,9,7,2,3,1],
[8,9,7,2,3,1,5,6,4],
[3,1,2,6,4,5,9,7,8],
[6,4,5,9,7,8,3,1,2],
[9,7,8,3,1,2,6,4,5]]
e=enumerate;print 243-len(set((a,t)for(i,r)in e(b)for(j,t)in e(r)for a in e([i,j,i/3*3+j/3]*(0<t<10))))
```
How it works: each row, column, and block must have each number from 1 to 9. So for each `0 <= i, j < 9`, the cell `i,j` is in block `3*floor(i/3) + floor(j/3)`. Thus, there are 243 requirements to satisfy. I make each requirement a tuple `((item index,item type number),symbol)` where `item index` is a number between 0 and 8 (inclusive), `item type number` is 0,1, or 2 to denote row, column or block respectively, and `symbol` is the entry `b[i][j]`.
Edit: I mistakenly didn't check for valid entries. Now I do.
[Answer]
## APL (46)
```
{∧/,↑∊∘Z¨(/∘(,⍵)¨↓Z∘.=,3/3⌿3 3⍴Z←⍳9),(↓⍵),↓⍉⍵}
```
This takes a 9-by-9 matrix. The example one can be entered on TryAPL like so:
```
sudoku ← ↑(1 2 3 4 5 6 7 8 9)(4 5 6 7 8 9 1 2 3)(7 8 9 1 2 3 4 5 6)(2 3 1 5 6 4 8 9 7)(5 6 4 8 9 7 2 3 1)(8 9 7 2 3 1 5 6 4)(3 1 2 6 4 5 9 7 8)(6 4 5 9 7 8 3 1 2)(9 7 8 3 1 2 6 4 5)
{∧/,↑∊∘Z¨(/∘(,⍵)¨↓Z∘.=,3/3⌿3 3⍴Z←⍳9),(↓⍵),↓⍉⍵} sudoku
1
```
Explanation:
* `↓⍉⍵`: get the columns of `⍵`,
* `↓⍵`: get the rows of `⍵`,
* `3/3⌿3 3⍴Z←⍳9`: make a 3-by-3 matrix containing the numbers `1` to `9`, then triplicate each number in both directions, giving a 9-by-9 matrix with the numbers `1` to `9` indicating each group,
* `Z∘.=`: for each number `1` to `9`, make a bitmask for the given group,
* `/∘(,⍵)¨`: and mask `⍵` with each, giving the groups of `⍵`.
* `∊∘Z¨`: for each sub-array, see if it contains the numbers `1` to `9`,
* `∧/,↑`: take the logical `and` of all of these numbers together.
[Answer]
### GolfScript, 39 characters
```
.zip.{3/}%zip{~}%3/{[]*}%++{$10,1>=!},,
```
It takes an array of arrays as input (see [online example](http://golfscript.apphb.com/?c=WwogIFsxIDIgMyA0IDUgNiA3IDggOV0KICBbNCA1IDYgNyA4IDkgMSAyIDNdCiAgWzcgOCA5IDEgMiAzIDQgNSA2XQogIFsyIDMgMSA1IDYgNCA4IDkgN10KICBbNSA2IDQgOCA5IDcgMiAzIDFdCiAgWzggOSA3IDIgMyAxIDUgNiA0XQogIFszIDEgMiA2IDQgNSA5IDcgOF0KICBbNiA0IDUgOSA3IDggMyAxIDJdCiAgWzkgNyA4IDMgMSAyIDYgNCA1XQpdCgouemlwLnszL30lemlwe359JTMve1tdKn0lKyt7JDEwLDE%2BPSF9LCwK&run=true)) and outputs `0` if it is a valid grid.
*Short explanation of the code*
```
.zip # Copy the input array and transpose it
.{3/}% # Split each line into 3 blocks
zip{~}% # Transpose these blocks
3/{[]*}% # Do the same for the lines themselves and join again
++ # Make one large list of 27 9-element arrays
# (9 for rows, 9 for columns, 9 for blocks)
{$10,1>=!}, # From those 27 select the ones which are not a permutation of [1 2 3 ... 9]
# $ -> sort
# 10,1> -> [1 2 3 ... 9]
# =! -> not equal
, # Count after filtering
```
[Answer]
## Java/C# - 183/180 181/178 173/170 bytes
```
boolean s(int[][]a){int x=0,y,j;int[]u=new int[27];for(;x<(y=9);x++)while(y>0){j=1<<a[x][--y];u[x]|=j;u[y+9]|=j;u[x/3+y/3*3+18]|=j;}for(x=0;x<27;)y+=u[x++];return y==27603;}
```
(Change `boolean` to `bool` for C#)
Formatted:
```
boolean s(int[][] a){
int x=0, y, j;
int[] u=new int[27];
for(;x<(y=9);x++)
while(y>0){
j=1<<a[x][--y];
u[x]|=j;
u[y+9]|=j;
u[x/3+y/3*3+18]|=j;
}
for(x=0;x<27;)
y+=u[x++];
return y==27603;
}
```
The method creates an array `u` with 27 bitmasks, representing the digits found in the nine rows, columns and squares.
It then iterates over all cells, performing the operation `1 << a[x][y]` to create a bitmask representing the digit and ORs its column, row and square bitmask with it.
It then iterates over all 27 bitmasks, ensuring that they all add up to 27594 (1022\*9, 1022 being the bitmask for all digits 1-9 being present). (Note that `y` ends up as 27603 due to it already containing 9 following the double loop.)
Edit: Accidentally left in a `%3` that's no longer necessary.
Edit 2: Inspired by Bryce Wagner's comment, the code has been compressed a bit more.
[Answer]
# python = 196
Not the most golfed, but the idea is there. Sets are pretty useful.
Board:
```
b = [[1,2,3,4,5,6,7,8,9],
[4,5,6,7,8,9,1,2,3],
[7,8,9,1,2,3,4,5,6],
[2,3,1,5,6,4,8,9,7],
[5,6,4,8,9,7,2,3,1],
[8,9,7,2,3,1,5,6,4],
[3,1,2,6,4,5,9,7,8],
[6,4,5,9,7,8,3,1,2],
[9,7,8,3,1,2,6,4,5]]
```
Program:
```
n={1,2,3,4,5,6,7,8,9};z=0
for r in b:
if set(r)!=n:z=1
for i in zip(*b):
if set(i)!=n:z=1
for i in (0,3,6):
for j in (0,3,6):
k=j+3
if set(b[i][j:k]+b[i+1][j:k]+b[i+2][j:k])!=n:z=1
print(z)
```
[Answer]
# Java - 385 306 328 260 characters
**Edit:**
I foolishly misread the instructions that the answer *had* to be a complete program. Since it can be just a valid function, I've rewritten and minimized to be a function, and rewritten my solution introduction with that in mind.
So, as a challenge to myself I thought I'd try to make the smallest Java solution checker.
To achieve this I assume that the sudoku puzzle will be passed in as a java multidimensional array, like so:
```
s(new int[][] {
{1,2,3,4,5,6,7,8,9},
{4,5,6,7,8,9,1,2,3},
{7,8,9,1,2,3,4,5,6},
{2,3,1,5,6,4,8,9,7},
{5,6,4,8,9,7,2,3,1},
{8,9,7,2,3,1,5,6,4},
{3,1,2,6,4,5,9,7,8},
{6,4,5,9,7,8,3,1,2},
{9,7,8,3,1,2,6,4,5}});
```
Then, we have the actual solver, which returns "0" if valid solution, "1" if not.
Fully golfed:
```
int s(int[][] s){int i=0,j,k=1;long[] f=new long[9];long r=0L,c=r,g=r,z=45L,q=r;for(f[0]=1L;k<9;){f[k]=f[k-1]*49;z+=f[k++]*45;}for(;i<9;i++){for(j=0;j<9;){k=s[i][j];r+=k*f[i];c+=k*f[j];g+=k*f[j++/3+3*(i/3)];q+=5*f[k-1];}}return (r==z&&c==z&&g==z&&q==z)?0:1;}
```
Readable:
```
int s(int[][] s) {
int i=0,j,k=1;
long[] f=new long[9];
long r=0L,c=r,g=r,z=45L,q=r;
for(f[0]=1L;k<9;){f[k]=f[k-1]*49;z+=f[k++]*45;}
for(;i<9;i++) {
for (j=0;j<9;) {
k=s[i][j];
r+=k*f[i];
c+=k*f[j];
g+=k*f[j++/3+3*(i/3)];
q+=5*f[k-1];
}
}
return (r==z&&c==z&&g==z&&q==z)?0:1;
}
```
So how does this work? I basically just create my own number base with sufficient resolution in each digit that I only have to do three numeric comparisons after passing through the puzzle once to know if it's valid. I chose base 49 for this problem, but any base larger than 45 would be sufficient.
A (hopefully) clear example: imagine that every "row" in the sudoku puzzle is a single digit in a base-49 number. We'll represent each digit in the base-49 number as a base-10 number in a vector for simplicity. So, if all rows are "correct" we expect the following base-49 number (as a base-10 vector):
```
(45,45,45,45,45,45,45,45,45)
```
or converted to a single base-10 number: `1526637748041045`
Follow similar logic for all the columns, and same for the "sub-grids". Any value encountered in the final analysis that doesn't equal this "ideal number" means the puzzle solution is invalid.
Edit to solve all-5s vulnerability and other related issues: I add a fourth base-49 number, based on the idea that there should be 9 of each number in every puzzle. So, I add 5 to each digit in the base-49 number for each occurrence of the base-10 number that represents the digit's index. An example, if there are 10 9's and 9 8's, 9 7's, 8 6's, and 9 of all others, you'd get a base-49 number (as a base-10 vector of size 10 to deal with overflow):
```
(1, 1, 45, 45, 40, 45, 45, 45, 45, 45)
```
Which will fail when compared against our "ideal" base-49 number.
My solution takes advantage of this mathematical solution, to avoid as much as possible looping and comparison. I simply use a `long` value to store each base-49 number as a base-10 number and use a lookup array to get the "factors" for each base-49 digit during column/row/subgrid check value computation.
As Java isn't designed to be concise, being careful in the mathematical construction was the only way I figured I could construct a concise checker.
Let me know what you think.
[Answer]
## R 145
```
function(x)colSums(do.call(rbind,lapply(list(R<-row(b<-matrix(1,9,9)),C<-col(b),(R-1)%/%3+1+3*(C-1)%/%3),sapply,`==`,1:9))%*%c(2^(x-1))==511)==27
```
The de-golfed code (more or less) can be found here <https://stackoverflow.com/a/21691541/1201032>.
[Answer]
## J 52 54
```
-.*/,(9=#)@~.@,"2(0 3 16 A.i.4)&|:(4#3)($,)".;._2]0 :0
```
Takes it's argument pasted on the command line, ended with a ) as:
```
1 2 3 4 5 6 7 8 9
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
2 3 1 5 6 4 8 9 7
5 6 4 8 9 7 2 3 1
8 9 7 2 3 1 5 6 4
3 1 2 6 4 5 9 7 8
6 4 5 9 7 8 3 1 2
9 7 8 3 1 2 6 4 5
)
```
Returns 1 if passed, 0 if not.
Internally, it converts the 9x9 grid to a 3x3x3x3 grid, and does some permutations on the axes to get the wanted unit (rows, lines and boxes) in the last 2 dimensions.
After doing that, it is checked that each unit has has 9 unique values.
Probably far from perfect, but beats the majority already ;-)
[Answer]
# Haskell (Lambdabot), 65 bytes
```
k x=and$(all$([1..9]==).sort)<$>[x,transpose x,join$chunksOf 3 x]
```
[Answer]
## Perl, 193 bytes
```
for(@x=1..9){$i=$_-1;@y=();push@y,$a[$i][$_-1]for@x;@y=sort@y;$r+=@y~~@x;@y=();push@y,$a[3*int($i/3)+$_/3][3*($i%3)+$_%3]for 0..8;@y=sort@y;$r+=@y~~@x}for(@a){@y=sort@$_;$r+=@y~~@x}exit($r!=27)
```
Input is expected in array form:
```
@a=(
[1,2,3,4,5,6,7,8,9],
[4,5,6,7,8,9,1,2,3],
[7,8,9,1,2,3,4,5,6],
[2,3,1,5,6,4,8,9,7],
[5,6,4,8,9,7,2,3,1],
[8,9,7,2,3,1,5,6,4],
[3,1,2,6,4,5,9,7,8],
[6,4,5,9,7,8,3,1,2],
[9,7,8,3,1,2,6,4,5]
);
```
Exit code is 0, if `@a` is a solution, otherwise `1` is returned.
**Ungolfed version:**
```
@x = (1..9);
for (@x) {
$i = $_ - 1;
# columns
@y = ();
for (@x) {
push @y, $a[$i][$_-1];
}
@y = sort @y;
$r += @y ~~ @x;
# sub arrays
@y = ();
for (0..8) {
push @y, $a[ 3 * int($i / 3) + $_ / 3 ][ 3 * ($i % 3) + $_ % 3 ];
}
@y = sort @y;
$r += @y ~~ @x
}
# rows
for (@a) {
@y = sort @$_;
$r += @y ~~ @x
}
exit ($r != 27);
```
Each of the 9 rows, 9 columns and 9 sub arrays are put into a sorted array
and checked, whether it matches the array `(1..9)`. The number `$r` is incremented for each successful match that must sum up to 27 for a valid solution.
[Answer]
# Mathematica, ~~84~~ 79 chars
```
f=Tr[Norm[Sort@#-Range@9]&/@Join[#,Thread@#,Flatten/@Join@@#~Partition~{3,3}]]&
```
**Examples:**
```
f[{{1,2,3,4,5,6,7,8,9},
{4,5,6,7,8,9,1,2,3},
{7,8,9,1,2,3,4,5,6},
{2,3,1,5,6,4,8,9,7},
{5,6,4,8,9,7,2,3,1},
{8,9,7,2,3,1,5,6,4},
{3,1,2,6,4,5,9,7,8},
{6,4,5,9,7,8,3,1,2},
{9,7,8,3,1,2,6,4,5}}]
```
>
> 0
>
>
>
```
f[{{2,1,3,4,5,6,7,8,9},
{4,5,6,7,8,9,1,2,3},
{7,8,9,1,2,3,4,5,6},
{2,3,1,5,6,4,8,9,7},
{5,6,4,8,9,7,2,3,1},
{8,9,7,2,3,1,5,6,4},
{3,1,2,6,4,5,9,7,8},
{6,4,5,9,7,8,3,1,2},
{9,7,8,3,1,2,6,4,5}}]
```
>
> 2
>
>
>
```
f[{{0,2,3,4,5,6,7,8,9},
{4,5,6,7,8,9,1,2,3},
{7,8,9,1,2,3,4,5,6},
{2,3,1,5,6,4,8,9,7},
{5,6,4,8,9,7,2,3,1},
{8,9,7,2,3,1,5,6,4},
{3,1,2,6,4,5,9,7,8},
{6,4,5,9,7,8,3,1,2},
{9,7,8,3,1,2,6,4,5}}]
```
>
> 3
>
>
>
[Answer]
# Javascript ES6, 150 chars
Takes input as a 81-char string without any delimeters.
```
s=>s.match("^(?=(#.{0,8}#.{9})+$)(?=(#(.{9}){0,8}#.){9})((#.?.?(.{9}){0,2}#...){3}.{18})+$".replace(/#(.*?)#/g,"123456789".replace(/./g,"(?=$$1$&)")))
```
Function returns `null` as negative answer and an array with original string in first element as a positive one. Can change to bool by adding `!!` to the function begining.
Test (see [related challenge](/q/78210/32091) for more detais):
```
f=s=>s.match("^(?=(#.{0,8}#.{9})+$)(?=(#(.{9}){0,8}#.){9})((#.?.?(.{9}){0,2}#...){3}.{18})+$".replace(/#(.*?)#/g,"123456789".replace(/./g,"(?=$$1$&)")))
;`123456789456789123789123456231564897564897231897231564312645978645978312978312645
725893461841657392396142758473516829168429537952378146234761985687935214519284673
395412678824376591671589243156928437249735186738641925983164752412857369567293814
679543182158926473432817659567381294914265738283479561345792816896154327721638945
867539142324167859159482736275398614936241587481756923592873461743615298618924375
954217683861453729372968145516832497249675318783149256437581962695324871128796534
271459386435168927986273541518734269769821435342596178194387652657942813823615794
237541896186927345495386721743269158569178432812435679378652914924813567651794283
168279435459863271273415986821354769734692518596781342615947823387526194942138657
863459712415273869279168354526387941947615238138942576781596423354821697692734185
768593142423176859951428736184765923572389614639214587816942375295837461347651298`
.split`
`.every(f)
&&
`519284673725893461841657392396142758473516829168429537952378146234761985687935214
839541267182437659367158924715692843624973518573864192298316475941285736456729381
679543182158926473432817659567381294914256738283479561345792816896154327721638945
867539142324167859159482736275398684936241517481756923592873461743615298618924375
754219683861453729372968145516832497249675318983147256437581962695324871128796534
271459386435168927986273541518734269769828435342596178194387652657942813823615794
237541896186927345378652914743269158569178432812435679495386721924813567651794283
168759432459613278273165984821594763734982516596821347615437829387246195942378651
869887283619214453457338664548525781275424668379969727517385163319223917621449519
894158578962859187461322315913849812241742157275462973384219294849882291119423759
123456789456789123564897231231564897789123456897231564312645978645978312978312645
145278369256389147364197258478512693589623471697431582712845936823956714931764825`
.split`
`.every(s => !f(s))
```
[Answer]
# R, ~~63~~ 50 bytes
Assumes the input `m` is a 9x9 matrix of numbers.
```
all(apply(m,1,match,x=1:9),apply(m,2,match,x=1:9))
```
I was right that further golfing was possible.
### Explanation:
```
apply(m,1,match,x=1:9),
```
Take `m`, and for each row, apply the `match` function. We specify a further argument `x=1:9` to be passed to `match`. `x` is the default first position argument, and therefore each row is placed in the second argument position, which is `table`. The function `match` looks for instances of `x` in
`table`. In this case, then, it's looking for `1:9` (the numbers 1 through 9) in each row. For each of `1:9`, it will return `TRUE` (or `FALSE`) if that number is found (or not).
So, this yields a series of 81 boolean values.
```
apply(m,2,match,x=1:9)
```
Repeat the above for each column of the input.
```
all( )
```
Finally, `all` checks if every element of the list of booleans is `TRUE`. This will be the case if and only if the solution is correct (i.e. each number `1:9` is present only once in each column and each row).
### ~~Old approach:~~
```
for(i in 1:2)F=F+apply(m,i,function(x)sort(x)==1:9);sum(F)==162
```
It takes each row, sorts it, and then compares it to `[1, 2, ... 9]`. A correct row should match exactly. Then it does the same for each column. In total, we should have 162 exact matches, which is what the final portion checks for. There is likely some scope for further golfing here...
[Answer]
## Haskell - 175
```
import Data.List
c=concat
m=map
q=[1..9]
w=length.c.m (\x->(x\\q)++(q\\x))
b x=c.m(take 3.drop(3*mod x 3)).take 3.drop(3*div x 3)
v i=sum$m(w)[i,transpose i,[b x i|x<-[0..8]]]
```
The function `v` is the one to call. It works by getting the difference of each rows, column and block against the list `[1..9]` and summing up the lengths of those difference lists.
Demo using the example Sudoku:
```
*Main> :l so-22443.hs
[1 of 1] Compiling Main ( so-22443.hs, interpreted )
Ok, modules loaded: Main.
*Main> v [[1,2,3,4,5,6,7,8,9],[4,5,6,7,8,9,1,2,3],[7,8,9,1,2,3,4,5,6],[2,3,1,5,6,4,8,9,7],[5,6,4,8,9,7,2,3,1],[8,9,7,2,3,1,5,6,4],[3,1,2,6,4,5,9,7,8],[6,4,5,9,7,8,3,1,2],[9,7,8,3,1,2,6,4,5]]
0
```
[Answer]
# Javascript - 149 Characters
```
r=[];c=[];g=[];for(i=9;i;)r[o=--i]=c[i]=g[i]=36;for(x in a)for(y in z=a[x]){r[v=z[y]-1]-=y;c[v]-=x;g[v]-=3*(x/3|0)+y/3|0}for(i in r)o|=r[i]|c[i]|g[i]
```
Expects an array `a` to exist and creates a variable `o` for output which is `0` on success and non-zero otherwise.
Works by checking that the sum of the position at which each value occurs for each row, column and 3\*3 grid equals 36 (0+1+2+3+4+5+6+7+8).
**Testing**
```
a=[
[1,2,3, 4,5,6, 7,8,9],
[4,5,6, 7,8,9, 1,2,3],
[7,8,9, 1,2,3, 4,5,6],
[2,3,1, 5,6,4, 8,9,7],
[5,6,4, 8,9,7, 2,3,1],
[8,9,7, 2,3,1, 5,6,4],
[3,1,2, 6,4,5, 9,7,8],
[6,4,5, 9,7,8, 3,1,2],
[9,7,8, 3,1,2, 6,4,5]
];
```
Gives 'o=0'
```
a=[
[1,2,3, 4,5,6, 7,8,9],
[4,5,6, 7,8,9, 1,2,3],
[7,8,9, 1,2,3, 4,5,6],
[2,3,1, 5,6,4, 8,9,7],
[5,6,4, 8,9,7, 2,3,1],
[8,9,7, 2,3,1, 5,6,4],
[3,1,2, 6,4,5, 9,7,8],
[6,4,5, 9,7,8, 3,1,2],
[9,7,8, 3,1,2, 6,5,4]
];
```
(Last 2 digits swapped)
Gives `o=-1`
```
a=[
[5,5,5, 5,5,5, 5,5,5],
[5,5,5, 5,5,5, 5,5,5],
[5,5,5, 5,5,5, 5,5,5],
[5,5,5, 5,5,5, 5,5,5],
[5,5,5, 5,5,5, 5,5,5],
[5,5,5, 5,5,5, 5,5,5],
[5,5,5, 5,5,5, 5,5,5],
[5,5,5, 5,5,5, 5,5,5],
[5,5,5, 5,5,5, 5,5,5]
];
```
Gives `o=-284`
[Answer]
# Haskell, ~~121~~ ~~130~~ 127 bytes (87 Lambdabot)
```
import Data.List
import Data.List.Split
c=concat
t=transpose
k=chunksOf
p x=all(==[1..9])$(sort<$>)=<<[x,t x,k 9.c.c.t$k 3<$>x]
```
uses:
```
-- k 9.c.c.t$k 3<$> x = chunksOf 9 $ concat $ concat $ transpose $ map chunksOf 3 x
let ts = k 9$[10*a+b|a<-[1..9],b<-[1..9]] --yep, this is ugly
in k 9.c.c.t$k 3<$>ts
-- prints:
--[[11,12,13,21,22,23,31,32,33],[41,42,43,51,52,53,61,62,63],[71,72,73,81,82,83,91,92,93],[14,15,16,24,25,26,34,35,36],[44,45,46,54,55,56,64,65,66],[74,75,76,84,85,86,94,95,96],[17,18,19,27,28,29,37,38,39],[47,48,49,57,58,59,67,68,69],[77,78,79,87,88,89,97,98,99]]
```
Lambdabot loads Data.List and Data.List.Split by default (I don't think BlackCap's solution checks the boxes).
Ideas for improvement welcome
//Edit: I messed up :)
//Edit: 3 bytes saved by BlackCap
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 143 bytes
```
A=>A.map((_,i)=>(c=d=>new Set(d).size==9)(A[i])&&c(A.map(b=>b[i]))&&c([0,0,0].reduce((a,_,O)=>a.concat(A[~~(i/3)*3+O].slice(l=i%3*3,l+3)),[])))
```
[Try it online!](https://tio.run/##XZA9T8MwEED3/IpbqM7tYUhd@jE4Un5BB8bIqlzHRUYhqZoAEkP/ejBEl8G67endO@ne7Zft3S1ch8e2q/140WOpi1J@2CviiYLQBTpd66L13/DqB6yF7MOP1/ogsKyCEYuFw8k/6@L8R/5R9UxxjLz5@tN5REsnOsaala5rnR3i8v2O4UmJpVodjeybELVGhwe1VNSslBBUxZYYo993jZdN94YXzCqoICdYEyiCDcELwZZgR7AnOIChDKKQcuIVFlI@p1iYYM6dDfs7FlLOnZyFlM8pFhRf3/L1yd@zkHLurFlI@ZwCAybL4vN@AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# J, 56 chars
Reads 9 lines of digits from ARGV and does magic:
```
echo-.*/,(b~:0),,(2 2$3)(-:~.)&,;.3 b=:"."0>cutLF{:>ARGV
```
Part of this is infused with an older script I wrote for a similar challenge elsewhere, so I don't remember what everything does. What I *do* remember is that `;.3` is really the funny magic here, because it "divides" the matrix of numbers into smaller "squares" according to the value `2 2$3` (I don't remember what it means, but pretend it's important).
[Try it online!](https://tio.run/##DYsxCsJAEEX7OUUIIols1uzM7MzOigEbbawsPECCIDY2Wgm5@rrV47/Pe5XyWJ7vwe/2rpvXPPbOddjghvpuyKvvt@7gqZmPufXtOC3fz/X8y9PpdrmXUpIwacBoQBgTm0oAq0LqIGCSYNUrBEsSlQkBKxJZEJBkSlxj0EARkxhDZKwXafoD)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 36 bytes
```
|©vy3ô})3ôøvyJvyê}}®øvyê}®vyê})êžh¦Q
```
[Try it online!](http://05ab1e.tryitonline.net/#code=fMKpdnkzw7R9KTPDtMO4dnlKdnnDqn19wq7DuHZ5w6p9wq52ecOqfSnDqsW-aMKmUQ&input=MTIzNDU2Nzg5CjQ1Njc4OTEyMwo3ODkxMjM0NTYKMjMxNTY0ODk3CjU2NDg5NzIzMQo4OTcyMzE1NjQKMzEyNjQ1OTc4CjY0NTk3ODMxMgo5NzgzMTI2NDU)
1 is true, anything else is false.
[Answer]
**Clojure, 151 bytes**
Quite long, but others seem to be as well. Also annoying that union of sets requires a `require`, so I used a concat of vectors instead.
Iterates over each row and column and if the value is between 1 and 9 it emits three vectors, one for row, col and 3x3 cell. Returns 0 on success and `nil` otherwise, with two extra characters could return 1 on fail. Handles numbers outside of 1 - 9 by returning `nil` but will crash on other anomalies such as non-integer values. Quotients are 0 - 2 so it is safe to use values `8` and `9` to differentiate cell values from rows and columns.
```
(fn[s](if(= 243(count(set(apply concat(for[i(range 9)j(range 9)](let[v(nth(nth s i)j)q #(quot % 3)](if(<= 1 v 9)[[8 v i][9 v j][(q i)(q j)v]])))))))0))
```
Input is a nested vector of vectors (so that `nth` works):
```
(def sudoku [[1 2 3 4 5 6 7 8 9]
[4 5 6 7 8 9 1 2 3]
[7 8 9 1 2 3 4 5 6]
[2 3 1 5 6 4 8 9 7]
[5 6 4 8 9 7 2 3 1]
[8 9 7 2 3 1 5 6 4]
[3 1 2 6 4 5 9 7 8]
[6 4 5 9 7 8 3 1 2]
[9 7 8 3 1 2 6 4 5]])
```
Ungolfed:
```
(defn f [s]
(->> (for [i (range 9) j (range 9)]
(let [v (-> s (nth i) (nth j)) q #(quot % 3)]
(if (<= 1 v 9)
[[:row v i] [:col v j] [:cell [(q i) (q j)] v]])))
(apply concat)
set
count
(#(if (= 243 %) :pass :fail))))
```
[Answer]
# PHP, ~~196~~ 190 bytes
```
while($i<9){for($b=$c=$k=$y="";$y++<9;)$b.=($a=$argv)[$y][$i];for(;$k<3;)$c.=substr($a[++$k+$i-$i%3],$i%3*3,3);if(($u=count_chars)($a[++$i],3)<($d=123456789)|$u($b,3)<$d|$u($c,3)<$d)die(1);}
```
Program takes 9 separate command line arguments (one string of digits for each line of the grid);
exits with `1` (error) for invalid, `0` (ok) for valid.
Run with `php -nr '<code>' <row1> <row2> ...`.
**breakdown**
```
while($i<9)
{
for($b=$c=$k=$y="";$y++<9;)$b.=($a=$argv)[$y][$i]; // column to string
for(;$k++<3;)$c.=substr($a[$i-$i%3+$k],$i%3*3,3); // sub-grid to string
if(($u=count_chars)($a[++$i],3)<($d=123456789) // check row
|$u($b,3)<$d // check column
|$u($c,3)<$d // check sub-grid
)die(1); // test failed: exit with 1
}
```
**explanation**
`count_chars` counts characters in a string and usually creates an array with ascii codes as keys and character count as values; but with `3` as mode parameter, it creates a sorted string from the characters; and that can easily be compared to the number with the wanted digits.
The comparison does not only check for duplicates, but also includes the check for invalid characters. And it only requires `<`, not `!=`, because this is numeric comparison: PHP will interpret the string as a number as far as it can. `123e56789`, `0x3456789` or similar cannot appear, because the characters are sorted; and any pure integer with a digit missing is smaller than `123456789` ... and `.23456789` too, of course.
`$a=$argv` saves one byte, `$d=123456789` saves nine and `$u=count_chars` saves 13.
[Answer]
# C# - 306 298 288 characters
The following Console program was used to call the checking function;
```
static void Main(string[] args)
{
int[,] i={{1,2,3,4,5,6,7,8,9},
{4,5,6,7,8,9,1,2,3},
{7,8,9,1,2,3,4,5,6},
{2,3,1,5,6,4,8,9,7},
{5,6,4,8,9,7,2,3,1},
{8,9,7,2,3,1,5,6,4},
{3,1,2,6,4,5,9,7,8},
{6,4,5,9,7,8,3,1,2},
{9,7,8,3,1,2,6,4,5}
};
Console.Write(P(i).ToString());
}
```
All this does is initialise the array and pass it into the checking function P.
The checking function is as below (in Golfed form);
```
private static int P(int[,]i){int[]r=new int[9],c=new int[9],g=new int[9];for(int p=0;p<9;p++){r[p]=45;c[p]=45;g[p]=45;}for(int y=0;y<9;y++){for(int x=0;x<9;x++){r[y]-=i[x,y];c[x]-=i[x,y];int k=(x/3)+((y/3)*3);g[k]-=i[x,y];}}for(int p=0;p<9;p++)if(r[p]>0|c[p]>0|g[p]>0)return 1;return 0;}
```
Or in fully laid out form;
```
private static int P(int[,] i)
{
int[] r = new int[9],c = new int[9],g = new int[9];
for (int p = 0; p < 9; p++)
{
r[p] = 45;
c[p] = 45;
g[p] = 45;
}
for (int y = 0; y < 9; y++)
{
for (int x = 0; x < 9; x++)
{
r[y] -= i[x, y];
c[x] -= i[x, y];
int k = (x / 3) + ((y / 3) * 3);
g[k] -= i[x, y];
}
}
for (int p = 0; p < 9; p++)
if (r[p] > 0 | c[p] > 0 | g[p] > 0) return 1;
return 0;
}
```
This uses the idea that all columns, rows and sub-grids should add up to 45. It works through the input array and subtracts the value of each position from it's row, column and sub-grid. Once complete it then checks that none of the rows, columns or sub-grids still have a value.
As requested returns a 0 if the array is a valid Sudoku solution and non-zero (1) where it's not.
] |
[Question]
[
[Chef Avillez](https://en.wikipedia.org/wiki/Jos%C3%A9_Avillez) is about to cook us some really nice meal. He is just waiting for us to give him some ingredients and to request a meal.
# Task
Given a list of ingredients (strings matching `/[a-z]+/`) and a requested meal (string matching `/[a-z][a-z ]*/`) output the integer amount of meals Chef Avillez can make.
## Algorithm
Each letter (`[a-z]`) in the ingredient list contributes with one character for the soon-to-be-cooked meals. Each portion of our requested meal costs as many of each character as there are in the request string, excluding spaces.
For example, if our requested meal is `"bacon"` and the ingredients are `"banana"` and `"coconut"`, the output is `1` because in `"bananacoconut"` there is only one `b`, and for each portion of `"bacon"` we need one `"b"`.
# Input
A list of ingredients in any reasonable format, like
* a list of strings
* a list of lists of characters
* a (whatever-you-please)-separated list of ingredients, in a single string
and a requested meal in any reasonable format, like
* a string
* a list of characters
# Output
A non-negative integer representing the amount of meals that can be cooked.
# Test cases
A [Python reference implementation](https://tio.run/##hVPbbtswDH33V3B6sQ146UPfCmw/UgSDItO2OltMJRnBGuTbM1IK5LZIURgwb@ccyjJ5/Bcnco/Xa48DGKK/jXVj6MDja/tUASilJAE2gIbZhgg0QIg@JbXrBZiLOcn4immp/AsUqN0LWZdEW84bWl2Uytk8CXWXEo1pYSAPhnlZkM8CPxL/wiyPcfUOlptQIT08OMQ@ZG4HOWCJ3GVnIy6hadtrxBD/GB1QOj@zYPOswlEvqoMv7UEbcuLgOIb3thQSci8Z1C6otsvCpf6tsy/exnX8CMIQ59d4B1M0ilbRLNp3aJEWHUkA5HHULrlH@/aW203cb9YR7zD5x@rTAb23mC5gsPkiNo5chva9dQzYp8P3MNgwbc0nDAmmfUbTkqznCaJ03SfyfcjOKWmQ3w5wQy@U2T3O1lhaE54HwmNvkX@4hBP62zfQTKOTtp9lvqVv5zzwxIf7crXI1R3UBxk2O6xzCvR482iQ9zt5CUVerM4mydef5Kt9VclAlz2Uid4mWJbyyJsWm0GdBXNhoTPDLjX8/M179XGHL6q9/gc) is available.
```
['spam', 'spam', 'spam', 'spam', 'bacon', 'eggs', 'eggs', 'bacon', 'spam'], 'beans' -> 2
['bacon', 'bacon', 'bacon', 'bacon', 'bacon'], 'bacon' -> 5
['banana', 'coconut'], 'bacon' -> 1
['acon', 'bcon', 'baon', 'bacn', 'baco'], 'bacon' -> 4
['tomato', 'oregano', 'pizza', 'chocolate'], 'bacon' -> 0
['strawberries', 'figs', 'chocolate', 'sardines'], 'cod fish' -> 1
['these', 'are', 'some', 'random', 'words', 'wow'], 'or' -> 3
['some', 'more', 'delicious', 'ingredients', 'here'], 'bolognese' -> 0
['some', 'delicious', 'ingredients', 'here', 'are', 'bliss'], 'bolognese' -> 1
['some', 'bountiful', 'bagful', 'of', 'ingredients', 'here', 'are', 'bliss'], 'bolognese' -> 1
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~95~~ ~~71~~ ~~70~~ 55 bytes
```
lambda i,m:min(i.count(c)/m.count(c)for c in m if" "<c)
```
[Try it online!](https://tio.run/##hVHBbtswDL3nKwjtUBtxs3XdLsXcH@lyUGTZ5mCJAiUva38@I@3A24IBhQ9@It97fJTSaxkpfr707ffLZMOps4BNeAoYKzw4mmOpXP0xbLAnBgcYIQD2Bsw3V18wJOIC@TXvdtqfMHqlSOGQS4fxaQfwAdjbTsppLg34X8m74juguUhB@lmK0EKwqcqFRceYmsXqkNOEpTL3z6auhYmNDG/B/7RTlbWgOpR0vl7mFLYxSw5JGAf2HfpYMhQCRyFYyD5ZtjpbZ8RBHcXANObwg3Tt1WXwRRLnedJwLIS@kovRXhJVAfNi9rg3RyNpGtBwDbCAyuzFt@K29fXe1ObycneyjuJdA@@D44bg/hm@7lQb5VOGI6nP5YbzIJzNY/PaPDfvG9kXkRUKtpASiP1g4wITvr2t40aZN8k93Sg/iVIWtOeTZ0afldvjkP/VyCFblqcXwnEJ30GPedwyl9HnhWZ5ZVNY/vJ2HQVFZ@Iur@C8eBAv6kcNcGUHWtWdn9AhzQv/r1fX4@j5ugNNNEQdu@1xtXlX/ifnacKc/2P38Bs "Python 2 – Try It Online")
**Input**: Ingredients `i` as a comma-separated string, and a meal `m` as a string.
**Output**: Max number of meals that can be made.
**How**: Divides the frequency of each character in the ingredient by its corresponding character in the meal, then takes the minimum.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~55~~ 50 bytes
Meal (m) is a list of characters, and Ingredients (i) is a single string with ingredients separated by spaces.
-5 bytes from Dingus.
```
->m,i{(m-[' ']).map{|c|i.count(c)/m.count(c)}.min}
```
[Try it online!](https://tio.run/##dY3dasMwDIXv8xS6GLSFNnuA0O1B2jIcW4kFthUkh7D@PHvmNd0GY0NwkM75JMnYvs/d/jjvXuKWLuu4O6xgddrU0QyXq71SbXlMeW03z/G7vdWR0m2ePAWEHrNWAHELBHt4eqt1CJThtSnmAN2hrHkjWuJThcnNrbGcmrvCP1p9MakUWC7DmB/mQi3owi9LjzhzNJmBBXuTGAY6n8sFX04Ek7Gy7KAj9Y1mMVOLIoRanF5/IFAjjhJqxdJkj4pgpLgcEcQkxxEmFqdFp6rlwH1hsbnnsTwGh4Es8ahAqRd0hCkreBT8jf9Nfn5rA6l@AA "Ruby – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 29 27 26 bytes
```
<./@(=/<.@%&(+/)]=/]);@cut
```
[Try it online!](https://tio.run/##dY7NTsMwEITvfYoRVZtGQNLycymNFIHECXHg3oOdbBKjxItsV5V64NWDE1eCQpFla@Wdb2be@4skqpCtEeEKS6z9vU7w9Pby3G@SNF9k6SbJZ/PFZRpvs3QbP@TFzvXx5PUxwWo@TbwAn@sYg3iGFaYJsnw7oaJh3CBDJCWklBEqP0JGYXM/bkTBGv@8ARingKwCov1Bwf5/5wbNqehuEAWT4BTsgucfy@WgdtwJx2BDtdCMD3U4@IDGJ7TC0fka1hmxl2SMIotK1fYbgBWmVJrsSBZc@r1tjvDtGNiQJQjjpdwRjNAld9izKa1/9yPH5mfFUdf5hiipVYXinYXStaFSkXYWDZljUW659tl0Unagz4NDCdkqa3/R/Rc "J – Try It Online")
*-2 bytes thanks to Bubbler*
*-1 byte thanks to FrownyFrog*
Inspired by [ValueInk's ruby answer](https://codegolf.stackexchange.com/a/201689/15469) -- be sure to upvote him.
Both args are strings. Meal is right arg. Ingredients are left arg and taken as space separated string.
Consider the example:
```
'banana coconut' f 'ba con'
```
`-.&' '` removes the spaces from the right arg:
```
'banana coconut' <./@(=/<.@%&(+/)]=/]) 'bacon'
```
Now the main verb is a fork whose tines are `=/` and `]=/]`. `]` is the right arg so that the right tine runs as `'bacon' =/ 'bacon'`:
```
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
```
And the left tine becomes `'banana coconut' =/ 'bacon'`:
```
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
1 0 0 0 0
0 1 0 0 0
0 0 0 0 1
0 1 0 0 0
0 0 0 0 1
0 1 0 0 0
0 0 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
0 0 0 0 0
0 0 0 0 0
```
Now take the rowwise sum `&(+/)` of each, which results in:
```
1 1 1 1 1 NB. right tine
1 3 2 2 3 NB. left tine
```
In the right tine (meal), the number at index `i` is the count of meal letter `i` within meal (all 1 in this example because the letters are unique).
In the left tine (ingredients), the number at index `i` is the count of meal letter `i` within ingredients.
We divide those elementwise `1 3 2 2 3 % 1 1 1 1 1` = `1 3 2 2 3`, rounding down `<.@` each element to handle fractional amounts (not relevant in this example).
Finally we take the min `<./@` of the whole result, which in this case is `1`. This reflects the constraint of having a single `b` in our ingredients, limiting the number of meals we can make to 1.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 94 bytes
```
a->s->{var z=new int[91];for(var c:a)z[c]++;for(;;z[0]++)for(var c:s)if(z[c]--<1)return z[0];}
```
[Try it online!](https://tio.run/##nVJRi9pAEH6/XzEIlqS3CfWxl1MoB4U@9Onok/iwJpu4NtkNMxNFxd9uZ43eiae0lJBdZub75vsSvqVe6WRZ/D7YpvXIsJQ67djW6efs4UOv7FzO1rswzGtNBD@1dbB7AGi7eW1zINYs18rbAhqZRa@M1lXTGWisKD5CAb6f9jznC43Tmbqu4YdjUxmcTKCE8UEnE0omu5VG2I6dWYN1PP06mmWlxyh08ycdb6f57PHx2Mqy7fSLFPH7nGJbRgGSJM@jGA136CCgsv0hO3o6GxWrbIgJxiezADsYzHXunbpzDtQJMIC9uuQ4eVTuZdLxHVC/pV/V7@uX3oGzbzR75dFU2nnV2u1WFBYiUWs2d0jEqNdzg2gNqdJW9M5QpLGwzlCg5r4oLS2uFBeGjNIoUN8YhdoVvlFrjwXJuQ48j1d6AdiIR1UYCYX1HSn5t2gKaxyTWhjsrfraV6JtbtDvM49eJGxEf9sx951jW3a1/NEqXL78v20hECocAcP8Ntz30TnHLCCe@vTEb@EJgwtRiVUASPJS9r/a1uCLJhPFUr1I@L8h6k0UZxfkxuj6zBr9E@t1Q2ya1HecthJqLqPBkOATyJFMYFgMQ2JvulC3ZRSUqW7behNdfEl8agV/8Ul7/xDe/eEP "Java (JDK) – Try It Online")
Both inputs are uppercase letters to save a byte. If not allowed, please tell me, I'll fix it and add the byte.
## Credits
* Kevin Cruijssen for tidying up the inputs
[Answer]
# JavaScript (ES6), ~~59 ... 51~~ 50 bytes
Takes input as `(ingredients)(meal)`, where *ingredients* is the list of ingredients as a comma-separated string and *meal* is a list of characters. All names are expected in upper case.
Returns *false* [instead of 0](https://codegolf.meta.stackexchange.com/a/9067/58563).
```
s=>g=m=>m.every(c=>s<(s=s.replace(c))|++c)&&1+g(m)
```
[Try it online!](https://tio.run/##jdHRasIwFAbg@z2FVzbFrM7N3a1C2h7bQJtIEhEcu5CuyoZasUMY7N271KCT1jIbOBCSfvx/@7k4LIp0/7H7ut/m71m5dMvCHa3cjTvaONkh23@j1B0VL6hwC2ef7daLNEOpbf/0eqnd7Q56K7SxyzTfFvk6c9b5Ci2RJSckwbXhEZ8zDGEozTD76siy0avjOJYHhEnrzbY7/X7n8a5mmvst80wcNxXReLT53DSZXtjn@q2pugFpmoO6aUKZZCaeyXirrs1h3VQ8IYpjLiAkjOMJnc916kjHjomC/2VtPtRNqQSZeSAEBYnHVP@RM4glEQFlIE@yz4POmMroEr/WXUUgAROhBZ4AFoQFPMEzLgKp5@zEcdHSX5tPjZyVlOjqOICY@pRPJaYsFBBQYEriCMTfF@AxD3VuuPCvdq/Mdu7YwIuplC1w1b38BQ "JavaScript (Node.js) – Try It Online")
### Commented
```
s => // s = list of ingredients
g = m => // g is a recursive function taking m[] = meal,
// as a list of characters
m.every(c => // for each character c in m[]:
s < ( // test whether s is less than ...
s = // ... the updated value of s where ...
s.replace(c) // ... the 1st occurrence of c is replaced with 'undefined'
) // end of comparison (falsy if c was not found)
| ++c // force a truthy result if c is a space
) && // end of every(); if successful:
1 + g(m) // increment the final result and do a recursive call
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 15 bytes
```
⌊⌂dab⍛(⌊/⍧÷⊣⍧⊣)
```
[Try it online!](https://tio.run/##NU0xTgMxEOx5xXaGIqLgCTSkQiJ8YH3eu7Pk80a2o4SUiZTilIugoKKkoKSkh5/sR469IFaaGY00O4PLMHNPGLiZ0aZQdOTGUY69HHcOrQxvl2quZfj4@ZL@XVX5aqzl8CzDSU6v83vp99@fN3J4Ubd4uFV@vJsvRmNZSyNlgv8zUIPJ3BFYXsXi61UAi80kXIOPTSLnKZYMLSUCVNjgczYXxmLF8fxfuMPCwIkajAxLv90iVC1XHLCQRjn95dppeuo4LyaMjjtYc3JZeW1@AQ "APL (Dyalog Extended) – Try It Online")
A dyadic train which takes the meal as its left arg and space-separated ingredients as right arg. (Comma-separated ingredients should work equally well.)
### How it works
```
⌊⌂dab⍛(⌊/⍧÷⊣⍧⊣) ⍝ Left: meal, Right: ingredients
⌂dab⍛( ) ⍝ Remove all spaces from the meal
⍧ ⍝ Counts of each char of meal in the ingredients
÷ ⍝ Divided by
⊣⍧⊣ ⍝ Counts of each char of meal in the meal
⌊/ ⍝ Minimum
⌊ ⍝ Floor (the result of division might be fractional)
```
Without the space-handling requirement, the code would be **9 bytes**:
```
⌊/⍤⌊⍧÷⊣⍧⊣
```
[Try it online!](https://tio.run/##JY0xbgIxEEV7TjGdK0SRI9CEKhLkAuP17K4lrwfZRhDaSBSrLEqKnCCRKCnpyU3mIpvJppj/9KU//@M2zN0LBm7mdCgUHblxlLd@IcO3QobLz036L6XqWMvpXYaznD9XT9K/3q8PcvpQt1kvVZ8fV5vRWNaySJkM1GAydwSWd7H4ehfAYvMHrsHHJpHzFEuGlhIB6tngczYzY7HiOP0X7rAwcKIGI8PWH48IVcsVByykUU7/uVYXp45pMWF03MGek8uqe/ML "APL (Dyalog Extended) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes
*-1 byte thanks to Kevin Cruijssen*
```
Jsθáδ¢`÷ß
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fq/jcjsMLz205tCjh8PbD8///j45WKi4pSixPSi0qykwtVtJRUErLTAfTyRn5yfk5iSWpIE5xYlFKZh5QQayOQrRSMkgoH0SkgAgFsDYQkQlWCyIylGJjAQ "05AB1E – Try It Online") or [validate all test cases](https://tio.run/##lY9BTsQwDEX3nCLquuxZMTsWXGE0Em5jWkttjJyMKs0p5gYIzoAEa7qfK5XEYTLApkKVfn8S@32bPTSEy83dfNxU5vrWVJvl3p8@5pfT2@frw/w@Py/1st1WDbTsqtqsm11tYnk6Q5I2CSeJT7srRbn46RvHhn1YbykJJakkluR1SuARgt6wYAdO7RMdDrm@j9MMEHAd5IPA1KAIoU/3j9T534h48CCWXCxQ3AVikxhtS0Jam6Q/j9mjVwJIBvGofwFneUxuYrE@mynjlSzn8b4bRs4AiwO1xHttIdcJWkIXcijKz4WVMxTX5a2jYBkT/6Ss0i@bNAN5//@0Lw).
Takes the ingredients as a list of strings, and the meal as a list of characters.
```
J # join each input
sθ # get the last input (meal)
á # keep only letters
δ¢ # double-vectorized count occurences
` # dump to the stack
÷ # integer division
ß # minimum
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~54~~ ~~63~~ 60 bytes
```
s=>t=>t.Min(x=>x>32?s?.Count(c=>c==x)/t.Count(c=>c==x):null)
```
`Min` can calculate the minimum selectively if `int?` objects are used. To obtain such objects, I use the `?.` operator: `s` will never be `null`, but it casts `int` to `int?` for 1 byte anyway.
[Try it online!](https://tio.run/##bY7BCsIwDIbvPkXZaQWdoDe13UHYTfAVuqxzhS2BpGN7@7mpByeSn0Dy/18IyA4kTEWPcJHIAR9btRoCxtxaVSijJjE2zspuAdPR2NEeD7nk2ZV6jCkYC8aMeh9/Fifs21ZP5819vhjTIk1KB4T/WqI/ZqL1V37@xQ2lZw5e6vAQaAioddGL4yqgl4UDqlQdpFmjsfHiHXuhzrPDirqBuJKBhoUhXqeJl3o76qXFn54 "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 48 bytes
```
%O`.
L$`\G((.)\2*)(?=.*¶.*?(\1)+)?
$#3
N`
1G`
```
[Try it online!](https://tio.run/##dY1BasQwDEX3PoWgM@CkJpB2XbKcTWkX3WZhJ1YTQ2INkofAHKwH6MVSk0wpFAbBB/3/pM@YQnT1etQf1qyg1PHdVur1YNuT1lXRPpWFbl6q8vurKhvd1sVj0ajDw7N6s6o@2XXtXE/RbAp3VP0yMQ/0lJdLupk7taM7vx/d4kSzSwTEOLhIcA7Xa/4w5heTS6h68vAZZDSS2C0dMgeU7AzyB4E49iGiKGKTRhQEx9mlGYFd9DTDQuwl66I6mmjILJotn3MxeJxCH@giEOLA6APGJDAi43/8PrlVdlMQ@QE "Retina – Try It Online") Link includes test suite. Takes input as dish on the first line and space-separated ingredients on the second line but the test suite uses a more convenient comma separator. Explanation:
```
```
Delete spaces in the dish and ingredients.
```
%O`.
```
Separately sort the letters in the dish and ingredients.
```
L$`\G((.)\2*)(?=.*¶.*?(\1)+)?
$#3
```
For each distinct letter in the dish, count the number of times its appearance in the dish divides into its appearance in the ingredients.
```
N`
```
Sort the counts.
```
1G`
```
Take the minimum.
[Answer]
# [Perl 5](https://www.perl.org/) `-nlF`, ~~54~~ ~~47~~ 39 bytes
*Shoutout to @Grimmy for helping me fix an issue with no net gain of bytes*
```
$_=<>;$j++while s/$F[$j%@F]//x;say$j/@F
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3tbGzlolS1u7PCMzJ1WhWF/FLVolS9XBLVZfv8K6OLFSJUvfwe3//6TE5HyFvHyuaHUQC4jz8tVj/@UXlGTm5xX/1/U11TMwNPivm5fjBuRk5pWkpqcWAQA "Perl 5 – Try It Online")
First line of input is the recipe; second line contains the ingredients (doesn't matter how or if they're separated).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 16 bytes
```
hSmL//hQd/eQdsce
```
[Try it online!](https://tio.run/##K6gsyfj/PyM410dfPyMwRT81MKU4OfX/f/WSjNTiVJ3EolSd4vzcVJ2ixLyU/Fyd8vyilGIgWa6uo6Cer1CkDgA "Pyth – Try It Online")
### Explanation
```
hSmL//hQd/eQdsce(Q)
(Q) : Implicit evaluated input
e : Get last element of input
c : Split string at spaces
s : Concatenate split strings
L : Lambda with argument named d
Q : Evaluated input
h : Get first element of input
/ d : Count occurrences of d in first element of input
Q : Evaluated input
e : Get last element of input
/ d : Count occurrences of d in last element of input
/ : Divided occurrences of d in first element of input by occurrences of d in last element of input
m : Map the lambda over last element of input
S : Sort the result of the map
h : Get the first element from result of sort
```
[Answer]
# C (gcc), ~~135~~ 133 bytes
Expects ingredients and request as command line arguments (the last one is the request). The return value of the program is the result.
```
l[128],n;char*a;main(c,v)char**v;{for(++v;c---2;)for(a=*v++;*a;++l[*a++]);for(a=*v,n=l[*a];*a;++a)n=*a-32&&l[*a]<n?l[*a]:n;return n;}
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~117~~ \$\cdots\$ ~~103~~ 70 bytes
Saved a whopping 33 bytes thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!!!
```
f=lambda l,m:all(e in l and[l.remove(e)]for e in m if' '<e)and-~f(l,m)
```
[Try it online!](https://tio.run/##hZLBTuMwEIbvfYoRlzirgGDLCqkiHHkCbiUHt5k0g2xPNXaoIMq@etdxu9mUPRAf8jv@/2880ew/QstueTw2pdF2U2swhV1pYxQCOTCgXb02N4KW31FhXjUskI4sUJNB9oh5tFz/blQM5seAPngoQS0gPkqts43esssK@F5Uk8oL@JUXM4SLazRuOR534dJ6N7NOxIk8VZgqXabvZ@nAVgcefSy40y7JPX1@noq3sbrRAS8BtzOAD6IPGxQh9GOkoZ2/jMaN11KTi4YqdVRDQ7792kho0Se3llOIbXpL/NtsR3Vgqf1JHBKKZYQs59c5hyyfIDUa2hJ3KUZuJ1gTupC2Lcq5MTa8c2P1r82dad9S/t16Y8j7/6l/G80XEmelf5EOV9Blr93Ph7tlzD1r46cv99tsWIxjF4o0eGnEVilPhY35kLQvG7X@kWU3b0xOUV7FcUwHeyEXVHPV01D0doDrJ@j9AL2sfVliNVzli@Mf "Python 3 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
kS £V¬èX zU¬èXÃrm
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=a1Mgo1as6FggelWs6FjDcm0&input=WyJiIiwibyIsImwiLCJvIiwiZyIsIiAiLCJuIiwiZSIsInMiLCJlIl0KWydzb21lJywgJ2JvdW50aWZ1bCcsICdiYWdmdWwnLCAnb2YnLCAnaW5ncmVkaWVudHMnLCAnaGVyZScsICdhcmUnLCAnYmxpc3MnXSA)
[Answer]
# [JavaScript (V8)](https://v8.dev/), 136 bytes
```
(a,b)=>{b=b.filter(a=>" "!==a),c=-1,d=!1;do c++,d=!0,b.forEach(b=>-1==(i=a.indexOf(b))?d=!1:a.splice(i,1)),c=d?c:c--;while(d);return c};
```
## Input:
* Ingredients: array of characters
* Meal: array of characters
Original commented code (`a=ingredients, b=meal, c=meals, d=yes`):
```
f = (ingredients, meal) => { // es6 arrow function syntax
meal = meal.filter(i => i !== ' '); // delete all the spaces
meals = -1 // set number of meals to -1, since we'll be adding one later on
yes = false // yes is whether there are any meals left to make
do { // do...while instead of while so it runs at least once
meals++; // increment meals
yes = true; // yes there is a meal to make
meal.forEach(v => { // es6 arrow function for each character of the meal
return (i = ingredients.indexOf(v)) == -1 ? // ternary operator, set i to index of character in ingredients, then check if its -1
yes = false // if it is we can't find the character, so we can't make a meal
: ingredients.splice(i, 1) // we take out the letter from the ingredients list
});
meals = // assign to meals
yes ? // ternary operator, check if we made a meal
meals : meals-- // if we didn't make a meal then decrement meals
} while (yes) // repeat if we made a meal
return meals; // return the number of meals
}
```
Methods mentioned:
* [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)
* [ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)
* [do...while](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while)
[Try it online!](https://tio.run/##tVJLbsIwFNz3FIENtkiiZlcRGVZd9wAVC8d2PlWwkR1I1apnT214bk0KKkjtYuT4/WbeOC90Tw3TzbZL9g9DSQZE4wKT5XtBirRs2k5oRMlyGk0nhFAcM5JkMSeTLOcqYvO5@76PbanSj5TVqCDLJCMENYSmjeTi9alEBcYr17Kgqdm2DROoiTPsZvEVW7Akyfu6aQXiONei22kZsY98YEoa1Yq0VRUq0fOsmMUzasEslIW0@NvYOo7O0awxzu8uqZGj07eFTDuL7qbp57Se035ul5@73cLcQXoD5f7uoC2ERRXs7OJbi8biDeBp6pEXbTBT3KTKQJeG8h52FBDToMDdXW0J9wruv6s51lGYxaFffuUOan2rS0cBjTmMv@hnHTCIgMXHvN8i2FACjc/1wRtw6POx/qjumL7oX8iyGb0oh7OFhRicCv5eE/hRjfq87xK8NMHG@vSlve0KxsgTY65S/r9KT9@mCHjM919w3SbDJw "JavaScript (V8) – Try It Online")
[Answer]
# [Erlang (escript)](http://erlang.org/doc/man/escript.html), 81 bytes
To fix the bug I had to switch to filtering.
```
f(I,M)->lists:min([length([X||X<-I,X==C])div length([X||X<-M,X==C])||C<-M,32<C]).
```
[Try it online!](https://tio.run/##jYwxC4MwEIV3f4U4JXA6tJuoSycHd0EcUhs1EBNJri2I/z09oUNLl97Bce/eu086LcyUSj84tWKIwshqaHhaaeXR54syrNPSTDizrt33tkhraMvy0vObesTfTvN29v1yiPOpIJGFRRyQnsdpFcVUyuZPp1CykSVXYahhsIM1d0yADrQlnAOljGYcfl7QLgItWCcnYSysatsIMBNBC5T/IaRHOAalET@iWXgB "Erlang (escript) – Try It Online")
## Explanation
```
f(I,M)-> % Function with operands I and M
lists:min( % Find the minimum of this list.
[length( % Find the length of:
[X||X<-I,X==C] % I items only containing C
)div % Integer-divided by
length( % the length of
[X||X<-M,X==C] % M items only containing C
)||C<-M, %Where the item is taken from M
32<C] % and the current item is larger than the space
).
```
[Answer]
# [MS SQL Server 2017](https://docs.microsoft.com/en-us/sql/sql-server/sql-server-technical-documentation?view=sql-server-2017), 300 bytes
```
CREATE FUNCTION F(@ NVARCHAR(MAX),@R NVARCHAR(MAX))RETURNS
TABLE RETURN WITH A AS(SELECT LEFT(@R,1)C,STUFF(@R,1,1,'')R
UNION ALL SELECT LEFT(R,1),STUFF(R,1,1,'')FROM A
WHERE R!=''),B AS(SELECT(LEN(@)-LEN(REPLACE(@,C,'')))/COUNT(*)OVER(PARTITION BY C)R
FROM A WHERE C LIKE'[A-Z]')SELECT MIN(R)R FROM B;
```
Try it on [db<>fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2017l&fiddle=430c11e47063451feba4b5440a14af39).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
I⌊EΦη№βι÷№θι№ηι
```
[Try it online!](https://tio.run/##NcpNCsIwEIbhvaeYZQrxBC4rgouCV8jP0AwkM5pJev20Vfzg27w8IbkaxOUxXpW4mdlpMwsxlV7M4t7mQblhNcnCLP0A3gJNk4UntzttFNH8@ufsf5S@6NxtDJWCEDFTIOkKxGvFSMhNIWFFcMd9JtWLlywro@K4bnkH "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a space-separated list of ingredients on the first line and the dish on the second line. Explanation:
```
η Second input (dish)
Φ Filter over characters
№ Count of
ι Current character
β In lowercase alphabet
E Map over characters
№ Count of
ι Current character
θ In ingredients
÷ Integer divide by
№ Count of
ι Current character
η In dish
⌊ Take the minimum
I Cast to string
Implicitly print
```
] |
[Question]
[
A bit floats from the [LSB](https://en.wikipedia.org/wiki/Bit_numbering#Least_significant_bit) to the [MSB](https://en.wikipedia.org/wiki/Bit_numbering#Most_significant_bit) moving one position each time until it floats to the *top* of the container:
```
0000
0001
0010
0100
1000
```
Once one bit floats to the top, another bit begins its journey and it stops when it meets other bit:
```
1001
1010
1100
```
This happens until the container is filled with bits:
```
1101
1110
1111
```
### Challenge
Given an integer number, output the "*Bit floating sequence*" for a container of that number of bits.
* Each term of the sequence can be separated by any separator of your choice.
* **Edit**: Sequence must be shown as decimal integer numbers, starting by the first therm: `0`.
* The container size sould be greater than zero and up to the number of bits of the bigest integer suported by the language of your choice. You can assume that the input always match this requirement.
### Examples
Only the numeric sequence is required, binary representation is shown as example:
* For **1**: `0 1`
```
0 -> 0
1 -> 1
```
* For **3**: `0 1 2 4 5 6 7`
```
000 -> 0
001 -> 1
010 -> 2
100 -> 4
101 -> 5
110 -> 6
111 -> 7
```
* For **4**: `0 1 2 4 8 9 10 12 13 14 15`
```
0000 -> 0
0001 -> 1
0010 -> 2
0100 -> 4
1000 -> 8
1001 -> 9
1010 -> 10
1100 -> 12
1101 -> 13
1110 -> 14
1111 -> 15
```
* For **8**: `0 1 2 4 8 16 32 64 128 129 130 132 136 144 160 192 193 194 196 200 208 224 225 226 228 232 240 241 242 244 248 249 250 252 253 254 255`
```
00000000 -> 0
00000001 -> 1
00000010 -> 2
00000100 -> 4
00001000 -> 8
…
…
…
11111000 -> 248
11111001 -> 249
11111010 -> 250
11111100 -> 252
11111101 -> 253
11111110 -> 254
11111111 -> 255
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
LRL˜Íoî.¥ï
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fJ8jn9JzDvfmH1@kdWnp4/f//JgA "05AB1E – Try It Online")
```
L # range [1..input]
R # reversed
L # convert each to a range: [[1..input], [1..input-1], ..., [1]]
˜ # flatten
Í # subtract 2 from each
o # 2**each
î # round up (returns a float)
ï # convert to integer
.¥ # undelta
```
[Answer]
# [Python 2](https://docs.python.org/2/), 45 bytes
```
y=n=2**input()
while y:print n-y;y=y&y-1or~-y
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9I2z9ZISyszr6C0REOTqzwjMydVodKqoCgzr0QhT7fSutK2Uq1S1zC/qE638v9/UwA "Python 2 – Try It Online")
It turns out shorter to generate `2**n` minus each term in the sequence for input `n`. If we look at their binary expansion, below for `n=5`, we see a nice pattern of triangles of 1's in the binary expansions.
```
100000 32
011111 31
011110 30
011100 28
011000 24
010000 16
001111 15
001110 14
001100 12
001000 8
000111 7
000110 6
000100 4
000011 3
000010 2
000001 1
```
Each number is obtained from the previous one by removing the rightmost one in the binary expansion, except if that would make the number 0, we subtract 1 instead, creating a new block of 1's that starts a new smaller triangle. This is implemented as `y=y&y-1or~-y`, where `y&y-1` is a bit trick to remove the rightmost 1, and `or~-y` gives `y-1` instead if that value was 0.
**[Python 2](https://docs.python.org/2/), 49 bytes**
```
def f(n,x=0):1%n;print x;f(n-x%2,x+(x%2**n or 1))
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI0@nwtZA08pQNc@6oCgzr0ShwhooqFuhaqRToa0BpLS08hTyixQMNTX/p2mYav4HAA "Python 2 – Try It Online")
A function that prints, terminating with error. The more nice program below turned out longer.
**51 bytes**
```
n=input()
x=0
while n:n-=x%2;print x;x+=x%2**n or 1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERDk6vC1oCrPCMzJ1UhzypP17ZC1ci6oCgzr0ShwrpCG8TV0spTyC9SMPz/3xQA "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage/wiki), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
RUḶ’F2*ĊÄŻ
```
Port of [*@Grimy*'s 05AB1E answer](https://codegolf.stackexchange.com/a/191392/52210), so make sure to upvote him!
-1 byte thanks to *@Grimy*.
[Try it online.](https://tio.run/##y0rNyan8/z8o9OGObY8aZroZaR3pOtxydPf///9NAA)
**Explanation:**
```
R # Create a list in the range [1, (implicit) argument]
U # Reverse it to [argument, 1]
Ḷ # Create an inner list in the range [0, N) for each value N in this list
’ # Decrease each by 1
F # Flatten the list of lists
2* # Take 2 to the power each
Ċ # Ceil
Ä # Undelta (cumulative sum) the list
Ż # And add a leading 0
# (after which the result is output implicitly)
```
[Answer]
# Perl 5 (`-n`), ~~41~~ 40 bytes
-1 byte thanls to Xcali
```
map{/01.*1/||say oct}glob"0b"."{0,1}"x$_
```
[TIO](https://tio.run/##K0gtyjH9/z83saBa38BQT8tQv6amOLFSIT@5pDY9Jz9JySBJSU@p2kDHsFapQiX@/3@Tf/kFJZn5ecX/dfP@6/qa6hkYAgA)
* `"{0,1}"x$_` : the string `"{0,1}"` repeated n times
* `"0b".` : concatenate to `"0b"`
* `glob` : glob expansion (cartesian product)
* `map{`...`}` : for each element
* `/01.*1/||` : to skip when `01` followed by something then `1`
* `say oct` : to convert to decimal and say
[Answer]
# JavaScript (ES6), 43 bytes
When in doubt, use [xnor's method](https://codegolf.stackexchange.com/a/191424/58563).
```
n=>(g=x=>x?[n-x,...g(x&--x||x)]:[])(n=1<<n)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k4j3bbC1q7CPjpPt0JHT08vXaNCTVe3oqamQjPWKjpWUyPP1tDGJk/zf3J@XnF@TqpeTn66RpqGoaZeVn5mnoa6joK6piYXqqQxPkkTfJIWKJL/AQ "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~59 57 55~~ 52 bytes
```
f=(n,x=0)=>x>>n?[]:[x,...f(n,x+=x+(x&=-x)>>n|!x||x)]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjT6fC1kDT1q7Czi7PPjrWKrpCR09PLw0krm1boa1RoWarW6EJlKxRrKipqdCM/Z@cn1ecn5Oql5OfrpGmYaipl5WfmaehrqOgrqnJhSppjE/SBJ@kBYrkfwA "JavaScript (Node.js) – Try It Online")
### How?
We define \$p(x)\$ as the highest power of \$2\$ dividing \$x\$, with \$p(0)=0\$ by convention.
This function can be implemented with a simple bitwise AND of \$x\$ and \$-x\$ to isolate the lowest bit set to \$1\$ in \$x\$. For instance:
$$p(52)=52 \operatorname{AND}-52=4$$
Using \$p\$, the sequence \$a\_n\$ can be defined as \$a\_n(0)=0\$ and:
$$a\_n(k+1)=\cases{
a\_n(k)+p(a\_n(k)), & \text{if $p(a\_n(k))\neq0$ and $a\_n(k)+p(a\_n(k))<2^n$}\\
a\_n(k)+1, & \text{otherwise}
}$$
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
x = 0 // x = current term of the sequence
) => //
x >> n ? // if x is greater than or equal to 2**n:
[] // stop recursion
: // else:
[ // update the sequence:
x, // append the current term to the sequence
...f( // do a recursive call:
n, // pass n unchanged
x += // update x:
x + (x &= -x) // given x' = lowest bit of x set to 1:
>> n // if x + x' is greater than or equal to 2**n
| !x // or x' is equal to 0: add 1 to x
|| x // otherwise, add x' to x
) // end of recursive call
] // end of sequence update
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~95~~ 76 bytes
```
n=input()
a=0
print 0
while n:
for j in range(n):print a+2**j
n-=1;a+=2**n
```
[Try it online!](https://tio.run/##Lc1LCgIxEATQfZ2iyWo@CJPoQkb6MGFsnQzSCSGinj7Gz7Ko4lV6lTWqq0s8CxtjqnLQdC9dD88TUg5aaMJjDTchnUGXmGmjoJS9XqXTfv5t/OiGYQPpju3Jj9yS1m@FxuIv2CbIUxb6/FULhz0OOL4B "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 43 bytes
```
{0 x$_,{say :2($_);S/(0)1|0$/1$0/}...1 x$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2kChQiVep7o4sVLBykhDJV7TOlhfw0DTsMZARd9QxUC/Vk9PzxCkpvY/SE2agsV/AA "Perl 6 – Try It Online")
Anonymous code block that takes a number and outputs the sequence separated by newlines. This works by starting with 0 repeated n times then replacing either `01` with `10` or the last `0` with a `1` until the number is just ones.
Or 40 bytes, using [Nahuel Fouilleul's approach](https://codegolf.stackexchange.com/a/191383/76162)
```
{grep /010*1/|{say :2($_)},[X~] ^2 xx$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Or0otUBB38DQQMtQv6a6OLFSwcpIQyVes1YnOqIuViHOSKGiQiW@9n@agsV/AA "Perl 6 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 60 bytes
```
f=lambda i,n=0,b=1:[n][i:]or[n]+f(i-1/b,n^b+b/2,b>>i or 2*b)
```
[Try it online!](https://tio.run/##RYzBCsIwEETv@Yq9tbGrbaMFCaQ/UipkkeCCTUoIBRG/PaZevL1h3sz6So/gVc7OPO1CdwuM3nRIpteTnyfWc4gFGlfzsW8J/Y0aahXSODKECOpAMrsCDOyhR1AIZ4QLwlULgDWyT@UTyl4K8Yti17ddd/Ug/1b11t1An@pU@sWmepP5Cw "Python 2 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), 76 bytes
```
f=lambda n:[0][n:]or[0]+[2**i for i in range(n-1)]+[x|1<<n-1for x in f(n-1)]
```
[Try it online!](https://tio.run/##PcpBCoMwEEbhvaf4l8ZOwWgXEvQkwUXEph1oJxJcWPDuMVJw9@B7y299B2lT8sPHfafZQYytRytmDDHHzTZVxfAhgsGC6OT1LOWuVaZt132f@9TtVP@XdO2a0BBawoPQmQJYIstaMuWVlUoH "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 67 bytes
```
n=0
i=2**input()-1
while n<=i:print n;d=n&(~-n^i)or 1;n+=n+d>i or d
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/WgCvT1khLKzOvoLREQ1PXkKs8IzMnVSHPxjbTqqAoM69EIc86xTZPTaNONy8uUzO/SMHQOk/bNk87xS5TAchL@f/fAgA "Python 2 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 62 bytes
```
def f(n,c=0):
while c<2**n:yield c;r=c&-c;c+=c+r>>n or r or 1
```
[Try it online!](https://tio.run/##ZZDBasMwEETv/orFh2InKtiy7MZOHSilh576AWkoQZGJIchGVkhC6Le7O26gpdVh0b6ZHYntL37f2Wwcd6ahJrJC10lcBXTatwdD@lHOZra6tOawI710tb6710s9r/XcrVaWOkcOJR29GfyH3g5moJrWQZQKWieC0k0sgkjeGkF8yyaU/UZKUC6oEPQwaeqPthBUcgvEIOXRlGmaT@bFf3PKSRl3BVwSQGI@gy2bEgpEQC3ASrASsSVYyapMEhSelVKh5CgQkCeRIhUsCg@rqYVPQVX8msyh5hDyDAVqzl8ONkHQ8MpaQebcU2vpZ3W8dz7d0WOHsyZq481EtsNgnP8WaowJasJ3@2r7o69guLaf7/bt6G/9lZ0MXs690d7sKrryDINwSutda30UPnfOsUxPdjgZF8bjFw "Python 3 – Try It Online")
The idea is more or less the same as [@Arnauld's solution](https://codegolf.stackexchange.com/a/191388/88506).
Another 65-byte solution:
```
lambda n:g(2**n-1)
g=lambda c:[0][c:]or g(c-((c&-c)//2 or 1))+[c]
```
[Try it online!](https://tio.run/##ZZDBSsQwEIbveYqhB0nWLNukad0WehDx4MkH6Bap2XYtaFraLK4sPnudiQuK5jBkvv@fP2HGD/8yuGTpyt3y2rw97xtwxYHr1cqtlWCH8gJtUcV1ZYt6mODA7Zpze7W2YrPRgEQJcV3ZevHt7J9sM7czlFAxriRUsQRVC8m4vjQS8JYElPxGRkIqIZNwEzTzR9tKyLElhEDhqEKq0mDe/jcrTEqwy8ilCWiaT8iWhISMIkjNiOXEcorNieWo6jimgrNaGyopFRIoT1OKNmQx9LAJLfkMqQZf0ympKQlpQoXUFL/MasY6XFwvoT2N0Dv4WV3BAM9w9LTDVcd7UQfSzHM7@W@hpDEJXbRzD248@oIM5/5z5x6P/tKf0Yng/jS21rf7As44gyAKaePUO8@ju2GaUIZbN7@3UySWLw "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
⁼þ‘ṚÄUo€ƊẎQḄ
```
[Try it online!](https://tio.run/##ASYA2f9qZWxsef//4oG8w77igJjhuZrDhFVv4oKsxorhuo5R4biE////OA "Jelly – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Tsãʒ1ÛSO2‹}C{
```
-1 byte thanks to *@Grimy* (also take a look at his shorter approach here).
[Try it online](https://tio.run/##yy9OTMpM/f8/pPjw4lOTDA/PDvZXrHWu/v/fBAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/kOLDi09NMjw8O9hfsda5@r/O/2hDHWMdEx2LWAA).
**Explanation:**
```
T # Push 10
sã # Swap to get the (implicit) input, and get the cartesian product with "10"
ʒ # Filter it by:
1Û # Remove leading 1s
SO # Get the sum of the remaining digits
! # Check that the sum is either 0 or 1 by taking the factorial
# (NOTE: Only 1 is truthy in 05AB1E)
}C # After the filter: convert all remaining strings from binary to integer
{ # And sort (reverse) them
# (after which the result is output implicitly)
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 26 bytes
```
.+
*0
L$w`.(.*)
$.`*1$'1$1
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS8uAy0elPEFPQ09Lk0tFL0HLUEXdUAUoZwEA "Retina – Try It Online") Outputs in binary. If that's not acceptable, then for 39 bytes:
```
.+
*0
L$w`.(.*)
$.`*1$'1$1
+`10
011
%`1
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS8uAy0elPEFPQ09Lk0tFL0HLUEXdUMWQSzvB0IDLwNCQSzUBqNACAA "Retina – Try It Online") Explanation:
```
.+
*0
```
Convert the input into a string of `n` zeros.
```
L$w`.(.*)
```
Match all possible non-empty substrings.
```
$.`*1$'1$1
```
For each substring, output: the prefix with `0`s changed to `1`s; the suffix; the match with the initial `0` changed to `1`.
```
+`10
011
%`1
```
Convert from binary to decimal.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 27 bytes
```
1;0|⟦₅;2z^₍ᵐLtT&-₁↰+ᵐ↙T,L,0
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Om5pT86vKHOxeV1z7cOuFRx/KHu3Y83NUJ4vw3tDaoeTR/2aOmVmujqrhHTb1AQZ@SEDXdR02NQL3aIA1tM0N0fHQM/v@PNtQx1jHRsYgFAA "Brachylog – Try It Online")
Outputs out of order and with duplicates. If that's not okay, tack `do` onto the end.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
I⮌E⊕θEι⁺⁻X²IθX²ιX²λ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyi1LLWoOFXDN7FAwzMvuSg1NzWvJDVFo1BTRwEklqmjEJBTWqzhm5kHJAPyy1OLNIx0FMB6CzWBiuBCmSi8HE0IsP7/3@K/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input
⊕ Incremented
E Map over implicit range
ι Outer index
E Map over implicit range
Iθ Input cast to integer
ι Outer index
λ Inner index
X² X² X² Power of 2
⁺⁻ Subtract and add
⮌ Reverse outer list
I Cast to string
Implicitly print
```
[Answer]
# [Perl 5](https://www.perl.org/), 40 bytes
```
map{say$-;$-+=2**$_}0,0..$_-2;$_--&&redo
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saC6OLFSRddaRVfb1khLSyW@1kDHQE9PJV7XyBpI6KqpFaWm5P//b/Evv6AkMz@v@L@ur6megaHBf908AA "Perl 5 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 24 bytes
```
.+
*0
/0/+<0`(0)1|0$
1$1
```
Outputs in binary. Input should have a trailing newline.
Attempt at explanation:
```
.+ #match the entire input
*0 #replace it with that many zeroes
/0/+<0`(0)1|0$ #while the string has a 0, substitute the first match and output
1$1 #if 01 is present in the string, replace it with 10, else replace the last character with $
```
I tried to avoid the 3 bytes long `/0/` regex option by rearranging the options, but couldn't.
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS8uAS99AX9vGIEHDQNOwxkCFy1AFKGPCBQA "Retina – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), 73 bytes
```
o,j,y;f(x){for(o=j=0;printf("%d ",o),x;o+=y+!y,y+=y+!y)j=!j?y=0,--x:--j;}
```
[Try it online!](https://tio.run/##JcvBCsIwDADQe7@iGwgJS6EnD4bgt4xpZUUbKRMaxr69Cp7e6S1hec7l0btSJuMEDfekFVSyRH7XtWwJxtPNj6RIjXUSmwYj@4tZhnw1iRRCu4SQ@ei/4l/zWgD97hKckV29b59afGR39C8 "C (clang) – Try It Online")
```
for(o=j=0;printf("%d ",o),x; o+=y+!y, y+=y+!y)
// adds 1, 1+1=>2 , 2+2=> 4 .... sequence
j=!j?y=0,--x:--j;
// uses ternary instead of nested loop to decrement 'x' when 'j' go to 0
```
[Answer]
# k4, ~~28~~ 24 bytes
```
0,+\"j"$2 xexp,/-1+|,\!:
```
@Grimy's approach ported to k4
edit: -4 thanks to ngn!
] |
[Question]
[
Given a string and the characters used to encode it, you need to compress the string by only using as many bits as each character needs. You will return the character codes for each character needed to create a compressed string.
For example, given the string `"the fox"` and the encoder characters `" abcdefghijklmnopqrstuvwxyz"`, the output should be `[170, 76, 19, 195, 32]`.
## How, though?
First, you need to map each encoder character to some bits. If we have the encoder characters `abc`, then we can map the characters to bits, by mapping the character to the position of the character in binary, like this:
```
a => 01
b => 10
c => 11
```
With `13579`, we would map it like this:
```
1 => 001
3 => 010
5 => 011
7 => 100
9 => 101
```
Note that we pad zeros at the beginning as many as necessary.
Next, we would go through the string, and for each character, we would get the corresponding bits for that character. Then join all the bits together, and then convert to chunks of 8 to get the bytes. If the last byte is not 8 bits long, add zeros at the end till it is 8 bits long. Lastly, convert each byte to its decimal representation.
[Reverse challenge is here.](https://codegolf.stackexchange.com/questions/247669/i-want-8-bits-for-every-character)
## Test cases
```
String: "the fox", encoder characters: " abcdefghijklmnopqrstuvwxyz" => [170, 76, 19, 195, 32]
String: "971428563", encoder characters: "123456789" => [151, 20, 40, 86, 48]
String: "the quick brown fox jumps over the lazy dog", encoder characters: " abcdefghijklmnopqrstuvwxyz" => [170, 76, 25, 89, 68, 96, 71, 56, 97, 225, 60, 50, 21, 217, 209, 160, 97, 115, 76, 53, 73, 130, 209, 111, 65, 44, 16]
String: "abc", encoder characters: "abc" => [108]
String: "aaaaaaaa", encoder characters: "a" => [255]
String: "aaaabbbb", encoder characters: "ab" => [85, 170]
```
## Rules
* Inputs can be a string, list, or even list of character codes. It doesn't matter, I/O is very flexible for this challenge.
* Input will always be valid, e.g. the string will never include characters not in the encoder characters, etc.
* Encoder characters will always contain \*\*less than 256 characters.
* Neither input will ever be empty.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes for each language wins.
* [Standard I/O rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422).
* [Default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
## Reference implementation in JavaScript
```
function encode(str, encoderChars) {
const maxBitCount = Math.ceil(Math.log2(encoderChars.length + 1));
const charToBit = Object.fromEntries(encoderChars.map((c, i) => [c, (i + 1).toString(2).padStart(maxBitCount, "0")]));
const bits = [...str].map((c) => charToBit[c]).join("");
const bytes = bits.match(/.{1,8}/g) || [];
return bytes.map((x) => parseInt(x.padEnd(8, '0'), 2));
}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=pVTNbtNAEBYSp1x4hZEVkbVwndiJE6dRQKLqASToodyMpTjOJnHq7Kbrdes0zRFOvAEg9QAvxbFPwqydH0dtDwhLK6935vvmm_HOfP_F-Ije3f1O5fjI_fPs6zhloYw4A8pCtJBECmOzFyfTQCQ6rCoAIWeJhHmQvY3kCU-ZhD58COTUDGkUk3wX84lNykgzpmwip_AKLF3v7UhCtH3iyIMUZ8MZDaU5Fnx-yqSIaHLIMA8WhIQGRDr0X4OHOxLlfKbk5-jPJsTWzUUwOpeBkKSkzwCtoel-OfAwkgnG9EzTxCz9DXnOvNPkhb5uznjEiKaVoUtJFVZRIE6GU1I3V5bhrusTHW5vwfOVs6AyFazwLuiznH6BudB3TJJMaT1lI-IaUGvUdANspXC9-R3PXxThEJ5LHVSKJI9Bk1MKY55pu5-Taw5CSUWCZgiG4YiOJ9NodhHPGV9cikSmV9fZ8kbLS2d1GgZ02gZYXbUcA5q2v6fvdqyW7Trt5lMBLLvZctodt7uhcyzUjpQtXC7Stlz_UOxlGoUXMBT8minhMEvniwT4FRIrcxzcLGHEJ_-fkI25uJhUG2vaxe8OKnPw3e2gTRnb6OjgspVkS502VA3UsfKxLKcgcpr4xmU1G1sfCyFtNLdaClDKENU9pVyZCoWNck2CzfMkrADZjvMvoGGBclUNEDgwETknupks4kiS2mdW0_OLmCm3bHusPmp6yeJlXsPfWvFqPgY6xmPPQq84CinBwhxhW6OuqyAmGRqw2XqVSn51zTEXpwE2CfG8BwPFN4CncpFKP--N_XQReYu9Pz_7qPoTCxCNl6Q8llTnHjAdjBUuBM6ShwxFMIzV76sQewTjynuLewOaBljSurb3oHM-iw597n98yd3uf37bOfKYqulHBtVVjliDVl2hgLUGL9W2rBnP-tUVhl5j7tXV41rXA70HlbXeK-bCdlz_BQ)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 19 [bytes](https://chat.stackexchange.com/rooms/240/the-nineteenth-byte)
```
¹żb:∩L∆ZĿf8ẇR8∆ZRvB
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCucW8YjriiKlM4oiGWsS/ZjjhuodSOOKIhlpSdkIiLCIiLCJcIiBhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5elwiXG5cInRoZSBmb3hcIiJd)
```
Ŀ # Replace each element of <the key> in <the input>
# with the corresponding value of...
¹ż # 1...len(key)
b # Convert each to binary
∆Z # left-pad each with zeroes to length
:∩L # The maximum length - the length when transposed
f8ẇ # Reshape into chunks of 8
R R # With each reversed...
8∆Z # Left-pad to length 8 (so right-pad)
vB # Convert each back from binary
```
[Answer]
# JavaScript (ES7), ~~124 122~~ 117 bytes
Expects `(encoder_characters)(string)`, where `string` is passed as an array of characters.
```
(b,o=k=[],i=32)=>g=a=>(i+=~Math.log2(b.length),k|=b.indexOf(a.shift())+1<<i)?g(a,i<25&&(o.push(k>>>24),k<<=8,i+=8)):o
```
[Try it online!](https://tio.run/##rZDJasMwFEX3/QrhRSIRVYnlSSmW@wWlHxC8kGfZjuV4yFBKf92VF1k06SKUPnjwQOjewynFUfRxJ9vhuVFJOmV8ghFWvOK7EEtuUcSDnAseQLniX29iKEitcgojUqdNPhQIV588IrJJ0vN7BgXpC5kNEKGV6fsSveZQYOlTZ7GAirRjX8AqCAJq63@@zxnWqQyhFzXFqulVnc7pMIMGEFGcpFleyLKq941qD10/jMfT@fJhILgjhBhDkYJMnY0QkVLJBi4xWCIEHpn1GuxMb4OB52Jgbud1MLBo@HSDYVLLdlyPba@lW8@0KXNc6y@1v2I4JgZUo9h6mcax2R3FgzIOo4wrEHXq1MxiQDnu2x6oY9qB@bkWHxeQqPyW/IcMqj0wLcRlGOhcjWNrO@4dkia6Vs/nP8i4E7Nh4fQN "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 21 bytes
```
JBUz0ZU⁸,yFŻ8¡s8z0ZḊḄ
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJKQlV6MFpV4oG4LHlGxbs4wqFzOHowWuG4iuG4hCIsIiIsIiIsWyIgYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoiLCJ0aGUgZm94Il1d)
```
JBUz0ZU⁸,yFŻ8¡s8z0ZḊḄ Main Link
J Generate [1, 2, ...] as long as the encoding list
B Convert to binary
Uz0ZU Reverse, transpose padding with 0, transpose, reverse (*)
⁸, Pair the encoding list with the padded binary list
y Use this to translate the message into binary strings
F Flatten
Ż8¡ Prepend 0 8 times (in case the list is shorter than 8)
s8 Slice into blocks of 8
z0Z Transpose padding with 0, transpose (**)
Ḋ Remove the block of 8 zeroes at the start
Ḅ Convert from binary into numbers
(*) this is a common pattern used to left-pad everything to the same length
(**) this is a common pattern used to right-pad everything to the same length -
because we prepended a block of 8 zeroes, there is at least one sublist
of length 8, so everything will be padded to length 8
```
[Answer]
# [Python](https://www.python.org), 115 bytes
```
lambda s,e,o=0:[*sum(-~e.find(x)<<8*(L:=(l:=len(f"{len(e):b}"))*len(s)+7>>3)-(o:=o+l)for x in s).to_bytes(L,'big')]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=pVFLbtswEEW3OcVAm5AObYj6S4h8guy6dIVCH8pmQouKKDl2ivYi3QQo2nt03RO0p-nQjoMsmlUXgwHnPb55j_z6oz-MG909fWvzD9-nsZ0nv40qt1VTgmGC6dzNVjMzbcn8i1i0smvInl5fJzNyk-VEZbkSHWmdT7YJmlWfHUpn9mDoVbxc-nROdJbrK0VbPcAeZAeGLkb9sTqMwpAbdlnJ9SUtnlf_sixlWbpHEZcuBlE2SnbIpdkFAEimIQe1ML2SI3EgX4JDjwCOV_vzPHPoihfwslSeAebQwtJnJ6Ft2ROxKxUjdkCPSv0gu5FI1uKM5rkGPZAVZjSZm2BAq2ms5hEv2L8gXVB6ivT0593P9yMqrjNwxo1AS3uHgehq3YgB6k05lPUoBoMwlFXdiHa9kbd3atvp_n4w47R72B8ej0FXPHYZxBEDntoKGfhecfEin8Y88JIw8t9awD0_CKM4SZ_lQs7AQ8kAK0HZIHmlZs3eT7K-g2rQD501DrfTtjegdyhsYVU-HqDR6_8P5GGWBENFCYMUzzE6C7GnMWIWjJAYYnnWMrdT176BHVsO5-FJKPSxY3HfPXM4XokQDgJ74VVCdPeWcwudHLr4Jqev_As)
## Old [Python](https://www.python.org), 122 bytes
```
def f(s,e,o=0):
for x in s:o<<=(l:=len(f"{len(e):b}"));o-=~e.find(x)
l*=len(s);return[*(o<<-l%8).to_bytes(l+7>>3,'big')]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=pZFNbtswEIXRrU8xEFCEdGlD1L-VyJfo0hAK2aJsJrSoULRju2gv0o037T267gna03RoxW0WzaqLAaF5Mx_fo7586452o9vz-evONpPs56kWDTSkZ4Lpwqf5CBpt4ACyhT7Xd3cFUXmhREsa76M7BM2XnzxKb_Wk-CymjWxrcqAjUOPLVE9vjbA70y7GBLcn6m1Gp1Z_WB6t6Il6l87nIbtZyvUNLZ8d_HAXKneh7pDg06kRVa1kiwvOD4BkGgpQ075T0hIPijl49CJge3G49nOPLnj517-8CsyjpRsfD6Bt1RGxrxQjrkEvpM7I1hLJGuzRotCgDVlg5D73M8zrmL1jXvSS_UvSJaVDpPOvN9_fWySuc_DsRqClg8dAtCtdCwOrTWWqlRWmRxmq5Qp_wXoj7x_UttXdo-ntbv90OJ4uQRc89RmkCQM-cxUzCINy9Ac_S3kUZHESvnYBD8IoTtJs9oyLOYMAkRFWhtgoe0FzZh93cvUAS6OfWmcc7nfbrge9R7CTVXU6Qq3X_x8owCwZhkoyBjP8TtFZjOcsRc2JCQ7GWIGzzF3Xd2_g2m6G83gAxSGeWDz0rzMcVxKUo8gtvEiI7l5z7qTBoY9vMvzK3w)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 90 bytes
```
L$`(.?)(?=.*(¶.*)(?!$)\1)
$.2*
+`(_+)\1
$1
_
_
P^`.+
.+$
7*
¶
L`.{8}
_
_
+`_
__
%`_
```
[Try it online!](https://tio.run/##FYpBDoIwFAX37xQ1qUlpk5/UjW4MF2DhAYwtahFQQbEqarwWB@Bite5mMtM5XzW5DiHjVlCaiHRJUowDyYgTnqx1Ak4zCWWFUVHBNQMzMFhtLCmQ4phLhnEAMkufxTem2JU1/89gak0IvnSsaHuwfLvbu@JQVvXxdG7ay7W7@fvj2b/ePw "Retina – Try It Online") Explanation:
```
L$`(.?)(?=.*(¶.*)(?!$)\1)
$.2*
```
Get the 1-indexed indices of all of the input string's characters in the encoder characters, plus the number of encoder characters.
```
+`(_+)\1
$1
_
_
```
Convert to binary using the custom base conversion characters `_`.
```
P^`.+
```
Left-pad all of the binary strings to the width of the binary number of encoder characters.
```
.+$
7*
```
Replace the binary number of encoder characters with seven spaces.
```
¶
```
Join the binary strings together.
```
L`.{8}
```
Split into strings of length 8, ignoring any trailing spaces.
```
_
_
+`_
__
%`_
```
Convert from the custom binary to decimal.
[Answer]
# Ruby, ~~128~~ ~~120~~ 118 bytes
First attempt, probably some ways to make it more optimal
```
->s,x{s.map{(x.index(_1)+1).to_s(2).rjust Math.log2(x.size+1).ceil,?0}.join.scan(/.{1,8}/).map{_1.ljust(8,?0).to_i 2}}
```
s should be the character codes of the input string and x should be the character codes of the encoder. Returns an array of character codes.
[Attempt this online!](https://ato.pxeger.com/run?1=jVFNbtNAFFbFqjnFw5WoDe7U4_9UShELYMWGbVNFjj1OJnVs1zNOnaQ-RxfdVAhOwinoaXgvSQUbJEZ6M-Pv5_2MH7837XT99C0f_Wh1fhb_Wp1dKrvbKrZM6q3ZMVlmojMn3HrHLaariTJdizWLVmn4kug5K6qZizIlN4IUqZCF_d7p2aKSJVNpUprnbMvtuD-3diknnBXkNmOU7TJKcPt-X_356NWHr58_MZGk80khSwFZBfd0uR8AKN3YIMoUt66GEbwlgiEqa6bqQmrTGGvDIiWyYpUUJpLWgTs93TVgvrmomoxE3YsIU_5T1AjKlTNT2dARULdamcbJFjP3MB7DyRbtPYwu8YZifC9Vi1T3xh8x_HyAjx2hIrsgQ1cjDTKHvwzwekRjDUSZ7d_i6fmoMvRcQF51xrEByTTNRD6by8VNsSyr-rZRul3ddeuNcXzFI8eGKLSBDykCGzz3emAMI-67cRB6mIC7nh-EUTwkecBtcNHiY8Ro82NUU7HbVqY3MG2qu5IKw6Jd1gqqlWiA6CLZrPGfzP6_IRd7ibGpMLZhiN8RVg7wHEbIERmiMMBwqSVOqEMzEEwazoN9osDDE4N7zouGoyVE2vfJgBNgS9jZbr_iDs2UHBbBCLpBcACnuHZaRGPMgQ1f7x_-Nw)
[Answer]
# [Factor](https://factorcode.org/), 123 bytes
```
[ dup length [1,b] dup last log2 1 + '[ >bin _ 48 pad-head ] map zip substitute concat 8 group [ 8 48 pad-tail bin> ] map ]
```
[Try it online!](https://tio.run/##lZG7bsJAEEV7f8WVFSlFEiTzNInkNkqTJkploWhsr@0Fs7vsAzCIb3fWgCBtpprXmRndKSm3UnffXx@f768grak1IGNkbrAmWw80iYoZrJgWrDmnUOr2UlOkDdMwbOOYyNkNrLR0iosKSjNrW6W5sGi4ZZoag7cgOAbw9nBEaGuGUu5DJOfdCEFZXrCyqvly1ayFVBttrNvu9u0hxOnGzWfReBhPpqM7GQ1H48l0Fs//9vXzN47nK2Ra7kS/C0u3VgZy60/vyw0dWhSy@vcNvuvOnINTcAq6FIVTaJiovFZp9JwtLgkyXgRZDRHhCY8pkowL/GAcQ1HxUjMqsPC6Khy4gnGZsdw6y5BLkZNFfJEVqfeujCXewE9JruCiKy8vSPpo0P0C "Factor – Try It Online")
## Explanation
Takes the string as an array of codepoints and the encoder characters as a string.
```
! { 57 55 49 52 50 56 53 54 51 } "123456789"
dup ! { 57 55 49 52 50 56 53 54 51 } "123456789" "123456789"
length ! { 57 55 49 52 50 56 53 54 51 } "123456789" 9
[1,b] ! { 57 55 49 52 50 56 53 54 51 } "123456789" { 1 2 3 4 5 6 7 8 9 }
dup ! { 57 55 49 52 50 56 53 54 51 } "123456789" { 1 2 3 4 5 6 7 8 9 } { 1 2 3 4 5 6 7 8 9 }
last ! { 57 55 49 52 50 56 53 54 51 } "123456789" { 1 2 3 4 5 6 7 8 9 } 9
log2 ! { 57 55 49 52 50 56 53 54 51 } "123456789" { 1 2 3 4 5 6 7 8 9 } 3
1 + ! { 57 55 49 52 50 56 53 54 51 } "123456789" { 1 2 3 4 5 6 7 8 9 } 4
'[ >bin _ 48 pad-head ] ! { 57 55 49 52 50 56 53 54 51 } "123456789" { 1 2 3 4 5 6 7 8 9 } [ >bin 4 48 pad-head ]
map ! { 57 55 49 52 50 56 53 54 51 } "123456789" { "0001" "0010" "0011" "0100" "0101" "0110" "0111" "1000" "1001" }
zip ! { 57 55 49 52 50 56 53 54 51 } { { 49 "0001" } { 50 "0010" } { 51 "0011" } { 52 "0100" } { 53 "0101" } { 54 "0110" } { 55 "0111" } { 56 "1000" } { 57 "1001" }
substitute ! { "1001" "0111" "0001" "0100" "0010" "1000" "0101" "0110" "0011" }
concat ! "100101110001010000101000010101100011"
8 group ! { "10010111" "00010100" "00101000" "01010110" "0011" }
[ 8 48 pad-tail bin> ] ! { "10010111" "00010100" "00101000" "01010110" "0011" } [ 8 48 pad-tail bin> ]
map ! { 151 20 40 86 48 }
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~133~~ ~~132~~ 131 bytes
```
def f(s,e):w=len(f"{len(e):b}");return[int((''.join(f'{e.find(c)+1:0{w}b}'for c in s)+8*'0')[i:i+8],2)for i in range(0,len(s)*w,8)]
```
[Try it online!](https://tio.run/##fVJdb6swDH3nV1i8QNbcifBNr7o/wtBVS0ObtgsswKBF/PZem657HJLl2OfYh8Rurt2x1sH9vpcVVG7LJVsPm4vUbmVP5DDezTb7a2TXG50r3bmu47yeaoUUZ5KvldJ7t2QrsfamYd7NTlUbKEFpaNkqfXE8h@VqrVZpwX1GmCLMbPVBuh4niZa9DDxlxb2Tbfev7UwLG3Dt7iihqkebg50lIvTTKA4ooPxnr8oz7Ew9aOLAqf9oWqi/pAGCL9vbFfb1gejbXWkza2ktdfloDZjECx@O6nS@fOi6@TRt138N4/VGJcIPwihO0swGjH4jw7cAMEuOjSw7uSeBXCQehyTmIDKyiEPgFxxyEQkOPmIhWop4mC7pJ91HZoolccohwzhBeoQ@SxAjMEZihOZTH0FZjxQoTRwhokejKECPJgLvyRFYEiMchlSwyHppwazyKMszPhz@t/Pe@0lYOhyWkwgcZtHIcC34SGO7qcb9mRKHn1fl8Lw@W1uAH7V7rNMSNoYWB/elnTlMcoY/bzCZGaZv8dxsNmMxO@z@Hw "Python 3 – Try It Online")
*Saved a byte thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)!!!*
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
IE⪪⭆θ◧⍘⊕⌕ηι !L↨L粦⁸⍘◨ι⁸ !
```
[Try it online!](https://tio.run/##TYzBDoIwDIbvPsXkVBK8eDLxpomJCSZEnmBuZZuOAaMi@vJzgAebNG3//@8nNPei4TaEwhtHcOQ9wYW3ULbWEJQUVTXdXcYKLnOsCA68x8WAsxMea3SEEk7GSdAZM2masYStkzhydIr0/AG/XUd5m06ZXew/VsRfjdIEZrFmRKx9CKSRVc24YvwmJFZKm/vD1q5pO9/Tc3iN70/YDPYL "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input string
⭆ Map over characters and join
η Encoder characters
⌕ Find 0-based index of
ι Current character
⊕ Incremented
⍘ Custom base conversion using
! Literal string ` !`
◧ Left-padded to length
η Encoder characters
L Length
↨ Converted to base
² Literal integer `2`
L Length
⪪ Split into substrings of length
⁸ Literal integer `8`
E Map over substrings
ι Current substring
◨ Right-padded to length
⁸ Literal integer `8`
⍘ Custom base conversion using
! Literal string ` !`
I Cast to string
Implicitly print
```
[Answer]
# APL+WIN, 45 bytes
Prompts for string followed by encoder characters:
```
2⊥⍉(m,8)⍴(8×m←⌈(⍴n)÷8)↑n←,⍉((⌈2⍟⌈/n)⍴2)⊤n←⎕⍳⎕
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##jY3NbcJAEIXvW8Xe1pZAkddgTAlIiVLD4n9Y7xobA6YAAghHySHKMZdQAUgpgE6mEWc2aYDL/LzvzRtRyH7YCKmTfiBFVWVBB68fT4@we3MJTpNnnBwC@5e443A8Q3uw8p5vQ3u1/NtnjhROewtXZd9@UN@9K9R6xmch4dB@YXtQ5oLbcPw2GIOhvWDtMJh0MWHLNKKx3jDCqJgGYRQnaTaby1zpYlFWy3q13jRbRtA5HjkD7g89F70OdwdDb@SP/4jJWNRZMKfTUq@VyaOzOi8qqldRSQ2WYtvQUCd3/EHM/usv "APL (Dyalog Classic) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
āb¤g°+€¦‡¾8׫8ô¨C
```
Inputs in reversed order, with the encoding string as first input.
[Try it online](https://tio.run/##AUsAtP9vc2FiaWX//8SBYsKkZ8KwK@KCrMKm4oChwr44w5fCqzjDtMKoQ///IGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6CnRoZSBmb3g) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC8f8jjUmHlqQf2qD9qGnNoWWPGhYe2mdxePqh1RaHtxxa4fxf5390tJJCYlJySmpaekZmVnZObl5@QWFRcUlpWXlFZZWSjlJJRqpCWn6FUqyOQrSSoZGxiamZuYUlUMLS3NDEyMLUzBgiRdiUwtLM5GyFpKL88jyQiQpZpbkFxQr5ZalFCiDpnMSqSoWU/HSIcUDTgNpAZGwsAA).
**Explanation:**
```
ā # Push a list in the range [1, (implicit) first input-length]
b # Convert each to a binary string
¤g°+€¦ # Right-pad with 0s to make them all the same length:
¤ # Push the last/longest binary-string
g # Pop and push its length
° # Pop and push 10 to the power this length
+ # Add it to each binary
€¦ # Remove the leading 1 from each
‡ # Transliterate all characters in the first input to these
# binary-strings in the second (implicit) input
¾8× # Push a string of 8 0s: "00000000"
« # Append the strings together
8ô # Split it into parts of size 8
¨ # Remove the trailing part
C # Convert all binary-strings to integers
# (after which it is output implicitly as result)
```
`¤g°+€¦` could alternatively be `¤gjð0:` for the same byte-count:
```
¤g # Same as above to get the length
j # Pad each with leading spaces up to this length
ð0: # Replace all spaces with 0s
```
[Answer]
# [Python 3](https://docs.python.org/3/), 116 bytes
```
lambda s,e,j=''.join:map(lambda*a:int(j(a),2),*[iter(j(f"{e.find(c)+1:0{len(bin(len(e)))-2}b}"for c in s)+7*'0')]*8)
```
[Try it online!](https://tio.run/##jZDBkoIwDIbvPkWmFxrsOgIqyIxPsruHAq0UocUCKjo@O9uOL7A5JJN8//zJpJ/H2uhkkaefpeVdUXEYmGDNKQg2jVE673hPPyDkudIjbShHFiMLv9UorGsleYmNVLqiJa6jfPtqhaaF0tRXgYhf8bt4E2kslKA0DLhOw2Ab4G@Y4eLHbqMHdEXJWAuQ5kEYAV6UlZDnWjWXttOmv9phnG73x/wkyJz0mEa7ONsfEieO4mS3P6TZ8YO8y3VS5QUKa@7aO0Izdf0A5iYseNzy5wyVOf9nk@NO5rNrMV@Bi976Z4SSuuMRlz8 "Python 3 – Try It Online")
Using [xnor's `zip/iter` trick](https://codegolf.stackexchange.com/a/184881/87681) for chunkification (but with `map` instead).
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 90 bytes
```
f(s,e)=digits(fromdigits([[i|i<-[1..#e],e[i]==c][1]|c<-s],2^l=#binary(#e))<<(-l*#s%8),256)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVBLasMwFKTQgwiZglTsgJ3YccDuMbqoUItsS44SfxTZTuKQm3STTemZ2tNEqlO67du8mTfDDLz3T8W0fCvV5fIx9MKLv14E6lyO00KWsu-Q0G19g4TIs0w84s9mDqcuJ5KmaU6JT8954nXUDV6r1Mlkw_SIHI5xkiCvenS6hxi7QRjhqeH77p4pVY2IAe8JKC2b3kBoCQQCPfMcMZOJXTDBgGJsCCGwX3Mg2iN0jZFlecFFuZabbVU3rdrprh_2h-N4gtSY4WrpL4I4jObW7QfzRRgt49Wk2ZzdIPMtyHR7aGwm2Ay16kC75xpYuWKnERRt-a8uo1ufXRO_zc_x75SZmXyQ0tszft9-BQ)
Inputs lists of characters.
[Answer]
# Desmos, ~~304~~ 265 bytes
```
g=[1...Q][c=s[floor(i/q)+1]][1]
Q=c.length+1
q=ceil(log_2Q)
l=[floor(log_2g)...0]
k=\{q=l[1]+1:[],[2...q-l[1]]0\}
d=[join(k,mod(floor(g/2^l),2))[mod(i,q)+1]fori=[0...qs.length-1]]
v=join(d,[1...8]0)[8u-7...8u]
f(s,c)=[total(2^{[7...0]}v)foru=[1...ceil(d.length/8)]]
```
Both inputs are list of codepoints, as is output. This took me a *long* time.
[Try it on Desmos!](https://www.desmos.com/calculator/xrqd2dr5n6)
*-39 bytes thanks to Aiden Chow*
[Answer]
# [MATL](https://github.com/lmendo/MATL), 17 bytes
```
&m2Gt&mBwY)!8e!XB
```
[Try it online!](https://tio.run/##y00syfn/Xy3XyL1ELdepPFJT0SJVMcLp/3/1RChQ51JPTFIHAA "MATL – Try It Online")
Of note, `B` returns a matrix with the binary strings as rows, so they are automatically padded to the same length.
[Answer]
# [Uiua](https://uiua.org), 30 bytes\*
*or **69 bytes** using native UTF-8 encoding*
```
▽±.⍘⋯≡⇌↯⊂¯1 8≡⇌⬚0⊂∶×0⋯⧻∶⋯+1⊗⊙.
```
[Try it!](https://www.uiua.org/pad?src=Q29tcHJlc3Mg4oaQIOKWvcKxLuKNmOKLr-KJoeKHjOKGr-KKgsKvMSA44omh4oeM4qyaMOKKguKItsOXMOKLr-Knu-KItuKLrysx4oqX4oqZLgpDb21wcmVzcyAidGhlIGZveCIgIiBhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5eiI=)
---
\**See answer to the reverse challenge [here](https://codegolf.stackexchange.com/a/265917/95126) and [here](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==) for a single-byte-character-system (SBCS) encoding.*
[Answer]
# [Julia 1.7](https://julialang.org), 125 bytes
```
s\e=parse.(Int,only.(eachmatch(r"(.{8})",join(string.(findlast.(s,e);base=2,pad=floor(Int,log2(2length(e)))))*"0"^7)),base=2)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVBLbtswEEWXySmmXCRUwQimrJ9TqLsuuugJbBegJcqmQ5OKSDt2ipwji268yUl6ivYwRYeymwJddYAhwTfz3rzht5f1VitxPL5sfXtT_nhyM1l1oncypp-MZ9boQ0ylqFcb4esV7QmNv5ZPEWFrqwx1vldmGdNWmUYL52PqmIzeL4STVcI60VSttrYfpLRdJjTR0iz9isooxDsyIl-KKGInQnQ28au1PShQBnopGq2MdDS6BAycx0CaGo99BxW4TitPFYPrmb9-bQkF30-TW2maGz4fYCQhjOc_8CAjd0LTz9KLeFidIhqd1HrpsD5FuTiO5zALCkOhw8W9Hn6AAYHZDMjZGYHqQ3gg9a_G22oYdXX1SiTw_Rk-7jtZe9ncDmyceoneTr9w_PnGEr-S0No9uSAgFnUj2-VKre_0xtjuvnd-u3vYHx7JxZQXIwZFzoBPQmYMxsn8kkwKniZllo9RgCfjNMuLchLaM84gQUqKWSItLbE7DLvfqvoOFr19MGEwrLebzoHdyR5CWYvHAzR2-f-GEvRSoqm8ZDDBd4GTM7wnBdZCMcfGDDMJlnhAR2GHAIcezrOTUDbGG5OPR396OFJyLKdpIOAGaAmdDeeUj8JO4hwBRjDJsjO4wBh6ES1RAw3PTx__Gw)
expects `s` as a list of characters and `e` a string. Needs Julia 1.7 for `only(::RegexMatch)`
] |
[Question]
[
Frustration is a solitaire card game which is played by calling out the sequence:
“Ace”, “Two”, “Three”, ... , "Nine", "Ten", “Jack”, “Queen”, “King”, “Ace”, “Two”, etc.
With each call, you simultaneously flip over a card from a shuffled deck of 52 cards. You win the game if you get through the entire deck without ever calling out the rank of the card being flipped over.
### Challenge
Given a string or list of characters representing an ordered deck of cards, return "Truthy" if the deck is a winning *Frustration* configuration, and return "Falsy" otherwise
### Input
Input will be a single string (or a list of characters, or a list of codepoints) consisting solely of the following 13 characters (you may choose to take the letters as uppercase or lowercase):
```
A 2 3 4 5 6 7 8 9 T J Q K
```
Each character will be repeated 4 times in the input. An example of a valid input is:
```
A23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQK
```
You may assume that the input is always valid (ie. it will contain exactly 52 characters and the 13 characters mentioned above will be repeated exactly 4 times each)
### Output
Output one of two distinct "Truthy" and "Falsy" values. The values you choose **must** be consistent (ie. different "Truthy" inputs must produce the same "Truthy" output and different "Falsy" inputs must produce the same "Falsy" output)
### Examples
The input `KA23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQ` would be a winning *Frustration* configuration (hence a "Truthy" input) because none of the cards in the sequence match the name called out when flipping that card over.
The input `2K3A456789TJQKA23456789TJQKA23456789TJQKA23456789TJQ` would **not** be a winning *Frustration* configuration (hence a "Falsy" input) because the 3rd card flipped over matches the name called out when flipping it (`3`).
### Test Cases (one per line)
**Truthy**
```
KA23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQ
2A2A2AKQKQK3Q456789345678934567893456789A2JJJJTQKTTT
KQJT98675432AKQJT98675432AKQJT98675432AKQJT98675432A
55667987TAQK8TAQK8TAQK8TAQK325476979965432JJJJ234234
JAK3TTJAK3TT33KAA2456789456789456789222456789JJQQQKQ
```
**Falsy**
```
A23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQK
2A2A2AKQKQKQ3456789345678934567893456789A2JJJJTQKTTT
KQJT98765432AKQJT98765432AKQJT98765432AKQJT98765432A
8TAQK8TAQK8TAQK8TAQK234567999765432JJJJ2342345566797
JAK3TTJAK3TT33KAA2456789456789456789222456789JJQQQQK
```
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins
[Answer]
# [Python 2](https://docs.python.org/2/), ~~45~~ 42 bytes
*-5 bytes thanks to @ovs*
```
lambda s:all(map(cmp,s,'A23456789TJQK'*4))
```
[Try it online!](https://tio.run/##nZBNa8MwDIbv/hW5NR291Io/VNjBV@sk8HEwvI/SQJKZNqPs12cO3iEdhXW1zGskW/jVk77Gw8cgp/3j09TF/uUtVqdd7Lq6j6l@7dPmtFk5CY3SxmLwTKuHZr2ezoe2e6@2O1GlYzuM1b4@xvNzO6TPsc7XdNFyWyKkm4M4B3Apw7XDSZ9XYAohCGIf0GqjGph7b0qEUlobtCY4JnspIFVjNBpEPb@df8oe8xbeEYRQFICck8XOUqX8KXrPnAcRd3CgJQiG/4EwejHun4mwVwgUK4hofhEo1MwdIJi@AQ "Python 2 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) -p, 29 bytes
```
$_^="A23456789TJQK"x4;$_=/\0/
```
[Try it online!](https://tio.run/##nZA9CwIxDIb3/ozDVZTm2jTIDV2bKZBRdHIQRA918Ndbe9ThTgQ/mvKWJC198/S788HlPNtuuiZaaJ3HQJqEm1u7mm27xXq5yJknre8SY@MQLCVAahneHdGmslRYVQ1LUgoeXQvD268S45z3SAE1CoepgHUtekIiP9wdfioeyzYpMqhWBeAYbbUzVmufxZREyiDG/AGCxyQEfiOBfjTvx8SENwiqFSLCFwQVG/5BQvh@6q/70/GS54f@AQ "Perl 5 – Try It Online")
Perl allows XOR on strings, how awesome is that?!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
QṢ“ṡ=2E’œ?ṁn⁸Ạ
```
A monadic Link accepting a list of characters which yields `0` or `1`.
**[Try it online!](https://tio.run/##y0rNyan8/z/w4c5FjxrmPNy50NbI9VHDzKOT7R/ubMx71Ljj4a4F////93L0Ng4JgZDGxt6OjkYmpmbmFpbIpJERVNDLKxAIvAE "Jelly – Try It Online")**
### How?
```
QṢ“ṡ=2E’œ?ṁn⁸Ạ - Link: list of characters, D
Q - de-duplicate D
Ṣ - sort
“ṡ=2E’ - base 250 integer = 3,832,012,820
œ? - nth permutation
ṁ - mould like (D)
n - not equal? (vectorises):
⁸ - chain's left argument, D
Ạ - all?
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Core utilities, 48 bytes
```
egrep "`echo \([^A ][^{{2..9},T,J,Q,K} ]\){4}`"
```
[Try the test cases online!](https://tio.run/##nVBdS8MwFH3Pr7gUHxTrBkmbNDAnedCH5EECedsHq2tYB107qlOh9rfXdHVYZeBcbjjhHu69Ofc8xc9ps4xfYAzbsliV8QZGI@/@8cFr7Kq0W/AWdpkWML2czAXMJvOqwoMBr33jS1/7qobZ9KoK6oWHGteF0DLdFAnsrt8P8xB6S9eZhdLGCWTr3CKApHAAsJ98k4N30fJwOwbvm@@4DxgMD8LGw8S@DvNdlvWq7vbjctsogUkQUhZxI/WJCcKiDaVdEN3R5NgjsHTHaGWMQUpLwyPKwoC0vSclKAwpZTxiRmgV/QSCw4BRzjinbW37k9PoLpJCEWM6JEQJgTs5fcT4i5RSa7cIOsMH1TdCk/8ZwWhv3T8TFB1xoJPCOWe/HOhcY2cY4Xb6BA "Bash – Try It Online")
Input is on stdin.
Output is the exit code: `0` for truthy, `1` for falsy.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 57 bytes
```
([^A][^2][^3][^4][^5][^6][^7][^8][^9][^T][^J][^Q][^K]){4}
```
[Try it online!](https://tio.run/##nZA9CwIxDIb3/g/hXJu2acZOQjMFssmJDg4uDuIm/vYzpQ6nHPjR9HlLQkuT93K8ns6HaTVs9tOw3ZVxu/MGGMGIRjLQyAYZalRDDB7Xt3CfJi4eQkyYSat8mThfWrBYgPQyLB3FV1sqrKqOpSrlhDFAe/tV4mJMCSmjFuH8KuBjwERIlNrd9pP1aNvVwqDaFYBL8b2duXr/LNYqYoO4P3zguRECvxmBaTbux8TlBQd6K0SEbw501/API4Qf "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Simply matches a string of 52 bytes that doesn't match the specified character at each given position.
[Answer]
# [Haskell](https://www.haskell.org/), 37 bytes
```
and.zipWith(/=)(cycle"A23456789TJQK")
```
[Try it online!](https://tio.run/##pZA9a8MwEED3/gphMiRDG5Csr8GDVt10cJCli3HixtR1TZOl@fFRZNQhFikNjU6cOHF6nN6@Przv@j601Wuoh@3LqRs33XG/XFerZfPd9LvCcVFKpY0lj1CswkfdDaxi288nxsavbjiyBWtZAbO@@4pijuBuCsAYAlOTuHU47uMiBCLKEICerFFalmIi3VVkCCmV0tZocghmngSXpVZWW6uml9MU8TdxZwjvQBClLAQ4x9Pg15nzn0vvEeOXM8Q/bMLvOlE8olOrK2l/FhnC3PCYhrbW6sxjcq8f1hldhHPT9vXbITw343gB "Haskell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes
-2 bytes thanks to EdgyNerd,
-1 byte thanks to Grimmy.
```
'A8L>"TJQK"JJ4×ø€Ëà
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f3dHCx04pxCvQW8nLy@Tw9MM7HjWtOdx9eMH//96ORsYmpmbmFpYgaeI4AA "05AB1E – Try It Online")
[Answer]
## JavaScript (ES6), 48 bytes
With the input being a string:
`t=>![...t].some((v,i)=>"A23456789TJQK"[i%13]==v)`
With the input as an array of char it's down to 43 bytes:
`t=>!t.some((v,i)=>"A23456789TJQK"[i%13]==v)`
```
var f=
t=>![...t].some((v,i)=>"A23456789TJQK"[i%13]==v);
[
"KA23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQ",
"2A2A2AKQKQK3Q456789345678934567893456789A2JJJJTQKTTT",
"KQJT98675432AKQJT98675432AKQJT98675432AKQJT98675432A",
"55667987TAQK8TAQK8TAQK8TAQK325476979965432JJJJ234234",
"JAK3TTJAK3TT33KAA2456789456789456789222456789JJQQQKQ"
].map(v=>console.log(v,f(v)));
[
"A23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQK",
"2A2A2AKQKQKQ3456789345678934567893456789A2JJJJTQKTTT",
"KQJT98765432AKQJT98765432AKQJT98765432AKQJT98765432A",
"8TAQK8TAQK8TAQK8TAQK234567999765432JJJJ2342345566797",
"JAK3TTJAK3TT33KAA2456789456789456789222456789JJQQQQK"
].map(v=>console.log(v,f(v)));
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 63 bytes
```
s->s.matches("A23456789TJQK".repeat(4).replaceAll(".","[^$0]"))
```
[Try it online!](https://tio.run/##nVBfa8IwEH/3UxxlQjs0jMY2jW5CXxsGC@ZNHGS1dXW1lSYKY/jZs9TuQYcwZy65y/2/@63lXg7Xyw9TbLZ1o2FtdbTTRYnyXZXqoq7Q/aSXllIpeJZFBV89gO3urSxSUFpqK/Z1sYSN9bkz3RTVar4A2ayUdwwFeGmyZZFKnT127ink8GTUcKrQRur0PVOuE/t4FIQkoiLhzEFNts2kdkde@ytlmsVl6TrIGTjz17uHheN5ZnKsndeNu5cN6Ezp8VlXgNmn0tkG1TuNtravzl2nr8bQV/3KGRwzBpCjVrot87yu5KHXvoMx7Gyo6xTjxy0xbgnzzowvidhP7BGcCSEM44mgUUiCEW5zr1JMEIQhoRERMWfROcN@MCIhJZSGbWzbyc5or0lihoXoOMYsjv1unFPu@z/GJOHcLmJuwIGdAsHx/4Ag4cm6fyomuoBANwqllPxCoEON3AAEZ98 "Java (JDK) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes
```
Inner[Equal,#,Characters[#<>#<>#<>#&@"A23456789TJQK"],Or]&
```
[Try it online!](https://tio.run/##nZBNawIxEIbv@RXLCp4WCsnmC7UYiocmhzY4tyWHIGtd0KVN4@/fZomHtQi1ZoY3vEOGzDwnHw/tycdu54d9sRpe@74Nzebr7I/VrHo5@OB3sQ3fzWz5fMn5ulSY1JRxIUFbU7rqLbj58B66Pjb74mldTPq2MZU/tp/HLjYlMled9xmE1RjGpiA2l8mtS2GdDlgDAMhYDVIwTmsy9t5lEKWMcSk4KGvEtRBMa84kl5KNb8ef0owpkVaGAGQlxCiF8zhTxfhS1NratAh6gIOZgrDkfyA4m6z7p0HiBoE8ipSS/yKQqfEHQKSdSufcYvgB "Wolfram Language (Mathematica) – Try It Online") Pure function. Takes a list of characters as input and returns `True` or `False` as output. Note that this function checks for losing configurations (since `Equal` and `Or` are shorter than `Unequal` and `And`), so `False` is the truthy value and `True` is the falsy value.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 44 bytes[SBCS](https://en.wikipedia.org/wiki/SBCS)
```
{A T J Q K←10+¯9 0 1 2 3⋄~∨/(13|⍳52)=13|⍎¨⍵}
```
[Try it online!](https://tio.run/##nZC7TsMwFIb3PMXZCgOitmM7Hhi82pMlv0AECR0qtSLJUHEZEEKoKBULIwtiyMYAvEAexS@SOgSJgCL14mP99jnysX9/8Xx6dLaIp7PzprmUYEGBAe3unxCgMSCvGBBxj3c37qE6PkDkypUfFB@efO9WdeXKr@smBd8Be/cHgStfwE4SyC@KfLKAPMlyOI2zJINZkc@LHFDgVs/@2rSuANzy1pVv9Ttyy9cQKHbl50hLTELKeCSsMlsmWLahjQ9iuioZWiRWflijrbXaKCsixmlI2tatEkoZ4yLiVhod/RWCaciZ4EKw9mj7jjfop5KaWNspIVpK3HnpK8Y/RaWM8b8Y/YJM42k2xHG8ieMeGHWPoyE7ceSsR2tjEg0A7HwIIfg/gB10vjtHo0fNGg "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
⬤θ¬⁼ι§⁺⪫…²χωTJQKA⊖κ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMxJ0ejUEfBL79Ew7WwNDGnWCNTR8GxxDMvJbVCIyCntFjDKz8zTyMoMS89VcNIR8HQQFNHoRyIlUK8Ar0dlYAsl9TkotTc1LyS1BSNbE0wsP7/3zvQK8TSwtzM1MTYyJFIzn/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean; `-` for truthy, nothing for falsy. Explanation:
```
θ Input string
⬤ All characters satisfy
ι Current character
¬⁼ Not equal to
…²χ Digits from 2 to 9
⪫ ω Joined together
⁺ TJQKA Suffixed with picture cards
§ Indexed by
⊖κ Current index incremented
```
[Answer]
# [Perl 5](https://www.perl.org/), 36 bytes
```
sub f{('A23456789TJQK'x4^pop)!~/\0/}
```
[Try it online!](https://tio.run/##1ZZBa4MwFMfvfoqsCFVw1CWamIpjuRp2COQ4NtiWdkKrrra0pe2@ukt0h3YU1u2UJfLkvTz1F/n/IbVazOK2bVbPYLLzhgyiKMYkoTIXfLiJHuuq9q8@Rg/h6NCuGgWkapbj8X21UKkz34K7pc6z97UH/t1w@MlmL0vAjTX4kJnJhZ5I9IDo3I3BXA8puJTSInwuckkTTOIImV1clFiEH8cYE5oQyQRPTgOCcUQwJZRiQ23@vlaQvizCzxlHUvYRIc4Y7MVyHCH8Kua5EFpmFuH/wbkchDZaV6BLrRtaZl2Cjwz6Y2IRfnLGs71QKKXkm2d7nxOL8H9vXau076fO@q2YKa87Ovg7B4D51nOLsg5ctan9rKlnxYvqVoMwgGnXANxptcwmXZ@/34emWjSeqXaPBQOzAq5vu8aB/sjBea1K9WReU5TTtP0E "Perl 5 – Try It Online")
`'A23456789TJQK' x 4` results in the 52 byte string of `A23456789TJQK` repeated four times.
This string is bitwise XOR-ed (operator `^`) by the equal length input string from `pop`.
Any equal byte (char) at the same positions in the two strings results in a null-byte from xor.
And `!~` (not regex-match) returns true if no null-byte `\0` exists. Otherwise false.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 64 bytes
```
i;f(char*s){for(i=0;i<52&&s[i]-"A23456789TJQK"[i++%13];);i-=52;}
```
Outputs zero for truthy and non-zero for falsy.
[Try it online!](https://tio.run/##pVNbT8IwFH7fr2hKICsXxZatqwNNHzRxfSr2RZEYMpg0wWEYGJHw22fHCA6DkeBpc27p157z5TRsvIRhmmo/ssPxYFZN0Cqazmzdafq67eBKJenpfgNyTFqOSz2mAilgT9dq5QvS95GvGx0H@@u0pONwshiOQDuZD/X0bHxllYajSMcjwLtd/vB8f/d4Y38gYCf6czSNjHu@9Yzba/YRsiwdz8HrQMf2@1QPkbWygJGsLFDV8dtinvT6oAPydCZQ7NV1XADr33jMsyWkWUTmJ8ghw3FgREmhlCrihQwU81zqtEh2zVFBEe84rkuZRxWXwttXBDst6jLKmJvBsvdNE2YX8QEXRKlcEyI4x3m9RY3xNhkEUppOi/gT6BO/8CfJyfxRt8DSn0ER7x0gLq@VMUZ/EJeTTf/H367/tW9t7Oa3mLnVZjKbvjHt4sDnY4tMvlZDu3ffZgYR2bCcPMWwDqLtMfPTELgG8HYwSZYQXAKoZov5eAmRb63TLw "C (gcc) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 26 bytes
```
1 e.(52$'A23456789TJQK')&=
```
[Try it online!](https://tio.run/##nZA9awMxDIZ3/QoRSi4HrUmk81fCDabQwe7i4rWUUnKUUuiQLPn1V7vucAmBprGs10hIWHo@xploBuzX2OAtLnGd/U7g/dPjw7jCrVhIumkccSeVNjb5GJp23o8twL4Xi@eNeKG2tC0hHFVdFgC5YiFm41jTfO5x5PNJMaSUIESfrFFadlx6LwpASqW0NTq5GMyxMMlOK6utVaW2/JRnzBe8C5xSVebgHNVxpkr0m/Q@xrwItLB9e//CYbbCPcDw@rk7nKC6glSYoor8P1RaTYD8GYA5w6iOYq3VJ4wqV30FqrzTBNUPp/Eb "J – Try It Online")
0 is truthy, 1 is falsy.
Straightforward as possible, posted mostly as a straw man because I thought it was interesting that there didn't seem to be a trick to compress 'A23456789TJQK' that was shorter than the literal.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 24 bytes
```
~|/(52#"A23456789TJQK")=
```
[Try it online!](https://tio.run/##nZKxCgIxDIZ3H6MO6iBqc20aQbBrMwXyBA4uDr6A3KufKXXwRPC8pKSkzU@Tj96299swXI/9Y7cOfumyhy5ETKRF2G1Ow6Havtqlv55Xa8ejkmmJWzifq7OYg7QL@LZlX8xUWFVNxlKUUsTQQVVPSkwWQoxICTULp3EAHzqMhESxVtfXrFNbJiuZQbVFAM7Zt6beo/evw1JEbByTzSDCYyQC/yLB@Db4z8Rk6QuL1hAR4QeLxg9nIan/ZjE8AQ "K (oK) – Try It Online")
* `(52#"A23456789TJQK")` build the frustration sequence
* `(...)=` compare it to the input
* `~|/` do none (i.e. not any) match?
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~24~~ 20 bytes
```
!sqV*X1"ATJQK"jkr2T4
```
[Try it online!](https://tio.run/##K6gsyfj/X7G4MEwrwlDJMcQr0FspK7vIKMTk/38lL0dv45AQCGls7O3oaGRiamZuYYlMGhlBBb28AoHAWwkA "Pyth – Try It Online")
* `X1"ATJQK"jkr2T` Construct the string "A23456789TJQK". Inserting the range 2-9 at position 1 of "ATJQK" is one byte shorter than using the full string literal
* `* ... 4` Duplicate that string 4 times
* `V` Vectorize the above string and the input string as inputs to the following function:
+ `q` (arg1) == (arg2)
* `!s` Return true if the result sums to 0 (ie. none of the cards from the input match the above string)
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 29 bytes
```
"A23456789TJQK"4*]zip{1/~=},!
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/X8nRyNjE1MzcwjLEK9BbyUQrtiqzoNpQv862Vkfx/38vR2/jkBAIaWzs7ehoBFGMTBoZQQW9vAKBwBsA "GolfScript – Try It Online")
```
"A23456789TJQK"4* # Push this string repeted 4 times
]zip # Zip the input and the previous string
{ }, # Find all elements that pass this test
1/ # Divide in groups of 1 "XY" -> ["X" "Y"]
~= # Are they equal?
! # Is it an empty array?
```
Outputs `1` for truthy and `0` for falsy.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-e`](https://codegolf.meta.stackexchange.com/a/14339/), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
kVg"tjqk"i9õ ¬ha
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWU&code=a1ZnInRqcWsiaTn1IKxoYQ&input=IktBMjM0NTY3ODlUSlFLQTIzNDU2Nzg5VEpRS0EyMzQ1Njc4OVRKUUtBMjM0NTY3ODlUSlEi)
[Answer]
# x86 machine code, ~~33~~ 32 bytes
Replace `xx xx xx xx` with the address of `.Llut`.
Machine code:
```
00000034: bb xx xx xx xx 6a 34 59 89 c8 d4 0d d7 ae 74 02 .....j4Y......t.
00000044: e2 f6 c3 41 4b 51 4a 54 39 38 37 36 35 34 33 32 ...AKQJT98765432
```
Commented assembly:
```
.intel_syntax noprefix
.section .text
.globl frustration
// Input: EDI: 52 byte string to test
// Clobbers: EAX, ECX, EBX, EDI
// Output: ECX: Zero for true, non-zero for false
frustration:
// Load the lookup table into EBX.
mov ebx, offset .Llut
// Set ECX to 52 for our loop iterator
push 52
pop ecx
.Lloop:
// Copy ECX to EAX
mov eax, ecx
// Convert to the LUT index. Read the .Llut comment before
// questioning my math. ;)
//
// AL = AL % 13, AH = AH / 13
aam 13
// Load the corresponding card rank into AL.
// AL = EBX[AL]
xlatb
// Compare to the byte in EDI, increment EDI
scas al, byte ptr [edi]
// If it was equal, return. ECX will be nonzero.
// Note that loopne wouldn't work: it decrements first, so it
// won't work for the last card. :(
je .Lfalse
// Loop for 52 iterations
loop .Lloop
// At this point, ECX is zero from the loop, our "truthy" value
.Lfalse:
ret
.Llut:
// We store our LUT in a slightly unsual order.
// This is because we are looping from 52->0, and using
// the index mod 13 to get the index. However, we read
// forwards, and we decrement AFTER the modulo.
//
// This means we need to reverse, then rotate one byte.
// 0 52 0
// 1 51 12
// 2 50 11
// ....
// 12 40 1
.ascii "AKQJT98765432"
```
[Try it online!](https://tio.run/##rVZtb9s2EP6uX3EQFmwDFCWWYzv2sAJamiKxjRVuNaxYWxSURNlaJFIlqdjuj292pGyZqo0i2CYbpHm6e3gvz5EmUtIyLrbnyyR5eoLd4@dM0eKT3DJFNsB4JWiWb5z2taSJyjkDX9GNOoiXBY8LyEQtlSBaoX11cQH3rKrVBG5f3k9gEEC8VRRQL2dLUBwUlcrWvkGomAqJBuE7D25v9PCbHl7e23qva9XA3rybwF9UcMi4ACVq6qHf7PzLXpSRQlLH8m1iw8w5SUGtKBScP9QVKBIXFDALXO/qt6olfzQzjTce8CyTVIE/L@qO729RiP7osDBQvTmvhUauIFcUd@eiVa9qudLzIDiIUM/skWwcxEazjqs3vNru4TE3x64RdE3bdmzYIxXKJBqDnP8RYWwp3fjwhu4CN1FAwsuSMgUxRbepDfG5xgph2nS9yi2URK18@OVnS8XWDufwqx7OoNf3ILzTqzu4wFWrRUhpZktkFyLhQlBZcZbqHRMiUhCEPTQ1Cef@0W5Yp/fh/GMr3xRExd0klBURdJ8EQ8CcaUJ5OCeCmshtfsmESONq4TXqlRLwnqb5xw6xMywrrFGVfq61qqCqFsw3RVrnRYHZ1FzUVOy4/TtHSLUiynCDUVjzukjZjwjGxcNEo6Z055eELBdSeSA5ym2UNd9bNNTXJCZSmZT5MPmp1f2b7tp03vRCJ@vIOW2NfG0oipWWrYahrrHUvzqZR06tcomcxbqYNgVcNU0neLlvqcozLeBiX6rV1oVHUtTU2TlyYDcmzjE87BD@T31OIBsNRENdICCLfLlSxRZqJjHrwEVKRSe9kXYMvzFNSC0xuxR0@bU7mlLGv0Fw/uLSA8JSqCVKbXvtu@kSbK0UaaqJs6TqIPfhjq8pNpansQV2km2O6VxjCWSDjgptLSF8Fd2@MTiIXBcdVhxFUFLCpLZnlKbaB6G3lHi@IQADwRVBGnHWMLqTAbjUBwtOHWEPhT3oBR0hag0uodezhT4@9rqHSlcIeVDyiUzyHNxwtphG4@vRcHDVD9yn44vCNTeFj7XCvqap67lk43pnleDLOFfScfySJEiaH6Lbt5G@Fo6PtTRvT9xediB12RyWQeb0Jl2/voD7AZFcJzi8SAi2Iz6n7qj9UWyfnZ1Ddb97fGxCvm/izyu86FT2yY7slPHev0b9cFamaYMpsZOwcj5lael8e/GWJGeOHibHe6T5sSw@7NvkHcCdhUH/ajAcXY@j6eKZC/cYJgj1Z7bAT3/RKPZPTWEwxSdazKIoOgHT0Go40rQKn7k4ATMYDIcjpGcULmbX3aEfDK5Gw/FoPDbc1d5gZPg9ATMNZ/0oasZ@fxaGQROEPQbBTjidLhYY/gmYf5Hh2fdTvOj/1xQ3nRs@c3EC5vpEbpsAxuPx6JvcNvUY/S8ptnPT/nOymN3KrA7Q94xj9@TxyXEm4fwFnKUfmOs8fU2ygizl03nZD/4B "Assembly (gcc, x64, Linux) – Try It Online")
The function takes the string pointer in `edi` and returns, in `ecx`, either zero for a win, or non-zero for a loss.
Doesn't follow standard calling convention.
I finally found a good use for both `aam` and `xlatb`, I feel accomplished.
See the comments for details.
This could use 2 fewer bytes on 16-bit, but that is solely because the LUT address is 2 bytes smaller. No fancy 16-bit tricks, so I'll leave it at x86 because it is easily testable on TIO.
I'd love to trim down this LUT a bit, but I'm not currently sure how. The LUT is 13 bytes plus a 5 byte `mov`, making more than half of the code.
] |
[Question]
[
Inspired by [this challenge](https://codegolf.stackexchange.com/q/188556/78849).
## Goal:
Given a pre-configured switchboard and a list of indexes, invert the switches at the given indexes.
A switchboard is made up of some number of switches (`v` or `^`) wrapped in `-`'s and arranged into rows of varying length. Here is an example switchboard:
```
-v-^-v-
-^-v-
-v-^-v-
```
To invert/flip a switch means changing it from `v` to `^`, or from `^` to `v`.
The switches are indexed left-to-right, top-to-bottom. E.g., in the example above, the last `v` in the first row would be in position 3 and the `^` in the middle row would be at 4 (using 1-indexing).
## Input:
* A string (or list of strings) representing the switchboard. It is guaranteed to match the regex `((-[v^])+-)(\n(-[v^])+-)*`.
* A possibly empty list of numbers representing indexes, may be 0 or 1 (or some arbitrary number if you want) indexed. These are the switches that need to be flipped.
## Output:
* A switchboard in the same shape as the input with the specified switches inverted. Any unspecified switches should retain their initial state.
## Rules:
* Input will always be correctly formatted and no given indexes will be out of bounds.
* The list of indexes will be sorted and will have no duplicates.
* State in your answer what indexing you use, be it 0, 1, or some arbitrary one.
* Trailing whitespace is fine as long as the output looks like the input.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins.
## Examples:
```
#Using 1-indexing
input: #Empty Case
[],
-v-^-v-
output:
-v-^-v-
input: #Single switch
[1],
-v-
output:
-^-
input: #Skip a line
[3,5],
-^-v-v-
-v-
-^-^-
output:
-^-v-^-
-v-
-v-^-
input: #Flip one in each line + number wrap
[3,4,6],
-^-v-v-
-v-
-^-^-
output:
-^-v-^-
-^-
-^-v-
input: #Flip 'em all
[1,2,3,4,5,6],
-^-v-v-
-v-
-^-^-
output:
-v-^-^-
-^-
-v-v-
```
[Answer]
# Vim, ~~60, 46, 38~~, 37 bytes/keystrokes
```
qq/\d
ggDJ@"/[v^]
sv^<esc>l?\V<C-r>"
x@qq4u@q
```
`<esc>` and `<C-r>` are both 1 byte/keystroke. [Byte Counter](https://tio.run/##K/v/v7BQPyaFKz3dxctBST@6LC6Wq7gsTjrHPiZMSImrwqGw0KTUofD/fwA)
[Test Case 1 (Verbose mode)](https://tio.run/##K/v/v7BQPyaFKz3dxctBST@6LC6Wq7gszia1ONkuxz4mzMZZt8hOiavCobDQpNSh8P9/Yy4TLjMu3TjdMiDkAuM4IPyvWwYA)
[Test Case 2 (Verbose mode)](https://tio.run/##K/v/v7BQPyaFKz3dxctBST@6LC6Wq7gszia1ONkuxz4mzMZZt8hOiavCobDQpNSh8P9/3TjdMiDkAuM4IPyvWwYA)
Thanks to Grimy for the ideas that led to a reduction of 22 bytes :)
[Answer]
# JavaScript, ~~63~~ 59 bytes
```
a=>s=>s.replace(/v|\^/g,x=>"^v"[a.includes(n++)^x>"^"],n=0)
```
[Try it online!](https://tio.run/##HYhBDoMgEADvfQanJQI2bXrEj1g3bnA1NgSMtMRD/47EzMxlPpQpuX3dvjrEictsC9kuVc3OmyfH0Ob/G9tFHbYTmEVPZg3O/yZOEJpG4lG3GFSwd1lcDCl6Nj4uMEP/UE/1GiSMGnWu3K6wMkpZTg)
Saved 4 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld).
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~31~~ 27 bytes
**Solution:**
```
`0:{@[x;(&x>93)y;"^v"94=]};
```
[Try it online!](https://tio.run/##y9bNz/7/P8HAqtohusJaQ63CztJYs9JaKa5MydLENrY2Wkk3TrcMCGPyIEQcECpZGykYK5jGWv//DwA "K (oK) – Try It Online")
**Explanation:**
Quick answer, will try to golf it. 0-indexed.
```
`0:{@[x;(&x>93)y;"^v"94=]}; / the solution
`0: ; / print to stdout
{ } / lambda taking 2 implicit args x & y
@[ ; ; ] / apply @[var;index;function]
94= / 94 (ASCII "v") equal to? returns 0 or 1
"v^" / index into "v^" (ie flip switch)
y / index into
( ) / do this together
x>93 / x greater than 93 (ASCII "]")
& / indices where true
x / apply to x
```
**Notes:**
* -4 bytes thanks to `>93` trick
[Answer]
# [Python 3](https://docs.python.org/3/), ~~140~~ ~~134~~ 103 bytes
**(-30 thanks to DJMcMayhem♦, -1 more thanks to Black Owl Kai)**
```
def f(i,y,x=1):
for c in y:q=c>'-';p=len(i)and x==i[0]*q;print([c,"v^"[c>'^']][p],end='');x+=q;i=i[p:]
```
[Try it online!](https://tio.run/##JcpBCoMwEEDRfU8xuJmkHaHWdmOYXiRNoKihgTJGEdHTp4Hy4K9@OtbPJG3OwxggqEgH7dzo7gRhWqCHKHB0M/dPrNEk/o6ion7LADtztFd3nk1aoqzK9lRtvrLl9OicTY5GGRhRm/3Cs4llT53LQdmGbtTSnR6OAGtfb8VL/vEF6vwD "Python 3 – Try It Online")
---
Oof, second try at golfing anything at all. This just uses a rather unsophisticated loop over the string, using `x` to keep track of the current switch index. Uses 1-indexing.
Ungolfed:
```
def f(i,y):
x = 1
for c in y:
nextchar = c # nextchar gets golfed out completely within the print
if c in 'v^': # golfed as c>'-'
if len(i) and x==i[0]:
nextchar = 'v' if c=='^' else '^'
i = i[1:]
x += 1
print(nextchar, end='')
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
O^%5T⁴ịƲ¦40Ọ
```
A full program accepting a string and a list of integers which prints the result.
**[Try it online!](https://tio.run/##y0rNyan8/98/TtU05FHjloe7u49tOrTMxODh7p7////rxumWASEXGMcB4X9jHRMdMwA "Jelly – Try It Online")**
### How?
```
O^%5T⁴ịƲ¦40Ọ - Main Link: list of characters, S; inversion indices, I
O - to ordinals ('\n':10, '-':45, '^':94, 'v':118)
¦ - sparse application...
Ʋ - ...to indices: last four links as a monad: f(O(S))
%5 - modulo 5 (10:0, 45:0, 94:4, 118:3)
T - truthy indices (giving, X, indices of '^' and 'v' in S)
⁴ - 4th command line argument = I
ị - index into X (giving indices of '^' and 'v' to invert in S)
^ 40 - ...action: XOR with 40 (94:118, 118:94)
Ọ - from ordinals
- implicit print
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~80~~, ~~78~~, ~~77~~, ~~71~~, 70 bytes
```
lambda x,s,i=0:''.join([c,'^v'[c<'v']][c>s and(i:=i+1)in x]for c in s)
```
*-1 byte, thanks to @Shaggy*
[Try it online!](https://tio.run/##fYxRC8IgHMTf/RTii0r/RWsVMVpfxBSWQ2aUG27I@vTminpbHAcH97vrn2PbueLY@2iqS7zXj2tT4wkGsNWmpHR966xjQgNVgQp9ooFKKfR5wLVrmC0ru8q5dXiSpvNY4xQHHntv3cgMExIIIVnIVHJKnCP06Tj6MfkXWgIK2MFBApqp@Shk6G2VtHgKW5h3@//L@AI)
[Answer]
# [Perl 6](http://perl6.org/), 31 bytes
```
->$_,\s{S:nth(s){\^|v}=$/~^'('}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtf104lXiemuDrYKq8kQ6NYszomrqas1lZFvy5OXUO99n9xYqVCmoaSbpxuGRBygXEcECrpKEQb6yiY6CiYxWr@BwA "Perl 6 – Try It Online")
(-2 bytes thanks to Jo King)
Perl 6's substitution operator `S` conveniently takes an `nth` adverb that accepts not only a single index at which to make the replacement, but a list of them, exactly as needed here.
The replacement is `$/ ~^ '('`, where `$/` is the matched text (either `v` or `^`), `~^` is the stringwise exclusive-or operator, and `(` is the character whose bits turn `v` into `^` and vice versa.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 29 bytes
```
c!tt45>o2yfi)(2=XK)t106-E-K(!
```
[Try it online!](https://tio.run/##y00syfn/P1mxpMTE1C7fqDItU1PDyDbCW7PE0MBM11XXW0Px//9qdd043TIgVNdRUIdRcUCoXssVbaxgomAWCwA) Or [verify all text cases](https://tio.run/##y00syfmf8D9ZsaTExNQu36gyLVNTw8g2wluzxNDATNdV11tD8b@6Z15BaUmxlTqXoXuykbuaC5e6f2kJUAgoYqqSxGWQzBXhElUR8r9aXbdMNw6I1Wu5omO5ULiGYD6IB@TrKKjDqDggBMkbK5gomBFQY6hgpABSZwpSCQA).
Input is a cell array of strings and a row vector of numbers, with 1-based indexing. Output is right-padded with spaces.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~105~~ ~~97~~ 91 bytes
```
lambda a,s:reduce(lambda(t,i),c:(t+[c,'^v'[c<'v']][c>'-'and i in a],i+(c>'-')),s,('',0))[0]
```
[Try it online!](https://tio.run/##JchBCsIwEEDRfU@R3czQCVTFTVEvEhOISYsBTUsbAz19Giqfv3nzlt5TPJfx/iwf@315Kyyv/TL4nxvwL5g4ELseU6scg8mg3A0yaK3cAyTY6EUQIQqrObR4GBGvjADcEalOl3kJMYkR1YkvfNXcAIA0MteaY1OrRmUH "Python 2 – Try It Online")
6 bytes saved by ~~stealing~~ using [Rin's Fourier transform](https://codegolf.stackexchange.com/a/188728/69880)'s `c>'-'` instead of `c in'^v'`.
`0`-indexed.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
⁾^vḟ$€>”-T⁹ịƲ¦
```
[Try it online!](https://tio.run/##y0rNyan8//9R4764soc75qs8alpj96hhrm7Io8adD3d3H9t0aNn///9143TLgJALjOOA8H@0sY6CiY6CWSwA "Jelly – Try It Online")
Full program.
This feels *too overlong*...
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
¿╫╦ÜΦ1▌X○!ΩTæ
```
[Run and debug it](https://staxlang.xyz/#p=a8d7cb9ae831dd580921ea5491&i=[]+%22-v-%5E-v-%22%0A[0]+%22-v-%22%0A[2,3,5]+%22-%5E-v-v-%5Cn-v-%5Cn-%5E-%5E-%22%0A[0,1,2,3,4,5]+%22-%5E-v-v-%5Cn-v-%5Cn-%5E-%5E-%22&a=1&m=2)
This uses 0-based indices.
1. Find all indices of the regex `[v^]`.
2. Index into the *index* array using the input.
3. At each result, xor the input's ascii code with `40`. This is `xor('v', '^')`.
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 93 bytes
```
import StdEnv
$i=foldl(\s c=s++[if(any((==)(sum[1\\k<-s|k>'-']))i&&c>'-')if(c>'^')'^''v'c])[]
```
[Try it online!](https://tio.run/##JYyxCsIwGIR3n@IfSpPQZlBxM046CG4dkxRi2khokoppCwWf3RiR447v4DjtehWSH7vZ9eCVDcn65/iaoJm6S1g2hWVmdJ3DIoJmsaq4NViFFWPGCI6z51shhiON7@GEKJKE2LLUPyR5mKFFJBstSEvCZWomlc8ZFMB3NexrOEjgiLZ0yRLhH20WkumjjVOPmOj1ls5rUN7qXO5f "Clean – Try It Online")
Defines the function `$ :: [Int] -> [Char] -> [Char]` taking a zero-indexed list of indices and returning a function that takes the string and returns the altered string.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~101~~ ~~98~~ ~~93~~ ~~91~~ ~~77~~ 67 bytes
```
a=>s=>[...s].map(c=>t+=c>s?"^v"[a.includes(i++)^c>"^"]:c,t=i=``)&&t
```
[Try it online!](https://tio.run/##JcRZCsMgEADQu/iRKC50/SmMPYhVIpOkWKyGar2@DZQH7@WbL/gJW5Upz0tfoXvQBbRRShWr3n6jCLpyQF3uxDVivAoJ43deCg2cM4eaOGJvKCoEmCY2DLVjTiXHRcX8pCs1B3EUJ3EWF3G1jI7SybZ7pH9uNzLWfw "JavaScript (Node.js) – Try It Online")
10 bytes, thx to suggestions by [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy).
Port of my [Python answer](https://codegolf.stackexchange.com/a/188732/69880). Not used to golfing javascript!
[Answer]
# [V](https://github.com/DJMcMayhem/V), 20 bytes
```
ÑñÀ/vüÞ
sv^l?Ö"
xH
```
[Try it online!](https://tio.run/##K/v///DEwxsPN@iXHd5zeB5XcVmcdI794WlCSlwVHv//68bplgEhFxjHAeF/4/8m/80A "V (vim) – Try It Online")
Uses some new features, such as `Ñ` which is **incredibly** useful.
[Answer]
# JavaScript, 111 bytes
### Code
```
x=>y=>{x.map(i=>eval(`y=y.replace(/(((v|\\^)[^^v]*){${i}})(v|\\^)/,(a,b,c,d,e)=>b+(e<"v"?"v":"^"))`));return y}
```
Takes input in format f(x)(y) where x is the indices and y is the switchboard. Indices are 0 indexed
[Try it online!](https://tio.run/##LYjtCoIwFEBfJSTw3rpqn3@qrQdRh1NnGDZl2lDMZzehOJzz4zyllW1myqbzdJ2ruWBzz/jA@Nj7L9lAybiysoJkYINvVFPJTEEAAPYTRQJDIWy8wXE9ltOE/xkQSEopo5wUMp5uQd0c69wXL45wEBPEq1Hd2@jVMM1Zrdu6Un5VP6CAcEd7OtCRTnSOEVxPeHYh0r@IBRdx/gI "JavaScript (Node.js) – Try It Online")
### Explanation
For each index
```
x.map(i=>...
```
construct the regex that finds the index+1 th "^" or "v"
```
`.../(((v|\\^)[^^v]*){${i}})(v|\\^)/...`
```
insert it into a string to replace it with the opposite symbol "v"<->"^"
```
y=y.replace(...,(a,b,c,d,e)=>b+(e<"v"?"v":"^"))
```
then evaluate the string as a function
```
eval(...)
```
After iterating through the indices to switch, return the switchboard
```
return y
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
⁾^vK;`©⁹e€ky@€⁸¦®
```
[Try it online!](https://tio.run/##y0rNyan8//9R4764Mm/rhEMrHzXuTH3UtCa70gFIPmrccWjZoXX///831DHSMf2vG6dbBoRcYBwHhAA "Jelly – Try It Online")
A full program taking the indices as first and string as second argument. Prints the output with the indicated switches flipped.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~66~~ 62 bytes
```
\d+
$*
T`v^`^v`.(?<=\b(?(3)$)(?<-3>1)+(,1+)*(-|¶|(v|\^))+)
1A`
```
[Try it online!](https://tio.run/##K0otycxL/P8/JkWbS0WLKyShLC4hrixBT8PexjYmScNew1hTRRPI0TW2M9TU1tAx1NbU0tCtObStRqOsJiZOU1Nbk8vQMeH/f2MdEx0zLt043TIg5ALjOCAEAA "Retina 0.8.2 – Try It Online") Link includes test case. 1-indexed. Explanation:
```
\d+
$*
```
Convert the input numbers to unary.
```
T`v^`^v`.(?<=\b(?(3)$)(?<-3>1)+(,1+)*(-|¶|(v|\^))+)
```
Transliterate between `v` and `^` all characters with the property that the number of `v`s and `^`s so far (inclusive) equals one of the input numbers.
```
1A`
```
Delete the input numbers.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
⭆η⎇№θ⌕ΦLη№v^§ηλκ§v^⁼vιι
```
[Try it online!](https://tio.run/##NYtNCwIhEIb/inhSGC9Fp04RLQQFQd22FWRXVllxW3Olfr2NSLzwzMcz0xsV@lm5nG/B@sjuEct4VS9mgDx08Cp82XFeUS1AGusH1lgXdWAX7cdomOFAqqdJUiCHePaD/pR3xznKqeC/rTenZVXujQP2tmgE3@fcthvYwq4DKqRImKevkBjaZZHcDw "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Explanation:
```
η Input string
⭆ Map over characters and join
⎇ If
№ Count of (i.e. exists)
⌕ Index of
κ Current index in
L Length of
η Input string
Φ Implicit range filtered by
№ Count of (i.e. exists)
η Input string
§ Indexed by
λ Current value
v^ In literal string `v^`
θ In input list
v^ Then literal `v^`
§ Indexed by
ι Current character
⁼ Equal to
v Literal `v`
ι Else current character
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 56 bytes
1-indexed.
```
->s,i{j=0;s.gsub(/[v^]/){i==i-[j+=1]?$&:"v^".tr($&,'')}}
```
[Try it online!](https://tio.run/##bYpbDoIwFET/u4orIQpaWt8fanUhlSY8itYQJLSQGGHt2Bo/zc0kd86Zpk1fY8HG6Kyxej/Y8qjJTbdpQHknYhq@FWMq4o8FW8UXf3rwOuER0wT@FM9m4TCM/ok0MsmJrktlAp/O1yGRSXaH/Am9kdr0CEABA9klZeAA0aXK5ASoIPNrRUPr69ZoKLizGFT8I0hW@chjFHWRsEGIr77FPhu8xXtbHLfgG2HPbfAaO737O/gA "Ruby – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 73 bytes
```
a=>b=>{int i=0;return a.Select(x=>x>45&&b.Contains(++i)?(char)(x^40):x);}
```
[Try it online!](https://tio.run/##jY6xasMwEIZ3P4XIEHREDm7rLJWlFkoLhWwdOoQYJFVpDhIFJNk1mDy7KztDClnKzy3/fXx3JuQm4PDWOFO9v7rmaL3SB1uZvfKSXeo1hlihi5LdEFLuxKCE1EL2iSAoCu5tbLwjavlhD9ZE2gnZyXI1n@vly8lFhS7QxQLhiY4KoF1dFvDYAT8PPGtP@EWiDZFezypGQvTovomG/tNjtGt0ll660WlUpDuqgSoA4FciKbPJ5ezPZtvfswe2OrPnWV7nbUo2TZ0yA/4XLNgdG@HyHzhJH26K7Yi1E5iWwy8 "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 15 bytes
```
®c^(Z>V©øT° *#(
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=rmNeKFo%2bVqn4VLAgKiMo&input=Ii1eLXYtdi0KLXYtCi1eLV4tIgpbMiwzLDVd)
```
®c^(Z>V©ø°T *#( U = Input String, V = Array of Indices
® Map each Z in U
c^ XOR Z's charcode by
(Z>V Z is 'v' or '^'
© Short-circuiting Logical and
øT° The current Z's index is in V
*#( Multiply the boolean with 40 (false = 0, true = 1)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~16~~ 14 bytes
```
Ëc^#(*(D>V©øT°
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=y2NeIygqKEQ%2bVqn4VLA&input=Ii1eLXYtdi0KLXYtCi1eLV4tIgpbMiwzLDVd)
```
Ë>V©øT° ?Dc^#(:D :Implicit input of multi-line string U & integer array V
Ë :Map each D in U
>V : Greater than V? (Coerces V to a string and, conveniently, all digits are > "\n" & "-" and < "^" & "v")
© : Logical AND with
ø : Does V contain
T° : T (initially 0) postfix incremented
? : If true
Dc : Charcode of D
^#( : XOR with 40
:D : Else D
```
] |
[Question]
[
# Input :
Two decimal integers `m` and `n` that respectively give the number of rows and columns of the table.
`m` and `n` are greater than or equal to 1.
# Output :
A table in HTML that has m rows and n columns.
The table should be displayable by a modern browser of your choice. Most browsers will display everything properly even if tags are not closed. Proper indentation and spacing is optional.
There should be at least one (non-whitespace) printable character in each cell.
**Cells on the first line should use `<th>` tags while the ones on the following lines should use `<td>`tags.**
# Win condition :
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest source-code for each language wins.
### Input example :
```
2 3
```
### Output example :
```
<table>
<tr>
<th>A</th>
<th>A</th>
<th>A</th>
</tr>
<tr>
<td>A</td>
<td>A</td>
<td>A</td>
</tr>
</table>
```
or :
`<table><tr><th>A<th>A<th>A<tr><td>A<td>A<td>A`
[Answer]
# JavaScript (ES6), 70 bytes
*Saved 2 bytes thanks to @RickHitchcock*
Takes input in currying syntax `(m)(n)`.
```
m=>n=>'<table>'+(g=c=>'<tr>'+`<t${c}>A`.repeat(n))`h`+g`d`.repeat(m-1)
```
[Try it online!](https://tio.run/##PchBDkAwEADAz0jsRkhw1SZ@slWrSLVSjYt4e4mD48yqTnXosOyxdH7kNIm0CemEzLuoBssyL8AI/Tm8oC5ml75lT1XgnVUEh0gzFYbGv7ayxqS9O7zlynoDEzQILWJ6AA "JavaScript (Node.js) – Try It Online")
### Demo
```
f=
m=>n=>'<table>'+(g=c=>'<tr>'+`<t${c}>A`.repeat(n))`h`+g`d`.repeat(m-1)
O.innerHTML = f(2)(3)
```
```
<div id=O></div>
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/) with [MiServer 3.0](https://github.com/dyalog/miserver), ~~31~~ 30 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Full program. Prompts stdin for the two-element list `[m,n]` and prints strict XHTML to stdout.
```
(⎕NEW _.Table((⎕⍴0)⍬1)).Render
```
Example session:
```
)xload C:\Users\Adam.DYALOG\Documents\MiServer\miserver.dws
C:\Users\Adam.DYALOG\Documents\MiServer\miserver.dws saved Wed Mar 7 17:19:40 2018
Load ''
Development environment loaded
MiSite "C:/Users/Adam.DYALOG/Documents/MiServer/MS3/" loaded
(⎕NEW _.Table((⎕⍴0)⍬1)).Render
⎕:
2 3
<table id="id691498143"><thead><tr><th>0</th><th>0</th><th>0</th></tr></thead><tbody><tr><td>0</td><td>0</td><td>0</td></tr></tbody></table>
```
[Try it online!](https://tio.run/##7X1rbxxHkuB3/oqa9oyralTsF6lXN0mBoihLXom2RVn2DskzqruLZFnN6lZVNUm53fpgH7wUVxys1zDs@7B3O54ZmFgYGNza3gEEGAvI/4R/ZC8emVVZr@6m7Jm9PRwtk91VmZGRkZGRkZERkXa/O9t5bHd7O/9xdvR32/9hnP3287XVd7T3yvftVtcx8PvZyXdV8@zkm5pplu85XsfxsezM2ck/abOTf6jc/Vur2trqyur6@vK9v9XeXL53f11746Z29/b66r0Hq/e0uXJ1aniNdtcOAu319TfWZqjSSs/bd/yQH2mGHWi21t61fbsdOr6277TDnm9qYU@zvY627ff2tHfv3qEvy2/eKTN@uw5@0bZ7/p4danv2Y83uBj0tsPcdLdi1@47mevzS7Xlc53bIZVyv3R10nEDz7D0n6Ntt@NgahFoIMKNHmu/0fSdwvJAgUAvdXuBoHTu0CdzBruMBUlqv9T5gTDW1dg/Ku14QdycAsICg7QPsXqjt2123AxgQ8tQY43a9F@4SAvgce4o9RvwDqlqrVn@FzQddBygJZR3/wA0cSQs30PYc2@O2GvQQft4PAO@zp78jEiLcsIe/6bFGjaTKYJthD3/j45kZBALsdPuNs0/@Af7evQN/a9rZ3/93fNrvw7e5eS33BzF4AJ1HytXL1SrDCntrgz2oNYTqN@8hsPqVywTP2Nc8k1t5cPO2tu0eQkmA8r14CxhaNbNxdvyxx@2ffDMikB3nrUEvdBCovrlZ0gHAPR3@HH8FXzc3@Tv@hQelkh6EvttHuFzbDe4521jXqC5CE/DcPDv6eq5@aRHq3binFMRSlbOTU@6H72I3zp79cHb05dC4UIFKm7qmLxKATz7Damcnv69T4UFAPX76z5vwGP6cnTzfDOHviz/VoGjVChHSyfMKlpDPEADRsG/7oYv853Q0LCCwXgHuQqhVrX52dAxo1aofAsYdX@3auuvtdIkyRm0RKAdSwRI9rC9xb@Oie31RtEoAv6N/VFZSRpbFOUttNxpVGosnoopgnagoDyIWbcEvfVZffEBdFWPaqjzAEddf/EnnIT36ukIFL@jQ0weNB6LY2dM/Ilme/fAAmtGdVd2sPBAN7IWiAaMedx8E37@eHZ0yLAC@6FOrIBS/b/iyad9klOi7z@CIN2isTp7j2@EoRgweLRowNp9iAxYNE35s4HDxoMl@Rd2nmb4GM5wQ1Ms6Uel7c6F69vQPKLRX4rItZweExjtuuMvtA5/8zpBDgC0953IaTdNbzqEYAOTSu@@WV@/ihFy//dra8h38tLo2o0xFMYGryrPapbPjP56dPK1d@hCaGM4kJ@9cDehXXkBmaRj6bY9l1q5zaHectrtnd2PpZgQmCjPdgsLPzRiJy5cvz6QlAs6J789OvgV2Rbwt3W61O862bvG35esrN1Zv6iMWFY1t1@l2tP6g1XXbKNB9mAGhP0Bqnh1/pONHvbjkNgh6WZQ@jynrDbpdURQ/6jNCfs7@HD@iNwGsECgLhSQWovXo7zSaxr0@vgxGUk7bvm8/boaP@0233ez4vX7TC5q0Gvn7TvMRCrzmo37TgYFphjNS3lItmKC4JkVQxCg0ltttXDkSPZ@JGIRHzagt8MynmmYFKGLoq2u6VquZhn4X6ts7Doi5ZWrIt72H2pJW003Zxn3f7msqmzVub0fCJYGO/MHe8ywW2NMM@uQfqyBwtfqHQAFeE0AUi/fQT2@w14KlJQWqse50cRmmmYVjSRX0dKkVO3DuuEGoXS3Pw//1mZy1K6IHfLp/6/Y6TMapKNK2PVziWw6qM6jyRKRJNA/N1nKa9WlxreLQvcEaRR7FGqvAzEW1QUjiIme9vowTNCgA4HWYVDMpqERcYB/sQ8BjZnC/c0ZN39BJ6J26bfjGK1J@e8ADYoHIey3hGbULbtuEVUrf2AKCQi/yRgY4I48eyGbtPMBWDlWsmJNQ4ns7rGF13KDftR@DPAB1NBi0dwsaqi9KdkgXWPY62Fd4/1VBZ0URsX4ffzyOIGNeF5GhmAIwUrB2Wrr14lTImBenVhF33N6eyQGC4/yZvqXPFBSOWSgrB4xoSlVMsWQZsGatrkWiAyBhLSkWC@QjyD8X1qIPnL@EkMS3oiFtVuwrQmAP@TAqhD8btS2QpaFWonaCEsDpDUChJo3@WrJoHYoKtKjJeHeSKji3pSG216B514PFFWqFWtexO4iFfnbyWx150/U6bpv3JLBDCn0HdxewlbL37fU2aDAhSGbcH@BewNNob8V8HjUW7WyA2Vuwb9K6KBB729oGynSL8LNQAh84MeZuaOH@xKP9z9YUy0qDJwOKY12QkPUp8QVVEhB3vJ9IsNIjlPoGUTZuHymDStsc6ENymKg3nR7iyaWjHRztbrJUvzYzxcL0My1K2Ab2/u07dwokBslRVjmycgaaWYSNiBiwbc3wgrQc1ld4wTno@Q81YAfaTbth4HS39VgVu1SrIeKptSwHlUf9MWtPnoCZas0pEBKT1hmc0ABeDuHCuGUG8eDyn8GyZMk6FRR4sEIZpPzHeo0VyUJ4gb8ysnrCmoWvn0TMJbnj7Pj3@QtZlsETghXILmSyFPm88/N7YQ@YwJmZYrFDjHCC5K83uBtiCj8BjGBP92W833hxqm8PPFJO4Z3zfhl@/9LQDYvkjYmo/OIXv0BxqL3/1sDxH8NYwdRaf@y1twe4vTflfLaELAp3aU2lJjyUXAfQjCYb0QAQtIJyqeuCjAPdvEgjIAwWcafF4wbDey6N6Gdd/FOjl9coibSzk2@Aa4yIPcwfv6iePTuCPeIFhQdnJq3SIAKPvlSXO1ivSd/6PbRy/NXYSRZBlHMiWrSVYolF9n0yUYT@2547iuZxv9vc9vxW2ARCNVvNQTto0lZysuhH6r4GSxfJI8UQRpY8se4qS5KYb7j3IETgFfy2AIHUlIRt6XFLFDg6JuRQgpY2K7SHfHtlXavVtRqsKXPaFe1qisiw64eKtO/fhEmJRiH4VcFf2/gL@X/Tx18t/BXqG9zCybdUcWscuVXsavUrC0AsXiMQp1RHeE4OL8HuXZgMmPDpPUG0b5c2iwj7gQ7MgeLr@KON6pZB22f4tWxuGPNAxNolED9/aFUAibFIE7EBaYA7iT@gICy3MG7bHq2vTVAh4rFewXmPmx4acB7ZxGBve6KByJgg4GSWqSewzJXZOILvQVYdz2nzojY0ikuz2CSLgvfY8MqY4Prf7nXkzHyf2WNQr1cv6xaWs/RSQ7cAEC9CYYD9wxf5mqdUNOJ1cW296TWJBKxhynmeQw0sNQvdHYAWY7t@DnVia7NAOKX04HDXY31nJhaOlj6MJvVNEKkesCCQFN6srRNZ7szWU/tMEgmigT37obPOmHimpTd0TSFgRA61nqSEpP7aOkhnrGvpcU3qrMJLgJkyw6Vp0UOrogHM67FxDFbhtXUcaTbqaMJgk15YFbTS0lchQdT9SAuYyxO2xtq6ZGfqQ2qeKIirs4YUthErFbNkLMEZ@ZmfzzyPEmRGlnkrUsFvghZPJANm6UqmsIOg13ZtVMtpzRSzZ9@GZaDVTQwM0vMRrOuI0NnJ/0DbIi6UKTpFe0kSRGgCfvYDW9iHLbRGo0EbRdYTNMwB/QHSe/ooCQCxXe87gFdXleUl0rA3tb1BQBaPELrq4balp9ntNuyFVPOCYaDAhpmomxXfRPKRHNOLaPyWZUB5KPkWkrGiC2NAhsI088MejCUdykzek8hKQ0GVtXVdmICJyUDfMHSL9cXnwBcm26v1UQQ@QqHheJ2MUe8vZzekk5u4873W@@q@mM91cJ1u15qtWBTRwRDwOA5OkJLPOHzhwIcp7YZi3Jjd@DhLBeLIOjTY271ut3egBcgT20Bgf9B1cFcKml0Hd509MoDBGPTDeC84ZkzEcq@sQhn7gWKRKzDAyXWFejgLOt3OYA82uHKbYcuNRvqUUTdNWHTEviJGYer9a6zaK9OFd6TFu08JHWT4YrvGqt@nTAY8WUI8ngjdAdQYodCITVOIQwoLR3BtptBqKWlUH0ci5xAGEEVNu9sLcHBHRAsQb/Js6tMkPfCH@U6uBX3QEx2YfBJpt58modivwK4MOqoV/5BlxhPb6T37ccv52bu3xd3bmtw9kE@/N56IToIq9VWivzCabO2Nj36ygEgfXIT1ASDm78mwqaNjXPAsWu4stAPk7GIkSscf0b@PcwDm7k2Q6iWk@s9NxxLTsTSZjsuv804iQaj8oRcC5lpOLwyrZuIBJGnDxx@3MofEMVABio49hUEmFzFcCGktbOVRjQwy0GJRt1IDFdUj5WVMPXyfV4@1nTEVqcCEvSeXTM@@v7x5NrUQdZyEifb/lRVp8vqz/BMXnL/cYvOzLjQvLT0mLS75C0t6TfmZ1pOX7sWkNeQnrx@FovunStSfXZoWSNIJUlTUYqv4zFQCNCM8JwnOrNBMC8y0sCwye/BMkURHYbZnBw@bwa67HTadoA2zLGgOPBetIV3YxDdhUxc03ebq3ZmYhGT/wN1@yho2zcE8bn7pkBU0iVgokRxYvYtbKLmDQrzIPn496NrBrpbHFikO2bP9h1oJt58lbTNu8PryDc3dNgjg0Sl1FQBLvyR8bJJzCNvgcEsXQUxvCZlC6nEQGqIRxEziLJObfIJuNtRehWELAgsLX2vb88OBsDX0vO5j4UknSgHheoNuRy4Fm0oLMEAIY6AvRtAn0uVtz0UzksYjb8BG/bHmOSAB9no@CtsejhnMDPXEQjABcha2s/kEGh7TTsf10Z4kauHaoRrCDfFcGv2ElJ6b167WtfnLIK4jS@fVDUmpk2@VWlvpoyigfTFGKcn5OEmBtDKOfC4clSrk0IOOSiPuNrSRVlAzCof8ATQ3ENZW3EPh38SvkKWxqaMvyxegnfmtKU3/NDki36j8E3TguhxFOtJy4h9k2A0XUayNs6by/DSe0BSp5AoX9eQemm/MZE6bEsjyFJdrkZhNOa5XBW0Zuli@dGv1bo5rVkLUkYYRKRHR@tsMD8Nm19l3us2g33VDYfsMmniovhfsxDrZ@sCnE3A6qh6OdFaDxDmztuv4ioV0tcv8TkcvgQOt2eIoOrbEEUKvlFUbTUIcAmIk8O47h6EmZw5hiqNwYRPeLwQooTaGujmrfN8aRU1AyQsV6hcOrmXQe6uBJ2RfY3kCtygZF7qrjkdEXKN2of6hRyd@A69ld22vjZ3xya2459Onh04I@pzesjvCsUCPgSque5eqeMZsELij02qkZRAiclj5fFuchhM9nqIy9@LU8H78c92s4wkA6gen3LPjj/Qm8IjsM1bGqYumSXROlA605J/34pTeJw3LAdpVV@32rha1rDApfFM5R1ii0oYOYDHUmbAvXsYv8Le6F5R1y7N0gATw9HzHpFBHfXQ7XX84@vHPBrpmfgZEe/oVnwrcfJcIVFHPGzrOtjfGeyU2@mbMjBGtopmGCN2Fp9qgL6z4dEKaMtiea4k3EnZcHP8nkQcpYRFPc19afekk@734JJtFqCyY6QdPa4QXn3iwj3FAmzH2YKfjC5qNst/n6seQ3WXRnsx@nWxUTlmmY6u05g/rqEOyFgoVhWH6@cgXIKLOyL6QWq9w3To51CS1a9TW@k30ZwGZlZZitEGKR/IeejKi7sKeOQAWZrCj2pTpBZ/uKkI70b6qCQA81FnR293Ak9@@OLQ8@VYno/KnUovjRaOfsSE13tl1QetGQEu872OnnJeAyuZtADQbOe8js1MDOctGTBWc/c5eP3zM9A5wm@kc4tacHIM6PU8PWSmCDXYsAHZF@EXMGEaCTsjYYrVj3eYzeSiu0jex2YdV4sDtdjW7ewAji3t5cosCLfONtVXN4dWEtLTYa8LUAtoYSwRhm4w72saUqxB6gIkjmj3Rk@SKEw1Xes1hvVhddfhJvO7o12EZ2BiOtgC5AD3M9PQKIICini1XH2WZEkAXadSPvk6uUvlzg8Tyi9OcdSHqh6xoUKTA7w0DFUbC/UvYYr04TR7OoXxKDevXOPEBN9NUvRNg/JPlYBuRapEnl@oZkXvKIo5AkucisddbUtSFvdfJW@VNGNU9h06sAHwzBJngzigcjrFDKLJxrqM2ZYPQ8zzHx0CewA1CZCw6i9vrAbuxB8xsED7ukrxh0KpvIVpOep6j9bYb0ePZRFDRNrCz13aUt2kTEXriCfdD4EfhdRO1FqhwgX@gSFyNGqrQMWxcbq18vQyFYd60gdW3B13uEeiTXdtX3OUUPAgAaJC7MOC2bhp6S9eMmlbX5kxTW1rShrt2Y9hqbNSsujW3NRoB8LY9gJVa1KCIIn3X1tXZPNFbkKJxkIry2Rs@bVy@rtCbF6fxK7mGsAeh4jef2PJLz0rJbuRW4vsZD3XpVcZ@QbHhDgibOYfAhe7Zv8NCp4@GaHzA83mOT0HwKejS35eURVq2h6AwslkLipqWPtJzGuADdfKmAnnbdR@iO0HMAWLAJ5iExRkE@ftpyr4ZZSgZ92Da9R20tgYZhsjZMgnyocXMYkc1k7Qu/FDgKm3UF3lao5hSnZ5ZoeuMbSVJyWLfZCZquiguXi45BPD@NAsNf3AFdRmlnLfksyCYo28uRB3oz@RvndmxoIYlyKeioJgMVPgQhiak2CAhcWsLIgTNRF0caVvUUhzFANw/U7yZJ4zE5IiakYFhWtRUWNRMwfY6AT4raaGdYog5wQfTNKf2ROvP5EPOMEdUM@nhkfXySPgdsrErMzkz@4U8kyGvPYDk68vvat5@v7nv@K3m9l7YJJnaDEAHPWx2miQCIgnN0p7jUSuxx1CQWJGCgRuSGwjuNGITFCos5PbUdXGxCtwOrj4aoxC1AGXhrWt3u1Tad0jrmdcQvSBeqgzdOXTagxAW@vdhZQ1oZTWV18LApIPC1OUwXUPHtVPXdsO9rlqShEtnioKgHkwsOX7tADqj0IA/WYsKPBQOHhizsiWcce85eNCUdcyNQgDpZCAb70deSujSy869w5E@LgKQIhQJmpAiCGHJEMsBgzsNeTMnPF0p5k4vwSIh/TAJAT0RDkM@gw1uEsMaU694eYm4UEFHBO7MZAWRQjsKUarx6IAq2nH6sDbULPROGuw5ch@etGZHR3hdWLQ6ad9swFIOg6B8oq06NRUrMfwpyG6HnsRjWhD8hezMxxI5ZaixiMELRcUQqI9w2FXQwCE8/hiJjSs9gEW5YOVVJzb8jJ2b6oVxZ/EUijlfTpYcoIc4LbQOq2QAeJ6RmAp7@AiV4ZMFnzpxfxjYVP2Yn8LiWhBRltpjEvXnmK3aZKsHhdRQBI6@3euhqhk/2MEHpvbGPSwXkw36pEcygmupGkiWFzLsMJ4ViJDCExuoABsmnFAvTuWMenGagpZDE4PGzTTEwKGpLjtqP3nEMpTnjs3PvFxnMuBSy@FWgRve0KbIVco/oR00P2iGE4U2c4HIAmFrvLDxsiX3Ynj@L6UC7D36IGX83gEuibjcUQ0z2vNwEgeRfUH6W3aE50C8FUquoTYvoNAQSrOydOOLDz9nNeH3andNAN4d7HnaLsdjBdIQi5AQIdGUxC/GKl7rDgAgrPO@e4h4YzcpysqOgmEGfdiaOx1LO9ioNbcoSo2Ebkf4MLB7cwKNHP8Bmxc5G9dEXFMO6OtBNKdzIq5I1b1S1a6IdAIiusnkkryLwXh0yzYX65xK4CBuBDZm@SClwI68LV@cGqK2iYdGxx/pKjv7ho2x92XFD1OaINHC@TzllGm@OB2SkxWumQQ2Xn@h/CefHUyhrJH1JKCd9BtiBL0AD3G7fNjrNdsDH3bscQQhFoUx851g0KWouYh5eAKg@6vfEYzF4BN1YTTd0BF5PdwofUgpGLRu4/PSNBoPHV1g1gluYFEgyfJOaVS4vOKiEURnAEHAzz6Ln3EV8ThRXx3HuHwSCdH6giBmRCXiV1gEOvA24W90/DGrVL5Zlt1GRjI8edgRmIkRSeBf1IcJ/ShiTgAgTz0pdAlgbIdsMryWFqT53DIFm4GIJO643yPF6eCc8ZO2HimxchOkSNyki1eqnJ1b0uvk42nb2nKnY9jagTmlO7Vt2PYQNWFMWcFqMk9UqTTjt4YhVWQxiWk1eo67ZNR4caclpu5zepx8PTIPUmZBWqjIAigNguIrpc057w@O/g3bu67Vq7VapVaPSXK4h6bdIQrzEWc3ES5toK01W83Q3mm2nJ0mzufYsPwmHkQkPNtoMYPa5xx1ipAhuohICR3T8uTEEwIe5A2C51@R9YacTzxhwqejHY56VuOHMTPRAfCF7fFkfUB7TzYTVXD9bffQGBY62n1bBmtB13GTa@9U9IWKjKpZYqyAGNE7fkWPkT7Rc/yiv6RzmjIfEwexDdXTLG1NL/Y64@EFpC0d422dxRIL49ISrD50ngSzPPZCMy3H6@S6ok2B11YWr63p8SLbeIzWsu/jDnQ8ZmkfMoaK5Mfxsox32bEpTotEgMTAYjEcVFRbHKGw252OJvBhxi6lmozS7pD3l5Y8MkBpe/xRXkcZJQEZEDNaZyff1vBEvabVKxJYq9frOran424Y0X@CdGuprhYxRPhtGYmemC/jCEfLAjkUed6F1b298ZizjxziJuvGlMO0Y2Qfr10GraalnxfjBIOtPVi@c/sGMZjCVLXaVO5siWQzKNGg5SZqk823QKL10MUjjjqOxRnLPjvkszYSaJTP7WfKA5BybU3H9StpFVjvgHUbcWbC0TJzCjzNyYWYoCRD4OOMSuUhFpJzjtTGWGdk/XgWBJfIUfTsB1x7UJGIwZDA4swyaL59TKfCFwGYQeicfAuzDs808dtM6tRAuq4ANFRzRzweOI8zbkQYxm4kAoIlsY6@FOP24hT2rqQ5Yd/i3ZkiAEiYSTynxGY4ysFmWIzNjiM0IcJHKkWM0UjPOJ/v8QGumMvoHoOzG3dBtE6lTmae6IsoNpCYysH2W5bx@rtsHKN23iIXwbwcCkLDg1JK9fyMC0oBKg64CiSvndcGzFDeVdxGAydsBugw9bBJfozNAUy1Qw6nbt5yDsWZZBQ4Tbn/OEJUUSPyvEIjf9B0lq@gK/fuz37YyziH4oEMn0sTPkgV4WCZ8taMw62hD1hsYenVkp4j3KCz3o7DmQljT3wmQez9lQ7EfrUbNkG0v7rDf@y9Pv3FSd/UN7DJVPR1RounU2rVIYkw7m4@GUinz25qhYibj7QLxZeS6ZEX861SpLs5iDwlN98@hB/hIZ0@LuRUbWPSnaXKY2klORtWP/lW@kIC5nya1TLJJbKW6xSZ6d9h2qEx8mcUUzJ4qPU4/SXMg34vcNVo43FsLwUELKBWxXiyp3o@5kwJOWtJh4ZPMAlwSpD/NMyRR5xvICeHgIwlx3nxarnc1KDwAE/Rg8iN7mFk2IB3OPTNV185FHHy@sryjStX23aH1x2ZOKA4ZQAdHyKG6J4bub8ZaXZlNpV8a0HDpgETpPSqbl2BUaJ2VMskjmE0hPAZWzg7@XOSPaErS4jc03/eFNMXR/vUmOVxh5UGP2FVXGdaMylvWhzXKDg/dcrFowANKDNCjMxyNDI5g4dSQxUg6E6lDBPFMh/QoRJFM7fs9kMq6JCNIxJIDEXf1BcBQGr7Jd102rtO@yHZ1PYG3dDFg3jpyx3SxAMgS9IbnbGJYIB64pNBxsHR2vF7gz5@20whwH@Pvg5BIdMECJHO1XfimOzNCPcEMSJPe3IDwv1YE2U7QOGEADKFkUhKikq4yLeq9JZcizq9Ae7JOYGU8DHvOF13zw1lbhIzhXo0ApSeNdkS/U2TJqdfJWVMRGcYxNEp8lzciUS3MUOU9CCEzUfWM7jAExg3KT/RExg9yEDT@Lq8SMlrKImKQEdaDxMR9QIMNg@7V@hirv/WS3kMq77C0v0q6ygskMOqtNcFIUS2g1z/q6KQunj3meODTYfDzcO/nPd1Hs0Zr782yc/ppJ3afY93yD6f4zUuzVVrWB29OCX6iz3GdH7XhxvN2habJf9hGGeGPf4KHygu2A2ym9AyxamLFtbXaPeDG2OpUnoSBQQaNzCHDQyp2hJaZhAbgxMPYdpVGkna9aCfN3sF4PhFhh0AUd9iO1LEsaKZumwmCvuyKtZhlnf3w31c1xIbAVjlPdxXqrQkI8GCvig1c0/kP8LMx6d6hV5k2aWHLNBa8pBVWjD8UgRyqwa8lt6QaDz4SMLIxzDaOsm5hatHM45OolQuA9bFabvbdx1KFG4HeLDEpzxkzFpSaCgkKnKQgjjBpi6zQDj5M25coBdisy@eJLuDoCpcM9Etep7bN17Leccc7cuoix7v8CkJSQs2@rFrM7nY@rYXoA9K3Fllb3@@7TYNJ4IXz4bT7qyliXNhSVijlC10I2FbwtmAFEvtsQUAoWRyu4ioMgNK@si4eEFYlxKb9HgPSG1o@iIbL4E69YULFW4zsccUzdEEkxA/TeSoSe1UVPWAPRsVB/@U050A/hZbV5Mb3HxvbcwYiMeij/tk501ssHFjwrkbYVXYFSdTnV45j7pkysqhrjxVJ1tHPg2Vk/Xc3LuCK0hAbW2wfCJJIlKesRaSb9/INsHGjTFNjIaFTeQbLRR//4imZJ0g0rECRWd@QN@sEYGxwselAqxyDA/p4/vITpLY8SswFNsHPjHH8IYQB2yfb@jW@Bw2eDqRdK1@O3S7QeoUi8TQ6L7vAMcGaClsenuwxFEQBbtUgUrAiUU5Nw@WFMf6hTcriCNUmdaRtgOYgjXylUZ2jWsrASp08sp@4dMdVul6jlGSOsVbQymzq/nn2XX00PTorFJkH6M0W7yE0WNiNviYU19J07UXZDw0jj8yjPqPXxACqHDham2ph6YhNYpJt3JmJXq4RHnTMlxZz/EMju84CIt8iQxC5kLNxPHOcerMJh7h7NYz54SVMw3SqcOEkhcdbuLRcZrE2TPXmFvXyFUjZtlmN8G0yFwyB@5/NVbV9b8ir3blGbglk7kJhv3kMx1D@P5T@bWrRUOdy61j0oTC9Ov@BO4ubnksb8uYNkUOp@NbQidQIlvwG3BQE3NzIjMH9eb7sD9stkC387tTMBYGS74fAGOkb4RJHkSMLzYcTVlwY2taiKVSo1YfTV26XmrgWjpthdqU5fC4csqiJSxbmrIwJ3ialmyqljCBvjWrtmVhEA79noPfdXpSpycYmjMlhtimNfVwbWyUXi9ZpQ8@qJasjdIK/JqrX7502SqtzJWs@XL9CvzUa5fmL8KvSxe3rBKUK71R2tqKG5CQSvN1WX3Lmq3VryDAwL5RsurlK/NX5y9fvnr5SvXK5St1hFNfK8Hvt7DVX1o1@AwkqEPFjdKD25eul0QmrdJFfFW6VbLi1sjTsnRz/dbdtb/9NdSnDiPqpc1BtboMeFMqLkTkCgCYRwDUQPS@dP21e3/zDuJVm5@HNktziMbd1964Tp2Dz78GcHP1VJtElzUo8jeiS9gRxnNjvl6@eLV2eb5er2/l0D5UvHgk/VPkAwSwZQHbKv3mA0T8EiH@6m8eEIW4q7eulGTvuEdX56nUa4Jq@Pnu61wGMH6TXv4tjFmaiDj2@O7q9V9er1ID2L1quTp/qVa7fPHq5dqVWv1qde7yRRrPrXP2bGwZIVVyObWwPEiLqHSL9rDDS9Vqo0HL3o9/TtZRnOWh7ItTkDYbW6MtcvjHVtG6hvcC0Vf8Ez0ubZZKo6nmz3DKYqVmqbGxNW1haL5RryVK68MPao1SJ7BL5J1VRKFh6YNaSZbLI2tNm7JaHK/L151pJRFTJuzZJUsEmQXiZPDu2@v38TzYt0GL6CaWKVjjoPmqaLIax/j1u5xj6du6NpcpH5Lynl/HuDiPgWWWHugmJU3WP4AfXbt46bJp6HbQ0Q14ohsA@ooZuZQnYdci2LUUdAKg6To2UYe3NVCOrl7lb3NoQeWkR5YhUbDqGjd6dvIvV6umCK88Z6vQUj5w7ISaSkNNpAGql2FrLa2Nh4QSjg4DCf90o6rVEeRFM6peL0DBUyftVem0FtS5FUrMAH3Dc08dfW3gDeuhGPEhCnAf8Y3ASIFoYHRhv2uOYYMEF5DWGsqgv3pNzTjjd5kG9@5Q08TBcTdEjocbLqimc9qLP10FDFXPqWkEV2EGCVTaYHdNShtoa4@aXu@tZnv34TRuvr23xH1kkaOKbmwMrS2zZJR/fc0sNcT9drXNegOvuFPEF7SAddFqDaR8hLA45Ojp7x6lLvtTahENHxENk6GFjxCgoLqkQIr5gO9UtiuqBd9wis1p8@ZE@PK/OTmFlh@ITO8IoT6@fsK3PPf9zztn42aK5WqCmx5lLl3MFeVj4Fql9uEHJY7D3pibs@bnt7Ym1BuWbKiMrgh@aTTSp@FeDkFv4iUJUzAtFpO32B3//uzkf0bX70kmG@r6CEtpOVH6@FzfhcWgBwNz0PO7UVTU5FrnrWGIhgxRTavVY7E/ua5uoOvAnFabn75WqhoG1sOzdhsezml6y3fRwREetwGb@pwZLUOpgUFBRs4@yQROkRCz/Z0mBe411xwP1l4HIxrI@s9hqOx59GCl6e23czLXd1zafdr@4zJn7KRUkNJCkolSdby23Q8GXbJ1UMhqZAIpJ7N2RnmZhYeQE5BdlWMMe2zCjhu3OJKG7dfGQvXsk3/csw8p6Ef0akbJWdYRzkdKnLyIxdkTmXp621GUDub1CJzuPl6/Gp@MHja07DrAuUfaWdpAEREP0HEcgg7YaVdFRgVyQuCO1bNRjfGazGJGuekBhoRPXB6scJnlB9IPuqqk6ZRBXnKAo4sj/1iNFgvjxy/oWsZnR9dqF/Cmx1HFYJRkLXnDAAwMZS/YsTjMx99Bm04NaBAto0pM/bWzk9O1xBCoYZrirktxfwOdpiYudVAzKj1Y2biGHcYT5lO6ePPZ8bW5C@IC1Xl4OFfdyk1aE4UtUYeWanSpgItHZEentcVrdXFxUnuA3qti0GDUXCeTzU6GVqqzZ9agpAFIhU9rE2L9ZP2zk2@Ifd7ur/eAAfGgBfCvU46EnXGp48hUDiSC/v@Wwh5khFPRfQqRINAyDQIXsPPiwEXXPNS8B@1w4FPSHB9mSW@P3alCZTrm3RaacFgBrFAGEKktjf0B6G/FPnTx5p/HmIMxZB9nmKniNmJuz0xeJkC@VF3H3uaJ1aIDAsyZgkAsPLHacw9RkGzT/b8uRud8kwSxLCbW2dM/1PDWRW3H8Rx0Y5AbjWRxPN8ilBE4/sHdCSApz3UeU7aX0A0HHYfi7Q/dvYHq7O05lAPzCtufUa@avVa7xGZYOm@Ch1BIm8P7G2Ucyyf/0LVVDRSreT3e/8CMzExWOUUxgQQwtQBJB3qymklA@b5gnqg0vT/5LNGS8Eo@e/ZDXVGh6mfHfyBgimurhYe9lrbd7dnwB7dkFp14wYhy4Mehpd1YXbmZCvr68YsKuSN5eMzscYYh/2GCXovVBhQ5@a6aPcKyhk@iO4YVB@yjY8SuYpA1gm56BfWqfhklUP2KRmYJ@Ix/r5r34jtvLP1Xr/76xe9/qZtCWTMunD37dxRcc@XLr9fKNfSU/PGLe6YRXTp9af6iGKT/9eHZF3@PNL9H43upXJ1fffGn@px2sXxRww/luvHrmmnM/vjnObNWzfyYo2T0fcdBjoSekyTDayC/iTpoce6NKA8AyTg86EeybFwjasE/9XY9Ei6UIAmvlLrmgSD/AUPhRHB@lAULJ4/MgkXJV9feuM@3kIpcNsw96iw/@rshIUbxVjQyoxenBgaXd@1Zdo5H9@KubbIL5X4ikc9ISh85/OJOb2UVA7BLxNvUrefsbnJog3QNUtnSarg8ccEPsWQ2Niua3bbI0AYCg26fjak/yskXBZprMDODcpPvn0dQeAzTaWnaL@85@y5eX9bQ6vW52mXtlzOvlMXN1uT7IO6svxXudYXDVAatUGhGpGJgeqiWHYAyLEeit01Je3YcuhcEKN7wnUcDF0TP4iadBnUe293eTqTRuT1e7smdojbmFuT39vli9SgjabLU2h2GM2gHMp13rZoH7r6IGsvvkexG5JmQrLzS80IRcArLXhTQHYqeqxBmcdwcXHnxjZDQFRckLnpmBRWi9AVQ28RRU7KhW7CGdB1yt9J15QpPVAL3ybtNFMip@96bQH6@4V3UjQ/q0EuVLtDErHFQTJMIqVHkRBDRjzxS9zBlLJGxKnxQHQodpRsXqTLnzw6BH6M8dZ2ew/55u/Y@XxXMNyuEtsgnnGzkTeGQLQdp1w4iJ226RRRzx9A1NBSJHiOsGYBEXDJA5PIaeDtwgpgRmEpBb@C3STvHCEGxTg8CPsukRkTYsoHLL67hwJS@2@nAitpCP1bf3adLI2BoMQS@mJsxYQgFHL4nbvfmeVjGb7FrL2cq3YZRoc7QNagal5wGtLwOXMDmNWYK0HylD73FtIY9P2wPwiBxyBsAmbEqXXrQ0XAT5JtjJi8mtUmxIgb349nirft378jBC1J3g@UDe/2taMQUYLz1rPCft2/D@HV2nCkhrt/Mgxhf93guYK@vr@ehF99Uu@65/f600G6s5KF2g6QoySO/150OksLouef2xPX0jsbaBvaXw1IR/SeO5vCJhypr4CQMephHtbe3B@SiMbVDEHqtQegEUzDr22s3Vm/GWfIjuULutQh@4DFDdsbDdfGog4AVBj27CogokUWxuJMbnQKglMWHzALnASp2hEWIkosFTtHzwCSxMx5RXt7PA5SyPo4HyokhzwMUNh2TgFKR8wHlDcA4ktJOoBhmDtCIP1eIsZcj1sOlw0UzKo09/OWwdZ0ojOl6kCgYDIz9wL/QNC/Gcp2K2ZhnHt/IiunxoTmbLI0uplMmrN6TKazf4yyV5G0rcokQVFqlKBtzPDvydAPCixc@fo@7VVRkrwnLpTSyjZJuRQ9Y@8q1hCr@O6hfWxuwAdkaVhsN2MXIONOy1N8wSQnaOX77@cqdZZCU4obmfGcm0q0Ow8QdgBOCbmOXmciXFWTatezdgPfWbw@jLdnzhjglql1qNPRMdsqj0wr@T4lcPhIZ0WRWl@dm2Uj3xuTMLM/TQWoiG4SJ/SNn4OLbHYuwTKOGBi@Bx7C6SIlk0ObEeDby7h@gAxV5NEp7od@OK1obRZlmnuc1PrZPxX5qYlN4MKVjWFUTSXpq1Q95eA@K4GIc@7Rg65OAiYssp0pdIt28nv7uYKbIsyu6I806yMnCmMiZd3b0dU2O/He1Cs2a448PprievFoYxViQQnOatg/GMGo1P5dW9nJQ8tI/mChF8KI1bD22lGB2QMqZUtJHhYN1H7Vne9rE7WR9pWRfnBXBspWlQtiKcssrujommo1Wa/VO22SN6JYfW1020@HNUXEbczSAaOdMErLC5dql2tmzf6sV9f4m6fcv0/1qovvT9p@3F1MSILq26HwUEJfipkhQLUjjo@GGZdqpb@dIf@JzmQMSN6txfL50W4QNX8@/vS1OqMmL8iuqixZ/5tjnyuUWdACY9G6MlAje5SMJEt3Ydg8fOph5fsqODOtLH3IO3YbFYj/Vl1UPN9sO9olNY1ny4VYH8cL4uPh@cizL27L7vruz4/igO3NwBqk5FikTFqk4FtmxE6Z7NEDDqvH0qwrALBtrzgEn2nmj26EP6gkylqCjkXUn5C@i9BPS58asJ42@3@s7fvhYA6KBDsS9iJksq25xNTshe2YUGyGZM3wbzw6dgybljRX3v7ieGvVBb/AeYShGKeRPvmM1zVzAmGehsp18K1U3Ma5AE98u34btzKGTyPdpCN1OKHumRcbmg7OjL0HxgCoRAdXrSkg55HobhFCFgqH5o1JpJjdNdOouo8tnT//IWm2RGiu1XVZnWemVXcxecWJgmmnRGV1knVZwKr5/OnHYE8@MnWhgcu@1o7upkfQKfTGqYJ693pfX/gZnb@YC@08@VcqviyPaTl6OZEFoi9RucyMe4cToosm7fvb0DzgpXfOCuzXFig06FENj5fk9JZl97vGZ6kQtJ0A8m5HXUTD0u7brjSiVDU4LOiDnaFqMv2uGzW2gpfOo6T2iBxgoACzOF7ptu34Q3u89dLxmSL@Vg/RHzSlcImbiNDpk/QniCYhvBHLarHZdRG3JFF2obu06dKqN9okeJd5x/L6PokGjahphpxFiaLvC2p0ZNpPu0OyfVVLrUjGyaVB8MZaLkuTXTPwNU4F2ebgbVEBbymEC64GGW3bKAicujQGE6Oy1iFkuTMopj2klbDyl4MjkV3Q8gdPLOhmZRXBEAmmZ4wizumraEjxeLMHnUgJTRhOtMuLEX6assKJ7D9kGja2IgDi1NcUoG8nCbOuUflbT9/B3jIgGTxdLO/hpDz/tpZGrExlFivUkyVrOjuuRXZny7SM53LzOv5LX@@gtIkBIiXJLjBIikk@uuekxyo4MG0oSCJQlevQqB0MmXzmffqLSGArOE76xgSG6UBC9TQAtx6VRZ0MtNrZILWGaWGXkTItt8OiN6saDTkAsvFYhuqaQdYLEEKBY24XNMhI57PWpt/h9sYRfM9yIri3CIabny0AhW@EualUkPwKKx@MvpoOcK@QWY3fjaU6WfbUpI4GXGTOBgl7MBonbN5Q4IhIdrOjRx/yQN3YKcdzAilUhIVDjI/lYOio35OXcv7Azk38FgsgNaPE9DDuZgJv0/QapXOBx6sX0DYV0BH5cEXcVUjMYBL@oF1z1AAWXahPubECwxx@LrG/6uNsZNHgv0ySJcx7BgCRPx9yqoMRIhYKsBrQ7WzOLu5tquqyrRk4yTuMp2bWZ8XkwyZ0GtFQcY9gH/bEvrgN6ccpPYCRhXrBCNDM5rabRR6eDj6muxVHVFJA7iQDTXD0RacsAXARwCcSMqAlzYhsFV0akqPmKHlnLpyaliheokdMhNU2n6d4xnLIL8cQTOWWixfraOQkHCP6FxqTOltnpoE8ajXF3hyjDtTiON2XU/rQTSh556OOAsggT2bWTO6O84dN1adQ5fcRhmBOQiAVajRMoGI8WsYop0v3ULPy2qG9OmpWyN/GdFQh2slSZYuAZv0jKTovJ9JJtEnsoXEfm7v3UXu8c19AUtDTFMCcWw2pORGnGgzE34FXpS4osuXcNRElvYn1DZuAj/aGhocXwc2KZnHyhU8WpRjuqoT/CDdXBrtveHZGNIozvn80zY/JlLE//mTUPqicS1AtV4pPPDAfvoMI3Ju/68LsKN50CFdtt2x7uPuhaM4wdYqXKltdYoZakdraC86ZK92GFnABxrn5J3DB5T2kstSmmK6wsfM2LgI4f4@0/Zu539jHloVwZABHDKe@UtR13H0Sz1OhIpybzCx5NuR32ejGzl4XVMO0SLL506Z5CA6UIXZXNqTEzRRQdjW7RSgHI5A5RK9Q0ZYMc5t8qrGZOTwEne9NGLVIYtsi3WH7LAyZOdvJPvdKMFhsLI3DS4ya2aFlM6MiY@l@TB9VB@b99SKab/4sZymND@aOazmRPlbTisvkna4zrDacbIUlmG@X6@VxsZUHe@ERfk@mdngh719GxfM8HgPxYWiFN8imHCmS2TL6bhtpsuMILTUevKbQuPAHO2@dhbbHPw48F@SLGdzo6qEs9p3d0tzt7GWLql0M@Fcix68njerQKnkb2wjyQBYZB6kBKlinXtaercX@PvhSkY46f4kSW@Wa501mhzVN7EqnZ1@Tp71TrPMXfCR@UdgF@fG4gtkXtqadiFs91cjoJCi7dUTBlB5YsptKxJbAMvakvioT0lNOjqRdgz@cdqMApVfCZqGaNBzaNwElc8pC444F6HOSIJTscCWpQifiG@nyipG50Z@@dhOakF6wf8QXudOrAzVmJhcQOMQj3X@CLYdDt3CZZw8UpO9cwTf5bQGTlGD1RrlhxxOvkxbEcLDc/foE4Q5N41XKqfg7edUy@Vy1fxKAhUcHMqyqu8prQNCkphlU3@QJh/H3yHV4/NR6RbGs54gDbOo8iO93qhi/vOSDEfGawJuFSlJJHrrjvZTFG4xczExrA3svtsryXi3mDpw6mKm40x50FCTwYOqaE9C29pOnjDgWTs0gG4lHAC0YGYUia8pytCLa/I93A79s7FqiseAkCO/@6YSAdvQOLQ2jwkaqCudsy9aiAvIa@DuzaFVt1heOwjAQUuhPf7bXD1l1RXYMKaKwXV08MWntuWErJhJVUh3hI79oPnWqkKrJ/vtL1nOPdnLd5ouO25@Y4dmBzNS1MuNOLbmKm8K7j7YS7ETroGY83Pqie9mLvoHfcfTYO03Vl8V0Q58eU3dPDiXjXDRp38@XRE4dOeKO1DATwNUN@xpEPfkI/CMeVXsdJ4JnphVKiiU02RftN0MWT@szT3zGjF3rHcmCBVp@Nr7lEzhQkGPAFJ7q6hRO0VszlSeklgtFik3C7N@jzxXd06miJbLqAcwcfsubrBgkA8RGXrz24/0DMwQPOudFx7G50nBNPtkY6aLK28CHdDL1DYZMopdFtIm2ml9dXk@5Zzxjoyfigjq/JMaSkYOZsD4rEeTuKJZkQKAnajiycpXqevC9m9zlgkgTqEYO8NO9LcLMJHDlSCwgxy1Pg5WeAwrcq5il2nctnVxDIuawqIFnp3Rffi84qcIbi0UzTwuT4FygyyRFSiRLdBIoX6m2LaHMOHqX1wg21HQyXEWfMcuEpT2QK4nJlUwyazP/2KRJI3DKfNZuM41iAFgsQteUxBpZpWDF6qnFkCPmU0SfxVEb/xClcclyWnPDtwGnmb1VkZA4ya476gsE/mf1cdSbPag2ch5HpMqgqx/zZjh2VdVms6LhNItAusNESrPKYxnLttPkPJzTXLgMVtBQl8nMApvec@XtIBCdjqCbNaHUgSHCKcCzcRUTPEojgU0uUSLSSl9g15XG3SiFzWW@7oYiiw43UGx75jqALzFhLCZSRBgM/CrkWcAS7rr6jATu//lZZRPElC5UNQifQVuxul@LxVugS8xt4AawSJXQDxPCOjTojZyJ5B3mU39HHlYEf9OTig1Hq2/agGy7DZ13XasC54l9No4QGKSTeoYAejhJU9wZxCeTBLOPj4AG0RVnqFgzEDgeawohlnkbupV9Z8l3U7dwEnsgXIvf2LTXEkX/kI2SE3QRxpbzyyPdOliszqfkMVyLAz6aHmlOSbxxJly0wrSSYzFHZJpfDYl4SLJkal7tOuNvDYye95zn6uA2dxLa599jtNHfzBSUsSr/4xS9gSu2ByGTl3d6mZdQJYoty8U4wZ5Rkau0qbn@hkNgER4OyLq68T@9vH1PwFsj1251x@hDtNHdpl5nTuMpImMC9qDUiafQSe/eKbiEK08hW2sfulpnMhTvXFEeMl1EMi8RT4r4K0mm9nrbKtxZoxgL8Xlqo4G@zPCOc3hybgynx1zasRVoLtYyuto1ZYbRdX3P38ELO/gDzeLPJEkThQ1A6Qptzx6RdqW9ShC2pBtM6IqNNz7b0Rd3imx0wjHzd3nbwIgw8ijsYx6xNe78ZNveDptPcbbYLHAwj3ZLr4M6c9@6RMsnxy2IHH93jmdoY8AXU3mMFdwa40oPdxEpCrUqcM2BegvhOUGKhzGxTrbHRS6nQpGZJFT1W91FK8plF@lYre18YTOLRqLw43Q/GTQ@uo5p00goiyELoBMYw6ahz0S2TncfwB9Pa6zlGaHs/8iH3rV2rP4Xd2lDrmJlKU1woR8dAPRhVHur0JiGt4BWwFY0o5nACvgrH81SHw@Jbg@5DGczvy0mpHfSiXB8JUSiuvaHQq@9Edo8h7zNzLuhWP2NN1XGM7WaoWChvIjet4LYI1AeITp40cvKkUWJLU1QTPfM1xyyonyNayc8a/nH82Od5/gahtPN98lmIFj50uFlo@ZUlfWrxGo5jmNxDehwYVebQlV1uc685aA7awUQhFsU1U8ghhTCXAgBVUsYds6/cvHsfIYunLt3ot7BUegUd4SX53Fly86DETF/TlTTu4kXTqopG/Ifaq1HUp6eH2quvSOs8ucmjtPlW5rrCO/1q9csL0If4/jbZkLFXIR3QiO8RzLuuzdzYq0SO6MZA1HkCSzOm3Kd74/XXFl595Te/@c3V5pIuejmoxHTzeUT9cZMtJeUK47tyFQlZWWZtV4Zf6v7IRTK@X0@Zh18pg8LNL7c9XTpH6wYu66RSmDkymPeQ4wzJhes1XhQB4OSJzHW@XomC1xZEqNqSPkpsV2/j@rs24SCTvNrQWYIWa2mKEfH3FitolJqCkm7sOuLKCZZdbkcGLtldDF1@jKUUwCLg2e3ICnxDdlEVuVqIpGbHdIaWcAqTJdxO/ntB5PEKnTiEddN3OXNOgKe/S@hkpCNOGWOK@pJchFAWeNNki@drxa34diNazuDrMEp8cvS1kstJjLxGOcwqfM5sKA9NYgbxAApYFDYW39HznF3HRoCgWXAcbo/odG1KNcwwLFS5jz@iszfDEBGxmCIujmdFucRxYwemeSDuxUqFiWmRTS1mIWxASzagenMcmAsS6tnxV1OHn3XsnG2s/JzwHRibg9OmxFKcI4y@yG06nsRmoWUIzWqr3WxN0VhLeBQunD37d4xzr@LtO5vo4vhleRHPgm0x5x5imsTNEp3tyF4YrYptCoEmJLQygHwHGga8Hh3bBaGOqJezkwxSatKeUpWzviB1RsOQSkLqpXKCuLb6DnRvWF/gJGzfNzjy/HvTGDqUse77kQgH/940I0UnB17iZBmJMM5u5peVjEYFprGJFrAcyyfDLrB/FhjCpEKlaGMF3ZvQsCFqmudCIFLIU@OX5x@pWKOUfF5mWclhdfxRBtAUirlwPEB8R28Ogl22m7Wb7S6fPTndvZ/Ai2gBXck1bEv3HvZFVPzY8px7IkoVTpSsaq1l6E924XntIqeRwORrmHGVTzRzfX6YpwT@luIIM8mrOFEJBqadwwqKDVb@xIM5SXGPwJMjL7Tg/5Rxp0MAGvZufN4Dz0qBzMlZkirGSvpYCMchOh@OEpBZMuqKkmG@j2FKuDmtoDL@UvokCs/saP8lmOjcXKIM9dTDljtmU1jl1VHDjV561KIUvx68lIPxsw/WhJue/qpjNg2lQCQ4fjgti8cBhb3t/8/vY/idZM9PllRTc/0dO5hIS9Rgnv2QGLSM/u072yN5Lmz3pk2wQUETWP9qeZ4VZNZ17F6@g52fVH98utN8mwzox1GCobj5cXfAMcLRuvZSONf/ujjzAXWv9f6U8uOqRA/vxNSLYPIx15Rgx1IgakWaG/CA7733H3ELqR7L9iKM3EDG5EdbMNSfOT0Wd51yMImswF9XoCYnykr3iHTF6cnEDWcRkgDZwnk71G5PK7iHyngr2@DEtj9OwkX20NQET5CA8/ykSsj0Cby9yABgIHK/IgoZaMcU@xFhyzStqHtiW5IDyOJrGlJvRtlHCa2fWzxncwrOXJ3UcwnlPGBgUCQUUXtSJUO@Lyqf6rEgy@h2WDS31CzBU0kYXjjSCaqkED46rbxSVmAu5suPSPhnDwso1wS7iTVbzSBagdfFde98O4E04Ik7HRZL5XK5NG6VYIhoWGmdnfwrbs7lbcmBWQnEuVcil1GLDLJYgJ6aSyAvN/WS/J7Y6uPd6S0QMIGcEv/EaGLsvEQA5@nZybcvTvVFJW8xFaMEt8pt9osK8GBocLyjtDjBRj0OgqSHtFUfvTgtMOu@5niR6W6iQud2KOAOEwqii8CF@q/ncnJVDfGMdZQ65y3cKEoToDgbTlgCI/8c8RKYiE/RRHRv@jCNComyaseK9JCo/Hk2Sp2w2xJ5EIcwwY9ON0U6Nbz@G7/RLeBmBaiPF6pxzqiUkGcnj5vkfhxMm8gOxxIPXPh4AG9aqYos5iqgzAiLl01vmouZ2KLw7vrtYe3CBViivsbOsae7zIb4HXX3k09x8Xo@Qj9vmRLR0st6KlMkRobpwMpEBozPQloMeU6I19gIFVmMC5yPtoBZ7YKHyP328zsraAnE45jalerZs38zxXPoUj557tr@w07vwDvfYADQV8pYdfnNO2UJok4nSmMHA50L/9MGZAwHDaXEEENCpF7Y5JSYODoLC7CYLC3p5OrxZx6mMVSvJ6ku5MdC33ekjz/6MMxu23tu93EDiDh35aL2tue2gT6lJfL/X6hA6SU9J0QIYaGDFBNSpBhv4raquY65j97w1jFN3R3Xc4Lmfd/da95EFwJM8AqrzvVurz3FJWXx9Tlvry@/ttqIvscvImfJJDJ6XyaDwUN3RKukpyrhBxTpO1Bxl/KnBH2Zii9RKMAgXLuLrhzqrUAFuLBzvvOYXKYTiwZluaPczbiWJ6HFQO6trr99535hVxeyHVvK9iKJM4zi0hRgpsY6AS8RC4sDTUkukXsj4WBWWEKIQhlGwBqTxJGom@GtRF3Ky0cfjr4uL8Kk0XRZEbuI@gIsmOnpIpRbqQfV@Mu99dtmOTWV5ExS5hOeYx19ySoV3WpfFgcxgBCGUGcQRjUGkUXkLJjgL06JaPghQxiipxbZKjKSDCPBtPVBC5Nz4Mzj/Hk7@0236Tv9bnPbPbyDv@5NKVEVqwhW5YubN4Yjw7z26/KFzc3/9ssPt8StgJubVc5BAwKi7eCVMs6Oc0ieTtF5VoD8sxkDvEeH@NDvX8H/m5sqJNV3GybzJtp8XtV@FdWOwtXkRlGNkxO3Z5druSky8Wdnn5wo/pE3Ui9OZbJAhCLujXzxp7qINd23fRcdXgIyuGwPPNJkA8pdZmlBzw/hF/sVcE6oPTts70LxlrONfjDwML1bN6jBjZ39LeyzgbRAHvj8xSliQKmBP4@KmKafTGwrOhbgQLvhgPRquh0tk0@AzgQRMdzgEmgO1Y@eZQ9bsB5NU/Q1SdeFFa24qoTPnUj3GBmI32w0a1um0m9@Vt/Cs0t/QkrbhGcAfuG0Q0QPZRczk9jTCAcV@a7BJiUKqdAaWqIoOfbdcALSBTGdRQO@YQJ8zOpFNaiEEgEGJTZkXMJG7Oy2tTUzPvX@jV77uk0XRei7YdhvVCoHBwflg7mgvdvrgdgACYvehgH@eo9aLttBX58MlS8pQLgV@EZ3blF8aYVfLL95O6igzfNimdzQJgCE4nfw4jlUVWZgGNBVZ0bKjTd546BeTTKjBpsoZNIa2FvNsKJQFhxTAbBG@U9/DqgESIFcTwUNNe2xzdicheqjCB6ndsXLlITxxEYutWXsgQA7AT2bMEKWJs6bMUTYRXwt3zdmmRqkBQSZTPDo/YhHqUI55sAkj0Lzfg8vQaGcj8zZs5TOvg8YgTzy3UPceuPlS3kMjM@BjZ0uZzDYQJdEx78HGrH8zM@RpCtQ6nYn4C9QBD7jxdtbfH0JAhI/s6mGUYbjxZRdUEpEjE3cn6htqohtKFn5qISCE5R4BaHyI81H1T4uwmBmtVv81k6CUbswq@FVw/GdT7dviBy2C2GHEtsRfrc77/n19lxpKarPvdYy9eE5w1gI/WT93kFd1Ge2A6UHJl3QaPBgvizVViZS7dZkqt2agmp3fyLV7v5Eqq3YfXkvEca8iW94mQ1dpuT4lEOSXbPCXl96kvJMWJDlVeDiGcDPubDhBl8fV9Wi6x7yrqUSxI@PhlK3SUWkj2xveQXGgVDIXgAjJmxc4GYCS@6nyKOYE61caAcqDhrMCUQmyfKS4JL@rcT0qGDIO/yA/tGzTORK7ezpH1HLyavFlywXVjdo2kVTSJkpyoxQGT@mtSnu0ks4Tr08uCxRxfIgnPSxqSbO12YbVIPmbsenLziRm7hfo09uJ2gG7gcOfaHwT6yCT7EIVcAP8gGXELNg3MipFkNB3BvxYIsnhuEzn//4RUWaLWgkTQtRpisP@ao/fir@yiAb7hAaXPHPM1DKv8Egl4iE8p7xiJexj/AHO6KczKo50AHC069WEt1LgtATYkG33I6lx1JBtyLTvZxCJto/RIGlvPwi6lndguiTGrTAgySwJ/oLZzR1e4BDiEW4OlEvpZ4rPJSyncYtDHXRK4O6RU5tut/mrebntDk26VYH/Pgttjk29keNPIqYOadx2SnqxMl3w3QMhZr1iw4/jr7c3hM5c9CXLRd4Bh0x@JT8RHQZ@hW1bw4NPdwlj0/T8dpaNI5sdYiY7VOFA2mbQrMlZ0gk0ZXJmlMrIjlRHB7rlsGnOQqls1xR1DscsJBCQ6gP1Ap2zI86xmd4I3Ijx4KTOFKKAZFpVU7F2SxOQk6ICTaBUyXY87Fq3MQ5WBVVczkxquaFc/OuFM45uJyXc1@cJhg3B3IGEyGsiG1F96GPUePmUAcFikYXndgV@cMUWKiEnSVdZeDP/toMLFq@AGSXoz5Fh4mTKdZpGk7Ggnkx7bHPnRDBFvK8pRSPt1TXl9dX1cCaxNIqXALE8CXSu/3VcjBOyL84Re7F/LyLeWdjSN8oPoJZi@IkFio0vs/5@peEV7wpoijiLStsQOOQ5f8QFryZOa3@fwA "APL (Dyalog Unicode) – Try It Online")
Explanation:
`(`…`).Render` Render the following HTML element:
`⎕NEW _.Table (`…`)` a new Table with the following parameters:
`(`…`) ⍬ 1` the following content, no special styling, 1 header row:
`⎕⍴0` evaluated input reshapes zero (i.e. an m-row, n-column matrix of zeros)
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes
```
lambda m,n:'<table><tr>'+'<th>A'*n+('<tr>'+'<td>A'*n)*~-m
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFXJ89K3aYkMSkn1c6mpMhOXRvIy7BzVNfK09ZQh4ukgEU0tep0c/8XFGXmlSikaRjpGGv@BwA "Python 2 – Try It Online") Assumes `m` isn't zero.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 31 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
<ŗ>
table⁸o╶[tr⁸⁶{¹1≡╵dh@t×⁸;}]
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JTNDJXUwMTU3JTNFJTBBdGFibGUldTIwNzgldUZGNEYldTI1NzYldUZGM0J0ciV1MjA3OCV1MjA3NiV1RkY1QiVCOSV1RkYxMSV1MjI2MSV1MjU3NWRoJXVGRjIwdCVENyV1MjA3OCV1RkYxQiV1RkY1RCV1RkYzRA__,i=NCUwQTM_,v=2) or
[Try it visualized!](https://dzaima.github.io/Canvas/?u=JTNDJXUwMTU3JTNFJTBBdGFibGUldTIwNzgldUZGNEYldTI1NzYldUZGM0J0ciV1MjA3OCV1MjA3NiV1RkY1QiVCOSV1RkYxMSV1MjI2MSV1MjU3NWRoJXVGRjIwdCVENyV1MjA3OCV1RkYxQiV1RkY1RCV1RkYzRCV1RkY1MCUyOHQlM0QlMjQlMjglMjJ0YWJsZSUyMiUyOSU1QjElNUQlMjklM0Z0LnJlbW92ZSUyOCUyOSUzQTAlM0JidXR0b25QYW5lbC5pbm5lckhUTUwrJTNEb3V0cHV0JXVGRjAzJXUyNTEw,i=NiUwQTEw,v=2)
After fixing 2 bugs (ಠ\_ಠ) in the interpreter, [30 bytes](https://dzaima.github.io/Canvas/?u=JTNDJXUwMTU3JTNFJTBBdGFibGUldTIwNzgldUZGNEYldTI1NzYldUZGM0J0ciV1MjA3OCV1MjA3NiV1RkY1QiVCOSV1MjU3NyV1MjAzQ2RoJXVGRjIwdCVENyV1MjA3OCV1RkYxQiV1RkY1RCV1RkYzRA__,i=NCUwQTM_,v=2) works too
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 30 bytes
```
’<…È>’sF"<tr>"„hdNĀè"<tÿ>A"I×J
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UcNMm0cNyw532AFZxW5KNiVFdkqPGuZlpPgdaTi8Asg/vN/OUcnz8HSv//@NuIwB "05AB1E – Try It Online")
**Explanation**
```
’<…È>’ # push "<table>"
sF # no-of-rows times do:
"<tr>" # push "<tr>"
„hd # push "hd"
NĀ # push the iteration counter truthified
è # index into the 2-char string with this
"<tÿ>A" # insert the result into the string "<tÿ>A" instead of ÿ
I× # repeat this string no-of-columns times
J # join the stack to a single string
```
[Answer]
# JavaScript, 65 bytes
```
f=(m,n)=>m?f(--m,n)+'<tr>'+`<t${m?'d':'h'}>x`.repeat(n):'<table>'
document.write(f(4,3));
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 28 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
üÉ$♠═?S┼╪├8°‼←sí☼←T≡┴╜ô‼\↑0ⁿ
```
[Run and debug it](https://staxlang.xyz/#p=81902406cd3f53c5d8c338f8131b73a10f1b54f0c1bd93135c1830fc&i=2+3&a=1)
Unpacked, ungolfed, and commented, it looks like this.
```
"<table>"P print "table"
"<th>A"* "<th>A" repeated specified number of times
,D repeat the rest of the program specified number of times
"<tr>"p print "<tr>" with no newline
Q print top of stack without popping
.hd|t replace "h" with "d"
```
[Run this one](https://staxlang.xyz/#c=%22%3Ctable%3E%22P%09print+%22table%22%0A%22%3Cth%3EA%22*++%09%22%3Cth%3EA%22+repeated+specified+number+of+times%0A,D++++++++%09repeat+the+rest+of+the+program+specified+number+of+times%0A++%22%3Ctr%3E%22p+%09print+%22%3Ctr%3E%22+with+no+newline%0A++Q+++++++%09print+top+of+stack+without+popping%0A++.hd%7Ct+++%09replace+%22h%22+with+%22d%22&i=2+3&a=1)
[Answer]
# Java 10, ~~139~~ ~~133~~ 102 bytes
```
m->n->{var r="<table>";for(int j=0,i;j++<m;)for(r+="<tr>",i=n;i-->0;r+=j<2?"<th>A":"<td>B");return r;}
```
[Try it online.](https://tio.run/##jY@xasMwEIb3PMWhycKWSFPoUNkK6VDo0Clj6aDYcipVlo18NoTgZ3fl1mRN4UA//30H@qwaFbPV91w61ffwroy/bgB6VGhKsHHLBzSO14Mv0bSev64hf/Oozzpk/4OOGIw/Swk1FDA3THomr6MKEAqSozo5LYmo25AYj2CLbWaETdO8EXQpQ7pQQZLMFF4YxuRWxM7mu33sv@SBPMe3ki@EiqBxCB6CmGYRTeJ0w8lFmdVpbE0FTfRM/v708QmKLs4Ax0uPuuHtgLyLK3Q@qbnqOndJdnQNj5SKe/ATvV3dhx/oLfzC02aafwA)
**Explanation:**
```
n->m->{ // Method with two integer parameters and String return-type
var r="<table>"; // Result-String, starting at "<table>"
for(int j=0,i;j++<m;) // Loop `j` over the rows in the range [0, `m`)
for(r+="<tr>", // Append "<tr>" to the result
i=n;i-->0; // Inner loop `i` over the columns in the range [`n`, 0)
r+=j<2? // If `j` is 1 (first iteration):
"<th>A" // Append "<th>A" to the result
: // Else:
"<td>B"); // Append "<td>B" to the result
return r;} // Return the result
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~42~~ 38 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
-4 thanks to ngn.
Full program. Prompts stdin for the two-element list [m,n] and prints unclosed tags to stdout.
```
'<table>',∊'<tr>',⍤1{'d'}@3⍀⎕⍴⊂'<th>A'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@6TUliUk6qnbrOo44uIKcIxOpdYlitnqJe62D8qLfhUd/UR71bHnU1AWUz7BzVQfr@KwBBGpexggkXhGWkYAQA "APL (Dyalog Unicode) – Try It Online")
`⊂'<th>A'` enclose this string to treat it as a whole
`⎕⍴` prompt for dimensions and cyclically **r**eshape the single cell to a matrix of that size
`…⍀` cumulatively insert the following function between each vertical pair of cells:
`{'d'}@3` ignore upper cell; place `d` at 3rd position in bottom cell
`'<tr>',⍤1` prepend this string each row
`∊` **ϵ**nlist (flatten)
`'<table>',` prepend this string
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~107~~ ~~99~~ ~~98~~ 97 bytes
```
i;f(x,y){char s[]="<th>A";for(puts("<table><tr>");x--;s[2]=96+puts("<tr>"))for(i=y;i--;)puts(s);}
```
[Try it online!](https://tio.run/##RY3NCsIwEITvfYrQU1Yb0AqCbBvwOUoOMfQnoKkkqbSUPntMA@KcZuabZRXrlQpBY0fnYoFVDdIS14g6r/zA7zl2o6XvyTsaC/l4trzylueAM2PomlLUt@vxx3cA@4GuF9RxAIk4wC1o48lLakN3I22vCpJ@HaL/NALImpGojko/aprKs4Din0oBgGljWz9ZQ06YbSGU4fIF "C (gcc) – Try It Online")
-8 bytes thanks to potato
-2 bytes thanks to ceilingcat
The `s` array has to be declared as an array not a pointer otherwise it won't be editable (we set the first h to a d). Most browsers don't even care if your closing tag is correct, so we just close all tags with `</t>`.
[Answer]
# [R](https://www.r-project.org/), 73 bytes
```
function(n,m)cat("<table><tr>","<th>A"<m,c("<tr>","<td>A"<m)<n-1)
"<"=rep
```
[Try it online!](https://tio.run/##K/qfZqP7P600L7kkMz9PI08nVzM5sURDyaYkMSkn1c6mpMhOSQfIy7BzVLLJ1UkGyUCFUsBCmjZ5uoaaXEo2SrZFqQX/0zSMdIw1/wMA "R – Try It Online")
Saved 7 bytes with a dirty hack - replace "rep" by "<".
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~72~~ 68 bytes
```
Function F($m,$n){'<table><tr>'+'<th>A'*$n+('<tr>'+'<td>A'*$n)*--$m}
```
[Try it online!](https://tio.run/##rVJLCsIwEF0npwglkH7sws9C7Afc9AQeQG0HFZq0thGFkrPXxKJWpKDQRV5mhsy8l7yUxRWq@gh57qdFBW1yEak8FYJsoJa4QRhRHs0CQkU0D0wGtxJSCRmJCAvlbp9DHMpKr2O87oMpZSZ4AtPNUg/VjQmhXE8MMLIMzUkcCI9ow9WECL0LtdpKy7O74z6cyYvVwZ2i6d@KRqVfPOhnv9J/vsVwNp7Gnm3L4A/XBuHLzkEY5xIIq/dfTGzKJ1Q4TV8781hnrEuFZ7NXKetKjuv7lKvWELd3 "PowerShell Core – Try It Online")
Here are my test cases and expected outputs (C.f., TIO)
* m=2; n=3 `<table><tr><th>A<th>A<th>A<tr><td>A<td>A<td>A`
* m=1; n=3 `<table><tr><th>A<th>A<th>A`
* m=4; n=2 `<table><tr><th>A<th>A<tr><td>A<td>A<tr><td>A<td>A<tr><td>A<td>A`
* m=2; n=8 `<table><tr><th>A<th>A<th>A<th>A<th>A<th>A<th>A<th>A<tr><td>A<td>A<td>A<td>A<td>A<td>A<td>A<td>A`
Thanks, @[mazzy](https://codegolf.stackexchange.com/users/80745/mazzy), for the -4 bytes!
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~24 23.5 22~~ 21.5 bytes
```
;~"able"::"<t"$">".`,_:@"r"^_:@?$"d" "h"
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWNzWs65QSgSJKVlZKNiVKKkp2SnoJOvFWDkpFSnFAyl5FKUVJQSlDCaIeqm1ltJKFko6SqVIsVAAA)
Takes arguments in the order `cols rows`. Outputs something like this (for `8 5`):
```
<table><tr><th>0<th>0<th>0<th>0<th>0<th>0<th>0<th>0
<tr><td>1<td>1<td>1<td>1<td>1<td>1<td>1<td>1
<tr><td>2<td>2<td>2<td>2<td>2<td>2<td>2<td>2
<tr><td>3<td>3<td>3<td>3<td>3<td>3<td>3<td>3
<tr><td>4<td>4<td>4<td>4<td>4<td>4<td>4<td>4
```
## Explanation
```
;~ Define function f(str)
"able" and call it with str = "able":
: join
: join
"<t" "<t"
$ str
">" ">"
. Map
`, 0...
_ number of rows
: join
@ f
"r" "r"
^ repeat
_ number of columns
: join
@ f
? if
$ row index is positive
"d" then "d"
"h" else "h"
row index
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~109~~ ~~107~~ 103 bytes
```
n!i="<t"++n++'>':i++"</t"++n++">"
r#c="able"!("r"!([1..c]*>"h"!"H")++([2..r]*>("r"!([1..c]*>"d"!"A"))))
```
So many parentheses… Thanks to @nimi for two bytes (and a loss of genericity)!
[Try it online!](https://tio.run/##bY@xDoJADIZ3n@IoA5wXMGhcDJxhY3BzNA6nnHIRDnLUwafHosZg4tI0zde/XyvV33RdD257ziBFdaq1TNFJECI8JHF8Ps4lzStZpAuqwIUA6j7AMo4dASH8WSllTmA5XeGf9nUFZlHEkmTNTg/UPbu0jinWo1PmWiEzTVfrRltUaFo7WM@MenTCChHIYGPeSe8BUJjz6YExGLwQHJWvSgUeFKPFxPcHKAnISY7zoVHGZt0d9@h2loUrf8mHJw "Haskell – Try It Online")
Without end tags the straight implementation wins at 87 bytes ([Try it online](https://tio.run/##y0gszk7Nyfn/v8g@2VbJpiQxKSfVzqakyE5JW1sj2lBPLzlWyw4onmHnoaQJEjLS0ysCCmkoYVGUYueopKkJVKZkow8xSel/bmJmnq1CQWlJcEmRT56ChrG9keZ/AA "Haskell – Try It Online")):
```
r?c="<table><tr>"++([1..c]*>"<th>H")++([2..r]*>("<tr>"++([1..c]*>"<td>A")))++"</table>"
```
[Answer]
# APL+WIN, ~~68 63~~ 56 bytes
12 bytes in total saved thanks to Adám
Prompts for number of rows followed by number of columns and outputs non-closure option:
```
t←⊂'<tr>'⋄'<table>'t(n⍴⊂'<th>A'),,t,((⎕-1),n←⎕)⍴⊂'<td>A'
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~56~~ 54 bytes
```
(.+) (.+)
<table>$1*$(<tr>$2*$(<td>@
T`\d`\h`^.*?r.*?r
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0NPW1MBRHDZlCQm5aTaqRhqqWjYlBTZqRiBGSl2DlwhCTEpCTEZCXF6WvZFIPz/v5GCMQA "Retina – Try It Online") Edit: Saved 2 bytes thanks to @CowsQuack. Explanation: The first stage uses Retina 1's string multiplication first to generate the appropriate number of cells, then to generate the appropriate number of rows. The second stage then changes the first row of `td`s into `th`s.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes
```
<table><tr>×<th>AηF⊖θ«<tr>×<td>Aη
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@mJDEpJ9XOpqTI7vB0m5IMO8dz29/vWfaoa9q5HYdWw4RTQML//0cb6RjH/tdNBAA "Charcoal – Try It Online")
### Explanation
```
<table><tr> Print "<table><tr>"
×<th>Aη Print "<th>A" * second input
F⊖θ« For i in (implicit) range over first input
<tr> Print("<tr>")
×<td>Aη Print("<td>A") * second input
```
[Answer]
# K, 58 bytes
K version is whatever is included in `KDB+ 3.5 2017.11.30`.
Port of the Python answer above. Ends up being 1 byte longer due to having to enlist and flatten multiple times.
```
{,/"<table><tr>",(y#,"<th>A"),(x-1)#,("<tr>",/y#,"<td>A")}
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~65~~ 54 bytes
*-11 bytes thanks to @msh2108's reminder*
```
/ /;$_="<table><tr>"."<th>A"x$'.('<tr>'.'<td>B'x$')x$`
```
[Try it online!](https://tio.run/##K0gtyjH9/19fQd9aJd5WyaYkMSkn1c6mpMhOSQ/Iy7BzVKpQUdfTUAcJqesBqRQ7J3WgkGaFSsL//6YKxv/yC0oy8/OK/@sW/Nf1NdUzMDQAAA "Perl 5 – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 130 bytes
```
m=>n=>{var r="<table>";for(int i=0;i++<m;)r+="<tr>"+string.Concat(System.Linq.Enumerable.Repeat(i<2?"<th>H":"<td>D",n));return r;}
```
[Try it online!](https://tio.run/##XY7BSgMxEIbP2acIOSVsu0i9mU160BYPFkQPnmOarQPNRCfZgpR99m2KguBpmPnn@/h9XvpEYfZHlzN/pnQgF88Ny8UV8PyUYM93DlCqemSv37mE2G1H9D1gWfzfcyHAg7V84GaOxqKx55MjTkb0xb0fgxV6SCTrLwdzo6Ft@6gVtdecrGh/BN19Qu@K/NU/AX51GxxjoKujewmfoabQr9YV@7CP4q7OvX0QC1RKUygjISc9zYzpv9ZVmlPF3whKqM4gB7lS8rYiDZuaab4A "C# (.NET Core) – Try It Online")
[Answer]
# [Carrot](https://github.com/kritixilithos/Carrot), ~~77~~ 51 bytes
```
<th>A^*$v<tr>vl+(^h)*($^F- 1)A"h"S"d"h+(^l)v<table>
```
(While working on this, I discovered a bug with `h` not working and fixed it)
Golfed some bytes by shortening the html as well as using "split, join" instead of "replace"
[Try it online!](https://tio.run/##S04sKsov@f/fpiTDzjFOS6XMpqTIrixHWyMuQ1NLQyXOTVfBUNNRKUMpWClFKQMonKMJVJKYlJNq9/@/sYIRAA "Carrot – Try It Online"), use the command-line option `-d` to see the AST (Note: this uses the new node interpreter, so the older version on the website cannot run this.)
This program takes the input 0-indexed and in reversed order, because of Carrot's weird nature, thus `3 2` printing a 3×4 table.
Run the program like so, `./carrot -f prog.carrot input.txt`
Basically creates the header row, then the data rows on another cell of the garden (2D tape), and concatenates them together.
---
Carrot works on a 2D tape, called a garden. Each cell on the garden is made up of three stack modes, string, float, array. There is a value for each mode, called a "stack" (note: misnomer). These stacks begin empty. When a cell is at a particular mode, the following commands will affect the stack that corresponds to this mode, for example in float mode, the operations will affect the stack float. And of course, there are commands for switching between modes. The modes are important because each operator can be overloaded for each mode and each argument type.
In addition, there are two additional modes (these only affect the commands, not the stack directly), normal mode and caret mode. Normal mode works normally, where there are operators taking in arguments and affecting the stack directly. In caret mode, (almost) every character is interpreted literally as a string, and is later prepended/appended accordingly to the stack. Caret mode is started/ended with carets (append) or down-carets (prepend).
Carrot begins in a cell on the garden, in stack-string mode, and in caret mode.
---
Beginning in caret-mode, the string `<th>A` is added to the initially empty stack-string. Then follows the `*` command that duplicates it `$`, the input, times. Then `<tr>` is prepended to the stack-string by the usage of the down-caret `v`. This creates the header row of the table.
To create the data rows, we duplicate the header to another cell. `l` moves the IP to the right empty cell, and `+` appends `(^h)` the string in the cell to the left (essentially copying it to the cell on the right). `()` starts a subshell, a new Carrot program with almost the same tape, and `^` exits out of caret-mode so that we can `h` get the string in the left cell. This is then `*` duplicated by `($^F- 1)`, the next input minus 1, times.
Still in the right cell, `A` sets the array of this cell to its stack- tring split by `"h"`. `S` joins the stack array by `"d"` and sets the stack string to this value. `A"h"S"d"` really just replaces `h`s with `d`s to form the data rows. Now `h` we move to the left starting cell.
Now we append the stack string of the cell to the right to this cell using `+(^l)`. All that's remaining is to add the `<table>` tag, so we do this by `v` prepending it.
[Answer]
# Powershell, 63 bytes
```
$m,$n=$args;$t='h';'<table>';1..$m|%{'<tr>'+"<t$t>A"*$n;$t='d'}
```
save it as `new-mntable.ps1`. Test script:
```
.\new-mntable.ps1 2 3
.\new-mntable.ps1 1 3
.\new-mntable.ps1 4 2
.\new-mntable.ps1 2 8
```
output (extra spaces are optional):
```
<table>
<tr><th>A<th>A<th>A
<tr><td>A<td>A<td>A
<table>
<tr><th>A<th>A<th>A
<table>
<tr><th>A<th>A
<tr><td>A<td>A
<tr><td>A<td>A
<tr><td>A<td>A
<table>
<tr><th>A<th>A<th>A<th>A<th>A<th>A<th>A<th>A
<tr><td>A<td>A<td>A<td>A<td>A<td>A<td>A<td>A
```
---
# Powershell, 65 bytes, `-replace`
```
'<table>h'+'d'*--$args[0]-replace'h|d',('<tr>'+'<t$0>A'*$args[1])
```
save it as `new-mntable.ps1`. Test script:
```
.\new-mntable.ps1 2 3
.\new-mntable.ps1 1 3
.\new-mntable.ps1 4 2
.\new-mntable.ps1 2 8
```
output:
```
<table><tr><th>A<th>A<th>A<tr><td>A<td>A<td>A
<table><tr><th>A<th>A<th>A
<table><tr><th>A<th>A<tr><td>A<td>A<tr><td>A<td>A<tr><td>A<td>A
<table><tr><th>A<th>A<th>A<th>A<th>A<th>A<th>A<th>A<tr><td>A<td>A<td>A<td>A<td>A<td>A<td>A<td>A
```
How it work:
1. `'<table>h'+'d'*--$args[0]` - create a string like `<table>hddd...`
2. `'h|d'`- search `h` or `d` chars in the string for replacing
3. `'<tr>'+'<t$0>A'*$args[1]` - replace each char with string like `<tr><t$0>A<t$0>A...`
4. where `$0` is a captured `group[0]` - the char in the `-replace`.
---
# Powershell, 65 bytes, `scriptblock`
```
$m,$n=$args;'<table>';&($r={'<tr>'+"<t$args>A"*$n})h;(&$r d)*--$m
```
save it as `new-mntable.ps1`. Test script:
```
.\new-mntable.ps1 2 3
.\new-mntable.ps1 1 3
.\new-mntable.ps1 4 2
.\new-mntable.ps1 2 8
```
output:
```
<table>
<tr><th>A<th>A<th>A
<tr><td>A<td>A<td>A
<table>
<tr><th>A<th>A<th>A
<table>
<tr><th>A<th>A
<tr><td>A<td>A<tr><td>A<td>A<tr><td>A<td>A
<table>
<tr><th>A<th>A<th>A<th>A<th>A<th>A<th>A<th>A
<tr><td>A<td>A<td>A<td>A<td>A<td>A<td>A<td>A
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 34 bytes
```
`<∨ø>`?(`<tr>`‛hdn1>i`<t%>A`$%⁰*Wṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgPOKIqMO4PmA/KGA8dHI+YOKAm2hkbjE+aWA8dCU+QWAkJeKBsCpX4bmFIiwiIiwiMlxuMyJd)
Port of Emigna's 05AB1E answer.
#### Explanation
```
`<∨ø>` # Push "<table>"
?( # Input number of times:
`<tr>` # Push "<tr>
‛hd # Push "hd"
n1> # Is the loop variable
# greater than 1?
i # Index into "hd"
`<t%>A` # Push "<t%>A"
$% # Replace "%" with
# either "h" or "d"
⁰* # Multiply this string
# by the second input
Wṅ # Join the stack into a string
# Implicit output
```
[Answer]
# [Go](https://go.dev), ~~130~~ 123 bytes
```
func f(r,c int)(s string){for d,i:="<th>A",0;i<r;i++{if i>0{d="<td>A"}
s+="<tr>"
for j:=0;j<c;j++{s+=d}}
return"<table>"+s}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY5NDoIwEEb3PUXTVRuqIRoT5aeJN_AKCBQHoZBSVk1P4oaYeAiP4m0sSoyrmcn7Zubd7lU3Pfssv2ZVidsMFIK277RZE9ka8hiNXO1fVo4qx5JqnmNQhtEBD0aDqpiVncYFhyglibmII-FhDImOIQgsSAwitMWMCo8cGoK514Kgea2O0jCukzyufdijwjmkSzNq5UPZuSkFCQa3KBw-CrMgZdiik_9uGkUl3fAtY7-Z_ZE933myHJimb30D)
* -7 bytes from removing unused variable, condensing string literals (@xigoi)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 40 bytes
```
J"<tr>"AQ"<table>"J*H"<th>A"*tGJ*H"<td>A
```
[Try it online!](https://tio.run/##K6gsyfj/30vJpqTITskxEEgnJuWk2il5aXkA2Rl2jkpaJe4QToqd4///RjrGAA)
[Answer]
# [Dart](https://www.dartlang.org/), 45 63 bytes
### Working solution:
```
(m,n){print('<table><tr>'+'<th>A'*n+('<tr>'+'<td>A'*n)*(m-1));}
```
[Try it online here!](https://dartpad.dartlang.org/d4dc45371d8929ecd1cdbe671bb03ced)
Lambda/anonymous function taking `m` and `n` as parameters, displays output to `STDOUT`.
Since tables with unclosed `<table>`, `<tr>`, `<th>`, and `<td>` tags still render in modern browsers (ex., Chrome), the output is valid.
### Old (broken) solution:
My first attempt forgot to switch to `<td>` after the first row:
```
(m,n){print('<table><tr>'+'<th>A'*n+('<tr>'+'<th>A'*n)*(m-1));}
```
Thanks to @Lynn for pointing that out.
[Answer]
# Google Sheets, 66 bytes
```
="<table><tr>"&Rept("<th>A",B1)&Rept("<tr>"&Rept("<td>A",B1),A1-1)
```
Input is in cell `A1` and `B1`.
There's nothing fancy, really; it's just nested `Rept` functions.
It *does* assume `m > n > 0` and that they're both integers.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~33~~ 32 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“<td>A”ẋ”h3¦s5ẋ€ṭ€“<tr>”ṭ“¢ssɱU»
```
A full program taking `rows`, `columns` which prints the result.
**[Try it online!](https://tio.run/##y0rNyan8//9RwxybkhQ7x0cNcx/u6gaSGcaHlhWbgthNax7uXAskwUqK7EAqgPyGOYcWFRef3Bh6aPf///@N/hsDAA "Jelly – Try It Online")**
---
hmm, also 32 using a table:
```
Ịị⁾hdṭ”t⁾<>j;ðþZṭ€“<tr>”ṭ“¢ssɱU»
```
[Answer]
# J, 64 bytes
Another port of the Python answer:
```
4 :0
'<table><tr>',(;y#<'<th>A'),;(<:x)#<('<tr>',(;y#<'<td>A'))
)
```
[Answer]
## PHP, 161 Bytes
[Try it online](https://tio.run/##XYzdCsIgGIZvZXx4oGBrOs@0YtcREWspBs2JfR1F1266k2AnD@8fb/Qxm1MsdO8w4WMJjaNk5iSwD8HDGXC8Pe0ROKBfeV@ZKs0eLtpOfmlemDBRMJ3poS3mmmy0I5ZEDEpAfWtBbbutl4OS/y0n805U2RWJTH@zo5L3TOcf)
**Code**
```
function f($m,$n){$t=["table>","th>","td>","tr>","</"];echo strtr("
<0<3".str_repeat("<1A41",$n)."43".str_repeat("<3".str_repeat("
<2A42",$n)."43",$m-1)."40",$t);}
```
**Explanation**
```
function f($m,$n){
$t=["table>","th>","td>","tr>","</"]; //array representing the tags its created
echo strtr("<0<3".str_repeat("<1A41",$n)."43" //strtr it's called and uses
//the array to replace values
.str_repeat("<3". //repeat the tags
str_repeat("<2A42",$n) //repeat the tags again
."43",$m-1)."40",$t);
//its repeated m-1 times because head is counted as one row
}
```
## PHP, 193 Bytes
Full table structure forgot `<tfooter>` `<thead>, <tbody>..etc..`
[Try example of the function](https://tio.run/##XY3LCsIwEEV/pQxdNBD7SEo3HSt@h4ikbUoF24Q4LkT89hojuMjmcs@ZC2Nnu@HB@pwe60BXsyZTli48Xdkrpf0JSPU33QEHmrUaQ@nN@PyZkJF0HZxbPcwmuZMjlwGWWEHu4eK01Yq8kUcsJHyf5IBFhSK6NxHXfl//941vy64KXWBReiTWvrcpE1yydvsA)
```
function f($m,$n) {$t=["table>","thead>","tbody>","th>","td>","tbody>","tr>"];
echo strtr(
"<0<1".str_repeat("<3A</3",$n).
"</1<2".str_repeat(
"<6".str_repeat("<4A</4",$n)
."</6",$m-1)."</2</0",
$t);
}
```
**Explanation**
`$t=["table>","thead>","tbody>","th>","td>","tbody>","tr>"];`
An array with all the tags for the table it's builded and then with `str_repeat` a number refering to an index in the array is written, **then** to `strtr` the string plus the array is passed
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.