text
stringlengths 180
608k
|
---|
[Question]
[
Your task is to write a program that makes your screen appear to have a bad pixel.
You should choose exactly one pixel on the screen, and exactly one channel between red, green and blue, and make its value either always 0 or always maximum (usually 255). The values of other channels should be the same as if your program didn't run.
You can choose the pixel and channel in whatever ways, such as hardcoding it or generate it randomly on each run. But it must always be visible on fairly modern hardwares.
If the color that originally should be displayed on that pixel has changed, your program should update in less than 0.5 seconds when the system is fast enough.
You cannot make assumptions about what is currently displayed on the screen (such as a taskbar using the default theme).
Your program doesn't need to work when a screensaver, login screen, effect from a window manager, etc, are active.
Shortest code wins.
[Answer]
# Bash on Linux - 25 bytes of Latin-1
*+3 from @wyldstallyns* /
*-2 from removing quotes* /
*-1 because I forgot how this works* /
*-9 from @Dennis*
```
printf ÿ>/dev/fb0;exec $0
```
Assumes that /dev/fb0 exists (it does on my Arch Linux system, and I think it should on any other Linux system). Requires root access as well. This does not work for me when X is running. On my system, this just constantly sets the blue channel of the top-left pixel to full (`ÿ` is 255).
[Answer]
# Visual C++, ~~102~~ ~~100~~ ~~99~~ 98 bytes
```
#include<Windows.h>
int main(){for(HDC d=GetDC(0);;Sleep(99))SetPixel(d,9,9,GetPixel(d,9,9)|255);}
```
Runs on Windows, directly using the Win32 API with Visual C++ compiler targeting the console subsystem. Uses the "screen" [device context](https://msdn.microsoft.com/en-us/library/windows/desktop/dd144871(v=vs.85).aspx) to set the red channel of the pixel at (9,9) to `0xFF`.
The sleep is necessary to allow other programs to draw in between the get/set - and 9ms was too short, leading to the pixel getting stuck1 on its initial colour.
---
1 Unfortunately, not quite the same type of stuck pixel this question is looking for...
[Answer]
# HolyC, 13 bytes
```
GrPlot(,9,9);
```
Puts a black dot on the persistent layer directly.
[![Layers](https://i.stack.imgur.com/WRK8c.png)](https://i.stack.imgur.com/WRK8c.png)
What it looks like.
[![Screenshot](https://i.stack.imgur.com/cDkA3.pngs)](https://i.stack.imgur.com/cDkA3.pngs)
[Answer]
# C#, ~~247~~ ~~244~~ ~~371~~ ~~366~~ ~~354~~ 352 bytes
Runs on Windows. Gets a [device context](https://msdn.microsoft.com/en-us/library/windows/desktop/dd144871(v=vs.85).aspx) for the entire screen, and repeatedly maximises the red channel at (9,9).
```
namespace System.Runtime.InteropServices{using I=IntPtr;class P{[DllImport("User32")]static extern I GetDC(I h);[DllImport("Gdi32")]static extern int GetPixel(I h,int x,int y);[DllImport("Gdi32")]static extern int SetPixel(I h,int x,int y,int c);static void Main(){for(I d=GetDC((I)0);;Threading.Thread.Sleep(99))SetPixel(d,9,9,GetPixel(d,9,9)|255);}}}
```
I originally didn't want to import `GetPixel`/`SetPixel`, but there's no particularly easy way to read a single pixel off a `Graphic`. So right now this is effectively the same as [my VC++ attempt](https://codegolf.stackexchange.com/a/102961/4163). Maybe saving to bitmap will be shorter...
---
-5 bytes thanks to @TuukkaX
[Answer]
# SmileBASIC, 20 bytes
```
SPSET.,299,99,1,1,33
```
Updates constantly.
Sets sprite `0` to a `1`x`1` area at `299`,`99` on the sprite sheet (which is a red pixel).
`33` is the display attribute, which is `1` (display on) + `32` (additive blending).
[Answer]
# Java 7, 266 bytes
```
import java.awt.*;public class K extends java.applet.Applet{public static void main(String[]a){new K();}Label l=new Label(".");public K(){add(l);}public void paint(Graphics g){s(Color.red);s(Color.green);s(Color.blue);repaint();}void s(Color c){l.setForeground(c);}}
```
I ran this on windows 7. Opens a Java Applet which has a white background by default. Adds a label with a period and then changes the color of the label ad nauseum.
[Answer]
# Tcl/Tk, 61
```
wm at . -tr #F0F0F0
wm o . 1
grid [canvas .c]
.c cr o 9 9 9 9
```
On the image there is a black pixel near the upper left corner of the Vivaldi icon:
[![badpixel](https://i.stack.imgur.com/owJWt.png)](https://i.stack.imgur.com/owJWt.png)
---
If on an interactive shell, there are abbreviations of commands available:
# Tcl/Tk, 57
```
wm at . -tr #F0F0F0
wm o . 1
gri [can .c]
.c cr o 9 9 9 9
```
There is a black pixel over the V white area of the Vivaldi icon:
[![badpixel](https://i.stack.imgur.com/iJwSM.png)](https://i.stack.imgur.com/iJwSM.png)
] |
[Question]
[
Inspired by [this question](https://codereview.stackexchange.com/questions/117174/write-a-function-named-issuper-that-returns-1-if-its-array-argument-is-a-issuper) from our rivals friends over at Code Review.
# Definitions
A *super array* is an array where each new element in the array is larger than the sum of all the previous elements. `{2, 3, 6, 13}` is a super array because
```
3 > 2
6 > 3 + 2 (5)
13 > 6 + 3 + 2 (11)
```
`{2, 3, 5, 11}` is *not* a super array, because
```
3 > 2
5 == 3 + 2
11 > 5 + 3 + 2
```
A *duper array* is an array where each new element in the array is larger than the product of all the previous elements. `{2, 3, 7, 43, 1856}` is a super array, but it is also a *duper* array since
```
3 > 2
7 > 3 * 2 (6)
43 > 7 * 3 * 2 (42)
1856 > 43 * 7 * 3 * 2 (1806)
```
# The challenge
Write a function or program that takes an array as input in your languages native list format, and determines how super the array is. You can also optionally take an array length input (for languages like C/C++). Also, you can assume that all of the numbers in the list will be integers greater than 0.
If it's a *super* array, you must print `It's a super array!` If it is a *super **duper*** array, you must print `It's a super duper array!` It's also possible for an array to be duper-non-super. For example `{1, 2, 3}` In this case, you should print `It's a duper array!` If the array is neither super nor duper, you can print a falsy value.
As usual, this is code golf, so standard loopholes apply, and the shortest answer in bytes wins.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~47~~ ~~45~~ 4̷4̷ 42 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md)
```
+\,×\<ḊZṖP“sd”x;€“uper ”;/“It's a ”,“¥ṫɲ»j
```
This prints an empty string (falsy) for arrays that are neither super nor duper. [Try it online!](http://jelly.tryitonline.net/#code=K1wsw5dcPOG4ilrhuZZQ4oCcc2TigJ14O-KCrOKAnHVwZXIg4oCdOy_igJxJdCdzIGEg4oCdLOKAnMKl4bmrybLCu2o&input=&args=MiwgMywgNywgNDMsIDE4NTI)
### How it works
```
+\,×\<ḊZṖP“sd”x;€“uper ” Main link (first half). Argument: A (array)
+\ Compute all partial sums of A.
×\ Compute all partial products of A.
, Pair the results to the left and to the right.
<Ḋ Perform vectorized comparison with A[1:].
This yields a 2D array of Booleans.
Z Zip; pair the Booleans corresponding to each integer.
Ṗ Remove the last pair.
(Nothing is compared with the last sum/product.)
P Take the product of each column.
“sd”x Perform vectorized character repetition.
This yields ['s', d'], ['s'], ['d'], or [].
;€“uper ” Append the string "uper " to each character.
;/“It's a ”,“¥ṫɲ»j Main link (second half).
;/ Reduce the resulting array of strings by concatenation.
This will fail for an empty array, exiting immediately.
“It's a ”,“¥ṫɲ» Push ['It's a ', 'array!'].
j Join that array, separating by the super duper string.
```
[Answer]
# JavaScript (ES6), ~~111~~ 110 bytes
*Saved a byte thanks to [@ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions)!*
```
a=>a.map((n,i)=>i&&(s=s&&n>s&&s+n,d*=d&&n>d&&n),s=d=a[0])|s|d&&`It's a ${s?"super ":""}${d?"duper ":""}array!`
```
## Explanation
Takes an array of numbers, returns a string or the number `0` for false.
```
a=>
a.map((n,i)=> // for each number n at index i
i&&( // skip the first number (because s and d are initialised to it)
s=s&&n>s&&s+n, // if it is still super and n > s, s += n, else s = false
d*=d&&n>d&&n // if it is still duper and n > d, d *= n, else d = false
),
s= // s = sum of previous numbers if super, else false
d= // d = product of previous numbers if duper, else false
a[0] // initialise s and d to the first number
)
|s|d // if it is neither super or duper, output 0
// Output the appropriate string
&&`It's a ${s?"super ":""}${d?"duper ":""}array!`
```
## Test
```
var solution = a=>a.map((n,i)=>i&&(s=s&&n>s&&s+n,d*=d&&n>d&&n),s=d=a[0])|s|d&&`It's a ${s?"super ":""}${d?"duper ":""}array!`
```
```
Numbers (space-separated) = <input type="text" id="input" value="2 3 7 43 1856" />
<button onclick="result.textContent=solution(input.value.split(' ').map(n=>+n))">Go</button>
<pre id="result"></pre>
```
[Answer]
# Java, ~~183~~ 182 Bytes
```
String w(int[]a){boolean s=1<2,d=s;int m=a[0],p=m,k=a.length,i=0,e;if(k>0)for(;++i<k;s&=e>m,d&=e>p,m+=e,p*=e)e=a[i];return d|s?"It's a "+(s?"super ":"")+(d?"duper ":"")+"array!":"";}
```
I made the following assumptions:
* The output is via return value.
* The empty String `""` is a falsy value.
If any of these are wrong, please tell me.
Anyway, I can't shake the feeling that I might have gone overboard with the amount of variables.
Edit: managed to save a byte, thanks to @UndefinedFunction
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 66 bytes
```
Ys5L)G6L)XK<?' super']GYp5L)K<?' duper']N?N$h'It''s a'wh' array!'h
```
Uses [current release (10.0.3)](https://github.com/lmendo/MATL/releases/tag/10.0.3), which is earlier than this challenge.
Input is from stdin. If not super or duper, output is empty (which is falsey).
*EDIT (April 7, 2016)*: due to changes in release 16.0.0 of the language, `5L` and `6L` need to be replaced by `3L` and `4L` repectively. The link to the online compiler includes those modifications.
[**Try it online**!](http://matl.tryitonline.net/#code=WXMzTClHNEwpWEs8Pycgc3VwZXInXUdZcDNMKUs8PycgZHVwZXInXU4_TiRoJ0l0JydzIGEnd2gnIGFycmF5ISdo&input=WzIsIDMsIDcsIDQzLCAxODU2XQ)
### Explanation
```
Ys % implicit input. Cumulative sum
5L) % remove last element
G6L) % push input. Remove first element
XK % copy to clipboard K
<? % if all elements are smaller
' super' % push string
] % end
GYp % push input. Cumulative product
5L) % remove last element
K % push input except first element
<? % if all elements are smaller
' duper' % push string
] % end
N? % if stack not empty
N$h % concatenate all elements (will be one or two strings)
'It''s a' % string
wh % prepend
' array!' % string
h % concatenate. Implicit end. Implicit display
```
[Answer]
## C++14, 178, ..., 161 157 bytes
Can't think of a way to make it any shorter. Seems like there's always some room for improvement!
**Update 1**: I'm all for safe code, but taking a raw array and its size as function arguments is 9 bytes shorter than taking a vector :(
**Update 2:** Now returns an empty string as false-value, at cost of 8 bytes.
**Update 3:** Back to 165 bytes, thanks to CompuChip's comment.
**Update 4:** Another comment by CompuChip, another 4 bytes off.
**Update 5:** using `auto` instead of `string` along with another suggestion by CompuChip shaves another 4 bytes off the code.
```
auto f(int*a,int n){int s,p,d=1,e=1,r;for(s=p=*a;--n;s+=r,p*=r)r=*++a,e=r>s?e:0,d=r>p?d:0;return e|d?"It's a "s+(e?"super ":"")+(d?"duper ":"")+"array!":"";}
```
Ungolfed full program with test cases:
```
#include <iostream>
#include <string>
#include <vector>
using namespace std::literals::string_literals;
auto f(int* a, int n)
{
int s,p,d=1,e=1,r;
for(s=p=*a; --n; s+=r, p*=r)
r=*++a, e=r>s?e:0, d=r>p?d:0;
return e|d ? "It's a "s + (e?"super ":"") + (d?"duper ":"") + "array!" : "";
}
int main()
{
std::vector<std::vector<int>> test_cases = {{2,3,6,13},
{2,3,5,11},
{2,3,7,43,1856},
{1,2,3}
};
for(auto& test_case : test_cases)
{
std::cout << f(test_case.data(), test_case.size()) << '\n';
}
}
```
Output:
```
It's a super array!
It's a super duper array!
It's a duper array!
```
[Answer]
## C, 150 bytes
```
#define M(N,O)N(int*d,int c){return*d?*d>c?N(d+1,c O*d):0:1;}
M(S,+)M(D,*)Z(int*d){printf("It's a %s%s array!\n",S(d,0)?"super":"",D(d,0)?"duper":"");}
```
Each input is terminated by a `0`. Test main:
```
#include <stdio.h>
int main() {
int test_data[4][6] = {
{2, 3, 7, 43, 1856, 0}, // superduper
{2, 3, 5, 11, 0}, // not super
{2, 3, 6, 13, 0}, // super
{1, 2, 3, 0} // duper not super
};
for (int i = 0; i < 4; ++i) {
Z(test_data[i]);
}
}
```
**Bonus** if we are allowed a more compact output format, we can cut it to **107 bytes**:
```
#define M(N,O)N(int*d,int c){return*d?*d>c?N(d+1,c O*d):0:1;}
M(S,+)M(D,*)Z(int*d){return S(d,0)*2^D(d,0);}
```
In this case, `Z` return `3` for superduper, `2` for super, `1` for duper and `0` for none.
[Answer]
# Pyth - ~~54~~ 52 bytes
The string formatting part can probably be golfed, but I like the super-duper testing approach.
```
jd++"It's a"fT*V+R"uper""sd"m*F>VtQd,sMK._Q*MK"array
```
[Test Suite](http://pyth.herokuapp.com/?code=jd%2B%2B%22It%27s+a%22fT%2aV%2BR%22uper%22%22sd%22m%2aF%3EVtQd%2CsMK._Q%2aMK%22array&test_suite=1&test_suite_input=2%2C+3%2C+6%2C+13%0A2%2C+3%2C+5%2C+11%0A2%2C+3%2C+7%2C+43%2C+1856&debug=0).
[Answer]
# Python 3, 127
Saved 5 bytes thanks to FryAmTheEggman.
Fairly basic solution right now, nothing too fancy. Just running a running total of sum and product and check each element.
```
def f(a):
s=p=a[0];e=d=1
for x in a[1:]:e&=x>s;d&=x>p;s+=x;p*=x
return"It's a %s array!"%('super'*e+' '*e*d+'duper'*d)*(e|d)
```
Here's the test cases in case anyone else wants to try to beat my score.
```
assert f([2, 3, 6, 13]) == "It's a super array!"
assert f([2, 3, 5, 11]) == ''
assert f([2, 3, 7, 43, 1856]) == "It's a super duper array!"
assert f([1, 2, 3]) == "It's a duper array!"
print('All passed')
```
[Answer]
**AWK - 140 bytes**
```
awk 'BEGIN{d[1]=" super";e[1]=" duper";RS=" ";p=1;a=1;b=1}{a=a&&$1>s;b=b&&$1>p;s+=$1;p*=$1}END{printf "It'\''s a%s%s array!\n",d[a],e[b]}'
```
For those that don't know AWK, records are automatically parsed into lines based on variable `RS` and lines are automatically parsed into fields based on variable `FS`. Also unassigned variables are "" which when added to a # acts like a 0. The `BEGIN` section is called exactly once, before any records/fields are parsed. The rest of the language is fairly C-like with each matching code block being applied to each record. See <http://www.gnu.org/software/gawk/manual/gawk.html#Getting-Started> for more details.
Example run where `'code'` is as above:
`echo 1 2 6 | 'code'`
Could also place array in a file named Filename and run as:
`'code' Filename`
If the code is to run often it can be placed in an executable script file. This would remove the enclosing `' '` and the `awk` command would be placed at the top of the file as: `#!/bin/awk -f`
[Answer]
# PHP, ~~144~~ ~~...~~ ~~113~~ 112 Bytes
```
$x=super;$d=duper;foreach($a as$v){$v>$s||$x="";$v>$p||$d="";$s+=$v;$p=$p*$v?:$v;}echo$x.$d?"It.s a $x $d $a!":0;
```
Explanation:
```
// Initiate `$s` to prevent isset calls. Leaving this out yields PHP
// notices, but doesn't functionally change the code.
$s = 0;
// Set product to 1, so when multiplying with the first value, `$p` will
// equal `$v`.
$p = 1;
// Not existing constants `super` and `duper` yield PHP notices
// but are interpreted as strings.
$x = super;
$d = duper;
// Iterate over input (register_globals).
foreach ($a as $v) {
// Check if current value "breaks" [sd]uper-ness: `value` not greater
// than current sum or product. If so, unset the string.
$v > $s || $x = "";
$v > $p || $d = "";
// Update sum.
$s += $v;
// Update product.
$p *= $v;
}
// Check if super or duper strings are set, if so, wrap output in the
// appropriate string. Otherwise, output falsy value `0`.
echo $x . $d ? "It's a $x $d $a!" : 0;
```
Without register globals it would be this (118 bytes):
```
php -r '$x=super;$d=duper;for($p=1;$v=$argv[++$i];$p*=$v){$v>$s||$x="";$v>$p||$d="";$s+=$v;}echo$x.$d?"It.s a $x $d array!":0;' 2 3 7 43 1856 2>/dev/null;echo
```
* Saved another 3 bytes by not caring about an extra space in the output
* Saved 3 bytes by printing `$a` (array to string conversion yields `Array`)
* Saved a byte by initializing `$p` to 1, so upping the product costs less.
[Answer]
# [R](https://www.r-project.org/), 115 bytes
```
function(x)cat("It's a",c("super","duper")[sapply(c(cumsum,cumprod),function(f)all(rev(x[-1]>f(x))[-1]))],"array!")
```
[Try it online!](https://tio.run/##PY1BCsIwEEX3niLGhRkYwTG2iqB7z1C6CKkBIW1D0kh7@hhL6@rPvA/v@xTvycROD@@@EyNoNQj@HPaBKY5a8BDdy3PkzZxQBeWcnYQWOrYhtpjD@b4B/DsMKGuFf33EWB2ofphshd8FUCNX3qtpyyHF7DihxAueJdK1KAF28xibpzZrXyLJtVogk8gKZESZG2XDlDkdb7R86Qs "R – Try It Online")
Falsy value: `It's a array!`
Nothing too fancy here except maybe using `sapply` on a list of functions.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 45 bytes
```
K0pṪ₍ṠvΠƛ?<A;‛sdf*';`u∧‛ `+:[`It's a %‹⟇!`$∑%
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJLMHDhuarigo3huaB2zqDGmz88QTvigJtzZGYqJztgdeKIp+KAmyBgKzpbYEl0J3MgYSAl4oC54p+HIWAk4oiRJSIsIiIsIlsyLCAzLCA3LCA0MywgMTg1Nl0iXQ==)
A bit of a mess
[Answer]
## Scala, 172 Bytes
```
def f(a:Seq[Int])={var q=" super"
var w=" duper"
val x=a.head
a.drop(1).foldLeft((x,x)){case ((s,p),a)=>{if(s>=a)q=""
if(p>=a)w=""
(a+s,a*p)}}
println(s"It's a $q$w array")}
```
Ungolfed (although there really isn't much work to do so):
```
def f(input:Seq[Int])={
var super=" super"
var duper=" duper"
val head=input.head
input.drop(1).foldLeft((head,head)){
case ((sum,product),val)=>
{
if(sum>=val)super=""
if(product>=val)duper=""
(val+sum,val*product)
}
}
println(s"It's a $super$duper array")
}
```
[Answer]
## Haskell, 136 Bytes
```
s o t=snd.foldl(\(s,b)x->(o s x,b&&x>s))(t,1>0)
f x="It's a "++(if s(+)0x then"super "else"")++(if s(*)1x then"duper "else"")++"array!"
```
`f` is the required function. Note that the empty sum is 0 and the empty product is 1 which is why `[0]` is neither super nor duper.
`s` captures the common structure of testing super or duper by taking an arbitrary operator `o` and an arbitrary neutral element `t`. The `foldr` keeps track of tuples `(s,b)` where `s` is the result of chaining all seen elements with the operator `o` and `b` says whether, for every element looked at so far, this element was larger than the previously computed sum/product.
The output is not golfed very much and I would appreciate it if someone contributed a better idea!
Slightly more readable version:
```
s :: (Integer -> Integer -> Integer) -> Integer -> [Integer] -> Bool
s o t = snd . (foldl (\(s,b) x -> (s `o` x, b && x>s)) (t, True))
f :: [Integer] -> [Char]
f x = "It's a " ++ (if s (+) 0 x then "super " else "")
++ (if s (*) 1 x then "duper " else "") ++ "array!"
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~53~~ 51 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"It's"'a„dsIη©εRćsO›}Pè.•dwā•UX¦«®εRćsP›}PiX}„¦È!ðý
```
[Try it online](https://tio.run/##MzBNTDJM/f9fybNEvVhJPfFRw7yUYs9z2w@tPLc16Eh7sf@jhl21AYdX6D1qWJRSfqQRSIVGHFp2aPWhdRAFAWAFmRG1QJ2Hlh3uUDy84fDe//@jjXSMdcx1TIx1DC1MzWIB) or [verify all test cases](https://tio.run/##MzBNTDJM/V9TVmmvpPCobZKCkv1/Jc8S9WIl9cRHDfNSiivPbT@08tzWoCPtxf6PGnbVBhxeofeoYVFK@ZFGIBUacWjZodWH1kEUBIAVZEbUAnUeWna4Q/HwhsN7/@v8jzbSMdYx0zE0juUCM811TIx1DC1MzaB8Ux1Dw1gA).
**Explanation:**
```
"It's" # Push string "It's"
'a # Push string "a"
„ds # Push string "ds"
Iη # Get the prefixes of the input-list
© # Store it in the register (without popping)
ε } # Map each sub-list to:
R # Reverse the list
ć # Take the head extracted
sO # Swap and take the sum
› # Check if the head is larger than the sum of the rest
P # Then check this is truthy for all sub-lists, resulting in 0 or 1
è # And use this to index into the "ds" string
.•dwā• # Push string "duper"
U # Store it in variable `X` (with popping unfortunately)
X¦ # Push `X` and remove the first character
« # Then merge it with the "d" or "s"
®εRćsP›}P # Do the same as explained above, but with the product instead of sum
i } # If this resulted in 1:
X # Push variable `X` ("duper")
„¦È! # Push string "array!"
ðý # Join all strings on the stack by spaces (and output implicitly)
```
[See here for an explanation of how `.•dwā•` is "duper" and how `„¦È!` is "array!".](https://codegolf.stackexchange.com/a/166851/52210)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 37 bytes
```
Ä,×\<ḊZṖPµ“¤ḋГ¡e⁽»x'“¡Ƈɠİ[lɦ“Ñŀṙ»jẋẸ
```
[Try it online!](https://tio.run/##y0rNyan8//9wi87h6TE2D3d0RT3cOS3g0NZHDXMOLXm4o/vwBBBrYeqjxr2HdleogznH2k8uOLIhOufkMiD38MSjDQ93zjy0O@vhru6Hu3b8//8/2lBHwUhHwTgWAA "Jelly – Try It Online")
Full program.
I got the `Z…P` idea from Dennis's (old) answer.
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=sum,product,all -pa`, 126 bytes
```
$_="It's a"." super"x(all{$_}map{$F[$_]>sum@F[0..$_-1]}@b=1..$#F)." duper"x(all{$_}map{$F[$_]>product@F[0..$_-1]}@b)." array!"
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lbJs0S9WCFRSU9Jobi0ILVIqUIjMSenWiW@NjexoFrFLVolPtauuDTXwS3aQE9PJV7XMLbWIcnWEMhWdtME6krBqaugKD@lNLkEVSdIS2JRUWKlotL//4YKRgrG//ILSjLz84r/6/qa6hkYGgBpn8ziEiur0JLMHFug1TpQg3SAVvzXLUjMAQA "Perl 5 – Try It Online")
] |
[Question]
[
Minecraft has a fairly unique lighting system. Each block's light value is either one less than the brightest one surrounding it, or it is a light source itself. Your task is to write a method that takes in a 2D array of light source values, and then returns a 2D array with spread out lighting, where 0 is the minimum value.
**Examples**
```
Input1 = [
[0, 0, 4, 0],
[0, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 0, 0]
]
Output1 = [
[2, 3, 4, 3],
[1, 2, 3, 2],
[1, 2, 2, 1],
[0, 1, 1, 0]
]
Input2 = [
[2, 0, 0, 3],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
Output2 = [
[2, 1, 2, 3],
[1, 0, 1, 2],
[0, 0, 0, 1],
[0, 0, 0, 0]
]
```
**Notes**
You can assume:
1. Input will not be empty
2. The y axis will be the same length
3. All numbers will be integers; no nulls, doubles, or floats
4. All numbers will be between 0 and 15 (inclusive).
Rules:
1. Return a 2D array following the above mechanics
2. No value can be less than 0
3. If there are two highest neighbors, just subtract one from them
4. Light sources do not change, unless a surrounding block is brighter than it.
5. No standard loopholes
6. This is code golf, so shortest code wins!
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 21 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
(⊢⌈¯1+«⌈»⌈«˘⌈»˘)⍟(≠⥊)
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgKOKKouKMiMKvMSvCq+KMiMK74oyIwqvLmOKMiMK7y5gp4o2fKOKJoOKliikKCj7ii4jin5xGwqgg4p+oCjTigL804qWK4p+oMCwwLDQsMCwwLDAsMCwwLDAsMiwwLDAsMCwwLDAsMOKfqQo04oC/NOKliuKfqDIsMCwwLDMsMCwwLDAsMCwwLDAsMCwwLDAsMCwwLDDin6kK4p+p)
`«⌈»⌈«˘⌈»˘` computes the element-wise maximum of:
* `«` Push in 0's from the bottom
* `»` Push in 0's from the top
* `«˘` Push in 0's from right
* `»˘` Push in 0's from the left
Then substract 1 from this / add ¯1 (`¯1+`) and take the maximum with the input matrix (`⊢`).
`≠⥊` gives the number of element in the flattened matrix and `(...)⍟` iterates the function on the left that many times.
[Answer]
# [R >=4.1](https://www.r-project.org/), ~~377~~ ~~215~~ ~~182~~ 150 bytes
```
f=\(m,w=T,n=1:ncol(m),z=Reduce(pmax,Map(\(j){o=outer(m[p][j]-abs(n-i[j,1]),abs(n-i[j,2]),`-`);o*(o>0)},1:nrow(i<-which(p<-m>1,a=T)))))`if`(w,f(z,F),z)
```
I sure learned a lot.
Thanks to [June Choe](https://twitter.com/yjunechoe/status/1507344665514848258?s=20&t=27rn8zNl-36D-3ppsslAjw) for the `outer()` tip which enabled a significant optimisation, and then some cleanup.
Also thanks to [@pajonk](https://codegolf.stackexchange.com/users/55372/pajonk) for some additional savings, use of `Map`, and for introducing me to ['attempt this online'](https://ato.pxeger.com/run?1=nZHPSsNAEMbxmqfY44zMQhI9iGZ705uXEk9pINs0oRvcbEg3pFZ8DS9e6sGH0qdxTVpFxD84fAwzfDDzY-bhsd1unzpb8pPn-1LMQFMvYqpFcFrn5ho00kZMi0WXF9BouaZL2cAMKrw1wnS2aEEnTZpUKZfzFdRcJRUFKdJHF7ou4xmemUMwEx_vyI1uTQ8q4v1S5UtoIq4nAUkR41tkqsygpxI2dOG240j3ciC0LVY2YBFnWtpWrSEHn5jT8ZA99jVG3__JD3_xd8JhjdP8xsEzweLp1Tl63gAVfoJ6n3j0b6g_-t9BlTDeCvdVuLvi_tev)
[Answer]
# JavaScript (ES6), ~~99 94~~ 93 bytes
Modifies the input matrix in-place.
```
m=>{for(d=64;d--;m.map((r,y)=>r.map((v,x)=>r[x]=(q=~-(m[y+D%2]||0)[x+~-D%2])>v?q:v)))D=d%4-1}
```
[Try it online!](https://tio.run/##rY1dC4IwFIbv9yt2I@3gJsusi2J2479YXkhqKG4rC1H6@OtLiyiCICI4nMPD4X2fMmmS/boutgemTZrZXFglwmNuapKKWbBIGVsoTyVbQmragQjrOzS0HUC2sSA7cWFEyc6NHD8@nTjI1r2wASBslrt5AwCRSJ2Ajc82JwoLLBHGklPcT9DvmD6Zv7L/xo8/igGtjd6bKvMqsyHKK02hyWilR4BdfLsIvbj8R3by0cX/5fqie/qDC@wV "JavaScript (Node.js) – Try It Online")
### Commented
```
m => { // m[] = input matrix
for( // repeat 64 times,
d = 64; // using d as a counter:
d--; //
m.map((r, y) => // for each row r[] at position y in m[]:
r.map((v, x) => // for each value v at position x in r[]:
r[x] = ( // update r[x]:
q = // q is the value of the neighbor cell
~-( // located at m[y + dy][x + dx],
m[y + D % 2] // using D as the current direction
|| 0 // (-1 = North, 0 = West, 1 = South,
)[x + ~-D % 2] // 2 = East), minus 1
) > v ? q // keep the maximum of q and the
: v // current value v
) // end of inner map()
) // end of outer map()
) D = d % 4 - 1 // set D to (d mod 4) - 1
} // implicit end of for()
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 24 bytes
```
Xz,G@+&fh]&1ZP-TYaX>GZye
```
[Try it online!](https://tio.run/##y00syfn/P6JKx91BWy0tI1bNMCpANyQyMcLOPaoy9f//aAMFAwUTBQNrBQMIBDGMYAwwjAUA) Or [verify all test cases](https://tio.run/##y00syfmf8D@iSsfdQVstLSNWzTAqQDckMjHCzj2qMvW/QXKES1RFyP9oAwUDBRMFA2sFAwgEMYxgDDCM5YoGCygYoyhCZcQCAA).
### Explanation
```
Xz % Implicit input. Get nonzeros as a column vector (*)
, % Do twice
G % Push input
@ % Push iteration index: 0 or 1
+ % Add, element-wise
&f % Two-output find: gives row and column indices of nonzeros
h % Concatenate horizontally. Gives a 2-row matrix where each
% row contains the coordinates of nonzeros (first iteration)
% or of all entries (second iteration)
] % End
&1ZP % Cityblock distance between rows
- % Subtract from (*), element-wise with broadcast
TYa % Extend with two rows of zeros. This serves two purposes:
% making sure that the maximum of each row is at least 0; and
% making sure that each column has more than 1 entry, so that
% the following function (maximum) operates along the first
% dimension (compute maximum of each column)
X> % Maximum along the first (non-singleton) dimension (**)
GZy % Push input. Size
e % Reshape (**) with the specified size. Implicit display
```
[Answer]
# C(gcc) 230 227 220 172 171 128 97 bytes
smaller thanks to @Muskovets an @engineergaming, and now @ceilingcat
```
i,j;f(n,x,y)int*n;{for(i=x*y;i--;)for(j=x*y;j--;n[j]=fmax(n[j],n[i]-abs(i%x-j%x)-abs(i/x-j/x)));}
```
[Try it Online!](https://tio.run/##hVBBboMwELzzilWqSLZjSppGvRj6kZSDYwIYEacC2hpFfL10bSKFpJUqWaud8eysPSoslBoftFH1R3aAuO0yfXosX4MbqtZ75EbNK5ETwy3vqTYdM@KcnxqiE8t6ocNQUAcrDyuEZlelSX6UlriOm51OQ7lviV7asFpaOoEIQWQppWIY0RWOUhviGtkUioMqZcOYA58UzgHAe4OXOVnsD4U2b2ZBRYBsxLC4qS@ddSUksBUXojzoouzmjGya3dNLitR5zQHP1te7s/lNDs6BRcG/q55vVm38qj@X3NvjWE5wiE/m/GI5/RHTBZ9Mn6wF9PF0h91qNUUzk1gnsbF3weaquAa4zDgsuH@ihRX0zItTKrxuCObaKWfHBsP4rfJaFu0Y1scf)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~100~~ ~~98~~ 94 bytes
```
A=Math.abs
f=(a,i,j)=>a.map((r,y)=>r.map((c,x)=>1/i?t=t>(u=c-A(i-y)-A(j-x))?t:u:f(t=a,y,x)|t))
```
[Try it online!](https://tio.run/##dY3BCoJAEIbvPoXHWZg1i07CKj5ATyAepk1rxVzRMRR6dxsIu1TDMD/fxw/T0INGO7iedecv1brm5kR8i@g8BrUBQoeNMilFd@oBBlwEhjdYnAX2O5ex4RQmY3UOTi9KotGzUhknU1IDG8JFuk9WarW@G31bRa2/Qg1FEG5TxBjKHuWWGH75@Jc//PFb/2NL@fwC "JavaScript (Node.js) – Try It Online")
-4 byte from ophact
[Answer]
# [Python 3](https://docs.python.org/3/) with [numpy](https://numpy.org/), 93 bytes
```
f=lambda a,n=0:f(rot90(fmax(a,r_[a[1:],a[-1:]]-1)),n+1)if n<len(a)*4else a
from numpy import*
```
[Try it online!](https://tio.run/##VcXBCgIhEADQe1/h0dlmQdkuLe2XiMREDgk6ihm0X297jXd4de@vIssYvCXKjycpQtnMyrqVfjWaM301Ybs7cnb1SG4@8rMFQDlbiKzkloJogukS0jsoOnErWckn113FXEvr06gtStesnTN48Pj34j3A@AE "Python 3 – Try It Online")
Each iteration spreads light upwards, then rotates the array by 90 degrees.
[Answer]
# [J](http://jsoftware.com/), 28 27 bytes
```
(>./@,((,-)=1 2)|.!.0<:)^:_
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Nez09B10NDR0dDVtDRWMNGv0FPUMbKw046zi/2ty@TnpKcSCVcQbaoMVKVvBVcVypSZn5CukKZgAoQrQTAMgbaAAZhhAGEYwBhhC1Kuro@qDqDFG0YfK@A8A "J – Try It Online")
Consider input:
```
0 0 4 0
0 0 0 0
0 2 0 0
0 0 0 0
```
* `(,-)=1 2)` 4 directions of movement:
```
1 0
0 1
_1 0
0 _1
```
* `|.!.0<:` Rotate the input minus 1 in those directions:
```
_1 _1 _1 _1
_1 1 _1 _1
_1 _1 _1 _1
0 0 0 0
_1 3 _1 0
_1 _1 _1 0
1 _1 _1 0
_1 _1 _1 0
0 0 0 0
_1 _1 3 _1
_1 _1 _1 _1
_1 1 _1 _1
0 _1 _1 3
0 _1 _1 _1
0 _1 1 _1
0 _1 _1 _1
```
* `>./@,` Prepend input and max reduce the 5 "planes":
```
0 3 4 3
0 1 3 0
1 2 1 0
0 1 0 0
```
* `(...)^:_` Repeat that process until a fixed point:
```
2 3 4 3
1 2 3 2
1 2 2 1
0 1 1 0
```
[Answer]
# Python 3, ~~207~~ 205 bytes
Once I first saw this challenge posted, I started having some ideas for python solutions bouncing around in my head. This solution turned out to be way longer than I would have hoped, but I did find away to do this without `numpy`, which the other python solution uses:
```
f=lambda x:[[eval(f"max(max({i*'x[i-1][j],'}{j*'x[i][j-1],'}{~i%len(x)*'x[i+1][j],'}{~j%len(x)*'x[i][j+1],'})-1,x[i][j])")for j in range(len(x))]for i in range(len(x))]
g=lambda x:x if f(x)==x else g(f(x))
```
[Try it online!](https://tio.run/##ZY7RCoMgFIbv9xSHYKRlsOhu0JOIF46pU8yixXDEenWnBW1jHA6H7@P/4QzP6da7JgTZWt5drhz8mVLx4BbJrOMepZ11kXuqq5pRw0j@ms3KkaJKvOijFQ55vPpyzy3m20dbrnlc1WRjhjMs@xEMaAcjd0qgrYBZ0vpfH9TnUQ9agoy6bT0IexegUEIc9rJClJ5IHEZ@bsMYPsMwajehQuPwBg)
I wanted to be able to fit this into one lambda, but I simply couldn't seem to get the conditional to work, so `g(x)` is the function that is actually called to get the result. The main bulk of the code is in the giant `eval()` statement, which basically calculates the highest adjacent block, subtracts 1 from that, and takes the the max of that and the blocks current value. The rest of the code just iterates that over each block, and then recursively does that until all light levels have been calculated.
[Answer]
# [Haskell](https://www.haskell.org), 107 bytes
```
r x=[0..length x-1]
f a=let(w,h)=(r$head a,r a)in[[maximum[a!!y!!x-abs(x-j)-abs(y-i)|x<-w,y<-h]|j<-w]|i<-h]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN7OLFCpsow309HJS89JLMhQqdA1judIUEm1zUks0ynUyNG01ilQyUhNTFBJ1ihQSNTPzoqNzEysyc0tzoxMVFSsVFSt0E5OKNSp0szTBjErdTM2aChvdcp1KG92M2JosIDO2JhPEhlgJtRnmAgA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
IEθEι⌈Eθ⌈Eν⁻π⁺↔⁻ξκ↔⁻ρμ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQKNQRwFEZYKoiszc0lyEKIKbB@Rm5pUWaxToKATkAGnHpOL8nNKSVA2IcIWOQrampo4CmnCRjkKuJhKw/v8/OjraSEfBAIyMY3UUuBQUog1gAgZECMTG/tctywEA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Same algorithm as @alephalpha's PARI/GP answer.
```
EθEι Map over input array
Eθ Eν Map over input array
π Innermost value
⁻ Subtract
↔⁻ξκ Absolute row difference
⁺ Plus
↔⁻ρμ Absolute column difference
⌈ ⌈ Take the maximum
I Cast to string
Implicitly print
```
Note that Charcoal's default I/O format is rather ugly so I've also written a 26-byte prettier version which unfortunately only works up to 9:
```
WS⊞υιEυ⭆ι⌈Eυ⌈Eν⁻π⁺↔⁻ξκ↔⁻ρμ
```
[Try it online!](https://tio.run/##XYpBCsIwEEX3OcUsJzDCIO66cumiEPAEsRQTTNKQJrW3jylVFP9m/nvzB6PTMGlX69NYNwJeQiz5mpMNd5QSVJkNFgIrO6GazNjruIl9soEl6PVqffGf3y@GhjaUGSOBcu2eb/PkSh5x1yvBQ0qCP50IvPymq5X5xIJbBB/53ephcS8 "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 73 bytes
```
m->matrix(#m~,#m,i,j,vecmax(matrix(#m~,#m,k,l,m[k,l]-abs(k-i)-abs(l-j))))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWNz1zde1yE0uKMis0lHPrdJRzdTJ1snTKUpNzEys0UCWydXJ0cqOBZKxuYlKxRrZupiaYkaObpQkEUAPbEgsKcio1chV07RQKijLzSoBMJRBHSSFNI1dTU0chOtpARwGITICktQKEbQBjGyGxoSgWqMUIxjPG0IGFHRsLdc2CBRAaAA)
\$output[i,j]=\underset{k,l}\max(input[k,l]-|k-i|-|l-j|)\$
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Δ<U4FøíXøíDUćaª‚øεø€à
```
Port of [*@Jonah*'s J answer](https://codegolf.stackexchange.com/a/245462/52210), so make sure to upvote him as well!
[Try it online](https://tio.run/##yy9OTMpM/f//3BSbUBO3wzsOr40AES6hR9oTD6161DDr8I5zWw/veNS05vCC//@jow10DHRMdAxidcAsAyjLCM6CiMUCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU3lotw6Xkn9pCZy/8v@5KTahh9aZuB3ecXhtBIhwCT3Snnho1aOGWYd3nNt6eMejpjWHF/yvra0Faj60zf5/dHS0gY6BjomOQawOmGUAZRnBWRCxWB2F6GiwoI4xmlJ0VmwsAA).
**Explanation:**
```
Δ # Loop until the result no longer changes:
< # Decrease each value in the matrix by 1
# (which will be the implicit input-matrix in the first iteration)
U # Pop and store it in variable `X`
4F # Loop 4 times:
øí # Rotate the matrix once clockwise:
ø # Zip/transpose; swapping rows/columns
í # Reverse each inner row
# (which will be the implicit input-matrix in the first iteration)
X # Push matrix `X`
øí # Rotate it once clockwise as well
DU # Store a copy as new value for `X`
ć # Extract head; pop remainder-matrix and first row separated
a # Convert all values in this row to 0 (with an is_letter check)
ª # Append this list of 0s as trailing row
‚øεø€à # Reduce the two matrices by maximum:
‚ # Pair the two matrices together
ø # Zip/transpose; creating pair of rows
εø # Zip/transpose each inner pair of rows to pair of cell-values
ۈ # Leave the maximum of each inner-most pair of cell-values
# (after which the resulting matrix is output implicitly)
```
] |
[Question]
[
This challenge is inspired by [xkcd](https://xkcd.com/612/):
[![enter image description here](https://i.stack.imgur.com/rDl1T.png/ "They could say \"the connection is probably lost,\" but it's more fun to do naive time-averaging to give you hope that if you wait around for 1,163 hours, it will finally finish.")](https://i.stack.imgur.com/rDl1T.png/ "They could say \"the connection is probably lost,\" but it's more fun to do naive time-averaging to give you hope that if you wait around for 1,163 hours, it will finally finish.")
## Challenge:
You'll simulate the copying a large file (1 Gigabyte). The transfer rate will vary between 10 kB/second to 100 MB/second.
Your task is to output the time remaining of the file transfer. The output should look like:
```
Time remaining: 03:12 (meaning it's 3 minutes and 12 seconds left)
Time remaining: 123:12 (meaning it's 2 hours, 3 minutes and 12 seconds left)
Time remaining: 02:03:12 (optional output, meaning the same as above)
```
Leading zeros need not be displayed for minutes and hours (optional), but must be shown for seconds. Showing the time remaining using only seconds is not OK.
**The file transfer:**
* The transfer rate will start at 10 MB/second.
* Every second, there will be a 30% chance that the transfer rate will change
* The new transfer rate should be picked randomly (uniform distribution) in the range `[10 kB/s, 100 MB/s]`, in steps of 10 kB/s.
**Note: You don't need to actually copy a file.**
You may choose to use: `1 GB = 1000 MB, 1 MB = 1000 kB, 1 kB = 1000 B`, or `1 GB = 1024 MB, 1 MB = 1024 kB, 1 kB = 1024 B`.
**Output:**
* You start at `01:40`, not `01:39`.
* You display the time after the transfer rate changes, but before anything is transferred at that rate
* The seconds should be displayed as integers, not decimals. It's optional to round up/down/closest.
* You should clear the screen every second, unless that's impossible in your language.
* The output should be constant: `Time remaining: 00:00` when the file transfer is over.
**Example:**
I have rounded up all decimal seconds.
Assume the lines below are shown with 1 second in between, and the screen is cleared between each one:
```
Time remaining: 01:40 (Transfer rate: 10 MB/s)
Time remaining: 01:39 1 GB - 10 MB
Time remaining: 01:38 1 GB - 2*10 MB
Time remaining: 01:37 1 GB - 3*10 MB
Time remaining: 01:28:54 1 GB - 4*10 MB (TR: 180 kB/s)
Time remaining: 01:28:53 1 GB - 4*10 MB - 180 kB
Time remaining: 01:28:52 1 GB - 4*10 MB - 2*180 kB
Time remaining: 00:13 1 GB - 4*10 MB - 3*180 kB (TR: 75 MB/s)
Time remaining: 00:12 1 GB - 4*10 MB - 3*180 kB - 75 MB
Time remaining: 00:11 1 GB - 4*10 MB - 3*180 kB - 2*75 MB
Time remaining: 00:10 1 GB - 4*10 MB - 3*180 kB - 3*75 MB
Time remaining: 00:09 1 GB - 4*10 MB - 3*180 kB - 4*75 MB
Time remaining: 00:08 1 GB - 4*10 MB - 3*180 kB - 5*75 MB
Time remaining: 14:09:06 1 GB - 4*10 MB - 3*180 kB - 6*75 MB (TR: 10 kB/s)
Time remaining: 14:09:05 1 GB - 4*10 MB - 3*180 kB - 6*75 MB - 10 kB
Time remaining: 00:06 1 GB - 4*10 MB - 3*180 kB - 6*75 MB - 20 kB (TR: 88.110 MB/s)
Time remaining: 00:05
Time remaining: 00:04
Time remaining: 00:03
Time remaining: 00:02
Time remaining: 00:01
Time remaining: 00:00 <- Transfer is finished. Display this.
```
[Answer]
# Pyth - ~~70~~ 68 bytes
```
K^T5J^T3W>KZ%." r3úBTê;¥
í".D/KJ60=J?<OT3O^T4J=-KJ.d1.
```
[Try it online without sleeps](http://pyth.herokuapp.com/?code=K%5ET5J%5ET3W%3EKZ%25.%22+r%04%1B%133%C2%92%17%C3%BABT%C3%AA%C2%9A%C3%AE%C2%A2%C2%97%0F%C2%A4%3B%C2%A5%0A%01%C3%AD%05%14%22.D%2FKJ60%3DJ%3F%3COT3O%5ET4J%3D-KJ&debug=0).
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), ~~190~~ ~~215~~ 187 bytes
```
($t="Time remaining: ")+"00:01:42";for($f,$r=1gb,10mb;$f-gt0;$f-=$r){if((Random 10)-lt3){$r=(Random -mi 1kb -ma (10mb+1))*10}$t+[Timespan]::FromSeconds([int]($f/$r));sleep 1}$t+"00:00:00"
```
[Try it online!](https://tio.run/nexus/powershell#NU69CsMgGHwVEQdtIvVrOxmy9gHabiGDSUwqjRqMW@hjd061UDg4OO5vpyTW@GGsRkFbZZxxk0SYFVgIKUBeTrgafaBkLEmoYepKELaryMinKDLVJLDNjJTelBu8RSAYn@OZbcn@17g1CF5dYoVozhfA2AHEm8Siydvrolwr5TV4e9e9d8NKG@Nim2aPqZ9V66z1giAHfscy8L5/nOe96p/6Cw "PowerShell – TIO Nexus") (TIO doesn't support clearing screen between lines)
Sets our initial `$f`ile size and our initial transfer `$r`ate to `1gb` and `10mb`/s, respectively. Then, so long as we still have `$f`ile remaining, we loop.
Inside the loop, the `if` selects a number from `0` to `9` inclusive, and if it's 0, 1, or 2 (i.e., 30% of the time), we change the rate. This picks a random integer between `1kb` and `10mb` then that's multiplied by `10` to get our step count.
We then leverage the `FromSeconds` [static method](https://technet.microsoft.com/en-us/library/system.timespan.fromseconds(v=VS.85).aspx) from the `TimeSpan` .NET library to construct the time remaining. The output format of that call exactly matches the challenge requirements, so no need for additional formatting.
*(Saved a bunch thanks to @ConnorLSW)*
[Answer]
# Ruby, ~~116~~ 110 bytes
[Try it online, except repl.it reads `\r` as a newline and also can't use `$><<` so it's replaced with its 5-byte equivalent, `print`.](https://repl.it/F56D)
Shoutout to JonasWielicki for the initial idea of using `\r` to reset the line.
```
f=1e5;r=1e3;(k=f/r=rand<0.3?1+rand(1e4):r;$><<"\rTime remaining: %02d:%02d"%[k/60,k%60];f-=r;sleep 1)while f>0
```
This version is untested on Windows, but works on Unix.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 78 bytes
*Thanks to [@Maltysen](https://codegolf.stackexchange.com/users/31343/maltysen) and [@DigitalTrauma](https://codegolf.stackexchange.com/users/11259/digital-trauma) for corrections.*
```
1e5 1e3`XK10&XxyXIy/t0>*12L/'MM:SS'XO'Time remaining: 'whD-r.3<?1e4Yr}K]I0>]xx
```
Try it at [MATL Online!](https://matl.io/?code=1e5+1e3%60XK10%26XxyXIy%2Ft0%3E%2a12L%2F%27MM%3ASS%27XO%27Time+remaining%3A+%27whD-r.3%3C%3F1e4Yr%7DK%5DI0%3E%5Dxx&inputs=&version=19.7.4) (you may need to press "Run" several times if it doesn't initially work).
The online interpreter times out after 30 seconds. You may want to change `10` (pause time in tenths of second) to something smaller [such as `3`](https://matl.io/?code=1e5+1e3%60XK3%26XxyXIy%2Ft0%3E%2a12L%2F%27MM%3ASS%27XO%27Time+remaining%3A+%27whD-r.3%3C%3F1e4Yr%7DK%5DI0%3E%5Dxx&inputs=&version=19.7.4) in order to increase speed of display
### Explanation
```
1e5 % Push 1e5: file size in 10-kB units
1e3 % Push 1e3: initial rate in 10-kB/s units
` % Do...while
XK % Copy current rate into clipboard K (doesn't consume it)
10&Xx % Wait 1 second and clear screen
y % Duplicate current file size onto the top of the stack
XI % Copy it to clipboard I (doesn't consume it)
y % Duplicate current rate onto the top of the stack
/ % Divide. This gives the estimated remaining time in seconds
% It may be negative in the last iteration, because the
% "remaining" file size may have become negative
t0>* % If negative, convert to 0
12L/ % Push 86400 and divide, to convert from seconds to days
'MM:SS'XO % Format as a MM:SS string, rounding down
'Time remaining: ' % Push this string
wh % Swap, concatenate
D % Display
- % Subtract. This gives the new remaining file size
r % Push random number uniformly distributed in (0,1)
.3< % Is it less than 0.3?
? % If so
1e4Yr % Random integer between 1 and 1e4. This is the new rate
% in 10-kB/s units
} % Else
K % Push rate that was copied into clipboard K
] % End
I % Push previous remaining file size from clipboard I
0> % Is it positive?
] % End. If top of the stack is true: next iteration
xx % Delete the two numbers that are on the stack
```
[Answer]
# Bash + common utils, 117
Straightforward implementation. A few bytes saved by dividing out by 10000:
```
for((b=10**5,r=1000;b>0;r=RANDOM%10<3?RANDOM%10000+1:r,b-=r));{
clear
date -ud@$[b/r] "+Time remaining: %T"
sleep 1
}
```
[Try it online](https://tio.run/nexus/bash#@5@WX6ShkWRraKClZapTBKQNDKyT7Aysi2yDHP1c/H1VDQ1sjO3hbCDQNrQq0knStS3S1LSu5krOSU0s4kpJLElV0C1NcVCJTtIvilVQ0g7JzE1VKErNTczMy8xLt1JQDVHiKs5JTS1QMOCq/f//a16@bnJickYqAA). Using `sleep 0` on the TIO so you don't have to wait. `clear` doesn't work on TIO.
[Answer]
# JavaScript (ES6), 162 bytes
Shows minutes as is with padded seconds (floored)
E.g., `123:45`
```
t=1e5
s=1e3
setInterval(c=>c.log(`Time remaining: ${c.clear(d=t/s),d/60|0}:`+`0${t-=s>t?t:s,r=Math.random,s=r()<0.3?1+r()*1e4|0:s,d%60|0}`.slice(-2)),1e3,console)
```
[Answer]
# Python 3.6 (~~212~~ 203 bytes)
```
from random import*
import time,datetime
r=1e7
d=1e9
while 1:
print(f"\x1b[KTime remaining: {datetime.timedelta(seconds=d//r)}",end="\r");d=max(0,d-r);time.sleep(1)
if random()>.7:r=randint(1,1e4)*1e4
```
Pretty straightforward, I think. Erases the line using ANSI escape sequence and `K` command.
* Saved 9 bytes thanks to [@ValueInk](https://codegolf.stackexchange.com/questions/108976/copy-a-file-windows-style/109026?noredirect=1#comment265544_109026)
[Answer]
## Batch, 193 bytes
```
@set/ap=10000,s=p*10,r=p/10
:l
@set/at=s/r,m=t/60,n=t%%60+100,s-=r
@cls
@echo Time remaining: %m%:%n:~1%
@timeout/t>nul 1
@if %random:~-1% lss 3 set/ar=%random%%%p+1
@if %t% gtr 0 goto l
```
Note: Slight bias towards rates of 27.68 MB/s or less.
[Answer]
## C ~~184~~ ~~171~~ 155 bytes
```
f(){i,j=0,r=1e7;for(i=1e9;i>0;i-=r){j=i/r;printf("Time remaining: %02d:%02d:%02d\r",j/3600,(j/60)%60,j%60);sleep(1);if(rand()%10<3)r=(rand()%10000)*1e4;}}
```
I hope this qualifies.
Ungolfed version:
```
void f()
{
int j=0;
float rate=1e7;
for(int size=1e9;i>0; size-=rate)
{
j=size/rate;
printf("Time remaining: %02d:%02d:%02d\r",j/3600,(j/60)%60,j%60);
sleep(1);
if(rand()%10<3)
rate=(rand()%10000)*1e4;
}
}
```
Explanation: In the golfed version `i` corresponds to `size` in ungolfed version and `r` is `rate` in ungolfed version. `j` stores the time remaining in seconds.
* I have 10^9 bytes to copy. I start copying at the rate of 10 Megabytes/second,
* If the probablity is less than 30% , change the rate (from 10 kilobytes to 100 Megabytes per second)
@ValueInk Thanks for saving 13 bytes.
@nmjcman101 Thanks for saving 16 bytes.
] |
[Question]
[
## Background
You awake to find yourself lost in a one dimensional labyrinth! A mystical genie (or something) appears and explains that the exit lies in front of you, but that between you and the exit is a series of challenges. As you wander forward you realize that all of the so-called *challenges* are merely locked doors. You first see a door with a tee-shaped key-hole, and having no such key yourself, retrace your steps, looking for a key with a `T` shape.
Frustrated, you find an alphabet soup of keys on the ground, none of which match the door you've come across. By some stroke of genius (or idiocy), you decide that the lower-case `t`-shaped key might be able to fit in the slot if you jam it in there hard enough. As you approach the door with the lower-case `t` key in hand, the `T` hole glows green and the door dissolves in front of you.
One down, many more to go...
## Challenge
The goal of this challenge is to mark how many steps it takes you to exit the labyrinth.
The input of this challenge is the labyrinth: one string containing only characters `[A-Za-z^$ ]`.
Glossary:
* `^` -- The start space. The input will contain exactly one `^`.
* `$` -- The exit (freedom!). The input will contain exactly one `$`.
* `[A-Z]` -- Capital letters signify doors. You can only go through this door if you have already collected the requisite key.
* `[a-z]` -- Lower case letters signify keys. You collect these keys by walking onto the space that contains the key.
There will be at most one of each capital letter in the input. This means the total number of doors will be between 0-26 inclusive.
Every locked door `[A-Z]` will have exactly one corresponding lower case key `[a-z]`. There may be any number of spaces () in the input.
All of the doors will be to the right of the start, and to the left of the exit. Thus there will be no superfluous doors. All inputs will be solvable.
The output for this challenge will be a number, the number of steps it took to exit the labyrinth.
## Algorithm
Your methodical approach to exiting this wretched place is as follows:
* Start at the beginning (`^`) and move forward (right) collecting any keys you come across.
* When you come across a door, if you have the correct key, you proceed forward onto the door. If you don't have the correct key, you walk backwards (left) collecting keys you come across until you find the key for the most recent door that you couldn't open.
* Once you collect the key for the current troublesome door, you turn back to the right and proceed onward.
* Repeat this process until you step on to the exit (`$`).
Experienced golfers will understand that your code doesn't have to implement this specific algorithm as long as it outputs the same result as if you had run this algorithm.
## Counting
Each time you step from one square onto another square, that counts as one step. Turning 180º incurs no additional step. You cannot step forward onto a door without the requisite key. You must step onto a key to pick it up, and must step onto the exit to win. After your first move, the start space (`^`) behaves just like any other regular space.
## Examples
In these examples I've left the spaces as underscores for human-readability.
Input is `_a_^_A__$__`. The output is `11`. You take `1` step forward, notice that you have no key for the `A` door, and then about face. You walk backward until you occupy the space containing the `a` (`3` steps backward, now `4` total). You then walk forward until you occupy the space containing the exit (`7` steps forward, `11` total).
Input is `b__j^__a_AJB_$`. The output is `41` You make two separate trips to the back of the labyrinth, one to get the `j` key, and the next one to get the `b` key.
Input is `__m__t_^__x_T_MX_$____`. The output is `44`. You won't make any extra trip to get the `x` key, as you picked it up on your way from the start to door `T`.
Input is `g_t_^G_T$`. The output is `12`. You cannot move onto the `G` space without a key, and immediately about-face. You're lucky enough to pick up the `t` key on the way to the `g` key, and thus open both doors on your way to freedom.
Input is `_^_____$`. The output is `6`. That was easy.
## I/O Guidelines and Winning Criterion
Standard I/O rules apply. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge.
[Answer]
# Pyth, 51 bytes
```
JxQ"^"K-xQ"$"JVQI&}NrG1>JxQrN0=JxQrN0=+K*2t-xQNJ;pK
```
sum the distance between the door and its key (doubled, to take the round trip), ignoring the "nested" keys and the distance from the start to the end:
```
JxQ"^" #Initialize the farther point with the starting position
K-xQ"$"J #Initialize the step counter with the difference between the exit and the start
VQ #iterate over the input
I&}NrG1>JxQrN0 #check if is upper and if the keys is father than one stored (to eliminate nested keys)
=JxQrN0 #update the farther key
=+K*2t-xQNJ; #update step counter with the round trip door<>key
pK #print the step counter
```
same algorythm in python2.7 :
```
lab=raw_input()
farther_key=lab.index('^')
steps = lab.index('$') - farther_key
for i in lab:
if i.isupper():
if farther_key> lab.index(i.lower()):
farther_key=lab.index(i.lower())
steps+=((lab.index(i) - farther_key)-1)*2
print steps
```
[Answer]
# Python 2, ~~155~~ ~~154~~ ~~134~~ 128 bytes
Edit: Thanks to @user2357112 and @loovjo for their comments that helped me shave another ~~20~~ 26 bytes off my solution!
```
def f(l):
i=l.index;b=i('^');t=i('$')-b
for d in filter(str.isupper,l):
k=i(d.lower())
if k<b:b=k;t+=2*(i(d)-k-1)
print t
```
[Answer]
# C, 136 bytes
```
q,x,p[300],z,c,k;main(i){for(;p[c=getchar()]=++i,c-36;z&&(k+=(x=p[c+32])&&x<q?(q=q>x?x:q,2*i-2*x-1):1))z=p[94],q||(q=z);printf("%d",k);}
```
[Answer]
# PHP 5.3, 123 bytes
This is my first post on Code Golf, hopefully this is of golfing quality high enough for a first post. Definitely a fun challenge and an awesome question!
```
function n($m){while('$'!=$o=$m[$i++])$o=='^'?$b=$i+$c=0:$o>'Z'||$b<=$k=stripos($m,$o))?$c++:$c+=2*$i-3-2*$b=$k;return$c;}
```
This program nicely abuses the fact that PHP doesn't need you to pre-declare any variables before you use them.
It also turned out to be a couple bytes shorter in my final solution to start at 0 and reset the step count when the start character is found, rather than starting at the '^'.
Any tips are definitely welcome!
[Answer]
# CJam, 45
```
1q_'$#<'^/~\W%:A;ee{~32+A#)_T>{:T+2*+}&]0=)}/
```
[Try it online](http://cjam.aditsu.net/#code=1q_'%24%23%3C'%5E%2F~%5CW%25%3AA%3Bee%7B~32%2BA%23)_T%3E%7B%3AT%2B2*%2B%7D%26%5D0%3D)%7D%2F&input=g_t_%5EG_T%24)
**Explanation:**
```
1 initial step count; this 1 is actually for the last step :)
q_'$#< read the input and only keep the part before the '$'
'^/~ split by '^' and dump the 2 pieces on the stack
\W%:A; take the first piece, reverse it and store it in A
ee enumerate the other piece (making [index char] pairs)
{…}/ for each [index char] pair
~32+ dump the index and character on the stack, and add 32 to the character;
uppercase letters become lowercase and other chars become garbage
A#) find the index of this character in A and increment it (not found -> 0)
_T> check if this index (number of steps from '^' back to the key)
is greater than T (which is initially 0)
{…}& if that's true (we need to go back), then
:T store that index in T (keeping track of how far we go back before '^')
+ add to the other index (from the pair, number of steps we took after '^')
2* double the result (going back and forth)
+ add it to the step count
]0= keep only the first value from the bottom of the stack (step count)
(if the condition above was false, we'd have 2 extra values)
) increment the step count (for the current step)
```
[Answer]
## JavaScript (ES6), 110 bytes
```
s=>(i=c=>s.indexOf(c),p=i`^`,l=i`$`-p,s.replace(/[A-Z]/g,(c,j)=>p>(t=i(c.toLowerCase()))?l+=j-(p=t)-1<<1:0),l)
```
Port of @Rob's Pyth answer.
[Answer]
# Python 2.7, ~~234~~ ~~199~~ 179
```
a=raw_input()
x=a.index
v=x('^')
b=x('$')-v
l=filter(str.islower,a[:v])[::-1]
for i in filter(str.isupper,a):
k=i.lower()
if k in l:b+=(x(i)-x(k)-1)*2;l=l[l.index(k)+1:]
print b
```
[Answer]
## AWK, 174 Bytes
```
func f(xmS){x+=S
c=a[x]
if(c~/^[A-Z]/&&!k[c]){C=c
S=-S
s--}else{c=toupper(c)
k[c]=1
s++
if(c==C){S=-S;C=9}}if(c=="$"){print s}else f(x,S)}{split($0,a,"")
f(index($0,"^"),1)}
```
There's probably a tighter algorithm, but this is what I came up with.
Do note that I'm using `gawk`. Some implementations of `AWK` may not split a string on `""` this way.
[Answer]
# C#, 309 bytes
```
class P{static void Main(string[]a){string m=Console.ReadLine(),k="";var f=true;char b,c=b=' ';int j=m.IndexOf('^'),t=0;for(;m[j]!='$';j+=f?1:-1){c=m[j];if(char.IsUpper(c)){if(k.IndexOf(char.ToLower(c))<0){f=!f;b=c;t--;}}if(char.IsLower(c)){k+=c;if(char.ToUpper(c)==b){f=!f;t--;}}t++;}Console.WriteLine(t);}}
```
Ungolfed version:
```
class P
{
static void Main(string[] a)
{
string m = Console.ReadLine(), k = "";
var f = true;
char b, c = b = ' ';
int j = m.IndexOf('^'), t = 0;
for (; m[j] != '$'; j += f ? 1 : -1)
{
c = m[j];
if (char.IsUpper(c))
{
if (k.IndexOf(char.ToLower(c)) < 0)
{
f = !f; b = c; t--;
}
}
if (char.IsLower(c))
{
k += c;
if (char.ToUpper(c) == b) { f = !f; t--; }
}
t++;
}
Console.WriteLine(t);
Console.ReadKey();
}
}
```
Nothing fancy here, just iterate through the string and change direction based on the character and whether the key is contained in a keys string.
m = the maze string
k = the keys string
f = the direction (true is forward in the maze)
b = the key to search for when backtracking
c = placeholder for m[j] to save some bytes due to frequent use
j = the char index of the string to look at
t = the count
Still relatively new to golfing so if you see somewhere I can slim it down, let me know!
] |
[Question]
[
Ah, Tinder . . . the app that takes the code golf approach to online dating. With just a few well-chosen right swipes and a bit of luck (or a cute puppy pic), you too could have more matches than [/(?!)/](https://codegolf.stackexchange.com/a/18446/92901).
This [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge involves Tinder dates of a very different kind. Given a Tinder version number as input, hook me up with the date on which that version was released. You may use any convenient formats for input and output (e.g. string, list of integers, date object). Refer to this table\*:
```
+-------------+--------------+
| **Version no.** | **Release date** |
+-------------+--------------+
| 11.19.0 | 2020-07-10 |
| 11.18.0 | 2020-06-18 |
| 11.17.0 | 2020-06-04 |
| 11.16.0 | 2020-05-26 |
| 11.15.0 | 2020-05-11 |
| 11.14.0 | 2020-04-27 |
| 11.13.0 | 2020-04-13 |
| 11.12.0 | 2020-03-27 |
| 11.11.1 | 2020-03-21 |
| 11.11.0 | 2020-03-20 |
| 11.10.4 | 2020-03-06 |
| 11.10.3 | 2020-03-02 |
| 11.10.2 | 2020-02-29 |
| 11.10.1 | 2020-02-28 |
| 11.9.0 | 2020-02-13 |
| 11.8.0 | 2020-01-30 |
| 11.7.2 | 2020-01-24 |
| 11.7.1 | 2020-01-20 |
| 11.7.0 | 2020-01-19 |
| 11.6.1 | 2020-01-04 |
| 11.6.0 | 2019-12-16 |
| 11.5.0 | 2019-12-06 |
| 11.4.0 | 2019-11-22 |
| 11.3.0 | 2019-11-10 |
| 11.2.1 | 2019-11-01 |
| 11.1.1 | 2019-10-16 |
| 11.1.0 | 2019-10-11 |
| 11.0.2 | 2019-10-09 |
| 11.0.1 | 2019-09-27 |
| 11.0.0 | 2019-09-20 |
| 10.20.0 | 2019-09-10 |
| 10.19.1 | 2019-09-03 |
| 10.19.0 | 2019-08-28 |
| 10.18.0 | 2019-08-15 |
| 10.17.0 | 2019-07-24 |
| 10.16.0 | 2019-06-24 |
| 10.15.1 | 2019-06-08 |
| 10.15.0 | 2019-06-05 |
| 10.14.0 | 2019-06-04 |
| 10.13.0 | 2019-05-16 |
| 10.12.1 | 2019-05-02 |
| 10.12.0 | 2019-04-28 |
| 10.11.0 | 2019-04-13 |
| 10.10.1 | 2019-04-10 |
| 10.10.0 | 2019-04-02 |
| 10.9.1 | 2019-03-23 |
| 10.9.0 | 2019-03-18 |
| 10.8.1 | 2019-03-15 |
| 10.8.0 | 2019-03-06 |
| 10.7.0 | 2019-02-16 |
| 10.6.0 | 2019-02-12 |
| 10.5.0 | 2019-01-22 |
| 10.4.1 | 2019-01-08 |
| 10.4.0 | 2018-12-17 |
| 10.3.0 | 2018-11-29 |
| 10.2.1 | 2018-11-20 |
| 10.2.0 | 2018-11-15 |
| 10.1.1 | 2018-11-02 |
| 10.1.0 | 2018-10-31 |
| 10.0.2 | 2018-10-25 |
| 10.0.1 | 2018-10-19 |
| 10.0.0 | 2018-10-17 |
| 9.9.2 | 2018-10-12 |
| 9.9.1 | 2018-10-11 |
| 9.9.0 | 2018-10-09 |
| 9.8.1 | 2018-10-03 |
| 9.8.0 | 2018-09-21 |
| 9.7.2 | 2018-09-14 |
| 9.7.1 | 2018-09-06 |
| 9.7.0 | 2018-08-29 |
| 9.6.1 | 2018-08-23 |
| 9.6.0 | 2018-08-21 |
| 9.5.0 | 2018-08-06 |
| 9.4.1 | 2018-08-03 |
| 9.4.0 | 2018-07-24 |
| 9.3.0 | 2018-06-22 |
| 9.2.0 | 2018-06-11 |
| 9.1.0 | 2018-05-29 |
| 9.0.1 | 2018-05-17 |
| 9.0.0 | 2018-05-14 |
| 8.13.0 | 2018-05-03 |
| 8.12.1 | 2018-04-28 |
| 8.12.0 | 2018-04-26 |
| 8.11.0 | 2018-04-12 |
| 8.10.0 | 2018-04-05 |
| 8.9.0 | 2018-03-15 |
| 8.8.0 | 2018-02-28 |
| 8.7.0 | 2018-02-16 |
| 8.6.0 | 2018-02-05 |
| 8.5.0 | 2018-01-22 |
| 8.4.1 | 2018-01-02 |
| 8.4.0 | 2017-12-15 |
| 8.3.1 | 2017-12-08 |
| 8.3.0 | 2017-11-29 |
| 8.2.0 | 2017-11-03 |
| 8.1.0 | 2017-10-17 |
| 8.0.1 | 2017-10-09 |
| 8.0.0 | 2017-09-25 |
| 7.8.1 | 2017-09-08 |
| 7.8.0 | 2017-09-05 |
| 7.7.2 | 2017-08-23 |
| 7.7.1 | 2017-08-15 |
| 7.7.0 | 2017-08-14 |
| 7.6.1 | 2017-07-24 |
| 7.6.0 | 2017-07-14 |
| 7.5.3 | 2017-06-22 |
| 7.5.2 | 2017-06-09 |
| 7.5.1 | 2017-06-02 |
| 7.5.0 | 2017-05-30 |
| 7.4.1 | 2017-05-17 |
| 7.4.0 | 2017-05-09 |
| 7.3.1 | 2017-04-19 |
| 7.3.0 | 2017-04-13 |
| 7.2.2 | 2017-04-03 |
| 7.2.1 | 2017-04-01 |
| 7.2.0 | 2017-03-30 |
| 7.1.1 | 2017-03-16 |
| 7.1.0 | 2017-03-06 |
| 7.0.1 | 2017-02-19 |
| 7.0.0 | 2017-02-16 |
| 6.9.4 | 2017-02-06 |
| 6.9.3 | 2017-01-27 |
| 6.9.2 | 2017-01-25 |
| 6.9.1 | 2017-01-17 |
| 6.9.0 | 2017-01-12 |
| 6.8.1 | 2017-01-03 |
| 6.8.0 | 2016-12-19 |
| 6.7.0 | 2016-11-30 |
| 6.6.1 | 2016-11-18 |
| 6.6.0 | 2016-11-16 |
| 6.5.0 | 2016-11-07 |
| 6.4.1 | 2016-11-01 |
| 6.4.0 | 2016-10-26 |
| 6.3.2 | 2016-10-19 |
| 6.3.1 | 2016-10-12 |
| 6.3.0 | 2016-10-04 |
| 6.2.0 | 2016-09-27 |
| 6.1.0 | 2016-09-20 |
| 5.5.3 | 2016-09-12 |
| 5.5.2 | 2016-09-08 |
| 5.5.1 | 2016-09-03 |
| 5.5.0 | 2016-08-31 |
| 5.4.1 | 2016-08-25 |
| 5.4.0 | 2016-08-18 |
| 5.3.2 | 2016-07-29 |
| 5.3.1 | 2016-07-21 |
| 5.3.0 | 2016-07-19 |
| 5.2.0 | 2016-06-27 |
| 5.1.1 | 2016-06-07 |
| 5.1.0 | 2016-06-06 |
| 5.0.2 | 2016-05-13 |
| 5.0.1 | 2016-04-29 |
| 5.0.0 | 2016-04-21 |
| 4.8.2 | 2016-03-02 |
| 4.8.1 | 2016-01-30 |
| 4.8.0 | 2016-01-27 |
| 4.7.2 | 2015-12-17 |
| 4.7.1 | 2015-11-13 |
| 4.7.0 | 2015-11-11 |
| 4.6.1 | 2015-09-23 |
| 4.6.0 | 2015-09-04 |
| 4.5.0 | 2015-07-07 |
| 4.4.6 | 2015-05-18 |
| 4.4.5 | 2015-05-12 |
| 4.4.4 | 2015-05-05 |
| 4.4.3 | 2015-04-28 |
| 4.4.1 | 2015-04-16 |
| 4.4.0 | 2015-04-15 |
| 4.3.0 | 2015-03-02 |
| 4.1.4 | 2015-02-13 |
| 4.1.3 | 2015-02-06 |
| 4.1.1 | 2015-02-02 |
| 4.0.9 | 2014-10-09 |
| 4.0.8 | 2014-09-27 |
| 4.0.7 | 2014-09-19 |
| 4.0.6 | 2014-09-18 |
| 4.0.4 | 2014-07-17 |
| 4.0.3 | 2014-06-26 |
| 4.0.2 | 2014-06-17 |
| 4.0.1 | 2014-06-06 |
| 4.0.0 | 2014-06-05 |
| 3.0.4 | 2014-03-12 |
| 3.0.3 | 2014-02-26 |
| 3.0.2 | 2013-12-19 |
| 3.0.1 | 2013-11-28 |
| 3.0.0 | 2013-11-21 |
| 2.2.3 | 2013-11-20 |
| 2.2.2 | 2013-09-25 |
| 2.2.1 | 2013-09-24 |
| 2.2.0 | 2013-09-14 |
| 2.1.1 | 2013-06-07 |
| 2.1.0 | 2013-05-23 |
| 2.0.3 | 2013-04-01 |
| 2.0.2 | 2013-03-29 |
| 2.0.1 | 2013-03-28 |
| 1.1.4 | 2013-02-08 |
| 1.1.3 | 2013-02-06 |
| 1.1.2 | 2013-01-21 |
| 1.1.1 | 2013-01-11 |
| 1.1.0 | 2013-01-08 |
| 1.0.6 | 2012-11-24 |
| 1.0.5 | 2012-11-16 |
| 1.0.4 | 2012-11-06 |
| 1.0.3 | 2012-09-20 |
| 1.0.2 | 2012-08-29 |
| 1.0.1 | 2012-08-15 |
| 1.0.0 | 2012-08-03 |
+-------------+--------------+
```
\*[Source](https://sensortower.com/ios/au/tinder-inc/app/tinder/547702041/overview), with four modifications to unify the version number format (1.03 → 1.0.3, 4.3 → 4.3.0, 4.4 → 4.4.0, iOS 8.4.0 → 8.4.0).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~527 ... 498~~ 493 bytes
Expects the version in the format described in the challenge. Returns a stringified Date object.
```
v=>"W302o288qB$87LB38R8gXL7x3egzBX9wW*2ec62od1X<H2eX8wX$30iiXL*Y398dXX<**Z7dab1u7jR6g67L447b$2o4lX2l29R$2l*[L`1o!++$*+Z[IR311v3eI`$RBAL3fB2pRRCZ2l$2vL*2u29B2fX$2vL252o%2755H+202l2p=313f2f+2pR1j;L312v=45BM3fR[$$+30[RX_RZ[R2v`I21282p2f1p21HM`C$M3f1o2p1vYL393l292vZ+A*30S`36I312pC1u3fX1o[2p3cXR1o2pX[272p2p3fI2p29".replace(/[\da-z]?./g,s=>(n=(s[1]?parseInt(s,36):Buffer(s)[0]-32-10*(s>'9'))^46,d-=~(n/6),n%=6,y=++n&4?z=++x-x:y,z=(n&2?!++y:z)+n%2,v==x+`.${y}.`+z?new Date(d*864e5):''),x=0,d=15554)
```
[Try it online!](https://tio.run/##PVVdc9pIEPwrPgoHCYHQzH7KF9kVfFdlqsiL7iGKie8gIPnsopBibGyTyv11n@hd/NIzOzvb3SNql/vFbrFdPtw1j8NNvSrfquxtl513voiEa7b2x7hrzXQsbG5vi6l5EeXtflykz1/6XC411ysqPl5xWdjnoiuSu7ti2v8qUrsqio/9/rVZLb7Tk7nP9a02UynN9y7Xcl3wmtO8y@v@bDqn@rco6vaj69kkF0Q7UU7m3Xz8aSqqMTd5fnnN6y7vpn1@4nTMVXFYsOL6lI1SVxEnLVuTCRIVV1F7gu5/nwriXSbV@LOo8lm3G4lklhf/5NeznHfzCRNbbriihunq8/yy27ZRzQ3tvk5FKlpzvLuOPvVF8tdc6ElL1lzSk6gKqmfciGWRH7qLGZuWpRHVpA1pJ34om/ViWQaj2bfVYri/uYhHt4Ntdh5ssmA7o5uLZvGwLSebx2A7EDo8Gz9VVfkQbMNZcjMUPKSkH2zPe2kvDP@WerAaZv8Fm5EOB5vTTA9esyjafJAX@za@DF/OXgf7LNh84Iv2872e7cNoc8qDXZa9RPO4@/P1VzyP9heb8vnkj8VjGaz6VstShWe9Xjh4yZLBKiOllAzfOhQncTI6IAEZKIASqIC6RUInoZPQSeiktpPBwGBgMDD6Gf0cM3L2OQPFSEBd4KzAWYGzAuoSuxK7ErsSu/J9VwMN0ALTFgn9hE5CpwCP9EhAAZRABTywKfRoj4dOg9z4/ODBomJRsW1FwaeCTwWfCrMrOFGYXcHDAQl46JGoSFQUcuVzBoqRBo8GgwaDBoMGgwaDBoMGg4ZzDecazjXcarjVcYo89TkDBVCODKYwmMJA18C/gbrBb2fw2xk4MXBi4MHAg4EHgykMpjCYwsCVgSsDVwbf0@B7Gjg0cGjhwcKDhQcLdQtFC0ULRQtFC0ULfgtmCzaLSVsGR0eOifgYwH6gTCGYQjCFYArBNHa70uNhVyHXHg8Vg9z4nFu0qFhUUuSpz9vrkri7lrjLlrjblrhrlbh7lUAdASvhVvIYUFRupV0wLthjQEvqVqlbkdclL0xHSX6Pru7lyOuReo9u30uS1yQvSul7dDNAzz8t/m3xj4t/RfwzQm5OcnOSm5PcgOQGJHzrNhi3MscVyKwrpp7TK9FRCi8ZokQ8antxNz/5ucnPTX5u8vOSn5f8vIR5O/G2Wd89Bp1RJ4yr@uHPxfLfYHeSnZ8s6822Xpfxur5tC9FJ79tjrw1VsAvj7fqu/Y@QgxNSYRi@/Q8 "JavaScript (Node.js) – Try It Online")
### How?
Each version is stored as a number \$d\$ of days elapsed since the previous version and a 3-bit value \$m\$ describing how the version numbers `x.y.z` are updated. The final value is:
$$n=\big(6\times(d-1)+(m-1)\big)\operatorname{XOR}46$$
The purpose of the XOR is to maximize the number of small values.
Numbers \$0\$ to \$15\$ are encoded with a single character in the ASCII range `32-47`.
Numbers \$16\$ to \$54\$ are encoded with a single character in the ASCII range `58-96`.
All other numbers are encoded as a 2-digit number in base 36, using digits and lower case letters (ASCII ranges `48-57` and `97-122` respectively).
We use the regular expression `/[\da-z]?./g` to match either a 2-digit number in base-36 or a single character in the other ASCII ranges.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 519 517 493 bytes
```
lambda x,e=enumerate:((y:=sum(ord(i)-35for i in"/1:U-+Ó&-4%W#$'Y3\x8a-$^$*:ê5|$.,:#d$+1Ĝ##'*8#P$#/,*)X`6W%GÍ&GV+3<$7;%+8*)'('+#*,+***),%/8³,(+%.-&6-1&%-)9+0'*0;-9$+1&43+5=.*¶72./69*1%*.&/1.E.&2%),+*1)%$(%))&0(,7º19'9,&(.+&2)17$&3C:0**-*1%(4#,/3-·2$')22#$('1$)5132-1;#"[:[(n,m,k)for n,i in e('1p 7o 5 6fp23 2aqc 2jno0l mzkii f1qqnj2p 4r96mr srha04m2ix5d 3lfbiojllc95'.split(),1)for m,j in e('a'*(n==4)+oct(int(i,36))[2:])for k in range(int(j,16))].index(x)])+1030403)>>9,(y>>5)&15,y&31)
```
[Try it online!](https://tio.run/##dVLNctMwEL7nKTS1LWtl2dFKthO7OBeG6ZULFKaEwW0c6jT@qZN2En4egRNXnoArMzDDMeW9ghwopyLNarW73@7qk9Ru15dNrcdtt59nbL/Mq/NZTjaiyIr6piq6fF2kjG3TbHVTsaabsRJ8Hc2bjpSkrI@GmD7zvbvP1A@dU8t2X@pXm3Hu269tnt59jT7YgUitme3hry@W5fKx9dS2hoLDizfxqXNy94mePPf0I3t07HhjDi5zPYsLj3MOwhmOd98E85zAp7GP1PEh8aTL5bGfmII01F6UBXz3faSCYZxwdHhAhxg8CahywBRBcGzmAFDJxGj3ExM3EZQFHlWAI5vqx6nk3Dd5LLTEUPu7H8p2QSnLZi7aEKFWPh5bR2fpGatFJa6gp12LnjgpDKYlo4ZEJJ63ShOVX18QtagbuSTVu6uyJHO8vq4XqiVhl8RVR1bdZS7DSpWbaEb0cn5eNovl8iKJ3GDVLss1A4GHFpVY/G2Ru5zVWRaC11ysWVkbEToGOFPp9AC96oFdXr8tDtGFQBOdBmU9KzZsA1PwUGoZSg2TSSLYdjKJgGIktlQj7GFwmz3E7f7lmRuHRKMmIUlCKWOJShGFUhmXlEZJM0OCqBC1WQhKiUYOA2Vv9giFfVYP7sMH/Sdy8JqNkjK8T5P/u41/hyofZG6YwnTQdr0xeF@mc4Mj9/@U3H4cwP43 "Python 3.8 (pre-release) – Try It Online")
Compressor+ungolfed:
```
import re
import time
import calendar
import base64
import math
with open('207234.txt','rt') as f:
s=f.read()
matcher=re.compile(
re.sub(r'\d+',lambda m:r'(\d+)',
re.sub(r'(?:\\\ )+',lambda m:r'\s*',
re.escape((x:=s.split('\n'))[0])
)
)
)
assert len(x_:=matcher.findall(s))==sum(1 for i in x if i)
x_=[[int(j) for j in i] for i in x_][::-1]
v_=[tuple(i[:3]) for i in x_]
#for v in [(2, 0, 1),(11, 2, 1)][::-1]:
# i=v_.index(v)
# a,b,c,d,e,f=x_[i]
# x_=x_[:i]+[[a,b,c-1,d,e,f]]+x_[i:]
for n,v in (v_add:=[(1,(2, 0, 1)),
(0,(4, 0, 4)),
(1,(4, 1, 1)),
(0,(4, 1, 1)),
(2,(4, 3, 0)),
(0,(4, 4, 1)),
(2,(6, 1, 0)),
(1,(11, 2, 1)),
(1,(11, 10, 1))])[::-1]:
i=v_.index(v)
a,b,c,d,e,f=x_[i]
plus_i,plus_c,plus_b=[(1,1,0),(0,-1,0),(0,0,-1)][n]
x_=x_[:i+plus_i]+[[a,b+plus_b,c+plus_c,d,e,f]]+x_[i+plus_i:]
x=[[0]]
old_a,old_b,old_c=1,0,0
for a,b,c,d,e,f in x_:
if old_c!=c:
if old_a==a and old_b==b:
assert c==old_c+1# or (old_a,old_b,old_c) in [
#(4, 0, 4),(4, 1, 1),(4, 4, 1)]
x[-1][-1]+=(c-old_c>=0 and c-old_c or 1)
if old_b!=b:
if old_c==c:
assert c==0# or (a,b,c) in [(11, 2, 1)]
x[-1][-1]=1
x[-1].append(0)
if old_a!=a:
if old_b==b:
x[-1].append(0)
x.append([0])
old_a,old_b,old_c=a,b,c
x[-1][-1]+=1
v__=[(n,m,k) for n,i in enumerate(x,1)
for m,j in enumerate(i)
for k in range(j)]
assert set(v_)-set(v__)==set()
assert len(set(v__)-set(v_))==len(v_add)
versions=x
x=[d*512+e*32+f
for a,b,c,d,e,f in x_
]
x2=[i-j for i,j in zip(x[1:],x)]
ls2,d2,s2=min((len(repr(
s:=''.join(chr(k+l) for k in x2+[0])
).encode('utf-8')),l,s) for l in range(32,128))
print(ls2,d2)
s0=''.join(''.join(((str(j) if j else ' ') if j0 and base_n(x//n,n)+chr(48+x%n+(97-48-10)*(x%n>=10)) or ''
s0_=' '.join(base_n(int(i,8),36) for i in s0.split())
assert (s0==
' '.join(
#('a'*(n==4)+
oct(int(i,36))[2:]
#)
for n,i in enumerate(s0_.split(),1))
)
print(len(s0_))
f=(
#print(len(r'''
lambda x,e=enumerate:((
y:=sum(ord(i)-35 for i in s2[
:[(n,m,k)
for n,i in e(s0_.split(),1)
for m,j in e('a'*(n==4)+oct(int(i,36))[2:])
for k in range(int(j,16))].index(x)
])+1030403
)>>9,(y>>5)&15,y&31)
#''')-8-4*(7+5)-3)
)
assert all(f((a,b,c))==(d,e,f_) for a,b,c,d,e,f_ in x_)
```
[Answer]
# Javascript - 862 bytes
```
r=(v=>{for(p=[1,0,0],s=0,d="0cc0ec16c2fc0ac08c2db03c0ac10c02c30a00c01c03c34b0fc63b0ac01c38c01a07c15c45c0ec55a01c0bc09c15c3fc00c01c08c0cc74b00c04c00c07c11b00b2cb01c0cc00c07c07c06c32b3bb13c31b02c22c29b03c20c32a08c0ec18b01c14b16b02c08c14b07c06b03c05c04c08a00b07b07b08c07c07b06c06b09b02c0cb13b0fc09b05c08c02c0ac0aa03c0fb0ac0eb02c02c0ab06c14b08c0db03c07c0dc16b0ac15b01c08c0db03c11a0ec08b11b1ab09c07b12c14b0eb0bb0cb0fb15b07b0eb02c05b0ba03c0cb0db0bb20b0ac03b0fb02c06b08c08c07b0cc06b02c01c05a02c06c06b02c0db05c09b12b16c0eb15b04b12b09c03b05c0ab08c03b0fb04c0eb13b01b03c10b1eb16b0db06c07b0aa07c0cc02b05c10b00c09b0cb0eb0ab13c0fb01c04c06b0eb0fb00c01c02c04c0eb01c06b11b0eb0eb0fb09b0eb16b00c",i=0;;i+=3){if(p.join(".")==v)return new Date(1343952e6+864e5*s).toISOString().substr(0,10);s+=parseInt(d[i]+d[i+1],16),l=d[i+2],[a,b,c]=p,p='b'>l?[a+1,0,0]:'c'>l?[a,b+1,0]:[a,b,c+1]}})
```
## Explanation
The release dates are encoded as a difference of days. Each diff is represented by 3 characters in `d`. The first 2 characters indicate the number of days to the next version. The last character uses 'a','b', or 'c' to represent which part of the version changed, if the version number is considered as a.b.c .
As some versions skip over numbers (such as 11.1.1 to 11.2.1), missing releases were added, costing only 3 bytes each.
There's probably some additional compression possible with the data string but I wanted to keep it strictly ASCII.
```
const version_dates = {
'11.19.0':'2020-07-10',
'11.18.0':'2020-06-18',
'11.17.0':'2020-06-04',
'11.16.0':'2020-05-26',
'11.15.0':'2020-05-11',
'11.14.0':'2020-04-27',
'11.13.0':'2020-04-13',
'11.12.0':'2020-03-27',
'11.11.1':'2020-03-21',
'11.11.0':'2020-03-20',
'11.10.4':'2020-03-06',
'11.10.3':'2020-03-02',
'11.10.2':'2020-02-29',
'11.10.1':'2020-02-28',
'11.10.0':'2020-02-28',
'11.9.0':'2020-02-13',
'11.8.0':'2020-01-30',
'11.7.2':'2020-01-24',
'11.7.1':'2020-01-20',
'11.7.0':'2020-01-19',
'11.6.1':'2020-01-04',
'11.6.0':'2019-12-16',
'11.5.0':'2019-12-06',
'11.4.0':'2019-11-22',
'11.3.0':'2019-11-10',
'11.2.1':'2019-11-01',
'11.2.0':'2019-11-01',
'11.1.1':'2019-10-16',
'11.1.0':'2019-10-11',
'11.0.2':'2019-10-09',
'11.0.1':'2019-09-27',
'11.0.0':'2019-09-20',
'10.20.0':'2019-09-10',
'10.19.1':'2019-09-03',
'10.19.0':'2019-08-28',
'10.18.0':'2019-08-15',
'10.17.0':'2019-07-24',
'10.16.0':'2019-06-24',
'10.15.1':'2019-06-08',
'10.15.0':'2019-06-05',
'10.14.0':'2019-06-04',
'10.13.0':'2019-05-16',
'10.12.1':'2019-05-02',
'10.12.0':'2019-04-28',
'10.11.0':'2019-04-13',
'10.10.1':'2019-04-10',
'10.10.0':'2019-04-02',
'10.9.1':'2019-03-23',
'10.9.0':'2019-03-18',
'10.8.1':'2019-03-15',
'10.8.0':'2019-03-06',
'10.7.0':'2019-02-16',
'10.6.0':'2019-02-12',
'10.5.0':'2019-01-22',
'10.4.1':'2019-01-08',
'10.4.0':'2018-12-17',
'10.3.0':'2018-11-29',
'10.2.1':'2018-11-20',
'10.2.0':'2018-11-15',
'10.1.1':'2018-11-02',
'10.1.0':'2018-10-31',
'10.0.2':'2018-10-25',
'10.0.1':'2018-10-19',
'10.0.0':'2018-10-17',
'9.9.2':'2018-10-12',
'9.9.1':'2018-10-11',
'9.9.0':'2018-10-09',
'9.8.1':'2018-10-03',
'9.8.0':'2018-09-21',
'9.7.2':'2018-09-14',
'9.7.1':'2018-09-06',
'9.7.0':'2018-08-29',
'9.6.1':'2018-08-23',
'9.6.0':'2018-08-21',
'9.5.0':'2018-08-06',
'9.4.1':'2018-08-03',
'9.4.0':'2018-07-24',
'9.3.0':'2018-06-22',
'9.2.0':'2018-06-11',
'9.1.0':'2018-05-29',
'9.0.1':'2018-05-17',
'9.0.0':'2018-05-14',
'8.13.0':'2018-05-03',
'8.12.1':'2018-04-28',
'8.12.0':'2018-04-26',
'8.11.0':'2018-04-12',
'8.10.0':'2018-04-05',
'8.9.0':'2018-03-15',
'8.8.0':'2018-02-28',
'8.7.0':'2018-02-16',
'8.6.0':'2018-02-05',
'8.5.0':'2018-01-22',
'8.4.1':'2018-01-02',
'8.4.0':'2017-12-15',
'8.3.1':'2017-12-08',
'8.3.0':'2017-11-29',
'8.2.0':'2017-11-03',
'8.1.0':'2017-10-17',
'8.0.1':'2017-10-09',
'8.0.0':'2017-09-25',
'7.8.1':'2017-09-08',
'7.8.0':'2017-09-05',
'7.7.2':'2017-08-23',
'7.7.1':'2017-08-15',
'7.7.0':'2017-08-14',
'7.6.1':'2017-07-24',
'7.6.0':'2017-07-14',
'7.5.3':'2017-06-22',
'7.5.2':'2017-06-09',
'7.5.1':'2017-06-02',
'7.5.0':'2017-05-30',
'7.4.1':'2017-05-17',
'7.4.0':'2017-05-09',
'7.3.1':'2017-04-19',
'7.3.0':'2017-04-13',
'7.2.2':'2017-04-03',
'7.2.1':'2017-04-01',
'7.2.0':'2017-03-30',
'7.1.1':'2017-03-16',
'7.1.0':'2017-03-06',
'7.0.1':'2017-02-19',
'7.0.0':'2017-02-16',
'6.9.4':'2017-02-06',
'6.9.3':'2017-01-27',
'6.9.2':'2017-01-25',
'6.9.1':'2017-01-17',
'6.9.0':'2017-01-12',
'6.8.1':'2017-01-03',
'6.8.0':'2016-12-19',
'6.7.0':'2016-11-30',
'6.6.1':'2016-11-18',
'6.6.0':'2016-11-16',
'6.5.0':'2016-11-07',
'6.4.1':'2016-11-01',
'6.4.0':'2016-10-26',
'6.3.2':'2016-10-19',
'6.3.1':'2016-10-12',
'6.3.0':'2016-10-04',
'6.2.0':'2016-09-27',
'6.1.0':'2016-09-20',
'6.0.0':'2016-09-20',
'5.5.3':'2016-09-12',
'5.5.2':'2016-09-08',
'5.5.1':'2016-09-03',
'5.5.0':'2016-08-31',
'5.4.1':'2016-08-25',
'5.4.0':'2016-08-18',
'5.3.2':'2016-07-29',
'5.3.1':'2016-07-21',
'5.3.0':'2016-07-19',
'5.2.0':'2016-06-27',
'5.1.1':'2016-06-07',
'5.1.0':'2016-06-06',
'5.0.2':'2016-05-13',
'5.0.1':'2016-04-29',
'5.0.0':'2016-04-21',
'4.8.2':'2016-03-02',
'4.8.1':'2016-01-30',
'4.8.0':'2016-01-27',
'4.7.2':'2015-12-17',
'4.7.1':'2015-11-13',
'4.7.0':'2015-11-11',
'4.6.1':'2015-09-23',
'4.6.0':'2015-09-04',
'4.5.0':'2015-07-07',
'4.4.6':'2015-05-18',
'4.4.5':'2015-05-12',
'4.4.4':'2015-05-05',
'4.4.3':'2015-04-28',
'4.4.2':'2015-04-28',
'4.4.1':'2015-04-16',
'4.4.0':'2015-04-15',
'4.3.0':'2015-03-02',
'4.2.0':'2015-03-02',
'4.1.4':'2015-02-13',
'4.1.3':'2015-02-06',
'4.1.2':'2015-02-06',
'4.1.1':'2015-02-02',
'4.1.0':'2015-02-02',
'4.0.9':'2014-10-09',
'4.0.8':'2014-09-27',
'4.0.7':'2014-09-19',
'4.0.6':'2014-09-18',
'4.0.5':'2014-09-18',
'4.0.4':'2014-07-17',
'4.0.3':'2014-06-26',
'4.0.2':'2014-06-17',
'4.0.1':'2014-06-06',
'4.0.0':'2014-06-05',
'3.0.4':'2014-03-12',
'3.0.3':'2014-02-26',
'3.0.2':'2013-12-19',
'3.0.1':'2013-11-28',
'3.0.0':'2013-11-21',
'2.2.3':'2013-11-20',
'2.2.2':'2013-09-25',
'2.2.1':'2013-09-24',
'2.2.0':'2013-09-14',
'2.1.1':'2013-06-07',
'2.1.0':'2013-05-23',
'2.0.3':'2013-04-01',
'2.0.2':'2013-03-29',
'2.0.1':'2013-03-28',
'2.0.0':'2013-03-28',
'1.1.4':'2013-02-08',
'1.1.3':'2013-02-06',
'1.1.2':'2013-01-21',
'1.1.1':'2013-01-11',
'1.1.0':'2013-01-08',
'1.0.6':'2012-11-24',
'1.0.5':'2012-11-16',
'1.0.4':'2012-11-06',
'1.0.3':'2012-09-20',
'1.0.2':'2012-08-29',
'1.0.1':'2012-08-15',
'1.0.0':'2012-08-03'
}
r=(v=>{for(p=[1,0,0],s=0,d="0cc0ec16c2fc0ac08c2db03c0ac10c02c30a00c01c03c34b0fc63b0ac01c38c01a07c15c45c0ec55a01c0bc09c15c3fc00c01c08c0cc74b00c04c00c07c11b00b2cb01c0cc00c07c07c06c32b3bb13c31b02c22c29b03c20c32a08c0ec18b01c14b16b02c08c14b07c06b03c05c04c08a00b07b07b08c07c07b06c06b09b02c0cb13b0fc09b05c08c02c0ac0aa03c0fb0ac0eb02c02c0ab06c14b08c0db03c07c0dc16b0ac15b01c08c0db03c11a0ec08b11b1ab09c07b12c14b0eb0bb0cb0fb15b07b0eb02c05b0ba03c0cb0db0bb20b0ac03b0fb02c06b08c08c07b0cc06b02c01c05a02c06c06b02c0db05c09b12b16c0eb15b04b12b09c03b05c0ab08c03b0fb04c0eb13b01b03c10b1eb16b0db06c07b0aa07c0cc02b05c10b00c09b0cb0eb0ab13c0fb01c04c06b0eb0fb00c01c02c04c0eb01c06b11b0eb0eb0fb09b0eb16b00c",i=0;;i+=3){if(p.join(".")==v)return new Date(1343952e6+864e5*s).toISOString().substr(0,10);s+=parseInt(d[i]+d[i+1],16),l=d[i+2],[a,b,c]=p,p='b'>l?[a+1,0,0]:'c'>l?[a,b+1,0]:[a,b,c+1]}})
const test_passed = Object.keys(version_dates).every(version=>
version_dates[version]===r(version)
);
console.log(test_passed ? 'TEST PASSED' : 'TEST_FAILED')
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~513~~ 508 bytes
Inspired by [Arnauld's answer](https://codegolf.stackexchange.com/a/207243/80745). It's nice code.
```
param($t)$v=,0*5;$d='2012-8'|date
'Ba2a4b2d7a0hT5ca0a6b@d8acU2a5Y9a0ae6Agb1f9a4H5aa1ib1`f3aha2Pa16`dgPQ7T4a`a2ggfU0U9a9T9bc4T1cc2E0ha4R4aR0R2bhR0gVced@XWWhgWfVYbQ2Q9a5Yehba0A0cQ5a0Q4bbQ0fR0hQ3cga3R2a0R1ahQ3cA7a4XQ7R6iWa8R0Q4Q1Q2Q5R1WQ4bUA1cQ2Q3Q1S2a0SQ5bVhhWa2VbaEbfVbQ3eYQ8b2Q4R1TQ8iSeQ0hSQ5dQ4Q9QcQ6S0R2Q3fWA0ga2RePa6YQ2Q4Q0a9Q5adVQ4Pa5abdQ4aVQ7Q4Q4Q5YQ4R2'-split'(?=\D)'|%{$d=$d|% *ys($a=[char]($_[0]-($i=($_[0]-48)-shr4)*16)+$_[1]+$_[2])
$v[$i-1]++;$v[$i]=$v[$i+1]=0;if(+$a-and$v[0..2]-join'.'-eq$t){$d}}
```
[Try it online!](https://tio.run/##bZhrbxQ3FIa/769YoaG7SzKRj@9TtCqpitSPzJILEY3Ae8tulQZIAm0F/HbqmYl9XkeNUMg@7/Gx51xsz3788Pfm9m63ub7@UW3H8/HXHx/DbfhrWt3Pqi/zQ/HMPK/W84kUJGs/@bYO95vR5Ncgg17KtQtid2JWQQS7fLH2YXUqg7lo4ueNPb5a0rYJ@ncTAu2X9H6rwi7IV4Hs@/XVq9ad6PA@yKur7ak4bUJz0ixX@oRWK/lS7IJe6LAQC7ncLcTV2WqzfvHm/Hx3db49u1i2sm3iNJvdMohjsWpNEK1eLluxXYhdq1ZXQS1kEAsK3adjF/Sb1i3s/jz4RbRsKTowCzqPg06PaRU/qZZexxGvW7M82@3OgzxbhpfL7dmyVZuL1i9lqxd00vr9600rdtFsHd007aq1r@MaW7U9PxZXQS42r4K9iP50K0IT17U@a/WrYMIy2oez1kVBt@YiepOT@u7j9f5@Mv1l/sdvs8m3p19jmKv1t6fjZ//eTaswf7vahdvLafXurbisp9V@/vCn9rP6bnerZ8/Izg4io8vut7ycjaovb6t9HT8fPO//vJz3/x3Q5Vw832@nB1Wow806QnF0JC/rPz/sbyZHk3rzKWY7zv/9@4/vo9GL6Wh0OJ0QHVFzJCaHMfdS1MLVJCazpHhQbE2eFVcoQrNiQTG1tKyYQiFiRYOia@lYUYVCihUJiirGxH@oECrFGHhScaRBERYVhYpERWZF1rJBhVDxqMQVVDefr68TwuhLfEIMPtWKF@tgXqqlBoFQwBHoinilthgBaUxZpKaOWwJxPEwhQKA0CHFyjpMqBCgv@TD5IAgC4XGQCEwFLofAucCaSskZBNGAkF2JButGsKtOSOuMjkqFWImtg86EQoXHeC4BwU01KGRYcaA4TqzgpuoUWygGVhAb0aOCYwTMo0sFvEGuuha1rECyopLbQHAjdoounpQKhSA6mARdRFQUY2AeDHXsXQWCAIF4fl@MgED7YoTgp8QESHx8Wwq8KgwyVH3cTmBywrzk4Pu@s1wWFAjE24ngPhkEKMxiBFZSMQKTBSNErSgLuV16QRoQCARqQEBX6TmamA70lELVcP48dmrD6fPYqA1nb@CKebbv2jT7cTxv16SaOQFPyW44175v0DyvBXuf66zhEhh4ntcUnP3rwg@vH/IPTd5g@rsWz3GTBee4QSq7czavHxLWtbBjjvYpPh56vhfSQj20vMfG9tDxg2CzQIWQcu@hq3sh7UUekw8t6oskS5jaFZzyzLbg7B@Tw@3pi@Rwg3hOjuubM/tRyb7nwjNne@5Zz0nrOcQUODeN56Q5bALPSXN9sT@sx3Fz9Dytx3HcBp7tc3M4LGrHzeHwLHIc54HrxC3Yc/E6jn/P2d48XJ46zkXdcQk8PW/HCTnYs3@T70KO8@iw2B3msavp7B/y2BUocIE8x0fCOnXOo@MteeDEnP0oWCeBvcp167Ae4CRyWA9dnTfMBfIHexv7SAMXwDn@lC87ljfpgRvmBJzAXiCXifvCPsXHch3avo@axB1wvtNarquepzPccl0NPD@XKbjI69SFn5QXy/Vg@@Mt@1EpDhZPN8t1YvEQs1wnPU83J8t5t3iptJxfi3dKe/ToNcBwo/SGaULDjWKx0Q03isWLp8HAxMZNB7zBwHQbgGGO9pT9Q2C6Rm@YE3JiLoBTtsfA2BwYww3RcwEc7VMhG76f2L7RFXP2o2GdAvzovE4dC5P98Nuc5kK2@LKlsZChgTRvqAZvcZo3VNMXrGIukOf1WLbvCkQxF8BToWnOr@niLPK8cUTmJuex4wa5ZK6Bp4Oi4ypzPvM7LrFgNRdUb5g6U3NBDTw7VsAx8I/e9aJbWJmECBKsjLe4jsvHDggNJRs@mim@OgyGGg/djvvEoZk77oAT2Fvknrl5PKHOhg6KJn3F0HGbdyfNRd9ztCfgAuwF8ofYq2JelYtAFfPKPK/ieRXu3ornVf1txzMXyB@KO56dyb/CFxfJp6rCW43kU3XgmrkATpkT2PMmInkTUf3VWCUueD1wakt83u7VsmFOyD3z8vsJrlnVl1x62eOaVVizNNTsA@eAUfFAvEtQ8UDwMsmVJ/sAa@YGeH6P5ULouQCuEsevPjgwEt@R4DsUWXyFwYUg8zvPaDb@Nn46/joax5/qy@b2bv/h5nBcbf75uFndb9bj@bh6N4i3m7vP1/cR/FRts2kvPammSa03n3jw7Odsl4Y/GQ3O1uE@HMwPp/8z5Wz0/cd/ "PowerShell – Try It Online")
Some versions of the Tinder are missing from the list. They're added as test cases.
The script starts with version `0.0.0` and the date of `August 1, 2012`.
Then the script iterates through the data string. Each substring contains the number of days since the previous release and the descriptor in the first character ASCII code. The descriptor is one of `16`,`32`,`48`:
* `16` - increment the major version by 1
* `32` - increment the middle version by 1
* `48` - increment the minor version by 1
The script excludes versions for which the number of days is zero, but makes an increment for the version. Thus, the script works correctly with the missed versions of the Tinder.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 333 332 bytes
```
“3ĖẎ⁺Ḣµ3bṄ9HĊ:%:ḞŻHuƤƊ²ⱮĠJėḷȧ!°ọṫọẠIÆGƙĿĠR%ėȦqȷSḂṘ^ṡ¬’BC2“®(0>FZ\`j‘¦3“"4‘¦s2;"“€żḍḋF=ẎhƘẎƁy7ẉr¶$qɦṁI>Ḥ⁾s÷,Ṇ~ʋƊt¦c@ɓḥḤ~ÐqHṀ °8{yþẒ⁺¬4ɠz DOṇĠƓK?Ọj!⁽>3'nẏmẹœƭUÑʠæƥæk¹Ð§©ḲŒmPɦġRXɓµọạṢṘỤzḍ⁻s¡+翹ḋ-^ɼRċIsẸƑñ*½Nı’b29¤[“¬¿“¬“£’];
“eÄneøỌC<½weƙBƤʠĠċUṅKȮCıẈ-ɱ¥*øṬḊ⁹®gṫ¥ɗɱɦɦN⁶ÐẈGṖƭƇ¶ȦĿ⁸ịỵ9ḟŒḥɱ=ṭcỴʠßɓḷ@ḳⱮsṪɠḞ.ṣ?9’B2“`ot~‘¦s3,¢¹×TṂ>3Ḷ¤Ʋ}+ʋ\€yW
```
[Try it online!](https://tio.run/##JVLrThNBFP7vUwCRaKAYaUmkIIWA4SIJGpRo5BICaTQVMFCMKUbSJQjaipY2oZAY2UK7RG0bFqWd2QWanJlOOn2Lsy9Sp/jnmzNzTma@ywT8CwuhWs0Jf/fwPbS@OpqF5AjOPXNIN73DPNLV3IXkR9kefivSIgJnjpnn@kOeRFKsnDTCKdo7SH/X0dJH2NaQOOAlro8382TFWK4UnyDZQLo/gzQFWSd80D/gVm9B/vZd3@CLqdmAE94Hw6OOmjquy6C7u0ntnI1s@QLJDpLoYI@i9UrsKxRa6B5an1egcHNZGki1ER@StKNdBVnRhXRrvRoVkVUw5vtkAklG9dZZbHkYabgBTjvfh9gVWnGlELIdUl9rePAI6TbXRWK0F@0vgUZHu/R5bi2h9W0RLVpOiNwE263qzBAZZrwGymJwAj@RnJXji4@lwVPjz2UCzq@1p5AeKZ1op9cUbUezg5BqZSdQAqo0tM3Ii3EeHQmiRcQuM1vgcoybyo45txfSk3VHslC6XupwrDrT3TdU6WebS35GFL2B@3D5zi8O@kW6qnOdRyeQfhyt5Ae4idanNmlCpkUN0iySiKNRyL9UsUBGJqUpDWmMOVqBxdTkENI9kRPbUKgYvORo6u4o2udeJIfluDJNmj1Ic/No/1XKD@s@FvuQ/FGxB5H@krr6DHeQHvd662HWs5x9s7r@PzqPC46US8mnSDd8HiQFSIuzD63V6JSKM/SsVqtNdrra3a726X8 "Jelly – Try It Online")
Input and output are a list of three integers. (The output is actually wrapped in a singleton list, but that's not visible.)
## Explanation
The version numbers are stored as increments from the last version, except if the minor version is increased, then the patch version is automatically reset, etc. For example: [7,8,9] + [0,1,2] = [7,9,2]. It turns out that most increments are made of 0's and 1's, so I concatenated them (starting with the initial version [1,0,0], replaced 2's with 0's and represented the huge binary number with a base-250 literal, then added code to set the specific indices to 2.
For dates, the same incrementing logic is used, but this time the day increments are much bigger (up to 28), so I stored them separately as a base 29 number. (Since there are no 0's, I tried using base 28 and incrementing, but it wasn't worth it.) Years and months are stored analogously to version numbers, except:
* The initial date is added separately
* The number had leading zeros, so I had to invert it
* There were some 3's, which I dealt with the same way as with 2's.
Merging this all together creates the table, which I simply pass to the `y` (translate) command to look up the input.
] |
[Question]
[
>
> User CarpetPython posted [a new take on this problem](https://codegolf.stackexchange.com/q/42215/8478) which puts a much bigger focus on heuristic solutions, due to an increased search space. I personally think that challenge is much nicer than mine, so consider giving that one a try!
>
>
>
Vector racing is an addictive game that can be played with a pen and a sheet of square-ruled paper. You draw an arbitrary racetrack on the paper, define a start and end and then you steer your point-sized car in a turn-based manner. Get to the end as fast as you can, but be careful not to end up in a wall!
## The Track
* The map is a two dimensional grid, where each cell has integer coordinates.
* You move on the grid cells.
* Each grid cell is either part of the track or it's a wall.
* **Exactly one** track cell is the starting coordinate.
* **At least one** track cell is designated as the goal. *Landing* on any of these completes the race. Multiple goal cells are not necessarily connected.
## Steering the Car
Your car starts at a given coordinate and with velocity vector `(0, 0)`. In each turn, you may adjust each component of the velocity by `±1` or leave it as is. Then, the resulting velocity vector is added to your car's position.
A picture may help! The red circle was your position last turn. The blue circle is your current position. Your velocity is the vector from the red to the blue circle. In this turn, depending on how you adjust your velocity, you may move to any of the green circles.
![enter image description here](https://i.stack.imgur.com/M8OAS.png)
If you *land* in a wall, you lose immediately.
## Your task
You guessed it: write a *program* which, given a racetrack as input, steers the car to one of the goal cells in as few turns as possible. Your solution should be able to deal reasonably well with arbitrary tracks and not be specifically optimised towards the test cases provided.
### Input
When your program is invoked, read **from stdin**:
```
target
n m
[ASCII representation of an n x m racetrack]
time
```
`target` is the maximum number of turns you may take to complete the track, and `time` is your total time budget for the track, in seconds (not necessarily integer). See below for details about timing.
For the newline-delimited track, the following characters are used:
* `#` – wall
* `S` – *the* start
* `*` – *a* goal
* `.` – all other track cells (i.e. road)
All cells outside the `n x m` grid provided are implied to be walls.
The coordinate origin is in the top left corner.
Here is a simple example:
```
8
4.0
9 6
###...***
###...***
###...***
......###
S.....###
......###
```
Using 0-based indexing, the starting coordinate would be `(0,4)`.
*After* every move you will receive further input:
```
x y
u v
time
```
Where `x`, `y`, `u`, `v` are all 0-based integers. `(x,y)` is your current position and `(u,v)` is your current velocity. Note that `x+u` and/or `y+v` could be out of bounds.
`time` is whatever is left of your time budget, in seconds. Feel free to ignore this. This is only for participants who really want to take their implementation to the time limit.
*When the game is over* (because you've landed in a wall, moved out of bounds, exceeded `target` turns, ran out of time or reached the goal), you'll receive an empty line.
### Output
For each turn, write **to stdout**:
```
Δu Δv
```
where `Δu` and `Δv` each are one of `-1`, `0`, `1`. This will be added to `(u,v)` to determine your new position. Just to clarify, the directions are as follows
```
(-1,-1) ( 0,-1) ( 1,-1)
(-1, 0) ( 0, 0) ( 1, 0)
(-1, 1) ( 0, 1) ( 1, 1)
```
An optimal solution for the above example would be
```
1 0
1 -1
1 0
```
Note that the controller does not attach itself to **stderr**, so you're free to use it for any sort of debug output you may need while developing your bot. Please remove/comment out any such output in your submitted code, though.
Your bot may take half a second to respond in each single turn. For turns that take longer, you will have a time budget (per track) of `target/2` seconds. Every time a turn takes longer than half a second, the additional time will be subtracted from your time budget. When your time budget hits zero the current race will be aborted.
**New:** For practical reasons, I have to set a memory limit (since memory seems to be more limiting than time for reasonable track sizes). Therefore, I will have to abort any test run where the racer uses more than **1GB** of memory as measured by [Process Explorer](http://technet.microsoft.com/en-gb/sysinternals/bb896653.aspx) as *Private Bytes*.
### Scoring
There is a [benchmark](https://github.com/mbuettner/ppcg-vector-racing/blob/master/benchmark.txt) of 20 tracks. For each track:
* If you complete the track, your score is the number of moves you need to reach a goal cell *divided by `target`*.
* If you run out of time/memory *or* don't reach the goal before `target` turns have elapsed *or* you land in a wall/out of bounds at any time, your score is `2`.
* If your program is not deterministic, your score is the average over 10 runs on that track (please state this in your answer).
Your overall score is the sum of the individual track scores. **Lowest score wins!**
Furthermore, *every participant may (and is strongly encouraged to) provide an additional benchmark track*, which will be added to the official list. Previous answers will be re-evaluated including this new track. This is to make sure that no solution is tailored too closely to the existing test cases and to account for interesting edge cases I might have missed (but which you may spot).
### Tie breaking
*Now that there is already an optimal solution, this will probably be the main factor for participants' scores.*
If there is a tie (due to several answers solving all tracks optimally or otherwise), I will add additional (larger) test cases to break the tie. To avoid any human bias when creating those tie-breakers, these will be *generated* in a fixed manner:
* I will increase the side length `n` by `10` compared to the last track generated this way. (I may skip sizes if they don't break the tie.)
* The basis is [this vector-graphic](https://github.com/mbuettner/ppcg-vector-racing/blob/master/tie-breaker.pdf)
* This will be rasterised at the desired resolution using [this Mathematica snippet](https://gist.github.com/mbuettner/dcb1e5efcc1a03c2b83f).
* The start is in the top left corner. In particular, it will be the left-most cell of the top-most row of that end of the track.
* The goal is in the bottom right corner. In particular, it will be the right-most cell of the bottom-most row of that end of the track.
* The `target` will `4*n`.
The final track of the initial benchmark was already generated like this, with `n = 50`.
## The Controller
The program that tests the submissions is written in Ruby and [can be found on GitHub](https://github.com/mbuettner/ppcg-vector-racing) along with the benchmark file I'll be using. There is also an example bot called `randomracer.rb` in there, which simply picks random moves. You can use its basic structure as a starting point for your bot to see how the communication works.
You can run your own bot against a track file of your choice as follows:
```
ruby controller.rb track_file_name command to run your racer
```
e.g.
```
ruby controller.rb benchmark.txt ruby randomracer.rb
```
The repository also contains two classes `Point2D` and `Track`. If your submission is written in Ruby, feel free to reuse those for your convenience.
**Command-line switches**
You can add command-line switches `-v`, `-s`, `-t` before the benchmark's file name. If you want to use multiple switches, you can also do, for instance, `-vs`. This is what they do:
`-v` (verbose): Use this to produce a little more debug output from the controller.
`-s` (silent): If you prefer to keep track of your position and velocity yourself and don't care about the time budget, you can switch off those three lines of output each turn (sent to your submission) with this flag.
`-t` (tracks): Lets you select individual tracks to be tested. E.g. `-t "1,2,5..8,15"` would test tracks 1, 2, 5, 6, 7, 8 and 15 only. Thanks a lot to [Ventero](https://codegolf.stackexchange.com/users/84/ventero) for this feature and the options parser.
## Your submission
In summary, please include the following in your answer:
* Your score.
* **If** you're using randomness, please state this, so I can average your score over multiple runs.
* The code for your submission.
* The location of a free compiler or interpreter for your language of choice that runs on a Windows 8 machine.
* Compilation instructions if necessary.
* A Windows command-line string to run your submission.
* Whether your submission requires the `-s` flag or not.
* *(optionally)* A new, solvable track which will be added to the benchmark. I will determine a reasonable `target` for your track manually. When the track is added to the benchmark, I'll edit it out of your answer. I reserve the right to ask you for a different track (just in case you add an disproportionally large track, include obscene ASCII art in the track, etc.). When I add the test case to the benchmark set, I'll replace the track in your answer with a link to the track in the benchmark file to reduce the clutter in this post.
As you can see, I'll be testing all submissions on a Windows 8 machine. If there is absolutely no way to get your submission running on Windows, I can also try on a Ubuntu VM. This will be considerably slower though, so if you want to max out the time limit, make sure your program runs on Windows.
*May the best driver emerge vectorious!*
# But *I* wanna play!
If you want to try out the game yourself to get a better feel for it, there is [this implementation](http://harmmade.com/vectorracer/). The rules used there are slightly more sophisticated, but it is similar enough to be useful, I think.
# Leaderboard
**Last updated:** 01/09/2014, 21:29 UTC
**Tracks in benchmark:** 25
**Tie-breaker sizes:** 290, 440
1. 6.86688 – [**Kuroi Neko**](https://codegolf.stackexchange.com/a/37108/8478)
2. 8.73108 – [**user2357112 - 2nd submission**](https://codegolf.stackexchange.com/a/32704/8478)
3. 9.86627 – [**nneonneo**](https://codegolf.stackexchange.com/a/32655/8478)
4. 10.66109 – [**user2357112 - 1st submission**](https://codegolf.stackexchange.com/a/32704/8478)
5. 12.49643 – [**Ray**](https://codegolf.stackexchange.com/a/32773/8478)
6. 40.0759 – [**pseudonym117**](https://codegolf.stackexchange.com/a/32669/8478) (probabilistic)
[Detailed test results](https://gist.github.com/mbuettner/1a4e7e486e7ebeaa07a7). (The scores for probabilistic submissions have been determined separately.)
[Answer]
# C++, 5.4 (deterministic, optimal)
Dynamic programming solution. Provably optimal. Very fast: solves all 20 testcases in 0.2s. Should be especially fast on 64-bit machines. Assumes the board is less than 32,000 places in each direction (which should hopefully be true).
This racer is a little unusual. It computes the optimal path at the starting line, and afterwards executes the computed path instantly. It ignores the time control and assumes it can finish the optimization step on time (which should be true for any reasonably modern hardware). On excessively large maps, there's a small chance that the racer may segfault. If you can convince it to segfault, you get a brownie point, and I'll fix it to use an explicit loop.
Compile with `g++ -O3`. May require C++11 (for `<unordered_map>`). To run, just run the compiled executable (no flags or options are supported; all input is taken on stdin).
```
#include <unordered_map>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <cstdint>
#define MOVES_INF (1<<30)
union state {
struct {
short px, py, vx, vy;
};
uint64_t val;
};
struct result {
int nmoves;
short dvx, dvy;
};
typedef std::unordered_map<uint64_t, result> cache_t;
int target, n, m;
std::vector<std::string> track;
cache_t cache;
static int solve(uint64_t val) {
cache_t::iterator it = cache.find(val);
if(it != cache.end())
return it->second.nmoves;
// prevent recursion
result res;
res.nmoves = MOVES_INF;
cache[val] = res;
state cur;
cur.val = val;
for(int dvx = -1; dvx <= 1; dvx++) for(int dvy = -1; dvy <= 1; dvy++) {
state next;
next.vx = cur.vx + dvx;
next.vy = cur.vy + dvy;
next.px = cur.px + next.vx;
next.py = cur.py + next.vy;
if(next.px < 0 || next.px >= n || next.py < 0 || next.py >= m)
continue;
char c = track[next.py][next.px];
if(c == '*') {
res.nmoves = 1;
res.dvx = dvx;
res.dvy = dvy;
break;
} else if(c == '#') {
continue;
} else {
int score = solve(next.val) + 1;
if(score < res.nmoves) {
res.nmoves = score;
res.dvx = dvx;
res.dvy = dvy;
}
}
}
cache[val] = res;
return res.nmoves;
}
bool solve_one() {
std::string line;
float time;
std::cin >> target;
// std::cin >> time; // uncomment to use "time" control
std::cin >> n >> m;
if(!std::cin)
return false;
std::cin.ignore(); // skip newline at end of "n m" line
track.clear();
track.reserve(m);
for(int i=0; i<m; i++) {
std::getline(std::cin, line);
track.push_back(line);
}
cache.clear();
state cur;
cur.vx = cur.vy = 0;
for(int y=0; y<m; y++) for(int x=0; x<n; x++) {
if(track[y][x] == 'S') {
cur.px = x;
cur.py = y;
break;
}
}
solve(cur.val);
int sol_len = 0;
while(track[cur.py][cur.px] != '*') {
cache_t::iterator it = cache.find(cur.val);
if(it == cache.end() || it->second.nmoves >= MOVES_INF) {
std::cerr << "Failed to solve at p=" << cur.px << "," << cur.py << " v=" << cur.vx << "," << cur.vy << std::endl;
return true;
}
int dvx = it->second.dvx;
int dvy = it->second.dvy;
cur.vx += dvx;
cur.vy += dvy;
cur.px += cur.vx;
cur.py += cur.vy;
std::cout << dvx << " " << dvy << std::endl;
sol_len++;
}
//std::cerr << "Score: " << ((float)sol_len) / target << std::endl;
return true;
}
int main() {
/* benchmarking: */
//while(solve_one())
// ;
/* regular running */
solve_one();
std::string line;
while(std::cin) std::getline(std::cin, line);
return 0;
}
```
## Results
```
No. Size Target Score Details
-------------------------------------------------------------------------------------
1 37 x 1 36 0.22222 Racer reached goal at ( 36, 0) in 8 turns.
2 38 x 1 37 0.24324 Racer reached goal at ( 37, 0) in 9 turns.
3 33 x 1 32 0.25000 Racer reached goal at ( 32, 0) in 8 turns.
4 10 x 10 10 0.40000 Racer reached goal at ( 7, 7) in 4 turns.
5 9 x 6 8 0.37500 Racer reached goal at ( 6, 0) in 3 turns.
6 15 x 7 16 0.37500 Racer reached goal at ( 12, 4) in 6 turns.
7 17 x 8 16 0.31250 Racer reached goal at ( 15, 0) in 5 turns.
8 19 x 13 18 0.27778 Racer reached goal at ( 1, 11) in 5 turns.
9 60 x 10 107 0.14953 Racer reached goal at ( 2, 6) in 16 turns.
10 31 x 31 106 0.25472 Racer reached goal at ( 28, 0) in 27 turns.
11 31 x 31 106 0.24528 Racer reached goal at ( 15, 15) in 26 turns.
12 50 x 20 50 0.24000 Racer reached goal at ( 49, 10) in 12 turns.
13 100 x 100 2600 0.01385 Racer reached goal at ( 50, 0) in 36 turns.
14 79 x 63 242 0.26860 Racer reached goal at ( 3, 42) in 65 turns.
15 26 x 1 25 0.32000 Racer reached goal at ( 25, 0) in 8 turns.
16 17 x 1 19 0.52632 Racer reached goal at ( 16, 0) in 10 turns.
17 50 x 1 55 0.34545 Racer reached goal at ( 23, 0) in 19 turns.
18 10 x 7 23 0.34783 Racer reached goal at ( 1, 3) in 8 turns.
19 55 x 55 45 0.17778 Racer reached goal at ( 52, 26) in 8 turns.
20 50 x 50 200 0.05500 Racer reached goal at ( 47, 46) in 11 turns.
-------------------------------------------------------------------------------------
TOTAL SCORE: 5.40009
```
## [New Testcase](https://github.com/mbuettner/ppcg-vector-racing/blob/master/benchmark.txt#L425)
[Answer]
## [Python 2](https://www.python.org/), deterministic, optimal
Here's my racer. I haven't tested it on the benchmark (still waffling about what version and installer of Ruby to install), but it should solve everything optimally and under the time limit. The command to run it is `python whateveryoucallthefile.py`. Needs the `-s` controller flag.
```
# Breadth-first search.
# Future directions: bidirectional search and/or A*.
import operator
import time
acceleration_options = [(dvx, dvy) for dvx in [-1, 0, 1] for dvy in [-1, 0, 1]]
class ImpossibleRaceError(Exception): pass
def read_input(line_source=raw_input):
# We don't use the target.
target = int(line_source())
width, height = map(int, line_source().split())
input_grid = [line_source() for _ in xrange(height)]
start = None
for i in xrange(height):
for j in xrange(width):
if input_grid[i][j] == 'S':
start = i, j
break
if start is not None:
break
walls = [[cell == '#' for cell in row] for row in input_grid]
goals = [[cell == '*' for cell in row] for row in input_grid]
return start, walls, goals
def default_bfs_stop_threshold(walls, goals):
num_not_wall = sum(sum(map(operator.not_, row)) for row in walls)
num_goals = sum(sum(row) for row in goals)
return num_goals * num_not_wall
def bfs(start, walls, goals, stop_threshold=None):
if stop_threshold is None:
stop_threshold = default_bfs_stop_threshold(walls, goals)
# State representation is (x, y, vx, vy)
x, y = start
initial_state = (x, y, 0, 0)
frontier = {initial_state}
# Visited set is tracked by a map from each state to the last move taken
# before reaching that state.
visited = {initial_state: None}
while len(frontier) < stop_threshold:
if not frontier:
raise ImpossibleRaceError
new_frontier = set()
for x, y, vx, vy in frontier:
for dvx, dvy in acceleration_options:
new_vx, new_vy = vx+dvx, vy+dvy
new_x, new_y = x+new_vx, y+new_vy
new_state = (new_x, new_y, new_vx, new_vy)
if not (0 <= new_x < len(walls) and 0 <= new_y < len(walls[0])):
continue
if walls[new_x][new_y]:
continue
if new_state in visited:
continue
new_frontier.add(new_state)
visited[new_state] = dvx, dvy
if goals[new_x][new_y]:
return construct_path_from_bfs(new_state, visited)
frontier = new_frontier
def construct_path_from_bfs(goal_state, best_moves):
reversed_path = []
current_state = goal_state
while best_moves[current_state] is not None:
move = best_moves[current_state]
reversed_path.append(move)
x, y, vx, vy = current_state
dvx, dvy = move
old_x, old_y = x-vx, y-vy # not old_vx or old_vy
old_vx, old_vy = vx-dvx, vy-dvy
current_state = (old_x, old_y, old_vx, old_vy)
return reversed_path[::-1]
def main():
t = time.time()
start, walls, goals = read_input()
path = bfs(start, walls, goals, float('inf'))
for dvx, dvy in path:
# I wrote the whole program with x pointing down and y pointing right.
# Whoops. Gotta flip things for the output.
print dvy, dvx
if __name__ == '__main__':
main()
```
After inspecting nneonneo's racer (but not actually testing it, since I also don't have a C++ compiler), I have found that it seems to perform a nearly-exhaustive search of the state space, no matter how close the goal or how short a path has already been found. I have also found that the time rules mean building a map with a long, complex solution requires a long, boring time limit. Thus, my map submission is pretty simple:
## [New Testcase](https://github.com/mbuettner/ppcg-vector-racing/blob/master/benchmark.txt#L528)
(GitHub cannot display the long line. The track is `*S.......[and so on].....`)
---
### Additional submission: Python 2, bidirectional search
This is an approach I wrote up about two months ago, when trying to optimize my breadth-first submission. For the test cases that existed at the time, it didn't offer an improvement, so I didn't submit it, but for kuroi's new map, it seems to just barely squeeze by under the memory cap. I'm still expecting kuroi's solver to beat this, but I'm interested in how it holds up.
```
# Bidirectional search.
# Future directions: A*.
import operator
import time
acceleration_options = [(dvx, dvy) for dvx in [-1, 0, 1] for dvy in [-1, 0, 1]]
class ImpossibleRaceError(Exception): pass
def read_input(line_source=raw_input):
# We don't use the target.
target = int(line_source())
width, height = map(int, line_source().split())
input_grid = [line_source() for _ in xrange(height)]
start = None
for i in xrange(height):
for j in xrange(width):
if input_grid[i][j] == 'S':
start = i, j
break
if start is not None:
break
walls = [[cell == '#' for cell in row] for row in input_grid]
goals = [[cell == '*' for cell in row] for row in input_grid]
return start, walls, goals
def bfs_to_bidi_threshold(walls, goals):
num_not_wall = sum(sum(map(operator.not_, row)) for row in walls)
num_goals = sum(sum(row) for row in goals)
return num_goals * (num_not_wall - num_goals)
class GridBasedGoalContainer(object):
'''Supports testing whether a state is a goal state with `in`.
Does not perform bounds checking.'''
def __init__(self, goal_grid):
self.goal_grid = goal_grid
def __contains__(self, state):
x, y, vx, vy = state
return self.goal_grid[x][y]
def forward_step(state, acceleration):
x, y, vx, vy = state
dvx, dvy = acceleration
new_vx, new_vy = vx+dvx, vy+dvy
new_x, new_y = x+new_vx, y+new_vy
return (new_x, new_y, new_vx, new_vy)
def backward_step(state, acceleration):
x, y, vx, vy = state
dvx, dvy = acceleration
old_x, old_y = x-vx, y-vy
old_vx, old_vy = vx-dvx, vy-dvy
return (old_x, old_y, old_vx, old_vy)
def bfs(start, walls, goals):
x, y = start
initial_state = (x, y, 0, 0)
initial_frontier = {initial_state}
visited = {initial_state: None}
goal_state, frontier, visited = general_bfs(
frontier=initial_frontier,
visited=visited,
walls=walls,
goalcontainer=GridBasedGoalContainer(goals),
stop_threshold=float('inf'),
step_function=forward_step
)
return construct_path_from_bfs(goal_state, visited)
def general_bfs(
frontier,
visited,
walls,
goalcontainer,
stop_threshold,
step_function):
while len(frontier) <= stop_threshold:
if not frontier:
raise ImpossibleRaceError
new_frontier = set()
for state in frontier:
for accel in acceleration_options:
new_state = new_x, new_y, new_vx, new_vy = \
step_function(state, accel)
if not (0 <= new_x < len(walls) and 0 <= new_y < len(walls[0])):
continue
if walls[new_x][new_y]:
continue
if new_state in visited:
continue
new_frontier.add(new_state)
visited[new_state] = accel
if new_state in goalcontainer:
return new_state, frontier, visited
frontier = new_frontier
return None, frontier, visited
def max_velocity_component(n):
# It takes a distance of at least 0.5*v*(v+1) to achieve a velocity of
# v in the x or y direction. That means the map has to be at least
# 1 + 0.5*v*(v+1) rows or columns long to accomodate such a velocity.
# Solving for v, we get a velocity cap as follows.
return int((2*n-1.75)**0.5 - 0.5)
def solver(
start,
walls,
goals,
mode='bidi'):
x, y = start
initial_state = (x, y, 0, 0)
initial_frontier = {initial_state}
visited = {initial_state: None}
if mode == 'bidi':
stop_threshold = bfs_to_bidi_threshold(walls, goals)
elif mode == 'bfs':
stop_threshold = float('inf')
else:
raise ValueError('Unsupported search mode: {}'.format(mode))
goal_state, frontier, visited = general_bfs(
frontier=initial_frontier,
visited=visited,
walls=walls,
goalcontainer=GridBasedGoalContainer(goals),
stop_threshold=stop_threshold,
step_function=forward_step
)
if goal_state is not None:
return construct_path_from_bfs(goal_state, visited)
# Switching to bidirectional search.
not_walls_or_goals = []
goal_list = []
for x in xrange(len(walls)):
for y in xrange(len(walls[0])):
if not walls[x][y] and not goals[x][y]:
not_walls_or_goals.append((x, y))
if goals[x][y]:
goal_list.append((x, y))
max_vx = max_velocity_component(len(walls))
max_vy = max_velocity_component(len(walls[0]))
reverse_visited = {(goal_x, goal_y, goal_x-prev_x, goal_y-prev_y): None
for goal_x, goal_y in goal_list
for prev_x, prev_y in not_walls_or_goals
if abs(goal_x-prev_x) <= max_vx
and abs(goal_y - prev_y) <= max_vy}
reverse_frontier = set(reverse_visited)
while goal_state is None:
goal_state, reverse_frontier, reverse_visited = general_bfs(
frontier=reverse_frontier,
visited=reverse_visited,
walls=walls,
goalcontainer=frontier,
stop_threshold=len(frontier),
step_function=backward_step
)
if goal_state is not None:
break
goal_state, frontier, visited = general_bfs(
frontier=frontier,
visited=visited,
walls=walls,
goalcontainer=reverse_frontier,
stop_threshold=len(reverse_frontier),
step_function=forward_step
)
forward_path = construct_path_from_bfs(goal_state, visited)
backward_path = construct_path_from_bfs(goal_state,
reverse_visited,
step_function=forward_step)
return forward_path + backward_path[::-1]
def construct_path_from_bfs(goal_state,
best_moves,
step_function=backward_step):
reversed_path = []
current_state = goal_state
while best_moves[current_state] is not None:
move = best_moves[current_state]
reversed_path.append(move)
current_state = step_function(current_state, move)
return reversed_path[::-1]
def main():
start, walls, goals = read_input()
t = time.time()
path = solver(start, walls, goals)
for dvx, dvy in path:
# I wrote the whole program with x pointing down and y pointing right.
# Whoops. Gotta flip things for the output.
print dvy, dvx
if __name__ == '__main__':
main()
```
[Answer]
# C++11 - 6.66109
Yet another breadth first search implementation, only optimized.
It must be run with the **-s** option.
Its input is not sanitized at all, so wrong tracks might turn it into a pumpkin.
I tested it with Microsoft Visual C++ 2013, release build with the default /O2 flag (optimize for speed).
DOES build OK with g++ and the Microsoft IDE.
My barebone memory allocator is a piece of crap, so don't expect it to work with other STL implementations of `unordered_set`!
```
#include <cstdint>
#include <iostream>
#include <fstream>
#include <sstream>
#include <queue>
#include <unordered_set>
#define MAP_START 'S'
#define MAP_WALL '#'
#define MAP_GOAL '*'
#define NODE_CHUNK_SIZE 100 // increasing this will not improve performances
#define VISIT_CHUNK_SIZE 1024 // increasing this will slightly reduce mem consumption at the (slight) cost of speed
#define HASH_POS_BITS 8 // number of bits for one coordinate
#define HASH_SPD_BITS (sizeof(size_t)*8/2-HASH_POS_BITS)
typedef int32_t tCoord; // 32 bits required to overcome the 100.000 cells (insanely) long challenge
// basic vector arithmetics
struct tPoint {
tCoord x, y;
tPoint(tCoord x = 0, tCoord y = 0) : x(x), y(y) {}
tPoint operator+ (const tPoint & p) { return tPoint(x + p.x, y + p.y); }
tPoint operator- (const tPoint & p) { return tPoint(x - p.x, y - p.y); }
bool operator== (const tPoint & p) const { return p.x == x && p.y == y; }
};
// a barebone block allocator. Improves speed by about 30%
template <class T, size_t SIZE> class tAllocator
{
T * chunk;
size_t i_alloc;
size_t m_alloc;
public:
typedef T value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef std::size_t size_type;
typedef value_type& reference;
typedef const value_type& const_reference;
tAllocator() { m_alloc = i_alloc = SIZE; }
template <class U> tAllocator(const tAllocator<U, SIZE>&) { m_alloc = i_alloc = SIZE; }
template <class U> struct rebind { typedef tAllocator<U, SIZE> other; };
pointer allocate(size_type n, const_pointer = 0)
{
if (n > m_alloc) { i_alloc = m_alloc = n; } // grow max size if request exceeds capacity
if ((i_alloc + n) > m_alloc) i_alloc = m_alloc; // dump current chunk if not enough room available
if (i_alloc == m_alloc) { chunk = new T[m_alloc]; i_alloc = 0; } // allocate new chunk when needed
T * mem = &chunk[i_alloc];
i_alloc += n;
return mem;
}
void deallocate(pointer, size_type) { /* memory is NOT released until process exits */ }
void construct(pointer p, const value_type& x) { new(p)value_type(x); }
void destroy(pointer p) { p->~value_type(); }
};
// a node in our search graph
class tNode {
static tAllocator<tNode, NODE_CHUNK_SIZE> mem; // about 10% speed gain over a basic allocation
tNode * parent;
public:
tPoint pos;
tPoint speed;
static tNode * alloc (tPoint pos, tPoint speed, tNode * parent) { return new (mem.allocate(1)) tNode(pos, speed, parent); }
tNode (tPoint pos = tPoint(), tPoint speed = tPoint(), tNode * parent = nullptr) : parent(parent), pos(pos), speed(speed) {}
bool operator== (const tNode& n) const { return n.pos == pos && n.speed == speed; }
void output(void)
{
std::string output;
tPoint v = this->speed;
for (tNode * n = this->parent ; n != nullptr ; n = n->parent)
{
tPoint a = v - n->speed;
v = n->speed;
std::ostringstream ss; // a bit of shitty c++ text I/O to print elements in reverse order
ss << a.x << ' ' << a.y << '\n';
output = ss.str() + output;
}
std::cout << output;
}
};
tAllocator<tNode, NODE_CHUNK_SIZE> tNode::mem;
// node queueing and storing
static int num_nodes = 0;
class tNodeJanitor {
// set of already visited nodes. Block allocator improves speed by about 20%
struct Hasher { size_t operator() (tNode * const n) const
{
int64_t hash = // efficient hashing is the key of performances
((int64_t)n->pos.x << (0 * HASH_POS_BITS))
^ ((int64_t)n->pos.y << (1 * HASH_POS_BITS))
^ ((int64_t)n->speed.x << (2 * HASH_POS_BITS + 0 * HASH_SPD_BITS))
^ ((int64_t)n->speed.y << (2 * HASH_POS_BITS + 1 * HASH_SPD_BITS));
return (size_t)((hash >> 32) ^ hash);
//return (size_t)(hash);
}
};
struct Equalizer { bool operator() (tNode * const n1, tNode * const n2) const
{ return *n1 == *n2; }};
std::unordered_set<tNode *, Hasher, Equalizer, tAllocator<tNode *, VISIT_CHUNK_SIZE>> visited;
std::queue<tNode *> queue; // currently explored nodes queue
public:
bool empty(void) { return queue.empty(); }
tNode * dequeue() { tNode * n = queue.front(); queue.pop(); return n; }
tNode * enqueue_if_new (tPoint pos, tPoint speed = tPoint(0,0), tNode * parent = nullptr)
{
tNode signature (pos, speed);
tNode * n = nullptr;
if (visited.find (&signature) == visited.end()) // the classy way to check if an element is in a set
{
n = tNode::alloc(pos, speed, parent);
queue.push(n);
visited.insert (n);
num_nodes++;
}
return n;
}
};
// map representation
class tMap {
std::vector<char> cell;
tPoint dim; // dimensions
public:
void set_size(tCoord x, tCoord y) { dim = tPoint(x, y); cell.resize(x*y); }
void set(tCoord x, tCoord y, char c) { cell[y*dim.x + x] = c; }
char get(tPoint pos)
{
if (pos.x < 0 || pos.x >= dim.x || pos.y < 0 || pos.y >= dim.y) return MAP_WALL;
return cell[pos.y*dim.x + pos.x];
}
void dump(void)
{
for (int y = 0; y != dim.y; y++)
{
for (int x = 0; x != dim.x; x++) fprintf(stderr, "%c", cell[y*dim.x + x]);
fprintf(stderr, "\n");
}
}
};
// race manager
class tRace {
tPoint start;
tNodeJanitor border;
static tPoint acceleration[9];
public:
tMap map;
tRace ()
{
int target;
tCoord sx, sy;
std::cin >> target >> sx >> sy;
std::cin.ignore();
map.set_size (sx, sy);
std::string row;
for (int y = 0; y != sy; y++)
{
std::getline(std::cin, row);
for (int x = 0; x != sx; x++)
{
char c = row[x];
if (c == MAP_START) start = tPoint(x, y);
map.set(x, y, c);
}
}
}
// all the C++ crap above makes for a nice and compact solver
tNode * solve(void)
{
tNode * initial = border.enqueue_if_new (start);
while (!border.empty())
{
tNode * node = border.dequeue();
tPoint p = node->pos;
tPoint v = node->speed;
for (tPoint a : acceleration)
{
tPoint nv = v + a;
tPoint np = p + nv;
char c = map.get(np);
if (c == MAP_WALL) continue;
if (c == MAP_GOAL) return new tNode (np, nv, node);
border.enqueue_if_new (np, nv, node);
}
}
return initial; // no solution found, will output nothing
}
};
tPoint tRace::acceleration[] = {
tPoint(-1,-1), tPoint(-1, 0), tPoint(-1, 1),
tPoint( 0,-1), tPoint( 0, 0), tPoint( 0, 1),
tPoint( 1,-1), tPoint( 1, 0), tPoint( 1, 1)};
#include <ctime>
int main(void)
{
tRace race;
clock_t start = clock();
tNode * solution = race.solve();
std::cerr << "time: " << (clock()-start)/(CLOCKS_PER_SEC/1000) << "ms nodes: " << num_nodes << std::endl;
solution->output();
return 0;
}
```
# Results
```
No. Size Target Score Details
-------------------------------------------------------------------------------------
1 37 x 1 36 0.22222 Racer reached goal at ( 36, 0) in 8 turns.
2 38 x 1 37 0.24324 Racer reached goal at ( 37, 0) in 9 turns.
3 33 x 1 32 0.25000 Racer reached goal at ( 32, 0) in 8 turns.
4 10 x 10 10 0.40000 Racer reached goal at ( 7, 7) in 4 turns.
5 9 x 6 8 0.37500 Racer reached goal at ( 6, 0) in 3 turns.
6 15 x 7 16 0.37500 Racer reached goal at ( 12, 4) in 6 turns.
7 17 x 8 16 0.31250 Racer reached goal at ( 14, 0) in 5 turns.
8 19 x 13 18 0.27778 Racer reached goal at ( 0, 11) in 5 turns.
9 60 x 10 107 0.14953 Racer reached goal at ( 0, 6) in 16 turns.
10 31 x 31 106 0.23585 Racer reached goal at ( 27, 0) in 25 turns.
11 31 x 31 106 0.24528 Racer reached goal at ( 15, 15) in 26 turns.
12 50 x 20 50 0.24000 Racer reached goal at ( 49, 10) in 12 turns.
13 100 x 100 2600 0.01385 Racer reached goal at ( 50, 0) in 36 turns.
14 79 x 63 242 0.24380 Racer reached goal at ( 3, 42) in 59 turns.
15 26 x 1 25 0.32000 Racer reached goal at ( 25, 0) in 8 turns.
16 17 x 1 19 0.52632 Racer reached goal at ( 16, 0) in 10 turns.
17 50 x 1 55 0.34545 Racer reached goal at ( 23, 0) in 19 turns.
18 10 x 7 23 0.34783 Racer reached goal at ( 1, 3) in 8 turns.
19 55 x 55 45 0.17778 Racer reached goal at ( 50, 26) in 8 turns.
20 101 x 100 100 0.14000 Racer reached goal at ( 99, 99) in 14 turns.
21 100000 x 1 1 1.00000 Racer reached goal at ( 0, 0) in 1 turns.
22 50 x 50 200 0.05500 Racer reached goal at ( 47, 46) in 11 turns.
23 290 x 290 1160 0.16466 Racer reached goal at ( 269, 265) in 191 turns.
-------------------------------------------------------------------------------------
TOTAL SCORE: 6.66109
```
# Performances
That crappy C++ language has a knack to make you jump through hoops just to move a matchstick. However, you can whip it into producing relatively fast and memory-efficient code.
## Hashing
Here the key is to provide a good hash table for the nodes. That is by far the dominant factor for execution speed.
Two implementations of `unordered_set` (GNU and Microsoft) yielded a 30% execution speed difference (in favor of GNU, yay!).
The difference is not really surprising, what with the truckloads of code hidden behind `unordered_set`.
Out of curiosity, I did some stats on the final state of the hash table.
Both algorithms end up with nearly the same bucket/elements ratio, but repartition varies:
for the 290x290 tie breaker, GNU gets an average of 1.5 elements per non empty bucket, while Microsoft is at 5.8 (!).
Looks like my hashing function is not very well randomized by Microsoft... I wonder if the guys in Redmond did really benchmark their STL, or maybe my use case just favors the GNU implementation...
Sure, my hashing function is nowhere near optimal. I could have used the usual integer mixing based on multiple shift/muls **but** a hash-efficient function takes time to compute.
It appears the number of hash table queries is very high compared with the number of insertions. For instance, in the 290x290 tie breaker, you have about 3.6 million insertions for 22.7 million queries.
In this context, a suboptimal but fast hashing yields better performances.
## Memory allocation
Providing an efficient memory allocator comes second. It improved performances by about 30%. Whether it is worth the added crap code is debatable :).
The current version uses between 40 and 55 bytes per node.
The functional data require 24 bytes for a node (4 coordinates and 2 pointers).
Due to the insane 100.000 lines test case, coordinates have to be stored in 4 bytes words, otherwise you could gain 8 bytes by using shorts (with a max coordinate value of 32767).
The remaining bytes are mostly consumed by the unordered set's hash table. It means the data handling actually consumes a bit more than the "useful" payload.
## And the winner is...
On my PC under Win7, the tie breaker (case 23, 290x290) is solved by the worst version (i.e. Microsoft compiled) in about 2.2 seconds, with a memory consumption of about 185 Mb.
For comparison, the current leader (python code by user2357112) takes a bit more than 30 seconds and consumes about 780 Mb.
# Controller issues
I'm not quite sure I might be able to code in Ruby to save my life.
However, I spotted and hacked two problems out of the controller code:
## 1) map reading in `track.rb`
With ruby 1.9.3 installed, the track reader would croak about `shift.to_i` not being available for `string.lines`.
After a long bit of wading through the online Ruby documentation I gave up on strings and used an intermediate array instead, like so (right at the begining of the file):
```
def initialize(string)
@track = Array.new;
string.lines.each do |line|
@track.push (line.chomp)
end
```
## 2) killing ghosts in `controller.rb`
As other posters have already noted, the controller sometimes tries to kill processes that have already exited. To avoid these disgracious error outputs, I simply handled the exception away, like so (around line 134):
```
if silent
begin # ;!;
Process.kill('KILL', racer.pid)
rescue Exception => e
end
```
# Test case
To defeat the brute force approach of the BFS solvers, the worst track is the opposite of the 100.000 cells map: a completely free area with the goal as far from the start as possible.
In this example, a 100x400 map with the goal in the upper left corner and the start in the lower right.
This map has a solution in 28 turns, but a BFS solver will explore millions of states to find it (mine counted 10.022.658 states visited, took about 12 seconds and peaked at 600 Mb !).
With less than half the surface of the 290x290 tie breaker, it requires about 3 times more node visits. On the other hand, a heuristic / A\* based solver should defeat it easily.
```
30
100 400
*...................................................................................................
....................................................................................................
< 400 lines in all >
....................................................................................................
....................................................................................................
...................................................................................................S
```
# Bonus: an equivalent (but somewhat less efficient) PHP version
This is what I started with, before the inherent language slowness convinced me to use C++.
PHP internal hash tables don't seem as efficient as Python's, at least in this particular case :).
```
<?php
class Trace {
static $file;
public static $state_member;
public static $state_target;
static function msg ($msg)
{
fputs (self::$file, "$msg\n");
}
static function dump ($var, $msg=null)
{
ob_start();
if ($msg) echo "$msg ";
var_dump($var);
$dump=ob_get_contents();
ob_end_clean();
fputs (self::$file, "$dump\n");
}
function init ($fname)
{
self::$file = fopen ($fname, "w");
}
}
Trace::init ("racer.txt");
class Point {
public $x;
public $y;
function __construct ($x=0, $y=0)
{
$this->x = (float)$x;
$this->y = (float)$y;
}
function __toString ()
{
return "[$this->x $this->y]";
}
function add ($v)
{
return new Point ($this->x + $v->x, $this->y + $v->y);
}
function vector_to ($goal)
{
return new Point ($goal->x - $this->x, $goal->y - $this->y);
}
}
class Node {
public $posx , $posy ;
public $speedx, $speedy;
private $parent;
public function __construct ($posx, $posy, $speedx, $speedy, $parent)
{
$this->posx = $posx;
$this->posy = $posy;
$this->speedx = $speedx;
$this->speedy = $speedy;
$this->parent = $parent;
}
public function path ()
{
$res = array();
$v = new Point ($this->speedx, $this->speedy);
for ($node = $this->parent ; $node != null ; $node = $node->parent)
{
$nv = new Point ($node->speedx, $node->speedy);
$a = $nv->vector_to ($v);
$v = new Point ($node->speedx, $node->speedy);
array_unshift ($res, $a);
}
return $res;
}
}
class Map {
private static $target; // maximal number of turns
private static $time; // time available to solve
private static $sx, $sy; // map dimensions
private static $cell; // cells of the map
private static $start; // starting point
private static $acceleration; // possible acceleration values
public static function init ()
{
// read map definition
self::$target = trim(fgets(STDIN));
list (self::$sx, self::$sy) = explode (" ", trim(fgets(STDIN)));
self::$cell = array();
for ($y = 0 ; $y != self::$sy ; $y++) self::$cell[] = str_split (trim(fgets(STDIN)));
self::$time = trim(fgets(STDIN));
// get starting point
foreach (self::$cell as $y=>$row)
{
$x = array_search ("S", $row);
if ($x !== false)
{
self::$start = new Point ($x, $y);
Trace::msg ("start ".self::$start);
break;
}
}
// compute possible acceleration values
self::$acceleration = array();
for ($x = -1 ; $x <= 1 ; $x++)
for ($y = -1 ; $y <= 1 ; $y++)
{
self::$acceleration[] = new Point ($x, $y);
}
}
public static function solve ()
{
$now = microtime(true);
$res = array();
$border = array (new Node (self::$start->x, self::$start->y, 0, 0, null));
$present = array (self::$start->x." ".self::$start->y." 0 0" => 1);
while (count ($border))
{
if ((microtime(true) - $now) > 1)
{
Trace::msg (count($present)." nodes, ".round(memory_get_usage(true)/1024)."K");
$now = microtime(true);
}
$node = array_shift ($border);
//Trace::msg ("node $node->pos $node->speed");
$px = $node->posx;
$py = $node->posy;
$vx = $node->speedx;
$vy = $node->speedy;
foreach (self::$acceleration as $a)
{
$nvx = $vx + $a->x;
$nvy = $vy + $a->y;
$npx = $px + $nvx;
$npy = $py + $nvy;
if ($npx < 0 || $npx >= self::$sx || $npy < 0 || $npy >= self::$sy || self::$cell[$npy][$npx] == "#")
{
//Trace::msg ("invalid position $px,$py $vx,$vy -> $npx,$npy");
continue;
}
if (self::$cell[$npy][$npx] == "*")
{
Trace::msg ("winning position $px,$py $vx,$vy -> $npx,$npy");
$end = new Node ($npx, $npy, $nvx, $nvy, $node);
$res = $end->path ();
break 2;
}
//Trace::msg ("checking $np $nv");
$signature = "$npx $npy $nvx $nvy";
if (isset ($present[$signature])) continue;
//Trace::msg ("*** adding $np $nv");
$border[] = new Node ($npx, $npy, $nvx, $nvy, $node);
$present[$signature] = 1;
}
}
return $res;
}
}
ini_set("memory_limit","1000M");
Map::init ();
$res = Map::solve();
//Trace::dump ($res);
foreach ($res as $a) echo "$a->x $a->y\n";
?>
```
[Answer]
# Python 3: 6.49643 (Optimal, BFS)
For the old 20 case benchmark file, it got a score of 5.35643. The solution by @nneonneo is not optimal since it got 5.4. Some bugs maybe.
This solution use BFS to search the Graph, each search state is in the form of (x, y, dx, dy). Then I use a map to map from states to distances. In the worst case, it's time and space complexity is O(n^2 m^2). This will rarely happen since the speed won't be too high or the racer will crash. Actually, it cost 3 seconds on my machine to complete all the 22 testcases.
```
from collections import namedtuple, deque
import itertools
Field = namedtuple('Map', 'n m grids')
class Grid:
WALL = '#'
EMPTY = '.'
START = 'S'
END = '*'
def read_nums():
return list(map(int, input().split()))
def read_field():
m, n = read_nums()
return Field(n, m, [input() for i in range(n)])
def find_start_pos(field):
return next((i, j)
for i in range(field.n) for j in range(field.m)
if field.grids[i][j] == Grid.START)
def can_go(field, i, j):
return 0 <= i < field.n and 0 <= j < field.m and field.grids[i][j] != Grid.WALL
def trace_path(start, end, prev):
if end == start:
return
end, step = prev[end]
yield from trace_path(start, end, prev)
yield step
def solve(max_turns, field, time):
i0, j0 = find_start_pos(field)
p0 = i0, j0, 0, 0
prev = {}
que = deque([p0])
directions = list(itertools.product((-1, 0, 1), (-1, 0, 1)))
while que:
p = i, j, vi, vj = que.popleft()
for dvi, dvj in directions:
vi1, vj1 = vi + dvi, vj + dvj
i1, j1 = i + vi1, j + vj1
if not can_go(field, i1, j1):
continue
p1 = i1, j1, vi1, vj1
if p1 in prev:
continue
que.append(p1)
prev[p1] = p, (dvi, dvj)
if field.grids[i1][j1] == Grid.END:
return trace_path(p0, p1, prev)
return []
def main():
for dvy, dvx in solve(int(input()), read_field(), float(input())):
print(dvx, dvy)
main()
```
# # Results
```
± % time ruby controller.rb benchmark.txt python ../mybfs.py !9349
["benchmark.txt", "python", "../mybfs.py"]
Running 'python ../mybfs.py' against benchmark.txt
No. Size Target Score Details
-------------------------------------------------------------------------------------
1 37 x 1 36 0.22222 Racer reached goal at ( 36, 0) in 8 turns.
2 38 x 1 37 0.24324 Racer reached goal at ( 37, 0) in 9 turns.
3 33 x 1 32 0.25000 Racer reached goal at ( 32, 0) in 8 turns.
4 10 x 10 10 0.40000 Racer reached goal at ( 7, 7) in 4 turns.
5 9 x 6 8 0.37500 Racer reached goal at ( 6, 0) in 3 turns.
6 15 x 7 16 0.37500 Racer reached goal at ( 12, 4) in 6 turns.
7 17 x 8 16 0.31250 Racer reached goal at ( 14, 0) in 5 turns.
8 19 x 13 18 0.27778 Racer reached goal at ( 0, 11) in 5 turns.
9 60 x 10 107 0.14953 Racer reached goal at ( 0, 6) in 16 turns.
10 31 x 31 106 0.23585 Racer reached goal at ( 27, 0) in 25 turns.
11 31 x 31 106 0.24528 Racer reached goal at ( 15, 15) in 26 turns.
12 50 x 20 50 0.24000 Racer reached goal at ( 49, 10) in 12 turns.
13 100 x 100 2600 0.01385 Racer reached goal at ( 50, 0) in 36 turns.
14 79 x 63 242 0.24380 Racer reached goal at ( 3, 42) in 59 turns.
15 26 x 1 25 0.32000 Racer reached goal at ( 25, 0) in 8 turns.
16 17 x 1 19 0.52632 Racer reached goal at ( 16, 0) in 10 turns.
17 50 x 1 55 0.34545 Racer reached goal at ( 23, 0) in 19 turns.
18 10 x 7 23 0.34783 Racer reached goal at ( 1, 3) in 8 turns.
19 55 x 55 45 0.17778 Racer reached goal at ( 50, 26) in 8 turns.
20 101 x 100 100 0.14000 Racer reached goal at ( 99, 99) in 14 turns.
21 100000 x 1 1 1.00000 Racer reached goal at ( 0, 0) in 1 turns.
22 50 x 50 200 0.05500 Racer reached goal at ( 47, 46) in 11 turns.
-------------------------------------------------------------------------------------
TOTAL SCORE: 6.49643
ruby controller.rb benchmark.txt python ../mybfs.py 3.06s user 0.06s system 99% cpu 3.146 total
```
[Answer]
## RandomRacer, ~40.0 (averaged over 10 runs)
It's not that this bot *never* finishes a track, but definitely much less often than once in 10 attempts. (I get a non-worst-case score every 20 to 30 simulations or so.)
This is mostly to act as a baseline case and to demonstrate a possible (Ruby) implementation for a racer:
```
# Parse initial input
target = gets.to_i
size = gets.split.map(&:to_i)
track = []
size[1].times do
track.push gets
end
time_budget = gets.to_f
# Find start position
start_y = track.find_index { |row| row['S'] }
start_x = track[start_y].index 'S'
position = [start_x, start_y]
velocity = [0, 0]
while true
x = rand(3) - 1
y = rand(3) - 1
puts [x,y].join ' '
$stdout.flush
first_line = gets
break if !first_line || first_line.chomp.empty?
position = first_line.split.map(&:to_i)
velocity = gets.split.map(&:to_i)
time_budget = gets.to_f
end
```
Run it with
```
ruby controller.rb benchmark.txt ruby randomracer.rb
```
[Answer]
**Random Racer 2.0, ~31**
Well this isn't going to beat the posted optimal solver, but it is a slight improvement on a random racer. Main difference is that this racer only will consider randomly going where there isn't a wall, unless it runs out of valid places to move, and if it can move to a goal that turn, it will. It also will not move in order to stay in the same spot, unless there is no other move available (unlikely, but possible).
Implemented in Java, compiled with java8, but Java 6 should be fine. No command line parameters. There's a pretty good clusterfuck of hierarchy, so I think I'm doing java right.
```
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class VectorRacing {
private static Scanner in = new Scanner(System.in);
private static Random rand = new Random();
private static Track track;
private static Racer racer;
private static int target;
private static double time;
public static void main(String[] args) {
init();
main_loop();
}
private static void main_loop() {
Scanner linescan;
String line;
int count = 0,
x, y, u, v;
while(!racer.lost() && !racer.won() && count < target) {
Direction d = racer.think();
racer.move(d);
count++;
System.out.println(d);
line = in.nextLine();
if(line.equals("")) {
break;
}
linescan = new Scanner(line);
x = linescan.nextInt();
y = linescan.nextInt();
linescan = new Scanner(in.nextLine());
u = linescan.nextInt();
v = linescan.nextInt();
time = Double.parseDouble(in.nextLine());
assert x == racer.location.x;
assert y == racer.location.y;
assert u == racer.direction.x;
assert v == racer.direction.y;
}
}
private static void init() {
target = Integer.parseInt(in.nextLine());
int width = in.nextInt();
int height = Integer.parseInt(in.nextLine().trim());
String[] ascii = new String[height];
for(int i = 0; i < height; i++) {
ascii[i] = in.nextLine();
}
time = Double.parseDouble(in.nextLine());
track = new Track(width, height, ascii);
for(int y = 0; y < ascii.length; y++) {
int x = ascii[y].indexOf("S");
if( x != -1) {
racer = new RandomRacer(track, new Location(x, y));
break;
}
}
}
public static class RandomRacer extends Racer {
public RandomRacer(Track t, Location l) {
super(t, l);
}
public Direction think() {
ArrayList<Pair<Location, Direction> > possible = this.getLocationsCanMoveTo();
if(possible.size() == 0) {
return Direction.NONE;
}
Pair<Location, Direction> ret = null;
do {
ret = possible.get(rand.nextInt(possible.size()));
} while(possible.size() != 1 && ret.a.equals(this.location));
return ret.b;
}
}
// Base things
public enum Direction {
NORTH("0 -1"), SOUTH("0 1"), EAST("1 0"), WEST("-1 0"), NONE("0 0"),
NORTH_EAST("1 -1"), NORTH_WEST("-1 -1"), SOUTH_EAST("1 1"), SOUTH_WEST("-1 1");
private final String d;
private Direction(String d) {this.d = d;}
public String toString() {return d;}
}
public enum Cell {
WALL('#'), GOAL('*'), ROAD('.'), OUT_OF_BOUNDS('?');
private final char c;
private Cell(char c) {this.c = c;}
public String toString() {return "" + c;}
}
public static class Track {
private Cell[][] track;
private int target;
private double time;
public Track(int width, int height, String[] ascii) {
this.track = new Cell[width][height];
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
switch(ascii[y].charAt(x)) {
case '#': this.track[x][y] = Cell.WALL; break;
case '*': this.track[x][y] = Cell.GOAL; break;
case '.':
case 'S': this.track[x][y] = Cell.ROAD; break;
default: System.exit(-1);
}
}
}
}
public Cell atLocation(Location loc) {
if(loc.x < 0 || loc.x >= track.length || loc.y < 0 || loc.y >= track[0].length) return Cell.OUT_OF_BOUNDS;
return track[loc.x][loc.y];
}
public String toString() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bos);
for(int y = 0; y < track[0].length; y++) {
for(int x = 0; x < track.length; x++) {
ps.append(track[x][y].toString());
}
ps.append('\n');
}
String ret = bos.toString();
ps.close();
return ret;
}
}
public static abstract class Racer {
protected Velocity tdir;
protected Location tloc;
protected Track track;
public Velocity direction;
public Location location;
public Racer(Track track, Location start) {
this.track = track;
direction = new Velocity(0, 0);
location = start;
}
public boolean canMove() throws GoHereDammitException {return canMove(Direction.NONE);}
public boolean canMove(Direction d) throws GoHereDammitException {
tdir = new Velocity(direction);
tloc = new Location(location);
tdir.add(d);
tloc.move(tdir);
Cell at = track.atLocation(tloc);
if(at == Cell.GOAL) {
throw new GoHereDammitException();
}
return at == Cell.ROAD;
}
public ArrayList<Pair<Location, Direction> > getLocationsCanMoveTo() {
ArrayList<Pair<Location, Direction> > ret = new ArrayList<Pair<Location, Direction> >(9);
for(Direction d: Direction.values()) {
try {
if(this.canMove(d)) {
ret.add(new Pair<Location, Direction>(tloc, d));
}
} catch(GoHereDammitException e) {
ret.clear();
ret.add(new Pair<Location, Direction>(tloc, d));
return ret;
}
}
return ret;
}
public void move() {move(Direction.NONE);}
public void move(Direction d) {
direction.add(d);
location.move(direction);
}
public boolean won() {
return track.atLocation(location) == Cell.GOAL;
}
public boolean lost() {
return track.atLocation(location) == Cell.WALL || track.atLocation(location) == Cell.OUT_OF_BOUNDS;
}
public String toString() {
return location + ", " + direction;
}
public abstract Direction think();
public class GoHereDammitException extends Exception {
public GoHereDammitException() {}
}
}
public static class Location extends Point {
public Location(int x, int y) {
super(x, y);
}
public Location(Location l) {
super(l);
}
public void move(Velocity d) {
this.x += d.x;
this.y += d.y;
}
}
public static class Velocity extends Point {
public Velocity(int x, int y) {
super(x, y);
}
public Velocity(Velocity v) {
super(v);
}
public void add(Direction d) {
if(d == Direction.NONE) return;
if(d == Direction.NORTH || d == Direction.NORTH_EAST || d == Direction.NORTH_WEST) this.y--;
if(d == Direction.SOUTH || d == Direction.SOUTH_EAST || d == Direction.SOUTH_WEST) this.y++;
if(d == Direction.EAST || d == Direction.NORTH_EAST || d == Direction.SOUTH_EAST) this.x++;
if(d == Direction.WEST || d == Direction.NORTH_WEST || d == Direction.SOUTH_WEST) this.x--;
}
}
public static class Point {
protected int x, y;
protected Point(int x, int y) {
this.x = x;
this.y = y;
}
protected Point(Point c) {
this.x = c.x;
this.y = c.y;
}
public int getX() {return x;}
public int getY() {return y;}
public String toString() {return "(" + x + ", " + y + ")";}
public boolean equals(Point p) {
return this.x == p.x && this.y == p.y;
}
}
public static class Pair<T, U> {
public T a;
public U b;
public Pair(T t, U u) {
a=t;b=u;
}
}
}
```
**The Results (Best case I've seen)**
```
Running 'java VectorRacing' against ruby-runner/benchmark.txt
No. Size Target Score Details
-------------------------------------------------------------------------------------
1 37 x 1 36 0.38889 Racer reached goal at ( 36, 0) in 14 turns.
2 38 x 1 37 0.54054 Racer reached goal at ( 37, 0) in 20 turns.
3 33 x 1 32 0.62500 Racer reached goal at ( 32, 0) in 20 turns.
4 10 x 10 10 0.40000 Racer reached goal at ( 9, 8) in 4 turns.
5 9 x 6 8 0.75000 Racer reached goal at ( 6, 2) in 6 turns.
6 15 x 7 16 2.00000 Racer did not reach the goal within 16 turns.
7 17 x 8 16 2.00000 Racer hit a wall at position ( 8, 2).
8 19 x 13 18 0.44444 Racer reached goal at ( 16, 2) in 8 turns.
9 60 x 10 107 0.65421 Racer reached goal at ( 0, 6) in 70 turns.
10 31 x 31 106 2.00000 Racer hit a wall at position ( 25, 9).
11 31 x 31 106 2.00000 Racer hit a wall at position ( 8, 1).
12 50 x 20 50 2.00000 Racer hit a wall at position ( 27, 14).
13 100 x 100 2600 2.00000 Racer went out of bounds at position ( 105, 99).
14 79 x 63 242 2.00000 Racer went out of bounds at position (-2, 26).
15 26 x 1 25 0.32000 Racer reached goal at ( 25, 0) in 8 turns.
16 17 x 1 19 2.00000 Racer went out of bounds at position (-2, 0).
17 50 x 1 55 2.00000 Racer went out of bounds at position ( 53, 0).
18 10 x 7 23 2.00000 Racer went out of bounds at position ( 10, 2).
19 55 x 55 45 0.33333 Racer reached goal at ( 4, 49) in 15 turns.
20 50 x 50 200 2.00000 Racer hit a wall at position ( 14, 7).
-------------------------------------------------------------------------------------
TOTAL SCORE: 26.45641
```
] |
[Question]
[
Imagine the following scenario: you are playing battleships with a friend but decide to cheat. Rather than moving a ship after he shoots where your ship used to be, you decide not to place any ships at all. You tell him all his shots are misses, until it is impossible to place ships in such a way.
You have to write a function, or a full program, that somehow takes 3 arguments: the field size, a list of amounts of ship sizes, and a list of shots.
### Battlefield
One of the given parameters is the board size. The battlefield is a square of cells, and the given parameter is simply one side of the square.
For example, the following is a board of size 5.
![](https://i.stack.imgur.com/aBHee.png)
Coordinates on the field are specified as a 2-component string: a letter followed by a number. You can rely on the letters being in some particular case.
Letter specifies the column, number specifies the row of the cell (1-indexed). For example in the above picture, the highlighted cell is denoted by `"D2"`.
Since there are only 26 letters, the field can't be larger than 26x26.
### Ships
The ships are straight lines of 1 or more blocks. The amount of ships is specified in a list, where the first element is the amount of 1-cell ships, second - of 2-cell ships and so on.
For instance, the list `[4,1,2,0,1]` would create the following shipset:
![](https://i.stack.imgur.com/X9EOJ.png)
When placed on the battlefield, ships cannot intersect, or even touch each other. Not even with corners. They can however touch the edges of the field.
Below you can see an example of valid ship placement:
![](https://i.stack.imgur.com/KaQnX.png)
You can assume that for a given shipset, there always exists a placement on an empty board of given size.
### Output
If such placements of ships exist, you have to output any of them.
The program has to output a newline-separated matrix of ascii characters of either of 3 types - one to denote blank cell, one - a ship piece, and one - a cell marked as "missed". No other characters should be output.
For example,
```
ZZ@Z
\@@Z
@\\Z
\Z\\
```
(In this example, I defined `@` to be blank cell, `\` to be a "missed" cell, and `Z` to be ship piece)
If no such placement exists, the program/function should return without outputting anything.
### Input
If you decide to make a fullblown program, it's up to specify you how the lists are input, some might go via arguments, some via stdin.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest amount of characters wins.
An example non-golfed optimized solution can be found [here](http://qp.mniip.com/p/t3)
Compile with `-std=c99`, first argument is the size of the board, the other arguments are ship sizes. A newline-separated list of shots is given on stdin. Example:
`./a 4 1 1 1 <<< $'A2\nA4\nB3\nC3\nC4\D4'`
[Answer]
# SWI-Prolog, ~~536~~ 4411 bytes
1 UNIX line ending, final new line not counted
The version with all optimizations removed (**441** bytes):
```
:-[library(clpfd)].
m(G,L):-maplist(G,L).
l(L,A):-length(A,L).
y(A,E,(X,Y)):-nth1(X,A,R),nth1(Y,R,F),var(F),F=E.
a(A,S):-l(L,A),X#>0,X#=<L,Y#>0,Y#=<L,h(S,(X,Y),A).
h(0,_,_).
h(L,(X,Y),A):-(B=A;transpose(A,T),B=T),y(B,s,(X,Y)),M#=L-1,Z#=Y+1,h(M,(X,Z),B).
e([],_,[]).
e([H|R],I,O):-J#=I+1,e(R,J,P),l(H,Q),Q ins I,append(P,Q,O).
r(R):-m(c,R),nl.
c(E):-var(E)->put(@);put(E).
g(L,H,S):-l(L,A),m(l(L),A),m(y(A,\),S),e(H,1,G),!,m(a(A),G),!,m(r,A).
```
Since the code is changed to minimize the number of bytes, it will no longer accept a list of shots that have duplicates.
---
The version with basic optimization, fully golfed (**536 → 506** bytes)
```
:-[library(clpfd)].
m(G,L):-maplist(G,L).
l(L,A):-length(A,L).
x(A,I,E):-X=..[a|A],arg(I,X,E).
y(A,E,(X,Y)):-x(A,X,R),x(R,Y,E).
a(A,S):-l(L,A),X#>0,X#=<L,Y#>0,Y#=<L,(B=A;transpose(A,T),B=T),h(S,(X,Y),B).
h(0,_,_).
h(L,(X,Y),A):-y(A,E,(X,Y)),var(E),E=s,M#=L-1,Z#=Y+1,h(M,(X,Z),A).
e([],_,[]).
e([H|R],I,O):-J#=I+1,e(R,J,P),l(H,Q),Q ins I,append(P,Q,O).
r(R):-m(c,R),nl.
c(E):-var(E)->put(@);put(E).
g(L,H,S):-l(L,A),m(l(L),A),sort(S,T),m(y(A,\),T),e(H,1,G),!,l(E,T),sumlist(G,D),L*L-E>=D,m(a(A),G),!,m(r,A).
```
I implement some basic checks (**count number of ship blocks necessary**) to make the code exits faster for clearly impossible cases. The code is also **immune to duplicate** in the list of shots so far.
---
Below is the (somewhat) readable version, with detailed comments:
```
:-[library(clpfd)].
% Shorthand for maplist, which works like map in high order function
m(G,L):-maplist(G,L).
% Creating a square matrix A which is L x L
board(L,A):-l(L,A),m(l(L),A).
% Shorthand for length, with order of parameters reversed
l(L,A):-length(A,L).
% Unification A[I] = E
x(A,I,E):-X=..[a|A],arg(I,X,E).
% Unification A[X][Y]=E
idx2(A,E,(X,Y)):-x(A,X,R),x(R,Y,E).
% Mark positions that have been shot
markshot(A,S):-m(idx2(A,\),S).
% Place all ships on the board
placeships(H,A):-m(placeship(A),H).
% Place a length S ship horizontal/vertical forward on the board
placeship(A,S):-
l(L,A), % Get length
X#>0,X#=<L,Y#>0,Y#=<L, % Constraint X and Y coordinates
transpose(A,T), % Transpose to work on columns
(placeship_h(S,(X,Y),A) ; placeship_h(S,(Y,X),T)).
% Place ship horizontal, forward at (X,Y)
placeship_h(0,_,_).
placeship_h(L,(X,Y),A):-
idx2(A,E,(X,Y)),var(E),E=s, % Make sure position is unassigned, then mark
L2#=L-1,Y2#=Y+1, % Do this for all blocks of the ship
placeship_h(L2,(X,Y2),A).
% Expand the list of ships
% e.g. [2,3,1] --> [3,2,2,2,1,1]
shipexpand(S,O):-shipexpand(S,1,O).
shipexpand([],_,[]).
shipexpand([H|R],I,O):-
I2#=I+1,shipexpand(R,I2,O2), % process the rest
l(H,O1),O1 ins I, % duplicate current ship size H times
append(O2,O1,O). % larger ship size goes in front
% Print the result
pboard(A):-m(prow,A).
prow(R):-m(pcell,R),print('\n').
pcell(E):-var(E)->print(@);print(E).
game(L,H,S):-
board(L,A), % create board
sort(S,SS), % remove duplicates
markshot(A,SS), % mark positions that have been shot
shipexpand(H,HH),!, % make a list of ships
l(SC,SS),sumlist(HH,BC),L*L-SC>=BC, % check to speed-up, can be removed
placeships(HH,A),!, % place ships
pboard(A). % print result
```
Query format:
```
game(Board_Size, Ships_List, Shots_List).
```
Sample query (using the sample in the question):
```
?- game(4,[1,1,1],[(2,1),(3,2),(3,3),(4,1),(4,3),(4,4)]).
ssss
\ss@
@\\@
\@\\
true.
?- game(4,[2,2,0,1],[(2,1),(3,2),(3,3),(4,1),(4,3),(4,4)]).
ssss
\sss
s\\s
\s\\
true.
```
[Answer]
# Matlab - 536 chars
*Updated: Much smaller output formatting, some loop whitespace removed.*
*Updated: Added golfed version*
*Updated: Added commented version, reduced golfed version by ~100 chars*
```
% Battleship puzzle solver.
%
% n: size of the map (ex. 4 -> 4x4)
% sh: list of shots (ex. ['A2';'C4'])
% sp: ships of each size (ex. [2,0,1] -> 2x1 and 1x3)
%
function bs(n,sh,sp)
% sp holds a vector of ship counts, where the index of each element is
% the size of the ship. s will hold a vector of ship sizes, with order
% not mattering. This is easier to work with using recursion, because
% we can remove elements with Matlab's array subselection syntax, rather
% than decrement elements and check if they're zero.
%
% Tricks:
% Since sp never contains a -1, find(1+sp) is the same as 1:length(sp)
% but is three characters shorter.
%
s=[];
for i=find(1+sp)
s(end+1:end+sp(i))=i;
end
% m will hold the map. It will be +2 in each direction, so that later we
% can find neighbors of edge-spaces without checking bounds. For now,
% each element is either '0' or '1' for a space or missed shot,
% respectively. We convert the shots as provided by the user (ex. 'A2')
% to marks on the map.
%
% Tricks:
% It takes one shorter character to subtract 47 than 'A' to determine
% the indices into the map.
%
m=zeros(n+2);
for h=sh'
m(h(2)-47,h(1)-63)=1;
end
% Solve the puzzle. q will either be the empty array or a solution map.
%
q=pp(m,s);
% If a solution was found, output it, showing the original shots and the
% ship placement. If no solution was found, print a sad face.
%
% Tricks:
% q is 0 on failure, which is treated like 'false'. q is a matrix on
% success which is NOT treated like 'true', so we have to check for
% failure first, then handle success in the 'else' block.
%
% q contains the "fake shots" that surround each placed ship (see the
% pl function). We don't want to output those, so we just copy the ship
% markings into the original map.
%
if ~q ':('
else
m(find(q==2))=2;
num2str(m(2:n+1,2:n+1),'%d')
end
% Depth-first search for a solution.
%
% m: map (see main code above)
% s: vector of ship sizes to place in the map
%
% Returns q: square matrix of integers, updated with all requested ship
% sizes, or 0 if no solution is possible.
%
function q = pp(m,s)
% If we have no ships to process, we're all done recursing and the
% current map is a valid solution. Rather than handle this in an 'else'
% block, we can assume it's the case and overwrite q if not, saving 4
% characters.
%
q=m;
% If we have any ships to place...
%
% Tricks:
% Since we are only interested in positive values in s, we can use
% sum(s) in place of isempty(s), saving 4 characters.
%
if sum(s)
% Try to place the first ship in the list into the map, both vertically
% (first call to p) and vertically (second call to p). We can process
% any ship in the list, but the first can be removed from the list
% with the fewest characters. r will hold a cell-array of options for
% this ship.
%
r=[p(m,s(1),0),p(m',s(1),1)];
% Recurse for each option until we find a solution.
%
% Tricks:
% Start with q, our return variable, set to 0 (indicating no solution
% was found. On each loop we'll only bother to recurse if q is still
% 0. This relieves the need for if/else to check whether to continue
% the loop, or any final q=0 if the loop exits without success.
%
% Sadly, there's no way around the length(r) call. Matlab doesn't
% provide syntax for iterating over cell-arrays.
%
q=0;
for i=1:length(r)
if ~q q=pp(r{i},s(2:end));end
end
end
% Place a single ship into a map.
%
% m: map (see main code above)
% s: ship size to place
% t: if the map has been transposed prior to this call
%
% Returns r: cell-array of possible maps including this ship
%
function r=p(m,s,t)
% Start with an empty cell-array and pre-compute the size of the map,
% which we'll need to use a few times.
%
r={};
z=size(m);
% For each row (omitting the first and last 'buffer' rows)...
%
for i=2:z(2)-1
% For each starting column in this row where enough consecutive 0s
% appear to fit this ship...
%
for j=strfind(m(i,2:end-1),(1:s)*0)
% Copy the map so we can modify it without overwriting the variable
% for the next loop.
%
n=m;
% For each location on the map that is part of this optional
% placement...
for l=0:s-1
% Let's leave this is an exercise for the reader ;)
%
v=-1:1;
n([(l+j)*z(1)+i,z(1),1]*[ones(1,9);kron(v,[1 1 1]);[v v v]])=1;
end
% Mark each location that is part of this optional placement with
% a '2'.
%
n(i,1+j:j+s)=2;
% Since our results are going into a cell-array it won't be
% convenient for the caller to undo any transpositions they might
% have done. If the t flag is set, transpose this map back before
% adding it to the cell-array.
%
if t n=n';end
r{end+1}=n;
end
end
```
Here is the golfed version.
```
function bs(n,sh,sp)
s=[];for i=find(1+sp)
s(end+1:end+sp(i))=i;end
m=zeros(n+2);for h=sh'
m(h(2)-47,h(1)-63)=1;end
q=pp(m,s);if ~q ':('
else
m(find(q==2))=2;num2str(m(2:n+1,2:n+1),'%d')
end
function q = pp(m,s)
q=m;if sum(s)
r=[p(m,s(1),0),p(m',s(1),1)];q=0;for i=1:length(r)if ~q q=pp(r{i},s(2:end));end
end
end
function r=p(m,s,t)
r={};z=size(m);for i=2:z(2)-1
for j=strfind(m(i,2:end-1),(1:s)*0)n=m;for l=0:s-1
v=-1:1;n([(l+j)*z(1)+i,z(1),1]*[ones(1,9);kron(v,[1 1 1]);[v v v]])=1;end
n(i,1+j:j+s)=2;if t n=n';end
r{end+1}=n;end
end
```
Here's some samples.
```
>>bs(4,['A1';'B3'],[2,1])
1220
0000
2120
0000
>>bs(4,['A1';'B4'],[2,2])
1022
2000
0022
2100
>> bs(4,['A1';'B4';'C2'],[3,1])
1022
2010
0020
2100
>> bs(4,['A1';'B4';'C2'],[3,2])
:(
```
The big line with 'kron' (near the bottom of the un-golfed code) is my favorite part of this. It writes a '1' to all locations in the map that neighbor a given position. Can you see how it works? It uses the kronecker tensor product, matrix multiplication, and indexes the map as linear array...
[Answer]
## Python, 464 chars
```
B,L,M=input()
R=range(B)
C=B+1
M=sum(1<<int(m[1:])*C-C+ord(m[0])-65for m in M)
def P(L,H,S):
if len(L)==0:
for y in R:print''.join('.#!'[(S>>y*C+x&1)+2*(M>>y*C+x&1)]for x in R)
return 1
for s in[2**L[0]-1,sum(1<<C*j for j in range(L[0]))]:
for i in range(C*C):
if H&s==s and P(L[1:],H&~(s|s<<1|s>>1|s<<B|s>>B|s<<C|s>>C|s<<C+1|s>>C+1),S|s):return 1
s*=2
return 0
P(sum(([l+1]*k for l,k in enumerate(L)),[])[::-1],sum((2**B-1)<<B*j+j for j in R)&~M,0)
```
Input (stdin):
```
7, [4,1,2,0,1], ['A1','B2','C3']
```
Output:
```
!#####.
.!.....
##!###.
.......
###.#.#
.......
#.#....
```
Works using integers holding bitmaps of various features:
```
M = bitmap of misses
H = bitmap of holes where ships can still go
S = bitmap of ships already placed
L = list of ship sizes not yet placed
B = dimension of board
C = bitmap row length
```
[Answer]
# Python, 562 characters, -8 with ugly output, +4? for bash invocation
```
I=int;R=range
import sys;a=sys.argv
S=I(a[1]);f=[[0]*(S+2)for _ in R(S+2)]
C=a[2].split()
X=[]
for i,n in enumerate(C):X=[i+1]*I(n)+X
Q=a[3].split()
for q in Q:f[I(q[1:])][ord(q[0])-64]=1
D=R(-1,2)
V=lambda r,c:(all(f[r+Q][c+W]<2for Q in D for W in D),0,0)[f[r][c]]
def F(X):
if not X:print"\n".join(" ".join(" .@"[c]for c in r[1:-1])for r in f[1:-1])
x=X[0];A=R(1,S+1)
for r in A:
for c in A:
for h in(0,1):
def P(m):
for i in R(x):f[(r+i,r)[h]][(c,c+i)[h]]=m
if(r+x,c+x)[h]<S+2and all(V((r+i,r)[h],(c,c+i)[h])for i in R(x)):P(2);F(X[1:]);P(0)
F(X)
```
Note: the indent levels are space, tab, tab + space, tab + tab, and tab + tab + space. This saves a few characters from using spaces only.
**Usage and example**:
Takes input from command line arguments. Outputs a blank as a space, a shot as a `.`, and a `@` as part of a ship:
```
$ python bships_golf.py "7" "4 0 2 0 1" \
"A1 C3 B5 E4 G6 G7 A3 A4 A5 A6 C1 C3 C5 C7 B6 B7 D1 D2 G3" 2>X
. @ . . @ @ @
@ .
. @ . @ @ .
. @ .
. . . @ @
. . @ .
@ . . @ @ .
```
When unsolvable, prints nothing:
```
$ python bships_golf.py "3" "2" "A1 A3 B1 C1 C3" 2>X
. . .
@ @
. .
$ python bships_golf.py "3" "2" "A1 A2 A3 B1 C1 C3" 2>X
$
```
The `2>X` is to suppress an error message since the program exits by throwing an exception. Feel free to add a +4 penalty if deemed fair. Otherwise I'd have to do a `try: ... except:0` to suppress it, which would take more characters anyway.
I can also print the output as numbers (`0`, `1`, and `2`) to shave off 8 characters, but I value aesthetics.
**Explanation**:
I represent the board as a list of lists of integers with size 2 greater than the input, to avoid having to do bounds checking. `0` represents an empty space, `1` a shot, and `2` a ship. I run through the shots list `Q` and mark all the shots. I convert the list of ships to an explicit list `X` of ships, e.g. `[4, 0, 2, 0, 1]` becomes `[5, 3, 3, 1, 1, 1, 1]`. Then it's a simple backtracking algorithm: in order of descending size order, try to place a ship, and then try to place the rest of the ships. If it doesn't work, try the next slot. As soon as it succeeds, the ship list `X` is null, and accessing `X[0]` throws an exception which quits the program. The rest is just heavy golfing (was initially 1615 characters).
[Answer]
### GolfScript, 236 characters
```
n%([~](:N):M;[.,,]zip{~[)]*~}%-1%:S;{(65-\~(M*+}%:H;{{M*+}+N,/}N,%H-S[]]]{(~\.{(:L;{{M*+{+}+L,%}+N)L-,/}N,%{.{.M/\M%M*+}%}%{3$&,L=},{:K[{..M+\M-}%{..)\(}%3$\- 1$3$K+]}%\;\;\;\+.}{;:R;;;0}if}do{{{M*+.H?)'!'*\R?)'#'*'.'++1<}+N,/n}N,%}R!!*
```
The input is given on STDIN. First line contains size and number of ships, each following line coordinates of a single shot.
*Example:*
```
4 1 1 1
A2
A4
B3
C3
C4
D4
##.#
!..#
#!!#
!.!!
```
I thought that also this challenge should have at least one GolfScript answer. In the end it became very ungolfscriptish due to the used algorithm which favours performance over shortness.
*Annotated code:*
```
n% # Split the input into lines
([~] # The first line is evaluated to an array [N S1 S2 S3 ...]
(:N # This happy smiley removes the first item and assigns it to variable N
):M; # While this sad smiley increases N by one and assigns it to M
[.,,]zip # For the rest of numbers in the first line create the array [[0 S1] [1 S2] [2 S3] ...]
{~[)]*~}% # Each element [i Si] is converted into the list (i+1 i+1 ... i+1) with Si items.
-1%:S; # Reverse (i.e. largest ship first) and assign the list to variable S.
# The result is a list of ship lengths, e.g. for input 3 0 2 we have S = [3 3 1 1 1].
{ # On the stack remains a list of coordinates
(65- # Convert the letter from A,B,... into numeric value 0,1,...
\~( # The number value is decreased by one
M*+ # Both are combined to a single index (M*row+col)
}%:H; # The list of shots is then assigned to variable H
# The algorithm is recursive backtracking implemented using a stack of tuples [A S R] where
# - A is the list of open squares
# - S is a list of ships to be placed
# - R is the list of positions where ships were placed
{{ # initial A is the full space of possible coordinates
M*+ # combine row and column values into a single index
}+N,/}N,% # do the N*N loop
H- # minus all places where a shot was done already
S # initial S is the original list
[] # initial R is the empty list (no ships placed yet)
]
] # The starting point is pushed on the stack
{ # Start of the loop running on the stack
(~\ # Pop from the stack and extract items in order A R S
.{ # If S is non-empty
(:L; # Take first item in S (longest ship) and asign its length to L
{{M*+{+}+L,%}+N)L-,/}N,%{.{.M/\M%M*+}%}%
# This lengthy expression just calculates all possible ship placements on a single board
# (could be shortened by 3 chars if we don't respect board size but I find it clearer this way)
{3$&,L=}, # This step is just a filter on those placements. The overlap (&) with the list of open squares (3$)
# must be of size L, i.e. all coordinates must be free
# Now we have possible placements. For each one generate the appropriate tuple (A* S* R*) for recursion
{
:K # Assign the possible new ship placement to temporary variable K
[
{..M+\M-}%
{..)\(}%
# For each coordinate add the square one row above and below (first loop)
# and afterwards for the resulting list also all squares left and right (second loop)
3$\- # Remove all these squares from the list of available squares A in order to get the new A*
1$ # Reduced list of ships S* (note that the first item of S was already remove above)
3$K+ # Last item in tuple is R* = R + K, i.e. the ship's placements are added to the result
]
}%
\;\;\; # Discard the original values A R S
\+ # Push the newly generated tuples on the stack
. # Loop until the stack is empty
}{ # else
;:R;;; # Assign the solution to the variable R and remove all the rest from the stack.
0 # Push a zero in order to break the loop
}if # End if
}do # End of the loop
{ # The output block starts here
{{
M*+
.H?) # Is the current square in the list of shots?
'!'* # then take a number of '!' otherwise an empty string
\R?) # Is the current square in the list of ships?
'#'* # then take a number of '#' otherwise an empty string
'.'++ # Join both strings and append a '.'
1< # Take the first item of the resulting string, i.e. altogether this is a simple if-else-structure
}+N,/n}N,% # Do a N*N loop
}
R!!* # Run this block only if R was assigned something during the backtracking.
# (!! is double-negation which converts any non-zero R into a one)
# Note: since the empty list from the algorithm is still on the stack if R wasn't assigned
# anything the operator !! works on the code block (which yields 1) which is then multiplied
# with the empty list.
```
[Answer]
## Perl, ~~455 447 437 436 422~~ 418
```
$n=($N=<>+0)+1;@S=map{(++$-)x$_}<>=~/\d+/g;$_=<>;$f=('~'x$N.$/)x$N;substr($f,$n*$1-$n-65+ord$&,1)=x while/\w(\d+)/g;sub f{for my$i(0..$N*$n-1){for(0..@_-2){my($f,@b)=@_;$m=($s=splice@b,$_,1)-1;pos=pos($u=$_=$f)=$i;for(s/\G(~.{$N}){$m}~/$&&("\0"."\377"x$N)x$s|(o."\0"x$N)x$m.o/se?$_:(),$u=~s/\G~{$s}/o x$s/se?$u:()){for$k(0,$N-1..$n){s/(?<=o.{$k})~|~(?=.{$k}o)/!/sg}return$:if$:=@b?f($_,@b):$_}}}}$_=f$f,@S;y/!/~/;print
```
Indented:
```
$n=($N=<>+0)+1;
@S=map{(++$-)x$_}<>=~/\d+/g;
$_=<>;
$f=('~'x$N.$/)x$N;
substr($f,$n*$1-$n-65+ord$&,1)=x while/\w(\d+)/g;
sub f{
for my$i(0..$N*$n-1){
for(0..@_-2){
my($f,@b)=@_;
$m=($s=splice@b,$_,1)-1;
pos=pos($u=$_=$f)=$i;
for(s/\G(~.{$N}){$m}~/
$&&("\0"."\377"x$N)x$s|(o."\0"x$N)x$m.o/se?$_:(),
$u=~s/\G~{$s}/o x$s/se?$u:()){
for$k(0,$N-1..$n){
s/(?<=o.{$k})~|~(?=.{$k}o)/!/sg
}
return$:if$:=@b?f($_,@b):$_
}
}
}
}
$_=f$f,@S;
y/!/~/;
print
```
I expect it can be golfed further (e.g. with `eval<>` for pre-formatted input, as I see it's OK (?)), and also some other things (50 `$` sigils? no, they'll stay).
Speed, as I said earlier, can be an issue (from instantaneous (see example below) to very-very long), depending on where the solution is on recursion tree, but let it be the question of obsolescence of hardware used. I'll do optimized version later, with recursion gone and 2-3 other obvious tricks.
It's run like this, 3 lines being fed through STDIN:
```
$ perl bf.pl
7
4 1 2 0 1
A1 B2 C3
xo~o~o~
~x~~~~~
o~xo~o~
~~~o~o~
o~~~~o~
o~~~~~~
o~ooooo
```
`~` is the ocean (artistic solution, isn't it), `o`'s and `x`s are ships and shots.
First 5 lines get the input and prepare our 'battlefield'. `$N` is size, `@S` is unrolled array of ships (e.g. `1 1 1 1 2 3 3 5` as above), `$f` is a string representing battlefield (rows with newlines concatenated). Next is recursive subroutine, which expects current battlefield state and list of remaining ships. It checks left to right, top to bottom and tries to place each ship in each position, both horizontally and vertically (see? Ripe to optimize, but that'll be later). Horizontal ship is obvious regexp replacement, vertical a bit trickier -- bitwise string manipulation to replace in 'column'. On success (H, V or both), new inaccessible positions are marked with `!`, and it forks to next iteration. And so on.
**Edit:** OK, here's **594** bytes (when un-indented) version that actually tries to be useful (i.e. fast) - optimized to the best of my ability while still implementing the same techniques - recursion (albeit done 'manually') and regexps. It maintains a 'stack' - `@A` - array of states worth to investigate. A 'state' is 4 variables: current battlefield string, index from where to start trying to place ships, reference to array of remaining ships, and index of next ship to try. Initially there's a single 'state' - start of empty string, all ships. On match (H or V, see above), current state is pushed to investigate later, updated state (with a ship placed and inaccessible positions marked) is pushed and block is restarted. When end of battlefield string is reached without success, next available state from `@A` is investigated (if any).
Other optimizations are: not restarting from the very beginning of the string, trying to place large ships first, not checking ship of same size if previous one failed in the same position, + maybe something else (like no `$&` variable etc.).
```
$N=<>+0;
$S=[reverse map{(++$-)x$_}<>=~/\d+/g];
$_=<>;
$f=('~'x$N.$/)x$N;
substr($f,$N*$2-$N+$2-66+ord$1,1)=x while/(\w)(\d+)/g;
push@A,$f,0,$S,0;
O:{
($f,$i,$S,$m)=splice@A,-4;
last if!@$S;
F:{
for$j($m..$#$S){
next if$j and$$S[$j]==$$S[$j-1];
$s=$$S[$j];
my@m;
$_=$f;
$n=$s-1;
pos=$i;
push@m,$_ if s/\G(?:~.{$N}){$n}~/
${^MATCH}&("\0"."\377"x$N)x$s|(o."\0"x$N)x$n.o/pse;
$_=$f;
pos=$i;
push@m,$_ if s/\G~{$s}/o x$s/se;
if(@m){
push@A,$f,$i,$S,$j+1;
my@b=@$S;
splice@b,$j,1;
for(@m){
for$k(0,$N-1..$N+1){
s/(?<=o.{$k})~|~(?=.{$k}o)/!/gs
}
push@A,$_,$i+1,\@b,0
}
redo O
}
}
redo if++$i-length$f
}
redo if@A
}
print@$S?'':$f=~y/!/~/r
```
.
```
perl bf+.pl
10
5 4 3 2 1
A1 B2 C3 A10 B9 C10 J1 I2 H3 I9 J10 A5 C5 E5 F6 G7
xooooo~oox
~x~~~~~~x~
ooxooooxo~
~~~~~~~~o~
xoxoxoo~o~
~o~o~x~~o~
~o~o~ox~~~
~~~~~o~ooo
oxo~~~~~x~
x~x~o~o~ox
```
OTOH, it still takes forever for impossible case `6 5 4 3 2 1` in example above. Maybe practical version should exit immediately if total ship tonnage exceeds battlefield capacity.
[Answer]
# C# solution
```
public static class ShipSolution {
private static int[][] cloneField(int[][] field) {
int[][] place = new int[field.Length][];
for (int i = 0; i < field.Length; ++i) {
place[i] = new int[field.Length];
for (int j = 0; j < field.Length; ++j)
place[i][j] = field[i][j];
}
return place;
}
private static void copyField(int[][] source, int[][] target) {
for (int i = 0; i < source.Length; ++i)
for (int j = 0; j < source.Length; ++j)
target[i][j] = source[i][j];
}
// Check if placement a legal one
private static Boolean isPlacement(int[][] field, int x, int y, int length, Boolean isHorizontal) {
if (x < 0)
return false;
else if (y < 0)
return false;
else if (x >= field.Length)
return false;
else if (y >= field.Length)
return false;
if (isHorizontal) {
if ((x + length - 1) >= field.Length)
return false;
for (int i = 0; i < length; ++i)
if (field[x + i][y] != 0)
return false;
}
else {
if ((y + length - 1) >= field.Length)
return false;
for (int i = 0; i < length; ++i)
if (field[x][y + i] != 0)
return false;
}
return true;
}
// When ship (legally) placed it should be marked at the field
// 2 - ship itself
// 3 - blocked area where no other ship could be placed
private static void markPlacement(int[][] field, int x, int y, int length, Boolean isHorizontal) {
if (isHorizontal) {
for (int i = 0; i < length; ++i)
field[x + i][y] = 2;
for (int i = x - 1; i < x + length + 1; ++i) {
if ((i < 0) || (i >= field.Length))
continue;
for (int j = y - 1; j <= y + 1; ++j)
if ((j >= 0) && (j < field.Length))
if (field[i][j] == 0)
field[i][j] = 3;
}
}
else {
for (int i = 0; i < length; ++i)
field[x][y + i] = 2;
for (int i = x - 1; i <= x + 1; ++i) {
if ((i < 0) || (i >= field.Length))
continue;
for (int j = y - 1; j < y + length + 1; ++j)
if ((j >= 0) && (j < field.Length))
if (field[i][j] == 0)
field[i][j] = 3;
}
}
}
// Ship placement itteration
private static Boolean placeShips(int[][] field, int[] ships) {
int[] vessels = new int[ships.Length];
for (int i = 0; i < ships.Length; ++i)
vessels[i] = ships[i];
for (int i = ships.Length - 1; i >= 0; --i) {
if (ships[i] <= 0)
continue;
int length = i + 1;
vessels[i] = vessels[i] - 1;
// Possible placements
for (int x = 0; x < field.Length; ++x)
for (int y = 0; y < field.Length; ++y) {
if (isPlacement(field, x, y, length, true)) {
int[][] newField = cloneField(field);
// Mark
markPlacement(newField, x, y, length, true);
if (placeShips(newField, vessels)) {
copyField(newField, field);
return true;
}
}
if (length > 1)
if (isPlacement(field, x, y, length, false)) {
int[][] newField = cloneField(field);
// Mark
markPlacement(newField, x, y, length, false);
if (placeShips(newField, vessels)) {
copyField(newField, field);
return true;
}
}
}
return false; // <- the ship can't be placed legally
}
return true; // <- there're no more ships to be placed
}
/// <summary>
/// Solve ship puzzle
/// </summary>
/// <param name="size">size of the board</param>
/// <param name="ships">ships to be placed</param>
/// <param name="misses">misses in (line, column) format; both line and column are zero-based</param>
/// <returns>Empty string if there is no solution; otherwise possible ship placement where
/// . - Blank place
/// * - "miss"
/// X - Ship
/// </returns>
public static String Solve(int size, int[] ships, String[] misses) {
int[][] field = new int[size][];
for (int i = 0; i < size; ++i)
field[i] = new int[size];
if (!Object.ReferenceEquals(null, misses))
foreach (String item in misses) {
String miss = item.Trim().ToUpperInvariant();
int x = int.Parse(miss.Substring(1)) - 1;
int y = miss[0] - 'A';
field[x][y] = 1;
}
if (!placeShips(field, ships))
return "";
StringBuilder Sb = new StringBuilder();
foreach (int[] line in field) {
if (Sb.Length > 0)
Sb.AppendLine();
foreach (int item in line) {
if (item == 1)
Sb.Append('*');
else if (item == 2)
Sb.Append('X');
else
Sb.Append('.');
}
}
return Sb.ToString();
}
}
...
int size = 4;
int[] ships = new int[] { 1, 1, 1 };
String[] misses = new String[] {"C1", "C2", "B2", "A3", "A1", "B3", "D1"};
// *X**
// .**X
// **.X
// XX.X
Console.Out.Write(ShipSolution.Solve(size, ships, misses));
```
[Answer]
# Java, 1178
Yeah much too long .\_.
```
import java.util.*;class S{public static void main(String[]a){new S();}int a;int[][]f;List<L>l;Stack<Integer>b;S(){Scanner s=new Scanner(System.in);a=s.nextInt();f=new int[a][a];for(int[]x:f)Arrays.fill(x,95);s.next(";");b=new Stack();for(int i=1;s.hasNextInt();i++){b.addAll(Collections.nCopies(s.nextInt(),i));}s.next(";");while(s.findInLine("([A-Z])")!=null)f[s.match().group(1).charAt(0)-65][s.nextInt()-1]=79;l=new ArrayList();for(int i=0;i<a;i++){l.add(new L(i){int g(int c){return g(c,i);}void s(int c,int v){f[c][i]=v;}});l.add(new L(i){int g(int r){return g(i,r);}void s(int r,int v){f[i][r]=v;}});}if(s()){String o="";for(int r=0;r<a;r++){for(int c=0;c<a;c++)o+=(char)f[c][r];o+='\n';}System.out.print(o);}}boolean s(){if(b.empty())return true;int s=b.pop();Integer n=95;for(L c:l){int f=0;for(int x=0;x<a;x++){if(n.equals(c.g(x)))f++;else f=0;if(f>=s){for(int i=0;i<s;i++)c.s(x-i,35);if(s())return true;for(int i=0;i<s;i++)c.s(x-i,n);}}}b.push(s);return false;}class L{int i;L(int v){i=v;}void s(int i,int v){}int g(int i){return 0;}int g(int c,int r){int v=0;for(int x=-1;x<2;x++)for(int y=-1;y<2;y++)try{v|=f[c+x][r+y];}catch(Exception e){}return v&(f[c][r]|32);}}}
```
Ungolfed:
```
import java.util.*;
class S {
public static void main(String[] a) {
new S();
}
/**
* Number of rows/columns
*/
int a;
/**
* A reference to the full field
*/
int[][] f;
/**
* List of Ls representing all columns/rows
*/
List<L> l;
/**
* Stack of all unplaced ships, represented by their length as Integer
*/
Stack<Integer> b;
S() {
// Read input from STDIN:
Scanner s = new Scanner(System.in);
a = s.nextInt();
f = new int[a][a];
// initialize field to all '_'
for(int[] x: f)
Arrays.fill(x, 95);
// ; as separator
s.next(";");
b = new Stack();
// Several int to represent ships
for (int i = 1; s.hasNextInt(); i++) {
// nCopies for easier handling (empty Stack => everything placed)
b.addAll(Collections.nCopies(s.nextInt(), i));
}
// ; as separator
s.next(";");
// find an uppercase letter on this line
while (s.findInLine("([A-Z])") != null) {
// s.match.group(1) contains the matched letter
// s.nextInt() to get the number following the letter
f[s.match().group(1).charAt(0) - 65][s.nextInt() - 1] = 79;
}
// Loop is left when line ends or no uppercase letter is following the current position
// Now create a List of Lists representing single columns and rows of our field
l = new ArrayList();
for (int i = 0; i < a; i++) {
l.add(new L(i) {
int g(int c) {
return g(c, i);
}
void s(int c, int v) {
f[c][i] = v;
}
});
l.add(new L(i) {
int g(int r) {
return g(i, r);
}
void s(int r, int v) {
f[i][r] = v;
}
});
}
// try to place all ships
if (s()) {
// print solution
String o = "";
for (int r = 0; r < a; r++) {
for (int c = 0; c < a; c++) {
o += (char) f[c][r];
}
o += '\n';
}
System.out.print(o);
}
}
/**
* Try to place all ships
*
* @return {@code true}, if a solution is found
*/
boolean s() {
if (b.empty()) {
// no more ships
return true;
}
// take a ship from the stack
int s = b.pop();
// 95 is the Ascii-code of _
Integer n = 95;
// go over all columns and rows
for (L c : l) {
// f counts the number of consecutive free fields
int f = 0;
// move through this column/row
for (int x = 0; x < a; x++) {
// Is current field free?
if (n.equals(c.g(x))) {
f++;
} else {
f = 0;
}
// Did we encounter enough free fields to place our ship?
if (f >= s) {
// enter ship
for (int i = 0; i < s; i++) {
c.s(x - i, 35);
}
// try to place remaining ships
if (s()) {
return true;
}
// placing remaining ships has failed ; remove ship
for (int i = 0; i < s; i++) {
c.s(x - i, n);
}
}
}
}
// we have found no place for our ship so lets push it back
b.push(s);
return false;
}
/**
* List representing a single row or column of the field.
* "Abstract"
*/
class L {
/**
* Index of row/column. Stored here as loop-variables can not be final. Used only {@link #g(int)} and {@link #s(int, int)}
*/
int i;
L(int v) {
i = v;
}
/**
* Set char representing the state at the i-th position in this row/column.
* "Abstract"
*/
void s(int i, int v) {
}
/**
* Get char representing the state at the i-th position in this row/column.
* "Abstract"
*
* @return {@code '_'} if this and all adjacent field contain no {@code '#'}
*/
int g(int i) {
return 0;
}
/**
* Get char representing the state at the position in c-th column and r-th row
*
* @return {@code '_'} if this and all adjacent field contain no {@code '#'}
*/
int g(int c, int r) {
// v stores the result
int v = 0;
// or all adjacent fields
for (int x = -1; x < 2; x++) {
for (int y = -1; y < 2; y++) {
// ungolfed we should use something like
// v |= 0 > c + x || 0 > r + y || c + x >= a || r + y >= a ? 0 : f[c + x][r + y];
// but his will do (and is shorter)
try {
v |= f[c + x][r + y];
} catch (Exception e) {
}
}
}
// we use '_' (95), 'O' (79), '#' (35). Only 35 contains the 32-bit
// So we only need the 32-bit of the or-ed-value + the bits of the value directly in this field
return v & (f[c][r] | 32);
}
}
}
```
Sample-Input
>
>
> ```
> 6 ; 3 2 1 ; A1 A3 B2 C3 D4 E5 F6 B6 E3 D3 F4
>
> ```
>
>
Sample-Output
>
>
> ```
> O###_#
> _O____
> O_OOO#
> #_#O_O
> #_#_O#
> _O___O
>
> ```
>
>
With
* `O` missed shot
* `#` ship-part
* `_` shoot here next ;-)
See on [ideone.com](http://ideone.com/WTaZLb)
Input-handling expects the spaces around numbers / `;` and won't work otherwise.
I am placing big ships first as they have fewer places to go. If you want to switch to small-first you can replace `pop()` by `remove(0)` and `push(s)` by `add(0,s)` even replacing only one of the two should still result in a valid program.
If you allow ships touching each other the `g(int,int)` function can be vastly simplified or removed.
] |
[Question]
[
## Input
* A binary matrix \$M\$ representing the walls of a dungeon.
* The position \$(x,y)\$ of the player within the dungeon.
* The direction \$d\$ that the player is currently facing (0 = North, 1 = East, 2 = South, 3 = West)
## Output
A pseudo-3D representation of the walls that are in the field of view of the player, as an ASCII art of \$30\times 10\$ characters.
Below are several possible output frames, along with the corresponding map and compass to help getting the hang of it (but drawing the map and the compass is not part of the challenge).
[![animation](https://i.stack.imgur.com/KZGWO.gif)](https://i.stack.imgur.com/KZGWO.gif)
## Specification
### Field of view
The player has \$13\$ walls in his field of view, labeled from \$A\$ to \$M\$. Below are the positions of the walls relative to the player (in yellow), in all possible directions.
[![field of view](https://i.stack.imgur.com/ee4Vv.png)](https://i.stack.imgur.com/ee4Vv.png)
### Drawing the walls
The walls are supposed to be drawn from \$A\$ to \$M\$ in this exact order, given that any part drawn previously may be overwritten by closer walls. You may of course implement it differently as long as the final result is the same.
The entire output is drawn with 7 distinct characters: `" "`, `"'"`, `"."`, `"|"`, `"-"`, `"_"` and `":"`.
Because detailing the shapes of the walls in the body of this challenge would make it too lengthy, they are instead provided in the following TIO link:
[**Try it online!**](https://tio.run/##ZZNbd5pAFIXf/RVTX4TiDW/osrYLNQka8YaKmuYBBRwQGeQmQ1f61y0X05qGB84M@5s9ezigS77k7G3NcgsmkpXrVWRHIwF0QFYZhjJddoRDyA66Xq9lVfrcMwzZxYbR5gvYLFcgXzuw2w3ljba75rZXF0p81fJpsXs@BpVusO/r7HqLpnY4r@j8Fj8emzwMDrPpFOryxttWhyNhua8qA8mwnt0zf5Y4oSxXG8za2e4hY3A6r1HWAXNes9IKWuteMKqdBjtudXEaJUUu1bh1acCVwxAfxRk3rHODHVU3ZjVdbO1Pvih25UujP5ANR3g49urcBm10/WmOqa42phFqQFlt0oLB@6zk6O7R0rmV7U24iSfJVkmXHmeBh@pPJchcmqguUOHTqLcQH7CvV/nwWTFpf@nJ49AYT@AEcyyvLgPIrCwdTlDNRBzfZFc7cwGXtdHD3tNGwXA2FB@3DF8ZM7Lfnzv@dIV6a4dZlnZIXJ60QPVUv271YZ9R2dOq1sm2MxlbOXuarRC50NB2ObLomaFmEaZyAV1PVRW7qNroRCQty4PsTnKURi1L5gGh2HYe7BKGBJ3v4FcGABXZhBl1ttwGJvgG6GpUKYpMNAAukmFEYrqm6CLBtTXzQJBFxzI0l8j9NKP9HUPbK5HJV0CX86DwOx2R7cQhOGmxPU4LDUrRTjdBChIhKYWbkkhxJpxmwnGmuP7LlOpBqgeRXo3rvQ6AphJx9Bf8@hK8gi8dkPuRu9f/5uIlFxajIRHP8yC4pU4v/B@DEwZ/YG7HSBkpIOL5Z5@PDE6Ye5@3zH1N73tkOshQigY6EDkxbkQOUCDtQNLiHpTsXvR7Eo16JJjkze/DugWygKGobvTUNhUbSC4gYpvk@BTI5RNTfJuRURNETXZhlDZ@npwGFN5pmoyhiOEU7QDddwinEL6H4g/jc5y4J0UdRa8yAe7Bt8wb2b5e/wA "JavaScript (Node.js) – Try It Online")
The characters that are not part of a given wall are marked with a `"?"` in these diagrams. They must be treated as 'transparent' characters that are not drawn at all. On the other hand, all spaces within a wall are 'solid' and must overwrite any other characters that may have been previously drawn there.
## Rules
### About the input
* You may take \$M\$, \$x\$, \$y\$ and \$d\$ in any reasonable format.
* You may use either 0-indexed or 1-indexed coordinates.
* You may use 4 distinct values of your choice for the directions.
* The matrix is guaranteed to be at least \$3\times 3\$.
* You may assume that there will always be surrounding walls on the edges.
* The player is guaranteed to be located on an empty square.
* The input is guaranteed to be valid.
### About the output
* The walls must be drawn exactly as described.
* However, the output format is also flexible: single string, array of strings, matrix of characters, etc.
* Leading and trailing whitespace is acceptable as long as it's consistent.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
## Test cases
All test cases are using the following matrix:
```
[ [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
[ 1, 0, 1, 1, 1, 0, 0, 0, 0, 1 ],
[ 1, 0, 1, 0, 1, 0, 0, 1, 0, 1 ],
[ 1, 0, 0, 0, 0, 0, 1, 1, 0, 1 ],
[ 1, 0, 0, 1, 0, 0, 0, 1, 0, 1 ],
[ 1, 0, 0, 1, 1, 0, 1, 1, 0, 1 ],
[ 1, 1, 1, 1, 0, 0, 0, 0, 0, 1 ],
[ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 ],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] ]
```
The following inputs are using 0-indexed coordinates, with \$(0,0)\$ pointing to the top-left corner.
```
x=3, y=3, d=0
x=6, y=4, d=3
x=4, y=4, d=1
x=1, y=5, d=2
x=7, y=7, d=3
x=6, y=6, d=1
x=8, y=1, d=2
x=7, y=6, d=1
```
Expected outputs:
```
------------------------------ ------------------------------
x=3, y=3, d=0: x=6, y=4, d=3:
------------------------------ ------------------------------
__ __ '. .'
|'. .'| | |
| '.--------------.' | |----. |
| | | | | | '.--------. |
| | | | | | | | |
| | | | | | | | |
| | | | | | .'--------' |
| .'--------------'. | |----' |
__|.' '.|__ | |
.' '.
------------------------------ ------------------------------
x=4, y=4, d=1: x=1, y=5, d=2:
------------------------------ ------------------------------
.' __ ________________________ .'
| | |
-------. .----| | |
| '.--------.' | | | |
| | | | | | |
| | | | | | |
| .'--------'. | | | |
-------' '----| | |
| __|________________________|
'. '.
------------------------------ ------------------------------
x=7, y=7, d=3: x=6, y=6, d=1:
------------------------------ ------------------------------
'. '.
|'. |'.
| '. | '.
| | '. .- | |--.--------.--------.-
| | |: :| | | | | |
| | |: :| | | | | |
| | .' '- | |--'--------'--------'-
| .' | .'
|.' |.'
.' .'
------------------------------ ------------------------------
x=8, y=1, d=2: x=7, y=6, d=1:
------------------------------ ------------------------------
'. __ '.
|'. .'| |
| '. .' | |----.--------------.-------
| | '. .' | | | | |
| | |: :| | | | | |
| | |: :| | | | | |
| | .' '. | | | | |
| .' '. | |----'--------------'-------
|.' '.|__ |
.' .'
```
---
***Related challenge:***
*[This challenge from 2013](https://codegolf.stackexchange.com/q/15932/58563) is closely related. But it has a different winning criterion (code-challenge), a much looser specification of the output, and requires interactive I/O.*
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux) (with [Snappy](https://github.com/google/snappy)), ~~800~~ ~~785~~ ~~670~~ 644 bytes
*~~460~~ 402 bytes of code + ~~360~~ 242-byte string literal
(escaped here and on TIO because it isn't valid UTF-8)*
You can verify the length of the literal [here.](https://tio.run/##1VQ9T8MwEJ2bX3FpBi/EBcaKTIUBiQGpI0WR5bjFkmNHtltUZOWnE5wPkiaidGHhlFPuzvfO7zlyqGBEVrnK9oJBTriseF4obWFtswd5uFqpjFG8UnmhmTFcSbyWpCiOATOUFCxLDf9gQIOZAwpJAmhzjcD1iT5N5EkyR7BYACUSWfDzGNHAJQgld2Cs5v4luGWaCBPMZgnc1hso@8b0OzeshnIDByJ4VsPIBNNAboIuaykmYPb5y5j1ZgP0Ll6aRlFKO5EwD8MwxhCCWzYeI/CVyHuJ4878cumgM98zTtB324DsbRhxUhzQl4rD6HZyzwc84a4dEB5ij/4xxijsSXpsPWvKcMKz5zNh9Vd1NN7XC4zStO3xtB3qNNbwRqBr0RcDrzRNHW5kRmUJ6Rnzn3TKbczyny2e0@nCCOHmJH91f2Dz12ptif8bJHB6mapPuhVkZ6r48am6P0qSc9omz4LYrdJ5FQv/tBfrCw)
```
import StdEnv,Data.List,Data.Maybe,Codec.Compression.Snappy,Text
@a b|b<'~'=b=a
$m x y d=map(@' ')(foldl(\a b=[@u v\\u<-a&v<-b])['~~'..][join['
']k\\Just(Just 1)<-[mapMaybe(\e=e!?(x+[u,v,~u,~v]!!d))(m!?(y+[~v,u,v,~u]!!d))\\u<-[-2,2,-1,1,0,-1,1,0,-1,1,0,-1,1]&v<-[3,3,3,3,3,2,2,2,1,1,1,0,0]]&k<-nub[q\\w<-split"#"(snappy_uncompress"\211\6\44\41\41\41\55\56\40\41\40\174\72\5\4\60\55\47\40\41\41\41\43\41\41\41\176\56\55\r\1\24\56\40\41\176\174\40\r\1\4\174\72\72\r\0\0\47\r\46\35\72\25\1\31\103\0\41\25\24\35\113\176\25\0\31\133\11\224\r\152\20\56\40\40\40\41\21\217\10\40\47\56\31\14\4\40\174\126\14\0\4\56\47\21\74\0\47\1\74\1\340\r\220\25\242\11\1\25\250\25\360\11\1\25\253\376\30\0\21\30\25\333\11\1\24\47\41\41\43\137\137\11\154\20\41\40\40\174\47\r\344\1\157\5\341\1\11\5\336\172\11\0\34\56\47\41\137\137\174\56\47\1\347\20\43\176\176\40\137\132\1\0\4\40\41\75\211\76\1\0\1\356\5\150\116\1\0\376\35\0\376\35\0\126\35\0\132\347\0\20\137\174\41\43\47\101\337\51\74\41\133\122\4\0\10\56\47\40"),q<-let l=[[c\\c<-:rpad s 30'~']\\s<-split"!"w]in[l,map reverse l]]])
```
[Try it online!](https://tio.run/##fVRra9swFP2eX6FkpbapHCQ/Yhg2K7T7sNHBoPtmmaLEzvDqR@pHlsDIT593rxTTlCVFN4l077lHR0d2VkUmq6Gs077ISCnzasjLTd105LFLP1dbei87OX/I207Pvsn9MqN3dZqt5nd1uWmyts3rav5Yyc1mT39ku25yK8nyzzI0Dka0jOTkqiQ7sidpVMqNeWsQwzLXdZEWpgBcFN/2ZCtEH9ryehvay8SKjcPBmM@T@FedV7ExMZJnIb72bWfiF@FWaMdApZSYIouy6SdzdxP3dEsPPT1sk@k0tSyzhPT@Jj5sqa7otNopth3qUJtTTtmZnwSFxC4dh6MGpxrBkuT6ObSrfhm/CPE7tNtNkXezDzOzVR489dXqaMxMOJyLhfA84fFj@L7wIcPUkgkeeCJwhC88sWBY9IKxqMN9nfNggb0AagQXjvdKhBVkghWWvJEWohEMBrA2wlsI18ec4wPIhTbmCtUPCaCDIueuIoMEUwgX1lCHKhD70MrGXdlxbwcjAC61DrCMjSBmPB93FriGquoNsCXwtCo1AzFKuQPsSoqDm2pZvkq5YM5ryhUuaHTxYEDlaoRWqnxBD0f3uBvoD9R8D/Vr44/alDGuhxq4D@JhjiSARkp0VWkBM0bxWB85gzGJJwgUuXu8DGWSBgKDOrz2K/DVU4EgyEIjXilsjgfUOXU4/3SCDuoJkOFODPcaJRwfE7wDoIOkr1z1jtfnOALN5mw8AJtZ9CW0i6wjRRTHKyFWof2x2ciUtMRl8N4mQrTjgz2d/U7gPSwovHOkybZZ02akSJLEGh47CX8UETGvSJqtZV90T6XsmnxHOPGJY00mb9OTiMQwOL0cJKETojHsJM9O4n8MO8Hwc5g37Zcx/C3sEoZf5jkr@H09ZzHv@EOS4e9qXcif7WB/eRju95Us85VefC9kt66bcrALCP1/NNjLfw "Clean – Try It Online")
Snappy compression actually does pretty well in this case, despite being speed-focused, because there are so many single-character runs in the string being compressed.
The uncompressed string (with `#` replaced with `\n` for clarity) is:
```
!!!-. ! |:! |:!-' !!!
!!!~.--------. !~| |:!~| |:!~'--------' !!!
!!!~~~~~~~~~~.--------.!~~~~~~~~~~| |!~~~~~~~~~~| |!~~~~~~~~~~'--------'!!!
!!-------. ! | '.! | |! | |! | .'!-------' !!
!!~~~~~~~.--------------.!~~~~~~~| |!~~~~~~~| |!~~~~~~~| |!~~~~~~~| |!~~~~~~~'--------------'!!
__ ! |'. ! | '.! | |! | |! | |! | |! | .'!__|.' !
~~ ________________________ !~~| |!~~| |!~~| |!~~| |!~~| |!~~| |!~~| |!~~|________________________|!
'. ! |! |! |! |! |! |! |! |!.'
```
This encodes the left-side versions of the different screen components with `!` instead of newlines, and `~` instead of `?`, which are then right-padded with `~` to 30 characters before having themselves and their line-reversals added to a lookup list.
The rest of the code simply handles coordinate lookup with out-of-bounds cases ignored.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~864~~ ~~854~~ ~~848~~ ~~826~~ 810 bytes
```
L=[zip(*[iter(w)]*30)for w in zip(*[iter("eJzdllESgyAMRL+5Rf7yRQ7AZbhIDl9BwTqzSVtHrbKffR0Mm13HEM5SFHIoadpNI3snDyaS6NCknhU+JfZOvq8kLoIBU1oEI+RTbiePGzBa3QM0rf78TGl17+CZr5ZrUXBN+ECfY1GvGKEqtDsSI4s6xTn5jgqyqNcTTnUjTQO2FAEqTC0ngCrtpywenX5le6or1SsGi9ZLBKt0HuXtVEeUNGdzG6EsRNmo2EzLxuBbqFH8njmfwnqGcl+VY+s5+5ezSYXVel4dxaRK/6F15SatK1frvm//y4aoT4Ckj6XWfY2cbvz2fLSCPiiVvR+3ZuerzDwPSqeSvgAP9woa".decode('base64').decode('zip'))]*300)]
E=enumerate
def f(m,x,y,d):
D=eval(`[[' ']*30]*10`);w,h=len(m[0]),len(m);a=[m,zip(*m)[::-1]][d%2];x,y=[x,y,w+~x,h+~y,y,w+~x,h+~y,x][d::4];X=sum([[0]*(x<2)+list(l)[x-2+(x<2):x+3]for l in[l*2for l in[a,[l[::-1]for l in a[::-1]]][d/2]*2][y:y+4]],[])
for d,w in zip(L,'sropqmklhfgca'):
for j,l in E(d):
for i,q in E(l):
if q*X[ord(w)%32]>=' ':D[j][i]=q
for l in D:print''.join(l)
```
[Try it online!](https://tio.run/##fVNpb9pKFP3Or7AqRbbxtPFO4jw/KYADlKUJNpQwGqkGj8HEC17Ay4f@9bzB5EWJmlQa6c4cnzn3@p47@zLbRqH4/DzSYeXtmSb0MpwwOYuaEs@6UULllBdSbz59wd8rx/cNc1PejqcjTpm6rXL60LpdrraDrn/dzq24MudZP1kNXXfKjwNB6htjxbzrDyLb2U8GUhp2S9tUJ52ncDvjvrvLH8f46mkUDdozITIG3NRaefi@V7Vt6WHMJ27ryur5QovrLBNlmcwW7QlndNxHoXfsDY0466bmQE7VwgqV3SYu48nassLZznr4Id7dGrHV4cNNJ8n2ZY7DheJjNUoEM@1518tRe5jx/cMimxt4Nuk5VU810ukkiESjGhWH9iq@61@Fu8DNw7i39rn5I5cqnIIr83Exx77sFPZ0eKneCYppZ0PBTY7B5WUp25Eld5526uKn@yiuV8dKdEdm597z5scpJy0POKm6@b0ZY/O4ub2/ziP7yzcHryMHM/TKTrEq0@wrQFpPs7UdPIsaho7DQ4ATO8MNB7uUywSgACVwWK1BdXV8tH3mF4Q0RZ9uoKbA/2JvcrDVfRwyAeQRC@ode2PrMAC1rwELNe2rgBB0LkR0Q@R0eNLMud8F2HK/y3f7gtA0TUY3Cz09BAwkmk2m@EdkOd9LM8ZnYfFV5GpEKzgJnWbIJzME/ab4urcB9M9J/4co@6UIIn8poqaIYKmVnIwQgIhtUCeeA16HcQToNIn2cfDkb93N2qZP/1@TdqCWM5i6JWfMA/EZ888Y5blU3FzAKHHIqF9IIvpXJy3TunCHoIf0@JyvFupq@8QLM5r@tou8kCg8j3VIQUoAny8KAZKm5vBvcP7N@pPDv@EIH3HeXf@cI7ynfcYRPtf5sOC/1/Mh5y/9oVCjcWpxPbunNkMJSIAnZqtABhKJMokCiQJQgEhiC7RqXAVqjV8B4QU/nYmtjs44nMheyA2qdow5vwtiJTN@eSPP/wE "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~500~~ 332 bytes
```
F⁴≔⮌E§θ⁰⁺00⭆θ§μλθ≔E✂θ⊖ζ⁺⁶ζ¹✂ι⊖η⁺⁶η¹θFε≔⮌E§θ⁰⭆θ§μλθB³⁰χ F²«‖FΦ⪪⟦“ |0⟧P+N?⟧‹G”³¦⁰”{➙d⊟EX⍘k↧D({Vt⍘gRd◨ⅉ^δ#T;”³¦¹“ ¶↖+9G₂pF^c1e⌈¬;”³χω⁰χ”{➙∧⊟∧◨ηü∧↖z↨⁸\G'λI∧¡∕⪫θJoΣ³⊖I⊟ζ⊙”²¦⁰”{➙∧⊟∧◨ηü∨§·◧﹪d‹⟲ OzºκFⅉRï⎇”²¦⁷ω⁰χ”{➙∧⊟≔⊘⬤|↔3Zθ✂≔÷t⍘ε✂↨≔⧴×ld≕≡⌕m⟧6ψ=Z”⁰¦⁰”}∧80KυgCAêJm⟦↘/§‖Ck⮌C₂¡μ↗W”⁰¦²ω⁰χ”{⊟∨·◧¤∨¶⧴⬤2GL▷⁸ê5Gψ”⁰¦⁰⟧³I§⭆θ⭆³§μ⎇ι⊕ξ⁻⁵ξλ«J⁻⊟κײ⁹¬ι⊟κ⊟κ
```
[Try it online!](https://tio.run/##tZPLbuIwFIbX8BRH2cSRTJRAL@rMqp3RSB2pFSrsWhRFqVushoQmbsVMw7OnxzeIJaBsapzgy@f//HZ8snlaZWWat@1TWQE5CeCyrvlzQe7YO6tqRm7SJbkU18UjW5FXClFAYZy/1cSLIo/CRFS8eJYMzllsQSEPZKHwGvzsG0EJTXKeMYn@ZlnFFqwQ7JH8t5JnFGQ7xkeD3AXnHXCuQBNBWWfHWD/oV4tdlSsyilAdHw88Kz8M4KPfu2NPOcsEwdGeGv7Dc8EqMlnmXJB7bxDCQwHND/Ma@ICHNMLYqBUOTJFMA6ZIzOn4FrNrY7vWgJs/RRpGBvBUHNXcRJKcFQc/7HSg2dcJfXRuPYB0MXR3sHX8VctuRmucuyaTxGIY1bde5WJtVMk0x7Wk5yRpQmM40oYh6ZTOObs2v6HbjavtDN29@6He7FGv0Ld7muHXxnv6K63F5mo7d3rbGTkXfMqqIq3@yZS6LrYptUKxG15gTp1SWJmkVckgb3vv79tiOS2JJsblkrzg9JQvWE2GFxRuS0G4WqLnZFb0xmhAkO3Aur9u23uQv5jurzCjfXl4ioo6M1Gn7qKiDhXvphyJQ1Tsgvup@JDWTutf@dpDHTgv5OBE1XjWDt7zTw "Charcoal – Try It Online") Link is to verbose version of code. Somewhat boring approach, I'm afraid; lots of printing of compressed string literals. Explanation:
```
F⁴≔⮌E§θ⁰⁺00⭆θ§μλθ
```
Pad the array with two extra `0`s on each side.
```
≔E✂θ⊖ζ⁺⁶ζ¹✂ι⊖η⁺⁶η¹θ
```
Slice a `7x7` subsection of the array centred on the given coordinates.
```
Fε≔⮌E§θ⁰⭆θ§μλθ
```
Rotate the array as appropriate for the given direction.
```
B³⁰χ
```
(note trailing space) Draw an empty `30×10` box so that the output is always a consistent size.
```
F²«‖
```
Draw each half separately, reflecting in between.
```
FΦ⪪⟦...⟧³I§⭆θ⭆³§μ⎇ι⁻⁵ξ⊕ξλ«
```
Take an array of wall descriptors, split into chunks of (string, y-coordinate, x-coordinate), filter on those chunks that have a wall at the relevant position in the relevant half of the array, and loop over the walls. The position is calculated by extracting 12 walls from the array and indexing them using the chunk index as this is golfier than locating the wall directly using the chunk index.
```
J⁻⊟κײ⁹¬ι⊟κ⊟κ
```
Jump to the coordinates of the wall and print it. Note that reflecting negates the X-coordinates from `[0, 30)` to `(-30, 0]` so that on one pass the canvas is effectively shifted 29 characters to the left.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~412 391 385~~ 383 bytes
```
->a,x,y,d{b=Array.new(97){[" "]*10}
e=[-1,0,1,0]
14.times{|i|m=-i%3-1
w=[31,25,15,9][n=i>2?4-i/3:(m*=2;3)]
(a*3)[y+n*e[d]+m*c=e[d-3]][x+n*c-m*e[d]]&&[p=w*(m*2-1)/2,r=[12,7,4,3][n]*m*m.abs+m/3].min.upto([q=w*(m*2+1)/2,r].max){|j|t=" .'"*9
b[j+15]=(p<j&&j<q ?%w{-%2s- -%4s- _%7s_}[-n]%"":t[k=(j^j>>9)%(36/-~n)]+" :| | |"[k%13]*(k/3*2)+t[-k]).center(10).chars}}
b[0,30].transpose}
```
[Try it online!](https://tio.run/##nZNtb5swEMff8ylOSGRgbMCYJEtWp9rnsLyKJHSDDIfyoCQC9tVTl1Z7k6Sikc6nk@9/vzud7LJZn87P/ExWMT7iE962a/6zLOOTp5KDvZg7rTDBlIgGvZFwQSgOsD7SoJFXp3lStV3a5ZykFiPUOHDBKA6nmE7xQgrF01X4GJHUZ0s7Rzz8wRxp2DFijji5CiViK90cbbgOCJNSHPXlhuRDQk4mouAHpAtDQh0/xCUXNMRzHGGm2RLlKPfideXmPpNeniqvKeq9LV4@itz3Ip2Kj07bZV3NTfC@mWhhrEXm0qnkdvGQTSbZwws8WoeWWGFFgFiR9k/WvHrqBVHSMs1lLXbczn5lq9XCsWw288k/5UjXBIBlB6BNO1PsLMoksnc@Q6Hj1oLspONtElUnpU0DHf6Jy6rvdfsAs0B6dRmrqthXSX/eNup3sldcgIC6bBJ8lweJDfhPUOlfuKZ8v7/0nxMu4@vZa4TPOn6FcIv5VcKt/dwijN/hfXsYQ7jvPYA0jKKpK3gWH08MAxssePsYxdv3Tb1sn6p@0F2IZxgirR8njgaj48QUwxRDOE48H4yNnnk2eozvwyTjx7hKPr8C "Ruby – Try It Online")
Takes input as an array of truthy/falsy values (note `0` is truthy in Ruby, but `nil` is falsy.)
Outputs an array of characters.
**Explanation**
Blocks are drawn front to back with distance `n` decreasing and side to side position `m` cycling through `-1,1,0` left,right,middle. The middle block E in the furthest row is actually drawn twice because we need to check both blocks A/B and blocks C/D. `n,m` and `d` are used to modify the `x` and `y` values to search array `a`. If `x` is out of range `nil` is returned for an out of range cell and no error is thrown, but if `y` is out of range `nil` will be returned for the row and Ruby will throw a type error when it tries to search for the cell. To avoid this the array is triplicated in the vertical direction prior to searching. If a truthy value is found a block is drawn.
The output is built in an array `b` of 10-element arrays representing the columns of the output, and is transposed into 10 rows at the end of the function. The full front face of all blocks is drawn (whether it appears in the viewport or not) so additional space is needed in the array to avoid out of range errors. The range of `j` values in the viewport is from `-15` to `+14`, this is offset by 15 when saving to the array to give a range of `0` to `29`. For each block drawn three values are calculated: `p` and `q` for the left and right corners of the front wall respectively, and `r` for the back of the side wall. `j` is iterated from the minimum to the maximum of these three values drawing the columns in turn.
There are 3 types of lines: horizontal `-` or `_`, vertical `|` or `:`, and diagonal with a repeating `" .'"` pattern. Where `p < j < q` columns containing spaces capped with `-` or `_` are drawn to form the front face. Where `j` is outside this range, columns containing space, `|` or `:` are drawn capped with symbols from `t=" .'"` to form the edges and/or side face. This is managed by variable `k=j` where `j` is positive or `k=-j-1` where `j` is negative. The number of characters between the top and bottom caps is `k/3*2`. In order to correctly handle the outer edges of the furthest blocks where `n=3`, `k` must be taken modulo 9, but this must not be done for smaller values of `n`. `k` is therefore taken modulo `36/-~n`, where `-~n` evaluates to `n+1`.
**Ungolfed code**
```
->a,x,y,d{
b=Array.new(97){[" "]*10} #Set up array for output, allow space for plotting outside viewport
e=[-1,0,1,0] #Direction offsets from player position
14.times{|i| #Iterate through all blocks including block E twice
m=-i%3-1 #Cycle -1,1,0 = left, right, centre
n=i>2?4-i/3:(m*=2;3) #Distance n=4-i/3. But if i/3==0 n=3 and double m for blocks A,B
w=[31,25,15,9][n] #Width of front face of block
r=[12,7,4,3][n]*m*m.abs+m/3 #Value of j for back edge of block. m/3 offsets by -1 when m negative
(a*3)[y+n*e[d]+m*c=e[d-3]][x+n*c-m*e[d]]&&( #If a block is present at the location then
[p=w*(m*2-1)/2,r].min.upto([q=w*(m*2+1)/2,r].max){|j| #Calculate left and right edges of front of block p,q and iterate
t=" .'"*9 #t=character constant for diagonal lines
k=(j^j>>9)%(36/-~n) #k=j for positive j=distance from centre. For negative j, k=-1-j by XOR with j>>9=-1. If n=3 take modulo 9 for correct output of outer side of block.
b[j+15]=(p<j&&j<q ?%w{-%2s- -%4s- _%7s_}[-n]%"": #If j between p&q, draw horizontal lines separated by 2,4 or 7 spaces depending on value of n
t[k]+" :| | |"[k%13]*(k/3*2)+t[-k]).center(10).chars #else draw space or vertical line capped by diagonal markers
}
)
}
b[0,30].transpose} #Truncate values outside viewport, transpose, and return value.
```
] |
[Question]
[
In Vernor Vinge's excellent and fascinating book *A Deepness in the Sky*
(which, by the way, I highly recommend1), the *Qeng Ho*, a culture
that spans various star systems, has no notion of "days," "months," "years,"
etc., and hence has a unique timekeeping system that measures time entirely in
seconds. The most commonly used units are the *Ksec* (kilosecond), *Msec*
(megasecond), and *Gsec* (gigasecond). Here's a handy chart from my own copy of
the book (since I can't find it online):
![handy chart](https://i.stack.imgur.com/v58ra.png)
You are currently flying on the *Pham Nuwen*, and you have just received a
message from a strange, unknown planet called "*Earth*."2 They use different
time units than you do, and your computers don't recognize theirs. As the
resident Programmer-Archaeologist of the ship, your job is to patch the
time-handling code so that it recognizes *Earth* units of time.
Naturally, since you're only out of coldsleep for another few Ksecs, you want
to make your code as short as possible so it can be written quickly.
Fortunately, as an interstellar trading culture, the Qeng Ho has access to
every programming language invented.
## Input
The input will be a single string containing one or more space-separated
*components*. A *component* is defined as an integer number > 0 and ≤ 255, then
a space, and then one of `second`, `minute`, `hour`, `day`, `week`, `month`,
`year`, `decade`, or `century`, possibly plural (with an added `s`, or
`centuries` for the last case).
Here are some valid example inputs:
```
10 days 12 hours
1 year
184 centuries 1 second
9 weeks 6 days 2 hours 1 minute 20 seconds
```
You may assume the following about the input:
* Pluralization of units will always agree with the relevant number.
* If there are multiple *components* in the input, they will always be in
descending order of length.
Here are what the various input units mean, for the purposes of this challenge:
```
unit relative absolute
---------------------------------------
second 1 second 1 second
minute 60 seconds 60 seconds
hour 60 minutes 3600 seconds
day 24 hours 86400 seconds
week 7 days 604800 seconds
month 30 days 2592000 seconds
year 365 days 31536000 seconds
decade 10 years 315360000 seconds
century 10 decades 3153600000 seconds
```
## Output
Here are the Qeng Ho units which your code has to support:
```
unit relative absolute
----------------------------------------
second 1 second 1 second
Ksec 1000 seconds 1000 seconds
Msec 1000 Ksecs 1000000 seconds
Gsec 1000 Msecs 1000000000 seconds
```
Use the following algorithm to determine your code's output:
* First, add up the total amount of time that the input represents.
* Find the largest Qeng Ho unit that is shorter or the same amount of time as
the input—essentially, find the largest unit that there is at least one of.
* Convert the total amount of time given in the input into this unit, and
output the result, rounded to three decimal places.
You may have your choice of which of the following methods to use: rounding up,
rounding down, rounding away from zero, or rounding towards ∞ or -∞. If the
rounded result ends in `0`, you may either remove trailing zeroes or keep as
many as you want (or do both, depending on the input).
If the rounded result is exactly `1.000`, you must use the singular form
(`second`, `Ksec`, `Msec`, `Gsec`); otherwise, use the plural form (`seconds`,
`Ksecs`, `Msecs`, `Gsecs`).
In certain edge-cases, you might be using the unit of, for example, Ksec, but
obtain a rounded result of 1000.000 Ksecs. In this case, you may simply output
`1000.000 Ksecs` instead of `1 Msec`.
You may always assume that the input is in descending order of units (century,
decade, year, etc.); furthermore, the component that comes after any given unit
will always be shorter (that is, `1 decade 20 years` is invalid input).
## Test cases
Note: results marked with an asterisk (`*`) may vary by a negligible amount due
to rounding differences.
```
input output
-------------------------------------------------------------
1 hour 3.600 Ksecs
1 day 86.400 Ksecs
2 weeks 1.210 Msecs
1 year 31.536 Msecs
32 years 1.009 Gsecs *
1 second 1.000 second
1 century 6 decades 5.046 Gsecs *
255 centuries 804.168 Gsecs
2 weeks 6 days 1 hour 19 minutes 4 seconds 1.733 Msecs
1 week 3 days 3 hours 7 minutes 875.220 Ksecs
1 week 4 days 13 hours 46 minutes 40 seconds 1.000 Msec
2 months 2 hours 5.191 Msecs *
16 minutes 39 seconds 999.000 seconds
```
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
---
1: only if you like hard scifi, of course. In which case I recommend
reading *A Fire Upon the Deep* first, which is (in my opinion) even more
fantastic.
2: well, technically "Old Earth" is mentioned several times in *A Deepness in the Sky*, but...
[Answer]
# JavaScript (ES6) 255
```
f=s=>(s=s.replace(/(\d+) (..)/g,(_,n,u)=>t+={se:1,mi:60,ho:3600,da:86400,we:604800,mo:2592e3,ye:31536e3,de:31536e4,ce:31536e5}[u]*n,t=0),[a,b]=t>=1e9?[t/1e9,' Gsec']:t>=1e6?[t/1e6,' Msec']:t>999?[t/1e3,' Ksec']:[t,' second'],a.toFixed(3)+b+(a-1?'s':''))
// test
console.log=x=>O.innerHTML+=x+'\n'
;[
['1 hour','3.600 Ksecs']
,['1 day','86.400 Ksecs']
,['2 weeks','1.210 Msecs']
,['1 year','31.536 Msecs']
,['32 years','1.009 Gsecs']
,['1 second','1.000 second']
,['1 century 6 decades','5.046 Gsecs']
,['255 centuries','804.168 Gsecs']
,['2 weeks 6 days 1 hour 19 minutes 4 seconds','1.733 Msecs']
,['1 week 3 days 3 hours 7 minutes','875.220 Ksecs']
,['1 week 4 days 13 hours 46 minutes 40 seconds', '1.000 Msec']
,['2 months 2 hours', '5.191 Msecs']
,['16 minutes 39 seconds', '999 seconds']
].forEach(t=>console.log(t[0]+' '+f(t[0])+' (Check:'+t[1]+')'))
```
```
<pre id=O></pre>
```
[Answer]
# [APL (Dyalog APL)](https://www.dyalog.com/), ~~157~~ ~~156~~ ~~154~~ ~~151~~ ~~154~~ ~~141~~ 142 bytes
```
{∊(3⍕N)' '((B/S⊃' KMG')'sec','ond'/⍨~B←T≥1E3),'s'/⍨1≠N←T÷1E3*S←⌊1E3⍟T←+/×/↑⍎¨'\d+ .a?i?'⎕S'&'⊢⍵⊣c←10×d←10×⊃y m w←365 30 7×da←24×h←×⍨mi←60×s←1}
```
Thanks to ngn for shaving off 13 bytes.
Must have `⎕IO←0`, which is default in many APLs.
[Try it online!](https://tio.run/nexus/apl-dyalog#VY/PSsNAEMbvPsWc3NYW82fTlJ4KBRERK6U9egnJQoMkhW5LCaIXodhgih5Kj4oi9AXEu3mTeZE4ySZWLzvffPubb3ZxvTm7xOWTng3ovMGHuMYx2fTrDFit1tOGGN8zOL84ZXUmhcuabBJ6TMNkd9ejgRGuPowTXm8yWZgGrl77uZ9@kX00JImPMUlMXkbUNLR0q@HyGZP1945deQ04drp@l@F6M2SHDOM3TD4xfneJNfR065WVXhFBAAtqud0CrkObLh1qTSvdjqkSk@wCn5RNvMznbrNsAMyA8WQ@ZQeF9JyoUCYshLiWpRsJRwHcLHTl04fz36rGFeFsPo3ABk@4jicUZLZa5Y1fOSo655xIgloPRgcCP5zPhASrzK225DhwRfOCltCu6L@MVSZWkGXvM/V/oSYEk3A2lmAqVKXscd75xX8A "APL (Dyalog APL) – TIO Nexus")
`{`…`}` "dfn"; argument is `⍵`:
`s←` let `s` be 1
`mi←60×` let `mi` be 60 times that (i.e. 60)
`h←×⍨` let `h` be that squared (lit. that multiplied by itself, i.e. 3600)
`da←24×` let `da` be 24 times that (i.e. 86400)
`y m w←365 30 7×` let `y`, `m`, and `w` be 365, 30, and 7 times that, respectively (i.e. 31536000, 2592000, and 604800)
`d←10×⊃` let `d` be 10 times the first of those (i.e. 315360000)
`c←10×` let `c` be 10 times that (i.e. 3153600000)
`⍵⊣` discard that in favour of the given argument
`'\d+ .a?i?'⎕S'&'⊢` **S**earch for, and extract all runs of digits followed by a space, any character, optionally an "a", and optionally an "i"
`⍎¨` execute each as APL code (gives pairs of counts and units in seconds)
`↑` mix the pairs into a 2-column matrix.
`×/` multiply along the rows, yielding a list of counts of seconds
`T←+/` let `T` be the sum of those (the total count of seconds)
`1E3⍟` \$\log\_{10}\$ of that
`N←⌊` let `N` be the floor of that (i.e. the order of magnitude of `T`)
`1≠` yield 1 if that is different from 1, but 0 otherwise
`'s'/⍨` use that to replicate the letters of the string "s" (yielding "s" if we need a plural)
`(3`…`3),` prepend the following three things:
1. `3⍕N` the string consisting of `N` rounded to 3 decimal places
2. `' '` a space
3. `B←T≥1E3` let `B` be 1 if `T` is at least 1000, but 0 otherwise
`~` logically negate that (i.e. 0 if `T` is at least 1000, but 1 otherwise)
`'ond'/⍨` use that to replicate the string "ond" (for the full word if there's no prefix)
`'(`…`)'sec',` prepend the 2-element list consisting of the following and the string "sec":
`S⊃' KMG'` use `S` as an index to select a prefix from the string " KMG"
`B/` replicate the letters of that by `B` (empty out `S` if `B` is 0, but leave as-is if it is 1)
`∊` **e**nlist (flatten until a simple string)
[Answer]
# Python, ~~366~~ 363 bytes
```
d={};l=1;q=str.replace;i=q(raw_input(),"ie","y")
for u,t in zip('second minute hour day week month year decade century'.split(),(1,60,60,24,7,30./7,73./6,10,10)):l=t*l;d[u]=d[u+"s"]=l
while" "in i:
i=q(q(i," ","*",1)," ","+",1)
q=eval(i,d);f={};l=1
for u in('second','Ksec','Msec','Gsec'):
l*=1e3
if q<l:q=q*1e3/l;print"%.3f %s%s"%(q,u,("s","")[q<1.001]);break
```
[Answer]
# SpecBAS - ~~476~~ 471 bytes
Because nothing says "cower before our technological superiority" better than line numbers and GOTO statements :-)
```
1 INPUT e$: DIM t$(SPLIT e$,NOT " "): DIM m=31536e5,31536e4,31536e3,2592e3,604800,86400,3600,60,1
2 LET q=0,n$=" cedeyemowedahomise"
3 FOR i=1 TO ARSIZE t$() STEP 2: LET t=VAL t$(i),u$=t$(i+1)( TO 2),p=POS(u$,n$)/2: INC q,t*m(p): NEXT i
4 IF q>=1e9 THEN LET r=q/1e9,r$=" G": GO TO 8
5 IF q>=1e6 THEN LET r=q/1e6,r$=" M": GO TO 8
6 IF q>999 THEN LET r=q/1e3,r$=" K": GO TO 8
7 IF q<1e3 THEN LET r=q,r$=" "
8 PRINT USING$("&.*0###",r);r$;"sec"+("ond" AND q<1e3)+("s" AND r>1)
```
[Answer]
# C# (in LinqPad as Function), 460 Bytes
```
void Main(){var x=Console.ReadLine().Split(' ');long s=0,v,i=0;for(;i<x.Length;){v=long.Parse(x[i++]);var w=x[i++].Substring(0,2);s+=w=="ce"?v*3153600000:w=="de"?v*315360000:w=="ye"?v*31536000:w=="mo"?v*2592000:w=="we"?v*604800:w=="da"?v*86400:w=="ho"?v*3600:w=="mi"?v*60:v;}decimal k=1000,m=k*k,g=m*k,r=0;var o="sec";r=s/g>=1?s/g:s/m>=1?s/m:s/k>=1?s/k:s;o=s/g>=1?"G"+o:s/m>=1?"M"+o:s/k>=1?"K"+o:o+"ond";Console.WriteLine(Math.Round(r,3)+" "+o+(r==1?"":"s"));}
```
ungolfed:
```
void Main()
{
var x=Console.ReadLine().Split(' ');
long s=0,v,i=0;
for(;i<x.Length;)
{
v=long.Parse(x[i++]);
var w=x[i++].Substring(0,2);
s+=w=="ce"?v*3153600000:w=="de"?v*315360000:w=="ye"?v*31536000:w=="mo"?v*2592000:w=="we"?v*604800:w=="da"?v*86400:w=="ho"?v*3600:w=="mi"?v*60:v;
}
decimal k=1000,m=k*k,g=m*k,r=0;
var o="sec";
r=s/g>=1?s/g:s/m>=1?s/m:s/k>=1?s/k:s;
o=s/g>=1?"G"+o:s/m>=1?"M"+o:s/k>=1?"K"+o:o+"ond";
Console.WriteLine(Math.Round(r,3)+" "+o+(r==1?"":"s"));
}
```
[Answer]
# Mathematica ~~296~~ 281 bytes
`h`: After breaking up the input string into a list of quantity magnitudes and units, `Capitalize` and `Pluralize` convert the input units into Mathematica `Quantity`'s, from which the total number of seconds is derived.
`d` converts seconds to the appropriate units. The final `s` is removed if the time corresponds to 1 unit (of any kind).
With minor adjustments in the code, this approach should work for conversion of natural language input into any measurement system, conventional or not.
```
h=Tr[UnitConvert[Quantity@@{ToExpression@#,Capitalize@Pluralize@#2},"Seconds"]&@@@Partition[StringSplit@#,2]][[1]]&;
d=ToString[N@#/(c=10^{9,6,3,0})[[p=Position[l=NumberDecompose[#,c],x_/;x>0][[1,1]]]]]<>StringDrop[{" Gsecs"," Msecs"," Ksecs"," seconds"}[[p]],-Boole[Tr[l]==1]]&
z=d@h@#&;
```
---
Put into table form:
```
z1[n_]:={n,z@n}
Grid[z1 /@ {"1 hour", "2 day", "2 weeks", "1 year", "32 years",
"1 second", "1 century 6 decades", "255 centuries",
"2 weeks 6 days 1 hour 7 minutes",
"1 week 3 days 3 hours 46 minutes 40 seconds",
"1 week 4 days 13 hours 46 minutes 40 seconds", "2 months 2 hours",
"16 minutes 39 seconds"}, Alignment -> Right]
```
[![pic](https://i.stack.imgur.com/v5KYQ.png)](https://i.stack.imgur.com/v5KYQ.png)
[Answer]
# Haskell, ~~565~~ 555 bytes
```
import Data.List
import Numeric
import Data.Bool
i=isPrefixOf
s x=showFFloat(Just 3)x""
r=read
f=fromIntegral
b=bool"s"""
c=b.(=="1.000")
h(c:u:l)
|i"s"u=(r c)+h l
|i"mi"u=(r c*60)+h l
|i"h"u=(r c*3600)+h l
|i"da"u=(r c*86400)+h l
|i"w"u=(r c*604800)+h l
|i"mo"u=(r c*2592000)+h l
|i"y"u=(r c*31536000)+h l
|i"de"u=(r c*315360000)+h l
|True=(r c*3153600000)+h l
h _=0
q i
|v<-s((f i)/10^9),i>=10^9=v++" Gsec"++c v
|v<-s((f i)/10^6),i>=10^6=v++" Msec"++c v
|v<-s((f i)/1000),i>=1000=v++" ksec"++c v
|True=show i++" second"++b(i==1)
t=q.h.words
```
I'm reasonably sure I'm missing so many golfing opportunities here…The price of being a golfing beginner I guess.
My answer is a function taking a string containing the Earth time as an input parameter and returning the Qeng Ho time.
*P.S. :* I stupidly forgot about the 3 digits precision…which does drive the byte count up.
*P.P.S. :* Better chosen top-level expressions shaved off 10 bytes…and it should now be accurate to boot.
[Answer]
## Matlab 315 bytes
```
K='cedeyemowedahomiseconds';Q=' KMGT';for j=1:9;y(j)=double(~isempty(strfind(S,K(2*j-1:2*j))));end
y(y==1)=sscanf(S,repmat('%d %*s ',1,9));y=86400*sum(datenum([sum(y(1:3)*10.^[2;1;0]),y(4),y(5:6)*[7;1],y(7:9)]));z=floor(log10(y)/3);y=num2str(y/10^(3*z)+1e-4);[y(1:4),' ',Q(z+1),K(17:23-(y(1:4)=='1.00'))]
```
Test:
```
S = '2 centuries 1 decade 2 years 3 months 3 weeks 4 days 1 hour 44 minutes 58 seconds';
```
Output:
```
ans =
6.69 Gseconds
```
] |
[Question]
[
**Let us take a break from the brain-wrecking questions and answer some of the simpler ones**
You have recently read something extremely funny, and want to express your laughter to the world! *But how can you?*
## Task
You have to display the string:
`Lolololololololololololololololololololololololololololololololololololololololololololololololololololololololol...`
...to STDOUT.
The string *should be of infinite length*, or *will constantly be printed until the end of time*.
It is just as simple!
But remember, this is `code-golf`, so the source code must be as short as possible!
*Note: Some languages may throw errors since excecution can be timed out, or for other reasons. That is okay! It can be weird when you laugh forever!*
---
Good luck!
[Answer]
# [Python 3](https://docs.python.org/3/), 32 bytes
```
x='L'
while[print(end=x)]:x='ol'
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8JW3UedqzwjMyc1uqAoM69EIzUvxbZCM9YKKJOfo/7/PwA "Python 3 – Try It Online")
In Python 3, the `print` function by default has `end='\n'` to put a newline after what you print. Rather than changing that to the empty string, we stick the value `x` that we want to be printed there, and don't provide any value to be printed.
We stick the printing in the `while` loop condition. Since `print` returns `None` by default but this is Falsey and won't continue the loop, we wrap it in a singleton list to make it Truthy.
I had tried to stick an infinite iterator into `print` like `print(*iter(...),sep='')`, but it looks like Python will consume the whole iterable first and never actually print.
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 8 bytes
```
"loL",<,
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9Xysn3UdKx0fn/HwA "Befunge-98 (PyFunge) – Try It Online")
### How?
***`Lo`***:
Initially the IP is going *east*.
`"loL"` pushes *`l`*, *`o`* and *`L`* to the stack.
`,` prints *`L`*, `<` turns the IP *west* and `,` prints *`o`*.
***`lo`*** forever:
The IP is now moving *west*.
`"loL"` pushes *`L`*, *`o`* and *`l`* to the stack.
The IP wraps around and `,<,` prints *`l`* and *`o`*.
*`L`* is left on the stack, but since we usually assume infinite resources, this is fine.
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), 5 bytes
```
L;o>l
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/9/HOt8u5/9/AA "Hexagony – Try It Online")
*Hexagony golfing language confirmed*
For some reason I was looking at [my own answer that prints "six" in 6 bytes](https://codegolf.stackexchange.com/a/195264/78410) and randomly thought "what if I remove `@`?", and exactly got this answer. 4 bytes is impossible because `Lol;` is already 4 bytes and it is impossible to alternate two chars and print both in a single loop without redirection.
Since there is no "halt" command in this program, the program flow looks like this: (It is recommended to read the docs on how `>` redirects the PC)
```
A B
C > D
E F
[.....................................] <= looping region
A B C > C B A D > A D B F > F C E A > D E F C > C ...
L ; o o ; L l L l ; . . o . L l . . o o
^ ^ ^ ^ ^ ^
```
After the initial `L;`, `o;` and `l;` appear in the big loop in that order, therefore printing `Lololol...`.
[Answer]
# x86-16 machine code, IBM PC DOS, ~~13~~ 10 bytes
```
00000000: b04c cd29 0c20 3403 ebf8 .L.). 4...
```
Listing:
```
B0 4C MOV AL, 'L' ; start off with capital L
PRINT:
CD 29 INT 29H ; write to console
0C 20 OR AL, 20H ; lowercase it
34 03 XOR AL, 3 ; swap between 'l' (0x6c) and 'o' (0x6f)
EB F8 JMP PRINT ; loop forever
```
[Try it online!](http://twt86.co/?c=sEzNKQwgNAPr%2BA%3D%3D)
A standalone PC DOS executable COM program. Output to console.
**-3 bytes thx to @nununoisy's very clever use of `XOR` to swap between `l` and `o`.**
Runtime:
[![enter image description here](https://i.stack.imgur.com/7AnHb.png)](https://i.stack.imgur.com/7AnHb.png)
*Forever and ever...*
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~41~~ 40 bytes
-1 byte thanks @ovs
```
+[+<[-<]>>++]<.>>+[+>+[<]>->]<[.---.+++]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fO1rbJlrXJtbOTls71kYPSEVrAzFQQNcu1iZaT1dXV08bKPX/PwA "brainfuck – Try It Online")
[Answer]
# [Labyrinth](https://github.com/m-ender/labyrinth), 7 bytes
```
762
8.3
```
[Try it online!](https://tio.run/##y0lMqizKzCvJ@P/f3MyIy0LP@P9/AA "Labyrinth – Try It Online")
Adds `623 % 256 == 111` to the previous answers below.
```
76 Push 76 and turn right (three-way junction)
. Pop and print % 256 as char (L)
Now the top is 0, so it should go straight, but instead it reflects to North
623 Turn right at 6 and push 623, going around the corners
. Pop and print % 256 as char (o); go straight (three-way junction)
876 Push 876
Loop forever, printing "lo"
```
---
## 10 bytes
```
76
8.1
11
```
[Try it online!](https://tio.run/##y0lMqizKzCvJ@P/f3IzLQs@QS8HQ8P9/AA "Labyrinth – Try It Online")
Same idea, but using `876 % 256 == 108`. Turns out that going from an uppercase to lowercase is just a matter of prepending a 8 because `800 % 256 == 32`. At the center junction, the top is always 0 right after pop and print, so the IP goes straight (first from north to south, and second from east to west). All the numbers are corners which turn the IP 90 degrees, so the overall path is infinity-shaped `76.111.876.111. ...`. This form is one byte shorter than the naive square loop:
## 11 bytes
```
76.
8 1
.11
```
[Try it online!](https://tio.run/##y0lMqizKzCvJ@P/f3EyPy0LBkEvP0PD/fwA "Labyrinth – Try It Online")
---
## 14 bytes
```
7
.63
1 1
11.
```
[Try it online!](https://tio.run/##y0lMqizKzCvJ@P9fwZxLz8yYy1DBkMvQUO//fwA "Labyrinth – Try It Online")
### How it works
First, the flow: the execution starts at the first valid command, which is `7` on top. The only junction is `6`, and since it causes the top of stack to be positive, the IP always turns right. It turns 180 degrees if it hits a dead end. So the sequence of commands executed in order is:
```
76.111.13676.111.13676.111. ...(runs indefinitely)
```
The stack has implicit zeros, and each of `0-9` adds that digit to the end of the top of the stack (in other words, `n` changes the top number `x` to `10x + n`). So the program is supposed to print the characters with charcode 76, 111, 13676, 111, 13676, ...
But 13676 is not `l`! Actually, Labyrinth's character output is done modulo 256.
How did I find such a number? With the path designed like this
```
7
.6?
1 ?
11.
```
The problem is to find a number `??676` that is same as `l` (108) modulo 256. Note that, the equation `??xxx == yyy modulo 256` (`x` and `y` are givens and `?`s are unknown) is solvable if `xxx == yyy modulo 8`, and if so, it always has a solution within two or fewer digits, in particular `0 <= ?? < 32`. Since `676 % 8 == 108 % 8 == 4`, this is solvable, and the solution here is `13`.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils, 23 bytes
```
(echo L&yes)|tr "
y" ol
```
[Try it online!](https://tio.run/##S0oszvj/XyM1OSNfwUetMrVYs6akSEGJq1JJIT/n/38A "Bash – Try It Online")
### Explanation
We can generate infinite output using `yes`: without arguments, it outputs an infinite stream of `y` separated by newlines. `echo L & yes` outputs an `L` first, so our output stream looks like
```
L
y
y
y
y
```
To turn this into the output we want, we just need to change newline to `o` and `y` to `l`. `tr "\ny" ol` does this transliteration, and we can save a further byte by using an actual newline in place of `\n`.
[Answer]
# [Haskell](https://www.haskell.org/), 13 bytes
```
'L':cycle"ol"
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX91H3Sq5MjknVSk/R@l/bmJmnoKtQkFpSXBJkYKKQtr/f8lpOYnpxf91I5wDAgA "Haskell – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~51~~ ~~48~~ 47 bytes
```
a->{for(var s="L";;s="ol")System.out.print(s);}
```
[Try it online!](https://tio.run/##TY7BCoMwEETvfsWSU3LQHwj2LrQnj6WHrUaJVSPZNVDEb0@DiHQOM7A7PGbAgPnQfuKyvkfbQDMiETzQzrBlGSTZmY3vsDFQpROcCs62YEDW7O3cAyp9vPbDTxYxcoqjOiXiWX6@AH1P6o9WgYUSIua3rXNeBvRApbgLrVO4Uaj6S2ymwq1cLInBkpTeo74AtjBSiGvEHn8 "Java (JDK) – Try It Online")
thanks to [user](https://codegolf.stackexchange.com/users/95792/user) and [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) helping me save 4 and 1 byte(s) respectively!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 6 bytes
ovs' far superior 6-byter:
```
„Lo[?l
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcM8n/xo@5z//wE "05AB1E – Try It Online")
**Explanation:**
```
„Lo Push 2-char string onto stack ('lo')
[ Begin infinite loop
? Output with no newline
l Push lowercase of top of stack ('Lo' -> 'lo')
(Implicitly close infinite loop)
```
---
[05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
My pitiful 8-byter:
```
'L?„ol[?
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f3cf@UcO8/Jxo@///AQ "05AB1E – Try It Online")
It might still be golfable, perhaps if there's a way to compress 'Lol' even further.
**Explanation:**
```
'L Push 'L' onto stack
? Print without newline ('L')
„ol Push 2-char string onto stack ('ol')
[ Loop Forever
? Print without newline ('ol')
(Implicitly close infinite loop)
```
[Answer]
# [Marbelous](https://github.com/marbelous-lang/docs/blob/master/spec-draft.md), 14 ~~31~~ bytes
```
6C
6F@0
@0/\4C
```
Marbelous is a language based on marble machines
* `@n` (`n` from `0` to `Z`) is a portal which teleport the marble to another portal with the same value
* `00`-`FF` initiate a marble with this value
* `/\` create a duplicate passing marble to it's left and right
* `..` is a noop
* marbles going out of the machine from the bottom are implicitly outputed
[interpretor](https://github.com/marbelous-lang/marbelous.py)
-17 bytes thanks to DLosc
[Answer]
# [Python 3](https://docs.python.org/3.8/), ~~37~~ 34 bytes
-3 thanks to xnor - noting that print may have no unnamed argument!
```
x='L'
while x:x=print(end=x)or'ol'
```
**[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/v8JW3UedqzwjMydVwdCqwragKDOvRCM1L8W2QjO/SD0/R/3/fwA "Python 3.8 (pre-release) – Try It Online")**
[Answer]
# [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/), 147 bytes
```
haha l-o-l funny!i saw a thingy,it was soo funny
o?what
i am crying
o?what
i am dying,literal CHOKING
dying r-n?goddamn
just see
ohhhhhh heh,lol ig
```
[Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?VcoxDgIhEIXhnlM8ezjDFhZqTPQM44LMGJZJgA3h9Kuula/83s/EhOTUJTzXnMdBUKmD0FhyHFYaOlVU1d9vdOpMzQhowVzGJ/oj/xWbpIVCCcfz/Xq5ncyuKC5PUb2nJZvXWhtqCEZ5HziwTZogcdse5N8)
In the form of a text conversation between two people collectively laughing at something they found online.
[Answer]
# PHP, 24 bytes
```
L<?php for(;;)echo'ol';
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 27 bytes
```
f(i){f(!printf("Lol"+!i));}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI1OzOk1DsaAoM68kTUPJJz9HSVsxU1PTuvY/UEQhNzEzT0NToZqLM01D05qLsyi1pLQoT8HAmqv2PwA "C (gcc) – Try It Online")
[![enter image description here](https://i.stack.imgur.com/XMD52.png)](https://i.stack.imgur.com/XMD52.png)
[Answer]
# [convey](http://xn--wxa.land/convey/), 10 bytes
```
['L'}'lo'}
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiWydMJ30nbG8nfSIsInYiOjEsImkiOiIifQ==)
Visualization (separated)
[![Visualization (separated)](https://i.stack.imgur.com/mZP3O.gif)](https://i.stack.imgur.com/mZP3O.gif)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
”L⁾olȮ¿
```
A full program which prints an `L` then repeatedly prints `ol`.
**[Try it online!](https://tio.run/##y0rNyan8//9Rw1yfR4378nNOrDu0//9/AA "Jelly – Try It Online")**
### How?
```
”L⁾olȮ¿ - Main Link: no arguments
”L - set the left argument to 'L'
¿ - while...
Ȯ - ...condition: print & yield the left argument
⁾ol - ...do: set the left argument to "ol"
```
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), ~~11~~ 6 bytes
-5 thanks to @Bubbler
```
L;o;l;
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/9/HOt86x/r/fwA "Hexagony – Try It Online")
```
L ; Executed once: Set memory to 'L' (76) and print
o ; l Executed repeatedly: Set memory to 'o' (111), print, set memory to 'l' (108)
; . Executed repeatedly: Print
```
After the first row is executed once, the second and third rows are repeatedly executed, infinitely printing `ol`.
[Answer]
# [Cascade](https://github.com/GuyJoKing/Cascade), ~~22~~ 14 bytes
```
@o|
.l@
L"^
/"
```
[Try it online!](https://tio.run/##S04sTk5MSf3/3yG/hksvx4HLRymOS1/p/38A "Cascade – Try It Online")
-8 thanks to Jo King.
[Answer]
### **x86-16 machine code MS-DOS - 23 bytes**
This answer inspired by [640KB](https://codegolf.stackexchange.com/questions/210976/lolololololololololololol/210988#210988) answer.
```
000000: B4 02 B7 4C 8A D7 CD 21 B2 6F CD 21 8A D7 80 F2 ...L...!.o.!....
000010: 20 CD 21 EB F3 CD 20 .!...
```
Listing:
```
6 0100 B4 02 MOV AH, 02H
7 0102 B7 4C MOV BH, 'L'
8 0104 8A D7 MOV DL, BH
9 0106 CD 21 INT 21H
10
11 0108 PRINT:
12 0108 B2 6F MOV DL, 'o'
13 010A CD 21 INT 21H
14 010C 8A D7 MOV DL, BH
15 010E 80 F2 20 XOR DL, 20H
16 0111 CD 21 INT 21H
17 0113 EB F3 JMP PRINT
18
19 0115 CD 20 INT 20H
```
Output:
[![output](https://i.stack.imgur.com/98Iw5.png)](https://i.stack.imgur.com/98Iw5.png)
[Answer]
# [braingasm](https://github.com/daniero/braingasm), 12 bytes
```
76.28524+[.]
```
Prints the byte streams `76` once, then `28524` forever
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), two answers of 33 bytes
```
BEGIN{for(;;)printf s=s?"ol":"L"}
```
and
```
BEGIN{for(printf"L";;)printf"ol"}
```
[Try it online!](https://tio.run/##SyzP/v9f2cnV3dOvOi2/SMPaWrOgKDOvJE2h2LbYXik/R8lKyUeplgtJCUQeKApXC1JW@/8/AA "AWK – Try It Online") (uncomment a line to try it)
First answer: a simple ternary condition upon the assignment of the variable `s`. On the first run, it is evaluated as false. As it is not assigned yet, it is parsed as a null string, which is false.
Second answer: just a for loop.
[Answer]
# [Flipbit](https://github.com/cairdcoinheringaahing/Flipbit), ~~35~~ ~~30~~ 28 bytes
*Thanks to Bubbler for -5 by shortening the loop*
*Thanks to ovs for -2 by being big smort*
```
^>>>^>^>>.<<<<<^>>>[>^>^.<<]
```
[Try it online!](https://tio.run/##S8vJLEjKLPn/P87Ozi4OCO30bEAAxI0GCQC5sf//AwA)
Prints `L`, gets the tape set up for `l`, then makes use of the fact that `o` and `l` differ by only their two least significant bits to create a short loop to print both characters repeatedly.
[Answer]
# [Forte (Forter)](https://github.com/judofyr/forter), 25 bytes
```
5PRINT"ol";:LET5=1
1PUT76
```
[Try it online!](https://tio.run/##S8svKkn9/980IMjTL0QpP0fJ2srHNcTU1pDLMCA0xNzs/38A "Forte – Try It Online")
### Explanation
An undefined behavior exploit courtesy of [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king):
```
1 PUT 76
```
Print an `L` character.
```
5 PRINT "ol"; : LET 5 = 1
```
Print `ol` without a final newline, and set 5 to 1.
Apparently, this overwrites the former line 1 with the former line 5, and thus (lacking an `END` statement) the `PRINT "ol";` line is executed repeatedly forever. But I don't really understand how this works--especially since it only works if you write line 5 before line 1, not [vice versa](https://tio.run/##S8svKkn9/98wIDTE3IzLNCDI0y9EKT9HydrKxzXE1Nbw/38A)...
---
Here's a **44-byte** version that doesn't use any undefined behavior:
```
1PUT76
5PRINT"ol";:LET6=6+0
6LET0=2:LET5=5+2
```
[Try it online!](https://tio.run/##S8svKkn9/98wIDTE3IzLNCDI0y9EKT9HydrKxzXEzNZM24DLDMgysDUCCZjammob/f8PAA "Forte – Try It Online")
### Explanation
```
1 PUT 76
```
Print an `L` character.
```
5 PRINT "ol"; : LET 6 = 6 + 0
```
Print `ol` without a final newline, and set 6 to 6.
```
6 LET 0 = 2 : LET 5 = 5 + 2
```
Set 0 to 2, and set 5 to 7.
```
~~5~~ 7 PRINT "ol"; : LET 6 = 6 + ~~0~~ 2
```
Print `ol` again, and set 6 to 8.
```
~~6~~ 8 LET ~~0~~ 2 = 2 : LET ~~5~~ 7 = ~~5~~ 7 + 2
```
Set 2 to 2, and set 7 to 9.
```
~~5~~ ~~7~~ 9 PRINT "ol"; : LET ~~6~~ 8 = ~~6~~ 8 + ~~0~~ 2
```
Print `ol` again, and set 8 to 10.
And so on forever.
[Answer]
# [Vim](https://www.vim.org) `+startinsert`, ~~14~~ 11 bytes
```
ol<C-v><C-r>"<C-o>ddL<C-r>"
```
[Try it online!](https://tio.run/##K/uf@T8/R0xIiT8lxUdI6f9/AA)
In TIO, when the recursive register expansion (RRE) times out, nothing is outputted since it didn't finish expanding. In Vim, you may not see anything right away since the console might freeze during the RRE, but if you `Ctrl`+`C`, you can stop the expansion and see that it does work.
Explanation:
```
# '+startinsert' flag - start vim in insert mode; TIO equivalent is 'i' in the header
ol<C-v><C-r>" # Insert 'ol<C-r>"'
<C-o> # Run normal mode command, then return to insert mode:
dd # Delete 'ol<C-r>"' into unnamed register
L # Insert 'L'
<C-r>" # Insert unnamed register, which recursively expands to 'ol' + unnamed register
```
[Answer]
Neither beats Johan du Toit's answer, but I enjoy that they are full programs, plus I like the way the longjmp answer works.
# [C (gcc)](https://gcc.gnu.org/), 39 bytes
As straight forward as it gets, uses `for` initializer to print `L`, then it's `ol`s from there on out.
```
main(){for(printf("L");printf("ol"););}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7M6Lb9Io6AoM68kTUPJR0nTGsbOzwFyNK1r//8HAA "C (gcc) – Try It Online")
# [C (gcc)](https://gcc.gnu.org/), 50 bytes
Definitely more fun, use an int array as jmp\_buf, then add the return of setjmp to the string pointer so that the first iteration adds 0, then pass 1 to longjmp so the rest add 1 and skip the `L`.
Thanks to jdt for -4 bytes!
```
j[9];main(){printf("Lol"+setjmp(j));longjmp(j,1);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z8r2jLWOjcxM09Ds7qgKDOvJE1DySc/R0m7OLUkK7dAI0tT0zonPy8dzNYx1LSu/f8fAA "C (gcc) – Try It Online")
[Answer]
# [Pyramid Scheme](https://github.com/ConorOBrien-Foxx/Pyramid-Scheme), 200 bytes
```
^ ^
/ \ / \
/out\ /do \
-----^-----^
/ \ ^-
/chr\ / \
^-----/out\
/ \ ^-----^
/76 \ / \ ^-
-----/chr\ / \
^-----/chr\
/ \ ^-----
/111\ / \
-----/108\
-----
```
[Try it online!](https://tio.run/##TY1LCoAwDET3OcVcoMRu1MOUgqhQF0Xxs/D0tTF@OouQDO@R5Vy7OA1m68MYx5QAD4knMFxe8iSej92BhznvRuJ1EhQQ3sjBfVjdrUgjuVX6INW4qeF@UcFC/WTpqPghyTdba19WQVu1KuJpUroA "Pyramid Scheme – Try It Online")
This *seems* to be the shortest way that I can find. This language isn't easy to golf in.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
p\L#p"ol
```
[Try it online!](https://tio.run/##K6gsyfj/vyDGR7lAKT/n/38A "Pyth – Try It Online")
## Explanation
```
p\L#p"ol
p\L : print "L"
# : while True:
p"ol : print "ol"
```
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), 5 bytes
```
L,{ǪȽ
```
[Try it online!](https://tio.run/##y05N///fR6f6@KoTe///BwA "Keg – Try It Online")
Finally! A reasonable use for the push'n'print commands!
## Explained
* Print the letter "L" (`L,`)
* While true: (`{`)
* ---- Print the letter "o" (`Ǫ`)
* ---- Print the letter "l" (`Ƚ`)
[Answer]
# [Flobnar](https://github.com/Reconcyl/flobnar), 18 bytes
```
og,!<
\l@>\<
2:L!_
```
[Try it online!](https://tio.run/##S8vJT8pLLPr/Pz9dR9GGKybHwS7GhsvIykcx/v///7pF/3UzAQ "Flobnar – Try It Online") (requires the `-i` flag)
## Explanation
Flobnar is a 2D language where expressions are laid out geometrically. For example, for a program that computes the number 10, you might write:
```
5
+ @
5
```
Here, `@` indicates the entry point for the program, and has the effect of evaluating the term to its west; `+` evaluates the terms to the north and south and returns their sum; etc.
The basic idea for this program is to embed the characters 'o', 'l', and 'L' in the source code at coordinates `(0, 0)`, `(1, 1)`, and `(2, 2)` respectively. Execution proceeds roughly like this:
```
def step(n):
step(!n if (!putchar(get(n, n))) else "impossible since putchar() returns 0")
step(2)
```
Here's what the program looks like ungolfed:
```
o >>>>v
l ^ \ < \ @
L v 2
:!_
:
g , !<
:
```
See [the specification](https://github.com/catseye/Flobnar) for more detailed information about what each term does.
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
Closed 7 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Can you write an [aphorism](http://en.wikipedia.org/wiki/Aphorism) in at most 4 lines of code ?
Code should read as much as possible as an aphorism in plain English and should return the boolean `true`.
Language: of choice.
Criteria for accepted answer: Most votes in 180 ~~30~~ days. (8th of July 2014)
Originality: can be an old aphorism but a creative one would be much more appreciated.
[Answer]
# Python
```
import this
love = this
this is love, love is not True or False, love is love
# (True, True, True)
```
Okay, this returns a tuple of Truths, but that itself evaluates as True anyway.
[Answer]
## Forth
```
2 : b or ! 2 ." b" ;
: that s" the questi" on ;
```
[Answer]
# C:
You'll have to squint a bit to read this one :-)
```
int x(){ int __,L ;
return (__ |__ ||__ |__ ,__,__ ,__ ,__ ,__ ,
__|| 1||__ | 1L/L|__||__|1/__| 1L)
; }
```
You might notice a potential division-by-zero error on line 3, but this is never executed because the expression evaluates as `true` before the calculation is performed.
[Answer]
It's difficult to avoid string literals, comments and tricks fo this kind, but I tried to keep them to a mininum. Also, the first line makes no sense. Well, I had `fun` doing it
## F#
```
(fun () -> (fun (_) -> // fun fun? wtf
try not <| failwith("me") ; (*but*) with |Failure((*co*)me(*s*)) -> true)("learning"))()
// "Try not to fail with me, but with failure comes true learning
```
I could also do some declaration abusing, but I ended up not finding a way to return true:
```
let the,bodies,hit_the=floor(0.0),(),()
```
or
```
let the_games=bigint() //pun intended
```
I really need to stop with the puns.
[Answer]
# C
No string literals or comments:
```
Better(to,re);main(silent){and();}be(thought,a,fool){}
than(to,open,your,mouth);and(){}remove(all,doubt);
```
Split over two lines, but one would work fine as well.
When compiled using gcc on Linux (x86-64), this produces an executable which exits with success (exit code 0), the same as the `true` Unix utility; this being how I choose to interpret the requirement of returning boolean `true` in a non-scripting language.
Note: notwithstanding the abuse of the "implicit int" rule, the principal trick behind this program is that while a C program that falls off the end of `main` without a `return` statement will usually result in a non zero exit code, by calling another function we can set the `EAX` register which is then used as the exit code of the program. This is of course totally undefined behaviour and utterly non portable.
[Answer]
# Python
```
war=peace=freedom=slavery=ignorance=strength=0
war is peace|freedom is slavery|ignorance is strength
Power=a=means=it=an=end=0
Power is not (a, means, it is (an, end))
```
# JavaScript
```
You=true;function BigBrother(){};BigBrother.isWatching=function(y){return y};
BigBrother.isWatching(You)
```
[Answer]
# C#:
```
short life = 0;
return (life is short);
```
"Life is short" (Hippocrates)
[Answer]
# Ruby
```
class String
def before(b) self < b end
end
```
A bit lengthy, but gets us a few aphorisms:
```
"age".before("beauty")
"business".before("pleasure")
"pearls".before("swine")
```
And (stretching slightly):
```
dont = []; y = 1
dont.count + y or ('chickens'.before('they hatch'))
```
[Answer]
# Scala
```
Some apply Double forall _; None isEmpty
```
[Answer]
# CoffeeScript
```
2 * @wrong isnt @right
```
=> true
[Answer]
# C++
```
bool life = true;
bool fair = false;
assert(life != fair);
```
[Answer]
# Python
```
love=[True];all,fair,war=love*3
all is fair in love and war
```
[Answer]
An aphorism about http verbs, in
## Ruby
```
puts do
something idempotent but are considered to be unsafe
because if the value at the beginning of a chain of calls is one possibly the value at the
end != 1
```
[Answer]
## C
```
if ((ifs && ands) == (pots && pans))
work_for_tinkers_hands = FALSE;
```
[Answer]
# Javascript
```
function be(who) {
if (who == 'thine own self') {
return true;
}
}
```
An approximation of "To thine own self be true."
I'm kind of fudging with the requirements, since it only returns true in one particular case ... but I'm hoping you'll let it slide because the return value is actually part of the aphorism.
[Answer]
# C
```
int main(int fear, int* computers){ int
i; do { !fear; computers[i]; fear; "the lack of them";
} while();return true;}
```
*I do not fear computers, I fear the lack of them.*
-Isaac Asimov
[Answer]
# C
```
main(int I,char **think) {char *a="there"; for (;--I;) a['m'];}
```
[Answer]
I got a wonderful error while attempting this:
It's very much inspired by Darren Stone's answer.
>
> TypeError: Cannot use 'in' operator to search for 'tis nobler' in mind to suffer the The Slings and Arrows of outrageous fortune
>
>
>
# Javascript
```
[2].be || ! [2].be ; this.is, "the question"
```
It returns an implicit true.
Slightly less terse, with a question mark:
```
[2].be || ! [2].be? is = this: !"the question"
```
[Answer]
# PHP
```
$all = array('not well', 'not well', 'not well', 'well');
$end = array_pop($all);
$all = ($end == 'well') ? $end : 'not well';
return true;
```
"All's well that ends well."
[Answer]
# Q
`any bird:`int$"hehand"=2^`int$"hebush"`
and
`(./) 2_iscomp:any 3,'s:"a",'"crowd"`
[Answer]
# PHP
An apple a day...
```
$aphorism = function(){
for($day=1;$day<=365;$day++) $apple++;
return ($apple==365) ? true : 'doctor';
};
```
[Answer]
# Common Lisp
```
(Do ((as)) ('(I say no)t) as I do)
(time (and 'tide (wait-for 'no-man))) ;requires sbcl
```
[Answer]
A bit lazy, but my take.
# Python:
```
life = short = True; art = long = True; life=art
life is short and art is long
```
# JavaScript:
```
The = word = 'Yoga'
has = been = 'vulgarized'
and = does = not= mean = anything =Date.now() ,!''
//Swami Rama
```
[Answer]
# Lua
```
-- all search is in vain
function search() end
-- only the void is true
function void() return function() return true end, true end
-- and what remains is to
for ever in void() do repeat search("light") until true end
return true
```
[Answer]
# JavaScript
```
return (Do || !Do) || (there == !try);
```
```
return 2 * be || !(2 * be);
```
[Answer]
## R
```
the_whole <- c(-1,-1)
the_part <- -1
the_whole > sum(the_part,the_part)
```
-Socrates
[Answer]
## [Simply-Basic 84](http://timtechsoftware.com/?page_id=1274 "Simply-Basic 84")
```
Label 1;a random number between 0 and 1~should be stored in~A
If A is equal to 1 Then Display A End;Stop&Else,Go to label 1
:End; Otherwise destroy quantum transmitters internationally.
Since quantum transmitters are gone, power lost. KA-POW, yes?
```
[Answer]
# Prolog
```
waste(not).
want(X) :-
waste(X).
```
[Answer]
**Python**
```
be = that = the = question = 1
2 - be or not 2 - be
that is the & question
```
[Answer]
**Ruby**
Not the most elegant solution, but very easy to read
```
def you_know_meaning(x) true end
!!!("aphorism" != "aphorism" unless you_know_meaning "aphorism")
=> true
```
] |
[Question]
[
(Title with thanks to @ChasBrown)
[Sandbox](https://codegolf.meta.stackexchange.com/a/17585/56555)
**The Background**
This challenge is inspired by a question that I recently posted on [Puzzling Stack Exchange](https://puzzling.stackexchange.com/questions/81925/sum-letters-are-not-two-different). Please feel free to follow the link if you are interested in the original question. If not then I won't bore you with the details here.
**The Facts**
Every printable standard ASCII character has a decimal value between 32 and 126 inclusive. These can be converted to their corresponding binary numbers in the range 100000 to 1111110 inclusive. When you sum the bits of these binary numbers you will always end up with an integer between 1 and 6 inclusive.
**The Challenge**
Given an integer between 1 and 6 inclusive as input, write a program or function which will output in any acceptable format all of the printable standard ASCII characters where the sum of the bits of their binary value is equal to the input integer.
**The Examples/Test Cases**
```
1 -> ' @'
2 -> '!"$(0ABDHP`'
3 -> '#%&)*,1248CEFIJLQRTXabdhp'
4 -> ''+-.3569:<GKMNSUVYZ\cefijlqrtx'
5 -> '/7;=>OW[]^gkmnsuvyz|'
6 -> '?_ow{}~'
```
An ungolfed Python reference implementation is available [here (TIO)](https://tio.run/##dc1NCoMwEAXgfU8xuErQjfGnIOQAXfUA6kKtqVk4kRjBnj5NLbUtxFm9GT7eTA8zKGTW3noBgkgKxQncKF7WWxBKwwoSQTd470nCopidP@o1DW8lkpXuh5Y3JSvqfe/42ExEoonaL5IC5mUkHeVc/pRtr0NedoN2le8O3ZtFIyg7aVcCwQWnxRQQV3hdzBYDCGE2mggSU@pyUGFw@tfMp9mRTnw6OdKpT6dHOvPp7EjnPp3v2j4B).
**The Rules**
1. Assume the input will always be an integer (or string representation of an integer) between 1 and 6 inclusive.
2. You may write a program to display the results or a function to return them.
3. Output may be in any reasonable format but **must be consistent for all inputs**. If you choose to output a quoted string then the same type of quotes must be used for all inputs.
4. Standard loopholes prohibited as usual.
5. This is code golf so shortest code in each language wins.
[Answer]
# x86-16 machine code, IBM PC DOS, ~~29~~ 25 bytes
**Machine code:**
```
00000000: be81 00ad b330 b108 d0c8 12dd e2fa 3adc .....0........:.
00000010: 7502 cd29 fec0 79ec c3 u..)..y..
```
**Listing:**
```
BE 0081 MOV SI, 081H ; SI = memory address of command line string
AD LODSW ; AL = start ASCII value (is 20H from space on cmd line)
; AH = target number of bits (in ASCII)
CHR_LOOP:
B3 30 MOV BL, '0' ; BL = counter of bits, reset to ASCII zero
B1 08 MOV CL, 8 ; loop through 8 bits of AL
BIT_LOOP:
D0 C8 ROL AL, 1 ; rotate LSB of AL into CF
12 DD ADC BL, CH ; add CF to BL (CH is always 0)
E2 FA LOOP BIT_LOOP ; loop to next bit
3A DC CMP BL, AH ; is current char the target number of bits?
75 02 JNE NO_DISP ; if not, do not display
CD 10 INT 29H ; display ASCII char in AL (current char in loop)
NO_DISP:
FE C0 INC AL ; increment char to next ASCII value
79 EC JNS CHR_LOOP ; if char <= 127, keep looping
C3 RET ; return to DOS
```
Standalone PC DOS executable program, input number from command line. Output is displayed to console window.
[![enter image description here](https://i.stack.imgur.com/kQNqg.png)](https://i.stack.imgur.com/kQNqg.png)
[Answer]
# [CP-1610](https://en.wikipedia.org/wiki/General_Instrument_CP1600) assembly ([Intellivision](https://en.wikipedia.org/wiki/Intellivision)), 20 DECLEs1 = 25 bytes
Takes \$N\$ in **R0** and a pointer to the output buffer in **R4**. Writes all matching characters in the buffer and marks the end of the results with **NUL**.
```
ROMW 10 ; use 10-bit ROM width
ORG $4800 ; map this program at $4800
;; ------------------------------------------------------------- ;;
;; test code ;;
;; ------------------------------------------------------------- ;;
4800 EIS ; enable interrupts
4801 MVII #$103, R4 ; set the output buffer at $103 (8-bit RAM)
4803 MVII #2, R0 ; test with N = 2
4805 CALL getChars ; invoke our routine
4808 MVII #$103, R4 ; R4 = pointer into the output buffer
480A MVII #$215, R5 ; R5 = backtab pointer
480C draw MVI@ R4, R0 ; read R0 from the buffer
480D SLL R0, 2 ; R0 *= 8
480E SLL R0
480F BEQ done ; stop if it's zero
4811 ADDI #7-256, R0 ; draw it in white
4815 MVO@ R0, R5
4816 B draw ; go on with the next entry
4818 done DECR R7 ; loop forever
;; ------------------------------------------------------------- ;;
;; routine ;;
;; ------------------------------------------------------------- ;;
getChars PROC
4819 MVII #32, R1 ; start with R1 = 32
481B @loop MOVR R1, R3 ; copy R1 to R3
481C CLRR R2 ; clear R2
481D SETC ; start with the carry set
481E @count ADCR R2 ; add the carry to R2
481F SARC R3 ; shift R3 to the right (the least
; significant bit is put in the carry)
4820 BNEQ @count ; loop if R3 is not zero
4822 CMPR R2, R0 ; if R2 is equal to R0 ...
4823 BNEQ @next
4825 MVO@ R1, R4 ; ... write R1 to the output buffer
4826 @next INCR R1 ; advance to the next character
4827 CMPI #127, R1 ; and loop until 127 is reached
4829 BLT @loop
482B MVO@ R3, R4 ; write NUL to mark the end of the output
482C JR R5 ; return
ENDP
```
### Output for N=2
NB: The opening parenthesis looks a lot like an opening square bracket in the Intellivision font. Both characters are distinct, though.
[![output](https://i.stack.imgur.com/DxHlW.gif)](https://i.stack.imgur.com/DxHlW.gif)
*screenshot from [jzIntv](http://spatula-city.org/~im14u2c/intv/)*
---
*1. A CP-1610 opcode is encoded with a 10-bit value, known as a 'DECLE'. This routine is 20 DECLEs long, starting at $4819 and ending at $482C (included).*
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
lambda n:[chr(i)for i in range(32,127)if bin(i).count('1')==n]
```
[Try it online!](https://tio.run/##PcvBCoQgEIDhV5mbCkOgbQWBT1J7sDZrosYQO@zTm6fO//9d/7QFNtnbMR/unH4OuB/mLUpSPkQgIIboeF1kbVCbTpGHibjkag43Jym0UNbyN7@7RoM1frDBtocrEicgBCGqPRToC1X5AQ "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~41~~ 34 bytes
```
{chrs grep *.base(2)%9==$_,^95+32}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OjmjqFghvSi1QEFLLymxOFXDSFPV0tZWJV4nztJU29io9n9xYqWCHlBxWn6RgqGenpn1fwA "Perl 6 – Try It Online")
Anonymous code block that takes a number and returns a string of valid characters.
### Explanation:
```
{ } # Anonymous code block taking a number
grep ,^95+32 # Filter from the range 32 to 126
*.base(2) # Where the binary of the digit
%9 # When parsed as a decimal modulo 9
==$_ # Is equal to the input
chrs # And convert the list of numbers to a string
```
It can be proven that for any number \$n\$ in base \$b\$, \$n \equiv \text{digitsum}(n) \pmod{b-1}\$ (clue: remember that \$b \pmod{b-1}=1\$).
We can use this to get the digitsum of our binary number by parsing it as a decimal number and moduloing by 9, which is valid because the range of numbers we are using is guaranteed to have less than 9 bits. This is helped along by Perl 6's automatic casting of the binary string to a decimal number when used in a numeric context.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
žQʒÇbSOQ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6L7AU5MOtycF@wf@/28MAA "05AB1E – Try It Online")
**Explanation**
```
žQ # push the printable ascii characters
ʒ # filter, keep elements whose
Ç # character code
b # converted to binary
SO # has a digit sum
Q # equal to the input
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ØṖOB§=ʋƇ
```
[Try it online!](https://tio.run/##y0rNyan8///wjIc7p/k7HVpue6r7WPv///@NAA "Jelly – Try It Online")
```
ØṖ printable ascii character list
OB to binary
§ popcount
= equal to input?
ʋƇ filter (implicitly output)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
∈Ṭ&ạhḃ+
```
[Try it online!](https://tio.run/##AUUAuv9icmFjaHlsb2cy/3t3IiAtPiAidz9@4oaw4oKC4bag4bqJfeG1kP/iiIjhuawm4bqhaOG4gyv//1sxLDIsMyw0LDUsNl0 "Brachylog – Try It Online")
A predicate which [functions as a generator](https://codegolf.meta.stackexchange.com/a/10753/85334), takes input through its output variable, and produces each character through its input variable. Because Brachylog.
```
The input variable (which is an element of the output)
∈ is an element of
Ṭ the string containing every printable ASCII character
& and the input
ạh converted to a codepoint
ḃ converted to a list of binary digits
+ sums to
the output variable (which is the input).
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 60 bytes
*Using [Jo King's modulo trick](https://codegolf.stackexchange.com/a/184649/58563)*
```
n=>(g=x=>x>>7?'':Buffer(x.toString(2)%9-n?0:[x])+g(x+1))(32)
```
[Try it online!](https://tio.run/##ZchLCsIwEADQvfeQzlBaNPWDhaTgFVyKi1KT0FJmJE3L3D66lbzlm/qtX4YwfmJF/LbJ6UTagNeijRhz7Yqiva/O2QBSR37EMJIHhftbRd2hfcoLSw9SHhGhUZgGpoVnW8/swcFvd/@jsmmyOWVzzuaCmL4 "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), ~~70~~ 69 bytes
```
n=>(g=x=>x>>7?'':Buffer((h=x=>x&&x%2+h(x>>1))(x)-n?0:[x])+g(x+1))(32)
```
[Try it online!](https://tio.run/##ZclLCoMwEADQfe@hzhCUNrYKQiL0GqULsUlUJBF/zO1T665k@97Q7M3Szv20ptZ9lNfCWyHBCBKSpCzrJKmem9ZqBuhOjGOKOOvg2BsiEKa2vlYveiMzQOxnOUffOru4UWWjM6Dh0Mu/8EDyQO6BPAIpEP0X "JavaScript (Node.js) – Try It Online")
### Commented
```
n => ( // n = input
g = x => // g = recursive function, taking a byte x
x >> 7 ? // if x = 128:
'' // stop recursion and return an empty string
: // else:
Buffer( // create a Buffer:
(h = x => // h = recursive function taking a byte x
x && // stop if x = 0
x % 2 + // otherwise, add the least significant bit
h(x >> 1) // and do a recursive call with floor(x / 2)
)(x) // initial call to h
- n ? // if the result is not equal to n:
0 // create an empty Buffer (coerced to an empty string)
: // else:
[x] // create a Buffer consisting of the character x
) + // end of Buffer()
g(x + 1) // append the result of a recursive call to g with x + 1
)(32) // initial call to g with x = 32
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 bytes
```
;EƶXc¤è1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O0XGtlhjpOgx&input=Ng) or [test all inputs](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=xA&code=O0XGtlhjpOgx&footer=KyIgPSAiK1Y&input=NgotbVI)
```
;EƶXc¤è1 :Implicit input of integer U
;E :Printable ASCII
Æ :Filter each X
¶ :Test U for equality with
Xc : Character code of X
¤ : To binary string
è1 : Count the 1s
```
[Answer]
# Excel (2016 or later), 76 bytes
```
=CONCAT(IF(LEN(SUBSTITUTE(DEC2BIN(ROW(32:126)),0,))=A1,CHAR(ROW(32:126)),""))
```
Takes input from A1, outputs in whatever cell you put this formula. This is an array formula, so you need to press `Ctrl`+`Shift`+`Enter` to input it. The "2016 or later" is because it needs the `CONCAT` function (the deprecated `CONCATENATE` won't take an array as argument).
[Answer]
# C (standard library), 74 67 bytes
```
i;j;k;f(n){for(i=31;i<126;k||puts(&i))for(k=n,j=++i;j;j/=2)k-=j&1;}
```
Using only standard library functions. Thanks go to @gastropner for improvement from 74 to 67 bytes.
[Try it online!](https://tio.run/##FctLCoAgEADQtZ7CVcxQERa0meYwIRijZNFnZZ3daP14rl2cK0UoUCQPCbPfDhAeLMlk@5Hi8@z3dUIliD9FTk3guv5H6LjH2HKoLL1F0mXWWRKgyVp5sEj61ap8)
[Answer]
# [R](https://www.r-project.org/), 77 68 bytes
### Approach using for loop
-9 bytes thanks to Giuseppe
```
n=scan();for(i in 32:126)if(sum(intToBits(i)>0)==n)cat(intToUtf8(i))
```
[Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTOi2/SCNTITNPwdjIytDITDMzTaO4NFcjM68kJN8ps6RYI1PTzkDT1jZPMzmxBCIcWpJmARTW/G/yHwA "R – Try It Online")
### Previously:
# [R](https://www.r-project.org/), 78 69 66 bytes
-12 bytes thanks to Giuseppe
```
a=32:126;cat(intToUtf8(a[colSums(sapply(a,intToBits)>0)==scan()]))
```
Turns the numbers 32 to 126 into a matrix of bits then sums across the rows to find which match the input number.
[Try it online!](https://tio.run/##K/r/P9HW2MjK0MjMOjmxRCMzryQkP7QkzUIjMTo5Pye4NLdYozixoCCnUiNRByzplFlSrGlnoGlrW5ycmKehGaup@d/kPwA "R – Try It Online")
[Answer]
# Java 10, ~~98~~ ~~97~~ ~~94~~ ~~70~~ 67 bytes
```
n->{for(var c='';c-->31;)if(n.bitCount(c)==n)System.out.print(c);}
```
-24 bytes thanks to *NahuelFouilleul*.
[Try it online.](https://tio.run/##ZU@xasNADN3zFY8sucPYEAoder0snTo0S8bS4XKxjRJHDndnQwmmn@7KrunQCkmgJ@np6ex6l59Pl9E3Lka8OeL7CiBOZaicL7GfSqBv6QSvXgWvywDWRuBBQjwml8hjD4bFyPnuXrVB9S7A283Xxvg83z1sjaZKcXGk9NJ2nJTX1rI@fMZUXou2S8Ut0AybYTQrob11x0ZoF/ZZwFXkqUOSwfr9Ay7UUf/Imw7KNshuDejZPkrOsqUJ/LtC2foJ6/mJybjwin6rv9MNq6U3zE8P4zc)
**Explanation:**
Contains an unprintable character with unicode value `127`.
```
n->{ // Method with Integer parameter and no return-type
for(var c='';c-->31;) // Loop character `c` in the range ['~', ' '] / (127,31):
if(n.bitCount(c) // If the amount of 1-bits in the two's complement binary
// representation of the current characters
==n) // equals the input:
System.out.print(c);} // Print the current character
```
[Answer]
# Java 8, ~~131~~ 71 bytes
-60 bytes thanks to everyone in the comments
Returns a `java.util.stream.IntStream` of codepoints
```
n->java.util.stream.IntStream.range(32,127).filter(i->n.bitCount(i)==n)
```
[Try it online!](https://tio.run/##dY4xa8MwEEZ3/4obJbCPJoV2MA6UQKBDoZCxdFBsyT1XPgXpnBKMf7urtkO7dLo3fPd4g7mYauje19ablODJEM8FsdjoTGvhMA95gJOQxyTRmhEfWY7fBE5ltr2NwLpeivN08tRCEiP5XAJ1MGadymvi/uUVTOyTnosDOGhWrnb/qzEa7q263Zab7b1GRz4HKap2jCeSfZhYFOmmYb3WX7VZ3obOPofMCRpw6NSdRgkPMZqr0nVxvCaxI4ZJ8JxzxLNi@wE/ber3ubwp/6jQW@7lTWfBsqyf)
Using HashSet, 135 bytes. Returns a `Set<Object>`:
```
n->new java.util.HashSet(){{for(int i=31;i++<126;add(Long.toBinaryString(i).chars().map(c->c-48).sum()==n?(char)i+"":""),remove(""));}}
```
[Try it online!](https://tio.run/##RY5BT4QwEIXv/IqG0zRIk12NMSBrYuLGg572aDyMpUARWtIOmA3Z346jHjzNS95737weF8z7@nPTA8YoXtG6NbGOTGhQG3Fcew6omeygToZEA@wJJ8tLMs0fg9UiEhKfxdtajNyGEwXr2rd3DG2Ua3IUTbW5/ODMl/hnPWPsmAdyXRsffqG2ut6VNsvud/vbEusaXrxrFflH6zCc/6hgpdIdhghSjTiBzg86v7mTKs4jyKpyD/BjS5ulaZGm8iqY0S8GWPLky1YmjWpgz3kKBrmiog9kahY84wl1B6dzJDMqP1NRTPyTZJlw8xs)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 86 bytes
```
n=>Enumerable.Range(32,95).Where(x=>"0123456".Sum(g=>x>>g-48&1)==n).Select(x=>(char)x)
```
Thanks to @ExpiredData for giving me the idea to use `Sum()`! When I get back to my PC, I will replace the string `"0123456"` with unprintables, saving three bytes.
[Try it online!](https://tio.run/##RY1NC4JAFADv/grxEPvIlrTsS3cvURB0yoNnW572QF@wriCIv93q1HUYZky3Mh3N155NRuzC24X7Fm35bDAzr9JqXamZlf5j@Si5RrGJw2MCsnihRTEoHayjeLNNdoHM@1bUSg9a16vtYRGBUgwyxwaN@5ni14UB5tSr3lZ8rz6pKKVsn9JyCZ7vF5Yc3olRBON6OvljNAUhhZ2zxLU8v9mUTlSCACCdPw "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# Dyalog APL Extended, ~~24~~ 22 bytes
```
⎕ucs a⌿⍨⎕=+⌿2⊤a←32…126
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKNdIe3/o76ppcnFComPevY/6l0B5NlqA5lGj7qWJD5qm2Bs9KhhmaGRGUjx/zQuQ640LiMgNgZiEyA2BWIzAA "APL (Dyalog Extended) – Try It Online")
-2 bytes thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn)
Alternative 22 bytes in regular Dyalog APL by ngn:
```
⎕ucs 32+⍸⎕=32↓+/↑,⍳7⍴2
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkGXI862hXSQPzS5GIFYyPtR707gBxbY6NHbZO19R@1TdR51LvZ/FHvFqP/QKX/07gMudK4jIDYGIhNgNgUiM0A "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 52 bytes
```
[ 32 126 [a,b] [ bit-count = ] with filter >string ]
```
[Try it online!](https://tio.run/##JYyxDoIwFEV3v@J@gJKAiYNGV@PCYpxIh9I8oAFKfX2E@PX1JWz35J6czjpZOH/er/p5xWxlKNiGntK@Wy@bT4SRONCERN@VgtM3CfvQJ0QmkV9UENwOFzTlsTW5wblCWSlaRTTQzsktq0p3GGxeBnR@EmI89hJMnm3UrHVjkf8 "Factor – Try It Online")
* `32 126 [a,b]` Create a range of printable ascii values
* `[ bit-count = ] with filter` Select values with the bit count indicated by the input
* `>string` Convert the result from a sequence of code points to a printable string
[Answer]
# [J](https://www.jsoftware.com), ~~31~~ ~~27~~ 23 bytes
```
((=1#.#:)u:@#])32+i.@95
```
*-2 thanks to south*
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxXUPD1lBZT9lKs9TKQTlW09hIO1PPwdIUIrtNkys1OSNfIU1JW8FQwUjBWMFEwVTBDCK5YAGEBgA)
# [J](http://jsoftware.com/), ~~31~~ 27 bytes
*-4 bytes thanks to Galen*
```
[:u:32+[:I.]=1#.32#:@+i.@95
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o61KrYyNtKOtPPVibQ2V9YyNlK0ctDP1HCxN/2typSZn5AM1Oagr6FoppCkYQgUUlVQ0DBydXDwCEqAyRlAZZVU1TS0dQyMTC2dXN08vn8CgkIjEpJSMAqg6Y6g6@/j88uraOqioGdd/AA "J – Try It Online")
## Original Answer
```
a.#~&(95{.32}.])]=1#.2#:@i.@^8:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/E/WU69Q0LE2r9YyNavViNWNtDZX1jJStHDL1HOIsrP5rcqUmZ@QDNTqoK@haKaQpGEIFFJVUNAwcnVw8AhKgMkZQGWVVNU0tHUMjEwtnVzdPL5/AoJCIxKSUjAKoOmOoOvv4/PLq2jqoqBnXfwA "J – Try It Online")
* `2#:@i.@^8:` produces the binary numbers 0 through 255 (`2 ^ 8` is 256)
* `1#.` sums each one
* `]=` produces a binary mask showing where the sum equals the original input
* `a.#~ mask` uses that binary mask to filter J's full ascii alphabet `a.`
* `&(95{.32}.])` but before doing so take only elements 32...126 from both the alphabet and the mask
[Answer]
# [Python 2](https://docs.python.org/2/), 69 bytes
```
lambda n:[chr(i)for i in range(32,127)if sum(map(int,bin(i)[2:]))==n]
```
[Try it online!](https://tio.run/##Dco7DoAgDADQq3RsExbrYELCSZQBP2gTKQR18PTo@vLKex9ZuUU3tTOkeQ2gdlyOikIxVxAQhRp037Bn0/FAEuF6EqZQUPQ2s@hfR7aeyDn1rdSfMSITtQ8 "Python 2 – Try It Online")
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 10 bytes
```
₵R⟪¤cbΣ=⟫⁇
```
[Try it online!](https://tio.run/##AR0A4v9nYWlh///igrVS4p@qwqRjYs6jPeKfq@KBh///Mw "Gaia – Try It Online")
```
| implicit input, n
₵R | push printable ascii
⟪ ⟫⁇ | filter the list where:
¤cbΣ | the sum of the code point in binary
= | is equal to n
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 48 bytes
```
->n{(' '..?~).select{|x|x.ord.digits(2).sum==n}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWkNdQV1Pz75OU684NSc1uaS6pqKmQi@/KEUvJTM9s6RYwwgoU5pra5tXW/u/QCEt2ij2PwA "Ruby – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, ~~50~~ 43 bytes
*@NahuelFouilleul saves 7 bytes*
```
map{$_=chr;unpack('B*')%9-"@F"||say}32..126
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saBaJd42OaPIujSvIDE5W0PdSUtdU9VSV8nBTammpjixstbYSE/P0Mjs/3/jf/kFJZn5ecX/dX1N9QwMDf7rJgIA "Perl 5 – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 20 bytes
**Solution:**
```
`c$32+&(+/2\32+!95)=
```
[Try it online!](https://tio.run/##y9bNS8/7/z8hWcXYSFtNQ1vfKAbIULQ01bQ1@/8fAA "K (ngn/k) – Try It Online")
**Explanation:**
Evaluated right-to-left:
```
`c$32+&(+/2\32+!95)= / the solution
= / equals?
( ) / do this together
!95 / range 0..94
32+ / add 32, so range 32..126
2\ / break into base-2
+/ / sum up
& / indices where true
32+ / add 32
`c$ / cast to character
```
[Answer]
# 6502 assembly (NES), 22 bytes
Machine code:
```
a0 1f a6 60 c8 98 30 fb ca 0a b0 fc d0 fb e8 d0 f1 8c 07 20 f0 ec
```
Assembly:
```
ldy #$1f ; Y holds the current character code
NextCharacter:
ldx $60 ; load parameter into X
iny
tya
bmi (NextCharacter + 1) ; exit at char 128, #$60 is the return opcode
CountBits:
dex
Continue:
asl
bcs CountBits
bne Continue
CompareBitCount:
inx ; fixes off-by-one error and sets Z flag if bit count matches
bne NextCharacter
sty $2007
beq NextCharacter ; always branches
```
[Full program](https://hastebin.com/raw/xemikiwege.asm). Tested with FCEUX 2.2.3, should work on any standard NES emulator.
Inspired by Ryan Russell's answer. Input given at CPU address $60. Outputs to the console's Picture Processing Unit memory.
[Answer]
# VBA, 146 bytes
```
Sub Main()
n=3
For i=32 To 127
b=CStr(Application.WorksheetFunction.Dec2Bin(i))
If Len(b)-Len(Replace(b,"1",""))=n Then MsgBox Chr(i)
Next
End Sub
```
I wonder if somehow it could be done using Excel alone, I am not a excel formula pro....
[Answer]
# [Nibbles](http://golfscript.com/nibbles), 5 bytes
```
|_~`^+`@ 2
```
That's 10 nibbles each encoded as half a byte in the binary form.
Translation:
```
| filter
_ printables (since stdin is empty)
~ not
`^ xor
+ sum
`@2 to base 2
$ filter var (implicit)
@ first input arg (implicit)
```
It uses not of the xor to set itself up for implicit args (instead of == which wouldn't be able to use any)
Usage:
```
nibbles <filename>.nbl <input number>
```
Nibbles isn't on TIO yet...
[Answer]
# [Python 3.10](https://www.python.org), 58 bytes
```
lambda n:(chr(i)for i in range(32,127)if i.bit_count()==n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3rXISc5NSEhXyrDSSM4o0MjXT8osUMhUy8xSKEvPSUzWMjXQMjcw1M9MUMvWSMkvik_NL80o0NG1t8zShJmih6TDUMde04uIsKMoEKlRS0svKz8zTSAOarAnVsWABhAYA)
It's kind of like [Lynn's answer](https://codegolf.stackexchange.com/a/183631/112099).
Just it uses the `.bit_count` introduced in Python3.10, so its shorter
More info about `.bit_count` here: <https://docs.python.org/3/library/stdtypes.html>
[Answer]
# [Kotlin](https://kotlinlang.org), 60 bytes
```
{n->(32..127).filter{n==it.countOneBits()}.map{it.toChar()}}
```
Note:
For the moment Kotlin's STDOUT in ATO is always empty.
And TIO doesn't support countOneBits().
More information about how to count bytes for a Kotlin answer:
<https://codegolf.stackexchange.com/a/202985/112099>
[Attempt This Online!](https://ato.pxeger.com/run?1=LYwxCsJAEEX7nCIEhN1iBxILRUwKrQTBQi-wSFZHN7MhmdgsOYlNGr1TbuMGU314n_fe36djizSMC9NRXGkkIX300jY2G3Eglqo4Ysvb_V03RZx_OjZqPW49qUIsM4A0W0kwaLlsPOU5MlxdR3yicofcCtlDpWsfMLspEUA_N5RIAYI8_XWDxJaEEcgSHg7p4s4c4E0kiZR9NEvD8N8f)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
6Y2tB!si=)
```
[Try it online!](https://tio.run/##y00syfn/3yzSqMRJsTjTVvP/fxMA "MATL – Try It Online")
## Explanation
```
6Y2 % All ASCII Chars
t % dup
B % convert each to binary
! % transpose
s % sum
i= % equal to the input?
) % Keep truthy elements
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 70 bytes
```
FromCharacterCode/@Select[32~Range~126,s=#;Tr@IntegerDigits[#,2]==s&]&
```
[Try it online!](https://tio.run/##BcHBCoMwDADQXxEET4Kswi5SKDiE3YbuVnoIXYiFtYU0Z389vpdBTswgKYKS1Y1rXk9giIK81h9O7sA/RvGzuXYohNfDPMdm@@XL7l0ECfmVKEnz/WiCtW0Ig344FekceRNUbw "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
Write a program or function that finds the number of zeroes at the end of `n!` in base 10, where `n` is an input number (in any desired format).
It can be assumed that `n` is a positive integer, meaning that `n!` is also an integer. There are no zeroes after a decimal point in `n!`. Also, it can be assumed that your programming language can handle the value of `n` and `n!`.
---
**Test cases**
```
1
==> 0
5
==> 1
100
==> 24
666
==> 165
2016
==> 502
1234567891011121314151617181920
==> 308641972752780328537904295461
```
This is code golf. Standard rules apply. The shortest code in bytes wins.
[Answer]
## Python 2, 27 bytes
```
f=lambda n:n and n/5+f(n/5)
```
The ending zeroes are limited by factors of 5. The number of multiples of `5` that are at most `n` is `n/5` (with floor division), but this doesn't count the repeated factors in multiples of `25, 125, ...`. To get those, divide `n` by 5 and recurse.
[Answer]
# [Mornington Crescent](https://github.com/padarom/esoterpret), ~~1949 1909~~ 1873 bytes
```
Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Parsons Green
Take District Line to Cannon Street
Take Circle Line to Victoria
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Turnham Green
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Turnham Green
Take District Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Blackfriars
Take Circle Line to Hammersmith
Take Circle Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Blackfriars
Take District Line to Upminster
Take District Line to Temple
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Bank
Take Circle Line to Blackfriars
Take Circle Line to Hammersmith
Take District Line to Upney
Take District Line to Cannon Street
Take District Line to Upney
Take District Line to Cannon Street
Take District Line to Upney
Take District Line to Blackfriars
Take Circle Line to Bank
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Angel
Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent
```
[Try it online!](https://tio.run/##1VVNa8MwDL33V/gPDKr0@7hl0B62Mmi6uwlaY2LLwdEG@/Wdt9HAsjhJ0zHo0TzpWe/Jsox1pOjAlm5Sh2WKxMdjInMUW@s4Q0fiQREKtuJOUj76gmLlUo0NwL0q2amUK@hJutJSKdYOkQIxsSSyJHbsY7jxgmcfbp2S3@DpVME7fEOf73nRlYGYnxSt/EF1NWAjjfEXGsVZQFny6iiTplV9N8u@MIo@tQ1m6FNHf5l1f7RM8xfv3sn7M/O3ltm/QLFRWou1ZLwg6oJedbm8Lwjfryw3PLH1np1NnaApNA5qePe89697QJvDdjYU9q/5Xepa/tlrfL099smvHXRLB9Sjv9tPwycoXONjtVJFXK1UiCbT2XyxXMEYACKYwBRmMIcFLGEVjT8A "Mornington Crescent – Try It Online")
-40 bytes thanks to NieDzejkob
-45 bytes thanks to Cloudy7
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
!Æfċ5
```
Uses the counterproductive approach of finding the factorial then factorising it again, checking for the exponent of 5 in the prime factorisation.
[Try it online!](http://jelly.tryitonline.net/#code=IcOGZsSLNQ&input=&args=MTAw)
```
! Factorial
Æf List of prime factors, e.g. 120 -> [2, 2, 2, 3, 5]
ċ5 Count number of 5s
```
[Answer]
## Pyth, 6 bytes
```
/P.!Q5
```
[Try it here.](https://pyth.herokuapp.com/?code=%2FP.%21Q5&input=666&test_suite=1&test_suite_input=1%0A5%0A100%0A666%0A2016&debug=1)
```
/ 5 Count 5's in
P the prime factorization of
.!Q the factorial of the input.
```
[Alternative 7-byte](https://pyth.herokuapp.com/?code=st.u%2FN5&input=666&test_suite=1&test_suite_input=1%0A5%0A100%0A666%0A2016&debug=1):
```
st.u/N5
```
The cumulative reduce `.u/N5` repeatedly floor-divides by `5` until it gets a repeat, which in this case happens after it hits 0.
```
34 -> [34, 6, 1, 0]
```
The first element is then removed (`t`) and the rest is summed (`s`).
[Answer]
## Actually, 10 bytes
```
!$R;≈$l@l-
```
[Try it online!](http://actually.tryitonline.net/#code=ISRSO-KJiCRsQGwt&input=MjAxNg)
Note that the last test case fails when running Seriously on CPython because `math.factorial` uses a C extension (which is limited to 64-bit integers). Running Seriously on PyPy works fine, though.
Explanation:
```
!$R;≈$l@l-
! factorial of input
$R stringify, reverse
;≈$ make a copy, cast to int, then back to string (removes leading zeroes)
l@l- difference in lengths (the number of leading zeroes removed by the int conversion)
```
[Answer]
## Haskell, 26 bytes
```
f 0=0
f n=(+)=<<f$div n 5
```
Floor-divides the input by `5`, then adds the result to the function called on it. The expression `(+)=<<f` takes an input `x` and outputs `x+(f x)`.
Shortened from:
```
f 0=0
f n=div n 5+f(div n 5)
f 0=0
f n|k<-div n 5=k+f k
```
A non-recursive expression gave 28 bytes:
```
f n=sum[n`div`5^i|i<-[1..n]]
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
:"@Yf5=vs
```
[**Try it online!**](http://matl.tryitonline.net/#code=OiJAWWY1PXZz&input=MTAw)
This works for very large numbers, as it avoids computing the factorial.
Like other answers, this exploits the fact that the number of times `2` appears as divisor of the factorial is greater or equal than the number of times `5` appears.
```
: % Implicit input. Inclusive range from 1 to that
" % For each
@ % Push that value
Yf % Array of prime factors
5= % True for 5, false otherwise
v % Concatenate vertically all stack contents
s % Sum
```
[Answer]
## 05AB1E, 5 bytes
Would be 4 bytes if we could guarantee n>4
**Code:**
```
Î!Ó7è
```
**Explanation:**
```
Î # push 0 then input
! # factorial of n: 10 -> 2628800
Ó # get primefactor exponents -> [8, 4, 2, 1]
7è # get list[7] (list is indexed as string) -> 2
# implicit output of number of 5s or 0 if n < 5
```
**Alternate, much faster, 6 byte solution:** Inspired by [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/79780/47066)
```
LÒ€`5QO
```
**Explanation:**
```
L # push range(1,n) inclusive, n=10 -> [1,2,3,4,5,6,7,8,9,10]
Ò # push prime factors of each number in list -> [[], [2], [3], [2, 2], [5], [2, 3], [7], [2, 2, 2], [3, 3], [2, 5]]
€` # flatten list of lists to list [2, 3, 2, 2, 5, 2, 3, 7, 2, 2, 2, 3, 3, 2, 5]
5Q # and compare each number to 5 -> [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
O # sum -> 2
```
**Edit:** removed solutions using **¢** (count) as all primes containing 5 would be counted as 5 e.g. 53.
**Edit 2:** added a more efficient solution for higher input as comparison.
[Answer]
## Matlab ***~~(59) (54)~~***(39)
Hey dawg !!!! we heard you like maths ....
```
@(n)sum(fix(n./5.^(1:fix(log(n)/1.6))))
```
* This is based on my created [answer in code review](https://codereview.stackexchange.com/questions/90911/calculating-the-factorial-of-a-number-efficiently/90941#90941).
* further than what is mentioned in my answer in code review, the formula for number of zeros in factorial(n) is Sum(n/(5^k)) where k varies between 1 and log\_5(n)
* The only trivial reason why it cant get golfier is that `log5` isnt available in matlab as a builtin , thus I replaced log(5) by 1.6, doesnt matter because it will be anyways floored.
[Give it a try](http://ideone.com/XhlzoH)
[Answer]
# Mathematica, 20 bytes
```
IntegerExponent[#!]&
```
`IntegerExponent` counts the zeros. For fun, here's a version that doesn't calculate the factorial:
```
Tr[#~IntegerExponent~5&~Array~#]&
```
[Answer]
# Julia, ~~34~~ ~~31~~ 30 bytes
```
n->find(digits(prod(1:n)))[]-1
```
This is an anonymous function that accepts any signed integer type and returns an integer. To call it, assign it to a variable. The larger test cases require passing `n` as a larger type, such as a `BigInt`.
We compute the factorial of `n` (manually using `prod` is shorter than the built-in `factorial`), get an array of its `digits` in reverse order, `find` the indices of the nonzero elements, get the first such index, and subtract 1.
[Try it online!](http://julia.tryitonline.net/#code=Zj1uLT5maW5kKGRpZ2l0cyhwcm9kKDE6bikpKVtdLTEKCmZvciB0ZXN0IGluIFsoMSwwKSwgKDUsMSksICgxMDAsMjQpLCAoNjY2LDE2NSksICgyMDE2LDUwMildCiAgICBwcmludGxuKGYoYmlnKHRlc3RbMV0pKSA9PSB0ZXN0WzJdKQplbmQ&input=) (includes all but the last test case because the last takes too long)
Saved a byte thanks to Dennis!
[Answer]
# C, 28 bytes
```
f(n){return(n/=5)?n+f(n):n;}
```
## Explanation
The number of trailing zeros is equal to the number of fives that make up the factorial. Of all the `1..n`, one-fifth of them contribute a five, so we start with `n/5`. Of these `n/5`, a fifth are multiples of 25, so contribute an extra five, and so on. We end up with `f(n) = n/5 + n/25 + n/125 + ...`, which is `f(n) = n/5 + f(n/5)`. We do need to terminate the recursion when `n` reaches zero; also we take advantage of the sequence point at `?:` to divide `n` before the addition.
As a bonus, this code is much faster than that which visits each `1..n` (and much, much faster than computing the factorial).
## Test program
```
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char **argv) {
while(*++argv) {
int i = atoi(*argv);
printf("%d: %d\n",i,f(i));
}
}
```
## Test output
>
> 1: 0
>
> 4: 0
>
> 5: 1
>
> 24: 4
>
> 25: 6
>
> 124: 28
>
> 125: 31
>
> 666: 165
>
> 2016: 502
>
> 2147483644: 536870901
>
> 2147483647: 536870902
>
>
>
[Answer]
# JavaScript ES6, 20 bytes
```
f=x=>x&&x/5+f(x/5)|0
```
Same tactic as in xnor's answer, but shorter.
[Answer]
# C, 36
```
r;f(n){for(r=0;n/=5;)r+=n;return r;}
```
Same method as [@xnor's answer](https://codegolf.stackexchange.com/a/79763/11259) of counting 5s, but just using a simple for loop instead of recursion.
[Ideone](https://ideone.com/SeisX3).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
!ọ5
```
[Try it online!](https://tio.run/##y0rNyan8/1/x4e5e0//Wh9s13f//N9RRMNVRMDQw0FEwMzPTUTAyMDQDAA "Jelly – Try It Online")
## How it works
```
!ọ5 - Main link. Takes n on the left
! - Yield n!
ọ5 - How many times is it divisible by 5?
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 33 bytes
Takes input in unary.
Returns output in unary.
```
+`^(?=1)(1{5})*1*
$#1$*1;$#1$*
;
```
(Note the trailing linefeed.)
[Try it online!](http://retina.tryitonline.net/#code=K2BeKD89MSkoMXs1fSkqMSoKJCMxJCoxOyQjMSQqCjsK&input=MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMQ)
## How it works:
### The first stage:
```
+`^(?=1)(1{5})*1*
$#1$*1;$#1$*
```
Slightly ungolfed:
```
+`^(?=1)(11111)*1*\b
$#1$*1;$#1$*1
```
What it does:
* Firstly, find the greatest number of `11111` that can be matched.
* Replace by that number
* Effectively floor-divides by `5`.
* The lookahead `(?=1)` assures that the number is positive.
* The `+`` means repeat until idempotent.
* So, the first stage is "repeated floor-division by 5"
If the input is 100 (in unary), then the text is now:
```
;;1111;11111111111111111111
```
### Second stage:
```
;
```
Just removes all semi-colons.
[Answer]
# Ruby, 22 bytes
One of the few times where the Ruby `0` being truthy is a problem for byte count.
```
f=->n{n>0?f[n/=5]+n:0}
```
[Answer]
# [Perl 6](http://perl6.org), 23 bytes
```
{[+] -$_,$_,*div 5…0}
{sum -$_,$_,*div 5...0}
```
I could get it shorter if `^...` was added to [Perl 6](http://perl6.org) `{sum $_,*div 5^...0}`.
It should be more memory efficient for larger numbers if you added a `lazy` modifier between `sum` and the sequence generator.
### Explanation:
```
{ # implicitly uses $_ as its parameter
sum
# produce a sequence
-$_, # negate the next value
$_, # start of the sequence
* div 5 # Whatever lambda that floor divides its input by 5
# the input being the previous value in the sequence,
# and the result gets appended to the sequence
... # continue to do that until:
0 # it reaches 0
}
```
### Test:
```
#! /usr/bin/env perl6
use v6.c;
use Test;
my @test = (
1, 0,
5, 1,
100, 24,
666, 165,
2016, 502,
1234567891011121314151617181920,
308641972752780328537904295461,
# [*] 5 xx 100
7888609052210118054117285652827862296732064351090230047702789306640625,
1972152263052529513529321413206965574183016087772557511925697326660156,
);
plan @test / 2;
# make it a postfix operator, because why not
my &postfix:<!0> = {[+] -$_,$_,*div 5...0}
for @test -> $input, $expected {
is $input!0, $expected, "$input => $expected"
}
diag "runs in {now - INIT now} seconds"
```
```
1..7
ok 1 - 1 => 0
ok 2 - 5 => 1
ok 3 - 100 => 24
ok 4 - 666 => 165
ok 5 - 2016 => 502
ok 6 - 1234567891011121314151617181920 => 308641972752780328537904295461
ok 7 - 7888609052210118054117285652827862296732064351090230047702789306640625 => 1972152263052529513529321413206965574183016087772557511925697326660156
# runs in 0.0252692 seconds
```
( That last line is slightly misleading, as MoarVM has to start, load the Perl 6 compiler and runtime, compile the code, and run it. So it actually takes about a second and a half in total.
That is still significantly faster than it was to check the result of the last test with WolframAlpha.com )
[Answer]
# Mathcad, [tbd] bytes
[![enter image description here](https://i.stack.imgur.com/1D6fQ.jpg)](https://i.stack.imgur.com/1D6fQ.jpg)
Mathcad is sort of mathematical "whiteboard" that allows 2D entry of expressions, text and plots. It uses mathematical symbols for many operations, such as summation, differentiation and integration. Programming operators are special symbols, usually entered as single keyboard combinations of control and/or shift on a standard key.
What you see above is exactly how the Mathcad worksheet looks as it is typed in and as Mathcad evaluates it. For example, changing n from 2016 to any other value will cause Mathcad to update the result from 502 to whatever the new value is.
<http://www.ptc.com/engineering-math-software/mathcad/free-download>
---
Mathcad's byte equivalence scoring method is yet to be determined. Taking a symbol equivalence, the solution takes about 24 "bytes" (the while operator can only be entered using the "ctl-]" key combination (or from a toolbar)). Agawa001's Matlab method takes about 37 bytes when translated into Mathcad (the summation operator is entered by ctl-shft-$).
[Answer]
# Julia, ~~21~~ 19 bytes
```
!n=n<5?0:!(n÷=5)+n
```
Uses the recursive formula from [xnor's answer](https://codegolf.stackexchange.com/a/79763).
[Try it online!](http://julia.tryitonline.net/#code=IW49bjw1PzA6IShuw7c9NSkrbgoKZm9yIG4gaW4gKDEsIDUsIDEwMCwgNjY2LCAyMDE2LCAxMjM0NTY3ODkxMDExMTIxMzE0MTUxNjE3MTgxOTIwKQogICAgcHJpbnRsbighbikKZW5k&input=)
[Answer]
# dc, 12 bytes
```
[5/dd0<f+]sf
```
This defines a function `f` which consumes its input from top of stack, and leaves its output at top of stack. See [my C answer](/a/79997) for the mathematical basis. We repeatedly divide by 5, accumulating the values on the stack, then add all the results:
```
5/d # divide by 5, and leave a copy behind
d0< # still greater than zero?
f+ # if so, apply f to the new value and add
```
## Test program
```
# read input values
?
# print prefix
[ # for each value
# print prefix
[> ]ndn[ ==> ]n
# call f(n)
lfx
# print suffix
n[
]n
# repeat for each value on stack
z0<t
]
# define and run test function 't'
dstx
```
## Test output
```
./79762.dc <<<'1234567891011121314151617181920 2016 666 125 124 25 24 5 4 1'
```
```
1 ==> 0
4 ==> 0
5 ==> 1
24 ==> 4
25 ==> 6
124 ==> 28
125 ==> 31
666 ==> 165
2016 ==> 502
1234567891011121314151617181920 ==> 308641972752780328537904295461
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 5 bytes
```
ɾǐƛ5O # main program
```
```
ɾ # range over input
ǐ # take the prime factors of each number
ƛ5O # for each value, count the 5s
-s # sum top of stack
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=%C9%BE%C7%90%C6%9B5O&inputs=2016&header=&footer=)
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes
```
¡5Ǒ
```
This one uses the same approach as caird coinheringaahing's answer
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C2%A15%C7%91&inputs=2016&header=&footer=)
# [Vyxal](https://github.com/Vyxal/Vyxal) `l`, 3 bytes (for inputs > 4)
```
¡Ġt
```
Approach by Lyxal, takes the factorial of the input, groups by consecutive, then gets the length of the tail using the -l flag.
[Try it Online!](https://lyxal.pythonanywhere.com?flags=l&code=%C2%A1%C4%A0t&inputs=100&header=&footer=)
[Answer]
# asm2bf, 32 bytes
```
@f
divr1,5
addr2,r1
jnzr1,%f
ret
```
Resulting brainfuck code (~500 bytes):
```
+>+[<[>-]>[>]>+<<<[>>>[-]<-<<-]+>>+[-<[>+>-<<-]>>[<<<->>[<+
>>+<-]>[-]]<[-]]<<[>>+<<-]>>[-<<+>>>>>>>>>+++++[>>>>+<<<<-]
<<<<[>>>>>>>+>-[>>]<[[>+<-]<+>>>]<<<<<<<<<-]>>>>>>[<<<<<<+>
>>>>>-]>[<<<+>>>-]>[<<<<+>>>>-]<<<<[-]<<<<[>+<<+>-]<[>+<-]>
>>>>+<<<<[<<<<<[-]>>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>
>>>>+<<<<<<<-]>>>[<<<+>>>-]]<<<[>>>+<<<-]>>>>>>>[-]<<<<<<<]
<<[>>+<<-]>>[-<<+[-]>[-]>>>>>>>>>>>>>>>>>>>>>[>>]<<->[<<<[<
<]<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>[>>]>-]<<<[<<]<<
<<<<<<<<<[-]<<<<<<<]<<[>>+<<-]>>[-<<+>>]<]
```
### Extras
If you want to test the algorithm, you can use the following driver code. The code expects `r1` to be the input number and leaves the output in `r2`, assuming `r2` is already cleared:
```
movr1,666
@f
divr1,5
addr2,r1
jnzr1,%f
outr1
```
The resulting value might be outputted as an ASCII character, so you might have to use `bfi fac.b | xxd` to see the numerical value.
### Optimizing for brainfuck source code size
We can optimize the code a fair bit. Since brainfuck has no notion of procedures, we can assume that `@f` is a while loop label (instead of being both a function and a normal label) and that we don't have to return.
The `jnz` instruction and the accompanying label can be replaced with a sequence of `nav r1 / raw .[` or `.]`. To top it off, we use the `-t` flag for bfmake. The result:
```
>>>[>>>>+++++[>>>>+<<<<-]<<<<[>>>>>>>+>-[>>]<[[>+<-]<+>>>]<<<<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]>[<<<+>>>-]>[<<<<+>>>>-]<<<<[-]<<<<[>+<<+>-]<[>+<-]>]
```
... at 144 bytes.
[Answer]
# Excel, 25 bytes
```
=SUM(INT(A9/5^ROW(1:99)))
```
Calculates the number of 5s in the prime factorization. In theory, it would work for all of the examples above, except Excel can't handle numbers as long as the last one with the correct precision.
[Answer]
# Jolf, 13 bytes
```
Ώmf?H+γ/H5ΏγH
```
Defines a recursive function which is called on the input. [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=zo9tZj9IK86zL0g1zo_Os0g&input=MjAxNg)
```
Ώmf?H+γ/H5ΏγH Ώ(H) = floor(H ? (γ = H/5) + Ώ(γ) : H)
Ώ Ώ(H) =
/H5 H/5
γ (γ = )
+ Ώγ + Ώ(γ)
?H H H ? : H
mf floor( )
// called implicitly with input
```
[Answer]
# J, ~~28~~ ~~17~~ 16 bytes
```
<.@+/@(%5^>:@i.)
```
Pretty much the same as the non-recursive technique from xnor's answer.
---
Here's an older version I have kept here because I personally like it more, clocking in at 28 bytes:
```
+/@>@{:@(0<;._1@,'0'&=@":@!)
```
Whilst not needed, I have included `x:` in the test cases for extended precision.
```
tf0 =: +/@>@{:@(0<;._1@,'0'&=@":@!@x:)
tf0 5
1
tf0 100
24
tf0g =: tf0"0
tf0g 1 5 100 666 2016
0 1 24 165 502
```
The last number doesn't work with this function.
## Explanation
This works by calculating `n!`, converting it to a string, and checking each member for equality with `'0'`. For `n = 15`, this process would be:
```
15
15! => 1307674368000
": 1307674368000 => '1307674368000'
'0' = '1307674368000' => 0 0 1 0 0 0 0 0 0 0 1 1 1
```
Now, we use `;._1` to split the list on its first element (zero), boxing each split result, yielding a box filled with aces (`a:`) or runs of `1`s, like so:
```
┌┬─┬┬┬┬┬┬┬─────┐
││1│││││││1 1 1│
└┴─┴┴┴┴┴┴┴─────┘
```
We simple obtain the last member (`{:`), unbox it (`>`), and perform a summation over it `+/`, yielding the number of zeroes.
Here is the more readable version:
```
split =: <;._1@,
tostr =: ":
is =: =
last =: {:
unbox =: >
sum =: +/
precision =: x:
n =: 15
NB. the function itself
tf0 =: sum unbox last 0 split '0' is tostr ! precision n
tf0 =: sum @ unbox @ last @ (0 split '0'&is @ tostr @ ! @ precision)
tf0 =: +/ @ > @ {: @ (0 <;._1@, '0'&= @ ": @ ! )
```
[Answer]
## Python 3, 52 bytes
```
g=lambda x,y=1,z=0:z-x if y>x else g(x,y*5,z+x//y)
```
[Answer]
## Pyke, 5 bytes
```
SBP5/
```
[Try it here!](http://pyke.catbus.co.uk/?code=SBP5%2F&input=100)
```
S - range(1,input()+1)
B - product(^)
P - prime_factors(^)
5/ - count(^, 5)
```
[Answer]
# Haskell, 39 bytes
Can't compete with `@xnor`, but it was fun and the result is a different approach:
```
f n=sum$[1..n]>>= \i->1<$[5^i,2*5^i..n]
```
[Answer]
# [RETURN](https://github.com/molarmanful/RETURN), 17 bytes
```
[$[5÷\%$F+][]?]=F
```
`[Try it here.](http://molarmanful.github.io/RETURN/)`
Recursive operator lambda. Usage:
```
[$[5÷\%$F+][]?]=F666F
```
# Explanation
```
[ ]=F Lambda -> Operator F
$ Check if top of stack is truthy
[ ][]? Conditional
5÷\%$F+ If so, do x/5+F(x/5)
```
] |
[Question]
[
### Goal
Write a function or program sort an array of integers in descending order by the number of 1's present in their binary representation. No secondary sort condition is necessary.
### Example sorted list
(using 16-bit integers)
```
Dec Bin 1's
16375 0011111111110111 13
15342 0011101111101110 11
32425 0111111010101001 10
11746 0010110111100010 8
28436 0000110111110100 8
19944 0100110111101000 8
28943 0000011100011111 8
3944 0000011111101000 7
15752 0011110110001000 7
825 0000000011111001 6
21826 0101010101000010 6
```
### Input
An array of 32-bit integers.
### Output
An array of the same integers sorted as described.
### Scoring
This is code golf for the least number of bytes to be selected in one week's time.
[Answer]
## J (11)
```
(\:+/"1@#:)
```
This is a function that takes a list:
```
(\:+/"1@#:) 15342 28943 16375 3944 11746 825 32425 28436 21826 15752 19944
16375 15342 32425 28943 11746 28436 19944 3944 15752 825 21826
```
If you want to give it a name, it costs one extra character:
```
f=:\:+/"1@#:
f 15342 28943 16375 3944 11746 825 32425 28436 21826 15752 19944
16375 15342 32425 28943 11746 28436 19944 3944 15752 825 21826
```
Explanation:
* `\:`: downwards sort on
* `+/`: sum of
* `"1`: each row of
* `#:`: binary representation
[Answer]
# JavaScript, 39
**Update:** Now shorter than Ruby.
```
x.sort(q=(x,y)=>!x|-!y||q(x&x-1,y&y-1))
```
**40**
```
x.sort(q=(x,y)=>x&&y?q(x&x-1,y&y-1):x-y)
```
Explanation:
q is a recursive function. If x or y are 0, it returns `x-y` (a negative number if x is zero or a positive number if y is zero). Otherwise it removes the lowest bit (`x&x-1`) from x and y and repeats.
**Previous version (42)**
```
x.sort(q=(x,y)=>x^y&&!x-!y+q(x&x-1,y&y-1))
```
[Answer]
# Ruby 41
```
f=->a{a.sort_by{|n|-n.to_s(2).count(?1)}}
```
Test:
```
a = [28943, 825, 11746, 16375, 32425, 19944, 21826, 15752, 15342, 3944, 28436];
f[a]
=> [16375, 15342, 32425, 11746, 28436, 28943, 19944, 15752, 3944, 21826, 825]
```
[Answer]
## Python 3 (44):
```
def f(l):l.sort(lambda n:-bin(n).count('1'))
```
[Answer]
## Common Lisp, 35
[`logcount`](http://www.lispworks.com/documentation/HyperSpec/Body/f_logcou.htm) returns the number of ‘on’-bits in a number. For a list `l`, we have:
```
(sort l '> :key 'logcount)
```
```
CL-USER> (sort (list 16375 15342 32425 11746 28436 19944 28943 3944 15752 825 21826) '> :key 'logcount)
;=> (16375 15342 32425 11746 28436 19944 28943 3944 15752 825 21826)
```
As a standalone function, and what I'll base the byte count on:
```
(lambda(l)(sort l'> :key'logcount))
```
[Answer]
# Python 3, ~~90~~ ~~77~~ ~~72~~ 67 characters.
Our solution takes an input from the command-line, and prints the number in descending order (67 chars), or ascending (66).
**Descending order**
```
print(sorted(input().split(),key=lambda x:-bin(int(x)).count("1"))) # 67
```
Thanks to **@daniero**, for the suggestion of using a minus in the 1's count to reverse it, instead of using a slice to reverse the array at the end! This effectively saved 5 characters.
Just for the sake of posting it, the ascending order version (which was the first we made) would take one character less.
**Ascending order**:
```
print(sorted(input().split(),key=lambda x:bin(int(x)).count("1"))) # 66
```
Thanks to **@Bakuriu** for the *key=lambda x…* suggestion. ;D
[Answer]
## JavaScript [76 bytes]
```
a.sort(function(x,y){r='..toString(2).split(1).length';return eval(y+r+-x+r)})
```
where `a` is an input array of numbers.
**Test:**
```
[28943,825,11746,16375,32425,19944,21826,15752,15342,3944,28436].sort(function(x, y) {
r = '..toString(2).split(1).length';
return eval(y + r + -x + r);
});
[16375, 15342, 32425, 19944, 11746, 28943, 28436, 15752, 3944, 21826, 825]
```
[Answer]
## Mathematica 30
```
SortBy[#,-DigitCount[#,2,1]&]&
```
Usage:
```
SortBy[#,-DigitCount[#,2,1]&]&@
{19944,11746,15342,21826,825,28943,32425,16375,28436,3944,15752}
```
>
> {16375, 15342, 32425, 11746, 19944, 28436, 28943, 3944, 15752, 825,
> 21826}
>
>
>
[Answer]
# k [15 Chars]
```
{x@|<+/'0b\:'x}
```
### Example 1
```
{x@|<+/'0b\:'x}19944, 11746, 15342, 21826, 825, 28943, 32425, 16375, 28436, 3944, 15752
16375 15342 32425 28436 28943 11746 19944 15752 3944 825 21826
```
### Example 2 (all numbers are 2^n -1)
```
{x@|<{+/0b\:x}'x}3 7 15 31 63 127
127 63 31 15 7 3
```
[Answer]
# Mathematica 39
`IntegerDigits[#,2]` converts a base 10 number to list of 1's and 0's.
`Tr` sums the digits.
```
f@n_:=SortBy[n,-Tr@IntegerDigits[#,2]&]
```
**Test Case**
```
f[{19944, 11746, 15342, 21826, 825, 28943, 32425, 16375, 28436, 3944, 15752}]
```
>
> {16375, 15342, 32425, 11746, 19944, 28436, 28943, 3944, 15752, 825, 21826}
>
>
>
[Answer]
# Java 8 - ~~87/113~~ ~~81/111~~ ~~60/80~~ 60/74/48 characters
This is not a complete java program, it is just a function (a method, to be exact).
It assumes that `java.util.List` and `java.lang.Long.bitCount` are imported, and has 60 characters:
```
void s(List<Long>a){a.sort((x,y)->bitCount(x)-bitCount(y));}
```
If no pre-imported stuff are allowed, here it is with 74 characters:
```
void s(java.util.List<Long>a){a.sort((x,y)->x.bitCount(x)-x.bitCount(y));}
```
Add more 7 characters if it would be required that it should be `static`.
[4 years later] Or if you prefer, it could be a lambda (thanks @KevinCruijssen for the suggestion), with 48 bytes:
```
a->{a.sort((x,y)->x.bitCount(x)-x.bitCount(y));}
```
[Answer]
# Python 2.x - 65 characters (bytes)
```
print sorted(input(),key=lambda x:-sum(int(d)for d in bin(x)[2:]))
```
That's actually 66 characters, 65 if we make it a function (then you need something to call it which is lamer to present).
```
f=lambda a:sorted(a,key=lambda x:-sum(int(d)for d in bin(x)[2:]))
```
Demo in Bash/CMD:
```
echo [16, 10, 7, 255, 65536, 5] | python -c "print sorted(input(),key=lambda x:-sum(int(d)for d in bin(x)[2:]))"
```
[Answer]
# Matlab, 34
Input in 'a'
```
[~,i]=sort(-sum(dec2bin(a)'));a(i)
```
Works for nonnegative numbers.
[Answer]
## **C - 85 bytes (~~108~~ 106 bytes)**
Portable version on GCC/Clang/wherever `__builtin_popcount` is available (106 bytes):
```
#define p-__builtin_popcount(
c(int*a,int*b){return p*b)-p*a);}
void s(int*n,int l){qsort(n,l,sizeof l,c);}
```
Ultra-condensed, non-portable, barely functional MSVC-only version (85 bytes):
```
#define p __popcnt
c(int*a,int*b){return p(*b)-p(*a);}
s(int*n,int l){qsort(n,l,4,c);} /* or 8 as needed */
```
---
* First newline included in byte count because of the `#define`, the others are not necessary.
* Function to call is `s(array, length)` according to specifications.
* Can hardcode the `sizeof` in the portable version to save another 7 characters, like a few other C answers did. I'm not sure which one is worth the most in terms of length-usability ratio, you decide.
[Answer]
# PowerShell v3, ~~61~~ ~~58~~ 53
```
$args|sort{while($_){if($_-band1){1};$_=$_-shr1}}-des
```
The ScriptBlock for the `Sort-Object` cmdlet returns an array of 1's for each 1 in the binary representation of the number. `Sort-Object` sorts the list based on the length of the array returned for each number.
To execute:
```
script.ps1 15342 28943 16375 3944 11746 825 32425 28436 21826 15752 19944
```
[Answer]
# ECMAScript 6, 61
Assumes `z` is the input
```
z.sort((a,b)=>{c=d=e=0;while(++c<32)d+=a>>c&1,e+=b>>c&1},e-d)
```
Test data
```
[28943,825,11746,16375,32425,19944,21826,15752,15342,3944,28436].sort(
(a,b)=>{
c=d=e=0;
while(++c<32)
d+=a>>c&1,e+=b>>c&1
},e-d
)
[16375, 15342, 32425, 11746, 19944, 28436, 28943, 15752, 3944, 21826, 825]
```
Thanks, toothbrush for the shorter solution.
[Answer]
# [R](https://www.r-project.org/), ~~132~~ ~~96~~ ~~94~~ ~~88~~ ~~84~~ ~~75~~ ~~73~~ ~~53~~ 51 bytes
-20 thanks to J.Doe's implementation
-2 more thanks to Giuseppe
```
function(x)x[order(colSums(sapply(x,intToBits)<1))]
```
My original post:
```
pryr::f(rev(x[order(sapply(x,function(y)sum(as.double(intToBits(y)))))]))
```
[Try it online!](https://tio.run/##FclBCoAgEAXQ63whOoDLztAuWlgaCObIjIaefqq3faxaeLC1Fzg86BuxDwxxpaSBPl0tnzVSxjDSbjiZPbUjBcRcV1pilW9@uzGqLw "R – Try It Online")
I tried several different methods before I got down to this result.
**Matrix Method:** Created a two column matrix, one column with the input vector, one of the sum of the binary representation, then I sorted on the sum of binary.
```
function(x){m=matrix(c(x,colSums(sapply(x,function(y){as.integer(intToBits(y))}))),nc=2,nr=length(x));m[order(m[,2],decreasing=T),]}
```
**Non-Matrix:** Realized I could toss out the matrix function and instead create a vector of binary values, sum them, order them, then use the ordered values to reorder the input vector.
```
function(x){m=colSums(sapply(x,function(y){as.integer(intToBits(y))}));x[order(m,decreasing=T)]}
```
**Minor Changes**
```
function(x){m=colSums(sapply(x,function(y)as.double(intToBits(y))));x[order(m,decreasing=T)]}
```
**More Minor Changes** Converting entire thing to one line of code instead of two separated by a semicolon.
```
function(x)x[order(colSums(sapply(x,function(y)as.double(intToBits(y)))),decreasing=T)]
```
**Sum Method** Instead of adding the columns with `colSums` of the binary matrix created by `sapply`, I added the elements in the column before `sapply` "finished."
```
function(x)x[order(sapply(x,function(y)sum(as.double(intToBits(y)))),decreasing=T)]
```
**Decreasing to Rev** I really wanted to shorten decreasing, but R squawks at me if I try to shorten `decreasing` in the `order` function, which was necessary to get the order desired as `order` defaults to increasing, then I remembered the `rev` function to reverse a vector. **EUREKA!!!** The last change in the final solution was `function` to `pryr::f` to save 2 more bytes
```
function(x)rev(x[order(sapply(x,function(y)sum(as.double(intToBits(y)))))])
```
[Answer]
# Haskell, 123C
```
import Data.List
import Data.Ord
b 0=[]
b n=mod n 2:b(div n 2)
c n=(n,(sum.b)n)
q x=map fst$sortBy(comparing snd)(map c x)
```
This is the first way I thought of solving this, but I bet there's a better way to do it. Also, if anyone knows of a way of golfing Haskell imports, I would be very interested to hear it.
## Example
```
*Main> q [4,2,15,5,3]
[4,2,5,3,15]
*Main> q [7,0,2]
[0,2,7]
```
## Ungolfed version (with explanations)
```
import Data.List
import Data.Ord
-- Converts an integer into a list of its bits
binary 0 = []
binary n = mod n 2 : binary (div n 2)
-- Creates a tuple where the first element is the number and the second element
-- is the sum of its bits.
createTuple n = (n, (sum.binary) n)
-- 1) Turns the list x into tuples
-- 2) Sorts the list of tuples by its second element (bit sum)
-- 3) Pulls the original number out of each tuple
question x = map fst $ sortBy (comparing snd) (map createTuple x)
```
[Answer]
# CoffeeScript (94)
Readable code (212):
```
sort_by_ones_count = (numbers) ->
numbers.sort (a, b) ->
a1 = a.toString(2).match(/1/g).length
b1 = b.toString(2).match(/1/g).length
if a1 == b1
0
else if a1 > b1
1
else
-1
console.log sort_by_ones_count [825, 3944, 11746, 15342, 15752, 16375, 19944, 21826, 28436, 28943, 32425]
```
Optimized (213):
```
count_ones = (number) -> number.toString(2).match(/1/g).length
sort_by_ones_count = (numbers) -> numbers.sort (a, b) ->
a1 = count_ones(a)
b1 = count_ones(b)
if a1 == b1 then 0 else if a1 > b1 then 1 else -1
```
Obfuscating (147):
```
c = (n) -> n.toString(2).match(/1/g).length
s = (n) -> n.sort (a, b) ->
a1 = c(a)
b1 = c(b)
if a1 == b1 then 0 else if a1 > b1 then 1 else -1
```
Ternary operators are excessively long (129):
```
c = (n) -> n.toString(2).match(/1/g).length
s = (n) -> n.sort (a, b) ->
a1 = c(a)
b1 = c(b)
(0+(a1!=b1))*(-1)**(0+(a1>=b1))
```
Too long yet, stop casting (121):
```
c = (n) -> n.toString(2).match(/1/g).length
s = (n) -> n.sort (a, b) ->
a1 = c(a)
b1 = c(b)
(-1)**(a1>=b1)*(a1!=b1)
```
Final (94):
```
c=(n)->n.toString(2).match(/1/g).length
s=(n)->n.sort((a, b)->(-1)**(c(a)>=c(b))*(c(a)!=c(b)))
```
[Answer]
# Smalltalk (Smalltalk/X), 36 (or maybe 24)
input in a; destructively sorts in a:
```
a sort:[:a :b|a bitCount>b bitCount]
```
functional version: returns a new sorted array:
```
a sorted:[:a :b|a bitCount>b bitCount]
```
there is even a shorter variant (passing the *name* or the function as argument) in 24 chars.
But (sigh) it will sort highest last. As I understood, this was not asked for, so I don't take that as golf score:
```
a sortBySelector:#bitCount
```
[Answer]
# PHP 5.4+ 131
I don't even know why I bother with PHP, in this case:
```
<?unset($argv[0]);usort($argv,function($a,$b){return strcmp(strtr(decbin($b),[0=>'']),strtr(decbin($a),[0=>'']));});print_r($argv);
```
Usage:
```
> php -f sortbybinaryones.php 15342 28943 16375 3944 11746 825 32425 28436 21826 15752 19944
Array
(
[0] => 16375
[1] => 15342
[2] => 32425
[3] => 28436
[4] => 19944
[5] => 11746
[6] => 28943
[7] => 3944
[8] => 15752
[9] => 825
[10] => 21826
)
```
[Answer]
# Scala, 58
```
def c(l:List[Int])=l.sortBy(-_.toBinaryString.count(_>48))
```
[Answer]
**DFSORT** (IBM Mainframe sorting product) **288** (each source line is 72 characters, must have space in position one)
```
INREC IFTHEN=(WHEN=INIT,BUILD=(1,2,1,2,TRAN=BIT)),
IFTHEN=(WHEN=INIT,FINDREP=(STARTPOS=3,INOUT=(C'0',C'')))
SORT FIELDS=(3,16,CH,D)
OUTREC BUILD=(1,2)
```
Just for fun, and no mathematics.
Takes a file (could be executed from a program which used an "array") with the integers. Before sorting, it translates the integers to bits (in a 16-character field). Then changes the 0s in the bits to nothing. SORT Descending on the result of the changed bits. Creates the sorted file with just the integers.
[Answer]
# C
```
void main()
{
int a[]={7,6,15,16};
int b,i,n=0;
for(i=0;i<4;i++)
{ for(b=0,n=0;b<=sizeof(int);b++)
(a[i]&(1<<b))?n++:n;
a[i]=n;
}
for (i = 1; i < 4; i++)
{ int tmp = a[i];
for (n = i; n >= 1 && tmp < a[n-1]; n--)
a[n] = a[n-1];
a[n] = tmp;
}
}
```
[Answer]
# C#, 88 89
```
int[] b(int[] a){return a.OrderBy(i=>-Convert.ToString(i,2).Count(c=>c=='1')).ToArray();}
```
Edit: descending order adds a character.
[Answer]
## **Javascript** 84
Inspired by other javascript answers, but without eval and regex.
```
var r=(x)=>(+x).toString(2).split('').reduce((p,c)=>p+ +c)
[28943,825,11746,16375,32425,19944,21826,15752,15342,3944,28436].sort((x,y)=>r(x)-r(y));
```
[Answer]
Javascript (82)
```
a.sort(function(b,c){q=0;while(b|c){b%2?c%2?0:q++:c%2?q--:0;b>>=1;c>>=1}return q})
```
[Answer]
## Postscript, 126
Because list of values by which we sort is known beforehand and very limited (32), this task can be easily done even if there's no built-in for sorting, by picking matching values for 1..32. (Is it O(32n)? Probably).
Procedure expects array on stack and returns 'sorted' array.
```
/sort_by_bit_count {
[ exch
32 -1 1 {
1 index
{
dup 2 32 string cvrs
0 exch
{48 sub add} forall
2 index eq
{3 1 roll} {pop} ifelse
} forall
pop
} for
pop ]
} def
```
Or, ritually stripped of white space and readability:
```
/s{[exch 32 -1 1{1 index{dup 2 32 string cvrs 0 exch{48 sub add}forall 2 index eq{3 1 roll}{pop}ifelse}forall pop}for pop]}def
```
Then, if saved to `bits.ps` it can be used like this:
```
gs -q -dBATCH bits.ps -c '[(%stdin)(r)file 1000 string readline pop cvx exec] s =='
825 3944 11746 15342 15752 16375 19944 21826 28436 28943 32425
[16375 15342 32425 11746 19944 28436 28943 3944 15752 825 21826]
```
I think it effectively is the same as this Perl (there's yet no Perl here, too):
```
sub f{map{$i=$_;grep{$i==(()=(sprintf'%b',$_)=~/1/g)}@_}reverse 1..32}
```
Though *that*, unlike Postscript, can be easily golfed:
```
sub f{sort{j($b)-j($a)}@_}sub j{$_=sprintf'%b',@_;()=/1/g}
```
[Answer]
# C - ~~124~~ 111
Implemented as a method and using the standard library for the sorting. A pointer to the array and the size should be passed as parameters. This will only work on systems with 32-bit pointers. On 64-bit systems, some characters have to be spent specifying pointer definitions.
Indentation for readability
```
c(int*a,int*b){
int d,e,i;
for(d=e=i=0;i-32;){
d+=*a>>i&1;e+=*b>>i++&1;
}
return d>e?-1:d<e;
}
o(r,s){qsort(r,s,4,c);}
```
Sample call:
```
main() {
static int a[] ={1, 2, 3, 4, 5, 6, 7, 8, 9};
o(a, 9);
}
```
[Answer]
# Java 8: 144
```
static void main(String[]a){System.out.print(Stream.of(a).mapToInt(Integer::decode).sorted(Comparable.comparing(Integer::bitCount)).toArray());}
```
In expanded form:
```
static void main(String[] args){
System.out.print(
Stream.of(args).mapToInt(Integer::decode)
.sorted(Comparable.comparing(Integer::bitCount))
.toArray()
);
}
```
As you can see, this works by converting the `args` to a `Stream<String>`, then converting to a `Stream<Integer>` with the `Integer::decode` function reference (shorter than `parseInt` or `valueOf`), and then sorting by `Integer::bitCount`, then putting it in an array, and printing it out.
Streams make everything easier.
] |
[Question]
[
# Your very own "for" instruction
Assuming you have the following input : `a, b, c, d`
Input can be in one-line using any format "a/b/c/d" or "a,b,c,d" etc..
You can also have 4 inputs.
You must code the following behaviour (pseudo-code here) :
```
var i = <a>
while (i <b> <c>)
print i
i = i + <d>
print "\n"
```
Here are some tests cases :
```
input : 1,<,10,1
output :
1
2
3
4
5
6
7
8
9
```
One more :
```
input : 20,>,10,1
output :
20
21
22
23
24
25
26
27
...
infinite loop / program crashes
```
* `a` is an **integer**, the initial value of `i`.
* `b` is a **string** or a **char**, it can't be something else, the comparator used in the ending condition of the
`for` loop.
`b` can and **must** be one of the following strings :
```
- ">"
- "<"
```
* `c` is an **integer**, the number used in the ending condition of the `for`
loop.
* `d` is an **integer** that is added to i at every loop.
This is code-golf, the shortest answer wins !
[Answer]
## JavaScript (ES6), ~~44~~ ~~43~~ 56 bytes
*Saved 1 byte thanks to ETHproductions*
*Edit: fixed to comply with output requirements*
```
(a,b,c,d)=>{for(s='';eval(a+b+c);a+=d)s+=a+`
`;alert(s)}
```
### Test
```
let f =
(a,b,c,d)=>{for(s='';eval(a+b+c);a+=d)s+=a+`
`;alert(s)}
f(1,'<',7,2)
```
[Answer]
## Javascript (ES6), ~~47~~ ~~42~~ 48 Bytes
Wanted to make the for version but someone was faster, so here's the recursive version.
```
(b,c,d)=>F=a=>eval(a+b+c)&&console.log(a)|F(a+d)
```
You need to add `f=` before and call it like `f(b,c,d)(a)`.
*Many thanks to Arnauld for the awesome golf.*
*`alert` changed to `console.log` because of output specification*
[Answer]
# Pure bash, 35
I assume its OK just to plug the parameters into the standard for loop:
```
for((i=$1;i$2$3;i+=$4));{ echo $i;}
```
[Try it online](https://tio.run/#VIul3).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
Ṅ+⁶µ⁴;⁵¹vµ¿t
```
[Try it online!](https://tio.run/nexus/jelly#ASYA2f//4bmEK@KBtsK14oG0O@KBtcK5dsK1wr90////NP8iPCL/MTH/Mg "Jelly – TIO Nexus")
Jelly has a lot of ways to tersely do iteration, create ranges, etc.. However, mirroring C++'s behaviour exactly is fairly hard, due to special cases like the increment being 0, the loop ending before it starts (due to the inequality being backwards), and the increment going in the wrong direction (thus meaning the exit condition of the loop can't be met naturally). As such, this solution is basically a direct translation of the C++, even though that makes it rather more low-level than a Jelly program normally is. Luckily, C++ has undefined behaviour on signed integer overflow (the question uses `int`), meaning that a program can do anything in that case, and thus there's no need to try to mimic the overflow behaviour.
## Explanation
```
Ṅ+⁶µ⁴;⁵¹vµ¿t
µ µ¿ While loop; while ((⁴;⁵¹v) counter) do (counter = (Ṅ+⁶)counter).
⁴;⁵ Second input (b) appended to third input (c), e.g. "<10"
v Evaluate, e.g. if the counter is 5, "<10" of the counter is true
¹ No-op, resolves a parser ambiguity
Ṅ Output the counter, plus a newline
+⁶ Add the fourth input (d)
t Crashes the program (because the counter is not a list)
```
Crashing the program is the tersest way to turn off Jelly's implicit output (otherwise, it would output the final value of the counter); it generates a bunch of error messges on stderr, but we normally consider that to be allowed.
Incidentally, the loop counter is initialised with the current value before the loop starts. As the loop appears at the start of the program, that'll be the first input.
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
```
a,b,c,d=input()
while eval(`a`+b+`c`):print a;a+=d
```
[Try it online!](https://tio.run/nexus/python2#@5@ok6STrJNim5lXUFqioclVnpGZk6qQWpaYo5GQmKCdpJ2QnKBpVVCUmVeikGidqG2b8v9/tIGOuo26jqGBjlEsAA "Python 2 – TIO Nexus")
[Answer]
## R, 63 bytes
```
function(a,b,c,d)while(do.call(b,list(a,c))){cat(a,"\n");a=a+d}
```
[Answer]
# Java, 58 bytes
```
(a,b,c,d)->{for(;b>61?a>c:a<c;a+=d)System.out.println(a);}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~22~~ 20 bytes
```
[D²`'>Q"‹›"è.V_#D,³+
```
[Try it online!](https://tio.run/nexus/05ab1e#@x/tcmhTgrpdoNKjhp2PGnYpHV6hFxav7KJzaLP2//@GBlzRxjrqduqxXLpGAA "05AB1E – TIO Nexus")
**Explanation**
```
[ # start loop
D # copy top of stack (current value of a)
²` # push b,c to stack
'>Q # compare b to ">" for equality
"‹›" # push this string
è # index into the string with this result of the equality check
.V # execute this command comparing a with c
_# # if the condition is false, exit loop (and program)
D, # print a copy of the top of the stack (current value of a)
³+ # increment top of stack (a) by d
```
[Answer]
# SmileBASIC, 53 bytes
```
INPUT A,B$,C,D
S=ASC(B$)-61WHILE S*A>S*C?A
A=A+D
WEND
```
Explanation:
```
INPUT A,B$,C,D
IF B$=="<" THEN S=-1 ELSE S=1 'get comparison direction
I=A
WHILE S*I>S*C 'loop while I is less than/greater than the end
PRINT I
INC I,D
WEND
```
This uses the fact that `X<Y` is the same as `-X>-Y`
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 34 bytes
```
@d@c@b[show d+][:c b tofunc!]while
```
[Try it online!](https://tio.run/nexus/stacked#@2@ooG6jrmBooGDE5ZDikOyQFF2ckV@ukKIdG22VrJCkUJKfVpqXrBhbnpGZk/r/PwA "stacked – TIO Nexus") (Testing included.) This is a function that expects the stack to look like:
```
a b c d
```
For example:
```
1 '<' 10 2
@d@c@b[show d+][:c b tofunc!]while
```
## Explanation
```
@d@c@b[show d+][:c b tofunc!]while
@d@c@b assign variables
[............]while while:
:c duplicate "i" and push c
b tofunc! convert b to a function and execute it
[.......] do:
show output "i" without popping
d+ and add the step to it
```
[Answer]
## Plain TeX, 88 bytes
```
\newcount\i\def\for#1 #2 #3 #4 {\i#1\loop\the\i\endgraf\advance\i#4\ifnum\i#2#3\repeat}
```
The command `\for` provides the requested function. Save this as `for.tex` and then run it and enter the variable values at the command line: `pdftex '\input for \for 1 < 5 1 \bye'` The variable values must be separated by spaces.
[Answer]
# [Python 2](https://docs.python.org/2/), 45 bytes
```
exec"i=%d\nwhile i%c%d:print i;i+=%d"%input()
```
[Try it online!](https://tio.run/nexus/python2#@59akZqslGmrmhKTV56RmZOqkKmarJpiVVCUmVeikGmdqQ2UUlLNzCsoLdHQ/P/fUEfdRl3H0EDHEAA "Python 2 – TIO Nexus")
A very literal implementation of the spec. Takes the code template, substitutes in the inputs via string formatting, and executes it.
[Answer]
# C++, 80
Whoops, this is `C++` not `C`. Was a bit confused by the question.
```
void f(int a,char b,int c,int d){for(;b==62?a>c:a<c;a+=d)cout<<a<<endl;}
```
[Answer]
# C, 52 51 bytes
-1 byte thanks to [H Walters](https://codegolf.stackexchange.com/users/58514/h-walters)
```
f(a,b,c,d){for(;b&2?a>c:a<c;a+=d)printf("%d\n",a);}
```
[Try it online!](http://ideone.com/N455xt)
[Answer]
# Python 3, 52 bytes
```
def f(a,b,c,d):
while[a>c,a<c][b<'>']:print(a);a+=d
```
**[repl.it](https://repl.it/FVyU)**
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 14 bytes
```
W Va.b.ca:d+Pa
```
Takes four command-line arguments. Supports negative & floating point numbers and comparison operators `< > = <= >= !=`. [Try it online!](https://tio.run/nexus/pip#@x@ZGK4QVqmXpJccmaIdUPn//38jg/92tv8NDf7rGgEA "Pip – TIO Nexus")
```
a,b,c,d are cmdline args
W While loop with the following condition:
Va.b.c Concatenate a,b,c and eval
Pa Print a with newline (expression also returns value of a)
a:d+ Add d to that and assign back to a
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ḢṄ+⁹;µV¿
```
This is a dyadic link that takes **a,b,c** as its left argument and **d** as its right one. Output may be infinite and goes to STDOUT.
[Try it online!](https://tio.run/nexus/jelly#ASkA1v//4bii4bmEK@KBuTvCtVbCv/8xLOKAnTwsMTAgw6cgMSDhuZkg4oCc/w "Jelly – TIO Nexus")
### How it works
```
ḢṄ+⁹;µV¿ Dyadic link.
Left argument: a,b,c (integer, character, integer)
Right argument: d (integer)
¿ While...
V the eval atom applied to a,b,c returns 1:
µ Combine the links to the left into a chain and apply it to a,b,c.
Ḣ Head; pop and yield a from a,b,c.
Ṅ Print a, followed by a linefeed.
+⁹ Add a and the right argument (d) of the dyadic link.
; Concatenate the result and the popped argument of the chain,
yielding a+d,b,c.
```
[Answer]
# Python 3, 61 bytes
One liner:
```
e=input;exec(f'i={e()}\nwhile i{e()}{e()}:print(i);i+={e()}')
```
[Answer]
## Common Lisp, ~~82~~ ~~80~~ ~~79~~ ~~73~~ 64 bytes
```
(defmacro f(a b c d)`(do((i,a(+ i,d)))((not(,b i,c)))(print i)))
```
## Test
```
(f 1 < 10 1)
1
2
3
4
5
6
7
8
9
NIL
CL-USER>
```
-9 bytes thanks to PrzemysławP.
[Answer]
# [Haskell](https://www.haskell.org/), ~~66~~ 64 bytes
```
f a b c d|last$(a<c):[a>c|b>"<"]=print a>>f(a+d)b c d|1<3=pure()
```
[Try it online!](https://tio.run/nexus/haskell#@5@mkKiQpJCskFKTk1hcoqKRaJOsaRWdaJdck2SnZKMUa1tQlJlXopBoZ5emkaidoglRa2hjbFtQWpSqofk/NzEzT8FWIU3BQAGoXsFSweg/AA "Haskell – TIO Nexus") Usage:
```
Prelude> f 0 "<" 9 2
0
2
4
6
8
```
[Answer]
# Bash (+Unix Tools), 29 bytes
**Golfed**
```
bc<<<"for(x=$1;x$2$3;x+=$4)x"
```
**Test**
```
./forloop 1 '<' 10 1
1
2
3
4
5
6
7
8
9
```
[Answer]
# Ruby, ~~43~~ 41 bytes
```
->a,*i,d{a=d+p(a)while eval"%s"*3%[a,*i]}
```
If `b` can be taken in as a *Ruby symbol* instead of a string, you get **38 bytes**:
```
->a,b,c,d{a=d+p(a)while[a,c].reduce b}
```
[Try either solution online!](https://repl.it/FWQd/1)
[Answer]
# PHP, ~~69~~ 65 bytes
```
for(list(,$i,$b,$c,$d)=$argv);$b<"="?$i<$c:$i>$c;$i+=$d)echo"$i
";
```
Run with '-r'; provide command line arguments as input.
For ~~just one byte more~~ 4 more bytes, I can take every operator:
```
for(list(,$i,$b,$c,$d)=$argv;eval("return $i$b$c;");$i+=$d)echo"$i
";
```
Yeah, evil eval. Did you know that it can return something?
---
Shorthand destructuring `[,$i,$b,$c,$d]=$argv;` would save 4 more bytes;
but PHP 7.1 postdates the challenge.
[Answer]
# [Perl 6](http://perl6.org/), 44 bytes
```
{.say for $^a,*+$^d...^*cmp$^c!= $^b.ord-61}
```
### How it works
```
{ } # A lambda.
$^a # Argument a.
,*+$^d # Iteratively add d,
...^ # until (but not including the endpoint)
*cmp$^c # the current value compared to c
# (less=-1, same=0, more=1)
!= $^b.ord-61. # isn't the codepoint of the b minus 61.
.say for # Print each number followed by a newline.
```
If it's okay to return a (potentially infinite) sequence of numbers as a value of type `Seq`, instead of printing the numbers to stdout, the `.say for` part could be removed, bringing it down to 35 bytes.
[Answer]
# Clojure, ~~66~~ 63 bytes
```
#(when((if(= %2"<")< >)% %3)(println %)(recur(+ % %4)%2 %3 %4))
```
-3 bytes by factoring out the `loop`. I'm "abusing" the init parameter to act as the running accumulator.
Recursive solution (with TCO). See comments in pregolfed code. I tried a non-TCO recursive solution, and it ended up being 67 bytes.
I'd love to see this beat in Clojure! I think this is the smallest I can get it.
```
(defn my-for [init-num com-str com-num inc-num]
(let [op (if (= com-str "<") < >)] ; Figure out which operator to use
(when (op init-num com-num) ; When the condition is true, print and recur
(println init-num)
(recur (+ init-num inc-num) com-str com-num inc-num))))
; Else, terminate (implicit)
```
[Answer]
## Groovy, 51 bytes
```
{a,b,c,d->while(Eval.me("$a$b$c")){println a;a+=d}}
```
This is an unnamed closure. [Try it Online!](https://tio.run/#v3N5j)
**Caution** - If you want to test this with `groovy console`, make sure you kill the entire process when the input causes an infinite loop. I noticed this after it consumed ~5 gigs of RAM.
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~51~~ 40 bytes
```
:;::{?a┘a=a+c~A=@<`|~a>=b|_X]\~a<=b|_X
```
And three minutes after posting I realised I could simplify the terminator logic...
```
:;:: Consecutively read a, A$, b and c from the command line
{?a┘ Start an infinite loop; print a, add a newline to the source
a=a+c increment a
~A=@<`| If we are in LESS THAN mode
~a>=b and IF we are no longer LESS
|_X] THEN QUIT, end if.
\ ELSE (we're in GREATER THAN mode)
~a<=b IF we are no longer GREATER
|_X THEN QUIT
The last IF and the loop are auto-closed
```
[Answer]
## Batch, 94 bytes
```
@set i=%1
@set o=gtr
@if "%~2"=="<" set o=lss
:g
@if %i% %o% %3 echo %i%&set/ai+=%4&goto g
```
If it wasn't for the second parameter behaviour, it could be done in 53 bytes:
```
@for /l %%i in (%1,%4,%n%)do @if not %%i==%3 echo %%i
```
This simply does nothing if the step has the wrong sign. The extra test is because Batch's `for` loop allows the loop variable to equal the end value.
[Answer]
## Clojure, 66 bytes
```
#(loop[i %](if(({">">"<"<}%2)i %3)(do(println i)(recur(+ i %4)))))
```
This could have been 55 bytes as`<` and `>` are functions in Clojure:
```
(def f #(loop[i %](if(%2 i %3)(do(println i)(recur(+ i %4))))))
(f 1 < 10 1)
```
[Answer]
# TI-Basic, ~~41~~ 34 bytes
```
Prompt A,Str2,Str3,D
While expr("A"+Str2+Str3
Disp A
A+D->A
End
```
] |
[Question]
[
Output or display the following three lines of text, exactly as they are shown below. A trailing newline is accepted.
```
bC#eF&hI)kL,nO/qR2tU5wX8z
A!cD$fG'iJ*lM-oP0rS3uV6xY9
aB"dE%gH(jK+mN.pQ1sT4vW7yZ
```
That block of text is the same as the one below, but where the n'th column is rotated n times downward:
```
!"#$%&'()*+,-./0123456789
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
```
Keep in mind that this is a [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenge, so the output format is not flexible.
[Answer]
# Java 8, ~~169~~ ~~162~~ ~~150~~ ~~146~~ ~~116~~ ~~113~~ ~~106~~ ~~95~~ ~~94~~ ~~93~~ ~~92~~ ~~91~~ ~~90~~ 84 bytes
Yay, we finally did it! We've beat the 88-byte literal output that can be found at the bottom. Thanks to all those who participated in the golfing!
```
v->{for(int i=0,t=0;++i<81;System.out.printf("%c",i%27<1?10:(4-t++%3)*32%97+i%27));}
```
-7 bytes thanks to *@StewieGriffin*.
-42 bytes thanks to *@Neil*.
-11 bytes thanks to *@PeterTaylor*.
-3 bytes thanks to *@OlivierGrégoire*.
-6 bytes thanks to *@OlivierGrégoire* and *@Neil* (Olivier suggested [a port of Neil's JavaScript answer](https://codegolf.stackexchange.com/a/155752/52210)).
[Try it online.](https://tio.run/##LY7BCsIwDIbvPkUQBq1z07mDYp0@gV4EL@Kh1k2isxtrNhCZrz4zFRKS/CH5v5tudFCUqb1d7p3JtXOw1WhfAwC0lFaZNins@hGgKfACRhz60kjFWsvJ4UgTGtiBhQS6Jli/sqISfA@YTMekfB9Xi0jtn47SR1jUFJYVbzMx9MxwjN5svoo20XTZdz6N4lkQTUhKSgROWHmj9GI/Vm2nfn5lfc7Z72/7xXowtNgTv70eT7q6OvljtqERts7zP27bfQA)
**Explanation:**
```
v->{ // Method with empty unused parameter and no return-type
for(int i=0,t=0;++i<81; // Loop from 1 to 81 (exclusive)
System.out.printf("%c", // Print the following character:
i%27<1? // If it's the last column
10 // Print a new-line
: // Else:
(4-t++%3)*32%97+i%27 // Print the correct character based on the index
```
[See here what each of the arithmetic parts do, and how it ends up at the correct characters.](https://tio.run/##fZHdSsMwFMfvfYpDoJAYW/YhbLar4gO4m4E31oss62Zml5YkLYj02etJWy@c05CQ8/E7h@R/jqIRYVnl@rh772QhrIUnofTnFYDSLjd7IXNYexegKdUOJH32V8MSjLV4cFsnnJKwBg0pdE147/l9aSi2AJVOblw6SThXq@U0YX2rzYd1@SkqaxdVBqlCU6JiIFz1ab84yZwKZosYMEy9xX7k6G3oOA/mzJd5B83LwPV81jMjhO7fYHC3OGMx8i/Oh0ee1/DfL360IN@EERJ1jb8/tZo@kCzTJKY@x@il7oyh2m2XDGpX9bZAtUfR@6GccGR041DJw8urMAfLhonpSFJdF8U4rLb7Ag)
---
# Java 8, 88 bytes
```
v->" bC#eF&hI)kL,nO/qR2tU5wX8z\nA!cD$fG'iJ*lM-oP0rS3uV6xY9\naB\"dE%gH(jK+mN.pQ1sT4vW7yZ"
```
Boring, ~~but utilizing the intended rotation of columns won't be any shorter in Java for sure..~~ I stand corrected! ~~Will post a solution in a moment either way to see how much bytes it differs.~~ Apparently the difference is just **-4 bytes! :D**
[Try it online.](https://tio.run/##LY7ZTsMwEEXf@YohbA6QsG@qQGJfG5aWAm14cB03OHUmIXZcCuq3B1eNNPdh7n04J6GGelnOMYmGFZNUKWhSgX9zAAI1LwaUcQimL0BLFwJjYKSTiQiM27DtxMae0lQLBgEgHENlvBMH@ucL/Gr569YdPqzj48b3y7Z@3Ru9H/6GeDrPLhYH1yviblU2vexps2jtlJ39n4@jEOlZ6ESXS/ENSe7X0sDPn7dUe9e8HYy7TtWY0fKyLy2thpqpTWqlyUyw90mLWLm181hpnvpZqf3cjpqgzwiWUrq1/qT6Bw)
---
[Answer]
# [Husk](https://github.com/barbuz/Husk), 13 bytes
```
Tzṙṫ26¡m→"Aa
```
Note the trailing space.
[Try it online!](https://tio.run/##yygtzv7/P6Tq4c6ZD3euNjI7tDD3UdskJcdEhf//AQ "Husk – Try It Online")
## Explanation
```
Tzṙṫ26¡m→"Aa No input.
"Aa The string "Aa ".
¡ Iterate
m→ map successor: ["Aa ","Bb!","Cc\"","Dd#",..
z Zip with
ṫ26 the reversed range [26,25,24,..,1]
ṙ using rotation: [" Aa","b!B",..,"z9Z"]
This also truncates the list to length 26.
T Transpose, implicitly print separated by newlines.
```
[Answer]
# SPL (Shakespeare Programming Language), ~~1679~~ ~~1618~~ 1600 bytes
```
.
Ajax,.
Ford,.
Puck,.
Act I:.
Scene I:.
[Enter Ajax and Ford]
Ajax:
You are the remainder of the quotient between the sum of the remainder of the quotient between the product of me and a fat joy and the sum of the cube of a big red day and the difference between a red fat pig and a big old fat cow and the quotient between me and the sum of a day and the square of the sum of a joy and a big red day and the sum of a cat and a fat son.
[Exit Ajax]
[Enter Puck]
Ford:
Am I as good as nothing? If so, you are a bad big old red fat day. Am I as good as a joy? If so, you are the sum of a joy and a the cube of an old bad day. Am I as good as a big day? If so, you are the sum of the square of the sum of a big red fat cat and an old cow and the sum of an old war and a lie.
[Exit Ford]
[Enter Ajax]
Ajax:
You are the sum of thyself and the remainder of the quotient between me and the sum of a man and the square of the sum of a son and a big fat cow. Speak thy mind!
[Exit Puck]
[Enter Ford]
Ford:
You are the sum of yourself and a son.
Ajax:
You are the remainder of the quotient between me and the sum of a cat and the square of the sum of a cow and an old red sky.
Ford:
Am I as good as nothing? If so, let us proceed to scene III.
Scene II:.
Ajax:
You are the product of the sum of a fat man and a cow and the sum of a man and the square of the sum of a cat and a big red son. Are you not better than me? If so, let us return to act I. Let us proceed to scene IV.
Scene III:.
Ajax:
You are the sum of a big old fat cat and a red cow. Speak thy mind! Let us return to scene II.
Scene IV:.
[Exeunt]
```
I had some issues with the interpreter (<https://github.com/drsam94/Spl>), so it's not as small as I think it could have been. But at least this works :)
---
Here's the same logic in PHP, to make it a bit easier to see what's going on.
```
<?php
Act1Scene1:
$ford = ((2 * $ajax) % 52 + $ajax / 26) % 3;
if ($ford == 0) {
$puck = 32;
}
if ($ford == 1) {
$puck = 65;
}
if ($ford == 2) {
$puck = 97;
}
$puck = $ajax % 26 + $puck;
echo chr($puck);
$ajax = $ajax + 1;
$ford = $ajax % 26;
if ($ford == 0) {
goto Act1Scene3;
}
Act1Scene2:
if ($ajax < 78) {
goto Act1Scene1;
}
goto Act1Scene4;
Act1Scene3:
$ford = 10;
echo chr($ford);
goto Act1Scene2;
Act1Scene4:
```
[Answer]
## JavaScript (ES6), ~~86~~ 75 bytes
```
f=(i=k=0)=>i<80?String.fromCharCode(++i%27?(4-k++%3)*32%97+i%27:10)+f(i):''
```
Edit: Saved 11 bytes thanks to @Ryan. Now 10 bytes shorter than the literal!
## [JavaScript (Node.js)](https://nodejs.org), 64 bytes
```
f=(i=k=0)=>i<80?Buffer([++i%27?(4-k++%3)*32%97+i%27:10])+f(i):''
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYj0zbb1kDT1i7TxsLA3qk0LS21SCNaWztT1cjcXsNEN1tbW9VYU8vYSNXSHCxoZWgQq6mdppGpaaWu/t86OT@vOD8nVS8nP10jTUNT0/o/AA "JavaScript (Node.js) – Try It Online") Thanks to @Ryan.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ 15 bytes
Saved 2 bytes thanks to *Erik the Outgolfer*
```
žQAuA)øε¼¾GÁ]ø»
```
[Try it online!](https://tio.run/##ASEA3v8wNWFiMWX//8W@UUF1QSnDuM61wrzCvkfDgV3DuMK7//8 "05AB1E – Try It Online")
**Explanation**
```
žQ # push the list of printable ascii characters
Au # push upper-case alphabet
A # push lower-case alphabet
)ø # zip
ε # apply to each
¼ # increment counter
¾G # for N in [1 ... counter] do:
Á # rotate string right
] # end loops
ø # zip
» # print list joined by newlines
```
[Answer]
## CJam (18 bytes)
```
26{_" Aa"f+m>}%zN*
```
[Online demo](http://cjam.aditsu.net/#code=26%7B_%22%20Aa%22f%2Bm%3E%7D%25zN*)
### Dissection
The obvious approach is to generate the original lines, zip, rotate with `ee::m>`, and zip back. But `ee::` is quite long, and it's shorter to generate the columns directly.
```
26{ e# For i = 0 to 25...
_" Aa"f+ e# Generate the unrotated column by offsets from the starting chars
m> e# Rotate the appropriate distance
}%
zN* e# Zip and join the rows with newlines
```
[Answer]
# [Python 2](https://docs.python.org/2/), 72 bytes
```
x=98
exec"r='';exec'r+=chr(x/3);x+=291*(x<180)-94;'*26;print r;x-=78;"*3
```
[Try it online!](https://tio.run/##FcZBCoAgEADAe68IL2uGlBalbPsaEexSsXjYXm80p3neWu7LtyYUQ5clJ8UEgP@AR0qFtUzLgDKSj85oOVyYBxtXBOM3fPi8as8olvaAyiytfQ "Python 2 – Try It Online")
This works by removing `31.333..` from the previous character, adding `97` when the previous codepoint is less than 60, and subtracting `26` at the end of each line.
[Answer]
# [R](https://www.r-project.org/), ~~64~~ 63 bytes
```
cat(intToUtf8(c(32:57,10,65:90,10,97:122,10)[(0:80*55)%%81+1]))
```
[Try it online!](https://tio.run/##K/r/PzmxRCMzryQkP7QkzUIjWcPYyMrUXMfQQMfM1MrSAMSwNLcyNDICsjSjNQysLAy0TE01VVUtDLUNYzU1//8HAA "R – Try It Online")
-1 byte thanks to Giuseppe
I arrived at this through quite a bit of trial and error, so I'm struggling with a concise explanation. Essentially, instead of the character codes, I started off with a more simple sequence of 1:81 representing the original block of text (3\*26 plus 3 newlines), and examined the indices of where these values end up in the rotated block. This follows a regular sequence that drops by 26 each time, modulo 81 (or equivalently, increases by 55 mod 81). It was then a matter of recreating that sequence `(0:80*55)%%81+1])`, mapping to the real unicode values `c(32:57,10,65:90,10,97:122,10)`, converting to characters and printing.
[Answer]
## [CJam](https://sourceforge.net/p/cjam), ~~23~~ 21 bytes
```
3{26{_I-" aA"=+}/N}fI
```
[Try it online!](https://tio.run/##S85KzP3/37jayKw63lNXSSHRUclWu1bfrzbN8/9/AA "CJam – Try It Online")
### Explanation
```
3{ e# For I from 0 to 2...
26{ e# For i 0 to 25...
_I- e# Duplicate i and subtract I. This shifts the starting
e# character of each line left in the following string.
" aA"= e# Pick the character at the start of the unrotated line
e# of the current character. We basically just cycle
e# through non-letters, lower-case, upper-case, which is
e# the cycle throughout the result. Due to the I-, when
e# We get to the second line we start from A, and on the
e# third line we start from a.
+ e# Add i to the starting character to get the correct
e# column.
}/
N e# Push a linefeed.
}fI
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~17~~ 15 bytes
```
"@`"
;By@=cÄ é
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=IkBgHyIKO0J5QD1jxCDp&input=)
### Explanation
```
"@`" The string "@`\x1F". The following newline sets U to this string.
; Reset variables A-L to various values. B is set to
B the uppercase alphabet, which we only use to get a length of 26.
y@ Map each column Z (initially just the letter itself) through this function:
cÄ Increment each char-code in U.
é Rotate by 1 character.
= Set U to the result to keep the chain going.
This generates the 26 columns exactly how we needed them.
Implicit: output result of last expression
```
7 other possible 15-byters:
```
;By@" Aa"c+Y éY
;ByÈpv)iSc+Y)éY
;ByÈ+v)iSc+Y)éY
;ByÈpv)iYd32)éY
;ByÈ+v)iYd32)éY
;ByÈpv)i32dY)éY
;ByÈ+v)i32dY)éY
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 16 bytes
```
1Y2tk9V:v26:l&YS
```
[Try it online!](https://tio.run/##y00syfn/3zDSqCTbMsyqzMjMKkctMvj/fwA)
### Explanation
```
1Y2 % Push 'AB...Z' (predefined literal)
t % Duplicate
k % Maker lowercase
9V % Push 9, convert to string representation: gives char '9'
: % Range. For chars, gives string from space to that
v % Concatenate vertically. Gives a 3×26 char matrix
26 % Push 26
: % Range. For numbers, gives numeric vector from 1 to that
l&YS % Circularly shift each column of the first input (char matrix)
% by the amount specified by the second input (numeric vector).
% Implicitly display
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
26“ aA‘ẋs+ḶỌY
```
[Try it online!](https://tio.run/##ASAA3/9qZWxsef//MjbigJwgYUHigJjhuotzK@G4tuG7jFn//w "Jelly – Try It Online")
### How it works
```
26“ aA‘ẋs+ḶỌY Main link. No arguments.
26 Set the argument and the return value to 26.
“ aA‘ẋ Repeat [32, 97, 65] (code points of ' ', 'a', and 'A') 26 times.
s Split the result into chunks of length 26.
Ḷ Unlength; yield [0, ..., 25].
+ Add [0, ..., 25] to each of the chunks.
Ọ Unordinal; cast all integers to characters.
Y Jojn, separating by linefeeds.
```
[Answer]
# [R](https://www.r-project.org/), ~~88~~ 86 bytes
```
cat(intToUtf8(rbind(diffinv(matrix(c(66,-32,-31),25,5,T)[,1:3],,,t(c(32,65,97))),10)))
```
[Try it online!](https://tio.run/##DcnLCoAgEEbh15mBP0hFuzxHraJFJcIsMpAhentzcc7mK7Veh5JkXZ5V00jllBwpSkqSX7oPLfLRRSGgc7ZlGNbDY@ENZnY7AG3eLHhMAzPD9O21/g "R – Try It Online")
~~R is terrible at string manipulation and although it has some neat matrix builtins, rotations are another thing it doesn't do very easily.~~ I will happily give a bounty to anyone who can out-golf me in R.
Despite my having found a shorter answer, I'll still award a 50 rep bounty to the first other R answer shorter than 88 bytes.
I suppose I'd award myself the bounty if I could, but this is a whole two bytes shorter than the "boring" answer! I avoid rotations by just using R's penchant for recycling.
EDIT: [user2390246's answer](https://codegolf.stackexchange.com/a/155863/67312) completely outgolfed me and I will be awarding a 100 point bounty since that solution is far superior.
To get here, I deconstructed the desired output to their ASCII code points with `utf8ToInt` (removing the newlines), built a matrix, and ran a `diff` on themm getting the columnwise differences. Noting the periodicity there, I set out to construct the matrix in a golfy fashion, hoping to use `diffinv` to recreate the original.
Thanks to the periodicity, we can recreate the `diff`ed matrix by forcing R to recycle with a non-multiple length, and extract the columns we actually wanted:
```
matrix(c(66,-32,-31),25,5,T)[,1:3]
```
Then we invert this process, with `diffinv` to recreate the code points, append a row of `10` (newlines) to the bottom, reconvert to ASCII with `intToUtf8`, and `cat` the result.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~14~~ 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü≤▐éh╢%╠£┐3]
```
[Run and debug it](https://staxlang.xyz/#p=81f3de8268b625cc9cbf335d&i=&a=1)
Unpacked, ungolfed, and commented, it looks like this.
```
3R26 push [1,2,3] and 26
K cross-map using the rest of the program, printing lines implicitly
this instruction maps over a cartesian join
- subtract
" Aa"@ index into " Aa" using the subtraction result
i+ add the iteration index
```
[Run this one](https://staxlang.xyz/#c=3R26++++%09push+[1,2,3]+and+26%0AK+++++++%09cross-map+using+the+rest+of+the+program,+printing+lines+implicitly%0A++++++++%09this+instruction+maps+over+a+cartesian+join%0A++-+++++%09subtract%0A++%22+Aa%22%40%09index+into+%22+Aa%22+using+the+subtraction+result%0A++i%2B++++%09add+the+iteration+index&i=&a=1)
This program only uses features that have been available since the initial release of stax, but apparently I forgot about `K` for cross-map when I originally write this answer.
One nearly interesting thing to note about this answer is that the `R` is an unnecessary instruction because `K` implicitly turns integers into ranges. However there's no way to push `3` and `26` without some extra byte in between.
[Answer]
# [Perl 5](https://www.perl.org/), 46 bytes
```
print map{chr$n+++ord,$/x!($n%=26)}($",a,A)x26
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoicHJpbnQgbWFwe2NociRuKysrb3JkLCQveCEoJG4lPTI2KX0oJFwiLGEsQSl4MjYifQ==)
Saved 13 bytes thanks to [@TonHospel](https://codegolf.stackexchange.com/users/51507/ton-hospel)'s arcane wizardry!
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 53 bytes
```
0..2|%{-join(32..57|%{[char]($_+(0,65,33)[$j++%3])})}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/30BPz6hGtVo3Kz8zT8PYSE/P1BzIjU7OSCyK1VCJ19Yw0DEz1TE21oxWydLWVjWO1azVrP3/HwA "PowerShell – Try It Online")
I see this is similar to Dom's Perl answer, but I arrived at it independently.
This exploits the fact that the pattern goes `Symbol - Lowercase - Capital`, even when wrapping newlines (`8 - z - A`, for example), and thus just adds the appropriate offset (chosen via `$j++%3`) to the current number `$_` before `-join`ing those together into a single string. That's done three times to come up with the three lines (preserving `$j` between iterations). Those three lines are left on the pipeline, and the implicit `Write-Output` gives us the newlines for free.
[Answer]
# [Julia 0.6](http://julialang.org/), 79 bytes
```
println.([prod([' ':'9' 'A':'Z' 'a':'z'][n,mod1(i-n,3)] for n=1:26) for i=2:4])
```
`[' ':'9' 'A':'Z' 'a':'z']` is the unrotated 2d array of characters, `[n,mod1(i-n,3)]` indexes into that array with appropriate rotation. `prod` takes a Vector of Characters to a String (since multiplication is used for string join). There are two nested Vector comprehensions resulting in a Vector containing 3 strings, then `println.` prints the each string in the Vector followed by a newline.
TIO lacks the appropriate method to multiply (with `prod`) two characters to get a String. I know that method was added somewhat recently, but the TIO version appears to be the same as the version on my PC where this code works, so I can't fully explain why it doesn't work on TIO.
Copy paste example (the `;` isn't necessary, it just supresses extra output in the REPL):
```
julia> println.([prod([' ':'9' 'A':'Z' 'a':'z'][n,mod1(i-n,3)] for n=1:26) for i=2:4]);
bC#eF&hI)kL,nO/qR2tU5wX8z
A!cD$fG'iJ*lM-oP0rS3uV6xY9
aB"dE%gH(jK+mN.pQ1sT4vW7yZ
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~26~~ ~~21~~ 15 bytes
```
E³⭆⧧⟦γαβ⟧⁻κμμ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDDWEchuATISwdxknQUHEs881JSKzRgdHS6jkKijkJSrI6Cb2ZeabFGto5CrqYmmNDUtP7//79uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
³ Literal 3
E Map over implicit range
β Lowercase letters
⭆ Map over characters and concatenate
κ Outer index
μ Inner index
⁻ Subtract
γ Printable characters
α Uppercase letters
β Lowercase letters
§⟦ ⟧ Circularly index into list (selects one of the three strings)
μ Inner index
§ (Circularly) index into string
Implicitly print each inner map result on a separate line
```
[Answer]
# [J](http://jsoftware.com/), 29, 27 25 bytes
-2 bytes thanks to FrownyFrog
-2 bytes thanks to miles
```
|:u:(<26)2&(|.>:)32 65 97
```
[Try it online!](https://tio.run/##y/r/PzU5I1@hxqrUSsPGyEzTSE2jRs/OStPYSMHMVMHS/D/XfwA "J – Try It Online")
Initial approach: [J](http://jsoftware.com/), 29 bytes
```
u:(-|."_1&.|:32 65 97+/])i.26
```
Explanation:
`i.26` - range 0-26
```
i.26
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 25
```
`32 65 97+/]` - create a 3-row table for the characters
```
32 65 97+/i.26
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
```
`&.|:` transpose then do the next verb (`|.`) and transpose again
`-|."_1` rotate each row n times
```
(-i.26)|."_1|:32 65 97+/i.26
32 65 97
98 33 66
67 99 34
35 68 100
101 36 69
70 102 37
38 71 103
104 39 72
73 105 40
41 74 106
107 42 75
76 108 43
44 77 109
110 45 78
79 111 46
47 80 112
113 48 81
82 114 49
50 83 115
116 51 84
85 117 52
53 86 118
119 54 87
88 120 55
56 89 121
122 57 90
```
`u:` convert to unicode
```
u:(-i.26)|."_1&.|:32 65 97+/i.26
bC#eF&hI)kL,nO/qR2tU5wX8z
A!cD$fG'iJ*lM-oP0rS3uV6xY9
aB"dE%gH(jK+mN.pQ1sT4vW7yZ
```
[Try it online!](https://tio.run/##y/r/PzU5I1@h1EpDt0ZPKd5QTa/GythIwcxUwdJcWz9WM1PPyOw/138A "J – Try It Online")
[Answer]
# C, ~~70~~ ~~69~~ ~~67~~ ~~60~~ 64 bytes
```
i;f(t){for(i=t=0;++i<81;putchar(i%27?(4-t++%3)*32%97+i%27:10));}
```
+4 bytes to make [the function reusable](https://codegolf.meta.stackexchange.com/a/4940/52210).
Invalid 60-bytes answer that isn't reusable:
```
i,t;f(){for(;++i<81;putchar(i%27?(4-t++%3)*32%97+i%27:10));}
```
Port of ~~[my Java 8 answer](https://codegolf.stackexchange.com/a/155732/52210)~~ [*@Neil*'s JavaScript answer](https://codegolf.stackexchange.com/a/155752/52210).
[Try it online.](https://tio.run/##S9ZNzknMS///P9M6TaNEszotv0gj07bE1sBaWzvTxsLQuqC0JDkjESioamRur2GiW6KtrWqsqWVspGpprg0StDI00NS0rv2fm5iZpwE0QAPEAQA)
[Answer]
# APL+WIN, 26 bytes
Index origin 0
```
⎕av[(-⍳26)⊖32 65 97∘.+⍳26]
```
Generate a matrix of integer index values of the characters in the APL atomic vector.
Rotate each column downwards by its number value.
Use the resulting indices to display the characters from the atomic vector.
[Answer]
# Vim, ~~81~~ 79 bytes
```
a !"#$%&'()*+,-./0123456789␛:h<_␍jjYZZpPgU$klqq"aDjlma"bD"ap`ajD"bpkkp`akl@qq@q
```
## Explanation (simplified)
```
a !"#$%&'()*+,-./0123456789␛ Insert the first line
:h<_␍jjYZZpPgU$ Insert the alphabet twice by copying it from the help page
klqq Define the loop `q`:
"aDjl Cut the rest of the line to `a`
ma"bD"ap Replace the rest of the second line (cut `b`, paste `a`)
`ajD"bp Replace the rest of the third line (cut `c`, paste `b`)
kkp Paste `c`
`akl@qq@q Run the loop, each time one more step to the right
```
[Answer]
# C, 72 bytes
```
f(k,x,n){for(n=81;n;putchar(x?k*32+59-x-!k:10))x=--n%27,k=(3+x-n/27)%3;}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 65 bytes
```
for x in 2,99,196:s='';exec"s+=chr(32+x%291/3);x-=94;"*26;print s
```
[Try it online!](https://tio.run/##JczZtkJQAADQd1@hUzKWHFLnWh5onufxrUQ0IFRHP697190fsMM0cQMfZpkTRCQmPZ@EAkKChNSfWKdpzca2BWJet9yIkSGPKYgkUWY1XNKRogEOqloYeX5CxpmhAwAIMgfyBapIMyzHC6WyWJGgrFTVWh0Rhtlottqdbq8/GI7Gk@lsvliu1pvtbk8cjtbJds6ud7ne7n4QPqI4eb7eOP38nYT5Xx8bebtddHvsdSj4E/Exh8mq@t7WP4SRs5oFp0N7fe42KgXTSrSQn2sV7xBxMMGpRZ27zGXA38flcCbFS@W1qaX73zP7Ag "Python 2 – Try It Online")
[Answer]
# Ruby, 59 bytes
[Try it online!](https://tio.run/##KypNqvz/P9FWtTw6RkHBUSExlsvcVK8kMze1uLomsyYxOlPVONbGJjG6ThfEis7UN47Vy0utKKnlKigtKVZI/P8fAA "Ruby – Try It Online")
```
a=%w[\ A a]
75.times{|i|a[i%3]<<a[~-i%3][i/3].next}
puts a
```
Initiates an array with first characters of the three strings and then grows them in a single loop.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~71~~ 63 bytes
```
3.times{|j|26.times{|i|$><<(i+"aA aA "[2-j+i%3].ord).chr}
puts}
```
[Try it online!](https://tio.run/##KypNqvz/31ivJDM3tbi6JqvGyAzGzqxRsbOx0cjUVkp0VAAipWgj3SztTFXjWL38ohRNveSMolqugtKS4tr/ygoKrhUFqcklqSlWXMpcQK5CkrNyqptahqdmto9Onr9@YZBRSahpeYRFFUjWUTHZRSXNXT3TSyvHVzc/wKAo2Lg0zKwi0hIkm@iklOKqmu6hkeWtneunVxBoWBxiUhZuXhn1HwA "Ruby – Try It Online")
For a bit there I was worried I wouldn't be able to beat the string literal version.
-8 bytes: Index into a 6-character string, instead of a rotating 3-int array
```
3.times{|j|
26.times{|i|
# Find the appropriate base character (2-j+i%3)
# Add i to the ascii value of that character
# Push to STDOUT
$><< (i + "aA aA "[2 - j + i % 3].ord).chr
}
# newline
puts
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 17 bytes
```
26Æ" Aa"c+X éX÷y
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=MjbGIiBBYSJjK1gg6VjDt3k=&input=)
---
## Explanation
```
26Æ Ã :Create the range [0,26) and pass each X through a function
" Aa" : String literal
c+X : Add X to the codepoint of each character
éX : Rotate right X times
· :Join with newlines
y :Transpose
```
[Answer]
# [Python 2](https://docs.python.org/2/), 79 bytes
```
p=0
exec"o=0;r='';exec'r+=chr(o+[32,65,97][(p-o)%3]);o+=1;'*26;p+=1;print r;"*3
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8DWgCu1IjVZKd/WwLrIVl3dGsRTL9K2Tc4o0sjXjjY20jEz1bE0j43WKNDN11Q1jtW0zte2NbRW1zIysy4AsQqKMvNKFIqslbSM//8HAA "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 23 bytes ([Adám's SBCS](https://github.com/abrudz/SBCS))
```
(⎕UCS-⊖∘↑32 65 97+⊂)⍳26
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/x/1zlVwKU1VKMlXKElNzsjLTE7MUShKTSzOzyvWUSjJSFVIzk8BEol56iUK6fkKGalFqXr//2sATQh1DtZ91DXtUceMR20TjY0UzEwVLM21H3U1aT7q3WxkBgA "APL (Dyalog Unicode) – Try It Online")
-1 thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m).
Runs in an interactive environment.
Assumes `⎕IO←0`.
[Answer]
# [K4](http://kx.com/download/), 38 bytes
**Solution:**
```
-1"c"$+(-t).q.rotate'32 65 97+/:t:!26;
```
**Example:**
```
q)k)-1"c"$+(-t).q.rotate'32 65 97+/:t:!26;
bC#eF&hI)kL,nO/qR2tU5wX8z
A!cD$fG'iJ*lM-oP0rS3uV6xY9
aB"dE%gH(jK+mN.pQ1sT4vW7yZ
```
**Explanation:**
9 characters to perform the rotation...
```
-1"c"$+(-t).q.rotate'32 65 97+/:t:!26;
-1 ; / print to stdout, swallow return
!26 / til 26, 0..25
t: / save as variable t
+/: / add each right item to...
32 65 97 / the list 32, 65, 97 (ASCII offsets)
.q.rotate' / rotate each-both
(-t) / negate, 0..-25
+ / flip rows and columns
"c"$ / cast to characters
```
] |
[Question]
[
## Challenge
Write \$2 \le n \le 10\$ distinct, valid non-halting full programs in your language of choice. If all of them are concatenated in order, the resulting full program should be a valid halting program, but if any of them are left out, the result should still be a valid non-halting program.
More formally, write \$2 \le n \le 10\$ distinct programs \$P\_1, P\_2, \cdots, P\_n\$ in a language \$L\$ of your choice, which satisfy the following property:
* \$P\_1 P\_2 \cdots P\_n\$ (where \$XY\$ means string concatenation of two programs \$X\$ and \$Y\$) is valid full program in \$L\$ and, given no input, halts in finite time.
* If you delete any of \$1 \le x \le n-1 \$ program segments (\$P\_i\$'s where \$1 \le i \le n\$) from the above, the result is still a valid full program in \$L\$, but does not halt in finite time.
+ In other words, any nonempty proper subsequence of \$P\_1 P\_2 \cdots P\_n\$ should be a valid non-terminating program in \$L\$.
A program is *valid* if a compiler can successfully produce an executable or an interpreter finishes any pre-execution check (syntax parser, type checker, and any others if present) without error. A valid program is *halting* if the execution finishes for any reason, including normally (end of program, halt command) or abnormally (any kind of runtime error, including out-of-memory and stack overflow). The output produced by any of the programs does not matter in this challenge.
For example, a three-segment submission `foo`, `bar`, and `baz` is valid if
* `foobarbaz` halts in finite time, and
* each of `foo`, `bar`, `baz`, `foobar`, `foobaz`, and `barbaz` does not halt in finite time in the same language. (The behavior of `barfoo` or `bazbar` does not matter, since the segments are not in order.)
The score of your submission is the number \$n\$ (the number of program segments). The higher score wins, tiebreaker being code golf (lower number of bytes wins for the same score). It is encouraged to find a general solution that works beyond \$n = 10\$, and to find a solution that does not read its own source code (though it is allowed).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 10 programs, 299 bytes
```
(A=_=>setTimeout(A,B=_=>0))();
(B=_=>setTimeout(B,C=_=>0))();
(C=_=>setTimeout(C,D=_=>0))();
(D=_=>setTimeout(D,E=_=>0))();
(E=_=>setTimeout(E,F=_=>0))();
(F=_=>setTimeout(F,G=_=>0))();
(G=_=>setTimeout(G,H=_=>0))();
(H=_=>setTimeout(H,I=_=>0))();
(I=_=>setTimeout(I,J=_=>0))();
(J=_=>setTimeout(J,A=_=>0))()
```
* [Try it online!](https://tio.run/##Xcm5CgIxFAXQ30ngCvYyQvaltpdBU4ygI0709yM28rjtObf5M2@X1/Lsu8d6bWMoM52n49b6abm39d2Vgf3JXmulD8rSWjixjtbBi/W0HkFsoA2IYiNtRBKbaBOy2EybUcQW2oIqttJWmP@O8QU "JavaScript (Node.js) – Try It Online")
* [Try it online with second one dropped!](https://tio.run/##Xcm9CoMwFAbQ10ngE7oXhdT8z@5F2gwKVjHR1490kctdz5nHc8yffdpK81u/qVah2nfb5VSGaUnrUYTC6y8PKYV8ip5tD01Ws9UwZA1bA0vWsrVwZB1bB0/Ws/UIZAPbgEg2so1Q99Z6AQ "JavaScript (Node.js) – Try It Online")
* [Try it online with second one left!](https://tio.run/##y0osSyxOLsosKNHNy09J/f9fw8k23tauOLUkJDM3Nb@0RMNJxxkkYqCpqaFp/f8/AA "JavaScript (Node.js) – Try It Online")
Line breaks are added for readability. They are not a part of any programs.
Node.js will keep running if there is any timers been scheduled, and halt as soon as timer callback queue is cleared.
The order of these programs does not matter. After append an extra `;` to the last one, you may shuffle them and it still meets the requirement of this challenge. It halts as long as you collected all 10 programs, and never halts if anyone is missing. You may also duplicate some programs here, and it works same as the program appears only once. :)
[Answer]
# [Zsh](https://www.zsh.org/), 56 bytes, 10 programs
```
until wc<<Q|grep 36
yes
yes;yes yes yes yes ;yes
yes yes
```
[Try it online!](https://tio.run/##qyrO@P@/NK8kM0ehPNnGJrAmvSi1QMHYjKsytRiErYFYAYg5obSCNVQCJPD/PwA "Zsh – Try It Online")
The first and most important program is:
```
until wc<<Q|grep 36
```
Each `yes` is part of one of the other programs.
[y it online!](https://tio.run/##qyrO@P@/MrWYC4itgVgBiDmhtII1VAIk8P8/AA "Zsh – Try It Online") (note: TIO kills the program very quickly because `yes` produces over 128 KB of output, but if you ran it elsewhere it would never halt)
[Tre!](https://tio.run/##qyrO@P@/NK8kM0ehPNnGJrAmvSi1QMHYlKsytRiErTmBxP//AA "Zsh – Try It Online")
## Explanation
* `<<Q`: heredoc; takes the rest of the script starting from the next line, as a string
* `wc`: output line, word, and character numbers
* `|grep 36`: and search for the string `36` in that output
* `until` : repeat this command until it succeeds
If all 10 programs are present, then there will be exactly 36 characters in the output of `wc` and the `grep` will succeed, so the loop will halt.
If the first program is removed, the remainder of the script will be interpreted as code instead of as a string in the heredoc, and `yes` will never halt.
All the weird whitespace around each `yes` is to make them all distinct and remain as short as possible (mostly 4 bytes).
If any of the `yes` programs is removed, there won't be a `36` in the output so the `until` will loop forever.
## Notes
* `yes` is intended to output `y` indefinitely so it can be piped into an interactive program that asks yes-or-no questions, but in this case it doesn't matter what it outputs
* `<<Q` actually only outputs the contents until the first line containing only `Q`, but there is no such line, so it just goes until the end of the file
* The exact splitting of the program is as follows; a `#` is used to separate each one here
```
until wc<<Q|grep 36
#yes
#yes;#yes #yes #yes# yes# ;yes#
yes# yes
```
Notice all the quirky whitespace, and there's a tab in there somewhere.
One of the programs is `;yes`; it could just be `;yes` with no space, except in the case the only remaining programs are `yes;;yes`: zsh would throw a syntax error because `;;` is treated as one token instead of two semicolon command separators.
---
# [Zsh](https://www.zsh.org/), 107 bytes, 10 programs
```
while 1=u
while 1+=i
while 1+=l
while 1+=t
while 1+=in
while 2=e
while 2+=x
while 2+=i
while 2+=t
until b$@
```
[Try it online!](https://tio.run/##qyrO@P@/PCMzJ1XB0LaUC8rSts1EMHMQzBIkBXlQtpFtKoylbVuBYGYimCVcpXklmTkKSSoO//8DAA "Zsh – Try It Online")
[Try it onlin](https://tio.run/##qyrO@P@/PCMzJ1XB0LaUC8rSts1EMHMQzBIkBXlQtpFtKoylbVuBYGYimCX//wMA "Zsh – Try It Online")
[Tryine!](https://tio.run/##qyrO@P@/PCMzJ1XB0LaUC8rSts2EMo20bSsQTCTREq7SvJLMHIUkFYf//wE "Zsh – Try It Online")
[nline!](https://tio.run/##qyrO@P@/PCMzJ1XByDaVC8rStq1AMDMRzBKu0rySzByFJBWH//8B "Zsh – Try It Online")
Each line is a program.
## Explanation
The idea is to use an infinite loop (well, 10 nested infinite loops), but, over the course of the 10 programs, construct and execute a string that will exit the loops.
If any program is removed, the string will no longer be a snippet that correctly exits, and the program will continue to loop.
The code to halt is built up by `1=u` `1+=i` etc. The string `uiltin` is stored in `$1`, and `exit` is stored in `$2`. Then, `$@` represents all the assigned numeric variables; a `b` is prepended to those to make `builtin exit`, which is executed and halts the program.
## Notes
* All the loops have no body - the code is entirely in the condition. Zsh seems not to care, though.
* The challenge states:
>
> A program is *valid* if [...] an interpreter finishes any pre-execution check (syntax parser, type checker, and any others if present) without error.
>
>
>
Despite producing lots of errors, the program(s) meet these criteria because they only occur at *runtime*. (that kind of comes with the territory when golfing in zsh)
* The `b` is prepended at execution instead of being made part of the string build-up, because it prevents the program where only `2` gets assigned to from halting - it will always result in `bexit` instead of `exit` (this is essentially a problem of irreducibility). There are also some substrings of `uiltin exit` that might be valid commands, which could end the `until` loop, but none exist once a `b` is prepended.
* `builtin` is a pre-command modifier that disambiguates in case `exit` is a user-defined function, but in this case it serves only to get us to 10 programs of which none can be removed.
* `in` is appended in one go instead of `i` and `n` separately because the 10 programs must be distinct, and `1+=i` is already used.
* For the first assignments to `1` and `2`, we can use `=` instead of `+=` to save a byte.
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), ~~25~~ 22 bytes (10 programs)
```
12+3+4+5+6+7+8+"#"`#@_
```
[Try it online!](https://tio.run/##S0pNK81LT/3/39BI21jbRNtU20zbXNtCW0lZKUHZIf7/fwA "Befunge-93 – Try It Online")
Thanks JoKing for the suggestion (-3 bytes).
**Exaplanation**
The programs are:
```
1 Push 1
2 Push 2, pop two value and push the sum
+ Pop two value and push the sum
3+ Push 3, pop two value and push the sum
4+ Same with 4
5+ ...
6+
7+
8+
"#"`#@_ Last program, it will halt if the stack has a number >35 in it:
"-" Push 35
` Pop two value, compare, push 1 if greater than 35
# Skip the next char (v)
@ End program
_ Pop one value, go left if 1, right otherwise
```
The first 9 programs cannot halt, because there is no halt instruction.
The last program takes a number from the stack, and compares it to 35: if it is greater than 35 (the sum is 36), then will halt the program; otherwise, it will let the PC run right, which will repeat the program and loop forever.
Removing any combination of program 1 to 9 will make the sum to be less than 36, so the program will never halt (comparison will always fail).
In theory, it can be extended by adding more number, and changing the value of the comparison in the last program (depending on the size available in your Befunge implementation).
---
# [Befunge-93](https://github.com/catseye/Befunge-93), ~~63~~ 73 bytes (10 programs)
```
v
v>v
v >v
v >v
v >v
v >v
v >v
v >v
v >v
v v@
```
[Try it online!](https://tio.run/##S0pNK81LT/3/X6GMq8wOiBXABJSEUXAawUBiITPLHP7/BwA "Befunge-93 – Try It Online")
Thanks NickKennedy for the fix.
**Explanation**
Each line is a program.
The first 9 lines (i.e. programs) are redirecting the PC down. Since there is no end of program instruction, they will loop forever.
The 10th line is redirecting the PC down, followed by an halt program (@) instruction. If this is executed alone, the PC will loop in the vertical direction forever.
When all together, the PC will be able to get to the @ and halt the program.
Removing any one line will break the flow and will leave the PC loop forever vertically.
It can actually be expanded to 25 programs (which is the limit of the 80x25 code size of the befunge) by just adding more `v >v` lines with the appropriate indentation.
If you use an implementation of befunge without the 80x25 limit, then it can be exdended indefinitely.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 10 programs, 188 bytes
```
for(b=('a'in this);!b;);
for(c=this.b;!c;);
for(d=this.c;!d;);
for(e=this.d;!e;);
for(f=this.e;!f;);
for(g=this.f;!g;);
for(h=this.g;!h;);
for(i=this.h;!i;);
for(j=this.i;!j;);
for(var a;!this.j;);
```
[Try it online! (all, halts)](https://tio.run/##Lcg9DoMwDAbQq@AJGNq50icO4/w7Q0EB5fqpUvuNr3Ln2ze5nlf/jJHOtrljW3mV7/IUuXeQw475/pjxdiBvE3Q8KNhEnQCKNkkngpJN1kmgbFN0MqjYiE4BiU3VEVC16dwWBv173hg/ "JavaScript (V8) – Try It Online")
[Try it online! (not all, does not halt)](https://tio.run/##Lcg7DoQwDAXAq@AKKJYa6YnDOD/iFOwqoFw/q2BPOYUb377K7/m0vff0rYs7lplnuaYny72CHFaM98eIzYG8TdDxoGATdQIo2iSdCEo2WecEZRvRySCxKToCKjaN68Sgt8f1/gc "JavaScript (V8) – Try It Online")
Javascript hoists the definition of `a` to the top of the scope, so even though it is defined later `'a' in this` returns `true`.
[Answer]
# JavaScript, 10 programs / 271 bytes
*Saved 12+ bytes per program thanks to @tsh*
This is similar to the method used by @darrylyeo in [this answer](https://codegolf.stackexchange.com/a/222929/58563).
```
o={get g(){while(k);},set go(_){k--;}};k=9;o.g
o={get g(){for(;;)0}};o.g
o={get g(){for(;;)1}};o.g
o={get g(){for(;;)2}};o.g
o={get g(){for(;;)3}};o.g
o={get g(){for(;;)4}};o.g
o={get g(){for(;;)5}};o.g
o={get g(){for(;;)6}};o.g
o={get g(){for(;;)7}};o.g
o={get g(){for(;;)8}};o.g
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/37Y6PbVEIV1Dszotv0jD2lrToLbWOl8v/f9/AA "JavaScript (Node.js) – Try It Online") (non-halting)
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/37Y6PbVEIV1Ds7o8IzMnVSNb07pWpxgklK8Rr1mdratrXVtrnW1raZ2vl46kOi2/SMPaWtMAKIlVwhCXhBEuCWNcEia4JExxSZjhkjDHJWEBkfj/HwA "JavaScript (Node.js) – Try It Online") (halting)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 programs, 23 bytes
* `Wn17l"`
* `#`
* `#1`
* `#2`
* `#3`
* `#4`
* `#5`
* `#6`
* `#7`
* `#8`
[Try it online!](https://tio.run/##K6gsyfj/PzzP0DxHSVnZUNlI2VjZRNlU2UzZXNni/38A "Pyth – Try It Online")
### How it works
With all programs present, the concatenation is equivalent to this halting Python loop:
```
while 17 != len("##1#2#3#4#5#6#7#8"):
pass
```
If the first program is present but another is missing, the string will no longer have length 17 and the loop will run forever.
If the first program is missing but another present, the concatenation begins with `#`, which loops a block until an error is raised (which will never happen):
```
while True:
try:
while True:
try:
print(1)
while True:
try:
print(2)
while True:
try:
print(3)
while True:
try:
print(4)
while True:
try:
print(5)
while True:
try:
print(6)
while True:
try:
print(7)
while True:
try:
print(8)
except Exception:
break
except Exception:
break
except Exception:
break
except Exception:
break
except Exception:
break
except Exception:
break
except Exception:
break
except Exception:
break
except Exception:
break
```
[Answer]
# [GNU sed](https://www.gnu.org/software/sed/manual/sed.html), 10 programs, 99 bytes
```
:a s/^/A/
ba
```
```
:a :b bb
```
```
:b :c bc
```
```
:c :d bd
```
```
:d :e be
```
```
:e :f bf
```
```
:f :g bg
```
```
:g :h bh
```
```
:h :i bi
```
```
:i :j s/A//
Tj
```
## Explanation
[Meta consensus](https://codegolf.meta.stackexchange.com/a/5477/9486) lets sed programs take a single empty line as input (for, without that, sed simply won't do anything at all)
So, evidently, GNU sed will just let you define the same label multiple times, and all except the last one are ignored for execution purposes, which is nice for this challenge. Programs 1 through 9 each define a simple infinite loop (Program 1 does a bit more, which we'll get to in a minute)
```
:a ba
```
This defines a label `:a` and `ba` is effectively a `goto :a`. This program does nothing but loop forever. Then if we concatenate the second
```
:a ba :a :b bb
```
Now the `ba` goes to the *second* `:a` label, which effectively does nothing, and then we loop on `:b` forever. Each program "disarms" the prior one and them introduces its own loop.
Now, the final program
```
:i :j s/A//
Tj
```
First, we disarm the `:i` loop from the ninth program. Then we try to remove an `A` from the pattern space. The pattern space started out containing an empty string (remember, our input is a single empty line), so if we run Program 10 on its own, this substitute will *fail*. `Tj` is a conditional jump. It's a `goto :j` that only executes if the previous substitution *failed*. This is an infinite loop.
However, if Program 1 is in play, then the first thing we did was introduce an `A` at the beginning of the pattern space, which Program 10 happily removes and then the `Tj` doesn't execute since the substitution was successful.
The only way a concatenation of these programs can terminate is if the following conditions are met.
1. For N from 1 to 9, Program N contains an infinite loop trap that we can only escape if Program (N+1) is present.
2. Program 10 contains an infinite loop trap that we can only escape if Program 1 is present.
Hence, a nonempty concatenation terminates if and only if all ten programs are present.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 10 programs, 390 bytes
```
trap "while(($[a+=1]<55));do :;done" 0
trap "while(($[a+=2]<55));do :;done" 0
trap "while(($[a+=3]<55));do :;done" 0
trap "while(($[a+=4]<55));do :;done" 0
trap "while(($[a+=5]<55));do :;done" 0
trap "while(($[a+=6]<55));do :;done" 0
trap "while(($[a+=7]<55));do :;done" 0
trap "while(($[a+=8]<55));do :;done" 0
trap "while(($[a+=9]<55));do :;done" 0
trap "while(($[a+=10]<55));do :;done" 0
```
[Try it online!](https://tio.run/##S0oszvj/v6QosUBBqTwjMydVQ0MlOlHb1jDWxtRUU9M6JV/BCkjkpSopGHBhKjMiTpkxccpMiFNmSpwyM@KUmROnzII4ZZbEKTM0wKLu/38A "Bash – Try It Online")
## How?
Each line contains an exit handler that contains a while loop. The while loop will only halt if all the numbers 1..10 have been added to the variable $a. If any lines are missing, then the while condition will be true and will not halt.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 programs, ~~37~~ 35 bytes
```
L}n27$¿“¹1¿¹2¿¹3¿¹4¿¹5¿¹6¿¹7¿¹8¿¹9¿
```
[Try it online!](https://tio.run/##y0rNyan8/9@nNs/IXOXQ/kcNcw7tNDy0/9BOIxBhDCJMQIQpiDADEeYgwgJEWB7a//8/AA "Jelly – Try It Online")
## Individual programs with explanation
```
L}n27$¿“ | While not 27, take the length of the right argument
¹1¿ | While 1 do the identity function
¹2¿ | While 2 do the identity function
¹3¿ | While 3 do the identity function
¹4¿ | While 4 do the identity function
¹5¿ | While 5 do the identity function
¹6¿ | While 6 do the identity function
¹7¿ | While 7 do the identity function
¹8¿ | While 8 do the identity function
¹9¿ | While 9 do the identity function
```
When the whole lot is concatenated together, this checks the length of the string between `“` and the end of the program is 27.
Any subsequence of these programs that does not include the first has an infinite while loop, while programs including the first one will only halt if all of the others are present so that the length is correct.
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), score 10, 11 bytes
```
90.123456!;
```
[Try it online!](https://tio.run/##S8/PScsszvj/39JAz9DI2MTUTNH6/38A "Gol><> – Try It Online")
At 1 point short of perfect this is as close as I can come in Gol><>.
The first 9 characters `90.123456` are all their own programs with `!;` being the only two byte program.
Since it contains the only halt instruction `!;` must be included to halt. And since it has a `!` we can't simply get to `;` from the right. The only other way to get to `;` is with the teleport `.`. So `.` must be included as well. If `.` is first it will pop two zeros and teleport to itself creating an infinite loop, so something must be present before it. `0` causes the same type of infinite loop as before so `9` must be present as well. Now `0,9` is a location that can never be filled since we have no newlines. Thus any jump there creates an irretrievable infinite loop, we must have the `0` program as well. Now we know the `.` must take us to `9,0`, and of course `;` must be the character there. In order for this to happen we must have all the characters present.
This is the perfect score for Gol><> because if it were 10, 1 byte programs there would have to be a 1 byte program which halts on it's own. As suggested by @Bubbler it might be possible to use source modification to insert a halt command, however since unknown commands crash Gol><> a `p` on it's own will override itself with a zero byte and halt with a crash.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 10 programs, ~~206 196~~ 174 bytes
## Whole program: (174 bytes)
```
i=1
while i:
0#while 1:
i=-8#while i:=2:
i+=1#while i:=3:
i+=1#while i:=4:
i+=1#while i:=5:
i+=1#while i:=6:
i+=1#while i:=7:
i+=1#while i:=8:
i+=1#while i:=9:
i+=1
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P9PWkKs8IzMnVSHTikvBQBnCNgSyM211LZRhUrZGIBFtW0OEiDGGiAmGiCmGiBmGiDmGiAWGiCVU5H9BUWZeiYZSSEaqQkFRfnpRYq5CRmKxQlpmXmZxRmqKkuZ/AA "Python 3.8 (pre-release) – Try It Online")
## Program 1: (16 bytes)
```
i=1
while i:
0#
```
## Program 2: (14 bytes)
```
while 1:
i=-8#
```
## Program 3 to 9: (18 char each)
```
while i:=2:
i+=1#
```
...
```
while i:=8:
i+=1#
```
## Program 10: (17 char)
```
while i:=9:
i+=1
```
## How it works:
* we set i to 1
* In the first program: `while i: 0` if `i` is not equal to `0` (wich is True at the start) we loop into the program. Otherwise the program finish.
* In the second program, if the first program is missing, `while 1` will loop indefinitely. We assign `i` to -8. If the second program is missing, `i` will always be strictly positive and the program will loop indefinitely
* Then we increment `i` by `1` inside the first while loop and comment to neutralize the next `while` statement
* If all 10 programs have been executed, `i` is now equal to `0` and the program stop. Otherwise, the program loops and `i` is set back to `-8` in the seacond loop or will continue to be incremented.
thanks to Bubbler, who pointed me that programs should all be differents, which ended saving me many bytes :p
Thanks to Wheat Wizard♦ which inspired me to improve my solution
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 10 programs, 127 bytes
The solution where the program reads its own source code I found is:
```
while len(next(open(__file__)))<127:0#while 1:0#while 2:0#while 3:0#while 4:0#while 5:0#while 6:0#while 7:0#while 8:0#while 9:0
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/vzwjMydVISc1TyMvtaJEI78AyIqPTwMKxsdramraGBqZWxkoQ1QZwllGcJYxnGUCZ5nCWWZwFsIUCzjL0srg/38A "Python 3.8 (pre-release) – Try It Online")
It is ... well ... a solution. Not clever, not even beautiful, but it is accepted so ...
### First program :
```
while len(open(__file__).read())<127:0#
```
exit if the program is at least 127 char long. Else loop
### Program 2 to 9:
```
while 1:0#
```
...
```
while 8:0#
```
Just infinite loop
### Program 10:
```
while 9:0
```
Same but without comment
[Answer]
# [Labyrinth](https://github.com/m-ender/labyrinth), score 10, 19 bytes
```
0 @
+-*&|$`"'
```
[Try it online!](https://tio.run/##y0lMqizKzCvJ@P/fQAECHLi0dbXUalQSlNT//wcA "Labyrinth – Try It Online")
Since Labyrinth programs operate by following the path formed by valid commands, solving this challenge in Labyrinth in its simplest form is about making sure the starting cell (the leftmost cell of the topmost row) is disconnected from the halt command `@` unless every piece appears in the program.
Whenever I thought I found something clever (which had 16 or 17 bytes), I was hit with a weird shortcut path. Also it doesn't help that a comment-only program isn't an infinite loop (the interpreter simply refuses to run it). So I decided to settle with this one, at least for now. (At least it's an improvement over the initial idea of 21 bytes)
```
0+-*&|$`"'
@
```
---
The fragments are:
```
0 @\n
+
-
*
&
|
$
`
"
'
```
Since every comment-only program halts, every fragment must contain at least one valid command. To avoid memory issues, the commands to form the no-op path were chosen so that the stack size or the number size doesn't grow infinitely when repeated.
```
All commands that pop and push something on the stack push a single 0
when run as the first command, and effectively do nothing otherwise
0 Multiply the top by 10 and add 0 (0 * 10 + 0 = 0)
+ Add two numbers (0 + 0 = 0)
- Subtract two numbers (0 - 0 = 0)
* Multiply two numbers (0 * 0 = 0)
& Bitwise & two numbers (0 & 0 = 0)
| Bitwise | two numbers (0 | 0 = 0)
$ Bitwise ^ two numbers (0 ^ 0 = 0)
` Negate top (-0 = 0)
" No-op
' Debugging no-op
```
It is obvious that we need the first program fragment (the only one containing `@`) to possibly halt. Then, since the `0` is the starting location, we need all the other 9 fragments to connect `0` to `@`.
[Answer]
# [Haskell](https://www.haskell.org/), score 10, 227 bytes
```
main=a;a=a where a=b;main=main;b=b where b=c;main=main;c=c where c=d;main=main;d=d where d=e;main=main;e=e where e=f;main=main;f=f where f=g;main=main;g=g where g=h;main=main;h=h where h=i;main=main;i=i where i=pure();main=main
```
[Try it online!](https://tio.run/##TclBCgIxDEDRq8xSz1D@YdI2bYIzIiPi8StKwGz@4n2T5033fa1D/I4UQba36ambUMsPvymVGl5pyRstvNGTd3p4R5MrGq6M5IMRPpjJJzN8YskNCzc8uePhzuN16uX6n2t9AA "Haskell – Try It Online")
Each program ends after the `where` except the last which just ends.
Here it is in a more readable manner.
```
main=a
a=a where
a=b
main=main
b=b where
b=c
main=main
c=c where
c=d
main=main
d=d where
d=e
main=main
e=e where
e=f
main=main
f=f where
f=g
main=main
g=g where
g=h
main=main
h=h where
h=i
main=main
i=i where
i=pure()
main=main
```
[Try it online!](https://tio.run/##dU5JDsMgDLznFXNsH@HHOGAWNamqVFWfT0NIEVsuxrMax@@HLEsIK/sn8cTE@DrZZAKY5n0eQhz7PtOc1YjU8ZYOQJEqPBHrc6t9gCadnDiJSEneWzsgJFV14kyB@gxgyHSpyNoKj5KAJdt@8S@4hhkXAI7c4HxSfMddtQCe/EVP1F6fTW73gZQLQ/gB "Haskell – Try It Online")
# Explanation
The idea here is to use variable shadowing to create a chain of assignments. If the chain is broken the shadow
means that we switch and define the variable in terms of itself an form a loop.
This is easier to see for just two programs.
```
main=a;a=a where a=pure();main=main
```
With just the first program
```
main=a;a=a where
```
`a` is a loop so `main` is a loop. But when we add the second `a` gets shadowed and now `a` is a halting program.
We do this several times each time changing the variable names so that the nothing can shadow something it is not supposed to.
[Answer]
# Lenguage, 10 programs, 2324143350556659959 bytes
```
-[]++++++++++++++++++
--[]++++++++++++++++
--[]++++++++++++++
--[]++++++++++++
--[]++++++++++
--[]++++++++
--[]++++++
--[]++++
--[]++
+) -.[]
---------------------------
>+-+-+-+-+-+-+-+-+<[]
201010101010101010367
```
Lacking the i-th program (\$i \in [2,10]\$), `>+-+-+-++[]` pattern appears (`-[]` when i=2).
Lacking the first several programs, `->+-+-+-+<[]` pattern is still an infinite loop, or `-.[]` if only the 10th one left, still infloop
[Answer]
# [Lost](https://github.com/Wheatwizard/Lost), Score 2, 5 bytes
```
/%
@/
```
[Try it online!](https://tio.run/##y8kvLvn/X1@Vy0H//38A "Lost – Try It Online")
The programs are
```
/%
```
and
```
@/
```
This works because any lost program that halts must have both `%` and `@`. Since `%` turns off the safety to allow halting and `@` actually does it. The simpler `%@` doesn't work because half the time the pointer is moving vertically and can only hit one of the two. In fact in order to *always* halt a lost program needs some kind of redirect in every column and row (technically there are some specific exceptions to this but lets not get into them), meaning that this is certainly the smallest program that always halts.
So we can't go shorter for score 2. But ...
# [Lost](https://github.com/Wheatwizard/Lost), Score 3, 5 bytes
```
%^
@>
```
[Try it online!](https://tio.run/##y8kvLvn/XzWOy8Hu/38A "Lost – Try It Online")
... we can increase the score at no cost to bytes!
The programs here are:
```
%^
```
```
```
```
@>
```
The second one being a single newline.
This is one of the specific exceptions to the one redirect in every row and column rule. It's the same length, but both of our redirects are in the same column since the other column automatically terminates by itself.
A program needs both `%` and `@` to halt at all so any program missing one of the first two mustn't halt. So we only need to check the case where program 2 is missing.
```
%^@>
```
Here there is no possible path from the `%` to the `@`. The redirects ensure it. So there is no way for this program to halt.
And of course this can't be beat since you can't make a shorter halting program.
# [Lost](https://github.com/Wheatwizard/Lost), Score 4, 7 bytes
```
%\<
<@^
```
[Try it online!](https://tio.run/##y8kvLvn/XzXGhsvGIe7/fwA "Lost – Try It Online")
Nothing much special here it's a modified version of the above. There might be a smaller program that scores 4. I'm not sure.
The programs here are
```
%
```
```
\
```
```
<
```
```
<@^
```
Once again since a program *needs* `%` and `@` to work so we have only to check
```
%<@^
```
```
%/<@^
```
```
%<
<@^
```
None of which halt.
# [Lost](https://github.com/Wheatwizard/Lost), Score 10, 19 bytes
```
%<ABCDE\<
<<<<<<<@^
```
[Try it online!](https://tio.run/##y8kvLvn/X9XG0cnZxTXGhssGAhzi/v//rxsGAA "Lost – Try It Online")
And here we have an extensible solution, adding 2 bytes for every 1 score (until we run out of noop bytes). It is modified from the score 4 solution. The programs are
```
%<
```
*Each letter is 1 program for 5 total*
```
\
```
```
<
```
```
<<<<<<
```
```
<@^
```
The first and last program are necessary because they have the `%` and `%`. Without the newline we will have something like
```
%<...<@^
```
Which can never have a path from `%` to `@`, so the newline is needed too. We can also treat the letters as interchangeable since they are all noops, so we are only concerned with *how many* letters are present. At this point we can say that the only way for a program made from these to halt is if `/` is exactly above the `@`. Since it can't approach from the left or the right due to `<` and `^`, and there is no other way to get a vertical direction on the first row. This tells us that `/` must be present, but also gives us a quick way of checking the programs.
Unfortunately there are still quite a few programs to check. In fact more than I think I want to list in this post. The checks are easy given what I've already shown so please have a go yourself if you doubt my work.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 4 bytes, 2 programs.
## #1
```
{
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=5&code=%7B&inputs=&header=&footer=) Simple forever loop. The `5` flag makes it terminate after 5 seconds so it doesn't jam up the interpreter.
## #2
```
0|{
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=5&code=0%7C%7B&inputs=&header=&footer=) Another simple loop.
## Halting program
```
{0|{
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%7B0%7C%7B&inputs=&header=&footer=)
This works because `|` is a branch in structure when in a structure, but does nothing when in the main scope. So in the second one, it pushes 0 then executes a forever loop, but in here, it executes a loop containing a forever loop with 0 as the condition, so the inside loop is never run and the program halts.
Note that like TIO, the Vyxal interpreter times out after 60 seconds to avoid breaking, but if that was removed these two would run forever.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 19 bytes / 3 programs
## #1
```
`{`{`
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=5&code=%60%7B%60%7B%60&inputs=&header=&footer=)
## #2
```
{`{`
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=5&code=%7B%60%7B%60&inputs=&header=&footer=)
## #3
```
`0|}0|{`{`
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=5&code=%600%7C%7D0%7C%7B%60%7B%60%0A&inputs=&header=&footer=)
## Concatenated
```
`{`{`{`{``0|}0|{`{`
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=5&code=%60%7B%60%7B%60%7B%60%7B%60%600%7C%7D0%7C%7B%60%7B%60&inputs=&header=&footer=)
A quite different approach to what I had before.
With NOPS removed, it becomes:
```
{ # While...
{ } # While
0 # 0
| # Do nothing
0 # 0
| # Do..
{ # Forever loop, never executed
```
[Answer]
# [Scala Interpreter], 10+ programs, 265 bytes
This challenge is impossible to solve in languages that require a global program body around their code.
Luckily, Scala *Interpreter* is a way to bypass this issue :)
However, the challenge is still hard to solve in a language that requires to declare variables before using them and that does not provide a simple global mutable context to share information between the subprograms. However, the necessary information sharing can be achieved indirectly by affecting the global state of the JVM.
So, here are the 10 programs (one per line). Of course, it can be extended to any number of programs:
```
new java.util.Timer("1");
new java.util.Timer("2");
new java.util.Timer("3");
new java.util.Timer("4");
new java.util.Timer("5");
new java.util.Timer("6");
new java.util.Timer("7");
new java.util.Timer("8");
new java.util.Timer("9");
while(Thread.activeCount!=10){};sys.exit
```
**Explanation**: Every instantiation of a new Timer creates a new background thread that prevents the program from stopping. Further, the 10th program runs forever if the number of threads (incl. main thread) is not 10. Thus, the total number of threads is the indirectly affected "global variable" here.
No concatenation of 1..9 programs halts, for example:
* `scala -e 'new java.util.Timer("2");'`
* `scala -e 'new java.util.Timer("1");new java.util.Timer("5");'`
* `scala -e 'while(Thread.activeCount!=10){};sys.exit'`
* `scala -e 'new java.util.Timer("4");while(Thread.activeCount!=10){};sys.exit'`
Only when concatenating all 10 sub-programs, the resulting program will halt.
You can try out this behavior in TIO:
[Try it online!](https://tio.run/##ddC9DoJAEATg3qdYqaAB8d8YC2NlYSUvcMImtwQPvFv@Qnj28@y9ZjLJl0wxJheVsPWrxJzhIUgBDoyqMHBtGpggSUDVjMBSsAsyIFEUqME1B6Dx05LGAl4jPH9bcFeMutHo0irsoRSdiFumKs7ojToM0iBa/IW1DzY@2Ppg54O9Dw4@OPrg5KCXVGGYSe1OiUXO1OGtbhUvL@kqmuazGU2MA7Gd7Rc "Scala – Try It Online")
This approach does also work via Copy&Paste into the Scala REPL or to some Scala IDE, but then you need to replace the literal `10` by `11`, since in this case another JVM thread is running in the background :)
[Answer]
# TypeScript Types, 10 programs, 630 bytes
```
interface X{a:keyof{b,c,d,e,f,g,h,i,j}extends keyof X?0:X["a"]}
interface X{b:keyof{a,c,d,e,f,g,h,i,j}extends keyof X?0:X["b"]}
interface X{c:keyof{a,b,d,e,f,g,h,i,j}extends keyof X?0:X["c"]}
interface X{d:keyof{a,b,c,e,f,g,h,i,j}extends keyof X?0:X["d"]}
interface X{e:keyof{a,b,c,d,f,g,h,i,j}extends keyof X?0:X["e"]}
interface X{f:keyof{a,b,c,d,e,g,h,i,j}extends keyof X?0:X["f"]}
interface X{g:keyof{a,b,c,d,e,f,h,i,j}extends keyof X?0:X["g"]}
interface X{h:keyof{a,b,c,d,e,f,g,i,j}extends keyof X?0:X["h"]}
interface X{i:keyof{a,b,c,d,e,f,g,h,j}extends keyof X?0:X["i"]}
interface X{j:keyof{a,b,c,d,e,f,g,h,i}extends keyof X?0:X["j"]}
```
[Try It Online!](https://www.typescriptlang.org/play?strict=false&noImplicitAny=false#code/JYOwLgpgTgZghgYwgAgBoG84C4DWECeA9jOgEYA0C5AJuROTOQObkAW5w5AVgL4QAekENQDOyPERhoA-AAYsqANoAiOMoC6PAFChIsRCgylcBYpko06DZmw7c+giMLETiM+UuWkN23dHhIaOgIJpLmFLT0jCzsnLwCQqLiplKocgoqCD464P4GQdShZnDkFFRRNrH2CU5JrqnpntTZfvqBGBBFJCVlltG2cQ6JLinuGcoQLblthugwXeEWkZV28Y7OyZJjnjBTegGzTAs9S1aMVWvDm25pHipMe3nt6KzHpacVLIM1G-XbKqxHjMgsA3r1lv12JdaiMtrdxsAgQcglwwR9rDEOEMYdcGndlFwfEA)
([with one program removed](https://www.typescriptlang.org/play?strict=false&noImplicitAny=false#code/JYOwLgpgTgZghgYwgAgBoG84C4DWECeA9jOgEYA0C5AJuROTOQObkAW5w5AVgL4QAekENQDOyPERhoA-AAYsqANoAiOMoC6PAFChIsRCgylcBYpko06DZmw7c+giMLETiM+UuWkN23dHhIaOgIJpLmFLT0jCzsnLwCQqLiplKocgoqCD464P4GQdShZnDkFFRRNrH2CU5JrqnpntTZfvqBGBBFJCVlltG2cQ6JLinuGcoQLblthugwXeEWkZV28Y7OyZJjnjBTegGzTAs9S1aMVWvDm25pHipM2QD0j60HQazHpacVLIM1G-VtipWHs8u10MBPr1lv12JdaiMtrdxsBQTMglwod9rDEOEMEdcGndlFwfEA))
Each line is its own program, and newlines between the programs are optional.
"Does not halt" is hard to define in TypeScript Types, so this uses the closest analog: a type that resolves to itself, resulting in an infinite loop.
Technically, the 'interpreter' still halts, but with an error; if this is problematic, than this program can be considered to be written in TypeScript Types\*, which is like TypeScript Types except any errors cause the 'interpreter' to never halt.
Note that this requires the flag `noImplicitAny: false`; this is the default in `tsc` itself, but not in the playground.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 96 bytes, score 10
```
Wα«≔⁻αAαWα«≔⁻αBαWα«≔⁻αCαWα«≔⁻αDαWα«≔⁻αEαWα«≔⁻αFαWα«≔⁻αGαWα«≔⁻αHαWα«≔⁻αIαWα«≔⁻αJKLMNOPQRSTUVWXYZα
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9nu3nNh5a/ahzyqPG3ec2Op7biCbihCHijCHigiHiiiHihiHijiHigSHiiSHi5e3j6@cfEBgUHBIaFh4RGXVu4///AA "Charcoal – Try It Online") Explanation: Each loop subtracts a different substring of the predefined uppercase alphabet, so the program will only finish if all of the letters get subtracted. The programs can of course be concatenated in any order. As ten separate programs:
```
Wα«≔⁻αAα
Wα«≔⁻αBα
Wα«≔⁻αCα
Wα«≔⁻αDα
Wα«≔⁻αEα
Wα«≔⁻αFα
Wα«≔⁻αGα
Wα«≔⁻αHα
Wα«≔⁻αIα
Wα«≔⁻αJKLMNOPQRSTUVWXYZα
```
This can be trivially extended to 26 programs by subtracting each letter separately. Furthermore, this can be trivially extended to 95 programs by subtracting from the whole printable ASCII character set instead of just the uppercase alphabet. (It might even be possible to extend this up to 150 programs by mixing the approaches.)
[Answer]
# [Julia 0.6](http://julialang.org/), 10 programs, ~~275~~ 256 bytes
```
!x=while x<1end
e+=1
!01
!x=while x*e<4end
e+=1
!01
!x=while x*e<5end
e+=1
!01
!x=while x*e<6end
e+=1
!01
!x=while x*e<7end
e+=1
!01
!x=while x*e<8end
e+=1
!01
!x=while x*e<9end
e+=1
!01
!x=while x*e<10end
e+=1
!01
!x=while x*e<11end
e+=1
!01
while e<11end
```
[Try it online!](https://tio.run/##yyrNyUw0@/9fscK2PCMzJ1WhwsYwNS@FK1Xb1pBL0QCI4RJaqTYmuKVMcUuZ4ZYyxy1lgVvKEreUoQEeOVSfQSSgwv//AwA "Julia 0.6 – Try It Online")
[ry it online!](https://tio.run/##yyrNyUw0@//fkEuxwrY8IzMnVaFCK9XGJDUvhStV2xYobIAmZYpbygy3lDluKQvcUpa4pQwN8MgZoshBJKDC//8DAA "Julia 0.6 – Try It Online")
[Try it line!](https://tio.run/##yyrNyUw0@/9fscK2PCMzJ1WhwsYwNS@FK1Xb1pBL0QCI4RJaqTYmuKVMcUuZ4ZayxC1laIBHDtWNEAmo8P//AA "Julia 0.6 – Try It Online")
[Try it onlin!](https://tio.run/##yyrNyUw0@/9fscK2PCMzJ1WhwsYwNS@FK1Xb1pBL0QCI4RJaqTYmuKVMcUuZ4ZYyxy1lgVvKEreUoQEeOWSf/f8PAA "Julia 0.6 – Try It Online")
the separation between the programs is between each `!0` and `1`
uses Julia 0.6 to be able to redefine `e` (the euler constant)
[Answer]
# [Forte](https://esolangs.org/wiki/Forte), 10 programs, 96 bytes
```
9LET0=1
10LET1=2
11LET2=3
12LET3=4
13LET4=5
14LET5=6
15LET6=7
16LET7=8
17LET8=21
20LET21=0
21END
```
Each line is a program, except that the last two lines together constitute the tenth program.
* [Try it online!](https://tio.run/##FcwpDoBAEARA36/Znj0R7VhHUHwBLAnh/8PgStV1P@/pvmzzSCKYApSBDJgyaIGsAuZAUQVLoKqBNdDUwRboGmAPDBlhf2RUgnHuq/sH "Forte – Try It Online")
* [ry it online!](https://tio.run/##FcwrDoAwEARQP6fpbL9mHHUE1SuAJSHcf1ncU@@6n/d0Z9rnogxkwJRBC2QVMAeKKlgCVQ2sgaYOtkDXAHtgyAj7I6MSjPPY3D8)
* [Try it onlin!](https://tio.run/##DcYpEoBAEANAn9dsZk9EJA7JF8BSRfH/Ia36ft7vytyO/SwiWBwqQDqhCoZT1cDqNHWwOV0D7M7QBIcztcDpLAWR@QM)
* [Try t online!](https://tio.run/##FcspDoBAEARA36/Znj0R7VhHUHwBLAnh/8PgytR1P@/pvmzzSCKYApSBDJgyaIGsApZAVQNroKmDLdA1wB4YMsL@b1SCce6r@wc)
* [e!](https://tio.run/##S8svKkn9/9/IwMc1xMjQ1oDLyNDVz@X/fwA)
### Explanation
Forte is a language built around redefining numbers. Execution control is achieved by redefining line numbers, thereby shuffling statements around.
The only way to exit is via the `END` statement. So right off the bat, if the tenth program is missing, there is no way to exit and the program loops forever.
If the tenth program is present but one of the earlier programs is missing, the `LET` statement on line 20 redefines the number 21 to be some value between 0 and 8 (depending on which of lines 9 through 16 were able to run). Since this number is less than the current line number of 20, the `END` statement moves to before the instruction pointer and is never executed. The program proceeds to loop infinitely.
If all ten programs are present, lines 9 through 17 redefine 0 (through a series of steps) to equal 21. Then line 20 redefines 21 to equal 21 (no change). Execution proceeds to line 21, which ends the program.
(I'm not sure whether all implementations of Forte will behave this way, but [Forter](https://github.com/judofyr/forter), the version on TIO, does. This behavior seems to be in line with the description in the Esolangs article, too.)
[Answer]
# [Perl 5](https://www.perl.org/), 10+ programs, 184 bytes
```
BEGIN{s//t/}{redo}BEGIN{s//i/}{redo}BEGIN{s//x/}{redo}BEGIN{s//4/}{redo}BEGIN{y/4/5/}{redo}BEGIN{y/5/6/}{redo}BEGIN{y/6/7/}{redo}BEGIN{y/7/8/}{redo}BEGIN{y/8/e/}{redo}BEGIN{eval}{redo}
```
[Try it online!](https://tio.run/##K0gtyjH9/9/J1d3Tr7pYX79Ev7a6KDUlvxYukokhUoEhYoIqUgkUMEUXMtU3Qxcy0zdHFzLXt0AXstBPRRVKLUvMgQr8/w8A "Perl 5 – Try It Online")
With newlines added for readability:
```
BEGIN{s//t/}{redo}
BEGIN{s//i/}{redo}
BEGIN{s//x/}{redo}
BEGIN{s//4/}{redo}
BEGIN{y/4/5/}{redo}
BEGIN{y/5/6/}{redo}
BEGIN{y/6/7/}{redo}
BEGIN{y/7/8/}{redo}
BEGIN{y/8/e/}{redo}
BEGIN{eval}{redo}
```
`{redo}` is a short infinite loop in perl. `BEGIN` blocks run before everything else, so all we need to do is exit from a `BEGIN` block.
To do this, we build the string `exit` and then `eval` it in a `BEGIN` block. `s//whatever/` is a concise way to prepend `whatever` to the global variable `$_`, and then `eval` evaluates that string. The first four programs set `$_` to `4xit` and then the next programs use the transliteration operator `y///` to successively change the `4` to various other numbers and finally to `e`.
Anything besides `exit` will do nothing when `eval` is run, and of course removing `eval` will keep the program from exiting, so the program will run forever.
This method can be extended to an arbitrary number of programs with additional uses of `y///` and `s///`.
[Answer]
# [R](https://www.r-project.org/), 10 programs, ~~156~~ 151 bytes
```
while(T<-T*2)1-while(T<-T^2)1-while(T<-T*3)1-while(T<-T*4)1-while(T<-T*5)1-while(T<-T*6)1-while(T<-T*7)1-while(T<-T*8)1-while(T<-T*9)1-while(T<-T<6e5)1
```
[Try it online!](https://tio.run/##K/r/vzwjMydVI8RGN0TLSNNQF8GNQ@VqGaNyTVC5pqhcM1SuOSrXApVricK1MUsFGvb/PwA "R – Try It Online")
## Separate programs:
```
while(T<-T*2)1
while(T<-T^2)1
-while(T<-T*3)1
-while(T<-T*4)1
-while(T<-T*5)1
-while(T<-T*6)1
-while(T<-T*7)1
-while(T<-T*8)1
-while(T<-T*9)1
-while(T<-T<6e5)1
```
The full program works by starting with T (which starts at `TRUE` and becomes 1 when used arithmetically) and then multiplied by each number from 2 to 9 as well as squaring it (after `T<-T*2`). The last program compares T to 6e5, at which point all of the comparisons will equal 0.
Separately, no combination of programs will ever reach 0 since anything excluding the last program will just head for +infinity, while any combination including the last program will evaluate to `TRUE` unless all of the prior programs were present.
If any subsequence without the first program did complete its `while` loop, the unary minus would throw an error, but since they never do, no error is generated.
Thanks to @RobinRyder for saving a byte!
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 10 progs, 27 bytes, take 3.
```
{`{
{1
{2
{3
{4
{5
{6
{7
{8
`L17<|`{
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%7B%60%7B%7B1%7B2%7B3%7B4%7B5%7B6%7B7%7B8%60L17%3C%7C%60%7B&inputs=&header=&footer=)
I finally figured out what the others are doing. This basically checks if the string between the backticks' length is 17, and if not loops forever.
No trailing newlines, they're just formatted like this for readability.
Any character except `X` and `|` can be used instead of the digits.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes, score 6
```
≔⁰ψWα«≔⁰αWβ«≔⁰βWγ«≔⁰γWφ«≔⁰φWχ«≔⁰χWψ«
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R55RHjRvOd7zfs/3cxkOrIdxzG0HcTXDuJhB3M5y7Gcg93wbjnm8Dcdvh3HYQt@PQ6v//AQ "Charcoal – Try It Online") Explanation: This is the concatenation of six six-byte programs. Each program sets a predefined variable to zero and then loops over another predefined variable. This means that no program will finish except for the concatenation of all six, which will ensure that all of the predefined variables are set to zero, causing all of the loops to terminate. (Concatenating the programs in a different order won't work because the first program will prevent the final program's loop from executing, preventing further programs from clearing the first program's loop variable.) As six separate programs:
```
≔⁰ψWα«
≔⁰αWβ«
≔⁰βWγ«
≔⁰γWφ«
≔⁰φWχ«
≔⁰χWψ«
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 114 bytes, 10 programs
```
1/($.-40)while 99while$.+=11while$.+=07while$.+=06while$.+=05while$.+=04while$.+=03while$.+=02while$.+=01while$.=1
```
[Try it online!](https://tio.run/##KypNqvz/31BfQ0VP18RAszwjMydVwdISTKvoadsaGsKZBuYIphmCaYpgmiCYxgimEYIJM8zW8P9/AA "Ruby – Try It Online")
The programs break down like this:
```
1/($.-40)while 9
```
```
9while$.+=1
```
```
1while$.+=0
```
```
7while$.+=0
```
...
```
1while$.=1
```
The `1/($.-40)` causes a `ZeroDivisionError` if all the other snippets successfully incremented the counter `$.` to `40`, breaking out of all of the loops. If any parts are missing, `$.` will be less than `40` and the division will work, so the program will continue to loop.
Because the inner loop never terminates, the outer loops can never increment `$.` more than once, so there's no opportunity for `$.` to reach 40 except if all the programs are there.
[Try nline!](https://tio.run/##KypNqvz/31BfQ0VP18RAszwjMydVwdISTKvoadsaGsKZBqYIpgmCaYxgGiGYMG22hv//AwA "Ruby – Try It Online")
[y it online!](https://tio.run/##KypNqvz/37I8IzMnVUVP29bQEM40MEcwzRBMUwTTBME0RjCNEEyYYbaG//8DAA "Ruby – Try It Online")
[Tre!](https://tio.run/##KypNqvz/31BfQ0VP18RAszwjMydVwdIQTKvo2Rr@/w8A "Ruby – Try It Online")
[Answer]
# [Klein](https://github.com/Wheatwizard/Klein) 000, Score 10, 17 bytes
```
ABCDEFG\
....!><@
```
[Try it online!](https://tio.run/##y85Jzcz7/9/RydnF1c09hksPCBTtbBz@//9vYGAAAA "Klein – Try It Online")
This is a modification of [my lost answer](https://codegolf.stackexchange.com/a/226845/56656) so to get a good idea of how this works I recommend reading that explanation. Since Klein is not a language designed to torture the programmer, this ends up being 2 bytes shorter.
The programs are:
*The 7 letters*
```
\
```
```
```
*(Just a newline)*
```
....!><@
```
This works of an alignment principle. The `/` has to be above the `@` or you are not going to reach it. There are some special bits `!><` for example is a trap that catches anything going rightwards, which is there for when the newline is removed.
[Answer]
# [PHP](https://php.net), 10+ programs; ~~342~~ ~~134~~ ~~127~~ ~~124~~ ~~123~~ 116 bytes.
Byte count for PHP assumes you don't require and count the 8 characters of the surrounding `<?php ?>` tags for each program; if so, add 80 bytes.
```
while(!file(__FILE__)[9]);die();
for(;;);
foR(;;);
fOr(;;);
fOR(;;);
For(;;);
FoR(;;);
FOr(;;);
FOR(;;);
while(1);
```
I realized that `FOR` is case-insensitive, so I could use seven more unique `for`s, saving 7 bytes.
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 10 programs, 13 bytes
```
~1\-2*4+7`#@_
```
[Try it online!](https://tio.run/##S0pNK81LT/3/v84wRtdIy0TbPEHZIf5/HZchVwyXLpcRlxaXCZc2F0iUK/4/AA "Befunge-93 – Try It Online")
I think there's at least one more byte that can golfed off this. 9 of the programs are one byte apiece, with the last being `7`#@`. The initial `~1\-2*4+` generates the number `8`, with any lesser combination generating a smaller number. This then uses the `7`#@_` to only terminate if the number is bigger than 7. Note that if the `7`#@` section is removed, the program has no way to terminate, and if the `_` is removed, there is no way for the pointer to travel left, and therefore no way to execute the `@`.
] |
[Question]
[
### Monopoly Board
For this code-golf challenge we will be building the board game Monopoly.
### Rules:
* Take no input.
* Output a 11x11 board where each ASCII character forming the board is the first letter of each space of the U.S. version of the Monopoly board.
* The characters must be separated by spaces.
* `Go` should start in the bottom right.
The exact string to produce is
```
F K C I I B A V W M G
N P
T N
C C
S P
P S
V C
S P
E L
S B
J C V C O R I B C M G
```
Note that from bottom right to bottom left the squares are as follows:
```
G --> Go
M --> Mediterranean Avenue
C --> Community Chest
B --> Baltic Avenue
I --> Income Tax
...
J --> Jail
```
**Edit**
Wow! you guys sure liked this one! :)
[Answer]
## [Retina](http://github.com/mbuettner/retina), 74 bytes
```
FKCIIBAVWMGN_PT_NC_CS_PP_SV_CS_PE_LS_BJCVCORIBCMG
S_`(._.)
_
9$*
\B
1
```
The third to last and last lines should contain a single space.
[Try it online!](http://retina.tryitonline.net/#code=CkZLQ0lJQkFWV01HTl9QVF9OQ19DU19QUF9TVl9DU19QRV9MU19CSkNWQ09SSUJDTUcKU19gKC5fLikKXwo5JCoKXEIKIAoxCiA&input=)
### Explanation
```
FKCIIBAVWMGN_PT_NC_CS_PP_SV_CS_PE_LS_BJCVCORIBCMG
```
This replaces the (empty) input with the string on the second line.
```
S_`(._.)
```
This is split stage, which splits the string around matches of the regex `(._.)` (that is, any three characters with a `_` in the middle). The reason we put the whole regex in a group is that split stages also return the results of capturing groups. E.g. splitting `abcd` around `bc` gives `[a, d]`, but splitting it around `b(c)` gives `[a, c, d]`. This way we get all the `._.` parts on separate lines but also the 11-character parts at the beginning and end. We use the `_` option to omit empty results between the individual `._.` matches. The result would be this:
```
FKCIIBAVWMG
N_P
T_N
C_C
S_P
P_S
V_C
S_P
E_L
S_B
JCVCORIBCMG
```
Next we process the underscores:
```
_
9$*
```
This replaces each underscore with nine `1`s. The reason we use `1`s here instead of spaces immediately is that it makes it easier to insert the padding spaces next.
```
\B
```
Remember that there's a space on the second line. This inserts a space in every position that *isn't* a word boundary, i.e. everywhere except at the beginning and end of the lines.
```
1
```
And finally, we replace all those `1`s with spaces as well.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 44 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“£ċ9NɲT⁴MỵƇñdMỊḞ*µ7Sʂɓ¢Ż}ạ¥ċwÞ’ḃ23ṣ4ịØAz⁶ṙ1G
```
[Try it online!](http://jelly.tryitonline.net/#code=4oCcwqPEizlOybJU4oG0TeG7tcaHw7FkTeG7iuG4nirCtTdTyoLJk8Kixbt94bqhwqXEi3fDnuKAmeG4gzIz4bmjNOG7i8OYQXrigbbhuZkxRw&input=)
### Idea
If we remove every second column and transpose rows with columns, we get the following board.
```
FNTCSPVSESJ
K C
C V
I C
I O
B R
A I
V B
W C
M M
GPNCPSCPLBG
```
Now, we can rotate each column one unit to the right, moving all remaining spaces to the right.
```
JFNTCSPVSES
KC
CV
IC
IO
BR
AI
VB
WC
MM
GGPNCPSCPLB
```
Then, we remove the remaining spaces and replace linefeeds with the letter **D**.
```
JFNTCSPVSESDCKDVCDCIDOIDRBDIADBVDCWDMMDGGPNCPSCPLB
```
Now, we replace each letter with its 1-based index in the alphabet.
```
10 6 14 20 3 19 16 22 19 5 19 4 3 11 4 22 3 4 3 9 4 15 9 4 18
2 4 9 1 4 2 22 4 3 23 4 13 13 4 7 7 16 14 3 16 19 3 16 12 2
```
Then, we convert this digit array from bijective base **23** to integer.
```
54580410997367796180315467139871590480817875551696951051609467717521
```
Now, we convert this integer to bijective base **250**.
```
2 232 57 78 163 84 132 77 228 144 27 100 77 176 195
42 9 55 83 167 155 1 210 125 211 4 232 119 20
```
Finally, we use these digits to index into [Jelly's code page](https://github.com/DennisMitchell/jelly/wiki/Code-page).
```
£ċ9NɲT⁴MỵƇñdMỊḞ*µ7Sʂɓ¢Ż}ạ¥ċwÞ
```
This is the encoded data we'll include in the program (**29 bytes**). To produce the desired output, we just have to reverse the steps above.
### Code
```
“£ċ9NɲT⁴MỵƇñdMỊḞ*µ7Sʂɓ¢Ż}ạ¥ċwÞ’ḃ23ṣ4ịØAz⁶ṙ1G Main link. No arguments.
“£ċ9NɲT⁴MỵƇñdMỊḞ*µ7Sʂɓ¢Ż}ạ¥ċwÞ’ Convert the string from bijective
base 250 (using the indices in
Jelly's code page) to integer.
ḃ23 Convert that integer to bijective
base 23.
ṣ4 Split the resulting array at
occurrences of 4.
ịØA Replace the remaining digits in the
resulting 2D array with the
corresponding uppercase letters.
z⁶ Zip/transpose rows and columns,
padding shorter rows with spaces.
ṙ1 Rotate the rows one unit down.
G Grid; join rows by spaces, columns
by linefeeds.
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~48~~ 47 bytes
Thanks to *Emigna* for saving a byte!
```
•(K·;“…¬È¦z"9äuŸé;TÞîÕs‡ÓÐV9XÒt\<•33B¾9ð×:S11ô»
```
**Explanation:**
First some compression. `•(K·;“…¬È¦z"9äuŸé;TÞîÕs‡ÓÐV9XÒt\<•` is a compressed version of the following number:
```
120860198958186421497710412212513392855208073968557051584380118734764403017
```
After that, this is converted to **base 33**, which results into the following string:
```
FKCIIBAVWMGN0PT0NC0CS0PP0SV0CS0PE0LS0BJCVCORIBCMG
```
The zeroes are replaced by **9 spaces**, using the following code `¾9ð×:`. After that, we `S`plit the string into characters and slice them into pieces of **11** elements (done with `11ô`). We get the following 2-dimensional array:
```
[['F', 'K', 'C', 'I', 'I', 'B', 'A', 'V', 'W', 'M', 'G'],
['N', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'P'],
['T', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'N'],
['C', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'C'],
['S', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'P'],
['P', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'S'],
['V', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'C'],
['S', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'P'],
['E', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'L'],
['S', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'B'],
['J', 'C', 'V', 'C', 'O', 'R', 'I', 'B', 'C', 'M', 'G']]
```
We *gridify* this array with `»` and output it implicitly.
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=4oCiKEvCtzvigJzigKbCrMOIwqZ6IjnDpHXFuMOpO1TDnsOuw5Vz4oChw5PDkFY5WMOSdFw84oCiMzNCwr45w7DDlzpTMTHDtMK7&input=)
[Answer]
## Python 2, 89 bytes
```
l='%s '*11+'\n'
print(l+'%s%20s\n'*9+l)%tuple("FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG")
```
Creates the template
```
? ? ? ? ? ? ? ? ? ? ?
? ?
? ?
? ?
? ?
? ?
? ?
? ?
? ?
? ?
? ? ? ? ? ? ? ? ? ? ?
```
to substitute in letters via string formatting. The template uses two types of lines:
* The outer line `l` of 11 copies of letter-plus-space, then a newline. It's also used for the first and last line. It has a trailing space.
* The inner line of a character, then a character preceded by 19 characters of padding spaces, then a newline. It's copied 9 times for the center lines.
Python 3.5 can save a byte with tuple unpacking `(*'...',)`.
[Answer]
## PowerShell v2+, ~~131~~ ~~123~~ ~~114~~ ~~110~~ 99 bytes
```
'F K C I I B A V W M G
N0P
T0N
C0C
S0P
P0S
V0C
S0P
E0L
S0B
J C V C O R I B C M G'-replace0,(" "*19)
```
This is just a literal string with newlines placed on the pipeline, with a little `-replace` at the end to turn the `0` into `19` spaces. The first and last lines are just verbatim. With only 10 spaces and little repetition otherwise, there wasn't enough room to golf them. This string is left on the pipeline, and output via implicit `Write-Output` happens at program completion.
```
PS C:\Tools\Scripts\golfing> .\take-a-ride-on-reading.ps1
F K C I I B A V W M G
N P
T N
C C
S P
P S
V C
S P
E L
S B
J C V C O R I B C M G
```
[Answer]
# Javascript ES6 [REPL](http://meta.codegolf.stackexchange.com/questions/7842/when-is-code-that-requires-a-repl-acceptable/7844#7844), ~~105~~ ~~102~~ 101 bytes
Not much interesting happening here.
Paste in the console to see the desired results
Saved 3 bytes thanks to @Arnauld
Saved 1 more byte thanks to @Neil
```
`FKCIIBAVWMG
N P
T N
C C
S P
P S
V C
S P
E L
S B
JCVCORIBCMG`.replace(/.( ?)/g,`$& `+`$1`.repeat(17))
```
```
a.innerHTML =
`FKCIIBAVWMG
N P
T N
C C
S P
P S
V C
S P
E L
S B
JCVCORIBCMG`.replace(/.( ?)/g,`$& `+`$1`.repeat(17))
```
```
<pre id=a>
```
[Answer]
# [///](http://esolangs.org/wiki////), ~~100~~ 98 bytes
```
/s/ //p/ssss //q/pC
SpP
//!/ C /F K!I I B A V W M G
NpP
TpN
CqPpS
VqEpL
SpB
J!V!O R I B!M G
```
[Try it online!](//slashes.tryitonline.net#code=L3MvICAgIC8vcC9zc3NzICAgLy9xL3BDClNwUAovLyEvIEMgL0YgSyFJIEkgQiBBIFYgVyBNIEcgCk5wUApUcE4KQ3FQcFMKVnFFcEwKU3BCCkohViFPIFIgSSBCIU0gRyA)
For some mysterious reason, there seem to be trailing spaces after the `G`s. Without them, my code would have been 96 bytes.
Thanks to [42545 (ETHproductions)](/users/42545) and [56258 (daHugLenny)](/users/56258) for reducing 1 byte each!
[Answer]
# [Turtlèd](https://github.com/Destructible-Watermelon/Turtl-d), 72 bytes
```
"K C I I B A V W M G">"GPNCPSCPLBG">"G M C B I R O C V C J">"JSESVPSCTNF
```
[Try it online](http://turtled.tryitonline.net/#code=IksgQyBJIEkgQiBBIFYgVyBNIEciPiJHUE5DUFNDUExCRyI-IkcgTSBDIEIgSSBSIE8gQyBWIEMgSiI-IkpTRVNWUFNDVE5G&input=)
`>` rotates turtle, `"foo"` writes strings on grid. last `"` was elidable
[Answer]
# [V](http://github.com/DJMcMayhem/V), ~~75, 62~~, 59 bytes
```
iFKCIIBAVWMG
NPTNCCSPPSVCSPELSB
JCVCORIBCMG-ò9á lli
òÍ./&
```
[Try it online!](http://v.tryitonline.net/#code=aUZLQ0lJQkFWV01HCk5QVE5DQ1NQUFNWQ1NQRUxTQgpKQ1ZDT1JJQkNNRxstw7I5w6EgbGxpCsOyw40uLyYg&input=)
Since this codel contains non-ASCII characters, here is a hexdump:
```
0000000: 6946 4b43 4949 4241 5657 4d47 0a4e 5054 iFKCIIBAVWMG.NPT
0000010: 4e43 4353 5050 5356 4353 5045 4c53 420a NCCSPPSVCSPELSB.
0000020: 4a43 5643 4f52 4942 434d 471b 2df2 39e1 JCVCORIBCMG.-.9.
0000030: 206c 6c69 0af2 cd2e 2f26 20 lli..../&
```
Explanation. First, we enter the following text:
```
FKCIIBAVWMG
NPTNCCSPPSVCSPELSB
JCVCORIBCMG
```
Then, we `<esc>` back to normal mode. At this point, the cursor is on the third line on the last `G`. Conveniently, there is a command to put us on the first column of the line right above the cursor. That command is `-`. Then, once we end up on the second line (on the `N`), we run the following loop:
```
ò9á lli
ò
```
Explanation:
```
ò " Recursively:
9á " Append 9 spaces
ll " Move to the right twice. This will fail on the last time because there isn't a space to move into
i " Enter a newline
ò " End
```
Now, the buffer looks like this:
```
FKCIIBAVWMG
N P
T N
C C
S P
P S
V C
S P
E L
S B
JCVCORIBCMG
```
Now we use a compressed regex to replace each character with that character and a space. That's the `Í./&` part. This translates to the following vim regex:
```
:%s/./& /g
```
Which means:
```
:% " On any line
s/ " Substitute
./ " Any character with
& / " That same character and a space
g " Allow for multiple substitutions on the same line
```
[Answer]
# R, 149 146 bytes
Not so impressive but also not sure how this would be golfed. Exploiting `paste` somehow is my first guess. Compare to raw text of 241 bytes.
```
x=strsplit("NTCSPVSESPNCPSCPLB","")[[1]];cat("F K C I I B A V W M G\n");for(i in 1:9)cat(x[i],rep("",18),x[i+9],"\n");cat("J C V C O R I B C M G")
```
[R-fiddle](http://www.r-fiddle.org/#/fiddle?id=7yy7jpqu&version=2)
[Answer]
## Python 2, 108 bytes
Slightly different than the other python answer, using no replaces, only string joins.
```
print'\n'.join(map(' '.join,['FKCIIBAVWMG']+map((' '*9).join,zip('NTCSPVSES','PNCPSCPLB'))+['JCVCORIBCMG']))
```
[Answer]
## Perl, 90 bytes
Pretty boring approach, can't think of a better way to reduce... Requires `-E` at no extra cost. Outputs an additional space at the end of every line. -2 bytes thanks to [@Dada](https://codegolf.stackexchange.com/users/55508/dada)!
```
say"FKCIIBAVWMG
NZP
TZN
CZC
SZP
PZS
VZC
SZP
EZL
SZB
JCVCORIBCMG"=~s/Z/$"x9/ger=~s/./$& /gr
```
### Usage
```
perl -E 'say"FKCIIBAVWMG
NZP
TZN
CZC
SZP
PZS
VZC
SZP
EZL
SZB
JCVCORIBCMG"=~s/Z/$"x9/ger=~s/./$& /gr'
```
[Answer]
# Jolf, 72 bytes
```
Ζ0ρ,ahtht"111"'.d?=H♣Q♣+."FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG"wΖhζ♣
```
Replace all `♣` with `\x05`, or [try it here!](http://conorobrien-foxx.github.io/Jolf/#code=zpYwz4EsYWh0aHQiMTExIicuZD89SAVRBSsuIkZLQ0lJQkFWV01HTlBUTkNDU1BQU1ZDU1BFTFNCSkNWQ09SSUJDTUcid86WaM62BQ)
```
Ζ0ρ,ahtht"111"'.d?=H♣Q♣+."..."wΖhζ♣
Ζ0 ζ = 0
,ahtht"111" a box of width&height 11, with borders "1"
ρ '.d replace each char in that string with...
?=H♣ is it a space?
Q♣ if so, return two spaces.
otherwise
."..." get the Nth member of this string
wΖhζ where N = (++ζ) - 1
+ ♣ and add a space to the end
```
This gives the desired string.
[Answer]
# Java 7, ~~177~~ ~~165~~ ~~142~~ 131 bytes
```
String c(){return"FKCIIBAVWMG\nN_P\nT_N\nC_C\nS_P\nP_S\nV_C\nS_P\nE_L\nS_B\nJCVCORIBCGM".replace("_"," ").replace(""," ");}
```
-15 bytes thanks to *@BassdropCumberwubwubwub*.
-11 bytes thanks to *@Numberknot*.
**Ungolfed & test code:**
[Try it here.](https://ideone.com/SkdsIK)
```
class M{
static String c(){
return "FKCIIBAVWMG\nN_P\nT_N\nC_C\nS_P\nP_S\nV_C\nS_P\nE_L\nS_B\nJCVCORIBCGM"
.replace("_"," ").replace(""," ");
}
public static void main(String[] a){
System.out.print(c());
}
}
```
**Output:**
```
F K C I I B A V W M G
N P
T N
C C
S P
P S
V C
S P
E L
S B
J C V C O R I B C M G
```
[Answer]
# Befunge, 120 bytes
```
<v"FKCIIBAVWMG NPTNCCSPPSVCSPELSB $JCVCORIBCMG "
:<,*48 ,_v#-*48<
>1-:#v_\,>$52*, :48*-!#v_,54*
^,*84< ^p19*88$<
```
First line has the string to be printed in reverse (it looks like it's not, but the code is going backwards on that line). Second line prints the top and bottom rows. Third line and the left side of the fourth line print the middle rows, and the small chunk on the bottom right does an interesting thing: it moves the cursor back to the second row to print out the last line, but after finishing it, it quits.
As you can see on the first line, the strings are separated by spaces to distinguish between the first, middle, and last rows. The spaces can be anything else, and if I used ASCII characters 0-9, I could've easily saved 4 bytes. The $ you see is just a garbage character that has to be there and could be replaced with anything but a space.
[Answer]
# J, ~~77~~ 73 bytes
```
' FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG'{~_22}.\,0,.(*+/\),0=*/~5-|i:5
```
Note that 43 bytes, over half the total, are used just for the string `' FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG'`.
## Explanation
First, make a list
```
|i:5
5 4 3 2 1 0 1 2 3 4 5
5-|i:5
0 1 2 3 4 5 4 3 2 1 0
```
Then make its times table
```
*/~5-|i:5
0 0 0 0 0 0 0 0 0 0 0
0 1 2 3 4 5 4 3 2 1 0
0 2 4 6 8 10 8 6 4 2 0
0 3 6 9 12 15 12 9 6 3 0
0 4 8 12 16 20 16 12 8 4 0
0 5 10 15 20 25 20 15 10 5 0
0 4 8 12 16 20 16 12 8 4 0
0 3 6 9 12 15 12 9 6 3 0
0 2 4 6 8 10 8 6 4 2 0
0 1 2 3 4 5 4 3 2 1 0
0 0 0 0 0 0 0 0 0 0 0
```
Then test for equality with zero
```
0=*/~5-|i:5
1 1 1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1 1
```
Flatten it, find the cumulative sums, and multiply elementwise
```
,0=*/~5-|i:5
1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1
+/\,0=*/~5-|i:5
1 2 3 4 5 6 7 8 9 10 11 12 12 12 12 12 12 12 12 12 12 13 14 14 14 14 14 14 14 14 14 14 15 16 16 16 16 16 16 16 16 16 16 17 18 18 18 18 18 18 18 18 18 18 19 20 20 20 20 20 20 20 20 20 20 21 22 22 22 22 22 22 22 22 22 22 23 24 24 24 24 24 24 24 24 24 24 25 26 26 26 26 26 26 26 26 26 26 27 28 28 28 28 28 28 28 28 28 28 29 30 31 32 33 34 35 36 37 38 39 40
(*+/\),0=*/~5-|i:5
1 2 3 4 5 6 7 8 9 10 11 12 0 0 0 0 0 0 0 0 0 13 14 0 0 0 0 0 0 0 0 0 15 16 0 0 0 0 0 0 0 0 0 17 18 0 0 0 0 0 0 0 0 0 19 20 0 0 0 0 0 0 0 0 0 21 22 0 0 0 0 0 0 0 0 0 23 24 0 0 0 0 0 0 0 0 0 25 26 0 0 0 0 0 0 0 0 0 27 28 0 0 0 0 0 0 0 0 0 29 30 31 32 33 34 35 36 37 38 39 40
```
Then join with zeros, split it into sublists of length 22, drop the head of each sublist, and use the values as indices in the string `' FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG'`
```
' FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG'{~_22}.\,0,.(*+/\),0=*/~5-|i:5
F K C I I B A V W M G
N P
T N
C C
S P
P S
V C
S P
E L
S B
J C V C O R I B C M G
```
[Answer]
# [Actually](http://github.com/Mego/Seriously), 74 bytes
```
"%s"9⌐α' j;"%s%20s"9α'
j(k'
j"FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG"#@%
```
[Try it online!](http://actually.tryitonline.net/#code=IiVzIjnijJDOsScgajsiJXMlMjBzIjnOsScKaihrJwpqIkZLQ0lJQkFWV01HTlBUTkNDU1BQU1ZDU1BFTFNCSkNWQ09SSUJDTUciI0Al&input=)
This program works off of the same basic principle as xnor's [Python 2 answer](https://codegolf.stackexchange.com/a/96797/45941).
Explanation (newlines replaced with `\n` for clarity):
```
"%s"9⌐α' j ' '.join(["%s"]*11)
; duplicate
"%s%20s"9α'\nj '\n'.join(["%s%20s"]*9)
( move bottom of stack to top
k'\nj '\n'.join(stack)
"FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG"#@% %tuple(longstring)
```
[Answer]
# C#6, ~~192~~ 190 Bytes
```
using System.Linq;
string f()=>string.Join("\n","FKCIIBAVWMG~N!P~T!N~C!C~S!P~P!S~V!C~S!P~E!L~S!B~JCVCORIBCMG".Replace("!"," ").Split('~').Select(s=>string.Join(" ",s.Select(c=>c))));
```
Without trailing space; without trailing newline.
A straightforward solution. Start with the literal string. `Replace` `!` by 9 spaces. Then `Split` into 11 strings by `~`, and further to `char`s (inner `Select`). Append a space to each character, then `Join` back to 11 strings. Finally another `Join` by newline character.
[Answer]
# Ruby, 92
Full program, prints to stdout using `$> <<`
```
40.times{|i|$><<"FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG"[i]+(i%29>9?[$/,' '*19][i%2]:' ')}
```
There are 40 total letters to plot. Letters 10 to 28 alternate between being followed by a newline or `' '*19`. The earlier and later letters are separated by single spaces.
[Answer]
# Perl, ~~115~~ 112 bytes
```
print FKCIIBAVWMG=~s/(.)/\1 /gr.NPTNCCSPPSVCSPELSB=~s/(.)(.)/"\n$1".$"x19 .$2/gre."\nJCVCORIBCMG"=~s/(.)/\1 /gr;
```
Produces the following output:
```
F K C I I B A V W M G
N P
T N
C C
S P
P S
V C
S P
E L
S B
J C V C O R I B C M G
```
The first and last rows of output have a trailing space.
The code makes use of regex replacements and the fact that if objects are not defined, they are interpreted as strings (e.g. FKCIIBAVWMG is treated as "FKCIIBAVWMG". Couldn't take the quotes out of the last row because of the preceeding newline, which I couldn't finagle anywhere else.
Edit 1: Saved 3 bytes by replacing `" "` with `$"`, removing the outer parentheses and inserting a space after print, and removing the parentheses around `$"x19` and adding a space afterwards (so the `.` wouldn't be interpreted as a decimal)
[Answer]
# [Charcoal](http://github.com/somebody1234/Charcoal), 66 bytes
```
B²¹¦¹¹F K C I I B A V W M GPNCPSCPLBG M C B I R O C V C JSESVPSCTN
```
[Try it online!](http://charcoal.tryitonline.net/#code=77yiwrLCucKmwrnCuUYgSyBDIEkgSSBCIEEgViBXIE0gR1BOQ1BTQ1BMQkcgTSBDIEIgSSBSIE8gQyBWIEMgSlNFU1ZQU0NUTg&input=&args=LW8+RiBLIEMgSSBJIEIgQSBWIFcgTSBHCk4gICAgICAgICAgICAgICAgICAgUApUICAgICAgICAgICAgICAgICAgIE4KQyAgICAgICAgICAgICAgICAgICBDClMgICAgICAgICAgICAgICAgICAgUApQICAgICAgICAgICAgICAgICAgIFMKViAgICAgICAgICAgICAgICAgICBDClMgICAgICAgICAgICAgICAgICAgUApFICAgICAgICAgICAgICAgICAgIEwKUyAgICAgICAgICAgICAgICAgICBCCkogQyBWIEMgTyBSIEkgQiBDIE0gRw)
`Box(21, 11, 'F K C I I B A V W M GPNCPSCPLBG M C B I R O C V C JSESVPSCTN')`.
[Noncompeting, 36 bytes](http://charcoal.tryitonline.net/#code=Qm94KDExLCAxMSwgJ0ZLQ0lJQkFWV01HUE5DUFNDUExCR01DQklST0NWQ0pTRVNWUFNDVE4nKTsgRXh0ZW5kKDEpOw&input=&args=LXNs+LXY+LW8+RiBLIEMgSSBJIEIgQSBWIFcgTSBHCk4gICAgICAgICAgICAgICAgICAgUApUICAgICAgICAgICAgICAgICAgIE4KQyAgICAgICAgICAgICAgICAgICBDClMgICAgICAgICAgICAgICAgICAgUApQICAgICAgICAgICAgICAgICAgIFMKViAgICAgICAgICAgICAgICAgICBDClMgICAgICAgICAgICAgICAgICAgUApFICAgICAgICAgICAgICAgICAgIEwKUyAgICAgICAgICAgICAgICAgICBCCkogQyBWIEMgTyBSIEkgQiBDIE0gRw)
[Answer]
# Python 2, 116 Bytes
Pretty straightforward, for whatever reason even though string replacing is so verbose it was the best thing I could come up with. Possibly using `re` might be shorter.
```
print' '.join('FKCIIBAVWMG!N@P!T@N!C@C!S@P!P@S!V@C!S@P!E@L!S@B!JCVCORIBCMG').replace(' ! ','\n').replace('@',' '*17)
```
[Answer]
## Batch, 171 bytes
```
@echo F K C I I B A V W M G
@set s=NPTNCCSPPSVCSPELSB
:l
@echo %s:~0,1% %s:~1,1%
@set s=%s:~2%
@if not "%s%"=="" goto l
@echo J C V C O R I B C M G
```
[Answer]
# GameMaker Language, 148 bytes
I know it's pretty basic, but I don't think this can be beat in GML...
```
a=" "return"F K C I I B A V W M G #N"+a+"P#T"+a+"N#C"+a+"C#S"+a+"P#P"+a+"S#V"+a+"C#S"+a+"P#E"+a+"L#S"+a+"B#J C V C O R I B C M G "
```
[Answer]
## [Pip](http://github.com/dloscutoff/pip), 64 bytes
63 bytes of code, +1 for `-S` flag.
```
.*"NTCSPVSES".sX19.^"PNCPSCPLB"PE^"FKCIIBAVWMG"AE^"JCVCORIBCMG"
```
[Try it online!](http://pip.tryitonline.net/#code=LioiTlRDU1BWU0VTIi5zWDE5Ll4iUE5DUFNDUExCIlBFXiJGS0NJSUJBVldNRyJBRV4iSkNWQ09SSUJDTUci&input=&args=LVM)
### Explanation
Operators used:
* `.` (binary) concatenates (operates item-wise on lists).
* `X` (binary) string-multiplies. (`s` is a variable preinitialized to `" "`.)
* `^` (unary) splits a string into a list of characters.
* `.*` is another way to split a string into characters. It consists of unary `.`, which is a no-op on strings, paired with the `*` meta-operator, which maps a unary operator to each item in its (iterable) operand. Using `.*"..."` lets us save a byte over `(^"...")`--the parentheses would be required because `.` is higher precedence than `^`.
* `PE` prepends an element to a list. `AE` appends an element to a list.
With that background, here's the code step by step:
```
.*"NTCSPVSES"
['N 'T 'C 'S 'P 'V 'S 'E 'S]
.sX19
["N "
"T "
"C "
"S "
"P "
"V "
"S "
"E "
"S "]
.^"PNCPSCPLB"
["N P"
"T N"
"C C"
"S P"
"P S"
"V C"
"S P"
"E L"
"S B"]
PE^"FKCIIBAVWMG"
[['F 'K 'C 'I 'I 'B 'A 'V 'W 'M 'G]
"N P"
"T N"
"C C"
"S P"
"P S"
"V C"
"S P"
"E L"
"S B"]
AE^"JCVCORIBCMG"
[['F 'K 'C 'I 'I 'B 'A 'V 'W 'M 'G]
"N P"
"T N"
"C C"
"S P"
"P S"
"V C"
"S P"
"E L"
"S B"
['J 'C 'V 'C 'O 'R 'I 'B 'C 'M 'G]]
```
When this result is autoprinted, the `-S` flag joins the sublists on spaces and the main list on newlines, giving the desired output.
[Answer]
# C, ~~171~~ 156 Bytes
```
i,j;char*b="FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG ";f(){for(i=1;*b;j=i%21==0?putchar(*b++),puts(""),i++,*b++:i<21||i>210?i&1?*b++:32:32,putchar(j),i++);}
```
Outputs a trailing newline character as well... Could probably be golfed down a bit more.
[Answer]
# Perl 5, 92 86 bytes
* saved 6 bytes thanks to Dada
```
$a="%s "x11;printf"$a
"."%s%20s
"x9 .$a,FKCIIBAVWMGNPTNCCSPPSVCSPELSBJCVCORIBCMG=~/./g
```
Uses `sprintf`, padding and the string repeat operator `x`.
[Answer]
## Haskell, ~~128~~ ~~125~~ 114 bytes
```
mapM(putStrLn.((:" ")=<<))$"FKCIIBAVWMG":zipWith(\a b->a:" "++[b])"NTCSPVSES""PNCPSCPLB"++["JCVCORIBCMG"]
```
[Try it here](https://ideone.com/aEoOU8)
* `((:" ")=<<)` is `concatMap (\a -> [a,' '])` - pads by adding a space behind every letter in its input
[Answer]
# Powershell, 95 bytes
*Inspired by @AdmBorkBork's [answer](https://codegolf.stackexchange.com/a/96733/80745).*
```
'FKCIIBAVWMG
N0P
T0N
C0C
S0P
P0S
V0C
S0P
E0L
S0B
JCVCORIBCMG'-replace0,(' '*9)-replace'.','$0 '
```
## Explanation
The first replacing operator makes the rectangle `11x11`.
```
FKCIIBAVWMG
N P
T N
C C
S P
P S
V C
S P
E L
S B
JCVCORIBCMG
```
The second replacing operator inserts a space after each character. The result has trailing spaces.
```
F K C I I B A V W M G
N P
T N
C C
S P
P S
V C
S P
E L
S B
J C V C O R I B C M G
```
] |
[Question]
[
Given some finite list, return a list of all its prefixes, including an empty list, in ascending order of their length.
(Basically implementing the Haskell function [`inits`](http://hackage.haskell.org/package/base-4.11.1.0/docs/Data-List.html#v:inits).)
### Details
* The input list contains numbers (or another type if more convenient).
* The output must be a *list of lists*.
* The submission can, but does not have to be a function, any [default I/O](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) can be used.
* There is a [CW answer](https://codegolf.stackexchange.com/a/177147/24877) for all [trivial solutions](https://codegolf.meta.stackexchange.com/questions/11211/should-we-combine-answers-where-the-same-code-works-in-many-different-languages/11218#11218).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
### Example
```
[] -> [[]]
[42] -> [[],[42]]
[1,2,3,4] -> [[], [1], [1,2], [1,2,3], [1,2,3,4]]
[4,3,2,1] -> [[], [4], [4,3], [4,3,2], [4,3,2,1]]
```
[Answer]
# [Haskell](https://www.haskell.org/), 20 bytes
Edit: Yet a byte shorter with a completely different scan.
An anonymous function slightly beating the trivial import.
```
scanr(\_->init)=<<id
```
[Try it online!](https://tio.run/##HcqxCsIwEADQvd/hkEIasHYqTRcnt4KLkAY50iQ9TE9JIv69sbi86a2QHjaEsgGSRMo2gsmHNwUkm8QGL5bW50c4waKFpe@vOSL5ZlSX/XobdV2L/62cnEsyQJHN92ZEwlzLYcClFKUr1bU7R97yE@/017gAPpXmdp6mHw "Haskell – Try It Online")
* Uses `=<<` for the abbreviation `(scanr(\_->init)=<<id) l = scanr(\_->init) l l`.
* Scans a list `l` from right to left, collecting intermediate results with the function `\_->init`.
* That function ignores the elements scanned through (they're only used to get the right total length for the collected results), so really iterates applying `init` to the initial value of the scan, which is also `l`.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~21~~ 12 bytes
*-9 bytes thanks to Arnauld suggesting the separator `ÿ` instead of newlines*
```
-[[<]>[.>],]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fNzraJtYuWs8uVif2//@AotS0zIrUYgA "brainfuck – Try It Online")
Takes bytes through STDIN with no null bytes and prints a series of prefixes separated by the `ÿ` character with a leading `ÿ` character. For example, for the input `Prefixes`, the output is `ÿÿPÿPrÿPreÿPrefÿPrefiÿPrefixÿPrefixeÿPrefixes`.
For readability, [here's a version with newlines instead](https://tio.run/##SypKzMxLK03O/v9fGw6io21i7aL17GJ1Yv//DyhKTcusSC0GAA).
# Explanation:
```
- Create a ÿ character in cell 0
[ ,] While input, starting with the ÿ
[<]> Go to the start of the string
[.>] Print the string
, Append the input to the end of the string
```
[Answer]
# JavaScript (ES6), 33 bytes
```
a=>[b=[],...a.map(n=>b=[...b,n])]
```
[Try it online!](https://tio.run/##bco7DoAgEEXR3pVAMk4i0g4bIVOM32gQiBq3j9TG8p13d3nkGs8t321M01wWKkLOD@QZEFHwkKwiuQp1DhBZcxlTvFKYMaRVLcqz1s2HrPnBDgz0YP/y6ga6@pQX "JavaScript (Node.js) – Try It Online")
### How?
```
+--- a = input array
|
| +--- initialize b to an empty array and include it as the first entry
| | of the output (whatever the input is)
| |
| | +--- for each value n in a[]:
| | |
| | | +--- append n to b[] and include this new array in
| | | | the final output
| | | |
a => [b = [], ...a.map(n => b = [...b, n])]
| |
+---------+--------+
|
spread syntax: expands all elements of
the child array within the parent array
```
[Answer]
# CW for all [trivial entries](https://codegolf.meta.stackexchange.com/questions/11211/should-we-combine-answers-where-the-same-code-works-in-many-different-languages/11218#11218)
# [Clean](https://github.com/Ourous/curated-clean-linux), 19 bytes
Haskell version works in Clean too.
```
import StdLib
inits
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMUnM@l/cEkikGOrkJmXWVKsEG2oo2Cko2Cso2Cio2Cqo2AW@/9fclpOYnrxf11Pn/8ulXmJuZnJEA7EAAA "Clean – Try It Online")
# [Haskell](https://www.haskell.org/), 22 bytes
```
import Data.List
inits
```
[Try it online!](https://tio.run/##y0gszk7Nyfn//39mbkF@UYmCS2JJop5PZnEJV25iZp6CrUJBUWZeiYKKQmZeZkmxQrShnp5p7H8A "Haskell – Try It Online")
# [Prolog (SWI)](http://www.swi-prolog.org), 6 bytes
```
prefix
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/3163oCg1LbNCI1In2lDHSMdYx0THNFZTp7wosyQ1J08jUlPH0NbA2tDWUO//fwA "Prolog (SWI) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
ṭṖƤ
```
[Try it online!](https://tio.run/##y0rNyan8///hzrUPd047tuT/4fZHTWsUjk56uHMGiBH5/390rI5CtIkRiDTUUTDSUTDWUTCJBQA "Jelly – Try It Online")
### How it works
```
ṭṖƤ Main link. Argument: A
Ƥ Map the link to the left over all non-empty(!) prefixes of A.
Ṗ Pop; remove the last element.
ṭ Tack; append A to the resulting list.
```
[Answer]
# [R](https://www.r-project.org/), ~~40~~ 39 bytes
```
function(L)lapply(0:length(L),head,x=L)
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NHMyexoCCnUsPAKic1L70kAyiik5GamKJTYeuj@T9NIyezuERDU5MLyjIxQrANdYx0jHVMNDX/AwA "R – Try It Online")
*-1 byte thanks to [digEmAll](https://codegolf.stackexchange.com/users/41725/digemall)*
The output of R's `list` type is a bit weird; it uses sequential indexing, so for instance, the output for
`list(1,2)` is
```
[[1]] # first list element
list()
[[2]] # second list element
[[2]][[1]] # first element of second list element
[1] 1
[[3]] # third list element
[[3]][[1]] # first element of third list element
[1] 1
[[3]][[2]] # etc.
[1] 2
```
[Taking input as a vector instead](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NHMyexoCCnUsPAKic1L70kAyiik5GamKJTYeuj@T9NI680N7UoM1nDQFOTK00jWcPECMow1DHSMdYx0dT8DwA) gives a neater output format, although then the inputs are not technically `list`s.
[Answer]
# [Python 2](https://docs.python.org/2/), 32 bytes
```
f=lambda l:(l and f(l[:-1]))+[l]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIcdKI0chMS9FIU0jJ9pK1zBWU1M7Oif2f0FRZl4JUDA6VpMLzjYxQuYZ6hjpGOuYxGr@BwA "Python 2 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 bytes
```
²£¯Y
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=sqOvWQ==&input=WzEsMiwzLDRdCi1R)
Explanation:
```
² :Add an arbitrary extra item to the end of the array
£ :For each item in the new array:
¯Y : Get an array of the items that are before it
```
[Answer]
# [Perl 6](http://perl6.org/), 13 bytes
```
{(),|[\,] @_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkNTpyY6RidWwSG@9n9xYqWCUrVeemZxSa2CrZ1CtUKahkq8JlhAoVZJIS2/SAGoQcHESM8HKKSjoGGoo2Cko2AMFAIKa5iAmUABQ03r/wA "Perl 6 – Try It Online")
To explain:
In Perl 6 you can wrap an operator in square brackets as an alternate way to write a list reduction. `[+] @array` returns the sum of the elements in `@array`, `[*] @array` returns the product, etc. You can also precede the operator with a backslash to make a "triangular" reduction, which some languages call "scan." So `[\+] @array` returns a list consisting of the first element of `@array`, then the sum of the first two elements, then the sum of the first three elements, etc.
Here `[\,] @_` is a triangular reduction over the input array `@_` using the list construction operator `,`. So it evaluates to a lists of lists: the first element of `@_`, the first two elements of `@_`, etc. That's almost what's needed, but the problem calls for a single empty list first. So the first element of the return list is a literal empty list `(),`, then the reduction over the input list is flattened into the rest of the return list with `|`.
[Answer]
# JavaScript, 36 bytes
```
a=>[...a,0].map((x,y)=>a.slice(0,y))
```
[Try it online!](https://tio.run/##DclLCoAgEADQ64wwDfbZ6kWkxWAahqlkRJ3eXD7ewQ9Xe4VyDylvrnnVWGlDRIxypZMLwIufUJqpxmAdyC7RbE41R0cx7@DBLDjjhOPa5wc "JavaScript (Node.js) – Try It Online")
[Answer]
# Mathematica, ~~22~~ 21 bytes
*-1 byte thanks to [Misha Lavrov](https://codegolf.stackexchange.com/users/74672)!*
```
{}~FoldList@Append~#&
```
Pure function. Takes a list as input and returns a list of lists as output. I believe this is the shortest possible solution.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 2 bytes
```
Θḣ
```
Gets all the `ḣ`eads and then prepends `Θ` (in this case `[]`):
[Try it online!](https://tio.run/##yygtzv7//9yMhzsW////P9pQx0jHWMckFgA "Husk – Try It Online")
(needs type annotation for empty list: [Try it online!](https://tio.run/##yygtzv7//9yMhzsW////PzrWyscPAA "Husk – Try It Online"))
[Answer]
# [J](http://jsoftware.com/), 5 bytes
```
a:,<\
```
[Try it online!](https://tio.run/##y/r/P83WSiHRSscm5n9qcka@QpqCekFRalpmRWqxOhdUxFDBVMHsPwA "J – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 65 bytes
```
param($a)'';$x=,0*($y=$a.count);0..--$y|%{$x[$_]=@($a[0..$_])};$x
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRU13dWqXCVsdAS0Ol0lYlUS85vzSvRNPaQE9PV1elska1WqUiWiU@1tYBqDgaKApka9YCtfz//99Bw1DHSMdYx0QTAA "PowerShell – Try It Online")
PowerShell *helpfully* unrolls lists-of-lists when the default `Write-Output` happens at program completion, so you get one item per line. Tack on a [`-join','`](https://tio.run/##FYttC0AwFEb/zNU23S1v37TyPyQtKYRpCOG3X/Pt6ZzzLPZo3dq140i0GGcmDkYwlsOpMQo5XBqMauw@byKPlJISrie44SyhrnTh49JTv8XrL7@p5WD7mSF7iajgMSaYYiY@ "PowerShell – Try It Online") to see the list-of-lists better, by converting the inner lists into strings.
(Ab)uses the fact that attempting to output an empty array (e.g., `@()`) results in no output, so an empty array input just has `''` as the output, since the `$a[0..$_]` will result in nothing. It will also throw out some [spectacular error messages.](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRU13dWqXCVsdAS0Ol0lYlUS85vzSvRNPaQE9PV1elska1WqUiWiU@1tYBqDgaKApka9YCtfz//99BQxMA "PowerShell – Try It Online")
[Answer]
# [Common Lisp](http://www.clisp.org/), 39 bytes
```
(defun f(l)`(,@(if l(f(butlast l))),l))
```
[Try it online!](https://tio.run/##Dck7CsAgEAXAq7wub8Emvz5HyccsCItI1PNvbKaZx1It7oyv9gylyclwMCmMyrs3u2qDiUgYOMuXcgMVE2csWLFhH@k/ "Common Lisp – Try It Online")
### Explanation
```
(defun f(l) ) ; Define a function f
`( ) ; With the list (essentially capable of interpolation), containing:
,@ ; The value of, flattened to one level
(if l ) ; If l is not the empty list (which is the representation of nil, i.e. the only falsy value)
(f(butlast l)) ; Recurse with all of l but the tail
,l ; The value of l
```
[Answer]
## F#, 53 bytes
I've actually got two pretty similar answers for this, both the same length. They both take a generic sequence `s` as a parameter.
First solution:
```
let i s=Seq.init(Seq.length s+1)(fun n->Seq.take n s)
```
[Try it online!](https://tio.run/##TY1BC4JAFITv/oqHEChhZHUzFzx0DzqKh0VWe7i9rd1XIPTfN9cinNPMNzDTuaw1VnmvFQOCKy/qsUFCToLRinq@glvnadI9CSgTAbMcFBC41NfHE7EdzwaJRROFkZtEAmn7F5QRTAqsNVqrltHQDwbVh2Jf7Iq8@ZO3AFyG@ctU1soxmvndTj8dQbyq4sXot9z6Dw)
`Seq.take` takes the first `n` elements of the sequence. `Seq.init` creates a new sequence with a count (in this case) of the length of sequence `s` plus 1, and for each element in the sequence takes the first `n` elements in `s`.
Second solution:
```
let i s=Seq.map(fun n->Seq.take n s){0..Seq.length s}
```
Similar to before, except it creates a sequence from 0 to the length of `s`. Then takes that number of elements from `s`.
[Try this online too!](https://tio.run/##TY09C4MwFEV3f8VDKLSDwX5s1oBD90JHcQgSbWh80Ze0IG1/e2psKd7tnAv3NjapDUnvtXSgwOYXObBO9OvmjoAJD@jETQKC3TxTxoLQElt3Bfv25fGEjsazUeh4FYWRTigEQe0D8gimBFcbrWXtlMGfDCkP2T7bZdvqb14c1BLmc1MQiTGafU/TT4MQr4p4MfotU/8B)
[Answer]
# [SWI PROLOG](http://www.swi-prolog.org) 22 bytes
`i(X,Y):-append(X,_,Y).`
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~31~~ 29 bytes
```
->a{[a*i=0]+a.map{a[0,i+=1]}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6xOjpRK9PWIFY7US83saA6MdpAJ1Pb1jC2tvZ/gUKanoZCdKwCFGgq2NoqREfHxnJBZUyMYlFldEBCcGlDHSMdYx2TWIQ0UAxM6BhBKR1jOAOoEGEwkGukY4ii0wRMQDSA5eEMoMLY/wA "Ruby – Try It Online")
Explanation:
```
->a{ # take array input a
[a*i=0]+ # set i to 0 and add whatever comes next to [[]] (a*0 == [])
a.map{ # for every element in a (basically do a.length times)
a[0,i+=1] # increment i and return the first i-1 elements of a to map
}
}
```
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), ~~8~~ 7 bytes
```
1_',\0,
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NyjBeXSfGQOd/iVW1SnRlXZFVmkKFdUJ@trVGQlpiZo51hXWldZFmbC1XSbSigbWOokEskKVjYmStAeKaGGmC@IYKRgrGCiYQMUNrINcaLGQNldCM/Q8A "K (ngn/k) – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~9~~ 8 bytes
```
{∧Ė|a₀}ᶠ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/pRx/Ij02oSHzU11D7ctuD//2hDHSMdYx2T2P9RAA "Brachylog – Try It Online")
### Explanation
```
{ }ᶠ Find all:
∧Ė The empty list
| Or
a₀ A prefix of the input
```
[Answer]
# MATL, ~~15~~ 12 bytes
*3 bytes saved thanks to @Giuseppe*
```
vin:"G@:)]Xh
```
Try it at [MATL Online](https://matl.io/?code=vin%3A%22G%40%3A%29%5DXh&inputs=%5B1%2C2%2C3%2C4%5D&version=20.10.0).
Due to the way that MATL displays the output, you can't explicitly see the empty array in the cell array. [Here](https://matl.suever.net/?code=vin%3A%22G%40%3A%29%5DXh%26D&inputs=%5B1%2C2%2C3%2C4%5D&version=20.10.0) is a version that shows the output a little more explicitly.
**Explanation**
```
v # Vertically concatenate the (empty) stack to create the array []
i # Explicitly grab the input
n # Compute the number of elements in the input (N)
: # Create an array from [1, ..., N]
" # Loop through this array
G # For each of these numbers, M
@: # Create an array from [1, ..., M]
) # Use this to index into the initial array
] # End of the for loop
Xh # Concatenate the entire stack into a cell array
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes
```
Eθ…θκθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUCjUEfBuTI5J9U5Ix/MydbU1LTmgsgXalr//x8drWSopKOgZAQijEGEiVJs7H/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input array
E Map over elements
θ Input array
… Moulded to length
κ Current loop index
Implicitly print each array double-spaced
θ Input array
Implicitly print
```
It's possible at a cost of 1 byte to ask Charcoal to print an `n+1`-element array which includes the input as its last element, but the output is the same, although the cursor position would be different if you then went on to print something else.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
η¯š
```
Explanation:
```
η Prefixes
š Prepend
¯ Global array (empty by default)
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3PZD648u/P8/2sQoFgA "05AB1E – Try It Online")
[Answer]
# [RAD](https://bitbucket.org/zacharyjtaylor/rad), 7 bytes
```
(⊂⍬),,\
```
[Try it online!](https://tio.run/##K0pM@f9f41FX06PeNZo6OjH///83VDBSMFYwAQA "RAD – Try It Online")
This also works in Dyalog APL as a function.
## How?
This works the same for both APL and RAD, given their close relation.
* `(⊂⍬)` the empty array
* `,` prepended to
* `,\` the prefixes (which exclude the empty array.)
[Answer]
# [Groovy](http://groovy-lang.org/), 37 bytes
```
{x->(0..x.size()).collect{x[0..<it]}}
```
[Try it online!](https://tio.run/##Sy/Kzy@r/F9iG22oY6RjrGMSy1Vp@7@6QtdOw0BPr0KvOLMqVUNTUy85PycnNbmkuiIaKGyTWRJbW/u/oCgzryQnT6FSo0TzPwA "Groovy – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 5 bytes
```
Êò@¯Y
```
[Try it online!](https://tio.run/##y0osKPn//3DX4U0Oh9ZH/v8fbahjpGOsYxLLxaUbCAA "Japt – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 43 bytes
Take a list of non-null characters as input and returns all prefixes separated by newline. Requires double-infinite or wrapping tape.
```
,>-[+>,]<[-<]<<++++++++++[[<]>[.>]>[-<+>]<]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fx043WttOJ9YmWtcm1sZGGw6io21i7aL17ICEro22XaxN7P//AUWpaZkVqcUA "brainfuck – Try It Online")
[Answer]
# Powershell, 24 bytes
```
,@()
$args|%{,($x+=,$_)}
```
Explanation:
1. The trivial accumulator wrapped to array by unary `,`.
2. The script uses [splatting](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting). See parameter `@a`.
Test script:
```
$f = {
,@()
$args|%{,($x+=,$_)}
}
@(
,( @() , @() )
,( @(42) , @(@(),@(42)) )
,( @(1,2,3,4) , @(@(), @(1), @(1,2), @(1,2,3), @(1,2,3,4)) )
,( @(4,3,2,1) , @(@(), @(4), @(4,3), @(4,3,2), @(4,3,2,1)) )
) | % {
$a,$expected = $_
$result = &$f @a
$false -notin $(
$result -is [array]
$result.Count -eq $expected.Count
for($j=0; $j-lt$result.Count; $j++){
"$($result[$j])" -eq "$($expected[$j])"
}
)
# $result # uncomment this line to display a result
}
```
Output:
```
True
True
True
True
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 39 bytes
```
x=>x.Select((_,i)=>x.Take(i)).Append(x)
```
[Try it online!](https://tio.run/##bY/LCsIwEEX3@YqQVYJjwepOW3ChoLir4KIUqXGqQY2SplqQfnuNL9TiZuCeucNhZN6WuarHhZaDyUgXBzTpao8DpW0I36C5DEOa0aAug7D0ItyjtJwvQYl7nqc75EoIb3g6oV7zUtR9QtxVnMQJtZjbnAZU44W@GLkS@snXCn5iz2@ADvjQhV6z5pgPHUcrZyPZ0WAqt/ycmofStZ5q8bAtjLI4Uxo5i1krskbpjTc9Ks0ZMMj4vSren7kv/7VK0WIJE8/ZJ1V9Aw "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [F# (Mono)](http://www.mono-project.com/), 45 bytes
```
fun x->List.mapi(fun i y->List.take i x)x@[x]
```
[Try it online!](https://tio.run/##SyvWzc3Py/@fk1qikKZgq6DxP600T6FC184ns7hELzexIFMDJJCpUAkVKknMTgVyKzQrHKIrYv9rWltzcRUUZeaVpOUpKKk6KilopEXHamIImRhhETS0NrI2tjbBphwobmRtGKv5HwA "F# (Mono) – Try It Online")
I am not totally sure if this is valid, but it seems like it follows the same "anonymous lambda" syntax that I've seem used in several other languages.
] |
[Question]
[
Display the 12 numbers on a clock face exactly like this:
```
12
11 1
10 2
9 3
8 4
7 5
6
```
To better see the grid, here's one with dots:
```
...........12............
.....11...........1......
.........................
.10...................2..
.........................
.........................
9.......................3
.........................
.........................
..8...................4..
.........................
......7...........5......
............6............
```
Note that the grid is stretched in width by a factor of two to make it look more square.
Also note that two-digit numbers are aligned with their ones digit in place. The 9 digit should be flush against the left.
Return or print the result as a multiline string (not a list of lines). Any trailing spaces are optional. The final newline also optional.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
F¹²«M⁻↔⁻¹⁴⊗÷×⁴鳦⁸⁻⁴↔⁻⁷÷×⁴﹪⁺³ι¹²¦³P←⮌I⊕ι
```
[Try it online!](https://tio.run/##bY7LCsJADEXX@hWzzMC4qBUUXRW7ESyI@AN9pBiYzsi8NuK3j4EqbgwEQpJzOf29db1tdc6jdQKKtRTP5aKxCaEhEz1Unf9MxUaJ2sZO4wAnE2pKNCDcaEIPfCKpRCm5lNhxzwzvfwFbJf5wjR2itnDR/FHOMWzxDZMHtok60MORCbA/4xiUuGJC5xGOrQ/s0juc0AT2ohl55ZxXSb8B "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Computes the offsets between each digit mathematically. Charcoal is 0-indexed (thus the `⊕` to output \$ 1 \ldots 12 \$), so the formulae for the horizontal and vertical offsets are as follows:
$$ \begin{align} \delta x &= \left \lvert 14 - 2 \left \lfloor \frac {4i} 3 \right \rfloor \right \rvert - 8 \\ \delta y &= 4 - \left \lvert 7 - \left \lfloor \frac {4i'} 3 \right \rfloor \right \rvert \end{align} $$
where \$ i' = i + 3 \pmod {12} \$.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 91 bytes
Not a very clever approach, but I've failed to find anything shorter at the moment.
```
_=>`K12
E11K1
A10S2
9W3
B8S4
F7K5
L6`.replace(/[A-Z]/g,c=>''.padEnd(Buffer(c)[0]&31))
```
[Try it online!](https://tio.run/##Dci7CoMwFADQ/X5ITaBGo30OERTskm4OhYpoyENaggmx7e@nLmc4b/ETqwwv/0kXp3Q0LI6smjgtoKWUU4Ca5l0BANdHudlcugPA7cyPcD9NJGhvhdQo6@v0OWTzXrIqSYgXql0Uar7G6IAk7vNhV1KMo3TL6qwm1s3IoC3@ "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~39~~ ~~33~~ 31 bytes
Thanks to *Magic Octopus Urn* for saving 6 bytes!
### Code
```
6xsG12N-N•°£•NèØú«тR∞Nè¶×]\6».c
```
Some 33 byte alternatives:
```
711ćŸā•Σ°w•₂вú‚øJƵt3в¶×‚ø»6xŠ».c¦
6xsŸ5L•Σ°w•₂вúõ¸ì‚ζJï2Ý«ƶ×)ø».c
6xsG¶12N-N•Θ{©•₂вNèú«ƵB∞Nè¶×]6J.c
6xsG12N-N•Θ{©•₂вNèú«тR∞Nè¶×]6s».c
```
Uses the [**05AB1E** encoding](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md). [Try it online!](https://tio.run/##MzBNTDJM/f/frKLY3dDIT9fvUcOiQxsOLQZSfodXHJ5xeNeh1Rebgh51zANyD207PD02xuzQbr3k//8B "05AB1E – Try It Online")
[Answer]
# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 82 76 73 bytes
```
00 C0 A2 0E BD 38 C0 29 03 A8 A9 0D 20 25 C0 BD 38 C0 4A 4A A8 A9 20 20 25 C0
BD 29 C0 20 D2 FF CA 10 E1 60 20 D2 FF 88 10 FA 60 36 35 37 34 38 33 39 32 30
31 31 31 31 32 31 31 2C 1A 4C 0B 5C 03 4C 00 06 2C 00 15 00 2C
```
* -6 bytes, thanks to [Arnauld](https://codegolf.stackexchange.com/questions/170297/display-a-clock-face/170339?noredirect=1#comment411339_170319) for the clever idea :)
* another -3 bytes after Arnauld's idea not to treat leading `1` digits specially
The idea here is to only store the digits of all the numbers in the order they are needed. Additional info required is the number of newlines to prepend and the number of spaces in front.
The maximum number of newlines is `3`, so we need 2 bits for this, and the maximum number of spaces is `23`, therefore 5 bits are enough. Therefore, for each digit to print, we can squeeze this info in a single "control byte".
So, the data for this solution takes exactly 30 bytes: 15 single digits and 15 associated "control bytes".
### [Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22clockface.prg%22:%22data:;base64,AMCiDr04wCkDqKkNICXAvTjASkqoqSAgJcC9KcAg0v/KEOFgINL/iBD6YDY1NzQ4MzkyMDExMTEyMTEsGkwLXANMAAYsABUALA==%22%7D,%22vice%22:%7B%22-autostart%22:%22clockface.prg%22%7D%7D)
Usage: `SYS49152` to start.
**Commented disassembly**:
```
00 C0 ; load address
.C:c000 A2 0E LDX #$0E ; table index, start from back (14)
.C:c002 .mainloop:
.C:c002 BD 38 C0 LDA .control,X ; load control byte
.C:c005 29 03 AND #$03 ; lowest 3 bits are number of newlines
.C:c007 A8 TAY ; to Y register for counting
.C:c008 A9 0D LDA #$0D ; load newline character
.C:c00a 20 25 C0 JSR .output ; repeated output subroutine
.C:c00d BD 38 C0 LDA .control,X ; load control byte
.C:c010 4A LSR A ; and shift by two positions for ...
.C:c011 4A LSR A ; ... number of spaces
.C:c012 A8 TAY ; to Y register for counting
.C:c013 A9 20 LDA #$20 ; load space character
.C:c015 20 25 C0 JSR .output ; repeated output subroutine
.C:c018 BD 29 C0 LDA .digits,X ; load current digit
.C:c01b 20 D2 FF JSR $FFD2 ; output
.C:c01e CA DEX ; decrement table index
.C:c01f 10 E1 BPL .mainloop ; still positive -> repeat
.C:c021 60 RTS ; and done.
.C:c022 .outputloop:
.C:c022 20 D2 FF JSR $FFD2 ; output a character
.C:c025 .output:
.C:c025 88 DEY ; decrement counting register
.C:c026 10 FA BPL .outputloop ; still positive -> branch to output
.C:c028 60 RTS ; leave subroutine
.C:c029 .digits:
.C:c029 36 35 37 34 .BYTE "6574"
.C:c02d 38 33 39 32 .BYTE "8392"
.C:c031 30 31 31 31 .BYTE "0111"
.C:c035 31 32 31 .BYTE "121"
.C:c038 .control:
.C:c038 31 2C 1A 4C .BYTE $31,$2C,$1A,$4C
.C:c03c 0B 5C 03 4C .BYTE $0B,$5C,$03,$4C
.C:c040 00 06 2C 00 .BYTE $00,$06,$2C,$00
.C:c044 15 00 2C .BYTE $15,$00,$2C
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~76 74~~ 70 bytes
```
"K12
E11K1
A10S2
9W3
B8S4
F7K5
L6"~~say S:g{<:Lu>}=" "x$/.ord-64
```
[Try it online!](https://tio.run/##K0gtyjH7/1/J29CIy9XQ0NuQi8vR0CDYiIuLyzLcGEg6WQSbcHG5mXubcvmYKdXVFSdWKgRbpVfbWPmU2tXaKikoVajo6@UXpeiamfz/756fmGPFpYAAQGMhtCGyIBeXgqGBAiYAW6uAHYAco6BggUXGhAtqozmSoCmyKxTMAA "Perl 6 – Try It Online")
Port of Arnauld's answer until I can come up with something shorter.
[Answer]
# HTML + JavaScript (Canvas), 13 + 161 = 174 bytes
Arbitrary canvas positioning uses 6 bytes.
```
with(C.getContext`2d`)with(Math)for(font='9px monospace',textAlign='end',f=x=>round(sin(x*PI/6)*6)*measureText(0).width*2,x=13;--x;)fillText(x,f(x)+80,f(9-x)+80)
```
```
<canvas id=C>
```
With grid for comparison:
```
with(C.getContext`2d`)with(Math){
for(font='9px monospace',textAlign='end',f=x=>round(sin(x*PI/6)*6)*measureText(0).width*2,x=13;--x;)fillText(x,f(x)+80,f(9-x)+80)
for(globalAlpha=0.2,y=-6;y<=6;y++)fillText('.'.repeat(25),6*measureText('.').width*2+80,y*measureText(0).width*2+80)
}
```
```
<canvas id=C>
```
---
## Explanation of Positioning Formula
See my [JavaScript with SVG answer](https://codegolf.stackexchange.com/a/170350/47097).
[Answer]
# Java ~~8~~ 11, ~~141~~ 138 bytes
```
v->{for(var x:"92BCN5BB92BNN1BA991CNNNJ995DNNN2I991ENN6H92FN93G".getBytes())System.out.print(x<59?" ".repeat(x-48):(char)(x>76?10:x-17));}
```
[Try it online](https://tio.run/##ZZDNbsIwEITvPMUqJ1siEUkbqEkLaugPrVRfkHqhHNxgaGhwIttJg1CePd2U3HrxeFfr2W98EJVwD9vvNsmEMfAmUnUeAKTKSr0TiQTelQBVnm4hIe@dVDTCXjPAw1hh0wQ4KLiDtnJn512uSSU01FOHBfGCh3GMyrkf3zPmLzjnr4yFD6jBCzYeOR8vWfDE2dWz4@2ljU9WGkLp6mSsPHp5ab1CIw6pb0M217KQwhIHnGHtXt/QKUm@hKaknk3Gc380rV1/QmnUtFFHV5SfGdL1kH8RjhiQrCw67tcbEPSSTnkJUWWW/Qt2mYR@bV8Zq4dIBOKYl8r2FlraUitQ8qd/RLprR7e@zG2ohzYZ/ilxPkbOEF36dU37Cw) (NOTE: `String.repeat(int)` is emulated as `repeat(String,int)` for the same byte-count, because Java 11 isn't on TIO yet.)
Explanation is similar as below, but it uses `" ".repeat(x-48)` for the spaces instead of format with `"%"+(x-48)+"s"`.
---
# Java 8, 141 bytes
```
v->{for(var x:"92BCN5BB92BNN1BA991CNNNJ995DNNN2I991ENN6H92FN93G".getBytes())System.out.printf("%"+(x>58?"c":x-48+"s"),x>76?10:x>58?x-17:"");}
```
[Try it online.](https://tio.run/##LY9Na4NAEIbv@RXDQmGXVKm2Jlmlhpp@Q@cS6KX0sN2swdRocNfFEPztdk1zmZd5B4bn2QkrvN3md5Cl0Bo@RFGdJgBFZVSTC6kAxxXA1sUGJP0cw7LEdf3EDW2EKSQgVHAPg/XSU1431IoGupjwMFthlGUuEYPsgfNghYjvnEePLsM3Vzwhzl55@Iz89oX4W2Wyo1GaMrY@aqP2ft0a/9A4nJySKzKlXRotlkSSuPPuFlOiCbvu0vlsGdzE51PnBfOYEJb0QzICHtqf0gFeOM8We@dI18Y93X59g2D/gpUvadWW5cWtH/4A)
**Explanation:**
```
v->{ // Method with empty unused parameter and no return-type
for(var x:"92BCN5BB92BNN1BA991CNNNJ995DNNN2I991ENN6H92FN93G".getBytes())
// Loop over the bytes of the above String:
System.out.printf("%"+ // Print with format:
(x>58? // If the character is a letter / not a digit:
"c" // Use "%c" as format
: // Else:
x-48+"s"), // Use "%#s" as format, where '#' is the value of the digit
x>76? // If the byte is 'N':
10 // Use 10 as value (newline)
:x>58? // Else-if the byte is not a digit:
x-17 // Use 48-58 as value (the 0-9 numbers of the clock)
: // Else:
"");} // Use nothing, because the "%#s" already takes care of the spaces
```
**Further explanation `92BCN5BB92BNN1BA991CNNNJ995DNNN2I991ENN6H92FN93G`:**
* All the digits will be replaced with that amount of spaces. (For 11 spaces it's therefore `92`.)
* All 'N' are new-lines
* All ['A','J'] are clock digits ([0,9])
[Answer]
# [R](https://www.r-project.org/), ~~75~~ 68 bytes
```
write("[<-"(rep("",312),utf8ToInt('*`®÷ĥĹĚä—M
'),1:12),1,25)
```
[Try it online!](https://tio.run/##K/r/v7wosyRVQynaRldJoyi1QENJScfY0EhTp7QkzSIk3zOvRENdK@HQusPbjyw9svPIrMNLDk33ledR19QxtAIpM9QxMtX8/x8A "R – Try It Online")
Compressed the digits positions.
Did this after spending lots of time trying to come up with a trigonometric answer (see history of edits).
Inspired by [this other R answer](https://codegolf.stackexchange.com/a/170366/80010) buy J.Doe - upvote it !
Saved 7 bytes thanks to J.Doe.
[Answer]
# [Python 2](https://docs.python.org/2/), 97 bytes
```
for i in range(7):w=abs(3-i);print'%*d'%(1-~w*w,12-i),'%*d'%(24-3**w-2*w,i)*(w<3),'\n'*min(i,5-i)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFTITNPoSgxLz1Vw1zTqtw2MalYw1g3U9O6oCgzr0RdVStFXVXDULeuXKtcx9AIKKEDFTMy0TXW0irXNQJKZGpqaZTbGAPlYvLUtXIz8zQydUyBav//BwA "Python 2 – Try It Online")
Computes all spacings and newlines in the loop
[Answer]
# R, ~~168~~ ~~159~~ 125 bytes
The naive solution of writing the numbers at the prescribed points in a text matrix. Points are stored as UTF-8 letters decoded via `utf8ToInt`
```
"!"=utf8ToInt
write("[<-"(matrix(" ",25,13),cbind(!"LMFGSBCWAYCWGSM",!"AABBBDDDGGJJLLM")-64,-64+!"ABAAAA@BICHDGEF"),1,25,,"")
```
Dropped 9 bytes with JayCe's suggestion to use `write` and avoid defining the matrix.
Dropped another 34 bytes with JayCe's storage suggestion.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 32 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁶ẋ“¿×¿ Œ4ç4Œ!¿Ø‘ż“øn0œ’Œ?D¤Fs25Y
```
A full program which prints the result.
**[Try it online!](https://tio.run/##AUIAvf9qZWxsef//4oG24bqL4oCcwr/Dl8K/IMWSNMOnNMWSIcK/w5jigJjFvOKAnMO4bjDFk@KAmcWSP0TCpEZzMjVZ//8 "Jelly – Try It Online")**
### How?
(I have not yet thought of/found anything shorter than `“¿×¿ Œ4ç4Œ!¿Ø‘` which seems long to me for this part - bouncing / base-decompression / increments, nothing seems to save!)
```
⁶ẋ“¿×¿ Œ4ç4Œ!¿Ø‘ż“øn0œ’Œ?D¤Fs25Y - Main Link: no arguments
⁶ - space character
“¿×¿ Œ4ç4Œ!¿Ø‘ - code-page indices list = [11,17,11,32,19,52,23,52,19,33,11,18]
ẋ - repeat (vectorises) -> [' '*11, ' '*17, ...]
¤ - nilad followed by link(s) as a nilad:
“øn0œ’ - base 250 number = 475699781
Œ? - first natural number permutation which would be at
- index 475699781 if all permutations of those same
- natural numbers were sorted lexicographically
- = [12,11,1,10,2,9,3,8,4,7,5,6]
D - to decimal lists = [[1,2],[1,1],[1],[1,0],[2],[9],[3],[8],[4],[7],[5],[6]]
ż - zip together = [[' '*11, [1,2]], [' '*17, [1,1]], ...]
F - flatten = [' ',' ',...,1,2,' ',' ',...,1,1,...]
s25 - split into chunks of 25 (trailing chunk is shorter)
Y - join with new line characters
- implicit print
```
[Answer]
## Haskell, ~~88~~ 87 bytes
```
f=<<"k12{e11k1{{a10s2{{{9w3{{{b8s4{{f7k5{l6"
f c|c>'z'="\n"|c>'9'=' '<$['a'..c]|1<2=[c]
```
The encode-spaces-as-letters method (first seen in [@Arnauld's answer](https://codegolf.stackexchange.com/a/170298/34531)) in Haskell. Using `{` and expanding it to `\n` is one byte shorter than using `\n` directly.
[Try it online!](https://tio.run/##Fc1NCsIwEEDhvacIQZiVxYm/hcQTuHPZdhGHpkpiCKYiOD27sW4e3@7dbPZ9CGUQRrTFGa2lR8U9okdmi@usmLl@b@Zej3nL7A5@x2EvF07QRCf4gJFtlH/WYECAXjZgoaqom1Ar01BXHvYe50F6jZfxeY5iKF9ywQ65rCilHw "Haskell – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org/), 96 bytes
```
||format!(r"{:13}
11{:12}
10{:20}
9{:24}
8{:20}
{:7}{:12}
{:13}",12,1,2,3,4,7,5,6)
```
[Try it online!](https://tio.run/##LYvBDoIwEETv@xVLT22yB7agaA0fw8EmJFBNLael316LOKc3kzdx@6TiA67THLRBgeWZ0OOIZd/9K65TanRU4rjLgEeYa7EZALkVZ9tKcK/QH4B4@2/ihnyKv68itsRkqaOeBrrQ1ZQHvOMc0hIaraQa6LUxkMsX "Rust – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~240~~ 235 bytes
```
++++++++++[>++>+>+++>+++++>++>++[<]>-]>>>++...........>-.+.<<.>.....>-..<...........>.<<..>.>.-.>-[<<.>>-]<++.<<...>>+++++++.>>+++[<<<.>>>-]<<------.<<...>..>+++++.<<<-[>>.<<-]>>>----.<<..>......>+++.<...........>--.<<.>............>+.
```
[Try it online!](https://tio.run/##VY7dCoAwCIUfSPQJ5LzI6KKCIIIugp5/HW3rxzlxnm/qdIzrvpzzVqs8ViACHsmbkV58gA4AU3sNamLuhv4y/6ohMcKUWgmOPVzyCwW0iXdGPYAgXNMaRr8xAloQXXOTB0Ebl8xvO32X6zWxWi8 "brainfuck – Try It Online")
**Commented code**
```
++++++++++ Put 10 in cell 0
[>++>+>+++>+++++>++>++[<]>-] Loop 10 times incrementing to leave 0 20 10 30 50 20 20 in memory
>>>++ 30 plus 2 = 32 (ascii space)
...........>-.+. print 11spaces followed by 12 (ascii 49 50)
<<.>.....>-..<...........>. print 1newline 5spaces 11 11spaces 1
<<..>.>.-.>-[<<.>>-]<++. print 2newlines 1space 10 19spaces 2
<<...>>+++++++.>>+++[<<<.>>>-]<<------. print 3newlines 9 23spaces 3
<<...>..>+++++.<<<-[>>.<<-]>>>----. print 3newlines 2spaces 8 19spaces 4
<<..>......>+++.<...........>--. print 2newlines 6spaces 7 11spaces 5
<<.>............>+. print 1newline 12spaces 6
```
A rare example where the text is repetitive enough that the brainfuck program is less than ~~twice~~ 1.6 times the length of the output!
2 bytes saved by suggestion from Jo King: `>>>>>>-` -> `[<]>-`
3 bytes saved by moving the third 20-place downcounter from far right of the ascii codes `10 30 50` to immediately to the left of them. Saves `<<>>` when filling the gap between `8` and `4` but adds 1 byte to the line `>>>++` .
**Original version**
```
++++++++++ Put 10 in cell 0
[>+>+++>+++++>++>++>++<<<<<<-] Loop 10 times incrementing to leave 0 10 30 50 20 20 20 in memory
>>++ 30 plus 2 = 32 (ascii space)
...........>-.+. print 11spaces followed by 12 (ascii 49 50)
<<.>.....>-..<...........>. print 1newline 5spaces 11 11spaces 1
<<..>.>.-.>-[<<.>>-]<++. print 2newlines 1space 10 19spaces 2
<<...>>+++++++.>>+++[<<<.>>>-]<<------. print 3newlines 9 23spaces 3
<<...>..>+++++.>>>-[<<<<.>>>>-]<<<----. print 3newlines 2spaces 8 19spaces 4
<<..>......>+++.<...........>--. print 2newlines 6spaces 7 11spaces 5
<<.>............>+. print 1newline 12spaces 6
```
[Answer]
# [PHP](http://www.php.net/), 97 bytes
```
<?=gzinflate(base64_decode(U1CAA0MjLghtqIAkyMWlYGiggAmMuLi4LBWwA2OgnIKCBRYZEy6IHQrmSIKmXMhKzAA));
```
[Try it online!](https://tio.run/##K8go@P/fxt42vSozLy0nsSRVIymxONXMJD4lNTk/JVUj1NDZ0dHAN8snPaOk0NMxu9I3PCfSPTM93THXt9Qn08THKbzc0cg/Pc/T29kpKDLKtdLM0yOwKDfY0zs3wjfDu8rRUVPT@v9/AA "PHP – Try It Online")
This is a hard coded compressed string. I couldn't find a solution shorter than this!
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 125 109 105 bytes
```
x,*d=L"<;1:293847564
0P`P
05";main(i){for(;i=d[12];printf("%*d",i/4,*d++-48))for(x=i&3;x--;)puts("");}
```
* -16 bytes (-3 for better loop arrangement, -13 for directly including the non-printable chars) thanks to [Jonathan Frech](https://codegolf.stackexchange.com/questions/170297/display-a-clock-face#comment411318_170339).
* -4 bytes by replacing a division for a shift and abusing the fact that on many systems (like the one hosting TIO), `sizeof(wchar_t) == sizeof(int)` -- won't work on windows :) Thanks [ErikF](https://codegolf.stackexchange.com/questions/170297/display-a-clock-face#comment411343_170339) for the idea.
[Try it online!](https://tio.run/##S9ZNT07@/79CRyvF1kfJxtrQysjS2MLE3NTMRNaAL4A9gT9AzsBUyTo3MTNPI1OzOi2/SMM60zYl2tAo1rqgKDOvJE1DSVUrRUknU98EaIi2tq6JhaYmSFmFbaaasXWFrq61ZkFpSbGGkpKmde3//wA "C (gcc) – Try It Online")
This is a port of my general idea from [the 6502 solution](https://codegolf.stackexchange.com/a/170319/71420) to C. It's a bit modified: Instead of having a flag for a leading `1`, the character is printed as a decimal by subtracting 48, so 10 - 12 are encoded as `:` to `<`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 145 137 125 bytes
Only the tab positions are hard-coded: all the line spacings and clock values are generated in the loop.
Thanks again to ceilingcat for the suggestions.
```
i,j,k;f(char*t){for(i=7;i--;t=memset(t+sprintf(t,"%*d%*d"+3*!j,"NHDA"[j]-65,6+i,"AMUY"[j]-65,6-i),10,k=j+i/4)+k)j=i>3?6-i:i;}
```
[Try it online!](https://tio.run/##PU47C8IwGNz9FTEiJE3ig/qgxioFBxfdHKQ4SNrql9oHTXQp/e21dRAO7gXHKfFQqh1Brl7vKEZbYyMoJs9dC1zzVCZEPe@VY2mdFBUBfy1BCGn9LM5MbIllpqwgtwmxHI@dqANmrjPUHJ@PhwCH@iZWS75iwHFwulz/gQDK5zOe@prBdEFZSrUPO3ffFRuQTdttouwOOfkUEFFUDxDqjyATet5Ndi4hhvZcvq35yab9Ag "C (gcc) – Try It Online")
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 37 bytes
```
3B 32 35 75 07 0d 13 0c 22 14 35 18 44 74 5F 74 2B 46 6F 68 32 C4 52 7D 74 2A 31 32 25 31 32 7C 60 52 2D 29 73
```
[Try it here!](https://pyke.catbus.co.uk/?code=3B+32+35+75+07+0d+13+0c+22+14+35+18+44+74+5F+74+2B+46+6F+68+32+C4+52+7D+74+2A+31+32+25+31+32+7C+60+52+2D+29+73&input=&warnings=0&hex=1) (raw bytes)
```
;25Dt_t+Foh2.DR}t*12%12|`R-)s
```
[Try it here!](https://pyke.catbus.co.uk/?code=%3B25Dt_t%2BFoh2.DR%7Dt%2a12%2512%7C%60R-%29s&input=%5B13%2C+19%2C+12%2C+34%2C+20%2C+53%2C+24%5D&warnings=1&hex=0) (Human readable)
```
- o = 0
;25 - set line width to 25 characters
- `[13, 19, 12, 34, 20, 53, 24]`
- (In hex version, encoded in base 256, regular version in input field)
t_t - reversed(^[1:])[1:]
D + - ^^ + ^
Foh2.DR}t*12%12|`R-) - for i in ^:
o - o++
h - ^+1
2.DR - divmod(^, 2)
}t - (remainder*2)-1
* - quotient * ^
12% - ^ % 12
12| - ^ or 12 (12 if 0 else ^)
` - str(^)
R- - ^.rpad(i) (prepend spaces such that length i)
s - sum(^)
- output ^ (with newlines added)
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~315~~ 313 bytes
*saved 2 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!*
```
++++[>++++<-]>[>+++>+++>+++>+++>>++>+++>+++>+++<<<<<<<<<-]>+++++>++++>+++>++>++++++++++>>+++++++>+><<<...........>>.<<<<.>.>.....>>..<<...........>>.<<<..>.>>.>.<<<...................<<.>...>>++.<.......................<<<.>>...>..>-.<...................<<<<.>>>..>......>-.<...........<<<<<.>>>>.>............>-.
```
[Try it online!](https://tio.run/##bY5LCoAwDEQPFDonKHMRcaGCIIILwfPXJDVKpVMa8nkTMp/TdqzXspciqoEWcxrpWfPZ1jmksJm8GdPaqe3IKVQan0iYH9T31OgAMMCY1h3yBcaKoDevTPbtRjKhv8YZ4jnmz@UA4lq8WCk3 "brainfuck – Try It Online")
all in one code block:
```
++++[>++++<-]>[>+++>+++>+++>+++>>++>+++>+++>+
++<<<<<<<<<-]>+++++>++++>+++>++>++++++++++>>+
++++++>+><<<...........>>.<<<<.>.>.....>>..<<
...........>>.<<<..>.>>.>.<<<................
...<<.>...>>++.<.......................<<<.>>
...>..>-.<...................<<<<.>>>..>.....
.>-.<...........<<<<<.>>>>.>............>-.
```
[Answer]
# Powershell, ~~94~~ ~~88~~ 82 bytes
Direct [Powershell format operator](https://ss64.com/ps/syntax-f-operator.html). `{i,w}` means a placeholder for a parameter with index `i`, width of the placeholder is `w` with right align.
```
"{11,13}
{10,7}{0,12}
10{1,20}
9{2,24}
8{3,20}
{6,7}{4,12}
{5,13}"-f1..12
```
# Powershell, 88 bytes
Port of [Arnauld's](https://codegolf.stackexchange.com/users/58563/arnauld) [Javascript answer](https://codegolf.stackexchange.com/a/170298/80745)
*-6 bytes thanks to @AdmBorkBork*
```
[RegEx]::Replace("K12
E11K1
A10S2
9W3
B8S4
F7K5
L6",'[A-Z]',{' '*("$args"[0]-64)})
```
To better see the grid, use `'.'` instead `' '`.
[Answer]
# JavaScript with SVG, 188 bytes
Arbitrary line height of 120% uses 4 bytes.
```
with(Math)for(s='<pre><svg viewBox=-8-8+16+16 style=font-size:1;text-anchor:end>',f=x=>round(sin(x*PI/6)*6),x=13;--x;)s+=`<text x=${f(x)*2}ch y=${f(9-x)*1.2}>${x}</text>`
document.write(s)
```
With grid for comparison:
```
with(Math)for(s='<pre><svg viewBox=-8-8+16+16 style=font-size:1;text-anchor:end>',f=x=>round(sin(x*PI/6)*6),x=13;--x;)s+=`<text x=${f(x)*2}ch y=${f(9-x)*1.2}>${x}</text>`
for(y=-6;y<=6;y++)s+=`<text x=12ch y=${y*1.2} style=fill:#0002>${'.'.repeat(25)}</text>`
document.write(s)
```
---
## Explanation of Positioning Formula
Let `f(x) = round(sin(x * π/6) * 6)`.
Assuming the origin is the center of the clock, the grid coordinates of the right-most digit of any given clock number `x` is
[`f(x) * 2`, `f(9 - x)`].
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 69 bytes
```
{ReplaceF["l12
f11l1
b10t2
9x3
c8t4
g7l5
m6",/"\\l",sp&`*@STN]}
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@786KLUgJzE51S1aKcfQiCvN0DDHkIsrydCgxIiLi8uywhhIJluUmHBxpZvnmHLlminp6CvFxOQo6RQXqCVoOQSH@MXW/g8oyswrUbCpUUiLjv0PAA "Attache – Try It Online")
This encodes each run of spaces as: `NTS[count of spaces]`; `NTS` is the "numeric to short" builtin, which allows numbers to be expressed as strings. E.g., `NTS[95] = $R1` and `NTS[170297] = $XQO`. `STN` is the inverse of this builtin.
This answer replaces (`ReplaceF`) all occurences of letters (`/\l/`) in the input with the result of the function `sp&`*@STN`, which firsts decodes the letter and then repeats `sp` (a space) that many times.
[Answer]
# [Swift](https://swift.org), ~~178~~ 165 bytes
~~`var b="";for c in"L12nF11L1nnB10T2nnn9X3nnnC8T4nnG7L5nM6"{let i=c.unicodeScalars.first!.value;if c=="n"{b+="\n"}else if i>64{for _ in 0..<(i-65){b+=" "}}else{b+="(c)"}};print(b)`~~
Based on what Downgoat posted, I've reduced this to 165 bytes:
`print("L12nF11L1nnB10T2nnn9X3nnnC8T4nnG7L5nM6".unicodeScalars.map{let x=Int($0.value);return x==110 ?"\n":(x>64 ?String(repeating:" ",count:x-65):"($0)")}.joined())`
Expanded out, with `$0` converted to a named variable:
`print("L12nF11L1nnB10T2nnn9X3nnnC8T4nnG7L5nM6".unicodeScalars.map { c in
let x = Int(c.value)
return x == 110 ? "\n" : (x>64 ? String(repeating:" ", count: x-65) : "(c)")
}.joined())`
The input string is encoded as follows: Uppercase letters (`A-Z`) represent blocks of spaces, offset by 65. So `A` means 0 spaces, `B` means 1 space, the first `L` means 11 spaces, etc. `n`s are converted to newlines. All other characters are printed as-is.
Run it online [here](https://tio.run/##DY1BC4IwGIb/yhgdNqjhTK0WJhQUgZ3y0MHL0BUL@5S5lRD99rXLy8NzeN7xo@828X4wGizBJY/hyHnJAfY8qmIA2NyWYQ/rKgE4rcoULhlmDnTTt@rayE6akb3k8O2URVN@DpVZxN6yc4pujbLOQNA55xEqcA1YkGmXJai42vD4IEYNStpAAiM8b3oHVkyLLKUC1yFEMf2xZ69BtYRS7/8) (thanks, mbomb007)
[Answer]
# vim, 103 bytes
```
25a <ESC>r30r9O0i <C-v><ESC>15l2xA <C-v><ESC><ESC>0"aDddqbYp<C-x>e<C-a>q2@a@b4@a@b6@aggqbYP<C-a>e<C-x>q@axr 2hr2@b4@a@b6@ayyjpr lr yyj2p2j2p2jp
```
`<ESC>` is 0x1b, `<C-a>` is 0x01, `<C-x>` is 0x18, and `<C-v>` is 0x16.
This includes all trailing spaces because I didn't notice they were optional until I'd finished for the additional challenge.
## Annotated
```
25a <ESC>r30r9 # create the 9...3 line
o0i <C-v><ESC>15l2xA <C-v><ESC><ESC>"a0D # create macro a that moves 2 spaces from the middle to the ends
# 15 is a magic number that lets the same macro work for the 6 and 12 lines
dd # delete empty line
qb # record macro b to...
Yp # duplicate line (down)
<C-x>e<C-a> # adjust numbers
q
2@a # adjust spacing for line 8..4
@b4@a # create line 7..5
@b6@a # create line 6
gg # move cursor to first line
qb # record macro b to...
YP # duplicate line (up)
<C-a>e<C-x> # adjust numbers
q
@axr 2hr2 # adjust spacing for 2-digit numbers
@b4@a # 11..1
@b6@a # 12
yyjpr lr yy # add a line of all spaces below 12, and copy to default register
j2p2j2p2jp # add the rest of the blank lines
```
[Try it online!](https://tio.run/##K/v/38g0UUG6yNigyNLfIFNBTNrQNMeowhHIkDZQSnRJSSlMiiyQSGUsNHJIdEgyARFmDonp6UDhAMZUiUKHxIoiBaOMIiOEZGVlVkGRQk6RApBhVGAExgX//wMA "V (vim) – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 151 bytes
```
foreach[a b c d][13 12 1""7 11 12 1 1""1""3 10 20 2 1""1"^/"0 9 24 3 1""1"^/"3 8 20 4 1""1""7 7 12 5 13 6 1""][print rejoin[pad/left b a pad/left d c]]
```
[Try it online!](https://tio.run/##PY3RCoMwDEV/5dIf0LRu3X5jr6WDronMMVSK/9@lToT7kHNIbopwfQiHWMelSMrvkPBCBsdADmRBxngQ7WMDjfoeVvPnZ2d63GEHuFM43NrGcFx4@FZwgXZem4thLdO8ochnmeawJu6@Mm76OuEERo6x1h8 "Red – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~112~~ ~~88~~ 87 bytes
A solution using string interpolation.
```
print(f'''{12:13}
{11:7}{1:12}
10{2:20}
9{3:24}
8{4:20}
{7:7}{5:12}
{6:13}''')
```
[**Try it online!**](https://tio.run/##JYwxDoAgEAR7XkGHdtyBovcgow0SQ2M2vP0U7SaTyZS77mcOquU6ch025xyIhUIzIJLUQELcjLHkwcL@RbMiCMdO1i6Iv0Xq9fTVmPvhfY2qDw "Python 3 – Try It Online")
*-25 bytes thanks to ovs and Herman L.*
[Answer]
# Pure [Bash](https://www.gnu.org/software/bash/), 123
`printf` does the heavy-lifting here:
```
n=" 0 a 0 a"
printf -vo %*s%*s\\n 0 a 13 12 7 11 12 1 $n 3 10 20 2$n$n 1 9 24 3$n$n 3 8 20 4$n 7 7 12 5 13 6
echo "${o//a}"
```
[Try it online!](https://tio.run/##HYzNCoQwDITvPsVQ6mVBNK3rz8E38VLFxb2kyypexGeviTBD5suQTGFbU@LBoEJQm@z3//L@QXFE5K9NNI78tORBDi2IdBIsQzYVnMiyEKGHq@Ef8Oi0qSW2euTw1g9NtsxrhLFnLMtwmZRu "Bash – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 135 123 110 bytes
This uses a simple encoding where any `c` between `'a'` and `'z'` represents `c-'a'+1` repeated spaces, `'`'` represents a newline, and all other characters are left unchanged.
```
f(i){char*s="k12`e11k1``a10s2```9w3```b8s4``f7k5`l6`";for(;i=*s;s++)i>96?printf("%*s",i-96,""):putchar(i%86);}
```
[Try it online!](https://tio.run/##FczRDoIgFIDhe5@CsbkB6hZWJDHrVQ6xsDPKHNi6cD472c1/9e13zeBczp4hX9zDRpF6GmQLdymDBLByl1oA0N/91luXDgD@FI7wVECNf0dmsBfJpKrieNHqOkUcZ89oKRKtsdGqppSfp8/8nzMsO8XNmjdDXhZHxslSEOIZN8Wafw "C (gcc) – Try It Online")
[Answer]
# T-SQL, 132 bytes
```
PRINT SPACE(11)+'12
11 1
10'+SPACE(20)+'2
9'+SPACE(23)+'3
8'+SPACE(19)+'4
7 5
6'
```
Only 12 bytes shorter than the trivial solution (`PRINT` of the entire string as-is).
Found a variation I like that is much longer (~~235~~ 226 bytes), but much more SQL-like:
```
SELECT CONCAT(SPACE(PARSENAME(value,4)),PARSENAME(value,3),
SPACE(PARSENAME(value,2)),PARSENAME(value,1))
FROM STRING_SPLIT('11.1..2,5.11.11.1,. .. ,1.10.20.2,. .. ,. .. ,.9.23.3,
. .. ,. .. ,2.8.19.4,. .. ,6.7.11.5,12.6.. ',',')
```
`STRING_SPLIT` breaks it into rows at the commas, and `PARSENAME` splits each row at the dots. The 1st and 3rd are used for how many spaces to print, the 2nd and 4th are used for what to display.
(line breaks in this one are just for readability)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 116 bytes
```
my@a=[" "xx 13]xx 13;($_=pi/6*++$;@a[0+|6*(1.1-.cos);0+|6*(1.1+.sin)]=fmt ++$: "%2s")xx 12;@a>>.join>>.&{say S/.//}
```
[Try it online!](https://tio.run/##K0gtyjH7/z@30iHRNlpJQUGpokLB0DgWTFprqMTbFmTqm2lpa6tYOyRGG2jXmGlpGOoZ6uol5xdrWsP52nrFmXmasbZpuSUKQLVWCkqqRsVKmiBTjIAa7ez0svIz84CUWnVxYqVCsL6evn7t//8A "Perl 6 – Try It Online")
(Ta @JoKing for saving 26 bytes)
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 142 bytes
```
my@a=[[[32,32]xx 13]xx 13];for 1..12 {$_=$^b*pi/6;@a[round 6*(1-.cos);round 6*(1+.sin)]=[" $b".ords.tail(2)]}
{say S/^.//}(.[*;*].chrs) for @a
```
[Try it online!](https://tio.run/##Rc1BC4IwGIDhe7/iQzxsq76xCV6GsP/QccyYWjQwJ1uBIv72RRB0eQ/P5Z1vcaxzfq7aNcaYSp4qaZcFRPWruocIAlFI2MprU7Ydmz2vlXYmhvc0QM2IOGMfElV/OGLyE7WNKaDsCgxxSPhyfiSS2v2wJbfChbfI@U7QMMUs9o@YKHxn2uX8AQ "Perl 6 – Try It Online")
I wanted to do something... different. So this one calculates the positions of all the digits, via pairs of characters, strips off the initial space and prints the lines.
Easily modifiable for different parameters, e.g. a [45 character wide version with 17 digits](https://tio.run/##Tc1BC8IgGIDhe79Chge1@sJv1Q4y8H@IhduKhDWHFmyM/XYj6NDlPTyXd7zF/pzzc9auNsaUuCvRThM5nn5V9xCJBJAVWei1ppdGoBj9QVZKOxPDe@gIomByD21IXP3JFpIfuK1NQWhTQIhdgpfzPUNu180Cyc0rAyOUsNA@YuLk@9Iu5w8).
] |
[Question]
[
There was [a challenge](https://codegolf.stackexchange.com/questions/125470/multiply-two-strings) up a while ago about multiplying strings. It showed us how we can multiply not only numbers, but also strings. However, we still can't multiply a number by a string properly. There has been [one attempt](https://codegolf.stackexchange.com/questions/71427/decimal-multiplication-of-strings) to do so but this is obviously wrong. We need to fix that!
## Your Task:
Write a function or program that multiplies two inputs, a string and an integer. To (properly) multiply an string by an integer, you split the string into characters, repeat each character a number of times equal to the integer, and then stick the characters back together. If the integer is negative, we use its absolute value in the first step, and then reverse the string. If the input is 0, output nothing (anything multiplied by 0 equals nothing).
## Input:
A string that consists solely of printable ASCII characters and newlines, and an integer (possible negative).
## Output:
The string multiplied by the integer.
## Examples:
```
Hello World!, 3 --> HHHeeellllllooo WWWooorrrlllddd!!!
foo, 12 --> ffffffffffffoooooooooooooooooooooooo
String, -3 --> gggnnniiirrrtttSSS
This is a fun challenge, 0 -->
Hello
World!, 2 --> HHeelllloo
WWoorrlldd!!
```
## Scoring:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte count wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ ~~5~~ 4 bytes
```
²Ɠxm
```
[Try it online!](https://tio.run/##y0rNyan8///QpmOTK3L/H25/1LQm61HDnEPbdEHg0Lb/6h5AFfkK4flFOSmK6lzqafn5QDK4pCgzLx3ICMnILFYAokSFtNI8heSMxJyc1Lz0VKAMWF9MHlTjf2MdBUMjHQVdIG2go2AEAA "Jelly – Try It Online")
### How it works
```
²Ɠxm Main link. Argument: n (integer)
² Yield n².
Ɠ Read and eval one line of input. This yields a string s.
x Repeat the characters of s in-place, each one n² times.
m Takes each |n|-th character of the result, starting with the first if n > 0,
the last if n < 0.
```
[Answer]
## JavaScript (ES6), 63 bytes
Takes input in currying syntax `(s)(n)`.
```
s=>n=>[...s].reduce((s,c)=>n<0?c.repeat(-n)+s:s+c.repeat(n),'')
```
### Test cases
```
let f =
s=>n=>[...s].reduce((s,c)=>n<0?c.repeat(-n)+s:s+c.repeat(n),'')
console.log(f(`Hello World!`)(3))
console.log(f(`foo`)(12))
console.log(f(`String`)(-3))
console.log(f(`This is a fun challenge`)(0))
console.log(f(`Hello
World!`)(2))
```
[Answer]
# [Python 3](https://docs.python.org/3/), 44 bytes
```
f=lambda s,n:s and s[0]*n+f(s[1:],n)+s[0]*-n
```
[Try it online!](https://tio.run/##PU49D4IwEP0r59RWiuFjI2F318QBGKq0UFOvhOLgr69nNV5ueF95ectrmz3WMZrWqcd1VBAkNgEUjhC6YthjZnjoymaQKLKk5BiX1eLGWY/553pkh7u3yCkpAQUYv8IPWoSOs6N2zku4@NWNOyahFhI4M94TLqtETht1TsTzr3mebQB6BeaJcJuVcxonTYEi@amyx39lJQbSNc1ugTER3w "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~59~~ ~~57~~ ~~50~~ 46 bytes
*-2 bytes thanks to Anders Kaseorg. -4 bytes thanks to Dennis.*
```
lambda s,n:''.join(i*n**2for i in s)[::n or 1]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFYJ89KXV0vKz8zTyNTK09Lyygtv0ghUyEzT6FYM9rKKk8ByDWM/V9QlJlXopCmoe6RmpOTr6MQnl@Uk6KorqNgrMkFlwsuAbLSgYK6xpr/AQ "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
S²Ä×J²0‹iR
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/@NCmwy2Hp3sd2mTwqGFnZtD//0pKSh6pOTn5XOH5RTkpikAul64RAA "05AB1E – Try It Online")
```
S # Split the string into characters
²Ä× # Repeat each character abs(integer) times
J # Join into a string
²0‹i # If the integer is less than 0...
R # Reverse the string
```
[Answer]
## R, ~~83~~ ~~78~~ ~~76~~ 74 bytes
```
function(s,i)cat('if'(i<0,rev,I)(rep(el(strsplit(s,'')),e=abs(i))),sep='')
```
Anonymous function.
Frederic saved 3 bytes, Giuseppe saved ~~2~~ 4, pajonk saved 2.
Explanation:
```
el(strsplit(s,'')) # split string into list characters
rep( ,e=abs(i))) # repeat each character abs(i) times
'if'(i<0,rev, ){...} # if i>0, reverse character list
I # otherwise leave it alone: I is the identity function
cat( ,sep='') # print the result
```
Tests:
```
> f('Hello World!', 3 )
HHHeeellllllooo WWWooorrrlllddd!!!
> f('foo', 12)
ffffffffffffoooooooooooooooooooooooo
> f('String', -3)
gggnnniiirrrtttSSS
> f('This is a fun challenge', 0)
> f('Hello
+ World!', 2)
HHeelllloo
WWoorrlldd!!
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
y|Y"w0<?P
```
Inputs are: number, then string.
Strings with newlines are input using char `10` as follows: `['first line' 10 'second line']`.
[Try it online!](https://tio.run/##y00syfn/v7ImUqncwMY@4P9/XWMu9eCSosy8dHUA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8L@yJlKp3MDGPuB/rEvIf2MudY/UnJx8hfD8opwURXUFLkMjLvW0/Hx1Ll2gXHBJUWZeujqXAZd6SEZmsQIQJSqkleYpJGck5uSk5qWnqnMZcUVDzFBXMDRQUIcaFKsAAA).
### Explanation
Consider inputs `-3` and `'String'`.
```
y % Implicitly take two inputs. Duplicate from below
% STACK: -3, 'String', -3
| % Absolute value
% STACK: -3, 'String', 3
Y" % Run-length decoding
% STACK: -3, 'SSStttrrriiinnnggg'
w % Swap
% STACK: 'SSStttrrriiinnnggg', -3
0< % Less than 0?
% STACK: 'SSStttrrriiinnnggg', 1
? % If so
P % Flip
% STACK: 'gggnnniiirrrtttSSS'
% End (implicit). Display (implicit)
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~41~~ 36 bytes
```
f n|n<0=reverse.f(-n)|1<3=(<*[1..n])
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hrybPxsC2KLUstag4VS9NQzdPs8bQxthWw0Yr2lBPLy9W839uYmaegq1CSj6XgkJBUWZeiYKKQpqCkYJSYlJyihKKoIaukSY2cQOo4H8A "Haskell – Try It Online")
Example usage: `f (-3) "abc"` yields `"cccbbbaaa"`.
**Edit:** -5 bytes thanks to xnor!
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~29, 23, 18~~, 17 bytes
```
æ_ñÀuñÓ./&ò
ÀäëÍî
```
[Try it online!](https://tio.run/##K/v///Cy@MMbDzeUAonJevpqhzdxHW44vOTw6sO9h9f9/@@RmpOTr1CeX5STovhfV/e/rjEA "V – Try It Online")
Hexdump:
```
00000000: e65f f1c0 75f1 d32e 2f26 f20a c0e4 ebcd ._..u.../&......
00000010: ee .
```
Thanks to @nmjcman101 for saving 6 bytes, which encouraged me to save another 5!
The original revision was pretty terrible, but now I'm really proud of this answer because it handles negative numbers surprisingly well. (V has next to no numerical support and no support for negative numbers)
Explanation:
```
æ_ " Reverse the input
ñ ñ " In a macro:
À " Run the arg input. If it's positive it'll give a count. If it's negative
" running the '-' will cause V to go up a line which will fail since we're
" on the first line, which will break out of this macro
u " (if arg is positive) Undo the last command (un-reverse the line)
Ó./&ò " Put every character on it's own line
```
At this point, the buffer looks like this:
```
H
e
l
l
o
w
o
r
l
d
!
<cursor>
```
It's important to not the trailing newline, and that the cursor is on it.
```
À " Run arg again. If it's negative, we will move up a line, and then give the
" absolute value of the count. If it's positive (or 0) it'll just give the
" count directly (staying on the last line)
ä " Duplicate... (count times)
ë " This column.
Íî " Remove all newlines.
```
[Answer]
# [J](http://jsoftware.com/), 19 15 13 bytes
```
(#~|)A.~0-@>]
```
[Try it online!](https://tio.run/##y/r/X0NDua5G01GvzkDXwS5W8/9/9eCSosy8dHUFNBkFYy6cUga4peKNAQ "J – Try It Online")
**Explanation**
```
0-@>] NB. first or last index depending on sign of right arg
A.~ NB. get first or last Anagram of left arg
(#~|) NB. copy left arg, absolute-value-of-right-arg times
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
0‚ÄπFR} í¬π√Ñ√ó?
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f4FHDTreg2lOTDu083HJ4uv3//7qmXEpKSh6pOTn5XOH5RTkpikAuAA "05AB1E – Try It Online")
**Explanation**
```
0‹F # input_1 < 0 times do:
R # reverse input_2
} # end loop
í # filter
¹Ä× # repeat current char abs(input_1) times
? # print without newline
```
[Answer]
# PHP>=7.1, 65 bytes
```
for([,$s,$n]=$argv;$i<strlen($s)*abs($n);)echo$s[$i++/$n-($n<0)];
```
[PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/3dc97c84fcc3abd76c0d3cdb949c5a31dbc1a326)
[Answer]
# [Brain-Flak (BrainHack)](https://github.com/Flakheads/BrainHack), ~~154~~ 152 bytes
```
([(({})(<()>))]<>)<>{({}()<([{}]()<([{}])>)<>({}<>)<>>)<>}{}<>{}<>({}<([][()]){{}({<({}<(({}<>)<>)>())>[()]}<{}{}>)([][()])}{}{}<>>){{}{({}<>)<>}(<>)}{}
```
[Try it online!](https://tio.run/##NYyxCsNADEP/JZM0ZMxmDP2GjscNaYc2FDKEbMbf7toHNwiZJ8mvaz/O7/7@RaAB5oSASnZRiloSUNDM@3RWkHwUSl53qSBab2Cn5dBkkNmlgtRKXSxHyll2Gz@0VjbrjrTkEbE@Yt1ied7XcX6WPw "Brain-Flak (BrainHack) – Try It Online")
Just here to give DJMcMayhem some competition. **;)**
## Explanation
Here's a modified version of DJMcMayhem's explanation
```
#Compute the sign and negative absolute value
([(({})<(())>)]<>)<>{({}()<([{}]()<([{}])>)<>({}<>)<>>)<>}{}<>{}<>
#Keep track of the sign
({}<
#For each char in the input string:
([][()])
{
{}
#Push n copies to the alternate stack
({<({}<(({}<>)<>)>())>[()]}<{}{}>)
#Endwhile
([][()])
}{}{}<>
#Push the sign back on
>)
#If so...
{{}
#Reverse the whole stack
{({}<>)<>}
#And toggle over, ending the loop
(<>)
}
#Pop the counter off
{}
```
[Answer]
# [Elm](https://elm-lang.org/), 69 bytes
```
f n=if n<0 then List.reverse>>f -n else List.concatMap(List.repeat n)
```
Defines `f` to be a function that takes an integer and a list of characters and returns a list of characters. You can try it [here](https://elm-lang.org/try). Here is a full test program:
```
import Html exposing (text)
f : Int -> List Char -> List Char
f n=if n<0 then List.reverse>>f -n else List.concatMap(List.repeat n)
main =
text (String.fromList (f -3 ['S','t','r','i','n','g']))
```
### Explanation
This is my first Elm submission, so please let me know any golfing tricks I've missed.
Using currying, we define a function `f` that takes an integer `n` and returns a function from a list of chars to a list of chars. There are two cases in the function definition:
* If `n` is negative, call `f` on its absolute value (`f -n`); then compose (`>>`) the resulting function with `List.reverse`.
* Else, create a function that puts `n` copies of a value in a list (`List.repeat n`) and map that function over each char in the list, flattening the result into a list of chars (`List.concatMap`).
[Answer]
# Dyalog APL, 15 bytes
```
{⌽⍣(⍵<0)⊢⍺/⍨|⍵}
```
String as a left argument, number as a right argument.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhOpHPXsf9S7WeNS71cZA81HXoke9u/Qf9a6oAQrU/v@v7pGak5OvEJ5flJOiqK6QpmDMpZ6Wnw9iGRpxqQeXFGXmpYN4h9YDZUIyMosVgChRIa00TyE5IzEnJzUvPRUkbwAA)
**How?**
`‚ç∫/‚ç®` - repeat the string
`|‚çµ` - abs(number) times
`⌽⍣` - reverse if
`(‚çµ<0)` - the number is below 0
[Answer]
# MATLAB, 37 bytes
```
@(s,n)flip(repelem(s,abs(n)),(n<0)+1)
```
This defines and anonymous function with inputs `s`: string and `n`: number.
Example runs:
```
>> @(s,n)flip(repelem(s,abs(n)),(n<0)+1)
ans =
@(s,n)flip(repelem(s,abs(n)),(n<0)+1)
>> f = ans;
>> f('String', 3)
ans =
SSStttrrriiinnnggg
>> f('String', -3)
ans =
gggnnniiirrrtttSSS
>> f('String', 0)
ans =
Empty matrix: 1-by-0
```
[Answer]
# [Brain-Flak (Haskell)](https://github.com/Flakheads/BrainHack), ~~202~~ 192 bytes
```
(({})<(([({})]<>)){({}()<([{}])<>({}<>)<>>)<>}{}([{}]<><{}>)([][()]){{}({<({}<(({}<>)<>)>[()])>()}<{}{}>)([][()])}{}{}<>>)([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}{{}{({}<>)<>}(<>)}{}
```
[Try it online!](https://tio.run/##TY2xDsJADEP/pZM9dGKNIvENjKcbCgNUSB2qblG@PSQHCIbo4hf7fN2XdXsst2cEYE4BWr1dlLTckKiZd4qmSipa43kpLCrmSrTewE5LbFJGfN3UcVHQ0/pv9pL13ajMBKns@DW/ewwYHanMRyJZ4U@BVyJ5RMznOMV0OfZ1u08v "Brain-Flak (BrainHack) – Try It Online")
This is probably the worst possible language to do it in, but it's done. Thanks to @Wheatwizard for providing the Haskell interpreter, which allows mixed input formats. This would be about 150 bytes longer without it.
Explanation:
```
#Keep track of the first input (n)
(({})<
#Push abs(n) (thanks WheatWizard!)
(([({})]<>)){({}()<([{}])<>({}<>)<>>)<>}{}([{}]<><{}>)
#For each char in the input string:
([][()])
{
{}
#Push n copies to the alternate stack
({<({}<(({}<>)<>)>[()])>()}<{}{}>)
#Endwhile
([][()])
}{}{}<>
#Push the original n back on
>)
#Push n >= 0
([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}
#If so...
{{}
#Reverse the whole stack
{({}<>)<>}
#And toggle over, ending the loop
(<>)
}
#Pop the counter off
{}
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~99~~ ~~98~~ ~~89~~ ~~87~~ 85 bytes
```
s->n->{for(int i=s.length*(n<0?n:-n),r=n<0?0:~i;i++<0;)System.out.print(s[(i+r)/n]);}
```
[Try it online!](https://tio.run/##XVDLbsIwELzzFVtONhA3tDcCVBVS1R6qHqjUQ5qDCQ6YOnZkb5AQSn89dR4gVMmyrZnVzOwc@JEHphD6sP2pZV4Yi3DwGCtRKpaVOkVpNBtFg6LcKJlCqrhz8M6lhvMAoEcdcvTP0cgt5J4ja7RS7@IEuN052o4CvPRy83TPbZxM3jSujHZlLuwSMljULljqYHnOjCVSI8iFY0roHe5HRM/DJz0LNJ3YRfMPZ78ykuPxPIzo@uRQ5MyUyApvi8TFRI4tvdcJjao6as0/NgeRYpz4TCgcOlj0qQDOw1ehlIEvY9X2bjiBx2pypTJjPDJ9uIE@99KBPxx8QeCXUU1K4cfCm6muAg8Gt3Kt07e@Wl10qy5ls/olaZtz1qWl17AZ40WhToT0HdOGj8OEMjQr3@uztfxEKGU8TUWBhPiWxU7Ybm7qG@mF/remNOm5ajBorqr@Aw "Java (OpenJDK 8) – Try It Online")
* -2 bytes thanks to @Xanderhall
* -2 bytes thanks to @Nevay
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~108~~ ~~106~~ ~~103~~ 101 bytes
-2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
```
e,p,j,d;f(s,i)char*s;{p=0,e=strlen(s);for(i*=d=i<0?p=e-1,e=-1:1;p^e;p+=d)for(j=i;j--;)putchar(s[p]);}
```
[Try it online!](https://tio.run/##ZY8/D4IwEMVn@RSVqcU2Ad08G1d3TRz8kxBooaS2TQsT4bNjdTAxJDfd@7279yrWVNU8C@poR2uQOFBFqrb0WYDR8ZwKHnqvhcGBgLQeq4zXXB3yo@OCFVFmxb4A9xTgNrwmH6TjCjrGgLih/5zC4eYeBKZZmR69SmUwScZVspI4PQmtLbpar@t1StGOAIqmgNOUwBeQ1sZ9sV0I594r00SNLU2XVgUUp0RyMChG0LFAIyKcL9hvgrv5Rfj/NM1v "C (gcc) – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 49 bytes
```
@(s,n){t=repmat(s,abs(n),1)(:)',flip(t)}{2-(n>0)}
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo1gnT7O6xLYotSA3sQTIS0wq1sjT1DHU1LDSVNdJy8ks0CjRrK020tXIszPQrP2fpqHukZqTk6@uY6zJheAYIHN0jTX/AwA "Octave – Try It Online")
I will provide an explanation tomorrow.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 59 +1 = 60 bytes
Uses `-n` flag.
```
n=eval$_
a=$<.read
a.reverse!if n<0
a.chars{|i|$><<i*n.abs}
```
[Try it online!](https://tio.run/##DcjBCkBAEADQ@34FtSch5bqc/YGjBiNb26xm2RJ@3XB69fgYTxFqMILTg4JGm5IRZgU/ETlgapeETPXHtAKH67a3bo2xGZUwhkekqFWHzvlc9Z7dnL5@262nIAV9 "Ruby – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
Fθ¿‹η0F±Iη←ιFIηι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBo1BTITNNQcMntbhYI0NHQclASVNTASzjl5qeWJKq4ZxYXKKRoQkUDSjKzCvRsPJJTSvRUcjUVEjNKU6FKIWpgSrJ1LT@/z@4BMhO59I1/q9b9l@3OAcA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Fθ For each character in the input string
¿‹η0 If the input number is less than zero
F±Iη Repeat the negation of the input number times
←ι Print the character leftwards (i.e. reversed)
FIη Otherwise repeat the input number times
ι Print the character
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 9 bytes
```
q~__*@e*%
```
[Try it online!](https://tio.run/##S85KzP3/v7AuPl7LIVVL9f9/peCSosy8dCUFXWMA "CJam – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 bytes
```
®pVaìr!+sVg
```
[Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=rnBWYcOsciErc1Zn&input=IkhlbGxvCldvcmxkISIgMg==)
## Explanation
Implicit input of string `U` and integer `V`.
```
®pVaÃ
```
Map (`®`) each letter of `U` (implicitly) to itself repeated (`p`) `abs(V)` (`Va`) times.
```
¬r
```
Turn the string into an array of chars (`¬`) and reduce (`r`) that with...
```
!+sVg
```
`"!+".slice(sign(V))` - this either reduces with `+` ‚Üí `a + b`, or with `!+` ‚Üí `b + a`.
[Thanks @Arnauld for the backwards-reduce idea!](https://codegolf.stackexchange.com/a/132008/69583)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
Based off Riley's approach.
```
SÂΛ@²Ä×J
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/@HDT4b5HDbscDm063HJ4utf//x6pOTn5Ogrh@UU5KYpcusYA "05AB1E – Try It Online")
### Explanation
```
SÂΛ@²Ä×J Arguments: s, n
S Push s split into individual characters
 Get a (without popping) and push a reversed
Λ n lower than 0 (true = 1, false = 0)
@ Get value at that index in the stack
²Ä×J Repeat each character abs(n) times and join
Implicit output
```
[Answer]
# [WendyScript](http://felixguo.me/wendy/), 46 bytes
```
<<f=>(s,x){<<n=""#i:s#j:0->x?x>0n+=i:n=i+n/>n}
f("Hello World", -2) // returns ddllrrooWW oolllleeHH
```
[Try it online!](http://felixguo.me/#wendyScript)
## Explanation (Ungolfed):
```
let f => (s, x) {
let n = ""
for i : s
for j : 0->x
if x > 0 n += i
else n = i + n
ret n
}
```
[Answer]
# C89 bytes
```
main(int c,char**v){for(;*v[1];v[1]++)for(c=atoi(v[2]+(*v[2]=='-'));c--;)putchar(*v[1]);}
```
I saw [Ben Perlin's version](https://codegolf.stackexchange.com/a/132050/22873) and wondered if you couldn't be shorter still and also have a full program; surely, `atoi()` and `putchar()` aren't that expensive in terms of bytes? Seems I was right!
[Answer]
# Pyth, ~~13~~ 11 bytes
```
*sm*.aQdz._
```
[Try it!](https://pyth.herokuapp.com/?code=%2asm%2a.aQdz._&input=-3%0AHello+World%21&test_suite=1&test_suite_input=-3%0AHello+World%21%0A3%0AHello+World%21%0A0%0AHello+World%21&debug=0&input_size=2)
*-2 bytes thanks to @jacoblaw*
## explanation
```
*sm*.aQdz._
m z # map onto the input string (lambda var: d)
*.aQd # repeat the char d as often as the absolute value of the input number
s # sum the list of strings into a single string
* ._Q # Multiply with the sign of the implicit input value: reverse for negative Q
```
## old approach, 13 bytes
```
_W<Q0sm*.aQdz
```
[Try it!](https://pyth.herokuapp.com/?code=_W%3CQ0sm%2a.aQdz&input=-3%0AHello+World%21&test_suite=1&test_suite_input=-3%0AHello+World%21%0A3%0AHello+World%21%0A0%0AHello+World%21&debug=0&input_size=2)
[Answer]
# [Python 3](https://docs.python.org/3/), 68 bytes
```
h=lambda s,n:h(s[::-1],-n)if n<0 else s[0]*n+h(s[1:],n)if s else s*n
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P8M2JzE3KSVRoVgnzypDozjaykrXMFZHN09TITNNIc/GQCE1pzhVoTjaIFYrTxukwNAqVgciWwyV08r7X1CUmVeikaGhnpGak5OvrmOiqckFF0vPz09JqkxV1zHDKqoLFP4PAA "Python 3 – Try It Online")
[Answer]
# Excel VBA, ~~93~~ ~~89~~ ~~88~~ ~~86~~ 85 Bytes
Anonymous VBE immediate window function that takes input as string from cell `[A1]` and int from cell `[B1]` and outputs to the VBE immediate window
```
l=[Len(A1)]:For i=1To l:For j=1To[Abs(B1)]:?Mid([A1],IIf([B1]>0,i,l+1-i),1);:Next j,i
```
-4 bytes for abandoning `[C1]` as intermediate variable
-1 byte for adding `a` as intermediate variable
-2 bytes for replacing `a` with `l`, (`[Len(A1)]`)
] |
[Question]
[
An [Octothorpe, (also called number sign, hash or hashtag, or pound sign)](https://en.wikipedia.org/wiki/Number_sign) is the following ASCII character:
```
#
```
Isn't that a fun shape? Lets make bigger versions of it! So here is your challenge:
>
> Given a positive integer **N**, output an ASCII hashtag of size **N**.
>
>
>
For example, an ASCII hashtag of size **1** looks like this:
```
# #
#####
# #
#####
# #
```
Trailing whitespace on each line is allowed, but not required.
The input will *always* be a valid positive integer, so you don't have to handle non-numbers, negative, or 0. Your output can be in any reasonable format, so outputting to STDOUT, returning a list of strings, or string with newlines, a 2D matrix of characters, writing to a file, etc. are all fine.
## Test cases
```
2:
## ##
## ##
##########
##########
## ##
## ##
##########
##########
## ##
## ##
3:
### ###
### ###
### ###
###############
###############
###############
### ###
### ###
### ###
###############
###############
###############
### ###
### ###
### ###
4:
#### ####
#### ####
#### ####
#### ####
####################
####################
####################
####################
#### ####
#### ####
#### ####
#### ####
####################
####################
####################
####################
#### ####
#### ####
#### ####
#### ####
5:
##### #####
##### #####
##### #####
##### #####
##### #####
#########################
#########################
#########################
#########################
#########################
##### #####
##### #####
##### #####
##### #####
##### #####
#########################
#########################
#########################
#########################
#########################
##### #####
##### #####
##### #####
##### #####
##### #####
```
Since this is a code-golf, try to write the shortest possible solution you can, and above all else, have fun!
[Answer]
# [MATL](https://matl.suever.net/), ~~20~~ ~~16~~ ~~12~~ 11 bytes
3 bytes thanks to DJMcMayhem.
1 byte thanks to Luis Mendo.
```
21BwY"&*~Zc
```
[Try it online!](https://matl.suever.net/?code=21BwY%22%26%2a~Zc&inputs=3&version=20.4.0)
## Explanation
```
% stack starts with input e.g. 2
21 % push 21 to stack 2 21
B % convert to binary 2 [1 0 1 0 1]
w % swap [1 0 1 0 1] 2
Y" % repeat [1 1 0 0 1 1 0 0 1 1]
&* % one-input multiplication [[1 1 0 0 1 1 0 0 1 1]
[1 1 0 0 1 1 0 0 1 1]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[1 1 0 0 1 1 0 0 1 1]
[1 1 0 0 1 1 0 0 1 1]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[1 1 0 0 1 1 0 0 1 1]
[1 1 0 0 1 1 0 0 1 1]]
~ % complement [[0 0 1 1 0 0 1 1 0 0]
[0 0 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]
[0 0 1 1 0 0 1 1 0 0]
[0 0 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]
[0 0 1 1 0 0 1 1 0 0]
[0 0 1 1 0 0 1 1 0 0]]
Zc % convert 0 to spaces ## ##
1 to octothorpes ## ##
and join by newline ##########
##########
## ##
## ##
##########
##########
## ##
## ##
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 420 bytes
```
(()()()){({}<(({})){({}<<>(<>({})<>){({}<((((()()()()){}){}()){}())>[(
)])}{}(<>({})<>){({}<((((()()()()){}){}){})>[()])}{}(<>({})<>){({}<(((
(()()()()){}){}()){}())>[()])}{}(<>({})<>){({}<((((()()()()){}){}){})>
[()])}{}((()()()()()){})<>>[()])}{}((({}))<(({})(({}){}){})>){({}<<>(<
>({})<>){({}<((((()()()()){}){}()){}())>[()])}{}((()()()()()){})<>>[()
])}{}{}>[()])}{}({}<>)(({})((({({})({}[()])}{})){}){}{}){({}<{}>[()])}
```
[Try it online!](https://tio.run/##pU/LCoBACPwdPXTovgh9R3TYDkEUHbqK32662eMSBbEyusyMMv2ax6Ua5jypAqA/ZGBJYBBjIrCyb6KDg9C6WqxKN6AWsEOx@c3h9V39d/9J7nSiO@VB97wFwvsj@/M1lktlywjjLHDpLAcbux1cePpUa62aDQ "Brain-Flak – Try It Online")
No, the score of 420 was not intentional. I promise. Readable version:
```
# 3 Times...
(()()())
{
({}<
#Duplicate the input
(({}))
#Input times...
{
({}<
#Switch to the main stack
<>
#Grab the duplicate of the input
(<>({})<>)
#That many times...
{({}<
# Push a hash
((((()()()()){}){}()){}())
>[()])}{}
#Grab the duplicate of the input
(<>({})<>)
#That many times...
{({}<
#Push a space
((((()()()()){}){}){})
>[()])}{}
#Grab the duplicate of the input
(<>({})<>)
#That many times...
{({}<
# Push a hash
((((()()()()){}){}()){}())
>[()])}{}
#Grab the duplicate of the input
(<>({})<>)
#That many times...
{({}<
#Push a space
((((()()()()){}){}){})
>[()])}{}
#Push a newline
((()()()()()){})
#Toggle back to the alternate stack
<>
#Decrement the (second) loop counter
>[()])
#Endwhile
}
#Pop the now zeroed loop counter
{}
#Turn [a] into [a, a*5, a]
((({}))<(({})(({}){}){})>)
#A times....
{
({}<
#Toggle back over
<>
#Grab a*5
(<>({})<>)
#That many times...
{({}<
#Push a space
((((()()()()){}){}()){}())
>[()])}{}
#Push a newline
((()()()()()){})
#Toggle back
<>
#Decrement the (second) loop counter
>[()])
}
#Pop the loop counter and the a*5
{}{}
#Decrement the outer loop counter
>[()])
}
#Pop the zeroed loop counter
{}
#Pop a over
({}<>)
#Pushes (a**2) * 5 + a
(({})((({({})({}[()])}{})){}){}{})
#That many times...
{({}<
#Pop a character off the output stack
{}
>[()])}
```
[Answer]
# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 59 56 bytes
```
00 C0 20 9B B7 A9 06 85 FC 86 FE A6 FE 86 FD A9 03 4D 1F C0 8D 1F C0 C6 FC D0
01 60 A9 23 A0 05 49 00 20 D2 FF CA D0 FA A6 FE 88 D0 F3 A9 0D 20 D2 FF C6 FD
D0 E6 F0 D3
```
### [Online demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"hash.prg":"data:;base64,AMAgm7epBoX8hv6m/ob9qQNNH8CNH8DG/NABYKkjoAVJACDS/8rQ+qb+iNDzqQ0g0v/G/dDm8NM="%7D,"vice":%7B"-autostart":"hash.prg"%7D%7D)
Usage: `SYS49152,N` where N is a number between 1 and 255.
(values greater than 4 will already be too large for the C64 screen, starting from 8, the output is even too wide)
**Explanation**:
```
00 C0 .WORD $C000 ; load address
.C:c000 20 9B B7 JSR $B79B ; read N into X
.C:c003 A9 06 LDA #$06 ; number of "logical" lines plus 1 for hash
.C:c005 85 FC STA $FC ; store in counter variable for lines
.C:c007 86 FE STX $FE ; store N in counter variable for char repetitions
.C:c009 A6 FE LDX $FE ; load repetition counter
.C:c00b 86 FD STX $FD ; store in counter variable for line repetitions
.C:c00d A9 03 LDA #$03 ; value to toggle the character toggle
.C:c00f 4D 1F C0 EOR $C01F ; xor character bit toggle
.C:c012 8D 1F C0 STA $C01F ; store character bit toggle
.C:c015 C6 FC DEC $FC ; decrement "logical" lines
.C:c017 D0 01 BNE $C01A ; not 0 -> continue
.C:c019 60 RTS ; program done
.C:c01a A9 23 LDA #$23 ; load hash character
.C:c01c A0 05 LDY #$05 ; load "logical" columns for hash
.C:c01e 49 00 EOR #$00 ; in each odd "logical" line, toggle character
.C:c020 20 D2 FF JSR $FFD2 ; output one character
.C:c023 CA DEX ; decrement character repetition
.C:c024 D0 FA BNE $C020 ; not 0 -> back to output
.C:c026 A6 FE LDX $FE ; reload character repetition
.C:c028 88 DEY ; decrement "logical" columns
.C:c029 D0 F3 BNE $C01E ; not 0 -> back to character toggle
.C:c02b A9 0D LDA #$0D ; line done, load newline character
.C:c02d 20 D2 FF JSR $FFD2 ; and output
.C:c030 C6 FD DEC $FD ; decrement line repetitions
.C:c032 D0 E6 BNE $C01A ; not 0 -> back to character init
.C:c034 F0 D3 BEQ $C009 ; else back to main loop (toggle char toggling)
```
[![Screenshot](https://i.stack.imgur.com/XzZd6.png)](https://i.stack.imgur.com/XzZd6.png)
[Answer]
# [Haskell](https://www.haskell.org/), 43 bytes
```
l%n=l!!1:l++l<*[1..n]
f n=["##"%n,"# "%n]%n
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0c1zzZHUdHQKkdbO8dGK9pQTy8vlitNIc82WklZWUk1T0dJWQFIxarm/c9NzMxTsFXITSzwVSgoLQkuKfLJU1BRSFMw@Q8A "Haskell – Try It Online")
Outputs a list of strings.
[Answer]
# [Python 2](https://docs.python.org/2/), 55 bytes
```
def f(n):p=[(" "*n+"#"*n)*2]*n;print(p+["#"*n*5]*n)*2+p
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI0/TqsA2WkNJQUkrT1tJGUhqahnFauVZFxRl5pVoFGhHgwW1TGPBMtoF/9PyixQyFTLzFIoS89JTNQx1zDSt0jQyNSE6/gMA "Python 2 – Try It Online")
This returns a 2D list of characters.
# [Python 2](https://docs.python.org/2/), 65 bytes
```
def f(n):p=((" "*n+"#"*n)*2+"\n")*n;print(p+("#"*n*5+"\n")*n)*2+p
```
[Try it online!](https://tio.run/##NYu7DoAgDAB/palLCy6S6IDxT1xMBGUpDXHx6/EVl1vuTs9jz@JqXUOESMJeJyIENGKxucnGWZwF2cioJclBauk1pv/F02iNuUCCJFAW2QJ17cA@UuJvqxc "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 66 bytes
```
def f(n):p=[(" "*n+"#"*n)*2]*n;print'\n'.join((p+["#"*n*5]*n)*2+p)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI0/TqsA2WkNJQUkrT1tJGUhqahnFauVZFxRl5pWox@Sp62XlZ@ZpaBRoR4OltUxjwWq0CzT/p@UXKWQqZOYpFCXmpadqGOqYaVqlaWRqQjT/BwA "Python 2 – Try It Online")
[Answer]
## [Husk](https://github.com/barbuz/Husk), ~~12~~ 10 bytes
```
´Ṫ▲Ṙ" # #
```
[Try it online!](https://tio.run/##yygtzv7//9CWhztXPZq26eHOGUoKykD4//9/YwA "Husk – Try It Online")
Note the trailing space.
## Explanation
```
´Ṫ▲Ṙ" # # Implicit input, e.g. n=2.
Ṙ" # # Repeat each character of the string n times: " ## ## "
´Ṫ Outer product with itself by
▲ maximum: [" ## ## "," ## ## ","##########","##########"," ## ## "," ## ## ","##########","##########"," ## ## "," ## ## "]
Print implicitly, separated by newlines.
```
[Answer]
# CJam, ~~27~~ ~~26~~ 25 bytes
```
{_[{S3*'#*'#5*}3*;]fe*e*}
```
[Try it online!](https://tio.run/##S85KzP2fqqwQlJqYopCYp5CZV5KanlqkkFaUn6sQHOLi6cdVlPm/Oj66OthYS10ZiEy1ao21rGPTUrVStWrBWkvzFEoyUhWScvKTs4FmpCik5RflJpaABYtSi0tzSoq56hT8tP6bAAA "CJam – Try It Online")
Fun fact: This originally started at 29 bytes, and bytes have been removed one-by-one ever since, alternating between block and full-program mode.
## Explanation:
```
{ e# Stack: | 2
_ e# Duplicate: | 2 2
[ e# Begin array: | 2 2 [
{ e# Do the following 3 times:
S e# Push a space | 2 2 [" "
3* e# Repeat it 3 times: | 2 2 [" "
'#* e# Join with '#': | 2 2 [" # # "
'# e# Push '#': | 2 2 [" # # " '#
5* e# Repeat it 5 times: | 2 2 [" # # " "#####"
}3* e# End: | 2 2 [" # # " "#####" " # # " "#####" " # # " "#####"
; e# Delete top of stack: | 2 2 [" # # " "#####" " # # " "#####" " # # "
] e# End array: | 2 2 [" # # " "#####" " # # " "#####" " # # "]
fe* e# Repeat characters: | 2 [" ## ## " "##########" " ## ## " "##########" " ## ## "]
e* e# Repeat strings: | [" ## ## " " ## ## " "##########" "##########" " ## ## " " ## ## " "##########" "##########" " ## ## " " ## ## "]
} e# End
e# Result:
e# [" ## ## "
e# " ## ## "
e# "##########"
e# "##########"
e# " ## ## "
e# " ## ## "
e# "##########"
e# "##########"
e# " ## ## "
e# " ## ## "]
```
[Answer]
# [Perl 5](https://www.perl.org/), 49 + 1 (-p) = 50 bytes
```
$_=' # #
'=~s/./$&x$_/gre x$_;$_.=(y/ /#/r.$_)x2
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lZdQRkIudRt64r19fRV1CpU4vXTi1IVgLS1SryerUalvoK@sn6Rnkq8ZoXR//8m//ILSjLz84r/6/qa6hkYGvzXLQAA "Perl 5 – Try It Online")
**How?**
Implicitly store the input in `$_` via the `-p` flag. Start with the most basic possible top line `" # # "` with its trailing newline. Replicate each of those characters by the input number. Then replicate that by the input number to form the top part of the octothorpe, storing all of that back in `$_`. Then append the line with all characters replaced by '#' times the input number. Then append the top section. Do those last two sentences a total of two times. Output of the `$_` is implicit in the `-p` flag.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
NθUOײθ#UOθ F²⟲OO²⁴⁶θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05rLPyknPy9dIyQzN7VYw0hHoVBTR0FJWQkhUwjkK4D4aflFChpGmgpB@SWJJan@ZalFOYkFUErDyMQMpNf6/3/T/7pl/3WLcwA "Charcoal – Try It Online") Link is to verbose version of code. I'd originally tried a cute bitmap approach:
```
F⁵F⁵F&|ικ¹«J×ιIθ×κIθUOθ#
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw1RTAYV2yiwpzyxOdcxLgTH9izQydRSyNXUUDDU1Faq5OL1KcwtC8jVCMnNTi0FSzonFJRqFmkAFEKFshJCmNRenf1JOfl66RqGOgpKykiZX7f//pv91y/7rFucAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Works by considering the `#` as an array of 5×5 squares. The squares that are in odd rows or columns need to be filled in.
[Answer]
# J, 22 bytes
```
#('# '{~#:5$21,0)#~"1]
```
[Try it online!](https://tio.run/##y/r/P03B1kpBWUNdWUG9uk7ZylTFyFDHQFO5TskwlosrNTkjXyFNTc9OwVDBSMGYy89JTwHEKy1OTVEoyVdIyq9QKMlIVcgvLSkoLSn@/x8A)
A lot of similarity to the other J answer, though I don't understand trains with lots of nouns well, so my answer has three potential bytes to cut off (two parens and a reflexive-`~`).
# Explanation
### Generating the octothorpe
The octothorpe is made by everything in the parenthetical, reproduced below for convenience.
```
'# '{~#:5$21,0
```
A lot of the way I make the octothorpe is abuse of the way that J pads its arrays when they aren't long enough.
`21,0` simply creates the array `21 0`.
`5$` reshapes that array into a 5-atom array: `21 0 21 0 21`.
`#:` converts each atom into a binary number. Since `#:` operates on each atom, the output is a matrix. Each `21` is replaced by `1 0 1 0 1` as expected, but each `0` is replaced by `0 0 0 0 0`! This is because J pads arrays not long enough to match the shape of the resulting 2D array which is forced to be `5 5` because of the `1 0 1 0 1` rows. Fortunately, for numbers it pads with `0`, so we get the resulting matrix
```
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
```
`'# '{~` converts each `1` to a space and `0` to `#`. `{` means "take" and `~` means "switch the dyadic arguments, so J looks to each element in the matrix as indices for the string `'# '` meaning each `0` becomes the zeroth element, `#` and each `1` becomes the first element, a space. This yields the size one octothorpe.
### Resizing the octothorpe
This is simply a matter of copying `n` times along each axis, done using
the first `#` (which is part of a hook) and `#~"1]`. `#` copies along the horizontal axis and `#"1` copies along the vertical axis.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ ~~13~~ 11 bytes
*Saved 2 bytes thanks to @JonathanAllen*
```
5ẋ€Ẏ&þ`ị⁾ #
```
A monadic link returning a list of lines. Note the trailing space.
[Try it online!](https://tio.run/##ASQA2/9qZWxsef//NeG6i@KCrOG6jibDvmDhu4vigb4gI//Dh1n//zg "Jelly – Try It Online")
### How it works
```
5ẋ€Ẏ&þ`ị⁾ # Main link. Arguments: n (integer) 1
5 Yield 5.
ẋ€ Create a range and repeat each item n times. [[1], [2], [3], [4], [5]]
Ẏ Tighten; dump all sublists into the main list.
[1, 2, 3, 4, 5]
þ Create a table of [[1, 0, 1, 0, 1],
& bitwise ANDs, [0, 2, 2, 0, 0],
` reusing this list. [1, 2, 3, 0, 1],
[0, 0, 0, 4, 4],
[1, 0, 1, 4, 5]]
ị⁾ # Index into the string " #". [" # # ",
0 -> "#", 1 -> " ", 2 -> "#", etc. "#####",
" # # ",
"#####",
" # # "]
```
[Answer]
# [J](http://jsoftware.com/), ~~23~~ 19 bytes
```
' #'{~1=]+./~@#i:@2
```
Saved 4 bytes thanks to @LeakyNun.
[Try it online!](https://tio.run/##y/r/P03B1kpBXUFZvbrO0DZWW0@/zkE508rBiIsrNTkjX0FHTyFNTc9OwVDBSMH4/38A)
## Explanation
```
' #'{~1=]+./~@#i:@2 Input: integer n
2 The constant 2
i:@ Range [-2, -1, 0, 1, 2]
] Get n
# Copy each n times
+./~@ GCD table
1= Equals 1, forms the hashtag for input 1
' #'{~ Index and select the char
```
[Answer]
# Game Maker Language, ~~138~~ 108 bytes
```
n=argument0 s=''for(j=0;j<5*n;j+=1){for(l=0;l<5*n;l+=1)if(j div n|l div n)&1s+='#'else s+=' 's+='
'}return s
```
Intended as a script (Game Maker's name for user-defined functions), thus the `n=argument0` and `return s`. 20 bytes could be shaved by taking `n` directly from the current instance and using `s` as the result. (The instance gets these variables anyway because they weren't declared with `var`).
Beware of course that `#` is used by Game Maker's graphics stuff as an alternative newline character, so you might want to prefix it with `\` if you want to output to the screen ;)
Also note that I'm using Game Maker 8.0's version of GML here; modern GML versions might have features that could save additional bytes.
Some ideas courtesy of friends wareya and chordbug.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~338~~ 332 bytes
6 bytes thanks to Riley.
```
(({}<>)<(())>)(()()()()()){({}<(<>)<>{({}<<>({}<(((((()()()()())){})){}{}{})<>([({})]()){(<{}({}<((((({}))){}){}{}){({}<<>(({}))<>>[()])}{}>)>)}{}(({})<{{}(<(()()()()()){({}<<>(<([{}](((((()()){}){}){}){}()){}())>)<>{({}<<>({}<(({}))>())<>>[()])}<>({}<>{})>[()])}{}>)}>{})<>((()()()()()){})>())<>>[()])}<>({}<>{}<([{}]())>)>[()])}<>
```
[Try it online!](https://tio.run/##dU@7DgJBCPwdKK6yJZP4HZstzsLEaCxsCd@OwHrrqXHZJzMws6fHerkv59t6dSdSE7AQMYNj34I1EUoMdRVUosabxWq5MoJILTjcq1rUZkGSklm0rVtlBWjEnQNAGIij8qJxkR87USXU1Pq0MbqOWa/6x5flFALtxAaAyO/UDeMPH6r2p/BlI8Um5H7w5fgE "Brain-Flak – Try It Online")
## More "readable" version
```
(({}<>)<(())>)(()()()()())
{({}<(<>)<>{({}<<>({}<(((((()()()()())){})){}{}{})<>
([({})]()){(<{}({}<
((((({}))){}){}{}){({}<<>(({}))<>>[()])}{}
>)>)}{}(({})<{{}(<
(()()()()()){({}<<>(<([{}](((((()()){}){}){}){}()){}())>)<>{({}<<>({}<(({}))>())<>>[()])}<>({}<>{})>[()])}{}
>)}>{})
<>((()()()()()){})>())<>>[()])}<>({}<>{}<([{}]())>)>[()])}<>
```
[Try it online!](https://tio.run/##dU8xDsIwDNz7io720InVssQ7ogxlQEIgBlbLbw9nh7QFiSStnLuz73J5rbfncn2s99aIzEVZiJiV8R@bJwuKgtQsRRPItcvYPL7YEE7zTAUyrqCMxDx6gAKPFeLoSPmYmqioFuLKICBXhEGVlBiKMWM3Ht1Cxbxusfr0fvKWD/t5QhgqHUw7ocC/U3hAU2Q8Ovuf5k@UMNyo1k5tOb8B "Brain-Flak – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ ~~22~~ 21 bytes
```
•LQ•bûε×}5ôεS„# èJ¹F=
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UcMin0AgkXR497mth6fXmh7ecm5r8KOGecoKh1d4HdrpZvv/v5EBAA "05AB1E – Try It Online")
---
***-1 because Emigna hates transliterate and, thankfully, reminds me I should too :P.***
---
Gotta be a better way than bitmapping it... Still working.
[Answer]
## JavaScript (ES6), 79 bytes
```
f=
n=>[...Array(n*5)].map((_,i,a)=>a.map((_,j)=>` #`[(i/n|j/n)&1]).join``).join`
`
```
```
<input type=number oninput=o.textContent=f(this.value)><pre id=o>
```
Port of the bitmap approach that I'd used for my original Charcoal attempt.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~124~~, ~~116~~, ~~113~~, ~~112~~, ~~98~~, ~~96~~ 66 bytes
New (Credit: HyperNeutrino):
```
def f(a):i='print(" "*a+"#"*a)*2;'*a;exec(i+'print"#"*a*5;'*a)*2+i
```
Old:
```
a=input();b,c="# "
for i in"012":
exec'print c*a+b*a+c*a+b*a;'*a
if i<"2":exec'print b*a*5;'*a
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9E2M6@gtERD0zpJJ9lWSVlBiSstv0ghUyEzT8nA0EjJiosztSI1Wb2gKDOvRCFZK1E7CYihtLW6ViIXZ2aaQqaNElApkkKgpJYpSPr/f2MA "Python 2 – Try It Online")
Obviously not the shortest solution, but I think it's decent. Any feedback would be appreciated!
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), 224 bytes
```
,[->+>>>>+<<<<<]>>>+>+++++[-<<<[->+>>>>>+>+++++[-<<<[->+<<<[->>>>>>+<<[->>>+>---<<<<]<<<<]>>>>>>[-<<<<<<+>>>>>>]>[-<<<+>>>]+++++[->+++++++<]>.[-]<<<<<<]>[-<+>]>[-<->]<+[->+<]>>]<<++++++++++.[-]<<<<<]>[-<+>]>[-<->]<+[->+<]>>]
```
[Try it online!](https://tio.run/##dY5LCoAwDAUXHucZT1BykZKFCoIILgTPH/Np3YizaT4vQ5dr3s/tXg/VsRKDDRRHvGI4lazv288wH26XUYKJKCTdZMSBkRaWHHgnTZhiwC6mSlLaPyyHjBNLiZw7bY@XN/8fVx0e "brainfuck – Try It Online")
## Making-of
I tried to build this code by hand and spent quite a few hours, so I decided to make a transpiler in Python.
Here is the code I entered to make this code:
```
read(0)
copy(0,(1,1),(5,1))
add(3,1)
add(4,5)
loop(4)
loop(1)
add(2,1)
add(7,1)
add(8,5)
loop(8)
loop(5)
add(6,1)
loop(3)
add(9,1)
loop(7)
add(10,1)
add(11,-3)
end(7)
end(3)
copy(9,(3,1))
copy(10,(7,1))
add(10,5)
copy(10,(11,7))
write(11)
clear(11)
end(5)
copy(6,(5,1))
copy(7,(6,-1))
add(6,1)
copy(6,(7,1))
end(8)
add(6,10)
write(6)
clear(6)
end(1)
copy(2,(1,1))
copy(3,(2,-1))
add(2,1)
copy(2,(3,1))
end(4)
```
[Try it online!](https://tio.run/##hZPBboMwDIbPzVNEnEibTFAKtFXbF5l6YAM6JpREgDT16ZljJ4hduktj@//92QmqfU5fRmezNeM1YeM1iljdtPxhJhNbcWabR28@qp6DLke26VpubxCf@bi7RrdoG1sFqSDlsigXp5hRWVAc2iK1quvYSr3CAtKPQoK@JdS/i7aaKhdfUUBUWiBnaKr6z3ZrjDNLusXP0E3NS@MbGXtj7EvfuyJjo18PvpPt09gn3HRbOauHs01rBt7Jb95pPpphauoYdPcmUASZ2NTfN9Xwz0L3aMZ3SATDcYmMU5kKGefwK5jjZhBhcJC5YLjHwZ9e2DsHRmXwHhfv0Z85CQV6sZJR5eQqWCipkCaBkqZSgcvdqaQj83ueJO7lM@jA0Ut/vhIAUoJCnzEFMr2LixAZvEW4NGalhIIKSNw6uGiSaz0uahIGFIFfeHxo3NPL@iyTUFjwe7lyZQv@IGY7dHqKRwkp/KvE/As)
[Answer]
# [Befunge](https://github.com/catseye/Befunge-93), ~~105~~ 103 bytes
```
p9p&5*08p>08g- v
>,g1+:00p^v0:/5g8_p9g1+:09p08g-#v_@
gvg90\/\g0< # # ##### 0:/5g8,+55<
^>\/2%5*+92++2
```
[Try it online!](https://tio.run/##JYpBCoQwDADvfUVA3INRmgRzUKTsQ4rCgpvbkov9fpfqzG2Yz/m9fnbW6uwvHUg8kdgEACVAMsaVyPdCa1STw/ku7O3pyvEOMBamHLPRBl2zAc8@ouoWbE@Wo/Q64CKIUuv8Bw "Befunge – Try It Online")
[Answer]
# [MAWP 2.0](https://esolangs.org/wiki/MAWP), 46 bytes
```
@!!!"#"*/" "*\+2*"
"+*!:/!5*"#"*"
"+*!:\!:/:/:
```
[Try it!](https://8dion8.github.io/MAWP/v2.0?code=%40!!!%22%23%22*%2F%22%20%22*%5C%2B2*%22%0A%22%2B*!%3A%2F!5*%22%23%22*%22%0A%22%2B*!%3A%5C!%3A%2F%3A%2F%3A&input=3)
[Answer]
# [SOGL (SOGLOnline commit 2940dbe)](https://github.com/dzaima/SOGLOnline/tree/2940dbe13bc955f6456c1d3a737b40e255a1d103), 15 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
ø─Ζ┘Χ⁴‘5n{.∙.*T
```
To run this, download [this](https://github.com/dzaima/SOGLOnline/archive/2940dbe13bc955f6456c1d3a737b40e255a1d103.zip) and run the code in the `index.html` file.
Uses that at that commit (and before it) `*` repeated each character, not the whole string.
Explanation:
```
ø─Ζ┘Χ⁴‘ push " # # ##### # # ##### # # "
5n split into lines of length 5
{ for each line do
.∙ multiply vertically input times
.* multiply horizontally input times
T output in a new line
```
Bonus: add 2 inputs for separate X and Y length!
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~98~~ 93 bytes
5 bytes thanks to Felix Palmen.
```
i,j;main(a){for(scanf("%d",&a);j<a*5||(j=!puts(""),++i<a*5);)putchar(i/a+1&j++/a+1&1?32:35);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9TJ8s6NzEzTyNRszotv0ijODkxL01DSTVFSUctUdM6yyZRy7SmRiPLVrGgtKRYQ0lJU0dbOxMkqmmtCRRKzkgs0sjUT9Q2VMvS1gbThvbGRlbGQPna//8tAA "C (gcc) – Try It Online")
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 9 bytes
```
# ”ṫ&:Ṁ‡
```
Pretty much a port of [Zgarb's great answer](https://codegolf.stackexchange.com/a/139584/53880)
[Try it online!](https://tio.run/##ASAA3/9nYWlh//8gIyDigJ3huasmOuG5gOKAof/ih5HhuaP/Mw "Gaia – Try It Online") (the footer is just to pretty print, the program itself returns a 2D list of characters)
### Explanation
```
# ” Push the string " # "
ṫ Bounce, giving " # # "
& Repeat each character by input
: Copy
Ṁ‡ Tabled maximum with itself
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 11 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
#¶##┼∙┼╶╶*
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JTIwJTIzJUI2JTIzJTIzJXUyNTNDJXUyMjE5JXUyNTNDJXUyNTc2JXUyNTc2JXVGRjBB,i=Mw__,v=1)
Explanation:
```
#¶## push "#\n##"
┼ quad-palindromize with 1 overlap
∙┼ quad-palindromize with 1 overlap again
╶╶* expand vertically and horizontally by the input
```
[Answer]
# Python, ~~88~~ ~~84~~ 77 bytes
```
lambda x:[[(' #'[i//x%2]+'#')[j//x%2]for j in range(5*x)]for i in range(5*x)]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCKjpaQ11BWT06U1@/QtUoVltdWV0zOgvCScsvUshSyMxTKErMS0/VMNWq0ASLZaKJ/QcJJiIJalpxcRYUZeaVaCRqwljqMXnqeln5mXkauYkFGuoQto5CGlAJEPwHAA)
Returns 2D list of characters.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~72~~ ~~68~~ ~~63~~ 60 bytes
```
param($a)(,($x=,((' '*$a+"#"*$a)*2)*$a)+,("#"*5*$a)*$a)*2;$x
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRU0NHQ6XCVkdDQ11BXUslUVtJWQlIaWoZaYIobR0NkIApWAgsbK1S8f//f2MA "PowerShell – Try It Online")
Takes input `$a`. Then, we do a bunch of ~~magic~~ string and array manipulation.
```
(,($x=,((' '*$a+"#"*$a)*2)*$a)+,("#"*5*$a)*$a)*2;$x
' '*$a+"#"*$a # Construct a string of spaces and #
( )*2 # Repeat it twice
,( )*$a # Repeat that $a times to get the top as an array
($x= ) # Store that into $x and immediately output it
, + # Array concatenate that with ...
,("#"*5*$a) # another string, the middle bar ...
*$a # repeated $a times.
( )*2; # Do that twice
$x # Output $x again
```
You can peel off the parts of the explanation starting from the bottom to see how the output is constructed, so hopefully my explanation makes sense.
[Answer]
## Haskell, 72 bytes
```
a#b=a++b++a++b++a
c%l=((c<$l)#('#'<$l))<$l
f n=(' '%[1..n])#('#'%[1..n])
```
Returns a list of strings. [Try it online!](https://tio.run/##y0gszk7Nyfn/P1E5yTZRWztJWxtKciWr5thqaCTbqORoKmuoK6uDGJpAgitNIc9WQ11BXTXaUE8vLxYiC@P8z03MzFOwVchNLPBVKCgtCS4p8slTUFFIUzD5DwA "Haskell – Try It Online")
How it works:
```
a#b=a++b++a++b++a -- concatenate the strings a and b in the given pattern
c%l= -- take a char c and a list l (we only use the length
-- of l, the actual content doesn't matter)
c<$l -- make length l copies of c
'#'<$l -- make length l copies of '#'
# -- combine them via function #
<$l -- and make length l copies of that string
f n= -- main function
# -- make the "a b a b a" pattern with the strings
-- returned by the calls to function %
' '%[1..n] -- one time with a space
'#'%[1..n] -- one time with a '#'
```
[Answer]
# Mathematica, 63 bytes
```
ArrayFlatten@Array[x=#;Table[If[OddQ@-##," ","#"],x,x]&,{5,5}]&
```
### Explanation
```
ArrayFlatten@Array[x=#;Table[If[OddQ@-##," ","#"],x,x]&,{5,5}]& (* input N *)
x=# (* Set x to N *)
& (* A function that takes two inputs: *)
If[OddQ@-##," ","#"] (* if both inputs are odd (1), " ". "#" otherwise *)
Table[ ,x,x] (* Make N x N array of that string *)
Array[ ,{5,5}] (* Make a 5 x 5 array, applying that function to each index *)
ArrayFlatten@ (* Flatten into 2D array *)
```
(1)`-##` parses into `Times[-1, ##]`
[Answer]
# Python 2, 113 bytes
**As an array of strings:**
```
r=[1-1*(i%(2*n)<n)for i in range(5*n)]
print[''.join(' #'[r[k]+r[j]>0]for k in range(len(r)))for j in range(n*5)]
```
---
**As ASCII art:**
# Python 3, 115 bytes
```
r=[1-1*(i%(2*n)<n)for i in range(5*n)]
for j in range(n*5):print(*(' #'[r[k]+r[j]>0]for k in range(len(r))),sep='')
```
# Python 3, 117 bytes
```
p=range(5*n)
for i,e in enumerate([j%(2*n)>=n for j in p]for k in p):print(*[' #'[i%(2*n)>=n or k]for k in e],sep='')
```
---
~~**As an array of booleans**~~
# Python 2, 75 bytes
```
p=range(5*n)
f=lambda o:o%(2*n)>=n
print[[f(j)or f(i)for j in p]for i in p]
```
[Answer]
# Java 8, 103 bytes
Lambda accepts `Integer` and prints the octothorpe to standard out. Cast to `Consumer<Integer>`.
```
n->{for(int s=5*n,x=0,y;x<s;x++)for(y=0;y<s;)System.out.print((x/n%2+y++/n%2>0?'#':32)+(y<s?"":"\n"));}
```
[Try It Online](https://tio.run/##XY8xT8MwEIXn5FdYQag2bk3UiqVu0oGJATF0BAbjusEhsSP7HCWq8tuDA0xMp7t37@l7tejFxnbK1OevuQsfjZZINsJ79Cy0Qdc06ZzuBSjkQUAU62hgAXTDLsFI0NawR2t8aJU7PBlQlXIlih4DLxIsfFrXKVTMZlNeL9bheEe@eLgz66HI1yMfDp4PlJJFG4ucj3Enp9GDapkNwH6SMB7uze2WjpQus8yPq5vVfrclFMf/Y5btszeTEcKnOeFpRP7t8UfcW31GbWyDTxDTqtd3JFzlyVIu@UfKhJSqA7wjPE2mdJq/AQ)
## Ungolfed lambda
```
n -> {
for (
int
s = 5 * n,
x = 0,
y
;
x < s;
x++
)
for (y = 0; y < s; )
System.out.print(
(x / n % 2 + y++ / n % 2 > 0 ? '#' : 32)
+ (y < s ? "" : "\n")
);
}
```
The key observation here is that, on a 5 by 5 grid of *n* by *n* cells, octothorpes appear wherever the row or column number (0-based) is odd. I'm pretty sure this is the cheapest general approach, but it seems further golfable.
## Acknowledgments
* -1 byte thanks to *Kevin Cruijssen*
] |
[Question]
[
Write a program or function that duplicates letters in a word, so that all the duplicated letters arranged from left to right in the word would form the input array.
For example:
```
input: chameleon, [c,a,l,n]
output: cchaamelleonn
```
## Input
* The starting word (e.g. `chameleon`)
* An array of characters (`[c,a,l,n]`) or a string to represent an array (`caln`), or something similar
* Input can be through function parameters, STDIN or language equivalents
* All inputs will be lower-case letters (a-z)
## Output
* The changed word
* If there are multiple solutions, any can be printed
```
input: banana [n,a]
possible outputs: bannaana, banannaa
|-|---------|-|--->[n,a]
```
* You may assume that the input word (not necessarily the array) will have the letters in the array (in order)
* You may also assume that the inputs have no consecutive letters which are the same (NOT apple, geek, green, glass, door...)
## Examples
```
input: abcdefghij, [a,b,c]
output: aabbccdefghij
input: lizard, [i,a,r,d]
output: liizaarrdd
input: coconut, [c,o]
ouput: ccooconut or coccoonut or ccocoonut
input: onomatopoeia, [o,o,a,o,o]
output: oonoomaatoopooeia
input: onomatopoeia, [o,a,o]
output: oonomaatoopoeia or onoomaatoopoeia or oonomaatopooeia etc.
```
Shortest program wins!
Leaderboard (thanks to Martin Büttner for the snippet)
```
/* Configuration */
var QUESTION_ID = 51984; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
/* App */
var answers = [], page = 1;
function answersUrl(index) {
return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
if (data.has_more) getAnswers();
else process();
}
});
}
getAnswers();
var SIZE_REG = /\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;
var NUMBER_REG = /\d+/;
var LANGUAGE_REG = /^#*\s*([^,]+)/;
function shouldHaveHeading(a) {
var pass = false;
var lines = a.body_markdown.split("\n");
try {
pass |= /^#/.test(a.body_markdown);
pass |= ["-", "="]
.indexOf(lines[1][0]) > -1;
pass &= LANGUAGE_REG.test(a.body_markdown);
} catch (ex) {}
return pass;
}
function shouldHaveScore(a) {
var pass = false;
try {
pass |= SIZE_REG.test(a.body_markdown.split("\n")[0]);
} catch (ex) {}
return pass;
}
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
answers = answers.filter(shouldHaveScore)
.filter(shouldHaveHeading);
answers.sort(function (a, b) {
var aB = +(a.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0],
bB = +(b.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0];
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
answers.forEach(function (a) {
var headline = a.body_markdown.split("\n")[0];
//console.log(a);
var answer = jQuery("#answer-template").html();
var num = headline.match(NUMBER_REG)[0];
var size = (headline.match(SIZE_REG)||[0])[0];
var language = headline.match(LANGUAGE_REG)[1];
var user = getAuthorName(a);
if (size != lastSize)
lastPlace = place;
lastSize = size;
++place;
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", user)
.replace("{{LANGUAGE}}", language)
.replace("{{SIZE}}", size)
.replace("{{LINK}}", a.share_link);
answer = jQuery(answer)
jQuery("#answers").append(answer);
languages[language] = languages[language] || {lang: language, user: user, size: size, link: a.share_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: 50%;
float: left;
}
#language-list {
padding: 10px;
width: 50%px;
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]
# Brainfuck, ~~46~~ 45 (63 with printable characters in input)
Compatible with Alex Pankratov's [bff](http://swapped.cc/#!/bff) (brainfuck interpreter used on SPOJ and ideone) and Thomas Cort's [BFI](http://esoteric.sange.fi/brainfuck/impl/interp/BFI.c) (used on Anarchy Golf).
The printable version takes the array first as a string, followed by a tab, followed by the starting string with no trailing newline.
[Demonstration](http://ideone.com/4d2L5E) on ideone.
```
-[+>,---------]
<[++++++++<]
<,+
[
-.
[>+>-<<-]
>>
[
<[>+<-]
]
<[.[-]]
,+
]
```
We can save some bytes by using `\x00` as a separator instead of tab:
```
,[>,]
<[<]
<,+
[
-.
[>+>-<<-]
>>
[
<[>+<-]
]
<[.[-]]
,+
]
```
[Answer]
# CJam, 15 bytes
```
rr{_C#)/(C@s}fC
```
[Try it online.](http://cjam.aditsu.net/#code=rr%7B_C%23)%2F(C%40s%7DfC&input=onomatopoeia%20oao)
### How it works
```
rr e# Read two whitespace-separated tokens from STDIN.
{ }fC e# For each character C in the second string.
_ e# Duplicate the first string.
C# e# Compute the index of the character in the string.
)/ e# Add 1 and split the string in slice of that size.
( e# Shift out the first slice.
C e# Push the character.
@ e# Rotate the remainder of the string in top of the stack.
s e# Stringify (concatenate the slices).
```
[Answer]
# C, 62 bytes
```
f(char*s,char*c){while(*s-*c||putchar(*c++),*s)putchar(*s++);}
```
Well, this is surprisingly competetive.
We define a function `f(char*, char*)` that takes the string as its first input and the array of characters to duplicate as its second input.
Some testing code:
```
int main (int argc, char** argv) {
f("onomatopeia", "oao");
return 0;
}
```
Which prints:
```
oonomaatoopeia
```
Try it [online](http://ideone.com/IVHCqG)!
If it is acceptable to submit a macro rather than a function, the following `#define g(s,c)` is just **58 bytes**, but requires `s` and `c` to be actual pointers:
```
#define g(s,c)while(*s-*c||putchar(*c++),*s)putchar(*s++);
```
[Answer]
# CJam, 15 bytes
```
rr{:X/(XX+@X*}/
```
An alternative CJam approach. [Try it online](http://cjam.aditsu.net/#code=rr%7B%3AX%2F%28XX%2B%40X*%7D%2F&input=onomatopoeia%20oao)
## Explanation
For each character in the second string, we do two things.
1. Split the current suffix of the string by the character, e.g. `"beeper" "e" -> ["b" "" "p" "r"]`
2. Uncons the first string in the array, insert two of the character, then rejoin the rest of the array with the character, e.g. `"b" "ee" "eper"`. The last string is the new suffix.
[Answer]
## Python, 61
```
def f(s,l):b=s[:1]==l[:1];return s and-~b*s[0]+f(s[1:],l[b:])
```
A greedy recursive solution. Saves to `b` whether the first letter of the string `s` is the first letter of the string `l` of letters to double. If so, take one of that letter and prepend it to the recursive call with the rest of `s`, removing the first element from `l`. If not `b`, do the same but don't double the letter and don't remove from `l`.
The code checks `s[:1]==l[:1]` rather than `s[0]==l[0]` to avoid an index-out-of-bounds error when `s` or `l` is empty.
[Answer]
# Retina, 33 bytes
[More information about Retina.](https://github.com/mbuettner/retina)
```
+`(?=(.))(((.)(?<!\4.))+\n)\1
$1$2
```
This expects the two strings on STDIN, separated by a newline.
For counting purposes, each line goes into a separate file, `\n` should be replaced with an actual newline character (0x0A). If you actually want to test this, it's more convenient to put this in a single file where `\n` remains as it is and then invoke Retina with the `-s` option before passing the file.
## Explanation
*(Outdated... I managed to get rid of the marker... I'll update this later.)*
Each pair of lines is a regex substitution (first line the pattern, second line the substitution).
```
^
#
```
This puts a `#` as a marker at the start of the input string.
```
+`#(.*?(.))(.*\n)\2
$1$2#$3
```
This finds the first letter in the input (after the marker) corresponding to the next letter to be duplicated, duplicates that letter, moves the marker behind it, and drops the first character of the second string. The `+`` at the front tells Retina to do this repeatedly until the string stops changing (in this case, because the second string is empty and all required letters have been duplicated).
```
#
<empty>
```
Finally, we clean up the string by dropping the marker.
[Answer]
# Prolog, ~~95~~ ~~83~~ ~~79~~ 56 bytes
```
d([A|S],H):-put(A),H=[A|T],put(A),d(S,T);d(S,H).
d(_,_).
```
Example:
```
d(`chameleon`,`caln`).
```
returns
```
cchaamelleonn
```
Edit: Saved 4 bytes thanks to Oliphaunt
Edit2: Saved 20 bytes using the deprecated `put/1` SWI-Prolog predicate instead of `writef`. Saved one byte replacing the recursion end predicate `d([],_).` to `d(_,_).`. Won't work if the ordering of the two definitions of `d` is swapped though, but we don't care about that in golfed code. Saved another 2 bytes removing the parenthesis around `H=[A|T],put(A),d(S,T)`
[Answer]
# Python 2, ~~83~~ ~~74~~ ~~72~~ 65 Bytes
No real special tricks here. `x` is the string, `y` is the array of characters that are duplicated. ~~To clarify if this doesn't copy properly, the first indentation level is a space, the next is a tab.~~
*Edit 1: Saved 9 bytes by using string manipulation instead of pop().*
*Edit 2: Saved 2 bytes by using `-~` to increment `g` by 1.*
*Edit 3: Saved 7 bytes by using `y[:1]` trick, thanks to xnor for this!*
```
def f(x,y,s=''):
for c in x:g=y[:1]==c;s+=c*-~g;y=y[g:]
print s
```
[Check it out here.](http://ideone.com/itjEAj)
Properly formatted and explained:
```
def f(x,y,s=''): # Defining a function that takes our input,
# plus holds a variable we'll append to.
for c in x: # For every character in 'x', do the following:
g = y[:1] == c # Get the first element from the second string, will
# return an empty string if there's nothing left.
# Thanks to xnor for this trick!
s += c * -~g # Since int(g) would either evaluate to 0 or 1, we
# use the -~ method of incrementing g to multiply
# the character by 1 or 2 and append it to 's'
y = y[g:] # Again, since int(g) would either evaluate to 0
# or 1, use that to cut the first value off y, or
# keep it if the characters didn't match.
print s # Print the string 's' we've been appending to.
```
[Answer]
# Pyth, 14 bytes
```
s+L&@d<Q1.(QZz
```
[Demonstration.](https://pyth.herokuapp.com/?code=s%2BL%26%40d%3CQ1.(Q0z&input=onomatopoeia%0A%5B%22o%22%2C%22o%22%2C%22a%22%2C%22o%22%2C%22o%22%5D&debug=0)
Input style:
```
banana
["b","a","n","a"]
```
Explanation:
```
s+L&@d<Q1.(Q0z
Implicit: z = input(); Q = eval(input())
+L z Map (lambda d) over z, adding the result to each character.
@d<Q1 Intersection of d with Q[:1], up to the first element of Q.
& Logical and - if the first arg is truthy, evaluate and
return the second arg, otherwise return first arg.
.(Q0 Q.pop(0)
The addition will either be the empty string, for the empty
intersection, or the character that was Q[0] otherwise.
s Concatenate and print.
```
[Answer]
### Excel VBA, 110 bytes
This is my first entry to CodeGolf so I hope this is ok.
You enter the input word in A1 and then the letters to be replaced in B1 and the resulting word is displayed in a message box.
```
w = Cells(1, 1)
l = Cells(2, 1)
For i = 1 To Len(w)
x = Left(w, 1)
R = R + x
If InStr(l, x) > 0 Then
R = R + x
End If
w = Right(w, Len(w) - 1)
Next
MsgBox R
```
[Answer]
# Haskell, 42 bytes
```
(a:b)#e@(c:d)|a==c=a:a:b#d|1<2=a:b#e
a#_=a
```
Usage example:
```
*Main> "coconut" # "co"
"ccooconut"
*Main> "lizard" # "iard"
"liizaarrdd"
*Main> "onomatopoeia" # "ooaoo"
"oonoomaatoopooeia"
```
How it works:
If one string is empty, the result is the first string. Else: if the first characters of the strings match, take it two times and append a recursive call with the tails of the strings. If the characters don't match, take the first character of the first string and append a recursive call with the tail of the first string and the same second string.
[Answer]
# Pyth, ~~18~~ 17 bytes
```
sm?+d.(QZqd&QhQdz
```
[Live demo.](https://pyth.herokuapp.com/?code=sm%3F%2Bd.(QZqd%26QhQdz&input=chameleon%0A%5B%27c%27%2C%27l%27%2C%27a%27%2C%27n%27%5D&debug=1)
Saved 1 byte thanks to @Jakube.
## Explanation:
```
z Read the first line of input.
m For each character in that line
? qd&QhQ If (?) the first char of the stretch list (`&QhQ`)
and the current character are equal,
+d.(QZ Then double the current character and pop an element off
the stretch list.
d Otherwise, just return the same character.
s Join all the characters together.
```
## Original version:
```
jkm?+d.(QZqd&QhQdz
```
[Live demo for original.](https://pyth.herokuapp.com/?code=jkm%3F%2Bd.(QZqd%26QhQdz&input=chameleon%0A%5B%27c%27%2C%27l%27%2C%27a%27%2C%27n%27%5D&debug=1)
[Answer]
# Javascript, 47 bytes
```
(a,b)=>a.replace(/./g,d=>b[0]!=d?d:d+b.shift())
```
Taking advantage of some ES6 features.
[Answer]
# Pyth, 16 bytes
```
u|pH<GJxGH>GJwz
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=u%7CpH%3CGJhxGH%3EGJwz&input=coconut%0Aco&debug=0)
This is quite hacky. Stack-based languages might have an advantage here.
### Explanation
```
implicit: z = 1st input line, w = 2nd
u wz reduce, start with G = z
for each H in w, update G to:
xGH index of H in G
h +1
J store in J
<GJ substring: G[:J] (everything before index J)
pH print substring then H (without newlines)
| afterwards (actually or, but p always returns 0)
>GJ substring: G[J:] (everything from index J to end)
update G with ^
afterwards implicitly print the remainder G
```
[Answer]
# JavaScript ES6, 47 bytes
```
(w,s)=>w.replace(/./g,c=>c==s[0]?c+s.shift():c)
```
Assumes `s` is an array `["c","a","l","n"]`
[Answer]
## [><> (Fish)](http://esolangs.org/wiki/Fish), 68 34 Bytes
```
ri&:o&:&=\
l&io& /!?/
?!;20.\l!\
```
You can run it at [http://fishlanguage.com/playground](http://fishlanguage.com/playground/Libf2RavJY5mHi7iT) inputting the string as the initial stack (with " marks, i.e. "chameleon") and the array of extra letters as the input stack (no " marks i.e. caln).
Don't forget to press the Give button to seed the input stack.
```
r reverses the stack
i& reads in the first input, and stores it in the register
:o copies the top of the stack, and outputs the top of the stack
&:& puts register value on stack, copies it, then puts top stack into register
= checks if the top two values are equal, if yes push 1, else push 0
? if top value is non-zero, execute next instruction
! skips the following instruction (unless it was skipped by the previous ?)
If yes, then we proceed on the same line
&o puts register value on stack, and outputs it
i& reads in the first input, and stores it in the register
l puts length of stack on stack, then proceed to lowest line
If no, we go directly to the last line
l As above.
?!; If zero value (from length), then end execution
20. Push 2 and 0 onto stack, then pop top two values, and go to that position (2,0) (i.e. next instruction is at (3,0))
```
EDIT: Halved it! :)
[Answer]
# REGXY, 24 bytes
Uses [REGXY](http://esolangs.org/wiki/REGXY), a regex substitution based language. Input is assumed to be the starting word and the array, space separated (e.g. "chameleon caln").
```
/(.)(.* )\1| /\1\1\2/
//
```
The program works by matching a character in the first string with the first character after a space. If this matches, the character is repeated in the substitution and the character in the array is removed (well, not appended back into the string). Processing moves on to the second line, which is just a pointer back to the first line, which causes processing to repeat on the result of the previous substitution. Eventually, there will be no characters after the space, at which point the second branch of the alternation will match, removing the trailing space from the result. The regex will then fail to match, processing is completed and the result is returned.
If it helps, the iterative steps of execution are as follows:
```
chameleon caln
cchameleon aln
cchaameleon ln
cchaameleonn n
cchaameleonn (with trailing space)
cchaameleonn
```
The program compiles and executes correctly with the sample interpreter in the link above, but the solution is perhaps a bit cheeky as it relies on an assumption in the vagueness of the language specification. The spec states that the first token on each line (before the /) acts as a label, but the assumption is that a null label-pointer will point back to the first command in the file with a null label (or in other words, that 'null' is a valid label). A less cheeky solution would be:
```
a/(.)(.* )\1| /\1\1\2/
b//a
```
Which amounts to 27 bytes
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), ~~10~~ 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
iVvUèVÎ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=aVZ2VehWzg&input=ImJhbmFuYSIKWyJuIiwiYSJd)
```
iVvUèVÎ :Implicit map of each character U in the first input (the string)
i :Prepend
V : The second input (the array)
v : Remove this many elements from the start ...
Uè : Count the occurrences in U of
VÎ : The first element of V
```
[Answer]
# R, 119
Based on @Alex's [answer](https://codegolf.stackexchange.com/a/52013/41782), this one is a couple of bytes shorter:
```
function(s,a){message(unlist(lapply(strsplit(s,"")[[1]],function(x){if(length(a)&x==a[1]){a<<-a[-1];c(x,x)}else x})))}
```
Ungolfed:
```
function(s, a) {
message( # Prints to output
unlist( # Flattens list to vector
lapply( # R's version of map
strsplit(s,"")[[1]], # Split vector to characters
function (x) {
if (length(a) & x == a[1]) { # If there are still elements in a
# and there's a match
a <<- a[-1] # Modify a
c(x, x) # And return the repeated character
} else x # Otherwise just return it
}
)
)
)
}
```
[Answer]
# Perl, ~~73~~ ~~62~~ ~~59~~ 56
Entirely new approach yields much better results. Still, I bet it can be shorter.
Call as `f('coconut', ['c','o'])`.
```
sub f{($s,$a)=@_;$s=~s/(.*?)($_)/\U$1$2$2/ for@$a;lc$s}
```
For each character in the array, find the first occurrence and duplicate it, and turn everything up to it to uppercase. Then return the entire string, converted to lowercase.
EDIT: shaved a couple of more characters by getting rid of `shift` and `pop`.
---
The previous version:
```
sub f{join '',map{shift @{$_[0]}if s/($_[0][0])/$1$1/;$_}split //,shift}
```
[Answer]
## Ruby, ~~52~~ 47 bytes
**Solution:**
`f=->(s,a){s.chars.map{|c|c==a[0]?a.shift*2:c}.join}`
**Example:**
`p f.call('banana', ['n','a']) # => "bannaana"`
**Explanation:**
Proc form of a method which takes a string as the first argument, and an array of characters as the second argument. Maps a block onto an array of the characters in the string argument, which checks each character against first element of the comparison array, and if there is a match, removes the first element of the comparison array, and doubles it.
---
*update*
`f=->s,a{s.chars.map{|c|c==a[0]?a.shift*2:c}*''}`
[Answer]
# JavaScript ES6, 72 bytes
```
(s,a,i=0,b=[...s])=>a.map(l=>b.splice(i=b.indexOf(l,i+2),0,l))&&b.join``
```
This is an anonymous function that takes 2 parameters: the starting word as a string and the characters to stretch as an array. Ungolfed code that uses ES5 and test UI below.
```
f=function(s,a){
i=0
b=s.split('')
a.map(function(l){
i=b.indexOf(l,i+2)
b.splice(i,0,l)
})
return b.join('')
}
run=function(){document.getElementById('output').innerHTML=f(document.getElementById('s').value,document.getElementById('a').value.split(''))};document.getElementById('run').onclick=run;run()
```
```
<label>Starting word: <input type="text" id="s" value="onomatopoeia" /></label><br />
<label>Leters to duplicate: <input type="text" id="a" value="oao"/></label><br />
<button id="run">Run</button><br />Output: <output id="output"></output>
```
[Answer]
# Python 2, 77
```
def f(x,y,b=''):
for i in x:
try:
if i==y[0]:i=y.pop(0)*2
except:0
b+=i
print b
```
Call as:
```
f('onomatopoeia',['o','a','o'])
```
I may have got the byte count horribly wrong... Uses a mixture of spaces and tabs.
[Answer]
# rs, 39 bytes
[More information about rs.](https://github.com/kirbyfan64/rs)
There's already a Retina answer, but I think this one uses a slightly different approach. They were also created separately: when I began working on this one, that answer hadn't been posted.
Besides, this one is 6 bytes longer anyway. :)
```
#
+#(\S)(\S*) ((\1)|(\S))/\1\4#\2 \5
#/
```
[Live demo and test suite.](http://kirbyfan64.github.io/rs/index.html?script=%23%0A%2B%23(%5CS)(%5CS*)%20((%5C1)%7C(%5CS))%2F%5C1%5C4%23%5C2%20%5C5%0A%23%2F%0A&input=chameleon%20caln%0Aabcdefghij%20abc%0Alizard%20iard%0Acoconut%20co%0Aonomatopoeia%20ooaoo%0Aonomatopoeia%20oao%0A)
[Answer]
# JavaScript, 92 characters
```
function f(s,c){r="";for(i=0;i<s.length;i++){r+=s[i];if(c.indexOf(s[i])>-1)r+=s[i]}return r}
```
Unobfuscated version:
```
function stretch(str, chars) {
var ret = "";
for(var i = 0; i < str.length; i++) {
ret += str[i];
if(chars.indexOf(str[i]) > -1) {
ret += str[i];
}
}
return ret;
}
```
[Answer]
# R, ~~136~~ ~~128~~ 122 bytes
```
function(s,a){p=strsplit(s,"")[[1]];for(i in 1:nchar(s))if(length(a)&&(x=p[i])==a[1]){p[i]=paste0(x,x);a=a[-1]};message(p)}
```
This creates an unnamed function that accepts a string and a character vector as input and prints a string to STDOUT. To call it, give it a name.
Ungolfed + explanation:
```
f <- function(s, a) {
# Split s into letters
p <- strsplit(s, "")[[1]]
# Loop over the letters of s
for (i in 1:nchar(s)) {
# If a isn't empty and the current letter is the first in a
if (length(a) > 0 && p[i] == a[1]) {
# Replace the letter with itself duplicated
p[i] <- paste0(p[i], p[i])
# Remove the first element from a
a <- a[-1]
}
}
# Combine p back into a string and print it
message(p)
}
```
Examples:
```
> f("coconut", c("c","o"))
ccooconut
> f("onomatopoeia", c("o","a","o"))
oonomaatoopoeia
```
Saved 8 bytes thanks to MickeyT and another 3 thanks to jja!
[Answer]
## Perl, 51 bytes
```
$s=<>;$s=~s=^.*$_=$_=,$,.=$&for split"",<>;print$,;
```
Input is provided via STDIN. First input is the starting word (e.g. `chameleon`), second input is the letters as a single string (e.g. `caln`).
The above is just an obfuscated (read "prettier") way of doing the following:
```
$word = <>;
for $letter(split "", <>) {
$word =~ s/^.*$letter/$letter/;
$result .= $&;
}
print $result;
```
As we go through each letter, we replace from the start of the word up to the letter in the source word with just the new letter, and append the match (stored in `$&`) to our result. Since the match includes the letter and then gets replaced with the letter, each letter ends up appearing twice.
Because STDIN appends a new line character to both of our inputs, we're guaranteed to capture the remnants of the full word on the last match, i.e. the new line character.
[Answer]
# Bash+sed, 51
```
sed "`sed 's/./s!^[^&]*&!\U\&&!;/g'<<<$1`s/.*/\L&/"
```
Input from stdin; characters to be doubled as a single argument:
```
$ echo chameleon | strtech caln
cchaamelleonn
```
This works by constructing a sed program from `$2` and then executing it against `$1`. The sed program replaces the first occurrence of each replacement letter with two copies of its uppercase version, and downcases the whole lot at the end. For the example above, the generated sed program is
```
s!^[^c]*c!\U&C!;s!^[^a]*a!\U&A!;s!^[^l]*l!\U&L!;s!^[^n]*n!\U&N!;s/.*/\L&/
```
pretty-printed:
```
# if only sed had non-greedy matching...
s!^[^c]*c!\U&C!
s!^[^a]*a!\U&A!
s!^[^l]*l!\U&L!
s!^[^n]*n!\U&N!
s/.*/\L&/
```
I use the uppercase to mark characters processed so far; this avoids re-doubling characters that have already been doubled, or applying a doubling earlier than the previous one.
Earlier version, before clarification that order of replacement list is significant (44 chars):
```
sed "`sed 's/./s!&!\U&&!;/g'<<<$1`s/.*/\L&/"
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~41~~ 21 bytes
-20 bytes by adapting my answer [here](https://codegolf.stackexchange.com/questions/217690/speed-of-lobsters/218688#218688)
```
{x@&y{y_x,1+y~:*x}/x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6qucFCrrK6Mr9Ax1K6ss9KqqNWvqOXiSotWSs5IzE3NSc3PU7JWSk7MyVOKBYkmJiWnpKalZ2RmAYWBHIhoTmZVYlEKUCQTRIGFkvOT8/NKS0Ca8yEi+Xn5uYkl+QX5qZmJQOH8/MR8HDKJIHEA2J8znA==)
* `y{...}/x` set up a reduction seeded with `y` (the characters to repeat), run over the characters in `x` (the full string). confusingly, within the function itself, `x` and `y` are flipped. this ends up returning a boolean array with `2`s in the positions containing the desired matches and `1`s everywhere else
+ `1+y~:*x` compare the first character to search for (`*x`) to the current character being iterated over (`y`), updating `y` with the result of `0` or `1`. then add one to this; this represents the number of copies of the current character to end up returning. note that as soon as we have matched all the search characters, no more matches will be identified (since a character will never `~` (match) a `1` or `2`)
+ `x,` append this result to the list of characters to search for (essentially overloading the reduction to end up returning the desired output)
+ `y_` if there was a match, drop the first character (if there wasn't a match, this is a no-op). this allows us to search for the next search character in the next iteration of the reduction
* `x@&` return the correct number of copies of each character
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 9 bytes
```
£ƛ¥h=[&Ḣd
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiwqPGm8KlaD1bJuG4omQiLCIiLCJvb2Fvb1xub25vbWF0b3BvZWlhIl0=)
```
£ƛ¥h=[&Ḣd
£ # Put the first input in the register
ƛ # Map over the second input:
¥h=[ # Is the current character equal to the first character of the register?
&Ḣd # If so, remove the first character of the register and double the current character
# (implicit) else, return the current character unchanged
# s flag smashes this list into a string
```
] |
[Question]
[
Your task is simple: write a program that receives an integer as input and outputs it if it was odd, and does nothing otherwise (not halting is allowed). The challenge is, that you can only use odd bytes.
You can optionally append a trailing newline to the output.
This is code-golf, shortest answer in (odd) bytes wins.
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. Furthermore, you cannot use versions of languages, which are newer than the posting of this challenge.
Example input > output:
`13` > `13`
`42` >
[Answer]
# [Lenguage](https://esolangs.org/wiki/Lenguage), ~~645529908926937253684695788965635909332404360034079~~ ~~9394157991500940492270727190763049448735~~ ~~1174269748937617561533841898064735499551~~ 2293382937520069758100171520285996319 bytes
That's roughly equal to 2 duodecillion bytes.
The file translates to the following brainfuck program:
```
,[<<+>+>-]<[>>+<<-]+>>[-[->]<]<[<[<]>.<]
```
Takes input as an ASCII code, with a maximum value of 256. Uses wrapping.
[Answer]
# x86-64 Machine Code, 8 bytes
Inspired by [Bruce Forte's solution](https://codegolf.stackexchange.com/a/132081/58518), but slightly under par. :-)
```
8D 07 lea eax, [rdi] ; put copy of input parameter in EAX
D1 EF shr edi, 1 ; shift LSB into CF
InfiniteLoop:
F3 73 FD rep jnc InfiniteLoop ; test CF; infinite loop back here if input was even
C3 ret ; return with original input in EAX if it was odd
```
A single integer parameter is taken in the `EDI` register, following the System V AMD64 calling convention.
A copy of this value is initially made, and put into `EAX` so it can be returned if appropriate. (`LEA` is used instead of the normal `MOV` because we need an instruction with odd bytes.)
Then, the value in `EDI` is shifted right by 1, which places the shifted-off bit into the carry flag (CF). This bit will be 0 if the number was even, or 1 if it was odd.
We then test CF using the `JNC` instruction, which will branch only if CF is 0 (i.e., the number was even). This means that we will go into an infinite loop for even values. For odd values, we fall through and the original value (in `EAX`) is returned.
There is a bit of a trick with the `JNC` instruction, though—it has a `REP` prefix! Normally, `REP` prefixes are only used with string instructions, but because the Intel and AMD manuals both agree that irrelevant/superfluous/redundant `REP` prefixes are ignored, we throw one on the branch instruction here to make it 3 bytes long. That way, the relative offset that gets encoded in the jump instruction is also odd. (And, of course, `REP` is itself an odd-byte prefix.)
Thank goodness `RET` is encoded using an odd byte!
**[Try it online!](https://tio.run/##rVDLTsMwELznK0aRKuyS0heiSKGnPqR@A0bIuE5qSNeV45RUiF8n2EHiwJmDtbO7szuzVqNSqa5TlmoPdZAOu7Ulvzlrel7ZvX58WiIV7f1atJOFaNdT0W62ot3ORbsIbxvqq3maJ4khj6M0xCKQrlRZv244jMmZ4yNJgNijPKLCOjDCEtMchAdMZyFeL2c89ICTC8yCpb9e2GDPA3mwF5RmoIxFGTbkjPM/hjkjznuJ8Ri7Ahfb4CTrGpKgAwlnWTU6gz9oqMDHu6kqlDZ6s5FkqDBkvEZl7elnzYtWsqnDUGXeNCRq66wz/oLSuCqD8Xht4vdJuvK9yE0/F8@b5T38l4Oc9o0jTPLks@u@VFHJsu5Gx7vbbw "C (gcc) – Try It Online")**
---
In case you don't think returning the value if it's odd or going into an infinite loop if it's even (so that you never return) satisfies the "output" requirements of the challenge, or you just want something more interesting, here's a function that outputs the value to a serial port (but only if it's odd, of course).
## x86-64 Machine Code (output to serial port), 17 bytes
```
8D 07 lea eax, [rdi] ; put copy of input parameter (EDI) in EAX
B1 F7 mov cl, 0xf7 ; put 0xF7 into low-order bits of CX
B5 03 mov ch, 0x03 ; put 0x03 into high-order bits of CX
FE C1 inc cl ; increment low-order bits of CX to 0xF8 (so all together it's now 0x3F8)
0F B7 D1 movzx edx, cx ; move CX to DX ("MOV DX, CX" would have a 16-bit prefix of 0x66)
D1 EF shr edi, 1 ; shift LSB of input parameter into CF
73 01 jnc IsEven ; test CF: branch if 0 (even), fall through if 1 (odd)
EF out dx, eax ; output EAX (original input) to I/O port 0x3F8 (in DX)
IsEven:
C3 ret ; return
```
What makes this a bit more interesting is that the code *does more*, which means it was more challenging to do it all using instructions that are encoded using only odd bytes. Of course, this also means that it fails at code golf, so it's kind of a tradeoff—do you want interesting and challenging, or do you want short?
Anyway, this uses the x86 [`OUT` instruction](http://x86.renejeschke.de/html/file_module_x86_id_222.html) to write to I/O port 0x3F8, which is the [standard COM1 serial port](https://en.wikipedia.org/wiki/COM_(hardware_interface)) on a PC. The fun part, of course, is that all standard I/O ports (serial and parallel) have even addresses, so they can't simply be encoded as immediates for the `OUT` instruction or moved directly into a register. You have to initialize with one less than the actual value, and then *increment* the value in the register. You're also limited to using certain registers for the manipulation because you need registers that are encoded using odd bytes in the instruction when used as operands.
Also, I had to initialize the `DX` register (via the `CX` register) at the top of the loop, even though this is only needed if the value is odd, to ensure that the `JNC` instruction would have an odd offset. However, since what we're skipping over is the `OUT` instruction, all this code does is waste cycles and clobber scratch registers; it doesn't actually *output* anything, so it doesn't break the rules.
Finally, this function will return (after having either done or not done the output to the serial port) with the input value left in `EAX`. But that doesn't actually break any rules; *all* functions in assembly language will return with a value in `EAX`—the question is just is it a *significant* value or a *garbage* value. That's determined by the function's documentation (essentially, does it return a value or does it return `void`), and in this case, I'm documenting it as not returning a value. :-)
No TIO link for this one, as it doesn't implement output to serial ports. You'll need real iron, or an imagination.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
ẋḂ
```
These characters correspond to bytes **0xF7** and **0xBF** in [Jelly's code page](https://github.com/DennisMitchell/jelly/wiki/Code-page).
[Try it online!](https://tio.run/##y0rNyan8///hru6HO5r@//9vaAwA "Jelly – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md)
```
Éi=
```
The code corresponds to the byte values `C9,69,3D` or `201,105,61` which are all odd.
[Try it online!](https://tio.run/##MzBNTDJM/f//cGem7f//hiZGxqYA "05AB1E – Try It Online")
**Explanation**
```
É # input % 2 == 1
i # if true
= # print without popping
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
o?G
```
MATL uses ASCII characters, so `o?G` corresponds to bytes (in decimal) `111`, `63`, `71`.
[Try it online!](https://tio.run/##y00syfn/P9/e/f9/I3MA "MATL – Try It Online")
### Explanation
```
o % Push (implicit) input modulo 2
? % If nonzero
G % Push input
% End (implicit)
% Display stack contents (implicit)
```
[Answer]
# Python REPL, 38 bytes
Takes input as the value of the previous expression using `_`. Output will be a string (the string representation of the integer for odd, or the empty string for even).
```
'%s'%[['']+[_]][-1][[_%[1+1][-1]][-1]]
```
[**Try it online**](https://tio.run/##JYzNCgIhFIX3PsXFEJVq4dRqaJ7kIjLMD3OhVMyCiJ7dlFmcj7P4zomfvAXfFTeQj6@sNJvCvAyc8yLFUwpEKe0RnbV4NhbRCby0UrOjVJUdYiKf4TttSZGGNSQgIA@PMaqQ5lP7RNNXXwOtQKK7mR/bR8t7vKsm6HL9Aw)
To run it in an actual shell, you can try it [here](https://www.python.org/shell/). Type the input, hit enter. Paste the code, hit enter.
### Explanation:
This took a while to figure out. There's no multiplication, no branching, no slicing, no commas, no periods, no imports, no parentheses, no `exec`, no `eval`, no `print`, and no functions. I got one solution working that output using stderr, but then I realized we had to output the actual integer, not just a truthy/falsey value.
I use brackets in place of parentheses with `[expression][-1]`. Simplifying that turns the above code into `'%s'%(['']+[_])[_%(1+1)]`.
Since there can be no commas, I used list addition to create `['',_]`. Using string formatting, the desired result is obtained.
[Answer]
# [Haskell](https://www.haskell.org/), ~~36~~ 33 bytes
```
c[1]=1;c[m]=1+1+c[m-1-1];o m=c[m]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PznaMNbW0Do5OhdIaRtqAxm6hrqGsdb5nLm2INH/uYmZeQq2CgVFmXklCioK@Qrm/wE "Haskell – Try It Online")
Usage: `o 7` yields `7`, `o 8` enters an infinite loop.
The actual algorithm is
```
o 1 = 1
o m = 2 + o(m-2)
```
The first problem I faced was the lack of space and `(`, because a function `o` which takes an argument `m` is usually defined as `o m=...` or `o(m)=...`. However I found out that an inline comment `{- some comment -}` works as token delimiter too, so a definition `o{--}m=...` is possible under the given rules. *Edit: Ørjan Johansen pointed out that one can use a tab character instead of a space, saving three bytes:* `o m=...`
The second problem was the recursive call `o(m-2)`. `-2` is just `-1-1`, but here the comment trick does not work because the parentheses are required. I fixed this by letting the function work on a singleton list containing a number: `o[m-2]`, however, as this is not a standard way of providing input, I outsourced the computation to a helper function `c` which works on lists and call `c` from `o` which has the correct format.
[Answer]
# CJam, 6 bytes
```
q_iY%%
```
`113` `95` `105` `89` `37` `37`
This program takes the mod 2 of the input (call it *r*) and prints every *r* th character in the input string. If the input number is odd, it prints the whole string, but if asked to print every 0th character the program throws an error.
[Try it here](https://tio.run/##S85KzP3/vzA@M1JV9f9/EyMA)
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), ~~23~~ ~~19~~ 17 bytes
```
;;u!I1)%/;O=!;;/;
```
[Try it!](http://ethproductions.github.io/cubix/?code=ICAgIDsgOwogICAgdSAhCkkgMSApICUgLyA7IE8gPQohIDsgOyAvIDsgLiAuIC4KICAgIC4gLgogICAgLiAuCg==&input=MTM=&speed=20)
`@`, which terminates a Cubix program, is ascii 64, so unfortunately this actually just enters an infinite loop after testing for oddness. No TIO link since it'll time out.
`=` (ascii 61) is a no-op in Cubix.
This is a slight modification of the prior algorithm (same # of bytes) that actually works for negative integers.
Cube version:
```
; ;
u !
I 1 ) % / ; O =
! ; ; / ; . . .
. .
. .
```
Algorithm:
* `I` `(73)` : read in input as number
* `1` `(49)` : push 1
* `)` `(41)` : increment
* `%` `(37)` : take the mod
* `/` `(47)` : turn left
* `!` `(33)` : skip next instruction if odd
+ `1;;/;` `;` is `(59)` : prepares the stack for output
+ `O` `(79)` : Output as a number.
+ Then it re-enters the algorithm but `I` reads a `0` for end of input, so we are guaranteed to enter the even branch
* `u` `(117)` : right-hand u-turn
* `;;;!I` : loop, effectively doing nothing.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-f`](https://codegolf.meta.stackexchange.com/a/14339/), 1 [byte](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
u
```
`u` has a char-code value of `117`.
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWY&code=dQ&input=WzQyXQ)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes
```
¿﹪Iθ÷χ⁵→θ
```
[Try it online!](https://tio.run/##ASMA3P9jaGFyY29hbP//wr/vuarvvKnOuMO3z4figbXihpLOuP//Mw "Charcoal – Try It Online")
Basically it prints rightwards the input if it is not a multiple of 10/5 (the `²` char is even in [the Charcoal code page](https://github.com/somebody1234/Charcoal/wiki/Code-page)). The characters used are:
* `¿`: code `BF`.
* `﹪`: code `A5`.
* `I`: code `C9`.
* `θ`: code `F1`.
* `÷`: code `AF`.
* `χ`: code `E3`.
* `⁵`: code `B5`.
* `→`: code `13`.
In fact the `→` near the end is redundant but then I saw that the answer had to have an odd length...
Explanation:
```
¿ if (
﹪ Modulo (
Iθ the input as number,
÷χ⁵ χ (predefined value: 10) divided by 5 = 2 ) [is 1])
→θ then print rightwards the input as string
```
[Answer]
# x86\_64 machine code (Linux), ~~12~~ 11 bytes
Unfortunately `0x80` is even, but it still worked out (assuming "does nothing" means not to return):
```
0000000000000000 <odd>:
0: 8d 07 lea (%rdi), %eax
2: 83 e7 01 and $0x1, %edi
5: 83 ff 01 cmp $0x1, %edi
8: 75 fb jne 5 <odd+0x5>
a: c3 retq
```
-1 byte, thanks @CodyGray!
[Try it online!](https://tio.run/##nY7NasMwEITveorBYNA6DvEPxQHVTxL14Ei2m0PWQXWLQ8izO6uavkBP8y0zO7tuPzq3rm7irxnusws43@feTb4/fbRI7HL0dika0douvWhRbjwMGzdvwme7uDoxSl14xrW7sI7QhdHlv6VZFocfwkMpIHpsIg1TgGa0KA0Y7ygr0V1bkXjALUhy0MnkvU49SSz1lpMcnOt4QGekif7@Jc1E0iqrhwNiaWU2/l8PEPr5OzAKo57r@gI "C (gcc) – Try It Online")
[Answer]
## Mathematica, 20 bytes
Appear to be the first solution in non-golfing language.
```
a=1+1;g[i_/;!a\[Divides]i]=i
```
In `MacintoshChineseTraditional` character encoding. `\[Divides]` is `{161, 253}` (2 bytes)
Alternative version (23 bytes)
```
\[CapitalAlpha]=1+1;\[CapitalGamma][\[CapitalChi]_/;\[CapitalAlpha]\[LeftFloor]\[CapitalChi]/\[CapitalAlpha]\[RightFloor]\[NotEqual]\[CapitalChi]]=\[CapitalChi]
```
or (shown in Unicode)
```
Α=1+1;Γ[Χ_/;Α⌊Χ/Α⌋≠Χ]=Χ
```
in `Symbol` character encoding. (use only 1-byte characters)
The solution defines a function `g` (or `Γ`) that, evaluate to input when the input is odd, and literally "do nothing" (does not evaluate) when the input is even.
[Answer]
## Perl, 54 bytes
**Requires `-E`.**
I really really enjoyed this challenge, I think I'd like to try and improve this answer, but I think that's might be the shortest I can make for now. I've been playing with these answers on and off for a few days now, but feel I'm happy with the 54 byte solution!
```
s//A_=Y[;A_=A_%O?A_W''/;y/#A-_/#-A/;s/[#-}]+/uc/ee;say
```
[Try it online!](https://tio.run/##K0gtyjH9X1qcqmCqZ2Bo/b9YX98x3jYy2hpIOsar@ts7xoerq@tbV@orO@rG6yvrOupbF@tHK@vWxmrrlybrp6ZaFydW/v9vCAA "Perl 5 – Try It Online")
### Explanation
By default, most of Perl's string functions work on `$_`, which is empty to start.
First, `s//A_=Y[;A_=A_%O?A_W''/` replaces the empty string in `$_` with `A_=Y[;A_=A_%O?A_W''`, then `y/#A-_/#-A/` replaces characters based on the following list (char above becomes char below):
```
#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_
#$%&'()*+,-./0123456789:;<=>?@A
```
which updates `$_` to contain `$_=<>;$_=$_%2?$_:''`. Next `s/[#-}]+/uc/ee` replaces all chars `[#-}]+` with `uc`. Without the `/ee` this would just be the string `uc`, but `/ee` evaluates the contents of the string twice. The first evaluation returns the result of `uc`, which is an uppercase version of `$_` but since `$_` contains no alphabetic characters, this just returns the whole string, then the second `/e` evaluates the string again, which sets `$_` to either `$_` (the input number) or `''` depending on whether or not the number is odd or even.
Finally, since `$_` now contains what we want, we call `say` (which is what requires `-E` instead of `-e`) which prints `$_` followed by a newline.
---
### Alternative Perl, 93 bytes
**92 bytes code + 1 for `-p`, which I feel would make it non-competing.**
```
s//_/g;s//uc/e;y/\x09-\x0b/_/;s/____/}[/;s/___/%C]/;s/_/{''H/;y/'{}1CDGH/'-)1-3+--/;s/[#-}]+/uc/ee
```
Contains a tab and a vertical tab in the `y///`, indicated as `\x09` and `\x0b`.
[Try it online!](https://tio.run/##K0gtyjH9/79YXz9eP90aSJUm66daV@pz6nIDRYAC8UCgXxsNZeqrOseCmfrV6uoe@kCF6tW1hs4u7h766rqahrrG2rq6IPloZd3aWG2wYan//xty/csvKMnMzyv@r1sAAA "Perl 5 – Try It Online")
[Answer]
# [LOGO](https://sourceforge.net/projects/fmslogo/), ~~390~~ ~~46~~ ~~52~~ 50 bytes
```
[ask 1 se[make]iseq 1-3 cos ?/ask 1[1/sum 1 179]?]
```
That is a template-list that return the input if the input is odd, and cause an error if the input is even.
Usage:
```
show invoke [ask ... (paste code here) ... ] 5
```
output
```
5
```
since 5 is odd, and
```
invoke [ask ... (paste code here) ... ] 6
```
will cause an error because 6 is even.
---
[Answer]
## TI-BASIC, 14 bytes
```
Input Q
sinֿ¹(gcd(Q²,int(e
Q
```
This throws a domain error (printing nothing to the homescreen) on an even number.
```
Input Q Q is a variable with an odd code. We cannot use "Ans" as it's even.
int(e floor(e) = 2; "2" is even.
Q² Q may be negative, so we square it which preserves parity.
gcd(Q²,int(e 1 if Q is odd; 2 if Q is even.
sinֿ¹(gcd(Q²,int(e Error iff Q is even.
Q If there was no error, print Q.
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~14~~ ~~11~~ ~~10~~ 9 bytes
```
~~I+Q\_+K/Q+3\_1KQ~~
~~I!sIcQ+3\_1Q~~
~~I!u+1\_GQ1Q~~
?u+1_GQ1k
```
[Test suite](http://pyth.herokuapp.com/?code=%3Fu%2B1_GQ1k&test_suite=1&test_suite_input=13%0A42&debug=0).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 bytes
```
u)çU
```
Japt uses [ISO/IEC 8859-1](https://en.wikipedia.org/wiki/ISO/IEC_8859-1), so this corresponds to (in decimal) `117 41 231 85`.
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=dSnnVQ==&input=NDI=)
### Explanation
```
Uu)çU Implicit: U = input integer
Uu) Return Python-style U % (missing argument = 2). This gives 1 if U is odd, 0 if even.
çU Implicitly convert U to a string and repeat it that many times.
Implicit: output result of last expression
```
I first tried solutions using `p`, which is basically `ç` with reversed arguments. However, `p` performs exponentiation if its left argument is a number, so we'd need to explicitly convert it to a string. This solution turns out to actually be a byte shorter, in addition to not containing any odd bytes.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 21 bytes
```
[c]sa?kKKCI-1;1k%1!=a
```
Decimal: `91 99 93 115 97 63 107 75 75 67 73 45 49 59 49 107 37 49 33 61 97`
As per [this](https://codegolf.meta.stackexchange.com/a/8507/52405) IO default, this program leaves the input on the main stack if it is odd and empties the stack otherwise. This can be confirmed by adding the `f` debug command to the end of the program as is the case on the TIO page.
[Try it online!](https://tio.run/##S0n@/z86ObY40T7b29vZU9fQ2jBb1VDRNvF/2n9TAA "dc – Try It Online")
## Explanation
```
[ # Begin macro definition.
c # Clear the main stack.
]sa # End macro definition and push the macro into register "a".
?k # Prompt for input and store it into precision parameter "k".
KK # Push two copies of the input to the main stack.
CI- # Push C-I = 12-10 = 2 to the main stack
1;1 # Push the value stored in the first index of array "1" (0 by default)
# to the main stack.
k # Push 0 into parameter "k" to reset the precision (otherwise the modulus
# function will not work correctly).
% # Push the input (mod 2) to the main stack.
1!=a # If the input (mod 2) does not equal 1, execute the macro in register "a".
f # OPTIONAL: Output the contents of the main stack.
```
[Answer]
## TI-Basic, 18 bytes
Saved 2 bytes thanks to lirtosiast
```
:Prompt Q
:While 5Q/ᴇ1-int(5Q/ᴇ1
:Q
```
in bytes (+2 newlines = 3F)
```
:Prompt Q
DD 51
:While 5Q/ᴇ1-int(5Q/ᴇ1
D1 35 3B B1 35 3B
51 31 51 31
83 71 83
:Q
51
```
See <http://tibasicdev.wikidot.com/one-byte-tokens>
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 3 bytes
```
¥{k
```
[Try it online!](https://tio.run/##y00syUjPz0n7///Q0urs//8NDQwB "MathGolf – Try It Online")
The used bytes are `157, 123, 107`.
### Explanation
```
¥ Input modulo 2
{ Loop that many times
k Push input
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 31 bytes
```
read a
[ $[a%2] = 0 ] ||echo $a
```
[Try it online!](https://tio.run/##S0oszvj/vyg1MUUhkStaQSU6UdUoVsFWwUAhtqYmNTkjX0El8f9/MwA "Bash – Try It Online")
# Explanation:
```
read a reading the input and define it on the variable a
[ $[a%2] = 0 ] outputs exit status 0 when a/2 is 0 and exit status 1 if not.
|| evaluates only when the exit status left of it is 1
echo $a displays the variable a
```
] |
[Question]
[
### A simple one:
Take a positive integer **n** less than 1000, and output the integers from **1** to **n** interleaved with the integers from **n** to **1**. You must concatenate the numbers so that they appear without any delimiters between them.
### Test cases:
```
n = 1
11
n = 4
14233241
n = 26
12622532442352262172081991810171116121513141413151216111710189198207216225234243252261
n = 100
110029939849759669579489399210911190128913881487158616851784188319822081218022792378247725762675277428732972307131703269336834673566366537643863396240614160425943584457455646554754485349525051515052495348544755465645574458435942604161406239633864376536663567346833693270317130722973287427752676257724782379228021812082198318841785168615871488138912901191109299389479569659749839921001
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest submission in bytes in each language wins. Explanations are encouraged.
[Answer]
## JavaScript (ES6), 30 bytes
```
f=(n,k=1)=>n?f(n-1,k+1)+n+k:''
```
### How?
This is pretty straightforward but it's worth noting that the string is built from tail to head. An empty string at the beginning is appended last and allows the coercion of the final result to a string to happen.
Below is the detail of the recursion for `f(4)`:
```
f(4) = // initial call
f(4, 1) = // applying the default value to k
f(3, 2) + 4 + 1 = // recursive call #1
(f(2, 3) + 3 + 2) + 4 + 1 = // recursive call #2
((f(1, 4) + 2 + 3) + 3 + 2) + 4 + 1 = // recursive call #3
(((f(0, 5) + 1 + 4) + 2 + 3) + 3 + 2) + 4 + 1 = // recursive call #4
((('' + 1 + 4) + 2 + 3) + 3 + 2) + 4 + 1 = // n = 0 --> end of recursion
'' + 1 + 4 + 2 + 3 + 3 + 2 + 4 + 1 = // final sum
'14233241' // final result
```
### Test cases
```
f=(n,k=1)=>n?f(n-1,k+1)+n+k:''
console.log(f(1))
console.log(f(4))
console.log(f(26))
console.log(f(100))
```
[Answer]
# [Python 2](https://docs.python.org/2/), 46 bytes
```
lambda n:''.join(`x+1`+`n-x`for x in range(n))
```
Thanks to ovs for 4 bytes
[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQZ6WurpeVn5mnkVChbZignZCnW5GQll@kUKGQmadQlJiXnqqRp6n5v6AoM69EIU3DRPM/AA "Python 2 – TIO Nexus")
Explanation:
```
lambda n:''.join(`x+1`+`n-x`for x in range(n))
lambda n: # anonymous lambda taking one parameter n
`x+1`+`n-x` # `x` is repr(x) which is equivalent to str(x) for integers less than INT_MAX
for x in range(n) # integers x in [0, n)
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 25 bytes
```
printf %s`seq $1 -1 1|nl`
```
[Try it online!](https://tio.run/nexus/bash#@19QlJlXkqagWpxQnFqooGKooGuoYFiTl5Pw//9/QwMDAA "Bash – TIO Nexus")
Prints decreasing sequence, number lines increasing and printf joins lines
~~Space delimited, 20 bytes :
seq $1 -1 1|nl|xargs~~
[Answer]
-5 thanks to Ørjan Johansen
# [Haskell](https://www.haskell.org/), 33 bytes
```
f n=do a<-[1..n];[a,n-a+1]>>=show
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzYlXyHRRjfaUE8vL9Y6OlEnTzdR2zDWzs62OCO//H9uYmaegq1CbmKBb7yCRkFpSXBJkU@egp5CmqZCtKGOiY6RmY6hgUHsfwA "Haskell – Try It Online")
[Answer]
# R, 35 bytes
```
n=scan();cat(rbind(1:n,n:1),sep="")
```
[Try it online](https://tio.run/#r#@59nW5ycmKehaZ2cWKJRlJSZl6JhaJWnk2dlqKlTnFpgq6Sk@d/0PwA)
`rbind(1:n,n:1)` creates a 2 row matrix with 1 to n in the first row and n to 1 in the second. The `cat` function collapses this matrix, reading down each column.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 5 bytes
Saved a byte using the new interleave built-in as suggested by *rev*
```
LÂ.ιJ
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f53CT3rmdXv//G5kBAA "05AB1E – TIO Nexus")
**Explanation**
```
L # range [1 ... input]
 # create a reversed copy
.ι # interleave the lists
J # join
```
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 10 bytes
```
ri,:)_W%]z
```
[Try it online!](https://tio.run/nexus/cjam#@1@UqWOlGR@uGlv1/7@RGQA "CJam – TIO Nexus")
### Explanation
```
ri e# Read input and convert to integer N.
, e# Turn into range [0 1 ... N-1].
:) e# Increment to get [1 2 ... N].
_W% e# Duplicate and reverse the copy.
] e# Wrap both in an array to get [[1 2 ... N] [N ... 2 1]]
z e# Transpose to get [[1 N] [2 N-1] ... [N-1 2] [N 1]]
e# This list is printed implicitly at the end of the program,
e# but without any of the array structure (so it's essentially flattened,
e# each number is converted to a string and then all the strings
e# are joined together and printed).
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 29 bytes
```
->n{n.times{|x|$><<x+1<<n-x}}
```
## Explanation:
```
->n{n.times{|x| # x in range [0..n-1]
$><< # output on console
x+1<<n-x}} # x+1, then n-x
```
[Try it online!](https://tio.run/nexus/ruby#S7P9r2uXV52nV5KZm1pcXVNRo2JnY1OhbWhjk6dbUVv7v6AoM69EIS3aJPY/AA "Ruby – TIO Nexus")
[Answer]
# Pyth, 7 bytes
```
jksC_BS
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=jksC_BS&input=100)
### Explanation:
```
jksC_BSQ implicit Q (=input number) at the end
SQ create the range [1, ..., Q]
_B bifurcate by inversion, this gives [[1, ..., Q], [Q, ..., 1]]
sC zip and flatten result
jk join to a string
```
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 71 bytes
```
```
[Try it online!](https://tio.run/nexus/whitespace#LYrBDQAwCALfxxQM4f6rUbWGBMhBbKuFYAK0gOas72gGXbuF/0MdSuoB "Whitespace – TIO Nexus")
## Explanation
```
sssn ; push 0 - seed the stack with 0 (this will be our 1->n counter, a)
sns ; dup
tntt ; getnum - read n (stored on the heap)
sns ; dup
ttt ; retr - pull n onto the stack (this will be our n->1 counter, b)
nssn ; label 'loop'
snt ; swap - bring a to the top
ssstn ; push 1
tsss ; add - increment a
sns ; dup
tnst ; putnum - output a as a number
snt ; swap - bring b to the top
sns ; dup
tnst ; putnum - output b as a number
ssstn ; push 1
tsst ; sub - decrement b
sns ; dup
ntstn ; jez 'exit' if b is 0
nsnn ; jmp 'loop'
```
The first couple of instructions are needed to set up the stack correctly, Whitespace's input commands write to the heap so we need to copy b (the input value) back onto the stack. We start with a = 0 since it is shorter to declare 0 instead of 1 (saves a byte) and we only need to reorder the increment instruction to cope. After that we just loop and increment a, output a, output b, decrement b, until b reaches 0 (checked after the decrement).
[Answer]
## Haskell, ~~65~~ ~~48~~ 47 bytes
1 byte saved thanks to Laikoni:
```
f n=show=<<(\(l,r)->[l,r])=<<zip[1..][n,n-1..1]
```
---
6 bytes saved thanks to nimi:
```
f n=show=<<(\(l,r)->[l,r])=<<zip[1..n][n,n-1..1]
```
---
Previous answer and explanation:
```
f n=concatMap show$concatMap(\(l,r)->[l,r])(zip[1..n][n,n-1..1])
```
There's already a better Haskell answer here, but I'm new to both Haskell and code golfing, so I may as well post it :)
This function zips the list [1..n] with its reverse, resulting in a list of tuples.
```
[(1,n),(2,n-1),(3,n-2)..(n,1)]
```
Then it uses `concatMap` to map a lambda to this list of tuples that results in a list of lists...
```
[[1,n],[2,n-1],[3,n-2]..[n,1]]
```
...and concatenates it.
```
[1,n,2,n-1,3,n-2..n,1]
```
Then a final `concatMap` maps `show` to the list and concatenates it into a single string.
`f 26
"12622532442352262172081991810171116121513141413151216111710189198207216225234243252261"`
[Answer]
# [Aceto](https://github.com/aceto/aceto), ~~25~~ 22 bytes
```
)&
pX`=
(pl0
id@z
r}Z)
```
### Explanation:
We read an integer and put it on two stacks.
```
id
r}
```
On one, we call range\_up (`Z`), on the other range\_down (`z`), then we set a catch mark to be able to return to this place later:
```
@z
Z)
```
We then check if the current stack is empty and exit if so:
```
X`=
l0
```
Otherwise, we print from both stacks and jump back to the catch mark:
```
)&
p
(p
```
[Answer]
# Octave, 29 bytes
```
@(n)printf("%d",[1:n;n:-1:1])
```
[Try it online!](https://tio.run/nexus/octave#@@@gkadZUJSZV5KmoaSaoqQTbWiVZ51npWtoZRir@T8xr1jDyEzzPwA "Octave – TIO Nexus")
[Answer]
**Scala, 43 bytes**
It's not the best but it's my first code golf.
```
n=>1.to(n).foldLeft("")((s,x)=>s+x+(n-x+1))
```
[Answer]
# [Perl 6](https://perl6.org), 20 bytes
```
{[~] 1..*Z~($_...1)}
```
[Test it](https://tio.run/nexus/perl6#NVBLaxNRFN7Pr7iLIklTp/e8zyFU3Lpx5UojoukIBduEPEQp7V@vX0JlYLjn9b2O@6n99nG9HO7/tjfrze3Ubl4evzx/bTSOl5@fZxffxnGk@dML5u8P0/7QbtrF5YeP43pz/2N2vbpdXM/H3eaw2c14vhyOwPuEreWw/fX9oS3OJ8vh52b3ev32XZut7h62x8PVavqzndaH6Xb@OLR2t28n@tniPJxftf/Tq3buDE8vD@CmgWgYTi8dSFmE9bVmH4id2dDCwBgFBfekKkrqFETkxGQkpPgEL0aHMOmURZXcAx1gsCir8AnkFZ56B3XvXCWVWmHlXhaliUYx9QJSdWIgSSZpBlk6eRpFKmXKieEkiCk7cxRLJGsEWzh7GEcoZwhXsPSAwujCXiKeoh5i7uJuEq6SLlLO2h1evCtbqViqWqiZq5tpmGqaaBlbN/jFn1EJuoqpYcuxHbhKXJcykJAJUBnoAhYFm4HVwR5QkVBTwlCG3KCSoVagWqHe4MLhJuAq4a6Y4RTpwzXDvSAFRRqGVBzpBFJKpFXESI6QYK9TwFkaZV5uFYqzc76d/gE "Perl 6 – TIO Nexus")
With an input of [100000](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLzk9JVbD9Xx1dF6tgqKenFVWnoRKvp6dnqFn7vzixUgEsb2gAAv8B "Perl 6 – TIO Nexus") this takes roughly 10 seconds, including compilation and printing the output.
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
[~] # reduce using concatenation operator 「&infix:«~»」
# (shorter than 「join '',」)
1 .. * # Range from 1 to infinity
Z~ # zip using concatenation operator
( $_ ... 1 ) # deduced sequence starting at the input
# going down to 1
}
```
The `Z~` needs the `~` because otherwise it generates a list of lists which will stringify with spaces.
There is no need to limit the Range starting at 1, because `Z` stops when any of the input lists run out.
This saves two bytes (a space would be needed after `$_`)
[Answer]
# Java 61 bytes
```
(int n)->{for(int i=0;i<n;System.out.print(i+1+""+(n-i++)));}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
RṚĖVV
```
[Try it online!](https://tio.run/nexus/jelly#@x/0cOesI9PCwv4fbn/UtEYh61HDnEPbDm171DBXQeHhju1AroJvYoFCTmZeto5CcWpBYlFiSapCfmlJQWlJsUJSpUJeajlQMrVY7/9/Qx0FEx0FIzMdBUMDAwA "Jelly – TIO Nexus")
### How it works
```
RṚĖVV Main link. Argument: n
R Range; yield [1, ..., n].
Ṛ Reverse; yield [n, ..., 1].
Ė Enumerate; yield [[1, n], ..., [n, 1]].
V Eval; convert each flat array to a string, interpret it as a Jelly program,
and yield the output. This concatenates the integers in each pair, yielding
a flat array of integers
V Repeat the previous step, concatenating the intgegers from before.
```
[Answer]
# [Röda](https://github.com/fergusq/roda), ~~21~~ 19 bytes
```
{seq 1,_<>seq _1,1}
```
[Try it online!](https://tio.run/##K8pPSfyfFvO/uji1UMFQJ97GDsSIN9QxrP2fm5iZV80VbWQWW5PGVfsfAA "Röda – Try It Online")
This is an anonymous function that takes input from the stream.
### Explanation
```
{seq 1,_<>seq _1,1} Anonymous function, takes integer n from the stream
<> Interleave
seq 1,_ the range 1 .. n with
seq _1,1 the range n .. 1
```
[Answer]
# Clojure, 61 bytes
```
#(let[a(range 1(+ 1 %))](apply str(interleave a(reverse a))))
```
Literally does what is asked. I believe it can be outgolfed by a less trivial solution.
[See it online](http://ideone.com/Ml9Hix)
[Answer]
# R, 41 bytes
```
pryr::f(for(i in 1:x){cat(i);cat(x-i+1)})
```
`pryr::f()` creates a function that takes one input. Loops over `1:x` and prints each element of `1:x` along with each element of `x:1`. Prints to STDOUT.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~10~~ 9 bytes
```
⟦₁g↔ᶻczcc
```
[Try it online!](https://tio.run/nexus/brachylog2#@/9o/rJHTY3pj9qmPNy2O7kqOfn/fyOz/1EA "Brachylog – TIO Nexus")
### Explanation
```
⟦₁ [1, …, Input]
g↔ᶻc [[1, …, Input],[Input, …, 1]]
z Zip
cc Concatenate twice
```
[Answer]
# PHP, 36 35 29 bytes
```
for(;$argn;)echo++$i,$argn--;
```
Saved one byte thanks to Jörg Hülsermann.
Saved six bytes thanks to Christoph.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 20 bytes
```
ywo1@"ñykPjñkògJ
```
[Try it online!](https://tio.run/nexus/v#@19Znm8o7aB0aO3hjZXZARJZjIc3Zh/elO71/7@RAQA "V – TIO Nexus")
Explain:
```
yw ' Copy the input number (for looping later)
o1 ' Insert a 1 under the input (on a newline)
@" ' [Copy register] number of times
ñ ñ ' Do the thing inside of this loop
ykP ' Copy the current line and line above it, and paste above both
j ' decrement the current (top) number, and increment the one below
k ' Go to the top line
ògJ ' recursively join all of the lines
```
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 17 bytes
```
....1I>sO)su.@?(O
```
[Try it online!](https://tio.run/nexus/cubix#@68HBIaedsX@msWleg72Gv7//5sCAA "Cubix – TIO Nexus")
cubified:
```
. .
. .
1 I > s O ) s u
. @ ? ( O . . .
. .
. .
```
Pushes `1`, reads in the input (`I`), then enters the loop which swaps the top of the stack, outputs it, increments, swaps, outputs the top of the stack, decrements, and stops if the top of the stack is 0.
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 16 bytes
```
{,//$r,'|r:1+!x}
```
[Try it online!](https://tio.run/##y9bNS8/7/79aR19fpUhHvabIylBbsaLWyOz/fwA "K (ngn/k) – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 5 bytes
```
{îkï-
```
[Try it online!](https://tio.run/##y00syUjPz0n7/7/68Lrsw@t1//835DLhMjLjMjQwAAA "MathGolf – Try It Online")
### Explanation:
```
{ Run a for loop over implicit input
î Push 1 based index of loop
k Push inputted number
ï- Subtract 0 based index of loop
Implicitly output all this joined together
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 41 bytes
```
: f 1+ dup 1 do i 1 .r 1- dup 1 .r loop ;
```
[Try it online!](https://tio.run/##TYzBCoAgEETvfcXgNRQN6VDQzyhWEChS328TiHmat292N8R8H3IPX5SyIMCM8E@CgY84GSrDyKrIV4wJa1GCIyA3CMcF3jFcHujt723vp7l5YlcYrdsjYm3KCw "Forth (gforth) – Try It Online")
### Explanation
Loops from 1 to n and outputs the index as well as n-index in a right-aligned space of size 1 (forces no space after output)
### Code Explanation
```
: f \ start new word definition
1+ dup 1 \ set up arguments to loop from 1 to n
do \ start loop
i 1 .r \ output the index in a right-aligned space of size 1
1- dup \ subtract 1 from current value of n and duplicate
1 .r \ output new n in right-aligned space of size 1
loop \ end loop
; \ end word definition
```
[Answer]
# Common Lisp, ~~63~~ 54 bytes
```
(lambda(n)(dotimes(i n)(format t"~a~a"(1+ i)(- n i))))
```
[Try it online!](https://tio.run/##S87JLC74r/FfIycxNyklUSNPUyMlvyQzN7VYI1MByEnLL8pNLFEoUapLrEtU0jDUVsjU1NBVyANSQPDfyEzzPwA)
[Answer]
# [Mouse-2002](http://mouse.davidgsimpson.com/mouse2002/), 32 30 bytes
-2 moved conditional to start of loop `(z.^ ... )` instead of `(... z.0>^)`
```
?n:n.z:(z.^a.1+a:a.!z.!z.1-z:)
```
[Try it online!](https://tio.run/##y80vLU41MjAw@v/fPs8qT6/KSqNKLy5Rz1A70SpRT7EKhAx1q6w0/6v8NzQwAAA "Mouse-2002 – Try It Online")
**Explanation:**
```
?n: ~ get input and store in n
n.z: ~ copy n into z
(z.^ ~ stop if z equals 0
a.1+a: ~ add 1 to a
a.! ~ print a
z.! ~ print z
z.1-z:) ~ substract 1 from z
```
[Answer]
# MATL, ~~13~~ ~~11~~ 9 bytes
*2 bytes saved thanks to @Luis*
```
:tPv1eVXz
```
Try it at [**MATL Online**](https://matl.io/?code=%3AtPv1e%22%40V%26h&inputs=10&version=20.0.0)
**Explanation**
```
% Implicitly grab input as a number, N
: % Create an array from 1..N
tP % Create a reversed copy
v % Vertically concatenate the two
1e % Reshape it into a row vector
V % Convert to a string
Xz % Remove whitespace and implicitly display
```
] |
[Question]
[
A Geiger counter is a device that is used to detect radiation.
We will be making a Geiger counter program.
As we all know, when radiation hits a computer program it removes exactly 1 byte at random. So a Geiger counter program is a program that itself does nothing, but when any byte is removed the modified program prints `beep`, to indicate the presence of radiation.
Answers will be scored in bytes with fewer bytes being better. Answers must be at least 1 byte.
Your program may print `beep` with trailing a newline or print a single newline for empty output, so long as it does so consistently. Your program may also use a different case for `beep` such as `BEEP`, `bEEP`, or `Beep` so long as it does so consistently.
[Answer]
# [Lost](https://github.com/Wheatwizard/Lost), ~~303 293 263 253 238~~ 228 bytes
```
v^"peeb"<\>"beepvv"((>@@>>%%>>(((((([[[[[[\
>>>>>>>>>//>>>>>>>>>>>>>>/>>/>>>>>>>>>>>>>\\
>>>>>>>>//>>>>\>>>>>>>>>>/>>>>>>>>>>>>>>>>>\\
>/>>>>>>>/>>>>>>>>>>>>\>>>>>>>>>>>>>>>>>>>>>\\
>>>>>>>>>>>>>>>>>>>>>>\\>>>>\>>>>>>>>>>>>>>>>\
```
[Try it online!](https://tio.run/##y8kvLvn/vyxOqSA1NUnJJsZOKSk1taCsTElDw87Bwc5OVdXOTgMMosEghssOBvT17VCAPhghgRiEYojaGBTFaACkWh@bbIwdNoBkOLoEVk0x////13UMBAA "Lost – Try It Online")
[Verification script](https://tio.run/##hVPbbtswDH22voJzUMhG2lzahwHeYnTr3odhj3HWKjZdC3UkQZIT5OszykmWpMg2wjBE8/DwcmSz9Y1WDzu5Mtp60I4Zq1@tWMEMLOd8t/4VG8Rl/LnI4yWiWa/jJMkfH/P85ibPk97mvRUsP9p4nF/YuH/OrDiB99jiAvzOAnp8LVrk1@yM/H3galKxo0Hn0@xuuqDppfIJ/7r1CKXulM/4LbSoksNaRqhKXWHChSul5GmaMlZhDbZTz612/vmAO@LTjEUb6RvQhkh4yCVCvuEpCAc1RaN6tLHS458MFln0nVUkxsj0aXVsepnuYayNH4c6/WtktnD35QcE1jgdWRRVQv3ozgf1/tbRyJlW0oyF4gQWzmEQvvPzu/sFzGbAv6FHu5JKOi9Lfo6Y7AGc0Z5w/dQIC8H9xNgAngR1rNoteHS@b4lchEa0NQgPArxcIeG@K3BYalWFDm@hbIR6RXjpjNcv4DV8nDAWHGKesMCFVX8Mqb5Bu5EOwTfS9YQu9AXCklRVX2sjtiAVq7UFSQewgT4JhBc6pkEYWcPBncsFfJjBcaoMYAA/36QBWaGiLYiWJlLUd@flGkPTVpS0JUf6/Xvd84yoh6c6w2m2uJQgiv6vwQXmoEL4G0PkTIrTNPT9sLvhDKbkDfY3W4Z6NPchmMPDJIMl3Zy3iO1@Aw) (borrowed from [user 202729's answer](https://codegolf.stackexchange.com/a/169964/76162)). Unfortunately this can only test half of the code at a time, but rest assured I've tested the whole program.
Ouch, this was a tough one. I'll quote WW's deleted answer:
>
> Lost is perhaps the most interesting language for this challenge. In
> Lost the start location and direction of the pointer is entirely
> random, thus to make deterministic programs you must account for every
> possible start location and direction. At the same time, by the nature
> of this challenge you must also account for any single byte being
> removed.
>
>
>
Unfortunately, his answer didn't take into account removing newlines, which screwed everything up.
### Explanation:
(note that a few bytes might be off here and there)
First let's talk about the general structure of the code:
```
v^^"peeb"<<\/"beepvv"((>>>@@>>%%>>(((((([[[[[[[\ Processing line
>>>>>>>>>>>//>>>>>>>>>>>>>>>>>>>/>>>>>>>>>>>>>>\\ Beep line
>>>>>>>>>//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\ Back-up beep line
>//>>>>>>>>>>>>>>>>>>>>\\>>>>>>>>>>>>>>>>>>>>>>>>\\ Back-up return line
>>>>>>>>>>>>>>>>>>>>>>>>\\>>>>>>\>>>>>>>>>>>>>>>>>\ Return line
```
Everything but the processing line must be entirely composed of either `>` or one of `\/`. Why? Well, as an example, let's remove a newline:
```
v^^"peeb"<<\/"beepvv"((>>>@@>>%%>>(((((([[[[[[[\>>>>>>>>>>>//>>>>>>>>>>>>>>>>>>>/>>>>>>>>>>>>>>\\
>>>>>>>>>//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\
>//>>>>>>>>>>>>>>>>>>>>\\>>>>>>>>>>>>>>>>>>>>>>>>\\
>>>>>>>>>>>>>>>>>>>>>>>>\\>>>>>>\>>>>>>>>>>>>>>>>>\
```
The first line is now *way* longer than the rest of the block. If a pointer were to spawn on a non-`>\/` character with vertical movement, then it would get stuck in an infinite loop.
---
The biggest radiation detector part is the section at the end of each line.
```
\
\\
>\\
>>\\
>>>\
```
Normally an IP passing through this from the first line would exit out the last line. However, if any character on the line is removed, then that line shifts down one, e.g:
```
\
\\
>\\
>\\
>>>\
```
And the IP instead exits out the line that is missing a byte (with the exception of the last line, where it exits out the second to last).
From there, each of the first four lines will redirect to the second line:
```
v
>>>>>>>>>>
>>>>>>>>//
>/
```
Which will then lead into either one of the two `beep`ers.
```
v^"peeb"<<\/"beepvv"((>
>>>>>>>>>>//
```
If any of the bytes in the first `beep`er have been removed, then it instead goes to the second:
```
v^^"peb"<<\/"beepvv"((>
>>>>>>>>>>>//
```
Both `beep`ers then lead back to the first line and the terminating `@`.
Some other miscellaneous parts:
The `(((((([[[[[[[` is used to clear the stack when the pointer starts inside a pair of quotes and ends up pushing the whole first line to stack. It has to be so unfortunately long because the first newline can be removed to make the first line twice the size. Experimenting in generating the `beep` using arithmetic instead of quotes ended up longer.
The `\`s and `/`s scattered across the lines are there to golf bytes in the top line of code by redirecting the pointer to the correct lines. As most of the bottom lines are just filler, only the top line is able to be golfed. If anyone has any ideas for a shorter radiation proof stack clearer then what I've got now, feel free to comment.
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), 38 bytes
```
.....;p;<>b;e;/<b;e;;p...@@.......;@..
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/18PBKwLrG3skqxTrfVtQKR1AVDMwUEPAqyBjP//AQ "Hexagony – Try It Online")
[Verification program.](https://tio.run/##fVBBboMwEDzjV6xyMVZaI9QbTqqo34gQMrAES41tLUaU11PTkLTqIXuw1vbM7Oz4OfTOvi3m6h0FcAPz5C6kr3AEzvki11JeHd5rhSo7rKfy8e10krdSsVki9JwXr3kZ6caGlH/MAaFxow0Ff4FPtOmmK9E2rsWU66ExhgshGGuxAxpt1eOXvjg7Vxv2zhEFSyYTenA@CvGVH0X5xAXoAbr4m3RyIhPwwWAJYRjJxo2k/6F1OxrrGTLnQ3YflEWvSD5CkSTVsCrvhCTUbRp96WHAGMpTa3Bcg2KdIzBgLJC2F0z/LCxW96RbowO21W@6W3cuTAn7x83s86JkybPJ/7VuFmpEz5dv "Python 3 – Try It Online")
---
## Explanation
We make use of Hexagony's auto-detection of hexagon side-length here.
If no bytes are removed, the program has side length 4 and looks like this:
[![Program without any bytes removed](https://i.stack.imgur.com/vnjiH.png)](https://i.stack.imgur.com/vnjiH.png)
If however, a byte is removed. There are 2 cases.
1. The removed byte is after the second `<`.
The execution flow would be:
[![Program with last byte removed](https://i.stack.imgur.com/Kmuth.png)](https://i.stack.imgur.com/Kmuth.png)
There are 2 consecutive `@` on the 5th line, so even if one of them are removed, the IP will safely hit a `@`.
2. The removed byte is at or before the second `<`.
Then the second half will stay intact, and the IP is no longer redirected upwards by that `<`. Image of execution flow:
[![Program with the second <code><</code> removed](https://i.stack.imgur.com/Hs7dg.png)](https://i.stack.imgur.com/Hs7dg.png)
[Answer]
# [Klein](https://github.com/Wheatwizard/Klein) XXX, ~~144~~ ~~136~~ ~~128~~ ~~122~~ 114 bytes
This answer completes [JoKing's challenge](https://codegolf.stackexchange.com/a/170976) to make a Geiger counter that works in every Klein topology.
```
\..//!?......\
!>>>.>>>>>>>\\\
!.//@"peeb"(<.\.\
!\\\@"peeb"(<..//
>>>>>>>>>>>>////
\\>.>....(.////
>\....?!/1!!./
```
[Try it online!](https://tio.run/##TYwxDoAwDAP3/iKdupCUHaU8xBNVBwRC/H8JaRngtrMtH2fbLzMwi1DhAQKpKusL4O7tGu/WtpgWRl94/CVeB/0hTgD8o/8lHq7oUkhm8j8zyznbVB8 "Klein – Try It Online") [Verification script](https://tio.run/##nVCxboMwEN39FYfLQNTW2IyoIV06V8padyDEKSiRTYMjNYr4dnq2E0KkdOlJYL13d8/Pb1V29TB0ttzbOSedOewrNadxUpV2RomqagM0DjSFAiqzVmy702Rj9tBAoyEWZG0IQHu0tdEZpKa16XanGh3@rD2OWxA38FyhjDlYZn8srjUb@IBw34WdUYjmQCl8Yt/WSuMBEKy8LZfvyxx1nkAbqOpSfynq@xMBcMSmQV9aeaPaG0069Q2xfyrEp4fwqH4W7J99nAKb61z0wcaVehSevONqnOG57qcL/U1mbmGam8P@clf/zM/V3xmulGqDY1ej67t5xhq/m/ePsxPhM4fpBveY8Jj1MEjG0jRaMF@SREVRsCKUlIix@0pbpVY0eWHSTSB9ZbBNikmlWERK1HB6CfO4kA4solREqDdwzgnngnCBpxBEIBaIBWKBOEOcIc7E5RS/ "Bash – Try It Online")
I don't believe it is really possible to make a perfectly satisfactory explanation. There are definitely aspects of this that *I'm* not aware of. It's just got too much going on. So the explanation below is a bit rough. I just want to get the *idea* across even if I gloss over a lot of the details.
The obvious next step is to create a version of Lost that can run on different Klein topologies, and create a Geiger counter in Lost that works in every topology. I don't know if really should be encouraging people to spend there time on such a awful and frustrating task, but I would certainly be willing to give a 500 rep bounty to someone who does the above.
## Explanation
The idea for this is to make a program with 2 parts.
The first is the path taken during normal execution. This path doesn't cross any boundaries, so we can avoid having to deal with the topology, and most importantly is very, very fragile. The idea here being that any disturbance to the program breaks the path and sends the ip flying off randomly.
The second part is a robust core. This part is sort of the opposite, it's role is to catch pointers that have gone off the path and direct them to the beeper. It needs to be impervious to radiation and it needs to catch as many stray pointers as possible.
The general strategy here was to build a program like this and just keep fixing the problems.
### The Path
The path looks like this:
```
\ / ?......\
! . \\
@ \.\
! //
//
\\ //
\....?! 1! ./
```
Some important about this things are
* We mostly use mirrors (`\` and `/`) rather than hard redirects. They are more fragile, and make it harder to get back on the path.
* The last character of every line is part of the path. This is required since removing them needs to break the path.
* It is sort of hexagon shaped. This is because a right angle turn can be simulated by a pole (e.g. the NE corner in 101) in the topology. So if we try to make a right angle turn at the corner there will end up being a topology that doesn't even need the mirror to make the turn.
* We have `?!/1` at the bottom and `?` near the end. This is to make sure that the bottom portion gets executed exactly once. Sometimes the pointer ends up back on the path after getting knocked off. This makes sure that if it hits the bottom portion of the path it doesn't get stuck in a loop there, and if it skips that portion it can't get to the end of the path.
* It covers basically the entire perimeter of the program. Hypothetically we only really need the left edge of the program but a full circuit is more fragile and we have to get to the other side anyway.
I experimented with both clockwise and anticlockwise paths. Ultimately clockwise should be better since you can make a shorter path. But I could not get it to work and some earlier attempts using this approach just never worked out. I managed to make an anticlockwise path so that's what's here. I might take some time with the lessons learned here to try clockwise again.
### The Core
The core is nothing too special. It is based off of the method used by pretty much every 2D Geiger counter we have two lines each which print `beep`, and we use the length of each to figure out which is damaged, so we can execute the other one. We surround this with ton of `>`s to force ips where we want them, this is the classic strategy for Lost programs.
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), ~~34~~ 29 bytes
```
//..>;e;<b@;p;/|/;e;;\.b@;p<@
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/19fX0/PzjrV2ibJwbrAWr9GH8i2jtED8Wwc/v8HAA "Hexagony – Try It Online") [Verification!](https://tio.run/##fZDBbsIwDIbPzVN4XNyILRHarYUJ7SF2YQil1C2RIIncVKzS3r1LN2DTDtxs@f8//3YY4sG759GegucIvhOBfcvmBCtgRBy1VuqlpHJZrctQ6k@d6vJdTd1yPSbFZlE8LbbJZl3M8XWIBHvfu1jgIxzJ5ReeIrf3NeVour21KKUUQtTUAPdud6AP03o37C7iq0kWIjvbeAAfEgknQKLiGSWYDpo0zRp1Zhvp5hAZU@zZpVNU@LY1M@6rAbQPUV8X6RSWOCQpseIKJvJMKiZT5ymY6TpK37gbDVYrQBSNZ7BgHbBxLeV/LpZTeja1NZHq3e9bL9WmsFuY3zo7XxRbkd3b/J/1E6EiCnh9/5s52voB5fgF "Python 3 – Try It Online")
### Explanation:
Here is the normal code formatted into a proper hexagon using [HexagonyColorer](https://github.com/Timwi/HexagonyColorer):
[![No Cancer...](https://i.stack.imgur.com/49CEI.png)](https://i.stack.imgur.com/49CEI.png)
The double `//` at the beginning ensures that this path is always taken. If any character is removed, the `@` is removed from the path, either being shifted one back or being removed itself:
[![Cancer!](https://i.stack.imgur.com/wVoyR.png)](https://i.stack.imgur.com/wVoyR.png)
In this case, we've removed a character after the `|`, which makes it follow this path, printing `beep`:
[![First beep](https://i.stack.imgur.com/wR1iS.png)](https://i.stack.imgur.com/wR1iS.png)
If we instead remove a character from before the `|` (or the `|` itself), we follow the other beep printer:
[![Second beep](https://i.stack.imgur.com/4v55c.png)](https://i.stack.imgur.com/4v55c.png)
We've then accounted for all possibilities and we only `beep` using the un-irradiated parts of the program.
[Answer]
# [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/), ~~73~~ 63 bytes
```
<<[[[[<<]]>[[.>>..>>.[,>]]]] bbeepp+[<<<]>>[[>]>>>.>>..>>.,+]
```
[Try it online!](https://tio.run/##K85NSvv/38YmGghsbGJj7aKj9ezs9EA4WscuFggYGBiSklJTCwq0gQpsYu2AKuyApB1MmY527P//AA "Self-modifying Brainfuck – Try It Online") [Verification!](https://tio.run/##dZDRboMgFIav5SnOTBokGtuld0a92O73Ao4sVLGStEAA1/XpHVhrl2UjEcTz///xO/rqBiX30zSJs1bGgbJoebNXi5A26mjYGapwza3rhMwNZ11C/KFPrOUJBpzh96/dDpOgF9Il@OXqOLRqlK7AGZy4TJagnMtWdd7EbCsEJoQslqXuIzregxnlx/JlrRQougg3gNI@DocUH40vmACz0Ptq1OcXIxx/ZEWGu9FID5Xr2dbHW6Xd1p4P/bxBiInJgoSQGp1H/av7nexNQTsweeQBzMsJYtbyMLhgrQDjMAT@@TowA7drrwwIEBJM8CU/pkEClOhhuTaCwlMFd3tAunWNNx0kG0uKeJOI7KEmGXDZVdhPPor@/femEDRdTelzQcmaPBNE0S@GA@caz5oV5NEUTWXZ@FWWlNZNk9d1Hp4mq6lfAHAIdp16QUlrr6j9Xt9lWUq/AQ)
The spaces in the middle of the code are actually representing NUL bytes.
### Explanation:
The code is split into two sections by 3 NUL bytes in the middle. Both of them basically prints `beep` if the other section is irradiated (with a couple of exceptions).
First, the `<<[[` at the beginning is to ensure that all `]`s are matched at any time. `[`s won't attempt to look for a matching `]` if the cell is positive, while `]`s *do*. If any `]` jumps back to one of these brackets it usually jumps back straight away because the cell is `0`.
The next part, `[[<<]]>` then checks if the length of section 2 is even. If so, it executes the other half of section 1, which prints `beep` using the `bbeepp` at the start of section 2.
```
[[.>>..>>.[,>]]]]
```
It then clears all of section 2 so it doesn't execute.
In section 2, we check if the length of section 1 and the NUL bytes is divisible by `3` with `+[<<<]>>`.
```
[[>]>>>.>>..>>.,+]
```
Similarly, we print `beep`.
[Answer]
# [Z80Golf](https://github.com/lynn/z80golf), ~~53~~ ~~36~~ 34 bytes
*-16 bytes thanks to @Lynn*
*-2 byte thanks to @Neil*
Since this is just Z80 machine code, there is a lot of unprintables in this one, so have a `xxd -r`-reversible hexdump:
```
00000000: ddb6 2120 10dd b615 280c 003e 62ff 3e65 ..! ....(..>b.>e
00000010: ffff 3e70 ff76 003e 62ff 3e65 ffff 3e70 ..>p.v.>b.>e..>p
00000020: ff76 .v
```
[Try it online! (exhaustive tester in Python)](https://tio.run/##fVFNT8MwDD23v8Ibh7QabJ34EKq0HThwRQJudJrSxtkitiRK0q0D8dcpaddtgBCHWHZsPz8/651bKnlZi7VWxoGyoTZqYegaJpDVOckqxrIqv@lBVo2TQ@T96yirksK/ZJpnFedTbGzr6cZu/kmRWhshXUTudg6hUKV0KTmHFcqomx7HYciQgynlvPs6ptIw2Aq3BKV9PSkUQ99LtjmJgVrgPh3w4dYIh8eWMDDoSiP9fkPd9vVHSrvR222yUCs@sqY4@NAA9uOhQcoiz4Jai16Yv4jAZAKEhFwZECAkGCoXGP3YwpMxlAnqkM1PwnbeSypmMDhGYjBOZ2FwtteG95/ROiEXkFTvIk2uqo@@30OVTpfOY3wn9HuErxMcutKeJ5kjatIIc8B@xLXaNOBuiZA3V6AOKGMGrT0NhNyoVwThhvDQgqXwvkftmZZN0KlzT1cWw@6oT2VReJgeietPL7JQ0tYX5Rc "Z80Golf – Try It Online")
## Explanation
z80golf is Anarchy Golf's hypothetical Z80 machine, where `call $8000` is a putchar, `call $8003` is a getchar, `halt` makes the interpreter exit, your program is placed at `$0000`, and all other memory is filled with zeroes. Making programs radiation-proof in assembly is pretty hard, but a generically useful technique is using one-byte idempotent instructions. For example,
```
or c ; b1 ; a = a | c
```
is just one byte, and `a | c | c == a | c`, so it can be made radiation-proof by just repeating the instruction. On the Z80, an 8-bit immediate load is two bytes (where the immediate is in the second byte), so you can load *some* values into registers reliably too. This is what I originally did at the beginning of the program, so you can analyze the longer variants I archived at the bottom of the answer, but then I realized that there is a simpler way.
The program consists of two independent payloads, where one of them could have been damaged by radiation. I check whether a byte was removed, and whether the removed byte was before the second copy of the payload, by checking the values of some absolute memory addresses.
First, we need to exit if no radiation was observed:
```
or a, (ix+endbyte) ; dd b6 21 ; a |= memory[ix+0x0021]
jr nz, midbyte ; 20 10 ; jump to a halt instruction if not zero
```
If any byte was removed, then all the bytes will shift and `$0020` will contain the last `76`, so `$0021` will be a zero. We can afford radiating the beginning of the program, even though there is virtually no redundancy:
* If the jump offset `$10` is removed, then radiation will correctly be detected, the jump will not be taken, and the offset will not matter. The first byte of the next instruction will be consumed, but since it's designed to be resistant to byte removals, this doesn't matter.
* If the jump opcode `$20` is removed, then the jump offset `$10` will decode as `djnz $ffe4` (consuming the next instruction byte as the offset -- see above), which is a loop instruction -- decrement B, and jump if the result is not zero. Because `ffe4-ffff` is filled with zeroes (`nop`s), and the program counter wraps around, this will run the beginning of the program 256 times, and then finally continue. I am amazed this works.
* Removing the `$dd` will make the rest of the snippet decode as `or (hl) / ld ($1020), hl`, and then slide into the next part of the program. The `or` will not change any important registers, and because HL is zero at this point, the write will also cancel out.
* Removing the `$b6` will make the rest decode as `ld ($1020), ix` and proceed as above.
* Removing the `$21` will make the decoder eat the `$20`, triggering the `djnz` behavior.
Note that using `or a, (ix+*)` saves two bytes over `ld a, (**) / and a / and a` thanks to the integrated check for zero.
We now need to decide which of the two copies of the payload to execute:
```
or (ix+midbyte) ; dd b6 15
jr z, otherimpl ; 28 0c
nop ; 00
; first payload
ld a, 'b' ; 3e 62
rst $0038 ; ff
ld a, 'e' ; 3e 65
rst $0038 ; ff
rst $0038 ; ff
ld a, 'p' ; 3e 70
rst $0038 ; ff
midbyte:
halt ; 76
otherimpl:
nop ; 00
ld a, 'b' ; 3e 62
; ... ; ...
rst $0038 ; ff
endbyte:
halt ; 76
```
The two copies are separated by a nop, since a relative jump is used to choose between them, and radiation could have shifted the program in a way that would make the jump skip the first byte after the destination. Additionally, the nop is encoded as a zero, which makes it easy to detect shifted bytes. Note that it doesn't matter which payload is chosen if the switch itself is corrupted, because then both copies are safe. Let's make sure that it will not jump into uninitialized memory, though:
* Deleting `$dd` will make the next two bytes decode as `or (hl) / dec d`. Clobbers D. No big deal.
* Deleting `$b6` will create an undocumented longer encoding for `dec d`. Same as above.
* Deleting `$15` will read the `$28` instead as the offset, and execution will proceed at the `$0c`, as below.
* When `$28` disappears, the `$0c` is decoded as `inc c`. The payload does not care about `c`.
* Deleting `$0c` - that's what the nop is for. Otherwise, the first byte of the payload would have been read as the jump offset, and the program would jump into uninitialized memory.
The payload itself is pretty simple. I think the small size of the string makes this approach smaller than a loop, and it's easier to make position-independent this way. The `e` in `beep` repeats, so I can shave off one `ld a`. Also, because all memory between `$0038` and `$8000` is zeroed, I can fall through it and use a shorter `rst` variant of the `call` instruction, which only works for `$0`, `$8`, `$10` and so on, up to `$38`.
## Older approaches
### 64 bytes
```
00000000: 2e3f 3f2e 3f3f 7e7e a7a7 201f 1e2b 2b1e .??.??~~.. ..++.
00000010: 2b2b 6b00 7ea7 2814 003e 62cd 0080 3e65 ++k.~.(..>b...>e
00000020: cd00 80cd 0080 3e70 cd00 8076 003e 62cd ......>p...v.>b.
00000030: 0080 3e65 cd00 80cd 0080 3e70 cd00 8076 ..>e......>p...v
```
### 58 bytes
```
00000000: 2e39 392e 3939 7e7e a7a7 2019 3a25 00a7 .99.99~~.. .:%..
00000010: 2814 003e 62cd 0080 3e65 cd00 80cd 0080 (..>b...>e......
00000020: 3e70 cd00 8076 003e 62cd 0080 3e65 cd00 >p...v.>b...>e..
00000030: 80cd 0080 3e70 cd00 8076 ....>p...v
```
### 53 bytes
This one has an explanation in the edit history, but it's not too different.
```
00000000: 3a34 00a7 a720 193a 2000 a728 1400 3e62 :4... .: ..(..>b
00000010: cd00 803e 65cd 0080 cd00 803e 70cd 0080 ...>e......>p...
00000020: 7600 3e62 cd00 803e 65cd 0080 cd00 803e v.>b...>e......>
00000030: 70cd 0080 76 p...v
```
## What if: any non-empty output was fine instead of beep
### 1 byte
```
v
```
`halt`s the program normally, but if radiation removes it, then the memory will be full of zeroes, making `$8000` execute an infinite number of times, printing a lot of null bytes.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 23 bytes
```
<|o<"beep"/
>o<"beep"<\
```
[Try it online!](https://tio.run/##S8sszvj/36Ym30YpKTW1QEmfyw7GtIn5/x8A "><> – Try It Online") [Verification.](https://tio.run/##fVHBbsIwDD2Tr/DKIa3YitBuHeywfcAOOzKEstal1iCJEpeq0v6duQwGmrRdIif2e37vxffcOHt/oJ13gcFF5YPbBLODBQSt9WH@6ebJO6JPpurxXM7fDtJbzoq72UoAZDnVTz0jlK61XOhb2KJNT0w52tJVmGoTSyKdZZlSFdYQWrveusjr09x5PivUqCNuwHkh0QNWCHWnMzARaumO6rwLxPiDUKOA3AYr@nN/hNWJ/3YGU@d5WlNsjkfuexgYkywPaKpUtLiWB7N/qVHKxIhDNsPcArRWYhn3z40JMFwflBrDCzcYOooI3FAEph3GI8IEiaSCxmzrzvRAVtUuAEkBwdgNpldJZYN1quF0XdIKbhZwXlYAjOH1gzxQhZapNFuxYiOWLdNespcZUzKGKAn9b2pZCPXksmcyK1YS4uiX0@GvtTxf2b1IU4cv "Python 3 – Try It Online")
It's honestly really surprising how short I got this. Ends with an error.
### Non-erroring version, 29 bytes
```
<<;oooo"beep"/
;oooo"beep"<\
```
[Try it online!](https://tio.run/##S8sszvj/38bGOh8IlJJSUwuU9LkUkHg2Mf//AwA "><> – Try It Online")
[Answer]
# [Klein](https://github.com/Wheatwizard/Klein), one of each topology, totaling 291 bytes
After seeing [WW's answer](https://codegolf.stackexchange.com/a/170741/76162) using the `001` topology, I decided to see how hard it would be to do a Geiger Counter for each topology. (Spoiler: very hard. It's difficult to figure out where the pointer will go without hand gestures that make me look like I'm figuring out which hand is my left)
[Verification!](https://tio.run/##jZPNbqMwFIXX@CkumYVBydiQ2UVEymjeYTZ1VTnFJNYQbBm3UVT12TM2wYBCVHXDj@93rs89GH2xR9X8usqTVsaCapE26mD4qYUtfFxxlmV4gwzGuCh2Cy3EfkER6Z8KBq6wQghn@fewLO@xmDwACSkIGTp@G80Hj5T2ZYYCV9CByu8pOlJxoMZBSNiVMUTYjvQoKwY0v5@5cCQJFmnYeT3PcPQXj1RoxxhhQ3aUuKHp2HUMcz1YpYwNOEN0R8icnTS/FZOkoCimu10xhdH1E6FSVGDempf@KCRWaVWrw2UF/Uq6QdFZ2iMoLZoEv6pS4BXgM06Bt1C5alSRs5FWJEGBIiPsm2ncESO6k1UL3R2@NVClLf1XC9ncrkRfwPeEj7DzJ/z8vUiJEbxMUoSssrx2BzRDqFIGZv5ANuGxJc7FqU285VDdhiJprZHadYxuHZdbqJ2z0fMPbWRjk6/DcBxvW@F@n4dcwGC7Bcwa7H2I9z9HbpwRl3jkR5DesuHNQSRTB951JKuw1ZN8hti7v@l9MTK8lNyK8mU23dPG4ctRu8w3z14RhroTptPao0Fmgk7x1egzRZfBXgjd5RBNkxhH9AF5E0Mb/JfXsozxahrNCu8vVrQEpyjg7hP2q9C9OEV3p/k6rPN3YfhBONX1Pw "Python 3 – Try It Online")
(I also thought about writing a program that is a valid Geiger counter on all topologies, but that might have to wait. If anyone else wants to try though, I'm offering a 500 rep bounty)
### 000 and 010, 21 bytes
```
<<@"peeb"/
.@"peeb"<\
```
[Try 000 online!](https://tio.run/##y85Jzcz7/9/GxkGpIDU1SUmfSw/Kson5//@/gYHBf11HAA "Klein – Try It Online") and [Try 010 online!](https://tio.run/##y85Jzcz7/9/GxkGpIDU1SUmfSw/Kson5//@/gaHBf11HAA "Klein – Try It Online")
This is ported from my [`><>` solution](https://codegolf.stackexchange.com/a/169995/76162). This obviously works in `000`, since that's the default topology for most 2D languages, but I was surprised that it also works in `010`.
### 001 and 011, 26 bytes
```
!.<<@"peeb"/
.@"peeb"..<..
```
[Try 001 online!](https://tio.run/##y85Jzcz7/19Rz8bGQakgNTVJSZ9LD8rS07PR0/v//7@BgeF/XUcA "Klein – Try It Online") and [Try 011 online!](https://tio.run/##y85Jzcz7/19Rz8bGQakgNTVJSZ9LD8rS07PR0/v//7@BoeF/XUcA "Klein – Try It Online")
This one is copied directly from [WW's answer](https://codegolf.stackexchange.com/a/170741/76162). Thanks!
### 100, 21 bytes
```
//@"peeb"\
@"peeb".</
```
[Try it online!](https://tio.run/##y85Jzcz7/19f30GpIDU1SSmGC8rQs9H///@/oYHBf11HAA "Klein – Try It Online")
### 101, 21 bytes
```
//@"peeb"/
@"peeb".<!
```
[Try it online!](https://tio.run/##y85Jzcz7/19f30GpIDU1SUmfC8rQs1H8//@/oYHhf11HAA "Klein – Try It Online")
### 110, 26 bytes
```
<.<@"peeb"\\
.\@."peeb".\<
```
[Try it online!](https://tio.run/##y85Jzcz7/99Gz8ZBqSA1NUkpJoZLL8ZBD8LRi7H5//@/oaHBf11HAA "Klein – Try It Online")
### 111, 24 bytes
```
<<@"peeb"<\
...@"peeb"//
```
[Try it online!](https://tio.run/##y85Jzcz7/9/GxkGpIDU1SckmhktPTw/K0df///@/oaHhf11HAA "Klein – Try It Online")
### 200, 21 bytes
```
<<@"peeb"\
@"peeb".!/
```
[Try it online!](https://tio.run/##y85Jzcz7/9/GxkGpIDU1SSmGC8rQU9T///@/kYHBf11HAA "Klein – Try It Online")
### 201, 31 bytes
```
\\.\.@"peeb"</./
./...@"peeb"<\
```
[Try it online!](https://tio.run/##y85Jzcz7/z8mRi9Gz0GpIDU1SclGX0@fS09fTw8uEPP//38jA8P/uo4A "Klein – Try It Online")
By far the most annoying.
### 210, 26 bytes
```
/\\@"peeb"</\
/@.."peeb"<\
```
[Try it online!](https://tio.run/##y85Jzcz7/18/JsZBqSA1NUnJRj@GS99BTw/Ki/n//7@RocF/XUcA "Klein – Try It Online")
### 211, 27 bytes
```
\\."peeb"((</
!/@@<"peeb"<\
```
[Try it online!](https://tio.run/##y85Jzcz7/z8mRk@pIDU1SUlDw0afS1HfwcEGwreJ@f//v5Gh4X9dRwA "Klein – Try It Online")
The only one where I had to handle entering the beeper through the right side.
[Answer]
# [Klein](https://github.com/Wheatwizard/Klein) 0X1, 26 bytes
*Works in both 011, and 001.*
```
!.<<@"peeb"/
.@"peeb"..<..
```
[Try it online!](https://tio.run/##y85Jzcz7/19Rz8bGQakgNTVJSZ9LD8rS07PR0/v//7@BgeF/XUcA "Klein – Try It Online")
[Verify!](https://tio.run/##bVHLbsIwEDzHX7Gkh41FMYTeIpDafkQvFCFDNrAq2JZjhPj61IEUUMnFWmsemtl157Cz5q3hg7M@gK2F83br9QHm4BGxGajZ7D11ROt0LFQ3KTVTqonwIi9G@TJq2IQMP8@BYGOPJhT4CnsyWWemyGxsSRnqesOMUkohREkV@KNZdZw/rixEcuKwA@uiAba6aIYnlKBrqCKaVOrkOdBNIRJP4ehNjK/cRVal7lJsCmPrwvhnT2yur3JnaD1hMslh9JFK5UmXWQx0LdGXSApd1xTX0wfCfA74bVBU1gMDG/DabCl7qC/bTl6XrAOVq/uCu2lR8BKGtx8P82Ipkpcuzz@ZvCMPYZ5YkdaT@Yl2Cb8mcm2B7opfes/lAGXzCw "Python 3 – Try It Online")
## Explanation
This program takes advantage of Klein's unique topologies in particular the **001** and **011** topology, which are the Klein bottle and the real projective plane. This explanation will focus on **001**, the klein bottle.
Unedited the program follows the execution path:
[![Orange path](https://i.stack.imgur.com/YSbr0.png)](https://i.stack.imgur.com/YSbr0.png)
Removing a byte from the program can effect the program in 4 ways (each in a different color):
[![Program sections](https://i.stack.imgur.com/ElVmw.png)](https://i.stack.imgur.com/ElVmw.png)
The first thing to note is that `<<` will always deflect the ip to the left of the origin at the start. If one of the `<`s is deleted the other takes its place. So if any byte is removed from the red section the following execution path will be followed:
[![Red path](https://i.stack.imgur.com/G41cW.png)](https://i.stack.imgur.com/G41cW.png)
If the blue byte is removed we get the very simple path:
[![enter image description here](https://i.stack.imgur.com/hi14q.png)](https://i.stack.imgur.com/hi14q.png)
If the newline is removed we get the path:
[![Green path](https://i.stack.imgur.com/l9HIp.png)](https://i.stack.imgur.com/l9HIp.png)
The yellow path is a bit more complex. Since the bottom line is one longer than the top line, when the program is squared at the beginning of execution a virtual character is added to the end of the first line to make them the same size. If any byte on the second line is removed the line is shortened and that virtual character is not added. This is important because `!` normally jumps over the virtual character, but in its absence it jumps over `/` instead.
[![Yellow path](https://i.stack.imgur.com/DBr7q.png)](https://i.stack.imgur.com/DBr7q.png)
[Answer]
# [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/), ~~144~~ 102 bytes
Unprintables are displayed as escape sequence (for example `\x01`).
```
\xa8<<[[<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<[[[.<-]>[>-]\x01qffb\x00\x00beep\x00]]]<[>]<<[>[-<+>]+<<]>[[>]>>[.>]]\x01
```
[Verification!](https://tio.run/##dVLLTsMwEDzXX7EqEk5IE@Jyq9Ic@ALuxkJJalMLYhvbUeHryzo0wAEOfmh2ZjK7jvuIR2vuzuezHp31EcLUO28HGQIhVzBYE6KfhggIPvtuJMRtYQ89fXyv67R6KV06hRANb0WDGy@bohVF04iWI9S2vGqFQBKjxLFZjTROoUg3epO9SpO5bV5u8xninFdNieK2nFVvSvWUXKQfUYaMl2EaM8fy6/pdKZFkjpEuBIkd1GBsBG1@QY7xWixwT4tyUzUtFxjnqys0dqxwW/yI1yZm9OEL39HN0ni@lO4xAc5lMjFV5@gXRk7IQSrwk3m6QN@lHVmddDyCdcingz1I1NL@RHPoAigsr1R18jrKbwlZdSZgsJ8HqYajHF6e7BTdFDO@vrUu3oaxV/O23sA6Ga/FBqIeJdL2DF28jJM3gGZkGcdfCWGf3oUSZT3oNCbfmWeZ/e6vZKmP/z34TotiueuC7cTFNf0j9PwJ "Python 3 – Try It Online")
[Answer]
# [Backhand](https://github.com/GuyJoKing/Backhand), ~~25~~ 21 bytes
```
vv""ppeeeebb""jjHH@
```
[Try it online!](https://tio.run/##S0pMzs5IzEv5/7@sTEmpoCAVCJKSRESUlLKyPDwc/v8HAA "Backhand – Try It Online") [Verification!](https://tio.run/##dZDBbsIwDIbP7ZkH8CKhNAIVTbtVqjSxC7vsBRBCaePSsJFESQrq03cJlDJNW0527P@3P5vet1q9DMMgT0ZbD9qlY@R6l6bG6oPlJyhjmjsvpMotcpGxWJPKZ3Tde4Rad8oXdAlfqLJRlKOqtcCMcldLSRljo2SsBwuBDdhO7cefqVKkyUX6FrQJdjS6BGt6oQy4gyZUkya/WOnx4ZVY9J1VASA3V1lDzA0OVtr4VcXrz5YrsVqPwf5debQmyNDmpoc4hbCJTnc@UP@13B38Q0MdjA4YuUM7S7lzGG8YpSVQGm@E57eWW7iljbYgQSqwUZf9OBaLzLKBMd3KHTyVcJdH4ttUMheQzR0ryDyTy0c3WwIqUVIaLpH8u/u2kLvFJFo8Fzs2OV8JkuQXQ4Vo6LVnAnkMTYfzmRBjMLyqms0IOR43m9dv)
This uses Backhand's ability to change the pointer step value to skip an instruction every step and neatly solve the redunancy issue. It then uses the `j` command to check if the code is irradiated by jumping to the last character (`@`, halt) if not, and jumping to the second last (`H`, halt and output stack) if so.
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 29 bytes
```
>>yyLL@"peeb"/
@"peeb"L\
```
[Try it online!](https://tio.run/##KyrNy0z@/9/OrrLSx8dBqSA1NUlJn0sBBKA8n5j//wE "Runic Enchantments – Try It Online")
Essentially the same as the Klein 000 answer or ><> answer (I started with the Klein one). The only change really needed was to turn the `<` into `L` and `.` into (translation of command symbols), inserting the IP entry points (need 2, otherwise a deletion would result in a non-compiling program) and the insertion of the dela`y` command to get the two IPs to merge (thus printing only one `beep`), again, needing two. Also required inserting additional NOPs to keep line lengths the same. Klein conveniently also uses `@` for "print and terminate."
No ability to utilize the whitespace in the lower left, as any reflectors to change direction inhibits the ability to detect radiation. e.g. (26 bytes, irradiated `y`):
```
/yLL@"peeb"/
\<< @"peeb"L\
```
Prints no output, due to the bent entry segment causing a re-reflection back to the lower line's terminator.
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 55 bytes
```
<< > vv
>,,@#"beep"<"
v | _ #-<_
>"peeb",,,,@>
```
[Try it online!](https://tio.run/##S0pNK81LT/3/38ZGwU4BAsrKuOx0dByUlZJSUwuUbJS4yhQUaoDi8QrKujbxXHZKBampSUo6QOBg9/8/AA "Befunge-93 – Try It Online") [Verification!](https://tio.run/##dZDdbsIwDIWvm6fwglAaUYomrla1Fdru9wIIof64NBIkVZIWIe3dWQKlTNOWKzv2Ofbn7mJbJdfX61WcOqUtKEPGyFwMIZ1WB12cIPNpbGwtZKyxqEPua0LakL1fLEKlemkTFsERZTiKYpSVqjFkhamEYJzzUTLWnUWNDehe7sefqZKQ4CxsC6pzdsy7xGXj3NmZcSgMNK4haOKzFhafdoFG22vpGOLupmzoSnV2VWLTywOuSiF9DN4PvsAW4gjLChbrN8onKtVbR/vXUg/gTwVVWzhDz@vaOSmMQX87L82AMX8bHD7aQsM9bZQGAUKC9rrwx5G4ZxUNjOlW7OAlg4fcY96n0nkN4dzwhM5DET27eQQo64wxhx/8u/s2EbvFJFq8Jjs@Od8IguAXQ4nYsVvPBPIcSq5pCjnc3zCQPIo2M@olNKVkAHdcgD3Mlume5LRDLGnk3ib/Bg "Python 3 – Try It Online")
I'd hoped to get it a little smaller than this, but the length of the `beep` printer is the bottleneck.
[Answer]
# [Wumpus](https://github.com/m-ender/wumpus), ~~37 34 32~~ 31 bytes
```
777*7..@ $o&4"beep"|"@peeb"4&o@
```
[Try it online!](https://tio.run/##Ky/NLSgt/v/f3Nxcy1xPz0FBJV/NRCkpNbVAqUbJoSA1NUnJRC3f4f9/AA "Wumpus – Try It Online") [Verification!](https://tio.run/##dZHfasMgFMav41OchbXGtdiOFQKBQNnu9wJdGfljGqFVUbMssHfPtLXpGNuVHs/3ffo7qsG2UjyN48hPSmoL0qCwM4NBSGl50MUJcl9SY2suqGZFnRC3qGNRsQQDXuK3z/UaE6/nwib4ebAMKtkJm@ElHJlIQhBlopK1MxWm4hwTQoIl9F1EzRrQnXgPJ1MnQ1HPbQtSuTjsU1w07jGBwkDjulFDe80tu2VFmtlOCwdF1dnWxLorB1hJZVd9d1KdCQvVJfjImAQ8hGRnHfZfL7lSvkqo2kIcmId0coIKY5gforfmgLEfCPt4aQsNl7KRGjhwAdr7kh@TIR6QNxDKHd/DXQ5Xu8e73BrPakhmhmTxLOHLm5osgYk6x@4Xoujft@8yvl9MpsVjtidT8pkgin4xlIwpfNZMILdL0Zim6UNK6Rbu5XwTe3H8FW8VY2W8mcvtNw "Python 3 – Try It Online")
This solution uses the fact that `.` jumps to a position modulus the length of the program.
Alternatively for the same amount of bytes
```
" @o&4"beep"}@
@o&4"beep"}$}
```
[Try it online!](https://tio.run/##Ky/NLSgt/v@fS0nBIV/NRCkpNbVAqdaBC4mjUqug8P8/AA "Wumpus – Try It Online") [Verification!](https://tio.run/##dZHRbsIgFIav4SnOmjlKbKrLdtWkidnu9wLOLNhSS6JAgK7rhc/egWI1i7uCw/n/H76DHlyr5Ms4juKglXGgLI47O1iMtVE7ww5QhjK3rhYyN5zVKfWL3rOKpwRIRj5/lktCg15Il5K3wXGoVCddQTLYc5nGoJzLStXexGwlBKGURkvs@4iaN2A6@RVPpk6BUS9cC0r7OBJSfDTpCQVmofFd1OS9EY5fs5DhrjPSQ@X6ZGsS020HWCjtFn130J2NS262ECITGvEwVp3z2PdecqH8UFC1TO54gPRyipm1PAwxWEsgJAyEf7@3zMC5bJQBAUKCCb70ZjI0AIoGYrkWG3go4WIPeOdbk1kN6czSIpmlIruqaQZc1iXxv4DQv29fF2Izn0zz52JDp@QTAUJ/GLaca3LSTCDXS/GIE1ipp9ckyJLjCt8Uj0eAXw "Python 3 – Try It Online")
This one utilises the difference in the direction of the pointer for odd and even line lengths. (I don't really know how the first `"` actually works when the newline is removed)
] |
[Question]
[
Not to be confused with [Find the factorial!](https://codegolf.stackexchange.com/questions/607/find-the-factorial)
## Introduction
The factorial of an integer `n` can be calculated by
$$n!=n\times(n-1)\times(n-2)\times(...)\times2\times1$$
This is relatively easy and nothing new. However, factorials can be extended to [double factorials](https://en.wikipedia.org/wiki/Double_factorial), such that
$$n!!=n\times(n-2)\times(n-4)\times(...)\times4\times2$$
for even numbers, and
$$n!!=n\times(n-2)\times(n-4)\times(...)\times3\times1$$
for odd numbers. But we're not limited to double factorials. For example
$$n!!!=n\times(n-3)\times(n-6)\times(...)\times6\times3$$
or
$$n!!!=n\times(n-3)\times(n-6)\times(...)\times5\times2$$
or
$$n!!!=n\times(n-3)\times(n-6)\times(...)\times4\times1$$
depending on the starting value.
In summary:
$${\displaystyle n!^{(k)}={\begin{cases}1&{\text{if }}n=0 \\n&{\text{if }}0<n\leq k\\n\cdot\left({(n-k)!}^{(k)}\right)&{\text{if }}n>k\end{cases}}}$$
where
$${\displaystyle n!^{(k)}=n\underbrace{!\dots!}\_{k}}$$
Or, in plain English: **Subtract the factorial count from the base number repeatedly and multiply all resulting positive integers.**
## The Challenge
Write a function that will calculate any kind of repeated factorial for any non-negative integer.
### Input
Either
* A string containing a non-negative base-ten integer, followed by 1 or more exclamation marks. E.g. `"6!"` or `"9!!"` or `"40!!!!!!!!!!!!!!!!!!!!"`.
or
* The same values represented by two integers: one non-negative base value and one positive value representing the factorial count. This can be done according to any format from the default I/O rules.
### Output
The result of said calculation.
## Challenge remarks
* `0!` equals `1` by definition. Your code must account for this.
* The factorial count is limited by $$ 0 < factorial~count \leq base~value $$outside this range, you are free to output whatever. Aside from `0!`, which is the only exception to this rule.
## Examples
```
Input Output
3!!! 3
0! 1
6! 720
9!! 945
10!!!!!!!! 20
40!!!!!!!!!!!!!!!!!!!! 800
420!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 41697106428257280000000000000000
```
Try it with an ungolfed Python implementation: [Try it online!](https://tio.run/##bY5BCoMwEEX3/xQZNyZiRasULPQwImkrSAwxKe3p06mK7aJ/9XnzZhL78vfJ1FE/dS/bLEmSOBgrOBfBJXip8OjGoFfgJcNi9m6wMqVUKRghdrvop8DKZyAmJ5Y9OD2H0bNQAVemA5vCdeam5SLkZX4w6ozlzCZnfA6w7vPgihQi/03FmohQEk6ElltV0hY0e/0NmuNf/s0b "Python 3 – Try It Online")
## General remarks
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer using the fewest bytes in each language 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.
* Please include a [Try it Online](https://tio.run/#)-link to demonstrate your code working.
* Please motivate your answer with an explanation of your code.
[Answer]
# [R](https://www.r-project.org/), 33 bytes
```
function(n,k)prod(seq(n+!n,1,-k))
```
[Try it online!](https://tio.run/##LclJCoAwDEDRvaeouwQjdBDRhadRA1JIHc8fW3H1H/xTeVJ@ZL63JCAUcT/TAtd6gDS1kKM2IipDIBOwYrBkXGn/dyTjS10eQ0GX4e0nnxks6gs "R – Try It Online")
Handles \$n=0\$ by adding the logical negation of \$n\$.
[Answer]
# [ArnoldC](https://lhartikk.github.io/ArnoldC/), 702 698 634 bytes
```
LISTEN TO ME VERY CAREFULLY f
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE p
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE r
YOU SET US UP 1
HEY CHRISTMAS TREE c
YOU SET US UP 0
STICK AROUND n
GET TO THE CHOPPER r
HERE IS MY INVITATION r
YOU'RE FIRED n
ENOUGH TALK
GET TO THE CHOPPER n
HERE IS MY INVITATION n
GET DOWN p
ENOUGH TALK
GET TO THE CHOPPER c
HERE IS MY INVITATION 0
LET OFF SOME STEAM BENNET n
ENOUGH TALK
BECAUSE I'M GOING TO SAY PLEASE c
GET TO THE CHOPPER n
HERE IS MY INVITATION 0
ENOUGH TALK
YOU HAVE NO RESPECT FOR LOGIC
CHILL
I'LL BE BACK r
HASTA LA VISTA, BABY
```
[Try it online!](https://tio.run/##rZJBb9swDIXv@hXvlksPTlsM25GWaUuoLBqSnMDHIVtPRTZ02@/PqGYd0C3BtmZH0k8f6ff4/nH/6eHD7uDLKiM72RY/sjGOF1iXfC4jZZTEjMePX749fDWLzMhcMGfMExpjBi20mUBZlYKRUn4WdwJfEGWLe9zgxhQKd1VTHMNR7J51fw1psL4c8uZ/QN7h@nLIusHbyym3Da6b85iamKMNo2WOKJxGH6lwdwgab@0ombHhpJFT4n4OYcG98YjM3XEBG0Sx@Vi0IiWjTngqRymS7GIDY/@aR5/N4HW5KmVMLJP2yKeTJ/jL9a1PiXa/nWgu3t6Bksw6fv9k6w@frJNp4qRgx4nhM8YFPm58oeIlHgeu9EvvE9e3HGUeHKrXpzj7M5zj0E62UX/3D4zdGUZjgoql75FF89LoaNRIY9Tuy8VatjSrmX41YhAfhzoi0wK1lnJ16B9Wb16gf95SFCTOE9uCXhKCDN4a63wIxq9C0MXQkrquzlIuhEDYaEp0pe12ORy@Aw "ArnoldC – Try It Online")
Translated to pseudocode:
```
f(n,p) {
r=1;
c=0;
while (n) {
r=r*n;
n=n-p;
c=n<0;
if (c) n=0;
}
return r;
}
```
Note: ArnoldC has only one type of data: 16-bit signed integer. Hence I cannot test the `420!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!` case.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
RṚmP
```
[Try it online!](https://tio.run/##y0rNyan8/z/o4c5ZuQH///83MfhvZAAA "Jelly – Try It Online")
**How?** Given \$n\$ and \$k\$, it first generates the range \$n,\cdots, 1\$ (with `RṚ`), then with `m` it keeps every \$k^{\text{th}}\$ element of this range (so \$n, n-k, n-2k,\cdots,n-\lfloor n/k\rfloor k\$), and finally multiplies them using `P`.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 7 [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. Takes `[n,b]` as argument.
```
×/-\…1¨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn///B0fd2YRw3LDA@t@J/2qG3Co96@R31TPf0fdTUfWm/8qG0ikBcc5AwkQzw8g/@nKRgrGHOBSHMgaaBgCCTNwKSlghGQNDRQsABSJgYKRgYg2shAwdgAAA "APL (Dyalog Extended) – Try It Online")
`1¨` one for each element of the argument; `[1,1]`
`-\` cumulative difference; `[n,n-b]`
`…` range using second element of left argument as indicator of step, e.g. `[9,7]` continues with `5`
`×/` product
[Answer]
# [Haskell](https://www.haskell.org/), 21 bytes
```
n%a=product[n,n-a..1]
```
[Try it online!](https://tio.run/##HcVLDoMgEADQq8yiJpCMZoCmqQtPYlxM6M8UR4Ky8PKltJv3Xry97yGUIg0PMa237PdRUFruOjOVhWeBAWKaZYcTLBxBZfE5pQNUozWMyqHTqAhN9fK3R1s1hNfamdDSb0voSE/l4x@Bn1tpfYxf "Haskell – Try It Online")
Combining the built-in product function with stepped range enumeration beats what I could code up recursively (even with flawr saving a byte).
**22 bytes**
```
n%a|n<1=1|m<-n-a=n*m%a
```
[Try it online!](https://tio.run/##HcXNCgIhEADgV5lDgsYIo0a0sD5JdBikn6V1ELc9BPvsmXX5vgcvz@s8tyaKNxlddFserViOss@KW@ZJIEKpk7xgB5kL6FXSWusbtDIGzjpgMKgJXff4d0DfdYSn3oHQ029PGMhc2ifdZr4vzaZSvg "Haskell – Try It Online")
Here's a solution taking input in string format like `9!!`, which I think is more interesting.
**42 bytes**
```
(\[(n,a)]->product[n,n-length a..1]).reads
```
[Try it online!](https://tio.run/##bcFBCoAgEADAr2zRwSCloGt9JDssphbZJmrfb/tAMzvm04bAbtIs9CKow3aVc0z39piyUEcyWPJlB1RqWFuVLG6ZLzwIJojpoAINOKjHvvpR82tcQJ9Zmhg/ "Haskell – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 6 bytes
These are all equivalent 6-byters:
```
*F:Q1E
*F:E1Q
*F%E_S
```
[Try it online! (`*F:Q1E`)](https://pythtemp.herokuapp.com/?code=%2aF%3AQ1E&input=40%0A20&debug=0)
Or, **11 bytes**, taking input as a string:
```
*F:.vQ1/Q\!
```
[Test suite.](https://pythtemp.herokuapp.com/?code=%2aF%3A.vQ1%2FQ%5C%21&input=%2240%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%22&test_suite=1&test_suite_input=%223%22%0A%223%21%21%21%22%0A%223%21%21%21%21%21%21%21%22%0A%220%21%22%0A%226%21%22%0A%229%21%21%22%0A%2210%21%21%21%21%21%21%21%21%22%0A%2240%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%22%0A%22420%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%21%22&debug=0)
[Answer]
# JavaScript (ES6), 21 bytes
Takes input as `(k)(n)`.
```
k=>g=n=>n<1||n*g(n-k)
```
[Try it online!](https://tio.run/##ZcxBDoIwEAXQvadgOWOCtEOhJbHchSA0CmmJGFfcvRY1IZSf2b3/59G8m7l93qdXat2t8732g66Ntrq2V74s9mzApgP61tnZjd1ldAZ6yDEcJmuyLMlPe@UIbFN@1HJTSSxyQqg2r0QRuULg//fBj3OGIH4eWLHY89XpWwgueFlJzkpBigpJob6P/wA "JavaScript (Node.js) – Try It Online")
Or [**24 bytes**](https://tio.run/##bc1LDoIwEIDhvadg2ZognVLaYiyehSA0CpkaMV6/Dj4SQCfp6v86c6kf9djcztd7iuHUxs7F3lXeoavwAHgE3OPWM0x7HpuAYxja3RA861iOfHo8mSbLknyz7EBdzDr86XrWjRQrIUmUM1GqYiUsCfgeIfG7giJTH0HAirXIX0K@CQkFujQgtJJWFkbSh@XEJw) to support BigInts.
---
# JavaScript (ES6), 55 bytes
Takes input as a string, using the format described in the challenge.
```
s=>(a=s.split`!`,k=a.length-1,g=n=>n<1||n*g(n-k))(a[0])
```
[Try it online!](https://tio.run/##jc7dCoIwGMbx867CebSFH9v8huaNROAwNXNs0qQj790sImqG@D//Pe975Xeuy1vbD65U52qq2aRZDjnTnu5FOxSgcDrGPVHJZri4xGmYZLk8kHGU@wZKt0MI8iM@oalUUitReUI1sIZ2AACwEbLW830r2BkSb3AvSUwZb5UJxabNtrz7tFkYmZZg8G5tYrbLs@GHfmfOzDTFS0v/YmNmtiGJs4TgOKQpjRI6T/02PQA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 91 bytes
```
[S S S T N
Push_1][S N
S _Duplicate_1][S N
S _Duplicate_1][T N
T T _Read_STDIN_as_integer_(base)][T T T _Retrieve_base][S S S N
_Push_0][T N
T T _Read_STDIN_as_integer_(factorial)][N
S S N
_Create_Label_LOOP][S N
S _Duplicate_base][S S S T N
_Push_1][T S S T _Subtract][N
T T S N
_If_negative_jump_to_Label_PRINT_RESULT][S N
S _Duplicate_base][S T S S T S N
_Copy_0-based_2nd_(result)][T S S N
_Multiply][S N
T _Swap_top_two][S S S N
_Push_0][T T T _Retrieve_factorial][T S S T _Subtract][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT_RESULT][S N
N
_Discard_top][T N
S T _Print_result_as_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/##JYxRCoAwDEO/k1PkCGN6IZHB/BMUPH5tulLS5pH2m9c7nvs4R4QkUFQ2CFcSei2W4gBKsICNjFgqriu/ofOeaRCx98at/Q) (with raw spaces, tabs and new-lines only).
**Explanation in pseudo-code:**
```
Integer result = 1
Integer base = STDIN as integer
Integer factorial = STDIN as integer
Start LOOP:
If(base <= 0):
Call function PRINT_RESULT
result = result * base
base = base - factorial
Go to next iteration of LOOP
function PRINT_RESULT:
Print result as integer to STDOUT
```
[Answer]
# [Python 2](https://docs.python.org/2/), 29 bytes
```
f=lambda n,b:n<1or n*f(n-b,b)
```
**[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIU8nySrPxjC/SCFPK00jTzdJJ0nzf0FRZl6JRpqGoZGOqabmfwA "Python 2 – Try It Online")**
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ݦRIιнP
```
Input as two separated inputs: first input being `base`; second input being `factorial`.
[Try it online](https://tio.run/##yy9OTMpM/f//8NxDy4I8z@28sDfg/38DLkMA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6H8fA@@giHM7L@wN@K/zPzraWMc4VgdImgNJAx1DIGkGJi11jICkoYGOBZAyMdAxMgDRRgY6xgaxsQA).
-2 bytes thanks to *@Mr.Xcoder*.
-1 byte thanks to *@JonathanAllan*.
**Explanation:**
```
Ý # Create a list in the range [0, (implicit) base-input]
¦ # And remove the first item to make it the range [1, base]
# (NOTE: this is for the edge case 0. For the other test cases simply `L` instead
# of `ݦ` is enough.)
R # Reverse this list so the range is [base, 1]
Iι # Uninterleave with the second input as step-size
# i.e. base=3, factorial=7: [[3],[2],[1],[],[],[],[]]
# i.e. base=10, factorial=8: [[10,2],[9,1],[8],[7],[6],[5],[4],[3]]
# i.e. base=420, factorial=30: [[420,390,360,...,90,60,30],[419,389,359,...],...]
н # Only leave the first inner list
P # And take the product of its values
# (which is output implicitly as result)
```
**Original 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:**
```
L0KD¤-IÖÏP
```
Input as two separated inputs: first input being `base`; second input being `factorial`.
[Try it online](https://tio.run/##yy9OTMpM/f/fx8DbxfPwtMP9Af//G3AZAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6H8fA2@XQ0t0Iw5PO9wf8F/nf3S0sY5xrA6QNAeSBjqGQNIMTFrqGAFJQwMdCyBlYqBjZACijQx0jA1iYwE).
**Explanation:**
```
L # Create a list in the range [1, (implicit) base-input]
0K # Remove all 0s (edge case for input 0, which will become the list [1,0])
D # Duplicate this list
¤ # Get the last value (without popping)
# (could also be `Z` or `¹` for max_without_popping / first input respectively)
- # Subtract it from each item in the list
IÖ # Check for each if they're divisible by the second factorial-input
Ï # In the list we copied, only leave the values at the truthy indices
P # And take the product of those
# (which is output implicitly as result)
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 22 bytes
```
{[*] $^a,*-$^b...^1>*}
```
[Try it online!](https://tio.run/##hc3RCoIwFIDh@z3FGUjoZnObc9OLepFKUFMINEOvRHz2ZRChUPnfnJvvnPMou1rbZoBdBQc7nsgFnDTzyd5Jc8ZYKo5kslXbgVvf7mXvwYgA@myAyqVNcL7SwH9NTANWtE3uocmGGGP4X4j4FgEQSG8jIzlKNv9BoiIkOH73k83H1EctW6mYz0x@dcsNJXRiBNdKxjIyct5a9wQ "Perl 6 – Try It Online")
Anonymous codeblock that returns the product of the range starting from the first input, decreasing by the second until it is below `1`, excluding the last number. This works for `0`, since the base case of a the reduce by product is 1, so the output is 1.
[Answer]
# x86-64 machine code, 12 bytes
Same machine code does the same thing in 32-bit mode, and for 16-bit integers in 16-bit mode.
This is a function, callable with args `n=RCX`, `k=ESI`. 32-bit return value in `EAX`.
Callable from C with the x86-64 System V calling convention with dummy args to get the real args into the right registers. `uint32_t factk(int, uint32_t k, int, uint64_t n);` I couldn't just use Windows x64 because 1-operand `mul` clobbers RDX, and we don't want REX prefixes to access R8/R9. `n` must not have any garbage in the high 32 bits so JRCXZ works, but other than that it's all 32-bit.
NASM listing (relative address, machine code, source)
```
1 factk:
2 00000000 6A01 push 1
3 00000002 58 pop rax ; retval = 1
4 00000003 E306 jrcxz .n_zero ; if (n==0) return
5 .loop: ; do {
6 00000005 F7E1 mul ecx ; retval *= n (clobbering RDX)
7 00000007 29F1 sub ecx, esi ; n -= k
8 00000009 77FA ja .loop ; }while(sub didn't wrap or give zero)
9 .n_zero:
10 0000000B C3 ret
```
0xc = 12 bytes
---
Or 10 bytes if we didn't need to handle the `n=0` special case, leaving out the `jrcxz`.
For standard factorial you'd use `loop` instead of sub/ja to save 2 bytes, but otherwise the exact same code.
---
Test caller that passes `argc` as `k`, with `n` hard-coded.
```
align 16
global _start
_start:
mov esi, [rsp]
;main:
mov ecx, 9
call factk
mov esi, eax
mov edx, eax
lea rdi, [rel print_format]
xor eax, eax
extern printf
call printf
extern exit
call exit
section .rodata
print_format: db `%#x\t%u\n`
```
```
[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 infix function. Takes `n` as right argument and `b` as left argument.
```
×/1⌈⊢,⊢-×∘⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/////B0fcNHPR2PuhbpALHu4emPOmY86t38P@1R24RHvX2P@qZ6@j/qaj603vhR20QgLzjIGUiGeHgG/zdWSFMw5jIHk4ZA0gBMmnEZAUlLLgsgaWjAZWQApE0MuIzBtJEBAA "APL (Dyalog Unicode) – Try It Online")
`×∘⍳` multiply `b` by the **ɩ**ntegers 1 through `n`
`⊢-` subtract that from `n`
`⊢,` prepend `n`
`1⌈` max of one and each of those
`×/` product
[Answer]
# [Ruby](https://www.ruby-lang.org/), 25 bytes
```
f=->s,r{s<1?1:s*f[s-r,r]}
```
[Try it online!](https://tio.run/##hdDbCoJAEIDh@32KXehCS9fddT2F5oPYgQ4IQqXsKBjas9teRChU/tffzMCo5vQYhjyxN2CpDmKe8jUs8wxsZandc2iTOAbkEkLw/1zE5gjGHPnzKBAMRbP3cCQ9xBl595PpZfKjxk1UyDQTX914QnI/CjjzpQiFFwg9NQ0BqpoacEuhuha1sXBMejtWXa/6PFOZs99eVs6O1uWhsLCi57K510ZKTP3oFw "Ruby – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~22~~ 21 bytes
```
1##&@@Range[#,1,-#2]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE7876Zg@99QWVnNwSEoMS89NVpZx1BHV9koVu1/QFFmXkm0sq6dhpuDg7JmrJq@Q3W1sY5xrU61gY4hkDQDk5Y6RkDS0EDHAkiZGOgYGYBoIwMdY4Pa2v8A "Wolfram Language (Mathematica) – Try It Online")
-1 thanks to attinat: `Times --> 1##&`
Explanation: use `Range` to make a list of the values `{n, n-k, n-2k, n-3k, ...}`, stopping before going below 1 (i.e., stopping just right). Then multiply all numbers in this list with `Times` (or `1##&`).
[Answer]
# Java 10, 44 bytes
```
f->b->{int r=1;for(;b>0;b-=f)r*=b;return r;}
```
Takes the factorial as first input, base as second.
[Try it online.](https://tio.run/##jZA9b4MwEIZ3fsWJCYohQKp@uTBWytApY9XBfDgyJQaZI1IU8dupIW4Jnbrd8/pO95wrdmJ@VXyNec26Dt6ZkBcLoEOGIodKvwY9ijrgvcxRNDJ4M8XrTmJ5KBX5X5Mp0hQ4JCP308xPL0IiqCSivFEOzdKQZn7CXXWXZFSV2CsJig4jtbRQ22e1FjJep0YUcNSuzh6VkIePT2Du5A2AZYfOlmxduuDjGiMSrvHhFmPyfItPJFp1xyG5/wk2m@s2HcXXbLCWz5sl54bpTs5ybJRg9U62PZIpylhXzmTU9@cOy2PQ9Bi0@iqspbOe8mxgsgDb@5307BeNPGBtW5//dLsmXdYYxWH8Bg)
This above doesn't work for the largest test case due to the limited integer range (32-bits). To fix this we can use `BigIntegers`, which ~~coincidentally~~ is ~~exactly double the size - **88**~~ 79 bytes:
```
f->b->{var r=f.ONE;for(;b.signum()>0;b=b.subtract(f))r=r.multiply(b);return r;}
```
-9 bytes thanks to *@OlivierGrégoire*.
[Try it online.](https://tio.run/##nZE9a8MwEIb3/Iojk0UckY/SL9ceCi1kaDNkLB0kx3KVyrKRToYQ8ttdxTV1HDqUbnreu1fce7djNZvutp9Nqpi18MKkPowALDKUKex8lTqUigqnU5Slps/d46GtFQw/6KPMVxqzPDPhfx0XapKAgLgR04RPk0PNDJhY0PXrUyRKE0ScWplrVwQkmUU89ug4GpZiIAgxsaGFUygrtQ84iUyGzmgw0bGJRj5a5bjy0bqEdSm3UPjUwQaN1PnbOzBy2gAAZhaDZbgkUY83Q5yHsyFen@MivDvH23A@6F7MwquBsPTC4ls5jvojtCO2DVIjCB@zNJKpla4chieJM5u11A2@2VvMClo6pJXPhEoHQ9dkDExvYTz5cU7G9x4FZdVpa7@dhNZMuWwtLr4i5C@efkLSxTs2Xw)
**Explanation:**
```
f->b->{ // Method with two integer parameters and integer return-type
int r=1; // Result-integer, starting at 1
for(;b>0; // Loop as long as the base is still larger than 0
b-=f) // After every iteration: decrease the base by the factorial
r*=b; // Multiply the result by the base
return r;} // Return the result
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
ɾṘḞΠ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiyb7huZjhuJ7OoCIsIiIsIjMsIDNcbjMsIDdcbjAsIDFcbjYsIDFcbjksIDJcbjEwLCA4XG40MCwgMjBcbjQyMCwgMzAiXQ==)
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), ~~34~~ 33 bytes
```
;=p=xE P;=yP;W<0=x-x y=p*x pO+p!p
```
[Try it online!](https://tio.run/##lVhrc9s2Fv2eX0GzqUWINC17Ou1YNO1JvM5OZhvZG7vNtJISgSAksaFIhQ9brsT96957wReol9MvHgo4uC@c@4D/og80ZpE3T46C0OXPzKdxrPwn8CbT5DqKwkjhi4QHbqyIX8ssB9zSKObNfelMifqYBok3exl3l0SczpYsDOIkSlkSRholy2TqxWYcphHjNs1gx5t/mnoJj@eUca3Yn9GETbXjz1p/MBz0BzGsZ92hvvqh/3kQDNvaIFi9JqR9TLI5519hN@JJGgWKJLzfGa5WQer7WS7MMZjdIUufJwq1HZMvONMkOLEKEXjEtm16iR9dGWJL32acOmC7RkGN6fNgkkyJQftsSLIkBMe9YLLVqiwT4VDu/7i9vrP7QysP1e/UT/kyTmjiMWWOt6A5ZOmYG@GxxhDFBxqBDx2LngsxhX6L6nruH7PFep8OzVKW5Y01Rgp7WCb5mkVpIMIehY9KwB9zRmQud9LJlvUd3gkhZr0JuF46c3i0A1duAu5tGPqcBjuA1W5WsOpXCEZE/Yp4eejWSBanc5RuCFFfXJpQ4FruqKRkizPF7/rcNk@K303Qhhvlggzj33w0r0BQxQOracB4OM69ltw4PJSMBz7mX2UUUHgVgiIkG/wpuV5n0/27Iem/Ofpz2D42TirK08NDvGCUqan3KmojmZvO5pUzo9KZ1yI/MzLK/GRau3JQ23p4SBvXNpFxiow7aAKznMzzNJ5quEqsPFWue7@//3jT@3Ddu7eXWZEw710eJGsceMn9Pj36@8sQ/3aOzr5ACNYDIISCsdk@NnkIAjY14yOOemMPcHmIchwGCsz1JgHKkTzp15hhRc3c4B0ozOCH0HOVzgHeT2m5VSeoXJe10W/B1yB8DBSvskxpNUxrjZoxFy6QMr5SdL@XXgNX3wwpBLRIF0rWSVVs1JyiritxpTxfc0anUukgGdTgvfCjJnyW@nvh7Sbc9R5kL@stvInGJZSiPtBkagJvAiZJPQa/d12SekWDIEwUUAV3ojhPyt88ClUwNXT/oe5a4Y/0RX0gPvVDSd88fNyvrxa/Wh1o9LxDvsv5dvs7vOeLeRggSWnChUFKEkJtDPgE@PbAFTCOR2Ckv6OSnMv3trPeXDRQDeLXtO9BQ9zPe6l6V8TvFSWV5JxHIY0SUlYQbLdrOaAiWCPqvs4g5BXOvxBKFs7ATC6OmGoVjH94Sg4OrpXRgeb4YnCQQo5NpZ6jtoYE5rh4cDdsX5LBybFxKmiF0QBmOTKRQAMOK/kQQ818uEOw2sK2xFarltrCD1K7VA@tWPTAqpkXAJNc5VsaAqF4wMIUl7nbVV4vaTba1tKF/c08Mk46ZLXqrNWsYkDYV7PQiVEBKBRulh4E1brMiM85hd4jV6AXGF@NWnsZX6HkS4XForvCKerePQWsSzM74t9SL@KaOo5VYixxRBZbjrTFpp7vfplHIeMxot791ru6f3/Tu6t78zuoAftas8SS/IJhMq/E9B2p04mblmZVS@LVZVdknb4yyXHOGI7zNM7H@MOF@dg9Z@Vs7Jaz8dgWFpmlKajsYLyDTh886N3BRKHRJJ3hwPF66eonmQJKlDF6CR3VwUZq8TywY5JJd4yB0JjhGHxtpIAltjZWoDib5t8BnXHbyb9BdWyzzdlVHNBM06xQVWXJq7iK2hMvDDRVr6RW4XGUcuQUR6luq4ai6o6Zy6i6uK5u1KYb5y/OEtOLBX8NGJeycaFKifjEixMuXCRLCO0J9qrygbT2ltDUHpikzFIY8hxI1AVlif@kQC9Q2JRG8AtmFj8MJlCTrJogdGg7kkYITNW55KstkgxeoJoj5QGRa089RuXvDWsrDdReqDygZCiUqe@irUKFewC1UsoqDDgxqhCot6qhEfuieJKpquHYb9PxmEcm9f2QaTCAuyEGiWodYEQHJnIDKO/Ak5I4YPhXi@ng6iNkHNdOoAuLHfGSMzG3PnmQ@OogUAlhNjNj34MXYsdQjurJvqw0jGSyZR9zyxqte@yH4OtPp2c/nf38y@nZz22xGtHADWcYNvn8tWpQ@wJDRhuhrSGtNy2EVImeh7ewypG7GxhwWZqZSzLHUTi7AgZchS4MmsXbiXRLc@XrNFmBe5PgzCYb@VYYSeWlq3ypeFyKv/L2SGxXfajp3A5H1f@KQ0VBNPnCW6/iEvagUiDeWs0HUAP5a4VEj2VDymSS0f9Cbl1U41sj2KVlceKGaWI@RtC4QWCe58SgjZjdNAXVWgtp6mAgnoflvz@Aapc7FBSIjlGmP2BJdyt4hF3y1YgY1fQk26QDWbGc1BeHLbfwshGGow0kvhC2IdsbSOzQ25DHG0jxLtiC/HFTZrjdzs8bSDF/b0GeV8iKNOURnA2qI/KZi91nJrvOXO4@g8V/65nD6oxGywxv/MfmsjjWbeTg6sVjtOts5qYlHct3jW0BsyVYo8rg43a1ApXSQ7@Z0tQsXuqOXel3GsI/VcKX2EetRvpaZC3xtpL5fS4C2r99QbcGi236/m/pkAhabbfhNJ5rBjYC6WdZy6p0RCGrlao2o3ZXKHCFivLQC6pc293UXIHLrMcB/5LqMF/WFcEhOtNrk3QXu3LdOv7Xkmtf8xEPOIhOWUVgdnnon0JPfH5@Pnt1@urZsuf24lq5teynW@vTecdeHC2UJ3veXijzG31@MP8/)
-1 byte thanks to Aiden Chow
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 bytes
```
TõUV f ×
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=VPVVViBmINc&input=MCwx)
-1 thanks to EoI pointing out how dumb uncaffeinated Shaggy can be!
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 41 bytes
```
r;f(n,k){for(r=1;n>0;n-=k)r*=n;return r;}
```
[Try it online!](https://tio.run/##ZcnBCkBAEADQM1@xKTWjVUsumtaXuGhZSYamdZJvX5y963Pl7FyMQh5Yr3j5XUBsRdwZ4tKuKIVlkimcwkrojtuwMKC60uSQhYOHLB97zrSHxmhVG0T6V/vOF3d8AA "C (gcc) – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), ~~7~~ 6 bytes
```
╙╒x%ε*
```
[Try it online!](https://tio.run/##y00syUjPz0n7///R1JmPpk6qUD23Vev/f2MFYy4LIDZUMABiMy4jBUsg39CAy8hAwcSAyxhIGhn8BwA "MathGolf – Try It Online")
Found a clever way to handle 0! without changing the other test cases. Takes input as `k n` (reverse order), which helps with implicit popping.
## Explanation
```
╙ maximum of two elements (pops largest of k and n,
which is n for every valid case except 0!, where 1 is pushed)
╒ range(1,n+1)
x reverse int/array/string
% slice every k:th element
ε* reduce list with multiplication
```
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), ~~21~~ 19 bytes
```
${x<y∨x*$[x-y,y]}
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@1@lusKm8lHHigotlegK3Uqdytja/36pqSnF0SoFBcnpsVwBRZl5JSGpxSXOicWpxdFqaToK0VwKQGBvrxBtrKNgEKsD5oLYxlA2VMocJmWgo2AIY5shsS11FIxgbEOgIgsYxwTIMYKbbGIE5BobxHLFxv4HAA "Attache – Try It Online") Pretty direct recursive implementation. (Note: `true` is essentially `1`, as it can be used in arithmetic operations as `1`.) This is one of the few programs I've written for this site where using a unicode operator saves bytes (1, to be precise).
## Alternatives
**20 bytes:** `${x<y or x*$[x-y,y]}`
**21 bytes:** `Prod@${{_%y=x%y}\1:x}`
**27 bytes:** `${x*[`1,$][x>y][x-y,y]∨1}`
**27 bytes:** `${If[x>y,x*$[x-y,y],_or 1]}`
**27 bytes:** `${x*[`1,$][x>y][x-y,y]or 1}`
**29 bytes:** `${If[x>y,x*$[x-y,y],_+not _]}`
[Answer]
# [Scala](http://www.scala-lang.org/), 53 bytes
Takes two arguments, the first being the number and the second being the `!` count.
Somehow breaks on the big test case. This step range costs many bytes in the end because of this `-1*` so improvements ought to be possible by refactoring.
I have, as always, a doubt about how we count bytes for function declarations, because everyone doesn't do the same way everywhere down there, so well... It's **17 bytes less**, so **36 bytes**, if we count out func variables' (`a` and `b`) declaration and func brackets.
```
(a:Int,b:Int)=>{var s=1
for(i<-a to b by -1*b)s*=i
s}
```
[Try it online!](https://tio.run/##jZBPb4MgHIbvfIqfnrSlKSD1TzOW7LjDPgRUzFgMGrHNlqafnblsdRo99D1wep73BdxJ1tI36kOfeniTxoL@7LUtHby07RWhUldQCR/J46vtsfo5Y/F8vcgOnKCoarrIPO0k9A0oUF@woxsVu40wyN082u/bzti@tlGYgIBwW0UJJvE2BGlLcO/NuS5BaTjbYcdYXYYx@jeCIBilZCklAzwdCH4zKtmDO@SuEEyXCp2i6R1N19CMkSlcjHcpMFvSBT9MaUqC@QMowfnSmk/wUZrmr4ATzFb@OifzCrbasWxjBCcrdZymRUZJylnODhkb2ucZttDNe/8N "Scala – Try It Online") I commented out the broken test cases, because, well, they do break.
[Answer]
# [Rust](https://www.rust-lang.org/), ~~92~~ ~~73~~ 61 bytes
```
fn f(n:i128,k:i128)->i128{if n<=0{return 1}return n*f(n-k,k)}
```
I am just starting to learn rust, so I'm sure this can be shorter. Will update as I learn. The return value should be `i128` in order to compute the last test.
Edit: Recursion is shorter.
[Try it online!](https://tio.run/##dYxLDgIhEET3fQqcFZiepAFjxu9dXEhC0I5hmBXh7IgTd@KqKu@lKi5zqtWxcJKPXpsJwxpqvH4ieyf4fKEc72mJLHT5Ft62wRgwqAIAbf@8eZYKMryi5/TgjRxyGbD9WrRKnX45oe7y/R9@QNPlmnDqih2hob4xhHZVpdY3 "Rust – Try It Online")
You can add your own test, or edit one of the already existing ones.
[Answer]
## **[q](https://code.kx.com/v2/ref/), ~~59 57 55~~ 53 bytes**
```
{prd 2+(&)1_i=last i:("J"$x(&)not[n])#(!)sum n:"!"=x}
```
explanation:
```
q)x:"12!!" / let our input be 12!!, assign to x
q)sum n:"!"=x / count "!"s
2i
q)(!)sum n:"!"=x / (!)m -> [0,m)
0 1
q)("J"$x(&)not[n]) / isolate the number in input
12
q)("J"$x(&)not[n])#(!)sum n:"!"=x / x#y means take x items from list y, if x>y, circle around
0 1 0 1 0 1 0 1 0 1 0 1
q)i:("J"$x(&)not[n])#(!)sum n:"!"=x / assign to i
q)i
0 1 0 1 0 1 0 1 0 1 0 1
q)(last i)=i:("J"$x(&)not[n])#(!)sum n:"!"=x / take last elem of i and see which are equal in i
010101010101b
q)1_(last i)=i:("J"$x(&)not[n])#(!)sum n:"!"=x / drop first elem
10101010101b
q)(&)1_(last i)=i:("J"$x(&)not[n])#(!)sum n:"!"=x / indices of 1b (boolean TRUE)
0 2 4 6 8 10
q)2+(&)1_(last i)=i:("J"$x(&)not[n])#(!)sum n:"!"=x / add 2 across array
2 4 6 8 10 12
q)prd 2+(&)1_(last i)=i:("J"$x(&)not[n])#(!)sum n:"!"=x / product across array
46080
```
here also is a version in k (same logic), ~~42~~41 bytes
```
{*/2+&1_i=last i:("J"$x@&~:n)#!+/n:"!"=x}
```
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, ~~30~~ ~~29~~ 24 bytes
* Saved 1 byte thanks to @Bubbler
* Saved 5 bytes thanks to @chunes!
```
[ 1 rot neg <range> Π ]
```
[Try it online!](https://tio.run/##LY47DsIwEER7TjEniBKQED/RIhoaRBWlsJxNiDB2WG8KFHIXTsSVjAkpdt7sSKvZSmlxHC7n4@mwwY3YkkHLJPJsubECT4@OrCYP47QyHncl11ESVramf5B0ttGuJGxnPXosMMcQmU5cIhu5nvYsxSqaAfkLBr/xpJ0to6ka9hLyeMBOYKnGbuzZ4/NGEeILBkXsbJGELw "Factor – Try It Online")
Takes `k` (which -th factorial) and then `n`. First we push an `n` onto the stack, then `rot` makes the stack look like `n 1 k`. `neg` negates `k`, which will act as the step for a range from `n` to 1 (made using `<range>`). Then `Π` finds the product of that range, and that's it.
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 3.5 bytes (7 nibbles)
```
`*`%@\,
```
```
, # get the range from 1..first input,
\ # reverse it,
% # and take each element in steps of
@ # the second input,
`* # and finally get the product
```
[![enter image description here](https://i.stack.imgur.com/5oXRZ.png)](https://i.stack.imgur.com/5oXRZ.png)
---
Or **7.5 bytes (15 nibbles)** with input as string of a base-ten integer followed by exclamation marks:
```
`*`%,|$\$D\,`r$
```
[![enter image description here](https://i.stack.imgur.com/Igyzn.png)](https://i.stack.imgur.com/Igyzn.png)
[Answer]
# [Physica](https://github.com/Mr-Xcoder/Physica), 22 bytes
```
f=>n;k:n<1||n*f[n-k;k]
```
[Try it online!](https://tio.run/##K8ioLM5MTvz/P83WLs862yrPxrCmJk8rLTpPN9s6O/a/W36RQklqcYmCZ55CdbWxtXGtNZA0B5IG1oZA0gxMWlobAUlDA2sLIGViYG1kAKKNDKyNDWprrbg4A4oy80oc0qK1QEbF/gcA "Physica – Try It Online")
---
**26 bytes**
Re-learning how to use my own "language" \o/... If I knew how to write a parser 2 years ago, this would have been 20 bytes :(
```
->n;k:GenMul##[n…1]{%%k}
```
or
```
->n;k:GenMul##Range[n;1;k]
```
[Try it online!](https://tio.run/##K8ioLM5MTvyfpmCrEPNf1y7POtvKPTXPtzRHWTk671HDMsPYalXV7Nr/bvlFCiWpxSUKnnkK1dXG1sa11kDSHEgaWBsCSTMwaWltBCQNDawtgJSJgbWRAYg2MrA2NqitteLiDCjKzCtxSIvWAhkV@x8A "Physica – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 66 bytes
```
^0
1
\d+
*!,
+`(!+)(!+),\1$
$1$2,$2,$1
!+$
1
+`(!+),(\d+)
$.($2*$1
```
[Try it online!](https://tio.run/##TUoxCoAwENvzi8AJ1RbpqQi@wE@IKOjg4iD@v7aKYkhCSHKs57bPGjLTT2H0UAyLRUEHOxnaPMkNKhCVyiUqaCX@nt2Z@M8hpZGqEA2hRk3ytgR4oiW6mNTzLZsv/nEB "Retina – Try It Online") Link includes faster test cases. Mauls numbers without exclamation marks. Explanation:
```
^0
1
```
Fix up `0!`.
```
\d+
*!,
```
Convert `n` to unary and add a separator.
```
+`(!+)(!+),\1$
$1$2,$2,$1
```
Repeatedly subtract `k` from `n` while `n>k`, and collect the results.
```
!+$
1
```
Replace `k` with `1` (in decimal).
```
+`(!+),(\d+)
$.($2*$1
```
Multiply by each intermediate value in turn, converting to decimal.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 bytes
```
1õUV f ×
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=MfVVViBmINc&input=MTAKOA)
] |
[Question]
[
This challenge is about implementing [Shm-reduplication](https://en.wikipedia.org/wiki/Shm-reduplication), originating in Yiddish, where one takes a word, duplicates it, and replaces the first syllable in the second word with "Shm" in order to indicate that one does not care. Some examples include:
* "Isn't the baby cute?", "Eh, baby shmaby"
* "Come buy from my store, we have a sale!", "Pff, sale shmale"
* "I got this smartphone yesterday, isn't it cool?", "Meh, smartphone shmartphone"
# Rules
In the real world there are a bunch of [special cases](https://en.wikipedia.org/wiki/Shm-reduplication#Phonological_properties), but for this challenge we will use rules that describe a simplified version of the full linguistic phenomenon that is more suitable for programming:
1. Consonants up to first vowel are replaced by "shm".
2. Prepend shm to words beginning with vowels.
3. If a word contains no vowels it is returned unchanged. No vowel, no shm.
4. The vowels are: a, e, i, o, u.
5. The input will be restricted to lowercase letters.
6. The output should be a lowercase string containing the reduplicated version of the input. **If the input is "string" the output should be "shming"**.
This is code golf, shortest code wins!
# Example solution (ungolfed python)
This is an example of code that would solve the challenge:
```
def function_shmunction(string):
vowels = "aeiou"
for letter in string:
if letter in vowels:
index = string.index(letter)
shming = "shm" + string[index:]
return shming
return string
```
# Test cases
* function -> shmunction
* stellar -> shmellar
* atypical -> shmatypical
* wwwhhhat -> shmat
* aaaaaaaaaa -> shmaaaaaaaaaa
* lrr -> lrr
* airplane -> shmairplane
* stout -> shmout
* why -> why
An answer has been accepted since there haven't been any new responses in a while, but feel free to add more!
[Answer]
# [sed](https://www.gnu.org/software/sed/), 29 bytes
```
s/[^aeiou]*\([aeiou]\)/shm\1/
```
[Try it online!](https://tio.run/##PYvRCsMgDEXf8yXbYMi@RzsIzjaBLIpGpF/fCoXepwPn3JZ@7037cTTnv5g49@UVHv6i8HSN/uHjprbKusHaNRpnhWZJBCug7YUjCowxiAgN8B5InQHXIqhpPnI3GLSf "sed – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 12 bytes
```
œlØḄṭ⁸¹?“shm
```
[Try it online!](https://tio.run/##y0rNyan8///o5JzDMx7uaHm4c@2jxh2Hdto/aphTnJH7/1HD3Ic7px1awvVwx6bD7Y@a1nj//59Wmpdckpmfp1BcAtScWKSQWFJZkJmcmKNQXl6ekZGRWKKQCAcKOUVABZlFBTmJealAHfmlJQA "Jelly – Try It Online")
*-4 thanks to ovs remembering there's a strip builtin*
```
œlØḄ Strip all leading consonants.
ṭ “shm Prepend "shm"
¹? if there's anything left, otherwise
⁸ give the original word.
```
[Answer]
# [Haskell](https://www.haskell.org/), 50 bytes
```
snd.break(`elem`"aeiou")>>=(?)
""?s=s
r?_="shm"++r
```
[Try it online!](https://tio.run/##PY7BDoIwDIbvPkXTcICgPoEbL6Anj2K04JDFMZZ1hPjyTqbG/9D/a/unaU/8UMbETtSR7W3beEWP/KqMGq5ISo8TFlKKvCpWiBULXvnqIpD7AcvSx4G0BQEDuQO4KRyD31vIIK8ZNhIYyhIQhFzKQh1wAbtMwgnn0d9wDdhQ80zOZNTHg9f2nqibbBv0aL/T5UXyCSk8nW7JJJ7nuV9E4bP4K3UmfNPaO0P2d3qcAp7jq@0M3TluWufe "Haskell – Try It Online")
*Thanks to Roman Czyborra for -2 bytes*
[Answer]
# [sed](https://www.gnu.org/software/sed/), 25 bytes
```
/[aeiou]/s/[^aeiou]*/shm/
```
[Try it online!](https://tio.run/##PYtBCoAwDMDufYogfZAoFJ22UDtZO4avn4JgTjkknrbxsNo7TpQk1xkdp@XTAZ1P7N2jiB2wV1tDsoFHUqUCFPclKym01piZAugHtLyBlEvJ0nvkGtD4fgA "sed – Try It Online")
`/[aeiou]/` is a conditional that only runs the substitution `s/[^aeiou]*/shm/` if there is a vowel in the line. This prevents needing to capture the first vowel and then using a backreference as in the more obvious `s/[^aeiou]*\([aeiou]\)/shm\1/`.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ÄFï¥░$º{═┘ç
```
[Run and debug it](https://staxlang.xyz/#p=8e468b9db024a77bcdd987&i=function%0Astellar%0Aatypical%0Awwwhhhat%0Aaaaaaaaaaa%0Alrr%0Aairplane%0Astout%0Awhy%0A&a=1&m=2)
1. Left-trim consonants.
2. If non-empty, prepend "shm".
3. Else restore original input.
[Answer]
# [Zsh](https://www.zsh.org/), 36 bytes
```
<<<${(S)1/#(#b)*([aeiou])/shm$match}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwU3f4tSS_IIShdSKktS8lNSU9Jz8JK60_CIFQwWN5PyU1PT8nDSF4pLUnJzEIoXEksqCzOTEHIVEMFDIKSrSLCjKzCtJU1AxjFFQU1taWpKma3FTxcbGRqVaI1jTUF9ZQzlJU0sjOjE1M780VlO_OCNXJTexJDmjFqJ2AZSC0gA)
* `<<<`: print
* `${1}`: the input...
+ `//`: replace the first match
- `#`: matching only at the beginning of the string
- `(#b)`: activate backreferences, so the `()` group gets stored in the `$match` variable
- `(S)`: use the shortest possible match, rather than the longest
- `*`: anything
- `()`: store this match in the variable:
* `[aeiou]`: followed by a vowel
+ with `shm$match`: the string `shm`, plus the matched vowel
`$match` is actually an array which contains all the backreference groups, but since there's only one group, we don't need to access any specific element with `[1]`
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 62 bytes
```
lambda s:(q:=s.lstrip('bcdfghjklmnpqrstvwxyz'))and'shm'+q or s
```
[Try it online!](https://tio.run/##PVC7csQgEOv5iu3Ak8s1aTKeId2lTZMyDbZxIIcBL@v4nJ938FPNSlqNliFOZIJ/eY04t/JrdqqrGgWpFH0p09UlQhsFr@qm/TY/d9f52GOi3/Ex/fGiUL7hyXT8qYeAkObRWKfhEwddMgDCaRkA1scLhIFALnQgUVxTdJYEh@c34MUaQp1ghYRW5NjmRrSeRN5JmQsuW1WWy1Y/ah0Jbh/vN8SA260KtbrP7eBrssEv/fmBu2KJtHMKd3flTNEUba3cbh6SjeNojFF0@kydOLwTzOHamgdTFqNTXh@hXebjyxdsZmb/ "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~28~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žNSÛ©ai®…shmì
```
[Try it online](https://tio.run/##ASYA2f9vc2FiaWX//8W@TlPDm8KpYWnCruKApnNobcOs//9hdHlwaWNhbA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/6P7/IIPzz60MjHz0LpHDcuKM3IPr/lfq/M/Wqk8vyhFSUdBKSkxqRJEFyfmpILpkqLMvHQQK600L7kkMz8PIpqak5NYBGImllQWZCYn5oDY5eXlGUCQWAKWgAMQL6cEojqzqCAnMQ9qdH5piVIsAA).
**Explanation:**
```
žNSÛ # Trim all leading consonants of the (implicit) input-string
© # Store this new string in variable `®` (without popping)
ai # Pop, and if any letters are left (thus the input-string contains
# a vowel):
® # Push string `®` again
…shmì # Prepend "shm"
# (implicitly print it as result)
# (implicit else)
# (implicitly output the implicit input-string)
```
[Answer]
# [Powershell](https://github.com/PowerShell/PowerShell), 36 bytes
```
$args-replace('^.*?([aeiou])','shm$1')
```
### Explanation
Simple replace with a named group reference.
[+4](https://tio.run/#%23K8gvTy0qzkjNyfn/XyWxKL042iBWtyi1ICcxOVVDXSNOT8s@OjE1M780VlNdR704I1fFUF3z////SiAt@UoA)
Thanks [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing)
[-5](https://tio.run/#%23K8gvTy0qzkjNyfn/XyWxKL1Ytyi1ICcxOVVdI05Pyz46MTUzvzRWU11HvTgjV8VQ/f///0og1flKAA)
Thanks [mazy](https://codegolf.stackexchange.com/users/8745/mazzy)
[Answer]
# [Python](https://www.python.org), 53 bytes
```
lambda s:re.sub("^.*?([aeiou])","shm\\1",s)
import re
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYxNCgIhGED3neLDlcYktAhCiA6SBU6jjeAfnwp2ljZC1J26TcT0Nm_13uOd7mWOoT_NQb5qMZv9Z-eUHycFWaDmuY6UXPj6SE9K21jPjAwkz17KLRkyW1mfIhZA_Y-FiQgNbCDXOOlbdAZy0c4pBPUDHCLhOTlbKBMJbSi0DYY2xpZD74u_)
Another regex answer.
---
Alternative:
# [Python](https://www.python.org), 53 bytes
```
lambda s:re.sub(".*?(?=[aeiou])","shm",s,1)
import re
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYxNCgIhGED3neLDlYYJLYIQhjlItXAabQT_-FSws7QRou7UbSKmt3mr9x7vdC9LDP1phvOrFrM7fg5O-WlWkCVqketEidiOdBxOSttYL4xwkhdPeOZ7trE-RSyA-h9LExEa2ECucda36Azkop1TCOoHOEQicnK2UCYT2lBo44Y2xtZD76u_)
[Answer]
# [Haskell](https://www.haskell.org/), 48 bytes
```
g.break(`elem`"aeiou")
g(s,"")=s
g(_,r)="shm"++r
```
[Try it online!](https://tio.run/##PY7BDoIwDIbvPkXTeICAPoHjCfTkUY0UHLA4xrKOEF/euaHxP/T/2v5pOhA/pdahE9fQ7xsn6ZnVUsuxRpJqmjHf9BmXiLngSPfS5QJ5GLEoXBhJGRAwkj2Bnf3Zu6OBLWRXhl0FDEUBCKKKJVIHnMNhW8EFl8k9sARsqHklZ9Jyde@U6RN1s2m9msx3Gh8kl5D8y6qWdOJlWYYo8uvir9Rp/00rZzWZ3@lp9ngL77bT1HPYtdZ@AA "Haskell – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
r"^.*?%v"ÈÌi`¢m
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciJeLio/JXYiyMxpYKJt&input=WwoiZnVuY3Rpb24iCiJzdGVsbGFyIgoiYXR5cGljYWwiCiJ3d3doaGhhdCIKImFhYWFhYWFhYWEiCiJscnIiCiJhZXJvcGxhbmUiCiJzdG91dCIKIndoeSIKXQotbVI) (Includes all test cases)
```
r"^.*?%v"ÈÌi`¢m :Implicit input of string
r :Replace
"^.*?%v" : RegEx /^.*?[aeiou]/gi
È : Pass each match through a function
Ì : Last character
i : Prepend
`¢m : Compressed string "shm"
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 19 bytes
Just a regex replacement, there might be some language feature which allows for a shorter solution.
```
^.*?(?=[aeiou])
shm
```
[Try it online!](https://tio.run/##PcFRCoAgDADQ/53E@gg6QHiQKBpibDA1dCKdfv31Xo3KGVdL7gI7l9k7v@0YufRjgkbJ7O45KJcMTaMIVkB9Hw4oMMYgIlTAH0itHw "Retina – Try It Online")
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 49 bytes
```
I =INPUT
I BREAK('aeiou') ='shm'
OUTPUT =I
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/n9NTwdbTLyA0hAvIcgpydfTWUE9MzcwvVddUsFUvzshV5@L0Dw0BKgCq43L1c/n/P7EoHQA "SNOBOL4 (CSNOBOL4) – Try It Online")
`BREAK` "matches zero or more characters provided they are not in the set of characters in the argument string. That is, it matches up to, but not including, a character from the argument string."
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 81 bytes
```
i;f(char*s){for(i=0;*s-"aeiou"[++i%6];i%6||s++);printf("shm%s"+3*!*s,s-i*!*s/6);}
```
[Try it online!](https://tio.run/##PU/bioMwEH1uviI7ICRGaWGhL2n3R4oPIehmIFXJRKRr/XY3sdudh5kz93Ns/W3ttqHuhHUmlCSXbggCryddUg2mxWGCm1JYnBud3PNJSkk9BuxjJ4DcvSBQn@VHSRXVmOPxLPW63Q32Qi4sX@VltLeGX/nCoJt6G3HooWJAsfXehAxNfIxojc94nmfnnIl7/d9y5sNrGMPoTd@@bgzTPjm7B7BVs0Sfi8SOY3p40ilcOOFPO3QiWsmP72SXK1M/6UnEDm9JBfH6i0PFE2dspGaHvPgHxymSAEhwZev2Cw "C (gcc) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes
```
k⁰øl:[«88«p|_
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLGmyIsImvigbDDuGw6W8KrODjCq3B8XyIsIl07WsabYCA9PiBgajvigYsiLCJbXCJ3b3JkXCIsIFwiYmFieVwiLCBcInNhbGVcIiwgXCJzdHJpbmdcIiwgXCJmdW5jdGlvblwiLCBcInN0ZWxsYXJcIiwgXCJhdHlwaWNhbFwiLCBcInd3d2hoaGhhdFwiLCBcImFhYWFhYWFhYWFcIiwgXCJsdHJcIiwgXCJhaXJwbGFuZVwiLCBcInN0b3V0XCJdIl0=)
Port of Jelly.
## How?
```
k⁰øl:[«88«p|_
k⁰øl # Strip leading consonants
:[ # If there's anything left:
«88«p # Prepend "shm"
|_ # Else, pop, returning the implicit input
```
[Answer]
# JavaScript, 36 bytes
```
s=>s.replace(/.*?([aeiou])/,"shm$1")
```
[Try it online!](https://tio.run/##PY1RDsIgEETvQvwAozQeoHoQbdINboVmyxKgkp4eaT@cr5nJm8wMX0gmupCvnt9Yp76m/p50xEBgUHb6/JBPQMfroLqLSHY53YSqhn1iQk38kU8xrd5kx140ICMRxOYgb8EZoGZLKdZayHv7VwsUDxAjtzePx5zXHSt2E4NeIMhJ6ZmdH19@VPUH) (includes all test cases)
[Answer]
# Excel, 149 bytes
```
=IFERROR(REPLACE(A1,1,FIND("$",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"a","$"),"e","$"),"i","$"),"o","$"),"u","$"))-1,"shm"),A1)
```
102 bytes just to find the vowels. If anybody knows a better way to do this. please share.
From inside out:
* SUBSTITUTE vowels with `$`
* Find the index of the first `$`
* Replace chars before this index with `shm`
* If no vowels, return input.
[Answer]
# [Perl 5](https://www.perl.org/) + `-p`, 20 bytes
Uses the `;` separator (as `;` is implicitly added via `-p`).
```
s;.*?(?=[aeiou]);shm
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiczsuKj8oPz1bYWVpb3VdKTtzaG0iLCJhcmdzIjoiLXAiLCJpbnB1dCI6ImZ1bmN0aW9uXG5zdGVsbGFyXG5hdHlwaWNhbFxud3d3aGhoYXRcbmFhYWFhYWFhYWFcbmxyclxuYWlycGxhbmVcbnN0b3V0In0=)
---
# [Perl 5](https://www.perl.org/) + `-lF/^[^aeiou]+/ -M5.10.0`, 17 bytes
Slightly more cheaty with the regex in the flags, but saves a few bytes
```
say@F?(shm,@F):$_
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoic2F5QEY/KHNobSxARik6JF8iLCJhcmdzIjoiLWxGL15bXmFlaW91XSsvXG4tTTUuMTAuMCIsImlucHV0IjoiZnVuY3Rpb25cbnN0ZWxsYXJcbmF0eXBpY2FsXG53d3doaGhhdFxuYWFhYWFhYWFhYVxubHJyXG5haXJwbGFuZVxuc3RvdXQifQ==)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~125~~ 113 bytes
*-8 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
```
#define T&&*s-
main(s,v)char**v,*s;{for(s=*++v;*s T'a'T'e'T'i'T'o'T'u'||!(*v=memcpy(s-3,"smh",3));++s);puts(*v);}
```
[Try it online!](https://tio.run/##DcpBDoMgEADAe19hNRFY4OSR@As@QFasJKLEVRJT@3bKYW6D@oNYSjf5OWy@sX0PpF/RhY2TygIXdwBkBWS@835wGkHKbIAayxyzzFeh2quLPc@bQx6jj5huTnpQLcWlVYMQRkoSJl0n1SHMr5QyufNOAd36Bw "C (gcc) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
≔⌕Eθ№aeiouι¹η¿⊕η«shm✂θη»θ
```
[Try it online!](https://tio.run/##LYy9CgIxEIRr8xQhVRZiYZ1KBMFCEHyCkNszC7mNlx8b8dljDi2m@JhvxgeXfXKx92Mp9GB9Jp701T31auQpNa5aOaTUlJEEYORhJIAVNEt9YZ9xQa446QAg32J3y7RNSljUkP54j@RxOxySFR@BsaD8VSvY3ufGvlLivn/FLw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⌕Eθ№aeiouι¹η
```
Count the number of vowels in each character and find the first `1` i.e. the index of the first vowel in the input.
```
¿⊕η
```
If there was in fact a vowel, then...
```
«shm✂θη»
```
... output the literal string `shm` followed by the input sliced starting at that index.
```
θ
```
Otherwise just output the input string.
[Answer]
# Java 8, 40 bytes
```
s->s.replaceAll("^.*?([aeiou])","shm$1")
```
Port of the [JavaScript](https://codegolf.stackexchange.com/a/247758/52210) and [Retina](https://codegolf.stackexchange.com/a/247754/52210) answers.
[Try it online.](https://tio.run/##PVDNTsMwDL7vKayIQ8KySBM3JkA8ALtwnIbkZdma4aVV4raq0J69uKPChyh2vj/ngh2uLsfv0ROWAh8Y088CICYO@YQ@wHZqAT45x3QGr@dLMRuZ3xZyFEaOHraQ4GUsq9ficmhIuO9EWn25xze9wxDrdm@UVaW6PqyVGTcTtWkPJNRZoavjEa6SYDbZ7dH8uZ/qrDvMwKEwPIPq63y0BzwMtiAFW@5we2qT51gn6QMRZos8NNEj2b7vKylki/9liQURs0RNk0TdsnKlochaYhpzN5bFB1G7Onl1jbgwJT2lWCpQ054BWa@fVtPIUUhnrrQxy@T8HWXmX7qNvw)
Or a minor alternative:
```
s->s.replaceAll("^.*?(?=[aeiou])","shm")
```
[Try it online.](https://tio.run/##PVDNbsIwDL7zFFZOyQiRpt2GGNoDjMuOiEkmBBpm0ipxW1UTz965rJoPUex8f84VO1xdT9@jJywFPjCmnwVATBzyGX2A3dQCfHKO6QJez5di1jK/L@QojBw97CDBZiyrt@JyaEi470Rafbmnrd5u9hhi3R6MsqpUN2XG9URt2iMJdVbo6niCmySYTfYHNH/u5zrrDjNwKAyvoPo6n@wRj4MtSMGWB9ye2@Q51kn6QITZIg9N9Ei27/tKCtnif1liQcQsUdMkUbesXGkospaQxjyMZfFB1G5OXl0jLkxJTymWCtS0Z0DWzy@raeQopAtX2phlcv6BMvMv3cdf)
**Explanation:**
```
s-> // Method with String as both parameter and return-type:
s.replaceAll( // Modify and return the String: Regex-replace all
"...", // these matches
"...") // with these replacements
```
*Regex-explanation 1:*
```
^.*?([aeiou]) # Match:
^ # At the start of the string
.* # Match zero or more characters
? # Which are optional, to give other matches precedence
[aeiou] # Followed by a vowel
( ) # captured in capture group 1
shm$1 # Replacement:
shm # Literal "shm"
$1 # And the vowel of capture group 1
```
*Regex-explanation 2:*
```
^.*?([aeiou]) # Match:
^ # At the start of the string
.* # Match zero or more characters
? # Which are optional, to give other matches precedence
(?= ) # Followed by a positive (non-matching) look-ahead to:
[aeiou] # A vowel
shm # Replacement:
shm # Literal "shm"
```
Minor note: the `replaceAll` with `^` is basically the same as a `replaceFirst` without the `^`, but 1 byte shorter: [try it online](https://tio.run/##PVC9bsMgEN7zFCfUARqCFHVrlHbr1iwdowwXjGNSgi0427KqPLt7pFZvQNzx/R1XHHBzrb5nGzBn@EQff1YAPpJLNVoHh9ICfFHy8QJWLpesdjy/r/jIhOQtHCDCfs6bt2yS6wJzP3zKJIV5fpdHdL7tT0pokZvb01aoeVe4XX8OzF0khtZXcOMIi8vxhOrPvm6THDABuUzwCmJsU6XPeJ50xuB0fsB13UdLvo3cuxAwaaSp8xaDHsex4ULS@F86ECN84qyxSLQ9CZO74DmzFko9jHnzidVuhl9Nxy4Uoiwp1gJEWdQhye3LpoxMcPFCjVRqHY19oNTyTff5Fw).
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 15 bytes
```
a~XVaH$(:"shm"a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhbrE-siwhI9VDSslIozcpUSIaJQyTXRSomZRQU5iXmpSrFQMQA)
### Explanation
```
a~XVaH$(:"shm"a
a Command-line argument
~ Find first match of
XV regex `[aeiou]`
$( Index of that match
aH Prefix of cmdline arg containing that many characters
: Set to
"shm" that string
If a vowel was not found, $( is nil, which means no assignment is done
and a's value remains unchanged
a Autoprint the (possibly changed) value of a
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 31 bytes
```
{⍵≢⍛≡n←⌊/⍵⍳'aeoiu':⍵⋄'shm',n↓⍵}
```
[Try it online!](https://tio.run/##XY9NCsIwEEb3PUV2UbDo2hu48gyhTU0gpqVNqUXciVC1IogrV3oF8UK5SEzS/2YRmDfvG2ZQxFw/RyzcuHgnMPexr@TtuVrL032hAv3vZfmTxUeWL1m8uQbyep4bVn4hwiFN4dJUlyNMyBbOtPHQ9UGpSQBgkHJP0JBDAKZA54GRGuYYIxGYMRRroWdUyPaRyCPqITaY0EKrZFlGCEFipNT59sFes4NWYrFdAHRLGFLlaRwxxPFweAPrE8JUwH5aKwZV25F8NNsQ5w8 "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org), ~~58~~ 57 bytes
```
f s|g s>""="shm"++g s|1>0=s
g=dropWhile(`notElem`"aeiou")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PVCxbgIxDN35CstiAF2R2g2kJlu3MjF0aJEwkLuLmkuixNEJiT_pwoLY-zf9GxKO4sF-z7aen_xzaSl-K2NOp3Piejb_W9QQjw1EiSgwth1WVWbHF_ks4qgR--D8R6uNmmys4zejug2S0i7h9C7w25G2IKAjvwSfeMXh3cIYJl8RZhIiVBUgCJlTRvnaFF7HEj6xd2GPT4Bb2h5KjWTUrXLQtimoTnbH2tmhm11TKJD44PWOTMF937c5iG-DRxRmeNjWwRuyd2mXGNeD8_8XXAE)
*-1 byte thanks to Wheat Wizard ♦*
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 531 bytes
```
->+[->[>],[+[-<+]->+[>]<[>+>+<<-]>>[<<+>>-]-[>++<-----]>-----<<[->>-<<]+>>[<<->>[-]]<<[+[-<+]->-]+[-<+]->[[>]<[>+>+<<-]>>[<<+>>-]-[>++<-----]>-<<[->>-<<]+>>[<<->>[-]]<<[+[-<+]->-]+[-<+]->[[>]<[>+>+<<-]>>[<<+>>-]-[>++<-----]>+++<<[->>-<<]+>>[<<->>[-]]<<[+[-<+]->-]+[-<+]->[[>]<[>+>+<<-]>>[<<+>>-]-[>--<-------]>+<<[->>-<<]+>>[<<->>[-]]<<[+[-<+]->-]+[-<+]->[[>]<[>+>+<<-]>>[<<+>>-]----[>+++++<--]>-<<[->>-<<]+>>[<<->>[-]]<<[+[-<+]->-]+[-<+]->[>]]]]]]+[-<+]->]>[>]<-[++[-<+]->>[.>]>-<]>+[[--------->++<]>+.-----------.+++++.<<<.,[.,]]
```
[Try it online!](https://tio.run/##rZJBCkIxDEQPlE5OEOYiYRZ@QRDBheD5a1oIbhX@bJIM7WNSerwu9@ftfX3MCVqCSY2sJkzLoCJptAiIzAgjIZRngSVxl4i6yyqyfayGhFR2s6Du8ifq6USr9hxmrQs09RRmaUW1nfbf5amtnrWcQFobTOdiVthMtNbLlOP4yncCjwgf6UOa8@j/8QE "brainfuck – Try It Online")
This implementation is as close to a nested if/else statement as bf allows. Simply checks each letter to see if it's a vowel. If it finds one, it prints "shm", then the vowel, then the rest of the input. If it doesn't, it simply prints out the input from its buffer.
---
# [brainfuck](https://github.com/TryItOnline/brainfuck), 423 bytes
```
+[--------->++<]>+.-----------.+++++.<->>+[>,[>+>+<<-]>>[<<+>>-]-[>++<-----]>-----<<[->>-<<]+>>[<<->>[-]]<<[<<->>-]<<[>[>+>+<<-]>>[<<+>>-]-[>++<-----]>-<<[->>-<<]+>>[<<->>[-]]<<[<<->>-]<<[>[>+>+<<-]>>[<<+>>-]-[>++<-----]>+++<<[->>-<<]+>>[<<->>[-]]<<[<<->>-]<<[>[>+>+<<-]>>[<<+>>-]-[>--<-------]>+<<[->>-<<]+>>[<<->>[-]]<<[<<->>-]<<[>[>+>+<<-]>>[<<+>>-]----[>+++++<--]>-<<[->>-<<]+>>[<<->>[-]]<<[<<->>-]]]]]+[-<+]->>]>.,[.,]
```
[Try it online!](https://tio.run/##rVFLCkJBDDtQpj1ByUVKFj5BEMGF4PnHdvDhUlGz6Yc0pO12O5yvp/vxMifSdhAIEW4vOBoeRiI5kiAiTGRGgDRZ9tgiiytEZNErCItWRZpU7ZVbZ3yr9BeV8v6DTq3yPIP4vU6hLWG5@mSxRn0loCpFH@lDc277zx4 "brainfuck – Try It Online")
A shorter version that only works for words with vowels.
[Answer]
# [V (Eh, vim shmim)](https://github.com/DJMcMayhem/V), 23 bytes
```
:%s/.\{-}\ze[aeiou]/shm
```
vim non-greedy regex with look-ahead.
[Try it online!](https://tio.run/##PcsxDoAgDEDRvfdwVHavIg4NwZSkAoEiQePZkck/v3/1vk5ZLfqZX33bDa0LZVeZzt6P4o244CGLZcYEKC06gwy1ViJCAfwDTgO4FBm9HUcoApXaBw "V (vim) – Try It Online")
Same in “magic very very” mode:
# 23 bytes
```
:%s/\v.{-}[aeiou]@=/shm
```
[Try it online!](https://tio.run/##PctBCoAgEEDR/dyjZbkPgu5RLQYxRphUdFQkOru16q/fL73PQ1J7me7x2dBYn491UYmu3s/stFjvIIlhxggoLViNDLVWIkIB/AOOH7AxMDrzHT4LVGov "V (vim) – Try It Online")
Further 3 bytes can be saved by replacing `:%s/` with V’s specific `í`
[Answer]
# [Go](https://go.dev), 103 bytes
```
import."regexp"
func f(s string)string{return MustCompile(`^.*?([aeiou])`).ReplaceAllString(s,"shm$1")}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY_PSsQwEMbPzlOE4CFZ1oI3EURE8CaIHkXtUKdtME1CMqEuy76Bb-BlEXyofRvT7bpzmT98M99vvn86v90tAjYf2JEY0DgwQ_CRK9kOLI9N4mhcl-Rv5vbsYtf9zyN19BkktNk1olVJzEI9p3UkztGJ-5z41g_BWFL1a7W4Vs9IxucXXevqkYLFhm6sfdovqbSUqR9Oz6XeHOy-9ucnOqXFGlofxdsyicsrEdEV7jtD9j2pepKx8Q4Sk7UYAXkVTIMWxnHs-x4Z8BhgYxGYWNwdlQ2fGcZ-BTN6PRmdPJSSrStI03NawwYOTNvtnP8A)
[Answer]
# [tinylisp 2](https://github.com/dloscutoff/tinylisp2), ~~64~~ 61 bytes
```
(\(S)(: T(drop-while(. !(p contains?"aeiou"))S)(? T(,"shm"T)S
```
Try it at [Replit](https://replit.com/@dloscutoff/tinylisp2). Example session:
```
tl2> (\(S)(: T(drop-while(. !(p contains?"aeiou"))S)(? T(,"shm"T)S
(() (S) (: T (drop-while (. ! (p contains? "aeiou")) S) (? T (, "shm" T) S)))
tl2> (def shm _)
shm
tl2> (map shm (list "codegolf" "stellar" "airplane" "lrr"))
("shmodegolf" "shmellar" "shmairplane" "lrr")
```
### Explanation
Port of [Unrelated String's Jelly answer](https://codegolf.stackexchange.com/a/247761/16766), among others.
First, we need a function that tests whether a character is not a vowel:
```
(. !(p contains?"aeiou"))
(. ) ; Compose
! ; Logical negation
(p ) ; with the partial application of
contains? ; the contains? function
"aeiou" ; to "aeiou"
```
Then our main function is as follows (where `(...)` represents the above function):
```
(\(S)(: T(drop-while(...)S)(? T(,"shm"T)S)))
(\ ) ; Lambda function
(S) ; that takes a string S:
(: T ) ; In what follows, let T be
(drop-while S) ; Drop characters from S while
(...) ; they are not vowels
(? T ) ; Is T truthy (nonempty)?
(,"shm"T) ; If so, concatenate "shm" with T
S ; If not, return the original string S
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 15.5 bytes
```
?,;>~$-~?"aeiou"$:"shm"@@
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWO-11rO3qVHTr7JUSUzPzS5VUrJSKM3KVHBwg8lBl66KVYpSKS4oy89JjlJRioaIA)
Nibbles has no built-in for vowels, which makes it slightly worse than other golfing languages for this.
## Explanation
```
? If
, non-empty
; x :=
>~ drop-while
$ from input
-~ not
? "aeiou" contained in "aeiou"
$ it
then
: "shm" prepend "shm"
@ to x
else
@ input
```
] |
[Question]
[
A simple challenge for your Monday evening (well, or Tuesday morning in the other half of the world...)
You're given as input a nested, potentially ragged array of positive integers:
```
[1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14]
```
Your task is to determine its depth, which is the greatest nesting-depth of any integer in the list. In this case, the depth of `11` is `6`, which is largest.
You may assume that none of the arrays will be empty.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
Input may be taken in any convenient list or string format that supports non-rectangular arrays (with nested arrays of different depths), as long as the actual information isn't preprocessed.
You must not use any built-ins related to the shape of arrays (including built-ins that solve this challenge, that get you the dimensions of a nested array). The only exception to this is getting the length of an array.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
### Test Cases
```
[1] -> 1
[1, 2, 3] -> 1
[[1, 2, 3]] -> 2
[3, [3, [3], 3], 3] -> 3
[[[[1], 2], [3, [4]]]] -> 4
[1, [[3]], [5, 6], [[[[8]]]], 1] -> 5
[1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14] -> 6
[[[[[[[3]]]]]]] -> 7
```
[Answer]
# K, 4 bytes
```
#,/\
```
In K, `,/` will join all the elements of a list. The common idiom `,//` iterates to a fixed point, flattening an arbitrarily nested list completely. `,/\` will iterate to a fixed point in a similar way, but gather a list of intermediate results. By counting how many intermediate results we visit before reaching the fixed point (`#`), we get the answer we want: the maximum nesting depth.
"Count of join over fixed-point scan".
In action:
```
(#,/\)'(,1
1 2 3
,1 2 3
(3;(3;,3;3);3)
,((,1;2);(3;,4)))
1 1 2 3 4
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 10
* Saved 1 byte thanks to @ӍѲꝆΛҐӍΛПҒЦꝆ
* Saved 14 extra bytes thanks to @MartinBüttner
```
+`\w|}{
{
```
Here the input format is a bit contrived - `_` characters are used for list separators, so an input would look like this `{1_{{2_3_{{4}_5}_6_{7_8}}_9_{10_{{{11}}}}_12_13}_14}`
* Stage 1 - repeatedly remove `}{` and all other `\w` characters. This has the effect of a) making all lists at all levels consist of only one element and b) removing all non-list-structural characters.
* Stage 2 - count remaining `{`. This gives the deepest level of nesting.
[Try it online.](http://retina.tryitonline.net/#code=K2Bcd3x9ewoKew&input=ezFfe3syXzNfe3s0fV81fV82X3s3Xzh9fV85X3sxMF97e3sxMX19fX1fMTJfMTN9XzE0fQ)
---
If that's too much of a stretch, then the previous answer was:
# [Retina](https://github.com/mbuettner/retina), 13
Assumes lists are contained in curly braces `{}`.
```
+`[^}{]|}{
{
```
[Try it online](http://retina.tryitonline.net/#code=K2BbXn17XXx9ewoKKHt9KikrCiQjMQ&input=ezEsIHt7MiwgMywge3s0fSwgNX0sIDYsIHs3LCA4fX0sIDksIHsxMCwge3t7MTF9fX19LCAxMiwgMTN9LCAxNH0).
[Answer]
## Python 2, 33 bytes
```
f=lambda l:l>{}and-~max(map(f,l))
```
Recursively defines the depth by saying the depth of a number is 0, and the depth of a list is one more than the maximum depth of its elements. Number vs list is checked by comparing to the empty dictionary `{}`, which falls above numbers but below lists on Python 2's arbitrary ordering of built-in types.
[Answer]
# Pyth - ~~11~~ ~~10~~ 7 bytes
*1 bytes saved thanks to @Dennis*
*4 bytes saved thanks to @Thomas Kwa*
```
eU.usNQ
```
[Try it online here](http://pyth.herokuapp.com/?code=eU.usNQ&input=%5B1%2C+%5B%5B3%5D%5D%2C+%5B5%2C+6%5D%2C+%5B%5B%5B%5B8%5D%5D%5D%5D%2C+1%5D++&debug=0).
Keeps on summing the array till it stops changing, which means its just a number, does this cumulatively to save all the intermediate results and gets length by making a urange with the same length as list and taking the last element.
[Answer]
## Haskell, 43 bytes
```
'['#x=x-1
']'#x=x+1
_#x=x
maximum.scanr(#)0
```
Usage example: `maximum.scanr(#)0 $ "[1, [[3]], [5, 6], [[[[8]]]], 1]"` -> `5`.
Haskell doesn't have mixed lists (`Integer` mixed with `List of Integer`), so I cannot exploit some list detection functions and I have to parse the string.
Im starting at the right with `0` and add 1 for every `]`, subtract 1 for every `[` and keep the value otherwise. `scanr` keeps all intermediate results, so `maximum` can do it's work.
[Answer]
# Julia, ~~55~~ 26 bytes
```
f(a)=0a!=0&&maximum(f,a)+1
```
This is a recursive function that accepts a one-dimensional array with contents of type `Any` and returns an integer. When passing an array to the function, prefix all brackets with `Any`, i.e. `f(Any[1,Any[2,3]])`.
The approach is pretty simple. For an input *a*, we multiply *a* by 0 and check whether the result is the scalar 0. If not, we know that *a* is an array, so we apply the function to each element of *a*, take the maximum and add 1.
Saved 29 bytes thanks to Dennis!
[Answer]
# JavaScript (ES6), 35 bytes
```
f=a=>a[0]?Math.max(...a.map(f))+1:0
```
## Explanation
Recursive function that returns the maximum depth of an array, or `0` if passed a number.
```
var solution =
f=a=>
a[0]? // if a is an array
Math.max(...a.map(f)) // return the maximum depth of each element in the array
+1 // add 1 to increase the depth
:0 // if a is a number, return 0
// Test cases
result.textContent =
`[1] -> 1
[1, 2, 3] -> 1
[[1, 2, 3]] -> 2
[3, [3, [3], 3], 3] -> 3
[[[[1], 2], [3, [4]]]] -> 4
[1, [[3]], [5, 6], [[[[8]]]], 1] -> 5
[1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14] -> 6
[[[[[[[3]]]]]]] -> 7`
.split`\n`.map(t=>(c=t.split`->`.map(p=>p.trim()),c[0]+" == "+c[1]+": "+(solution(eval(c[0]))==c[1]?"Passed":"Failed"))).join`\n`
```
```
<input type="text" id="input" value="[1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14]" />
<button onclick="result.textContent=solution(eval(input.value))">Go</button>
<pre id="result"></pre>
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 11 ~~14 15~~ bytes
```
'}{'!=dYsX>
```
Curly braces are used in MATL for this type of arrays. Anyway, the input is taken and processed as a string, so square brackets could equally be used, modifying the two characters in the code.
[**Try it online!**](http://matl.tryitonline.net/#code=J317JyE9ZFlzWD4&input=J3sxLCB7ezIsIDMsIHt7NH0sIDV9LCA2LCB7NywgOH19LCA5LCB7MTAsIHt7ezExfX19fSwgMTIsIDEzfSwgMTR9Jw)
```
% implicitly take input as a string (row array of chars)
'}{'! % 2x1 (column) char array with the two curly brace symbols
= % 2-row array. First / second row contains 1 where '}' / '{' is found
d % second row minus first row
Ys % cumulative sum of the array
X> % maximum of the array
% implicitly display result
```
[Answer]
# Jelly, ~~10~~ 7 bytes
```
¬;/SпL
```
[Try it online!](http://jelly.tryitonline.net/#code=wqw7L1PDkMK_TA&input=&args=WzEsIFtbMiwgMywgW1s0XSwgNV0sIDYsIFs3LCA4XV0sIDksIFsxMCwgW1tbMTFdXV1dLCAxMiwgMTNdLCAxNF0) or [verify all test cases](http://jelly.tryitonline.net/#code=wqw7L1PDkMK_TApbMV0sWzEsMiwzXSxbWzEsMiwzXV0sWzMsWzMsWzNdLDNdLDNdLFtbW1sxXSwyXSxbMyxbNF1dXV0sWzEsW1szXV0sWzUsNl0sW1tbWzhdXV1dLDFdLFsxLFtbMiwzLFtbNF0sNV0sNixbNyw4XV0sOSxbMTAsW1tbMTFdXV1dLDEyLDEzXSwxNF0sW1tbW1tbWzNdXV1dXV1dw4figqw&input=).
### How it works
```
¬;/SпL Main link. Input: A (list)
¬ Negate all integers in A. This replaces them with zeroes.
п Cumulative while loop.
S Condition: Compute the sum of all lists in A.
If the sum is an integer, it will be zero (hence falsy).
;/ Body: Concatenate all lists in A.
L Count the number of iterations.
```
### Update
While writing this answer, I noticed that Jelly behaves rather weirdly for ragged lists, because I calculated the depth of a list as the incremented *minimum* of depths of its items.
This has been addressed in the latest version, so the following code (**6 bytes**) would work now.
```
¬SSпL
```
This sums the rows of the array instead of concatenating them.
[Answer]
# Octave, 29 bytes
```
@(a)max(cumsum(92-(a(a>90))))
```
Maps `[` to 1 and `]` to -1, then takes the max of the cumulative sum.
Input is a string of the form
```
S6 = '[1, [[3]], [5, 6], [[[[8]]]], 1]';
```
Sample run on [ideone](http://ideone.com/3LeGxV).
[Answer]
## Ruby, 53 bytes
```
i=0;p gets.chars.map{|c|i+=('] ['.index(c)||1)-1}.max
```
Input from STDIN, output to STDOUT.
```
i=0; initialize counter variable
p output to STDOUT...
gets get line of input
.chars enumerator of each character in the input
.map{|c| map each character to...
i+= increment i (and return the new value) by...
('] ['.index(c)||1) returns 0 for ], 2 for [, 1 for anything else
-1 now it's -1 for ], 1 for [, 0 for anything else
therefore: increment i on increase in nesting, decrement i
on decrease, do nothing otherwise
}.max find the highest nesting level that we've seen
```
[Answer]
# Mathematica, 18 bytes
```
Max@#+1&//@(0#-1)&
```
[Answer]
# Mathematica, ~~27~~ 20 bytes
```
Max[#0/@#]+1&[0#]-1&
```
Simple recursive function.
[Answer]
# PHP, 61 bytes
```
function d($a){return is_array($a)?1+max(array_map(d,$a)):0;}
```
recursive function that uses itself as a mapping function to replace each element with its depth.
[Answer]
# PHP, ~~84~~ ~~72~~ ~~64~~ ~~63~~ 60 bytes
Note: requires PHP 7 for the combined comparison operator. Also uses IBM-850 encoding
```
for(;$c=$argv[1][$i++];)$c>A&&$t=max($t,$z+=~ú<=>$c);echo$t;
```
Run like this:
```
php -r 'for(;$c=$argv[1][$i++];)$c>A&&$t=max($t,$z+=~ú<=>$c);echo$t;' "[1, [[3]], [5, 6], [[[[8]]]], 1]"
```
* Saved 12 bytes by just counting braces of the string representation instead
* Saved 8 bytes by simplifying string comparisons and using ordinal number of the char in case of `[` and `]`
* Saved a byte by not casting `$i` to an int. String offsets are casted to an int implicitly
* Saved 3 bytes by using combined comparison operator instead of ordinal number
[Answer]
# [Haskell](https://www.haskell.org/) + [free](https://hackage.haskell.org/package/free-5.1.7/docs/Control-Monad-Free.html#t:Free), 29 bytes
Haskell doesn't have a built in ragged list type so we need to build one out of free monads from the [free](https://hackage.haskell.org/package/free-5.1.7/docs/Control-Monad-Free.html#t:Free) package.
```
iter((+1).maximum).fmap(*0)
```
[Try it online!](https://tio.run/##fVA9T8MwEN3zK26IhA2koh0r0glVYoKBDUXoaGxyInaqxIEM/e/hbCctGWBw5Pdx755TYfep6nrMMjjBg9JkyX6Aq6iDSrUKOrIHxViBbpUC05R9rYA6e@UAv5BqfGfcWHh5fEpKdAh779OACUAOzz1n@Osp8kKDmA1SJgnZziFvYIeAfW8PrmlBM5J8OGB3Jqcxz3/7ZkHXBo8cJcKaQUIeWIhrU1aGhS1E/LIFnEZZRJPkkYScamG7vRTyRbg6Qrbj3v47PyIwceBt6sGGfOaOFU1rjWcDPAv36Y7pUeeeEeJmLVcGBzK9kSvfRlzfydEg2bxsuPGxJevCq2Lia9i2LuTf2m38E5v/PYu0BdzMaGEpikvu@AM "Haskell – Try It Online")
[Answer]
# C, ~~98~~ 69 bytes
29 bytes off thanks [@DigitalTrauma](https://codegolf.stackexchange.com/users/11259/digital-trauma) !!
```
r,m;f(char*s){for(r=m=0;*s;r-=*s++==93)r+=*s==91,m=r>m?r:m;return m;}
```
Takes an *string* as input and return the result as integer.
Live example in: <http://ideone.com/IC23Bc>
[Answer]
## Python 3, ~~42~~ 39 bytes
*-3 bytes thanks to Sp3000*
This is essentially a port of [xnor's Python 2 solution](https://codegolf.stackexchange.com/a/71487/12914):
```
f=lambda l:"A"<str(l)and-~max(map(f,l))
```
Unfortunately, `[] > {}` returns an `unorderable types` error, so that particular clever trick of xnor's cannot be used. In its place, `-0123456789` are lower in ASCII value than `A`, which is lower than `[]`, hence the string comparison works.
[Answer]
## CJam (15 bytes)
```
q~{__e_-M*}h],(
```
[Online demo](http://cjam.aditsu.net/#code=q%7E%7B__e_-M*%7Dh%5D%2C(&input=%5B1%20%5B%5B2%203%20%5B%5B4%5D%205%5D%206%20%5B7%208%5D%5D%209%20%5B10%20%5B%5B%5B11%5D%5D%5D%5D%2012%2013%5D%2014%5D)
### Dissection
```
q~ e# Read line and parse to array
{ e# Loop...
_ e# Leave a copy of the array on the stack to count it later
_e_- e# Remove a flattened version of the array; this removes non-array elements from
e# the top-level array.
M* e# Remove one level from each array directly in the top-level array
}h e# ...until we get to an empty array
],( e# Collect everything together, count and decrement to account for the extra []
```
---
For the same length but rather more in ugly hack territory,
```
q'[,-{:~_}h],2-
```
[Answer]
# Sed, 40 characters
(39 characters code + 1 character command line option.)
```
s/[^][]+//g
:;s/]\[//;t
s/]//g
s/\[/1/g
```
Input: string, output: unary number.
Sample run:
```
bash-4.3$ sed -r 's/[^][]+//g;:;s/]\[//;t;s/]//g;s/\[/1/g' <<< '[1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14]'
111111
```
## Sed, 33 characters
(32 characters code + 1 character command line option.)
If trailing spaces are allowed in the output.
```
s/[^][]+//g
:;s/]\[//;t
y/[]/1 /
```
Input: string, output: unary number.
Sample run:
```
bash-4.3$ sed -r 's/[^][]+//g;:;s/]\[//;t;y/[]/1 /' <<< '[1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14]'
111111
```
[Answer]
## [Hexagony](https://github.com/m-ender/hexagony), 61 bytes
*Edit*: Thanks @Martin Ender♦ for saving me 1 byte from the marvelous -1 trick!
```
|/'Z{>"-\..(.."/'&<'..{>-&,=+<$.{\$._{..><.Z=/...({=Z&"&@!-"
```
[Try it online to verify test cases!](http://hexagony.tryitonline.net/#code=fC8nWns-Ii1cLi4oLi4iLycmPCcuLns-LSYsPSs8JC57XCQuX3suLj48Llo9Ly4uLih7PVomIiZAIS0i&input=WzFdICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLT4gMQpbMSwgMiwgM10gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAtPiAxCltbMSwgMiwgM11dICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0-IDIKWzMsIFszLCBbM10sIDNdLCAzXSAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLT4gMwpbW1tbMV0sIDJdLCBbMywgWzRdXV1dICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAtPiA0ClsxLCBbWzNdXSwgWzUsIDZdLCBbW1tbOF1dXV0sIDFdICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0-IDUKWzEsIFtbMiwgMywgW1s0XSwgNV0sIDYsIFs3LCA4XV0sIDksIFsxMCwgW1tbMTFdXV1dLCAxMiwgMTNdLCAxNF0gLT4gNgpbW1tbW1tbM11dXV1dXV0gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAtPiA3)
The images below are not modified but the flow is basically the same. Also note that this will return `-1` if the input is not an array (i.e. without `[]`).
I have lots of no-ops inside the Hexagon... I guess it can definitely be golfed more.
### Explanation
In brief, it adds `-1` when encounters a `[` and adds `1` when encounters a `]`. Finally it prints the max it has got.
Let's run along Test Case 5 to see its behaviour when it runs along the String `[1, [[3]], [5, 6], [[[[8]]]], 1]`:
It starts at the beginning and takes its input at the W corner:
[![Brackets](https://i.stack.imgur.com/ArKtR.png)](https://i.stack.imgur.com/ArKtR.png)
Since there is still input (not the null character `\0` or EOL), it wraps to the top and starts the crimson path.
Here is what happens when from there till cute `><`:
`,` reads `[` into Buffer, and `{` and `Z` sets the constant Z to be 90. `'` moves to Diff and `-` calculates the difference. For `[` and `]` the difference will be `1` and `3` respectively. For numbers and spaces and commas it'll be negative.
[![M1](https://i.stack.imgur.com/7iwgY.png)](https://i.stack.imgur.com/7iwgY.png) [![M2](https://i.stack.imgur.com/ql94L.png)](https://i.stack.imgur.com/ql94L.png)
Then we run `(` twice (once at the end of crimson path, one at the start after wrapping at the green path) to get `-1` and `1` resp for `[` and `]`. Here we change the naming of `Diff` to `Value`. Add this Value to Depth. (I used `Z&` to ensure that it copies the right neighbor). Then we calculate `lastMin - Depth` and got a number on the Memory edge `minLR`.
Then we apply `&` (at the end of green path) to `minLR`: If the number is <=0, it copies the left value (i.e. `lastMin - Depth <= 0 => lastMin <= Depth`), otherwise it takes the right value.
We wraps to the horizontal blue path and we see `Z&` again which copies the `minLR`. Then we `"&` and made a copy of the calculated min. The brackets are assumed to be balanced, so the min must be <=0. After wrapping, the blue path go left and hit `(`, making the copy `1` less than the real min. Reusing the `-`, we created one more 1-off copy as a neighbor of Buffer:
[![M3](https://i.stack.imgur.com/N4VKi.png)](https://i.stack.imgur.com/N4VKi.png)
Note: `copy` is renamed as `1-off`
When blue path hits `\` and got a nice `"` and `<` catches it back to the main loop.
When the loop hits `1`, `,` or or other numbers as input:
[![others](https://i.stack.imgur.com/dZVYh.png)](https://i.stack.imgur.com/dZVYh.png)[![M4](https://i.stack.imgur.com/JtTgJ.png)](https://i.stack.imgur.com/JtTgJ.png)
The Diff will become negative and it got reflected back to the main loop for next input.
When everything has gone through the main loop, we reach EOL which makes Buffer `-1` and it finally goes to the bottom edge:
[![M5](https://i.stack.imgur.com/8QmYR.png)](https://i.stack.imgur.com/8QmYR.png)
`'` moves the MP to the `1-off copy` and `)` increments it, and with `~` negation it got the correct Max Depth value which is printed with `!`
And the story ends with a `@`.
I guess I must have over complicating things a little bit. If I have had to only "move back" and "print" without incrementing and negation, I would have well saved 2 bytes without using the full Hexagon.
Great thanks to [Timwi](https://github.com/Timwi) for [Esoteric IDE](https://github.com/Timwi/EsotericIDE) and [Hexagony Colorer](https://github.com/Timwi/HexagonyColorer)!
[Answer]
## brainfuck, 48 bytes
```
,[<++[>-<------]>++[+[<]>>[-]]+<,]-[<[>+<-]>>]<.
```
Formatted:
```
,
[
<++[>-<------]>++
[
not close paren
+
[
not open paren
<
]
>>[-]
]
+<,
]
-[<[>+<-]>>]
<.
```
Takes input formatted like `(1, ((3)), (5, 6), ((((8)))), 1)` and outputs a [byte value](http://meta.codegolf.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values/4719#4719).
[Try it online.](http://brainfuck.tryitonline.net/#code=LFs8KytbPi08LS0tLS0tXT4rK1srWzxdPj5bLV1dKzwsXS1bPFs-KzwtXT4-XTwu&input=KDEsICgoMiwgMywgKCg0KSwgNSksIDYsICg3LCA4KSksIDksICgxMCwgKCgoMTEpKSkpLCAxMiwgMTMpLCAxNCk&debug=on)
This stores the depth by memory location, moving the pointer right for `(` and left for `)` and ignoring other characters. Visited cells are marked with a `1` flag, so at the end of the main loop there will be `depth + 1` flags to the right of the current cell. These are then added to print the final result.
---
A previous 69-byte solution using a different approach:
```
,
[
>>++[<<->>------]<-<++
[
not close paren
>++<+
[
not open paren
>-<[-]
]
]
<
[
[>+>]
<[<-<]
>
]
>>[<+> >+<-]
,
]
<.
```
In this version, the depth and max depth are stored explicitly in cells.
[Answer]
# [Io](http://iolanguage.org/), 53 bytes
Port of the JavaScript (ES6) answer.
```
f :=method(x,if(x type=="List",x map(i,f(i))max+1,0))
```
[Try it online!](https://tio.run/##TYxLDoMwDESvYrHyqF7gQr9SbtBLIJWolgigNov09GmgLFjY4zczsk05e7q70MfX9OQk5jlR/M69c9XDPrGSRKGb2cSzAaFLB5UayJ6HErMKrbquo1Cz5xZCpzLnzbwIXVH4trHW@/bfUmCpaPmlzXK0AM1vG@Mw5h8 "Io – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 64 bytes
```
d,l;f(char*s){return*s?l=d?d>l?d:l:0,d+=*s>90?92-*s:0,f(s+1):l;}
```
[Try it online!](https://tio.run/##VZBvi4MwDMbf@ymCIFSXgfXfpuL8IF5fDDs9wXPD7o6Dsc/uJa7stkJok@eXJ6Httm/bZdE4lp1oP49zYPzbfLp@z1Ng6rHStT6MtS7GIkS9qQJzyMM6j7aBoUInzEb6xVjel5/zoKG3DjhMV/j14eYAXGZKOuF6BirwtPC0/zG5CAaB2n0krnTujvN1HCbxaOmF20hFjCTJpggRQvxejBEeoViycvyUn01cjv7LJBAcKdudKLUSyeuwhkwZSBEyvunsmaPxzKbvLE/hOyE9pcgo2SHsmc/pLcPVQkprQbzkhWXCZtnras06WdmdduvfLH8 "C (gcc) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
ẎƬL
```
[Try it online!](https://tio.run/##y0rNyan8///hrr5ja3z@H25/1LTm6KSHO2f8/x/NxRltGKujQBlQ1rVTMASZpKNgpKNgTIF5MJPgRpFtFsgkI6BJxjoKEBwLcRnprgOZZAxyUzQ4qIxioSaaxMaS6DyQSSaQcIqOBvst2lRHwQxEA4EFxDyiogNkkinMJFBAgWgToE5TIDYDcsx1FCxAplkC2YYGYAsMDaEWANUbgoLBEKQBZJIZxHfRYEfFkuwtJDeZc8UCAA "Jelly – Try It Online")
This is a translation of [JohnE](https://codegolf.stackexchange.com/users/38485/johne)'s [K answer](https://codegolf.stackexchange.com/a/71494/66833).
`Ẏ` is the "tighten" command. When applied to a list, it "unwraps" each list in it, essentially reducing the depth by one. `Ƭ` repeated applies `Ẏ` to the input until it reaches a fixed point. We then count the number of iterations with `L`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
dΔ€`}N>
```
[Try it online](https://tio.run/##yy9OTMpM/f8/5dyUR01rEmr97P7/jzbUiY420jEGkiaxOqaxOmY60eY6FrGxOpY60YYGQOFoQ8NYINAxNNIxNAZSJrEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/lHNTHjWtSaj1s/uv8z862jBWRyHaUMdIxxjEgLJATGMdMIrVgSCgHFixUSxY3CQ2NhaiMzoapD7aVMcMSAKBBVjGECYJNA5ImsTqmMbqmOlEm@sA5XUsdaINDUCqDQ0hqo10DIF2GJpA7YkGGwoBAA).
**Explanation:**
```
d # Convert each integer in the (implicit) input-list to 1 (with a >=0 check)
Δ # Loop until the result no longer changes:
€ # Map over each inner item:
` # Pop and dump its contents to the stack
}N # After the loop, push the last 0-based index
> # Increase it by 1 to make it a 1-based index
# (which is output implicitly as result)
```
The `€`` basically flattens a list one level down, but will push its items in reversed order. E.g. [list `[[1,[2,3],4]]` will become `[4,[2,3],1]`](https://tio.run/##yy9OTMpM/f//UdOahP//o6MNdaKNdIxjdUxiYwE). In addition, it will do the same for multi-digit numbers, hence the need for the leading `d` to convert every integer to a single digit first. E.g. [list `[12,345,67]` will become `[2,1,5,4,3,7,6]`](https://tio.run/##yy9OTMpM/f//UdOahP//ow2NdIxNTHXMzGMB).
[Answer]
# [Whython](https://github.com/pxeger/whython), 28 bytes
```
f=lambda l:1+max(map(f,l))?0
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RVBLCsIwEN17ilmmGKHTn7UgHiTMIiKhhfRDqahncdONeAkv4t6DmKSJBiYzk_fePCb356W-TXXfzfPjPKlN-VJ7LdvjSYKucN3KK2vlwBTXUXSIF8r7o_oRNDQdiBUIJG5vDgmH1NW_xnUp90EODxxhhZCQRzMiCoOEsFIQOYfCZnNKBwP-KdbA5sw85yYK02w5lJa2MzXGTonolYaP1h6z4C-cD3ljqlYAw9h0E1PMbLvsGr7lCw)
### Explanation
The depth of a list is the maximum depth of its elements; the depth of an integer is 0.
```
f=lambda l:1+max(map(f,l))?0
f= # Define f as
lambda l: # a function of one argument, l:
map(f,l) # Call f recursively on each element of l
max( ) # Take the maximum
1+ # Add 1
# If l is an integer, map raises an exception
?0 # Catch that exception and return 0
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
>0|↰ᵐ⌉+₁
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w386gBigAZD3q6dR@1NT4/390tGGsTrShjoKRjoIxkAVnAtnGOgoQHAuWg8iDNSgYxULlTGJjYyEGREeDNClEm@oomIFoILAASyoYwhSADAbRJkBBUyA2A3LMdRQsQIosgWxDA7A@Q0OoPqB6Q5DFhiYQm6PBdkAAAA "Brachylog – Try It Online")
```
0| Output 0
> if the input is a positive integer;
|↰ᵐ else map this over the elements of the input
+₁ and add 1 to
⌉ the largest result.
```
[Answer]
# Raku, 53 48 bytes
The closure:
```
{my $d;/[\[{$d++;$!=max $!,$d}|\]{$d--}|.]*/;$!}
```
Needs an argument, eg:
```
> {my $d;/[\[{$d++;$!=max $!,$d}|\]{$d--}|.]*/;$!}("[[[3]][2]]")
3
```
Explanation:
```
{ # start outer IIFE closure;
my $d; # declare depth variable `$d`;
/ # start IIFE regex match;
[ # start (non-capturing) group;
# EITHER:
\[ # match `[` in input; if successful then:
{ # start inner (within regex) IIFE closure;
$d++; # increment depth variable; and then:
$! = max $!, $d # (ab)use `$!` variable to track MAX depth;
} # end inner IIFE closure;
| # OR:
\] # match `[` in input; if successful then:
{$d--} # decrement depth variable in IIFE closure;
| # OR:
. # match one character;
]* # end capture group; match zero or more times;
/; # end regex;
$! # max depth as last value in closure;
} # end outer closure, returning last value (max depth);
("[[[3]][2]]") # pass string "[[[3]][2]]" as outer closure argument.
```
[Answer]
## Pyth, ~~15~~ 13 bytes
*-2 bytes by @Maltysen*
```
eSm-F/Ld`Y._z
```
Counts the difference between the cumulative counts of `[` and `]`, and takes the maximum. `Y` is the empty array, and its string representation (```) is conveniently `[]`.
Try it [here](http://pyth.herokuapp.com/?code=eSm-F%2FLd%60Y._z&input=%5B1%2C+%5B%5B2%2C+3%2C+%5B%5B4%5D%2C+5%5D%2C+6%2C+%5B7%2C+8%5D%5D%2C+9%2C+%5B10%2C+%5B%5B%5B11%5D%5D%5D%5D%2C+12%2C+13%5D%2C+14%5D&debug=0).
] |
[Question]
[
In the [Anno video game series](https://en.wikipedia.org/wiki/Anno_(series)) there are 6 games with a 7th one announced for early 2019. Their titles always feature a year in a specific pattern:
`Anno 1602, Anno 1503, Anno 1701, Anno 1404, Anno 2070, Anno 2205, Anno 1800`
* The digital sum is always 9.
* The years are four digits long.
* They contain at least one zero.
Within these constrains there exist 109 possible titles:
```
[1008,1017,1026,1035,1044,1053,1062,1071,1080,1107,1170,1206,1260,1305,1350,1404,1440,1503,1530,1602,1620,1701,1710,1800,2007,2016,2025,2034,2043,2052,2061,2070,2106,2160,2205,2250,2304,2340,2403,2430,2502,2520,2601,2610,2700,3006,3015,3024,3033,3042,3051,3060,3105,3150,3204,3240,3303,3330,3402,3420,3501,3510,3600,4005,4014,4023,4032,4041,4050,4104,4140,4203,4230,4302,4320,4401,4410,4500,5004,5013,5022,5031,5040,5103,5130,5202,5220,5301,5310,5400,6003,6012,6021,6030,6102,6120,6201,6210,6300,7002,7011,7020,7101,7110,7200,8001,8010,8100,9000]
```
Your objective is to list them all in any reasonable form in the fewest number of bytes.
[Answer]
# [R](https://www.r-project.org/), ~~59~~ 51 bytes
Outputs the valid numbers as the *names* of a list of 201's. Why 201? Because ASCII 0 is 48, and 4\*48+9 is... yeah. Saved 6 bytes by aliasing `^` to `Map` and another 2 by using `1:9e3` as range.
```
"^"=Map;x=sum^utf8ToInt^grep(0,1:9e3,,,T);x[x==201]
```
[Try it online!](https://tio.run/##K/r/XylOydY3scC6wra4NDeutCTNIiTfM68kLr0otUDDQMfQyjLVWEdHJ0TTuiK6wtbWyMAw9v9/AA "R – Try It Online")
# Explanation
```
# Create list of sums of ASCII char values of numbers,
# with the original numbers as the names of the list
x <- Map(sum,
# Create a list from the strings where each element is the string split
# into ASCII char values
Map(utf8ToInt,
# Find all numbers between 1 and 9e3 that contain a zero
# Return the matched values as a vector of strings (6th T arg)
grep(pattern=0,x=1:9000,value=TRUE)
)
)
# Pick out elements with value 201 (i.e. 4-digits that sum to 9)
# This implicitly only picks out elements with 4 digits, since 3-digit
# sums to 9 won't have this ASCII sum, letting us use the 1:9e3 range
x[x==201]
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~35~~ 33 bytes
*-2 bytes thanks to Jo King*
```
{grep {.ords.sum==201&&/0/},^1e4}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Or0otUChWi@/KKVYr7g019bWyMBQTU3fQL9WJ84w1aT2f0FpiUKahuZ/AA "Perl 6 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~67~~ ~~66~~ 64 bytes
```
print[y for y in range(9001)if('0'in`y`)*sum(map(ord,`y`))==201]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM68kulIhLb9IoVIhM0@hKDEvPVXD0sDAUDMzTUPdQD0zL6EyQVOruDRXIzexQCO/KEUHJKBpa2tkYBj7/z8A "Python 2 – Try It Online")
---
Saved:
* -1 byte, thanks to Luis felipe De jesus Munoz
* -2 bytes, thanks to Kevin Cruijssen
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
9ȷṢ€æ.ẹ9ṫ19
```
[Try it online!](https://tio.run/##AR4A4f9qZWxsef//Oci34bmi4oKsw6Yu4bq5OeG5qzE5//8 "Jelly – Try It Online")
### How it works
```
9ȷṢ€æ.ẹ9ṫ19 Main link. No arguments.
9ȷ Set the left argument and the return value to 9000.
Ṣ€ Sort the digits of each integer in [1, ..., 9000].
æ. Perform the dot product of each digit list and the left argument,
which gets promoted from 9000 to [9000].
Overflowing digits get summed without multiplying, so we essentially
map the digit list [a, b, c, d] to (9000a + b + c + d).
ẹ9 Find all 1-based indices of 9.
Note that 9000a + b + c + d == 9 iff a == 0 and b + c + d == 9.
ṫ19 Tail 19; discard the first 18 indices.
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~50~~ 49 bytes
```
999..1e4-match0|?{([char[]]"$_"-join'+'|iex)-eq9}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/39LSUk/PMNVENzexJDnDoMa@WiM6OSOxKDo2VkklXkk3Kz8zT11bvSYztUJTN7XQsvb/fwA "PowerShell – Try It Online")
Constructs a range from `999` to `10000`, then uses inline `-match` as a filter to pull out those entries that regex match against `0`. This leaves us with `1000, 1001, 1002, etc.` We then pipe that into a `Where-Object` clause where we take the current number as a string `"$_"`, cast it as a `char`-array, `-join` those characters together with `+` and `I`nvoke-`Ex`pression (similar to eval) to come up with their digit sum. We check whether that is `-eq`ual to `9`, and if so it's passed on the pipeline. At program completion, those numbers are picked up from the pipeline and implicitly output.
[Answer]
# JavaScript (ES6), ~~78~~ 73 bytes
*Saved 2 bytes thanks to @KevinCruijssen*
Returns a space-separated string.
```
f=(n=9e3)=>n>999?f(n-9)+(eval([...n+''].join`+`)&/0/.test(n)?n+' ':''):''
```
[Try it online!](https://tio.run/##DcnBCsIwDADQX/FkEsoywVOEbh8iwspMZaMkYst@v@7wTm9PR6rrb/u2wfytveeIFkXvFCebRGTOaINQQD1SwSczWwB48e6bLWGh63gbuWltaDSfdYEHAJ366la9KBf/YEai/gc "JavaScript (Node.js) – Try It Online")
### How?
We iterate over the range \$[1008..9000]\$ with an increment of \$9\$, ignoring numbers that don't have a \$0\$.
All these numbers are multiples of \$9\$, so the sum of their digits is guaranteed to be a multiple of \$9\$ as well.
Because valid numbers have at least one \$0\$, they have no more than two \$9\$'s, which means that the sum of the remaining digits is at most \$18\$. Therefore, it's enough to test if the sum of the digits is odd.
Hence the test:
```
(eval([...n + ''].join`+`) & /0/.test(n)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 89 bytes
```
[...Array(9e3)].map(_=>i++,i=1e3).filter(a=>(s=[...a+""]).sort()[0]<1&eval(s.join`+`)==9)
```
[Try it online!](https://tio.run/##FcpRCsIwDADQu@xDEqrB4dfADDzHKC7MKh21GWkZePqqv4@3yi5lsbjVU9ZHaIvmoilQ0he0iYhuZvKBIVzQ01s2uPMYnTtG7n9Ez5hqMBAeofC/i@s6j1TUKuB09tf@EHZJUGjVmGc3I/OADdsX "JavaScript (Node.js) – Try It Online")
* -4 bytes thanks to @ETHproductions
# JavaScript (Node.js), ~~129~~ ~~127~~ ~~126~~ ~~124~~ ~~115~~ ~~114~~ ~~111~~ ~~110~~ ~~105~~ ~~97~~ ~~93~~ ~~92~~ 90 bytes
```
[...Array(9e3)].map(f=(_,i)=>eval(s=[...(i+=1e3)+""].sort().join`+`)-9|s[0]?0:i).filter(f)
```
[Try it online!](https://tio.run/##FcpRCsIwDADQu@wroS5M/JpQxXOM4sJsJaM2oy0DwbtXfd9v5Z3LkmWrfdKHb4umotFT1Ce0iYhuOfMbRn9CRy/eIFi4HwTtxe8codj/ATH2@Bum6xwVzRWQVpU0mxn78VOmwV2HsyAFidVnCNiwfQE "JavaScript (Node.js) – Try It Online")
### Explanation
```
[...Array(9e3)].map(f=(_,i)=>eval(s=[...(i+=1e3)+""].sort().join`+`)-9|s[0]?0:i).filter(f)
[...Array(9e3)].map(f=(_,i)=> ) // Create a 9000-length array and loop over it; store the loop body
[...(i+=1e3)+""] // Add 1000 to the index and split it into an array of characters (17 -> ["1", "0", "1", "7"])
.sort() // Sort the array of characters in ascending order by their code points ("0" will always be first) (["1", "0", "1", "7"] -> ["0", "1", "1", "7"])
s= .join`+` // Join them together with "+" as the separator (["0", "1", "1", "7"] -> "0+0+2+9"); store the result
eval( )-9 // Evaluate and test if it's different than 9
s[0] // Take the first character of the string and implicitly test if it's different than "0"
| ?0 // If either of those tests succeeded, then the number doesn't meet challenge criteria - return a falsey value
:i // Otherwise, return the index
.filter(f) // Filter out falsey values by reusing the loop body
```
First time doing code golf in JavaScript. I don't think I need to say it, but if I'm doing something wrong, please notify me in the comments below.
* -3 bytes thanks to @Luis felipe De jesus Munoz
* -6 bytes thanks to @Kevin Cruijssen
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes
```
n=999
exec"n+=9\nif'0'in`n`>int(`n`,11)%10>8:print n\n"*n
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/W0tKSK7UiNVkpT9vWMiYvM03dQD0zLyEvwS4zr0QDSOsYGmqqGhrYWVgVFAGFFPJi8pS08v7/BwA "Python 2 – Try It Online")
*2 bytes thanks to Dennis*
Uses an `exec` loop to counts up `n` in steps of 9 as 1008, 1017, ..., 9981, 9990, printing those that meet the condition.
Only multiples of 9 can have digit sum 9, but multiples of 9 in this range can also have digits sum of 18 and 27. We rule these out with the condition `int(`n`,11)%10>8`. Interpreting `n` in base 11, its digit sum is equal to the number modulo 10, just like in base 10 a number equals its digit sum modulo 9. The digits sum of (9, 18, 27) correspond to (9, 8, 7) modulo 10, so taking those`>8` works to filter out nines.
The number containing a zero is check with string membership. `'0'in`n``. This condition is joined with the other one with a chained inequality, using that Python 2 treats strings as greater than numbers.
[Answer]
# sed and grep (and seq), ~~72~~ ~~64~~ 63 bytes
```
seq 9e3|sed s/\\B/+/g|bc|grep -wn 9|sed s/:9//|grep 0|grep ....
```
[Answer]
# [Haskell](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0QhOrMm00a3OCO/3EbFLtpQT880zixWx8jA0Na2uDRXI60oP9c1rzQXKJmpqZOak5qroG6gnhn7/z8A), 55 bytes
```
[i|i<-show<$>[1..5^6],201==sum(fromEnum<$>i),elem '0'i]
```
Thanks to @Laikoni, see the comments.
Readable:
```
import Data.Char (digitToInt)
[i | i <- show <$> [1000..9999]
, sum (digitToInt <$> i) == 9
, '0' `elem` i
]
```
[Answer]
# [R](https://www.r-project.org/), 82 bytes
```
write((x=t(expand.grid(1:9,0:9,0:9,0:9)))[,colSums(x)==9&!apply(x,2,all)],1,4,,"")
```
[Try it online!](https://tio.run/##K/r/v7wosyRVQ6PCtkQjtaIgMS9FL70oM0XD0MpSxwCBNTU1o3WS83OCS3OLNSo0bW0t1RQTCwpyKjUqdIx0EnNyNGN1DHVMdHSUlDT//wcA "R – Try It Online")
Generates a matrix `x` of all possible 4-digit numbers, excluding leading zeros, going down columns. Then filters for column (digital) sums of 9 and containing zero, i.e., not `all` are nonzero. `write` prints down the columns, so we `write` to `stdout` with a width of `4` and a separator of `""`.
[Outgolfed by J.Doe](https://codegolf.stackexchange.com/a/174054/67312)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~20~~ 18 bytes.
*-2 bytes thanks to @Shaggy and @ETHproductions*
```
A³òL² f_=ì)x ¥9«Z×
```
---
```
A³òL² f_=ì)x ¥9«Z× Full program
A³òL² Range [1000, 10000]
f_ Filter by :
=ì) Convert to array
x ¥9 Sum equal to 9?
« And
Z× Product not 0
```
[Try it online!](https://tio.run/##ASMA3P9qYXB0//9BwrPDskzCsiBtcyBmX8KseCDCpTnCqVrDuDD//w "Japt – Try It Online")
[Answer]
# Java 8, ~~128~~ ~~117~~ 115 bytes
```
v->{int i=109,r[]=new int[i],n=i;for(;i>0;n++)if((n+"").chars().sum()==201&(n+"").contains("0"))r[--i]=n;return r;}
```
-11 bytes thanks to *@nwellnhof*.
[Try it online.](https://tio.run/##NZDPasMwDMbvfQqTw5BJY9LdhnFhD7BeCruEHDw3WZU5cvGfjFLy7JnTdheB9OkTv0@DnnQ1nH4WY3UI7EMj3TaMIcXO99p07LC290HTMgOfDk9s4jIP500uIeqIhh0YMbVM1f6WFxmqXf229U2rqPu9W7HdkkLZOw8S97WksuTYA1BZFFyYs/YBuAhpBK7Ua717@VccxYwUoKgLzn1TVZiPSt/F5Il5OS8rySV92QzxZJlWxDG74Bg90nfm1vyR4ngNsRuFS1FcshQtwZAfIFJEK96919cgonvYgIQBStZy/ow7L38)
**Explanation:**
```
v->{ // Method with empty unused parameter & int-array return
int i=109, // Index-integer, starting at 109
r[]=new int[i], // Result-array of size 109
n=i; // Number integer, starting at 109
for(;i>0; // Loop as long as `i` is not 0 yet:
n++) // After every iteration, increase `n` by 1
if((n+"").chars().sum()==201 // If the sum of the unicode values of `n` is 201,
// this means there are four digits, with digit-sum = 9
&(n+"").contains("0")) // and `n` contains a 0:
r[--i // Decrease `i` by 1 first
]=n; // And put `n` in the array at index `i`
return r;} // Return the array as result
```
[Answer]
# [R](https://www.r-project.org/), 85 bytes
(just competing for the best abuse of R square brackets ... :P )
```
`[`=`for`;i[a<-0:9,j[a,k[a,w[a,if(sum(s<-c(i,j,k,w))==9&any(!s)&i)write(s,1,s='')]]]]
```
[Try it online!](https://tio.run/##DcNRCoAgDADQs/RTG0yoT0tPIoESBSsqcIV0@uWDl1VjiD5ud44Th@RMP1raQ6KjLjVvIO8J4swCTDsdVBC9t226PmgEW8aS@VlBaCDxXYdzpfoD "R – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ ~~13~~ ~~12~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₄4°ŸεW°ö9Q
```
-2 bytes thanks to *@Emigna*
-3 bytes thanks to *@Grimy*
[Try it online.](https://tio.run/##ARsA5P9vc2FiaWX//@KChDTCsMW4ypJXwrDDtjlR//8)
**Explanation:**
```
₄4°Ÿ # Create a list in the range [1000,10000]
ʒ # Filter this list by:
W # Get the smallest digit in the number (without popping the number itself)
° # Take 10 to the power this digit
ö # Convert the number from this base to an integer (in base-10)
9Q # Check if it's equal to 9
```
* If the smallest digit is \$d=0\$ it will become \$1\$ with the \$10^d\$ (`°`). And the number in base-1 converted to an integer in base-10 (`ö`) would act like a sum of digits.
* If the smallest digit is \$d=1\$ it will become \$10\$ with the \$10^d\$ (`°`). And the number in base-10 converted to an integer in base-10 (`ö`) will of course remain the same.
* If the smallest digit is \$d=2\$ it will become \$100\$ with the \$10^d\$ (`°`). And the number in base-100 convert to an integer in base-10 (`ö`) would act like a join with `0` in this case (i.e. `2345` becomes `2030405`).
* If the smallest digit is \$d=3\$ it will become \$1000\$ with the \$10^d\$ (`°`). And the number in base-100 convert to an integer in base-10 (`ö`) would act like a join with `00` in this case (i.e. `3456` becomes `3004005006`).
* ... etc. Smallest digits \$d=[4,9]\$ would act the same as \$d=2\$ and \$d=3\$ above, with \$d-1\$ amount of `0`s in the 'join'.
If the smallest digit is \$>0\$ with the given range \$[1000,10000]\$, the resulting number after `°ö` would then be within the range \$[1111,9000000009000000009000000009]\$, so can never be equal to \$9\$. If the result is equal to \$9\$ (`9Q`) it would mean the smallest digit is \$d=0\$, resulting in a base-1 with `°ö`; and the sum of the digits was \$9\$.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 18 bytes
```
{0Na&$+a=9}FIm,t*m
```
Use an ouput-format flag such as `-p` to get readable output. [Try it online!](https://tio.run/##K8gs@P@/2sAvUU1FO9HWstbNM1enRCv3////ugUA "Pip – Try It Online")
```
{0Na&$+a=9}FIm,t*m
m,t*m Range from 1000 to 10*1000
{ }FI Filter on this function:
0Na There is at least one 0 in the argument
& and
$+a The sum of the argument
=9 equals 9
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~56~~ 55 bytes
```
Select[9!!~Range~9999,Tr@#==Times@@#+9&@*IntegerDigits]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z84NSc1uSTaUlGxLigxLz21zhIIdEKKHJRtbUMyc1OLHRyUtS3VHLQ880pS01OLXDLTM0uKY////69bUJSZVwIA "Wolfram Language (Mathematica) – Try It Online")
We test the range from 9!! = 945 to 9999, since there are no results between 945 and 999. Maybe there's a shorter way to write a number between 9000 and 10007, as well.
`Tr@#==Times@@#+9&` applied to `{a,b,c,d}` tests if `a+b+c+d == a*b*c*d+9`, which ends up being equivalent to The Anno Condition.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~46 42~~ 41 bytes
```
?9.upto(?9*4){|x|x.sum==201&&x[?0]&&p(x)}
```
[Try it online!](https://tio.run/##KypNqvz/395Sr7SgJF/D3lLLRLO6pqKmQq@4NNfW1sjAUE2tItreIFZNrUCjQrP2/38A "Ruby – Try It Online")
### How it works:
* Iterate on strings ranging from '9' to '9999'
* Check that sum of ASCII values is 201
* Check if string contains a zero (without regex, a regex would be 1 byte longer)
(Thanks Laikoni for -2 bytes)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 49 bytes
*6 bytes saved using a more convenient output format as suggested by [J.Doe](https://codegolf.stackexchange.com/users/81549/j-doe).*
*Thanks to [@Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni) for a correction*.
```
y=dec2base(x=1e3:9999,10)'-48;x(sum(y)==9>all(y))
```
[Try it online!](https://tio.run/##y08uSSxL/f@/0jYlNdkoKbE4VaPC1jDV2MoSCHQMDTTVdU0srCs0iktzNSo1bW0t7RJzcoAszf//AQ "Octave – Try It Online")
[Answer]
# [Dart](https://www.dartlang.org/), ~~103 100~~ 96 bytes
```
f()=>List.generate(9001,(i)=>'$i').where((i)=>i.contains('0')&&i.runes.fold(0,(p,e)=>p+e)==201);
```
- -3 bytes by setting the value in the array to string, making the conversion once and not twice
- -4 bytes by using runes instead of codeUnits
Pretty self-explanatory. generates a list of 9001 (0-9000) cells with the cell's index as value, filters the ones containing a 0 then the one having an ASCII sum of 201 (The result if all the ASCII characters sum to 9). These conditions implictly include that the year is 4 digits long because using 2 ASCII numbers (and the 0), you cannot reach 201.
[Try it on Dartpad!](https://dartpad.dartlang.org/76525a5c2f46e9a22683ff7b4532f897)
[Answer]
# [Bash](https://www.gnu.org/software/bash/) (with `seq`, `grep`), 39 bytes
```
seq 0 9 1e4|egrep '([0-4].*){3}'|grep 0
```
[Try it online!](https://tio.run/##S0oszvj/vzi1UMFAwVLBMNWkJjW9KLVAQV0j2kDXJFZPS7PauFa9Bixm8P8/AA "Bash – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 22 bytes
```
55_&(|/~a)&9=+/a:!4#10
```
[Try it online!](https://tio.run/##y9bNS8/7/9/UNF5No0a/LlFTzdJWWz/RStFE2dDg/38A "K (ngn/k) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 23 bytes
```
55↓⍸(×⌿<9=+⌿)10⊥⍣¯1⍳9e3
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///39T0UdvkR707NA5Pf9Sz38bSVhtIaRoaPOpa@qh38aH1ho96N1umGhOtEAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
## PHP, ~~69, 87 bytes~~ 74 bytes
~~`for($i=999;$i<9001;$i++){echo((array_sum(str_split($i))==9&strpos($i,"0")!=0)?$i:" ");}`~~
`for($i=999;$i++<1e4;)echo!strpos($i,48)|array_sum(str_split($i))-9?" ":$i;`
Note this puts a space for every "failed" number, leading to some kind of funky spacing. This can be changed to comma separation, but will add another 4 characters: `?$i.",":""`
Got bigger because I wasn't checking for 0. Derp. Shortened by 13 by Titus!
[Answer]
# APL(Dyalog), ~~33~~ 29 bytes
```
1e3+⍸(0∘∊∧9=+/)¨⍎¨∘⍕¨1e3+⍳9e3
```
*-4 bytes thanks to @Adam*
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L9hqrH2o94dGgaPOmY86uh61LHc0lZbX/PQike9fUACKNg79dAKiKrNlqnGIF3/FcCgAAA)
[Answer]
# [Scala](https://www.scala-lang.org/) (76 63 61 56 bytes)
```
for(n<-0 to 9000;t=n+""if t.sum==201&t.min<49)println(t)
```
[Try it online](https://tio.run/##BcFRCkBAEADQq0w@RKIhP2I/HMAhFqtWu7ObHaXk7OO9tGmnJayn2RgWbQnMw4b2BHOMrxzhKmiqETjAgIgjK6qyzB7ATbq9Uh22OTfe0tQPZbwssaOCS/lEfg)
* Thanks to Laikoni for the suggestions
* Two more bytes shed after applying Jo King's comment
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes
```
k1k2r'∑9=n0c∧
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJUIiwiIiwiazFrMnIn4oiROT1uMGPiiKciLCIiLCIiXQ==)
Extremely slow.
[Answer]
# [Tcl](http://tcl.tk/), 77 bytes
```
time {if [incr i]>1e3&[regexp 0 $i]&9==[join [split $i ""] +] {puts $i}} 9999
```
[Try it online!](https://tio.run/##K0nO@f@/JDM3VaE6M00hOjMvuUghM9bOMNVYLbooNT21okDBQEElM1bN0tY2Ois/M08hurggJ7MEKKagpBSroB2rUF1QWlIM5NfWKlgCwf//AA "Tcl – Try It Online")
[Answer]
# Japt, 16 bytes
Returns an array of digit arrays.
```
L²õì l4 k_ת9aZx
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.6&code=TLL17CBsNCBrX9eqOWFaeA==&input=LVE=)
---
## Explanation
```
L :100
² :Squared
õ :Range [1,L²]
ì :Convert each to a digit array
l4 :Filter elements of length 4
k_ :Remove each Z that returns truthy (not 0)
× : When reduced by multiplication
ª : OR
Zx : When reduced by addition
9a : And subtracted from 9
```
[Answer]
# APL(NARS), 45 chars, 90 bytes
```
f←{⍵×⍳(0∊x)∧9=+/x←⍎¨⍕⍵}⋄f¨1e3..5e3⋄f¨5e3..9e3
```
test afther some formatting:
```
1008 1017 1026 1035 1044 1053 1062 1071 1080 1107 1170 1206 1260
1305 1350 1404 1440 1503 1530 1602 1620 1701 1710 1800 2007 2016
2025 2034 2043 2052 2061 2070 2106 2160 2205 2250 2304 2340
2403 2430 2502 2520 2601 2610 2700 3006 3015 3024 3033 3042 3051
3060 3105 3150 3204 3240 3303 3330 3402 3420 3501 3510 3600
4005 4014 4023 4032 4041 4050 4104 4140 4203 4230 4302 4320 4401
4410 4500
5004 5013 5022 5031 5040 5103 5130 5202 5220 5301 5310 5400 6003
6012 6021 6030 6102 6120 6201 6210 6300 7002 7011 7020 7101 7110
7200 8001 8010 8100 9000
```
possible alternative
```
r←f;i;x
r←⍬⋄i←1e3⋄→B
A: r←r,i
B: i+←1⋄→A×⍳(0∊x)∧9=+/x←⍎¨⍕i⋄→B×⍳i≤9e3
```
] |
[Question]
[
[Related but very different.](https://codegolf.stackexchange.com/questions/64330/reverse-boustrophedon-text)
A [boustrophedon](https://en.wikipedia.org/wiki/Boustrophedon) is a text where every other line of writing is flipped or reversed, with reversed letters.
In this challenge, we will just reverse every other line, but leave the actual characters used intact. You may chose which lines to reverse, as long as it is every other one.
You may take the text in any suitable format as long as you support zero or more lines of printable ASCII, each with zero or more characters.
### Examples:
```
["Here are some lines","of text for you","to make a","boustrophedon"]:
["Here are some lines","uoy rof txet fo","to make a","nodehportsuob"] or ["senil emos era ereH","of text for you","a ekam ot","boustrophedon"]
["My boustrophedon"]:
["My boustrophedon"] or ["nodehportsuob yM"]
[]:
[]
["Some text","","More text","","","Last bit of text"]:
["Some text","","More text","","","txet fo tib tsaL"] or ["txet emoS","","txet eroM","","","Last bit of text"]
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 4 bytes
```
⊢∘⌽\
```
The input is a vector of character vectors.
`⌽` is a function that reverses a vector (when `⌽` is applied monadically).
`⊢` is "*dex*" - a function that returns its right argument. When composed (`∘`) with another function `f` it forces the latter to be monadic as `A ⊢∘f B` is equivalent to `A ⊢ (f B)` and therefore `f B`.
`\` is the *scan* operator. `g\A B C ...` is the vector `A (A g B) (A g (B g C)) ...` where `g` is applied dyadically (infix notation). Substituting `⊢∘⌽` for `g` it simplifies to:
```
A (A ⊢∘⌽ B) (A ⊢∘⌽ (B ⊢∘⌽ C)) ...
A (⌽B) (⌽⌽C) ....
A (⌽B) C ....
```
The reversals at even positions (or odd, depending on how you count) cancel out.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhEddix51zHjUszcGyFf3SC1KVUgE4uL83FSFnMy81GJ1BfX8NIWS1IoShbT8IoXK/FKgSEm@Qm5iNlApkJ2UX1pcUpRfkJGakp@nzpWm86irSd23UgFdXMHgUe8WkJw6AA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 26 bytes
```
zipWith($)l
l=id:reverse:l
```
[Try it online!](https://tio.run/##dYy9DoIwFIV3nuKkcYAEfQASdhdmB2WocCsNpbdpixEf3lrcPckZzk@@SYaZjEmqvaW3dhcdp/JQmcK0emw8PckHakxapLZosUjXoXRe24gTVFUg64qrOJMnyOzAC8FoS0HUEKwQ6RWh2GPjda8iZ8qcz3u48xqiZzfRyFb0P1ydcd2GP1OPPn0GZeQjpOPg3Bc "Haskell – Try It Online") Usage example: `zipWith($)l ["abc","def","ghi"]` yields `["abc","fed","ghi"]`.
**Explanation:**
`l` is an infinite list of functions alternating between the `id`entity function and the `reverse` function.
The main function zips `l` and the input list with the function application `$`, that is for an input `["abc", "def", "ghi"]` we get `[id$"abc", reverse$"def", id$"ghi"]`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
z*İ_
```
Takes and returns a list of strings (the interpreter implicitly joins the result by newlines before printing).
The first string is reversed.
[Try it online!](https://tio.run/##yygtzv7/v0rryIb4////RysZGinpKBmbAAlTMyBhbgEkLA2UYgE "Husk – Try It Online")
## Explanation
```
z*İ_ Implicit input.
İ_ The infinite list [-1,1,-1,1,-1,1..
z Zip with input
* using multiplication.
```
In Husk, multiplying a string with a number repeats it that many times, also reversing it if the number is negative.
[Answer]
# JavaScript (ES6), Firefox, 43 bytes
This version abuses the sort algorithm of **Firefox**. It generates garbage on Chrome and doesn't alter the strings at all on Edge.
```
a=>a.map((s,i)=>[...s].sort(_=>i&1).join``)
```
### Test cases
```
let f =
a=>a.map((s,i)=>[...s].sort(_=>i&1).join``)
console.log(f(["Here are some lines","of text for you","to make a","boustrophedon"]))
console.log(f(["My boustrophedon"]))
console.log(f([]))
```
Or [Try it online!](https://tio.run/##hYxBCsMgEEX3PYW4KAqp0AOYdTc9QQiJTcbWJDrimNKc3rruposPj8fjL@ZtaEou5gtFN0PyGFY4itXF6NYob6IQ1Dip204pRb0iTFkMunXnq1QLujCOskwYCDdQGz6FFR2/QQJm6gg9sM0FIN5wtCzDJzOLiR24V5ORebPWtPIDd8oJ4wtmDLyX8vT7ej/Y36iq8gU "JavaScript (SpiderMonkey) – Try It Online") (SpiderMonkey)
---
# JavaScript (ES6), 45 bytes
```
a=>a.map(s=>(a^=1)?s:[...s].reverse().join``)
```
### Test cases
```
let f =
a=>a.map(s=>(a^=1)?s:[...s].reverse().join``)
console.log(f(["Here are some lines","of text for you","to make a","boustrophedon"]))
console.log(f(["My boustrophedon"]))
console.log(f([]))
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 bytes
```
⌽¨@{2|⍳≢⍵}
```
Works both ways:
[Try it online!](https://tio.run/##Fcs9DsIwDAXgnVN4y8TCCRi5RkqctjSJQ5JCw8@KhEQlzsDEjhhZOEouUszgT096z9KbucrSUD1Nulzu5fb5PpfHxamMr3J9lPF95kLIai1AKNRs3bTspjOsdcT6bWBj6tndfmDzQcy0WGFAkHyRLIJpHUbuSEPCIYGmAJn@P4nAyo6nnCvqYwrkG1TkxA8 "APL (Dyalog Unicode) – Try It Online") with `⎕IO←1`
[Try it online!](https://tio.run/##Fcs9DsIwDAXgnVN4y4SEOAEjTJwhpU5bmtYlSUvDz4qERBELF2BiR4wsHCUXCWbwpye9Z9noceqlpiyG632xDKfbJCo2XD7f52w/PYThFc6PMLyPMSohk5UAkaJis7xg16Vmq5rYZmNY61q22/as34mREnM0CJLPUoWgixotd6TAYe9AkQFP/x9HUMmSp5wTaq0z1OSYUi1@ "APL (Dyalog Unicode) – Try It Online") with `⎕IO←0`
### How it works:
```
⌽¨@{2|⍳≢⍵} ⍝ tacit prefix fn
{ ≢⍵} ⍝ Length of the input
⍳ ⍝ generate indexes from 1 (or 0 with ⎕IO←0)
2| ⍝ mod 2; this generates a boolean vector of 0s (falsy) and 1s (truthy)
@ ⍝ apply to the truthy indexes...
⌽¨ ⍝ reverse each element
```
[Answer]
# Perl 5, 17 + 2 (-pl) = 19 bytes
odd lines reversed
```
$_=reverse if$.%2
```
even lines reversed
```
$_=reverse if$|--
```
After @Martin's comment : input needs to have a trailing linefeed.
[try it online](https://tio.run/##K0gtyjH9/18l3rYotSy1qDhVITNNRU/V6P//xCSu5BQurvQMrn/5BSWZ@XnF/3ULcgA)
[Answer]
# [Haskell](https://www.haskell.org/), 27 bytes
```
foldr((.map reverse).(:))[]
```
[Try it online!](https://tio.run/##dYxNDsIgFIT3nmLCChLtAUy6d9MTVBbYPmxTyiNAjb28SN07ySzmJ99k0kLOFdvei2U3Rimb1QREelFMpBp5VarXZTWzR4s6dZAhzj6jgVUnVPXoxY0iwVQnXglu9pTEGYItMr0zLEfsvB1V5kpZ6vkID95SjhwmGtkL/cOdK67b8WfS0OUzWGeeqVyGEL4 "Haskell – Try It Online")
## [Haskell](https://www.haskell.org/), 30 bytes
```
f(a:b:c)=a:reverse b:f c
f a=a
```
[Try it online!](https://tio.run/##dYxNCoMwFIT3nmLISkF6gED23XgCcfG0LyiavJDEUk@fxu47MIv54Vsp7XwcpdiW9KyXzpCO/OaYGLO2WBoLMlQcbR4GjsKANsTNZzxguwZVI0b15Mig6iSOcWyek@qhxCLzJ8NKxCXnXWWplL2e7zDLmXKUsPJLvJp@uL7ihgt/pglT@QI "Haskell – Try It Online")
Recursion FTW.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5~~ 4 bytes
```
εNFR
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3FY/t6D//6OVPFKLUhUSgbg4PzdVISczL7VYSUcpP02hJLWiRCEtv0ihMr8UKFKSr5CbmA1UCmQn5ZcWlxTlF2SkpuTnKcUCAA "05AB1E – Try It Online")
**Explanation**
```
ε # apply to each element (row)
NF # index times do:
R # reverse
```
[Answer]
# [R](https://www.r-project.org/), 85 bytes
```
for(i in seq(l<-strsplit(readLines(),"")))cat("if"(i%%2,`(`,rev)(l[[i]]),"\n",sep="")
```
[Try it online!](https://tio.run/##Fc1BCsIwEIXhfU8xBAoTSDeu9QbeoBYa7YQOppk6SUVPH@Pi7T7er7UGUWTgBJleGM9DLpr3yAWV/HLlRBmtM8Za@/AFDQeD3PcnN@PslN4W4zjyNDVzS8Zl2i8N15WUwLdl2Qji/6aTAIU@BVoRvnJ0RWDzz8bgLkfLyr7SIqn@AA "R – Try It Online")
Input from stdin and output to stdout.
Each line must be terminated by a linefeed/carriage return/CRLF, and it prints with a corresponding newline. So, inputs need to have a trailing linefeed.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~17~~ 14 bytes
**Solution:**
```
@[;&2!!#x;|]x:
```
[Try it online!](https://tio.run/##y9bNz/7/3yHaWs1IUVG5wromtsJKQ8kjtShVIRGIi/NzUxVyMvNSi5WslfLTFEpSK0oU0vKLFCrzS4EiJfkKuYnZQKVAdlJ@aXFJUX5BRmpKfp6S5v//AA "K (oK) – Try It Online")
**Example:**
```
@[;&2!!#x;|]x:("this is";"my example";"of the";"solution")
("this is"
"elpmaxe ym"
"of the"
"noitulos")
```
**Explanation:**
Apply `reverse` at odd indices of the input list:
```
@[;&2!!#x;|]x: / the solution
x: / store input as variable x
@[; ; ] / apply @[variable;indices;function] (projection)
| / reverse
#x / count (length) of x, e.g. 4
! / til, !4 => 0 1 2 3
2! / mod 2, 0 1 2 3 => 0 1 0 1
& / where true, 0 1 0 1 => 1 3
```
**Notes:**
* switched out `&(#x)#0 1` for `&2!!#x` to save 3 bytes
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 12 bytes
```
⍳∘≢{⌽⍣⍺⊢⍵}¨⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHvZsfdcx41Lmo@lHP3ke9ix/17nrUtehR79baQyuAjP//H/WuSlNQ90gtSlVIBOLi/NxUhZzMvNRidQX1/DSFktSKEoW0/CKFyvxSoEhJvkJuYjZQKZCdlF9aXFKUX5CRmpKfp86lrq2trc4FNu5RV5N6YlIyqljvGgA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~40~~ 36 bytes
*-4 bytes thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)*
```
def f(k):k[::2]=map(reversed,k[::2])
```
[Try it online!](https://tio.run/##JY2xCsQgEAX7fMViE4VwRUoh/f1DSGFwJZ7RFTVy@XrPcMWDxzAw8S4Hhbk1jQYMd0K6Vcp5W7yKPGHFlFFPfyaagwVW9saEoPoyeYTTBsxsYmSg4LeAoQQ3XZ0UAq9cV/vf6colUTxQU2Db8KSGmGwo8JRO5XetoMpxfH3IBn7aXHgVYgIn2g8 "Python 2 – Try It Online")
Outputs by modifying the input list
---
# [Python 2](https://docs.python.org/2/), 43 bytes
```
f=lambda k,d=1:k and[k[0][::d]]+f(k[1:],-d)
```
[Try it online!](https://tio.run/##DYpBCsMgEADvfcXiKaEWmh4F7/2DeDDsSsJGV4yB5vXWw8AwTLnbJvnTe7RHSCsGYI12MQwho2P39s4Y9P4ZJ3aL8fqFc2ew4NSXKkEYnJIIjj3TqbSSCI1@DaJUuOUapQmkwGMdvsp1tiplI5Ss/KPUPY934rn/AQ "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 bytes
```
U¹ƭ€
```
[Try it online!](https://tio.run/##y0rNyan8/z/00M5jax81rfl/uD3y//9oJY/UolSFRCAuzs9NVcjJzEstVtJRyk9TKEmtKFFIyy9SqMwvBYqU5CvkJmYDlQLZSfmlxSVF@QUZqSn5eUqxAA "Jelly – Try It Online")
Thanks *HyperNeutrino* for -1 bytes! (actually because I never knew how `ƭ` works due to lack of documentation, this time I got lucky)
[Answer]
# [Alumin](https://github.com/ConorOBrien-Foxx/Alumin), 66 bytes
```
hdqqkiddzhceyhhhhhdaeuzepkrlhcwdqkkrhzpkzerlhcwqopshhhhhdaosyhapzw
```
[Try it online!](https://tio.run/##LYpbCsAgDMD@vc1eByrWUek2qyJiL98xWT4CgcDV7viYEebMEVHJh0EfCKFpEC4X@Y6ZuZAKa5idk9T/SnUQiHYzqHi6Zd12N328 "Alumin – Try It Online")
```
FLAG: h
hq
CONSUME A LINE
qk
iddzhceyhhhhhdaeuze
pk
rlhcw
REVERSE STACK CONDITIONALLY
dqkkrhzpkzerlhcwqops
OUTPUT A NEWLINE
hhhhhdao
syhapzw
```
[Answer]
# [J](http://jsoftware.com/), 9 bytes
```
(,|.&.>)/
```
Reduce from right to left, reversing all strings in the result and prepending the next string as is.
[Try it online!](https://tio.run/##hY29CsJAEIT7fYqpjAE5wVZjbRErH0AuZo9Eza3cjxjw3c@LxNqBgWEY5rumZCqF5eqtFmpfrhNfOgE/2Y0w2G3VeQMr0aJl01umAzuGzvYyMO658iQGgV8BRhxGiRQEg77lGTUSfXDy6LgVSyV9z4tqVkF/YKeJMV0THcX9ItXaBzR9wAymMn0A)
We can do **6** using [ngn’s approach](https://codegolf.stackexchange.com/a/150153/74681), but there will be extra spaces:
```
]&|./\
```
[Try it online!](https://tio.run/##dY0xC8IwFIT39ytusnSJ4CrdHXRytUhqX2jV5pXkBRT87zEVHT04OI7ju2vOrjFoVy@zPmW@DAKHdmvOG3hJHj270TPtODBscZSJcS9VJHFQfiicBDwlkQomeysz6iRFDTIP3Iunmj7YqllU0d@P44JeiEQHCb9IexsV3aj4/lGd3w)
[Answer]
# T-SQL, 65 bytes
Our standard input rules allow SQL to [input values from a pre-existing table](https://codegolf.meta.stackexchange.com/a/5341/70172), and since SQL is inherently unordered, the table must have row numbers to preserve the original text order.
I've defined the table with an identity column so we can simply insert lines of text sequentially (not counted toward byte total):
```
CREATE TABLE t
(i int identity(1,1)
,a varchar(999))
```
So to select and reverse alternating rows:
```
SELECT CASE WHEN i%2=0THEN a
ELSE reverse(a)END
FROM t
ORDER BY i
```
Note that I can save 11 bytes by excluding the `ORDER BY i`, and that is *likely* to return the list in the original order for any reasonable length (it certainly does for the 4-line example). But SQL only *guarantees* it if you include the `ORDER BY`, so if we had, say, 10,000 rows, we would definitely need this.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 4 bytes
```
òjæ$
```
[Try it online!](https://tio.run/##K/v///CmrMPLVP7/T0xKTuFKTUvP4MrMys7hys3LLwAA "V – Try It Online")
```
ò ' <M-r>ecursively (Until breaking)
j ' Move down (breaks when we can't move down any more)
æ$ ' <M-f>lip the line to the end$
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 44 bytes
```
lines.map: ->\a,$b?{a.put;.flip.put with $b}
```
[Try it](https://tio.run/##HYuxDgIhEAV7vuIVVyrlFV6irR9hs@iSI8ItgeXUGL8dT4tJppjJXOLYW2Wso71OPYaFq02UD9gfL7Qb3OlNNjedrI8h/wyPoDMG9@n9zIVBG1US4/8a8VB@KrwUvKQZFSS6b5lx0qoWyTPfZDFf "Perl 6 – Try It Online")
```
lines # get the input as a list of lines
.map:
-> \a, $b? { # $b is optional (needed if there is an odd number of lines)
a.put; # just print with trailing newline
.flip.put with $b # if $b is defined, flip it and print with trailing newline
}
```
[Answer]
Comma delimited:
# [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü«äì╠▒╕█╬pεû
```
[Run and debug it](https://staxlang.xyz/#p=81ae848dccb1b8dbce70ee96&i=ABC,def,GHI,jkl,MNO,pqr,STU&a=1&m=1)
input: ABC,def,GHI,jkl,MNO,pqr,STU
Newline delimited:
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Çε÷┘)¼M@
```
[Run and debug it](https://staxlang.xyz/#p=80eef6d929ac4d40&i=ABC%0Adef%0AGHI%0Ajkl%0AMNO%0Apqr%0ASTU&a=1&m=1)
input:
```
ABC
def
GHI
jkl
MNO
pqr
STU
```
output for both:
```
CBA
def
IHG
jkl
ONM
pqr
UTS
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes
```
i↔ⁱ⁾
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6kUFCUn1KanFpsxaX0cFen/aO2DY@amh5uW1D3cGc7UODhjm1Asvbh1gn/Mx@1TXnUuPFR477//6OjlTxSi1IVEoG4OD83VSEnMy@1WElHKT9NoSS1okQhLb9IoTK/FChSkq@Qm5gNVApkJ@WXFpcU5RdkpKbk5ynF6kQr@VYqYAiCxINBhoJMAuoCIt/8ImQuEPkkFpcoJGWWKEBtVIqNBQA "Brachylog – Try It Online")
Doesn't feel *entirely* honest to call this [generator](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) a 4-byter considering it costs 3 more bytes to [actually use it](https://codegolf.stackexchange.com/a/210297/85334).
```
i Take an element from the input paired with its 0-index,
↔ ⁾ and reverse the element
ⁱ repeatedly
⁾ a number of times equal to the index.
```
[Answer]
# [Pyth](https://pyg.readthedocs.io), 6 bytes
```
.e@_Bb
```
**[Try it here!](https://pyth.herokuapp.com/?code=.e%40_Bb&input=%5B%22Here+are+some+lines%22%2C%22of+text+for+you%22%2C%22to+make+a%22%2C%22boustrophedon%22%5D&debug=0)**
* `.e` ~ Enumerated map. `k` is the index, `b` is the current element.
* `_Bb` ~ Bifurcate `b` with its reverse.
* `@` ~ Modular index in ^ with `k`.
[Answer]
# [Actually](https://github.com/Mego/Seriously), 7 bytes
```
;r'R*♀ƒ
```
Explanation:
```
;r'R*♀ƒ
;r range(len(input))
'R* repeat "R" n times for n in range
♀ƒ call each string as Actually code with the corresponding input element as input (reverse each input string a number of times equal to its index)
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/9@6SD1I69HMhmOT/v@PVvJILUpVSATi4vzcVIWczLzUYiUdpfw0hZLUihKFtPwihcr8UqBISb5CbmI2UCmQnZRfWlxSlF@QkZqSn6cUCwA "Actually – Try It Online")
[Answer]
## [Alice](https://github.com/m-ender/alice), 13 bytes
```
M%/RM\
d&\tO/
```
[Try it online!](https://tio.run/##DcoxDoAgDAXQ3VN00ZVruBATZxbUGonAN1ASPX1leNvzMeysakezWjcck5PFqOrMhcl3FYkphsxVcZLwK3Si0IemAkr@7k03tCoFz8UH8g8 "Alice – Try It Online")
Input via separate command-line arguments. Reverses the first line (and every other line after that).
### Explanation
```
At the beginning of each loop iteration there will always be zero
on top of the stack (potentially as a string, but it will be
converted to an integer implicitly once we need it).
M Push the number of remaining command-line arguments, M.
% Take the zero on top of the stack modulo M. This just gives zero as
long as there are arguments left, otherwise this terminates the
program due to the division by zero.
/ Switch to Ordinal mode.
t Tail. Implicitly converts the zero to a string and splits off the
last character. The purpose of this is to put an empty string below
the zero, which increases the stack depth by one.
M Retrieve the next command-line argument and push it as a string.
/ Switch back to Cardinal mode.
d Push the stack depth, D.
&\R Switch back to Ordinal mode and reverse the current line D times.
O Print the (possibly reversed) line with a trailing linefeed.
\ Switch back to Cardinal mode.
The instruction pointer loops around and the program starts over
from the beginning.
```
[Answer]
# [Tcl](http://tcl.tk/), 61 bytes
```
proc B L {lmap e $L {expr [incr i]%2?"$e":"[string rev $e]"}}
```
[Try it online!](https://tio.run/##dYwxDsIwEAR7XrGyzAcoaZBSUcALIhdJuICF47PODkpk@e3GHRXFSqPd1aTJ1RqEJ3S4IbtlCCDohrQFQW/9JLDmeLooTeqs@pjE@ieEPtBkVCk1rCmi75DzlYQwtEReCM56igWZZyTaEmYW7Ly2JjGW4d2ujUdem5LDix7sSzGHn@6@4/9aTP0C "Tcl – Try It Online")
[Answer]
# [Standard ML (MLton)](http://www.mlton.org/), 51 bytes
```
fun$(a::b::r)=a::implode(rev(explode b)):: $r| $e=e
```
[Try it online!](https://tio.run/##TY5NCsMgEEb3PcUgLhTaCwh23Tv0J5h0pKHqiJqQQO@eGrvpYpjH8L6Pyd6dvCsUts1OgQujVK9UkrrC6KOjJ4qEs8ClMfRSKgU8fYCjxm02DgrmAhqu7IIJwdTJ5BHcGDCzIyNbjaWApQQrTfVSCLx5V7VyT1MuieILnxTY/bAXxoSlrF1MY9iLf5tgoDCYHbyJIGyADPoM@cFugckW7Jr9Fxa8fSe3Lw "Standard ML (MLton) – Try It Online") Usage example: `$ ["abc","def","ghi"]` yields `["abc","fed","ghi"]`.
**Explanation:**
`$` is a function recursing over a list of strings. It takes two strings `a` and `b` from the list, keeps the first unchanged and reverses the second by transforming the string into a list of characters (`explode`), reversing the list (`rev`), and turning it back into a string (`implode`).
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 18 bytes
```
[{x i:x$revi*}map]
```
[Try it online!](https://tio.run/##DYrBCoMwEAXvfsU7CGn9BE8e@w@lh2g2GGzckF0lIv32NIeBYRhRu2zkan3fBWEsfaYzDL9o06dOo@8e5kWZYBvCkfANO4mBYQ@lovCccfHRijKi3drafOZDNHNayfFunvBwQVL9Aw "Stacked – Try It Online")
This simply reverses each string in the array according to its position.
## Alternative, 24 bytes
```
[:#':>#,tr[...$rev*]map]
```
Same approach, but generates indices manually.
[Answer]
# [Python 2](https://docs.python.org/2/), 45 bytes
```
lambda k:[r[::i%-2|1]for i,r in enumerate(k)]
```
[Try it online!](https://tio.run/##FYxBCsMgEEWvMggFhXTRLIXuewfrwpCRiNERHaGB3t3axYPP4/PKxQfldfjne5wubbuDqE01Wofbff0@rKcKYZlkwNwTVscoo7Kj1JBZemnECyuCmzRKCGfI2MQiyAPjh@EfuKhPwwTJxXmde6PeuFI5cKcsrFLjBw "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 46 bytes
```
f=lambda k:k and[k[0][::len(k)%-2|1]]+f(k[1:])
```
[Try it online!](https://tio.run/##DYrLCsMgEAB/ZREKSltochR67z@IB4MrCT5WdAMN9N@th4FhmHrxTmUdI7yTy5t3EHUEV7yJ5mWN1gmLjOr2XH@Ltfcgo1m0VaO2o7AM0ogPNgQ36ZQR0lGwi4egAIxfhkANLjpnYYLs4lynb3R2blR39FSEVWr8AQ "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
UJḤ$¦
```
[Try it online!](https://tio.run/##y0rNyan8/z/U6@GOJSqHlv0/3H500sOdM/7/j1bySC1KVUgE4uL83FSFnMy81GIlHaX8NIWS1IoShbT8IoXK/FKgSEm@Qm5iNlApkJ2UX1pcUpRfkJGakp@nFAsA "Jelly – Try It Online")\*
*\*Jelly outputs nested lists joined by spaces, and there is no native string type. Strings in Jelly are lists of characters, and that's why they're displayed that way. If you want them to be merged by spaces, [Try this](https://tio.run/##y0rNyan8/z/U6@GOJSqHlv0/3O79/3@0kkdqUapCIhAX5@emKuRk5qUWK@ko5acplKRWlCik5RcpVOaXAkVK8hVyE7OBSoHspPzS4pKi/IKM1JT8PKVYAA).*
[Answer]
# [Retina](https://github.com/m-ender/retina), 18 bytes
```
{O$^`\G.
*2G`
2A`
```
[Try it online!](https://tio.run/##K0otycxL/P@/2l8lLiHGXY@LS8vIPYHLyDHh/3@P1KJUhUQgLs7PTVXIycxLLebKT1MoSa0oUUjLL1KozC/lKslXyE3MBirjSsovLS4pyi/ISE3JzwMA "Retina – Try It Online") Explanation: The first stage reverse the first line, then the second stage prints the first two lines, after which the third stage deletes them. The whole program then repeats until there is nothing left. One trailing newline could be removed at a cost of a leading `;`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes
```
Fold[StringReverse@*Append,{},#]&
```
[Try it online!](https://tio.run/##DYpBCsIwEEWvMkRwITlE3YhL0WXpIppfG2wyYTItSunZYxYf3nv86HRCdBpert4kJO3rhWffP7TJ@44VUtCdzjkjebvt9jAcK3W0mSsE5NoKR9AcEoqxhkdSfJVGFvrx0ooyRfdp18ZPXooK5wmek9mH@gc "Wolfram Language (Mathematica) – Try It Online")
## How it works
`StringReverse@*Append`, when given a list of strings and another string as input, adds the string to the end of the list and then reverses all of the strings.
`Fold`ing the input with respect to the above means we:
* Reverse the first line.
* Add the second line to the end and reverse both of them.
* Add the third line to the end and reverse all three.
* Add the fourth line to the end and reverse all four.
* And so on, until we run out of lines.
Each line gets reversed one time fewer than the previous line, so the lines alternate direction.
] |
[Question]
[
Write a cat program, a quine, and a Hello World in the same language such that when two specific programs of the three are concatenated in a certain order, you get the third program. It does not matter which program is the first, second, and third are as long as all three types are represented once each.
e.g. if \$A\$ is a cat and \$B\$ is a quine then \$AB\$ is Hello World. Alternatively, if \$A\$ is Hello World and \$B\$ is a cat then \$AB\$ is a quine. You only need to make *one permutation* of the possible 6 work.
For completeness of explanation:
* A cat program outputs the input exactly
* A quine is a program that outputs its own source code
* A hello world program outputs the string "Hello World!"
## Rules, Scoring, Formatting
* Shortest code wins. Scoring goes by the length of the concatenated program, i.e. the longest of the three.
* Standard rules and loopholes apply.
* The hello world program and quine might possibly receive input. You must output the appropriate text regardless of what is given as input.
* Programs may output a trailing newline.
* You can treat all three programs as if they are surrounded by your language's function closure (please specify the name of your implicit argument in this case) or `main` function boilerplate if that is required for your solution to work. Use the same convention for all three programs. The quine should not contain the boilerplate in this case.
Format the header of your answer like this:
>
> <first type> + <second type> = <third type>, <language>, <score>
>
>
>
or
>
> <language>, <first type> + <second type> = <third type>, <score>
>
>
>
[Answer]
# [Python 3](https://docs.python.org/3.8/), Hello World + Quine = Cat, 129 bytes
### [Hello World](https://tio.run/##HczBCsIwDADQe74i7pTAGAMvInj3DzyOwqIGahvSDPTrq@7@ePaJZy3Hk3nv@rLqgbWNKeStgalhAruYawlIk8tDW4iTjcNVcq54q57Xw8Cwyh13RgufAY202BbEDL9uWv4bzdz7Fw "Python 3.8 (pre-release) – Try It Online"):
```
import os,atexit as a
p=print
a.register(p,"Hello World!")
def print(_):
p(input())
os._exit(0)
```
### [Quine:](https://tio.run/##K6gsycjPM7YoKPr/v9hWvdhWtci6oCgzr0SjWFW1WFMdzinW/P8fAA "Python 3.8 (pre-release) – Try It Online")
```
s='s=%r;print(s%%s)';print(s%s)
```
### [Cat](https://tio.run/##PcxNCsIwEEDh/ZxiLIRmoBTBjSjZewOXJdCogdgMM1PQ08c/cPng4/HTbnXZ7Vlay3euYlh1iJYe2TAqRuDAkheDOEq6ZrUknofulEqpeK5S5k1HMKcLfpmf6ADIPi@8mieC926cPje/JdDQa3By/FF1Tqn/h1JrltRe "Python 3.8 (pre-release) – Try It Online"):
```
import os,atexit as a
p=print
a.register(p,"Hello World!")
def print(_):
p(input())
os._exit(0)
s='s=%r;print(s%%s)';print(s%s)
```
`atexit` lets you define cleanup steps that will run when your program exits "normally". In this case, I register the `print` function (renamed `p`) with the argument `"Hello World!"`, so it will print that string when the program ends.
I then redefine `print` to become a `cat` function. Normally, this would cause the program to print its input *and* "Hello World!", but `os._exit()` is an "abnormal" exit that bypasses the cleanup steps.
Now that `print` has been redefined, the Quine simply calls this `cat` function and the program abruptly exits. If the Quine doesn't exist, then the program exits normally, printing "Hello World!" in the process.
The final program doesn't work on TIO, but it works for me running Python 3.7.3 on MacOS.
[Answer]
# Bash, Quine + Cat = Hello World, 110 bytes
## [Quine](https://tio.run/##S0oszvj/v9BWPbUsMUehoCgzryRNQUmlWAlMqFsX26oX2saYmGOVBooDFQBJ1WIQU6VQHYj//wcA)
```
q='eval printf "$s" "$s"';s='q=\47eval printf "$s" "$s"\47;s=\47%s\47;$q';$q
```
## [Cat](https://tio.run/##S0oszvj/v6SoNFUhLTGnOFVNLTmxpKYmNTkjX8EjNScnXyE8vygnRfH//4zE4pQ0CE6DMQE)
```
true false&&cat||echo Hello World!
```
## [Hello World](https://tio.run/##S0oszvj/v9BWPbUsMUehoCgzryRNQUmlWAlMqFsX26oX2saYmGOVBooDFQBJ1WIQU6VQHYhLikpTFdISc4pT1dSSE0tqalKTM/IVPFJzcvIVwvOLclIU///PSCxOSYPgNBgTAA)
```
q='eval printf "$s" "$s"';s='q=\47eval printf "$s" "$s"\47;s=\47%s\47;$q';$qtrue false&&cat||echo Hello World!
```
This takes advantage of the fact that undefined variables expand to the empty string and that `true` is a command that can take arguments.
You can trivially swap the cat and the hello world by swapping `true` and `false`
[Answer]
# [R](https://www.r-project.org/), Quine + hello, world = cat; ~~48 + 49~~ ... 43 + 44 = 87 bytes
Or **[75 bytes](https://tio.run/##lY9BC4IwGIbv@xVrFzeY0V0UQogOXqQdAzVbMRhbuFlK2F9fUy8JQXT8no/3eb@vcULdhREnyfGhN2vDrdR15ae6svyqmx7GEGVpsc0yROG8G1GKCAEgrWx8aVVthVa4I08XhAmLfBSbvNWWY0YoIwH8Rl@7MOmjUlxKzJINRXsupYYP3cjzCtGOuAHkrVB8UQD@KAADmJzF5FxqfpX77PgcRkLdWovIfAomYCxBR@XJh9tz9wY)** as internal code of functions and not including `function(){}` wrappers.
*Edit: -14 bytes thanks to Robin Ryder!*
Nontrivial quine:
```
'->T;cat(sQuote(T),T)' ->T;cat(sQuote(T),T)
```
[Try it online!](https://tio.run/##K/qfmVeWWZyZlJOqEVxZrFecWpKTn5wI5CUnlqSm5xdVKtgqKPk4xzv6@CjpKEDkQELOSpqa/9V17UKsgQo1igNL80tSNUI0dUI01RWwif7n@g8A "R – Try It Online")
Hello,world:
```
~F->y;cat(`if`(T>0,"Hello world!",scan(,T)))
```
[Try it online!](https://tio.run/##K/qfmVeWWZyZlJOqEVxZrFecWpKTn5wI5CUnlqSm5xdVKtgqKPk4xzv6@CjpKEDkQELOSpqa/@vcdO0qrYEqNRIy0xI0QuwMdJQ8UnNy8hXK84tyUhSVdIqTE/M0dEI0gYq5/gMA "R – Try It Online")
Cat:
```
'->T;cat(sQuote(T),T)' ->T;cat(sQuote(T),T)~F->y;cat(`if`(T>0,"Hello world!",scan(,T)))
```
[Try it online!](https://tio.run/##K/qfmVeWWZyZlJOqEVxZrFecWpKTn5wI5CUnlqSm5xdVKtgqKPk4xzv6@CjpKEDkQELOSpqa/9V17UKsgQo1igNL80tSNUI0dUI01RWwida56dpVgkUTMtMSNELsDHSUPFJzcvIVyvOLclIUlXSKkxPzNIAqgeZm5hWUlnD9BwA "R – Try It Online")
A 'trivial quine' version could be Quine = `~1`, and Hello, world = `+F->y;cat(`if`(y<0,scan(,''),'Hello world!'))`, for **2+45=47 bytes**.
**How? (nontrivial & trivial versions)**
The default behaviour of [R](https://www.r-project.org/) is to output any unassigned values (such as variables or expressions). So, to print a quine, we simply need to generate an expression containing the program code, and it is output by default (this applies both to the nontrivial quine, which is contructed using `cat` to join the various text elements together, as well as the trivial quine `~1` consisting simply of a formula which is outputted)
If a value is assigned to a variable, it is not output. So to stop the quines from printing, we incorporate them into an expression and assign this to the variable `y`.
To do this, we need to use a binary operator, but since this operator will also appear at the start of the 'Hello, world' program, it must also function as a unary operator. Both the `~` (formula) and `+` (positive/sum) operators have this property.
Conveniently, [R](https://www.r-project.org/) also includes a (little used outside coding challenges) left-to-right assignment operator, `->`, which - together with a unary/binary operator - lets us package the quine into the variable `y` & forget about it. Then all we need to do is to determine whether this has happened or not, and use this to switch between 'Hello, world' and 'cat' behaviour.
[Answer]
# Quine + Cat = Hello World, [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes
*-2 bytes thanks to @Jonathan Allan*
### Quine (12 bytes)
```
“Ṿṭ⁷;⁾v`”v`
```
(starts with a newline)
[Try it online!](https://tio.run/##y0rNyan8/5/rUcOchzv3Pdy59lHjdutHjfvKEh41zC1L@P//v5KSkqGRsYlOYlIykAkA)
### Cat (13 bytes)
```
Ṇ
“,ḷṅḳȦ»³ÑƑ?
```
[Try it online!](https://tio.run/##ATIAzf9qZWxsef//4bmGCuKAnCzhuLfhuYXhuLPIpsK7wrPDkcaRP////yIxMjM0LCdhYmMnIg) (argument quoted to avoid casting to a Python object from string as per @Jonathan Allan's suggestion)
### Hello World (25 bytes)
```
“Ṿṭ⁷;⁾v`”v`Ṇ
“,ḷṅḳȦ»³ÑƑ?
```
(starts with a newline)
[Try it online!](https://tio.run/##AUoAtf9qZWxsef//CuKAnOG5vuG5reKBtzvigb52YOKAnXZg4bmGCuKAnCzhuLfhuYXhuLPIpsK7wrPDkcaRP////yIxMjM0LCdhYmMnIg)
## How it Works
In Jelly, the last link (last line) is always executed as the main link. The Cat and Hello World have the same last link, so they are differentiated by the value of the first link (blank (identity) or `Ṇ` (logical not)).
```
“,ḷṅḳȦ»³ÑƑ?
? # If
ÑƑ # The first link is the identity
“,ḷṅḳȦ» # Return "Hello World!" (String Compressor: https://codegolf.stackexchange.com/a/151721/68261)
# Else
³ # Return the input
```
The quine is slightly difficult because it needs to prepend a blank line.
```
“Ṿṭ⁷;⁾v`”v`
“Ṿṭ⁷;⁾v`” # Set the string "Ṿṭ⁷;⁾v`"
v` # Eval it on itself:
Ṿṭ⁷;⁾v`
Ṿ # Uneval: "“Ṿṭ⁷;⁾v`”"
ṭ⁷ # Prepend a newline "¶“Ṿṭ⁷;⁾v`”"
;⁾v` # Concatenate "v`" to get "¶“Ṿṭ⁷;⁾v`”v`"
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), Quine + Cat = Hello World, ~~15+28=43~~ 15 + 22 = 37 bytes
3 functions.
### Quine
```
ToString[#0] &
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyQ/uKQoMy89WtkgVkFN4X8AkFPikOagVFiamZeq9B8A "Wolfram Language (Mathematica) – Try It Online")
### Cat
```
#/.#_:>"Hello World!"&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1lfTzneyk7JIzUnJ18hPL8oJ0VRSe1/QFFmXolDmoNScmKJ0n8A "Wolfram Language (Mathematica) – Try It Online")
### Hello World
```
ToString[#0] & #/.#_:>"Hello World!"&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyQ/uKQoMy89WtkgVkFNQVlfTzneyk7JIzUnJ18hPL8oJ0VRSe1/AFBJiUOag1IGWLwcJK70HwA "Wolfram Language (Mathematica) – Try It Online")
---
### ~~HW+Q=C,46+58=104 Q+C=HW,43+48=91~~ Cat + Quine = Hello World, 49 + 37 = 86 bytes
**Cat**
```
Print[#/._@_->"Hello World!"]&@$ScriptInputString
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z@gKDOvJFpZXy/eIV7XTskjNScnXyE8vygnRVEpVs1BJTi5KLOgxDOvoLQkuASoNv3//@TEEgA "Wolfram Language (Mathematica) – Try It Online")
**Quine**
```
Print[ToString[#0, InputForm][]] & []
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z@gKDOvJDokP7gEyEiPVjbQUfDMKygtccsvyo2Njo1VUFOIjv3/v7A0My8VAA "Wolfram Language (Mathematica) – Try It Online")
**Hello World**
```
Print[#/._@_->"Hello World!"]&@$ScriptInputStringPrint[ToString[#0, InputForm][]] & []
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z@gKDOvJFpZXy/eIV7XTskjNScnXyE8vygnRVEpVs1BJTi5KLOgxDOvoLQkuASoNh2iISQfwotWNtBRAMu65RflxkbHxiqoKUTH/v@fATaoHGQQAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org/), Quine + Cat = Hello, world! (106 + 2 = 108 bytes)
### Quine (~~108~~ 106 bytes):
-2 bytes: removed ',' from "Hello world!"
```
let s=format!("Hello world!");format!("{},{0:?})","let s=format!(\"Hello world!\");format!(\"{},{0:?})\"")
```
`.into()` instead of `format!` saves a few bytes but is context-dependent.
### Cat (2 bytes):
```
;s
```
### Quine + Cat = Hello, world! (~~110~~ 108 bytes):
```
let s=format!("Hello world!");format!("{},{0:?})","let s=format!(\"Hello world!\");format!(\"{},{0:?})\"");s
```
[Try it!](https://tio.run/##xZHBTsMwDIbveQrPB0ikwDi3MG4VRySuvYQt3SKlyUhcTajrs5e0Qy1jHLjNp9@OP@uPHZpIfV85qJVxXEDLIAXpSHxUQ@BaEcopPcZjasvjVOhGJfK/0I/GOH0BW00QnyofakULji/aWg8HH@xmgSKf6m0n24fsuRMo8Rwpz5jyB1TOVIko/mVyN8@6otXLjbKOsXSawe1jseJO1TqDm9tIiswaIgUJVQaFYIedDnpkipQ7/kbBuK2AuxWcJDvddZ80WZf8vga/DarOoO1QwjD5ezVzy/hScTRu3xDep7LnQvxuEzksl5C@BEGrjXo31tBnMt73Xw)
Updated to not use `include_str!`. Hopefully this doesn't break any rules anymore.
This relies on it being in a closure/function that implements `Fn(String) -> String` with argument `s`.
---
Old answer, uses `include_str!`:
### Quine (67 bytes):
```
match include_str!("f"){p@_ if p.len()==67=>p,_=>"Hello, world!"}//
```
(Not very creative, unfortunately)
### Cat (1 byte):
```
s
```
### Quine + Cat = Hello, world! (68 bytes):
```
match include_str!("f"){p@_ if p.len()==67=>p,_=>"Hello, world!"}//s
```
~~Try it! (Repl.it link due to multiple files)~~
This depends on the code being in its own file named "f" and being `include!`'d into main.rs before being executed. The Repl.it link has the programs in separate files with different names, which means that the quine and hello world programs are different by one character so that they include the correct string.
~~This challenge was especially difficult in Rust (without using a comment at the end of one of the programs) because of the syntax of the language. Functions and multi-statement closures have braces surrounding them, so you can't just concat two closures to get a third, unfortunately.~~
[Answer]
# [Python 2](https://docs.python.org/2/), Hello World + Cat = Quine, 200 198 189 bytes
## Hello World
```
id=0;a="Hello World!";a0='id=0;a="%s";a0=%r;print a0%%((a,a0)if id<1else 1)\nimport sys\nif id:print sys.stdin.read()';print a
```
## Cat
```
0%((a,a0)if id<1else 1)
import sys
if id:print sys.stdin.read()
```
My previous answer was actually wrong. `raw_input` only reads one line. This reads the entire input.
## Quine
```
id=0;a="Hello World!";a0='id=0;a="%s";a0=%r;print a0%%((a,a0)if id<1else 1)\nimport sys\nif id:print sys.stdin.read()';print a0%((a,a0)if id<1else 1)
import sys
if id:print sys.stdin.read()
```
[Try it online!](https://tio.run/##fc7BCsIwDAbge58iDspakNF5dPbuG3jxEmjFQE1LW5E9/ayK7CLekvz8H0lzvUbeLQs5aya03dGHEOEUc3CbbkJj@28iy3uXeUqZuAIaKZXCLRpNFyB3GH0oHkZ9ZrqlmCuUubT5le0/lXYYSnXEQ/bolO5X6qckVkj8c9r7nO7NKfDIVKtnwSkyiyc "Python 2 – Try It Online")
---
*2020-08-05: -42 bytes thanks to Jonathan Allen, +33 to fix a bug*
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), Hello World + Quine = Cat, 26 bytes
```
«H%c¡|,!«``:[④|᠀,]`:[④|᠀,]
```
[Try it online!](https://tio.run/##y05N////0GoP1eRDC2t0FA@tTkiwin40cXHNwwUNOrHI7P//iwE "Keg – Try It Online")
## How it Works
### Hello World
```
«H%c¡|,!«`
```
[Try it online!](https://tio.run/##y05N////0GoP1eRDC2t0FA@tTvj/HwA "Keg – Try It Online")
This is my answer to the HW challenge with some additional string closing syntax. Why? Because a) the main string needs closing to be concatenated and b) the end ``` is needed to "ignore" the quine part
### Quine (non-trivial)
```
`:[④|᠀,]`:[④|᠀,]
```
[Try it online!](https://tio.run/##y05N//8/wSr60cTFNQ8XNOjEIrP//wcA "Keg – Try It Online")
```
`:[④|᠀,]`
```
Push the string `:[④|᠀,]` to the stack
```
:[④|᠀,]
```
Duplicate the string and start an if-block. The if block uses the truthiness of the t.o.s to determine which branch is to be executed. In this case, the string is truthy, so the `④` is executed (printing the string raw). Implicit output then prints the string nicely.
### Concatenation
```
«H%c¡|,!«``
```
Push the string `Hello, World!` followed by an empty string onto the stack.
```
:[④|᠀,]
```
Duplicate the top of the stack (an empty string) and start the if block. Empty strings are considered falsey, so the `᠀,` branch is executed. This takes input and prints it.
```
`:[④|᠀,]
```
Push the string `:[④|᠀,]` and don't do anything with it.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), Cat + Quine = Hello, ~~101 91~~ 89 bytes
## Cat (32 bytes)
```
a=id=""
while 1:a=input(a)+"\n";
```
[Try it online!](https://tio.run/##DcexDkAwEADQ3VdcOhGTWIQY/IeloWi0d5dzTePry9sev3oR9gNLKXb2@2xMlS8fHHTjf@SktW1as6KZSlnkTNGhPnCQwGYVWOgUG6uYgvrg0T2QSW5QIhj5Aw "Python 3.8 (pre-release) – Try It Online")
## Quine (57 bytes)
```
exec(s:='+input(id and"exec(s:=%r)"%s or"Hello World!")')
```
[Try it online!](https://tio.run/##NcgxDsIwDADAnVeYSFUbdWRBlRjY@EHnqDElwrEjxxHw@nTixis/ewlfrkV7xy9uU11u45y4NJtShMDR/XtQ74YKou6BRAKrKMWz86Pv/a57y8hW4SkKWzAoKruGfMqNLFFirPARfYOJwFIO "Python 3.8 (pre-release) – Try It Online")
## Hello World (89 bytes)
```
a=id=""
while 1:a=input(a)+"\n";exec(s:='+input(id and"exec(s:=%r)"%s or"Hello World!")')
```
[Try it online!](https://tio.run/##NcixDsIgEADQvV9xXtK0pJNxMRiGbv6Biwsp2BKBIwek@vVoYhzfS@@yUTydE7emlTMKsds35y0c5dcx1TJqMeE94sW@7DJmqYbp986Ajgb/3bPAPgMxXq33BDdibw4oBtHazGsNNpYMD2JYdIHEtLIOXai@OO@izbATP6EQgUwf "Python 3.8 (pre-release) – Try It Online")
## How it works:
For the cat program:
* `a=id=0` we assign `a` and `id` to the empty string. `id` is now evaluated as `False` (remember it for later)
* At the first loop of `while 1`: `a=input(a)+"\n"` will display `a` without a new line (so the empty string) and store in `a` the first line of the input plus a newline
* Then we loop again, displaying the input of the previous iteration until the program has written all the lines of the input and crash (`EOFError`)
For the quine program:
* The main structure of the quine is `exec(s:='print("exec(s:=%r)"%s)')`, a well known quine in python.
* We uses `input()` instead of `print()` to avoid the trailing new line
* the `+` at the start is here to make the program crash as soon as it finished printing to make sure the program ends.
* `id` is a python built-in. Because of that it is evaluated as `True` so `id and <code 1> or <code2>` will be equal to `<code 1>` (which contains the code for our quine to work).
For the hello world program:
* remember the cat program where we assigned `id` to the empty string?
* `id and <code 1> or <code2>` will now execute `<code2>` since `id` is now evaluated as `False`, resulting the printing of `Hello World!`
* The `+` crashes the program avoiding looping in the cat code again
## Old solution: cat (37) + quine (64) = hello (101 bytes)
Here is my old solution using triple quoted string and comments to "squeeze" the quine part and directly printing `"Hello World!"`. It uses some cool tricks with comments:
```
while p:=print:id or p(input());id="" # cat (37 bytes)
"";exec(s:='input(\'"";exec(s:=%r)\'%s)#"""-p("Hello World!")#') # quine (64 bytes)
while p:=print:id or p(input());id="""";exec(s:='input(\'"";exec(s:=%r)\'%s)#"""-p("Hello World!")#') # hello (101 bytes)
```
[Try it online!](https://tio.run/##TYwxDsIwDEV3TmFaVUkGJhYU1IGNG7B0qdrQWqSx5bgqnD5UYuGP7z19/uhM6XxhKWWbMQZg37JgUo8jkABbTLyqde6KY1vtu4Z3GGz2rfmZzvyxRlxnmuzqPTyxre4hRoIHSRyPlauNK@Um07qEpBme@//QK7DQJP1yWNaoGDGFDBvJC5QIPH8B "Python 3.8 (pre-release) – Try It Online")
Who said that comments were not usefull in codegolfing?
[Answer]
# [R](https://www.r-project.org/), Quine (~~74~~ 51 bytes) + Cat (~~77~~ 74 bytes) = [Hello world](https://tio.run/##dY2xCsIwFEV3vyJmaR68ip1LC1IoDlnE7LbGVAIhkSQqXfz1GK2r4z3nwPVJ24cO@mwUO85hE1Q0To55yTGqq/MzaQjl3WnHOUWyuA/qKEAqyravRbOtc8zC4e6iYj1gDwX5Z15V2c5fOuhpYKKtMNy8tnFiAn@hAMDFYpCjZUgpIN0rYxx5Om8u63wOaZXe) ~~151~~ 125 bytes
# [R](https://www.r-project.org/), Hello world (~~173~~ 174 bytes) + Cat (~~77~~ 74 bytes) = [Quine](https://tio.run/##K/qfmVeWWZyZlJOqEVxZrFecWpKTn5wI5CUnlqSm5xdVKtgqKPk4xzv6@CjpKEDkQELOSpqa/@sMde0qrUNs1WEM1WJroD6NhMy0BA03GwOd4uTEPA0dJSVNHSWP1JycfIXy/KKcFEWgXogOuOIQO0Od4oKizLySNI0QneLA0vySVI0QTU0diCwegzTV6W/lf67/AA) ~~250~~ 248 bytes
# [R](https://www.r-project.org/), Quine (~~74~~ 51 bytes) + Hello world (~~173~~ 174 bytes) = [Cat](https://tio.run/##jZCxCsIwEIZ3nyIGJDlIpZ21BSkEhy5idltrKoHQlCRVuvjqNVp1U9zu7vvufjg7qvainDpqSfeDWzrptamr0NWVl2djB5QiXOSHTVFghib2GOUYYCRRxlcijVdBpm7XGy8pB8aBoG/klkTZEAh5Fwv3dErVlJSvY@bqqqUMY2B4K7U26GqsPs1D3LTxkUWWMNdZ1fqGCvbKEABsoj8OAfk3Mnyn6/1svAM) ~~247~~ 225 bytes
**A set of Quine, Cat & Hello world from which any 2 can be combined to form the third.**
Not the shortest answer, but pleasingly symmetric.
**Quine (~~74~~ 51 bytes)**
```
'->F;T=0;cat(sQuote(F),F)' ->F;T=0;cat(sQuote(F),F)
```
[Try it online!](https://tio.run/##K/qfmVeWWZyZlJOqEVxZrFecWpKTn5wI5CUnlqSm5xdVKtgqKPk4xzv6@CjpKEDkQELOSpqa/9V17dysQ2wNrIGKNYoDS/NLUjXcNHXcNNUVcMn8/w8A "R – Try It Online")
**Cat (~~77~~ 74 bytes)**
```
~1->y;cat(`if`(T>1,sprintf(T,sQuote(T)),`if`(T,scan(,""),"Hello world!")))
```
[Try it online!](https://tio.run/##JY7BCsIwEER/Jea0C6vQs1iQXjzkIuZuY0wlEJqSTZVc/PUY6XHmPYZJ1c9vz/4RHNwKH9jlEK1pyZrsXjEVcRJSDfezUpLExv7VIBHrt9v35dhMGP00gu474iX5OU@gia9rzA40Im2U2JoZSEokeXEhRPGJKTx3bQnbjWXN9Qc "R – Try It Online")
**Hello world (~~173~~ 174 bytes)**
```
~1->y;T='~1->y;T=%s;cat(`if`(F<0,scan(,""),"Hello world!"))~1->y;cat(`if`(T>1,sprintf(T,sQuote(T)),`if`(T,scan(,""),"Hello world!")))';cat(`if`(F<0,scan(,""),"Hello world!"))
```
[Try it online!](https://tio.run/##K/qfmVeWWZyZlJOqEVxZrFecWpKTn5wI5CUnlqSm5xdVKtgqKPk4xzv6@CjpKEDkQELOSpqa/@sMde0qrUNs1WEM1WJroD6NhMy0BA03GwOd4uTEPA0dJSVNHSWP1JycfIXy/KKcFEWgXogOuOIQO0Od4oKizLySNI0QneLA0vySVI0QTU0diCwegzTVibXy/38A "R – Try It Online")
[Answer]
# [Aceto](https://github.com/aceto/aceto), quine (67) + cat (33) = Hello World (100 bytes\*)
(\*I counted one file including a final newline so that catting them together works as expected)
### [quine](https://codegolf.stackexchange.com/a/209076/21173) (made it for this challenge):
```
£"24«cs%55«3+cp24«2+cdpsdpsppn"24«cs%55«3+cp24«2+cdpsdpsppn
```
### cat:
```
X
n
p el
r"HlX
^^ oldnp
^Wor!"
```
---
The quine itself was the hardest part, due to the nature of having code on a Hilbert curve (The "Hello World", and cat programs are trivial compared to it). The solution of having the concatenated program do something else than the parts is simple in Aceto: Because the (longer-line) quine enforces a square size of an even power of two (64 = 2^6), and the cat program has, on its own, a square of size 8x8 (8 = 2^3, an odd power of two), the instruction pointer starts moving in a different direction.
[Answer]
# [Alice](https://github.com/m-ender/alice), Cat + Quine = Hello World, 51 bytes
**Cat:** (With trailing newline)
```
\ > "!dlroW olleH"d&O@
^/ v
# < i
```
[Try it online.](https://tio.run/##S8zJTE79/z9GwU5BQUkxJacoP1whPycn1UMpRc3fgUtBIU5foQxIKSvYKGRy/f@flp@flFgEAA)
Uses # to skip the redirect west and instead hit the redirect south into the i, which pushes the input as a string to the top of the stack. The instruction pointer then reflects off the top and bottom boundaries of the grid, hitting the o and @ from the Hello World program, causing it to output the top of the stack as a string and then terminate. The code requires a trailing newline, which I couldn't get to display here in the code block.
**Quine:**
```
"!<@O&9h.
```
[Try it online.](https://tio.run/##S8zJTE79/19J0cbBX80yQ@///7T8/KTEIgA)
Just a standard Alice quine.
**Hello World:**
```
\ > "!dlroW olleH"d&O@
^/ v
# < i
"!<@O&9h.
```
[Try it online.](https://tio.run/##S8zJTE79/z9GwU4hQUkxJacoP1whPycn1UMpJUHN34FLQSFOX6EMSCkr2Chkcikp2jj4q1lm6P3/n5afn5RYBAA)
The # is now used to skip the @ from the quine program, causing the instruction pointer to instead hit the redirect west, which passes through a mirror and hits two more redirects to hit a standard Alice Hello World program.
[Answer]
# Hello World + Quine = Cat, C (GCC), 149 (81 + 68)
### Hello World
```
a;main(s){a?read(0,&s,1)&&main(putchar(s)):puts("Hello World!");}
#define main m
```
[Try it online!](https://tio.run/##S9ZNT07@/z/ROjcxM0@jWLM60b4oNTFFw0BHrVjHUFNNDSxeUFqSnJFYBJTXtAKyizWUPFJzcvIVwvOLclIUlTSta7mUU1LTMvNSFUDqFXL//w/JyCxWAKKSjFSFzDygJgA "C (gcc) – Try It Online")
### Quine
```
a=1;main(s){printf(s="a=1;main(s){printf(s=%c%s%1$c,34,s);}",34,s);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/R1tA6NzEzT6NYs7qgKDOvJE2j2FYJq6hqsmqxqqFKso6xiU6xpnWtEozx/z8A "C (gcc) – Try It Online")
### Cat (Hello World + Quine)
```
a;main(s){a?read(0,&s,1)&&main(putchar(s)):puts("Hello World!");}
#define main m
a=1;main(s){printf(s="a=1;main(s){printf(s=%c%s%1$c,34,s);}",34,s);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/ROjcxM0@jWLM60b4oNTFFw0BHrVjHUFNNDSxeUFqSnJFYBJTXtAKyizWUPFJzcvIVwvOLclIUlTSta7mUU1LTMvNSFUDqFXK5Em0N4UYWFGXmlaRpFNsqYRVVTVYtVjVUSdYxNtEpBhqlBGP8/x@SkVmsAEQlGakKmXlAmwE "C (gcc) – Try It Online")
[Answer]
# [><>](http://esolangs.org/wiki/Fish), Quine + Cat = Hello World!, 48 bytes
**[Quine](https://tio.run/##S8sszvj/X6nIwCA9P8de0drEQO//fwA)**
`"r00gol?!;40.`
The classic ><> quine
**[Cat](https://tio.run/##S8sszvj/Xym2TCnTykDD3jqfyy7HXhFIxSl5pObk5CuE5xflpCgq2fz/X5JaXAIA)**
```
"]v"i:0(?;o
>l?!;o
^"Hello World!"<
```
A simple cat program, loaded with some other code that isn't being run.
**[Hello World!](https://tio.run/##S8sszvj/X6nIwCA9P8de0drEQE8ptkwp08pAw946n8sOJJbPFafkkZqTk68Qnl@Uk6KoZPP/PwA)**
```
"r00gol?!;40."]v"i:0(?;o
>l?!;o
^"Hello World!"<
```
The quine part makes the instruction pointer stop interpreting "]v" as text, instead clearing the stack and moving down to the "Hello World!" printer.
---
Equivalently, the program can be written as
```
'rd3*ol?!;40.']v'i:0(?;o
>l?!;o
^"Hello World!"<
```
Which, as Jo King points out, avoids using the `g` code reflection instruction, arguably making the quine more genuine.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), Quine + Hello World = Cat, 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
**Quine:**
```
2096239D20BJ
```
[Try it online (with input)](https://tio.run/##yy9OTMpM/f/fyMDSzMjY0sXIwMnr//@S1OISAA) or [try it online (without input)](https://tio.run/##yy9OTMpM/f/fyMDSzMjY0sXIwMnr/38A).
**Hello World:**
```
I.gi”Ÿ™‚ï!
```
[Try it online (with input)](https://tio.run/##yy9OTMpM/f/fUy8981HD3KM7HrUsetQw6/B6xf//S1KLSwA) or [try it online (without input)](https://tio.run/##yy9OTMpM/f/fUy8981HD3KM7HrUsetQw6/B6xf//AQ).
**Cat:**
```
2096239D20BJI.gi”Ÿ™‚ï!
```
[Try it online (with input)](https://tio.run/##yy9OTMpM/f/fyMDSzMjY0sXIwMnLUy8981HD3KM7HrUsetQw6/B6xf//S1KLSwA) or [try it online (without input)](https://tio.run/##yy9OTMpM/f/fyMDSzMjY0sXIwMnLUy8981HD3KM7HrUsetQw6/B6xf//AQ).
(All three output with trailing newline.)
**Explanation:**
```
2096239 # Push integer 2096239
D # Duplicate it
20B # Convert it to base-20 as list: "D20BJ"
J # Join stack together: "2096239D20BJ"
# (after which it is output implicitly as result)
I # Push the input (or an empty string if none is given)
.g # Get the amount of items on the stack (which will be 1)
i # If this amount is 1 (which it always is):
”Ÿ™‚ï! # Push dictionary string "Hello World!"
# (after which it is output implicitly as result)
2096239D20BJ # Same as above
I # Push the input (or an empty string if none is given)
.g # Get the amount of items on the stack: 2
i # If this amount is 1 (which it isn't):
”Ÿ™‚ï! # Push dictionary string "Hello World!"
# (implicit else:)
# (implicitly output the input we pushed earlier as result)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `”Ÿ™‚ï!` is `"Hello World!"`.
Credit of the quine goes to [*@Grimmy*'s answer here](https://codegolf.stackexchange.com/a/186809/52210).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), Quine + Cat = Hello World! 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Note that using a formatted input has been deemed valid and this entry takes input as a command-line argument formatted as a Python string. To have a pure-Cat program we'd need to use STDIN in Jelly, since it first attempts to evaluate any command-line argument as Python. This is achievable in 21 bytes with `”ṘṘ` + `”1$0¡ƈȮ¤L¿“,ḷṅḳȦ»Ṇ?` [TIO](https://tio.run/##AT4Awf9qZWxsef//4oCd4bmY4bmYMSQwwqHGiMiuwqRMwr/igJws4bi34bmF4bizyKbCu@G5hj///1NvbWUKdGV4dA).
```
”ṘṘ
```
**[Quine](https://tio.run/##y0rNyan8//9Rw9yHO2cA0f///5WC83NTFUpSK0qUAA "Jelly – Try It Online")**
```
1$0¡³“,ḷṅḳȦ»⁼?
```
**[Cat](https://tio.run/##ATEAzv9qZWxsef//MSQwwqHCs@KAnCzhuLfhuYXhuLPIpsK74oG8P////yJTb21lIHRleHQi "Jelly – Try It Online")**
```
”ṘṘ1$0¡³“,ḷṅḳȦ»⁼?0
```
**[Hello World!](https://tio.run/##AToAxf9qZWxsef//4oCd4bmY4bmYMSQwwqHCs@KAnCzhuLfhuYXhuLPIpsK74oG8P////yJTb21lIHRleHQi "Jelly – Try It Online")**
### How?
The shortest proper quine in Jelly is:
```
”ṘṘ - Main Link: any arguments
”Ṙ - an 'Ṙ' character
Ṙ - print Jelly representation of x (i.e. ”Ṙ) and yield x ('Ṙ')
- implicit print (i.e. Ṙ)
```
To use it we need to not let the `Ṙ` execute in the largest program.
One way to not execute a link is to follow it with `0¡` - repeat zero times, but `¡` needs a link to repeat, like `X0¡`, so we make `X` equal `1$`.
`$` composes the preceding two links into a single monadic link and (slightly surprisingly) `1$` can start a full program, as a monad which yields \$1\$ but when repeated zero times it just yields whatever its left argument is.
As such starting a program which has one command-line argument with `1$0¡` applies `1$` zero times to that argument, i.e. is a no-op, giving the rest of the program that same left argument.
But when `1$0¡` is prefixed with `”ṘṘ` we have the `X` (described earlier) equal to `Ṙ1` which when applied zero times to `”Ṙ` yields the character `'Ṙ'`.
Since the character, `'Ṙ'`, is not equal to the right argument of the Main Link (which, when given a single command-line argument is that argument) since that is a *list* of characters, we can use equality, `⁼`, to test, `?`, (effectively) whether the prefix `”ṘṘ` is present and either...
...Cat\* (if not):
```
³ - yield the programs 1st command-line argument
```
...or Hello World!:
```
“,ḷṅḳȦ» - compressed string = "Hello World!"
```
---
\* The Cat code for the 21 byte STDIN version is:
```
ƈȮ¤L¿ - niladic link (no arguments)
¿ - do...
¤ - ...instruction: nilad followed by link(s) as a nilad
ƈ - read a character from STDIN
Ȯ - print & yield
L - ...while?: length (0 at EOF)
```
and we use the monad logical-NOT, `Ṇ`, as our test since we get an implicit left argument of `0` with no command-line arguments and by this point `Ṇ` gets an argument of `0` (`0Ṇ` = \$1\$ -> Cat) or `'Ṙ'` (`”ṘṆ` = \$0\$ -> Hello World!).
[Answer]
# [Ruby](https://www.ruby-lang.org/), Cat + Quine = *Hello World!*, ~~100~~ ~~97~~ 96 bytes
Reading the source code is prohibited for quines but there is no such rule for *Hello World!* programs. We exploit this fact using Ruby's `DATA`/`__END__` mechanism. If `__END__` appears alone on any line in the code, execution terminates there. However, any further code is accessible via the constant `DATA`, which is initialised to a `File` object containing all of this non-executable 'data'.
### Cat
```
$><<(DATA||=$<).read;a
```
[Try it online!](https://tio.run/##KypNqvz/X8XOxkbDxTHEsabGVsVGU68oNTHFOvH//5CMVIXkxBKFYiDOz1MoAXJzE0sA "Ruby – Try It Online")
The idiomatic `||=` operator sets the value of the variable `DATA` only if it is not already defined. In this case, `DATA` is not defined because the program does not contain `__END__`. In effect, the first part of the code therefore reduces to `$><<$<.read`, where `$<` and `$>` point to STDIN and STDOUT, respectively. For later use, the final `a` (which is an undefined variable) throws an error, which is inconsequential here.
### Quine
```
eval$s=%q($><<"eval$s=%q(#$s)
__END__
Hello World!")
__END__
Hello World!
```
[Try it online!](https://tio.run/##KypNqvz/P7UsMUel2Fa1UEPFzsZGCcFVVinW5IqPd/VziY/n8kjNyclXCM8vyklRVMIu/P9/SEaqQnJiiUIxEOfnKZQAubmJJQA "Ruby – Try It Online") or [verify quine](https://tio.run/##S0oszvj/vzxZQTdZQS8zr6C0RK8kM9@aKzfFtLg0F0WoqDSpEklAoUYBoghDxvr//9SyxByVYlvVQg0VOxsbJQRXWaVYkys@3tXPJT6eyyM1JydfITy/KCdFUQm7MAA "Bash – Try It Online").
All of the real work is done in the first line, which is a basic Ruby quine template. With `__END__` now making an appearance, it shouldn't be too hard to see where this is going.
### *Hello World!*
```
$><<(DATA||=$<).read;a
eval$s=%q($><<"eval$s=%q(#$s)
__END__
Hello World!")
__END__
Hello World!
```
[Try it online!](https://tio.run/##KypNqvz/X8XOxkbDxTHEsabGVsVGU68oNTHFOpErtSwxR6XYVrVQA6RACcFVVinW5IqPd/VziY/n8kjNyclXCM8vyklRVMIu/P9/SEaqQnJiiUIxEOfnKZQAubmJJQA "Ruby – Try It Online")
Finally we have `DATA` and `__END__` together. Unlike in the *cat* program, `DATA` is defined this time: it's a `File` object containing `Hello World!`. Once this has been printed, there is no further output because of the error thrown by the final `a` (undefined) in the first line.
[Answer]
# Python 3, Cat + Quine = Hello World, 121 bytes
* -2 bytes thanks to @Jo King
**Cat**:
Actual `cat` part is taken from the top comment of [this SO answer](https://stackoverflow.com/a/40462515/4608364).
If the file is long enough, switch to a Hello World program.
```
len(open(__file__).read())<99or~print('Hello World!')
import sys
print(sys.stdin.read())
```
The `~print` exits the program after printing: `print` returns `None` and `~None` throws. (Crashing to exit was allowed by OP in a comment.)
**Quine**:
Pretty standard. Originally wanted to use Python 3.8 `:=` to do `print((s:='print((s:=%r)%%s)')%s)`, but that was longer. Stole the use of `;` instead of `\n` from [one of the other Python answers](https://codegolf.stackexchange.com/a/209043/43266).
```
s='s=%r;print(s%%s)';print(s%s)
```
**[Combined](https://tio.run/##PU27CsMwDNz9Fe5gbC2BtlNos@cPMpqCXSpwJSN5yZJfT01fyz24O66u7cF03veSKXDtEOMdS44RBsm3FACu48iyVUFqwc@5FLYLS0kHDwaflaVZXdV8Cl0N2hLSb2108jo5uXxz5xT83yiYfo2U7dG86fQC)**:
```
len(open(__file__).read())<99or~print('Hello World!')
import sys
print(sys.stdin.read())
s='s=%r;print(s%%s)';print(s%s)
```
[Answer]
# [Haskell](https://www.haskell.org/), Cat + Quine = Hello World, 127 bytes
## Cat, 27 bytes
```
o=interact id
main=o where
```
[Try it online!](https://tio.run/##DcnRDcAgCAXA/07BAo7gMERJfBGhVZuOT/29a7y6qEZKhTc9L0yoHXD6fGoNz7Atk8sm1GswLJ9qMoUiuOuq43LADeb3Dw "Haskell – Try It Online")
## Quine, 100 bytes
```
o=putStr"Hello, world!";main=putStr$(++)<*>show$"o=putStr\"Hello, world!\";main=putStr$(++)<*>show$"
```
[Try it online!](https://tio.run/##y0gszk7Nyfmvq5ucWKJQWJqZl6qQARTIVyjPL8pJ@Z9vW1BaElxSpOQBEtSBiCoqWecmZuZBpVQ0tLU1bbTsijPyy1WUYBpiUHXE4NHy/39idk5xSi5XfmZmfl5mXn4BAA "Haskell – Try It Online")
## Hello World
```
o=interact id
main=o where o=putStr"Hello, world!";main=putStr$(++)<*>show$"o=putStr\"Hello, world!\";main=putStr$(++)<*>show$"
```
[Try it online!](https://tio.run/##fcsxEoIwEIXhnlOsGQoVOYHGmt6WZofsTHYIWUyW4fgRZSxsbN//Po95pBBK2w6o8Fw4EvhtEFglBVfEclRKOCiwqybkaLfkKRGInRd9aDLd@3/ZwcFcP6c91cemOd3O9@xlrc0X9L@i/0NKwTFkN1XCLJGjzC8 "Haskell – Try It Online")
## Explanation
The main trick in this answer is scoping. In the cat we have a simple program. We have a `main` which is just defined to be `o`, which is a cat program. At the end of the program there is a `where` which opens a new scope. This will make our entire quine program attached to the scope of the main program. Two things are solved by doing this.
* Since the quine program's `main` is not defined in the global scope we avoid the duplicate main declaration error.
* We can declare a version of `o` that overrides the one in the global scope. Our quine program declares `o` to be a hello world program.
The overall technique is very similar to [Silvio Mayolo's answer](https://codegolf.stackexchange.com/a/209120/56656), however improves upon it in two ways.
* Silvio Mayolo's answer declares a variable `c=1`, which is never used (I am not sure why this is done. Removing it doesn't break anything). This does not have this.
* I used a shorter quine technique. I took a glance at Silvio Mayolo's quine and I don't know how it works, but it is longer than mine.
[Answer]
# [Python 2](https://docs.python.org/2/), Quine + Cat = Hello World, 86 bytes
### [Quine](https://tio.run/##K6gsycjPM/r/PzPFVh2IVYusC4oy80oUMlNUVTNT1BG8zJT//wtLM/NSAQ "Python 2 – Try It Online") (35 bytes)
```
id='id=%r;print id%%id';print id%id
```
### [Cat](https://tio.run/##K6gsycjPM/r/X9tAS109MS9F3SM1JydfITy/KCdFUZ2rPCMzJ1Vd3S4zxaqgKDOvRKEosTw@M6@gtERD8///5MQSLiAqAQA "Python 2 – Try It Online") (51 bytes)
```
+0*''and'Hello World!'
while''>id:print raw_input()
```
### [Hello World](https://tio.run/##K6gsycjPM/r/PzPFVh2IVYusC4oy80oUMlNUVTNT1BG8zBRtAy119cS8FHWP1JycfIXw/KKcFEV1rvKMzJxUdXW7zBQriOKixPL4zLyC0hINzf//AQ "Python 2 – Try It Online") (86 bytes)
```
id='id=%r;print id%%id';print id%id+0*''and'Hello World!'
while''>id:print raw_input()
```
[Answer]
# [Pxem](https://esolangs.org/wiki/Pxem) ([esolang-box notation](https://github.com/hakatashi/esolang-box#pxem)), Hello World: 48 bytes + Quine: 110 bytes = Cat: 158 bytes.
Unprintables are escaped.
## Hello World
```
.f!.zHello World.p.d.a.w.c.z.w.o.i.c\001.+.a.d.a.a
```
## Quine
```
!Be!?BzBc!!B+BzXXFBaBcFBzBsXXFBBaBsBtBvBmBvBcAcB-BaBsBp".e!?.z.c!!.+.zXXF.a.cF.z.sXXF..a.s.t.v.m.v.cAc.-.a.s.p
```
## Cat
```
.f!.zHello World.p.d.a.w.c.z.w.o.i.c\001.+.a.d.a.a
!Be!?BzBc!!B+BzXXFBaBcFBzBsXXFBBaBsBtBvBmBvBcAcB-BaBsBp".e!?.z.c!!.+.zXXF.a.cF.z.sXXF..a.s.t.v.m.v.cAc.-.a.s.p
```
## [Try it online!](https://tio.run/##jVhtV9rKFv7urxjSSCaGvAyiUmJUQGs5R6laj9cK6IpJEDAkNAmKBs5f790zCQKht@u6lmbm2c9@mb1nTyY@h71fnz5ZpmntWs7jXrf4uUhMs@tsm1Z52@qWSFEj1k5Z23N2i93iRuhESHbG@nhohs9I04pF3ZmM/CBCZ/WH6tmZUddx9DZy0JMTWb7XzefZzPKHQ9OzxQPVdl5Ub@y6qHiQJ/l8qnxRvf5qcDxOeUgezQ0wkcjH9CFVZslAnnFzt/80G7cP36@PjaKmbc/Bi2/fG7dnPx7q366uTurXBtFbiOPjWvX714ebk6vvjW/NivQ245CB3lAnn2er8tHID/uTZCbVEpW7/6HhDMeuGTko7DG@P4pg@OoHdjhy@1E@b7p9M0TyExL4mEgcf8TNBEOgTyGfb/5zdlY/PzYqzAem/mw97PW7kc7GiPJSwLF6PuI/idQzoZ5z4Kjou/ZBHlL/YrqIy6Gu6YYON50uy5hppj2Zho6NhFCdqG@qHsKfd1VgBt9RhyoxFnDmqhYWsQ9FqHpIfonGZBoFSK6HqN3S5M8dJLTa3lZHmD4FzggpiXH1vrTLq3GlqvOPelNX2x6bX4C7e0Vpe6qqP1b1WTJt3VM7hBR5daTq0TJY1tYxQgiv@hlw7/M6Rghoe1lieR0j2g6v9rPE7XXsM/Aeshh4tjLY7t46Rggoh9n1ba9jhECIL1ni7jpGNMhYNxu2to4RDTLmZGP8vI4RUuLVIOu6uI4RAtqvWeLeOgbnBQ8bLUMsr2OkCDG@ZYmf1zFShHjes0XQfoNBOGZ20TvrGCGQ2yjrubSOEQ3CGWbzvbeOEQ3CsbOuy@tYCcovZTEIUc5g28DLZTGIms9iEMwmxWbCFFtmelzYYtqUrF/V@JQ25US3of9OqXYbK22xjdse/atstUVebW@3i22iAitUlS3o1slqf1dcnc/Faut18vZu2h01Fzf1RxcMzvQ3aHYVqbrauk@ldIvzKrLVFRuyh4TUfev@qNABvxABbiVDCKF4hGgIvZST4EjZAhGLLPEO6xmxMHm1QNFHCAFKHMMsF4cwqqoj/fES0IRWOAIDH0T7g2irx3PiCm0uSfNQCXQ@TtwdIWoajjjGRtU5ElVZavlcEyRtr4Xk986WTa1FwRICS2L56SSLVZnIBNqI1TRZnJlozSDayuWHSYXFFl1mztw0H18hM8dVyMskLS7L7CJvSX5OU0vsNwkliSSt@u8UBTR/dSwVRO13sWs@Oq5hcG3CiTFbCW6NfK//YIUvXSeIhlKO35Q7lN0mWNTVp4RD92M7JoX2jIoucJukMnM5pHD8iDlaEK5AtQ9hzFW4I67A3Iqz1OEq/0/kY159DBzzmU2gblXMub4/Qp4foaEZWb2@98QBVZgvV8Ki@oiJSPkyG8vJJMcmGhvzMP6ZjjfZGDjQh6wHha4fpGmCYHRdjAX9o0GFmSCKv3qO6/qGoHRzyvtXOkb/8QPXVkaKrZjKq2Ip7/DXV/qK1dY0okiAUonZ9oSNn@O@5xhCrubkDmvvNSuXq0m199vbLzWzZn0BJKRjmIS1qPZSG8KvVbVqMkNGnAJqYB7UwCxVA7vWF0ComgKTUImUF2UIv6CmyAwZCRsbQ992jF7y@Jk8rI0NywwdxNMZ6nuo1bM64gb60qyen8Ctjq2T29D1n0sgi5@CTmiCgfq35vVJ89rIWLJENJfMVeYaeBT0vagLtxxmkk953PTVQrIlwj3mVxhYhlA7OW00Y9izUug4thgGcL/EbDjrjj0r6vseusDHYvy99Vz4G4sd41iHYUeSFvITLMaBE40DD@Uk4Cwkfy0kgB@QheTvhYSaWwiuVwTUpUyWxLf4SoyvDGCxMGRZT8lXC84Y18WYrR/VF@gpvircfdiG@7ML@TrQDnmtIi8F9jVxwBOd9c09a0oJ2ofjxBUIJdC6@3@o@7FnLPmu4vN5ROdTDjY65J/e0fsRWnI9gqW/9vqug3OQUtFfziRMYgCn0zG@BdlC4OFG4aZwXHBFWkWmGN8YwNFdw3W8p6iHb0SdtlsDLvqNfcPVxTHGxwasJYwCfFNoSFKBiOK/HFsXd3gslcqV0o44Wzjpg/cLfLri@AGfF@qFu8IPMT43OOWhgppwXpjIdqz@EC7esFjnyQngORpHnF43QF2/gxhoLLTjIdzS3n49n6/v75RFdgLpgNX/5e5Lre2dDg@H551RKsn1VDk5pICCy4kaKUFC6oaxXRTjhALfRFHfGzszmnFKre@XysA52NkTKZQ4X7hNLIs/DPwDekkulXVaPf0C3239WFqrNc/@Bb5eSUI4F9wuF@sFajIo3Ihxw9CYx4HB9jGkf0C3bWEgyx3jhhaKzhodBkIdOmw@6CylPli4hoxi1p/iFt0DSw5fF02zHs0EXxaYrxy0I81wDmaXbIvcGJf7lJvq3iyU3v6odPB7pfePMKgWC0NeCSWaL6YHvWusiIYgeqaHGnwyXmAqXxI@YhMSmmzxv@gOv8DmIahLJs1E5TbNiL44MbYMIhe3sLmviVu0ZvBcSurPrL1B2jG36WLxYMsVYceAG07ZhDemAruRq6A7J4ALZP@lH4IZjm4UWhTzcHDgHg423Yq7OaiwscrGUKNZcsJCZIbWge0AX7mZs5mbWiInLILrQiZWWB9n9/pX5x8@Oo3kbZ1ckeAGCm9v@vEvB94zmVpjGNkCEpDcLc5f63Cju8B5kX79LoXjsM2cXBdi2LhsQz9Lki5Jg31MD2G6aSHlSfoH6RQGov77ZdDl2o7rRA6COkMrpMcTNIgkNfZBXSJJS7A3TYNZlAj0SXLoS8m8MxN0@qai/xmBO6SF2H9PxrRD/CH9XwCAwRq4yKFdQnKztEKYTvEoBLmPRn274ET9oVMYWaNx4SV8120zcsTlGpT@/OWPIrPvwr2@tJRg@m0Rl@n9jt0ihan5@gy2kGnIRVLaK5W3d0tlJMSmZPDa7KR5nL41TLgScRv/d/1Tq2l26IODAsALn2Migdfgcgo/HAqT8mBu0@cKvCYK04kZPEEOGhOUVm6CNn79Fw "ksh – Try It Online")
Use variable `mode` to switch programs.
## How it works
The Hello World program consists of several parts, as in:
```
# branch if content begins with '!' or not
.f!.z
# Hello World program
# Note that '!' is recycled here
Hello World.p.d
.a
.w.c.z
# Cat program
# Note that content of stack is cleared before entrying here
.w.o.i.c\001.+.a.d
.a.a\n
```
Quine is [recycled from here](https://codegolf.stackexchange.com/a/221399/100411).
Cat program uses this specification:
>
> The first line is the file name of the pxem code.
>
>
> The rest is the content of the pxem code.
>
>
>
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), Cat + HW = Quine, 156 bytes
```
BEGIN{k=1}1;BEGIN{if(k){printf a="BEGIN{k=1}1;BEGIN{if(k){printf a=%c%s%c,34,a,34,34,34;exit}print%cHello World!%c}",34,a,34,34,34;exit}print"Hello World!"}
```
[Try it online!](https://tio.run/##SyzP/v/fydXd068629aw1tAaws5M08jWrC4oyswrSVNItFUiqEI1WbVYNVnH2EQnEUSAkXVqRWZJLViJarJHak5OvkJ4flFOiqJqcq0STqVKyCqVav//d04sAQA "AWK – Try It Online")
This is the overall algorithm:
```
BEGIN{k=1}1;
BEGIN{if(k){
print"Quine";exit
}
print"Hello, World!"
}
```
## Cat
```
BEGIN{k=1}1;
```
## Hello World
```
BEGIN{if(k){printf a="BEGIN{k=1}1;BEGIN{if(k){printf a=%c%s%c,34,a,34,34,34;exit}print%cHello World!%c}",34,a,34,34,34;exit}print"Hello World!"}
```
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), Quine + Hello World = Cat, 32 bytes
## Quine
```
dG2idG2i
```
Explanation:
* `dG`: Delete the buffer (saving it to the unnamed register)
* `2idG2i`: Insert `dG2i` twice.
## Hello World
```
"_dG4iHello World!
␛pH3D
```
With trailing newline. TryItOnline also shows a trailing space after that, but this appears to be an artifact of it's V runner.
Explanation:
* `"_dG`: Delete the buffer (without saving it to a register)
* `4iHello World!␊␛`: Write "Hello World!" 4 times
* `p`: Paste from the (empty) unnamed register
* `H3D`: Delete the first 3 lines of the buffer
## Cat
```
dG2idG2i"_dG4iHello World!
␛pH3D
```
Since all no-ops in V are automatically cat programs, the trick here is to make the combined program cancel out itself.
Explanation:
* `dG`: Delete the buffer (saving it to the unnamed register)
* `2idG2i"_dG4iHello World!␊␛`: Write `dG2i"_dG4iHello World!` twice (trailing newline)
* `p`: Paste from the unnamed register.
+ Since the motion used to delete was `G`, this pastes it onto the following line.
+ Therefore, the first two lines of the buffer are that crazy string, the third is an empty line, and the rest is the original buffer
* `H3D`: Delete the first 3 lines of the buffer
[Try it online!](https://tio.run/##K/v/P8XdKBOEleJT3E0yPVJzcvIVwvOLclIUuWxSi5PtCjxSjFP@/w/JSFUoLM1MzlZIKsovz1NIy6/gyirNLShWyC9LLVIoAUrnJFZVKqTkp//XLQMA "V (vim) – Try It Online")
[Answer]
# PHP, Hello World + Quine = Cat, 117 bytes
Because of the input method this only works using the command line.
## Hello world
the double die is because the php code has to get interupted earlier in order to prevent errors being printed (missing function a)
```
<?php if(!function_exists('a')){die('Hello world!');}die(a($argv));
```
## Quine
without opening tag, php just outputs whatever it contains
```
function a($b){unset($b[0]);echo implode(' ',$b);}
```
## Cat
Because function declations are passed first, the die() isn't called yet and therefor a() exists, and is called in order to print its arguments. The unset avoids the scriptname from being printed (which is not an input)
```
<?php if(!function_exists('a')){die('Hello world!');}die(a($argv));function a($b){unset($b[0]);echo implode(' ',$b);}
```
If only the first argument has to be printed, a shortcut can be used (101 bytes):
```
<?php if(!function_exists('a')){die('Hello world!');}die(a($argv));function a($b){unset($b[0]);echo implode(' ',$b);}
```
This however is not the full input and i consider this invalid
[Answer]
# Java 10+, Cat + Quine = Hello World, 384 (135 + 249) bytes
## [Cat](https://tio.run/##LcyxDoIwEIDh2bdonGCwEHFAHUw0Jg5OonEwDhd6mEK5ajlAQnh2ZHD9k@/PoYFFropx1MToMkhRHPqKgXUqGquVKEGTl7DT9Ho8we@TrmIspa1ZvqfIhry9tQaB5PVyO@4IW5FPV1mzNjJJgQid91eafEn45bMm9PzN/ITGWHG3zqi5vx2GIBhHyKtCZXE4W3aRcFG8Dj9du/oB), 135 bytes
```
interface C{static void main(String[]a){System.out.println(Boolean.TRUE?new java.util.Scanner(System.in).nextLine():"Hello World");}}//
```
## [Quine](https://tio.run/##y0osS9TNSsn@/z8zryS1KC0xOVXBNzEzr7q4JLEkM1mhLD8zRSEXKKARXFKUmZceHZuoWV2WWKRQbKuE0BFIhHLVZNVi1WTr4MriktRcvfzSEr0CoIqSNI1iHWMTHTBhaKBpXVurmoww2Ck/Pyc1Ma86CUIrhASFutqmJeYUp1rXKhFhFhdxRv3/DwA), 249 bytes
(note: TIO doesn't let me run the code unless I rename my interface from `Q` to `Main`, but just know that it's supposed to be named the former)
```
interface Q{static void main(String[]a){var s="interface Q{static void main(String[]a){var s=%c%s%c;System.out.printf(s,34,s,34,10);}}%cinterface Boolean{boolean TRUE=false;}";System.out.printf(s,34,s,34,10);}}
interface Boolean{boolean TRUE=false;}
```
## [Hello World](https://tio.run/##lY/BasJAEIbvfYolENiAXSt6apBCodBDe9AoHqSHcTMpm66zZXeMSsizx2gFwYPYywz8zHx8fwkVPJb5T9saYvQFaBSfYKgODGy0qJzJxboLZMbe0PfyC5I62wfGtXIbVr9dyJbkq3MWgdRsOn97IdyKsgOrDRurMg1E6OX5y1CiCHf8YQhl8hy9o7VOLJy3eZSkTdPvX0wmNzUq8CKMo/@dxzoOsU6vKxQy9Iaj3mkMno4esb6Az@3q1d8Wx5bjAmzAtInuYD3ch2rbAw), 384 bytes
```
interface C{static void main(String[]a){System.out.println(Boolean.TRUE?new java.util.Scanner(System.in).nextLine():"Hello World");}}//interface Q{static void main(String[]a){var s="interface Q{static void main(String[]a){var s=%c%s%c;System.out.printf(s,34,s,34,10);}}%cinterface Boolean{boolean TRUE=false;}";System.out.printf(s,34,s,34,10);}}
interface Boolean{boolean TRUE=false;}
```
Again, the TIO link contains an interface called `Main`, but it's actually `C`, the cat program.
It redefines `Boolean.TRUE` to be `false` when the quine is concatenated to the cat.
[Answer]
# Haskell, Cat + Quine = Hello World, 140 bytes
## Cat
```
b=interact id
main=b where c=1;
```
## Quine
```
main=putStr a>>print a;b=putStrLn "Hello world!";a="main=putStrLn a>>print a;b=putStrLn \"Hello world!\";a="
```
## Hello World!
```
b=interact id
main=b where c=1;main=putStr a>>print a;b=putStrLn "Hello world!";a="main=putStrLn a>>print a;b=putStrLn \"Hello world!\";a="
```
We exploit the rules of variable shadowing. The cat program simply calls the global `b`, defined as `interact id` (a standard cat in Haskell). We declare a variable `c` that's never used, simply so we can concatenate later. The quine is pretty standard; we define a variable `b` that we never use, but otherwise it simply prints its payload and exits.
Here's a version of "Hello world" with better spacing.
```
b = interact id
main = b
where c=1
main=putStr a>>print a
b=putStrLn "Hello world!"
a="main=putStrLn a>>print a;b=putStrLn \"Hello world!\";a="
```
`main` simply calls `b`, but this time is calls the locally-declared `b`, which prints "Hello world!". All of the other variables are unused.
[Answer]
# [Klein](https://github.com/Wheatwizard/Klein) 001, Quine + Cat = Hello World, 28 bytes
## Quine, 11 bytes
*This is Martin Ender's quine from [here](https://codegolf.stackexchange.com/a/121511/56656)*
```
:?\:2+@> "
```
[Try it online!](https://tio.run/##y85Jzcz7/9/KPsbKSNvBTkGJ6////wYGhv91HQE "Klein – Try It Online")
## Cat, 17 bytes
```
@ >"Hello world!"
```
[Try it online!](https://tio.run/##y85Jzcz7/99BwU7JIzUnJ1@hPL8oJ0VR6f///7rJ/w0MDP8n5uTkFAMA "Klein – Try It Online")
## Hello World, 28 bytes
```
:?\:2+@> "
@ >"Hello world!"
```
[Try it online!](https://tio.run/##y85Jzcz7/9/KPsbKSNvBTkGJy0HBTskjNScnX6E8vygnRVHp////BgaG/3UdAQ "Klein – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), Quine + Cat = Hello World, 43 bytes
All of the complexity is jammed into making a quine that includes a variable that holds `Hello World!`. Cat simply outputs the default input and the Hello World merger reuses the variable from the quine.
## [Quine, 41 bytes](https://ethproductions.github.io/japt/?v=1.4.6&code=IkhlbGxvIFdvcmxkISIKImlRILJpUmlRaVVpUSJpUSCyaVJpUWlVaVE=&input=)
```
"Hello World!" // U = "Hello World!"
"iQ ²iRiQiUiQ"iQ ²iRiQiUiQ // A bunch of messy string manipulations to make this a quine
```
## [Cat, 2 bytes](https://ethproductions.github.io/japt/?v=1.4.6&code=ClU=&input=ImZvb2JhciI=)
```
U // Output the default first input
```
## [Hello World, 43 bytes](https://ethproductions.github.io/japt/?v=1.4.6&code=IkhlbGxvIFdvcmxkISIKImlRILJpUmlRaVVpUSJpUSCyaVJpUWlVaVEKVQ==&input=)
```
"Hello World!" // U = "Hello World!"
"iQ ²iRiQiUiQ"iQ ²iRiQiUiQ // Throwaway line
U // Output U
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), Cat + Quine = Hello, 16 bytes
## Hello world, 13 bytes
```
kh\!+□⁋`I^`I^
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJraFxcISvilqHigYtgSV5gSV4iLCIiLCJhXG5iXG5jXG5kXG4iXQ==)
## Cat, 7 bytes
```
kh\!+□⁋
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJraFxcISvilqHigYsiLCIiLCJhXG5iXG5jXG5kXG4iXQ==)qwhYOKWoeKBiyIsIiIsImFcbmJcbmNcbmRcbiJd)
## Quine, 6 bytes
```
`I^`I^
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgSV5gSV4iLCIiLCJhXG5iXG5jXG5kXG4iXQ==)
## Explanation :
```
## Cat (10)
kh # push 'Hello World' onto the stack
\!+ # add '!' to the string
□ # push the list of the inputs onto the stack
⁋ # join the element on top of the stack, with '\n' as separator
# implicit output
## Quine (6)
`I^` # push 'I^' on the stack
I # string -> `string`string
^ # reverse the stack
# implicit output
## Hello (16)
kh\!+ # push `Hello World!` onto the stack
□ # | do
⁋ # | many
`I^` # | useless
I # | things
^ # reverse the stack
# implicit output
```
] |
[Question]
[
Draw lines between every pair of distinct points for `n` points arranged in a circle, producing something like the below result. Shortest code (in bytes) wins! Your lines don't have to be transparent, but it looks better that way. The output must be a vector graphic, or be an image at least 600 pixels by 600 pixels (either saved to a file or displayed on the screen). To complete the challenge you must draw at least 20.
[![enter image description here](https://i.stack.imgur.com/erAyJ.jpg)](https://i.stack.imgur.com/erAyJ.jpg)
[Answer]
**Mathematica, 13 bytes**
```
CompleteGraph
```
[![lined-up-circle-37-points](https://i.stack.imgur.com/BLIGp.png)](https://i.stack.imgur.com/BLIGp.png)
Looks like this only fails to give a circular embedding for `n=4`, but the question states `n>=20`
[Answer]
# [MATL](https://matl.suever.net/?code=%3AG%2F4%2aJw%5E2Z%5E%21XG&inputs=21&version=19.5.1), ~~16~~ 14 bytes
As I'm not terribly fluent with MATL I expect that this is somewhat more golfable. (Would be nice to at least beat Mathematica :-) I.e. the the flip `w` is not optimal, it could probably be avoided...
```
:G/4*Jw^2Z^!XG
```
[Test it Online!](https://matl.suever.net/?code=%3AG%2F4%2aJw%5E2Z%5E%21XG&inputs=21&version=19.5.1) (Thanks @Suever for this service, thanks @DrMcMoylex for -2 bytes.)
Explanation (for `N=3`):
```
: Generate Range 1:input: [1,2,3]
G/ Divide By the first input [0.333,0.666,1]
4* Multiply by 4 [1.33,2.66,4.0]
Jw^ i ^ (the result so far) [-0.49+ 0.86i,-.5-0.86i,1.00]
(This results in a list of the n-th roots of unity)
2Z^ Take the cartesian product with itself (i.e. generate all 2-tuples of those points)
!XG Transpose and plot
```
It is worth noting that for generating the N-th roots of unity you can use the formula `exp(2*pi*i*k/N)` for `k=1,2,3,...,N`. But since `exp(pi*i/2) = i` you could also write `i^(4*k/N)` for `k=1,2,3,...,N` which is what I'm doing here.
![](https://i.stack.imgur.com/taK5j.jpg)
[Answer]
## [PICO-8](http://www.lexaloffle.com/pico-8.php), 131 bytes
I wasn't really sure if I'd be breaking any rules, but I did it anyway!
**Golfed**
```
p={}for i=0,19 do add(p,{64+64*cos(i/20),64+64*sin(i/20)})end for x in all(p)do for y in all(p)do line(x[1],x[2],y[1],y[2])end end
```
**Ungolfed**
```
points={}
for i=0,19 do
x=64+64*cos(i/20)
y=64+64*sin(i/20)
add(points,{x,y})
end
for x in all(points) do
for y in all(points) do
line(x[1],x[2],y[1],y[2])
end
end
```
[![128x128 madness](https://i.stack.imgur.com/tJqZ8.png)](https://i.stack.imgur.com/tJqZ8.png)
PICO-8 is a Lua based fantasy console with a native resolution of **128x128.** I made the circle as big as I could...
[Answer]
# Mathematica, 42 bytes
Creates a set of 37 points arranged in a circle, and then draws lines between all possible subsets of two points. Someone posted a shorter answer that takes advantage of CompleteGraph, but I believe this is the shortest one aside from those relying on CompleteGraph.
```
Graphics@Line@Subsets[CirclePoints@37,{2}]
```
[![enter image description here](https://i.stack.imgur.com/7jjWK.png)](https://i.stack.imgur.com/7jjWK.png)
[Answer]
# HTML + JS (ES6), 34 + ~~177~~ ~~164~~ 162 = 196 bytes
Using the [HTML5 Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API).
[See it on CodePen](http://codepen.io/darrylyeo/pen/xRpXYM).
```
f=n=>{with(Math)with(c.getContext`2d`)for(translate(S=300,S),O=n;O--;)for(rotate(a=PI*2/n),N=n;N--;)beginPath(stroke()),lineTo(0,S),lineTo(sin(a*N)*S,cos(a*N)*S)}
/* Demo */
f(20)
```
```
<canvas id=c width=600 height=600>
```
*-13 bytes*: Removed `closePath()`, moved `stroke()` inside `beginPath()`
*-2 bytes*: Defined variable `a` inside `rotate()`
[Answer]
# Java, ~~346~~ ~~338~~ ~~322~~ 301 Bytes
This solution works for all `n>1`, even though the original post didn't require that, it does.
My favorite is `n=5`, don't ask why, also, if you want a cooler GUI, use:
`int a=Math.min(this.getHeight(),this.getWidth())/2;`
In place of the hard-coded 300, it'll use the width or height of the frame as the diameter.
*Saved 8 bytes thanks to Shooqie.*
*Saved 21 bytes thanks to Geobits.*
```
import java.awt.*;void m(final int n){new Frame(){public void paint(Graphics g){Point[]p=new Point[n];int a=300;for(int i=1;i<n+1;i++){p[i-1]=new Point(a+(int)(a*Math.cos(i*2*Math.PI/n)),a+(int)(a*Math.sin(i*2*Math.PI/n)));for(int j=0;j<i;j++){g.drawLine(p[i-1].x,p[i-1].y,p[j].x,p[j].y);}}}}.show();}
```
Output for `n=37`:
[![enter image description here](https://i.stack.imgur.com/PCPpz.png)](https://i.stack.imgur.com/PCPpz.png)
[Answer]
## Python 2, ~~258~~ ~~235~~ 229 Bytes
```
import itertools as T,math as M
from PIL import Image as I,ImageDraw as D
s=300
n=input()
t=2*M.pi/n
o=I.new('RGB',(s*2,)*2)
for x in T.combinations([(s*M.cos(t*i)+s,s*M.sin(t*i)+s)for i in range(n)],2):D.Draw(o).line(x)
o.show()
```
Output for `n=37`
[![n=37](https://i.stack.imgur.com/DVMoT.png)](https://i.stack.imgur.com/DVMoT.png)
[Answer]
# Octave, ~~88~~ 69 bytes
```
N=input('');t=0:2*pi/N:N;k=nchoosek(1:N,2)';line(cos(t)(k),sin(t)(k))
```
Output for `N=37`:
[![enter image description here](https://i.stack.imgur.com/NtKPt.png)](https://i.stack.imgur.com/NtKPt.png)
Output for `N=19`:
[![enter image description here](https://i.stack.imgur.com/eZfQh.jpg)](https://i.stack.imgur.com/eZfQh.jpg)
[Answer]
## Perl, 229 bytes
It uses the same formula as most languages that don't have convenient builtin for this challenge (even if I didn't look at them to find it, but that's a fairly easy to find formula). So not very interesting, but there are usually not a lot of Perl answers to this kind of challenges, so I just wanted to propose one.
```
$i=new Imager xsize=>700,ysize=>700;for$x(1..$_){for$y(1..$_){$i->line(color=>red,x1=>350+300*cos($a=2*pi*$x/$_),x2=>350+300*cos($b=2*pi*$y/$_),y1=>350+300*sin$a,y2=>350+300*sin$b)}}$i->write(file=>"t.png")
```
And you'll need `-MImager` (9 bytes), `-MMath::Trig` (providing `pi`, 13 bytes), and `-n` (1 byte) ==> + 23 bytes.
To run it :
```
perl -MImager -MMath::Trig -ne '$i=new Imager xsize=>700,ysize=>700;for$x(1..$_){for$y(1..$_){$i->line(color=>red,x1=>350+300*cos($a=2*pi*$x/$_),x2=>350+300*cos($b=2*pi*$y/$_),y1=>350+300*sin$a,y2=>350+300*sin$b)}}$i->write(file=>"t.png")' <<< 27
```
It will create a file named `t.png` which contains the image.
You'll need to install `Imager` though, but no worries, it's quite easy :
```
(echo y;echo) | perl -MCPAN -e 'install Imager'
```
(The `echo`s will configure you cpan if you've never used it before. (actually that will only work if your perl is recent enough, I think for most of you it will be, and I'm sorry for the others!)).
And the more readable version (yes, it's fairly readable for a Perl script!) :
```
#!/usr/bin/perl -n
use Imager;
use Math::Trig;
$i=Imager->new(xsize=>700,ysize=>700);
for $x (1..$_){
for $y (1..$_){
$i->line(color=>red,x1=>350+300*cos($a=2*pi*$x/$_), x2=>350+300*cos($b=2*pi*$y/$_),
y1=>350+300*sin($a), y2=>350+300*sin($b));
}
}
$i->write(file=>"t.png");
```
[![enter image description here](https://i.stack.imgur.com/qa4Bf.png)](https://i.stack.imgur.com/qa4Bf.png)
*-1 byte thanks to Titus.*
[Answer]
# [GeoGebra](https://www.geogebra.org/), 92 bytes
```
a=polygon((0,0),(1,0),20)
sequence(sequence(segment(vertex(a,i),vertex(a,j)),j,1,20),i,1,20)
```
Each line is separately entered into the input bar. Here is a gif showing the execution:
[![Execution](https://i.stack.imgur.com/l1wyn.gif)](https://i.stack.imgur.com/l1wyn.gif)
**How it works**
The `polygon` command creates a 20-sided polygon, with the vertices of the baseline at `(0,0)` and `(1,0)`. The next command then iterates over each vertex of the polygon with index `i`, using the `sequence` and `vertex` commands, and for each vertex with index `i`, draws a line segment to every other vertex with index `j` using the `segment` command.
[Answer]
# PHP, ~~186~~ ~~184~~ 196 bytes
```
imagecolorallocate($i=imagecreate(601,601),~0,~0,~0);for(;$a<$p=2*M_PI;)for($b=$a+=$p/=$argv[1];$b>0;)imageline($i,(1+cos($a))*$r=300,$r+$r*sin($a),$r+$r*cos($b-=$p),$r+$r*sin($b),1);imagepng($i);
```
writes the image to STDOUT
**breakdown**
```
// create image with white background
imagecolorallocate($i=imagecreate(601,601),~0,~0,~0);
// loop angle A from 0 to 2*PI
for(;$a<$p=2*M_PI;)
// loop angle B from A down to 0
for($b=$a+=$p/=$argv[1];$b;) // ($a pre-increment)
// draw black line from A to B
imageline($i, // draw line
(1+cos($a))*$r=300,$r+$r*sin($a), // from A
$r+$r*cos($b-=$p),$r+$r*sin($b), // to B ($b pre-decrement)
1 // undefined color=black
);
// output
imagepng($i);
```
**-12 bytes for fixed `n=20`**
Replace `$p=2*M_PI` with `6` (-8), `/=$argv[1]` with `=M_PI/10` (-2), and `$b>0` with `$b` (-2)
Using exact PI/10 doesn´t hurt. With `.3142`, the rounding errors from the parametrized version remained, but with `M_PI/10` they vanished and I can check `$b`(<>0) instead of `$b>0`. I could have saved two bytes with `.314`, but that would have off-set the points.
The limit `$a<6` is sufficiently exact for 20 points.
[![exact PI graph](https://i.stack.imgur.com/xrTFg.png)](https://i.stack.imgur.com/xrTFg.png)
**174 bytes for fixed `n=314`**
```
imagecolorallocate($i=imagecreate(601,601),~0,~0,~0);for(;$a<314;)for($b=$a++;$b--;)imageline($i,(1+cos($a))*$r=300,$r+$r*sin($a),$r+$r*cos($b),$r+$r*sin($b),1);imagepng($i);
```
Using 314 points results in a filled circle in that resolution (as do 136,140, every even number above that, and everything above 317).
[Answer]
## [NetLogo](https://ccl.northwestern.edu/netlogo/) - 44 bytes
```
cro 20[create-links-to other turtles fd 20]
```
![NetLogo output](https://i.stack.imgur.com/OQJGV.png)
[Answer]
## R, ~~127~~ 123 bytes
```
plot((e=cbind(sin(t<-seq(0,2*pi,l=(n=21)))*2,cos(t)*2)));for(i in 2:n)for(j in 1:i)lines(c(e[i,1],e[j,1]),c(e[i,2],e[j,2]))
```
**Produces :**
[![](https://i.stack.imgur.com/ofkIh.jpg)](https://i.stack.imgur.com/ofkIh.jpg)
Nice axis' labels uh ?
*-4 bytes* thanks to @Titus !
[Answer]
# BBC BASIC, 98 ascii characters
Tokenised filesize 86 bytes
```
r=600V.5142;29,r;r;:I.n:t=2*PI/n:F.i=1TOn*n:a=i DIVn*t:b=i MODn*t:L.r*SINa,r*COSa,r*SINb,r*COSb:N.
```
Dowload interpreter at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html>
There's nothing wrong with drawing every line twice, the appearance is identical :-P
**Ungolfed**
```
r=600 :REM Radius 600 units. 2 units per pixel, so 300 pixels
VDU5142;29,r;r; :REM Set mode 20 (600 pixels high) and move origin away from screen corner
INPUTn :REM Take input.
t=2*PI/n :REM Step size in radians.
FORi=1TOn*n :REM Iterate through all combinations.
a=i DIVn*t :REM Get two angles a and b
b=i MODn*t :REM by integer division and modlo
LINEr*SINa,r*COSa,r*SINb,r*COSb :REM calculate cartesian coordinates and draw line
NEXT
```
**Output n=21**
This looks much better in the original rendering than in the browser.
[![<code>enter image description here</code>](https://i.stack.imgur.com/bxYnE.png)](https://i.stack.imgur.com/bxYnE.png)
[Answer]
# Octave, ~~50 48 46~~ 45 bytes
```
@(N)gplot((k=0:2*pi/N:N)+k',[cos(k);sin(k)]')
```
This is an anyonmous function that plots the graph we're looking for.
Explanation:
`(k=0:2*pi/N:N)+k'` Makes a full `N+1 x N+1` adjecency matrix and simultaneously defines the vector `k` of angles, which we we use then for `[cos(k);sin(k)]'`, a matrix of coordinates where each graph node is positioned. `gplot` just plots the graph that we want.
For `N = 29` we get:
[![enter image description here](https://i.stack.imgur.com/wcxsW.jpg)](https://i.stack.imgur.com/wcxsW.jpg)
[Answer]
## JavaScript (ES5)/SVG (HTML5), 181 bytes
```
document.write('<svg viewBox=-1e3,-1e3,2e3,2e3><path stroke=#000 fill=none d=M1e3,0')
with(Math)for(i=37;--i;)for(j=37;j--;)document.write('L'+1e3*cos(a=i*j*PI*2/37)+','+1e3*sin(a))
```
Only works for prime numbers, such as the original suggestion of 37. You can halve (rounded up) the initial value of `i` to obtain a fainter image. You can also consistently adjust the `1e3,2e3` to other values to taste (I started with `300,600` but decided that it was too coarse).
[Answer]
# MATLAB, 36 bytes
```
@(n)plot(graph(ones(n),'Om'),'La','c')
```
This is an anoymous function that creates the plot.
```
@(n) Define an anonymous fuction of ùòØ
ones(n) Create an ùòØ√óùòØ matrix of ones
graph( ,'Om') Create a graph object with that adjacency
matrix, omitting self-loops
plot( ,'La','c') Plot the graph with a circular layout
```
Example:
[![enter image description here](https://i.stack.imgur.com/kv3Ob.png)](https://i.stack.imgur.com/kv3Ob.png)
[![enter image description here](https://i.stack.imgur.com/4leFr.png)](https://i.stack.imgur.com/4leFr.png)
[Answer]
## QBasic 4.5, ~~398~~ 271 bytes
```
CLS:SCREEN 11:DEFSTR M-Z:DEFDBL A-L
INPUT"N",A:I=(360/A)*.0175:J=230
Q=",":FOR E=0 TO A
FOR F=E TO A
M=x$(COS(I*E)*J+J):N=x$(SIN(I*E)*J+J):O=x$(COS(I*F)*J+J):P=x$(SIN(I*F)*J+J):DRAW "BM"+M+Q+N+"M"+O+Q+P
NEXT:NEXT
FUNCTION x$(d):x$=LTRIM$(STR$(CINT(d))):END FUNCTION
```
The screen in QBasic can onl be 640x480, so the circle has a radius of only 230 px, unfortunately. Also, there's some artifacting because of float-to-int precision loss. Looks like this for `N=36`:
[![enter image description here](https://i.stack.imgur.com/JVsDo.png)](https://i.stack.imgur.com/JVsDo.png)
EDIT: I didn't need the storage, the type declaration and all the looping. Calculating all Carthesians from Polars in place is 50% cheaper in byte count...
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~98~~ 94 bytes
```
$SCREEN 11|:i=6.3/a j=230[0,a|[b,a|line(cos(b*i)*j+j,sin(b*i)*j+j)-(cos(c*i)*j+j,sin(c*o)*j+j)
```
I've converted ~~my original QBasic answer~~ @LevelRiverSt 's answer to QBIC. I thought this would rely too heavily on functions that are not built into QBIC to be feasible, but as it turns out, it saves another 90 bytes. Substituting the
`DRAW` for `LINE` saves another 80 bytes. I knew I was forgetting something simple...
When run with a command line parameter of 36, it looks like this:
[![enter image description here](https://i.stack.imgur.com/5wiXo.png)](https://i.stack.imgur.com/5wiXo.png)
[Answer]
# Processing, 274 bytes (239 + `size` call and function call)
```
void d(int s){float a=2*PI/s,x=0,y=-400,m,n;float[][]p=new float[2][s];translate(400,400);for(int i=0;i<s;i++){m=x*cos(a)-y*sin(a);n=x*sin(a)+y*cos(a);x=m;y=n;p[0][i]=x;p[1][i]=y;for(int j=0;j<i;j++)line(p[0][j],p[1][j],p[0][i],p[1][i]);}}
void setup(){size(800,800);d(50);}
```
I honestly don't know why, but `setup` had to be on the second line. I used <https://en.wikipedia.org/wiki/Rotation_matrix> to help me calculate the maths for rotation. This program calculates the points and pushes them to an array, with which we are using to draw lines.
Here is a picture of a polygon with 50 edges (the 100 edges one was almost completely black)
[![50 points](https://i.stack.imgur.com/Gtooa.jpg)](https://i.stack.imgur.com/Gtooa.jpg)
You can add `stroke(0,alpha);` to have transparent edges, where `alpha` is the opacity of the line. Here's the same polygon with `alpha` of `20`.
[![enter image description here](https://i.stack.imgur.com/Sb4Eg.png)](https://i.stack.imgur.com/Sb4Eg.png)
[Answer]
# Bash + Jelly + GraphViz, 52 characters, 52 or 63 bytes
Given that the programs in question disagree on which character encoding to use, the program is full of control characters. Here's what it looks like under `xxd`, in Latin-1 encoding (which represents each character in one byte):
```
00000000: 6a65 6c6c 7920 6520 2793 5213 636a 0c8e jelly e '.R.cj..
00000010: 2d2d 59fe 9a3f 1d15 dc65 34d3 8442 7f05 --Y..?...e4..B..
00000020: 1172 80cf fb3b ff7d 277c 6369 7263 6f20 .r...;.}'|circo
00000030: 2d54 7073 -Tps
```
I couldn't actually get the program to run, though, without converting the input into UTF-8 for some reason (which would make it 63 bytes long). Logically it *should* work as Latin-1 – none of the characters are outside the range 0 to 255 – but I keep getting "string index out of range" errors no matter how I configure the character encoding environment variables. So this will have to be counted as 63 bytes unless someone can figure out a way to run it without re-encoding it.
The program might be slightly more readable if we interpret it in Jelly's encoding:
```
jelly e 'ƓRŒcj€⁾--Y“Ȥ?øßṇe4ạ⁴B¶¦×r°Ẇ»;”}'|circo -Tps
```
The program takes the number of points on standard input and outputs a PostScript image on standard output. (It can trivially be adapted to output in any format GraphViz supports by changing the `-Tps` at the end; it's just that PostScript has the shortest name. Arguably, you can save five characters by removing the `-Tps`, but then you get output in GraphViz's internal image format that nothing else supports, which probably doesn't count for the purposes of the question.)
Fundamentally, this is just a Jelly program that calls into GraphViz to do the drawing; however, Jelly doesn't seem to have any capabilities for running external programs, so I had to use bash to link them together. (This also means that it's cheaper to make Jelly request input from stdin manually; normally it takes input from the command line, but that would mean extra bytes in the bash wrapper.) `circo` will automatically arrange all the points it's asked to draw in a circle, so the Jelly code just has to ask it to draw a list of points, all of which are connected to each other. Here's how it works:
```
ƓRŒcj€⁾--Y“Ȥ?øßṇe4ạ⁴B¶¦×r°Ẇ»;”}
Ɠ read number from stdin
R produce range from 1 to that number
(here used to produce a list with
that many distinct elements)
Œc select all unordered pairs from that
‚Åæ-- a string consisting of two hyphens
j€ join each pair via the string
Y join on newlines
; prepend (in this context)
“Ȥ?øßṇe4ạ⁴B¶¦×r°Ẇ» "graph{node[shape=point]"
”} follow output with a "}" character
```
The use of Jelly lets us slightly compress the string that configures the GraphViz output via its built-in dictionary. The dictionary has `graph`, `node`, and `point`. Annoyingly, it doesn't have `shape` (it has `SHAPE`, but GraphViz is case-sensitive), so we have to encode that character-by-character.
Here's the output for input 21 (with a slight modification to the program to make it output in a format that can be uploaded to Stack Exchange):
[![complete graph on 21 points](https://i.stack.imgur.com/2nVrk.png)](https://i.stack.imgur.com/2nVrk.png)
[Answer]
# PHP + HTML SVG, ~~316~~ 263 bytes
**Golfed version with hardcoded `n` points and no input `n` parameter:**
```
<svg height="610" width="610"><?for($i=1;$i<33;$i++){$x[]=300*sin(2*M_PI/32*$i)+305;$y[]=300*cos(2*M_PI/32)+305;}foreach($x as$j=>$w){foreach($y as$k=>$z){echo'<line x1="'.$x[$j].'" y1="'.$y[$j].'" x2="'.$x[$k].'" y2="'.$y[$k].'" style="stroke:red;"/>';}}?></svg>
```
**Previous golfed version with input parameter for `n` points, 316 bytes:**
```
<svg height="610" width="610"><?$n=$_GET[n];$d=2*M_PI/$n;$r=300;$o=305;for($i=1;$i<=$n;$i++){$x[]=$r*sin($d*$i)+$o;$y[]=$r*cos($d*$i)+$o;}foreach($x as$j=>$w){foreach($y as$k=>$z){echo'<line x1="'.$x[$j].'" y1="'.$y[$j].'" x2="'.$x[$k].'" y2="'.$y[$k].'" style="stroke:rgba(0,0,0,.15);stroke-width:1;" />';}}?></svg>
```
Usage: save in a file and call from the browser:
```
http://localhost/codegolf/circle.php?n=32
```
Ungolfed version with input parameter for `n` points and CSS:
```
<style>
line {
stroke: rgba(0,0,0,.15);
stroke-width:1;
}
</style>
<svg height="610" width="610">
<?php
$n=$_GET[n]; // number of points
$d=2*M_PI/$n; // circle parts
$r=300; // circle radius
$o=305; // offset x,y
for ($i=1;$i<=$n;$i++){
$x[]=$r*sin($d*$i)+$o; // store x,y coordinates in array
$y[]=$r*cos($d*$i)+$o;
}
foreach($x as $j => $w){ // iterate all x,y points and connect to each other
foreach($y as $k => $z) {
echo '<line x1="'.$x[$j].'" y1="'.$y[$j].'" x2="'.$x[$k].'" y2="'.$y[$k].'" />'."\n";
}
}
?>
</svg>
```
Couldn't attach a 32 points fully functional snippet because of the 30k characters limit for a single post. Here is a screenshot:
[![enter image description here](https://i.stack.imgur.com/ZuUVn.png)](https://i.stack.imgur.com/ZuUVn.png)
The attached snippet is limited to 18 points because of the 30k single post limit.
```
line {
stroke: rgba(0,0,0,.15);
stroke-width:1;
}
```
```
<svg height="610" width="610">
<line x1="407.6060429977" y1="586.90778623577" x2="407.6060429977" y2="586.90778623577" />
<line x1="407.6060429977" y1="586.90778623577" x2="497.83628290596" y2="534.81333293569" />
<line x1="407.6060429977" y1="586.90778623577" x2="564.80762113533" y2="455" />
<line x1="407.6060429977" y1="586.90778623577" x2="600.44232590366" y2="357.09445330008" />
<line x1="407.6060429977" y1="586.90778623577" x2="600.44232590366" y2="252.90554669992" />
<line x1="407.6060429977" y1="586.90778623577" x2="564.80762113533" y2="155" />
<line x1="407.6060429977" y1="586.90778623577" x2="497.83628290596" y2="75.186667064307" />
<line x1="407.6060429977" y1="586.90778623577" x2="407.6060429977" y2="23.092213764227" />
<line x1="407.6060429977" y1="586.90778623577" x2="305" y2="5" />
<line x1="407.6060429977" y1="586.90778623577" x2="202.3939570023" y2="23.092213764227" />
<line x1="407.6060429977" y1="586.90778623577" x2="112.16371709404" y2="75.186667064307" />
<line x1="407.6060429977" y1="586.90778623577" x2="45.192378864669" y2="155" />
<line x1="407.6060429977" y1="586.90778623577" x2="9.5576740963376" y2="252.90554669992" />
<line x1="407.6060429977" y1="586.90778623577" x2="9.5576740963376" y2="357.09445330008" />
<line x1="407.6060429977" y1="586.90778623577" x2="45.192378864668" y2="455" />
<line x1="407.6060429977" y1="586.90778623577" x2="112.16371709404" y2="534.81333293569" />
<line x1="407.6060429977" y1="586.90778623577" x2="202.3939570023" y2="586.90778623577" />
<line x1="407.6060429977" y1="586.90778623577" x2="305" y2="605" />
<line x1="497.83628290596" y1="534.81333293569" x2="407.6060429977" y2="586.90778623577" />
<line x1="497.83628290596" y1="534.81333293569" x2="497.83628290596" y2="534.81333293569" />
<line x1="497.83628290596" y1="534.81333293569" x2="564.80762113533" y2="455" />
<line x1="497.83628290596" y1="534.81333293569" x2="600.44232590366" y2="357.09445330008" />
<line x1="497.83628290596" y1="534.81333293569" x2="600.44232590366" y2="252.90554669992" />
<line x1="497.83628290596" y1="534.81333293569" x2="564.80762113533" y2="155" />
<line x1="497.83628290596" y1="534.81333293569" x2="497.83628290596" y2="75.186667064307" />
<line x1="497.83628290596" y1="534.81333293569" x2="407.6060429977" y2="23.092213764227" />
<line x1="497.83628290596" y1="534.81333293569" x2="305" y2="5" />
<line x1="497.83628290596" y1="534.81333293569" x2="202.3939570023" y2="23.092213764227" />
<line x1="497.83628290596" y1="534.81333293569" x2="112.16371709404" y2="75.186667064307" />
<line x1="497.83628290596" y1="534.81333293569" x2="45.192378864669" y2="155" />
<line x1="497.83628290596" y1="534.81333293569" x2="9.5576740963376" y2="252.90554669992" />
<line x1="497.83628290596" y1="534.81333293569" x2="9.5576740963376" y2="357.09445330008" />
<line x1="497.83628290596" y1="534.81333293569" x2="45.192378864668" y2="455" />
<line x1="497.83628290596" y1="534.81333293569" x2="112.16371709404" y2="534.81333293569" />
<line x1="497.83628290596" y1="534.81333293569" x2="202.3939570023" y2="586.90778623577" />
<line x1="497.83628290596" y1="534.81333293569" x2="305" y2="605" />
<line x1="564.80762113533" y1="455" x2="407.6060429977" y2="586.90778623577" />
<line x1="564.80762113533" y1="455" x2="497.83628290596" y2="534.81333293569" />
<line x1="564.80762113533" y1="455" x2="564.80762113533" y2="455" />
<line x1="564.80762113533" y1="455" x2="600.44232590366" y2="357.09445330008" />
<line x1="564.80762113533" y1="455" x2="600.44232590366" y2="252.90554669992" />
<line x1="564.80762113533" y1="455" x2="564.80762113533" y2="155" />
<line x1="564.80762113533" y1="455" x2="497.83628290596" y2="75.186667064307" />
<line x1="564.80762113533" y1="455" x2="407.6060429977" y2="23.092213764227" />
<line x1="564.80762113533" y1="455" x2="305" y2="5" />
<line x1="564.80762113533" y1="455" x2="202.3939570023" y2="23.092213764227" />
<line x1="564.80762113533" y1="455" x2="112.16371709404" y2="75.186667064307" />
<line x1="564.80762113533" y1="455" x2="45.192378864669" y2="155" />
<line x1="564.80762113533" y1="455" x2="9.5576740963376" y2="252.90554669992" />
<line x1="564.80762113533" y1="455" x2="9.5576740963376" y2="357.09445330008" />
<line x1="564.80762113533" y1="455" x2="45.192378864668" y2="455" />
<line x1="564.80762113533" y1="455" x2="112.16371709404" y2="534.81333293569" />
<line x1="564.80762113533" y1="455" x2="202.3939570023" y2="586.90778623577" />
<line x1="564.80762113533" y1="455" x2="305" y2="605" />
<line x1="600.44232590366" y1="357.09445330008" x2="407.6060429977" y2="586.90778623577" />
<line x1="600.44232590366" y1="357.09445330008" x2="497.83628290596" y2="534.81333293569" />
<line x1="600.44232590366" y1="357.09445330008" x2="564.80762113533" y2="455" />
<line x1="600.44232590366" y1="357.09445330008" x2="600.44232590366" y2="357.09445330008" />
<line x1="600.44232590366" y1="357.09445330008" x2="600.44232590366" y2="252.90554669992" />
<line x1="600.44232590366" y1="357.09445330008" x2="564.80762113533" y2="155" />
<line x1="600.44232590366" y1="357.09445330008" x2="497.83628290596" y2="75.186667064307" />
<line x1="600.44232590366" y1="357.09445330008" x2="407.6060429977" y2="23.092213764227" />
<line x1="600.44232590366" y1="357.09445330008" x2="305" y2="5" />
<line x1="600.44232590366" y1="357.09445330008" x2="202.3939570023" y2="23.092213764227" />
<line x1="600.44232590366" y1="357.09445330008" x2="112.16371709404" y2="75.186667064307" />
<line x1="600.44232590366" y1="357.09445330008" x2="45.192378864669" y2="155" />
<line x1="600.44232590366" y1="357.09445330008" x2="9.5576740963376" y2="252.90554669992" />
<line x1="600.44232590366" y1="357.09445330008" x2="9.5576740963376" y2="357.09445330008" />
<line x1="600.44232590366" y1="357.09445330008" x2="45.192378864668" y2="455" />
<line x1="600.44232590366" y1="357.09445330008" x2="112.16371709404" y2="534.81333293569" />
<line x1="600.44232590366" y1="357.09445330008" x2="202.3939570023" y2="586.90778623577" />
<line x1="600.44232590366" y1="357.09445330008" x2="305" y2="605" />
<line x1="600.44232590366" y1="252.90554669992" x2="407.6060429977" y2="586.90778623577" />
<line x1="600.44232590366" y1="252.90554669992" x2="497.83628290596" y2="534.81333293569" />
<line x1="600.44232590366" y1="252.90554669992" x2="564.80762113533" y2="455" />
<line x1="600.44232590366" y1="252.90554669992" x2="600.44232590366" y2="357.09445330008" />
<line x1="600.44232590366" y1="252.90554669992" x2="600.44232590366" y2="252.90554669992" />
<line x1="600.44232590366" y1="252.90554669992" x2="564.80762113533" y2="155" />
<line x1="600.44232590366" y1="252.90554669992" x2="497.83628290596" y2="75.186667064307" />
<line x1="600.44232590366" y1="252.90554669992" x2="407.6060429977" y2="23.092213764227" />
<line x1="600.44232590366" y1="252.90554669992" x2="305" y2="5" />
<line x1="600.44232590366" y1="252.90554669992" x2="202.3939570023" y2="23.092213764227" />
<line x1="600.44232590366" y1="252.90554669992" x2="112.16371709404" y2="75.186667064307" />
<line x1="600.44232590366" y1="252.90554669992" x2="45.192378864669" y2="155" />
<line x1="600.44232590366" y1="252.90554669992" x2="9.5576740963376" y2="252.90554669992" />
<line x1="600.44232590366" y1="252.90554669992" x2="9.5576740963376" y2="357.09445330008" />
<line x1="600.44232590366" y1="252.90554669992" x2="45.192378864668" y2="455" />
<line x1="600.44232590366" y1="252.90554669992" x2="112.16371709404" y2="534.81333293569" />
<line x1="600.44232590366" y1="252.90554669992" x2="202.3939570023" y2="586.90778623577" />
<line x1="600.44232590366" y1="252.90554669992" x2="305" y2="605" />
<line x1="564.80762113533" y1="155" x2="407.6060429977" y2="586.90778623577" />
<line x1="564.80762113533" y1="155" x2="497.83628290596" y2="534.81333293569" />
<line x1="564.80762113533" y1="155" x2="564.80762113533" y2="455" />
<line x1="564.80762113533" y1="155" x2="600.44232590366" y2="357.09445330008" />
<line x1="564.80762113533" y1="155" x2="600.44232590366" y2="252.90554669992" />
<line x1="564.80762113533" y1="155" x2="564.80762113533" y2="155" />
<line x1="564.80762113533" y1="155" x2="497.83628290596" y2="75.186667064307" />
<line x1="564.80762113533" y1="155" x2="407.6060429977" y2="23.092213764227" />
<line x1="564.80762113533" y1="155" x2="305" y2="5" />
<line x1="564.80762113533" y1="155" x2="202.3939570023" y2="23.092213764227" />
<line x1="564.80762113533" y1="155" x2="112.16371709404" y2="75.186667064307" />
<line x1="564.80762113533" y1="155" x2="45.192378864669" y2="155" />
<line x1="564.80762113533" y1="155" x2="9.5576740963376" y2="252.90554669992" />
<line x1="564.80762113533" y1="155" x2="9.5576740963376" y2="357.09445330008" />
<line x1="564.80762113533" y1="155" x2="45.192378864668" y2="455" />
<line x1="564.80762113533" y1="155" x2="112.16371709404" y2="534.81333293569" />
<line x1="564.80762113533" y1="155" x2="202.3939570023" y2="586.90778623577" />
<line x1="564.80762113533" y1="155" x2="305" y2="605" />
<line x1="497.83628290596" y1="75.186667064307" x2="407.6060429977" y2="586.90778623577" />
<line x1="497.83628290596" y1="75.186667064307" x2="497.83628290596" y2="534.81333293569" />
<line x1="497.83628290596" y1="75.186667064307" x2="564.80762113533" y2="455" />
<line x1="497.83628290596" y1="75.186667064307" x2="600.44232590366" y2="357.09445330008" />
<line x1="497.83628290596" y1="75.186667064307" x2="600.44232590366" y2="252.90554669992" />
<line x1="497.83628290596" y1="75.186667064307" x2="564.80762113533" y2="155" />
<line x1="497.83628290596" y1="75.186667064307" x2="497.83628290596" y2="75.186667064307" />
<line x1="497.83628290596" y1="75.186667064307" x2="407.6060429977" y2="23.092213764227" />
<line x1="497.83628290596" y1="75.186667064307" x2="305" y2="5" />
<line x1="497.83628290596" y1="75.186667064307" x2="202.3939570023" y2="23.092213764227" />
<line x1="497.83628290596" y1="75.186667064307" x2="112.16371709404" y2="75.186667064307" />
<line x1="497.83628290596" y1="75.186667064307" x2="45.192378864669" y2="155" />
<line x1="497.83628290596" y1="75.186667064307" x2="9.5576740963376" y2="252.90554669992" />
<line x1="497.83628290596" y1="75.186667064307" x2="9.5576740963376" y2="357.09445330008" />
<line x1="497.83628290596" y1="75.186667064307" x2="45.192378864668" y2="455" />
<line x1="497.83628290596" y1="75.186667064307" x2="112.16371709404" y2="534.81333293569" />
<line x1="497.83628290596" y1="75.186667064307" x2="202.3939570023" y2="586.90778623577" />
<line x1="497.83628290596" y1="75.186667064307" x2="305" y2="605" />
<line x1="407.6060429977" y1="23.092213764227" x2="407.6060429977" y2="586.90778623577" />
<line x1="407.6060429977" y1="23.092213764227" x2="497.83628290596" y2="534.81333293569" />
<line x1="407.6060429977" y1="23.092213764227" x2="564.80762113533" y2="455" />
<line x1="407.6060429977" y1="23.092213764227" x2="600.44232590366" y2="357.09445330008" />
<line x1="407.6060429977" y1="23.092213764227" x2="600.44232590366" y2="252.90554669992" />
<line x1="407.6060429977" y1="23.092213764227" x2="564.80762113533" y2="155" />
<line x1="407.6060429977" y1="23.092213764227" x2="497.83628290596" y2="75.186667064307" />
<line x1="407.6060429977" y1="23.092213764227" x2="407.6060429977" y2="23.092213764227" />
<line x1="407.6060429977" y1="23.092213764227" x2="305" y2="5" />
<line x1="407.6060429977" y1="23.092213764227" x2="202.3939570023" y2="23.092213764227" />
<line x1="407.6060429977" y1="23.092213764227" x2="112.16371709404" y2="75.186667064307" />
<line x1="407.6060429977" y1="23.092213764227" x2="45.192378864669" y2="155" />
<line x1="407.6060429977" y1="23.092213764227" x2="9.5576740963376" y2="252.90554669992" />
<line x1="407.6060429977" y1="23.092213764227" x2="9.5576740963376" y2="357.09445330008" />
<line x1="407.6060429977" y1="23.092213764227" x2="45.192378864668" y2="455" />
<line x1="407.6060429977" y1="23.092213764227" x2="112.16371709404" y2="534.81333293569" />
<line x1="407.6060429977" y1="23.092213764227" x2="202.3939570023" y2="586.90778623577" />
<line x1="407.6060429977" y1="23.092213764227" x2="305" y2="605" />
<line x1="305" y1="5" x2="407.6060429977" y2="586.90778623577" />
<line x1="305" y1="5" x2="497.83628290596" y2="534.81333293569" />
<line x1="305" y1="5" x2="564.80762113533" y2="455" />
<line x1="305" y1="5" x2="600.44232590366" y2="357.09445330008" />
<line x1="305" y1="5" x2="600.44232590366" y2="252.90554669992" />
<line x1="305" y1="5" x2="564.80762113533" y2="155" />
<line x1="305" y1="5" x2="497.83628290596" y2="75.186667064307" />
<line x1="305" y1="5" x2="407.6060429977" y2="23.092213764227" />
<line x1="305" y1="5" x2="305" y2="5" />
<line x1="305" y1="5" x2="202.3939570023" y2="23.092213764227" />
<line x1="305" y1="5" x2="112.16371709404" y2="75.186667064307" />
<line x1="305" y1="5" x2="45.192378864669" y2="155" />
<line x1="305" y1="5" x2="9.5576740963376" y2="252.90554669992" />
<line x1="305" y1="5" x2="9.5576740963376" y2="357.09445330008" />
<line x1="305" y1="5" x2="45.192378864668" y2="455" />
<line x1="305" y1="5" x2="112.16371709404" y2="534.81333293569" />
<line x1="305" y1="5" x2="202.3939570023" y2="586.90778623577" />
<line x1="305" y1="5" x2="305" y2="605" />
<line x1="202.3939570023" y1="23.092213764227" x2="407.6060429977" y2="586.90778623577" />
<line x1="202.3939570023" y1="23.092213764227" x2="497.83628290596" y2="534.81333293569" />
<line x1="202.3939570023" y1="23.092213764227" x2="564.80762113533" y2="455" />
<line x1="202.3939570023" y1="23.092213764227" x2="600.44232590366" y2="357.09445330008" />
<line x1="202.3939570023" y1="23.092213764227" x2="600.44232590366" y2="252.90554669992" />
<line x1="202.3939570023" y1="23.092213764227" x2="564.80762113533" y2="155" />
<line x1="202.3939570023" y1="23.092213764227" x2="497.83628290596" y2="75.186667064307" />
<line x1="202.3939570023" y1="23.092213764227" x2="407.6060429977" y2="23.092213764227" />
<line x1="202.3939570023" y1="23.092213764227" x2="305" y2="5" />
<line x1="202.3939570023" y1="23.092213764227" x2="202.3939570023" y2="23.092213764227" />
<line x1="202.3939570023" y1="23.092213764227" x2="112.16371709404" y2="75.186667064307" />
<line x1="202.3939570023" y1="23.092213764227" x2="45.192378864669" y2="155" />
<line x1="202.3939570023" y1="23.092213764227" x2="9.5576740963376" y2="252.90554669992" />
<line x1="202.3939570023" y1="23.092213764227" x2="9.5576740963376" y2="357.09445330008" />
<line x1="202.3939570023" y1="23.092213764227" x2="45.192378864668" y2="455" />
<line x1="202.3939570023" y1="23.092213764227" x2="112.16371709404" y2="534.81333293569" />
<line x1="202.3939570023" y1="23.092213764227" x2="202.3939570023" y2="586.90778623577" />
<line x1="202.3939570023" y1="23.092213764227" x2="305" y2="605" />
<line x1="112.16371709404" y1="75.186667064307" x2="407.6060429977" y2="586.90778623577" />
<line x1="112.16371709404" y1="75.186667064307" x2="497.83628290596" y2="534.81333293569" />
<line x1="112.16371709404" y1="75.186667064307" x2="564.80762113533" y2="455" />
<line x1="112.16371709404" y1="75.186667064307" x2="600.44232590366" y2="357.09445330008" />
<line x1="112.16371709404" y1="75.186667064307" x2="600.44232590366" y2="252.90554669992" />
<line x1="112.16371709404" y1="75.186667064307" x2="564.80762113533" y2="155" />
<line x1="112.16371709404" y1="75.186667064307" x2="497.83628290596" y2="75.186667064307" />
<line x1="112.16371709404" y1="75.186667064307" x2="407.6060429977" y2="23.092213764227" />
<line x1="112.16371709404" y1="75.186667064307" x2="305" y2="5" />
<line x1="112.16371709404" y1="75.186667064307" x2="202.3939570023" y2="23.092213764227" />
<line x1="112.16371709404" y1="75.186667064307" x2="112.16371709404" y2="75.186667064307" />
<line x1="112.16371709404" y1="75.186667064307" x2="45.192378864669" y2="155" />
<line x1="112.16371709404" y1="75.186667064307" x2="9.5576740963376" y2="252.90554669992" />
<line x1="112.16371709404" y1="75.186667064307" x2="9.5576740963376" y2="357.09445330008" />
<line x1="112.16371709404" y1="75.186667064307" x2="45.192378864668" y2="455" />
<line x1="112.16371709404" y1="75.186667064307" x2="112.16371709404" y2="534.81333293569" />
<line x1="112.16371709404" y1="75.186667064307" x2="202.3939570023" y2="586.90778623577" />
<line x1="112.16371709404" y1="75.186667064307" x2="305" y2="605" />
<line x1="45.192378864669" y1="155" x2="407.6060429977" y2="586.90778623577" />
<line x1="45.192378864669" y1="155" x2="497.83628290596" y2="534.81333293569" />
<line x1="45.192378864669" y1="155" x2="564.80762113533" y2="455" />
<line x1="45.192378864669" y1="155" x2="600.44232590366" y2="357.09445330008" />
<line x1="45.192378864669" y1="155" x2="600.44232590366" y2="252.90554669992" />
<line x1="45.192378864669" y1="155" x2="564.80762113533" y2="155" />
<line x1="45.192378864669" y1="155" x2="497.83628290596" y2="75.186667064307" />
<line x1="45.192378864669" y1="155" x2="407.6060429977" y2="23.092213764227" />
<line x1="45.192378864669" y1="155" x2="305" y2="5" />
<line x1="45.192378864669" y1="155" x2="202.3939570023" y2="23.092213764227" />
<line x1="45.192378864669" y1="155" x2="112.16371709404" y2="75.186667064307" />
<line x1="45.192378864669" y1="155" x2="45.192378864669" y2="155" />
<line x1="45.192378864669" y1="155" x2="9.5576740963376" y2="252.90554669992" />
<line x1="45.192378864669" y1="155" x2="9.5576740963376" y2="357.09445330008" />
<line x1="45.192378864669" y1="155" x2="45.192378864668" y2="455" />
<line x1="45.192378864669" y1="155" x2="112.16371709404" y2="534.81333293569" />
<line x1="45.192378864669" y1="155" x2="202.3939570023" y2="586.90778623577" />
<line x1="45.192378864669" y1="155" x2="305" y2="605" />
<line x1="9.5576740963376" y1="252.90554669992" x2="407.6060429977" y2="586.90778623577" />
<line x1="9.5576740963376" y1="252.90554669992" x2="497.83628290596" y2="534.81333293569" />
<line x1="9.5576740963376" y1="252.90554669992" x2="564.80762113533" y2="455" />
<line x1="9.5576740963376" y1="252.90554669992" x2="600.44232590366" y2="357.09445330008" />
<line x1="9.5576740963376" y1="252.90554669992" x2="600.44232590366" y2="252.90554669992" />
<line x1="9.5576740963376" y1="252.90554669992" x2="564.80762113533" y2="155" />
<line x1="9.5576740963376" y1="252.90554669992" x2="497.83628290596" y2="75.186667064307" />
<line x1="9.5576740963376" y1="252.90554669992" x2="407.6060429977" y2="23.092213764227" />
<line x1="9.5576740963376" y1="252.90554669992" x2="305" y2="5" />
<line x1="9.5576740963376" y1="252.90554669992" x2="202.3939570023" y2="23.092213764227" />
<line x1="9.5576740963376" y1="252.90554669992" x2="112.16371709404" y2="75.186667064307" />
<line x1="9.5576740963376" y1="252.90554669992" x2="45.192378864669" y2="155" />
<line x1="9.5576740963376" y1="252.90554669992" x2="9.5576740963376" y2="252.90554669992" />
<line x1="9.5576740963376" y1="252.90554669992" x2="9.5576740963376" y2="357.09445330008" />
<line x1="9.5576740963376" y1="252.90554669992" x2="45.192378864668" y2="455" />
<line x1="9.5576740963376" y1="252.90554669992" x2="112.16371709404" y2="534.81333293569" />
<line x1="9.5576740963376" y1="252.90554669992" x2="202.3939570023" y2="586.90778623577" />
<line x1="9.5576740963376" y1="252.90554669992" x2="305" y2="605" />
<line x1="9.5576740963376" y1="357.09445330008" x2="407.6060429977" y2="586.90778623577" />
<line x1="9.5576740963376" y1="357.09445330008" x2="497.83628290596" y2="534.81333293569" />
<line x1="9.5576740963376" y1="357.09445330008" x2="564.80762113533" y2="455" />
<line x1="9.5576740963376" y1="357.09445330008" x2="600.44232590366" y2="357.09445330008" />
<line x1="9.5576740963376" y1="357.09445330008" x2="600.44232590366" y2="252.90554669992" />
<line x1="9.5576740963376" y1="357.09445330008" x2="564.80762113533" y2="155" />
<line x1="9.5576740963376" y1="357.09445330008" x2="497.83628290596" y2="75.186667064307" />
<line x1="9.5576740963376" y1="357.09445330008" x2="407.6060429977" y2="23.092213764227" />
<line x1="9.5576740963376" y1="357.09445330008" x2="305" y2="5" />
<line x1="9.5576740963376" y1="357.09445330008" x2="202.3939570023" y2="23.092213764227" />
<line x1="9.5576740963376" y1="357.09445330008" x2="112.16371709404" y2="75.186667064307" />
<line x1="9.5576740963376" y1="357.09445330008" x2="45.192378864669" y2="155" />
<line x1="9.5576740963376" y1="357.09445330008" x2="9.5576740963376" y2="252.90554669992" />
<line x1="9.5576740963376" y1="357.09445330008" x2="9.5576740963376" y2="357.09445330008" />
<line x1="9.5576740963376" y1="357.09445330008" x2="45.192378864668" y2="455" />
<line x1="9.5576740963376" y1="357.09445330008" x2="112.16371709404" y2="534.81333293569" />
<line x1="9.5576740963376" y1="357.09445330008" x2="202.3939570023" y2="586.90778623577" />
<line x1="9.5576740963376" y1="357.09445330008" x2="305" y2="605" />
<line x1="45.192378864668" y1="455" x2="407.6060429977" y2="586.90778623577" />
<line x1="45.192378864668" y1="455" x2="497.83628290596" y2="534.81333293569" />
<line x1="45.192378864668" y1="455" x2="564.80762113533" y2="455" />
<line x1="45.192378864668" y1="455" x2="600.44232590366" y2="357.09445330008" />
<line x1="45.192378864668" y1="455" x2="600.44232590366" y2="252.90554669992" />
<line x1="45.192378864668" y1="455" x2="564.80762113533" y2="155" />
<line x1="45.192378864668" y1="455" x2="497.83628290596" y2="75.186667064307" />
<line x1="45.192378864668" y1="455" x2="407.6060429977" y2="23.092213764227" />
<line x1="45.192378864668" y1="455" x2="305" y2="5" />
<line x1="45.192378864668" y1="455" x2="202.3939570023" y2="23.092213764227" />
<line x1="45.192378864668" y1="455" x2="112.16371709404" y2="75.186667064307" />
<line x1="45.192378864668" y1="455" x2="45.192378864669" y2="155" />
<line x1="45.192378864668" y1="455" x2="9.5576740963376" y2="252.90554669992" />
<line x1="45.192378864668" y1="455" x2="9.5576740963376" y2="357.09445330008" />
<line x1="45.192378864668" y1="455" x2="45.192378864668" y2="455" />
<line x1="45.192378864668" y1="455" x2="112.16371709404" y2="534.81333293569" />
<line x1="45.192378864668" y1="455" x2="202.3939570023" y2="586.90778623577" />
<line x1="45.192378864668" y1="455" x2="305" y2="605" />
<line x1="112.16371709404" y1="534.81333293569" x2="407.6060429977" y2="586.90778623577" />
<line x1="112.16371709404" y1="534.81333293569" x2="497.83628290596" y2="534.81333293569" />
<line x1="112.16371709404" y1="534.81333293569" x2="564.80762113533" y2="455" />
<line x1="112.16371709404" y1="534.81333293569" x2="600.44232590366" y2="357.09445330008" />
<line x1="112.16371709404" y1="534.81333293569" x2="600.44232590366" y2="252.90554669992" />
<line x1="112.16371709404" y1="534.81333293569" x2="564.80762113533" y2="155" />
<line x1="112.16371709404" y1="534.81333293569" x2="497.83628290596" y2="75.186667064307" />
<line x1="112.16371709404" y1="534.81333293569" x2="407.6060429977" y2="23.092213764227" />
<line x1="112.16371709404" y1="534.81333293569" x2="305" y2="5" />
<line x1="112.16371709404" y1="534.81333293569" x2="202.3939570023" y2="23.092213764227" />
<line x1="112.16371709404" y1="534.81333293569" x2="112.16371709404" y2="75.186667064307" />
<line x1="112.16371709404" y1="534.81333293569" x2="45.192378864669" y2="155" />
<line x1="112.16371709404" y1="534.81333293569" x2="9.5576740963376" y2="252.90554669992" />
<line x1="112.16371709404" y1="534.81333293569" x2="9.5576740963376" y2="357.09445330008" />
<line x1="112.16371709404" y1="534.81333293569" x2="45.192378864668" y2="455" />
<line x1="112.16371709404" y1="534.81333293569" x2="112.16371709404" y2="534.81333293569" />
<line x1="112.16371709404" y1="534.81333293569" x2="202.3939570023" y2="586.90778623577" />
<line x1="112.16371709404" y1="534.81333293569" x2="305" y2="605" />
<line x1="202.3939570023" y1="586.90778623577" x2="407.6060429977" y2="586.90778623577" />
<line x1="202.3939570023" y1="586.90778623577" x2="497.83628290596" y2="534.81333293569" />
<line x1="202.3939570023" y1="586.90778623577" x2="564.80762113533" y2="455" />
<line x1="202.3939570023" y1="586.90778623577" x2="600.44232590366" y2="357.09445330008" />
<line x1="202.3939570023" y1="586.90778623577" x2="600.44232590366" y2="252.90554669992" />
<line x1="202.3939570023" y1="586.90778623577" x2="564.80762113533" y2="155" />
<line x1="202.3939570023" y1="586.90778623577" x2="497.83628290596" y2="75.186667064307" />
<line x1="202.3939570023" y1="586.90778623577" x2="407.6060429977" y2="23.092213764227" />
<line x1="202.3939570023" y1="586.90778623577" x2="305" y2="5" />
<line x1="202.3939570023" y1="586.90778623577" x2="202.3939570023" y2="23.092213764227" />
<line x1="202.3939570023" y1="586.90778623577" x2="112.16371709404" y2="75.186667064307" />
<line x1="202.3939570023" y1="586.90778623577" x2="45.192378864669" y2="155" />
<line x1="202.3939570023" y1="586.90778623577" x2="9.5576740963376" y2="252.90554669992" />
<line x1="202.3939570023" y1="586.90778623577" x2="9.5576740963376" y2="357.09445330008" />
<line x1="202.3939570023" y1="586.90778623577" x2="45.192378864668" y2="455" />
<line x1="202.3939570023" y1="586.90778623577" x2="112.16371709404" y2="534.81333293569" />
<line x1="202.3939570023" y1="586.90778623577" x2="202.3939570023" y2="586.90778623577" />
<line x1="202.3939570023" y1="586.90778623577" x2="305" y2="605" />
<line x1="305" y1="605" x2="407.6060429977" y2="586.90778623577" />
<line x1="305" y1="605" x2="497.83628290596" y2="534.81333293569" />
<line x1="305" y1="605" x2="564.80762113533" y2="455" />
<line x1="305" y1="605" x2="600.44232590366" y2="357.09445330008" />
<line x1="305" y1="605" x2="600.44232590366" y2="252.90554669992" />
<line x1="305" y1="605" x2="564.80762113533" y2="155" />
<line x1="305" y1="605" x2="497.83628290596" y2="75.186667064307" />
<line x1="305" y1="605" x2="407.6060429977" y2="23.092213764227" />
<line x1="305" y1="605" x2="305" y2="5" />
<line x1="305" y1="605" x2="202.3939570023" y2="23.092213764227" />
<line x1="305" y1="605" x2="112.16371709404" y2="75.186667064307" />
<line x1="305" y1="605" x2="45.192378864669" y2="155" />
<line x1="305" y1="605" x2="9.5576740963376" y2="252.90554669992" />
<line x1="305" y1="605" x2="9.5576740963376" y2="357.09445330008" />
<line x1="305" y1="605" x2="45.192378864668" y2="455" />
<line x1="305" y1="605" x2="112.16371709404" y2="534.81333293569" />
<line x1="305" y1="605" x2="202.3939570023" y2="586.90778623577" />
<line x1="305" y1="605" x2="305" y2="605" />
</svg>
```
[Answer]
# R, 108 bytes
```
plot(x<-cos(t<-seq(0,2*pi,l=21)),y<-sin(t),as=1);apply(expand.grid(1:21,1:21),1,function(e)lines(x[e],y[e]))
```
Could shave 5 bytes off if I got rid of argument `,as=1` which forces an aspect ratio of 1. Uses `expand.grid` to create a matrix with all possible pair of points, and uses `apply` to loop through it.
[![N=21](https://i.stack.imgur.com/ztK6z.png)](https://i.stack.imgur.com/ztK6z.png)
# R + igraph, 87 bytes
Another solution using package `igraph`.
```
library(igraph);plot(make_full_graph(21),layout=cbind(cos(t<-seq(0,2*pi,l=21)),sin(t)))
```
[![N=21](https://i.stack.imgur.com/0Nvl0.png)](https://i.stack.imgur.com/0Nvl0.png)
] |
[Question]
[
Given a set of letters, output all strings made of those letters. (This is [Kleene star](https://en.wikipedia.org/wiki/Kleene_star) of the set.) For example, for `{'a','b'}`, the strings are:
```
'', 'a', 'b', 'aa', 'ab', 'ba', 'bb', 'aaa', 'aab', ...
```
**Input:** A non-empty collection of distinct letters `a..z`. These may be characters or single-character strings.
**Output:** All strings in those letters, in any order, without repeats. You may use lists of chars as strings.
This is an infinite list, so you can output it by:
* Running forever writing more and more strings. These strings can be written in any flat separated format, meaning that they you can tell where each string ends, but the strings aren't subdivided into groups.
* Taking a number `n` as input and outputting the first `n` strings in any flat separated format
* Yielding each string in turn from a generator object
* Producing an infinite object
Be sure that your method eventually produces every string in the output, since it's possible to produce infinitely many strings from the set while never getting to some strings.
You may **not** output it by
* Producing the `n`th string given `n`
* Providing a membership oracle that decides if a given string belongs to the set
Built-ins are allowed, but I ask voters to give attention to answers that implement the operation themselves over ones that mostly rely on a built-in.
```
var QUESTION_ID=74273,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/74273/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]
# Python 2, 53 ~~56~~
-3 after realizing that `yield x` can be used as an expression.
```
def f(s):yield'';[(yield w+c)for w in f(s)for c in s]
```
[Answer]
# Haskell, 24 bytes
```
f s=[]:[b:a|a<-f s,b<-s]
```
Produces an infinite list.
```
*Main> f "abc"
["","a","b","c","aa","ba","ca","ab","bb","cb","ac","bc","cc","aaa","baa","caa","aba","bba","cba",…
```
[Answer]
# Mathematica, ~~32~~ 31 Bytes
```
Do[Echo/@#~Tuples~n,{n,0,∞}]&
```
# Edit:
CatsAreFluffy scraped off one byte.
[Answer]
## JavaScript (ES6), 61 bytes
```
function*g(s){yield'';for(let r of g(s))for(c of s)yield c+r}
```
Port of @feersum's Python generator. The `let` is necessary. Save 2 bytes by using an array comprehension (failed ES7 proposal, but works in Firefox 30-57):
```
function*g(s){yield'';[for(r of g(s))for(c of s)yield c+r]}
```
Alternative version for 73 bytes that returns the first `n` elements yielded by the above generator:
```
(s,n)=>Array(n).fill('').map(g=(r,i)=>i--?g(r+s[i%l],i/l|0):r,l=s.length)
```
[Answer]
# Perl, ~~39~~ ~~37~~ 35 bytes
(First describes an older version. The new shorter program is at the end)
Includes +3 for `-alp`
Run with the set of characters on STDIN, e.g. `perl -alp kleene.pl <<< "a b c"`
`kleene.pl` (this version is 34+3 bytes):
```
$#a=$"=","}for(@a){push@a,<{@F}$_>
```
Add +2 for `-F` (drop implicit `-a` if no spaces between input characters, or -6 (only `@a=""` before `}`) if we already put commas between the characters on STDIN
## Explanation:
The `-alp` options make the code effectively:
```
BEGIN { $/ = "\n"; $\ = "\n"; }
LINE: while (defined($_ = <ARGV>)) {
chomp $_;
our @F = split(' ', $_, 0);
$#a = $" = ',';
}
foreach $_ (@a) {
use File::Glob ();
push @a, glob('{' . join($", @F) . '}' . $_);
}
```
As you can see `<>` in perl is not only used for readline, but can also do shell style globbing (in fact in ancient perls it was implemented by calling the shell).
For example `<{a,b}{1,2}>` will expand to `"a1","a2","b1","b2"`
So if we have the elements in `@F` we just need to add commas inbetween. The default inbetween character for interpolation is space, which is stored in special variable `$"`. So setting `$"` to `,` will turn `"{@F}"` into `{a,b}` if `@F=qw(a b)` (globs expand as strings)
In fact I would really have liked to loop with something like `glob"{@F}"x$n++`, but I kept running into the problem that the first empty line doesn't get generated and all workarounds I found made the code too long.
So another essential part of this code is that if you use a `for` to loop over an array you can actually push extra elements on it during the loop and the loop will also pick up these new elements. So if in the loop we are e.g. at element `"ab"`, then `<{@F}$_>` will expand to `<{a,b}ab>` which in list context becomes `("aab", "bab")`. So if I push these on `@a` then the strings extended one to the left become available too
All I still need to do is prime the loop with an empty string. That is done using`$#a = 0` (`,` in numeric context becomes `0`) which causes the first and only element of `@a` to become undef which will behave like `""` when I use it
## Improvement
In fact by doing tests for this explanation I found a short way to use a growing glob that properly handles the first empty entry. Run as `perl -ap kleene0.pl <<< "a b"` (so add 2 bytes for `-ap`)
`kleene0.pl` (this version is 33+2 bytes):
```
$"=",";print<$z,>;$z.="{@F}";redo
```
All these solutions will keep more and more of the output in memory and that will cause the program to fail after some time. You can also use perl globs for lazy generation by using them in scalar context, but that makes the programs longer....
[Answer]
# Pyth, 7
```
<s^LzQQ
```
[Try it here](http://pyth.herokuapp.com/?code=%3Cs%5ELzQQ&input=ab%0A4&debug=0)
This computes the cartesian product of the input with each number from `0..n-1`, joins them, and then only keeps the first `n`. This will time out online for numbers or strings that are much bigger than 3-4.
Alternatively, to get infinite output look at Jakube's [answer](https://codegolf.stackexchange.com/a/74287/31625).
[Answer]
# Jelly, ~~8~~ 6 bytes
```
⁷³p$Ȯ¿
```
[Try it online!](http://jelly.tryitonline.net/#code=4oG3wrNwJMiuwr8&input=&args=YWI)
### How it works
```
⁷³p$Ȯ¿ Monadic link. Argument: A (alphabet)
⁷ Set the return value to '\n'.
¿ While loop.
Condition:
Ȯ Print the current return value and return it (always truthy).
Body:
$ Combine the two links to the left into a single, monadic link.
³ Yield A.
p Perform the Cartesian product of A and the current return value,
updating the return value in the process.
```
## Alternate version, 6 bytes
```
R’ḃL}ị
```
This is a dyadic link that accepts an alphabet and the desired number of strings as left and right arguments, respectively.
[Try it online!](http://jelly.tryitonline.net/#code=UuKAmeG4g0x94buLCsOn4bm-&input=&args=Nw+YWI)
### How it works
```
R’ḃL}ị Dyadic link. Arguments: n (integer), A (alphabet)
R Range; yield [1, ..., n].
’ Decrement; yield [0, ..., n-1].
L} Yield l, the length of A.
ḃ Convert every i in [0, ..., n-1] to bijective base l.
ị For each array of digits, retrieve the corresponding characters of A.
```
[Answer]
# Python 2, ~~89~~ ~~84~~ 83 bytes
```
x,n=input()
l=len(x)
for i in range(n):
s=''
while i:i-=1;s+=x[i%l];i/=l
print s
```
[Answer]
## CJam, ~~16~~ 10 bytes
*Thanks to jimmy23013 for saving 6 bytes.*
```
N{eam*_o}h
```
Input is one command-line argument per character. Output is one string on each line.
[Try it online!](http://cjam.tryitonline.net/#code=TGF7XzpwO2Vhc20qOnN9aA&input=&args=YWI) (But kill it immediately...)
### Explanation
```
N e# Push [\n]. At each step this array will contain all strings of length N,
e# each followed by a linefeed.
{ e# Infinite loop...
ea e# Read command-line arguments.
m* e# Cartesian product: pairs each letter with each string in the list.
_o e# Output all the strings of the current length.
}h
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 2 bytes
```
Ňŧ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FkuOth9dvqQ4KbkYKrBgiVJikhKEDQA)
```
Ňŧ
Ň Nondeterministically choose an natural number, say n
ŧ Nondeterministically choose a tuple of n elements from the input list
```
In the default mode, Nekomata prints all possible outputs.
[Answer]
# Pyth, 7 bytes
```
.V0j^zb
```
Alternative to @fry.
This program reads a string and keeps on printing strings until infinity.
### Explanation:
```
.V0 for b in (0 to infinity):
^zb compute all strings of length b consisting of the input alphabet
j print each one on a separate line
```
Alternatively the following will also work. A little bit more hacky though.
```
u
M^zH7
```
[Answer]
# Haskell, 33 bytes
```
k u=do s<-[0..];mapM(\_->u)[1..s]
```
For exampe, `k "xyz"` is the infinite list `["","x","y","z","xx","xy","xz","yx","yy","yz","zx","zy","zz","xxx",...]`
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 10 bytes
```
0cD`G@Z^DT
```
[**Try it online!**](http://matl.tryitonline.net/#code=MGNEYEdAWl5EVA&input=J2FiJw) But don't leave it running for long, to avoid large computational load on the server.
The program displays the strings dynamically, each string on a different line.
```
0cD % force display of a newline to represent the empty string
` T % infinite do-while loop
G % push input, or nothing if no input has been taken yet
@ % push iteration. Gives 1, 2,... in each iteration
Z^ % Cartesian power. In the first iteration takes input implicitly
D % display
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~6 7~~ 5 bytes
```
Θṁπ⁰N
```
[Try it online!](https://tio.run/##yygtzv7//9yMhzsbzzc8atzg9////8QkAA "Husk – Try It Online")
## Explanation
```
ṁ N map natural numbers to:
π⁰ cartesian power of input
ṁ and join
Θ prepend empty string
```
[Answer]
# Python 3, 95
```
from itertools import*
def f(x,l=0):
while 1:print(*combinations_with_replacement(x*l,l));l+=1
```
Why must itertools functions have such long names.
[Answer]
## Ruby, ~~65~~ 60 bytes
```
->a{n=-1;loop{puts a.repeated_permutation(n+=1).map &:join}}
```
Such long builtin names...
[Answer]
# Scala, 69
```
def f[A](s:Set[A]):Stream[List[A]]=Nil#::f(s).flatMap(x=>s.map(_::x))
```
Lazy streams are quite nice for this kind of thing.
[Answer]
# C (gcc), ~~99~~ ~~97~~ ~~95~~ 93 bytes
-2 bytes thanks to @ceilingcat (replaced `putchar(v[~s[i++]])` by `printf(v+~s[i++])`).
-2 more bytes thanks to @ceilingcat (made `i` a pointer rather than an index).
-2 bytes once more, again thanks to ceilingcat (replaced `(*i)--+l` by `--*i==~l`, reversing the last two arguments of the ternary conditional operator, making it possible to remove the parentheses around `*i++=-1`).
```
s[999];*i;f(v,l)int*v;{for(i=s;printf(v+~*i++););for(i=s,puts("");;)--*i==~l?*i++=-1:f(v,l);}
```
[Try it online!](https://tio.run/##LYxLDsIgFEXHsgrCiMcnsc7whbgBd6AOKgbzkto2pTJp2q0jRqfnnHuDfYZQSro4526oCKPMpgPqZ5VxicMkySccpwqq0ZsirQEB/8aM7zlJIQARrFXk/dadvo23zfF3hWupY/5qqZd5oAewhe2iPIvrvr0Lrnlj@AGQreUD)
[Answer]
## [Pyke](https://github.com/muddyfish/PYKE) (commit 31), ~~10~~ 9 bytes
```
=blR.fbtp
```
Explanation:
```
=b - set characters for base conversion to eval_or_not(input())
l - len(^)
R - [^, eval_or_not(input()]
.f - first_n(^)
b - conv_base(^)
t - ^[-1]
p - print(^)
```
[Answer]
# Japt, ~~50~~ ~~40~~ ~~34~~ 28 bytes
```
V²o ®s1+Ul)£UgXnH)¯X¦0}Ãâ ¯V
```
Input is `"string", number of items`. Output is sorted by length, then reverse alphabet order. [Test it online!](http://ethproductions.github.io/japt?v=master&code=VrJvIK5zMStVbCmjVWdYbkgpr1imMH3D4iCvVg==&input=ImFiYyIgNTA=)
### How it works
```
V² o ® s1+Ul)£ UgXnH)¯ X¦ 0}Ã â ¯ V
Vp2 o mZ{Zs1+Ul)mX{UgXnH)s0,X!=0}} â s0,V
Vp2 o // Create the range [0..V²).
mZ{ } // Map each item Z in this range to:
Zs1+Ul) // Take the base-(1+U.length) representation of Z.
mX{ } // Map each char X in this to:
XnH // Parse X as a base-32 number.
Ug ) // Take the char at index -^ in U.
s0,X!=0 // If X is 0, slice it to an empty string.
â // Uniquify the result.
s0,V // Slice to the first V items.
```
This version takes a while if you want to do any more than 100 items. If you want a faster version, [try this 32-byte one](http://ethproductions.github.io/japt?v=master&code=VioyIG8gbXMxK1VsKWZAIVhmJzDDrqNVZ1huSH3Dr1Y=&input=ImFiYyIgNTA=):
```
V*2 o ms1+Ul)f@!Xf'0î£UgXnH}ïV
```
[Answer]
# Cinnamon Gum, 6 bytes
```
0000000: 6801 301c e74b h.0..K
```
Non-competing because Cinnamon Gum was made after this challenge.
[Try it online (TIO limits output).](http://cinnamon-gum.tryitonline.net/#code=MDAwMDAwMDogNjgwMSAzMDFjIGU3NGIgICAgICAgICAgICAgICAgICAgICAgICAgICBoLjAuLks&input=ImFiIg)
## Explanation
The `h` puts Cinnamon Gum in *format and generate mode*. The rest of the string decompresses to `[%s]*`. The `%s` is then replaced with the input, and a generator is created that outputs all possible strings matching the regex.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
g<∞*εÅв¦J
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/3eZRxzytc1sPt17YdGiZ1///iUnJAA "05AB1E – Try It Online")
```
g # length of the input
< # - 1
∞ # infinite list [1, 2, 3, …]
* # multiply each by the length-1
ε # for each:
Åв # custom base conversion, using the input as the list of digits
¦ # chop off the first digit
J # join the rest to a string
```
[Answer]
# [R](https://www.r-project.org/), ~~53~~ 50 bytes
-3 bytes thanks to Dominic van Essen
```
r=scan(,s<-"");repeat cat("",s<-outer(s,r,paste0))
```
[Try it online!](https://tio.run/##K/r/v8i2ODkxT0On2EZXSUnTuii1IDWxRCE5sURDSQkkmF9aklqkUaxTpFOQWFySaqCp@T@RK4kr@T8A "R – Try It Online")
Prints the infinite list, separated by spaces.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
∞€ã˜õš
```
[Try it online!](https://tio.run/##ARoA5f9vc2FiaWX//@KInuKCrMOjy5zDtcWh//9hYg "05AB1E – Try It Online")
```
∞ # push a list of all positive integers
ۋ # take the input to each cartesian power
˜ # flatten the resulting list of lists
õ # push the empty string
š # prepend it to the infinite list of strings
```
Taking a string the 0th cartesian cartesian yields `[[]]`, which would get completely lost when flattening (`˜`), this is why the empty string is prepended manually.
[`∞<€ã€``](https://tio.run/##yy9OTMpM/f//Ucc8m0dNaw4vBhIJ//8nJgEA) is an alternative 6-byter which uses `[]` to represent the empty string.
[Answer]
# [Curry (KiCS2)](https://www-ps.informatik.uni-kiel.de/kics2/index.html), 18 bytes
```
f s=""?anyOf s:f s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m706ubSoqDI-OzO52GjBgqWlJWm6FpvSFIptlZTsE_Mq_YFMKyCGSKzNTczMU7BVSFNQSkxSgojBNAEA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
ƛ⁰τḢ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLGm+KBsM+E4biiIiwiIiwiMjAwMFxuXCJhYmNcIiJd) Takes the number of strings and the string.
```
ƛ # For each number in 1...n
⁰τ # Convert to base <string>
Ḣ # Remove the first character
```
Alternatively, a version that prints infinitely (and is probably more efficient)
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
{:⁋,ẊṠ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJ7OuKBiyzhuorhuaAiLCIiLCJcImFiXCIiXQ==)
```
{ # Forever
:⁋, # Print the current string joined by newlines
ẊṠ # Take the cartesian product with the input
```
[Answer]
## Python, 55 bytes
```
s=input();l=['']
for x in l:print x;l+=[x+c for c in s]
```
This is longer than [feersum's 53-byte solution](https://codegolf.stackexchange.com/a/74277/20260), but it illustrates a different method with printed output. The list `l` is updated while it is iterated over, by appending every one-character suffix of each string that is read.
It's equally long to use `map`:
```
s=input();l=['']
for x in l:print x;l+=map(x.__add__,s)
```
The same length can be done in Python 3, losing a char for `print()`, and saving one by input unpacking.
```
s,*l=input(),''
for x in l:print(x);l+=[x+c for c in s]
```
[Answer]
# [Zsh](https://www.zsh.org/), 31 bytes
```
f(){<<<${(F)a};a=($^a$^@);f $@}
```
[Try it online!](https://tio.run/##qyrO@P8/TUOz2sbGRqVaw00zsdY60VZDJS5RJc5B0zpNQcWh9n@aQqJC0n8A "Zsh – Try It Online")
Print the array, then zip on the arguments before recursing. Despite including the function name, this is one byte shorter than the iterative version:
```
for ((;;))<<<${(F)a}&&a=($^a$^@)
```
] |
[Question]
[
We are going to fold a list of integers. The procedure to do so is as follows, If the list is of even length, make a list of half of its length where the nth item of the new list is the sum of the nth item of the old list and the nth-to-last item of the old list. For example if we had the list
```
[1 2 3 4 5 6 7 8]
```
We would fold it like so
```
[8 7 6 5]
+[1 2 3 4]
__________
[9 9 9 9]
```
If the list is of *odd* length, to fold it we first remove the middle item, fold it as if it were even and the append the middle item to the result.
For example if we had the list
```
[1 2 3 4 5 6 7]
```
We would fold it like so
```
[7 6 5]
+[1 2 3]
__________
[8 8 8]
++ [4]
__________
[8 8 8 4]
```
## Task
Write a program or function that takes a list of integers as input and outputs that list folded.
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.
## Sample implementation
Here's an implementation in Haskell that defines a function `f` that performs a fold.
```
f(a:b@(_:_))=a+last b:f(init b)
f x=x
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00j0SrJQSPeKl5T0zZROyexuEQhySpNIzMvE8jQ5EpTqLCt@J@bmJlnW1CUmVeikhZtqGOkY6xjomOqYxb7HwA "Haskell – Try It Online")
[Answer]
# [Python](https://docs.python.org/2/), 46 bytes
```
f=lambda l:l[1:]and[l[0]+l[-1]]+f(l[1:-1])or l
```
[Try it online!](https://tio.run/##dYxBCoNAEATPySv6qNgBV5MYF/KSYQ4rskSYrCJe8vpVH5BLU1RBL7/tM6cm5/i28B3GAPMmzmtIo5jUWpncnGoVi1MfWM4rLMdzMSWIIxqiJe7Eg3gSHfFS/itEr/56WdYpbThey7wD "Python 2 – Try It Online")
Same length:
```
f=lambda l:l[1:]and[l.pop(0)+l.pop()]+f(l)or l
```
A much shorter solution works for even-length lists (30 bytes)
```
lambda l:[x+l.pop()for x in l]
```
[Try it online!](https://tio.run/##dcnLCkBAGAbQNU/xLcmXcr@UJ2EWpIn6zUyy4OlHHsDu1HHPtVmTez1MXuZjWWdIP96JpM66KNb2xI3dQJT/LJ/HjMiJgiiJiqiJhmgV/4boVB8G7tzNBR1J7F8 "Python 2 – Try It Online")
I'm still trying to find a short way to correct it for odd length.
[Answer]
# [Emojicode](http://www.emojicode.org/), 203 bytes
```
üêãüç®üçáüêñüî¢üçáüîÇi‚è©0‚ûóüêîüêï2üçáüòÄüî°‚ûïüç∫üî≤üêΩüêïiüöÇüç∫üî≤üêΩüêï‚ûñüêîüêï‚ûï1iüöÇ10üçâüçäüòõ1üöÆüêîüêï2üçáüòÄüî°üç∫üî≤üêΩüêï‚ûóüêîüêï2üöÇ10üçâüçâüçâ
```
This was the most painful Emojicode answer to code for me. The unnecessary length :/
[Try it online!](https://tio.run/##S83Nz8pMzk9J/f//w/wJ3R/m964A4nYge9qH@VMWQdhTmjIf9a80eDRvOlB8ChBPNYJIzGgASi58NG8qkLsLyNwElNsLks/8MH9WE7rgo3nTYPqBWgzBagwNgKo6gbgLaNpsQ6DQOqx2YJqF7BYkc8AY6Jf@RgWQfgUuBQWQR0CcFQqGCkYKxgomCqYKZgrmIKE2LrByAA "Emojicode – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
### Code
```
2ä`R+
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f/f6PCShCDt//@jDXUUjHQUjHUUTHQUTHUUzHQUzGMB "05AB1E – Try It Online")
### Explanation
```
2ä # Split the list into two pieces
` # Flatten the stack
R # Reverse the second element from the list
+ # Vectorized addition
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~21~~ ~~18~~ 16 bytes
```
l
íUj°V/2V w)mx
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=CmwK7VVqsFYvMlYgdylteA==&input=WzEgMiAzIDQgNSA2IDdd)
~~Completely awful~~ Slightly less awful thanks to [@Oliver](https://codegolf.stackexchange.com/users/61613). BRB after I implement more built-ins and fix some bugs...
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 7 [bytes](https://github.com/splcurran/Gaia/blob/master/codepage.md)
```
e2÷ev+†
```
### Explanation
```
e Eval the input (push the list).
2√∑ Split it in half. The first half will be longer for an odd length.
e Dump the two halves on the stack.
v Reverse the second.
+† Element-wise addition. If the first half has an extra element, it is simply appended.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
œs2U2¦S
```
[Try it online!](https://tio.run/##y0rNyan8///o5GKjUKNDy4L///8fbaijYKSjYKyjYKKjYKqjYKajYK6jYBELAA "Jelly – Try It Online")
-2 thanks to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions)...and me realizing before.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~55~~ 41 bytes
```
f(_,l)int*_;{for(;l--;*_+++=l?_[l--]:0);}
```
[Try it online!](https://tio.run/##dY7dCoJAFITvfYppQdh1j5D2o7RIDyIhYRjClqLWjfjsdlbpoovuZphv5pwyvJflPFeyIKvq5xAUZqyaThobhiYotNaZPRc5u8tpq8w0v5v6hrZj9Np10jXAgsAKVmH0uA1p4PpqBSsp/JvfC0LAqNYEAaE3VhmvfQ29FILV5D2u9VO6BTc1RPklGyNCTNgR9oQD4UhICOlkViT@g3BeySGi1B34fsp@r5YgpuQniJdgmj8 "C (gcc) – Try It Online")
Overwrites the first \$\left\lfloor\frac{l}{2}\right\rfloor\$ entries of the input array.
### [C (gcc)](https://gcc.gnu.org/), 46 bytes
```
f(_,l)int*_;{_=l>1?*_+=_[l-1],1+f(_+1,l-2):l;}
```
[Try it online!](https://tio.run/##dc7LCsIwEAXQfb/iGhCSZrJIfLQYqh@iEqRSKcQqbXVT@u01VUEE3V1mzjxydcrzYSi4Iy/Kqo2d7Vzm13oTO5m5rVd6T1qGvtTklRErb/vhfimPuNbBH@qaj2MIgRASvEAXFZca3MIrZcULFpxNj9OGEeJApSQwMDnxwkbXW9twxkLqo/OhrPi4YVzV6u0@6zTBEGaEOWFBWBISQtrbFzF/SOh/7u4qRgVvNaVCvOvj46EwFz@coeTbmafrhwc "C (gcc) – Try It Online")
Additionally returns the length \$\left\lceil\frac{l}{2}\right\rceil\$ of the output.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
I√∑·πò+
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJJw7fhuZgrIiwiIiwiWzEsIDIsIDMsIDQsIDUsIDYsIDddIl0=)
```
I # Halve the list
√∑ # Push each half
·πò # Reverse the second half
+ # Add them together (vectorising)
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~14~~ 12 bytes
```
YCHa;@y+Ry@1
```
-2 Thanks to [DLosc](https://codegolf.stackexchange.com/users/16766/dlosc)!
How?
```
YCHa;@y+Ry@1 : One arg; list
a : First input
CH : Chop iterable into 2 pieces of roughly equal length
Y : Yank value
y : The two halves
@1 : Get item/slice at index 1; The second half
R : Reverse
+ : Add with
y : The two halves
@ : Get item at index 0; The first half
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJZQ0hhO0B5K1J5QDEiLCIiLCIiLCInWzE7MjszOzQ7NTs2OzddJyAteCJd)
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$23\log\_{256}(96)\approx\$ 18.932 bytes
```
J+t_HLxxt_HLx$xs_HLxtHL
```
[Try it online!](https://fig.fly.dev/#WyJKK3RfSEx4eHRfSEx4JHhzX0hMeHRITCIsIlsxLDIsMyw0LDUsNiw3XSJd)
\$-26\log\_{256}(96)\approx21.401\$ thanks to [Seggan](https://codegolf.stackexchange.com/users/107299/seggan)
First time using Fig. Any golfing tips are welcome.
### Explanation (outdated):
```
fw+[yfy$fy$fyx[yfy$fy$fy$x?h%1HLx[]yfy$fy$fyx]yW1
[yfy$fy$fyx First Mid
+ Add
[yfy$fy$fy$x Second Mid
fw Concat
? If
h%1HLx List length is odd,
[]yfy$fy$fyx Mid
]yW1 Else Empty list
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), ~~7~~ 5 bytes
```
2ẆẸr+
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWK40e7mp7uGtHkfaS4qTkYqjogvXRhjpGOsY6JjqmOmY65rEQYQA)
```
2ẆẸr+ # implicit input
2Ẇ # split list in half
·∫∏ # push both halves to the stack
r # reverse top one
+ # vectorized addition
# implicit output
```
[Answer]
# Mathematica, 88 bytes
```
(d=Array[s[[#]]+s[[-#]]&,x=‚åät=Length[s=#]/2‚åã];If[IntegerQ@t,d,d~AppendTo~s[[x+1]]])&
```
[Answer]
## Mathematica 57 Bytes
```
(#+Reverse@#)[[;;d-1]]&@Insert[#,0,d=‚åàLength@#/2‚åâ+1]&
```
Inserts a zero at the midpoint, adds the list to its reverse and takes the appropriate length.
[Answer]
# JavaScript (ES6), 41 bytes
```
f=a=>1/a[1]?[a.shift()+a.pop(),...f(a)]:a
```
```
f=a=>1/a[1]?[a.shift()+a.pop(),...f(a)]:a
console.log(JSON.stringify(f([1,2,3,4,5,6,7,8])));
console.log(JSON.stringify(f([1,2,3,4,5,6,7])));
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 bytes
```
å@o +Y*(Z<Ul
```
[Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=5UBvICtZKihaPFVs&inputs=WzEsIDIsIDMsIDQsIDUsIDYsIDdd,WzEsIDIsIDMsIDQsIDUsIDYsIDcsIDhd,WzEsMiwzLDQsNSw2LDcsOCw5LDEwLDExLDEyLDEzXQ==,WzEsMiwzXQ==,WzUsNCwzLDIsMV0=&flags=LVE=) with the `-Q` flag to view the formatted array.
## Alternate solution, 14 bytes
```
o(½*Ul)c)íU mx
```
[Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=byi9KlVsKWMp7VUgbXg=&inputs=WzEsIDIsIDMsIDQsIDUsIDYsIDdd,WzEsIDIsIDMsIDQsIDUsIDYsIDcsIDhd,WzEsMiwzLDQsNSw2LDcsOCw5LDEwLDExLDEyLDEzXQ==,WzEsMiwzXQ==,WzUsNCwzLDIsMV0=&flags=LVE=)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 53 bytes
```
x=>x.splice(0,x.length/2).map(y=>y+x.pop()).concat(x)
```
[Try it online!](https://tio.run/##dc3dCoIwGIDhc6/iOwjc6GuV/YLMGzHBsaZNbBu6ZBJd@wrPO37heTsxiVEO2vmNsXcVGx4DLwIbXa@lIjsMrFem9Y9tRtlTODLzYl4H5qwjlDJpjRSeBBrzSQygjXt54FAmAOUeIUM4IBwRTghnhAvCtcI/rUqqPPl5o@0V621LFmx5CuAF1Kt3QwT91JR1VhuS3kxKaR6/ "JavaScript (Node.js) – Try It Online")
Another suggestion:
# [JavaScript (Node.js)](https://nodejs.org), 43 bytes
```
f=x=>x+x?[x.pop()+(0|x.shift()),...f(x)]:[]
```
[Try it online!](https://tio.run/##dcxLCsIwEADQfU8xC6EJjoN/xZJ6kBhoqI2m1CS0tQTUs0dw7/rBa/Wkh7q3YVw4f21SMiKKMs7jWUYKPjA@Z8t3pOFuzcg4RyIyLHJ1kioVk@7BuvAcQYDMAOQKYY2wQdgi7BD2CAeEo8I/pjJVZLV3g@8a6vyN/TJ66MA0iBKq2cswzT8Vp9Zbx/KLyzkv0hc "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~81~~ ~~70~~ ~~68~~ 57 bytes
```
function(l)c((l+rev(l))[1:(w=sum(l|1)/2)],l[w+1][!!w%%1])
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jRzNZQyNHuyi1DMjUjDa00ii3LS7N1cipMdTUN9KM1cmJLtc2jI1WVCxXVTWM1fyfpmFoZaLJBaJMIZQZhDKHUBaa/wE "R – Try It Online")
anonymous function; returns the result.
[Answer]
# [Zsh](https://www.zsh.org/), 55 bytes
If the answer must be put to stdout, but output whitespace is flexible, **55 bytes**:
```
for ((;++i<=#/2;))<<<$[$@[i]+$@[-i]]
<<<$@[#%2*(1+#/2)]
```
[Try it online!](https://tio.run/##XYzLCoMwEEX38xWXaEEbQmuq1mIE/0OyEIwYEAXti/58mnTZuxhmzhnuZ5/cbu4Qb3pNdjbYTD9gtoupMaxknv2MnxdgccDMjeuGJKk5t6qJTrJOU6VU3MVtZzX3U1itKaC2iw7ymGTcf6XaPZZQZINiTQijYV2MyyBxQY4CJa6o6O/GjUQGUfm9gCi9OFMuib4 "Zsh – Try It Online")
---
If the output must be stored in an array, **53 bytes**: (We can't use this method in place of the above because of `<<<...[--i]...`. The here-string forces a subshell, so the decremented value of `i` never makes it out.)
```
for n ($@[1,#/2])y+=($[$@[--i]+n])
y+=$@[#%2*(1+#/2)]
```
[Try it online!](https://tio.run/##XYzLCoMwFET39yuGmILWhjapWksV@h@ShWCKAYmgfdmfT2OXvas5Z4b7mXs/mzvEm169HQwm03YYrDMXdCOZZzvg1wswvmrmb@MEh5hfG7mL9konS1rHvAkshNWp0wkFEzDaqG0s07BJtK@qii/0cOszB4uFgmH1eoy60RkvoXBEhhwFTijpj3EmISHKkHOIIhQHyhTRFw "Zsh – Try It Online")
If the answer must be output in one line separated by spaces, then append `<<<$y` for a 6 byte penalty.
---
Zsh arrays are indexed from the start starting at `1`, or from the end starting at `-1`. So what happens if you attempt to index at `0`? Well, nothing! We take advantage of that here to only output the middle number based on a parity check:
```
$@[#%2*(1+#/2)]
# # # parameter count
(1+#/2) # index of the middle element when count is odd
#%2*(1+#/2) # multiply by 0 if even, or 1 if odd
$@[ ] # Index the parameter array
```
[Answer]
# [Factor](https://factorcode.org/), 35 bytes
```
[ halves reverse 0 pad-longest v+ ]
```
[Try it online!](https://tio.run/##ZY29DgFBFEZ7T/H1YuOf0OhEoxGVKMb62I0xu@69JkT22QeVQndycpJzcrlVkrab1Xo5g/J2Z8ipP8r4MHGKq7Mii/zWigsl0KMWmj1rKYNh3mq90EMfAwwxwhgTTNH8uSbtUDgfPwthpCjRRe2OHV@FM9UQ29inQ7lApsg9naQ3 "Factor – Try It Online")
## Explanation
It's a quotation (anonymous function) that takes a sequence from the data stack and leaves a sequence on the data stack. Assuming `{ 1 2 3 4 5 6 7 }` is on the data stack when this quotation is called...
| Snippet | Comment | Data stack (top on right) |
| --- | --- | --- |
| `halves` | Split a sequence in half | `{ 1 2 3 } { 4 5 6 7 }` |
| `reverse` | Reverse a sequence | `{ 1 2 3 } { 7 6 5 4 }` |
| `0 pad-longest` | Pad the shorter of two sequences with 0s until it's the same length as the longer sequence | `{ 1 2 3 0 } { 7 6 5 4 }` |
| `v+` | Vector addition; element-wise addition between two sequences | `{ 8 8 8 4 }` |
[Answer]
# [Go](https://go.dev), 115 bytes
```
func(x[]int)(o[]int){s:=len(x)
for i:=range x[:s/2]{o=append(o,x[i]+x[s-i-1])}
if s%2>0{o=append(o,x[s/2])}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dU5LasMwFNzrFGogIBE5bdz8MKhnyN54IWLJiMZPRpKDwOgW3WVjCj1UblM7zqKBZjW8mTefy3dl-utLI46fopK4FhqQrhtj_XKmaj9D6CwsVvyn9SrZX51q4UhCXmjwlJgJO5fxkwQSKFLGYp1xK2AIC3nmXtOiM1w0jYSSGBZyXSxC7hKdrAoakVbYzdOPt8ef0TWIVvrWQrxXf43Vt4GE4g7JswSccXyb0K1Yyt7Zmm3Ylu3YPiJTlk_UiA52IE9AFBlDKP1DDLaHe_Jv4j_kyN239f2Evw)
### Generic with custom operator, 136 bytes
```
func f[T any](x[]T,O func(T,T)T)(o[]T){s:=len(x)
for i:=range x[:s/2]{o=append(o,O(x[i],x[s-i-1]))}
if s%2>0{o=append(o,x[s/2])}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fVHNTgMhGIxXnoJsYgIpVVutNmvWV6iHvW2IYf8qdgsrbO2aDXffwUtj4sVH8E30aQTpxmoaD4TJDN8wMM8vc7l5r1m2YPMCLhkXgC9rqZqjoFw2AXhdNeVw-vFUrkQGyySGTDxS1CY0JjPoSBSTGMcYSUvhTodRVQjUYlBKBXkYKSasb5uE-nhMOxmxui5EjiSZWRNOSZvoIR-OKMYG8BLqw_HVye4xq9tBK6qiWSlhfJ7Pg7fvQC4vwrADLM9hGPlAjKSQiwbb1fkpyAapAcVDIdyhhDplRMbklJyRCTknF2RqgPQWe1QDrpUlK4HKxO4UOSdir8T4r2JN9gvedmL-U3sR6EZpn8UiLuZdcFtUlQwIDNZSVbkD9yueLRxIlVwLB0rZBgbUSt4VWcOl-PUh3sjW1KPOFXRDVF8R2xK6J9LO9qGiSHdyEPkhpLAx5hJuu9h5hdcpcskJ_MlgX7OtbLPx-xc)
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/index.html), 34 bytes
```
f(a:b++[c])=a+c:f b
f x@([]?[_])=x
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m706ubSoqDK-IDE7uXjBgqWlJWm6FjeV0jQSrZK0taOTYzVtE7WTrdIUkrjSFCocNKJj7aPjgYIVEJW7chMz8xRsFdIUog11jHSMdUx0THXMdMx1LGIhCmBGAgA)
Based on the sample implementation in Haskell.
[Answer]
# C (gcc), ~~62 bytes~~ 60 bytes
-2 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
```
i;f(v,l)int*v;{for(i=0;i<l/2;++i)v[i]+=v[l+~i];return~l/-2;}
```
`f` is a function taking vector (`v`) and length (`l`) as arguments. It modifies the vector and returns the new length.
[Try It Online!](https://tio.run/##VY9hi4MwDIY/N78iDAbtWdEJd18yf4nIOJzdBXp1ONfBxP11r9UxdvkSwvs8CWnSU9PMM5ORXlvFbvjwNJqul1zmxHubFZQkrHzFdVL6yiYPrqlvh2vvHjZLC5oAgoW/3@yk7/ioYAR8VgwsX4aqxhLHT41fGguNu1xjutMYWjERiAVr3Wn4CZi88L3tzOIpzP7NVV4rglVw7e3wkoyMsX5uCYwIL6CMHIc4p9D2bwphfApHEOLcB8rIzfaIG71e4XhFTDDBPP8B)
How it works:
```
i;
f(v,l) int*v; // v is an integer pointer (or array), l is an integer
{
for (i = 0; i < l / 2; ++i) // iterate through half the indices using i (if l is odd, the middle element won't be included)
v[i] += v[l + ~i]; // add the value at the i'th index from the back to the i'th index from the front. ~i == -i - 1, so l + ~i == l + -i -1 = l - i - 1 (l - 1 is the first index from the back, and we subtract i for each index beyond the first)
return ~l / -2; // return half the length rounded up (~l == -l - 1 => ~l / -2 == (-l - 1) / -2 => (l + 1) / 2
}
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), ~~15~~ 12 bytes
```
(⌊≠÷2˙)⊸↑⊢+⌽
```
[Try it online!](https://bqnpad.mechanize.systems/s?bqn=eyJkb2MiOiJpbnB1dCDihpAg4p%2BoMSwgMiwgMywgNCwgNSwgNSwgNiwgNywgOOKfqVxuU29sIOKGkCAo4oyK4omgw7cyy5kp4oq44oaR4oiYKOKKoivijL0pXG5Tb2wgaW5wdXQiLCJwcmV2U2Vzc2lvbnMiOltdLCJjdXJyZW50U2Vzc2lvbiI6eyJjZWxscyI6W10sImNyZWF0ZWRBdCI6MTY3NDI0MDM3ODA1OX0sImN1cnJlbnRDZWxsIjp7ImZyb20iOjAsInRvIjo2NywicmVzdWx0IjpudWxsfX0%3D)
-3 thanks to Marshall Lochbaum
Sum the list and its reverse, then take the first `⌊≠÷2˙` digits. `⌊≠÷2˙` the floor of the length divide 2. Floor is necessary because there is no integer division in BQN. `⊸` is used to bind the output of `⌊≠÷2˙` to the take operator `↑` on the left and also puts the output of `(⊢+⌽)` on the right. Better explanation [here](https://mlochbaum.github.io/BQN/tutorial/combinator.html#before-and-after).
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 6.5 bytes
```
/`\~_!:\@0@+
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWa_QTYuriFa1iHAwctCFCUJkFN60MFYwUjBVMFEwVzBTMFSy4UPhcILYpUNzQUMHQWMEQyLBUMDJWMLJUMDaEGAEA)
```
/ Fold
`\~ split into two parts
_ input (row from STDIN as a list of integers)
! zip
: join
\ reverse
@ the second part
0 0
@ the first part
+ with addition
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~69~~ 68 bytes
```
!s=(~=length;~s%2>0&&insert!(s,(1+~s)√∑2,0);(s+reverse(s))[1:~s√∑2])
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/X7HYVqPONic1L70kw7quWNXIzkBNLTOvOLWoRFGjWEfDULuuWPPwdiMdA01rjWLtotSy1KLiVI1iTc1oQ6u6YqBMrOZ/h8RikAYFxWhDHSMdYx0THVMdMx1zHYtYBVtbhWhLHTCM5cKhDqLKQgcETWL/AwA "Julia 1.0 – Try It Online")
-1 byte thanks to MarcMush: replace `==1` with `>0`
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 6 bytes
```
;ᶜç↔ᶻ+
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FmutH26bc3j5o7YpD7ft1l5SnJRcDJVZcFMx2lDHSMdYx0THVMdMx1zHIpYLVSQWohIA)
```
;ᶜç↔ᶻ+
; Nondeterministically split the input into two parts
ᶜç Optionally prepend a zero to the second part
‚Üî Reverse the second part
ᶻ+ Zip with addition
```
The `+` operator is automatically vectorized, but it does not check if the two operands have the same length. So here I use `ᶻ` (`\zip`) to make sure that the two parts are of equal length.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes
```
Set[f[a_,b___,c_],a+c,f@b]
f@a___=a
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z84tSQ6LToxXicpPj5eJzk@VidRO1knzSEplivNIREoZpv4P6AoM68kWlnXLs3BQTlWrS44OTGvrporKDEvPdXBXAfKsOCq/Q8A "Wolfram Language (Mathematica) – Try It Online")
Input `[list...]`. Returns a sequence.
---
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 39 bytes
```
f@{a_,b___,c_}:={a+c,##&@@f@{b}}
f@a_=a
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/NoToxXicpPj5eJzm@1sq2OlE7WUdZWc3BASiTVFvLleaQGG@b@D@gKDOvJFpZ1y7NQTlWrS44OTGvrporKDEvPdXBXAfKsOCq/Q8A "Wolfram Language (Mathematica) – Try It Online")
Input and output a list instead of a sequence.
[Answer]
# [Perl 5](https://www.perl.org/) `-aE`, 36 bytes
```
map{$F[$_]+=pop@F}0..$#F/2-1;say"@F"
```
Takes advantage of the autosplit flag and iterates through the first half (rounded down) of the resulting list, modifying it in-place.
Slightly ungolfed:
```
for (0 .. ($#F / 2) - 1) {
$F[$_] += pop(@F);
}
say "@F";
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saBaxS1aJT5W27Ygv8DBrdZAT09F2U3fSNfQujixUsnBTen/f0MjYy5DBSMFKKlgomCKYCmYcRkaKBgAuQYKhgb/8gtKMvPziv/rJiro@prqGRgaAAA "Perl 5 – Try It Online")
[Answer]
# [sed](https://www.gnu.org/software/sed/) `-E`, 60 bytes
```
s/^/</
:a
s/<(!*);(.*;)?(!*);$/\1\3,<\2/
ta
s/[<;]//g
s/,$//
```
Only works with zero and positive numbers.
Input is repeated exclamation marks separated by semicolons.
Output is repeated exclamation marks separated by commas.
[Try it online!](https://tio.run/##K05N0U3PK/3/v1g/Tt9Gn8sqkatY30ZDUUvTWkNPy1rTHsxU0Y8xjDHWsYkx0ucqAamItrGO1ddPB7J0VPT1//9XtFYEITCGEFASRsFpRWsuIhT/yy8oyczPK/6v6woA "sed – Try It Online")
[Answer]
# [Uiua](https://www.uiua.org/), 12 bytes
```
⬚0+⇌⊃↘↙⌊÷2⧻.
```
[Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4qyaMCvih4ziioPihpjihpnijIrDtzLip7suCmYgWzEgMiAzIDQgNSA2IDcgOCA5XQpmIFsxIDIgMyA0IDUgNiA3IDhd)
```
⬚0+⇌⊃↘↙⌊÷2⧻. input: a numeric vector
⌊÷2⧻ half of length, rounded down (let's call it k)
⊃↘↙ . fork(drop, take): first k elements removed, first k elements
‚áå reverse the top
⬚0+ elementwise add, filling with zeros when lengths don't match
```
] |
[Question]
[
*Originally [sandboxed](https://codegolf.meta.stackexchange.com/a/19105/78410) by [@xnor](https://codegolf.meta.stackexchange.com/users/20260/xnor)*
Left-or-right is a very simple language @xnor made up. Its expressions are made of arrows `<` (left), `>` (right), and parentheses. The goal is to evaluate an expression to either `<` or `>`.
An expression `A<B` picks the left item `A`, while `A>B` picks the right one `B`. Think of `<` and `>` as arrows pointing to the item we want, not as comparison operators.
Take, for example, `><>`. The operator in the middle is `<`, and confusingly, the items on each side `A` and `B` are also arrows. Since the operator tells us to take the left one `A`, which is `>`. So, `><>` equals `>`.
Expressions also nest. We can replace the expression with its value. So, for example, `(><>)<<` equals `><<` equals `>`. And, `>(><>)<` equals `>><` equals `<`. For another example, `(><>)(<<<)(>><)` equals `><<` equals `>`.
In the input, you'll be given a well-formed expression consisting of either a trio of arrows like `><>` or the result of repeatedly replacing some arrow by a trio of arrows in parens like `><(><>)` . You can assume the input won't already be a lone arrow. You may alternately accept the whole inputs encased in parens like `(><>)` or `(<(><>)>)`.
The input is given as a flat string consisting of symbols `<>()`. You may not take it in a pre-parsed form like a tree.
The shortest code in bytes wins.
## Test cases
Generated using [this script](https://tio.run/##bZDBcoMwDETvfMXeLDUZDy03CvxIk0MSTHALNmORdvL11BDSaab1RaPVW2nHw3VsvcumqQm@RzCw/eDD@JTc@oOrY7lrtWlwNo5qM4xtmeqU8wTx2WYliVFgmeZx13gJDqfW25MhVVSKF3gZY1Mi1dkirKAihQ2U0u/eOnr7ucNofICFdfORs6GM9zyTrJZA4rtPQ7JG@WptZ9BFszAqZDkEJeRypKB2RJoLvWO1ReyeYxF@fQB0FZFH4HdGSWSml3B/cr2kvI9zLfGv6MNcy@7QH@sDJKd7xu0tGHMye2X2iuQYgnVj1P9VVytP0zc).
### Evaluates to `<`
```
>><
<<(<><)
(>>>)><
(<(<<>)(<<<))<<
((>(>><)>)(><>)>)><
(<<(>(<>>)<))((><>)(><<)>)(<<<)
((<<<)<>)((>><)<(<><))((>>>)<<)
>(>((><>)<>)(<>>))((>><)((><>)<<)<)
((><<)(><<)(<<>))(<(>><)(>><))(<<(<<>))
(<(><<)(>(>>>)>))((>>>)>>)((<>(>><))<<)
```
### Evaluates to `>`
```
<>>
((<<<)>(<<>))(><<)>
((>>>)<>)<((<<<)>>)
>(>>(<<<))(>((<>>)<<)<)
((><>)(<<>)>)(<<(<<<))(<(>>>)<)
(><((><>)><))(>(>>(>>>))(<><))(>>>)
(((>><)<>)(><>)(><>))(<<(<>>))(<<>)
((><>)<(<<(<<>)))((<(<<>)<)(<><)>)(>>>)
(<<(<><))(((<>>)><)(><<)(><>))(<(><>)>)
((>>>)<<)(<(<><)<)((<<(<<<))>(>(><>)<))
```
[Answer]
## x86-16 machine code, ~~31~~ ~~26~~ 22 bytes
Saved 5 bytes thanks to @Bubbler.
Saved 4 bytes thanks to @640KB.
```
0000:0000 AC 3C 29 74 03 50 EB 0A-5A 58 3C 3E 58 74 01 92 .<)t.P..ZX<>Xt..
0000:0010 58 52 E2 EC 58 C3 XR..X.
```
Callable function.
Expects `SI` = address of code, `CX` = length of code.
Expects the code to be enclosed in `(...)`:
>
> You may alternately accept the whole inputs encased in parens like `(><>)` or `(<(><>)>)`.
>
>
>
Returns the output at `AL`.
Disassembly:
```
LOOP: ; Main loop:
AC LODSB ; AX = [SI++]
3C29 CMP AL, ')' ; AX == ')'?
7403 JZ BRACE ; * If so, jump to 'BRACE'
PUSHSTH: ; Otherwise...
50 PUSH AX ; * Push AX onto stack
EB0A JMP END ; * Jump to 'END'
BRACE: ; If AX == ')'?
5A POP DX ; * pop TOS to DX
; * (So DX is now the rightmost angle brace)
58 POP AX ; * pop TOS to AX
; * (So AX is now the middle angle brace)
3C3E CMP AL,'>' ; * Compare current AL with '>' (result stored in PSW)
58 POP AX ; * AX = left argument
7401 JZ RAB ; * If prev. value of AL == '>', jump to 'RAB'
LAB: ; * Handle prev. value of AL == '<':
92 XCHG DX,AX ; * DX = left argument instead
RAB: ; Now, DX is the chosen value.
58 POP AX ; * Discard TOS (which is an excess '(')
52 PUSH DX ; * Push DX onto stack
END: ; Finally,
E2EC LOOP LOOP ; * Loop the above CX times
58 POP AX ; Pop TOS to AX
C3 RET ; Return to caller
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 50 bytes
```
f=a=>a[1]?f(a.replace(/\((.>)?(.)(<.)?\)/,'$2')):a
```
[Try it online!](https://tio.run/##TVLRTsMwDHzPV/QBrbYGmeCRubcnvoIhEZUOhso6dRUviG8vjp1OSJWbOHfny7Wf6Ttd2vF4nu5Ow1s3z4cmNUjP9y@7A6U4duc@tR1t9kQRvKPIJJF3e97c1jcPNfNjmqeqqV4DIEGEBMKBALDuSfcCpYgwi@4JeiSsLWi/YES7ogTFkPW1GCbTlJNfuWtUn2AbZei5KjrLBmmzAEtTGVkjK3rJhrQ6BqYlbpOzXwf6BZYxyMPFrdvMoHOKMRRBsxyKLX3KKcwgPIHsVPDfFNwPigcpzmDnEIfAqXBXXALIa9XwUEqgVlzLkYJljlxvme9iK3EpLFpyzdboWBLDkpg5DdfoyfE56sV9/hg2TcN8jdN4/CKOl3N/nKjen2rehikehvEptR/UVw2qn1BV7XC6DH0X@@Gd@tXqQDXV635ds/5e4Ze38x8 "JavaScript (Node.js) – Try It Online")
Repeat apply regex replace until only 1 char left. The regex `/\((.>)?(.)(<.)?\)/` get the calculate result as 2nd capturing group.
---
Save 1 byte, thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 121 bytes
```
0&v
>o ;
^? <=1l~<;o~$?=">"$
<<v<<<&0 ~&~$?=">"$<
~]v&0[0~ < >
>>>i:0(?^ :>>>v
<< v<<<<<^? ="("<
+&^>>:")"=?^&:&2= ?^&1
```
[Try it online!](https://tio.run/##NYw9CsMwDIV3n0KYICS6OB2dZ/kgpR5LA4UMBY@@uqsQOr0/vvfav@85E/dgB22hVUJZPwPbMZZaosUlAB0AJxr87xDGs3N6pEEgC2a25yS1EVH20J2hEwL8sESJCDduZjlqLLVx5nsh13VOgRigYuKgmqpcxtzgLKHq@w8 "><> – Try It Online")
This code takes advantage of the `><>` functionality where a new stack/register can be created, code can operate on that new stack, then once that stack is closed, the results are merged back into the lower level stack.
It reads one character (codepoint really) at a time creating new stacks whenever it hits a `(` and closing them when a `)` is encountered.
The other logic use is a simple state machine, based on the contents of the register associated with the current stack.
When the value of the register is `0` the char just read is the left hand side of the statement, a value of `1` means it's the operator (`<` or `>`), and a value of `2` means we have the right hand side.
Anytime the state is `2`, the code can resolve the 3 character on the stack (RHS, OP, LHS) to get an answer for that operation.
When the input is exhausted, we'll be back at the base stack with either `1` or `3` entries on the stack. If there are `3` entries on the stack, the code does one final operation to resolve the stack, then the sole entry on the stack is printed as a character.
The code is broken up to save characters, but I'm going to explain it using the original code. The only difference is that direction shifts, extraneous spaces and directional indicators have been removed to make it easier to see what's happening. Well, unless I goofed when formatting it...
```
# initialization
0&v # Set the register (state) to 0, call input loop
[0]
# [0] loop to read input and process each char
[1] [2] [3] [4]
>>>i:0(?^:"("=?^:")"=?^&:&2=?^&1+&
.. i # Read next char/codepoint
:0( # Check it codepoint < 0
?^ # If true, all input done call [1]
:"("= # Compare char to "("
?^ # If true, call [2] to open new stack
:")"= # Compare char to ")"
?^ # If true, call [3] to close stack
&:& # Load and resave the register
2= # Compare state to 2 (RHS,OP,LHS)
?^ # If true, call [4] to pick answer
&1+& # Increment the register (state)
# [1] code to handle EOF
[5]
>~1l=?^$"<"=?$~o;
.. ~ # Delete top of stack, clean-up
1l= # Compare stack size to 1
?^ # If true, call [5] to print/exit
$ # Flip top two stack entrys, pulls OP to top
">"= # Compare OP to ">"
?$ # If true, flip top two stack entries
~ # Delete top of stack (the choice we don't want)
o; # Print top of stack as char, then exit
# [5] called on EOF if the stack has only 1 entry
>o;
.. o; # Print top of stack as char, then exit
# [2] code to handle "(", stack a new stack
>~0[0&
.. ~ # Delete top of stack, clean-up...
0[ # Open a new stack with 0 entries from the old one
0& # Set the register (state) to 0
# [3] code to handle ")", close the stack
>~]
.. ~] # Delete top of stack, close stack to merge down
# [4] code to resolve a stack with RHS,OP,LHS
>$">"=?$~&~0&
.. $ # Flip top two stack entrys, pulls OP to top
">"= # Compare OP to ">"
?$ # If true, flip top two stack entries
~ # Delete top of stack (the choice we don't want)
&~&0 # Set register (state) to 0
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~30~~ 23 bytes
```
(⍎'(⊣⊢)'['(<>'⍳⍞])/'<>'
'(<>'⍳⍞ take the input ⍞ and get the indices of '(<>'
this fills with the last index + 1 if not found, saving 1 char
'(⊣⊢)'[ stuff ] index into '(⊣⊢)', replacing <> with ⊣⊢, the left and right tack functions
⍎ evaluate this as a train
APL trains of the form (f g h) when applied to left and right arguments x and y produce (x f y) g (x h y)
This translates directly to this language
Replacing <> with ⊣ and ⊢ which do the same thing, the input becomes a valid function in APL
( train )/'<>' Reduce over '<>', which uses '<' as a left argument and '>' as a right one
```
[Try it online!](https://tio.run/##VVE7TsQwFOx9inS2ixUc4Gl6Kg6AKII2S8EKEKKACwBaKSsaSijgCNzIFwnzPklE82Q/z8ybN@7v95vtc7@/u94MT4/D7XbYTu34cXbeXt5PU3t73U2ljcdc2uGnHb5rvshFkNv428avy3qSeZkIm3ZdAiTtkggBUhMbBUDVJo/sCiqL1CqKKwV8l8om@OJA4oR9IY@4Yi8shlKq8fSgfaP7NLuQYwjqOtMGsh3QaJLjOqrrRa2xOgqmJ27YkBJQ32ceBrUgvoRNTgyOseXctfGzu3oY@pukgQCLbcQoW8lNwHxKvCMWgCelmwj@m4b7RXiUcI5AQBwEp8Nd14gJPqFEeBG@FddzrGCdJksWuq@dxOWw6snyDyaBOVnMyZrjdWNVMIZ@y7yHfpxNrPUP "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 22 bytes
```
{`\((.>)?(.)(<.)?\)
$2
```
[Try it online!](https://tio.run/##VVEhcgNBDOP3jgCbHAjWKB8JSEFBSECnrI@/2pI3NyGeHVmWZO/P9@/z9XUcf497xM68xZ6BPW/33C7X4wgSuQUQqEe9CmAKi8LAYqMaEBIUv0BW581D4aix4oU6VcTSaM/1o3GNj5etzChdT8qw4KEOiByd1nXpaFXNovTgwOnspnqdZcaOAC9h501uKyJH1vFlSGXC9Dlh6dU6NfgZkM7GyYNJyWEQJtHjdMKck9AOMYeaQ6tYz1zwdMO59/oyWI6nHt43lwTXFbmuqMTnxq2gif6CtUd/khzL6h8 "Retina 0.8.2 – Try It Online")
Basically the port of my JavaScript answer in Retina. I just learnt how to write loop in past 10 minutes and got this.
`{`` loops the replace until nothing changed. The replacement calculate one step each time.
[Answer]
# [J](http://jsoftware.com/), 30 bytes
```
')/''<>'''".@,~'(',rplc&'<[>]'
```
[Try it online!](https://tio.run/##hVFNS8NAEL3vr1h6cHYhxuKxjg9B8NRTr1JEQmorgmJy9q/H@drgTUgm2Zn3Zua9fV82PZ3y/S5T7vI27@S97vPjYf@0UL0hYhDRpn/ofqhQ9/31MVwRP@NIS03jcP7MtB9Pc57Hac7D6zRO5OnTXf9ym4/acpsATsyFwTUVAFXORc6MKoFrZTkXSImrpCD5wLBkWQiCKZaXYBilCUc/mjWqT7CDMKQuHZ1lgyQZwEgKQ3toRw@6kETHwHqxr1l1Xwe6gDYGOpx9dZtZU/hyuLyd/zNGdgoRiOEmL4UEeaIKEwN3S1Ux/gqA747Yl0MFrA52CJwKV1DDLP2XHm5gmG/BezmS0ebw6ojqtj/2Vmi9eL0Ho6O5i@aubZrWayqO12tp2@vF2TQxvi6/ "J – Try It Online")
Very similar to rak1507's APL answer, though I had the idea independently -- it's natural for J, though loses some elegance because of the quote escaping.
* `rplc&'<[>]'` replace `<>` with `[]`, which in J are the "left" and "right" identity operators, meaning they return the left or right argument.
* `(` Prepend a left paren to that result.
* `')/''<>'''...,~` Append `)/'<>'` to the previous result.
* Now we have `( ~~input with [] instead of <>~~ )/'<>'`.
* Which is the same as: `'<' ( ~~input with [] instead of <>~~ ) '>'`
* `".@` Evaluate that string. From here, J trains and the definition of `[` and `]` do exactly what we want.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~98~~ 74 bytes
Saved a whopping 24 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!!
```
import re
f=lambda p:p[1:]and f(re.sub('\(((.)<.|.>(.))\)',r'\2\3',p))or p
```
[Try it online!](https://tio.run/##pVLLbsJADLzzFatcdi3SSEClSsjxjxBU8UhKVAhRshwqyrenXnsDqD02B2fjHY/H47Rf/nBuFsNQn9pz501XTqr8uDlt9xvTLtvVbLneNHtTua7M@svW2cI5lwFm3xnxGwqwaWeLebGwaQtw7kw7@LL378ey8r3JjTMJESapSRAdEkI4OiICzTrOIgEHBEBNOWIAAmeJrx5I5AvkSkY6ueIgsFCsleEULoRAG8oHFymEqbVWmnI@YmOSiyJToNYQ9HFUGAkjqmqIEyhWpxr7UVCBOok2h4k409Ufh9EaFvDQTbGTDBVFkAjFCKBxBFK/wixIv2STKqaoEqN2GiGEiiIlINUN0SuKTVy0MC5BgjIqGOmpId4NCTPLCZWQnhjxvg8hodFfGv0V1U@DBw4pCesZhwkLlJ4glu4O5e6z7IKdtrjM3153NjVymi0sTCr@I72pG/P4KZcTw09YQOWss1M/tcDIkGy7uvGusld/My9krv3NXGODVZ/nCSbr2x9S3ec/WElYhx8 "Python 3 – Try It Online")
Takes an input string with enclosing in parentheses and returns whether it's left (`<`) or right (`>`).
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 32 bytes
```
s/\((.>(.)|(.)<.)\)/$2$3/g&&redo
```
[Try it online!](https://tio.run/##VVFBagNBDLvnHSF4DtmFht6EXpJjQimE7JL02Ld3YlueLD2MGTSyJHvW6@P22ftzPptNtKn9@sHUzm3ef@xP89fh8Lhelt6NRNsZYPCL3xxgS8wcA5sXf0AixuQ7SH958@A4vM15li9ekpWt0ReXwLO9vGQlhuuqMw0dLmqBaKUTuioRzatYTD0ocFN2UTXOMGNEgIYo5zAbCVmqSp9@zEiod1ZWarIIDf7PR0VjxUGFZDEIkah2KmCrjVAOVnuqPWeRnrjg5oZt7PFjkBw3PbxXnhIcS@RYYibeJg6F7IgfGHPEH6WjW/0t68/3cn/243p7AQ "Perl 5 – Try It Online")
Takes advantage of the spec allowing outside parentheses to be required.
[Answer]
# [Red](http://www.red-lang.org), ~~136~~ ~~120~~ 86 bytes
This version is courtesy @hiimboris (<https://gitter.im/red/parse>)!
```
func[s][r:["<"|">"]while[parse s[to change["("x: r["<"r |">"x: r]")"](x/1)to end]][]s]
```
[Try it online!](https://tio.run/##ZVLLbsMgELz3KxAnOFW9Wqv5iF4RhyjGTarUiXCq5tB/d/eB7Vj1YWXYYR4LtfTze@lTfhm6efgej2nKqXbJk//18PnndL6UdDvUqbgp3a/ueDqMHyX54B@dq4KrTpCyyj76HB6vb5GBZexzTnnK83Ct5XA8uckl9@L48wB5@yMKBIptFQDEtRe4R4hcKEZadwMYRpEb4O4OT9wjpmB80C4XRQrFel4W0lMa09cFn1tRrGEMaoBbDd42@dzGJxpWxC5XQ0J5yULELZPBLeoiDLFDFuzJBQvvXKMpaKpNH2qTGgZPGWDDkzCE/75hltFsUjOPJxTIgDAamPHYpoZNLbR5tnvRYryGJ@yVaR2NRNc/MlrseWm9IqXCMmwsw9YE@2kIk56SG1uyyZ2qstxGTu5Wz@Pdpa/rpee36bvOu8HV8nk9j/K@ZY/fc3Z5/gM "Red – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~117~~ \$\cdots\$ ~~101~~ 98 bytes
Saved 10 bytes thanks to an idea from [Davide](https://codegolf.stackexchange.com/users/100356/davide)!!!
Saved 3 bytes (and got below 100!) thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
i;f(char*p){for(i=0;*p++-40||p[3]-41;++i);p[-1]=p[p[1]-62?0:2];bcopy(p+4,p,strlen(p));i&&f(p+~i);}
```
[Try it online!](https://tio.run/##XVPBbsIwDP0VVAmUtKlEWbUJ4pozd26lhxG1W6UNItoDE7BfZ06cFrRLFNnP7z07jkk/jLnfW90I8/l@iq28NMeTaIu5jm2SpPn8erXlS5XmmU6SVmpbpllV2NKWWZW@Ltbz1aLSe3O0P8ImubKq609f9UFYKXU7mzUU/aWy232jOhVvy6q4RAIRZKQiASCArv5OQZQhLigOKOmgJISYQF9HYaTcExYoA1RMWOFzdHicL@dad3UZTxFUWXLAEDtXe2FKBHAIghy5HDsfziSdjEPPCWxdDn0wmJsbJNEZAW5n1HeSD68YuLmToIveHAQEjr6RO3UNAP73imwTgzUIhnHEIDAMmQLZrAwzwkFHhNmF@fuDORkN@KwJj0EMrwlMic@cMD6Fp8FhsDgM1jt/7t@x@Br3MkNH7u28qpv7TcW9/n5vD6LmZdYbWMy1PbWHvhHRtJukOJmaye5cL3bnpZma3SFSPa1nl9brLF@usvxNyov7D5N9Gfa5L7blppIVfRSKGFr3veppx7si3qu6iACjcpMkuKz07Xb/Aw "C (gcc) – Try It Online")
Takes an input string with enclosing parentheses and reduces it to either a left (`<`) or a right (`>`).
### Explanation (before some golfs)
```
i;f(char*p){ // function taking a string parameter p
for(i=0;p[i++]-40||p[i+3]-41;); // loop until we find chars '(' and ')'
// separated by 3 characters.
// since our input is enclosed in
// parentheses we will always find one.
p[i-1]= // i has gone forward one but set the
// first of these characters - the '('
// to...
p[i+1]-62? // ...depending on whether the middle
// char is a '<' or a '>'...
p[i]: // ...the one before the middle if '<'
p[i+2]; // ...the one after the middle if '>'
memcpy(p+i,p+i+4,strlen(p)); // move the back end of the string forward
// over the other 4 chars.
// now a "(A<B)" is reduced to "A"
// and a "(A>B)" is reduced to "B"
~-i&& // if we didn't just reduce the start of p
f(p); // then recursively call f.
// otherwise p is reduced to the answer
// and we're done.
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
O;1ị“/ṛ ɗḷ”vØ<
```
A monadic Link accepting a list of characters\*, which yields a character.
\* Uses the encased in parens option.
**[Try it online!](https://tio.run/##AS4A0f9qZWxsef//Tzsx4buL4oCcL@G5myAgyZfhuLfigJ12w5g8////KDw8KDw@PCkp "Jelly – Try It Online")**
### How?
Converts the input to Jelly code which will reduce the pair `['<', '>']` to produce the answer. Jelly ignores spaces and has a 1-indexed and modular index-into function, `ị`, so the Link starts by converting the input characters to their ordinal values and uses `ị` to form the code:
```
input character ordinal indexed into "/ṛ ɗḷ" meaning
( 40 (space) ignored
< 60 ḷ yield left argument
> 62 ṛ yield right argument
) 41 ɗ last three links as a dyadic function
(or reduce command) 1 / reduce by
```
So:
```
O;1ị“/ṛ ɗḷ”vØ< - Link: list of characters e.g. (<>>)
O - ordinals [40,60,62,62,41]
;1 - concatenate a one [40,60,62,62,41,1]
“/ṛ ɗḷ” - "/ṛ ɗḷ" "/ṛ ɗḷ"
ị - index into " ḷṛṛɗ/"
Ø< - "<>" "<>"
v - evaluate with input '>'
```
---
The example above evaluated:
```
ḷṛṛɗ/ - monadic chain (with left argument ['<', '>'])
/ - reduce (['<', '>']) by - i.e. f('<', '>'):
ɗ - last three links as a dyad - i.e. g('<', '>'):
ḷ - yield left = '<'
ṛ - yield right = '>'
ṛ - (ḷ) yield right (ṛ) = '>'
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~36 31~~ 30 bytes
```
>i:6%0$.
v
v~0[
v0(?o$6%?$~]
```
[Try it online!](https://tio.run/##S8sszvj/3y7TykzVQEWPi6sMiOoMornKDDTs81XMVO1V6mL//9ews7PRBAA "><> – Try It Online") [Verification of test cases](https://tio.run/##TVHNTuMwED7jp7CiotgiG1qtxCGaHV6CG0Ko27rUEsRW7FB64dW74xmnixSNPT/fjyfxnI9h/H3xHzFMWYek6i2dU5fmv3EKO5eSUruwd/qPbprmgn54uF2veqU@6fteP6vPtXkMq4fbx9X3y4VGnjfDr82LUnt30NM8vhLL27T9MH6Mc7aDujn5fNQhutG0hbjtdHtqrd4mfRj0oT9NPjtTOlbdRJL976QnPtNEsa3vQ8z3B5@OHPp41gXU9Cm@@2xsp3fbmOfJvYY5kzQxPU2z6zQboYzPTmf3tfRIcHIEGXXsU94TTqnT0b87vRni5Mdsfj6oNe0dcxh719rWWnVBBAVgAMEqg4iWckM5oKUA1gLlBqkFlkpI9ToDVAUC0IzhOgWeKTDClKNUGSoKnBCC@sQoKBaiYh2sRUIUjsIooRiiKDPIXCA2bfErg/KARQaLOIh11lSkU41hJWTLqtqir3aRDaJsoDgF/GkKxQ9WD1CdIfcRZAQFiuLK1gWUO3HIUupCOQiXTAIuOnB9ZXkL30CocOGC624ZjsvGcNkYO1XX1RuZL6te3JefwWrW/gM)
Takes input surrounded by parenthesis, and outputs a single character before terminating with an error.
### Explanation:
```
>i: Take input and make a copy
6% Map the possible codepoints through modulo: EOF,<,>,(,) => 5,0,2,4,5
0$. Jump to that line
> Line 0 ('<'): This just jumps back to the first line again
v Line 2 ('>'): Does nothing and goes back to the first line again
v~0[ Line 4 ('('): Pop the extra copy of input and create a new stack
0(? Line 5 (')'): If the input is EOF (-1)
o Output the top of stack (and error later)
$6% Otherwise, check what the middle character is
?$ If it is a >, swap the other two
v ~] Discard the right character and leave the other other one on top of the next stack
o~ Line 1 (EOF): If there is no more input, pop the copy and output the remaining character
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
“)ɗ<ḷ>ṛ( ”y;”/vØ<
```
[Try it online!](https://tio.run/##TVFLSsRQENznFC5frzyARd1jDuBmmLUwu8GN4AVmQL2BS0HFZUCYYyQXeVZ/XhBCJ91dVV3d2d8fDsfe19OrXc9Yvj65fL@0m/X0drxTuH2YL@jLz8d8afv56fd5fXzf9U5iAhoImxpJU96Ug6YAMyhvVAumElUvDFSFCMK0qCsExmni@MurQc0JkYihvhSTFYNULGAVxXANV8zghhQTw9BC2jT3m8BcYIyhD0daj5kaU75YeuF4Kld6qsvwxzyAGwX/e2LaYVlAGWP0iYQwqUxTVvv7tzTyJnXPCKmVSHDMwbakrxJfSCkOLWynDTrHwTgOFk6n7fIt8X7p4d7/RUwz@wM "Jelly – Try It Online")
Same essential approach as rak1507's APL answer. Requires the input fully parenthesized.
```
“ ”y Replace
) ) with
ɗ last-three-links-as-dyad,
< < with
ḷ return-left-argument-and-ignore-right,
> > with
ṛ return-right-argument-and-ignore-left,
( and ( with a space which is essentially ignored.
;”/ Append the reduce quick,
v and evaluate the result as a monad with argument
Ø< "<>".
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Δ„<>3々(ÿ)¬¦¨ºĆ'>ª:
```
Takes the input wrapped in parenthesis in both programs, as is allowed.
[Try it online](https://tio.run/##yy9OTMpM/f//3JRHDfNs7IwPL37UtOZRwzKNw/s1D605tOzQikO7jrSp2x1aZfX/v4aGjYadjY2mhp2GnZ2dpp2mpgaEYQdk2IAEbTQ1gfKaAA) or [verify all test cases](https://tio.run/##VVExSkNREOw9RUjje2BnJ8PkLAoWqSwEIZBAsMgBxNpGCBJygjTCi7WH@Bf57u7sy8dmeczOzszue3q@f1g@juuX1WI@G3Zvs/liNf6@D9sP8Pb8Obweh@2@nL9rO7Z9@2qnn9012@Fu3NyMhUS9KkCBPexlAGtgxTCwWrEGAikMvoG0zoUHw2FjxivRsRKsGPU5fzge4@klKzFMV5NhaHBSE0RNHddV8WhWxWLoQYGrsouqdboZPQK0RDq7WU/IVFX68GNEQvaZWanNPDT4Px8VjRkHGZLJIESixqmANS9COZS8U945ivTEBSc3TGv3H4PkOOnhcvKQYD8i@xEj8bSxK8SE/0Dfw/8oHM3qDw).
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'<∞©3ãε…(ÿ)}¬®Ã∞®«S:
```
Should have been 19 bytes by also using `€…(ÿ)`, but apparently there is a bug in the legacy version, so we'll have to use `ε…(ÿ)}` (or `'(ì')«`) instead.
[Try it online](https://tio.run/##MzBNTDJM/f9f3eZRx7xDK40PLz639VHDMo3D@zVrD605tO5wM0h83aHVwVb//2to2GjY2dhoathp2NnZadppampAGHZAhg1I0EZTEyivCQA) or [verify all test cases](https://tio.run/##VVFBSgNBELz7ipBLZsCDIl6kqDzCF0TwC0JAQRBCznlALoIQDLl5FnbvecR@ZO3u6snipRmqq6uqe27uV0@3z@Pry3o5nw2b3Wy@XI8LDNt9d7jrP88/w/tX6X/rW3fsTv2H46fu@/FhvB4LiXpVgAJ72MsA1sCKYWC1Yg0EUhh8A2mdCw@Gw8aMV6JjJVgx6nP@cDzG00tWYpiuJsPQ4KQmiJo6rqvi0ayKxdCDAldlF1XrNDN6BGiJdHazlpCpqvThx4iE7DOzUpt5aPB/PioaMw4yJJNBiESNUwFrXoRyKHmnvHMU6YkLTm6Y1m4/Bslx0sPl5CHBdkS2I0biaWNXiAn/gbaH/1E4mtUf).
**Explanation:**
```
Δ # Continue until it no longer changes, using the (implicit) input:
„<> # Push string "<>"
3ã # Create all possible triplets of these two characters:
# ["<<<","<<>","<><","<>>","><<","><>",">><",">>>"]
€ # Map over each string in the list
…(ÿ) # And wrap it in parenthesis
¬ # Get the first item (without popping the list): "(<<<)"
¦¨ # Remove its first/last characters: "<<<"
º # Mirror it: "<<<>>>"
Ć # Enclose; appending its own head: "<<<>>><"
'>ª '# Convert it to a list of characters, and append ">":
# ["<","<","<",">",">",">","<",">"]
: # Replace all ["(<<<)",...,"(>>>)"] with ["<",...,">"]
# (after the loop, the result is output implicitly)
'<∞ '# Push "<" and mirror it to "<>"
© # Store this string in variable `®` (without popping)
3ãε…(ÿ)}¬ # Same as above
®Ã # Only keep the characters that are also in `®`, removing the "()"
∞ # Mirror it: "<<<>>>"
®« # Append `®`: "<<<>>><>"
S # Convert it to a list of characters:
# ["<","<","<",">",">",">","<",">"]
: # Keep replacing all ["(<<<)",...,"(>>>)"] with ["<",...,">"]
# until there is nothing more to replace
# (after which the result is output implicitly)
```
[Answer]
# JavaScript (ES6), ~~69~~ 67 bytes
*Saved 2 bytes thanks to @Neil*
```
f=s=>s<(s=s.replace(/.?([<>]{3}).?/,(_,s)=>s[s[1]>'<'?2:0]))?f(s):s
```
[Try it online!](https://tio.run/##fVLLbsIwELz3K1AueCUa@rihZXLqV6RRFdFQFUUEYcql6ren610HFWH3skrsmdnx7O7ac@s3x8/D6X4/vHfjuF37NTw7v/blsTv07aZzy7JyNaP5fv6hslou3NvCk6BqXz82mPO8elo9NETV1nla@XEz7P3Qd2U/fLji5dz2X@2p87PTMOOC7v7ebl0ByOHNKbNjMCVuHABKcpxwGCSFiTiJcBA6k4AgyKwOC46ljeg4RUpRVpBO6oaLgFN5864/opFkiA9TVsMCi9R4KBrpPsGHlfBUqcaC9mMLgNLZGNXim8whWGYLZXJ6RS1e91cDxO0AxX02EkSbGl/6QdAMOOKRCQs21ZAa4/@AYNkg5sExJWQYYCPB5GEJURwh0o5cHHRcJC3Wz7iMvDu@zClkr19s7ZDvx5ed0haYtgDTFuiL8wmHDqoQVmzKJSyhOtKVGX8B "JavaScript (Node.js) – Try It Online")
[Answer]
# PCRE, 52 bytes
```
(((<|>|\((?3){3}\))(?=(?>(?4))?>)(?3))?(\((?1))?)(.)
```
[Try it online!](https://tio.run/##VVGxTgNRDNv5DoYEiZ5Q6WZ8P9KVAamiJ8qARPl1jiTO64nlKXIc28lbXj9Oh/UyrWaGK69Hs3nv3/ufo7vNLzbT5mf3mZ64z5aEpyjcdr7uHqb7w/S1Ggm/M8AQRVQB0AuzwBDTQDRQiLH4ATI6Nx4CR4wFz6oTT7FqNOeySLzG20tWYoSuJssw4KY2CG@d1NWT0eIVi6UHBXZlF1XrDDNmBGiJdk6zkZCtqvTlx4qE7rOzUptlaPB/PioaOw46JJtBiESNUwG9L0I5WN@p71yP9MQFNzdsa48fg@S46eF28pLgOCLHESvxtnEq1ET@wNgj/6gcw@r3vHy@nd8v6@Ny@gM "Perl 5 – Try It Online") Link includes Perl 5 test harness. Does not take outer parentheses (admittedly a version that takes outer parentheses would probably be shorter.) The desired result is captured in group 5. Explanation: Group 3 matches an operator. Group 2 matches two operators, but only if the second operator evaluates to `>`; a recursive atomic match is used to determine whether that is true. Group 4 then recurses if the current operator is an expression.
```
( Group 1 is:
( Group 2, which is:
( Group 3, which is either:
<|>| ... a literal `<` or `>` or...
\((?3){3}\) ... three recursive matches of group 3 inside parentheses;
)
(?= Followed by a lookahead to:
(?>(?4))? An optional atomic recursive match of group 4...
> ... which must be followed by a `>`;
)
(?3) Followed by another recursive match of group 3.
)? Group 2 is optional.
( Group 4, which is...
\( ... a literal `(`...
(?1) ... followed by a recursive match of group 1.
)? Group 4 is optional.
) End of group 1.
(.) Group 5 then captures the desired result.
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/) (no builtins), ~~147~~ 143 bytes
*4 bytes saved thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!*
```
i,m,c,q,w;f(char*s){for(i=m=w=0;c=s[i]%9;i++)if(c-1?c-4?w+=w-~c%3,++m==4:(q=i,m=w=0):0)for(s[q]=w-2&&w<9?62:60;q++<i;)s[q]=1;s=*s%3-1?*s:f(s);}
```
[Try it online!](https://tio.run/##dVRdb@IwEHzPr9imotgkPeiHKpXYRtWplU466Sq1b4WHNDjFuhAgDqK6qvfXuV070F4BCYXgnZkdzxpnpy9Ztl6beBpn8SJeJTnLJmnVsfwtn1XMyKlcyV6SSftkRq3rxEQRN4g5PRtkp5eDVSRXp3@z1kUcRVMpL/tsIVGLOLzf4yRhnxYjBJ2fnKzE9eDqvH/VSxZRJEzCXekssbJjWxeo2LH9nFmevK@PTZkVy7EGYeuxmX2bqOC/pcI801rgvIKtq1@Nb3xPaw5vAYApayh0CRJ6Cf5cTUyhGZWfcHXEqRZFVPHESluETtOimGXMmj965iU5dAjKCekiQVnjRPFLUAlfMBUSwIyw4nqYEREqXS@rkkpJ8B4ExM1TU3yfLfHNGQuOxzo3pYbH24dHZmPQr2gfhkjeOKunc6dKm8R0oNuBl7Se6ApSmC7r9LnQVDXlC3S6n5jNlnKGAkjzBRweLR9J12hrBpNoAHMUqnMWPmpbo2QfhmHLDsNhefs611mtx31ot7L2sLzJ6mVabH5JBQgrwxjcHmJqTi8gpfMxgPD@5uEhhD6Edzc/foZbR3ml9dZiE9I0NSUwmmO324Rwts0gZIIpIbjiwx7KBIjBQUg4i0FRqEEwX9aWhRJb3xQF2MlsWYzhWUNbtNGPJJKLO2RKCY6esfCxJgQTuLyzjmDF9@DRjhCK4wNJYk@dKdcHIQpxBzRwT9hWcdRgDtfs0cvuatIyoZx049hb3IdHB17VGUVQQ2wWBd/bgxz4B22QU@7EUa6X8Nvm@/LwRB/YxpYis8JH8b/Hw/NSX@dF1omndrJQjUef2i7GJYOfBq34Doas@bQpLKE@5/JFy49b@fE0HOFb7MEr4SnKSysfDG9mpvZ5Yc1cmzPjHr6XZwp1yJf4GMzmZArfSh3qJbbHx8mrzdDVZuhup4cyJXXHp9O0SYPOm3PDP/Hoj4p3XVrg9aSz3/hXz9n2BvKX9sf9c4cFPYaWgRpvIrz4jtzt8oGnG1UXVm947gzdp9YiC29xR7NHocPhZ/0P "C (gcc) – Try It Online")
Function that takes a null-terminated `char` array as input, and returns a `char` (`int`).
Here's a visualization of how it works:
```
(((>>>)<<)(<(<><)<)((<<(<<<))>(>(><>)<)))
((>....<<)(<<....<)((<<<....)>(>>....<)))
(>........<........(<........><........))
(>........<........<....................)
>........................................
```
(In the code, it uses 0x01 instead of `.`, but due to the modulus, they're equivalent even in data representation.)
Essentially it scans the code looking for instances of `(data)`, where `data` consists of substring of 3 characters, except `'.'` and `'('`. (4, in the code, since it tracks the `)` as the 4th character.) The program keeps track of the start of this string (`q`) and a binary representation of the visited characters (`w`). If we consider `'>'` to be equivalent to the binary `1`, and `'<'` the binary `0`, we simply look at a table of what the results of the binary strings should be. As it turns out, for `q=1,4,5,6`, the answer is `'<'`, and `'>'` otherwise. Thus, `w-1&&w<5` is a sufficient determiner. (In fact, since we keep track of `)` as part of this binary string, we have to consider that everything is doubled, and for no byte cost, we can modify this formula to obtain the `w-2&&w<9`.)
After we determine what the result should be, we replace the initial `(` with the result, and all subsequent characters with `.`. Then, so long as the initial character of the string is `(`, we repeat our function. This allows us to skip moving the string around, which, in my head, should save bytes, but I haven't tested the alternative.
Started working on this before I saw the [existing (much shorter) C answer](https://codegolf.stackexchange.com/a/218650/31957). But I enjoyed this nonetheless.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~51~~ ~~49~~ 44 bytes
-1 byte thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)! (match any character `.` instead of the opening bracket `\(`)
-4 bytes thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)! (`String#sub!` returns `nil` if there was no match)
Outputs by modifying the input. This would be 43 bytes with [tsh's regex](https://codegolf.stackexchange.com/a/218620/64121).
```
->s{s.sub!(/.((.)<.|.>(.))\)/,'\2\3')&&redo}
```
[Try it online!](https://tio.run/##TVHRSsNAEHzPV8Qq7S1oCvq6nR8xItSmVqi29BpEar89zu5eghD2bvdmZmc3p379M2xX7fCAfMlN7tc3admk1Ig2vw14SivL@0X72D4tZD4/dZvDdfjefey7@r0756qu82qWbi93r83b7vB5vMqMte1zfuFx7M@5zlX3tRkArVSTQqVKAIR5Yq4QBhVR5gl8UmEJrBeMsqokEJO8zuAYo5Fjh1WdGh08IYPvVAyWN2KxAEuRDNMwxQhmiDEwcC0Nm2J@AxgDjG1gzTWse0@2Kb5Q9NxxVVzxK69wf4gFmFHFf08IOygWtBiDv0MDgqAiTEmZ3@7UiJ2UfXoIrUAqxj46DWmj@E1DCqOWTqt1OsaFYVyYO62mzafA26ZH9/YvvJvIHw "Ruby – Try It Online")
---
# [Ruby](https://www.ruby-lang.org/) `-p`, ~~40~~ ~~39~~ 38 bytes
-1 byte thanks to [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus)!
```
sub /.((.)<.|.>(.))\)/,'\2\3'while/../
```
[Try it online!](https://tio.run/##VVHLasMwELz3KwQ9RIJWhva6zJf40gSXGBzb@EEI9Nur7ksxvazEaHZmdrXs50e5XKfbHF7D2F26df1aHuF7WsJtH7Z@HrrQj/O@rWXdz6HJMeZE@SeDz9Sm5u3UfrSfp/u1H7om56aUCFB6iUSR@MI3BpAUi4wREhd@IEUilM8g@OXJI8aJ25gX9YWLsrRV@uQiuLa7l1kZg3WtUw0ZdqqDlFxHdK1INK7GguqRBU6W3ag2TjWDRCAbwp3FrCaEq1p69YNGIn@HZ4VNJqEJ//PBosHjkIeEM0BGgrXDAibfCMwh@p58z1pMz7iEw42OseuPkcnh0KPnylUCdYmoS9TEx8SioB3yA3UO@SN1ZKvfad76aVzL@/wH "Ruby – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~22~~ 20 bytes
*-2 bytes thanks to Jo King*
```
i:2%?\
?$~$~\0(?o$6%
```
[Try it online!](https://tio.run/##S8sszvj/P9PKSNU@hstepU6lLsZAwz5fxUz1/38NOzsbTQA "><> – Try It Online") or [verify all test cases](https://tio.run/##TZHBTsMwDIbP5CmialNjMQoDicNkvJfgxhCCrWiVRhM1qcYuvPpw7HQgTV7s/L/9xQ2ntPf9w7n7Cn5I1kdTTvEUF3H8CIPftjEas/W71j7Zoaqqc7e6n683Zj37mf1s7tzazx7nZ754Wa5ulq/GHPfdobXLlbnyoe1dnb31wtbHGprj0KXW5QqYqzB0fXJ/Y5ph7F0VlMne@pBuP7u4l9CEk822qonh0CUHC7t9D2kc2jc/pjAmpnsexnZhu16z2tXXcnZwXQMDpPZ7UkET0459YM5EaBAdEoJxRAScO86RgAMCIOeO@AqBS8T1okGuIhtY46TOQTTZxp78l6ti1QmSsIPvuaO6ZBAXi7AU2ZF75I4aMhBH1ZD0QsWEzKtCfcA0hvJwVHSZaXhOAaPSUJBNweJfuSUBJN1AJkX6D0XKQ4UBCxnJPaFKSK2kVFAWkM/cQ5dSFipBe6kSaZqDl1fmt8gJtRVNvfCyW7HTtDGaNiak5rJ6p/q86ok@fwyZBvAL)
## Explanation
```
i:2%?\ main loop:
i Read a character from the input and push it onto the stack
:2%? If it's not a multiple of two (")" or EOF),
\ Swap to the branch
IP wraps around, repeat
?$~$~\0(?o$6% branch:
\ Entrance
0(? If the character is less than 0 (EOF),
o$ Output the result and error
Otherwise,
$ Check the middle value
? 6% If it's not a multiple of 6 (">"), [the IP wraps around]
$ $ Reverse the other two values
~ Pop the right value
$~ Remove the "(" from the stack
\ Return to the main loop
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 23 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü▼2δ`▀ÆH╞íq`º╪ ≈♀ô☺ßX→ú
```
[Run and debug it](https://staxlang.xyz/#p=811f32eb60df9248c6a17160a7d820f70c9301e1581aa3&i=%28%3E%3E%3C%29%0A%28%3C%3C%28%3C%3E%3C%29%29%0A%28%28%3E%3E%3E%29%3E%3C%29%0A%28%28%3C%28%3C%3C%3E%29%28%3C%3C%3C%29%29%3C%3C%29%0A%28%28%28%3E%28%3E%3E%3C%29%3E%29%28%3E%3C%3E%29%3E%29%3E%3C%29%0A%28%28%3C%3C%28%3E%28%3C%3E%3E%29%3C%29%29%28%28%3E%3C%3E%29%28%3E%3C%3C%29%3E%29%28%3C%3C%3C%29%29%0A%28%28%28%3C%3C%3C%29%3C%3E%29%28%28%3E%3E%3C%29%3C%28%3C%3E%3C%29%29%28%28%3E%3E%3E%29%3C%3C%29%29%0A%28%3E%28%3E%28%28%3E%3C%3E%29%3C%3E%29%28%3C%3E%3E%29%29%28%28%3E%3E%3C%29%28%28%3E%3C%3E%29%3C%3C%29%3C%29%29%0A%28%28%28%3E%3C%3C%29%28%3E%3C%3C%29%28%3C%3C%3E%29%29%28%3C%28%3E%3E%3C%29%28%3E%3E%3C%29%29%28%3C%3C%28%3C%3C%3E%29%29%29%0A%28%28%3C%28%3E%3C%3C%29%28%3E%28%3E%3E%3E%29%3E%29%29%28%28%3E%3E%3E%29%3E%3E%29%28%28%3C%3E%28%3E%3E%3C%29%29%3C%3C%29%29%0A%28%3C%3E%3E%29%0A%28%28%28%3C%3C%3C%29%3E%28%3C%3C%3E%29%29%28%3E%3C%3C%29%3E%29%0A%28%28%28%3E%3E%3E%29%3C%3E%29%3C%28%28%3C%3C%3C%29%3E%3E%29%29%0A%28%3E%28%3E%3E%28%3C%3C%3C%29%29%28%3E%28%28%3C%3E%3E%29%3C%3C%29%3C%29%29%0A%28%28%28%3E%3C%3E%29%28%3C%3C%3E%29%3E%29%28%3C%3C%28%3C%3C%3C%29%29%28%3C%28%3E%3E%3E%29%3C%29%29%0A%28%28%3E%3C%28%28%3E%3C%3E%29%3E%3C%29%29%28%3E%28%3E%3E%28%3E%3E%3E%29%29%28%3C%3E%3C%29%29%28%3E%3E%3E%29%29%0A%28%28%28%28%3E%3E%3C%29%3C%3E%29%28%3E%3C%3E%29%28%3E%3C%3E%29%29%28%3C%3C%28%3C%3E%3E%29%29%28%3C%3C%3E%29%29%0A%28%28%28%3E%3C%3E%29%3C%28%3C%3C%28%3C%3C%3E%29%29%29%28%28%3C%28%3C%3C%3E%29%3C%29%28%3C%3E%3C%29%3E%29%28%3E%3E%3E%29%29%0A%28%28%3C%3C%28%3C%3E%3C%29%29%28%28%28%3C%3E%3E%29%3E%3C%29%28%3E%3C%3C%29%28%3E%3C%3E%29%29%28%3C%28%3E%3C%3E%29%3E%29%29%0A%28%28%28%3E%3E%3E%29%3C%3C%29%28%3C%28%3C%3E%3C%29%3C%29%28%28%3C%3C%28%3C%3C%3C%29%29%3E%28%3E%28%3E%3C%3E%29%3C%29%29%29&a=1&m=2)
Uses the same regex as tsh's Javascript solution, and replaces till a fixed point is reached.
## Explanation
```
"\((.>)?(.)(<.)?\)".$2RgiH
g generator:
i apply the following till invariant:
"\((.>)?(.)(<.)?\)".$2 regex replace with second capture group
H take last generated value
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 54 bytes
```
#//._[a___,"(",b_,c_,d_,")",e___]->a.If[c=="<",b,d].e&
```
[Try it online!](https://tio.run/##ZVFBisMwDLz3GQkUG9z0A8pQ2NPeFnoMwXjThPbQHrK5Le3Xs7JkJw17EbY0mhlJ9zBd@3uYbl2Yh3ouj8fKN8F77wpTuG/vOu8u/LGF6znbHhCqz6Hp6rogrrtLW/X7@Wu8PaamPGA4fVzDGLqpH39OZbt/nbvweP3uCgMQc/CDyBC/9cNp2FwxXCFYDlymnDSQXs6Di@9o4hJxP6ONFDkIUAhSd3zHkpAkaZVdQCyg/SLOlYROSbIrWxTQEJ1yVCCEldS/XaZRtM6YVRG9kM60Woiqb4aR6HWerA1xSAmC1T104jgG4Z9jqFkkg5RsYwWBFAclgVq2aVlYpEzaYrqFBGVVOGEjS@tG8m1JSbFhpeUsQoS8YuQVi/vNGiKPNMUr5bHiHUU3nmD3nP8A "Wolfram Language (Mathematica) – Try It Online")
Input a list of characters.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 73 bytes
```
f=lambda s:~(q:=s.rfind('('))and f(s[:q]+s[q+ord(s[q+2])-59]+s[q+5:])or s
```
[Try it online!](https://tio.run/##TVLRasMwDHz3V5hCqUVZHzYKW1D1IyUPHWlYIEvTOC972a9nJ8kJK0WJz3fS@eLxZ/56DG/v47Qs7aW/fX82t5ir3/SsLvk0td3QpEM6EN2GJrYpX6tnfczX5/ExNUmfrzW9nD8cO1c1PaaYlxa174Z77Ia42@2CCAfmxMIUkogQ1glrFkJhIsY6CbaYAAnwwmGgDAE4yXAU46gMGn0oalKfYAsosI@OrrJBAAuxgFBoD@3oRQ2hOkesF7tNUr9O9AOsY0SHs1u3mQFzijEpDc1yKLbwL7tiBsUTUKcs/02J@5HigYszsX1hp4hLxV1RCUDf0cNDKYFa8V7OZFnn8HZKPYu9sbeStRdv2Zpc1sRkTcychi365HyNenWvH8OmIUxcilMe@27WW5ITVSHi17V2a6o4Tt0wpxY3b5/psFcQIqXc@7ztG7z8AQ "Python 3.8 (pre-release) – Try It Online")
# [Python 3](https://docs.python.org/3/), 77 bytes
```
def f(s):q=s.rfind('(');return~q and f(s[:q]+s[q+ord(s[q+2])-59]+s[q+5:])or s
```
[Try it online!](https://tio.run/##TVJBasMwELzrFSIQoiU0h5Yc6mz3IyGHgm1qCEpsuYde@nV3dlc2DWFtjWZ2R2M9f@avR35blrbrY58KNeNHOU39kNt0SAe6TN38PeXfMX7mVgnXZrwdy3U8PqY26fP1Ri/nd8fOzY0eUyxLj3ofcheHHHe7XRDhwJxYmEISEcI6Yc1CKEzEWCfBFhMgAV45DJQhACcZjmIclUGjD0VN6hNsAQX20dFVNghgJVYQCu2hHb2oIVTniPVit0nq14l@gHWM6HB26zYzYE41JrWhWQ7VFv51V8ygeALqlOW/KXE/Uj1wdSa2L@wUcam4K6oB6Dt6eCg1UCvey5ks6xzeTqlnsTf2VrL24i1bk8uamKyJmdOwRZ@cr1Gv7vVj2DSEiUtxKs/7MOstKYmaEPEbers1TXxOQ55Tjyu4L3TYKwiRUrp72fYNXv4A "Python 3 – Try It Online")
Solution without regex. Requires the whole input be parenthesized.
-1 byte thanks to ovs
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
F⁻S(≡ι)«≔⊟υθ≡⊟υ>§≔υ±¹θ»⊞υιυ
```
[Try it online!](https://tio.run/##NY7BCoMwEETP5itCTrvQHnrVEPDooUXoF4QYNSDRmqQtFL89XRHZyzAzbxkz6tXMesq5n1cOd@dTgMYvKT7j6vwAeOECBCIPHxfNyMEh/zGjg@UCRUm6qENwg4d2XiBR/YUVK872Ye5IcTCKmAOoY@M7@4V04Q876GjhdtIb21hne52mWPI2hXEvOUo21tKqSC@rnAFAKYVSIkiQSiIJkCTJQQV0klJEzNf39Ac "Charcoal – Try It Online") Link is to verbose version of code. Takes input wrapped in `()`s. Explanation: Port of @2x-1's answer.
```
F⁻S(
```
Remove `(`s from the input and loop over the remaining characters.
```
≡ι)«
```
If the current character is a `)` then...
```
≔⊟υθ
```
... pop the last character from the stack; and ...
```
≡⊟υ>
```
... if the (second) last character was a `>` then...
```
§≔υ±¹θ
```
... overwrite the (third) last character with the originally popped character.
```
»⊞υι
```
Otherwise push the current character to the stack.
```
υ
```
Print the final remaining character.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 76 bytes
```
s->{while(s.length()>1)s=s.replaceAll("\\((.>)?(.)(<.)?\\)","$2");return s;}
```
[Try it online!](https://tio.run/##VZFNb9swDIbv@RWCsQO5tgK248Ky2GW3nXpcdvBSJ3Wm2IYlZyiK/HaNIuVgAwx9kC9fPqJP7aV9OL38zv15GufkTnL3S@qDPyzDPvXj4D9uN/vQxui@t/3g3jfOTcuv0O9dTG2S7TL2L@4sOXhOcz8cf/x07XyMqFLnvlUfsuy9s53dwT3m@MDvf1770EH0oRuO6RWQP2F8jH7uptDuu68hQLPbAXjGJ/AI5PFpt8PmvvnwucHt3KVlHlzcXvNW@x3G2cGlnQvEl/9InHt@i6k7@3FJfhKIFAY4@Haawhs00NyJ@K7BBtGcrrpuyuGaMzNlIiAmzMDMKHeQO7EwESGS3IElRSghlnjVkERJCkQDGpdFNaVMaspWolpqHfQiFZIXR6vSRhKswhqUiuJRHG0pQLKahtWLDBMLrwntAWsbLs3J0LWntKlcXP2UOFcq@WqWlY9tAAWU@F8mNhyuCFTBWPNMJmErZYPC@v5yFg@bSZ2nLuZlSuK1D90eWZ6iJzIrXr3oNlot53VgvA5MSfNt8mD6MumVvvwL7Yb4Fw "Java (JDK) – Try It Online")
## Credits
* -16 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) by porting [tsh](https://codegolf.stackexchange.com/users/44718/tsh)'s [JavaScript answer's regex](https://codegolf.stackexchange.com/a/218620/52210)
[Answer]
# [Julia](http://julialang.org/), 61 bytes
using [tsh's regex](https://codegolf.stackexchange.com/a/218620/98541)
```
f(x,y=replace(x,r"\((.>)?(.)(<.)?\)"=>s"\2"))=x==y ? x : f(y)
```
[Try it online!](https://tio.run/##TVLLasNADLz7K8SepBAC7bHIkx/xJbQOuBg32C44X@/qsQ4NYbOSRqPZib5/x@H2tu37nbfzs537x3j77O0@l475ArnyRVgvcu2ktFhK915E2q1tn3SljT7ozk/Z135ZF2qplNIA2qiyQqVhAGIxW6wwIlURtZhhJRVLwfIVo5ZVazAMR96OwHib9fiPZ6M1J0RgHVY3xuyKQZaswJq0DudwxjxckJ2JQXBpyhTXm8B8wDEGPlxTesy0MVUXKl8obqoq@9YqQh/SABeq@K8JKQdVglZhiDo0IchWpCip7/e7caQn1c84kiuRimOOvh7pT4mbJhUOLn1ZG@04DMNhWChtXs5z4t3pQ73/FzHNvPSdaO4/M/mS0DDR8hiHlWNlpCH7RMGWhwudMjhRkRK1xzxM6zgF/EylMyConG3tPGP0/fS1/wE "Julia 1.0 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 27 bytes
```
'\((.>)?(.)(<.)?\)'⎕R'\2'⍣≡
```
[Try it online!](https://tio.run/##VZAxDsIwDEX3noLN9tAOzNbvHZi7VEKwVIKVCyAxgFg4AOJmuUhrO0lVqshJnO/v547XqT3exulynudTur9pYO4gPXfC2kk/CKXX50DDntLzlx5fk@2IARVq/MSqDFZAVIQZCrGgYpvaVlWRy0FNYjE8IngqZ1fPIrdnCMLXD@ZpnXJN9m6o3Xx293KHqW2dAaVlxlqBHNlW0UA2A2lQcTihcqNyazD9@fhYUaWSDRwPPoDGjxFaAA "APL (Dyalog Unicode) – Try It Online")
This is longer than rak1507's [answer](https://codegolf.stackexchange.com/a/218621/95792), but I just wanted to use a different approach. Uses the same regex as everyone else.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 24 bytes
```
L#aaR:`\((...)\)`B@A@>Ba
```
[Try it online!](https://tio.run/##ZVExbgJBDOx5BYJmt8g9AI1GQB0aWojElZFS0Ed5@2J7vLec0li79nhmbD@/n@23fe7n@Xp43EuZpqne6@N8PB15ntvf9rK5bba7QqLu/AEU2FsfS7P2SrEKWC1YGT1ZGL2WpxXf0bASrN/QJYoWAhgE2e1vLwVJSkt2AZmA@kPcKonOJOpgcwEFd2pRQAYr5L8u0witGbsq3Qs007Dgqm@GmfSap2szHCIhHO6piX0M8J9jyizTINI2B4gQjiKhLNdcFhepklvMW0QQq@DgShZjI/22EClXrFjOEkTsK2ZfcbhfrcF5osmv1MfyO4ZunOCrtY@fFw "Pip – Try It Online")
### Explanation
This one is a regex replacement solution:
```
L#aaR:`\((...)\)`B@A@>Ba
a is command-line argument
L#a Do the following len(a) times:
aR: In a, replace (and assign back to a)
` ` this regex:
\( Literal open paren
(...) Three characters (captured in group 1)
\) Literal close paren
with the result of the following callback function:
@> All but the first character of
B capture group 1
A ASCII code of (the first character of) that string
B@ Use that value to index cyclically into group 1
a After the loop, output the value of a
```
The replacement works because the charcode of `<` is 60 and the charcode of `>` is 62. Using those values as modular 0-based indices into a three-character string gives the first character and the last character, respectively--exactly what we need.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 25 bytes
```
u:G."(\‹Kž%
<—åkí2""\\2
```
[Try it online!](https://tio.run/##K6gsyfj/v9TKXU9JI4bpULf3oXmqPDYsh6YfXpp9eK2RklJMjNH//0oadho2NnaaNppKAA "Pyth – Try It Online")
---
Uses the regex from [tsh](https://codegolf.stackexchange.com/users/44718/tsh)['s Javascript answer](https://codegolf.stackexchange.com/questions/218618/evaluate-left-or-right/218620#218620). Replaces each match with its second matching group until a fixed point is found and printed.
[Answer]
# [sed -r 4.2.2](https://www.gnu.org/software/sed/), 27
Using the same regex as everyone else:
```
:
s/\((.>)?(.)(<.)?\)/\2/
t
```
[Try it online!](https://tio.run/##VVExbsNADNv9EmmoDWQMCOYjHtuhS1LUeX@vkqiLkUU4UBRJ6Y6vzzGuy7HtZiv9ZqsbVr/tvu2XbXmOYSR8McAQj3gFQC/MAgNjANFAIcbiB8jovHgIHDEWPKtOlGLVaM7lI/Eaby9ZiRG6mizDgJvaILx1Ulclo0UVi6UHBXZlF1XrTDNmBGgJOS/lNiOyZRW/DFmZ0H12WGq1TA2@B6SysfOgU7IZhEjUOJXQ@ySUg/Wh@tBVpCcueLrh3Ht@GSTHUw@vm5cE5xU5r1iJz41ToSbyC@Ye@UnlGFZ/j5/n9@N@jI/ffw "sed 4.2.2 – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 27 bytes
```
VaR^"<>"''._R'("({bQ'<?ac}"
```
Takes input with outer parentheses. Verify all test cases: [Try it online!](https://tio.run/##ZVGxTkMxDNz7FVWWlwzwBafjCxjowIIAFSYkhu5Vvz3YPifpE4uV2Oe7s335ufRrfz2fPgpYtu3x87TVUq9fLxuezt@30m/H58Pb4VgqiVb8AVTYWx9Ls41KtQrYLFgZI1kZvZanFe/RsBKs39A1ihYCGATZ7W8vBUlKS3aCTED9IW6VRGcSbbG5gII7tSgggxXy3@Y0QmvGoUr3As20LLjqnWEmveYZ2gyHSAiXe2piHwP855gyyzSItM0FIoSjSCjLLZfFKVVzi3mLCGIVHNzJYm1k3BYi5Y4V8yxBxLFijhWH@90anCea/EpjLL9j6MYJ3nt/@O2T/A8 "Pip – Try It Online")
### Explanation
Translates the input into a Pip expression and evaluates it. In Pip, function call syntax is `(f a b c)`, so all we have to do is quote the angle brackets and insert an appropriate function inside each opening parenthesis:
```
a Command-line input
R Replace
^"<>" either of < and > with
''._ itself with a single quote prepended
R Replace
'( open parenthesis with
"( " open parenthesis followed by a string representation of
{ } this function:
bQ'<? If the second argument is equal to <
a then return the first argument
c else return the third argument
V Evaluate as Pip code
```
] |
[Question]
[
## Challenge:
Given a number, take the largest prime strictly less than it, subtract it from this number, do this again to this new number with the biggest prime less than it, and continue doing this until it's less than 3. If it reaches 1, your program should output a truthy value, else, the program should output a falsey value.
## Examples:
All of these should give a truthy value:
```
3
4
6
8
10
11
12
14
16
17
18
20
22
23
24
26
27
29
30
32
34
35
37
38
40
41
42
44
46
47
48
50
```
All of these should give falsey values:
```
5
7
9
13
15
19
21
25
28
31
33
36
39
43
45
49
```
## Rules:
* You can either write a program or function.
* You can assume that the input is bigger than 2.
* [Standard loopholes apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer wins!
[Answer]
# [Retina](http://github.com/mbuettner/retina), 31 bytes
```
.+
$*
+`1(?!(11+)\1+$)11+
1
^1$
```
Prints `0` (falsy) or `1` (truthy).
[Try it online!](http://retina.tryitonline.net/#code=JShHYAouKwokKgorYDEoPyEoMTErKVwxKyQpMTErCjEKXjEk&input=Mwo0CjUKNgo3CjgKOQoxMAoxMQoxMgoxMwoxNAoxNQoxNgoxNwoxOAoxOQoyMA) (The first line enables a linefeed-separated test suite.)
### Explanation
```
.+
$*
```
Convert input to unary by turning input `N` into `N` copies of `1`.
```
+`1(?!(11+)\1+$)11+
1
```
Repeatedly remove the largest prime less than the input. This is based on [the standard primality test with regex](https://codegolf.stackexchange.com/a/57618/8478).
```
^1$
```
Check whether the result is a single `1`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
’ÆRṪạµ¡Ḃ
```
[Try it online!](http://jelly.tryitonline.net/#code=4oCZw4ZS4bmq4bqhwrXCoeG4gg&input=&args=MTIzNA) or [verify all test cases](http://jelly.tryitonline.net/#code=4oCZw4ZS4bmq4bqhwrXigbjCoeG4ggrDh-KCrOKCrEc&input=&args=W1szLCA0LCA2LCA4LCAxMCwgMTEsIDEyLCAxNCwgMTYsIDE3LCAxOCwgMjAsIDIyLCAyMywgMjQsIDI2LCAyNywgMjksIDMwLCAzMiwgMzQsIDM1LCAzNywgMzgsIDQwLCA0MSwgNDIsIDQ0LCA0NiwgNDcsIDQ4LCA1MF0sIFs1LCA3LCA5LCAxMywgMTUsIDE5LCAyMSwgMjUsIDI4LCAzMSwgMzMsIDM2LCAzOSwgNDMsIDQ1LCA0OV1d).
### How it works
```
’ÆRṪạµ¡Ḃ Main link. Argument: n
µ Combine all atoms to the left into a chain.
’ Decrement; yield n - 1.
ÆR Prime range; yield all primes in [2, ..., n -1].
Ṫ Tail; yield p, the last prime in the range.
If the range is empty, this yields p = 0.
ạ Compute the absolute difference of p and n.
¡ Call the chain to the left n times.
This suffices since each iteration decreases n, until one of the fixed
points (1 or 2) is reached.
Ḃ Bit; return the parity of the fixed point.
```
[Answer]
# Regex (ECMAScript or better), ~~33~~ 32 bytes
```
^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$
```
Takes its input in unary, as a string of `x` characters whose length represents the number.
[Try it online!](https://tio.run/##TY87b8IwFIX/Co0Q3Js0JqCqA67J1IGFoR37kCy4JLc1jmUbSHn89jQMlTqcb/mOdHS@9EGHtWcX8@B4Q37X2G/66byydBy8UPXcOoCTWkzS7hOgVCIre0LbZiW@z9Jhj1swbYddOjmhiM1r9GwrQBEMrwke7/MHRBlUIY81GwIwypPeGLYEiHfK7o3Bc6WMCM5whHE@RslbAKsqYchWscbF7HLhsNIrYOW0D7S0Eaq34gPxT9B/YRfTcjq/aYy1b47J0h604c3Aa1vRfJBkRm4bD5KfFEnOMuwHkzYRnhzpCIxip@O6Bo94DqOR6y9FuL2YSrePIfq@Iq/XrshnRfEL "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript
[Try it online!](https://tio.run/##bVJdb9swDHzvr@CMDpGSVHX6ONUItmEDBqzb0D6mGaDYcqJUpj1JbpwW/e0Z5XgfBWLAlkmejroTt@pRXWyLh4OpmtoF2FIsTC3GEv7PtMHYkzmn17qjylnTrqzJIbfKe7hRBuEZhpwPKtDyWJsCKqqwu@AMrkG5tV8sOYSNq3cePnW5boKpaecZwGdjNZQZ6l3/yxKR14UWVE@4/NCWpXa6uNWq0A5WPex1kv3ZOYQl53Lo66dB7jaRnzGfrUiDKr4a1IzzNxm21nJTMi/0r1ZZz5LL8XiccP78GnpkYCycJHgmhvCXgQguiWFFuAfpJ9noHkdxDfLlmHv5oULQDsFlwx@prZrYwHNJbqzq2mqF8JSVxKgl3OUKkaQbbNoAGUS1Q47d7X3QlTDIJQw6e5jYKP9Nd4GO2VsMMBhi6ezEcQQhIQaJQ32xBEvliBK@sSaw5IIugfABMKXKFww0Bk40ynlNAbOLdMmngLOTRWE1rsPm@grmEJHwjpbZkhjzjXKLZTfo6SOcLSW8d07tvSiNtaybjrpRbwpAWbuojY6RYSoBrzOc0TKZkMAbFfINOVQRmxPVMWL95CIN@EciP06M2DnVsKFFXjf77@WtwrWmTukUOY9KS2AVtceCvIt3@8QHk2tybOdM0CxeKpdPWXBtvJ9/5YY8DCVL3vqELOHyJT5ncaoOPxmbZ2Iypy/rusmc31@Nz@kTXz7uzg9xcg7pxVWa/gY "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##RU7LasMwEPyVJYhYG9u1bOilsmIH0mtPvTWpSEsMAjVxJRdUhPvr7toN9LDDzuxjpj87ez99fANzEqK9vp8ssEISVfV@97zbjtBdHWdeCVlvJUYwHTGMvTOXAVaHy0qO0Frle2sGnuRJ5r/e/EAnOsvLrMTz57zU/KuCdHxgGuX8y5PjybW2rjC29qU8KkJxlDdfc6PM1GoZU5emGE0HnCchgQC0hAjqBwrmCozMr9dLuCUbBS/lX1Zm5DiOWj8@7bWeXjlv1F3aEPIQ0gYP1YYRzIWbwKZJ5JUQvw "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##XVBNa8MwDL33V4hgiNUkbdKra3LZBoWxw7Zb05ksc5qA65jEhUDpb8/kstMOEvp4T0@S69yyL13ngI0gIdpGsAE36rMatTN1o3m83axLpbraeNUMF9cbPVa8QlG9b6c4hZispaI66wCwXls/caVeDq/PSmEKBdJIGixW7TBy1stcMCNbgk/84/Pp8IYCb9C3nJnj5EejLUWYFScpo8pGSODp@k0dKqd5mhUY@Hp2ZvjRPMqilOCC@M1wtT5w9zsiHWkA@fwkVgAPZfuXM7uXjz5FSYIkDfxx8qX2TcfZmJJYuF/XnsdznDKLiHALK/aom24IewmgUwoBIQdmxZ1k7v/@xFEsX5yXcpOU5Pk8JyVWuzUjFwzXM1uWPNvl@S8 "PHP – Try It Online") - PCRE
[Try it online!](https://tio.run/##dVPbjpswEH3PV0zT1cYOkIWs1AcIG6lSf6DqQ6tsiljHAauJQcYoJNX@@qZjs6E0JZYweC5n5pwxrCy9jLHzRyHZrt5wWLwURaUfFM94M8vL8ml07eIN46UWhXzYiDSTaBIsEXJbqH1qzG0Wy1MFSblaQwxfx58Ph18vj/WP4/H7t/zTISfnn4Qs45mzxJ00jbOkz/PpHW7modPm7kyvc8YuTMs4KZ0g6vUksL7i6f5pJKSGfSokofB7BLjKFbp2XJKSesE69iOoMeZxnmgozMkkZOaj0pswxFghMzSWtY5sPitkpcGSDkMrCCiOYNHFViFhlsMhT98zUAMgBvYU@y6ceAeecb0TkhN7YEK6bR0aXXo1yyRKH/VKdSGIDZixBPsilLogAxfKokJ369kKuSETb0KjDkAG6DUxH@I@pzCUxrgcwAXHxjsQUAix@F8sO7@pKSf5oT2tZOAE6wj2fF9xTSoXJs3ENIaKVOg0Enf5nRQilkbrRSyDCBxH9BmbpdXxymK12ALpK59UPFUsJ6THi96bqp5Yu3YELk6H0gGsC96JAlI3VMjkWaJwOKYgGgxv51TUGhYLEP/HvI5un5i9FOSf29P9M3DPlaI3CA83eNWM2cYhfFGqUONoGIdT2BokC@MaAFM1Mjeyw0NLH29s3u/dDv/XxGLcIN5@tbviulYS8DK8nn1v7vtvbLtLs@rs7WyBxE70Dw "C++ (gcc) – Try It Online") - Boost
[Try it online!](https://tio.run/##NY3NisMwDITveQpherDyY5zuLcHkQbpdKG261eLKQfay6dNn7ZYeNAjNN6PlkW6BPza6L0ESxEdsZW5/YuARxIlSavvSenKmmbLqdW0m/NzXuyxlsF53W4YO/dD1xxHI2eoaBDwQlzIT04V4qMA7b@LiKWnVKaygQFwgOfH3rImT9gd7xPa15TJsesxBoCvIbO6ndL5paUGtquanURwaYJESwefB9eP7a/hN5k8ozTom0Yy42W5v7T8 "Python 3 – Try It Online") - Python
[Try it online!](https://tio.run/##PY5Bi8IwEIXv@ytmi2BS6ZD2GkMR9Oph2Vt1w4qxBkIsacR42b/enYh6mAfz5n0zE66H@xRAwZfpTRrQmxusV98rDOb3KMEqIeF2ts6AU72J4weAPYHrqnqvVLHzhaSB6wRi1ewlGH@kBDk4Ds5GNq/m/ImgM76PZ8aXDTEd8YS9kdMlgAfrIZsYL9qyWnDEHHy3lHvsYkUqSs9B/UGQ2bCf@c/hGsfHvvx3TX2wPoJ/nciaS@vNdq319MNYq3DRkrKUFi3fNeWMJBcv02yaRNUI8Q8 "Ruby – Try It Online") - Ruby
[Try it online!](https://tio.run/##RY9Ra4QwEIT/SpAFE23E8/EkeNDn@wWehWD3aiC3kZhDOclvt9pS@jAD37AMs6Ob0U8DWruBV63HL1y685lw5pd0@@C8UUXe7M6XJW/Ercpgt0MiW2BLL2/Ju3uMxuJnImp4qbK@O4@6HzhYZoiBofEZxApagZXTaE1IZFKbOwdd9O5JQdrAquMgV6Dbsot7AQdSraHQ/SQ1kLT4x6eD81ysR4cvrjr0A048XdIMSPzGL7HO3gSUg5tC3Ged6n9mktz@oDWEDCjGuJWyKstv "PowerShell – Try It Online") - .NET
I finally found a use for the positive lookahead primality test I came up with on 2018-12-07! This is 2 bytes longer than the ["standard"](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime/57618#57618) [negative lookahead primality test](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime/177196#177196), but it allows the full regex to be 1 byte shorter:
```
^ # tail = input number
( # Loop the following:
(?= # Atomic lookahead - finds the first match, and once
# finished, its result won't be changed by backtracking
.+? # tail = largest number that is less than the current tail,
# for which the following matches:
(?=(xx+?)\2*$)\2$ # Assert tail is prime; \2 = tail
)
\2 # tail -= \2
)* # Iterate the above loop zero or more times
x$ # Assert tail==1
```
A neat thing about this regex is that it can be logically negated for all inputs other than zero simply by adding one byte, because after the repeated subtraction, all \$n>0\$ end up at either \$1\$ or \$2\$:
```
^((?=.+?(?=(xx+?)\2*$)\2$)\2)*xx$
```
[Try it online!](https://tio.run/##TY87b8IwFIX/Co0Q3Js0JqCqA67J1IGFoR37kCy4JLc1jmUbSHn89jQMlTqcb/mOdHS@9EGHtWcX8@B4Q37X2G/66byydBy8UPXcOoCTWkzS7hOgVCIre0LbZiW@z9Jhj1swbdthl05OKGLzGj3bClAEw2uCx/v8AVEGVchjzYYAjPKkN4YtAeKdsntj8FwpI4IzHGGcj1HyFsCqShiyVaxxMbtcOKz0Clg57QMtbYTqrfhA/BP0X9jFtJzObxpj7ZtjsrQHbXgz8NpWNB8kmZHbxoPkJ0WSswz7waRNhCdHOgKj2Om4rsEjnsNo5PpLEW4vptLtY4i@r8jrtSvyWVH8Ag "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript
[Try it online!](https://tio.run/##bVJdb9swDHzvr@CMDpGSVHX6ONUItmEDBqzb0D6mGaDYcqJUpj1JbpwW/e0Z5XgfBWLAlkmejroTt@pRXWyLh4OpmtoF2FIsTC3GEv7PtMHYkzmn17qjylnTrqzJIbfKe7hRBuEZhpwPKtDyWJsCKqqwu@AMrkG5tV8sOYSNq3cePnW5boKpaecZwGdjNZQZ6l3/yxKR14UWVE@4/NCWpXa6uNWq0A5WPex1kv3ZOYQl53Lo66dB7jaRnzGfrUiDKr4a1IzzNxm21nJTMi/0r1ZZz5LL8XiccP78GnpkYCycJHgmhvCXgQguiWFFuAfpJ9noHkdxDfLlmHv5oULQDsFlwx@prZrYwHNJbqzq2mqF8JSVxKgl3OUKkaQbbNoAGUS1Q47d7X3QlTDIJQw6e5jYKP9Nd4GO2VsMMBhi6ezEcQQhIQaJQ32xBEvliBK@sSaw5IIugfABMKXKFww0Bk40ynlNAbOLdMmngLOTRWE1rsPm@grmEJHwjpbZkhjzjXKLZTfo6SOcLSW8d07tvSiNtaybjrpRbwpAWbuojY6RYSoBrzOc0TKZkMAbFfINOVQRmxPVMWL95CIN@EciP06M2DnVsKFFXjf77@WtwrWmTukUOY9KS2AVtceCvIt3@8QHk2tybOdM0CxeKpdPWXBtvJ9/5YY8DCVL3vqELOHyJT5ncaoOPxmbZ2Iypy/rusmc31@Nz@kTXz7uuvNDHJ1DenGVpr8B "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##RU7LasMwEPyVJYhYG9u1bOilsmIH0mtPvTWpSEsMAjVxJRdUhPvr7toN9LDDzuxjpj87ez99fANzEqK9vp8ssEISVfV@97zbjtBdHWdeCVlvJUYwHTGMvTOXAVaHy0qO0Frle2sGnuRJ5r/e/EAnOsvLrMTz57zU/KuCdHxgGuX8y5PjybW2rjC29qU8KkJxlDdfc6PM1GoZU5emGE0HnCchgQC0hAjqBwrmCozMr9dLuCUbBS/lX1Zm5DiOWj8@7bWeXjlv1F3aEPIQ0gYP1YYRzIWbENg0ibwS4hc "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##XVBNa8MwDL33V4hgiNU4bdKra3LZBoWxw7Zb05ksc5pA6hgnhUDpb8/kstMOEvp4T0@Sa92yL1zrgHlQEG0j2IDz5qy9cX1VGx5vN@tC67bqJ10PF9f1xpe8RFm@b8dYQEzWUFGfTQDYydhp5Fq/HF6ftUYBOdJIGixXzeA561QmWa8ago/84/Pp8IYSb9A1nPXHcfK9sRRhmp@UikobIYHH6zd1qCwykeYY@GZ2/fBjeJRGguCS@PVwtVPg7ndEOtIA8tlJrgAeyvYvZ3avHn2KkgRJGvjj5Es11S1nXpBYuN9UE4/nWDCLiHALK3Zo6nYIe0mgU3IJIQdm5Z1k7v/@xFEuX5wXapMU5Pk8JwWWuzUjFwzX88yWJUt3WfYL "PHP – Try It Online") - PCRE
[Try it online!](https://tio.run/##dVPbjpswEH3PV0zT1cYOkIWs1AcIG6lSf6DqQ6tsiljHAauJQcYoJNX@@qZjs6E0JZYweC5n5pwxrCy9jLHzRyHZrt5wWLwURaUfFM94M8vL8ml07eIN46UWhXzYiDSTaBIsEXJbqH1qzG0Wy1MFSblaQwxfx58Ph18vj/WP4/H7t/zTISfnn4Qs45mzxJ00jbOkz/PpHW7modOmuTvT66SxC9MyTkoniHpNCWxA8XT/NBJSwz4VklD4PQJc5QpdOy5JSb1gHfsR1BjzOE80FOZkEjLzUelNGGKskBkay1pHNp8VstJgWYehVQQUR7DoYquQMcvhkKfvGSgCEAN7in0XTrwDz7jeCcmJPTAh3bYOjS69mmUSpY@CpboQxAbMWIJ9EUpdkIELZVGhu/VshdyQiTehUQcgA/SamA9xn1MYSmNcDuCCY@MdCCiEWPwvlh3g1JST/NCeVjJwgnUEe76vuCaVC5NmYhpDRSp0Gom7/E4KEUuj9SKWQQSOI/qMzdLqeGWxWmyB9JVPKp4qlhPS40XvTVVPrF07AhenQ@kA1gXvRAGpGypk8ixROBxTEA2Gt3Mqag2LBYj/Y15Ht0/MXgryz@3pfhq450rRG4SHG7xqxmzjEL4oVahxNIzDKWwNkoVxDYCpGpkb2eGhpY83Nu/3bod/bGIxbhBvv9pdcV0rCXgZXs@@N/f9N7bdpVl19na2QGIn@gc "C++ (gcc) – Try It Online") - Boost
[Try it online!](https://tio.run/##NY3dasMwDIXv8xTC9ELOj3G6uwSTB@k6KFu6arh2kDXmPn1md@xCB6HznaPtIbcYXna6b5EF0iP1vPZfKYYZ2LFSan9DXJzplqKYc7fo12N7KFJHtzkf9kKdxmkYzzOQs801MnigUNtMkg8KUwPeeZM2T4JqULqBCoUK8SV8rkhB0J/sWfd/WynT3ahLEOgKvJr7Rd5vyD2orNrwNKpDE2xcI/p5cOP8/zV@i/lhkhWTMAatdzscrf0F "Python 3 – Try It Online") - Python
[Try it online!](https://tio.run/##PY5Bi8IwEIXv@ytmi2BS6ZD2GkMR9Oph2Vt1w4qxBkIsacR42b/enYh6mAfz5n0zE66H@xRAwZfpTRrQmxusV98rDOb3KMEqIeF2ts6AU72J4weAPYHrqnqvVLHzhaSB6wRi1ewlGH@kBDk4Ds5GNq/m/ImgM76PZ8aXDTEd8YS9kdMlgAfrIZsYL9qyWnDEHHy3lHvsYkUqSs9B/UGQ2bCf@c/hGsfHvvx3TX2wPoJ/nciaS@vNdq319MNYq3DRkrKUFi3fNeWMJBcvU5pNk6gaIf4B "Ruby – Try It Online") - Ruby
[Try it online!](https://tio.run/##RY9Ra4QwEIT/SpAFE20k5@NJ8KDP9ws8C2L3aiC3kZjDcOJvt9pS@jAD37AMs6Ob0U8DWruB143HL4zt@Uw480u6fXBe6yKvd@cx5rW4lRnsdkhkMcKWXt6Sd/cYjcXPRFTw0qq6O49dP3CwzBADQ@MziAU6DVZOozUhkUll7hy6ondPCtIGVh4HuYauUe26F3Ag3RgK7U9SAUmLf3w6OM/FcnT44tqFfsCJpzHNgMRv/BLL7E1AObgprPusU/XPTJLbP7SGkAGt67opWSr1DQ "PowerShell – Try It Online") - .NET
---
Here is the regex implemented in some languages that have golf-efficient regex calls, where it either beats the other submitted solution(s) or is the only one in that language:
### \$\large\textit{Anonymous functions}\$
# [Julia](http://julialang.org/) v0.4+, 58 bytes
```
n->split("x"^n,r"^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$")[1]==""
```
[Try it online!](https://tio.run/##TY3BbsIwDIbvewov4pAAnWiPy7KeeYYNpCASyGSZKkmlqC9fnBUkDv5l@/f/@W/EYNsyezNT850GDFmKIo60jeIoZW8@Nj2rLGXTq99uvWKppdZlJdRPezBGiHky3mJyGvwtAkIgiM6eMZBLUr0BoFnIuBWNUBqCB3R0yVeJ6qvTMIzp@s4uMpBtR2cOVRZV1mBjcnJPefE/X@fuUPlQiV7S0gNc8HayCJPm9aSHGCgjSaUZrGEyOY7ucfnvPYPL36pcc9t0u90d "Julia 1.0 – Try It Online")
The above returns truthy for an input of `0`. If returning falsey for `0` were needed, it'd be **60 bytes**:
```
n->match(r"^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$","x"^n)!=nothing
```
[Try it online!](https://tio.run/##TY3BTsMwDIbvPIUX7eBsK@p6XAg98wywSYElbZBxqySVqr58SShIHPzL9u//8@dE3pzn1emVq@cvkz56DOKG2OrHY5sV5/nYyrfmsM9SSh7mvTiJWdxY7jQPqffcrYt2hqJV4IYABJ4hWHMnzzaifAAgHUfyCekkKiEVeAdkuUs9knxqFIxT7HfZpdfzNduW7zlUWFxYownR4gunzb/8n5tr4UMhOuStB@hoeDcEi8rrRY3BcyJGqTJYwaJTmOzv5Y/3F9z@Fs211lVT198 "Julia 1.0 – Try It Online")
or **59 bytes** in Julia v0.7 and earlier with `!=Void()`: [Try it online!](https://tio.run/##TY3BTsMwDIbvPIUX7eBsKyq9IBFCz7wAF9ikQJM1yLhVkkpVX74kFCQO/mX79//5cyJv7lenV66evkz66DGIC2Krb49tVpznYyvfmsM@Syl5mPfiJGZxYbnTL4PvUK6LdoaiVeCGAASeIVjTkWcbUd4AkI4j@YR0EpWQCrwDsnxNPZJ8bBSMU@x32aXXu3O2LXc5VFhcWKMJ0eIzp81/@D8358KHQnTIWw9wpeHdECwqrxc1Bs@JGKXKYAWLTmGyv5c/3l9w@1s011pXTV1/Aw "Julia 0.7 – Try It Online")
Of course as far as Julia v0.4 goes, [Glen O's answer](https://codegolf.stackexchange.com/a/92937/17216) outgolfs this at 32 bytes, but for v0.5 and later, this and the below may be optimal golf.
# [Julia](http://julialang.org/) v0.7+, 54 bytes
```
n->occursin(r"^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$",'x'^n)
```
[Try it online!](https://tio.run/##TY3RbsIwDEXf9xVehYQDFJU@Lsv6vG/YQMoggUyWWyWpFPXnu4SCtAdf2b6@x78jOX1Is1Uz1x/9@Tz64Bh9dULs1H7bZcWUtp34bjerLKXEJq2q3TqtTyzmSVlNwUiwvQcCx@CNvpBjE1C8AJAKA7mItKvqSkhwFsjwNd6QxHsrYRjD7TW79HU4ZtvwJYcKiwtr0D4Y/OS4@G//5/ZY@FCIFnnpAa7U/2iCSeb1JAfvOBKjkBksYVLRj@ZxefeeweVv0VxzU7dN8wc "Julia 1.0 – Try It Online")
# [Julia](https://julialang.org) v1.2+, 53 bytes
```
n->endswith('x'^n,r"^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY_BSgMxEIbvPsW4CE3arqwLghjjnn0GbSHSpI0M0yXJ4rKv4qUI-0ZefBsnpoKH-cnkz__N5GN-G9Cb06fT85Bcffd9S_WjpV189-kgFuNiS-tQbYXo9PWqYxXjuOrkS7u8Yskll2Mlz-GvSTuD0SpwxwAIniBYs0NPNgp5AYA69uiTwHVVV1KBd4CW9jwK5UOroB_i4ZJdfL7ZsM2LcCizKLN6E6IVT5SKf_-_bzeZD5noBJUzwB6PrwZhUnw9qT54SkhCKgYrmHQKgz2__PX-gmVuVq7yt9Pc1G3TlOYH "Julia 1.7.3+ – Attempt This Online")
# PowerShell, ~~52~~ 51 bytes
```
'x'*"$args"-match'^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$'
```
[Try it online!](https://tio.run/##RY5dCoMwEISvEmSpiSEl9TUED9IfCBJrIN2IRpRKzm5jofRhh/2WmWGHsNhx6q33O3R628u1rAow43MqxMvEti8flDb6zJusdF15w251BVmOYdUK5Z4UvLVUXRitaXsKnjgk4HCYI9vAaPBiGryLhSiU6yiYcxtmjMJHUh8GrsFc5T3lAgqorw7j/XtRgMLbH18O5pxtueMEHQH8rvBm2zK6aEUfppjyKxf1ZyIwoF28Q5sDKaVdilrKDw "PowerShell – Try It Online")
*-1 bytes thanks to Julian*
# [Python](https://docs.python.org/), ~~70~~ 69 bytes
```
lambda n:re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*n);import re
```
[Try it online!](https://tio.run/##LYzLCoMwEEX3fsVQhCS@iC6V4IdUF7ZqDcRRkiyiP2@T2sVczoUzdz/ssmF1yXXftAVzmAZOwRuYRXepYX2NA2Ctp2Id7HuhmlDaiiJtfVLn0pZ1VRL7CMcSF5OMOJIga/6DerrmTYMCiWG8MHaUWEeghCrMrqSlj/zBIggSBkkP@JmoREvVk/csuykve5aWzD@CnGGm@MPAZw279lKopyibu4Gx2kvZxfOK8y8 "Python 2 – Try It Online")
# [Python](https://docs.python.org/), 73 bytes
```
lambda n:__import__('re').match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*n)
```
[Try it online!](https://tio.run/##JY1LDoMwDET3nMKqkGLzU2AJQhykrRD9UCIFg5IsKJenSVl45LGeZ9avmxauDjWvi3Fgv7aBvZXRuBjQoDhcCuteiusIdKsLu2rl8JJfKIIAcYDMwJ83Knaor/JO2bnl5Z3SkvwjqBHw0MP8eA3Add@fdX2PwrwFFfPgnhMagdi1Rdp5xW1LO7pVSewlDCVbLDKxiYTpACDkf3BI3mtYja8Mdm/L5nRgnfFQdsi8kvIH "Python 2 – Try It Online")
(If it must be a pure lambda.)
# JavaScript (ES6), ~~58~~ 54 bytes
```
n=>/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/.test(Array(n+1))
```
[Try it online!](https://tio.run/##TY3NbsIwEIRfhSIEu0QxCb1hnKhHLrxAfySLbJItrmPZBoSAZ0/NoVIP883hk2a@9VmHg2cX8@C4If8z2CNdx1aNVlWrL4BaiaxOBJEaP9bLWcIzuBSzlYgUIrx5r69gsxJxDKqQl54NARjlSTeGLQHii7InY/DWKSOCMxxhkS9QcgtgVScM2S72WK3vdw57vQdWTvtAOxuhey8@Ef8E/Re2Kuty89QYez9cpjt71oabide2o81kmhnZDh4kbxVJzjJMhy0w4i3M585zWkEZVCndKYbok5GPx1jkr0XxCw "JavaScript (SpiderMonkey) – Try It Online")
*-4 bytes thanks to a technique used by [RK.](https://codegolf.stackexchange.com/a/58174/17216) and [CubeyTheCube](https://codegolf.stackexchange.com/a/220521/17216)*
# [Perl](https://www.perl.org/), ~~49~~ 47 bytes
*-2 bytes [thanks](https://codegolf.stackexchange.com/questions/85/fibonacci-function-or-sequence?page=1&tab=modifieddesc#comment546580_223243) to dingledooper*
```
sub{1x pop~~/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/}
```
[Try it online!](https://tio.run/##PYvLDsIgFER/5S5uKrTaV@JGRH/EmFRD9SZCCWBsY@qvI3XhYubMWYxV7rGNT6/AB0fXIGDZr84ZMjcvwAx/gZUarXKklQndY7fzunNBd@F6XwnQE2Avo39e3s0IdrCfT3Vm7CjL4pialYn81OaYagnPS6zmKPrBMT2hl/U6gWQtkPayrRcWBX8D9Qz7zYEh8WTos8w6MgErkU6NgJ8BEswwxy8 "Perl 5 – Try It Online")
This beats a port of [Ton Hospel's **41 byte** answer](https://codegolf.stackexchange.com/a/93003/17216) (**57 bytes**):
```
sub{my$x=1x pop;$x=$`while$x=~/\B(?!(11+)\1+$|$)|11$/;$x}
```
[Try it online!](https://tio.run/##HYtbCoMwFAW3cgsXSUiLptCvNC10HX70gWkvaAyJoqJ262ns18zAOa7y9Sn2oYLQeXp1CjYfHt6SfQcFzQRodAz9c24mHLUcwbVOJcP78KG6SvbNyxu77piUgpdS4IJ8kRLztFqjMq1n6Rp0sU8gXSiksz4WG4XgM5BhaA4XhsRTYcgy58l22z9oqeBfgAQrrPEH "Perl 5 – Try It Online")
Even if it's allowed to modified the global variable `$_` (**51 bytes**):
```
sub{$_=1x pop;$_=$`while/\B(?!(11+)\1+$|$)|11$/;$_}
```
[Try it online!](https://tio.run/##HYvbCsIwEAV/ZYWlJERpV/ApRsHvELzR6EIvIWmppe23x9SnmYFzXOmrQ@xDCaHz/Oo0rD48fMPNO2ioR0BrYuifE94MfcG1TifD@/DhqsyvF3HeCCIlr6RwRjkTYZ4WS9S29aIeMZhim8Cm0MhHsy9WKiUnYCvQ7k4CWabCkGXOc9Ot/2BIw78AGRZY4g8 "Perl 5 – Try It Online")
# [Ruby](https://www.ruby-lang.org/), ~~48~~ 45 bytes
```
->n{?x*n=~/^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$/}
```
[Try it online!](https://tio.run/##PY7NDoIwEITvPsVqSGwhLYUrVh4E0MTIT5NmMVAixuir49Yoh510p/NNdpguj6XRizjiM59D1O/4xFiuZZSTsnmOcl6mYUDih4dzEL8Wo1UG987YGqxuazduAEwDthBJpfWuxF1GH7ZQUoq0yqDGKyXIkePNGsf2Ys9/iLQ1tq5j/JASUxBP2Io0/QAIBsGb0vVnwxLFpfTBdaXct6spkEB6mK2/7za58dtDnk5oHww6wH@1V5pFiVSpDw "Ruby – Try It Online")
*-2 bytes by switching the truthy value from "string of `x` characters whose length is the input number" to "the integer value `0`", while keeping the same falsey value of `nil`*
*-1 byte by using `?x` instead of `"x"`*
# [PHP](https://php.net/), ~~89~~ ~~75~~ 71 bytes
```
fn($n)=>preg_match('/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/',str_pad('',$n))
```
[Try it online!](https://tio.run/##LY89b4MwEIb3/AoLncRd@IhhNS5Lly5d2i1Jo5TYAck1FhCpUpTfTs9RB7/n@3j8nkMf1qYNfRBg9Wo9gif9EiZzPf2cl67HdPeF2Ooya1mx5EiHegss8dC2hF2az8t0CucLpmnOPK1qY8cJYdBSgdP2apYZPz5f395J0V0MFsHtmXGG/RwV1VHr5OAT4uH59s0dLucyLyqKvPkNbrwYTIok53HFfDfe/BLZpmZozw@wyqPaCPF09v85@EY/@3zLMmJrgWDjJ0nc4x4Dma4fo7kSvG@lRMwFePV4rLKopfwD "PHP – Try It Online")
*-4 bytes by switching from `x` to as the repeated character*
# [R](https://www.r-project.org/), ~~73~~ ~~72~~ ~~68~~ 63 bytes
```
\(n)grepl('^((?=.+?(?=(..+?)\\2*$)\\2$)\\2)*.$',strrep(1,n),,1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LU5BasMwELz3FYsJeDeRje1TqRD-QO492C6YRnIFQjVa5ZKQl_SSFvKEPqa_qdT0MrvD7Mzsx2e4fhl1O0ZTPf70I3pagl4dli-Ivap3fUKs06Rx7LabjH9A23pTCo4hXWMrPAnR0n_MN6tGwkkZ6zQWHA_WFyTBvAd0YD3wcV2DZn6eg7d-YQx6Puyt14wnIjo_ADhQkMJ5dTaiE1BUBQ1DO00SrAF02i_xDR0p1RK4oZuUS2oy5hKbSzJ_ygolBxq0RHBOG9PrHLEcfUmSVSshU0uXy_35662puqa5k18) / [Try it online!](https://tio.run/##PU3LboMwELznK7YoErupQcARauUHeu8BqJQmNrFiOcjrqioR307tSu1ldkfz8pt@KbbZf/u21Th5NVvM3xGPsnw@RsQyXhqG5rBP@At0KPe54OCjG2vhSIiaaGNZdbBIbazCjMPFuIx2X9dEa3rsACxI4M959or57eSdcROjV6fLq3GKcRHgZCzqwGh8sspN4YqWCB5ne2eFS1Q@ov22/nUFz7M1Aa2ArMio7@txTGnA/7SMjWD7ZpQ2qjGo7x4NGAeJt0mhtKfRpKX4MZ1PAfPB5dSxrDtI1NC6blXRVNUP "R – Try It Online")
```
\(n)grepl('^((?=.+?(?!(..+)\\2+$)(..+))\\3)*.$',strrep(1,n),,1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY5BasMwEEX3PcXUBDwTy8ZyNyVG-ALdd2G7YBrJFQjVaJRNQk7STVrIEXqY3qZy0937_Pn_z8dnuHwZdT1EUz7-dAN6moNeHOYviJ2qig67e6yqgoahKTb0h4kfaFttcsExpGuUwpMQkv5rvlnVLRyVsU5jxnFvfUYtmPeADqwHPixL0MzPU_DWz4xBT_sn6zXjkYhOdwAOFKRyXpyN6ARkZUZ9L8exBWsAnfZzfENHSkkC1zejcslNwXXEriOr3q0OpQQatERwSsT0OkXMB59Ty0q2sEpL5_Pt-cu1Lpu6volf) / [Try it online!](https://tio.run/##PY3NaoQwFIX38xR3ZMB7axR1dtrgC3TfhVqwM4kTGjKSpJQ6@Ow2KbS783H@7C6f832x37ZpJM5WLBrTN8SOF1mH3RGLIqNhqLMT/cqgz/RUnFLmvA1prJghxiqi3fGyhZVLpQUmzl@VSejwdYtY0eMAoIGD@1wWK5x7naxRZnZoxXR9UUY4XBkYHoZaUBKPWpjZ31ATweOi707gGpz3EP/Y/ra8dYtWHjWDJE@o76txjG3A/zYPi6D7euQ6uKEo7xYVKAORm@hQ/JOo4lNQji6Tx3QwKbWOVy1EVLRte5nXZfkD "R – Try It Online")
*-1 byte [thanks to Giuseppe](https://codegolf.stackexchange.com/questions/248690/is-it-a-valid-list/248747#comment555846_248747)*
*-4 bytes by using `grepl()` instead of `sum(grep())` or `any(grep())`*
*-5 bytes by using a new anonymous function syntax introduced in R v4.1.0*
Since TIO uses R v3.5.2, the TIO links have the old **68 byte** versions of the function.
# Java 8, ~~92~~ ~~89~~ ~~88~~ 71 bytes
```
n->new String(new char[n]).matches("((?=.+?(?=(..+?)\\2*$)\\2$)\\2)*.")
```
[Try it online!](https://tio.run/##bVBNb9swDL33VxBGh1D5EJwcp7jBehgwYNslx8QH1ZVjpQptSHLzMey3Z7SdtodOB1LUe3zi416/6tn@@eVqD03tI@y5lm20TpYtFdHWJMcKPoFjdVc4HQL80pbgzx1A0z45W0CIOnJ6re0zHBjDdfSWdpsctN8F0VMBvt@0lz8omp3x08e6dkbTA5SQXWn2QOYIQyd216LSfkO5kAcdi8oETBBXmZysOKLkLLbbxfi@i30QY5mIq@K/ngZhuGSldsEoWBeayHiw1LQRMuh/Gt5wfQ7RHKQloeBYWWcAe5qsdPhtThHFm4FhNnCWDGsMJGLGT35A7n537RjuWDI0zkZMZgmjliJQysjNvmy0D4YLdJs0F1Og@X9B6QztYrVcwAo6JnzlNM9ZsV9Qfrr5GdY1zxV8816fgyytc3iajk4jofr5y9p33niMjFIFtMxozmkyYYO2BCylbhp3RhKCa7yI22pq9nn0NhocbYnFLln0bbfVD7hh57HE5EtI2IhQf7tzTWeLNP0H "Java (JDK) – Try It Online")
```
n->new String(new char[n]).matches("((?=.+?(?!(..+)\\2+$)(..+))\\3)*.")
```
[Try it online!](https://tio.run/##bVBNk9MwDL3vrxAZmMpN60nLDTfbgQMzzACXHtscvFmncXGVjO1sPxh@e1dJChzAF0l@T096OugXPT88/7jZY9v4CAeuZRetk1VHZbQNyamCf8CpeiidDgG@aUvw8wGg7Z6cLSFEHTm8NPYZjozhJnpL@20B2u@DGKgAn@/aqy8Uzd742aemcUbTI1SQ32j@SOYEYyf2aVlrv6VCyKOOZW0CJojrXKZrXL9BKVOx2y3Tt2JIOX8vpjIRN8WznkZhuOaVdsEo2JSayHiw1HYRchgmjX@4uYRojtKSUHCqrTOAA03WOnw354jit4FxN3CWDGuMJGLGV/5A7v7j2jHcs2RonY2YzBNGLUWgjJG7fdlqHwwX6LZZIWZAi/@C0hnax3q1hDX0TPjAYVGw4nCg4nz3M55rUSj46L2@BFlZ5/A8m5wnQg37V43vvfEaOWUKaJXTgkOaskFbAVZSt627IAnBNV7F/TQN@zx5Gw1OdsRi1zz6rr/qX7hl57HC5F1I2IhQv/p3y@bLLHsF "Java (JDK) – Try It Online")
*-17 bytes by just matching the regex straight against a string of NUL characters instead of replacing the NULs with `x`*
# Java 11, 61 bytes
```
n->"x".repeat(n).matches("((?=.+?(?=(xx+?)\\2*$)\\2$)\\2)*x")
```
[Try it online!](https://tio.run/##bVDLbtswELznKxZCA5N@ELKPpRUjORQokPTio60Do1AWHXolkKtYdtFvd1ey0x5aHnYxnOFwZ/fmw8z2b@8Xd2jqQLBnrFpyXpUtFuRqVGMN/5BjfVd4EyO8GIfw8w6gaV@9KyCSIW4ftXuDA3NiTcHhbpODCbsoBynAt5v38juS3dkwfaprbw0@QAnZBWcPSZeoYBtrSKBUB0NFZaNIhFhlarLiKhR3ud0uxl/6OhQ5Vom8aP7h9WoH56w0PloN68Ig2gAOm5YgA7THzzuxPkWyB@VQajhWzlsQg0xVJv6wHQn5OfY1C3iHlj2uImTFM18Ifv0nq2e6V6nYeEcimSXMOiTAlJlbaNWYEC0D4TdpLqeA8/@SylvcUbVcwAp6JXzlNs/ZsahM2OTdLc@AcJ5reAzBnKIqnfeim466kdTD/GUd@mw8RoapBlxmOOc2mXBAV4IolWkaf@KVS8biLG@rqTnnMTiyYrRFNjtnFNp@q3/phpNTKZL7mHAQqX/155LOFmn6Gw "Java (JDK) – Try It Online")
*-10 bytes relative to Java <11, [thanks to Kevin Cruijssen](https://codegolf.stackexchange.com/questions/138011/is-it-a-semiprime?answertab=votes#comment547728_138086)*
### \$\large\textit{Full programs}\$
# [Python 2](https://docs.python.org/2/), 69 bytes
```
import re
re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*input()).re
```
Outputs [via its exit code](https://codegolf.meta.stackexchange.com/a/5330/53748), value `0` for truthy (by exiting normally), and `1` for falsey (by triggering an `AttributeError`).
[Try it online!](https://tio.run/##K6gsycjPM/r/PzO3IL@oRKEolasoVS83sSQ5Q6NIXUPD3lZP2x5IalRUaNtrxhhpqQAJENbUqlBR11GvUNfKzCsoLdHQ1NQrSv3/39AYAA "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), ~~71~~ 70 bytes
```
import re
re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*xx$','x'*input()).re
```
Outputs [via its exit code](https://codegolf.meta.stackexchange.com/a/5330/53748), value `1` for truthy and `0` for falsey, using the truth-inverted regex.
[Try it online!](https://tio.run/##K6gsycjPM/r/PzO3IL@oRKEolasoVS83sSQ5Q6NIXUPD3lZP2x5IalRUaNtrxhhpqQAJENbUqqhQUddRr1DXyswrKC3R0NTUK0r9/9/QAAA "Python 2 – Try It Online")
Alternative method using the uninverted regex, outputting exit code `1` for truthy (by triggering a `NameError`), and `0` for falsey (by exiting normally), at **71 bytes**:
```
import re
if re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*input()):z
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PzO3IL@oRKEolSszDUjq5SaWJGdoFKlraNjb6mnbA0mNigpte80YIy0VIAHCmloVKuo66hXqWpl5BaUlGpqaVlX//xsaAAA "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), ~~79~~ 74 bytes
```
import re
print re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*input())>0
```
Outputs `True` or `False` via stdout.
[Try it online!](https://tio.run/##K6gsycjPM/r/PzO3IL@oRKEolaugKDMPxNDLTSxJztAoUtfQsLfV07YHkhoVFdr2mjFGWipAAoQ1tSpU1HXUK9S1MvMKSks0NDXtDP7/NzQAAA "Python 2 – Try It Online")
# [Python 3](https://docs.python.org/3/), ~~84~~ 83 bytes
```
import re
print(not re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*xx$','x'*int(input())))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEolaugKDOvRCMvH8TRy00sSc7QKFLX0LC31dO2B5IaFRXa9poxRloqQAKENbUqKlTUddQr1LVAGjPzCkpLNDSB4P9/QwMA "Python 3 – Try It Online")
The above uses the truth-inverted regex. Without it is **84 bytes**:
```
import re
print(bool(re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*int(input()))))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEolaugKDOvRCMpPz9HoyhVLzexJDlDo0hdQ8PeVk/bHkhqVFRo22vGGGmpAAkQ1tSqUFHXUa9Q1wJpzMwrKC3R0ASB//8NDQA "Python 3 – Try It Online")
# [PHP](https://php.net/) `-F`, 70 bytes
```
<?=preg_match('/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/',str_pad('',$argn));
```
[Try it online!](https://tio.run/##VVDLbsIwEDyXr5i6Lk5CQ1I4OoEbUk8ceoQWhdghVoMdmUitaPj21OEhVEs7qx1Ls7OzzQ5lZ2UmEFoBxmCThG2uj3XJPK2t3G32WZOXHos@PW@ejkdzh97YdX89CaiDvvxgTCP2cmjsps6Ex9gLzexO@z7vboIDmZcGoQahlrB@IGtNOMMMuRGSQ/7IHNPZ8JVj/1WowmDJ8V2qSuJt8Z7i6hRV264uOhXBBxcGhbHwPOiU0N/qmYQkOBEOnZznp8ARJwJHjEZwjoQZPJy9UM3/K2dIsETbOiuq4VAFVqCZ2yURu01NKfWFfER4BD3euF5tNpzyQnEcU@f/fqom/QcKNRBGuyN7RIvI1E1Ul3W0VbrvCBfnFFwYy3sSYReHkzj@Aw "Bash – Try It Online")
# [Perl](https://www.perl.org/) `-p`, ~~45~~ 43 bytes
*-2 bytes [thanks](https://codegolf.stackexchange.com/questions/85/fibonacci-function-or-sequence?page=1&tab=modifieddesc#comment546580_223243) to dingledooper*
```
$_=1x$_~~/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/
```
[Try it online!](https://tio.run/##LY3RbsIgGIVfhZg/FuxaqYk3MqbvMbemUzpJyg8Bmmmb@ujraLKLc76T7@Y45bv93AdF9iWvuCBoyU/jUeN3IJm6O@W1URib7nAIpvHRNPFyywQxD2hl6L9GqKWzTsyJ1R3q53P7SelRlvkxNS0T2Xm3gVRL2KaE7SygngQJsYmKwCAuN2ucMI9TJ4PrdKRZkb1AzQRprafpCeWpe@cfAvB1WUW1zDxno24ptMUbBWRshGG9dl5jXJ1xJWCQlSBQ/zsCOE2kx6tqk5x5seP817qoLYa5cH8 "Perl 5 – Try It Online")
Beaten by [Ton Hospel's **41 byte** answer](https://codegolf.stackexchange.com/a/93003/17216) which mixes regex and code: [Try it online!](https://tio.run/##LY3RaoMwGEZfJSs/NcG6JoPeNLMre405nO3iDCR/QhJpq/XV5yzs6hwOH3xeBbOb@6jI7pkLLgk6cmkCavyJJFNXr4K2ClNj9vtom5Bsk85dJom9QVvG/jRCXXrn5bxQXKGWC@Hr0mmjttU7fXuiQuSsEjncgd2FgO28TCZJYmqSIjDIc@esl/Z2NGX0RieaFdkGaiZJ6wJdfrA8mg/@KQFfH1aIh@Y5G3VLoS0OFJCxEYb12geNaVXhSsJQCkmg/m8EcJpIj9@qXeLMixfOf51P2mGcC/8H "Perl 5 – Try It Online")
# [Perl](https://www.perl.org/), ~~46~~ 44 bytes
```
say 1x<>~~/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/
```
[Try it online!](https://tio.run/##FY7ZSsNQFADf5ysiFJpUTO9ZbhZc@gX@gQhBrrTQjSRiReynG@PDzLzOOfX7OH0MKUuXc@p3h3Qcu322HA5dPx668W27vP/c7vYpv0mn97wovqeh@8rk8vB0va5f83zzWN5uZufl3OJFV4tZ/xSrcrGefibDqWiQgAiiiCMVUiMNGlBFDXW0Qmu0xQKmmGMRq7EGD7jgijte4TXeEAORmhYxJCItKmhEG0wwwyqsxeeBiLe/p/O4Ox2H6e45lkHCHw "Perl 5 – Try It Online")
Now beats a port of Ton Hospel's answer (**45 bytes**):
```
$_=1x<>;$_=$`while/\B(?!(11+)\1+$|$)|11$/;say
```
[Try it online!](https://tio.run/##Hc7LSgNBEEbh/XmLQC9mCJr@q6rnQryAe98goC5GDAQnJAEV46vbBldn8W3OfjrsSv142@6mZjHNr03bftf0dKvPm7v1pen531abh@Z@0UjLdqNlOqf2LKXV@vjyVX@qE3QMKCMhQ4E61KMBy5hhjgXWYT024hk3PPCC9/hAZEKEEUF0RE8MlEyhZ0SOChoxYQUbcOGOd/hIXAYKMf7O@9N2fj/Wq8dynZX/AA "Perl 5 – Try It Online")
[Answer]
# Pyth, ~~18~~ ~~15~~ 14 bytes
*Thanks to @Maltysen for -1 byte*
```
#=-QefP_TUQ)q1
```
A program that takes input on STDIN and prints `True` or `False` as appropriate.
[Try it online](https://pyth.herokuapp.com/?code=%23%3D-QefP_TUQ%29q1&debug=0)
**How it works**
```
#=-QefP_TUQ)q1 Program. Input: Q
# ) Loop until error statement (which occurs when Q<3):
UQ Yield [0, 1, 2, 3, ..., Q-1]
fP_T Filter that by primality
e Yield the last element of that
=-Q Q = Q - that
q1 Q is 1 (implicit variable fill)
Implicitly print
```
**Old version with reduce, 18 bytes**
```
qu-G*<HGH_fP_TSQQ1
```
[Try it online](https://pyth.herokuapp.com/?code=qu-G%2a%3CHGH_fP_TSQQ1&debug=0)
**How it works**
```
qu-G*<HGH_fP_TSQQ1 Program. Input: Q
SQ Yield [1, 2, 3, ..., Q]
fP_T Filter that by primality
_ Reverse it
u Reduce it:
Q with base case Q and
function G, H ->
<HG H<G
* H *H (yields H if H<G, else 0)
-G Subtract that from G
q 1 The result of that is 1
Implicitly print
```
[Answer]
# JavaScript (ES6), ~~64~~ 63 bytes
*Saved 1 byte thanks to @Neil*
```
g=(x,n=x-1)=>n<2?x:x%n?g(x,n-1):g(x-1)
f=x=>x<3?x%2:f(x-g(x-1))
```
I wrote this in 2 minutes... *and it worked perfectly the first time.* First user to find the inevitable bug wins....
### Try it out
```
g=(x,n=x-1)=>n<2?x:x%n?g(x,n-1):g(x-1)
f=x=>x<3?x%2:f(x-g(x-1))
```
```
<input type="number" value=3 min=3 onchange="A.innerHTML=f(this.value)"><br>
<p id=A>1</p>
```
### How it works
First we define **g(x)** as the function that finds the first prime number **p <= x**. This is done using the following process:
1. Start with **n = x-1**.
2. If **n < 2**, **x** is prime; return **x**.
3. If **x** is divisible by **n**, decrement **x** and go to step 1.
4. Otherwise, decrement **n** and go to step 2.
The solution to this challenge, **f(x)**, is now fairly straightforward:
1. If **x < 3**, return **x = 1**.
2. Otherwise, subtract **g(x-1)** and try again.
[Answer]
# Julia (0.4), 32 bytes
(Update (as of 1.4): This is rather out-of-date, now - `primes` is no longer in Base, and `?:` needs spaces around the `?` and the `:`)
While it's not going to be the shortest solution among the languages, this might be the shortest of the human-readable ones...
```
!n=n>2?!(n-primes(n-1)[end]):n<2
```
[Try it online!](https://tio.run/##TY4xDoMwDEX3nsJhSqQiQUZC2rlnQAxIhJLKdVESFi5PHejQwda3/vezXyv6Yd8FWbrpu5BULsG/XWRRq87R2KuGWr1vdhowOgPTJwCCJwhuGNETR9UFAG1c0CeJ16IslAE/ATp6plmiarWBZY2zYBe7umebwbyUWZRZyxCikw9Kp9/8z7rPfMhEQYc69Gb4UUpIUhmmGdhsCqv7BQ5P0rl5Hsuda69LXVVf "Julia 0.4 – Try It Online")
Or, to put it in slightly clearer terms
```
function !(n)
if n>2
m=primes(n-1)[end] # Gets largest prime less than n
return !(n-m) # Recurses
else
return n<2 # Gives true if n is 1 and false if n is 2
end
end
```
Called with, for example, `!37`.
[Answer]
## Pyke, ~~15~~ 11 bytes
```
WDU#_P)e-Dt
```
[Try it here!](http://pyke.catbus.co.uk/?code=WDU%23_P%29e-Dt&input=49)
```
- stack = input
W - while continue:
U#_P) - filter(is_prime, range(stack))
e - ^[-1]
D - - stack-^
Dt - continue = ^ != 1
```
Returns `1` if true and raises an exception if false
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~11~~ 9 bytes
```
εωλ-→fṗŀ¹
```
[Try it online!](https://tio.run/##Dc67CcJQGIDRhT7h/o/7miWklYCkEnu1EGxtnEQh2AVs4wxmkatngjMc9rs2P8dxPZ/a8vhcl9dmvdy23@n@Ps5Ta63rDCdRkIAIoogjCclIQQOqqKGOJjSjFQuYYo5FLGMFD7jgijue8IwXYujpIpmKGBKRigoa0YIJZljCKv4vRLz2/Q8 "Husk – Try It Online")
-2 bytes from Leo.
None of the testcases reach zero because the max number we can subtract from `n` can only be `n-1`. Hence, we can check insignificance instead of equality with 1.
## Explanation
```
εωλ-→fṗŀ¹
ωλ iterate on the input till fixpoint
ŀ¹ range 0..n-1
fṗ filter out nonprimes
→ last element
- subtract from n
ε is fixed point insignificant? (<= 1?)
```
[Answer]
# Python3, 102 92 90 89 88 bytes
```
f=lambda n:n<2if n<3else f(n-[x for x in range(2,n)if all(x%y for y in range(2,x))][-1])
```
Golfing suggestions welcome! I see that `gmpy` contains a function `next_prime`, but I can't test it yet :(
-2 bytes, thanks to [@JonathanAllan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!
-1 byte, thanks to [@Aaron](https://codegolf.stackexchange.com/users/42652/aaron)!
## Testcases
```
f=lambda n:n<2if n<3else f(n-[x for x in range(2,n)if all(x%y for y in range(2,x))][-1])
s="3 4 6 8 10 11 12 14 16 17 18 20 22"
h="5 7 9 13 15 19 21 25 28 31 33 36 39"
for j in s.split(" "):print(f(int(j)))
for j in h.split(" "):print(f(int(j)))
```
Output is 13 truthy values and 13 falsey values.
`s` contains the truthy cases and `h` the falseys.
[Answer]
# [Haskell](https://www.haskell.org/), ~~65~~ 63 bytes
```
f n|n>2=f$n-last[p|p<-[2..n-1],all((>0).mod p)[2..p-1]]|1>0=n<2
```
[Try it online!](https://tio.run/##Pc2xCsMgFIXhV7lDB4UoJl2jU8e@QcggNLa3NVfR26GQd7cpgW6HjwP/w9fXEmPDNafCcPHs9RUrg8i@MDImkqAUPN@7hVQgFyRGurcAtJEbbDiRir7ylLc8qmnQmlQ/dz5GIZyRek03yPLnefd5652xNA5t9Ug2Liw@S@0oSfsPQpjOWvfGzEhHD/aPc8ek1L4 "Haskell – Try It Online")
[Answer]
## Mathematica, 32 bytes
```
2>(#//.x_/;x>2:>x+NextPrime@-x)&
```
This is an unnamed function which takes an integer and returns a boolean.
### Explanation
There's a lot of syntax and funny reading order here, so...
```
# This is simply the argument of the function.
//. This is the 'ReplaceRepeated' operator, which applies
a substitution until the its left-hand argument stops
changing.
x_/;x>2 The substitution pattern. Matches any expression x as
long as that expression is greater than 2.
:> Replace that with...
NextPrime@-x Mathematica has a NextPrime built-in but no
PreviousPrime built-in. Conveniently, NextPrime
works with negative inputs and then gives you the
next "negative prime" which is basically a
PreviousPrime function (just with an added minus sign).
x+ This gets added to x, which subtracts the previous
prime from it.
2>( ) Finally, we check whether the result is less than 2.
```
[Answer]
# Python, with sympy, 60 bytes
```
import sympy
f=lambda n:n>2and f(n-sympy.prevprime(n))or n<2
```
---
My previous method was 83 bytes without sympy using recursion, but I took truthy/falsey to mean distinguishable and consistent, but I have been informed that's an incorrect interpretation. I can't seem to salvage it due to the tail, but I'll leave it here in case someone knows how to do so:
```
f=lambda n,p=0:n>2and(any(p%x==0for x in range(2,p))and f(n,p-1)or f(n-p,n+~p))or n
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 27 bytes
```
{⍵<3:⍵=1⋄∇⍵-⊃⌽(⊢~∘.×⍨)2↓⍳⍵}
⍵<3 ⍝ Termination condition
:⍵=1 ⍝ return value
⋄ ⍝ Separator
∇ ⍝ Recursive call
⍵-⊃⌽ ⍝ Subtract largest prime
(⊢~∘.×⍨) ⍝ Calculate primes less than argument
2↓⍳⍵ ⍝ Range 2–(N-1)
```
[Try it online!](https://tio.run/##HY89DkFREIV7q1BSEHdm/DxhASprkMjTSGhFaAiCJxIRapVelCo7mY0891PMyZ0535zJHUzHleFsMJ6Mcj9de33fnGt5GnXu2buj7ajd4Ie177bxWfH9yo@fku8fS9/dq9@bZ8@y@Obi2Sv6izxPi1pIixarEasVK9SQgAiCFzBDEwEREMEVtgVEQAREkigKoiCKq3UEVwkwXOOGgRiIEWAgBlIHYYsJiYFTgUmgFbaFVsCVVkGUHAWx/9dALPkB "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes
```
1|-↙Xṗ∧X≜!↰
```
[Try it online!](https://tio.run/##FY47CgJBEESvMm48itPd/hK9hiAGKn4CQfCDiJooLG5mJoK5qYmB3mbnIuszKKiu19X0cDkYzXbzxVSK/TZx5bZLtp19TF/xdI6XZ7JebsaV5PC3k8F8hT/m3@yYv69FOJRjeu/mnxu0G7NHiVpR9NQ7867uXdO7UEUBCSINxKGBYAITcqEgMIEJTFreKUxhSq41RK50jNy4ZzCDGR2DGawGY5WJA4GjgSnghYLghSXFK0wpKsz@38Ks1f8B "Brachylog – Try It Online")
```
1 The input is 1,
| or:
X≜ X is the integer with the least absolute value such that
-↙X it is positive, and if it is subtracted from the input
ṗ∧ the result is prime.
! Consider no other value of X.
↰ Call this predicate again with X as the input.
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 7 bytes
```
‡∆ṗεẊ1=
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%80%A1%E2%88%86%E1%B9%97%CE%B5%E1%BA%8A1%3D&inputs=48&header=&footer=)
Very nice and neat answer (flagless too!)
## Explained
```
‡∆ṗεẊ1=
‡∆ṗε # lambda x: abs(x - prev_prime(x))
Ẋ # repeat that on the input until it doesn't change
1= # does that equal 1?
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 13 bytes
```
`tqZq0)-t2>}o
```
[Try it online!](http://matl.tryitonline.net/#code=YHRxWnEwKS10Mj59bw&input=NTA) Or [verify all test cases at once](http://matl.tryitonline.net/#code=YGkiQApgdHFacTApLXQyPn1vCl1ddiFEVA&input=WzMgNCA2IDggMTAgMTEgMTIgMTQgMTYgMTcgMTggMjAgMjIgMjMgMjQgMjYgMjcgMjkgMzAgMzIgMzQgMzUgMzcgMzggNDAgNDEgNDIgNDQgNDYgNDcgNDggNTBdCls1IDcgOSAxMyAxNSAxOSAyMSAyNSAyOCAzMSAzMyAzNiAzOSA0MyA0NSA0OV0).
### Explanation
```
` % Do...while
t % Duplicate. Takes input implicitly in the first iteration
qZq % All primes less than that
0) % Get last one
- % Subtract (this result will be used in the next iteration, if any)
t % Duplicate
2> % Does it exceed 2? If so: next iteration. Else: execute the "finally"
% block and exit do...while loop
} % Finally
o % Parity. Transforms 2 into 0 and 1 into 1
% End do...while implicitly
% Display implicitly
```
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), ~~21~~ 16 bytes
*Thanks to Dennis for saving 4 bytes.*
```
ri{_1|{mp},W=-}h
```
[Try it online!](http://cjam.tryitonline.net/#code=cml7XzF8e21wfSxXPS19aA&input=OQ)
### Explanation
```
ri e# Read input and convert to integer N.
{ e# Run this block as long as N is positive (or until the program aborts
e# with an error)...
_1| e# Duplicate and OR 1. This rounds up to an odd number. For N > 2, this
e# will never affect the greatest prime less than N.
{mp}, e# Get all primes from 0 to (N|1)-1.
e# For N > 2, this will contain all primes less than N.
e# For N = 2, this will contain only 2.
e# For N = 1, this will be empty.
W= e# Select the last element (largest prime up to (N|1)-1).
e# For N = 1, this will result in an error and terminate the program, which
e# still prints the stack contents though (which are 1, the desired output).
- e# Subtract from N. Note that this gives us 0 for N = 2, which terminates the
e# loop.
}h
```
[Answer]
# Perl, 42 bytes
Includes +1 for `-p`
Run with input on STDIN
`reach1.pl`:
```
#!/usr/bin/perl -p
$_=1x$_;$_=$`while/\B(?!(11+)\1+$|$)|11$/
```
Uses the classic primality regex
[Answer]
## .NET Regex, 38 bytes
Just to show that it can be checked in a single regex.
```
^(?>(?<=(.*))..+(?<!^\1\2+(.+.)|$))+.$
```
Input is assumed to be in unary.
### Explanation
It simply implements the requirement to the word, repeatedly removing the biggest prime and check whether there remainder is 1.
* `(?>(?<=(.*))..+(?<!^\1\2+(.+.)|$))+`: Non-backtracking group makes sure the biggest prime we found is not overriden, and `+` simply repeat the process of matching the biggest prime.
+ `(?<=(.*))..+(?<!^\1\2+(.+.)|$)`: Match the biggest prime less than the remaining number
- `(?<=(.*))`: Record how much we have subtracted to establish an "anchor" point for assertion.
- `..+`: Look for the biggest number...
- `(?<!^\1\2+(.+.)|$)`: ... which is prime and less than the remaining number.
* `(?<!^\1\2+(.+.))`: The usual prime test routine, with `^\1` tacked in front to make sure we are checking the amount matched by `..+`
* `(?!<$)`: Assert less than the remaining number
[Answer]
# Python 2.7: ~~88~~ 87 Bytes
```
r=lambda n:n>2and r(n-[a for a in range(2,n)if all(a%b for b in range(2,a))][-1])or n<2
```
Thx @TuukkaX for -1 more byte!
[Answer]
# [Factor](https://factorcode.org/) + `math.primes`, 51 bytes
```
[ [ dup 1 - primes-upto last - dup 2 > ] loop 1 = ]
```
[Try it online!](https://tio.run/##JY@5TsNAGIT7PMX3AkH@D18gaBENDaKKUhizKBG219jrAiGe3TikGWkuaeajaVOc1teXp@fHWz7DNISOvkmnf7gZp3MfZsYppPS9kSExh68lDO2mniN3u90PhlNQIRkiiCKOFEiJVGiGKmqoowVaojWWYYo5lmMlVuEZLrjijhd4iVfkGTvIKakRQ3KkRgXN0QoTzLACq/FtQ47X/K4HDrwvI8Ke6/z9MqZI18xpky6W8sCRLsZL6p7j1hmv5966zWhjP8Y5EJr2tP4B "Factor – Try It Online")
[Answer]
# Vitsy, ~~28~~ 26 bytes
This can definitely be shortened.
```
<]xN0)l1)-1[)/3D-];(pD-1[D
```
```
< Traverse the code in this direction, rotating on the line.
For the sake of reading the code easier, I'm reversing the
code on this line. This will be the order executed.
D[1-Dp(;]-D3/)[1-)1l)0Nx]
D Duplicate the top member of the stack.
[ ] Do the stuff in brackets until break is called.
1- Subtract 1 from the top item of the stack.
D Duplicate the top member of the stack.
p( If the top member is a prime...
; break;
- Pop a, b, push a - b.
D3/)[ ] If this value is less than 3, do the bracketed code.
1- Subtract the top item of the stack by 1.
) If the top item is zero...
1 Push 1.
l) If the length of the stack is zero...
0 Push 0.
N Output the top member of the stack.
x System.exit(0);
```
[Try it online!](http://vitsy.tryitonline.net/#code=PF14TjApbDEpLTFbKS8zRC1dOyhwRC0xW0Q&input=&args=NTA)
[Answer]
# [Perl 6](http://perl6.org), ~~54 53 52~~ 51 bytes
```
{($_,{$_-($_-1...2).first: *.is-prime}...3>*)[*-1]==1}
{($_,{$_-($_-1...2).first: *.is-prime}...3>*).any==1}
{any($_,{$_-($_-1...2).first: *.is-prime}...3>*)==1}
```
```
{any($_,{$_-(^$_).grep(*.is-prime)[*-1]}...3>*)==1}
```
## Explanation:
```
# bare block lambda with implicit parameter 「$_」
# used to generate all of the rest of the elements of the sequence
{
# create an any Junction of the following list
any(
$_, # initialize sequence with the inner block's argument
# bare block lambda with implicit parameter 「$_」
{
# take this inner block's argument and subtract
$_ -
( ^$_ ) # Range up-to and excluding 「$_」
.grep(*.is-prime)\ # find the primes
[ * - 1 ] # return the last value
}
... # keep doing that until
3 > * # the result is less than 3
# test that Junction against 「1」
# ( returns an 「any」 Junction like 「any(False, False, True)」 )
) == 1
}
```
## Example:
```
# show what is returned and if it is truthy
sub show ($_) {
# 「.&{…}」 uses the block as a method and implicitly against 「$_」
my $value = .&{any($_,{$_-(^$_).grep(*.is-prime)[*-1]}...3>*)==1}
say join "\t", $_, ?$value, $value.gist;
}
show 3; # 3 True any(False, True)
show 4; # 4 True any(False, True)
show 5; # 5 False any(False, False)
show 10; # 10 True any(False, False, True)
show 28; # 28 False any(False, False, False)
show 49; # 49 False any(False, False)
show 50; # 50 True any(False, False, True)
```
[Answer]
# [Irregular](https://dinod123.neocities.org/irregular.html), 63 bytes
```
p~?1_$-1p:;
n=i(0)?1_$-1p:;
_~
N=n
1(?!(11+)\1+$)11+~1
^11$~0
N
```
I created this language two days ago, and the basic premises are that there are no built in loops, the only features are basic arithmetic and decision making, and program evaluation is based on regular expressions.
## Explanation
```
p~?1_$-1p:;
n=i(0)?1_$-1p:;
_~
N=n
```
This part converts the input into unary. It repeatedly subtracts 1 from the input until it equals 0, prepending `1_` each time. It then removes all of the `_`s. If I hadn't forgotten a `break` in my code it could be written as so:
```
p~?1_$-1p:;
_~
n=i(0)?1_$-1p:;
```
The next part repeatedly removes the largest prime from the input until it is equal to `1` or `11`, with `11` being replaced with `0`.
```
1(?!(11+)\1+$)11+~1
^11$~0
N
```
I used the regex from [Martin Ender's answer](https://codegolf.stackexchange.com/a/92929/41938).
[Answer]
## PowerShell v2+, 81 bytes
```
param($n)while($n-gt2){$n-=(($n-1)..2|?{'1'*$_-match'^(?!(..+)\1+$)..'})[0]}!--$n
```
Takes input `$n`. Enters a `while` loop so long as `$n` is still `3` or greater. Each iteration, subtracts a number from `$n`. The number is the results of the [regex primality test](https://codegolf.stackexchange.com/a/57636/42963) applied against a range `($n-1)..2` via the `Where-Object` (`?`) operator, then the first `[0]` of the results (since the range is decreasing, this results in the largest one being selected). After concluding the loop, `$n` is either going to be `1` or `2`, by definition, so we pre-decrement `$n` (turning it into either `0` or `1`), and take the Boolean-not `!` thereof. That's left on the pipeline and output is implicit.
### Examples
```
PS C:\Tools\Scripts\golfing> 3..20|%{"$_ --> "+(.\can-the-number-reach-one.ps1 $_)}
3 --> True
4 --> True
5 --> False
6 --> True
7 --> False
8 --> True
9 --> False
10 --> True
11 --> True
12 --> True
13 --> False
14 --> True
15 --> False
16 --> True
17 --> True
18 --> True
19 --> False
20 --> True
```
[Answer]
# [Floroid](https://github.com/TuukkaX/Floroid), 45 30 29 bytes
```
f=Bb:b<2Fb<3Gf(b-en(b-1)[-1])
```
[Answer]
# Clojure, 125 bytes
```
#(loop[x %](if(> x 2)(recur(- x(loop[y(dec x)](if(some zero?(vec(for[z(range 2 y)](mod y z))))(recur(dec y))y))))(quot 1 x)))
```
Yikes, that is one long piece of code. The most verbose language strikes again!
Ungolfed:
```
(defn subprime [n]
(loop [x n]
(if (> x 2)
(recur
(- x
(loop [y (dec x)]
(if (some zero? (vec (for [z (range 2 y)] (mod y z))))
(recur (dec y)) y))))
(quot 1 x))))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ΔD<ÅPà-
```
Outputs `2` as falsey (only `1` is truthy in 05AB1E).
[Try it online](https://tio.run/##yy9OTMpM/f//3BQXm8OtAYcX6P7/b2gEAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W@sYGpwdEdZpb2SwqO2SQpK9pX/z01xsTncGnB4ge7/Wp3/AA).
**Explanation:**
Unfortunately the *previous prime* builtin `ÅM` goes into an infinite loop for \$\leq2\$, otherwise it could have been used to save a few bytes.
```
Δ # Loop until the result no longer changes:
D # Duplicate the current value
# (which is the implicit input-integer in the first iteration)
<ÅP # Pop it, and push a list of all primes < this value:
< # Decrease the value by 1
ÅP # Pop and push a list of all primes <= this value-1
à # Pop and push the maximum prime of this list
# (or an empty string if the list is empty)
- # Subtract it from the value (where subtracting the empty string is a no-op)
# (after which the found result is output implicitly)
```
[Answer]
# Haskell, 79 bytes
Not really short but pointfree :)
```
(<2).until(<3)(until(flip(`until`(+1))2.(.)(<1).mod>>=(==))pred.pred>>=flip(-))
```
[Answer]
# Matlab, 51 bytes
```
v=@(x)x-max(primes(x-1));while(x>=3)x=v(x);end;x==1
```
This is VERY similar to the JS6 solution by [ETHProductions](https://codegolf.stackexchange.com/users/42545/ethproductions), but needs the variable to be in the workspace.
] |
[Question]
[
## Background
**HQ0-9+-INCOMPUTABLE?!** is a half-joke programming language introduced in [Internet Problem Solving Contest 2011, Problem H](https://ipsc.ksp.sk/2011/real/problems/h.html).
>
> HQ9+ is an esoteric programming language specialized for certain
> tasks. For example, printing “Hello, world!” or writing a quine (a
> program that prints itself) couldn’t be any simpler. Unfortunately,
> HQ9+ doesn’t do very well in most other situations. This is why we
> have created our own variant of the language, HQ0-9+-INCOMPUTABLE?!.
>
>
> A HQ0-9+-INCOMPUTABLE?! program is a sequence of commands, written on
> one line without any whitespace (except for the trailing newline). The
> program can store data in two memory areas: the buffer, a string of
> characters, and the accumulator, an integer variable. Initially, the
> buffer is empty and the accumulator is set to 0. The value of the
> buffer after executing all the commands becomes the program’s output.
>
>
> HQ0-9+-INCOMPUTABLE?! supports the following commands:
>
>
>
| command | description |
| --- | --- |
| `h`, `H` | appends `helloworld` to the buffer |
| `q`, `Q` | appends the program source code to the buffer (not including the trailing newline) |
| `0-9` | replaces the buffer with `n` copies of its old value – for example, `2` doubles the buffer (`aab` would become `aabaab`, etc.) |
| `+` | increments the accumulator |
| `-` | decrements the accumulator |
| `i`, `I` | increments the ASCII value of every character in the buffer |
| `n`, `N` | applies ROT13 to the letters and numbers in the buffer (for letters ROT13 preserves case; for digits we define `ROT13(d) = (d + 13) mod 10`) |
| `c`, `C` | swaps the case of every letter in the buffer; doesn’t change other characters |
| `o`, `O` | removes all characters from the buffer whose index, counted from the end, is a prime or a power of two (or both); the last character has index 1 (which is a power of 2) |
| `m`, `M` | sets the accumulator to the current buffer length |
| `p`, `P` | removes all characters from the buffer whose index is a prime or a power of two (or both); the first character has index 1 (which is a power of 2) |
| `u`, `U` | converts the buffer to uppercase |
| `t`, `T` | sorts the characters in the buffer by their ASCII values |
| `a`, `A` | replaces every character in the buffer with its ASCII value in decimal (1–3 digits) |
| `b`, `B` | replaces every character in the buffer with its ASCII value in binary (exactly eight `0`/`1` characters) |
| `l`, `L` | converts the buffer to lowercase |
| `e`, `E` | translates every character in the buffer to l33t using the following table: `ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789` `48(03=6#|JXLM~09Q257UVW%Y2 a6<d3f9hijk1m^0p9r57uvw*y2 O!ZEA$G/B9` |
| `?` | removes 47 characters from the end of the buffer (or everything if it is too short) |
| `!` | removes 47 characters from the beginning of the buffer (or everything if it is too short) |
>
> To prevent code injection vulnerabilities, **during the execution of your program the buffer must never contain non-alphanumeric characters**, i.e. characters other than A-Z, a-z, and 0-9. Should this happen, the program fails with a runtime error, and your submission will be rejected.
>
>
>
The original problem statement contains limits about the code length and buffer length, but I removed them in this challenge. This is also reflected in the interpreter link below. (If you need even larger buffer, you can change the `MAX_BUFFER` constant near the top. I doubt using a longer buffer will give reasonably short code though.)
## Task
Output the string (which is 50 digits of Pi without leading `3.`)
```
14159265358979323846264338327950288419716939937510
```
in HQ0-9+-INCOMPUTABLE?!.
An answer is scored as follows:
* Each occurrence of `Q`/`q` adds **1,000,000 points**.
* Each occurrence of `E`/`e` adds **10,000 points**.
* Each occurrence of any other valid command adds **1 point**.
Lowest score wins.
Bonus: ~~+500 bounty to the first answer that achieves the score of 9,999 points or lower. I have confirmed that this is possible.~~ *claimed by dingledooper*
[C++ interpreter](https://tio.run/##vVdtV@JGFP7Or7hiXRIRmoArRVAPWtzas9Z9qdvtupQTJxMIhCTNS@nuav@6vTNDkom8euopX0jm3ue@zTNzb4jvVwaEPDxs2y5xYpNCm4SRaXvHBWmFRF98Kq@EUWC7A3nFcAZeYEfDSU4N9aiBS3GI6uAaExr6BqGALlqFwrZJLdulcNn52D@7@rELALomfjnZ6fX5efddJisI90A8k7aSl9vYsmjQKtx6ngNjSv2bDFreb/Qkf5ZhO0q1WlVB8REbWUq//6HT77x79b7fV/eA/m1Hiq6qhQIKIfAiva6wJ6LCtwKAbSkEjo@gZJTgxQsg0MbnryUVAhrFgcvXy6AopIJPKj7qdXWndtCSoR0J@kmCdlJoZxlUk6BNCaqlUC2F6hqDzjRIq3AvUgqnhk@MkD4lKwKVWWYY2ia5cADPB2GLwxh6UzmEFIhW67XUqF47gBN8PITSSSkFR55erzdkOPHcEF@GRrALpj2wIziC4tXWp27nu1ffnzaLrUc6jjelAdMxDtpm3WoO7dFYn/yh@c3gZSP@a7r7pTaHiX1fYPZ/ULT60cH23c8fX1/@ozXf1l42rj/8tvO7wKzbLR7fDd@rXmuD6vNYbzijepsUn8d5w2nUW1j7iWG7iqgbPyxaD7PSW8mrnr5aXsCLbONCrYV/bZAPFlsql1VU5EFtcbTdEwsZeoRou2y38GEOP4IyChPELIDRwgD0xQHALsYmDMz8oy5SnxWK8YOZmQ5th@LxQMmARmw3FVWFrSPoXp3zEuJlUg3trxSr0k6vJLw5hF0u9uNw2L81yFgharoLwoQqbpXim8AbBMYE6enhprmDz25RzdzLTo5BY3752o0kqLDa425@dktwdwdLxUFJlUILKBfnFNMYc16T1FZHLBXeJ7ya7L8tl4mt4NZzDs0KPTFRNfI4@0RiPunxMIRC7A4N13QoU7MMJ6RCFE5t3BEF4Yk1zArvJyj9VDpMeSFu@KqBxl1TKQ6pg6fCCxyzOPPAlbDhjHn4mZG3S42wENeAf5HAMhU1QcWZvaQi6VmQvQk@ij6Srqxx25HcfpMsim4n@iqEYUsSPTk6tBZCu41NA2HqosiSDNBiGFbRqyIJ71cmcLoyAXDpNOnY/ykD@YJpsLvkmENHlUpeDzKP0jHOtgPwJOrt9gjvhBMo6SXWbbCPLizFgthX1@LiWThULq@mzPVzMTU5wJty9fXzOeZ9bmPHZ8/lOB2INvV8lXoW72/@H7bbFij8kj1iLpGpot2VsScciuechUrWiFedgjUn/8l0P5m/b2ftKRcdO6r7DUwiHzMuHYK2pv5b8y5owDZQ24PFTrjZnGiNi@7zsZpPqptS61fJb@gFUVK0WzpgI1uaH@tf63IoP6Jp5dH7pVzGHB4/lYzYiTKx3LqjIKZzjjNe4MiRabPRChkrzcL4lkzDyVFZdkwW1B3hbGoWFZfoPOvo4i0ty3ISLxlF5jNI5qRrd@x6U5yhvckEJbBDQOm8P7u4gB1TxaFpT3zPsCFmj0WZjD3WY9ZL42ti@1SEyTTw65NQamJcOya3KmkLi08iI5vJ7dBw3HgiMTCjqvB/hnMQDmgjSiLbwxSHlIy5iJrJoWGfQRF@NITLEs@s70Ge6/eFwpOi9mMxn@etJKtsMFalbxqNf9M8PAz/bP4L)
If you're wondering about the role of the accumulator, you're right: it still does nothing useful.
[Answer]
# HQ0-9+-INCOMPUTABLE?!, ~~7884~~ ~~5134~~ ~~4122~~ 806 points
*Thanks to @JonathanAllan for suggesting using `n` in the pool code*
*Thanks to @Neil for suggesting being looser with the pool and using strings instead of char code arrays*
```
hahaha!!4?????3?????????h?2!!????2!!!h?2!!!2!!!!!hh2????2???2hhhhh?hhh2!!!!!!!!h?2!!?????!6!!!!!!!!!!!!hhh?hhhhh?hhhh?2!!?????!!2hhhhh?3!!!!!!hhhh?2??2!hh2????2???h?2!???!2hhhh?2!!!h3??????hh?2!??!2!h?3!!!2?2!hhhh?hhh2!!!h?2!!h2??h2??h?2?!6!!!!!!!h?2!!2!?4!!!!h?2?h?2??2?!2!3!!!!!3!!!!h?5????2?h?2?2hhhhh?2!!!h2!!2??2?2!hhh?hhh2!!!hh?hhhh2????2??!2h2!!!hhhh?hhhh?2??!2!3!!!2!!3???2??2?6????????2!???!2!hhh2!!!h?3!!!!!3????h3??????2?!2h?2!!!2!!!!hh2!!!hh?2!??2hh3!!!!!!!!hh?h2??2???h?2??!2hhhh?2!??2!hh2!!!!h?hhhh?2??!2!2!!hhhh?2?4???h2???2???2!??2hh?2!!!!2!!!!!hhhh2?????2!???!2!4!!!!!2!!!3???h?2?2!!hh?2!!2??2?!2h?hhh2!!!!3??????h?2!??2hhhh?2!!!hh2!!!!2???h2???2??!2!h2!hh2!!!!2??2???2?4!!!!h2!!!h2???2????2??!2!hhhh?hhhh?2??!6!!!!!2!!h2??2?2!hh2!!!!h?2??3????2?2!2!!!!!2????2????h?2!???!3!!hhh2!!!h3?????
```
[Verify it online!](https://tio.run/##vVdtU9tGEP7uX3GCEksxdvQCpmCDx1BI6YSSl5KmIa5HSGdLxpY0klw3CfSv071XncDGZsrUjLHudp/dZ/f27lZektSHnnd3tx5G3njqY9T2stwP44OKMuPlXxOszmR5GkZDdcYdD@M0zINJSQ30sAtT0wzUUeROcJa4HkbgolWprPt4EEYYnXU/9Y/OfzpGCFkm@5RkhxcnJ8fvpcysVJh/5MU@bonB1XQwwGmrchXHY3SNcXJZYGtbOz3F4cANx3qj0TCQngA2H@j9/sduv/v@9Yd@39hE@O8w1y3DqFRAiNI4txydPHkG@l5BKBzoHjrYR1W3il68QB5qw/O3qoFSnE/TiM7XkK57dXgy4NFyjA272VKhXQX6WYF2JbS7CGoq0F0FakqoKaGWSaBcw2tVbllI2cxNPDfDT4nKQ3UeGVBbJRYKoPEAbD6NIJ6pFCQQrDq2NGrZTdSBxz1U7VQlOI8tx9lR4V4cZTAI3PQl8sNhmKN9tHaufT7u/vD61eHuWuuezjie4ZTouM227wx2g3B0bU3@NJPddHtn@tfs5Vf7AWaaJAyz9aNuOvvN9ZtfPr05@8fcfWdv71x8/H3jD4ZZtlqU3yVdq15rhexTrpe0onqrJJ/yvKRl1Jub@4kbRjrLG90sZg@islpiaMnhIE5pkkOYsFvw00bqxiJTtZoBipSURtFhj00U6BGgw1rYgocH@BGqgVAgOIHRXALWfALoJXBjBrh/0IXSJ4ki9UHMzIJwjGF7gGSIc7KaumEgbR8dn5/QFMJh0sjCbxiy0pZnEpwczC4VJ9Ms6F@53rXuGXIVmAmDnSprb9N4mLoTKM8YFi0afonWjMK96uQAmcQvnbtUBHWSe1jNL1EV3dygheK0aijUUkzFJUXJseRVhPY4YyXxiUezSX7baprIDCw9rSGe6IkPqnlMq48Flng9SoMpTKPAjfwxJmoDd5xhJspmIayIDnBhDaKC8wlVf67uybpgJ3zDBeORr68FeAy7Ik7H/hr3QJXgxrmm9Asj7xYaIRSXgH9VwGopmqwUuT2REbkXVG@sHtk9ImeWuO0qbr8rFtltxy5WlGUtRfRkdmAtQ@02XBoAM@YxExGAxSxrgFddEd4@GsDhowGgCM/Ejf2fIlAPmB1ylhxQ6KheL@uhwqOyjYvlQLATrXZ7BGdCB1WtKrlt4B6dm4o53B/Pxemz1FCt9njJXDxXpYoNvGqtvnk@x/SeW9nx0XM5lg3Rqp7PpWc2fvv/VHs4QDo9ZPeJS6hUdt3V4E7YY88lC/XiIn5sFyzZ@U8u987D85ZfTyV2ZKtu7UAQZc4wtYfMJfnXHrrAKVlAcxPNd0LNlkRLXBw/X1XTTnXV0vpN8ZvFaS6SdoWHpGWT8ZH7a1kMtXtlWr83PlPTWMLDq5I7HeeFWL2683SKHzgu6gJajkKbtFZQsUovDCPRDYutsmibzMk7wEnXzDKulDO/0dlIpmVxES9oRR5GIPqki@g6imfQQ8eTCUjQhof07oej01O04RvQNG2y9xnSxGwSlqLtGdyveqV9FbYPGU2iAW@fHsY@8NrwqVVFm1l8UjGSnjzM3HE0nSgVWJQq838EfRA0aCPs5WEMIQbYu6Yi7ItNQ16DcnhpyBYFXljfROVav61UnsQ6mbL@vGxFzJLG2FDeaUz6TnN3F7jkT9O2OuTjdMQn6NiaRh7gR6MDjXzhObDpNPkG5NOBLxMJTWpAa2rKh@vx/4WSxm04Ui0gpm3VDVEnuraAagHnGTARMGMWbAosKFFtYoh@wZgkRSWA3eKDDnNLTDEqDhNsMxJEyplSuwRM5m1N9caCE7yBry1CEnFx8zDvMCW70xQZ50FqkjsnQgPlAROCymJIvwQL/Jwi3TRknj0ldzy1LDiFlS1zTwqBxmBzTjYPWq4/D1ESpjmkUof7szkpzRaURY04RXXx@mEJZVJb8U0yYSsCNs3Wi60B5yiUS3luCk6BXCdbLDWrcjLJIpKFJivN0eQqMML/Ag)
This uses a much different approach from dingledooper's answer – notably, it only uses `h1-9a?!`. The initial `hahaha` fills the buffer with a pool containing all digits, and then it uses careful duplications and slices to construct the string in a contiguous stretch in the buffer, at which point it chops off the surrounding character pool.
## [Generating Program](https://replit.com/@tjjfvi/hq0-9-INCOMPUTABLE#index.ts)
```
import { BinaryHeap } from "https://deno.land/[[email protected]](/cdn-cgi/l/email-protection)/collections/binary_heap.ts";
class State {
constructor(public answer = "", public buffer = "") {}
clone() {
return new State(this.answer, this.buffer.slice());
}
set(state: State) {
this.answer = state.answer;
this.buffer = state.buffer;
}
i() {
this.answer += "i";
this.buffer = fromCharCodes(toCharCodes(this.buffer).map((x) => x + 1));
}
a() {
this.answer += "a";
this.buffer = toCharCodes(this.buffer).join("");
}
h() {
this.answer += "h";
this.buffer += "helloworld";
}
n() {
this.answer += "n";
this.buffer = fromCharCodes(
toCharCodes(this.buffer).map((x) =>
x >= "0".charCodeAt(0) && x <= "9".charCodeAt(0)
? ((x - "0".charCodeAt(0) + 13) % 10) + "0".charCodeAt(0)
: x >= "a".charCodeAt(0) && x <= "z".charCodeAt(0)
? ((x - "a".charCodeAt(0) + 13) % 26) + "a".charCodeAt(0)
: x >= "A".charCodeAt(0) && x <= "Z".charCodeAt(0)
? ((x - "A".charCodeAt(0) + 13) % 26) + "A".charCodeAt(0)
: -1
),
);
}
cutStart47(n = 47): number {
while (n >= 47) {
n -= 47;
this.answer += "!";
this.buffer = this.buffer.slice(47);
}
return n;
}
cutEnd47(n = 47): number {
while (n >= 47) {
n -= 47;
this.answer += "?";
this.buffer = this.buffer.slice(0, -47);
}
return n;
}
copy(n: 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9) {
this.answer += n;
this.buffer = this.buffer.repeat(n);
}
cut(start: number, end: number) {
start = this.cutStart47(start);
end = this.cutEnd47(end);
[start, end] = this.search(
[start, end],
(_, [start]) => start === 0,
function* (state, [start, end]) {
if (state.buffer.length % 47) {
for (const n of [2, 3, 4, 5, 6, 7, 8, 9] as const) {
const state2: State = state.clone();
let start2 = start + state2.buffer.length * (n - 1);
state2.copy(n);
start2 = state2.cutStart47(start2);
yield [state2, [start2, end]];
}
}
state.h();
end += 10;
end = state.cutEnd47(end);
yield [state, [start, end]];
},
)!;
// start = this.cutStart47(start);
// end = this.cutEnd47(end);
this.search(
end,
(_, end) => end === 0,
function* (state, end) {
if (state.buffer.length % 47) {
for (const n of [2, 3, 4, 5, 6, 7, 8, 9] as const) {
const state2 = state.clone();
let end2 = end + state2.buffer.length * (n - 1);
state2.copy(n);
end2 = state2.cutEnd47(end2);
yield [state2, end2];
}
}
state.h();
end += 10;
end = state.cutEnd47(end);
yield [state, end];
},
);
}
search<T>(
init: T,
isDone: (state: State, data: T) => boolean,
opts: (state: State, data: T) => Iterable<[State, T]>,
) {
const pq = new BinaryHeap<[State, T]>(([a], [b]) =>
a.answer.length - b.answer.length
);
pq.push([this.clone(), init]);
let cur;
while ((cur = pq.pop())) {
if (isDone(...cur)) {
this.set(cur[0]);
return cur[1];
}
pq.push(...opts(...cur));
}
}
}
function toCharCodes(x: string) {
return [...x].map((x) => x.charCodeAt(0));
}
function fromCharCodes(x: number[]) {
return x.map((x) => String.fromCharCode(x)).join("");
}
let state = new State();
state.h();
state.a();
state.h();
state.a();
state.h();
state.a();
const goal = "14159265358979323846264338327950288419716939937510";
let nextEnd = 0;
for (let i = 0; i < goal.length;) {
if (state.buffer.length > i + nextEnd + 47) {
const state2 = state.clone();
state2.cutStart47();
if (
[..."1234567890"].every((x) =>
state2.buffer.slice(0, -nextEnd).includes(x)
)
) {
state = state2;
continue;
}
}
console.log(state.buffer, i);
let bestCnt = 0;
for (let j = 0; j < state.buffer.length; j++) {
let cnt = 0;
while (goal[i + cnt] === state.buffer[j + cnt]) cnt++;
bestCnt = Math.max(cnt, bestCnt);
}
if (bestCnt === 0) throw 0;
let bestLen = Infinity;
let best: [State, [number, number]] | undefined;
for (let j = 0; j < state.buffer.length; j++) {
let cnt = 0;
while (goal[i + cnt] === state.buffer[j + cnt]) cnt++;
if (cnt !== bestCnt) continue;
const inner: State = state.clone();
const len = inner.buffer.length - nextEnd;
if (i === 0) {
const end = inner.cutEnd47(len + nextEnd - j - cnt);
best = [inner, [i + cnt, end]];
continue;
}
inner.copy(2);
inner.cut(j, nextEnd);
inner.copy(2);
inner.cutStart47(len + nextEnd - j);
const end = inner.cutEnd47(len * 2 + nextEnd - j - cnt);
if (i + cnt === goal.length) {
inner.cut(inner.buffer.length - end - goal.length, end);
}
if (inner.answer.length < bestLen) {
bestLen = inner.answer.length;
best = [inner, [i + cnt, end]];
}
}
[state, [i, nextEnd]] = best!;
}
state.answer = state.answer.replace(/22/g, "4").replace(/23|32/g, "6");
console.log(state.answer);
console.log(state.answer.length);
console.log(state.buffer);
console.log(goal);
```
[Answer]
# Score 1253 791 717 684 495 379
```
hicnhannnhh?4!4!!h?3!hh?3!!!!4?h?3!h?3!hh?5?!h?4??2?h?3!3?!!h?5?!!5?!!!!h2???4!!!h2?h?4?!h?5!!!!2??4!!!2???3!!2??4!!!!2h?5?????2???3?!h2!!hhh?2!!7?!!!!!!3!h?2!!!hhhh?5????h?3!!!!3?3????!!!!3??!hhh?3!!!!!4??!!hh2!!h?4!!h?hhhh?2?hhh?hhh2!!h?2!!!5???h?5???!!!!h?2!hhh?2!!4??!3???2??4??!h3!!!!!!!!2???3??!h?2!!!2!!hhhh?3??2!!h2!!!!h?7???!!!2???2???2?2???h?3???!!!2!!!2!!2?2??h?3!!!!!
```
[Try it online!](https://tio.run/##vVdtU9tGEP7uX7GCEksxJpJscMEGjaGQ0gklLyVNQ1yPkM6WjC1pJLluEuhfp7t3knwGG5spU83YutvdZ99u727lRFG17zh3d@t@4AzHLoOWk6SuHx6UJIqTfo2YTEnS2A/6MsUe9sPYT73RjBjKMRtJ4wTFIbBHLIlshwGaaJZK6y7r@QGDs/an7tH5T8cAYOjimeEdXpycHL8veHqpJOyDE7qsmU@uxr0ei5ulqzAcwjVj0eUUW6k3OpLBnu0P1a2tLQ3UCLFpT@12P7a77fevP3S72iawv/1UNTStVEImxGFq1FQaORp8LwH4PdWBg30o22V48QIcaOH4W1mDmKXjOOD0CqiqU8WRhkOjpm2YO00Z2pagnyVou4C2F0F1CborQfUCqhdQQydoJuE0S7cipGRiR46dsKdE5UA1iwxdWyUWDuDxIGy@G144kV0ogKi1ZhZKDXMHLBzuQdkqF@A0NGq1hgx3wiDBiWfHL8H1@34K@7B2rnw@bv/w@tXh7lrznswwnLCYZOydllvr7Xr@4NoY/alHu/F2Y/zX5OVX8wFmHEUCU/9R1Wv7O@s3v3x6c/aPvvvO3G5cfPx94w@BWbZa3L9Lvlad5grZ575e8orqrJJ87uclL6PO3NyPbD9QRd74ZtE7GJXRzKdGMe2FMU@yjwSzia8WyBuLSJWKhoLcKYWj/Y4gTNEDRPsVv4mDB/gBVJCZIzIHBnMdMOY7AC/RN6Egs4@yWPqUKKoPUjPx/CHD7YGcPktpNVVNA2Ufjs9PeArxMNlK/G8Ms9IqziQ8OYRezo7Gide9sp1r1dGKVRAqNHGqrL2Nw35sj7A8Q1y0oP8lWNOm5mUjB6CTXU67lBhVyj2u5pegDDc3sJAdlzXJtZhx9oxg4eOM1Ty0xz2WEh85PJv0bslpIgouPa@hLNEjF0XTkFefCCxyOtwNITAOPDtwh4zEevYwYYKVTHxcERXhuTaMCs8nKP9c3ivqQpzwWzYqD1x1zWND3BVhPHTXMgtcCG@ca@7@VMm7hUrIxSXgXyWwXIq6KMVMX56RYi/I1kQ9inukoCwx25bMfpc0ittOXKyQJE2J9WTvUFsCrRZeGgjT5nmWR4Aak2QLraoS8/bRAA4fDQACNslv7P8UgXzANOgsOeDQQbU6KwdTi9I2ni4H4E40Wq0BngkWlI0y3TZ4j85NxRzfH8/F6bPUUKXyeMlcPFel5ht41Vp983yG@T23suGj5zJcNESrWj4vLIv52/@n2v0eqPyQ3SeTWKniuqvgnbAnxjMaqtOL@LFdsGTnP7ncrYfnbXY9zXhHW7XewCBmfUbSHuhL8q88NMFiWkB9E@Yb4WpnWEtMHD9fVfNOddXS@k2ym4RxmiftivWpZSvio/trWQyVe2VavTc/k9M4g8dPJXs8TKds@epO4zF7YHhaF9hyTKWptcKKlXphnOXdcL5VFm2TOXlHOHXNIuNSOWc3upgVaVlcxAtakYcR5H3SRXAdhBPsocPRCDmw4YDa/nB0egobroZN06b4nqEmZpO8zNue3v2ql9rXXPehcJMk8OvTYcxFvzZcrlWSFhqfVIzUk/uJPQzGI6kCp6Uq7B9hH4QN2oA5qR9iiB5zrjmLufmmoc@gFD8akkWBT7Vvwmyt35ZKT/I6Gov@fFZLTqXGWJO@aXT@TXN35/kOLVkQeJ5VV@qK4lk1xaM/fOoWnwnKtoWjumWZnFizSBRpCv1wbFoWKuADEiMm0U1BJW6tmCkmQenhdBQ2EYg28NXg6hSF7JoKJ2fCmVM1BOAjhhaHcTp6Sz5xVRYPhENNetGP00njNte1nekgWmaaFNSEUzT0hNrce6JwvJk5hRQamkJLQ@gzs6BM/s@FLIGhH6fm/v4L "C++ (gcc) – Try It Online")
##### How?
Just a heavily tweaked (but still surely not optimal) version of @tjjfvi's strategy.
Thanks to @Mukundan314 for -9.
[Answer]
# [HQ0-9+-INCOMPUTABLE?!](https://tio.run/##vVdtV@JGFP7Or7hiXRIRmoArRVAPWtzas9Z9qdvtupQTJxMIhCTNS@nuav@6vTNDkom8euopX0jm3ue@zTNzb4jvVwaEPDxs2y5xYpNCm4SRaXvHBWmFRF98Kq@EUWC7A3nFcAZeYEfDSU4N9aiBS3GI6uAaExr6BqGALlqFwrZJLdulcNn52D@7@rELALomfjnZ6fX5efddJisI90A8k7aSl9vYsmjQKtx6ngNjSv2bDFreb/Qkf5ZhO0q1WlVB8REbWUq//6HT77x79b7fV/eA/m1Hiq6qhQIKIfAiva6wJ6LCtwKAbSkEjo@gZJTgxQsg0MbnryUVAhrFgcvXy6AopIJPKj7qdXWndtCSoR0J@kmCdlJoZxlUk6BNCaqlUC2F6hqDzjRIq3AvUgqnhk@MkD4lKwKVWWYY2ia5cADPB2GLwxh6UzmEFIhW67XUqF47gBN8PITSSSkFR55erzdkOPHcEF@GRrALpj2wIziC4tXWp27nu1ffnzaLrUc6jjelAdMxDtpm3WoO7dFYn/yh@c3gZSP@a7r7pTaHiX1fYPZ/ULT60cH23c8fX1/@ozXf1l42rj/8tvO7wKzbLR7fDd@rXmuD6vNYbzijepsUn8d5w2nUW1j7iWG7iqgbPyxaD7PSW8mrnr5aXsCLbONCrYV/bZAPFlsql1VU5EFtcbTdEwsZeoRou2y38GEOP4IyChPELIDRwgD0xQHALsYmDMz8oy5SnxWK8YOZmQ5th@LxQMmARmw3FVWFrSPoXp3zEuJlUg3trxSr0k6vJLw5hF0u9uNw2L81yFgharoLwoQqbpXim8AbBMYE6enhprmDz25RzdzLTo5BY3752o0kqLDa425@dktwdwdLxUFJlUILKBfnFNMYc16T1FZHLBXeJ7ya7L8tl4mt4NZzDs0KPTFRNfI4@0RiPunxMIRC7A4N13QoU7MMJ6RCFE5t3BEF4Yk1zArvJyj9VDpMeSFu@KqBxl1TKQ6pg6fCCxyzOPPAlbDhjHn4mZG3S42wENeAf5HAMhU1QcWZvaQi6VmQvQk@ij6Srqxx25HcfpMsim4n@iqEYUsSPTk6tBZCu41NA2HqosiSDNBiGFbRqyIJ71cmcLoyAXDpNOnY/ykD@YJpsLvkmENHlUpeDzKP0jHOtgPwJOrt9gjvhBMo6SXWbbCPLizFgthX1@LiWThULq@mzPVzMTU5wJty9fXzOeZ9bmPHZ8/lOB2INvV8lXoW72/@H7bbFij8kj1iLpGpot2VsScciuechUrWiFedgjUn/8l0P5m/b2ftKRcdO6r7DUwiHzMuHYK2pv5b8y5owDZQ24PFTrjZnGiNi@7zsZpPqptS61fJb@gFUVK0WzpgI1uaH@tf63IoP6Jp5dH7pVzGHB4/lYzYiTKx3LqjIKZzjjNe4MiRabPRChkrzcL4lkzDyVFZdkwW1B3hbGoWFZfoPOvo4i0ty3ISLxlF5jNI5qRrd@x6U5yhvckEJbBDQOm8P7u4gB1TxaFpT3zPsCFmj0WZjD3WY9ZL42ti@1SEyTTw65NQamJcOya3KmkLi08iI5vJ7dBw3HgiMTCjqvB/hnMQDmgjSiLbwxSHlIy5iJrJoWGfQRF@NITLEs@s70Ge6/eFwpOi9mMxn@etJKtsMFalbxqNf9M8PAz/bP4L), ~~8265~~ 8261 points
*-5 points thanks to @Bubbler*
*-4 points thanks to @Mukundan314*
This was a very interesting puzzle to solve; note that this is definitely not the cleanest solution.
```
h5?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiinhhhhh?iiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?ichhhhh?iiiiiiiiiiiinciiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiichhhhh?iiiiiiiiiinciiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiiniihhhhh?iiiiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiichhhhh?iiiiiiiiinchhhhh?hhhhh?iiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiichhhhh?iiiiiiiiiinciiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?ichhhhh?iiiiiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?chhhhh?iiiiiiiiiiiiinciiiichhhhh?iiiiiiiiinciiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iichhhhh?iiiiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?ihhhhh?iiiiiiiiiiiinhhhhh?iihhhhh?iiiiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiinihhhhh?iiiiiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiiniiihhhhh?iiiiiiiiiinhhhhh?iiiihhhhh?iiiiiiiiiniihhhhh?iiiiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiiniiiihhhhh?iiiiiiiiiniihhhhh?iiiiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iihhhhh?iiiiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiiniiichhhhh?iiiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiinihhhhh?iiiiiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiiniiiihhhhh?iiiiiiiiinhhhhh?iiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiiniiichhhhh?iiiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiichhhhh?iiiiiiiiinciiiihhhhh?iiiiiiiiiniiiihhhhh?iiiiiiiiinchhhhh?iiiiiiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiiniiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?chhhhh?iiiiiiiiiiiiinciiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiinhhhhh?iiiichhhhh?iiiiiiiiinchhhhh?hhhhh?iiiihhhhh?iiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iihhhhh?iiiiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiichhhhh?iiiiiiiiinciiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiihhhhh?iiiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?iiichhhhh?iiiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?ihhhhh?iiiiiiiiiiiinhhhhh?chhhhh?iiiiiiiiiiiiinciiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiiniiiihhhhh?iiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiiniiichhhhh?iiiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iichhhhh?iiiiiiiiiiinciiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiiniiiihhhhh?iiiiiiiiiniiiichhhhh?iiiiiiiiinchhhhh?iiiihhhhh?iiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiinhhhhh?apppppppppppppppppppppppppphhhhhhhhhhhhhh???
```
[Verify it online!](https://tio.run/##7RjbdtpG8J2vGDt1kIJxJOPYtcHmYNdJ05PUudRpGody5NUCwiDpSKI0idNfd2d3kbQYiYsNxA/Sw7CXue/szCzEdYstQm5uHlk26fZNChXiB6blHOWkFRJ8cam84geeZbfkFaPbcjwraPdG0BCPGrjU9xEdbKNHfdcgFFBEOZd7ZNKmZVN4XfvYODn75RQAdE18I3vH58@fn76L93JCPBDHpOVwctlvNqlXzl06TheuKHUvYtLCzl5dktc0rK6ytbWlguIibdBUGo0PtUbt3Yv3jYa6CfRfK1B0Vc3lcBM8J9BLChsRFb7lAKymQuDoEPJGHh4/BgIVHH/Nq@DRoO/ZfL0AikKKOFJxqJfUje3dskxak0g/SaS1iLSWRqpJpPsSqRaRahGprjHSIQYp574Lk/yB4RLDp/NYRaA4tAxVm8UWTsDtQbJkNdrOQFYhIkSupe2Iqb69C1UcHkC@mo@IA0cvlfZkcuLYPk7ahvcETKtlBXAI62drn05rP714ery/Xr6F03UG1GM4xm7FLDX321bnSu/9rbn73rO9/j@DJ1@2x2j6ritodn5WtNLh7qPr3z6@ev2ftv92@9ne@Yc/N/4SNNNOi@t3wc@qXp7B@1zXCx5R9Vmcz/W84GFUT/R9z7BsRfiNXxatjlbp5XCqR9Om43EnW7iwXcafCsgXiy0VCioicqXWOLVVFwsxdQeprYJVxsEYfQcKuBlSDBXoJCqgJysAT1A3wWAoH3Ex9JmjWHwwNoO21aV4PXCnRQN2moqqwtohnJ495y7EZLLlW18peqUSpSTMHIIv33b7frtxaZArhajRKQgWqsgq6288p@UZPQxPBw/Nbn2219VYvCzkCDQml69dSBtF5ns8zc92Hq6vIXXby6uSah7l2yOIkY4jUkPTJmssOd4l3JvstyK7ia3g0fMYGjq6ZyJq4PDoE4a5pM7VEAh9u23YZpcytKbR9anY8gcWnoiC5CE3tArzE@R/zR9EcSEy/JaBzG1TWW/TLt4Kx@ua60MJHAkLzhVXP2byNpUJU3EK8e8SsRyKmgjFIb/QI9FdkKWJeBR1JFqZIrYmif0mcRTVTtRV8P2ytDW3dsjNh0oFiwaSqUmahRYgR9/fQqmKtPl9ogHHEw0Amw7Cin0vC@QEs8dyyREn7RSLo3gQS5SucXwcgDdRr1Q6mBOqkNfzrNpgHU10RYLuk33xciExVChMDpnzRUVqeIFnjdVXixPM69zMgk8WJThqiGaVfBZJFvM3q4l2qwkKT7KHTCRGqih3BawJB2I8wqEYF@JJt2DKzZ873Kvj@XZYnka0Y1d1Zw@NGNUZlw5Am@L/tXER1GMHqG1CshDOdmRriojTxUU171RnDa0/JLm@4wWh0y5pi7VskX2sfk2zoXArTIu35q9lN47Q41PJ6HeDeFsu3YHXp2OC47jAliPGZq0VRqzUC@Ms7IbDq5J2TRL8juSsaxYel8J5WNHFLHJLehCntCLjFoR90rl9ZTsD7KGdXg93YIOAUnt/8vIlbJgqNk2b4j3DmphNpmXY9jRvR73Uvoa8j4WaDANfn4RSE/XaMDlXCVtwnCsYWU9u@UbX7vekCIxDVcg/wT4IG7QOJYHloIltSq74FjXDS8OeQQE@Gvw0w2PumzAa699zubm0dvuiPx/lEq6yxliV3jQaf9Pc3LSfVa3ws0mbfdUMZjCDGcxgBjOYwQxmMIMZzGAGM5jBVUL2v0Q8En9TLI4HG5LbWz/4X5AxhbhOq9Y0QdwP0GK2sxxbuUOMLEvXyd5avD@Xf27J8flwfTwOEwxI9dFd@Cccwf1P9d5ZcCneTwiFcGmVdzIxK6TqNl9uGeNjry4TpWi0ArkPLaOmeCIh160iXmY9lyVm@QV646Fk7Vm9mpy/73@rFntG81SZ5fWvy68cy8wVi6vJEXpKNv8x/chd7mx6nlpcxN0lyz20HD@bxKRObRWvnNkre7ouy30bG27q1x75qtXq/w)
### Explanation
The main idea is to generate a long string of letters, and then perform a single `a` operation to convert it to the desired output. By itself, there is no such sequence of letters which lead exactly to the first 50 digits of pi. To increase our chances, we can instead find a sequence that works *after* performing some number of `p` operations. To illustrate this, if `p=1`, we would need to find a sequence of letters that decodes to the below (the `?`s are wildcards):
```
?????1??41?5?92??6?535?89793?2??3846?264?3?383?27950?28841?9?71?69?399?3?7510
```
And for `p=2`:
```
??????????????1?????41??5?92?????6?5?35??8?979?3?2???3846??2?64??3??38?3??2795?0?2?8841??9?71?69??39?9??3??7?510
```
As you can see, the position of the digits become more sparse, therefore there is more room for a valid letter sequence to exist.
The next part is figuring out how to build this letter sequence. First, notice that a command with 33 `h`s followed by 7 `?`s appends exactly one `h` to the buffer. Second, take note of the `a` and `r` operations, which increments and *rot13s* each character, respectively. Using these two facts, we can effectively append every letter from `a` to `h`.
For example, to append `c` to `abg`, we can take these steps:
* Perform `aaaaa`, so `abg` becomes `fgl`
* Perform 33 `h`s + 7 `?`s, so `fgl` becomes `fglh`
* Perform `aaaaaaaa`, so `fglh` becomes `notp`
* Perform `n`, so `notp` becomes `abgc`
Alright, so we know how to build an arbitrary string consisting of `a-h` (as well as `A-H`, by making use of the `c` operator). It turns out that there exists a string consisting of only `a-hA-H`, such that it turns into the desired output after applying an `a` followed by 14 `p`s (don't quote me on this number). We can calculate this string in many ways, such as with dynamic programming.
In essence, this is how the algorithm works. The actual code actually applies another optimization that decreased my score from 30K to <10K. That is, instead of using 33 `h`s and 7 `?`s every time we want to append, we can instead use 5 `h`s and 1 `?`, which creates the string `hel`. Note that this requires more `p`s so that the digits are sparse enough for a solution to exist.
[Answer]
# HQ0-9+-INCOMPUTABLE?!, ~~1577~~...~~536~~ 510 points
```
hcoh3ioohhh8hh???????ichhhhh?iichh6????iiihh7?????iiiiiiinch9h?????chh3??3h?ch5???ich4hhh???ihhhhh?2hh?h8??????ch2?3hhh??h4???3hh??2hh3h??????iiiiiiiiiiinchh2h??2?ihhhhhhh2????iih6hh???????iiiiiiiiiinh5hhh??????iichhhh2h???chh2??iihh3hh????iiiiiiiiiniiichh3h????ihhhhh?ih2h??iiiiiiiiniiih2h??hhhhh?ihhhhh?iiiiiiiiinihhhhh?ih2??iih3????2hhhhhh???iihh3h?????iiiiiiiniihhhhh?ihhh3hh??????iiiiiiiiiinchhhhh2????hhhhh2????iihh2h???iichhhhh?2??chhh3??????2??2hhhh???2hhh???iiiiiiiiinhhhhh?2hh???2h???2???iannnnppop?o
```
[Try it online!](https://tio.run/##vVj7c9o4EP6dv2JLL8Uugdo4CU0gYUgu7fWmvb4uvV5TjnFkgUTA9tjm6Cv3r@dWkh8iQCBzmfNMBkm73770yVqHhGFtSMj1Q@6T8dSj0CZx4vHgqKStkORrSPWVOIm4P9RX3PEwiHjCJnNqqEddXJrGqA6@O6Fx6BIK6KJVKj306ID7FF51P/ZPXv98CgC2pZ452fHZs2en73KZVSop/3AxHQxo1CpdBMEYLikNzwv16k6zp/kYuHxs1Ot1E4wQscnA6Pc/dPvdd8/f9/vmNtAvPDFs08xtkwAzOIR3ZeOakYA5PAgYY08Z66iHEyaeDheDPbnCOWPNTjoUj0/YvtJHHafTcRgOdhV4h0lTXFlp4B972kl1G6gppGynI0A4QrmTeubFg/ZZQ0hTMzhTGmyviLPQZruM5UZk@AIsYmtIEHOUuEBwqac8p5FyCdI15EImTGuSi3OQ9OAIQw0VaifzOVcxzgtLDltI2SdFmnMJq1R4tisNmZbyJ@qjnKbO51Is6i@ESrnDXR@fMAzCTnBtlpFHSBmIgsR2DDEiJnwvAfCBQeDoECpuBR49AgJtHH@rmBDRZBr5cr0KhkFqODJxaDvmVmOvpUO7GvSTBu3m0O4qqKVB9zWolUOtHGpbAppqkFbpSqUUz9yQuDG9S1YEamlmGNomuUiAzAdhy8NgwUwPIQeiVaeRG7Ube9DB4QFUOpUcnAS24zR1OAn8GCfMjR6Dx4c8wYNcfv3g02n3p@dPjvfLrRs642BGI6Hj7rU9Z7DP@OjSnvxlhfvRbnP69@zx18YCZhqGCrPz1LCcw72HP379@PLVP9b@28Zu8@zDH1t/Ksy63ZLxncu96rU2qL6M9VwyqrdJ8WWc55JGvaW1n7jcN1Td5CvU6mFWdiub2vl0EESyyBwXGi38aYP@uhVL1aqJijKoBxLNe2qhQI8Qzau8hYMF/AiqKMwQaQCjpQHYywOAxxibMpD6R12kvtw8j9ZpJMhubYNttuDJExjwKN1R4DF89lFvxviYGlI75t8oluYILFFauXauCWqiNljtz34FfvyAleKoYqqQpDCiUjynaGY7Oec1uxdNdXuV30TBMHInSPgAaeAPP/tlU6aWFSYkMlvx2wbNlljBrZF7jH7EQZl4qJoEkh0qsZD0ZBhKYeoz1/fGVKgN3HFMlSie8YQwA@GZNcwKSwqVXyoH@b6pe7nuonHfM8qMjpG1QTT2yqkHqYStwaUMvzDydqUREeIa8G8aWKeKpaiS2ssqknNV96b4ot7z@coat13N7XfNouojVAcEcdzSRHeODq3F0G7jSx1h5rLIsgzQYhzX0auhCa9uTeD41gTAp7Osz/pPGegvgKY460cSOqrV5vWg8FgPpzHrX7jk0ii2A/Ak2u32yDTxLqjYFXEb4D23tBRLYr@9Fi/uhUPV6u2UObsvpmYHeFOuvrw/x/Ie2tjxyX05zhuWTT2/zj2r@Zv/h@18AIZ8yR4Kl8hUdR1V8U44UOM5C7XiorztFKw5@Xeme2fxfZteT3PRiaO608Qk5mPGpQOw1tT/waKL/BJe7kSanROtcXF6f6yWneSm1Ppd8xsHUZIV7YIORUuV5yfur3U5VG/QtHZj/kov4xweP3Dd6TgpxPrVnURTuuC44AW2HIW26B6RsVqvirOsW82OyqpjsqTuCBddraq4Ruf0RlezvCyrSbyiFVnMIOuTzvxLP5hhjxtMJiiBLQJG9/3Jixew5ZnYNG2r7w3RxGyLKLO2Z3CT9Vp7mdk@VmEKDaBfCKUexrXlSauatrJ4JzKKnpnH7tifTjQGFlRV/k/EvyW4P6Ik4QGmyCi5lCLqZYdGfKYk2NTHqxIvrG/DPNevSqU7RR1OE9E73zgx2apojE3tmwP78KvrfwE)
This mostly extends [@dingledooper approach](https://codegolf.stackexchange.com/a/254548/91267); differences:
* uses both `o` and `p` operation
* allows constructing rot13 of the solution the transforming it back
* uses `2-9` (multiplication) in the middle of the solution
Things that are tuned by hand:
* currently there are occurrences of `i...ini...i` in the result which can be shortened by hand
* the end of the sequence can usually be optimized manually since we are no longer restricted to characters in `a-fA-F`
Code used for generation (bit outdated):
```
import functools
import itertools
import json
import pathlib
import time
import re2 as re # stdlib's regex can't handle this
TARGET = "14159265358979323846264338327950288419716939937510"
CACHE_PATH = pathlib.Path(__file__).parent / "incomputable-cache.json"
MAX_BUFFER = 10**5
ROT_13 = (
"------------------------------------------------"
"3456789012"
"-------"
"NOPQRSTUVWXYZABCDEFGHIJKLM"
"------"
"nopqrstuvwxyzabcdefghijklm"
"-----"
)
def prime_sieve(n):
"""returns a sieve of primes >= 5 and < n"""
flag = n % 6 == 2
sieve = bytearray((n // 3 + flag >> 3) + 1)
for i in range(1, int(n**0.5) // 3 + 1):
if not (sieve[i >> 3] >> (i & 7)) & 1:
k = (3 * i + 1) | 1
for j in range(k * k // 3, n // 3 + flag, 2 * k):
sieve[j >> 3] |= 1 << (j & 7)
for j in range(k * (k - 2 * (i & 1) + 4) // 3, n // 3 + flag, 2 * k):
sieve[j >> 3] |= 1 << (j & 7)
return sieve
def prime_list(n):
"""returns a list of primes <= n"""
res = []
if n > 1:
res.append(2)
if n > 2:
res.append(3)
if n > 4:
sieve = prime_sieve(n + 1)
res.extend(3 * i + 1 | 1 for i in range(1, (n + 1) // 3 + (n % 6 == 1)) if not (sieve[i >> 3] >> (i & 7)) & 1)
return res
REMOVE_SET = set(prime_list(MAX_BUFFER) + [2**i for i in range(24)])
def run(prog, buffer=()):
"""HQ0-9+-INCOMPUTABLE?! interpreter"""
buffer = list(buffer)
for char in prog:
if char == "h":
buffer.extend("helloworld")
elif char.isdigit():
buffer *= ord(char) - 48
elif char == "i":
if any(i in "9Zz" for i in buffer):
return
buffer = [chr(ord(c) + 1) for c in buffer]
elif char == "n":
buffer = [ROT_13[ord(c)] for c in buffer]
elif char == "c":
buffer = [c.swapcase() for c in buffer]
elif char == "o":
buffer = [c for i, c in enumerate(buffer) if (len(buffer) - i) not in REMOVE_SET]
elif char == "p":
buffer = [c for i, c in enumerate(buffer) if (i + 1) not in REMOVE_SET]
elif char == "u":
buffer = [c.upper() for c in buffer]
elif char == "t":
buffer.sort()
elif char == "a":
buffer = [i for c in buffer for i in str(ord(c))]
elif char == "b":
buffer = [i for c in buffer for i in f"{ord(c):08b}"]
elif char == "l":
buffer = [c.lower() for c in buffer]
elif char == "?":
buffer = buffer[:-47]
elif char == "!":
buffer = buffer[47:]
if len(buffer) > MAX_BUFFER:
return
return buffer
def unrun(prog, buffer):
"""un-runs part of a program; computes possible buffers before prog was executed"""
ret = list(buffer)
for char in reversed(prog):
if char == "o":
ret = ["#" if i + 1 in REMOVE_SET else ret.pop() for i in range(10 * len(ret)) if ret]
ret.reverse()
elif char == "p":
ret.reverse()
ret = ["#" if i + 1 in REMOVE_SET else ret.pop() for i in range(10 * len(ret)) if ret]
elif char == "?":
ret.extend("#" * 47)
elif char == "!":
ret = ["#"] * 47 + ret
return ret
def brute_start(max_length=5):
"""
brute-force for programs that satisfy conditions:
- shortest to generate its output
- does not contain 0-9, m-z, M-Z in output
"""
if CACHE_PATH.exists():
saved = json.loads(CACHE_PATH.read_text())
return list(zip(saved.values(), saved.keys()))
mid_chars = "h23456789incopt?!"
last_chars = "hincopt?!"
saved = {"": ""}
for length in range(1, max_length + 1):
for prog in itertools.product("h", *[mid_chars] * (length - 2), last_chars):
if (output := run(prog)) is None or any(c.lower() > "l" for c in output):
continue
output = "".join(output)
if output not in saved:
saved[output] = "".join(prog)
CACHE_PATH.write_text(json.dumps(saved))
return list(zip(saved.values(), saved.keys()))
@functools.cache
def optimal_trim(size, trim):
"""more optimal ways exists, but good enough for now"""
best = None
for i in range(1, 10):
tens = (-(trim + size * (i - 1)) * pow(10, -1, 47)) % 47
rem = (size * (i - 1) + tens * 10 + trim) // 47
pre, post = tens // i, tens % i
curr = f"{'h' * pre}{i if i != 1 else ''}{'h' * post}{'?' * rem}"
if best is None or len(curr) < len(best):
best = curr
return best
@functools.cache
def optimal_prefix(size, extra):
"""optimal way to achieve buffer + buffer[:extra]"""
best = None
for i in range(2, 10):
if size * (i - 1) < extra:
continue
if size * (i - 1) == extra:
return str(i)
trim = optimal_trim(size * i, size * (i - 1) - extra)
if best is None or len(trim) + 1 < len(best):
best = f"{i}{trim}"
return best
def solve(target, start, transform_map, max_prog=10 ** 9):
dp = [(None, None)] * (len(target) + 1)
def add(matched, prog, output):
if len(prog) > max_prog:
return
if dp[matched][0] is None or len(prog) < len(dp[matched][0]):
dp[matched] = (prog, output)
for prog, output in start:
transformed = [j for i in output for j in transform_map[i]]
if all(i in ["#", j] for i, j in zip(target, transformed)):
add(len(transformed), prog, output)
for matched, (prog, output) in enumerate(dp):
if prog is None:
continue
for prefix in ["h", "he", "hel", "hell"]:
trim = optimal_trim(len(output) + 10, 10 - len(prefix))
for shift in range(ord(min(prefix)) - ord('a') + 1):
shifted = "".join(chr(ord(i) - shift) for i in prefix)
for is_upper, cased in enumerate([shifted, shifted.upper()]):
transformed = [j for i in cased for j in transform_map[i]]
if matched + len(transformed) > len(target):
continue
if all(target[i] in ["#", c] for i, c in enumerate(transformed, matched)):
add(
matched + len(transformed),
(
f"{prog}"
f"{'c' * is_upper}"
f"{'i' * shift}"
f"h{trim}"
f"{'i' * (-shift % 13)}{'n' * bool(shift)}"
f"{'c' * is_upper}"
).replace("cc", ""),
output + cased,
)
new_matched, new_output = matched, output
for i, c in enumerate(itertools.cycle(output)):
if new_matched + len(transform_map[c]) > len(target) or i >= len(output) * 8:
break
if not all(target[j] in ["#", k] for j, k in enumerate(transform_map[c], new_matched)):
break
new_output += c
new_matched += len(transform_map[c])
add(new_matched, prog + optimal_prefix(len(output), i + 1), new_output)
return dp[-1]
def main():
start = brute_start()
# constraint: transform(a) + transform(b) == transform(a + b)
transforms = [f"{'n'*j}a{'n'*i}" for i in range(10) for j in range(2)]
best = None
prev = time.perf_counter()
for transform in transforms:
transform_map = {i: run(transform, i) for i in "ABCDEFGHIJKLabcdefghijkl"}
regex_filter = re.compile(f"^({'|'.join(''.join(f'[{j}#]' for j in i) for i in transform_map.values())})+$")
print(
"\033[0;33m",
f"[{time.perf_counter() - prev:.2f}]",
f"transform: {transform}",
f"(filter size: {regex_filter.programsize})",
"\033[0m",
)
prev = time.perf_counter()
for end in itertools.product("po", repeat=11):
sparse_target = unrun(end, TARGET)
if regex_filter.match("".join(sparse_target)) is None:
continue
prog, _ = solve(sparse_target, start, transform_map, len(best) if best else 2000)
if prog is not None:
prog = f"{prog}{transform}{''.join(end)}"
# assert "".join(run(prog)) == TARGET
if best is None or len(prog) < len(best):
print(len(prog), prog)
best = prog
if __name__ == "__main__":
main()
```
[Answer]
1000076 points
```
1415c9c265c35c89c7c93238c46264c338c3c279c5028cc8c41971c693c9cc93c7c51cc0cccqo
```
c is a placeholder. It can be replaced with any digit, or with any other letter command that has no effect when the buffer is empty.
The only commands that do anything are q and o. So it loads the source code into the buffer then removes characters using o, but it only removes the letters. I tried to do it by ending with qp instead but it didn't line up.
These two attempts don't work because if you use q then ? can not be in the source code.
```
14159265358979323846264338327950288419716939937510q111111111111111111111111111111111111111111111?
14159265358979323846264338327950288419716939937510q5?????
```
] |
[Question]
[
You are little speck on a Cartesian plane. Pondering your existence, you decide to roam around your plane and touch things. You notice that every coordinate pair you visit has a light switch. To entertain yourself, you decide to toggle every switch that you come across.
**The Challenge**: Create a program that will take an input of random length, using only the characters `v`,`^`,`<`, and `>`. These characters correspond to movements.
* `<` moves you one unit to the left
* `^` moves you one unit up
* `>` moves you one unit to the right
* `v` moves you one unit down
Using this randomly generated input, calculate how many switches will be left in the `ON` position, assuming you start at (0,0), all lights begin in the `OFF` state, and you don't turn on any lights until you make your first move. (Meaning, if you start at (0,0), and move up 1 unit to (0,1), there will now be **1** light on). If you come across a switch that is on the `ON` position, it will be turned `OFF`.
Test cases:
```
v>v<^^<v<<^<^><<>^^>>><v>vv^v>v^><><<^>><<<vvv^vvv>v>>v><vv^^<<>vv^^>v^<>>^^<^^>^^v<^>^<vvv^v^v><^<<v<<>><<>v>>^><^>^^<>>>>vv>^<<^<<><vvv<v^>>vvv>v^>>><<v^>^^^^v>>^>^v>v<vv^<>^<<v>vv>><^^<^><vv^^v<v<v^^^>v<^vv^v<><vv^^^>v^>v>vv<<^><v<^v><<v^^v>>v<vv<><^^^v<^v><><<^^<>^>><^^^>vv^<>>>>^<^<<<<>>>v<<v<v<vv><<vv<vv<^v^^^>>vv<>v>><<<v^>vv><v<<<v<<>^vvv^<v^v>^^v^v><<v^>>>v<v<v^>>>v><>>>^<><<<<>vv>v><v>v><^v<>v>>>vv<<>^>^>v<^><^<^vv^><^^>v<^^v>v^v<^^^^vv<>v<>><v^^><>v<<<>v^<v^^><>^<>^<>><>^^<>^v><>>><v<^^>>v>^^^<v
```
yields 125 lights on.
```
>>><^>>>^vv><^^v^<<<>>^<>>^<^>^<<^^v^<v^>>^<<><<>^v<^^^vv>v><^>>^<^<v><^v<^<<^^v><>>^v<^>^v<vvv<<<v^vv>>^vv>^^<>>vv>^<^>vv<>v^<^v<^^<v^^^<<^><><>^v>vvv<^vvv<vv><vv<^^v^^<^^>>><<<>^<>>><^<<<>><>^v><^^vv<>>><^^^<^>>>>v<v^><<>v<v<v^<<^><v^^><>v>^<>^^^vvv<v^>^^^^v>v<v>>>v^^<v<vv>><<>^vv><<vv<<>^^v>>v<^^v>><v<v<<>^^vv>>^v>v>v<>^>^v<>>><>v>v<<v<^<>>>vv>>v>^<>vv^v><><^v^>v<^^>v<^v>>v^>^>>v>v>^>^<^^>vv>>^vv<^><>^><<v^<><<^<^>^^vv^<<^^<^^v<v<>^>v>>>>>>vv<<v>^>vv^>^><^<^^><<vvvv>vvv<><<><v^vv><v^^<>^>><^vv<><>^>vv>>>vv^vv<<^v^^<<v^^>^>vvv<><<v>^>^>v<v>^<^^^^<^>^>><>>^^vv<>v<^>v><v<v^>>v<^v<vv>v^>v<v^<^^^^v<^<^<<v<<<v<v^^>vv^>><<<v>>^^^>^<^>>>v^v><^^vv^>><^^vv<vv<v^><>>^><<<>>^^v^v<<v^<vv^^^>><>>^v^^^>>^>^<<^>v>^^v>><>v>^>vv^^<vvvv<><^v>^><<>>><^<^v^<<vvv^v<<<<<><><<><><<v>v<v>v><^v^^vvv>><>^>^>^v<<vv^^^v^vv><v><><v<v<<>>>v<^<^v<<>^v<<^v<><>v>>^^>^<v^<<^v^^^vv>><v^<v>^v><^<>>>>^^<vv<>^^>^>v^v^^>><>^^<^v^<v<<v<^<<^^vv>v>^<vv<<^^v^vv^>^^<>v>^>^<>vv><v>>><<><<vv^^<vv<>>^v>^<<vv>^><<>^<v>v><<v^<v<><v>^<^<^><^^^^>>>^<>^^><>>v^<vv^<^<<vvvv>>>v^v>>^>v^><<>>v<>>^>><vvvvv<<vvvv<v>^v<vv^<>><<><v^^<^<v>^v<^<<>^v<v^<>v<<>^<<vvv><^><^^^<>>v^<<>vv><^^^>><^>v^v>v<v^>>v>>v>vv<<v<<vvv^^^>^<v^^<^<v<^<>>v^<<v>>v^><v<vvvvv^^^<v^^<><v<<^>>^><^<v^v^^>><v><>v>^<vvvv><<v^^v^>^>v>><>^^v>v^>vv^>v<^<<^vv^>vv^<v>^<v^<>^v>v^>v^<<>^^<^>^^>vv^>>vv>v>vvv><>^v<<<<v^>v^^v<><v<v>^<^><^><<v<>><<>v^^>>><<><>>><<>><v^^>><^>><^<>v^^vvv>v<^<<vv^>vv^><<>v><>^<>v^^v>^>v^<>^><v>^><<^v<v^^<v>><^^>>^<^<^v<v>^>^<^<v><><>>>><>^<^<v>v<v^>v><>v^>v^<<><^<>>v<^vv^^^>^<<<<>^>^<><^vvv>^^<v^v>v>v^v>v>>vv>^><>^vv>^<v<v^<>vv^<v<><>^>>vvv><>>^<<v^<<>^<v^>v<^^^<^<^^<>^>>v>^<v>vv<v^^>><<<<<>>v>^v>^>>>>v>>^^>^<<<^<<<v>>^><<<<^vv<<>^v<^>v^<v<<>v<>^<^<^<^<>>^^^vvv<v>^vv>^><^<v^>^v<v>><><vvv<^^>>v<^v>^>>>><v^<v^^<^^v<vvv<v>^^<<>><^<v^v<^vv>v>vv>^^<>^^^^>>^v><vv<<<v>^v^>>v^>><<<^v^v<<>><<vvvvv<v^vv>vvvv><v^v<^^^><vv^^<>><>><^>^^^^v>v><><v^<>^v<>^^<^^>^^^vvv>>vv^v^<v<vv^v>v>>>^v^^vv^<^v>v^v>>^v>v<v^<^^><vvv>><<>><>><v>v<^<v>>>>v^^v^^>^><<v><^<<>>v<>^^<<>vv^>>vv^^^v>>>^v^><v<<^>v<v><>>>^>>^<<>>^><<vv<^^>^^^v^^<>>>vv><<>v<><<<>v<<>>>v<>v<>^<vv^v<^^<<<v>^v>>^^>^><<^vv<><><>v>^v>^<>v>>^^^<^^>>vv>v<<<v^><<v><^v><>v<^<<^<>^vv>^><^^^^^<<v^^<>v>><^<v^^^vv>^v<>^<v<v>v>^><^<<^<>><^^>vv^<>^<>vv<>>v<vv^>><^^<^>v<><>vv<v<>>v><v^^^>^^^<<vv^><^^v>v>^<^>v^><<vvv>v^><vv<><^<><^>^v<><<v^<<><>^^^^<<^>>^>^v^>v>^<<^>vv^vv^v<>^<<^>v<^^<<v<v<<<^>vv^>><>v>><><v>v><v^><vvv>vv<<vvv>v^<<^v<^<><<^v>v<>>vv<<v^>v>v<<>>^vv^<^^^<^v>>^<vv>^<v>><>v>^^<<v^<>>>>>v^v>><>v^>>^<>>^<^vvv^^^<^v<><vvv^>^>v><<v>>^v>v<v>v^<v>v>^<>vvv>vvv^^<>vv>^^^^^>v<<^v<>>>><<<>>><vv>>^v^^v<v^>>>^>^v<^v>^v<>vv<><vvv^v<<<<v<vv>vv^<^vvv<^v>v^^vv<^>>>^^>>^^><>^>>v<>>>^^<<v<^<<<<<^^<v^^^<<>><<<^>^v^>vv<>>>^^v><<>^^^^<vvv><^^<>>>^><<^>><v>^<>^v^<vvvv^>>^><<>><^<v^>>vv^vv<^>>>><^>^v<^<v<^^<^<^><^<>>^<>v^v<<>v>v<>><<v<^v<<<^v<v<>><v<^<^>>v>v>><v^<v><>>>>>v^v>><^<^<v>><v^v>v<>v<v><<<>^^><>^^<^vv^^<>v><><><^>^^v^vv^<><>>>>v><>>^>^<<^<v<v^>v^^<v>>><<^^vv^^>><<^<vvvvv>><^>^>>^vv<><<>v>v^<<<^v<^^<<^vv>v<vvv><^v>vv^vvvv<^>^v^<<<<^v<<<>^vvv>^v><<>>v<v<^v^<>v>>^^v^vv>>>^v^^>>^<><><<<<^vv>>>>>v>v^>v<>><<<>^vv>^^^^<^^^>^^^^>^^^v^v><^>^>>>v<v<^<^^<<^v<<^<>vvv^^^^v^<<>vv>^^>>><^^v<^<<<v<>v<<><>v<><>^<v<<^>^^>><<v>^^><^^v<^<v^<^^<>^<>^v^>>^^v^v^<>v<>^<<<>^v^v>^<vvvv<>v<<>vv^<<>vv>>>>^<v><>>>v^><<>^v>><<>>^^v><^<>>vv^^^>vv^<^^v><v>>vvv^v<^v>v<<^^<>v^^^v^^>><v^>>v^v^vv<^>v^<^>^>v<v^><vvv^>^<>v<<^><^^<vv>v>>vv>v^>>^vvv>>v^>^^>vvv>>v><<>>^^v>v<v<><<<<^^v<^<>^v>><v^^^<>>vvv>v><<v>^^<^vvvv^v>v>^vv>^vv^^v><<>>^^>>v>>>^v><^>v<^^<>vv>v>v^^^>>^^^><<<<>>^>>^<^v<^<^<>^><v<<v>v<>^>>^<<v^^<v^vvvvv>>v^>>^^^<^^<><<><><>^v>vvv^>^^>v<^^>^<<^v^^^><>><<v<^^^<<<<>><>><<^^v><v^<<^v<v><<>^<v>^>^v>vv>><v^<^<v<v<v><^^^^>>><^<><^v^v<<<^>vv^<v^>^^v^>>><<<<^<>>><v>>>vv^>^^<v^v>>>v^<^<>vv>^v^^><<<v>v>v>><>>>v<^>^<>>^^<v^<<^<v^>><^v^><><v><><v^vvv<<>v>>><<><v>v<>>><^<^^v<v>^<<>^v>^>^>^^<^^><^>>>>><^^>vv>^<^^<><^>^<^^><^<v>v^>><^>^^^>>v^v<^>>^<v^<>^><><v>>^v<v^^^^v<^vv><^v>>^^^<>^<^<^>vv^v<<>vv>^<>v>^>^>vv^v<vv<^^^v<v>v>v^<^^^v><v<<<^^<><^^>>>><<^^v<<^>v<<vv^^^vv^vv^<v><>^v<v>>><vv^v<v^>>>>^<<<vv^>>v>^><<><<^<^><<vv^>v^>><>v^<<<>v^><>><<>>v><>v^<v><>^v>>><><>>>^vvv^v>vv>>>^^v^><<v<>>^^^v^^><<^v<><><v<<v<v<><<<v^<^^^<>v^^v<^^<<^>v<<v><^<<<<>><>^v>^<>^<^^v^vvv>^^<>^>><v^^vv^<>^<><<^^^v<^^^>>^^v>^>^<^>v><<^<>^v<><vv^vv<><<<<<<v<<v<<vv^<<^<^vvvv><v^v^v<>>>vvvvv^<vv^<^<>vv>^<><<v><>v^^<v<>>>vvv^><^<^>v^^<v>^<>>>^^v^<vv<<<<^><v<<<>v<<<v<>>^^^>^><>v>^v^>^<v^^><^v^^<^v^^>^v>>^^^<<><><<<>v>><^><>>>vvvv>v>>v>^^^^v<><vv<^<v^v>>^^vv<^>vvv>^v>>><v<v<v^<^>^^<vvv<vv<v>>^vv>^<<^<^<v>v^<vv^^^v>vv<v><v><v>^<v>>vv<>v>^^>v^^^<>v<>v^v<>^<><v><^>^<v^v><<^v^v^v<<v><<^^<^vv>^<^v><>v>><v^v^>><><><<<v<>v<^vv>v<v<<>^vvvvv^<<<^<vv><<><>v^<^v<<<^>v>v<v^<<^>v<<^<v><<<^>vv>v>^<^^v>>>><>vv>>vv>vvv<>^^<>^v^<>vvv<^^^vv>v><<<<vv^v><v^<^<<<><v<>^><<>^>v<^^<<>v>>v<<>><^^<<<^<^vv^^>v>v<>^^>>^v^vvv>^v^>v>>v>v>v>>vv^<><<<<>v^^>vv<^^v>>v<vv<^>>^<>^^v<><vv^<><v><v<<v^v<^^<^v^v<>v<<><vvv><<<^<^^<<>>^v>>>^v>>>v<>>^><<<><><<<v<vv<^<>v^^v^^>^<<^^^v^>^<<^>^>^>>>>v<v<v<>vv<<vv^<<^<vv>^^<^<<>><^v><><>^<v><v^>^v>^<^>^^><v><<^<v^^<<^><><v>v<>>><<^><v<^vvv^<<<>><<>^v^^><vv>vv<>^>^>vv<>v^<^<>vv><<>^<v<vv<^<^<><^vv<<^>>>v<>><<>>>^^^^<<^v>>v<vv>^^>v<v<vv^><<><>>>v>>^^v<^v^^>>v^<>>v^>><^<^^v<v<><<><>>^<>><^v<^^^^><>^>vv>>^vv<<>v<<<<<<><<<><<>><v><^^^<>>v<^><^vvv<>^>^^v>^<v><^v^vv^<<>v<<<<v>^vv>>v>vv<<^>^<>>vvv^<v<><>><>^^^^vvvvvvv<<>v<^><^^>vv^^<v<<^^<vvv<v<v<<>><<><v^^>><^<>^v^vv<<v<v<>><<>>>>>^vv<><v<>v><v>v>><v<v^vvvvv<><>v>>v<><<<^^<>^<^^<v>v^<vv>^vv^<>^<<^<vv><v<v>>v>^<>v^<<v^<v>^v<>><v>>>>^<<^^^v<^<>><^<><v>>vv^>^<^<^>>v^>^^^^>vvvvv>^v<^><^^<^^>^<^^^^^^^>v>>vv>v^^^v^^^<>v><^>>>v>^>^>^>vv<vv<^^>>^>>>v<>v><<^<<v^>^>>>>^^><^^<v<<<<>>v>v^v^^<>><v<^<<<<v^^^^<v<<<^>v>^^<vv<^^^^^v>^v^<v><>>^^>^v>^>^vv^v>v>v^>v>^>>^^^^>>^>>^><>><v>v>>><<^v^v^>^>^>>vv><<^>v<v<v^<<>>^v<<^v<<^><^>>^<v>^>vv>v>^^^>v^^<^<^^>vv>^^><v>>^v>^v<<^^^<<^v^>^<<^>vv^>>^<^v><<>v><^^^<^^>>vv>^vv>><^<<<^>vv^v>v<^<<<^<^<<><^^>>>v^<^^^>^<><^v>>^<<v<^v>>v^<^<^<^^^<v^><<vvv^<^v^vv^vv<v<<v<^<>^v>^^^<^^v<v<v><<<^<>^^^^v>v^v^v^v<v><v>>^v><vv^^^v>><<v^vvvv<<<^v<<><^>^<v^^v<>vvvv^vv<>^v<><>^^<>>vvv<^>><v^<<>v>v<>^v^>v^>><<>>^^<^v<>>^>^><>>^<v<v^^<^v><v^<v<><><^<<><v^v<<>vv<v<v<^>>><>vv^^<><<v<^^<<^<><^^^>^>>>^<^>>>^>><^^^<^v^^^v^v^v>v>v><vv>><vvv<<v><><^^>^v<v>><v><^><^<<>v^vv^v><^vv>^>>v<vv><^<^^v<^^vv<vv<v<v>v><v<vv<<>^^v^^v<<<^<>v^^^<><>>><^>v^^^v^vv<<<^>>v><^>v^<>>>>^<>^^vvv^^<><^>^^<><>^vvv^^<vv^>vv^^^^v<>vv<^^^v<<>><<vvvvv>v>^^^vv>><v><v<>vvvv<v^><^<>^>^<>v>v>v^vvvv<><^v>>>^^>><vvv<>^>^v^<vvv>v^vv^vv><>><>v^^v^vv<^v>vv>>v<v><^<<^v<>>^vv^<v>v><v>v>^v>^<v>^<<^>vv>v<^<^vv^<^><<<v<<^^vv<vvv><>v>v<vv^<><><^vvv>>vv<^^^v><^v><<^>^^v>^<>><v<>>^^<<<v><>^>^><vvvv<>^<<<><<<^<>>v^vv^>><^vv^^>^<v^<v>><^^>>>^v>^v<>^v<><^><vv>v^^^<^>>^<<^<^><<<^^<v<<^vv<^<>v<^<<^^<v<vv<<><v<v^<>^<>v>>v<^v>v<>^^vvv<>vv^v^<><v^vv^<^v^v><>^><v^<>>^^^<>>vv^<v>^^v><v<^>^^^^^^><>>vvv<<><><v<^>v<>v^v<<<<>v^>>>>^v>^^<v^>v><v^<^^v<<<<v<<<>^v<^>^v>v^^>v^^vvv>vv<>^>v><v<>^<vv><>>><<^>>><<v>v^^<^<<<<v^<>>>v<<<^v^vv<>^v>v<<<<>^^>><v><>v<v><^^>><>^>^>v>>><v>^vvvv<><><^>>^v^><<>^v<><><^><<<>v^^>v>^>v^<v^vv<>><^vv^^>^^><vv<<>v>v^^>><v^>^<^<>>>vv<>^>v>v^<>v<^<<v>>>^<>v^>v>>vv^^<>>v<v<<^<>v>v^<^^^>v^^>v>v>vv<^<v>v^^><<<v<><>^^<>v>v>^^v>v>v^v>>^<v^v>><>^^>^<>>>^vv^><v^<^>v^>^v><^>^^^vv^^v<>vv<>>^><<^v>^v^>>v>^v^<<^^^vv<<vvv>^vv^v<<<v^^<<><vv<>>^^vv>^^^vv>><><v>v<^v^>>>vv^><>><v<^v<>^><v<^^^^>><^<>v>^v<^vv>v>v<^<>v>v>^<vv>v<^>vvv<v^<vv<vv<>v>^><v^v<>>>>>v>><^v<>v>^v><v^v^vv<>^<vvv^>><v^<vvv^^<^vvv^v^<>><v>v^^v<><>v^^^v<<<^><v<<<>><<vv<<><vvv^v>>v^v<v^>>><<v<>^v><>vv<<v>v^vv>v^v<^<vv<><><^v>^<vv>v^^>>^^^><vv<><^>>>^<v^<<^^>^>vv^><v<vvv>^^>>>^><<vv>vv>^<>>^^><^v><<>^<<<v^>^
```
yields 1408 lights on.
To generate input, you may use the following Python script:
```
import random
length = random.randint(15, 10000)
walk = ''
chars = ['v', '<', '>', '^']
for i in range(length):
walk += random.choice(chars)
print(walk)
```
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") scoring, winner is the smallest number of bytes.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~19~~ ~~18~~ ~~17~~ 13 bytes
*5 bytes off thanks to @LeakyNun's idea (see [his answer](https://codegolf.stackexchange.com/a/89972/36398)) of using the imaginary unit as a base for exponentiation.*
```
Jj11\^Ys8#uos
```
Try it online! Test cases: [**1**](http://matl.tryitonline.net/#code=SmoxMVxeWXM4I3Vvcw&input=dj52PF5ePHY8PF48Xj48PD5eXj4-Pjx2PnZ2XnY-dl4-PD48PF4-Pjw8PHZ2dl52dnY-dj4-dj48dnZeXjw8PnZ2Xl4-dl48Pj5eXjxeXj5eXnY8Xj5ePHZ2dl52XnY-PF48PHY8PD4-PDw-dj4-Xj48Xj5eXjw-Pj4-dnY-Xjw8Xjw8Pjx2dnY8dl4-PnZ2dj52Xj4-Pjw8dl4-Xl5eXnY-Pl4-XnY-djx2dl48Pl48PHY-dnY-PjxeXjxePjx2dl5edjx2PHZeXl4-djxednZedjw-PHZ2Xl5ePnZePnY-dnY8PF4-PHY8XnY-PDx2Xl52Pj52PHZ2PD48Xl5edjxedj48Pjw8Xl48Pl4-PjxeXl4-dnZePD4-Pj5ePF48PDw8Pj4-djw8djx2PHZ2Pjw8dnY8dnY8XnZeXl4-PnZ2PD52Pj48PDx2Xj52dj48djw8PHY8PD5ednZ2Xjx2XnY-Xl52XnY-PDx2Xj4-PnY8djx2Xj4-PnY-PD4-Pl48Pjw8PDw-dnY-dj48dj52Pjxedjw-dj4-PnZ2PDw-Xj5ePnY8Xj48XjxednZePjxeXj52PF5edj52XnY8Xl5eXnZ2PD52PD4-PHZeXj48PnY8PDw-dl48dl5ePjw-Xjw-Xjw-Pjw-Xl48Pl52Pjw-Pj48djxeXj4-dj5eXl48dg), [**2**](http://matl.tryitonline.net/#code=SmoxMVxeWXM4I3Vvcw&input=Pj4-PF4-Pj5ednY-PF5edl48PDw-Pl48Pj5ePF4-Xjw8Xl52Xjx2Xj4-Xjw8Pjw8Pl52PF5eXnZ2PnY-PF4-Pl48Xjx2PjxedjxePDxeXnY-PD4-XnY8Xj5edjx2dnY8PDx2XnZ2Pj5ednY-Xl48Pj52dj5ePF4-dnY8PnZePF52PF5ePHZeXl48PF4-PD48Pl52PnZ2djxednZ2PHZ2Pjx2djxeXnZeXjxeXj4-Pjw8PD5ePD4-PjxePDw8Pj48Pl52PjxeXnZ2PD4-PjxeXl48Xj4-Pj52PHZePjw8PnY8djx2Xjw8Xj48dl5ePjw-dj5ePD5eXl52dnY8dl4-Xl5eXnY-djx2Pj4-dl5ePHY8dnY-Pjw8Pl52dj48PHZ2PDw-Xl52Pj52PF5edj4-PHY8djw8Pl5ednY-Pl52PnY-djw-Xj5edjw-Pj48PnY-djw8djxePD4-PnZ2Pj52Pl48PnZ2XnY-PD48XnZePnY8Xl4-djxedj4-dl4-Xj4-dj52Pl4-XjxeXj52dj4-XnZ2PF4-PD5ePjw8dl48Pjw8XjxePl5ednZePDxeXjxeXnY8djw-Xj52Pj4-Pj4-dnY8PHY-Xj52dl4-Xj48XjxeXj48PHZ2dnY-dnZ2PD48PD48dl52dj48dl5ePD5ePj48XnZ2PD48Pl4-dnY-Pj52dl52djw8XnZeXjw8dl5ePl4-dnZ2PD48PHY-Xj5ePnY8dj5ePF5eXl48Xj5ePj48Pj5eXnZ2PD52PF4-dj48djx2Xj4-djxedjx2dj52Xj52PHZePF5eXl52PF48Xjw8djw8PHY8dl5ePnZ2Xj4-PDw8dj4-Xl5ePl48Xj4-PnZedj48Xl52dl4-PjxeXnZ2PHZ2PHZePjw-Pl4-PDw8Pj5eXnZedjw8dl48dnZeXl4-Pjw-Pl52Xl5ePj5ePl48PF4-dj5eXnY-Pjw-dj5ePnZ2Xl48dnZ2djw-PF52Pl4-PDw-Pj48Xjxedl48PHZ2dl52PDw8PDw-PD48PD48Pjw8dj52PHY-dj48XnZeXnZ2dj4-PD5ePl4-XnY8PHZ2Xl5edl52dj48dj48Pjx2PHY8PD4-PnY8Xjxedjw8Pl52PDxedjw-PD52Pj5eXj5ePHZePDxedl5eXnZ2Pj48dl48dj5edj48Xjw-Pj4-Xl48dnY8Pl5ePl4-dl52Xl4-Pjw-Xl48XnZePHY8PHY8Xjw8Xl52dj52Pl48dnY8PF5edl52dl4-Xl48PnY-Xj5ePD52dj48dj4-Pjw8Pjw8dnZeXjx2djw-Pl52Pl48PHZ2Pl4-PDw-Xjx2PnY-PDx2Xjx2PD48dj5ePF48Xj48Xl5eXj4-Pl48Pl5ePjw-PnZePHZ2XjxePDx2dnZ2Pj4-dl52Pj5ePnZePjw8Pj52PD4-Xj4-PHZ2dnZ2PDx2dnZ2PHY-XnY8dnZePD4-PDw-PHZeXjxePHY-XnY8Xjw8Pl52PHZePD52PDw-Xjw8dnZ2PjxePjxeXl48Pj52Xjw8PnZ2PjxeXl4-PjxePnZedj52PHZePj52Pj52PnZ2PDx2PDx2dnZeXl4-Xjx2Xl48Xjx2PF48Pj52Xjw8dj4-dl4-PHY8dnZ2dnZeXl48dl5ePD48djw8Xj4-Xj48Xjx2XnZeXj4-PHY-PD52Pl48dnZ2dj48PHZeXnZePl4-dj4-PD5eXnY-dl4-dnZePnY8Xjw8XnZ2Xj52dl48dj5ePHZePD5edj52Xj52Xjw8Pl5ePF4-Xl4-dnZePj52dj52PnZ2dj48Pl52PDw8PHZePnZeXnY8Pjx2PHY-XjxePjxePjw8djw-Pjw8PnZeXj4-Pjw8Pjw-Pj48PD4-PHZeXj4-PF4-PjxePD52Xl52dnY-djxePDx2dl4-dnZePjw8PnY-PD5ePD52Xl52Pl4-dl48Pl4-PHY-Xj48PF52PHZeXjx2Pj48Xl4-Pl48Xjxedjx2Pl4-XjxePHY-PD48Pj4-Pjw-XjxePHY-djx2Xj52Pjw-dl4-dl48PD48Xjw-PnY8XnZ2Xl5ePl48PDw8Pl4-Xjw-PF52dnY-Xl48dl52PnY-dl52PnY-PnZ2Pl4-PD5ednY-Xjx2PHZePD52dl48djw-PD5ePj52dnY-PD4-Xjw8dl48PD5ePHZePnY8Xl5ePF48Xl48Pl4-PnY-Xjx2PnZ2PHZeXj4-PDw8PDw-PnY-XnY-Xj4-Pj52Pj5eXj5ePDw8Xjw8PHY-Pl4-PDw8PF52djw8Pl52PF4-dl48djw8PnY8Pl48XjxePF48Pj5eXl52dnY8dj5ednY-Xj48Xjx2Xj5edjx2Pj48Pjx2dnY8Xl4-PnY8XnY-Xj4-Pj48dl48dl5ePF5edjx2dnY8dj5eXjw8Pj48Xjx2XnY8XnZ2PnY-dnY-Xl48Pl5eXl4-Pl52Pjx2djw8PHY-XnZePj52Xj4-PDw8XnZedjw8Pj48PHZ2dnZ2PHZednY-dnZ2dj48dl52PF5eXj48dnZeXjw-Pjw-PjxePl5eXl52PnY-PD48dl48Pl52PD5eXjxeXj5eXl52dnY-PnZ2XnZePHY8dnZedj52Pj4-XnZeXnZ2Xjxedj52XnY-Pl52PnY8dl48Xl4-PHZ2dj4-PDw-Pjw-Pjx2PnY8Xjx2Pj4-PnZeXnZeXj5ePjw8dj48Xjw8Pj52PD5eXjw8PnZ2Xj4-dnZeXl52Pj4-XnZePjx2PDxePnY8dj48Pj4-Xj4-Xjw8Pj5ePjw8dnY8Xl4-Xl5edl5ePD4-PnZ2Pjw8PnY8Pjw8PD52PDw-Pj52PD52PD5ePHZ2XnY8Xl48PDx2Pl52Pj5eXj5ePjw8XnZ2PD48Pjw-dj5edj5ePD52Pj5eXl48Xl4-PnZ2PnY8PDx2Xj48PHY-PF52Pjw-djxePDxePD5ednY-Xj48Xl5eXl48PHZeXjw-dj4-PF48dl5eXnZ2Pl52PD5ePHY8dj52Pl4-PF48PF48Pj48Xl4-dnZePD5ePD52djw-PnY8dnZePj48Xl48Xj52PD48PnZ2PHY8Pj52Pjx2Xl5ePl5eXjw8dnZePjxeXnY-dj5ePF4-dl4-PDx2dnY-dl4-PHZ2PD48Xjw-PF4-XnY8Pjw8dl48PD48Pl5eXl48PF4-Pl4-XnZePnY-Xjw8Xj52dl52dl52PD5ePDxePnY8Xl48PHY8djw8PF4-dnZePj48PnY-Pjw-PHY-dj48dl4-PHZ2dj52djw8dnZ2PnZePDxedjxePD48PF52PnY8Pj52djw8dl4-dj52PDw-Pl52dl48Xl5ePF52Pj5ePHZ2Pl48dj4-PD52Pl5ePDx2Xjw-Pj4-PnZedj4-PD52Xj4-Xjw-Pl48XnZ2dl5eXjxedjw-PHZ2dl4-Xj52Pjw8dj4-XnY-djx2PnZePHY-dj5ePD52dnY-dnZ2Xl48PnZ2Pl5eXl5ePnY8PF52PD4-Pj48PDw-Pj48dnY-Pl52Xl52PHZePj4-Xj5edjxedj5edjw-dnY8Pjx2dnZedjw8PDx2PHZ2PnZ2XjxednZ2PF52PnZeXnZ2PF4-Pj5eXj4-Xl4-PD5ePj52PD4-Pl5ePDx2PF48PDw8PF5ePHZeXl48PD4-PDw8Xj5edl4-dnY8Pj4-Xl52Pjw8Pl5eXl48dnZ2PjxeXjw-Pj5ePjw8Xj4-PHY-Xjw-XnZePHZ2dnZePj5ePjw8Pj48Xjx2Xj4-dnZednY8Xj4-Pj48Xj5edjxePHY8Xl48XjxePjxePD4-Xjw-dl52PDw-dj52PD4-PDx2PF52PDw8XnY8djw-Pjx2PF48Xj4-dj52Pj48dl48dj48Pj4-Pj52XnY-PjxePF48dj4-PHZedj52PD52PHY-PDw8Pl5ePjw-Xl48XnZ2Xl48PnY-PD48PjxePl5edl52dl48Pjw-Pj4-dj48Pj5ePl48PF48djx2Xj52Xl48dj4-Pjw8Xl52dl5ePj48PF48dnZ2dnY-PjxePl4-Pl52djw-PDw-dj52Xjw8PF52PF5ePDxednY-djx2dnY-PF52PnZ2XnZ2dnY8Xj5edl48PDw8XnY8PDw-XnZ2dj5edj48PD4-djx2PF52Xjw-dj4-Xl52XnZ2Pj4-XnZeXj4-Xjw-PD48PDw8XnZ2Pj4-Pj52PnZePnY8Pj48PDw-XnZ2Pl5eXl48Xl5ePl5eXl4-Xl5edl52PjxePl4-Pj52PHY8XjxeXjw8XnY8PF48PnZ2dl5eXl52Xjw8PnZ2Pl5ePj4-PF5edjxePDw8djw-djw8Pjw-djw-PD5ePHY8PF4-Xl4-Pjw8dj5eXj48Xl52PF48dl48Xl48Pl48Pl52Xj4-Xl52XnZePD52PD5ePDw8Pl52XnY-Xjx2dnZ2PD52PDw-dnZePDw-dnY-Pj4-Xjx2Pjw-Pj52Xj48PD5edj4-PDw-Pl5edj48Xjw-PnZ2Xl5ePnZ2XjxeXnY-PHY-PnZ2dl52PF52PnY8PF5ePD52Xl5edl5ePj48dl4-PnZedl52djxePnZePF4-Xj52PHZePjx2dnZePl48PnY8PF4-PF5ePHZ2PnY-PnZ2PnZePj5ednZ2Pj52Xj5eXj52dnY-PnY-PDw-Pl5edj52PHY8Pjw8PDxeXnY8Xjw-XnY-Pjx2Xl5ePD4-dnZ2PnY-PDx2Pl5ePF52dnZ2XnY-dj5ednY-XnZ2Xl52Pjw8Pj5eXj4-dj4-Pl52PjxePnY8Xl48PnZ2PnY-dl5eXj4-Xl5ePjw8PDw-Pl4-Pl48XnY8XjxePD5ePjx2PDx2PnY8Pl4-Pl48PHZeXjx2XnZ2dnZ2Pj52Xj4-Xl5ePF5ePD48PD48Pjw-XnY-dnZ2Xj5eXj52PF5ePl48PF52Xl5ePjw-Pjw8djxeXl48PDw8Pj48Pj48PF5edj48dl48PF52PHY-PDw-Xjx2Pl4-XnY-dnY-Pjx2XjxePHY8djx2PjxeXl5ePj4-PF48Pjxedl52PDw8Xj52dl48dl4-Xl52Xj4-Pjw8PDxePD4-Pjx2Pj4-dnZePl5ePHZedj4-PnZePF48PnZ2Pl52Xl4-PDw8dj52PnY-Pjw-Pj52PF4-Xjw-Pl5ePHZePDxePHZePj48XnZePjw-PHY-PD48dl52dnY8PD52Pj4-PDw-PHY-djw-Pj48XjxeXnY8dj5ePDw-XnY-Xj5ePl5ePF5ePjxePj4-Pj48Xl4-dnY-XjxeXjw-PF4-XjxeXj48Xjx2PnZePj48Xj5eXl4-PnZedjxePj5ePHZePD5ePjw-PHY-Pl52PHZeXl5edjxednY-PF52Pj5eXl48Pl48XjxePnZ2XnY8PD52dj5ePD52Pl4-Xj52dl52PHZ2PF5eXnY8dj52PnZePF5eXnY-PHY8PDxeXjw-PF5ePj4-Pjw8Xl52PDxePnY8PHZ2Xl5ednZednZePHY-PD5edjx2Pj4-PHZ2XnY8dl4-Pj4-Xjw8PHZ2Xj4-dj5ePjw8Pjw8XjxePjw8dnZePnZePj48PnZePDw8PnZePjw-Pjw8Pj52Pjw-dl48dj48Pl52Pj4-PD48Pj4-XnZ2dl52PnZ2Pj4-Xl52Xj48PHY8Pj5eXl52Xl4-PDxedjw-PD48djw8djx2PD48PDx2XjxeXl48PnZeXnY8Xl48PF4-djw8dj48Xjw8PDw-Pjw-XnY-Xjw-XjxeXnZednZ2Pl5ePD5ePj48dl5ednZePD5ePD48PF5eXnY8Xl5ePj5eXnY-Xj5ePF4-dj48PF48Pl52PD48dnZednY8Pjw8PDw8PHY8PHY8PHZ2Xjw8XjxednZ2dj48dl52XnY8Pj4-dnZ2dnZePHZ2XjxePD52dj5ePD48PHY-PD52Xl48djw-Pj52dnZePjxePF4-dl5ePHY-Xjw-Pj5eXnZePHZ2PDw8PF4-PHY8PDw-djw8PHY8Pj5eXl4-Xj48PnY-XnZePl48dl5ePjxedl5ePF52Xl4-XnY-Pl5eXjw8Pjw-PDw8PnY-PjxePjw-Pj52dnZ2PnY-PnY-Xl5eXnY8Pjx2djxePHZedj4-Xl52djxePnZ2dj5edj4-Pjx2PHY8dl48Xj5eXjx2dnY8dnY8dj4-XnZ2Pl48PF48Xjx2PnZePHZ2Xl5edj52djx2Pjx2Pjx2Pl48dj4-dnY8PnY-Xl4-dl5eXjw-djw-dl52PD5ePD48dj48Xj5ePHZedj48PF52XnZedjw8dj48PF5ePF52dj5ePF52Pjw-dj4-PHZedl4-Pjw-PD48PDx2PD52PF52dj52PHY8PD5ednZ2dnZePDw8Xjx2dj48PD48PnZePF52PDw8Xj52PnY8dl48PF4-djw8Xjx2Pjw8PF4-dnY-dj5ePF5edj4-Pj48PnZ2Pj52dj52dnY8Pl5ePD5edl48PnZ2djxeXl52dj52Pjw8PDx2dl52Pjx2XjxePDw8Pjx2PD5ePjw8Pl4-djxeXjw8PnY-PnY8PD4-PF5ePDw8XjxednZeXj52PnY8Pl5ePj5edl52dnY-XnZePnY-PnY-dj52Pj52dl48Pjw8PDw-dl5ePnZ2PF5edj4-djx2djxePj5ePD5eXnY8Pjx2dl48Pjx2Pjx2PDx2XnY8Xl48XnZedjw-djw8Pjx2dnY-PDw8XjxeXjw8Pj5edj4-Pl52Pj4-djw-Pl4-PDw8Pjw-PDw8djx2djxePD52Xl52Xl4-Xjw8Xl5edl4-Xjw8Xj5ePl4-Pj4-djx2PHY8PnZ2PDx2dl48PF48dnY-Xl48Xjw8Pj48XnY-PD48Pl48dj48dl4-XnY-XjxePl5ePjx2Pjw8Xjx2Xl48PF4-PD48dj52PD4-Pjw8Xj48djxednZ2Xjw8PD4-PDw-XnZeXj48dnY-dnY8Pl4-Xj52djw-dl48Xjw-dnY-PDw-Xjx2PHZ2PF48Xjw-PF52djw8Xj4-PnY8Pj48PD4-Pl5eXl48PF52Pj52PHZ2Pl5ePnY8djx2dl4-PDw-PD4-PnY-Pl5edjxedl5ePj52Xjw-PnZePj48XjxeXnY8djw-PDw-PD4-Xjw-PjxedjxeXl5ePjw-Xj52dj4-XnZ2PDw-djw8PDw8PD48PDw-PDw-Pjx2PjxeXl48Pj52PF4-PF52dnY8Pl4-Xl52Pl48dj48XnZednZePDw-djw8PDx2Pl52dj4-dj52djw8Xj5ePD4-dnZ2Xjx2PD48Pj48Pl5eXl52dnZ2dnZ2PDw-djxePjxeXj52dl5ePHY8PF5ePHZ2djx2PHY8PD4-PDw-PHZeXj4-PF48Pl52XnZ2PDx2PHY8Pj48PD4-Pj4-XnZ2PD48djw-dj48dj52Pj48djx2XnZ2dnZ2PD48PnY-PnY8Pjw8PF5ePD5ePF5ePHY-dl48dnY-XnZ2Xjw-Xjw8Xjx2dj48djx2Pj52Pl48PnZePDx2Xjx2Pl52PD4-PHY-Pj4-Xjw8Xl5edjxePD4-PF48Pjx2Pj52dl4-XjxePF4-PnZePl5eXl4-dnZ2dnY-XnY8Xj48Xl48Xl4-XjxeXl5eXl5ePnY-PnZ2PnZeXl52Xl5ePD52PjxePj4-dj5ePl4-Xj52djx2djxeXj4-Xj4-PnY8PnY-PDxePDx2Xj5ePj4-Pl5ePjxeXjx2PDw8PD4-dj52XnZeXjw-Pjx2PF48PDw8dl5eXl48djw8PF4-dj5eXjx2djxeXl5eXnY-XnZePHY-PD4-Xl4-XnY-Xj5ednZedj52PnZePnY-Xj4-Xl5eXj4-Xj4-Xj48Pj48dj52Pj4-PDxedl52Xj5ePl4-PnZ2Pjw8Xj52PHY8dl48PD4-XnY8PF52PDxePjxePj5ePHY-Xj52dj52Pl5eXj52Xl48XjxeXj52dj5eXj48dj4-XnY-XnY8PF5eXjw8XnZePl48PF4-dnZePj5ePF52Pjw8PnY-PF5eXjxeXj4-dnY-XnZ2Pj48Xjw8PF4-dnZedj52PF48PDxePF48PD48Xl4-Pj52XjxeXl4-Xjw-PF52Pj5ePDx2PF52Pj52XjxePF48Xl5ePHZePjw8dnZ2Xjxedl52dl52djx2PDx2PF48Pl52Pl5eXjxeXnY8djx2Pjw8PF48Pl5eXl52PnZedl52XnY8dj48dj4-XnY-PHZ2Xl5edj4-PDx2XnZ2dnY8PDxedjw8PjxePl48dl5edjw-dnZ2dl52djw-XnY8Pjw-Xl48Pj52dnY8Xj4-PHZePDw-dj52PD5edl4-dl4-Pjw8Pj5eXjxedjw-Pl4-Xj48Pj5ePHY8dl5ePF52Pjx2Xjx2PD48PjxePDw-PHZedjw8PnZ2PHY8djxePj4-PD52dl5ePD48PHY8Xl48PF48PjxeXl4-Xj4-Pl48Xj4-Pl4-PjxeXl48XnZeXl52XnZedj52PnY-PHZ2Pj48dnZ2PDx2Pjw-PF5ePl52PHY-Pjx2PjxePjxePDw-dl52dl52PjxednY-Xj4-djx2dj48XjxeXnY8Xl52djx2djx2PHY-dj48djx2djw8Pl5edl5edjw8PF48PnZeXl48Pjw-Pj48Xj52Xl5edl52djw8PF4-PnY-PF4-dl48Pj4-Pl48Pl5ednZ2Xl48PjxePl5ePD48Pl52dnZeXjx2dl4-dnZeXl5edjw-dnY8Xl5edjw8Pj48PHZ2dnZ2PnY-Xl5ednY-Pjx2Pjx2PD52dnZ2PHZePjxePD5ePl48PnY-dj52XnZ2dnY8Pjxedj4-Pl5ePj48dnZ2PD5ePl52Xjx2dnY-dl52dl52dj48Pj48PnZeXnZednY8XnY-dnY-PnY8dj48Xjw8XnY8Pj5ednZePHY-dj48dj52Pl52Pl48dj5ePDxePnZ2PnY8XjxednZePF4-PDw8djw8Xl52djx2dnY-PD52PnY8dnZePD48PjxednZ2Pj52djxeXl52Pjxedj48PF4-Xl52Pl48Pj48djw-Pl5ePDw8dj48Pl4-Xj48dnZ2djw-Xjw8PD48PDxePD4-dl52dl4-PjxednZeXj5ePHZePHY-PjxeXj4-Pl52Pl52PD5edjw-PF4-PHZ2PnZeXl48Xj4-Xjw8XjxePjw8PF5ePHY8PF52djxePD52PF48PF5ePHY8dnY8PD48djx2Xjw-Xjw-dj4-djxedj52PD5eXnZ2djw-dnZedl48Pjx2XnZ2Xjxedl52Pjw-Xj48dl48Pj5eXl48Pj52dl48dj5eXnY-PHY8Xj5eXl5eXl4-PD4-dnZ2PDw-PD48djxePnY8PnZedjw8PDw-dl4-Pj4-XnY-Xl48dl4-dj48dl48Xl52PDw8PHY8PDw-XnY8Xj5edj52Xl4-dl5ednZ2PnZ2PD5ePnY-PHY8Pl48dnY-PD4-Pjw8Xj4-Pjw8dj52Xl48Xjw8PDx2Xjw-Pj52PDw8XnZednY8Pl52PnY8PDw8Pl5ePj48dj48PnY8dj48Xl4-Pjw-Xj5ePnY-Pj48dj5ednZ2djw-PD48Xj4-XnZePjw8Pl52PD48PjxePjw8PD52Xl4-dj5ePnZePHZednY8Pj48XnZ2Xl4-Xl4-PHZ2PDw-dj52Xl4-Pjx2Xj5ePF48Pj4-dnY8Pl4-dj52Xjw-djxePDx2Pj4-Xjw-dl4-dj4-dnZeXjw-PnY8djw8Xjw-dj52XjxeXl4-dl5ePnY-dj52djxePHY-dl5ePjw8PHY8Pjw-Xl48PnY-dj5eXnY-dj52XnY-Pl48dl52Pj48Pl5ePl48Pj4-XnZ2Xj48dl48Xj52Xj5edj48Xj5eXl52dl5edjw-dnY8Pj5ePjw8XnY-XnZePj52Pl52Xjw8Xl5ednY8PHZ2dj5ednZedjw8PHZeXjw8Pjx2djw-Pl5ednY-Xl5ednY-Pjw-PHY-djxedl4-Pj52dl4-PD4-PHY8XnY8Pl4-PHY8Xl5eXj4-PF48PnY-XnY8XnZ2PnY-djxePD52PnY-Xjx2dj52PF4-dnZ2PHZePHZ2PHZ2PD52Pl4-PHZedjw-Pj4-PnY-Pjxedjw-dj5edj48dl52XnZ2PD5ePHZ2dl4-Pjx2Xjx2dnZeXjxednZ2XnZePD4-PHY-dl5edjw-PD52Xl5edjw8PF4-PHY8PDw-Pjw8dnY8PD48dnZ2XnY-PnZedjx2Xj4-Pjw8djw-XnY-PD52djw8dj52XnZ2PnZedjxePHZ2PD48Pjxedj5ePHZ2PnZeXj4-Xl5ePjx2djw-PF4-Pj5ePHZePDxeXj5ePnZ2Xj48djx2dnY-Xl4-Pj5ePjw8dnY-dnY-Xjw-Pl5ePjxedj48PD5ePDw8dl4-Xg).
### Explanation
The code traces the path using unit steps in the complex plane. Then it counts how many times each position was visited, and outputs how many positions were visited an odd number of times.
```
J % Push the imaginary unit, 1j
j % Input string
11\ % Modulo 11. This gives 7 6 5 8 for > ^ < v
^ % 1j raised to those numbers, element-wise. This gives -1j for >, -1 for ^,
% 1j for < and 1 for v. So it gives the displacements in a "transposed"
% complex plane
Ys % Cumulative sum. This transforms displacements into positions
8#u % Count of occurrences of each unique position
o % 1 if odd, 0 if even
s % Sum. Implicitly display
```
[Answer]
# Python, 68 bytes
**25 bytes thanks to Sp3000.**
**2 bytes thanks to Luis Mendo's idea of taking modulus with 11.**
**17 bytes thanks to xnor.**
```
d=set()
p=0
for c in input():p+=1j**(ord(c)%11);d^={p}
print(len(d))
```
[Ideone it!](http://ideone.com/NYFa9b)
[Answer]
# Java 8, ~~169~~ ~~130~~ 127 bytes
Thanks to Leaky Nun for saving ~~29~~ 32 bytes.
```
s->{int l=s.length,d=2*l+1,p=l*d+d,r=0,m[]=new int[d*d];for(char c:s){p+=c<61?-1:c<63?1:c<95?-l:l;m[p]^=2;r+=m[p]-1;}return r;}
```
Ungolfed (sorta):
```
public static int f(char[] s) {
int l = s.length, d = 2*l+1, p=l*d+d, r = 0;
int[] m = new int[d*d];
for(char c : s) {
p += c<61 ? -1 : c<63 ? 1 : c<95 ? -l : l;
m[p] ^= 2;
r += m[p] - 1;
}
return r;
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
A port of [Luis Mendo's answer in MATL](https://codegolf.stackexchange.com/a/89961/48934)
```
O%11*@ı+\œ^/L
```
[Try it online!](http://jelly.tryitonline.net/#code=TyUxMSpAxLErXMWTXi9M&input=&args=Jz4-PjxePj4-XnZ2PjxeXnZePDw8Pj5ePD4-XjxePl48PF5edl48dl4-Pl48PD48PD5edjxeXl52dj52PjxePj5ePF48dj48XnY8Xjw8Xl52Pjw-Pl52PF4-XnY8dnZ2PDw8dl52dj4-XnZ2Pl5ePD4-dnY-XjxePnZ2PD52XjxedjxeXjx2Xl5ePDxePjw-PD5edj52dnY8XnZ2djx2dj48dnY8Xl52Xl48Xl4-Pj48PDw-Xjw-Pj48Xjw8PD4-PD5edj48Xl52djw-Pj48Xl5ePF4-Pj4-djx2Xj48PD52PHY8dl48PF4-PHZeXj48PnY-Xjw-Xl5ednZ2PHZePl5eXl52PnY8dj4-PnZeXjx2PHZ2Pj48PD5ednY-PDx2djw8Pl5edj4-djxeXnY-Pjx2PHY8PD5eXnZ2Pj5edj52PnY8Pl4-XnY8Pj4-PD52PnY8PHY8Xjw-Pj52dj4-dj5ePD52dl52Pjw-PF52Xj52PF5ePnY8XnY-PnZePl4-PnY-dj5ePl48Xl4-dnY-Pl52djxePjw-Xj48PHZePD48PF48Xj5eXnZ2Xjw8Xl48Xl52PHY8Pl4-dj4-Pj4-PnZ2PDx2Pl4-dnZePl4-PF48Xl4-PDx2dnZ2PnZ2djw-PDw-PHZednY-PHZeXjw-Xj4-PF52djw-PD5ePnZ2Pj4-dnZednY8PF52Xl48PHZeXj5ePnZ2djw-PDx2Pl4-Xj52PHY-XjxeXl5ePF4-Xj4-PD4-Xl52djw-djxePnY-PHY8dl4-PnY8XnY8dnY-dl4-djx2XjxeXl5edjxePF48PHY8PDx2PHZeXj52dl4-Pjw8PHY-Pl5eXj5ePF4-Pj52XnY-PF5ednZePj48Xl52djx2djx2Xj48Pj5ePjw8PD4-Xl52XnY8PHZePHZ2Xl5ePj48Pj5edl5eXj4-Xj5ePDxePnY-Xl52Pj48PnY-Xj52dl5ePHZ2dnY8Pjxedj5ePjw8Pj4-PF48XnZePDx2dnZedjw8PDw8Pjw-PDw-PD48PHY-djx2PnY-PF52Xl52dnY-Pjw-Xj5ePl52PDx2dl5eXnZednY-PHY-PD48djx2PDw-Pj52PF48XnY8PD5edjw8XnY8Pjw-dj4-Xl4-Xjx2Xjw8XnZeXl52dj4-PHZePHY-XnY-PF48Pj4-Pl5ePHZ2PD5eXj5ePnZedl5ePj48Pl5ePF52Xjx2PDx2PF48PF5ednY-dj5ePHZ2PDxeXnZednZePl5ePD52Pl4-Xjw-dnY-PHY-Pj48PD48PHZ2Xl48dnY8Pj5edj5ePDx2dj5ePjw8Pl48dj52Pjw8dl48djw-PHY-XjxePF4-PF5eXl4-Pj5ePD5eXj48Pj52Xjx2dl48Xjw8dnZ2dj4-PnZedj4-Xj52Xj48PD4-djw-Pl4-Pjx2dnZ2djw8dnZ2djx2Pl52PHZ2Xjw-Pjw8Pjx2Xl48Xjx2Pl52PF48PD5edjx2Xjw-djw8Pl48PHZ2dj48Xj48Xl5ePD4-dl48PD52dj48Xl5ePj48Xj52XnY-djx2Xj4-dj4-dj52djw8djw8dnZ2Xl5ePl48dl5ePF48djxePD4-dl48PHY-PnZePjx2PHZ2dnZ2Xl5ePHZeXjw-PHY8PF4-Pl4-PF48dl52Xl4-Pjx2Pjw-dj5ePHZ2dnY-PDx2Xl52Xj5ePnY-Pjw-Xl52PnZePnZ2Xj52PF48PF52dl4-dnZePHY-Xjx2Xjw-XnY-dl4-dl48PD5eXjxePl5ePnZ2Xj4-dnY-dj52dnY-PD5edjw8PDx2Xj52Xl52PD48djx2Pl48Xj48Xj48PHY8Pj48PD52Xl4-Pj48PD48Pj4-PDw-Pjx2Xl4-PjxePj48Xjw-dl5ednZ2PnY8Xjw8dnZePnZ2Xj48PD52Pjw-Xjw-dl5edj5ePnZePD5ePjx2Pl4-PDxedjx2Xl48dj4-PF5ePj5ePF48XnY8dj5ePl48Xjx2Pjw-PD4-Pj48Pl48Xjx2PnY8dl4-dj48PnZePnZePDw-PF48Pj52PF52dl5eXj5ePDw8PD5ePl48PjxednZ2Pl5ePHZedj52PnZedj52Pj52dj5ePjw-XnZ2Pl48djx2Xjw-dnZePHY8Pjw-Xj4-dnZ2Pjw-Pl48PHZePDw-Xjx2Xj52PF5eXjxePF5ePD5ePj52Pl48dj52djx2Xl4-Pjw8PDw8Pj52Pl52Pl4-Pj4-dj4-Xl4-Xjw8PF48PDx2Pj5ePjw8PDxednY8PD5edjxePnZePHY8PD52PD5ePF48XjxePD4-Xl5ednZ2PHY-XnZ2Pl4-PF48dl4-XnY8dj4-PD48dnZ2PF5ePj52PF52Pl4-Pj4-PHZePHZeXjxeXnY8dnZ2PHY-Xl48PD4-PF48dl52PF52dj52PnZ2Pl5ePD5eXl5ePj5edj48dnY8PDx2Pl52Xj4-dl4-Pjw8PF52XnY8PD4-PDx2dnZ2djx2XnZ2PnZ2dnY-PHZedjxeXl4-PHZ2Xl48Pj48Pj48Xj5eXl5edj52Pjw-PHZePD5edjw-Xl48Xl4-Xl5ednZ2Pj52dl52Xjx2PHZ2XnY-dj4-Pl52Xl52dl48XnY-dl52Pj5edj52PHZePF5ePjx2dnY-Pjw8Pj48Pj48dj52PF48dj4-Pj52Xl52Xl4-Xj48PHY-PF48PD4-djw-Xl48PD52dl4-PnZ2Xl5edj4-Pl52Xj48djw8Xj52PHY-PD4-Pl4-Pl48PD4-Xj48PHZ2PF5ePl5eXnZeXjw-Pj52dj48PD52PD48PDw-djw8Pj4-djw-djw-Xjx2dl52PF5ePDw8dj5edj4-Xl4-Xj48PF52djw-PD48PnY-XnY-Xjw-dj4-Xl5ePF5ePj52dj52PDw8dl4-PDx2Pjxedj48PnY8Xjw8Xjw-XnZ2Pl4-PF5eXl5ePDx2Xl48PnY-PjxePHZeXl52dj5edjw-Xjx2PHY-dj5ePjxePDxePD4-PF5ePnZ2Xjw-Xjw-dnY8Pj52PHZ2Xj4-PF5ePF4-djw-PD52djx2PD4-dj48dl5eXj5eXl48PHZ2Xj48Xl52PnY-XjxePnZePjw8dnZ2PnZePjx2djw-PF48PjxePl52PD48PHZePDw-PD5eXl5ePDxePj5ePl52Xj52Pl48PF4-dnZednZedjw-Xjw8Xj52PF5ePDx2PHY8PDxePnZ2Xj4-PD52Pj48Pjx2PnY-PHZePjx2dnY-dnY8PHZ2dj52Xjw8XnY8Xjw-PDxedj52PD4-dnY8PHZePnY-djw8Pj5ednZePF5eXjxedj4-Xjx2dj5ePHY-Pjw-dj5eXjw8dl48Pj4-Pj52XnY-Pjw-dl4-Pl48Pj5ePF52dnZeXl48XnY8Pjx2dnZePl4-dj48PHY-Pl52PnY8dj52Xjx2PnY-Xjw-dnZ2PnZ2dl5ePD52dj5eXl5eXj52PDxedjw-Pj4-PDw8Pj4-PHZ2Pj5edl5edjx2Xj4-Pl4-XnY8XnY-XnY8PnZ2PD48dnZ2XnY8PDw8djx2dj52dl48XnZ2djxedj52Xl52djxePj4-Xl4-Pl5ePjw-Xj4-djw-Pj5eXjw8djxePDw8PDxeXjx2Xl5ePDw-Pjw8PF4-XnZePnZ2PD4-Pl5edj48PD5eXl5ePHZ2dj48Xl48Pj4-Xj48PF4-Pjx2Pl48Pl52Xjx2dnZ2Xj4-Xj48PD4-PF48dl4-PnZ2XnZ2PF4-Pj4-PF4-XnY8Xjx2PF5ePF48Xj48Xjw-Pl48PnZedjw8PnY-djw-Pjw8djxedjw8PF52PHY8Pj48djxePF4-PnY-dj4-PHZePHY-PD4-Pj4-dl52Pj48XjxePHY-Pjx2XnY-djw-djx2Pjw8PD5eXj48Pl5ePF52dl5ePD52Pjw-PD48Xj5eXnZednZePD48Pj4-PnY-PD4-Xj5ePDxePHY8dl4-dl5ePHY-Pj48PF5ednZeXj4-PDxePHZ2dnZ2Pj48Xj5ePj5ednY8Pjw8PnY-dl48PDxedjxeXjw8XnZ2PnY8dnZ2Pjxedj52dl52dnZ2PF4-XnZePDw8PF52PDw8Pl52dnY-XnY-PDw-PnY8djxedl48PnY-Pl5edl52dj4-Pl52Xl4-Pl48Pjw-PDw8PF52dj4-Pj4-dj52Xj52PD4-PDw8Pl52dj5eXl5ePF5eXj5eXl5ePl5eXnZedj48Xj5ePj4-djx2PF48Xl48PF52PDxePD52dnZeXl5edl48PD52dj5eXj4-PjxeXnY8Xjw8PHY8PnY8PD48PnY8Pjw-Xjx2PDxePl5ePj48PHY-Xl4-PF5edjxePHZePF5ePD5ePD5edl4-Pl5edl52Xjw-djw-Xjw8PD5edl52Pl48dnZ2djw-djw8PnZ2Xjw8PnZ2Pj4-Pl48dj48Pj4-dl4-PDw-XnY-Pjw8Pj5eXnY-PF48Pj52dl5eXj52dl48Xl52Pjx2Pj52dnZedjxedj52PDxeXjw-dl5eXnZeXj4-PHZePj52XnZednY8Xj52XjxePl4-djx2Xj48dnZ2Xj5ePD52PDxePjxeXjx2dj52Pj52dj52Xj4-XnZ2dj4-dl4-Xl4-dnZ2Pj52Pjw8Pj5eXnY-djx2PD48PDw8Xl52PF48Pl52Pj48dl5eXjw-PnZ2dj52Pjw8dj5eXjxednZ2dl52PnY-XnZ2Pl52dl5edj48PD4-Xl4-PnY-Pj5edj48Xj52PF5ePD52dj52PnZeXl4-Pl5eXj48PDw8Pj5ePj5ePF52PF48Xjw-Xj48djw8dj52PD5ePj5ePDx2Xl48dl52dnZ2dj4-dl4-Pl5eXjxeXjw-PDw-PD48Pl52PnZ2dl4-Xl4-djxeXj5ePDxedl5eXj48Pj48PHY8Xl5ePDw8PD4-PD4-PDxeXnY-PHZePDxedjx2Pjw8Pl48dj5ePl52PnZ2Pj48dl48Xjx2PHY8dj48Xl5eXj4-PjxePD48XnZedjw8PF4-dnZePHZePl5edl4-Pj48PDw8Xjw-Pj48dj4-PnZ2Xj5eXjx2XnY-Pj52XjxePD52dj5edl5ePjw8PHY-dj52Pj48Pj4-djxePl48Pj5eXjx2Xjw8Xjx2Xj4-PF52Xj48Pjx2Pjw-PHZednZ2PDw-dj4-Pjw8Pjx2PnY8Pj4-PF48Xl52PHY-Xjw8Pl52Pl4-Xj5eXjxeXj48Xj4-Pj4-PF5ePnZ2Pl48Xl48PjxePl48Xl4-PF48dj52Xj4-PF4-Xl5ePj52XnY8Xj4-Xjx2Xjw-Xj48Pjx2Pj5edjx2Xl5eXnY8XnZ2Pjxedj4-Xl5ePD5ePF48Xj52dl52PDw-dnY-Xjw-dj5ePl4-dnZedjx2djxeXl52PHY-dj52XjxeXl52Pjx2PDw8Xl48PjxeXj4-Pj48PF5edjw8Xj52PDx2dl5eXnZ2XnZ2Xjx2Pjw-XnY8dj4-Pjx2dl52PHZePj4-Pl48PDx2dl4-PnY-Xj48PD48PF48Xj48PHZ2Xj52Xj4-PD52Xjw8PD52Xj48Pj48PD4-dj48PnZePHY-PD5edj4-Pjw-PD4-Pl52dnZedj52dj4-Pl5edl4-PDx2PD4-Xl5edl5ePjw8XnY8Pjw-PHY8PHY8djw-PDw8dl48Xl5ePD52Xl52PF5ePDxePnY8PHY-PF48PDw8Pj48Pl52Pl48Pl48Xl52XnZ2dj5eXjw-Xj4-PHZeXnZ2Xjw-Xjw-PDxeXl52PF5eXj4-Xl52Pl4-XjxePnY-PDxePD5edjw-PHZ2XnZ2PD48PDw8PDx2PDx2PDx2dl48PF48XnZ2dnY-PHZedl52PD4-PnZ2dnZ2Xjx2dl48Xjw-dnY-Xjw-PDx2Pjw-dl5ePHY8Pj4-dnZ2Xj48XjxePnZeXjx2Pl48Pj4-Xl52Xjx2djw8PDxePjx2PDw8PnY8PDx2PD4-Xl5ePl4-PD52Pl52Xj5ePHZeXj48XnZeXjxedl5ePl52Pj5eXl48PD48Pjw8PD52Pj48Xj48Pj4-dnZ2dj52Pj52Pl5eXl52PD48dnY8Xjx2XnY-Pl5ednY8Xj52dnY-XnY-Pj48djx2PHZePF4-Xl48dnZ2PHZ2PHY-Pl52dj5ePDxePF48dj52Xjx2dl5eXnY-dnY8dj48dj48dj5ePHY-PnZ2PD52Pl5ePnZeXl48PnY8PnZedjw-Xjw-PHY-PF4-Xjx2XnY-PDxedl52XnY8PHY-PDxeXjxednY-Xjxedj48PnY-Pjx2XnZePj48Pjw-PDw8djw-djxednY-djx2PDw-XnZ2dnZ2Xjw8PF48dnY-PDw-PD52Xjxedjw8PF4-dj52PHZePDxePnY8PF48dj48PDxePnZ2PnY-XjxeXnY-Pj4-PD52dj4-dnY-dnZ2PD5eXjw-XnZePD52dnY8Xl5ednY-dj48PDw8dnZedj48dl48Xjw8PD48djw-Xj48PD5ePnY8Xl48PD52Pj52PDw-PjxeXjw8PF48XnZ2Xl4-dj52PD5eXj4-XnZednZ2Pl52Xj52Pj52PnY-dj4-dnZePD48PDw8PnZeXj52djxeXnY-PnY8dnY8Xj4-Xjw-Xl52PD48dnZePD48dj48djw8dl52PF5ePF52XnY8PnY8PD48dnZ2Pjw8PF48Xl48PD4-XnY-Pj5edj4-PnY8Pj5ePjw8PD48Pjw8PHY8dnY8Xjw-dl5edl5ePl48PF5eXnZePl48PF4-Xj5ePj4-PnY8djx2PD52djw8dnZePDxePHZ2Pl5ePF48PD4-PF52Pjw-PD5ePHY-PHZePl52Pl48Xj5eXj48dj48PF48dl5ePDxePjw-PHY-djw-Pj48PF4-PHY8XnZ2dl48PDw-Pjw8Pl52Xl4-PHZ2PnZ2PD5ePl4-dnY8PnZePF48PnZ2Pjw8Pl48djx2djxePF48PjxednY8PF4-Pj52PD4-PDw-Pj5eXl5ePDxedj4-djx2dj5eXj52PHY8dnZePjw8Pjw-Pj52Pj5eXnY8XnZeXj4-dl48Pj52Xj4-PF48Xl52PHY8Pjw8Pjw-Pl48Pj48XnY8Xl5eXj48Pl4-dnY-Pl52djw8PnY8PDw8PDw-PDw8Pjw8Pj48dj48Xl5ePD4-djxePjxednZ2PD5ePl5edj5ePHY-PF52XnZ2Xjw8PnY8PDw8dj5ednY-PnY-dnY8PF4-Xjw-PnZ2dl48djw-PD4-PD5eXl5ednZ2dnZ2djw8PnY8Xj48Xl4-dnZeXjx2PDxeXjx2dnY8djx2PDw-Pjw8Pjx2Xl4-PjxePD5edl52djw8djx2PD4-PDw-Pj4-Pl52djw-PHY8PnY-PHY-dj4-PHY8dl52dnZ2djw-PD52Pj52PD48PDxeXjw-XjxeXjx2PnZePHZ2Pl52dl48Pl48PF48dnY-PHY8dj4-dj5ePD52Xjw8dl48dj5edjw-Pjx2Pj4-Pl48PF5eXnY8Xjw-PjxePD48dj4-dnZePl48XjxePj52Xj5eXl5ePnZ2dnZ2Pl52PF4-PF5ePF5ePl48Xl5eXl5eXj52Pj52dj52Xl5edl5eXjw-dj48Xj4-PnY-Xj5ePl4-dnY8dnY8Xl4-Pl4-Pj52PD52Pjw8Xjw8dl4-Xj4-Pj5eXj48Xl48djw8PDw-PnY-dl52Xl48Pj48djxePDw8PHZeXl5ePHY8PDxePnY-Xl48dnY8Xl5eXl52Pl52Xjx2Pjw-Pl5ePl52Pl4-XnZ2XnY-dj52Xj52Pl4-Pl5eXl4-Pl4-Pl4-PD4-PHY-dj4-Pjw8XnZedl4-Xj5ePj52dj48PF4-djx2PHZePDw-Pl52PDxedjw8Xj48Xj4-Xjx2Pl4-dnY-dj5eXl4-dl5ePF48Xl4-dnY-Xl4-PHY-Pl52Pl52PDxeXl48PF52Xj5ePDxePnZ2Xj4-Xjxedj48PD52PjxeXl48Xl4-PnZ2Pl52dj4-PF48PDxePnZ2XnY-djxePDw8XjxePDw-PF5ePj4-dl48Xl5ePl48Pjxedj4-Xjw8djxedj4-dl48XjxePF5eXjx2Xj48PHZ2dl48XnZednZednY8djw8djxePD5edj5eXl48Xl52PHY8dj48PDxePD5eXl5edj52XnZedl52PHY-PHY-Pl52Pjx2dl5eXnY-Pjw8dl52dnZ2PDw8XnY8PD48Xj5ePHZeXnY8PnZ2dnZednY8Pl52PD48Pl5ePD4-dnZ2PF4-Pjx2Xjw8PnY-djw-XnZePnZePj48PD4-Xl48XnY8Pj5ePl4-PD4-Xjx2PHZeXjxedj48dl48djw-PD48Xjw8Pjx2XnY8PD52djx2PHY8Xj4-Pjw-dnZeXjw-PDx2PF5ePDxePD48Xl5ePl4-Pj5ePF4-Pj5ePj48Xl5ePF52Xl5edl52XnY-dj52Pjx2dj4-PHZ2djw8dj48PjxeXj5edjx2Pj48dj48Xj48Xjw8PnZednZedj48XnZ2Pl4-PnY8dnY-PF48Xl52PF5ednY8dnY8djx2PnY-PHY8dnY8PD5eXnZeXnY8PDxePD52Xl5ePD48Pj4-PF4-dl5eXnZednY8PDxePj52PjxePnZePD4-Pj5ePD5eXnZ2dl5ePD48Xj5eXjw-PD5ednZ2Xl48dnZePnZ2Xl5eXnY8PnZ2PF5eXnY8PD4-PDx2dnZ2dj52Pl5eXnZ2Pj48dj48djw-dnZ2djx2Xj48Xjw-Xj5ePD52PnY-dl52dnZ2PD48XnY-Pj5eXj4-PHZ2djw-Xj5edl48dnZ2PnZednZednY-PD4-PD52Xl52XnZ2PF52PnZ2Pj52PHY-PF48PF52PD4-XnZ2Xjx2PnY-PHY-dj5edj5ePHY-Xjw8Xj52dj52PF48XnZ2XjxePjw8PHY8PF5ednY8dnZ2Pjw-dj52PHZ2Xjw-PD48XnZ2dj4-dnY8Xl5edj48XnY-PDxePl5edj5ePD4-PHY8Pj5eXjw8PHY-PD5ePl4-PHZ2dnY8Pl48PDw-PDw8Xjw-PnZednZePj48XnZ2Xl4-Xjx2Xjx2Pj48Xl4-Pj5edj5edjw-XnY8PjxePjx2dj52Xl5ePF4-Pl48PF48Xj48PDxeXjx2PDxednY8Xjw-djxePDxeXjx2PHZ2PDw-PHY8dl48Pl48PnY-PnY8XnY-djw-Xl52dnY8PnZ2XnZePD48dl52dl48XnZedj48Pl4-PHZePD4-Xl5ePD4-dnZePHY-Xl52Pjx2PF4-Xl5eXl5ePjw-PnZ2djw8Pjw-PHY8Xj52PD52XnY8PDw8PnZePj4-Pl52Pl5ePHZePnY-PHZePF5edjw8PDx2PDw8Pl52PF4-XnY-dl5ePnZeXnZ2dj52djw-Xj52Pjx2PD5ePHZ2Pjw-Pj48PF4-Pj48PHY-dl5ePF48PDw8dl48Pj4-djw8PF52XnZ2PD5edj52PDw8PD5eXj4-PHY-PD52PHY-PF5ePj48Pl4-Xj52Pj4-PHY-XnZ2dnY8Pjw-PF4-Pl52Xj48PD5edjw-PD48Xj48PDw-dl5ePnY-Xj52Xjx2XnZ2PD4-PF52dl5ePl5ePjx2djw8PnY-dl5ePj48dl4-XjxePD4-PnZ2PD5ePnY-dl48PnY8Xjw8dj4-Pl48PnZePnY-PnZ2Xl48Pj52PHY8PF48PnY-dl48Xl5ePnZeXj52PnY-dnY8Xjx2PnZeXj48PDx2PD48Pl5ePD52PnY-Xl52PnY-dl52Pj5ePHZedj4-PD5eXj5ePD4-Pl52dl4-PHZePF4-dl4-XnY-PF4-Xl5ednZeXnY8PnZ2PD4-Xj48PF52Pl52Xj4-dj5edl48PF5eXnZ2PDx2dnY-XnZ2XnY8PDx2Xl48PD48dnY8Pj5eXnZ2Pl5eXnZ2Pj48Pjx2PnY8XnZePj4-dnZePjw-Pjx2PF52PD5ePjx2PF5eXl4-PjxePD52Pl52PF52dj52PnY8Xjw-dj52Pl48dnY-djxePnZ2djx2Xjx2djx2djw-dj5ePjx2XnY8Pj4-Pj52Pj48XnY8PnY-XnY-PHZedl52djw-Xjx2dnZePj48dl48dnZ2Xl48XnZ2dl52Xjw-Pjx2PnZeXnY8Pjw-dl5eXnY8PDxePjx2PDw8Pj48PHZ2PDw-PHZ2dl52Pj52XnY8dl4-Pj48PHY8Pl52Pjw-dnY8PHY-dl52dj52XnY8Xjx2djw-PD48XnY-Xjx2dj52Xl4-Pl5eXj48dnY8PjxePj4-Xjx2Xjw8Xl4-Xj52dl4-PHY8dnZ2Pl5ePj4-Xj48PHZ2PnZ2Pl48Pj5eXj48XnY-PDw-Xjw8PHZePl4n)
```
O%11*@ı+\œ^/L
O convert to codepoint
%11 modulo 11
*@ı power of i (imaginary unit)
+\ cumulative sum
œ^/ reduce by multiset symmetric difference
L length
```
Credits of the `œ^/` trick to [Dennis](https://codegolf.stackexchange.com/a/78303/48934)
[Answer]
# Perl, 49 bytes
Includes +1 for `-p`
Run with the control string on STDIN
```
./lights.pl <<< "<<>"
```
`lights.pl`:
```
#!/usr/bin/perl -p
$\-=1-($a{$x+=/</-/>/,$y+=/\^/-/v/}^=2)for/./g}{
```
If input is restricted to 10000 bytes this reduces to `44+1`:
```
$\+=$#{$x+=/</-/>/.e5+/\^/-/v/}*=-1for/./g}{
```
[Answer]
# TSQL, ~~238~~ ~~235~~ ~~203~~ 191 bytes
Creating a table in memory using recursive SQL. Selecting and calculating from that table(one line code).
Golfed:
```
DECLARE @ varchar(max)= 'v>v<';
WITH C as(SELECT 0 a,b=1UNION ALL SELECT
a+POWER(CHARINDEX(SUBSTRING(@,b,1),'> <v')-2,15),b+1FROM
C WHERE b<=LEN(@))SELECT top
1sum(sum(1-1/b)%2)over()FROM c
GROUP BY a OPTION(MAXRECURSION 0)
```
Ungolfed:
```
DECLARE @ varchar(max)= '>>>><^v^v';
WITH C as
(
SELECT 0 a,b=1
UNION ALL
SELECT a+POWER(CHARINDEX(SUBSTRING(@,b,1),'> <v')-2,15),b+1
FROM C
WHERE b<=LEN(@)
)
SELECT top 1sum(sum(1-1/b)%2)over()
FROM c
GROUP BY a
OPTION(MAXRECURSION 0)
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/1064558/how-many-lights-are-on)**
[Answer]
# Mathematica, 64 bytes
A port of [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/89961/48934).
```
Count[{_,_?OddQ}]@Tally@Accumulate[I^Mod[ToCharacterCode@#,11]]&
```
[Answer]
# [SQF](https://community.bistudio.com/wiki/SQF_syntax), 160 bytes
Using the function-as-a-file format:
```
x=0;y=0;a=[];{switch(_x){case"v":{y=y-1};case"^":{y=y+1};case"<":{x=x-1};case">":{x=x+1};};if([x,y]in a)then{a=a-[[x,y]]}else{a=a+[[x,y]]}}forEach _this;count a
```
Call as: `"STRING" call NAME_OF_COMPILED_FUNCTION`
Ungolfed:
```
//position tracker variables
x = 0; y = 0;
//`a` keeps track of which coords are switched on
a = [];
{
//switch based on the magic variable `_x`
//which is the current element of the forEach
//and adjust coord tracker variables
switch(_x) {
case "v": {
y = y - 1
};
case "^": {
y = y + 1
};
case "<": {
x = x - 1
};
case ">": {
x = x + 1
};
};
//check if the coord is already turned on
if ([x, y] in a) then {
//remove it from `a` using array exclusion
a = a - [[x, y]]
} else {
//append it to `a`
a = a + [[x, y]]
}
//do this for each character in _this (the argument)
} forEach _this;
//return the length of `a`
count a
```
[Answer]
## Python: ~~207~~ ~~189~~ 181 Bytes
```
a = input()
l=[]
for i in range(0,len(a)):
if a[i]=='v':y-=1
if a[i]=='^':y+=1
if a[i]=='<':x-=1
if a[i]=='>':x+=1
if [x,y] in l:l.remove([x,y])
else:l.append([x,y])
print(l)
```
Input is a string.
Thanks to @LuisMendo for pointing out that I can actually only indent by 1 space. Darn my Python teachers for telling me to ***always*** do it increments of four.
Fixing it so that input was obtained rather than assumed stored actually saved me 8 bytes.
[Answer]
# Ruby, 64 + 6 = 70 bytes
+6 bytes for `-rset` flag.
A straight port of [Leaky Nun's Python answer](https://codegolf.stackexchange.com/a/89972/11261).
```
->s{d=Set.new
q=0
s.each_char{|c|d^=[q+=1i**(c.ord%11)]}
d.size}
```
See it on repl.it: <https://repl.it/Cnjy>
[Answer]
## Javascript (ES6), ~~97~~ ~~93~~ 85 bytes
```
i=>[...i].reduce((c,d)=>c-1+(v[p+=v['^<>v'.search(d)]]^=2),0,p=1E6,v=[-1E3,-1,1,1E3])
```
EDIT: -8 bytes, thanks to Neil
Test:
```
var test0 = 'v>v<^^<v<<^<^><<>^^>>><v>vv^v>v^><><<^>><<<vvv^vvv>v>>v><vv^^<<>vv^^>v^<>>^^<^^>^^v<^>^<vvv^v^v><^<<v<<>><<>v>>^><^>^^<>>>>vv>^<<^<<><vvv<v^>>vvv>v^>>><<v^>^^^^v>>^>^v>v<vv^<>^<<v>vv>><^^<^><vv^^v<v<v^^^>v<^vv^v<><vv^^^>v^>v>vv<<^><v<^v><<v^^v>>v<vv<><^^^v<^v><><<^^<>^>><^^^>vv^<>>>>^<^<<<<>>>v<<v<v<vv><<vv<vv<^v^^^>>vv<>v>><<<v^>vv><v<<<v<<>^vvv^<v^v>^^v^v><<v^>>>v<v<v^>>>v><>>>^<><<<<>vv>v><v>v><^v<>v>>>vv<<>^>^>v<^><^<^vv^><^^>v<^^v>v^v<^^^^vv<>v<>><v^^><>v<<<>v^<v^^><>^<>^<>><>^^<>^v><>>><v<^^>>v>^^^<v';
var test1 = '>>><^>>>^vv><^^v^<<<>>^<>>^<^>^<<^^v^<v^>>^<<><<>^v<^^^vv>v><^>>^<^<v><^v<^<<^^v><>>^v<^>^v<vvv<<<v^vv>>^vv>^^<>>vv>^<^>vv<>v^<^v<^^<v^^^<<^><><>^v>vvv<^vvv<vv><vv<^^v^^<^^>>><<<>^<>>><^<<<>><>^v><^^vv<>>><^^^<^>>>>v<v^><<>v<v<v^<<^><v^^><>v>^<>^^^vvv<v^>^^^^v>v<v>>>v^^<v<vv>><<>^vv><<vv<<>^^v>>v<^^v>><v<v<<>^^vv>>^v>v>v<>^>^v<>>><>v>v<<v<^<>>>vv>>v>^<>vv^v><><^v^>v<^^>v<^v>>v^>^>>v>v>^>^<^^>vv>>^vv<^><>^><<v^<><<^<^>^^vv^<<^^<^^v<v<>^>v>>>>>>vv<<v>^>vv^>^><^<^^><<vvvv>vvv<><<><v^vv><v^^<>^>><^vv<><>^>vv>>>vv^vv<<^v^^<<v^^>^>vvv<><<v>^>^>v<v>^<^^^^<^>^>><>>^^vv<>v<^>v><v<v^>>v<^v<vv>v^>v<v^<^^^^v<^<^<<v<<<v<v^^>vv^>><<<v>>^^^>^<^>>>v^v><^^vv^>><^^vv<vv<v^><>>^><<<>>^^v^v<<v^<vv^^^>><>>^v^^^>>^>^<<^>v>^^v>><>v>^>vv^^<vvvv<><^v>^><<>>><^<^v^<<vvv^v<<<<<><><<><><<v>v<v>v><^v^^vvv>><>^>^>^v<<vv^^^v^vv><v><><v<v<<>>>v<^<^v<<>^v<<^v<><>v>>^^>^<v^<<^v^^^vv>><v^<v>^v><^<>>>>^^<vv<>^^>^>v^v^^>><>^^<^v^<v<<v<^<<^^vv>v>^<vv<<^^v^vv^>^^<>v>^>^<>vv><v>>><<><<vv^^<vv<>>^v>^<<vv>^><<>^<v>v><<v^<v<><v>^<^<^><^^^^>>>^<>^^><>>v^<vv^<^<<vvvv>>>v^v>>^>v^><<>>v<>>^>><vvvvv<<vvvv<v>^v<vv^<>><<><v^^<^<v>^v<^<<>^v<v^<>v<<>^<<vvv><^><^^^<>>v^<<>vv><^^^>><^>v^v>v<v^>>v>>v>vv<<v<<vvv^^^>^<v^^<^<v<^<>>v^<<v>>v^><v<vvvvv^^^<v^^<><v<<^>>^><^<v^v^^>><v><>v>^<vvvv><<v^^v^>^>v>><>^^v>v^>vv^>v<^<<^vv^>vv^<v>^<v^<>^v>v^>v^<<>^^<^>^^>vv^>>vv>v>vvv><>^v<<<<v^>v^^v<><v<v>^<^><^><<v<>><<>v^^>>><<><>>><<>><v^^>><^>><^<>v^^vvv>v<^<<vv^>vv^><<>v><>^<>v^^v>^>v^<>^><v>^><<^v<v^^<v>><^^>>^<^<^v<v>^>^<^<v><><>>>><>^<^<v>v<v^>v><>v^>v^<<><^<>>v<^vv^^^>^<<<<>^>^<><^vvv>^^<v^v>v>v^v>v>>vv>^><>^vv>^<v<v^<>vv^<v<><>^>>vvv><>>^<<v^<<>^<v^>v<^^^<^<^^<>^>>v>^<v>vv<v^^>><<<<<>>v>^v>^>>>>v>>^^>^<<<^<<<v>>^><<<<^vv<<>^v<^>v^<v<<>v<>^<^<^<^<>>^^^vvv<v>^vv>^><^<v^>^v<v>><><vvv<^^>>v<^v>^>>>><v^<v^^<^^v<vvv<v>^^<<>><^<v^v<^vv>v>vv>^^<>^^^^>>^v><vv<<<v>^v^>>v^>><<<^v^v<<>><<vvvvv<v^vv>vvvv><v^v<^^^><vv^^<>><>><^>^^^^v>v><><v^<>^v<>^^<^^>^^^vvv>>vv^v^<v<vv^v>v>>>^v^^vv^<^v>v^v>>^v>v<v^<^^><vvv>><<>><>><v>v<^<v>>>>v^^v^^>^><<v><^<<>>v<>^^<<>vv^>>vv^^^v>>>^v^><v<<^>v<v><>>>^>>^<<>>^><<vv<^^>^^^v^^<>>>vv><<>v<><<<>v<<>>>v<>v<>^<vv^v<^^<<<v>^v>>^^>^><<^vv<><><>v>^v>^<>v>>^^^<^^>>vv>v<<<v^><<v><^v><>v<^<<^<>^vv>^><^^^^^<<v^^<>v>><^<v^^^vv>^v<>^<v<v>v>^><^<<^<>><^^>vv^<>^<>vv<>>v<vv^>><^^<^>v<><>vv<v<>>v><v^^^>^^^<<vv^><^^v>v>^<^>v^><<vvv>v^><vv<><^<><^>^v<><<v^<<><>^^^^<<^>>^>^v^>v>^<<^>vv^vv^v<>^<<^>v<^^<<v<v<<<^>vv^>><>v>><><v>v><v^><vvv>vv<<vvv>v^<<^v<^<><<^v>v<>>vv<<v^>v>v<<>>^vv^<^^^<^v>>^<vv>^<v>><>v>^^<<v^<>>>>>v^v>><>v^>>^<>>^<^vvv^^^<^v<><vvv^>^>v><<v>>^v>v<v>v^<v>v>^<>vvv>vvv^^<>vv>^^^^^>v<<^v<>>>><<<>>><vv>>^v^^v<v^>>>^>^v<^v>^v<>vv<><vvv^v<<<<v<vv>vv^<^vvv<^v>v^^vv<^>>>^^>>^^><>^>>v<>>>^^<<v<^<<<<<^^<v^^^<<>><<<^>^v^>vv<>>>^^v><<>^^^^<vvv><^^<>>>^><<^>><v>^<>^v^<vvvv^>>^><<>><^<v^>>vv^vv<^>>>><^>^v<^<v<^^<^<^><^<>>^<>v^v<<>v>v<>><<v<^v<<<^v<v<>><v<^<^>>v>v>><v^<v><>>>>>v^v>><^<^<v>><v^v>v<>v<v><<<>^^><>^^<^vv^^<>v><><><^>^^v^vv^<><>>>>v><>>^>^<<^<v<v^>v^^<v>>><<^^vv^^>><<^<vvvvv>><^>^>>^vv<><<>v>v^<<<^v<^^<<^vv>v<vvv><^v>vv^vvvv<^>^v^<<<<^v<<<>^vvv>^v><<>>v<v<^v^<>v>>^^v^vv>>>^v^^>>^<><><<<<^vv>>>>>v>v^>v<>><<<>^vv>^^^^<^^^>^^^^>^^^v^v><^>^>>>v<v<^<^^<<^v<<^<>vvv^^^^v^<<>vv>^^>>><^^v<^<<<v<>v<<><>v<><>^<v<<^>^^>><<v>^^><^^v<^<v^<^^<>^<>^v^>>^^v^v^<>v<>^<<<>^v^v>^<vvvv<>v<<>vv^<<>vv>>>>^<v><>>>v^><<>^v>><<>>^^v><^<>>vv^^^>vv^<^^v><v>>vvv^v<^v>v<<^^<>v^^^v^^>><v^>>v^v^vv<^>v^<^>^>v<v^><vvv^>^<>v<<^><^^<vv>v>>vv>v^>>^vvv>>v^>^^>vvv>>v><<>>^^v>v<v<><<<<^^v<^<>^v>><v^^^<>>vvv>v><<v>^^<^vvvv^v>v>^vv>^vv^^v><<>>^^>>v>>>^v><^>v<^^<>vv>v>v^^^>>^^^><<<<>>^>>^<^v<^<^<>^><v<<v>v<>^>>^<<v^^<v^vvvvv>>v^>>^^^<^^<><<><><>^v>vvv^>^^>v<^^>^<<^v^^^><>><<v<^^^<<<<>><>><<^^v><v^<<^v<v><<>^<v>^>^v>vv>><v^<^<v<v<v><^^^^>>><^<><^v^v<<<^>vv^<v^>^^v^>>><<<<^<>>><v>>>vv^>^^<v^v>>>v^<^<>vv>^v^^><<<v>v>v>><>>>v<^>^<>>^^<v^<<^<v^>><^v^><><v><><v^vvv<<>v>>><<><v>v<>>><^<^^v<v>^<<>^v>^>^>^^<^^><^>>>>><^^>vv>^<^^<><^>^<^^><^<v>v^>><^>^^^>>v^v<^>>^<v^<>^><><v>>^v<v^^^^v<^vv><^v>>^^^<>^<^<^>vv^v<<>vv>^<>v>^>^>vv^v<vv<^^^v<v>v>v^<^^^v><v<<<^^<><^^>>>><<^^v<<^>v<<vv^^^vv^vv^<v><>^v<v>>><vv^v<v^>>>>^<<<vv^>>v>^><<><<^<^><<vv^>v^>><>v^<<<>v^><>><<>>v><>v^<v><>^v>>><><>>>^vvv^v>vv>>>^^v^><<v<>>^^^v^^><<^v<><><v<<v<v<><<<v^<^^^<>v^^v<^^<<^>v<<v><^<<<<>><>^v>^<>^<^^v^vvv>^^<>^>><v^^vv^<>^<><<^^^v<^^^>>^^v>^>^<^>v><<^<>^v<><vv^vv<><<<<<<v<<v<<vv^<<^<^vvvv><v^v^v<>>>vvvvv^<vv^<^<>vv>^<><<v><>v^^<v<>>>vvv^><^<^>v^^<v>^<>>>^^v^<vv<<<<^><v<<<>v<<<v<>>^^^>^><>v>^v^>^<v^^><^v^^<^v^^>^v>>^^^<<><><<<>v>><^><>>>vvvv>v>>v>^^^^v<><vv<^<v^v>>^^vv<^>vvv>^v>>><v<v<v^<^>^^<vvv<vv<v>>^vv>^<<^<^<v>v^<vv^^^v>vv<v><v><v>^<v>>vv<>v>^^>v^^^<>v<>v^v<>^<><v><^>^<v^v><<^v^v^v<<v><<^^<^vv>^<^v><>v>><v^v^>><><><<<v<>v<^vv>v<v<<>^vvvvv^<<<^<vv><<><>v^<^v<<<^>v>v<v^<<^>v<<^<v><<<^>vv>v>^<^^v>>>><>vv>>vv>vvv<>^^<>^v^<>vvv<^^^vv>v><<<<vv^v><v^<^<<<><v<>^><<>^>v<^^<<>v>>v<<>><^^<<<^<^vv^^>v>v<>^^>>^v^vvv>^v^>v>>v>v>v>>vv^<><<<<>v^^>vv<^^v>>v<vv<^>>^<>^^v<><vv^<><v><v<<v^v<^^<^v^v<>v<<><vvv><<<^<^^<<>>^v>>>^v>>>v<>>^><<<><><<<v<vv<^<>v^^v^^>^<<^^^v^>^<<^>^>^>>>>v<v<v<>vv<<vv^<<^<vv>^^<^<<>><^v><><>^<v><v^>^v>^<^>^^><v><<^<v^^<<^><><v>v<>>><<^><v<^vvv^<<<>><<>^v^^><vv>vv<>^>^>vv<>v^<^<>vv><<>^<v<vv<^<^<><^vv<<^>>>v<>><<>>>^^^^<<^v>>v<vv>^^>v<v<vv^><<><>>>v>>^^v<^v^^>>v^<>>v^>><^<^^v<v<><<><>>^<>><^v<^^^^><>^>vv>>^vv<<>v<<<<<<><<<><<>><v><^^^<>>v<^><^vvv<>^>^^v>^<v><^v^vv^<<>v<<<<v>^vv>>v>vv<<^>^<>>vvv^<v<><>><>^^^^vvvvvvv<<>v<^><^^>vv^^<v<<^^<vvv<v<v<<>><<><v^^>><^<>^v^vv<<v<v<>><<>>>>>^vv<><v<>v><v>v>><v<v^vvvvv<><>v>>v<><<<^^<>^<^^<v>v^<vv>^vv^<>^<<^<vv><v<v>>v>^<>v^<<v^<v>^v<>><v>>>>^<<^^^v<^<>><^<><v>>vv^>^<^<^>>v^>^^^^>vvvvv>^v<^><^^<^^>^<^^^^^^^>v>>vv>v^^^v^^^<>v><^>>>v>^>^>^>vv<vv<^^>>^>>>v<>v><<^<<v^>^>>>>^^><^^<v<<<<>>v>v^v^^<>><v<^<<<<v^^^^<v<<<^>v>^^<vv<^^^^^v>^v^<v><>>^^>^v>^>^vv^v>v>v^>v>^>>^^^^>>^>>^><>><v>v>>><<^v^v^>^>^>>vv><<^>v<v<v^<<>>^v<<^v<<^><^>>^<v>^>vv>v>^^^>v^^<^<^^>vv>^^><v>>^v>^v<<^^^<<^v^>^<<^>vv^>>^<^v><<>v><^^^<^^>>vv>^vv>><^<<<^>vv^v>v<^<<<^<^<<><^^>>>v^<^^^>^<><^v>>^<<v<^v>>v^<^<^<^^^<v^><<vvv^<^v^vv^vv<v<<v<^<>^v>^^^<^^v<v<v><<<^<>^^^^v>v^v^v^v<v><v>>^v><vv^^^v>><<v^vvvv<<<^v<<><^>^<v^^v<>vvvv^vv<>^v<><>^^<>>vvv<^>><v^<<>v>v<>^v^>v^>><<>>^^<^v<>>^>^><>>^<v<v^^<^v><v^<v<><><^<<><v^v<<>vv<v<v<^>>><>vv^^<><<v<^^<<^<><^^^>^>>>^<^>>>^>><^^^<^v^^^v^v^v>v>v><vv>><vvv<<v><><^^>^v<v>><v><^><^<<>v^vv^v><^vv>^>>v<vv><^<^^v<^^vv<vv<v<v>v><v<vv<<>^^v^^v<<<^<>v^^^<><>>><^>v^^^v^vv<<<^>>v><^>v^<>>>>^<>^^vvv^^<><^>^^<><>^vvv^^<vv^>vv^^^^v<>vv<^^^v<<>><<vvvvv>v>^^^vv>><v><v<>vvvv<v^><^<>^>^<>v>v>v^vvvv<><^v>>>^^>><vvv<>^>^v^<vvv>v^vv^vv><>><>v^^v^vv<^v>vv>>v<v><^<<^v<>>^vv^<v>v><v>v>^v>^<v>^<<^>vv>v<^<^vv^<^><<<v<<^^vv<vvv><>v>v<vv^<><><^vvv>>vv<^^^v><^v><<^>^^v>^<>><v<>>^^<<<v><>^>^><vvvv<>^<<<><<<^<>>v^vv^>><^vv^^>^<v^<v>><^^>>>^v>^v<>^v<><^><vv>v^^^<^>>^<<^<^><<<^^<v<<^vv<^<>v<^<<^^<v<vv<<><v<v^<>^<>v>>v<^v>v<>^^vvv<>vv^v^<><v^vv^<^v^v><>^><v^<>>^^^<>>vv^<v>^^v><v<^>^^^^^^><>>vvv<<><><v<^>v<>v^v<<<<>v^>>>>^v>^^<v^>v><v^<^^v<<<<v<<<>^v<^>^v>v^^>v^^vvv>vv<>^>v><v<>^<vv><>>><<^>>><<v>v^^<^<<<<v^<>>>v<<<^v^vv<>^v>v<<<<>^^>><v><>v<v><^^>><>^>^>v>>><v>^vvvv<><><^>>^v^><<>^v<><><^><<<>v^^>v>^>v^<v^vv<>><^vv^^>^^><vv<<>v>v^^>><v^>^<^<>>>vv<>^>v>v^<>v<^<<v>>>^<>v^>v>>vv^^<>>v<v<<^<>v>v^<^^^>v^^>v>v>vv<^<v>v^^><<<v<><>^^<>v>v>^^v>v>v^v>>^<v^v>><>^^>^<>>>^vv^><v^<^>v^>^v><^>^^^vv^^v<>vv<>>^><<^v>^v^>>v>^v^<<^^^vv<<vvv>^vv^v<<<v^^<<><vv<>>^^vv>^^^vv>><><v>v<^v^>>>vv^><>><v<^v<>^><v<^^^^>><^<>v>^v<^vv>v>v<^<>v>v>^<vv>v<^>vvv<v^<vv<vv<>v>^><v^v<>>>>>v>><^v<>v>^v><v^v^vv<>^<vvv^>><v^<vvv^^<^vvv^v^<>><v>v^^v<><>v^^^v<<<^><v<<<>><<vv<<><vvv^v>>v^v<v^>>><<v<>^v><>vv<<v>v^vv>v^v<^<vv<><><^v>^<vv>v^^>>^^^><vv<><^>>>^<v^<<^^>^>vv^><v<vvv>^^>>>^><<vv>vv>^<>>^^><^v><<>^<<<v^>^';
S=i=>[...i].reduce((c,d)=>c-1+(v[p+=v['^<>v'.search(d)]]^=2),0,p=1E6,v=[-1E3,-1,1,1E3])
console.log(S(test0))
console.log(S(test1))
```
[Answer]
# R, 172 156 137 101 96 bytes
```
n=function(a)sum(table(cumsum(sapply(strsplit(a,"")[[1]],switch,v=-1,"^"=1,">"=1i,"<"=-1i)))%%2)
```
Using @LeakyNun's complex plane idea.
ungolfed
```
n=function(a){
b=strsplit(a,"")[[1]] #Splits String up
p=sapply(b,switch,v=-1,"^"=1,">"=1i,"<"=-1i) #Replaces characters with directions
q=cumsum(p) #Finds each location visitied
t=table(q)%%2 #Determines if spots were visited an odd # of times
sum(t) #counts odd visited spots
}
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 136 bytes
```
$a=@();switch -w($args|% t*y){'^'{$y++}'>'{$x++}'v'{$y--}'<'{$x--}*{if("$x,$y"-in$a){$a=$a|?{$_-ne"$x,$y"}}else{$a+="$x,$y"}}};$a.length
```
[Try it online!](https://tio.run/##PVGLbsJADPsVhG4qj3U/gMn2JZmqqQOkik20OkCl397ZObQKlZzPcRz39@faXvpj23XznJr9x2q966@n4eu4qK@r1FwO/eNlMWzu67Hyakz37XaqjMVNRRZS11MFISw24@l7tUy313Rf1qdzatYjRVPzeB/TZ31un1fT1HZ9y6vt/h@Zdql569rzYTjO85wtwx0ZcLgB5m5mIJydL0IECQHIgjJB448ntkE0Jw3GRgrxTT3zQqYCZSUuATVSTxyeKZLJ073EMjjLQj4M6Oh8okdONBBqkDUSPPxqPK/Ilg24pqLAsmUiI4iQGfFknwRIwgusFSUesm4xiY/LnLyzATElJKLbY4LUtRbCr64zyr5KiilQ3UsOsZ8VrxYJxgSLCZEq4uVFMXxrdW2lFLWa7MX3Ukr6ZyW64tV3UCk1f54iMFOhqoxUEjKudJH/AA "PowerShell – Try It Online")
I think there's more to optimize here, but this is the lowest I got for now.
Easier to read:
```
$a=@();switch -w($args|% t*y){
'^'{$y++}
'>'{$x++}
'v'{$y--}
'<'{$x--}
*{if("$x,$y"-in$a){$a=$a|?{$_-ne"$x,$y"}}else{$a+="$x,$y"}}
};$a.length
```
**Explanation:** The input is changed to a character array and each piece is matched to one of the first 4 switch cases to increment the x or y coord. Everything matches the 5th case where we decide if a light is turned on or off. Length at the end determines total number of switches turned on.
Note: The comma in the coordinates is necessary so we don't get collisions like (10,10) and (101,0)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~96~~ 95 bytes
```
$(switch -w($args|% t*y){^{$y++}'>'{$x++}v{$y--}'<'{$x--}*{"$x,$y"}})|group|% c*|%{$r+=$_%2}
$r
```
[Try it online!](https://tio.run/##TZnrbhVZDoX/5ykidJgQLtJMa0ZqjYw1T@LWiElfJKSmE9qAQp6dKa9vuWhA4ZxK1d7evqy17Prw@6e7@4df796//3b5@frt9eO3y4uHT799fPfr9ZtPLy7/vf/l4evz648vv9w@1uPly6tXTzd583j5fHzo4/ubN083Md@PDy8fn10@v758efb0dPv1l/vf//xwPPnu5dfnj5f7V28vPz3/4enqcv/t6erqPy@uro8/r1/844d/vb7p7KiKjqiojMiqzIzjctfx47h0XDwuRUTPpT4u5vHv@HY8FnNbHbdFHg8eCx0/j/WyuPlY4Vh2Fp8F5sFjvbnn@H4s0sd98/tZrOPYK7W8DJivdfzRM2PJbBjzwJh23FCyd7Y/fnXcPWZEza7B5TEr5@bQjTHGzH1j/nFDzBLF5TniLK5lK7XT8afGuLH9eCC0i5bQ06UdZvU5Vsje@XUH5x1PHV44Vi/8oPMltqY8qB1SO8iroR/FirJ7jj6nGi/O0cY8xWu8NP8fn@b2ce/EYT7OauVvcljOh/nEluOJMXy8G31zu8nwz7//@Ppmfj/W1RxlDNfxFV1FlWtzAIVtFpUXsRyPcQbunR1JiFaMxwsTvfmhLFAOFG4sPSfbSzFLGd3yduP91ulJNbldxinLOCh2NxeVI3hduY33yQfcJRdVOf9IuOPjPKOqUKoF/ghCQgLpPyWFLulMk22KGdvr67g7SHZ2U11N8jWhVNbOdqmo9Dyvy7hJfiilj9JU5dM6xNw2BkyOZKZzZhZorRZaR3WLF1OlprP0me@6nuwn46ZeVNvjotoH27moeOHYeTxzU7CUwVRxKNyqv7G7KDRDAdUqG1U3s4TOLKc7fpQipSYQkg/YrlreoMbJMH0iQZXZjfu1i7BI5d5ahHRRbgukQhWIc3TQ3kJUXiirCCpb2oFzM@HXgefIKgcVMFgnHCzcqRSR2eQoAFMCIvw8d7lWVWSkTri6dGewOwhKpgA6qoXEQC05m@iAHLk4kvYfu1WoghPVkYpgPIlbo5w0BETGyXFaOAXXSjWVDbVdQLwSi0MK2UsJkPKNHkhvy2aYTxzlgnQGpZGbXcqu1NKxz1I1KlLuIavFZTBNrFPbta5TwQJF2VDQTT7i8OabvNQAZxfWkvdOXsVFCyZZpLvgH1ysw0ab/QxZoPBCtmBzjuRsa5zPFuJMQZx4C6ItxS@VaAq3SgXsrQ4DCAmawiG@yrNyhA@DI3Ve@TcgHFUK@NxgWsH52hXoDofV@ZSmbvFE4KkwvskswKbJw/bB4VbVAyjtkpEmiHbJC6EgmqQsBLLB3zzRG8MIutIu08KiDEnsEu1MMiXpoJHOlihHFcoEV@AdYaDijvEAURpgG2AlwUzOFknCqDjZRWYpreLUTACNJJPyGY8nEDRhdSH2AqpO5jRCrinG8BbAHYH6UtmuVtMmwkedhVrpsBqB1nm217Ja/sLzEhhGPSLRHNcOIogZyyzhCBsSYW4lesDKglpJF6nBM45iGUq6HR5hYbFpwJV@CGWEQpSaQDCuTgSSRZYJ@@lsVBp6Ch1ivgRYmhpBvqQTm6wwxIjETTtt8ck3OUT8EMt16ZTEAiJoGE1oIuB4yQh@VYgISYGimsaNQRGa5ag5FICpr07VZmi0LDbsUV6mOshBflMCF6yiAKQJzWJL2O@8RMfKN0VUevcADSUBGhNIYfSMMgTCKTiFI6C2vytAqgwf@66mQ4HTFdskXQF5ZQ8oDwNsXa@yAQGwWULYNIjIpaDxvuxR9MgamWeFZh7/q8eB2AQxg4oKs2oh3gswJ5/gcSM0wEkz1GYRc7rqX3jDsRrzkYbwg0S6K1AQZN/Qwsn3iZLnQAm6txldrYyLE3GekGahh1gUMwXplt3OkHApGSva5rGwbVKFkoe1pA8ZogtFka3agk2AJc6tW31jm0oCINaGZRSSTbUkz3q9u0njEDFotQyetWLMHaN2QFGRyIqndkX7KdFEAk6oRgr3ljSiLJA50UudTcys9CWrFXjboCQj@xsQRB9gmsWbM8n0ABa2iyJp6mAr448VCiRWsKlR3no8oQD3LWm8JW0w1ZC98tgNGUcI6Br5vTVT7pnD6ZuWwNErROnnXUZFY31KUQAXCLEMo1xAIIRzuFdZjSI9aNRqDtquVNR5ekDR1BiNT4HG7okofYvY7G0TUFRkjNoA2FdAYtJJO8iNG2KrlvKTVj1XTLIpwtgDCKpVnrYwb0OReZM@rBg8YJLqvvAvoIkKtNfhIDcsYI11agPii9@qHIQBgLmDIGlQaKsYKhDStIb0ehKYwcigHVfihfB10WxbFJ6kMDGhERCZVK3JGWcGoRvKbY81GYWxXB@e4pDjFr8qF0usAPmRm7EthfKgTrUGxdFHuAOy84PeQcMAbqGxNkaXeYn2zJMmFNIePz1oaPcwdJaBSnPYDbUInVxbaIPIEkYfZLt51DDuMQQ4VGjajh2yhKlpG2b0d/KvwDlERAI3DQ/q7KB5ML@qduvNtIzVUW4QX5EKC@fmIhNOQ1OM0HKnPfTrO5QRUXS68pFkOmAC4jvGKPM8o6EdP5HHbVRRGYe7X8sx@RNNgDGQK@gnfDY1lhtQsPsc0qna4/sEsdw5O8twmFQb0kJ@bM83kx0R2Abq7ah3ABEsG6eIJ7s92KjcYVYgtjaPqQx3MWgM@VGNULplJW7C9zAIAXI7HW1P@yBSkZlyA/CJ7xAb1t@mEBq08mGCgoD48RNcgR53@0sSUwNMjwHMnWhxG7qeOec5o6IdZGpD0dBLn1MFMW/bcgQBjIIYCPcp54gBcuizl7XC7/aUwyvuLAmB2r3DHw89YC5EQXScrlilpiILq8dlWA@KQCej/1msuRjnqlFNQwgIfkQ3ZLip4l4orGDKfJIebgJxNNPh5pNOq@oUKso91CqT6toccDPtWJNQ0c7LsuLZtr7dOq6wb3R77IzOZKYQrZ4GEktHbwvORISwb227S@Y2c5xyf1rnhDd3FMcQxroDUAHqYqes1EbSw4Qzt86mLo1y@ON7/8pAr1ameHLDlNNU3FbHYX6np7BYgfy24SxnqPIqVgLWOeM1fOwMwVjca/lie4ZTy2J/8ZvuzEwIE6@0pHWqbXxqad9vdAAoJrBMbsMYC5@XZ8rh/poei/dCYUUYwESRKEx6a@fzHqkSbtpLXhUwJT9nOZ4cCofBeQYFQIyh4xwZu8s@R/YF2YRJDnWXO85VEMn389WPWLZX2BXa1/NVsMBepe6@D4JIsbbNdnwgGzyypTrOqTTiPRaz6GB9zAaR2oZaYbVlEuFpt/D08SBeLYma5gJVHOui9vsJd6GxEyhrShjf@KkapklH9SWtzvZdluW9c/vuHX3vbNLVReqZWvx2plZw7mtIMyCz7w2hB45lvCxzNp0eXWB0bR3xysRvJd3dBe8FlKAGPBeAdWmt9LHatdXlsSmdoTVk7FstRIFHt34VE56K5dIrbSyYEzuraY8Qm54qPC7wrBo@23cPiLzclAHRtpH1hVOhMCZm5TMYjLMYF7iFrX0xhdW9Tu/0MMTqpzwmiIqz6/BOOjOE5fQysLTfwuzcMjyXAg1JWVyaiJTwFHRrylOdnbgywOB1Z7S5kQmi3x/7TdRZep6J8q7VvYsmOrS8VUvZsCGdcqzpQeUkletXvnRI7hUSrd4eb0ZvLJkBgJDd7tiL9yO97wdAnr/0C/t2kfEZPeO@CPerWzCRKTPTEId@7T3bfHAlc18/uX30qxJGL/COmxy428oORr@5vbq9/nr9/PpRL4gvd58/3L37ePe/15eH67fXl5@4en/38Of7j8eFv11@vr486OKzywtff3P3x/nc7b/37mdXT9/@Dw "PowerShell – Try It Online")
Unrolled:
```
$plane=$(switch -w($args|% toCharArray){
^ {$y++}
'>'{$x++}
v {$y--}
'<'{$x--}
* {"$x,$y"}
})
$plane|group|% count|{$result+=$_%2}
$result
```
---
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~112~~ 109 bytes
A port of [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/89961/48934).
```
$args|% t*y|%{($p+=($c=[numerics.complex])::Pow($c::new(0,1),$_%11))}|group{'{0:N2}'-f$_}|% c*|?{$r+=$_%2};$r
```
[Try it online!](https://tio.run/##TZndbhzXEYTv@RQLYxWSNh1IQgwETLOTJwhyH6QFg1nZAWSLIaWWA5LPrsypr3poSaC4szPn9Omfquqeu49fTvcPP58@fPh6fH@4OTx@Pf54/9PD06vDp2//9/Tq8eJ4993NxfH25p@/fv7ldP@f24c/3n785e7D6bd/XV5f/@Pjl@276@tfT18uXl@9ubw6vnv15s3l5fPTT/cfP989nj@@vv772@fz798f3z1va95@@/TXx@P9dzfbfW@f/3K8//p8dva3i7PD9ufq4s3bH67OOzuqoiMqKiOyKjNju9y1/dgubRe3SxHR61JvF3P7t33aHot1W223RW4PbgttP7f1srh5W2Fbdi2@FlgPbuute7bP2yK93be@X4t1bHullpcB62Ntf/TMsmRtGOuBZdp2Q8netf321Xb3MiNq7RpcXmblujl0Yyxj1n3L/O2GWEsUl9cR1@JatlI7bX9qGbds3x4I7aIl9HRph7X6OlbI3vV1B@ddntq8sK1e@EHnS2xNeVA7pHaQV0M/ihVl9zr6OtXy4jraMk/xWl5a/2@/rduXe1cc1q9rtfInOSzXL@s3tlyeWIYv70afX04y/On1n6/O1/fLulpHWYbr@Iquosq1dQCFbS0qL2I5HuMM3Lt2JCFaMV5eWNFbP5QFyoHCjaXnZHspZimjW95uvN86Pakmt8s4ZRkHxe7monIEryu38T75gLvkoirnHwm3/bqeUVUo1QJ/BCEhgfSfkkKXdKaVbYoZ2@vjcneQ7OymulrJ14RSWbu2S0Wl1/O6jJvkh1L6KE1VPq1DrNuWAStHMtM5sxZorRZaR3WLF1OlprP0nu@6nuwn41a9qLaXi2oebOei4oVj1@OZk4KlDKaKQ@FW/S27i0IzFFCtslF1s5bQmeV0x49SpNQEQvIB21XLG9Q4GabfSFBlduN@7SIsUrm3FiFdlNsCqVAF4hwdtKcQlRfKKoLKlnbgupnw68DryCoHFTBYJxws3KkUkdnkKABTAiL8vO5yrarISJ1wdenOYHcQlEwBdFQLiYFacm2iA3Lk4kjaf9mtQhWcqI5UBMuTuDXKSUNAZJwcp4VTcK1UU9lQ2wXEK7E4pJC9lAAp3@iB9LZshvnEUS5IZ1Aaudml7EotHfMsVaMi5R6yWlwG08Q4tV3rOhUsUJQNBd3kIw5vPslLDXB2YS157@RVXLRgkkW6C/7BxTpstNnPkAUKD2QLNteRnG2N89lCnCmIE29BtKX4pRJN4VapgL3VYQAhQVM4xEd5Vo7wYXCkziv/BoSjSgGfG0wrOF@7At3hsDqf0tQtngg8FcY3mQXYNHnYPjjcqnoApV0y0gTRLnkhFESTlIVANvibO3pjGEFX2mVaWJQhiV2inUmmJB000tkS5ahCmeAKvCMMVNwxHiBKA2wDrCSYydkiSRgVO7vILKVV7JoJoJFkUj7j8QSCVlhdiD2AqpM5jZBrijG8BXBHoL5UtqPVtInwUWehVjqsRqB1nu2xrIa/8LwEhlGPSDTHtYMIYsYwSzjChkSYW4kesLKgVtJFanCPo1iGkm6HR1hYbBpwpR9CGaEQpSYQjKMTgWSRZcJ@OhuVhp5Ch5gvAZamRpAv6cQmKwwxInHTTlt88kkOET/EcF06JbGACBpGE5oIOF4ygq8KESEpUFTTcmNQhGY5ag4FYOqrXbUZGi2LDXuUl6kOcpDflMAFqygAaUKz2BL2Oy/RsfJNEZWePUBDSYDGBFIYPaMMgXAKTuEIqO0XBUiV4WPf1XQocLpim6QrIK/sAeVhgKnrUTYgADZLCJsGEbkUNN6XPYoeWSPzrNDM47/3OBCbIGZQUWFWLcR7AebkEzxuhAY4aYbaLGJOV/0LbzhWYz7SEH6QSHcFCoLsG1o4@T5R8hwoQfc2o6uVcXEizhPSLPQQi2KmIN2y2xkSLiVjRds8FrZNqlDysIb0IUN0oSiyVVuwCbDEuXWrb2xTSQDE2rCMQrKphuRZr2c3aRwiBq2WwbNGjLlj1A4oKhJZ8dSuaD8lmkjACdVI4Z6SRpQFMid6qLOJmZW@ZLUCbxuUZGR/A4LoA0yzeHMmmR7AwnZRJE0dbGX8sUKBxAo2NcpbjycU4L4ljbekDaYaskceuyHjCAFdI7@nZso9czh90xI4eoQo/bzLqGisdykK4AIhlmGUCwiEcA73KqNRpAeNWs1B25WKOk8PKJoao/Ep0Ng9EaVvEZs9bQKKioxRGwD7CkhMOmkHuXFDbNVQftKq54hJNkUYewBBtcrTFuZtKDJv0ocVgwdMUt0X/gU0UYH2OhzkhgWssU5tQHzwW5WDMAAwZxAkDQptFUMFQprWkF5PAjMYGbTjSrwQvi6aaYvCkxQmJjQCIpOqMTljzyB0Q7ntsSajMIbrw1McctziV@ViiRUgP3IzpqVQHtSu1qA4@gh3QHZ@0DtoGMAtNNbG6DIv0Z550oRCmuOnBw3tHobOMlBpDruhFqGTYwttEFnC6INsN48axj2GAIcKTdsxQ5YwNU3DjP5O/hU4h4hI4KbhQZ0dNA/mV9VuvZmWsTrKDeIrUmHg3FxkwmloihFazrSHfn2GMiKKTlc@kkwHTEB8xhhlnmc0NOMn8riNKirjcPdrOSZ/ogkwBnIF/YTPpsZyAwp270M6VXu8TBDLnbOzDIdJtSEt5Mf2fDPZEYFtoJ6OegYQwbKxi3iy24ONyhlmBWJr8pjKcBeDxpAf1QilW1biJnwPgxAgN9PR9rQPIhWZKTcAn3iB2LD@NoXQoJUPExQExI@f4Ar0uNtfkpgaYHoMYM5Ei9vQ9cw59xkV7SBTG4qGXnqfKoh525YjCGAUxEC4T9lHDJBD772sFX63pxxecWZJCNTuGf546AFzIQqiY3fFKDUVWVg9DsN6UAQ6Gf33Ys3BOFeNahpCQPAjuiHDSRX3QmEFU@aT9HATiKOZDjefdFpVu1BR7qFWmVTX5ICbaceahIp2XpYVz7T17dZxhH2j22NmdCYzhWj0NJBYOnpbcCYihH1r2l0yt5njlPvT2ie8OaM4hjDWHYAKUBczZaU2kh4mnLm1N3VplMMfL/0rA70ameLJDVNOU3FbHYf5nZ7CYgXym4aznKHKqxgJWPuM1/AxMwRjcY/lg@0ZTi2L/cFvujMzIUw80pLWqabxqaF9v9EBoJjAMrkNYyx8Xp4ph/treizeC4UVYQATRaIw6a2Zz3ukSrhpL3lVwJR8n@V4cigcBucZFAAxho59ZOwuex/ZF2QTJjnUXc44V0Ek3/dXP2LZHmFXaF/PV8ECe5W6exkEkWJtm@34QDZ4ZEt17FNpxHsMZtHB@pgNIrUNtcJqyyTC027h6eNBvBoSNc0FqjjGRe33E@5CYyZQ1pQwvvFTNUyTjupLWp3puyzLe@b23TP6ntmkq4vUM7X47UyN4JzXkGZAZt8TQg8cy3hZ5mw6PbrA6Jo64pWJ30q6uwveCyhBDXguAOvSGuljtWury2NTOkNryJi3WogCj279KiY8FcuhV9pYMCdmVtMeITY9VXhc4Fk1fDbvHhB5OSkDok0j6wu7QmFMzMp7MBhnMS5wC1vzYgqre5ze6WGI1U95TBAVe9fhnXRmCMvpZWBpv4WZuWV4LgUakrK4NBEp4Sno1JSnOjNxZYDB685ocyMTRL8/9puovfQ8E@Vdq3sXTXRoeauGsmFDOuUY04PKSSrXr3zpkNwrJFq9Pd6MnlgyAwAhu92xF@9Het4PgDy/6xfm7SLjM3rGeRHuV7dgIlNmpiEO/di7t/ngSua8fnL76FcljF7gHTc5cLeVHYx@fnl2eXg6vDo86gXx8fTb3en20@nfV8eHw83h@I6r96eHzx8@bRf@cHx/OD7o4jfHC1///vTf/bnL67n7m7Pnr/8H "PowerShell – Try It Online")
[Answer]
# [Actually](https://github.com/Mego/Seriously), ~~24~~ 23 bytes
This is a port of [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/89961/47581). Golfing suggestions welcome. [Try it online!](https://tio.run/##LZGxTUNBEER7seQGEBmjlRtAUMFKllOHeCVCROqQLxICEAVQAgE59HCNfM/b4@vr/t3e7Mzs/P3h4bQ/Hh/X9W6c36/vd9ufr/H0Pc4ft3/PN2N5HcuLL8bydrjabSn/fq7rpqKUqZJSGVJkRoRcrvTikosuSSpK5WL49cltApaGKdxoIq/mi5xgM5gWcghoNB8Yn01SxnEPWcla0fRtgGP66R6cICgasGZAtl/kfWU0NpSoapaxFYDVQGEGHPYNEBQ5y4wIedNmtJKfxBze3aBWaYruzlaAnbHUfrkuzXlJyimYPWcOPV9Mr9EJtkK0QqeqXnIytm9GZypSZDTs9f8iJb7eASde/gNb2PL/1IEFG3ZTkiQwTrqqzQU "Actually – Try It Online")
**Edit:** One byte thanks to Leaky Nun.
```
O⌠4P@%ïⁿ⌡Mσ;╗╔⌠╜c2@%⌡MΣ
```
**Ungolfing:**
```
O ord(c) of the input string (implicit input)
⌠...⌡M Start a function, and map over the list of ord(). Call the variable i.
4P@% i mod 11 (the 4-th prime).
ïⁿ 1i to the power of (i%11).
σ Push a list of cumulative sums of the new list of complex numbers.
This is a list of the coordinate visited.
;╗ Duplicate coord_list, and push to register 0.
╔ uniquify(coord_list)
⌠...⌡M Map over the uniquified list. Call the variable j.
╜c Push coord_list.count(j)
2@% Push count mod 2
Σ Return the sum of this last list.
```
[Answer]
# C, 203 190 189 bytes
```
#define S(s)1-(*s%11<7)*2<<*s%11%2*16
char*t,*u;P,p,r,L,e;
f(char*s){for(P=L=0,t=s;*t;++t){P+=S(t);e=r=1;for(p=0,u=s;u<t;u++)e*=(p+=S(u))!=P;for(p=P;*++u;r^=p==P)p+=S(u);L+=e*r;}return L;}
```
O(n^2) with O(1) memory algorithm.
It loops over every position, checks if this position occurs earlier, and if not checks if this position occurs an even/odd amount of time afterwards, adding it to the total.
[Answer]
## Perl, ~~102 98 91~~ 90 (89 + -n) bytes
```
perl -nE '$i=ord()%5,$x+=(-1..1)[$i],$y+=((0)x3,1,-1)[$i],$p{$x,$y}^=1 for/./g;say~~grep$_,values%p'
```
**Readable:**
```
$_ = <>; # -n
for (/./g) {
$i = ord() % 5;
$x += (-1 .. 1)[$i];
$y += ((0) x 3, 1, -1)[$i];
$p{$x, $y} ^= 1;
}
say 0 + grep $_, values %p;
```
* thanks Dada for -4 and -7
[Answer]
# C# ~~210~~ ~~205~~ ~~139~~ ~~138~~ ~~135~~ ~~128~~ 113 Bytes
```
using System.Linq;int f(string s,int x=0,int y=0)=>s.GroupBy(c=>(x+=c%6%3-1)+s+(y-=c/3%6-2)).Sum(g=>g.Count()%2);
```
## Explanation
```
//Have X and Y as default params allows us to use a expression bodied member
//and then remove the return statement
int f(string s, int x = 0, int y = 0) =>
//treat the string as a char array
s.GroupBy(c =>
//Using the unerlying int of the char this math reduces down to either x - 1, x + 1, x + 0, y - 1 or y + 1, or y + 0
//Concat the resulting values with the original string to ensure uniqueness ie x=1 and y=11 vs x=11 and y=1 for the grouping
(x += c % 6 % 3 - 1) + s + (y -= c / 3 % 6 - 2))
//Mod 2 will return either 1 or 0 so we can use sum to count the groups with odd counts
.Sum(g => g.Count() % 2);
```
* Thanks to VisualMelon for 5 bytes switching `Count` to `Sum`
* Thanks again to VisualMelon, this time for 66 bytes by suggesting some fancy math to get the translations.
* VisualMelon to the rescue again with combining the select and group by for 13 bytes and just using the input string for the x/y separator for another 2
[Answer]
# [Perl 6](http://perl6.org/), 47 bytes
```
{sum bag([\+] (-i,*i...*)[.ords X%11]){*}X%2}
```
[Try it online!](https://tio.run/##LZFRa8JAEIT/yr1YEmsD9qFP2/0dgnXB0loEpZLggYi/PZ1vryFc7vZmZ2Ynl@/x9Dafb@XpUN7n@3Q9l8/9T7f9eN6V7uW4Wh6HYVj22@F3/JrKZrFe7/r78rFZvD7maX8rh246XcdL1/dz9WoRVs3Cws08wt1N5RpaVFJRJTOrlKqKrlcntRmwEMxcjSLSKj6PBhaDaCGHgEbxgdFZJFU47iGrJi1P@jTAMfRkD04QNBqwJkCkX@R1JTQ2LFC1VsaWA7YEGmbAYV8AgyJamREhT9rwVNITmMO7GixVkiK7IxVgZyxLv1xXa/OSlFIQe7Qccj5vXj0TTAVPhUzVconGmL4ZnalIkdGwl/@LlPhqB5x4@Q9sYYv/UwbmbNg1SZLAOOla/QM "Perl 6 – Try It Online")
* `(-i, *i, ... *)` is the infinite repeating sequence `-i`, `1`, `i`, `-1`, ...
* `[.ords X% 11]` slices into that sequence with the ordinal values of the characters in the input string, modulo 11.
* `[\+]` performs a triangular reduction (or "scan") on those values, producing a list of the coordinates visited on the complex plane.
* `bag()` creates a `Bag` containing those coordinates, each of which has an associated multiplicity (the number of times it appeared in the list).
* `{*}` fetches all of the multiplicities from the bag.
* `X% 2` crosses those multiplicities with the number `2` using the modulus operator `%`. Odd multiplicities result in a `1`, even multiplicities result in a `0`.
* `sum` sums those remainders.
[Answer]
# [Common Lisp](https://lisp-lang.org/), 198 bytes 186 bytes
**Solution:**
```
(let((p 0)(c 0)(h(make-hash-table)))(progn(loop for s across i do(incf(gethash(incf p(nth(position s "^>v<")'(1e3 1 -1e3 -1)))h 0)))(maphash #'(lambda(k v)(incf c(mod v 2)))h)(write c)))
```
[Run it!](https://tio.run/##TZlNblxHDIT3OcXAWWS0MBAnW4JHIaDIciREsgRJYI7vPNZXfA7iSJqZft1s/lQVOXdPj@@vP35cv95/e719u32@/7h/uzxePmVm1PGjuo8/qisijlf6v47/ea9rXkce/6qPt2Z168FjVcxfx7tam/Nkz6Md3X3s1rNY@9dsO7@Pj4@P8thYux1Lap4@np39c56r@TE2zd@HCcfSMXOsm10yMFTrZ0Hz5qw7/sgek48Fx@9o9j72OJbP6akLaEnNn7NqnhlL5kyueew7h8/qng31axbwlu6U82zqsnO8Xsa4InVRTuuWW44rlbaZH/PZ8dis6Hleb@Mm@WGMP@w@fioMx9ty7xgROnEM1iHHunmp3UL7jNmNF@cmBGCuP8@NGS0/6zwZd@whD8tFtQ/KLrlmdpVj5/FMvD12tvxR8o48pxs268cNs@ekgHYeGyeAc83SneV0x0@mlYKu2KV8wHHV8kZPnmACf5Gg40HFJu2JkgPkcW1Cuii3u7XZbIxzdNG5pJJYeaGsIqgcaQfOYsKvC8@VVQ7zhw5P3UqRamokZTY5Oo@lbIvEz7NKh2GcUydcXVoZnF6qHTIlMUZZioHacg7RBblycSWdP3arUEsVonKXDVOOcmuUk4aAyDg5ThvPNeRR/NrU9lyI9AIDgAB9NkbKhnkgfSyHYT5xlAvSGaRSkAsUJLtSW8c@S9WoSFlDVs8zyoZZbKe2a123UmarQghukanU40SLV/LSGO/PdR3qj@RVXLRhkkVapfC7TnTZ8bjAx5CVwS8wSLA5V3K2Nc7niHkqBXHzqeIgMCCq8u2YmULDIgkNICRoCod4Kc/KEb4MjtR95V@h6RwmuFVygmn6meQS0B0Oq/NJ0NWgvZJMGQe@ySzApsnD9sV1YKoeQGmXTAjN2yUvhIJokrIQyAb/5YneGEbQlXapChVhcE1OUQ0sdvJgKRq6bpSjqhKjPAreEQYq7hgPEKUBtgFWEqyhxaQehVFxsovMUlqRT@UrgL6QDh5PIGjC6kLsBVTdzGmk/G7FGN4CuENM7LItak1xkhna3LXSShaVttZDGmtZLX/h@QjKWdsqEs117SCCmLHMEo6wIRHmVqIHrCyozXDxxRlHsQwl3Q6PsLA4NOBKP5RQZlEsrUsvi@iGqbf1gQpPd6PSgrBonfkSYGlqBPmSTmyywhAjEjftCJllW5D5AT/Ecl06JbGACBpGE5oIOF4ygo8KESEpUFTTuDEoQrMcNYcCMPXVqdoMjcBSG/YoL1Md5CC/KYELVlEA0oRmsSXsd14KqCHGIiq9Z4CGkgCNCaQwekYZAuEUnMIVVPbxUwFSZfjYq5SE8j9UUqStohGIuQblYYCt61U2IAA2h2IESiNyKWi8L3sUPbJG5lmhmcf/73EgNkHMoKLCrCrvO49VEZXmcSM0wKnEQUEZ1hP2Byy5VmM@0hB@kEh3BQqC7Jvmzo38LqA0ELOIEKpEaoPiRJwnpFnoITbFTEG6ZbczJFxKxoq2eWxsm1Sh5GEt6UOG6EJRZKu2YBNgiXtrqRe2qSQAYh1YRiHZVEvy7Nd7mjQOEYNWy@BZK8YgQYoMRUUiK546Fe2nRBMJOKEaKdxb0oiyQOaoBIA7YmalL1mtwNsGJRnZ34Ag@gDTLN6cSaYHsLBdFPIWwcvFHysUSKxgU6O89XhCAe5b0nhL2mCqIXvlsRsyrhDQNfJ7a6YQErzGlyRBrxAtNqGMlPHRpxQFcIEQyzDKBQRCOId7ldUo0oNGreai7UpFnQOGVuMBL6itsI4XRKkIELHZ2yagqMgYtQGwr4DEpJN2kBs3xFYt5StV6I2t3hLwjXZf5GqVpy3M21Bk3qQPk2BRu83tVHtqusIGAG8yWjnghgWssU5tQHzxW5WDMAAw6TGtQaEtFVc7xGkN6f0kMIORQTuuxAvh66LZtoi2hlw3oaGZq9Zkmvnt5nGJis2ajMJYrg8c4hy3@FW5WGIFyI/cjG0plAd1qjUojj7CHZCdH/QOGgawhMbaGF3mJdozJgtWSHv99KCh3cPQWQYqzWE31CJ0cm2hDSJLGH2Q7eZRw7jHEOBQoWk7dsgSpqZtmNHfyb8C5xARCdw0PKi7g@Y6FL1bBCgAIuGIdU0XyUJkI3u5yITT0FSgI3faQ7@@QxkRRacrH0mmCyYgvmOMMs8zGtrxE3ncRhWVcbj7tRyTP9EEGAO5gn7CZ1NjuQEFu4vkSaYW4QFQu6hzo2OHSbUhLeRH8Rptpwkx0/o7t6PeAUSwbZwinuz2YKNyh1mB2No8pjLcxaAx5Ec1QumWlbgJ38MgBMiRs@UIedxFh6HcAHziJ8SG9bcphAatfJmgICB@/ARXoMfd/pLE1ICaWgPmTrRYhq5vqGFnVLSDTG0oGnrpc6og5m1bjiCAURAD4T7lHDFADn32slb43Z5yeMedJSFQu3f446EHzIUoiI7TFavUVGRh9bgM60ER6GT0P4s1F@NcNappCAHBj@iGDDdV3AuFFUyZT9LDTSCOZjrcfNJpVZ1CRbmHWlVU4b1s009a3xlko52XZcWzbX27dVxh3@j22BmdyUwhWj0NJJau3haciQjh3Np2l8xt5jjl/rTOCW/uKI4hjHUHoALUxU5ZqY2khwlnbp1NXRrl8MfP/pWBXq1M8eSGKaepuK2Ow/xOT2GxAvltw1nOUOVVrASsc8Zr@NgZgrG41/LF9gynlsX@4jfdmZkQJl5pSetU2/jU0j6CqQAoJrBMbsMYC5@XZ8rh/poeKygWK8IAJopEYdJbO5/3SJVw017yVQFT8nOW48mhcBicZ1AAxBg6zpGxu@xzZF@QTZjkUHe541wFkXx3Iw2u@xLMW@Ex5S1YYK9Sdz8HQaRY22Y7PpANHtlSHedUGvEei1l0sL5mg0htQ62w2jKJ8LRbePp4EK@WRE1zgSqOdVH7@wl3obETKGtKGN/4qRqmSUf1Ja3O9l2W5b1z@@4dfe9s0tVF6pla/O1MreA0eJQZkNn3htADxzJeljmbTo8uMLq2jvjKpD0epLsLvhdQghrwXADWpbXSx2rXVpfHpnSG1pCx32ohCjy69Vcx4alYLr3SxoI5sbOa9gix6anC4wLPquGz/e4BkZebMiDaNrJ@41QojInZ@QwG4yzGBW5ha7@Ywupep3d6GGL1Ux4TRMXZdfgk3RnCcnoZWNrfwuzcMjyXAg1JWVyaiJTwFHRrylOdnbgywNAK5mXlKVMjnnnCM4k@52xB39juXTTRoeWtWsqGDemUY00PKiep3ABU6JDcKyRavT3ejN5YMgMAIbvdsRffj/R@PwDy/K9f2G8XGZ/RM7rnJUEs@JIpM9MQh37tPdt8cCVzv35y@@ivShi9wDtucuBuKzsY/dPNL79cn@4/rtfXy@8317v58XB9vv3n/vPD7fvD54/bv57ub25urq9vL39/vz69vLxevr28Xd4vt3dvL@/vl8fL15fr4/e7b9e/7z/mEb24vF6/fzxcX1/eHz8eX74fyz9N3X26@e365f7Py5fL5/n1@cux88Nx5LH/8@3rPH359bfr0@3zX19vr/9c@obN7q7PL18vffljlt9c/317/Li/3B0vfvz4Dw)
**Explanation:**
```
(let ((p 0)(c 0)(h (make-hash-table)))
(progn
(loop for s across i
do(incf (gethash (incf p (nth (position s "^>v<")'(1e3 1 -1e3 -1))) h 0)))
(maphash #'(lambda (k v) (incf c (mod v 2))) h)
(write c)))
```
* **p** is a hashtable map key, generated as an index of the character within the string "^>v<", remapped to values 1000, -1000, 1 -1 representing the x,y. (x axis is +-1, y axis is +-1000)
* the hash value at that index is incremented by 1 (switch counter)
* the hashtable is than looped trough, and the map function increment the final count as modulo 2 of the value on a given key
Note: i (input) is defined it test as:
```
(defparameter i ">>><^>>>^vv><^^v^<<<>>^<>>^<^>^<<^^v^<v^>>^<<><<>^v<^^^vv>v><^>>^<^<v><^v<^<<^^v><>>^v<^>^v<vvv<<<v^vv>>^vv>^^<>>vv>^<^>vv<>v^<^v<^^<v^^^<<^><><>^v>vvv<^vvv<vv><vv<^^v^^<^^>>><<<>^<>>><^<<<>><>^v><^^vv<>>><^^^<^>>>>v<v^><<>v<v<v^<<^><v^^><>v>^<>^^^vvv<v^>^^^^v>v<v>>>v^^<v<vv>><<>^vv><<vv<<>^^v>>v<^^v>><v<v<<>^^vv>>^v>v>v<>^>^v<>>><>v>v<<v<^<>>>vv>>v>^<>vv^v><><^v^>v<^^>v<^v>>v^>^>>v>v>^>^<^^>vv>>^vv<^><>^><<v^<><<^<^>^^vv^<<^^<^^v<v<>^>v>>>>>>vv<<v>^>vv^>^><^<^^><<vvvv>vvv<><<><v^vv><v^^<>^>><^vv<><>^>vv>>>vv^vv<<^v^^<<v^^>^>vvv<><<v>^>^>v<v>^<^^^^<^>^>><>>^^vv<>v<^>v><v<v^>>v<^v<vv>v^>v<v^<^^^^v<^<^<<v<<<v<v^^>vv^>><<<v>>^^^>^<^>>>v^v><^^vv^>><^^vv<vv<v^><>>^><<<>>^^v^v<<v^<vv^^^>><>>^v^^^>>^>^<<^>v>^^v>><>v>^>vv^^<vvvv<><^v>^><<>>><^<^v^<<vvv^v<<<<<><><<><><<v>v<v>v><^v^^vvv>><>^>^>^v<<vv^^^v^vv><v><><v<v<<>>>v<^<^v<<>^v<<^v<><>v>>^^>^<v^<<^v^^^vv>><v^<v>^v><^<>>>>^^<vv<>^^>^>v^v^^>><>^^<^v^<v<<v<^<<^^vv>v>^<vv<<^^v^vv^>^^<>v>^>^<>vv><v>>><<><<vv^^<vv<>>^v>^<<vv>^><<>^<v>v><<v^<v<><v>^<^<^><^^^^>>>^<>^^><>>v^<vv^<^<<vvvv>>>v^v>>^>v^><<>>v<>>^>><vvvvv<<vvvv<v>^v<vv^<>><<><v^^<^<v>^v<^<<>^v<v^<>v<<>^<<vvv><^><^^^<>>v^<<>vv><^^^>><^>v^v>v<v^>>v>>v>vv<<v<<vvv^^^>^<v^^<^<v<^<>>v^<<v>>v^><v<vvvvv^^^<v^^<><v<<^>>^><^<v^v^^>><v><>v>^<vvvv><<v^^v^>^>v>><>^^v>v^>vv^>v<^<<^vv^>vv^<v>^<v^<>^v>v^>v^<<>^^<^>^^>vv^>>vv>v>vvv><>^v<<<<v^>v^^v<><v<v>^<^><^><<v<>><<>v^^>>><<><>>><<>><v^^>><^>><^<>v^^vvv>v<^<<vv^>vv^><<>v><>^<>v^^v>^>v^<>^><v>^><<^v<v^^<v>><^^>>^<^<^v<v>^>^<^<v><><>>>><>^<^<v>v<v^>v><>v^>v^<<><^<>>v<^vv^^^>^<<<<>^>^<><^vvv>^^<v^v>v>v^v>v>>vv>^><>^vv>^<v<v^<>vv^<v<><>^>>vvv><>>^<<v^<<>^<v^>v<^^^<^<^^<>^>>v>^<v>vv<v^^>><<<<<>>v>^v>^>>>>v>>^^>^<<<^<<<v>>^><<<<^vv<<>^v<^>v^<v<<>v<>^<^<^<^<>>^^^vvv<v>^vv>^><^<v^>^v<v>><><vvv<^^>>v<^v>^>>>><v^<v^^<^^v<vvv<v>^^<<>><^<v^v<^vv>v>vv>^^<>^^^^>>^v><vv<<<v>^v^>>v^>><<<^v^v<<>><<vvvvv<v^vv>vvvv><v^v<^^^><vv^^<>><>><^>^^^^v>v><><v^<>^v<>^^<^^>^^^vvv>>vv^v^<v<vv^v>v>>>^v^^vv^<^v>v^v>>^v>v<v^<^^><vvv>><<>><>><v>v<^<v>>>>v^^v^^>^><<v><^<<>>v<>^^<<>vv^>>vv^^^v>>>^v^><v<<^>v<v><>>>^>>^<<>>^><<vv<^^>^^^v^^<>>>vv><<>v<><<<>v<<>>>v<>v<>^<vv^v<^^<<<v>^v>>^^>^><<^vv<><><>v>^v>^<>v>>^^^<^^>>vv>v<<<v^><<v><^v><>v<^<<^<>^vv>^><^^^^^<<v^^<>v>><^<v^^^vv>^v<>^<v<v>v>^><^<<^<>><^^>vv^<>^<>vv<>>v<vv^>><^^<^>v<><>vv<v<>>v><v^^^>^^^<<vv^><^^v>v>^<^>v^><<vvv>v^><vv<><^<><^>^v<><<v^<<><>^^^^<<^>>^>^v^>v>^<<^>vv^vv^v<>^<<^>v<^^<<v<v<<<^>vv^>><>v>><><v>v><v^><vvv>vv<<vvv>v^<<^v<^<><<^v>v<>>vv<<v^>v>v<<>>^vv^<^^^<^v>>^<vv>^<v>><>v>^^<<v^<>>>>>v^v>><>v^>>^<>>^<^vvv^^^<^v<><vvv^>^>v><<v>>^v>v<v>v^<v>v>^<>vvv>vvv^^<>vv>^^^^^>v<<^v<>>>><<<>>><vv>>^v^^v<v^>>>^>^v<^v>^v<>vv<><vvv^v<<<<v<vv>vv^<^vvv<^v>v^^vv<^>>>^^>>^^><>^>>v<>>>^^<<v<^<<<<<^^<v^^^<<>><<<^>^v^>vv<>>>^^v><<>^^^^<vvv><^^<>>>^><<^>><v>^<>^v^<vvvv^>>^><<>><^<v^>>vv^vv<^>>>><^>^v<^<v<^^<^<^><^<>>^<>v^v<<>v>v<>><<v<^v<<<^v<v<>><v<^<^>>v>v>><v^<v><>>>>>v^v>><^<^<v>><v^v>v<>v<v><<<>^^><>^^<^vv^^<>v><><><^>^^v^vv^<><>>>>v><>>^>^<<^<v<v^>v^^<v>>><<^^vv^^>><<^<vvvvv>><^>^>>^vv<><<>v>v^<<<^v<^^<<^vv>v<vvv><^v>vv^vvvv<^>^v^<<<<^v<<<>^vvv>^v><<>>v<v<^v^<>v>>^^v^vv>>>^v^^>>^<><><<<<^vv>>>>>v>v^>v<>><<<>^vv>^^^^<^^^>^^^^>^^^v^v><^>^>>>v<v<^<^^<<^v<<^<>vvv^^^^v^<<>vv>^^>>><^^v<^<<<v<>v<<><>v<><>^<v<<^>^^>><<v>^^><^^v<^<v^<^^<>^<>^v^>>^^v^v^<>v<>^<<<>^v^v>^<vvvv<>v<<>vv^<<>vv>>>>^<v><>>>v^><<>^v>><<>>^^v><^<>>vv^^^>vv^<^^v><v>>vvv^v<^v>v<<^^<>v^^^v^^>><v^>>v^v^vv<^>v^<^>^>v<v^><vvv^>^<>v<<^><^^<vv>v>>vv>v^>>^vvv>>v^>^^>vvv>>v><<>>^^v>v<v<><<<<^^v<^<>^v>><v^^^<>>vvv>v><<v>^^<^vvvv^v>v>^vv>^vv^^v><<>>^^>>v>>>^v><^>v<^^<>vv>v>v^^^>>^^^><<<<>>^>>^<^v<^<^<>^><v<<v>v<>^>>^<<v^^<v^vvvvv>>v^>>^^^<^^<><<><><>^v>vvv^>^^>v<^^>^<<^v^^^><>><<v<^^^<<<<>><>><<^^v><v^<<^v<v><<>^<v>^>^v>vv>><v^<^<v<v<v><^^^^>>><^<><^v^v<<<^>vv^<v^>^^v^>>><<<<^<>>><v>>>vv^>^^<v^v>>>v^<^<>vv>^v^^><<<v>v>v>><>>>v<^>^<>>^^<v^<<^<v^>><^v^><><v><><v^vvv<<>v>>><<><v>v<>>><^<^^v<v>^<<>^v>^>^>^^<^^><^>>>>><^^>vv>^<^^<><^>^<^^><^<v>v^>><^>^^^>>v^v<^>>^<v^<>^><><v>>^v<v^^^^v<^vv><^v>>^^^<>^<^<^>vv^v<<>vv>^<>v>^>^>vv^v<vv<^^^v<v>v>v^<^^^v><v<<<^^<><^^>>>><<^^v<<^>v<<vv^^^vv^vv^<v><>^v<v>>><vv^v<v^>>>>^<<<vv^>>v>^><<><<^<^><<vv^>v^>><>v^<<<>v^><>><<>>v><>v^<v><>^v>>><><>>>^vvv^v>vv>>>^^v^><<v<>>^^^v^^><<^v<><><v<<v<v<><<<v^<^^^<>v^^v<^^<<^>v<<v><^<<<<>><>^v>^<>^<^^v^vvv>^^<>^>><v^^vv^<>^<><<^^^v<^^^>>^^v>^>^<^>v><<^<>^v<><vv^vv<><<<<<<v<<v<<vv^<<^<^vvvv><v^v^v<>>>vvvvv^<vv^<^<>vv>^<><<v><>v^^<v<>>>vvv^><^<^>v^^<v>^<>>>^^v^<vv<<<<^><v<<<>v<<<v<>>^^^>^><>v>^v^>^<v^^><^v^^<^v^^>^v>>^^^<<><><<<>v>><^><>>>vvvv>v>>v>^^^^v<><vv<^<v^v>>^^vv<^>vvv>^v>>><v<v<v^<^>^^<vvv<vv<v>>^vv>^<<^<^<v>v^<vv^^^v>vv<v><v><v>^<v>>vv<>v>^^>v^^^<>v<>v^v<>^<><v><^>^<v^v><<^v^v^v<<v><<^^<^vv>^<^v><>v>><v^v^>><><><<<v<>v<^vv>v<v<<>^vvvvv^<<<^<vv><<><>v^<^v<<<^>v>v<v^<<^>v<<^<v><<<^>vv>v>^<^^v>>>><>vv>>vv>vvv<>^^<>^v^<>vvv<^^^vv>v><<<<vv^v><v^<^<<<><v<>^><<>^>v<^^<<>v>>v<<>><^^<<<^<^vv^^>v>v<>^^>>^v^vvv>^v^>v>>v>v>v>>vv^<><<<<>v^^>vv<^^v>>v<vv<^>>^<>^^v<><vv^<><v><v<<v^v<^^<^v^v<>v<<><vvv><<<^<^^<<>>^v>>>^v>>>v<>>^><<<><><<<v<vv<^<>v^^v^^>^<<^^^v^>^<<^>^>^>>>>v<v<v<>vv<<vv^<<^<vv>^^<^<<>><^v><><>^<v><v^>^v>^<^>^^><v><<^<v^^<<^><><v>v<>>><<^><v<^vvv^<<<>><<>^v^^><vv>vv<>^>^>vv<>v^<^<>vv><<>^<v<vv<^<^<><^vv<<^>>>v<>><<>>>^^^^<<^v>>v<vv>^^>v<v<vv^><<><>>>v>>^^v<^v^^>>v^<>>v^>><^<^^v<v<><<><>>^<>><^v<^^^^><>^>vv>>^vv<<>v<<<<<<><<<><<>><v><^^^<>>v<^><^vvv<>^>^^v>^<v><^v^vv^<<>v<<<<v>^vv>>v>vv<<^>^<>>vvv^<v<><>><>^^^^vvvvvvv<<>v<^><^^>vv^^<v<<^^<vvv<v<v<<>><<><v^^>><^<>^v^vv<<v<v<>><<>>>>>^vv<><v<>v><v>v>><v<v^vvvvv<><>v>>v<><<<^^<>^<^^<v>v^<vv>^vv^<>^<<^<vv><v<v>>v>^<>v^<<v^<v>^v<>><v>>>>^<<^^^v<^<>><^<><v>>vv^>^<^<^>>v^>^^^^>vvvvv>^v<^><^^<^^>^<^^^^^^^>v>>vv>v^^^v^^^<>v><^>>>v>^>^>^>vv<vv<^^>>^>>>v<>v><<^<<v^>^>>>>^^><^^<v<<<<>>v>v^v^^<>><v<^<<<<v^^^^<v<<<^>v>^^<vv<^^^^^v>^v^<v><>>^^>^v>^>^vv^v>v>v^>v>^>>^^^^>>^>>^><>><v>v>>><<^v^v^>^>^>>vv><<^>v<v<v^<<>>^v<<^v<<^><^>>^<v>^>vv>v>^^^>v^^<^<^^>vv>^^><v>>^v>^v<<^^^<<^v^>^<<^>vv^>>^<^v><<>v><^^^<^^>>vv>^vv>><^<<<^>vv^v>v<^<<<^<^<<><^^>>>v^<^^^>^<><^v>>^<<v<^v>>v^<^<^<^^^<v^><<vvv^<^v^vv^vv<v<<v<^<>^v>^^^<^^v<v<v><<<^<>^^^^v>v^v^v^v<v><v>>^v><vv^^^v>><<v^vvvv<<<^v<<><^>^<v^^v<>vvvv^vv<>^v<><>^^<>>vvv<^>><v^<<>v>v<>^v^>v^>><<>>^^<^v<>>^>^><>>^<v<v^^<^v><v^<v<><><^<<><v^v<<>vv<v<v<^>>><>vv^^<><<v<^^<<^<><^^^>^>>>^<^>>>^>><^^^<^v^^^v^v^v>v>v><vv>><vvv<<v><><^^>^v<v>><v><^><^<<>v^vv^v><^vv>^>>v<vv><^<^^v<^^vv<vv<v<v>v><v<vv<<>^^v^^v<<<^<>v^^^<><>>><^>v^^^v^vv<<<^>>v><^>v^<>>>>^<>^^vvv^^<><^>^^<><>^vvv^^<vv^>vv^^^^v<>vv<^^^v<<>><<vvvvv>v>^^^vv>><v><v<>vvvv<v^><^<>^>^<>v>v>v^vvvv<><^v>>>^^>><vvv<>^>^v^<vvv>v^vv^vv><>><>v^^v^vv<^v>vv>>v<v><^<<^v<>>^vv^<v>v><v>v>^v>^<v>^<<^>vv>v<^<^vv^<^><<<v<<^^vv<vvv><>v>v<vv^<><><^vvv>>vv<^^^v><^v><<^>^^v>^<>><v<>>^^<<<v><>^>^><vvvv<>^<<<><<<^<>>v^vv^>><^vv^^>^<v^<v>><^^>>>^v>^v<>^v<><^><vv>v^^^<^>>^<<^<^><<<^^<v<<^vv<^<>v<^<<^^<v<vv<<><v<v^<>^<>v>>v<^v>v<>^^vvv<>vv^v^<><v^vv^<^v^v><>^><v^<>>^^^<>>vv^<v>^^v><v<^>^^^^^^><>>vvv<<><><v<^>v<>v^v<<<<>v^>>>>^v>^^<v^>v><v^<^^v<<<<v<<<>^v<^>^v>v^^>v^^vvv>vv<>^>v><v<>^<vv><>>><<^>>><<v>v^^<^<<<<v^<>>>v<<<^v^vv<>^v>v<<<<>^^>><v><>v<v><^^>><>^>^>v>>><v>^vvvv<><><^>>^v^><<>^v<><><^><<<>v^^>v>^>v^<v^vv<>><^vv^^>^^><vv<<>v>v^^>><v^>^<^<>>>vv<>^>v>v^<>v<^<<v>>>^<>v^>v>>vv^^<>>v<v<<^<>v>v^<^^^>v^^>v>v>vv<^<v>v^^><<<v<><>^^<>v>v>^^v>v>v^v>>^<v^v>><>^^>^<>>>^vv^><v^<^>v^>^v><^>^^^vv^^v<>vv<>>^><<^v>^v^>>v>^v^<<^^^vv<<vvv>^vv^v<<<v^^<<><vv<>>^^vv>^^^vv>><><v>v<^v^>>>vv^><>><v<^v<>^><v<^^^^>><^<>v>^v<^vv>v>v<^<>v>v>^<vv>v<^>vvv<v^<vv<vv<>v>^><v^v<>>>>>v>><^v<>v>^v><v^v^vv<>^<vvv^>><v^<vvv^^<^vvv^v^<>><v>v^^v<><>v^^^v<<<^><v<<<>><<vv<<><vvv^v>>v^v<v^>>><<v<>^v><>vv<<v>v^vv>v^v<^<vv<><><^v>^<vv>v^^>>^^^><vv<><^>>>^<v^<<^^>^>vv^><v<vvv>^^>>>^><<vv>vv>^<>>^^><^v><<>^<<<v^>^")
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~37~~ ~~29~~ 27 bytes
**Solution:**
```
+/2!.#:'=+\-99 0 99 -1 1@5!
```
[Try it online!](https://tio.run/##TZlNjmRFDISvMsCCBRpgkFiAjMVBkC8wC3Zx/eY5vvAbxNBdXZUv0@mfiLDr6@d/v358/PTLb9/9/MOfP/710z@f//jj06@fnh@fv3z68vfv333f3TXPj5GeF6Opqucv/z/P/7yn2b@rn3@j561dLT/4rKp99bzrtb1Pah9VSXp20y72/rPb7u/n4@ejfjb2bs@S2aefZ3f/3udmf6xN@/ox4Vm6Zq51u0sXhnr9LhBv7rrnRWtNfhY8v0vs/ezxLN/T2xfwktmXu2qfWUv2TK757LuH72rthv61C3jLd@p9tn3ZPd5/1rqifVFOk@yW50rjbfbHfvY8tiu0z/tt3GQ/rPGP3c9Ph@F52@5dI8onrsE@5Fm3f3q38j5rtvDi3oQA7PX3uTVD9rPPs3HPHvawXTT3oO2ya3ZXO3Yf78bba6fsj7F37DnfUKxfN@yemwLeeW3cAO41x3e20xM/mzYOumPX9gHHjewNbZ5gAq9I0PWgY9PxxNgB9rg3IV2c25I3241xji@6l3QSOy@cVQSVI@PAXUz4feG9ssthX/jw9q0cKVEjbbPJ0X2sbVs1ft5VPgzjkjqV6vLK4vRx7ZApjTHOUgz0lnuIL8iVhyv5/LXbhTquEJe7bdhytFtrkjQExMbZcd54r2GP4ldR23sh0gsMAAL82RppG/aBzrEchvnE0S7oZJBLwS5wkOJKb133LFXjImUNWb3POBt2cZyq1Lpv5cx2hRDcIVOpx40Wf9lLa3w@93WoP5LXcfGGTRZ5lcOfOvFl1@MGn0BWF7/AIMPmXinZJpzPEftUG@L2U8fBYEBU7ds1s42GQxIGQEjQNg7xpz1rR@QyONL3tX@NpnuY4dbJCab5Z5NLQHclrMknQ5dAeyeZMw58s1mAjchD5eI@sF0PoHRKpozmSskboSCapiwMssV//aI3hhF0p127Qk0YXJNTXAOHnTw4joavW5OousQoj4F3jIGOO8YDRB2AFcBKgglabOrRGFUvu9gspxX5NLkC6Avp4PEGgjasKUQdoPpmSSPntxxjeAvgLjNxynaoNcfJZnjz1IqcLC5tr4c0zrI5/sLzVZSzt3UkxHXjIILYdcxSiXAgEeZ2ohesbKjtSvHVG0ezDCWthMdYOBxacGUeaihzKBb50scivmH7bX/gwvPdqLQiLF4XvgRYRI0gXzqJTVYEYkzioR0js20rMr/ghzqu66QkFhDBwGhDEwXHW0bw0SAiLAWGalo3FkUYlqPmUAChvnlVW6ARWFJgj/IK1UEO9psTeGAVB6BDaBFbxv7kpYEaYhyiojsDNLQEECaQwugZZwiEM3AKV3DZ1zcFSJXh46xyEtr/UMmQto5GIeYEysMAV9enbEAAbC7HCJRG5FLQeN/2OHpkjc2LQguP/9/jQGyDmEVFVVjV3k8euyKmw@NBaIDTiYOCCqw37A9Yci1hPtIQfrBITwUaguIbcWchvwcoLcQsIoQqsdqgOBHnDWkOeohNMdOQHtmdDKmUUrBCMY@NY5MrlDycI33IEF1oipRrCzYBlri3l2ahQiUFEPvACQrZpjmSZz/dadY4RAxanYDnnBiDBCkyFBWJ7Hj6VLSfE80kkIQSUlhX0oiyQua4BIA7Yhalb1ntwMcGJxnZL0AQfYBpEW/JpNADWKgUhb1F8PrwJwoFEhvYNCgfPd5QQPqWDt6SNpgayD55nIaMKxR0jfy@mhmEBH/jS5JAJ0SHTSgjZ3zplaIALhASGUa5gEAI50qvchrFejCoJS6qVCrqHDCMGi94wW1FdLwhykWAiG1dm4CiImPcBsC@BpKQTsdBadwQW3OU71ShN456a8C3lL4o1WpPR5grUBTepA@zYHG7ze1ce266KgYAbzbaOZCGBayJThUgfvjtykEYAJj0mNGg0JaLSwlxR0NmPwvMYmSgxJV4IXxTNNcW0daQ6yE0NPPMmUwzf908LnGxRZNRGMf1hUOS4xG/LpdIrAL5kZt1LYXzYF61BsXRR6QDivOL3sHDAJbQWAejJ7xEe8ZkIQrprt8ZNCg9DJ1lodIS9kAtQqfPFtogsoTRB9keHg2MZwwBDg2aVnVDlgo1XcOM/m7@DTiHiGjgRvCg7w6a@1D07hCgAoiMI9E1GpKFyFbruCiEI2iq0JE37aFfv6GMiUKdykeS@YINiN8YY8LzjIZu/EQeK6jiMq50v5Fj9ieaAGMgV9DP@BxqnDSgYPeQPM3UojIAUoq6LzpxmFUb0sJ@NK/RdoYQu6O/@zrqG0AU29Yr4snuDDamb5hViK3LYyojXQwaw350I9RpWYmb8b0CQoAcOTuJUMZddBjODcCnvkFsRX@HQmjQJpcpCgLix09wBXo87S9JTA24qQ1g3kSLZeh6QQ03o6IdZGpD0dBLv1MFM69iOYIARkEMVPqUd8QAOejtZaPwpUw5suPNkhCo0g1/MvSAuRAFpXpdcUrNRVZRj8ewGRSBTkH/t1j7MC5V45qGEBD8iG7I8FIlvVBFwUz4pDPcBOJopivNJ53WzCtUnHuoVUcV3muFfjr6LiBbSl5OFM@19UrreMJe6Pa6GV3IzCE6PQ0kjq@uCM5GhHDuXLtL5oo5zqQ/nXfC2zeKYwgT3QGoAHV1U1Zqo@lhKpk7b1PXQTn88a1/ZaA3J1MyuWHKGSpW1HGF3@kpIlYgv2s4JxnqvKqTgPPOeAMfN0MIFussP2zvSmpF7B9@052FCWHik5a0TnONzxztI5gGgGICy@S2grHw@WSmXOmv6bGKYokiLGBiSBQmvXPz@YxUCTftJV8VMCV/ZzmZHBqHwXkGBUBMoOMdGafLfkf2A9lUSA511zfOdRDJ9zTS4HouwbwVHnPeggXxKnX3bRBEiik2x/GFbMjIlup4p9KI9zrMooPNNQUiKYZGYSkyifAoLTx9PIg3R6KhuUIV17lI@X4iXWjdBCqaEsYPfrqGadJRfU2rc31XZLlubi/d6Ptmk6kuUi/Ukm9n5gRnwGPCgMy@L4QZOE7wcsLZdHp0gaW5OuIrE2U8SHdXfC/gBA3gpQCiS@ekT9RurJ6MTekMoyHrvtVCFGR0m69iKlOxPnqljQVz6mY1yghR9FSVcUFm1fDZffeAyOtLGRDtGtm88SoUxsTs/AaDcRbjgrSwc19MYbXO6eoMQ6J@JmOCmnq7jpzkO0NYSa8Ai/ItzM0tK3Mp0JCUxaWNSKlMQa@mMtW5iSsDDK9gXjaZMgnxzBOZSeidsxV9o9K7eKJDyztzlA0b0inXmV5UTlO5BajQIaVXaLS6Mt4sXSyZAYCQUjr24fsR3fcDIM//@oX7dpHxGT1jel4SJIKvmTIzDUnoz963zQdXuu/rp7SP@aqE0Qu8kyYH7o6yg9G///j4Dw "K (oK) – Try It Online")
**Explanation:**
Create list of steps, create path, group, count each repeat, if mod 2 is 0 then off, else on. Felt very AdventOfCode-ish.
```
+/2!.#:'=+\-99 0 99 -1 1@5! / the solution
5! / input mod 5, "^v<>" yields 4 3 0 2
-99 0 99 -1 1 / left, null, right, down, up
+\ / sum along
= / group into key=>value
#:' / count each value
. / take the value
2! / modulo 2
+/ / sum up
```
**Notes:**
* **-8 bytes** by stealing David Horák's method of squashing x-y into x (I know it has limitations, but it works for the examples)
* **-2 bytes** thanks to ngn
[Answer]
# [krrp](https://github.com/jfrech/krrp), 137 bytes
```
^>:\L\T[length],^v>xy:!tTxy!V?[elem]tv[without]vLtELtv?#?E>V!c#!f>?=c$62.@V#!r>+x1y?=c$60.@V#!r>-x1y?=c$94.@V#!r>x-y1@V#!r>x+y1.LT00E>00.
```
[Try it online!](https://tio.run/##bU7LDoIwEPyWBk4gTdsYoyQWL731SLjwuBAUIz5Cam2/viI2UtTLZHZmd2ZPfX8zBQeBqWhc8CLNu@ZyEG25qCRVOgYiVRpkSd50zbkUMn8cRXu9i1JywbiQiZcwmoHaA3uabGt/ReAu80BPQ4X1KCArRFbYLK2gIo0tCzWGPEWIUYSgCbiP8RryV9iHogGGUwvj6DiT7TAyc8fRSSBzcAKn1jeO@z/edwf584sbz8wT "krrp – Try It Online")
---
# Explanation
```
^>:\L\T ~ lambda expression, import list and tuple module
[length],^v>xy: ~ the answer is the number of lattice points
~ which were visited an odd number of times
!tTxy ~ current lattice point
!V ?[elem]tv ~ if the lattice point is already present,
[without]vLtE ~ remove it, else
Ltv ~ add it
?#?E> V ~ no further moves
!c#!f> ~ move character
?=c$62. @V#!r>+x1y ~ move right
?=c$60. @V#!r>-x1y ~ move left
?=c$94. @V#!r>x-y1 ~ move up
@V#!r>x+y1 ~ move down
.LT00E>00. ~ initialize at point (0, 0)
```
[Try it online!](https://tio.run/##bZJBb6MwEIXPm18xUXrYtjQiUVXtVlrSS24co1ySVHJhKKM1NjIDgR72r2eNISm04TDyaD6/N8/irzH5aR9O706vwfM@3G/gy/cPpMjeYgFY5waLgrTygLJcGwZJBYNQMXCZS4RMx6XECewkqndOD95rFdTN80UIOEWLF0c0QIXrVJm92U4n1oWZIoRck@JiAtc/K3JMKUrBaiBUVBBjbDVBx/FAjCnDVmPKm7q5ogFRaQwqHrtCe2MLqx1KzA5cjW5Q4hYeX7AphDQo4gbax7GKXr/57kic6pIPVcjrswYYzHSFQOwBygJ7NhxYXfxA2ETEFlnNVusAtt8RpSEpjd3KQCvrAkezaRJcCex8o1QYETGaVvVPdPO0nMPLdjY1wX29aIakofe09e4w/4w9OMyt5zCJiaMc9vvxjNUPzaKjOqzMu6T99N5Oh0l7KtZH9WMC83Dj@@vAt6ajDKSISUj6sP8Q9@//0/fAvz3dhTeLxa952Aa6HH1b7Ep9ce1g8jkenJajqWsHCstxGQh@unbV8d9mXz2WV3YZyq9P/wE "krrp – Try It Online")
Unfortunately, *krrp* only has one rather slow implementation, making the long test cases difficult to verify.
[*krrp* String conversion](https://tio.run/##TVJBTsMwELznFSurB1CVvmDZC3DrjSNiJSsgJaJtosSYC38PM2sORJVrj2dnZycZ8/b5cbns@3Rd5rXIUy759DjmtfsPnKetdN2SyygPkqpVddeq6uqmau5mpoCrYwEEEJAm6XtRrcQrbgw/nFCr5Dq4aqiGGlaImjcyZKDNDkZ9FEKUHJwhUsHjPcWqoqGFfLjg0fFEDe2wobKA/kDwMM32uAKbNtTZVRtMW0ayBlFphjzaB0Ep4Q3mnBQPWbfohMdpjt5RoNElJKLaowPVOZaGX15XbfMyKaQAdW85xHzWvFokGB0sOkSqGos3xfDN0TkVU@RotBcvjSnxHzvSGS/fA7dU879TBGbccNdaMgkaZ7paU9dd83TD57B8lZeyykGG@TbkIq/pfEhyPMrdNs7fwOf1XYZ7IumU5EcG0V74Lb0F9pz2/Rc).
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~21~~ 20 bytes[SBCS](https://github.com/abrudz/SBCS)
```
+/≠/×⊢⌸+\0j1*'^<v'⍳⎕
```
[Try it online!](https://tio.run/##XZrNinbVEYXnfRXOGqLBOC/qSqRACEpEUPigIDcQTUhCJsGpeAuZOM@d9I182bWeVeecjoi@/fY5e@/6W2tV7f7qh@9@/8c/f/Xd9998fPvnv//0/dtf/vXFy9tPP3798dPP3/76y@f//fntb7@@/f23T7/8w7df/O61ol/f/vGf8@jH89DHD5@c5187O@r8JqKiMiKrMjPO113nP@er8@X5KiJ6vurzZZ5/z0/ntZjH6jwWeV48C53/nvWyePiscJaN15cPn2mv8/xscRY4686z5@ezWJ/n57lZtOPsmdpGB5kf6/yjd@ZEs3HMC3PE80Dp3HOM86tjofeqOVbUnCL49Rwz56XQCzGHi9bKs2jMUsXXY/JsouUrteP5p@aQY8N54bnXeXuW0iqlnWaXMTN0/vl1z8dx7zgmxjOFf2Rv6uz6kKGdUjvJ22NpXnsVK8uOcclYOV4eU@e4iud4b/5/Ps3j4/aJ03ycVcs/yZE5H@YTW5@D3D6c89Skx@vL1y8fXl7ImXlqzlpj2JghpygHFHu@G3MU1FlavpUxhR/nUwfPzr6kTSsDxidXzjT7KFeUKYVzS@/LklJEUya0YqBYpOIxAQmSOjBXOYnZnP/OzyTisi4VkXGXYkPW4EQ5rsrZSnqej/OOakmJGfgnCBRpVrdd8rR/JRsnNxVRjqEfJ02DEmFXVeWkahNo5fhsm4pVz/v6epa8fSj/lJJNya3iaxk1j89BJpMy05k1C7VWDa2n6se7qUKVbX1VydOHWooULVWbkGJcV7tAO3MVTxw@y2RuwpbyHiwIpYWqd85/@1DlOsGkuJpSpepmKflCQSHOTUFTqII2@YRtq@UdkIKMnE@7V5LYqocmPNpNSCfwaC1GeqkmBIGhOsZpMryDMmjlj7KQoN94MhvbwfMSaSJHjCtUToIBkFRoW7hZqSQzyG1gqwRv@H@emk1vH@qwTrVwleqN4BTgNJkFlKmWlBJeejaTwbigMFHnmPPfPoRkSi6miMbTuD3KSUbAdFg5VBukyEGpqbIDKwpCUSJi9I2TOGoekc/0Ynp7NsUc4i3XpDMuzRPsVnaxtoh99zx0x0tBap6lKsSo8Fys09vYISvhnqLsAIgmfwlE85NK5Pzv9iHPyTzqmKRX3LRwknV6CvajzmR8tDnYkAjmL0EInm/812Oqe4LDVmJwQanYE/ofFyj68vkcW2REyDsMTCR0Ct/48cYNsXNcxuFo@UH@D@hOlQYfNJhZKBLtDlWEw@78SwuK24fKhiJTwVEdEzBr8rftEBhf9QQruOSkWKINIVHtytTxbw4V@2r1QCTVpm9vcihNMy1/ypDHbtHOPFOjDI90VgXV@uDKgplKJRlw6SCZKCJ1zrIMo5yEMySkJYOlnTAwLnbT8eqBGx2X4gPIJPhUB0QkgbgJvwu6F8BlqdMOsalcgD8hioin5jEMrOLUZsJh2UatdVg7ITtYo/eEtTwqQhfqL6pq5YeWQ1fgOIKdxDeB3IKJFUzCJapGLQjaJbSkaa84i@WAhhsPCaMwV/4MyEF5oXSJVZ9K50Cp1qpeKEDknbCxbKVSUYF3vMJ4amltxRuJ7EoXBNlj6JLIMO21pTQ/yUHipVjOfeylXOFERNqwndBUoEEkd/hVIXak9IpqHPcGxWy2pWZRKPX0YaI0hTWGYIt@wytlauqFnORPJX7BagpQmlgtFsU5Tx2lKhR1JZ2CxPjuBepKqjRHIfVL@kuZBOEVnIZJ9BSXkr1xQ9VKDPx005@hOZQDSZpDLso22AXmWZxYJQaicPbZ@JEb9BAJqHegPoUSkhyBRFTbFFaa1hlXRBA@wS@aumpEdz2wt2hVChIh/9AZZgbaAVrCNotZcwhPhGOY2ZijvAl4qR/9pjsEUNI@o7FVbJLOBQMTVmkrDjVyLnJBJHBGZ7aAP6e97LJAdZvhjAqXpDGofVw28NlU6eRtrSiBnNG3ouwJye1DWA3Ywx96xS@0qSwAfm1c5iGdrVaEsG7vrtJkRPTuo2lkAOtaUel@WjuhCCkAxV27o2GVmCIfJ2Aj9XuhQYz@mA/IiOil9Ca27nDUPihBfBYlJdXTgC06hiNahDrjTEs3f4mDXVRJqwtrGt@sqCDTguXNLu47Eupx35bGd9Kr3/nQVLFtgBtVTArkBO3G1lx50hBO@7TEj16BzTTEZViPGYuescQG4IEmy0nKDYSjQQj3aquppG@Nio3h7YqnC3noeboLapVGsEB/94hAiUV69rZHKEIyS@0PqkAAZdJLHHbXcvqZIC2QJsmgIxHJ6c0R/h7nUPWKgBuQNsSZx@lL69ZszbgCq1XDHuAoggWMygjlCj0jDBnW3w15LF@o8hAuAPMDo1DlwjnIjBENoU9rYq8r4RyMXtrxJ54Iexfdtofxf3Mq5lE0QCKzqjUh48o49E25/bOmpLBWi4RnZdSGxb3K7dE77OStXaT0U7I1wjWpLIFy6Z/cCTo4Qc@koQqPMJDgq3d5mAydRMLUJdMuuyU9uGn3cnTggdp0ehjaE1rZM9EOPuaKtitcLeZ304fHOuBcodk7dogVpsgdNNBnJP8WOPrAQ@ED0YKX5RNYJJgeVnt0wcySXVCgEHGRMksj5kITXt8YFZAqCMV0jXnHDr9EVJ1GkqRAm16uDdfMGdAhjOJ27Bfv5htt1BIshKcGlpXyN9qFQ0H6oKz4wFRdbtThimtkKvR4zDB3vlueODgrcaTUZ@O5Wp6lPTdBZ7rPyJ1E7EAnWPYRLzcvVIcHRpU7TAzE4uY/leVuDi0k/6ohTLf2xFW8wozzzg3AdGfZ7SksBC9yVS4BbnFDerjPMIXRuJaNCwoJYfLQNhwWI5gAxLbCjLyTOwCAeSeKPEYfwzT6mg3SLjMdky/v3oGOcKc0UgRtSxAuMBqiJdynXSMbCYrsq/d3R9Pt6dE7/nJ7hZJyscbeUuxABMUEkq6LVnFqFh9Ww8v8Hsz1O7vMPlfx52Kpq04YASHR6NBcQM6bUu4Jw4qrzGfpIfQdr6ZCLKcYhJZbHAsr5SoqnHuH2lzxEMI5QQJGO4/LCu3iFI9H2i32NjRNnxI7M2VVQV5t3wD0llzRFtCJWGJ/SLAfGjsX8qgr5XNdE/rc0SjDLuskwAoojZ2OU1tJDxfO@HrMAbaxBU3x093vM2itlVWekDGNtkRoq/@w/qCXsrjS7@6ZgxvzcmYrD2MlbV0zesPSzmSM/b2WLKeomSfdGRhHPeYADAURxG2W3uuVppWsbQBrZYnv9wBAJudM3MNYjt7gEu8xI/J8gt6T28Kwwg3gp0gsJvW19y8egZMWtOFcDXH7cc3M@lHLbI8DEyYE@heSrtG/pxPX1UxBdmGyRaXmjuEV5HzMD33huXxio5iT@4avdlpa9jb1ew/eSEnsAkd8m0RfUY/5IdV13TLQrMRiIh2/zW4Qr31wK8S2vCN87REIc5CBnIfeWHI37QbqP9Z17Xspd@uxkz9rZBSJcVpYwJAD9ap26dbY24@6Dem9n@neK42dIbtKSVVTm2/pau@t9xIbRmb69sh5Qu3BcBmfy5qCTpguObq2Drky8922u97g/kcJbUClcG7cQHfXSjareVtRHnPTOVsTx95@Il48cveVXDAY9OWsquTeq41psbOx9oi36THD4xffPcCre@eEWM1NLRCz3fD7i3jYhQpjvq0drmAxTmT84pa/9uISK3qD0ukhk1VbedzyTkctdlr3JWI7txldwGrfxu18GT3OTZebJAIoEPP0hRnSoyfqVXW1k3IGQ1yeR5urmfD6rxR8U3mVsGfY3OC7d9Pk7F3OuysPus6d3pOwvhhKtxJcRQZ/RlDM5tPXD/4TgNrmyQmi6nnoeWCIRrE8Zi9fG5YRz33S3lIzxqSn3j@/8B8GgL3cFjBl6njOe2vPf41LwKvMvZ50m@2rMkZc8J6bPbSFFSqKQ3928D8 "APL (Dyalog Unicode) – Try It Online")
uses `⎕io←1`
`⎕` input
`'^<v'⍳` find the index of each input char among `'^<v'`, i.e. `^` becomes 1, `<` 2, `v` 3, and anything else 4
`0j1*` *i* to the power (the imaginary constant)
`+\` partials sums
`⊢⌸` matrix in which each row is the list of occurrences (indices) of a unique partial sum; padded with 0s to make it rectangular
`×` signum - all indices become 1s, the padding remains 0s
`≠/` sum mod 2 for each row
`+/` sum
[Answer]
# [Ruby](https://www.ruby-lang.org/), 67 bytes
Inspired by orlp's C solution. Assembles a list of all visited positions, and then for each unique one (using setwise intersection `(d&d)` since it saves a byte over `d.uniq`), count the ones with an odd number of occurrences (technically, map it to the occurances%2, and sum them together, since that does the same thing)
```
->s,q=0{d=s.bytes.map{|c|q+=1i**(c%11)}
(d&d).sum{|c|d.count(c)%2}}
```
[Try it online!](https://tio.run/##LVHRToNAEHz3K3ypgapEfB72R5puYqFVH7BU4JKm5dtxZk9Cjru92ZnZ4Xc@XNdTs77a@HJp3m5dM1aH63Qcq/5juN3b@@W5qb@326Ld1HW5PBTdU1dW49zrrqva8/wzFW25eV@WdXg87T6P01i1X@d@2K/JEtyRAIcbYO5mBpaTc2GJRZYAJJUSi8aXJ7ZBMCcMxkYScSWfeQaTgbQiF4EayScMzyRJxOleZAnUsqAPAzo6n@iREwlCDbJGgIdfyfOKaNmASxW5LFsmMAIImRFO9gmAKDyXNaLIg9YtlPi4zMk7GxAqQRHdHgpi11gIv7pOyPMqKaZAds85xHyWvVokGAoWCpEqYvHMGL41uqZSihpN9uJ/KSV9uRNc8eo/aCs2/z9FYKaNdllSSci40kX6Aw "Ruby – Try It Online")
] |
[Question]
[
When I was a kid, and wanted to count the dollar bills in my life savings, I would count out loud:
>
> one, two, three, four, five, six, seven, eight, nine, ten;
>
> eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty;
>
> twenty-one, twenty-two, twenty-three, twenty-four, twenty-five...
>
>
>
Eventually I got tired of pronouncing each of these multi-syllable numbers. Being mathematically minded, I created a much more efficient method of counting:
>
> one, two, three, four, five, six, seven, eight, nine, ten;
>
> one, two, three, four, five, six, seven, eight, nine, twenty;
>
> one, two, three, four, five, six, seven, eight, nine, thirty...
>
>
>
As you can see, I would only pronounce the digit(s) that have changed from the previous number. This has the added advantage that it's considerably more repetitive than the English names for numbers, and therefore requires less brainpower to compute.
## Challenge
Write a program/function which takes in a positive integer and outputs/returns how I would count it: that is, the right-most non-zero digit and all trailing zeroes.
### Examples
```
1 1
2 2
10 10
11 1
29 9
30 30
99 9
100 100
119 9
120 20
200 200
409 9
1020 20
```
A full list of test-cases shouldn't be necessary. This is [A274206](http://oeis.org/A274206) on OEIS.
## Rules
* Your entry must theoretically work for all positive integers, ignoring precision and memory issues.
* Input and output must be in decimal.
* You may choose to take input and/or output as a number, a string, or an array of digits.
* Input is guaranteed to be a positive integer. Your entry can do anything for invalid input.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **the shortest code in bytes wins.**
[Answer]
# [Python 2](https://docs.python.org/2/), 28 bytes
```
f=lambda n:n%10or 10*f(n/10)
```
[Try it online!](https://tio.run/nexus/python2#DcexCoAgEADQub7iltDioDubFPqSajBCEOoKcfDvzenxalhv/5yXB3EyML0JmKagZWYaa2gtEAU2RoNMyE2LC6G1re2G0BAdru@@FCVDQbVnhRB0GesP "Python 2 – TIO Nexus")
A recursive formula works out very cleanly. If the last digit is nonzero, output it. Otherwise, remove the final zero, compute the output for that, and multiply it by 10.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-3 bytes by having I/O as a [decimal list of digits](https://codegolf.stackexchange.com/questions/110836/efficient-counting/110861#comment269927_110836).
```
ṫTṪ
```
Test suite at **[Try it online!](https://tio.run/nexus/jelly#@/9w5@qQhztX/dc53O7Ndbj9UdOayP//o6MNY3WijYDYUMcATIL5OpZA0hgsYglmA2Vh8lC@EZhvBBU3AdIwdSCZWAA)**
### How?
```
ṫTṪ - Main link: listOfDigits e.g. [1, 0, 2, 0] or [1, 1, 9 ]
T - truthy indexes [1, 3 ] [1, 2, 3 ]
ṫ - tail (vectorises) [[1,0,2,0], [2,0] ] [[1,1,9],[1,9],[9]]
Ṫ - tail pop [2,0] [9]
```
---
If we could not take decimal lists a 6 byter is:
```
DµṫTṪḌ
```
Which you can see **[here](https://tio.run/nexus/jelly#@@9yaOvDnatDHu5c9XBHz/@jew63P2pa4/7/f7ShjpGOoYGOIZC21DE20LG0BHJBfCBtZKBjBGSbGIDEjAxiAQ)**.
This does the same thing, but converts an integer to a decimal list beforehand and converts back to an integer afterwards.
[Answer]
# C, ~~30~~ ~~29~~ 27 bytes
Proud of this as I abuse two C exploits to golf this up (described at end of post); This is specifically for C (GCC)
---
3) `b=10;f(a){a=a%b?:b*f(a/b);}`//27 bytes
2) ~~`b;f(a){b=a=a%10?:10*f(a/10);}`~~ //29 bytes
1) ~~`f(i){return i%10?:10*f(i/10);}`~~ //30 bytes
[Try it online (27 byte version)](https://tio.run/nexus/c-gcc#@59ka2hgnaaRqFmdaJuommRvlaQF5OknaVrX/s/MK1HITczM09Cs5lJQKCgC8tM0lFQzY/KUdNI0jDU1rbEIm2EXNjTAIW6ESxyXBgPcMgZQmaLUktKiPAUDa67a/1/z8nWTE5MzUgE)
---
First attempt (30 bytes): Abuses the fact that in GCC if no value is declared in ternary, the conditional value will be returned. Hence why my ternary operator is blank for the truth return value.
Second attempt (29 bytes): Abuses **memory bug** in GCC where, as far as I understand, if a function has no return value, when more than two variables have been meaningfully utilized in the function, the last set value of the first argument variable will be returned.
*(Edit: but this "set value" must set in certain ways, for example setting a variable with `=` or `+=` works but setting it with `%=` does not work; weird)*
Third attempt (27 bytes): Since I must meaningfully utilize the second variable (b) anyways to properly abuse the memory bug mentioned above, I may as well use it as an actual variable for "10" for substitution.
*(Note: I should be able to swap `a=a%b` with `a%=b` to save another byte but unfortunately this causes the memory bug exploit above to stop "working", so I can't)*
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~7~~ 6 bytes
```
!`.0*$
```
[**Try it online**](https://tio.run/nexus/retina#U9VI4PqvmKBnoKXy/78hlxGXoQGXIZC25DI24LK0BHJBfCBtZMBlBGSbGIDEDA0A) (all test cases)
Output matches of a digit followed by any zeros at the end of the input string. Though not required, this also happens to work for `0`.
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 18 ~~32~~ bytes
~~I think I'll have to spend sometime on this later and see if I can compress it a bit. But for the moment here it is.~~
Turns out I was thinking about this totally the wrong way. Now the process incrementally applies a mod (1,10,100,1000,...) to the input integer and prints out the first one which isn't zero. Bit more boring, but shorter.
```
!N%*I1^\.u;u@O\;;r
```
[Try it here](https://ethproductions.github.io/cubix/?code=IU4lKkkxXlwudTt1QE9cOzty&input=MTAyMjAxMA==&speed=20)
```
! N
% *
I 1 ^ \ . u ; u
@ O \ ; ; r . .
. .
. .
```
[Answer]
## JavaScript, 21 bytes
```
f=n=>n%10||10*f(n/10)
```
### Test cases
```
f=n=>n%10||10*f(n/10)
console.log(f(1 )); // 1
console.log(f(2 )); // 2
console.log(f(10 )); // 10
console.log(f(29 )); // 9
console.log(f(99 )); // 9
console.log(f(1020)); // 20
```
[Answer]
## Javascript ~~19~~ 18 bytes
Thanks to ETHproductions for golfing off one byte and Patrick Roberts for golfing off two bytes
```
x=>x.match`.0*$`
```
Returns an array of strings that match the regex of being at the end of the input string with any character followed by the largest possible number of zeroes.
[Try it Online](https://tio.run/nexus/javascript-node#S7P9X2FrV6GXm1iSnKGhr2egpaKfrvm/uKTINjqWqzwjMydVA8jRy0nNSy/JsLE00ATxCkqLMzSUlLSRpLQNDTU1uZLz84rzc1L1cvLTwXK5iQUaaZp6WfmZeRrqCuqamv8B)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes
```
a₁
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wP/FRU@P//9GGOkY6hgY6hkDaUsfYQMfSEsgF8YG0kYGOEZBtYgASMzKIBQA "Brachylog – Try It Online")
The suffix builtin `a₁`, for integers, is implemented as:
```
brachylog_adfix('integer':1, 'integer':0, 'integer':0).
brachylog_adfix('integer':1, 'integer':I, 'integer':P) :-
H #\= 0,
H2 #\= 0,
abs(P) #=< abs(I),
integer_value('integer':Sign:[H|T], I),
integer_value('integer':Sign:[H2|T2], P),
brachylog_adfix('integer':1, [H|T], [H2|T2]).
```
Brachylog likes to be able to treat integers as lists of digits, and for that it uses the custom utility predicate `integer_value/2`. The interesting thing about `integer_value/2` here is that since it has to be able to correctly translate a digit list with leading zeros, it ends up also being able to translate an integer to a digit list with leading zeros, so predicates that don't want that to happen (most of them, *especially* the nondet ones like `a`) forbid the heads of their digit lists from being 0. So, while `a₁` generates suffixes shortest first for lists and strings, it skips over any suffix of an integer with a leading 0, which in addition to removing duplicates, also means that the first suffix generated is the rightmost non-zero digit with all trailing zeroes.
[Answer]
# Bash + coreutils, 12
```
grep -o .0*$
```
[Try it online](https://tio.run/nexus/bash#@59elFqgoJuvoGegpfL/vyGXEZehAZchkLbkMjbgsrQEckF8IG1kwGUEZJsYgMSMDAA).
[Answer]
## [Grime](https://github.com/iatorm/grime), 5 bytes
```
d\0*e
```
[Try it online!](https://tio.run/nexus/grime#@58SY6CV@v@/oYGBkQEA "Grime – TIO Nexus")
## Explanation
```
Find the longest substring of the input matching this pattern:
d a digit, then
\0* zero or more 0s, then
e edge of input (which is handled as an Nx1 rectangle of characters).
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 74 bytes
```
{({}<>)<>}(()){{}<>(({}<>)[((((()()()){}){}){}){}]<(())>){((<{}{}>))}{}}{}
```
[Try it online!](https://tio.run/nexus/brain-flak#PYrBCQAxEALb0Ucg3HvZRsK9rgyx9k2Wg@ggKJYgRzLSAKku@KeFFtuUL2/0MSkgZDnJk4eqZ84a3wY "Brain-Flak – TIO Nexus")
Only prints the last non-0 and all trailing 0s.
**Explanation:**
```
{({}<>)<>} # Move everything to the other stack (reverse the input)
(()) # Push a 1 to get started
{ # do...
{}<> # pop the result of the equals check (or initial 1)
( # push...
({}<>) # the top value from the other stack (also put this on the stack)
[((((()()()){}){}){}){}] # minus the ASCII value of 0
<(())> # on top of a 1
) # close the push
{ # if not zero (ie. if not equal)
((<{}{}>)) # replace the 1 from 3 lines back with a 0
}{} # end if and pop the extra 0
} # while the copied value != "0"
{} # pop the result of the equals check
```
[Answer]
# Vim, 19 bytes
Two versions, both 19 bytes:
```
:s/\v.*([^0]0*)/\1
:s/.*\([^0]0*\)/\1
```
Plus a trailing carriage return on each.
[Verify all test-cases online!](https://tio.run/nexus/v#@2@lWqyvpxWjER1nEGugFaOpH2P4/78hlxGXoQGXIZC25DI24LK0BHJBfCBtZMBlBGSbGIDEjAwA) (One byte added to test on multiple lines)
[Answer]
# TI-Basic, 18 bytes
```
If fPart(.1Ans
Return
Ans.1
prgmA
10Ans
```
[Answer]
# R, 33 bytes
Implemented as an unnamed function
```
function(x)rle(x%%10^(0:99))$v[2]
```
This applies a mod of 10^0 through 10^99. `rle` is used to reduce the results down so that the second item is always the result we want.
[Try it online!](https://tio.run/nexus/r#S7PlSivNSy7JzM/TqNAsyknVqFBVNTSI0zCwsrTU1FQpizaK/V9elFmSqlGcWFCQU6lRnFqoYaRjaGBgoGOkqZOmqaOurmNqoPn/PwA "R – TIO Nexus")
[Answer]
# [Zsh](https://www.zsh.org/), ~~18~~ 16 bytes
```
<<<${(M)1%[^0]*}
```
~~[Try it online!](https://tio.run/##qyrO@F@ekZmTqlCUmpiikJOZl2qtkJLPlVqWmKNQnFqioKuroAIS/W9jY6NSreGraagaHWcQq1X7PyUfKGrIZcRlzGXCZWjAZWwAxEYGXCYGYAwigDwA "Zsh – Try It Online")~~
[Try it online!](https://tio.run/##qyrO@F@ekZmTqlCUmpiikJOZl2qtkJLPlVqWmKNQnFqioKuroAIS/W9jY6NSreGraagaHWcQq1X7PyUfKGrIZcRlzGXCZWjAZWwAxEYGXCYGYAwigDwA "Zsh – Try It Online")
# [Bash](https://www.gnu.org/software/bash/), ~~25~~ 20 bytes
***-5 bytes** by @roblogic*
```
echo ${1#${1%[^0]*}}
```
[Try it online!](https://tio.run/##S0oszvhfnpGZk6pQlJqYopCTmZdqrZCSz5ValpijUJxaoqCrq6ACEv2fmpyRr6BSbagMxKrRcQaxWrW1/1PygTKGXEZcxlwmXIYGXMYGQGxkwGViAMYgAsgDAA "Bash – Try It Online")
~~[Try it online!](https://tio.run/##S0oszvhfnpGZk6pQlJqYopCTmZdqrZCSz5ValpijUJxaoqCrq6ACEv1fZKtSbagaHWcQq1XLlZqcka8A5CurFNX@T8kHShtyGXEZc5lwGRpwGRsAsZEBl4kBGIMIIA8A "Bash – Try It Online")~~
---
Shells need to call external programs to use regex, so we have to make do with globbing.
The `${1%[^0]*}` expansion matches the shortest suffix beginning with a nonzero character, and removes it.
* In Zsh, adding the `(M)` flag causes the matched suffix to be kept instead of removed.
* In Bash, the `${1% }` expansion removes as a prefix whatever is left.
[Answer]
## [GNU sed](https://en.wikipedia.org/wiki/Sed), ~~17~~ 14 + 1(r flag) = 15 bytes
**Edit:** 2 bytes less thanks to [Riley](/users/57100/riley)
```
s:.*([^0]):\1:
```
It works by deleting everything until the right-most nonzero digit, which is then printed along with any existing trailing zeros. The script can handle multiple tests in one run, each on a separate line.
[**Try it online!**](https://tio.run/nexus/bash#K05NUdAtUlD/X2ylp6URHWcQq2kVY2j1X/2/IZcRl6EBlyGQtuQyNuCytARyQXwgbWTAZQRkmxiAxIwMAA) (all test examples)
[Answer]
## Mathematica, 26 bytes
Pure function which takes a list of digits and outputs a list of digits:
```
#/.{___,x_,y:0...}:>{x,y}&
```
## Explanation
```
# First argument
/. Replace
{ start of list followed by
___, zero or more elements followed by
x_, an element (referred to later as x) followed by
y:0... a sequence of zero or more 0s (referred to later as y) followed by
} end of list
:> with
{x,y} {x,y}
& End of function.
```
This works since it finds the leftmost match for `x`, which must be the rightmost nonzero element of the list since it is followed by a sequence of zero of more `0`s and then the end of the list.
[Answer]
# Java 8, 47 bytes
this is a lambda expression assignable to a `IntUnaryOperator`:
```
x->{int m=1;for(;x%m<1;m*=10);return x%m*m/10;}
```
explanation:
multiply m by 10 until `x%m` is not 0.
`return x%m*m/10` requires the division because m is an order of magnitude more than the desired result.
[Answer]
# [Perl 6](http://perl6.org/), 10 bytes
```
{+m/.0*$/}
```
Trivial regex solution. Inputs and outputs a number.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~10~~ 7 bytes
*3 bytes saved thanks to [@B. Mehta!](https://codegolf.stackexchange.com/users/64748/b-mehta)*
```
tfX>Jh)
```
Input and output are an array of digits.
[Try it online!](https://tio.run/nexus/matl#@1@SFmHnlaH5/3@0oY6BjpGOQSwA "MATL – TIO Nexus")
Or [verify all test cases](https://tio.run/nexus/matl#S/hfkhZh55Wh@d8l5H@0YSxXtBEQGyoYgEkwX8ESSBqDRSzBbKAsTB7KNwLzjaDiJkAaIg5kgKQA).
### Explanation
```
t % Input string implicitly. Duplicate
f % Push indices of non-zero digits
X> % Keep maximum, say k
Jh % Attach 1j to give [k, 1j]. This is interpreted as an index "k:end"
) % Index into original string. Display implcitly
```
[Answer]
# C#, ~~30~~ 28 bytes
Based on [this JavaScript answer](https://codegolf.stackexchange.com/a/110872/65012), so I suppose all the credits kinda go to him.
## Golfed
```
i=a=>a%10<1?10*i(a/10):a%10;
```
* -2 bytes by removing `()` around `a` thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna)
[Answer]
# J, 27 bytes
```
10&|`(10*(p%&10))@.(0=10&|)
```
It's based off of xnor's formula, so credits to him.
[Answer]
# Kotlin, 49 bytes
lambda, assignable to `(List<Int>) -> List<Int>`
```
{a->a.slice(a.indexOfLast{it in 1..9}..a.size-1)}
```
* implicit parameter name `it` in `indexOfLast`
* `..` for building ranges
[Answer]
# Perl 5, 12 bytes
11, plus 1 for `-nE` instead of `-e`
```
say/(.0*$)/
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
RD0Ê1k>£R
```
[Try it online!](https://tio.run/nexus/05ab1e#@x/kYnC4yzDb7tDioP//ow11DHSMdAxiAQ)
or as a
[Test suite](https://tio.run/nexus/05ab1e#qymrDP4f5GJwuMsw2@7Q4qD/lUqH91spHN6vpPPfkMuIy9CAyxBIW3IZG3BZWgK5ID6QNjLgMgKyTQxAYkYGAA)
**Explanation**
```
R # reverse input
D # duplicate
0Ê # check each for inequality with 0
1k # get the index of the first 1
> # increment
£ # take that many digits from the input
R # reverse
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 6 bytes
```
f".0*$
```
[Try it online!](https://tio.run/##y0osKPn/P01Jz0BL5f9/JUMDIwMlAA "Japt – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
æΩ$3╚
```
[Run and debug it](https://staxlang.xyz/#p=91ea2433c8&i=1%0A2%0A10%0A11%0A30%0A99%0A100%0A409%0A1020%0A&a=1&m=2)
### Procedure:
1. Calculate "multiplicity" by 10. (That's the number of times 10 evenly divides the input)
2. Add 1.
3. Keep that many characters from the right of (the input as a string).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ĀÅ¡θ
```
I/O as a list of digits.
[Try it online](https://tio.run/##yy9OTMpM/f//SMPh1kMLz@34/z/aUsdAxxiITYDYIBYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvxPmobRKnkn2lS/D/Iw2HWw8tPLfjv5fOf0MuIy5DAy5DIG3JZWzAZWkJ5IL4QNrIgMsIyDYxAIkBOZYGxgYmBgYA) (test suite contains a join for better readability).
**Explanation:**
```
Ā # Python-style truthify each digit in the (implicit) input-list (0 if 0; 1 if [1-9])
# i.e. [9,0,4,0,3,0,0] → [1,0,1,0,1,0,0]
Å¡ # Split the (implicit) input-list on truthy values (1s)
# i.e. [9,0,4,0,3,0,0] and [1,0,1,0,1,0,0] → [[],[9,0],[4,0],[3,0,0]]
θ # And only leave the last inner list
# i.e. [[],[9,0],[4,0],[3,0,0]] → [3,0,0]
# (after which it is output implicitly as result)
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `t`, 3 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
V€ỵ
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPVYlRTIlODIlQUMlRTElQkIlQjUmZm9vdGVyPSZpbnB1dD0xJTJDMCUyQzIlMkMwJmZsYWdzPXQ=)
Port of Jonathan Allan's Jelly answer.
#### Explanation
```
V€ỵ # Implicit input
V # Truthy indices
€ỵ # Head remove over each
# Take the last item
# Implicit output
```
[Answer]
# [Desmos](https://www.desmos.com/calculator), 62 bytes
Input (variable `A`) and output (variable `B`) are both arrays of digits. Run the ticker to start the program.
**Ticker:**
```
B->join(A[n],B),n->\left\{A[n]=0:n-1,0\right\}
```
**Expression List:**
```
B=[]
n=A.length
```
[Try it on Desmos!](https://www.desmos.com/calculator/yberrez2td)
Scans `A` from right to left until a nonzero digit is encountered. Afterwards, set `n=0` to invalidate the action and halt the program.
] |
[Question]
[
Correct a single-letter typo in a fixed text.
**Input:** The paragraph below but with exactly one typo, where a single letter `a-zA-Z` is replaced by a different letter `a-zA-Z`. To be clear, the letter isn't replaced everywhere it appears, but just in that one place. For example, the first word "In" might become "IZ". Non-letter characters like spaces or punctuation cannot be affected.
**Output:** The paragraph exactly as below, without the typo. A trailing newline is OK.
>
> In information theory and coding theory with applications in computer
> science and telecommunication, error detection and correction or error
> control are techniques that enable reliable delivery of digital data
> over unreliable communication channels. Many communication channels
> are subject to channel noise, and thus errors may be introduced during
> transmission from the source to a receiver. Error detection techniques
> allow detecting such errors, while error correction enables
> reconstruction of the original data in many cases.
>
>
>
[TIO with text](https://tio.run/##dZFBUsMwDEWvogOU3oIFCw6h2kotxpaKZNPp6UFxEgaYIStH@v76enbKT1cZn/G9CLAsag07q0AvpPYAlAxJM8v1qNy5F8DbrXKaSo9rIWm30cnAE5Mkmvc6VYpGG7JLT0BmapCpU5pTNnuz/Td6myKpdNMKaBQ2qQi/D/KIgB1I8FIJjCrPQ47DB0UyXSDzlTtWyNgRNKow5Fv4KwukgiJU/QyvKI9/mjOAj8tbBISuRx1E2em0bVmGb6kdGj7gQgEkwueRKEMeNtkZijd2X80X07bSBNdhwSp8MdZJtK5xhuc/jH7sj7Xq/WiFrY9U9tknuBeOJQ9@30w3XL4OiMfqNnbUy4ygFsTkIBYv2SYMdPLzFw "sed – Try It Online")
The text is taken from the Wikipedia article [Error detection and correction](https://en.wikipedia.org/wiki/Error_detection_and_correction). But, your code may not fetch the text from Wikipedia or elsewhere, as per the [standard loophole](https://codegolf.meta.stackexchange.com/a/1062/20260).
Any site-default string I/O is acceptable. Fewest bytes wins. Please check that your solution works for all 23001 possible inputs, if you're able to run that much.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~136~~ ... ~~97~~ 96 bytes
```
def f(s,n=0):k=s[:n>>7]+chr(n%128)+s[n/128+1:];return 0x2e838ca8118c7496+hash(k)and f(s,n+1)or k
```
[Try it online!](https://tio.run/##7VZta9swEP6eX3EYBnaSZXU22jQjhTI6CFsZbB2MlVIU@VJrsSXvTlqaX5@d7TprA/sH/mKke33uuQfhaudzZ6d7U1aOPBCyC6RxDLzjQXebMHoqTGl8fDB9/by8Xt7cf7u5/PBpDPF0OJyej1@nSTKQzCYBdSA2zraJ6clweJrsM1zDOuaxXZwk882Cb@f24uLsbqRziu2rdDpLRnxr38hhlM7v3hP6QBZOHqc4ezvTapamM3327vx0lCvO402ibNbWG6WJI9jstSPp7O/ZEywgWlowdu2oVF6ggM/R0Q7qLO0yYx86y9b4HFRVFUY3kSxpElJWwSMBa4NWY5PnsUBxlME@hY4BiaR3hl4a113a8g2O@iq@NkI768kVoAiljM6t@R2QBYLygFatCpQFFKY5ZHL4g4LMrSEzD8arAjLlFTixQrCHwBdYQOfKWix4AtfK7v7jbABwWP0SgOBdZwfrDMvqmynzwC1qhlLtYIVCiIDPgsYMskANd6Qsl4brLcOaXFmzCa1A6rpKxtFYjzGBqyOOns2visJtO5eU5aDzp95j2OZGhuz4O3Da0sV1A1mWp/BE9bqB4EgYsx1jssmyIUMx8iQaDNqaNxRwPpAhdvIFXhgry46jKBkAPmqsPFx9@djArv0rQrWRaBGV6E1iKqHAx/7fCRYLeKa@zgFRtI@WP3sZ9jJ8KcPI9G9TL4pjUVz2ouhFcSwK@Yv53ouiF8WxKPqXohfFQRQ/JtFf "Python 2 – Try It Online")
Simply replace each character in the given input with each possible letter, then check if the hash matches the correct string.
I use Python 2 `hash` function, which is deterministic and has no collision within our search space.
[This program](https://tio.run/##dVNNb9swDL37V3ApBthxltXZ0KYZWmAYdii2XrbeiqBQZTrWIlOePpbm12eUbBfbgN0kke/x8ZHqj741tDqprjfWg0VngpW4AHd02XRbOvRWq075/OXp29fbu9v7x@/3Hz99WUC@ms9XV4s3VVFkjEwAlME6ZWgAVufz@UVxqrGBJncLuj4vNvtr97Chm5vLbSlbm9PrarUuSvdAb/lQVpvtB4s@WILz5xWu362lWFfVWl6@v7ooW@HafF8Iqge@siqMhf3JwTXMbgkUNcZ2wrMA8C0ae4SYK02taDe9HJRvQfS9VjJlOoZxStcHjxacVEgSE86jRg50gcbUBaC1XLFGjzJVGeitHa8cGzKkIW@NBmGRaWRL6mdAxxKEByTxpJFt1yodaj78QlZmGqjVTnmhoRZegOFXCPSS@JcWkK0gQu2WcCfo@J9gEuDC0w8WCN5M70BGOR546rINblDtoBNHeEI2hMXXQWINdbDJOyvIdcrF2UJjTRfdhGEtIq/gdiTGNpbw@R@P/uhfaG0OU4hpXZDtWHsBh1Zxk5N/L54OdrlYgIflbRitbpIEY9kxmhzjSXbJDOHQLWdZNq44w7hclp2xASj3wxyGDnRIdAdj9w54faJG5uFtyOJNRs4BvhS8HOpRo@dFcZsMUrqKCezODnONlLuiiBEA1bDJXPlBbZfKCd23Ih9DkNZDUcB0PQMPir2B3rC/cdBD@RjzvNn8X9QWSpZSRrr4R0bcDocuTPAMiJbwQKAJlCwaCFbM0OS@mEq1SKMJqpmAXH00fJLOsFdcedLbc/9@IgHAZ/7c8ZLuWYrCrDaEs9Nv) checks if the function returns correct output for all possible input. It takes ~2 hours to run on my computer
*Thanks @Jitse for saving -22 bytes with recursion!*
[Answer]
# MATLAB with Communications Toolbox, ~~88~~ ~~64~~ 59 bytes
```
Z=rsdec(gf([+input('') 879 323],10),532,530);disp([Z.x ''])
```
This uses a (1023, 1021) [Reed-Solomon code](https://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction) shortened to (532, 530). This is a systematic, non-binary code with alphabet size 1023, which can correct any single-symbol error.
The number 1023 has been selected because, in Reed-Solomon codes, both the alphabet size and the maximum input length must be of the form *n* = 2*m*−1 for *m* integer. Since the input text has alphabet size bounded by 95 (number of printable ASCII characters) and length 530, *m* = 9 (*n* = 511) would be too small, and *m* = 10 (*n* = 1023) is enough.
The error-correcting code has first been applied to the input message to obtain the parity bits. This has been done offline. The submitted program only implements the decoder.
### Encoder
Each ASCII character in the input is considered as a symbol from a 1023-size alphabet, and then the code is applied using the [`gf`](https://www.mathworks.com/help/comm/ref/gf.html) and [`rsenc`](https://www.mathworks.com/help/comm/ref/rsenc.html) functions.
Note that the code is not part of the submitted solution, and is not golfed.
```
x = 'In information theory and coding theory with applications in computer science and telecommunication, error detection and correction or error control are techniques that enable reliable delivery of digital data over unreliable communication channels. Many communication channels are subject to channel noise, and thus errors may be introduced during transmission from the source to a receiver. Error detection techniques allow detecting such errors, while error correction enables reconstruction of the original data in many cases.';
x_ext = [zeros(1,491) double(x)]; % convert to code points. Zero-pad to length 1021
y_ext = rsenc(gf(x_ext, 10), 1023, 1021); % encode
y = y_ext(492:end); % remove zero padding
y = double(y.x); % convert to double
check_symbols = y(numel(x)+1:end)
```
This gives `check_symbols = [879 323]`. The encoded codeword is the input expressed as code points with these two numbers appended.
### Decoder
This is a program that reads the input text as a string from STDIN and displays the corrected text in STDOUT.
```
Z=rsdec(gf([+input('') 879 323],10),532,530);disp([Z.x ''])
```
The parity-check symbols are appended to the code points of the input, and the result is provided to the decoder with code parameters `532`, `530`, which define the shortened code. This causes the decoder to implicitly assume zero-padding. The `gf` and [`rsdec`](https://www.mathworks.com/help/comm/ref/rsdec.html) functions are used for this. The result `Z` is converted to char.
Note that `+` is used instead of `double` to save bytes; and similarly, `[... '']` is used instead of `char(...)`.
### Example run
[![enter image description here](https://i.stack.imgur.com/rvcby.gif)](https://i.stack.imgur.com/rvcby.gif)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
JœPjⱮØẠɗ€⁸Ẏ1,ȷ9ḥ⁼“×Ṙ*-’ƲƇ
```
A full program printing the result (as a monadic Link it yields a list of one list of characters).
**[Try it online!](https://tio.run/##dZE9TgMxEIWvMjUKkSg5AAVISHTUjj3JOvKOw9gm2o7Q0NFQBCQKGjqEBA0/okNEcIzsRZaJN4kAic6eeZ557/MQnauaZu/j4mBYP9y/X85fb76m9eldPXmev55vdT6ftufPt/XkrT65fp/OXy43NuuTq9nj7Kxpml0CS33PpYrWE8QC/WEFigxobywNcoUrGNtYgBqNnNVZGeSZSMpRisgQtEXSmN9FdCiNMtFS2gFk9gwGI@q8pR3PvLxKr1VoT5G9A8UoY3RB9ihhEAsqApLqOQRGZ/PByOEYxZnvg7EDG5UDo6ICL1VItBb@8gK6UEToQhf2FVX/NLOBkHpDMQjRr@pA3gbstCmLFFrXAUpVQQ8FiJg3SaMBkzizY0WhtCEshvfZlwuaEHxiYSVzlcTRuIjRhZ0/jH7kV8758aolY0PSxXJ3B8aFlZArfmumLa6wWCCfFTktUfezBc9CjFbE5CfLDEMFDN1v "Jelly – Try It Online")**
### How?
Changes each character (including non-`A-Za-z` ones) to every character in `A-Za-z` and checks if a hashed value is equal to that of the required input. The hash function was chosen so that none of the \$450 \times 51 + 79 \times 52 = 27058\$ possible states for each \$451 \times 51 = 23001\$ inputs hash to the same value as the expected output\*.
The program to check for collisions is [here](https://tio.run/##pVVtU@M2EP6eX7HNzI3tizEJF0KamTBDKe3RO6Al9PrCMR7FVmIZWzKSDKSd/na6kuzwdlyZqWaSSNrVo91H@2yqlc4Efzeu5N0dKyshNWREZQWbdzopXUDml2TJkhCuSVHTEHgw6QAOuwu9KQzsUmXkksK0PRvZdby1PfIlraRvDwcR5YlIqe/VerEx9oIgStmSKu1vD7YCC1MIvlQIc864jhZSlPF8panyLdw5gwkw6MH4IgSvYFoX1AtgISTuMg6S8CX1@yEgXAjj4MJCSqpryUHVpe@7XGB3F1gAG/BgiaiDIIC3LoJzdvEUdjRE8xsYjIfD0c5w2N95t9P/dnt7MBqM8BQ3IKNhp8MWEMeclDSOYTqFbhyXhPE47jrWZphb95AjLMKXRDPBQWdUyBUQngKyw/iy3blhOgNSVQVLrKcy0SSirGpNJaiEIZ3UntO0oGgoa964hkClxARSqmlib3HwUjZLtDmPRHAtRQFEUoRJMs6uaqowBKKBcjIvKDJYMDtJcXJNMTKxAHw5pkkBKdEEBO5CzdeOj2KBJCOc00JFcET46gWjDUDV8xwDBC3afeCCKSw7m2VWKxe1wvJbwZwiIRh8Wic0hbSWljt8LlUypQy4qSDDJihRS@QKcQmmk1CTRgQHTzh6kD8pCnHTmhBW1UnW3B3CTcYwyZa/NaeOLmUuwMfSsm6oXtgQhETGeMsYvmRpySCKqqhri@Pj4ewsNhVSMNTEzCli//3eqdnz9r7b//7ghx/fH/704ePR8cnPv5zOzn799Nvvf/xJ5gkqdZmx/LIouaiupNL19c3t6i/vHiKeHZwhjKLat2uHfgStgI/NrN@Ojt0zYj6lVzWTND2pNdadUbh/FDahhnDsYCqkXvtektHk0rKFX6YMMiJJYoo1ZYsFlaZeVRRFnjv1RGEF5Zh0015ae2IdbMT3BjNQaGhDic1QrBNbxozX9JHPLYbrIj2foKJ7cJ7Yn2bPin5y8RTWJnhrcjPwzzl4HIdtMQRrFD6ZHmdLyve8KBeM@7dB0PkiQamo5y8T1PCjhRHYFBpmsGENbIdyq03Ysl7zCl2c66Z7QbudiJqb55pX@82s/zLpFvox8fm9D@sNQnj2Og1bLf6uueo5NS6M3jqOZw4NM5/l3/1JtLX4540Xudbou6NvXU6wufkwyQAbHE@nXsPUw3Gf8IbfzrFvP3ZsDev/r1fV3Gvrbg2UfwWoBcsdWP41sMbXXIkNUa9RrahNazTnn1n@A/BV6sidIX9gyL8gm/8lnxdlxELIQ6QbP/j7gqi6n@XeyYdvukHn7u5f "Jelly – Try It Online") (I split the 2-char check into 5 parts and ran for over 1h to completion).
\* smaller hash functions might work for just visited states which could save bytes (although if a collision does exist further on than the correct match then an `Ḣ` must be appended).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~260~~ ~~259~~ ~~247~~ ~~226~~ ~~223~~ ~~217~~ ~~215~~ ~~214~~ ~~198~~ 189 bytes
```
y;*R=L"ė|h0\"k5&j4Đzm7ſ4sM6~0=a[z@z4zp4y j,-#3#mu7qĘdd";char n,k,t,u,r,c,x;f(char*s){for(n=y=23;n--;c?u=n:0,r?x=r,t=n:0)for(r=R[n],c=R[n+y],k=y;k--;r^=s[y*n+k])c^=s[y*k+n];s[y*t+u]^=x;}
```
[Try it online!](https://tio.run/##7VJNbxMxEL3nV4xaCSWNkxaaUonVqnDgUIlK0CMhlRyvk3V3d5z6o8kmlN/ADf4Nl/K7wti7LQXEiRtqDpuRPfP83psnBnMhtts62TtP3@zcfvmYH3zYKY6eXI5uP6@r4@/fRvbs@aeDlI/XL9ej9WJUwyUb7B7uVv746vZrlu0kIucGkBXMMc8ME2yVzLrhcM/2NjNtupjW6bPDBAeDRJz4FF8cMHOySg1zoe6FFpOej3HCRPjr1xNWpHVSUL@5SO243sN@MemJpi76OElC4fp@cpGukputQgcVV9i91irrdTYdiJzs@Ojw6STpwDJXpYTuXDrbtb0ewP4@nEuegUYJChfeQamo5A44OFXJDtBvE7@gZtAlJbEOg6/KUi9hWnIs4pQlBHB5C8SA5AAqIU2oKu6cwjnoWWxx0rphAwswIy7JT9jFoqxBGkPjQhsjhVOagDXYYacZIXh7P0Mjb00Q3g3AKJdwzUsv6aVemAgtN52b7SkSr4ZIhMulNjVwzOiRLDBrT5bK5cCJgxKxM6p6ryt6k5RYoSQKGeecLKXQVeWxbWUt60y6lnQDf6@B7u50oTO6BG6CFSJHdeXJP5eT8RL5lJZkZKlikVFxLYkZWZepuXK8hIw7DppOweN94y9cwuIRZWmHcMax/stlJGD99JIIBofbc0CtrGSNytzbhrWlaNUwDfsl8pkXMoPMm@id4WgrZW0AnxldxSVb7Q15Rbic5AgZZAzh9W8ePdDPY6LaK4K1XuTt26zN7h@5aOyy4QFaljO@tbrJmTbkGN45RpusohncyhCm1b9kQjxm4n/MxOljJh4z8SAT74Y/AA "C (gcc) – Try It Online")
---
*Now with 9 fewer bytes, thanks to @ceilingcat!*
---
*Thanks to @Bubbler for golfing 16 bytes off!*
*I haven't updated the readable version to include @Bubbler's modifications, but the biggest improvement is in the XOR computation loop. The shorter approach starts at the desired values `R[n]` and `R[n+23]`, and repeatedly does an XOR, which will yield `0` at the end (except at the bad character). My answer had the loop starting at `0`, and checking for the values `R[n]` and `R[n+23]` at the end.*
---
**I've added a readable version of the code, commented and with whitespace, at the end of the answer.**
---
This doesn't use an md5sum or hash function, since that's not available in C without using an external library. Here's how this program works instead:
Imagine the input text, except for the final `'.'`, arranged in a square. The XOR of each row and the XOR of each column are computed, and they're compared with the correct XOR values from the original text. One row XOR value and one column XOR value will not be what they should, and that tells you which character to fix, and which bits to flip to make it right.
---
---
Here's the more readable version of my last version of the code (before @Bubbler and @ceilingcat's improvements), commented and with whitespace:
```
f(char*s)
{
/*****
The original text contains 530 characters.
Using the fact that 23 * 23 = 529, view the text as
arranged in a 23 x 23 square (plus the '.' at the end,
which doesn't matter since it can't be changed).
*****/
// The string R below is 46 characters long.
// It consists of the XOR of each of the 23 rows in the original text,
// folllowed by the XOR of each of the 23 columns.
char *R = "\x17|h0\"k5&j4\x10zm7\x7f""4sM6~0=a[z@z4zp4y j,-#3#mu7q\030dd",
n,k,t,u,r,c,x;
for (n = 23; n--; )
{
// Compute the XOR of row n of the input string, and store it in r.
// In the same loop, compute the XOR of column n of the input, and store it in c.
r = c = 0;
for (k = 23; k--; )
{
r ^= s[23*n+k];
c ^= s[23*k+n];
}
// If the computed row value doesn't equal the row value from the original text,
// save the bad row number in t. Also save (in x) the bits that are wrong.
if (r-R[n])
{
t=n;
x=r^R[n];
}
// If the computed column value doesn't equal the column value from the original text,
// save the bad column number in u. There's no need to save the bits that are wrong,
// since they're guaranteed to be the same as the bits that are wrong for the row.
u = c-R[n+23] ? n : u; // Golfed equivalent of:
// if (c != R[n+23]) u=n;
}
// Fix the bad character, which is in row t and column u, by flipping the bits in x.
s[23*t+u]^=x;
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~122 121 119~~ 113 bytes
```
->s{s[a=(0..9).sum{|x|",JEDI>(:6#"[x].ord==(0..529).sum{|w|s[w].ord*w[x]}%84?0:2**x}]=""<<50998-s.sum+s[a].ord;s}
```
[Try it online!](https://tio.run/##dZJRb9MwEMff8ylOQUht6aKsULSOZRUSe9gkvgBRHxz7shgldvDZpGXtZy9Xt5kAiSfbd3/f/e9nu1DtjnVxvLqnFypFMcmzbDXNKHQv@@0@nT89fHm8n9x@fJOW201mnSqiZLkYRcOeyiFmZgNLDm9vPqzz28Vstj1sijS9u1vmq9XNFZ3U77hDlH6iw5HyIn00oE1tXSe8tgZ8g9btQBgF0iptnsfIoH0Dou9bLaOS@BpLuj54dEBSo5EY73lskRNdMBfpHNA560ChRxm7nMs7dzly7qyQ1nhnWxAOuYxsjP4RkNiC8IBGVC2Cw1bHjeLNT2Rntgaln7UXLSjhBViOQjCvwr@8gGyEMdhSBl@F2f0nGQ1QqL6zQfB2jIOxmnB@nrIJdHZN0IkdVMhA2LwKEhWo4CI7Jwx1muhUvHa2O9EEssExK64reByJpzEyePiH0R/zi7a1w5jishRkc@k9h6HRPOTI75XpGRedGvBjeRcuqOtowTomZkZi/JJdhCEIKUuThK4LyrMqobzsgWdQk@X7fLop@kk5W3/OsvW3@WwteP21yUh0fYvTJOGfQEB5QouiLinfXAKLcS0Kuj7@Bg "Ruby – Try It Online")
### How:
Compare partial sums applying different masks to the string:
```
In information theory and coding theory with applicati [...]
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 X -> "I nomto hoyad [...]"
XX XX XX XX XX XX XX XX XX XX XX XX XX XX -> "Innfmaonhey d [...]"
XXXX XXXX XXXX XXXX XXXX XXXX XXXX -> "In imatiheord [...]"
```
With 10 partial sums (and the total sum of the original string) we have enough information to detect and fix a single error.
Incidentally, the partial sums modulo 84 converted to ASCII form the word "JEDI" and an Australian smiley, which I hope bring some imaginary bonus point.
### Why not hash?
From the Ruby documentation:
***The hash value for an object may not be identical across invocations or implementations of Ruby. If you need a stable identifier across Ruby invocations and implementations you will need to generate one with a custom method.***
I'm lazy. That's why.
[Answer]
# [Python 3](https://docs.python.org/3/), 83 bytes
```
def f(s,t=118,u=-10340):
for x in s:t-=x-96;u-=t
*l,=s;l[u//t]+=t;return bytes(l)
```
[Try it online!](https://tio.run/##dVTLbtswEDxbX7F1D5YayYmTog8HOgVJkUMvdQ8FDMNgqFXEliJVPpr469Ml9UicogcB1HI5Mzu7ZHdwjVYXT08V1lCnNnflavUp92WxOrt4f5atE6i1gUcQCuzaFeVj8fnDpS9Kl8A7mZf2Um796anbnZTu0qDzRsHdwaFNZfa0Kee3ik4SQsuc0Apcg9ocgKkKuK6Euh8jD8I1wLpOCh4zbSDkuu28QwOWC1Qc4zmHEmmj9WpIzQGNIY0VOuSRpYc3ZvilvT6Da@WMlsAMEgxvlPjt0ZIE5gAVu5MIBqWIi4oWf5CU6RoqcS8ck1Axx0BTFLyaEo@0AG@YUijtEr4ydfjPZhRg/d1PEghOj3FQWljM@yobb3vVFlp2gDskQ0h85TlWUHkTvTNM2VZYG8Bro9vgJljtDXlFuIzK4RjKWML1K49e1M@k1A/jFsFaz5uBO4eHRlCRo3@Tp71dNhBQs5zxg9V1lKANOaZGx6iTbTSDWbTLeZKIttPGAR0juiR5C9@wk4w0kxGG8dBx6kinrYigop8OnoQZbdkv3LtDp2lWRc5pQGfD2NntWuzgBDh9ditOVutdEsC/oELDHOkPk0zFglZYPFMFMDsqvye31KjsLdzWINFRlt1rJQ95yKEqaTnEC6eLfjXgPAgioG5VRBIFE2HUa0nwEVj53XgM@sUxCUVmkzoL5aBmyegWiP2QmcxojvCf1MVi@VMLlW55Y1K6YdjRn8ti5dNvaAhNzj2mF@c5rM4/ZruMgJJZyBL5VdhH5dvgGqY2SIxbPN7JiS6EZ4ZIX7ckxKmm9Oo4P4uDnRp4QyVF0NnsIFBWYEKbvqN1NLG1V8OAhlspFD0ANh7U3vXr@L4UQ4uCw/TauLQOiEFlfDmeTd9EJrsfZpcuTxneuSW9J@RHmgW1JJbg0hdJOSy8q4tPiyyo3fSl9mN2w8j4aehCD5OkIy0unYcSQqeWy3mWBFV7g9ZLR5SDxiFzO79hdK2qeQ7zjeccsaKf3fbFGWpJEirAat@XSiDp4vbH4mSzPV/vsqmAZBL9nFinx0ezSeL1I2s7ib2x6/ko6Ch9DGavD/UteD71mjlLnv4C "Python 3 – Try It Online")
We compute a custom numerical checksum that let us locate and fix the error. This means don't need to try possible changes until we find one that works. As a result, the code run very fast, letting us test all 23,001 possible inputs in under 2 seconds in the linked TIO.
Input and output are as bytestrings, which requires Python 3.
**The checksum**
It's a bit easier to understand the idea using the code below.
```
def f(s):
t=50998-sum(s)
k=13447420-sum(i*x for i,x in enumerate(s))
i=k//t
l=list(s)
l[i]+=t
return bytes(l)
```
[Try it online!](https://tio.run/##dVRNj9MwED3Xv2IohyZsWvYLAZVyQoD2wIVyQKqqyutMNmYdO/iD3f76Zex87LaIQyRnPH7z3puxu4NvjL56eqqwhjpz@ZqBL9@df/z4YelCSwEG9@XF1fX1@@vL8xSSbx6hNhZk8QhSA@rQouUeKZeSZXn/9q1noEolnU/n1VbuzkqKWfTBarg9eHSZyp825fxGEwahtdxLo8E3aOwBuK5AmErquzHyIH0DvOuUFCnTxdLCtF3waMEJiVpgOudRIW20QQ@pBaC1xLdCjyJV6eGtHX5pr88QRntrFHCLBCMaLX8HdESBe5LJbxWSBCXToqLFHyRmpoZK3knPFVTcczAUhaCnxCMuIBquNSq3gm9cH/6zmQi4cPuLCII3Yxy0kQ6LXmUTXM/aQcsPcItkCJGvgsAKqmCTd5Zr10rnInhtTRvdBGeCJa8Il5McgVHGCj6fePRCP1fKPIxbBOuCaIbaBTw0kkSO/k2e9na5WICa5W0YrK4TBWPJMT06Rp1skxncoVvNGZNtZ6wHOkblGHsN37FTnDiTEZaL2HHqSGecTKCynw7B4gy3/B73/tCZzBWyEDTPs2Hs3HYtd3AGgj63lWcX6x2L4F9Rx/kl/nGqSSwYjcvnUhHMjczvyC09MnsNNzUo9JTl9karQxFzSCUth/jSm2W/GnAeJBWgblVUJBGmgomvI8JHYOUPGzDyl8dFKDKb2DkoBzYrTrdA7odMNqM5wn9SF4vVLyN1thWNzeiGYUd/Pk/Kp9/YEJqcO8yuLgu4uHyf73ICYrP@1n86vfWxSgJId3IqF8MzS0VPWxLjpCn7dJyfp8HOLLwiSQl0NjtIVBXY2KYf6DxNbB30MKDxVkpND4BLB03w/Tq9L8uhRdFhem18VkfEyDK9HM@mb1Iltx9mly5PGd/BFb0n5EeWR7ZEluCyF0kFLIKvlx8WeWS76aX2Y/aFk/HT0MUeMtYRF5/No4TYqdVqnrPIam/RBeWp5MBxyNzOv3C6VtW8gPkmCIFY0c9u@@IMtYRFBVjte6kEki1ufi7ONtvL9S6fBLCJ9HNinR0fzSeKnx952ynsjV3PR0JH6WMwPz3Ut@D51GnlnD39BQ "Python 3 – Try It Online")
The core is the checksum, which gives two values. The correct string (and only it) gives the values `(50998, 13447420)`, which are used in the code above.
```
def checksum(s):
t=sum(s)
u=sum(i*x for i,x in enumerate(s))
return(t,u)
```
[Try it online!](https://tio.run/##dZKxctswDIZ3PwUuk9XTeemWu4wdOnTKE9AkFLElAQUA6/jpHYiyfG3vuoHAL@DHBy1Xm5m@3m4JJ4gzxl/a6lGH5wPYyxYeoPUof/mAiQXy@AGZAKlVlGDoEtcIWhM62tiG2@vL03dyjatrsMwENiPLFQIliJwyve2ZS7YZwrKUHLtS19aR69IMBTRmpIj9O8OCXqiN7tIRUMT9JDSMfcrWXuT@9NqmiEwmXCAIeps4U35vqG4hmK8RzgXdfsk9SB78RnfGE6T8li0USMECsGeh0UP4lxdHF4iw6Al@BLr@p9gNaDv/dINgvOeBOCuO25Zz0821Qg1XOKMDcfOpRUyQmnR2EkhrVl2bT8J1pQnKTZyV9w2@TsR1jRN8@4fRH/uHUviyl7yttjjfZ49wmbMvufN7MN1w6TrAj2XS7qinboHFidFOzC9ZO4ygqKenw2Fx93Z8/GWvJz8uJzwOw3D7BA "Python 3 – Try It Online")
The checksum not only lets us know whether the string is correct, but the difference from the checksum to the real string lets us deduce what the error is and fix it. This doesn't rely on the typoes being with letters.
**How does it work?**
The checksum consists of two parts, each of which is a number.
The part `t=sum(s)` is simply the sum of the (ASCII) values in the string. Given a string with a single typo from the original, we can figure out the numerical difference between the original and typoed character by comparing the sum to the original's sum of 50998. For example, if we find a sum of 51001, we know that the typo increased a character by 3, such as `a->d` or `M->P`.
So, we know the amount that the character is off, but not which one. That is, we don't know the index. For that, we use the additional information given in the second value `u` of the checksum,
```
u=sum(i*x for i,x in enumerate(s))
```
Here, we add up all the characters, but each one is given a multiplier equal to its index, so zero times the initial character plus one times the next one, up to 529 times the last one.
The idea is similar to a classic puzzle:
>
> You have 10 bags of coins. Each bag has 10 gold coins that each weigh 10 grams, except one bag is filled with lighter counterfeits that each weigh 9 grams but otherwise look normal. You have a digital scale that displays exact numerical weight. How can you determine which bag has the counterfeits, using only a single weighing?
>
>
>
The solution is to number the bags 1 to 10, and put 1 coin from bag 1 on the scale, 2 coins from bag 2, up to 10 coins from bag 10. That's 55 coins total, so if all the coins had been real, they'd weigh 550 grams. But, each counterfeit coins lowers the total weight by 1 gram. So, since the fake bag will contribute its index-number of underweight coins, which is however many grams under 550 we see. This tell uses which bag is fake. (We could also have zero-indexed 0-9 and used 45 coins.)
The checksum `u` works just like this. Suppose that the typo is index `j`, and it's off by an amount `d` as determined by the first checksum value `t`. Then, the index `j` will contribute to the error in `u` with a multiplier equal to `j`, so it will be off by `j*d`. Knowing both `d` and `j*d` lets us find the typoed index `j` by dividing.
**Fixing the error**
The error is fixed as `*l,=s;l[u//t]+=t;return bytes(l)`. This converts the string to a list, modifies the indexed value in place with `+=`, and then converts back a bytestring. This is pretty ugly. Note that strings and bytestring are immutable in Python, unlike lists, so we couldn't just modify the string directly.
I'm still not really clear what default string I/O permits, despite having given it the go-ahead in the challenge. If we can do input and output on lists of ASCII values, then we can save a lot of code, especially by modifying the input list in place.
*61 bytes*
```
def f(l,t=118,u=-10340):
for x in l:t-=x-96;u-=t
l[u//t]+=t
```
[Try it online!](https://tio.run/##hVLLbtswELzrKxa@xEZkJ26KInGhYw459JRLgSAw1uQqYsGHSi5r6@vd1SuoixQ9idqZnZ0dsu24Cf7ufNZUQ720JVfb7X2Zq/X29u7z7WpXQB0inMB4sDteV6f1w5eveV1xAfYl39zw63XF5@dq8eSFI1yHbIIHbijEDtBrUEEb/zZXjoYbwLa1Rg3M1Eur4NrMFCEpQ17R0MdkSQCX/UQtgWIUN5qY1DBllI9x@hVsZKjgOQYLGElkVOPNz0xJLCADeTxYgkjWDActh18kzkIN2rwZRgsaGSFIFbJ/J154AdWg92TTBr6h7/4BDgZSPvwQg8BhroMPJlE5btnkNLpO4LCDA0kgYl5nRRp0jkN2EX1yJqVevI7B9WlCCjlKVqKLso6ifo0NPP6V0R/7o7XhOEMim7JqptklHBsjS875vWc6xpX6AXJZHPMUdT1YCFES83NicpNuCAMTpc2iKLhrA@m9tPXjKrh6@n4F1/D88mn3egnuMe2tSSyk/rN02C5D1OUFabUqilYOvFw8ntC1ts9KHg5gGrp2i9WEf6g9g6JSf8yA//SffwM "Python 3 – Try It Online")
**Optimizations**
```
def f(s,t=118,u=-10340):
for x in s:t-=x-96;u-=t
*l,=s;l[u//t]+=t;return bytes(l)
```
We save some characters in the above code with a few optimizations.
Instead of computing the checksum values `(t,u)` and subtracting the target values, we get the differences directly by initializing `t` and `u` to to their target values and subtracting the contributions for each character iteratively. Passing in the original string would make them end up both as zero, giving a divide-by-zero error in the code.
Instead of using `enumerate` to compute the weighted sum `u`, we repeatedly subtract the running sum `t`, which subtracts each character value successively more times. This effectively computes the weighted sum for the reversed string, that is with the biggest weights at the front. But we end up with a negative index that goes from the back, so it works out.
Finally, we are able to obtain shorter-to-write checksum values `(t,u) = (118,-10340)` instead of `(50998, 13447420)` by using a slightly different checksum that first subtracts 96 from each ASCII value. This is the rounded average ASCII value for the text, so subtracting it makes the string values average out to roughly zero. This make the checksums have both positive and negative summands that make them close to zero. These values of `(118,-10340)` are tantalizingly close to being one digit shorter, and one is negative, but I didn't see a way to shorten them.
I was originally planning to do all checksums computations modulo some prime to make the resulting values shorter to write, but they are short enough anyway that it's not nearly worth it, even without the optimization above.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 78 bytes
This is a port of [xnor's great answer](https://codegolf.stackexchange.com/a/201032/58563).
```
s=>(t=118,u=10340,g=k=>Buffer(s).map(x=>(u+=t-=k&x-96)-531*t?x:x+t))(g(~0))+''
```
[Try it online!](https://tio.run/##dZFBb9swDIX/CtHDai@OkaDrsBZwBxToYYfdd1Uk2lYrUx4pNcllfz1j7LhYB/QmkU/ke5@ezasRy35Ma4oOT21zkuahSM12@63KzXZz82VTdc1L8/CY2xa5kLIezFgcVJRXTVo3L58O67uv5fr2Zvs5fT/cH1apLIuu@LMpy9X19clGkhiwDrEr2uLqB8EvaiMPJvlIkHqMfARDDmx0nrqlsvepBzOOwdtJKeBJJcOYEzKI9UgWp3cJA2pjyHSRVoDMkcFhQjttmcczX67amxXqLXEMYBh1jO3J/84oasEkQDK7gMAY/HRwenhFdRZbcL7zyQRwJhmIWoVMb8J3XsD2hgiD1PDT0PGD5mRA8u5ZDUKKSx0oesFqTtlnmV0LDOYIO1Qgat5liw5c5okdG5LBi5yHtxyHM02QmFlZ6VyjcSyeY9Tw9B@jf/KbEOJ@aelYyba/7K5g33sNufB7YzrjkvMC/azE@YK6nSxEVmK0ENOfHCYYRlDqq7I8/QU "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), ~~121 118~~ 116 bytes
```
s=>[...s+'jEIM'].some(c=>[...s].some(C=>Buffer(o=p+c+s.slice(++i)).map(c=>k=k*99^c,k=p+=C)|k==0x6B9400B8,i=p=''))&&o
```
[Try 10 random test cases online!](https://tio.run/##dVPbctMwEH3vVyx9qO06ddNOYSjFZUgboEC4hXsmzCjSOpZjS64kN00v3x7WjlOgMzxJ2ss5Z4@kjF0wy40s3Y7SApdJvLTx8SiKIht6Wf9s4I0jqwv0eRttjyfxca9KEjS@jsuQhzayueToh6EMgqhgZd0wi2fbh4e/eGdGNfFJcDOL4@7lo97hQbfbe9yRcRl7XhBsbenlEGLYPFMgVaJNwZzUClyK2iyAKQFcC6mm68hcuhRYWRJjU2mpjUqKsnJowHKJimPT5zBHShSVaks7gMZoAwId8oZlBW9Me6TcqoJr5YzOgRkkGJ4qeV6hJQnMASo2yREM5rLZCNpcICnTCQg5lY7lIJhjoCkKlbor/EcL8JQphbmNYMDU4j/JRoCtJhkJBKfXcVBaWuyspkwru1JtoWALmCAZQuJFxVGAqEzjnWHKFtLaGjwxuqjdBKsrQ14RLqNxONZjRNC/59Ff87M81/N1imBtxdOWuwPzVNKQa//uPF3ZZWsCuixnqtbqpJGgDTmm1o7RTRaNGcyijTaPNjboQfg5OpD0RPaOaHlKa5c2YRjA9QaA0HANGWUHzKURjSl04QewDcMoRzWlt3IDVH@7kuc/2B2xnavxrowcWucPR9k4CI7WOLx@iGzCBSbTVGazvFC6PDfWVRfzy8XV897Jaf/Fy1dnr9@8Hbx7/@Hjp@HnL1@/ff/xc3N0n/7hfk08/sNM2DE0fDWdJaZh@226HcgCCIk9vItltN9rKmvXdI5Rrqe@v043bAW7bHphhywJWhBv5LVQ3ti7D1gX07JHv7Rkoq@Ev39AjYlvg0YdPAOvZNai8OAJeAkj4cIjGbfL3w "JavaScript (Node.js) – Try It Online")
## How?
### Replacement letters
All letters in the original paragraph appear at least twice, except ***j***, ***E***, ***I*** and ***M*** that appear only once and may disappear in the modified paragraph.
That's why we do:
```
[...s + 'jEIM'].some(c => ...)
```
This way, it is guaranteed that each possible replacement letter is tried.
### Hash
Using a built-in hash would be rather lengthy in Node:
```
require('crypto').createHash('md5').update(string).digest('hex')
```
Instead of that, we use the following custom 32-bit hash:
```
Buffer(string).map(c => k = k * 99 ^ c, k = 0)
```
This was (rather painfully) tested against all possible inputs.
[Answer]
# [Perl 5](https://www.perl.org/) `-MDigest::MD5=md5_base64 -F`, 86 bytes
```
map{//;for$j(a..z,A..Z){$_=$j;(aNCL7lqAQsi7llQYWh7r8A eq md5_base64@F)&&say@F}$_=$'}@F
```
[Try it online!](https://tio.run/##dZJvaxsxDMa/il6E/oH02sGyjJZCQtvA2DLoq7G9KYqt5Bx89kWyF7LSr76r7pJru0FfnU96LD36yTWxHzVNhfXj@fnVMvJgfYJF8Wc4LYpfp4@Dh@vB@uoEv998G/vN9F7c2Pv7nz/KMX@eAm2gsqOHBQp9@jiZnR4dCe4ms6f21vHTZNY0XwK4oFUrTC4GSCVF3gF@tWCidWHVR7YulYB17Z3plKLXVFLVORGDGEfBEGCwkMiTJqocDtIhEHNksJTIdF1amYnMh1/N7RUmhsTRAzJpGVMGt8kkagETUMCFJ2DyrjtYPfwmdRaXYN3KJfRgMSFEjUIOL8J/vIApMQTyUsAcw@6dZGdA8mKtBiHFPg4hOqHhfsoyy961QIU7WJACUfM2G7JgM3fsGINUTqQtvuRYtTRBYmZlpXVRxzHUjlHA3X@M3syP3sdtn9Kykk156D2Ebel0yJ7fC9M9Lmkb6LIS5wPqZWchshILPTHdZNXB0Gcixd9Ydwtuzuaj4uLDhX5v3YokXV7Ob0fXr@@pOZs9Aw "Perl 5 – Try It Online")
Brute force method. Runs each character position through all possibilities until it finds that the md5 checksum matches the original message.
[Proof that no other single character change matches the checksum.](https://tio.run/##dZJha9swEIb/yhFC1kLqdrAsoyHgsM4wWAb9NNYv5SxdYgVZck7SQlb61@ednbjdBvtk@e703nvPqSG2s7bNy2VeLGpsnq6vFxvP490FZtnP6SrLHi6fxo/L8W5xgV8/fpnb/eo@mLm199@/VXP@sALaQ61njyUGev8uLy4nk1FejhyN8mI0mQQ85sVzp/DmOS/a9rMD46RDjdF4B7Eiz0dAp0F5bdx2iBxMrACbxhrVVwa5JiV1kyIxBGXIKervRbIkiTq5c@kUiNkzaIqk@i4neebzr@ROFcq7yN4CMomMqpzZJwpiASOQw9ISMFnTH7QcfpA48xvQZmsiWtAYEbxEIbmXwr@8gKrQObIhgzW643@SvYGQyp0YhOiHODhvAk1PU1YpnFwHqPEIJQkQMa@TIg06cc@O0YXahNCJb9jXHU0IPrGwEl2UcRR1Y2Tw6R9Gf8yP1vrDkBLZkFR17j2FQ2VkyIHfC9MTrtA1kGVFTmfUm96CZyHmBmKyybqHIU8mZL980y@4vVrPspu3N/K9M1sK8fZ2fTdbvr6t9qr4DQ "Perl 5 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~181~~ 163 bytes
```
n,*R=L"[z@z4zp4y j,-#3#mu7qĘddė|h0\"k5&j4Đzm7ſ4sM6~0=a",u,v,x,y;f(char*s){for(n=529;n--;s[n]^=u&v)for(y=23,u=R[n/y+y],v=R[x=n%y];y--;u^=s[n-x+y])v^=s[23*y+x];}
```
[Try it online!](https://tio.run/##7VJNb9NAEL37V4xaUSWpk5Z8UCHLEhw4VKIHeiSk0ma9ibe1Z9P9cOOU8hu4wb/hEn5XmF07VUHixA3VB3tmd/zmzZvH@0vOdzuMe5fp@4Pp5s1mvFmNa7iO@4ejw9Kd3W6/Z9n22@f89NPBzeToerz9uinPfv4Ym4tXX05TdhC7uIrXcZ0sOjxnume69wulO5hOhq8T7PcTM8XZVeqOqq4/r9PhKHbp5RRP6uN6FlcUrlN8Uc@SmordVUr1/TVddSsfD0e9@ng9Sx52Ei2UTGKnUjLrRvcR@H5gppPRy1kSwV0uCwGdpbCmY7rdCOi5D2@QC@gQMYCTE3hbFOrOwLxgeAOFRGFAIthc0GflbAzEElByoX1UMmslLkEtQokVxg4aTIAFtUmiJqM/TUh98hA97M6R8BoAqQK@0jUwzICrzCO2J3fS5sBWq0LyUBnYfFQlARIDw6VALsJ/VhSCq7J02JbGILQmspmwgocuDbzWbUp3TQVXaLUqgGk/As9R3jqa2@bMgkA2J920KGQIMgoqQcxo5EwupWUFZMwyUHQKDh8Lf@Pid4EoCjOAC4b1Xy4DAePm10QQrNqfAyppRNxMmTvTsDa07Rrmfi9EPnNcZJA5HbTTDE0pjfHgC63KsByjnCatCJfROFz4MQbw7g@NnszPvBX2VwRrHM/b3nFrp71@j5o2chnfgJZltWulbvyhNCmGe8Vok2UQgxlhBlG0/hdP8GdP/I@eOH/2xLMnnnjiw@AX "C (gcc) – Try It Online")
-13 bytes thanks to @ceilingcat using the L-string trick. -5 bytes by moving the remaining local variables to the global scope; it doesn't matter if they are `int` or `char` because the ultimate destination is `s[n]^=u&v`, i.e. assignment to `char`.
A small improvement over [Mitchell Spector's C answer](https://codegolf.stackexchange.com/a/200773/78410). Instead of keeping track of which row and column have the typo, this one computes for *every char* the XOR-sums of its own row and column. If both are nonzero (they are necessarily equal), correct the current cell (which is the only offending cell) right away.
### Commented
```
// declare global(?) variables n,u,v,x,y
// and initialize *R to point to the XOR hash array
n,*R=L"[z@z4zp4y j,-#3#mu7qĘddė|h0\"k5&j4Đzm7ſ4sM6~0=a",u,v,x,y;
// the function: takes char array and modifies it in place
f(char*s){
// loop over first 529 chars backwards...
for(n=529;n--;s[n]^=u&v)
// loop over the chars on the same row/col as n,
// initialize u=row hash, v=col hash
for(y=23,u=R[n/y+y],v=R[x=n%y];y--;
// collect XOR sums of row/col
u^=s[n-x+y])v^=s[23*y+x];
// at this point, go back to s[n]^=u&v
// i.e. fix the typo if both sums are nonzero
}
```
[Answer]
# [PHP](https://php.net/), 91 bytes
```
for(;($a=$argn)[$i];$i++){for($j=9;++$j<123;crc32($a)!=3603504069?:die($a))$a[$i]=chr($j);}
```
[Try it online!](https://tio.run/##dVHBbtswDP0VDvChRrIga9oCnRv0tAE77AuKHhiJiRTIlEdJC4Jhv96UVuJiLbCLIZOPj@89Dm44PTwO@t1GuequGlw3KDtunxr/3DV@Nmv/jJ1mv77vZrNm//DletUZMatrxbaf1qu75ep2ebO8u3/8aj2NxbbBcXpt3DjXdn9Ppx8MnpWnx@wjQ3YU5QiFLZhoPe@mysFnBzgMwZuKTDqmkH4omQSS8cSGAHUuUyBt9IUv0DmQSBSwlMnULVjpRS6/2jsjTOQsMQAKKY1x7H8VSioBMxDjJhAIBV8fVh@/SZXFLVi/8xkDWMwIUatq4A34TgsYh8wU0gJ@Ih//06wCUtnsVSDkONWBo080P7t0JZ1VJ@jxCBvSQFS8LYYs2CI1O0FOvU9pJN9K7Mc0IcUimpXyotoxNNpYwLcPGf3jH0OIh6mltKkYd9k9h4PzanLK7y3Tc1xpXKDHylIuUW@rhCiaGE@J6SX7GgYmSouXONQDnz5/fwU "PHP – Try It Online")
Brute force version, actually checking with replacing each letter with all ASCII between codes 10 and 122 (many useless checks, but it saves bytes for example initializing `$j` to 9 instead of 64, those results can't be positive anyway)
As noted by @LuisMendo and @PeterCordes (thanks), this works because `crc32` [can reliably detect](https://barrgroup.com/embedded-systems/how-to/crc-math-theory) every burst of up to 32 bit errors, and in the ASCII-encoded input, replacing a character will cause a burst of 14 (7\*2) bit errors at most.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 94 bytes
```
g←252|1⊥⊢⍪⎕AV⍳⊣
252|⊢+0,⍨∘(,'⊂⍷≠Eæ×(í/7Ãs·¨\=Ш⍎ëáØ@'∘g∘.⌊⍨'#⌿O⍒`=~{└⊤Üã/cëÖ¶⌹⌹bð'g⍉)23 23⍴-
```
[Try it online!](https://tio.run/##7VVBaxNBFMZr/oQPPGzFNLVJxVPBEgMGLEXTCooHJ7uzuyO7M3Fm1jQqHiwUE7KhSqs9KFirEhRRUCyehOw/mT8S326SWsXePElgd5mZ97033/vmY5Y0glmnRQLhDU380vR2apXCWnn5olUX64x7ILhlOvuUk3pAa0uXV3GCoPJ1S5FAW0PPbG4VzxUfzJvOW9N5beL3GF26ZuIvCMylEVw9czZv4r55vDuTx2KPTHxg2q8qybvk@Uzyce58sqEGB4P@zcVka9A3cS/5kOwluxcsTPDwLZhuB9OtU6b7Y8XET28tnnx432xvm86bE8mLZH/OxoRng2@m@x2fevLZ8kzcPl0sQbFk4q@zQxc5YlkkVl0xnY3Bp5LZfJJ2erWM39VL1dqQzaeY3s5auWZVOTDuChkSzQQH7VMhW0C4A7ZwUknGK02mfSCNRsDsDKkwDSFhI9JUgrIZ5TbN8jQNKAbCiI@heaBSCgkO1dTOdhmVl3I8xdgIYQuupQiASIplbJ@zOxFVSIFoGB0KSBqwbODg4C5FZsIFh3lMkwAcogkIXIWIHwJ/4wK2TzingSrAMuGtY4IZARXVbyNB0GKyDlwwRfOjLv1IjVgrCEkL6hQFQfJOZFMHnEhm2knCVciUSou7UoSpmqBEJFErrEuwHZumbRSg8odGR/onQSCakxCWVZHtj/fOQ9Nn2OREv0NNR3KpdAM8LC2jsdRuRkFIVIxPFMOTDDMxiKKqYOVyrPiPDHJvapD/0SB4gbT3XGBFtErpl1VuTO@SqVWOsUoJrbIw/e1MrfJ3q1w5YpWFnw "APL (Dyalog Unicode) – Try It Online")
Uses the vector of Unicode codepoints as the I/O format. Otherwise it would cost me 11 bytes to convert from/to strings:
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 105 bytes
```
g←252|1⊥⊢⍪⎕AV⍳⊣
⎕UCS 252|46,⍨∘(,-+'⊂⍷≠Eæ×(í/7Ãs·¨\=Ш⍎ëáØ@'∘g∘.⌊⍨'#⌿O⍒`=~{└⊤Üã/cëÖ¶⌹⌹bð'g⍉)23 23⍴-∘⎕UCS
```
[Try it online!](https://tio.run/##7VVBaxNBGMVr/oQfeNiKSUqTqKeCJQYMWIqmFRQPTnYn2ZHdmTgzaxoVDxaKWbKlStUeFKxVCYooKBZPQvafzB@J3@4mpRZ68iaBzTIz35s373vz2JCOV3B6xBPtsYnemK0XjVpxrbp82WqKdcbbILhlwn3KSdOjjaWrqzhBUPWmpYinrXHbbG6XzpceLZjwgwnfmegTVpdumOg7AnM4Xqs2IAFULuRNNDRPd@fyhXNI@cREB6b/thZ/jF/NxV/mL8YbanQwGt5ejLdHQxNtxZ/jvXj3koVb2vgrmkGIBNYZM/i9YqLndxZPP35odnZM@P5U/Dren7dxw8vRTzP4hU8z/ma1TdQ/WypDqWyiHwWkyNSMWygZ@XFWXzHhxuhr2Ww@Sxq/XsX36pV6Y8wWEGPVOTDeEtInmgkO2qVC9oBwB2zhJN5MVrpMu0A6HY/ZKVLhNoT4nUBTCcpmlNs03aepR7HgB3wCzQOVUkhwqKZ2ekpGL@VkirUMYQuupfCASIo0tsvZvYAqlEA0ZLcDknosHTg4uE9RmWiBw9pMEw8cogkIXIWAHwL/0gK2SzinnirCMuG9E4qpABU076JA0GK6DlwwRfNZl26gMtUKfNKDJkVDULwT2NQBJ5Cpd5Jw5TOlEvKWFH7iJigRSPQKeQm2Y9OkjSLUjnl0pH/ieaI7LSGtCmx3cnYeui7DJqf@HXqa2aWSA/CytAwmVrdSCUKiY3zqGN6kn5pBFFVFK5djpX@OxoNZNP7HaOBHo7/XAlbCkJSTkNyafT9mITkhJGUMSWX2JzMLyfGQXDsSksof "APL (Dyalog Unicode) – Try It Online")
Uses the row/col checksum approach as in [Mitchell Spector's C answer](https://codegolf.stackexchange.com/a/200773/78410). Because bitwise XOR is not a built-in function in APL, I had to use plain sum and negation instead.
### How it works
```
g←252|1⊥⊢⍪⎕AV⍳⊣ ⍝ Auxiliary function: checksums g matrix → checksum vector
⎕AV⍳⊣ ⍝ Convert string written in APL SBCS to integer
⊢⍪ ⍝ Append the checksum vector at the bottom of the matrix
1⊥ ⍝ Column-wise sum
252| ⍝ Modulo 252
⍝ Main function: Correct the typo based on checksum
252|⊢+0,⍨∘(,'⊂⍷≠Eæ×(í/7Ãs·¨\=Ш⍎ëáØ@'∘g∘.⌊⍨'#⌿O⍒`=~{└⊤Üã/cëÖ¶⌹⌹bð'g⍉)23 23⍴-
23 23⍴- ⍝ Negate each element and reshape into 23x23 matrix, discarding the last '.'
(...) ⍝ Pass to the inner tacit function...
'...'g⍉ ⍝ Check rows against the row checksums
∘.⌊⍨ ⍝ Outer product by minimum (rows and columns reversed) with...
'...'∘g ⍝ Check columns against the column checksums
⍝ Result = all-zero matrix except at the typo (difference mod 252)
, ⍝ Flatten the result
0,⍨∘ ⍝ Append a zero to account for the last '.'
252|⊢+ ⍝ Fix the typo using the offset
```
[Answer]
# Java 10, ~~140~~ ~~139~~ 137 bytes
```
s->{var r=s;for(int i=0;;i++)for(var c='z';c>65;c-=c==97?7:1)if((r=s.substring(0,i)+c+s.substring(i+1)).hashCode()==0xA89D0862)return r;}
```
-2 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##7VVNbxMxEL33V4xy6a6SbFMk@sHKRQg49EBViVsRB8eedB28duKPhFDlt6dj76YEJJCQOEEvK@/MeOa9N0@7c77i47n8shOaew8fuDIPRwDKBHQzLhBu0ivAx@CUuQdR9Adf1hTfHtHDBx6UgBswwGDnx1cPK@7AMV/PrCuoEyg2qWs1HJYpkJKCHX87rsXV2ctajJlg7PL89fmr01LNioIuVj5OfZ5TTEaqHIrhYUgNT8uyarhv3lqJRcnY5Oubi8t3k4uzF6XDEJ0BV293dQK3iFNN4HqMK6sktMSxp/HpM/CyIwgnJ3DNlsQcNHKZOA6uzaAjv/EB28rGUC3oWtCmMJUoBktD5cSppebWQGjQug1wI0HY3KGPrFVogC8WhCRX@jRF2HYRSWXwQqEhpdO9gBop0UbTl44AnbMOJAYUeUrX3rn@lXJdhbAmOKuBO6Q2ojFqGdETBB4ADZ9qBIda5YOkwwoJmZ2BVPcqcA2SBw6WohDNU@EPWEA03BjUviKfmM0vkhkAbWtOACHYfRyMVR5HHcsm@g61p21sYIrJcM7KKFCCjNlhwXHjW@V9aj5ztk1qgrfRkVbUlxMdgYlGBe9/0uiAP9farvepZNwomn72CNaNIpJ7/Z407eTyaQAtK7jYSz3LEKwjxcxeMdpkm8XgHn01KMtsu2wnzu5SenC4@d8b6vpPDHX3bKj/zFCC3aY0EVE6f6ByzV@01PM36p@21O13S6V/93b3CA)
**Explanation:**
Also uses an hash like most other answers. The hash of the expected text is `-1466103710`. All other possible double replacements of letters cause no collisions, which has been verified locally with [this test program](https://tio.run/##jVVbb9owFH7vrzjNw5QoNKOvZWzquu5@b3fXNBnbEKeOTX2BsYnfzo4TEggFaUgojs/t@z6f4xRkRk4KdrNaUUmshTdEqL9HAFM/koKCdcThY6YFgxJN8ZUzQk1@/ASSBDcAqdUkuBkHQ7haWMfLTBGlr0XJ42RQ@dRBwH9POXWcoSP50f9Z24RykF9uLI1TlhObX2i2SVLn1t5lU0znpIqjNq5xPoMobbMlmwpUexUA9juAJHeOG4v7ERlRxseTXBQ3slR6emus87P578Wf88cXTy6fPnv@4uWr12/evnv/4ePV9afPX75@@x7VycbaxKGGGPYHIB60BCRXE5cjfBBpulYL0Yzj43XdjGrlUFQbtzE0J@bcxSJJoyhJ1iEAwVEozwfrnVAyuAKFs4ZF5vRFiDaGLOKkrdeSNXwqCeXsnaJ8W2frR7byiPs9rEvTPRaRniaDNmFDuAiEi32Eiy3CB0lvA2qIFzvE95HvCMD@Q4A9IlzPRaVCB8OOEiw9YO2q0fDrpM74rSdyc7BdRvi7d6/rv@l2GA43A7HDYu8UpGnV3WkUmp@mURylIo2SXoQMwkuBL8HUKbhDYHm0b92s6ufy0BhW5R@ePtrluHWCFT58Sims0MriAXrFjqNDIWcHc0Vv9Z08g2r@TyjqB8KCV@LW8yw6fHHEdy6qk@oKS@6f/ur3@80fIVuO7cdsnWt5tFytVi8UXinYgCVejVqBy7k2CyCKIS4Wmmy9MxcuBzKd4j1aeVoMQ5dy6rFbwVLBwySGOMcllilLBF679oAbo7G7ucM2CFXq9MasX9FWe4ThMFoCMRzT0LyibhECccAVGUmOPS5FtWC4mHFEpsfAxEQ4IoERR0DjLqrWOnawAM6ZUlzaDD8OanHAWAHAESkQIDjd7IPSwvJezTL3tkZt8VuygBEPV7PRzGNTAvPVgDpDlC2FDacLY6PLoCZY7Q1qhXkJ0qE80MjgckejLf5ESj1vTOED5Wm@rt2DeS6QZKNfq2ktlw0F8LCc8WupxxUEbVAx1SiGJ1lWYhDLbfYP). (Obviously times out on TIO since it has to do \$(52\times 530)^2=759\text{,}553\text{,}600\$ iterations, including calculating the hash-code and substituting characters in each iteration. It takes between 8 and 9 minutes locally.)
```
s->{ // Method with String as both parameter and return-type
var r=s; // Result-String (starting at the input to save bytes)
for(int i=0;;i++) // Loop `i` upwards from 0 indefintely:
for(var c='z';c>65; // Inner loop over the characters `c` in the ASCII range ['z','A']
c-=c==97?7:1) // skipping the characters "`_^]\[" between 'a' and 'Z':
if((r=s // Set `r` to the input-String,
.substring(0,i)+c+s.substring(i+1))
// with the `i`'th character replaced with `c`
.hashCode()==0xA89D0862)
// And if its hash-code is -1466103710:
return r;} // Return `r` as result
```
[Answer]
# C (gcc), 125 bytes
Note: my code includes 2 unprintable characters `\x0c` and `\0x01` in the string literal which aren't visible in the snippet.
```
b,i,j,m,n;C(char*T){b=i=n=0;for(;i<10;b|=("N<Syr4Zd"[i]!=m)<<i++)for(m=j=0;T[j];n^=!i*T[j++])m^=(1&j>>i)*T[j];T[b]^=120^n;}
```
[Try it online!](https://tio.run/##dVRNb9NAEBXHWPyIIQiwG5M2iAPCcSVUOCABF3qipGi9O6k3Xe@G/WgbQX97mV3HaVoJKVKcNzNv3rwZh7@@4PzurilluSq7UlcnOW@ZPTgt/jS1rHV9VC2NzSs5nx1Vzd86H3@bf3@6sW9/iCfjM7l4VnfFfC4nkyKmdfWKCk7PVotKn9fP5AE9TiaLojuv89nL1fGxLA5S9PSsWZzXszdH57q6vcuy51JzFQTOnRdKNtP2eB@yUl88goQ0EcmiWDjweOOhhvFnDVKTkI55aTT4Fo3dANMCuBFEMiDX0rfA1mslecp0VEYp3Tp4tOC4RM0x1XlUSIEu6G1qCWitsSDQI09denprtz8p1mdwo701CphFouGtlr8DOpLAPKBmjUKwqGR6EPRwhaTMLEHIC@mZAsE8A0MoBL1LfKAFaHqtUbkpfGV6859gEuBCsyKB4M2AgzbSYdlP2QbXq3bQsQ00SIaQeBE4ChDBJu8s066TzkXypTVddBOcCZa8Il5G43CMY0zh0yOP9uZnSpnrIUS0LvB227uE61bSkIN/O097u1xsQMvyNmytXiYJxpJjenCMNtklM5hDNx1XWUajECR1XmR/slF/MQ0Tv7ZX00VFPCdahTqPYDGZFVU2IoSvN/mQWkKKUSAb0Y1BHnljUGqBN0R0VKWMsx22qO7j9IYAdX9YecVUQKp8PXvzrtpD5vAQGIpHh4fw0aDTrzxcG3vZH7IOSsWtWsbpfB1tj7PgMHqzIUW2I3M89tvq36Ut1ZfAL6XagPRgNH1TfSAzNtAyFzeaWkTBTK1b1qCXfK9PYpFLyPcmIROKdPhSByTrKWOwb88Wmjj9yxS7yipmnuysLqqBO@6gW@e9/7vw1o3Rmqbxy3zcn5s2fjgaFO/hhUgf91OPy/s9lPeu7hGmfiOLPlgNs/TrdkR7Ht1m9Ml2jT6Q0x6dd/FsOaJAMR1T9e3dPw "C (gcc) – Try It Online")
The `i`th character in the literal is the XOR of all the characters in the original text at positions whose `i`th bit is `1`. The program performs the same XOR on the modified text. The computed value will be different iff the modified character is in a position with `i`th bit `1`. This gives us all the bits of the modified character's position.
Finally, we modify the character such that the XOR of all characters is that of the original text(120).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~52~~ 49 bytes
```
θJ↨²⮌E =&%ce9KG*¬⁼§γΣEΦθ&μX²κ⌕γλι⁰§γ⁻²⁸ΣEθ∧⁻κⅈ⌕γι
```
[Try it online!](https://tio.run/##dZJNb9swDIbv/RVEgQ5yoQVDTxuKHVqgHbohQ7Ht0CsjMbFWmXL0US@/3qPluMsG7GSKpF6@fGTTYjQB/Tg@RsdZ7Zvrs8@l638EdYuJ1JWGb/RCUcI19uocPr65MPThy6fLcw1fQ1Z3@4I@qZv8wJZ@qZ2G76WrvffOZ4pqr@HW5cElumGrOg2PYZC0CD83TaPh3klarvmmHl0zf9@JkdnSifTacUnq6v2fIaI@yc6FZw1P6lRzFmuux/GBwfE2xA6zCwy5pRAPgGzBBOt4t2QGl1vAvvfO1M4k16Sl64vsAsk4YkP1XiZPUugKH1s1UIwhgqVMpk6Z5WM8HqU2d5jAOQYPGElkTMtuXyiJBcxAjBtPEMm7GlgJhP8Bwhas27mMHixmhCBZKPza@JcXMC0yk08rWCMf/lOsBlLZ/BSDkMOSBw7yWnresi1pdp2gwwNsSICIeVsMWbAlVnYROXUupUl8G0M30YQUShRWoouyjqFpjRXc/cPoZH/0PgxLSWRTMe1xtoahdbLkwu@V6YwrTQPksXIsR9TbaiFEIcYLMXnJrsKQHzutzsa3L/43 "Charcoal – Try It Online") Link is to verbose version of code. Works with all printable ASCII, not just letters. I originally wanted to do a Hamming check on all of the letters in the input but I was too ill to implement that at the time and by the time I got better I realised that @GB's modular sums would suit Charcoal better anyway. Explanation:
```
θ
```
Print the input string.
```
E =&%ce9KG*
```
Loop over 10 partial sums. These characters are the result of cyclically indexing the appropriate sum from the correct input back into the predefined printable ASCII variable.
```
ΣEΦθ&μX²κ⌕γλ
```
Filter on the desired characters for this sum and take the sum of their indices within the predefined printable ASCII variable.
```
J↨²⮌...¬⁼§γ...ι⁰
```
Interpret those sums that don't match as a number in base 2 LSB first, and jump to that character, which will be the incorrect character.
```
§γ⁻²⁸ΣEθ∧⁻κⅈ⌕γι
```
Subtract the sum of all the other printable character indices from 28 which gives the index (modulo 95) of the current character.
@xnor's algorithm can be implemented in 42 bytes:
```
θ≔⁻⁵⁰⁹⁹⁸ΣEθ℅ιηJ÷⁻¹³⁴⁴⁷⁴²⁰ΣEθ×℅ικη⁰§γ⁺η⌕γKK
```
[Try it online!](https://tio.run/##dZLbbhMxEIbv@xRz6UgmSiEIql5VKkhBiqhEX8CxJ/FQe7zxISFPv0z2UCgSe2XP4Z9/Pq/1JttkQt8/ZeKqjov7m4dS6MBqS9yK@ri6u/us4UeLams6ddTwPTtiExQt5NPgpeNbi91zUhuuj3Qih1Pv7Yf1@tP6/epN@zNFLOqPiIaXWUjDSsRGIw91ww5/qYOGpyBaXsNXYjfcEV/UtWdx3/cbBuJ9ytFUSgzVY8oXMOzAJhlxmCNnqh5M1wWyQ2WRNimJXauYoVhCtjj0VQwoidh4KtWAOacMDivaYcoon/N0ldxYYRPXnAKYjCJjPdOxYRELpgKy2QWEjIGGg5PDCcVZ2oOjA1UTwJlqIEkUGr8WvvEC1htmDGUJW8OX/yQHA6XtfopBqGmOAycqqMctfSuj6wLRXGCHAkTMu2bRgWt5YJcNl0jyP4j4Pqd4pQkltSysRNfIOhavayzhyz@M/trfhJDOc0pkS7N@mq3h7EmWnPm9Mh1xlesAeaya24R6P1hIWYjxTExeMg4wTMGyvOnfncJv "Charcoal – Try It Online") Link is to verbose version of code. Works with all printable ASCII, not just letters, but fails if the input is correct (would cost 3 bytes to fix). Explanation:
```
θ
```
Print the input string.
```
≔⁻⁵⁰⁹⁹⁸ΣEθ℅ιη
```
Calculate the size of the error.
```
J÷⁻¹³⁴⁴⁷⁴²⁰ΣEθ×℅ικη⁰
```
Calculate and jump to the position of the error.
```
§γ⁺η⌕γKK
```
Correct the character that is in error.
[Answer]
# [Python 3](https://docs.python.org/3/), 364 bytes
Output is bz2 encoded. Input is ignored. Code contains unprintable characters, so here is the hex version. Utf-8 encoded version is 55 bytes regular code + 309 bytes compressed data. See commented lines in the header of the TIO link.
```
import bz2
lambda s:bz2.decompress(b'BZh91AY&SY\xd3\xaa\xfe\xfd\x00\x00(\x15\x80@\x05\x02"?\xf7\xff\xa00\x01F\n\x86\x82bI\xfa\x14\xf4&\x99\r\n\x00\x06\x80\x00\x04\xa6\x84\x9a\x9e\xd455<\xa6\x99\x19\x10o\xcf|b5oN"\x06V\xab\xd0\xa3\x8awA\xbb}\x8a=\xa6\xcc\x9b#\x1a\xcd\x94Q\x83%Lp\xc9-n\x99\xd9\xee\xb5\xbc\xb4xc\x1a\xeaz\x03\xe49*\x90\xc9E\xf8\xa1y\xb7q\xcb!O\xbeA\xf5\rj\xd9Vg2\xec\xe9&A\x08\xb0\x91\x0c\xde\x05_m\xeb.\xa8\x9a~\x0b?\xec\x0e+\x14\xf0q\x05\x19\xa3O\x84\xb0\xbb\xea\xb6\xc3d\xab\xa6\xa3\x1b\x02c\xd3\x8fE\x99F\xf8\xdf\x07\x95\xdam\x10\x1b!\xb0m\xd7m\xb9\xdf\x9d:&\x0e\x13\xa4{S\xa3\x9ao\x95\x98\r\x995#\xdb\xbb\x17\x1d`2\xd0\x1d7$\xb5E\xe1Y9\xf4u\xbd\xcc9\x01va\x0e\x12\x7fA\x06\xa6[\xceg>\x05\xc8T\xaf\x87\x1a\t\x18Hcq\x87\x04\xa2\xa5\xf8\xc2\x0643\xbci\x14\x14\xbe5\xd77\x99w\'\xba&\r\x19b\x1ck\x16\x10&v\xd0\xb9\xe1W\xc3\x82{\xbe\xdb-\x81\xb0\xac\xc8A\xfc]\xc9\x14\xe1BCN\xab\xfb\xf4').decode('ascii')
```
[Try it online!](https://tio.run/##dVRrb9s2FP2eX8Gmmx1vqSH5EUvFsi4dUqzA1qJo0SGbho2Pq1idRDqkFMvt1r@enivaWTdgH0iR93HuuefS3uzatbPzu3B@/NyKypbON7KtnBXtmpzfCWmN0M5U9vpg2VbtWsjNpq70EBmQhpBm07XkRdAVWU1DXks1wdF0dh96Ksh754WhlvRQJcJ7v7/CFyO0s613tZCeAKPXtrrpKICCbAVZqWoSnupqOBgcbgnMXClMdV21shZGtlI4WEVn7wP/xUXotbSW6jAVP0m7@x/nQCB06h0IitYd7MK6KtBp7HLdhcg6iEbuhCIIAvKm02SE6fygnZc2NFUIDF5617CaIrjOQyvgSrSjiduYisv/aPRZ/7Ku3fbgAmzo9Hpf@1Rs1xWaPOh3r2mUK3ABDKv13V7qcqDgPBSzB8UwyWYQQwYK0@Ojqtk43wr1fnakz7FPec6eQjgJU4zZGToZd22ZjSeTo4dig1bbE/3PsSaL6@TuM5haNspIER4zmqF7PDV@@ss6Ty@uRq@vit7Mi17Koi8JyxR9kvA6Kfp0WfRZ8h1uOCSz4yfwr7BKxA9B6bPCIuQMa6aewwOUdIHvYlT0eV54dg@RHJLszwiQfMc3R0KOsmaxXH4TzUjrU16JK3pd/qWW7sUxI7yFXyEUEBKMM7m9KHql/ubjeczVGvnqIZKBq9FKvngF9/zLHze4549shDdYhKoKbSmkqEWvYw7J9ygFdFrkXyE44bRLNJShQLpD6OoGJvXgJY6E@uWy8O8Y8e31DFmAoXwEe4IEhew8xRlWQ6zi7w38agqsjHv/CJt6EtMS@nqvXXITBWcR5PxlFIqxlGKC@HKncxPl4LZZjlTxiHScZlZecqfPInGDeSWYWw5QIxuWluMfMCpuZoVN5TEuN49HTAYB/CoWH15H@Fy6CJBnmCqwl1DZqEgqBXhq/pjF4aRm9QVrCwqUXuX8GjrcDY8n50dzK/cVkLAqL@LrkGe/IoCuv43N6@wNbCCUrYbJtNizH/RNNAxPCNlyGTvUMwZZzHmcVZSRlyLueMWt59tiDIMcMfs0Z9L6T2xnrMboNjJnESj9mdXlF/2BEbjLR7ilcQZSMzcevP6N30YsROnT71/EeZS8FuPJ8HPjX6zEn3Q1ntzdfQI "Python 3 – Try It Online")
] |
[Question]
[
It is fairly simple to, given a number `n`, create a range from `0` to `n-1`. In fact, many languages provide this operation as a builtin.
The following CJam program reads an integer, and then prints out such a range ([Try it online!](https://tio.run/##S85KzP3/vyhT5/9/QwMDAA "CJam – Try It Online")):
```
ri,
```
Notice that it prints out numbers *without* a separator.
## The Challenge
Your task is to reverse this process. You should write a program that, given a string representing a range, returns the number used to produce that range.
## Specifications
* The numbers are given without any separator.
* You may assume the string forms a valid range.
* You may use 0- or 1-based indexing for your range.
* You may assume that a correct output will never exceed 32,767 (so a valid input will never have a length greater than 152,725).
* You may assume that a correct output will always be positive (so you do not have to handle 0 or negative).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest competing answer (measured in bytes) wins.
## Test Cases
0-indexed:
```
0123 -> 4
0 -> 1
0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 -> 101
```
1-indexed:
```
1234 -> 4
1 -> 1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 -> 100
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~91~~ 80 bytes
0-indexed.
```
X*L:-atom_length(X,L),
between(0,L,Y),
numlist(0,Y,B),
atomic_list_concat(B,X)
;L=0.
```
Newlines added for readability.
[Try it online!](https://tio.run/##FcpBCoAgEEDR46QyhdWuaNPaA9hKTMQE08iJjm@5/I9/3Skk1@bXlyKZmFqN6VTBRocHkSAo7BZfayPhIGCjEJ8z@Ix/brBSqLs3qpIyKRqNZAVJZ7HwrpSG98PYMNl9 "Prolog (SWI) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
LCmLN
```
[Try it online!](https://tio.run/##DY6xbQNADMR28QSSTnc61WkNz2HAcBVk/s/3BMn33@/nnOfP9/k65zyy0NR4MzKzEtnJVE46t6KyqlBdLNWUaxFIFIAGIQyM7ejsanQ3Wz3tXgaTRbBJikNzFUqVoBYljaydmJwaTA9HM@NZh9NluE3LY3s39g7tje0V7YX2PsfjHw "Husk – Try It Online")
Only letters!
Takes input as a string, result is 1-indexed.
### Explanation
```
LCmLN
mLN get the list of lengths of all positive naturals
C cut the input into slices of those lengths
L get the length of the resulting list
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 6 bytes
1-indexed.
```
āηJsk>
```
[Try it online!](https://tio.run/##MzBNTDJM/f//SOO57V7F2Xb//yuBAQA "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##HY4tbsJxEEQ9pyBoxM7uzH5UcABu0SaoyiYkJJieqhJBda/07y@YpyZvnun9A5ftfr1t99/vv5/z1@dpux2ej7f983E4bjvs4MEXlNUDA@AIEEKi0Bg3h7uH0@Xp5e0TFgiPCIYio6JjaASdQVJMFpsjE@QKUVKq1Jq0RHpGMpWZlZ1TViivKJYqq6pr2hrtHc1WZ1d3z9isoFlns0SzRrOa7R8)
**Explanation**
```
ā # push range [1 ... len(input)]
η # compute prefixes of the range
J # join each prefix to a string
sk # get index of the input in the list of prefixes
> # increment
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~9~~ 7 bytes
```
⟦kṫᵐc,Ẹ
```
[Try it online!](https://tio.run/##ASUA2v9icmFjaHlsb2cy///in6Zr4bmr4bWQYyzhurj//1r/IjAxMjMi "Brachylog – Try It Online")
0-indexed.
### Explanation
Here we pass the input through the Output variable, and access the result through the Input variable.
```
⟦ The result is the input to a range…
k …with the last element removed…
ṫᵐ …which when all elements are casted to string…
c …and are then concatenated results in the input string
,Ẹ (Append the empty string, this is necessary for it to work in the case where the
input is the empty string)
```
[Answer]
# Java 8, ~~66~~ 59 bytes
```
s->{int r=0;for(String c="";!c.equals(s);c+=r++);return r;}
```
0-indexed
-7 bytes thanks to *@PunPun1000*.
~~I have the feeling this can be shortened by only checking the length of the input somehow, since we can assume the input is always valid. Still figuring this out.~~ Unable to figure this out, and it will probably cost too many bytes in Java to be useful anyway (same applies to returning a substring of the end of a 1-indexed input).
**Explanation:**
[Try it here.](https://tio.run/##hZDPTsJAEIfvPMXKCUIgO/9n0@Ab6MWj8VBLMVUs2BYTY3h2XBGukuwcdua333zZ1/KznG93dfu6ejtWm7Lvw13ZtN@jEJp2qLt1WdXh/vd6aoRq8jB0TfsS@mmRm4dc@fRDOTRVuA9tWIZjP7/9/s12y1ist93lRbUcj4ubalF/7MtNP8mAarbsZrNp0dXDvmtDVxyOxR9wt3/eZOCZ@7ltVuE9a51Rj0@hnP45PXz1Q/2@2O6HxS6Phk07aRfVZBwBaTw9Of4Tupq4jsh7WNQ8QQQABAIGAQUDh4QRAREJGQUVDR0TRQJCImISUjJyShwZGJmYWVjZ2DlJFBAUEhYRFROXpFFBUUlZRVVNXZNFA0MjYxNTM3NLHh0cnZxdXN3cPaWYslDKy1IGpRxK2fnyBYfR4fgD)
```
s->{ // Method with String parameter and integer return-type
int r=0; // Result-integer
for(String c=""; // Check-String
!c.equals(s); // Loop as long as the sum-String doesn't equal the input-String
c+=r++ // Append the number to the the Check-String,
// and increase the Result-integer by 1
); // End of loop
return r; // Return the result-integer
} // End of method
```
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 29 bytes
```
iys&p>0<11[ppl>s1+<lfspSylL]>
```
[Try it online!](https://tio.run/##BcE9CgIxEAbQ29jYzPczkwRkT2BnKbaCkCKw1Z4@vjevvX/XeVtHPID3WvM4cX/M77le13x@jr0DlLNaHwgAhGAkCg0dg0GQFM1ksbFzKARRkpUqNXUNh2FattPl5u6RkUim0plZ2bLnqCgUS@U/ "Ly – Try It Online")
Can't believe this worked as well as it did...
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 8 bytes
Starting to get to grips with function methods in Japt.
0-indexed. Can take input as a string, an integer or an array containing 0 or 1 elements.
```
_o ´U}a
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=X28grKVVfWE=&input=IjAxMjM0NTY3ODkxMDExMTIxMzE0MTUxNjE3MTgxOTIwMjEyMjIzMjQyNTI2MjcyODI5MzAzMTMyMzMzNDM1MzYzNzM4Mzk0MDQxNDI0MzQ0NDU0NjQ3NDg0OTUwNTE1MjUzNTQ1NTU2NTc1ODU5NjA2MTYyNjM2NDY1NjY2NzY4Njk3MDcxNzI3Mzc0NzU3Njc3Nzg3OTgwODE4MjgzODQ4NTg2ODc4ODg5OTA5MTkyOTM5NDk1OTY5Nzk4OTkxMDAi)
---
## Explanation
Implicit input of string `U`.
```
_ }a
```
Get the first integer `>=0` that returns true when passed through a function that ...
```
o
```
Generates an array of integers from `0` to 1 less than the current integer ...
```
¬
```
Joins it to a string ...
```
¥U
```
Checks that string for equality with `U`.
Implicit output of resulting integer.
---
## Alternative, 8 bytes
```
ÊÇo ¬ÃbU
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=ysdvIKzDYlU=&input=IjAxMjM0NTY3ODkxMDExMTIxMzE0MTUxNjE3MTgxOTIwMjEyMjIzMjQyNTI2MjcyODI5MzAzMTMyMzMzNDM1MzYzNzM4Mzk0MDQxNDI0MzQ0NDU0NjQ3NDg0OTUwNTE1MjUzNTQ1NTU2NTc1ODU5NjA2MTYyNjM2NDY1NjY2NzY4Njk3MDcxNzI3Mzc0NzU3Njc3Nzg3OTgwODE4MjgzODQ4NTg2ODc4ODg5OTA5MTkyOTM5NDk1OTY5Nzk4OTkxMDAi)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
I⌕E⁺ψθ⪫EκIλωθ
```
[Try it online!](https://tio.run/##HY67asNAFER/ReUuyHDfD1wGUgQM/gXhFBERcmw5Mf76zdrNFIdh5py@puvpPC2tHa/zeitv03Yr7/P6WQ7TTzkuv1t5jMOljsPHeV5f8HscXq2ldnp/xqXWum8NkFjUPBIBEQkZBRUNHQOTgJCImISUjJyCkoGRiZmFlY2dg1NAUEhYRFRMXEJSQVFJWUVVTV1D08DQyNjE1MzcwtLB0cnZxdXN3cMzIDAoOCQ0LDwiMiG7UPaz7EPZS9mdoe3@2m5b/gE "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
λ Inner map variable (μ inner map index also works)
I Cast to string
κ Outer map index
E Map over implicit range
⪫ ω Join result
θ Input string
⁺ψ Plus an extra character
E Map over each character
⌕ θ Find the index of the original string
I Cast from integer to string
Implicit print
```
[Answer]
# Haskell, ~~40~~ 37 bytes
```
f s=[n|n<-[0..],(show=<<[0..n])>s]!!0
```
Function that reverses zero-based ranges.
Thanks to Laikoni for saving 3 bytes!
[Try it online.](https://tio.run/##y0gszk7Nyfn/P02h2DY6rybPRjfaQE8vVkejOCO/3NbGBsTLi9W0K45VVDT4n5uYmadgq5CSz6UABAVFmXklCioKaQpKBkoYIoZYhIyMTbCLmpqZW1gaGhgaGhoZGitx/QcA)
[Answer]
# [Retina](https://github.com/m-ender/retina), 30 bytes
```
+1`(\d+?)(?!\D)(?<!\1.+)
$0;
;
```
Recursively adds a semicolon after each number then counts the number of semicolons
[Try it online!](https://tio.run/##DY4xakNRDAR738KQwuZD0GolrYQDbnKMX9iQFGlShNz/@zVTLbPz9/3/8/s8jg2Py/613a@X@3n/XPw473jfrqc3u51ux2FwRpZ6YAAcRCBREBrj5nB3enh6ubx9aASdZDBZFJsTFggPRkRGhaJj0hLpyYzMrFR2TlmhvFhRWVWqrpEJclGhVElqTVujvdnR2dXq7hmbFTTrbJZo1mhWs70A "Retina – Try It Online")
[Answer]
# JavaScript (ES6), ~~32~~ 31 bytes
*Saved 1 byte thanks to Challenger5*
```
f=(s,r=n='')=>r<s?f(s,r+n++):+n
```
### Test cases
```
f=(s,r=n='')=>r<s?f(s,r+n++):+n
console.log(f('0123'))
console.log(f('0'))
console.log(f(''))
console.log(f('0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100'))
```
[Answer]
## [Perl 5](https://www.perl.org/), 19 bytes
**18 bytes code + 1 for `-p`.**
```
$i++while s/$i\B//
```
Uses 1-based indexing. -7 bytes thanks to @[nwellnhof](https://codegolf.stackexchange.com/users/9296/nwellnhof)'s *much* better approach!
[Try it online!](https://tio.run/##DY47agNREASv4kCZMDuf7pmeVOdwKvCCsBbL4Nt7/fKiqo7794Pnedmv19/P/XF/e22X/eO2befpkWC1xs3dw9Ph9PJ2@YSFR0QGglHRoZi09IzMRDIrO5UDgyOQAIhCQxgancEkSBab4pSVV1QWilXVpZq29o7ORrOru9UjkyuUgqhSS5qxWUOzYrNEs6BZz/b3PH7259frfD/@AQ "Perl 5 – Try It Online")
### Explanation
`$\` is a special variable that is `print`ed automatically after each statement, so by using that to store our number we don't need to update `$_` (which is automatically printed as part of the functionality of the `-p` flag) to contain the desired output. Then, whilst the input starts with `$\`, remove it and `redo` the program, which again increments `$\` and replaces it. When it no longer finds the number at the beginning of the string, we're done! Finally, decrement `$\` so we have the last number in the range.
[Answer]
# Mathematica, 46 bytes
```
Array[""<>ToString/@Range@#&,2^15]~Position~#&
```
1-indexed
**input**
>
> ["12345678910"]
>
>
>
[Answer]
# [Ruby](http://ruby-doc.org/), ~~51~~ ~~50~~ 46 bytes
```
->n{(0..4e4).map{|x|(1..x).to_a.join}.index n}
```
(This is my first Ruby program ever so it must be easy to golf it further)
-4 bytes thanks to @Nnnes
[Answer]
# [Python 2](https://docs.python.org/2/), 43 bytes
```
f=lambda s,i=1,r='':r<s and-~f(s,i+1,r+`i`)
```
[Try it online!](https://tio.run/##ZY09bsMwDIXn6hTaLEJqEMXNUKO6RFbDQJTEdhjYlCGpQ5Ze3RVdZOoD@PcBfG955nugw7oObvLz5eZlMuisia6qmviVpKfb@8@gCtWF6jOeYcV5CTHL9Eyi1C71OfbX75gw0IQzZlXvi0CML09qqmr3CEgq5agQhhAlSiQZPY29soa0BRDi5F7AsoFuefBuO91@Fm18Ixuyh/rj2IklImXpp0m17D@oUREAOMcXgeQ44rhTV0L@hdd7aMTbnwka/kYAw339BQ "Python 2 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 43 bytes
```
f=lambda s,i=1:s>''and-~f(s[len(`i`):],i+1)
```
[Try it online!](https://tio.run/##ZY1NasMwEIXX1Sm0swarIYrbRQ3qIbI1hqiN7UyRR0ZSF9nk6o7GIas8mL8H873lmi@BDus6Wu/mn7OTSaM1bfquKkfn99uoUucHUic8QdtrrA2sOC8hZpmuSZTapSHH4fc/Jgzkccasmn0RiOnJpLaqdn8BSaUcFcIYokSJJKOjaVBGU8GCEEf7NAwD6o4H76avu6@izd@czTKH5uOzF0tEytJ5rzrmj2pSBADW8kUgOY447tiXkJfwZg@teHtAUPM3Amju6x0 "Python 2 – Try It Online")
---
# [Python](https://docs.python.org/2/), 46 bytes
```
lambda s:s[-sum(i*'0'in s for i in range(5)):]
```
[Try it online!](https://tio.run/##ZU7BroIwEDzbr@iNrvAMFTk8kv6EV@SACrgGtqRbD349trznRSfZ3ckkM7Pz098s7ZfenJaxnc7XVnLF9Q8/JoXbJE@QJMveOokyUNfS0KkSoGoWnGbrvOQnizA77rzrLg/HaGnECb0q8gAQg/kPpipJdneLpNg7hfCRqjNKNYAQR/MWdAxI63gi101a/was@qqskt4Xh7IRs0Pysh1HVfdqUARgTCwiWP@n2HRsQv5Xb5FDJTZ/fsyiGQGyuJcX "Python 2 – Try It Online")
A different strategy. Takes a number of characters from the end equal to the length of the largest run of `0`'s in s.
---
# [Python](https://docs.python.org/2/), 46 bytes
```
f=lambda s,c=0:c*'0'in s and f(s,c+1)or s[-c:]
```
[Try it online!](https://tio.run/##PY1BDoIwEADP9hV7oxU0FPUgST/BlXCoCLgGtqStB1@PLYqbNG0n2Zn57R@GimXp1ain212Dy1qVl@0@yRMkcKDpDj0PNJXCWHD1oS2bBafZWA/u7Vg4R9d527Uv69DQiBN6fsrDCDZsWiqT5Pg0SNx5y1H0wYUQClbT0HGZUfALxiq1ARkFaR2v@JZNWl/DrHwlK5LF6Xxp2GyRPOhx5HXPB05CKBVDJCCWKJaqJvj/vy1T5KJku@8@Zb/l5QM "Python 2 – Try It Online")
Recursive version of the above.
[Answer]
# [R](https://www.r-project.org/), 47 bytes
```
n=nchar(scan(,""));which(cumsum(nchar(1:n))==n)
```
[Try it online!](https://tio.run/##K/r/P882LzkjsUijODkxT0NHSUlT07o8IzM5QyO5NLe4NFcDImtolaepaWubp/nf0MjYxNTM3MLS0MDQ0NDoPwA "R – Try It Online")
1-indexed
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~17~~ 11 bytes
-6 bytes thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn).
```
{,\⍕¨⍳≢⍵}⍳⊂
```
[Try it online!](https://tio.run/##HU4/SsNhFNu9yG9p4eW9vH93cSmUuhR0FXFxEBR@4OIFnLqXXsCjfBdpP11CQkKS3dNxu3/eHR8frtfDeP962dyP9fv3NNbz@PgZ6@X1j32@TXeBGpe7w2bBxH/lkdUQAAoD4QgkCq2iUFVTqmtoammbGEzNjOYWllbWFIJKI@kMJovt4nB1c7p7eHp5hwRCw4LhEZFR0SmJ1LRkekZmVnZJobSsWF5RWVXd0vNQz7GeRT1DPT/LcgM "APL (Dyalog Unicode) – Try It Online")
`⍳⊂` find the **ɩ**ndex of the entire argument in
`{`…`}` the result of this anonymous function:
`≢` length of the argument
`⍳` **ɩ**ntegers until that
`⍕¨` format (stringify) each
`,\` cumulative concatenation of those
[Answer]
# [Python 2](https://docs.python.org/2/), 46 bytes
0-indexed
```
l=lambda x,z="",y=0:z<x and l(x,z+`y`,y+1)or y
```
[Try it online!](https://tio.run/##1Y89bsJgEET7nMJygy1c7Oz/RvFdcESRSA4gRIG5vPmukXY0mvfmtj1@rhfe93Vel7/v89I9p9fc99M20@fr69ktl3O3Di08nrbTtB0xXu/dtt/uv5fHsA49gUXNIwsEgCFQGByBRDExmFlY2dg5OLmEBMIiomLiEpJSSgplFVU1dQ1NLSODsYmpmbmFpZWTw9nF1c3dw9MrKBAcEhoWHhEZlZRITklNS8/IzCqqJlQNVm2oWqmaM/XjuB/@/YvDxxs)
[Answer]
# [Aceto](https://github.com/aceto/aceto), ~~27~~ 25 bytes
1-based index.
```
;L[¥
`=]z
MLdI<
r!`; p
```
We `r`ead the input and `M`emorize it (and directly `L`oad it again), then we negate it (`!`; leading to a truthy value only for an empty string). If this value is truthy (```), we jump to the end (`;`), where we `p`rint the implicit zero.
Otherwise, we increment the current stack value (initially a zero), duplicate it, and put one copy on the stack to the right, while also moving there (`Id]`). We then construct a decreasing range (`z`), join the stack as a string (`¥`), and move the value (and us) on the original stack again (`[`). We `L`oad the value we memorized earlier (the input) and compare it with this string. If equal, we jump to the end again, where we print the current "counter" value (`=`;`).
Otherwise, lots of empty space is traversed until the Hilbert curve eventually hits the `<` which puts the IP on top of `I` again, incrementing the counter and testing again.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 16 bytes
```
r0({)_,s2$=!}g\;
```
[Try it online!](https://tio.run/##DY6xSkQBDAS/RbhC4YpkN5tNOPwTQcRCEK45S/Hbn68fZubz@@N@HI94/n15v/7g8vr09/V2O45IsNSezchMJLNS2emcXAQSAFEQGsZgGUyCZFFsmsOtqCwUq0rV5ZpahVIQVZJa1mg7OhvNrlZ3u6fX4TRMl@W2Pd6JycFwajQ9npnd2HNoz9ieoj2h3X8 "CJam – Try It Online")
## Alternative 16 bytes
```
r:V;0({)_,sV=!}g
```
[Try it online!](https://tio.run/##DY6xSkQBDAS/xe4Ei2ST3WwUf@NaEYuDg2u0FL/9@fphZr7un4/j@H69vsXl9/nj5ef6/vR3O45IVFPjzchMZGUnUznpXAQSQKFBCANjKyoLVdXFUk25tqOz0dXdbPW0exlMgsUmKQ7NVSgFlVqUNLJ2YnIwNT0czYxnHU7D5TYtj@3d2HNoz9ieoj2h3X8 "CJam – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 13 bytes
```
q:Q,),{,sQ=}#
```
So many commas...
[Try it online!](https://tio.run/##DY4xSkZhDAQPYyW8IrubbBLBQ/xH@LETLMRSPPvz64eZ@fh8ft3399vjer1@r5/H@9/LfQeoLPcsAgAhJApGY7AMgqSYLJrN4SoEUVKqZLVGm5FIpjKz0tk5uRWFYqmyqlxdU@swTMvpst0eb0ej2ersanf39E4MhqPJqfH0zOzGnqE9sT2iPdCe5/gH "CJam – Try It Online")
### Explanation
```
q:Q Read the input and store it in Q
, Get its length
), Get the range 0..n
{,sQ=}# Find the index of the first number in the range to satisfy this block:
, Get the range 0..(number)-1
s Stringify it
Q= Check if it equals the input
```
[Answer]
# [Perl 6](https://perl6.org), ~~30 28~~ 27 bytes
```
{first :k,*eq$_,[\~] '',0...*}
```
[Test it](https://tio.run/##LY7LDoIwFET3/YqRNPJIbQokkFjRn3DnowssBl8gRRNj8NexiLvJzJ1zp9bNJekfRuOZ8FyS6wvTvDpoZP27KBvTYn5mgb5TxTbbzw6uywTnPOh@nbU2rSRF1UDAuggjhlAIhjhSaZLiTQBLpKZtkMHbU@XzU1Xe5N8/lvZBBkoVFoiFwGoFZ7jmtd3l@ZgtQZWDyQTOKCWx1dJg2OiNYJ/ZgI0wSbr@Cw "Perl 6 – Try It Online")
```
{[\~]('',0...*).first($_):k}
```
[Test it](https://tio.run/##LY7LDoIwFET3/YqRNFJMbQokkFiRn3DngwUWgy8IRRND8NexiLubO3NOptbNLRqeRuMViVyR@xvzvDppJEO3238OzHW5FEIsPFGUjWkZzbzVtf8RW21aRYqqgYStwA84fCk5wiCLoxgdAayPmrZBAna0qLhU5UP9/@fStDagNMMaoZRIUzhjW9R2FfOw3IBmDmYzONOpiEVLg3Ehm8QetwGfZIr0wxc "Perl 6 – Try It Online")
```
{first :k,$_,[\~] '',0...*}
```
[Test it](https://tio.run/##LY7dCoIwAIXv9xQnGamxxlRQaJkv0V0/uzCN9ac4C0Ls1W1md4fz83HqornFw9MUeMU8l@T@xjyvTgXSoSt1Y1qsrowqttt/DnBdJjjni/432BamlaSsGghYF0HIEAjBEIUqiRN0BLA4atoGKbwjVT6/VPoh//5ZW3oKShXWiIRAlsEZ27y2pzwfyw2ocjCbwZmkJHaqDcaD3gT2mQ3YBJOkH74 "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
first # find the first one
:k, # return the index into the Seq instead of what matched
$_ # that matches the input
# from the following
[\~] # triangle reduce using &infix:«~» (string concatenation)
# a Seq
'', # that starts with an empty Str
0 # then a 0
... # generate values
* # indefinitely
}
```
---
`'',0...*` produces an infinite sequence of values `''`,`0`,`1`,`2`,`3` …
`[\~] '',0...*` produces an infinite sequence of all of the possible inputs
```
""
"0"
"01"
"012"
"0123"
...
```
Note that this code will never stop if you give it an invalid input.
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~11~~ 10 bytes
1-indexed.
```
fqQ|jkSTk0
```
**[Try it here](https://pyth.herokuapp.com/?code=fqQ%7CjkSTk0&input=%22123456789101112%22&debug=0)**
If the empty string could be ignored, this can be shortened to **[6 bytes](https://pyth.herokuapp.com/?code=fqQsjk&input=%22123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100%22&debug=0)**:
```
fqQjkS
```
*-1 byte thanks to [@Mnemonic](https://codegolf.stackexchange.com/users/48543/mnemonic)*
[Answer]
# CJam, ~~14~~ ~~12~~ 11 bytes
```
q,_){,s,}%#
```
[Try it Online](http://cjam.aditsu.net/#code=q%2C_)%7B%2Cs%2C%7D%25%23&input=0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100)
```
q, e# Get length of input string
_) e# Duplicate length, increment by 1
{ e# Generate array by mapping [0,1,2,...,length] using the following function:
, e# Generate range [0,x] (x is the int we're mapping)
s e# Convert range to string (e.g [0,1,2,3] => "0123"
, e# Get the length of that string
}% e# Map the int to the length of it's range string
# e# Return the index of the length of the input string in the generated array
```
[Answer]
# [Dyvil](https://github.com/dyvil/dyvil), 42 38 bytes
```
s=>"".{var r=0;while($0!=s)$0++=r++;r}
```
Same algorithm as [this Java answer](https://codegolf.stackexchange.com/a/139869/42570), except it (ab)uses some of Dyvil's syntactic specialties.
Explanation:
```
s=> // starts a lambda expression with one parameter
"".{ // begins a brace access expression, the value before the '.'
// is available within the braces as a variable named '$0'
var r=0; // variable with inferred type int
while($0!=s) // while the accumulator $0 does not (structurally) equal s
$0++=r++ // concatenate $0 and the String representation of r,
// then store the result in $0 and increment r by 1
; // end of while
r} // return r as the result of the lambda
```
---
* **Saved `4` bytes by using a brace access expression instead of a variable for the accumulator**
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 47 bytes
```
do{$b=1..$a-join"";$a+=1}while($b-ne$args);$a-1
```
[Try it online!](https://tio.run/##DY5LasNAEAXvImYRE2T69b8JPoxMROwgrGAvvDA5@3i2xaNe/e3P9f64rNvW@/f@aucTjse2zL/79TZNX235POH/eblu60c7z7e1Lfefx2HwGb33CSxqHlkgAAyBwuAIJIqJwczCysbOwcklJBAWERUTl5CUUlIoq6iqqWtoahkZjE1MzcwtLK2cHM4urm7uHp5eQYHgkNCw8IjIqKREckpqWnpGZlZRjaAaZzVENUY1mml6Aw "PowerShell – Try It Online")
[Answer]
# [Arturo](https://arturo-lang.io), 31 bytes
```
$->s[0while[s<>join@1..<=]->1+]
```
[Try it!](http://arturo-lang.io/playground?NZGGxl)
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ƘRJ=
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNiU5OFJKJTNEJmZvb3Rlcj0maW5wdXQ9JTIyMTIzNDU2Nzg5MTAlMjImZmxhZ3M9)
## [Thunno 2](https://github.com/Thunno/Thunno2), 6 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
żƒ€JȮ⁺
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNSVCQyVDNiU5MiVFMiU4MiVBQ0olQzglQUUlRTIlODElQkEmZm9vdGVyPSZpbnB1dD0lMjIxMjM0NTY3ODkxMCUyMiZmbGFncz1l)
#### Explanation
```
ƘRJ= # Implicit input
Ƙ # First integer where:
RJ # Join the range
= # Equals the input?
# Implicit output
```
```
żƒ€JȮ⁺ # Implicit input
ż # Push [1..length]
ƒ # Prefixes of this list
€J # Join each into a string
Ȯ⁺ # 1-based index of input
# Implicit output
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
`@q:VXzGX=~}@q
```
1-indexed.
[Try it online!](https://tio.run/##DY47TkMBEMSOk3Y/MzuzSEjpuEGUEvqkiESFBFd/vN6y/fz6fhzH5/X1drv/fNzf/36vr@O4ZDU48mZkZmUnkjmpdG5FZVV1oVhTKtd2dHZ1N5o9rXYvAolCAyAGgrEMJotNkByK5k5MTk0PhjOj8axCqVILokaStQ6ny22YHsv2buw5tGdsT9Ge0J7PcfkH)
### Explanation
```
` % Do...while
@ % Push iteration index (1-based), k
q % Subtract 1: gives k-1
: % Range: [1 2 ... k-1]. Will be empty for k=1
V % Convert to string
Xz % Remove spaces
G % Push input
X= % Are the two strings equal?
~ % Negate. This is the loop condition. If true: next iteration
} % Finally (execute at the end of the loop)
@ % Push k
q % Subtract 1: gives k-1. This is the solution
% End (implicit). Display (implicit)
```
[Answer]
## [C#](http://csharppad.com/gist/e40eb4a6e8d2e25dd319e0a8544afb1d), 72 bytes
---
### Data
* **Input** `String` `i` The int array to be deciphered
* **Output** `Int32` The number used to make the array
---
### Golfed
```
(string i)=>{int c,p=c=0;for(;p<i.Length;c++)p+=(c+"").Length;return c;}
```
---
### Ungolfed
```
( string i ) => {
int
c,
p = c = 0;
for( ; p < i.Length; c++ )
p += ( c + "" ).Length;
return c;
}
```
---
### Ungolfed readable
```
// Takes the string with the int array
( string i ) => {
int
c, // Counter, it will count how many ints the array has.
p = c = 0; // Padding, it will help jumping from int to int on the string.
// Start counting. If 'i' is empty, the 'c' will be 0.
for( ; p < i.Length; c++ )
// Increase the number of digits with the length of 'c'.
p += ( c + "" ).Length;
// Return the counter.
return c;
}
```
---
### Full code
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestBench {
public static class Program {
private static Func<String, Int32> f = ( string i ) => {
int
c,
p = c = 0;
for( ; p < i.Length; c++ )
p += ( c + "" ).Length;
return c;
};
static void Main( string[] args ) {
List<String>
testCases = new List<String>() {
"0123",
"0",
"",
"0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100",
};
foreach(String testCase in testCases) {
Console.WriteLine($" Input: {testCase}\nOutput: {f(testCase)}\n");
}
Console.ReadLine();
}
}
}
```
---
] |
[Question]
[
## Overview
The cover of a book will be provided in the following ASCII format:
```
______
| |
| |
| |
| |
------
```
The input can be in any reasonable format (eg. a list of strings, a nested list of characters, etc.)
Inside the "borders" of the cover, other printable ascii characters might appear, which contribute to the "popularity index" (the definition of which has been completely made up for this challenge).
### Popularity Index
Let the *popularity index* of a book be the number of unique characters that appear on the book cover (this does not include space characters or the edges of the cover). A book may have no unique characters on the cover (the cover is blank), in which case the popularity index is **0**.
**Examples**
```
______
|\/ /|
|/\/ |
| /\/|
|/ /\|
------
```
Two unique characters (`/` and `\`) so the popularity index is **2**.
```
______
| / /|
|/ / |
| / /|
|/ / |
------
```
One unique character (`/`), so the popularity index is **1**
```
______
| |
| |
| |
| |
------
```
No unique characters, the popularity index is **0**
```
______
|\^$@|
|/\/ |
| 456|
|/ /\|
------
```
8 unique characters, so the popularity index is **8**.
```
______
|\^$@|
|987 |
| 456|
|/hi!|
------
```
14 unique characters, so the popularity index is **14**.
```
______
|////|
|////|
|////|
|////|
------
```
One unique character (`/`), so the popularity index is **1**.
### Damaged Books
The edges of the book might also be damaged:
```
Top Left Right Bottom
_~____ ______ ______ ______
| | | | | | | |
| | | | | | | |
| | or { | or | } or | |
| | | | | | | |
------ ------ ------ ---~--
```
The book may have several of these "scratches". The scratches at the top and bottom will always be represented by a `~`, while the scratches on the left and right will always be represented by a `{` and `}` respectively. Each scratch will decrease the popularity index by **1**.
As a result, it is possible for a book to have a **negative** popularity index.
## Task
Given an ASCII representation of a book cover in the format described above, determine the "popularity index" of the book
### Assumptions
* You can assume that the characters `|`, `_`, and `-` will not appear elsewhere on the book cover (only on the edges). However, the scratch characters (`{`, `}`, and `~`) **may** appear on the book cover in which case they should be treated as any other unique character on the cover.
* All characters appearing on the cover will be printable ascii
* Note that spaces do not count as a unique character. As the examples above show, a "blank" cover is one that only contains spaces.
* The book will always be the same size (height and width are fixed). Hence, the popularity index will never exceed **16**.
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Happy golfing!
**More Examples**
```
______
|{. }|
|/. /|
|/. /}
|/. /|
------
```
4 unique characters (`{`, `}`, `.` and `/`) and one scratch (`}` on the right) so the popularity index is **3**.
```
______
{ |
| .. |
| }
{ |
--~~--
```
One unique character (`.`) and 5 scratches so the popularity index is **-4**.
### Test Cases
```
______
| |
| |
| |
| |
------ -> 0
______
|\/ /|
|/\/ |
| /\/|
|/ /\|
------ -> 2
______
| / /|
|/ / |
| / /|
|/ / |
------ -> 1
______
|\^$@|
|/\/ |
| 456|
|/ /\|
------ -> 8
______
|!!!!|
|+ +|
| ** |
|<**>|
------ -> 5
______
|\^$@|
|987 |
| 456|
|/hi!|
------ -> 14
______
|THIS|
| is |
| a. |
|BOOK|
------ -> 11
______
|////|
|////|
|////|
|////|
------ -> 1
______
|abcd|
|efgh|
|ijkl|
|mnop|
------ -> 16
______
|{. }|
|/. /|
|/. /}
|/. /|
------ -> 3
______
{ |
| .. |
| }
{ |
--~~-- -> -4
~~~~~~
{ }
{ }
{ }
{ }
~~~~~~ -> -20
______
|~~~~|
|. |
{....}
|. |
------ -> 0
______
|{~~}|
| |
| |
| |
------ -> 3
__~~__
|{~~}|
| |
| |
{ |
-----~ -> -1
```
[Answer]
# JavaScript (ES6), ~~75 74~~ 73 bytes
Takes a single string of 36 characters as input, i.e. without any line feed.
```
s=>s.replace(o=/[^ |_-]/g,(c,n)=>t+=n*9%56%37%9&1?o[c]^(o[c]=1):-1,t=0)|t
```
[Try it online!](https://tio.run/##jZJdb9owFIbv8ytcqTR2wA5pgZapSatKnTb1ohfsrpQqCwmYZTaNs0lVPv46Ow4EIhqknQu/Oc55zmtbZ@X/9VWQ8HVKhZyHm8jdKNdTLAnXsR@EWLr2ywzlb/TVXvRw0BPE9dKuK6xxZzjqXF13xhfOnXwJXmdYr65DvlCnl7p9kqebJHz/w5MQm5EyCbT05195HE4@RID7hKVykiZcLDBhah3zFNuoSz1mTcWdDVsxB/t@D1GHsEgmj36wxAq5noFQIIWScchiucARVjvcnApwWUkusGkSQgyyeavCyBFE3i60Cv1NPb32jRqa2siGMhtUV4PqDPQzdLmH0A5CO6iRHUPOwWl2ft9wGgxHJ51u9tAZBJR1EepqyLI0e2tZ3mdoeOw0vrluOi35WcvxBnvqx7fvE13OVUX5TMvD8/NTC3W4lQ2Rt8vpp/B/BnMoC6PFEoSvfsUgv4Vct0CjPZUxVOjmbPvcIEWdHVNXNZTVY8BYPQ1FvUlpWTYhOjDKKrYFRbtsSxrU5WGY9B9wYVX7jEEUdXZ6ArOyLP5zbPW1yvIUlDWg5gGdfw "JavaScript (Node.js) – Try It Online")
### How?
We filter out spaces, pipes, underscores and hyphens:
```
/[^ |_-]/g
```
It means that we're going to match only:
* scratches on the border (-1 point)
* or non-space characters on the cover (+1 point the first time each of them appears)
Given the 0-indexed position \$n\$ of the character in the input string, the shortest solution I've found so far to figure out if we're located on the border or on the cover is the following convoluted modulo chain:
$$\big(((9\times n)\bmod 56)\bmod 37\big)\bmod 9$$
which gives:
$$\begin{pmatrix}
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&25&26&27&28&29\\
30&31&32&33&34&35
\end{pmatrix}
\rightarrow
\begin{pmatrix}
\color{blue}0&\color{blue}0&\color{blue}0&\color{blue}0&\color{blue}0&\color{blue}8\\
\color{blue}8&7&7&7&7&\color{blue}6\\
\color{blue}6&5&5&5&5&\color{blue}4\\
\color{blue}4&3&3&3&3&\color{blue}2\\
\color{blue}2&1&1&1&1&\color{blue}0\\
\color{blue}0&\color{blue}0&\color{blue}8&\color{blue}8&\color{blue}8&\color{blue}8
\end{pmatrix}$$
With even numbers on the border and odd numbers on the cover.
### Generalization of the formula
Given a square matrix of width \$w>3\$ whose cells are indexed from \$0\$ to \$w^2-1\$, the \$n\$-th cell is located on a border iff the result of the following expression is even:
$$\big(((p\times n)\bmod m\_0)\bmod m\_1\big)\bmod p$$
with:
$$p=2w-3$$
$$m\_0=2\cdot (w-1)^2+w$$
$$m\_1=2\cdot (w-2)^2+w-1$$
[Try it online!](https://tio.run/##TZBBboMwEEX3nGIWQbExQZB2UxF6iWy7CA0koiK25TiBCvnsdMZOSrzwzHy9P/r2T32vr0fTabuRqmnn@VuZpjXd6RcqGKD6hCkC6FsLGlDZQoLqBt5SVOlc8ofKSC44JAmOAoZ/oHgFtgtAeBkhdVTyqvo269WZHTTSq0m7NGxeTZec@iL0hfuSB@5dJ2UYxaKceQqSSonTDgYsQnAfPERXN6tvFon1uvTi0zwG1xhc4@KCp0dUwCSm1xBTopiixKB5ZtXemk6eGc903extbSx75@XDLYUIrfP36xPDYk@6yC3/zT74/Ac "JavaScript (Node.js) – Try It Online")
NB: This is an empirical result that I didn't attempt to prove.
[Answer]
# [Python 2](https://docs.python.org/2/), 73 bytes
Input is taken as a 2D list \$ b \$. Output is the popularity index of \$ b \$.
```
lambda b:len({j.pop(1)for j in b[1:5]*4}-{' '})-sum(map(`b`.count,'{}~'))
```
[Try it online!](https://tio.run/##fZJLT8JAFIX3/RWXxKQdcaYWAZFYY1xpXLDQnSi00NJiX2lLiCnTv17vlD4IoGfRk3vnm5M7nYl@UicMeoWtTwvP8M2lAebYswIlW7MojBSN2GEMa3ADMD@08eDzss9pJoPMCU02vuIbkTI352wRboL0Ss54LhNSbB3Xs0AbS7gvAh08N0mV8hMb2xn2NqlCCIhoV0THRrCylCEhEoSbVOyoGAmMJLHiFGwFOwR0vQSKWSlpB6jdeaOlpGupZqcqqLiqogsIXVToDdtrWKhYqNiDqmK1Nvfr4vEgtz8YHueOGraDwtUuQFewlIot95Q@NOzgOPdudHuY67iddoZ@A78/v7wJyk1K2GDCniaT1xZuJ1ZRu/N2cjrDXCxx1bJXDpq7/vbQ/CCMWnbYwBkDLqLY/n@h8bqq4JuazerLYqy@M143Kc1zZGlfykvt@/y8VQjttTctGpjJyrCMoXhdnbyKLM/5/y9IjJznf7HZAYtTaL8 "Python 2 – Try It Online")
---
The left part of the expression does two things: adds up the popularity index inside the cover, and removes its characters. The right part subtracts the damaged characters from the remaining characters.
[Answer]
# [J](http://jsoftware.com/), 51 41 40 bytes
```
_1#.1#.(+./~#:33)e.&'{}~'`(' '~:~.)/.&,]
```
[Try it online!](https://tio.run/##hY@xCsIwEIb3PMWPhabB5lJbp0gnwcnJvVSQFnFx6dYkrx7T2CKCxY@E48Ldx5@H3xDvUWtw5Cigw5WE4@V88u0uoXCyLSmX6KoSHaV8tI5fMw7utCOhKM0bL9hQE7LmQG0pJknB2ggzI8EaZhRBzcUunYwwwbrb/YkKNXoMbFU1IhAcIIolYJdHKZ37qNr9qstF3mv2d5lHFldZ/AtmpvmQiGKUkQJ26b7/OKv8Cw "J – Try It Online")
*-11 bytes thanks to Bubbler!*
*Both the function table trick to compress `#:@68208171135` down to `+./~@#:@33`, and the "negative one base trick" are due to them.*
## how
1. `+./~@#:@33` Let's begin with this phrase, which produces:
```
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 0 0 0 0 1
1 1 1 1 1 1
```
How? 33 in binary `#:@33` is `1 0 0 0 0 1`. Then create an "or" function table `+./` of this list with itself. It is easy to verify this will be 1 exactly on the border cells.
2. `/.&,]` Flatten the input and use the mask above to split the input into two groups, using J's Key `/.` adverb:
```
Apply this verb to the Damage:
1st group, the edges: --------> Is each character an
| element of '{}~'?
___/____ Returns a 0-1 list.
e.&'{}~'`(' '~:~.)
^^^^^^^^^
| Reputation:
And this one to the second --> Is space not equal
(the interior) to each character
of the uniq? Also
a 0-1 list.
```
We now have two 0-1 lists. For example:
```
Reputation: 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
Damage: 1 1 0 1 1
```
J will extend the shorter list to the length of the longer, filling it with zeros:
```
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
1 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
```
3. `1#.` Sum rowwise:
```
1 4
```
4. `_1#.` This uses a -1 base as a golfy way to subtract 1 from 4. By definition of base:
```
(1 * -1^1) + (4 * -1^0)
(1 * -1) + (4 * 1)
3
```
[Answer]
# [Python 2](https://docs.python.org/2/), 68 bytes
```
lambda s:len(set((s[8:-6]*4)[::7])-{' '})-20+sum(map(s.count,'_|-'))
```
[Try it online!](https://tio.run/##fZJPT8JAEMXv/RQDMWFb6PJHBGzEGE8aDxz0BkoWKFAs26ZbQkxpvzrOlt2WKDqXl3nz25dpd8OveB3wznE5nBx9tp0tGAjHdzkRbkyIGA8cu/dudc2x4/TfTTupQS017U6rLnZbsmUhEXQe7HjcqE0Pds00j/u157vQdgzweAhDqE54lW4Cj5OI7afo7WJiwjKIwEMCIsZXLumZpgExi1ZujEcUZEDkip0vnSVBDw0mhBvF2ofhUB1qgAQaatBQLh4II49r/jjNyzgA1uGy2HkZLUOzkyY0cdpElRCq7FALtlOwoFhQ7Fmn2HaZ@3H1cJbbven9zB0UbAULp3WAumQtSx65s6z7gr35mXs76J/nrr1KuUO3gN@enl8l5YkcZlTK42j0UsLlxk2sw2X59XVsNl/g1F2u1ije5tNH2fIgLNleAScUUhlFT/8LJdWdgq81m@jLolTfWapN284yZO2ukeV18tPLohB8yMUa0sBMmoclFCvV3a9XkWRZ@v8Lkitn2V9scsbiFu1v "Python 2 – Try It Online")
Instead of counting defects on the borders, counts non-defects `_|-` throughout and subtract from 20, using the rule that only the borders can contain these characters. The `(s[8:-6]*4)[::7]` is a nice string-slicing way to extract the characters on the cover without borders.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
4Fćˆøí}˜ðKÙg¯˜…~{}S¢O-
```
-3 bytes by taking inspiration of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/205323/52210), so make sure to upvote him!
Input as a matrix of characters.
[Try it online](https://tio.run/##yy9OTMpM/f/fxO1I@@m2wzsOr609PefwBu/DM9MPrT8951HDsrrq2uBDi/x1//@PjlaKV9JRwEHE6ihEK9WA2NUgQg9EKICIWhBRgySvjyqvT4x8LXH6dUFs7ERsLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU@l1aLeOkn9pCYRvX/nfxO1I@@m2wzsOr609PefwBu/DM9MPrT8951HDsrrq2uBDi/x1/@sc2vI/OjpaKV5JBwuO1YlWqgGyFNBwDQ1kdIEsTBwLlCLkupgYIKEPNUwfxSp9dGlUV6BIo@pCkabUhQp4HaiA133E6qEw/OKAWAWIHUgJPxMgNgViM9oGnyIaRliljZSMtDGcpwXFqA63QZKxo23wWQKxBRCbkxh6GUCcieJZ8p0XAsQeQOwJxMEYbgDZUozVdYlArIch4wTE/lDsTQXX6aPhGhrIkO86UBgkAXEyEKeg2JQKxGlAnA6NLYQMKESzgDgbiHNQZHKBOA@I84G4gAquq0aKoVqMcNDDWXYgy9QS0EOe66oJlv96WFMXup5aAqbBXFQHxciuq0MSR2Bc5tXSQAaHC4iIWXRdiBDSwxoO1UghCsO1BPRQlu5gLqsdwNYAzA20cl01Sa4DxWwsAA).
**Original 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach:**
```
|¦¨ε¦¨}ðýê¦gIJ…_|-S¢O20-+
```
Default input as loose lines in STDIN.
[Try it online](https://tio.run/##yy9OTMpM/f@/5tCyQyvObQWRtYc3HN57eNWhZemeXo8alsXX6AYfWuRvZKCr/f9/PBhw1VTrKdTWcNXo6ynoQ6laGE8XDAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU3lot46Sf2kJhGtf@f/QskMrzm0FkbWHNxzee3jVoWXplV6PGpbF1@gGH1rkb2Sgq/1f5390tFI8GCjpKNUoAEENfoYuGCjF6iDri4nRV9AHK9MHMSEaQEyIGIiJU68CXKsCXCeaCA4741Qc0O00MTUjwkpFIAAr01ZQ0IZo1NKCmGCjpWVHhJWWFuboNmZkKuLUGOLhGQxRnlkM1ZeoB2E4@ft749SnDwQ1@BlY9SUmJaeAVaWmpWeAGZlZ2TlgRm5efgFOfdV6CrUQ0/VgUQBk1CKLYNNXjUglenqI5FKLLKWrW1cH1VcHBjDJWvwMqGJUd4KEwNboQU2v1gOCWmQR7P6rq6slJX3X1RHSV42iD@jOWAA).
**Explanation:**
```
4F # Loop 4 times:
ć # Extract head; pop and push remainder-matrix and first line separately
ˆ # Pop and add this first line to the global array
ø # Zip/transpose the remaining matrix; swapping rows/columns
í # Reverse each line
# (`øí` basically rotates the matrix once clockwise)
}˜ # After the loop: flatten the remaining matrix
ðK # Remove all spaces
Ù # Uniquify it
g # And pop and push the amount of remaining unique (non-space) characters
¯˜ # Push the global array, and flatten it as well
…~{} # Push string "~{}"
S # Convert it to a list of characters: ["~","{","}"]
¢ # Count each in the flattened global array
O # Sum those
- # Subtract the two from one another
# (after which the result is output implicitly)
| # Push all lines of inputs as a list of strings
¦¨ # Remove the first and last lines
ε } # Map over each line:
¦¨ # And also remove the first and last character of each line
ðý # Join everything together with space delimiter
ê # Uniquify and sort the characters
¦ # Remove the first character (the space)
g # And pop and push its length
I # Push the input-list of lines again
J # Join them all together
…_|- # Push string "_|-"
S # Convert it to a list of characters: ["_","|","-"]
¢ # Count each in the joined input
O # Take the sum of those counts
20- # Subtract 20 from this
+ # Add the two together
# (after which the result is output implicitly)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ḣ;ɼȧZṚµ4¡FQḟ⁶,®f“~{}”¤Ẉ_/
```
A full program accepting a single argument as a list of Python strings which prints the result.
**[Try it online!](https://tio.run/##y0rNyan8///hjkXWJ/ecWB71cOesQ1tNDi10C3y4Y/6jxm06h9alPWqYU1dd@6hh7qElD3d1xOv///8/Wj0@vq4uPl6dS0e9prqurrYGzFIAAjRWNZylCwJ16rEA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hjkXWJ/ecWB71cOesQ1tNDi10C3y4Y/6jxm06h9alPWqYU1dd@6hh7qElD3d1xOv/Nzi08sT6w@1cD3dvKTZ/uHPao6Y1D3csBpJAZHa4HUj@/x8PBlw1CkBQg53SBQMQW9cORBpwccF0xegr6APV6QNpkHIgDeIBaUxdRghdClBdClBdSDx0XYZIdsWpOCDZZWJqhtMuC4QuRSAAqtNWUNAG6dLSAmm20dKyw9RlimGXpYU5sl0ZmYpYXGiC0Bbi4RkMUp9ZDNaWqAeinPz9vbFoQ/KZPhDUYKfwhEdiUnIKUF1qWnoGkMrMys4BUrl5@QVYdJkhtFXrKdSCjNeDhDqQqoXx0LUZw3VVwxKEnh4sXdTCBHV16@qQdekCA6QODCAqarFTECVI2oyQ0hVICmiPHtiCaj0gqIXx8KTG6rq6WiLTMNhrdXW4dFUj6UJ2oyEXAA "Jelly – Try It Online").
### How?
```
Ḣ;ɼȧZṚµ4¡FQḟ⁶,®f“~{}”¤Ẉ_/ - Main Link: list of lists of characters (the lines)
µ4¡ - repeat this monadic chain four times:
Ḣ - head (gives us the head AND modifies the chain's input)
ɼ - recall from the register (initially 0) and apply & store:
; - concatenate
Z - transpose the chain's (now modified) input
ȧ - logical AND (the concatenate result with the transpose, to get us the transpose of the chain's input)
Ṛ - reverse (together with the transpose this is rotate one quarter)
F - flatten (what we have left is the cover's inner characters)
Q - de-duplicate
ḟ⁶ - discard spaces
¤ - nilad followed by link(s) as a nilad:
® - recall from the register (the cover's edge characters)
f“~{}” - keep only "~{}" characters
, - pair (the two lists of characters)
Ẉ - length of each
/ - reduce by:
_ - subtraction
- implicit print (a list containing only one entry prints just that entry)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 66 bytes
```
lambda s:len(set((s[8:-6]*4)[::7]+' '))-21+sum(map(s.count,'_|-'))
```
[Try it online!](https://tio.run/##fZJBT8JAEIXv/RUjMWFb6CIIBRsxxpPGgwe9AZJVClTLtumWGFPav46zdbdtAJ3Ly7z59mXa3eg7WYe8t1@Op/uAbd4WDIQbeJwILyFETEau7cysvjlx3eGs1YSmadq9bktsN2TDIiLoe7jlSbs539k42n@t/cCDrmuAzyMYQ2PKG/Qj9DmJ2dccvW1CTFiGMfhIQMz4yiOOaRqQsHjlJXhEQQbEntgG0lkS9NBgQnhxon0Yj9WhNkigrQZt5eKBKPa55vfzoowdYO1Oi12UcWFodtqBDk47qBJClR1qyfZKFhQLiq11iu1Wua/nt7Xc/sA5zB2V7BkWTlsALclaljxybVk3JTs4zL0aDeu5a/@s2qFfwi/3D8@S8kUBMyrl7unpsYKrjTtYu9Ny9HXs7X2BU2@5WqP4H58ByoaHUcU6JZxSyGQU/f1fKJnuFHyp2VRfFqX6zjJt2naeI2v3jbyoXz87LQqxe9VNSwMzaRGWUqxMd0evIs3z7P8XJFfO87/YtMbiFt0f "Python 2 – Try It Online")
---
A slight improvement over [@xnor's answer](https://codegolf.stackexchange.com/a/205369/88546). Instead of removing spaces from the cover, we *add* spaces to the cover, and then subtract 1.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~106~~ ~~102~~ 80 bytes
```
lambda b:len({*(b[8:12]+b[15:19]+b[22:26]+b[29:33])})-21+sum(map(b.count,"-|_"))
```
[Try it online!](https://tio.run/##dYxLDoIwFEXnrqISB/2IhCJEGjXug6KhKtEEClEYGMBlsQA2VktNjAM9k3tfcs8rH9WlkJ5KN1xlSS5OCRAsO0vYYCiiFXNpTETk@swNx0Ipo4EpIfO8GHXIpi651znMkxKKxbGoZTW37PZgIaTK21VWMIXW0zD0DdB0//O90@rkox4MQ9/y/WzX6nS4A8YESz8wN3C4TtvwW51qxikBgBgVY/NijfH2W1Uv "Python 3 – Try It Online")
I know there's a shorter Python answer, and I know that this isn't the most optimal method. But I had come up with a solution which I golfed, and I'm posting it for the sake of completion. *-2 thanks to @Kevin and -2 thanks to OVS*. *A further -22 thanks to @mathjunkie*.
[Answer]
# perl -M5.010 -n -0543, 82 bytes
```
$i--for/\}$|^\{|~(?=[-_~]*$)/gm;s/^[-_~]+$|^.|.$//gm;$c{$_}++for/\S/g;say$i+keys%c
```
[Try it online!](https://tio.run/##K0gtyjH9/18lU1c3Lb9IP6ZWpSYuprqmTsPeNlo3vi5WS0VTPz3Xulg/DszVBkrr1eip6IMEVZKrVeJrtbXBGoP1062LEytVMrWzUyuLVZP//48HA65qBSCo4apR0NMDU0BQCxPU1a2r09X9l19QkpmfV/xf19dUz8DQ4L9u3n9dA1MTYwA "Perl 5 – Try It Online")
First, the penalty is calculated by counting `{`s which start a line, `}`s which end a line, and any `~` in the top and bottom lines. We then strip off the boundaries, and count the number of unique non-space characters; the penalty is added to that, to get the final score.
Reads a single cover from `STDIN`, writes the score to `STDOUT`.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~42~~ 35 bytes
-6 thanks to Bubbler.
Anonymous tacit prefix function. Requires `⎕IO←0` (0-based indexing).
```
-⍨/(,∘.⍱⍨6⍴5↑1){≢∪⍣⍺⊢⍵~⊃⍺↓⊂'_|-'}⌸∊
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/3Uf9a7Q19B51DFD71HvRiDH7FHvFtNHbRMNNasfdS561LHqUe/iR727HnUtetS7te5RVzOI0zb5UVeTenyNrnrto54djzq6/qcBTXvU2weWXwM04tB6Y6AhQHuCg5yBZIiHZ/D/NAX1eDBQV1CvUQCCGvwMXTBQ50LRF6OvoA9WpQ9kQZQDWRARIAunPgW4PgW4PjQR7PbFqTig2WdiakbYPkUgAKvSVlDQhujT0oIYYKOlZUfYPksLc3T7MjIVceoDhTBEeWYxVF@iHoTh5O/vjVOfPhDU4Gdg1ZeYlJwCVpWalp4BZmRmZeeAGbl5@QU49VXrKdRCTNeDBT@QUYssgk1fNSJ16OkhkkktspSubl0dVF8dGMAka/EzoIpR3QkSAlujBzW9Wg8IapFFsPuvrq6WlHRdV0dIXzWKvjp1AA "APL (Dyalog Unicode) – Try It Online")
`∊` **ϵ**nlist (flatten)
`(`…`){`…`}⌸` apply the below function to each of the two groups identified by 1s and 0s in:
`5↑1` take five elements from 1; `[1,0,0,0,0]`
`6⍴` cyclically **r**eshape that to length six; `[1,0,0,0,0,1]`
`∘.⍱⍨` NOR-table of that;
`[[0,0,0,0,0,0],`
`[0,1,1,1,1,0],`
`[0,1,1,1,1,0],`
`[0,1,1,1,1,0],`
`[0,1,1,1,1,0],`
`[0,0,0,0,0,0]]`
`,` ravel (flatten)
The following function will be applied to each multiset (0: edge characters; 1: inner characters):
`'_|-'` a string; `"_|-"`
`⊂` enclose it; `["_|-"]`
`⍺↓` drop 1 element if the set is that of inner characters, otherwise drop 0 elements
`⊃` get the first element; the above string or `" "` if gone
`⍵~` remove those characters from the edge/inner set
`∪⍣⍺⊢` if inner, then get the unique of that, else leave as-is
`≢` tally that
`-⍨/` subtract the first count from the last count
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~49~~ 41 bytes
```
≔⪫E⁶S¶θPθB⁶ WΦKA¬№υκ⊞υ⊟ι⎚I⊖⁻Lυ⁻²⁰ΣE-_|№θι
```
[Try it online!](https://tio.run/##PY5Ba8MwDIXv@RXCJxkcGDvs0lOXUdhYRqDXgTGZSUxdO43tbdDMf91TmrF3eXoSn6R@VHPvlS1lH4IZHL5447BVEz4IeHZTisc4Gzcg5wLYu2NkF76r2mSjmWgScY2P/nsFGDAKX6OxGvBgbNQzdlqf9tYigW8@YuMTMUnAiZOgS2FcU@cnNJzgxmo1IxXdbXmjQsQn3c/6rF3UH9galwK@ajdEAmnp1ri/E3BM59vnrJYLE7Bduggw/E@7UqTMWcpqueb8s1QLkP7tulm9KkOpP@0v "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪫E⁶S¶θ
```
Input the cover.
```
PθB⁶
```
Print the cover, but immediately erase the border.
```
WΦKA¬№υκ⊞υ⊟ι
```
Collect all the unique characters, which always includes a space, as we used that to erase the border. (I feel that I should be able to use `W⁻KAυ⊞υ⊟ι` but Charcoal crashes when I try.)
```
⎚I⊖⁻Lυ⁻²⁰ΣE-_|№θι
```
Clear the canvas and output the popularity, adjusting for the extra space collected and the number of missing border characters in the original string.
I also tried counting the popularity by directly inspecting the string instead of printing it and deleting the border but it turns out that that costs bytes overall.
Previous 49-byte solution does not assume that edge characters only appear on the edge:
```
≔⪫E⁶S¶θPθB⁶ WΦKA¬№υκ⊞υ⊟ιPθ↘UO⁴ ≔ΦKA№{~}ιθ⎚I⊖⁻LυLθ
```
[Try it online!](https://tio.run/##ZU7LTsMwELznKyyf1lJ6QxzoqaSqBCIQwRUpMmGVWDV26keLlNS/HjY0cOlcZmdXszNNJ11jpZ6mjfeqNfBolYFS9nCbswfTx/AWnDItCJEz/m440UGsszLqoHq6BJjlvf2eDZxxEqdOaWSwUzqggwpxv9EayPhsAxQ2kifmbC8IrIq@m1Vle1Di@nFpjwh3W3syr6rtAm1ePrSlPjd/aUvv67RLEh/SmedMiaV4oVE6oKH6zSikD7DFxuEXmoCfUCoTPTyhaQMVI9MyHua6Yj1NdZ1SXWfjkNJ5zEZG@KfhQqsZiU2ro/4B "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪫E⁶S¶θ
```
Input the cover.
```
PθB⁶
```
Print the cover, but immediately erase the border.
```
WΦKA¬№υκ⊞υ⊟ι
```
Collect all the unique characters, which always includes a space, as we used that to erase the border. (I feel that I should be able to use `W⁻KAυ⊞υ⊟ι` but Charcoal crashes when I try.)
```
Pθ↘UO⁴
```
Print the cover again, but this time keep only the border.
```
≔ΦKA№{~}ιθ
```
Collect all the `{`, `~` and `}` characters.
```
⎚I⊖⁻LυLθ
```
Clear the canvas and output the calculated popularity, adjusting for the extra space collected.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 326 320 319 305 bytes
```
int f(List<Character>[]c){int s=0,i=3;c[0].addAll(c[5]);for(;i>1;)S(50*i---55,c[0]);c[5].clear();for(;i<5;c[5].addAll(c[i++]))s+=c[i].remove(0)-c[i].remove(4);S(32,c[5]);for(;c[5].size()>0;i++)S(c[5].get(0),c[5]);return i-5-c[0].size()+s;}void S(int x,List c){c.removeAll(Collections.singleton((char)x));}
```
[Try it online!](https://tio.run/##xVdtb9pIEP4Mv2K@1S6Yd7fXI4lUpYr64e6@oPaqQ@i02AtsYrycd0lCCf3ruZldmxhwecmlPUUjYs/uzOzM88ysr9kt8@SMx9fhzaOYzmSi4Rrf1eZaRLVLGUU80ELGqlve0fa4Lnj7GTfIpEDxm1C4vjybDyMRQBAxpeB3JmJYlsul9K3STOPPrRQhTFHn9HQi4nF/ACwZK9csLQUTlvQH9AeBvOWJgnNYQqlUqtdhKOUNKDadRVwB2m59wJ0JWyjcV1ouX/39qlogq6pRv3rApy@pQCoPG9rs7ZdC7ae9ez@lb@/TVU9aD592ZYXqNOxvB8OGLXnYq12ttcv0zcej9z5pv6Whfvte2IezPUNZoIxQxjuuA5QEJUJhO1qJwlHmKGJHG6JMUDRKfHq2d2U7Y/vz@fLa70S1Qu2qS6EbMg0DZEPM7wy1HNco6nVLyrNLZA4LNE8uDHsucalTqHKNCavqdwb9N4Mu2iEGF9ooUFgLpMj2m0D0PIlBT/iamCBHQIQmtmppVGw2S@QsEUxz0IsZx40jmYCDC@AG3TW6@HMGHfypVFxKzlotrFqg@g3@oBpbBi4oXfZvBn0xSHOzc2ZKVClv6NoauraGrlM/azs1FoYOWVqbcGwrsur@9cC1FlflLPqdHMF7@BUujd3eQmk@rcm5ruG5Yx3FzjCojZz3aAWwq41AKAgdF42tHim80a65wF2SRp03quK83Q36DRPl@yhygr4/cLsYhdMVF82u23P8xmvheZ7vV2md26UVtSDiLHGyhWe@fbu2gdnEU6nKeUAJSPgUD@w0XC//2HG7PafdquY8GiNKfOWOe9HoUkl6JqDamGvcni5NuEGG8HzPRG43VFR3ZWZBzxTlvkqnBjxpkDqkyHJDCrfF44hrGTsOgcq9xwSuHsvlet1mrQDsJ@Tt6kfm7epg3q5Oz9tVmredc5@aQ0Rhu/kOhguNc1XJaE5rKa8fecKrRNsEiYvyFkIxGuET@r3DuQsCC8awL3EIZczhTuhJbglmSaArFsGU64kMFUK8Xo@lVYgNTYnOEhfVECGBN4B6vdNqwJApbuMk6pnSEperpjc0iU4Jn3HsLWG0gITPFV0U6KpArSfm9xqGkQxuUt46tpn4tpkQVxVUzmGzlODBVjHRS8RH6FqEHLWJGE/SB7zPWOMISWJ1LO/QetYkyNuFbWHeuW/85SwfqpTzzvfE62bDtW0DgYKeQ@qwWs6AxSFej7TWcrrl3/PNM/p@W8FjmgfPh5b9pwNt@08bOvafFtCGu4mIOHZLTI/XSkNt5nBvbA1MJIGcDgUWn0URRYOQMM2e8JCgf6eJI0AqjihZ4JUuvuWx4HHA3SpCLSv/Bookas1VkDweSg7OUZuQUKiEj1kSgpqxgKutLLTWVTBmN7i3Pt4hZ2aRpah1esP5DMwuXAMMFFYFc2BBSK@CDMiqRqiHJlAQnAUTmyDjMKTTZmSHCrQM5tYdwjyt6Y96Ra7nsfhnznMOwFETMULoU6JbmM2AIf6pHndMURXRDpvKeWxCVEHCdDBBfhgsS0sRgpKHhtiUm0AJUnJKPh3PNRBf70NY4/wzhMZRmXWNlMh/7CPyZwwWl2KMBF66EwwxCbt8bncNCLZb9rqQ4gzbtq1d42gWrZu8a4f4RpPP2sL3@rxpEYd6fWb0OOTmYOkXwtI/BpZ@DpZ5LHngF6DHVM5ke3pcnUxfbw3ByZf6GQW7SAu2e0f5UZXIXVgOZLro4nJcKpECPA6JC/jRnMtkz0AO7t3lk53iAt7bIdxkdD@dzbVhhcGrIZhJv@2U0GS2cn/tHZVvG0Xj8T9NveOnWK9gYtXr7/wqdE4ZLadNgJdv76f2ZMuqbQiYK9phBGS3MYuDYYYDnCgTmaAlmqmICpySBlMFuBhaXHzdi4u2/7/iYg2Il8EDkdvOYfqahvaJM773IgVPP2Es1atQdBmnyA@CL7uJt5ip7Z@52rZSzn/YW9vGLz@ztjskr9Jes@WEgvaIvVVSH2TwRrWetjy/Yvbj6fkF2/yAag13y5ZSMtxfts7PLVtar2eWy0zTn1it1eO/ "Java (OpenJDK 8) – Try It Online")
THANKS to Muskovets's suggestion of using List (-4), I also omitted the generic type in the second method (List instead of List< Character>)
Takes input as List< Character>[] and outputs an int.
It uses 2 methods (I'm not entirely sure how "allowed" that is)
See inside for comments and ungolfed and alternate solutions (including a single method one).
Interesting part: the ascii values for { | } are 123, 124, 125. That means that this part changes the popularity index by:
for each row: the left char minus the right char
{...} 123 - 125 = -2
{...| 123 - 124 = -1
|...} 124 - 125 = -1
|...| 124 - 124 = 0
It only works with only exactly the given possible inputs, none else (illegal inputs like }...{). Pretty lucky.
This was done with ArrayList, but possibly some other Collection with a shorter name or better methods would be better. Edit: indeed there is: Vector. updated. (Now List)
---
Takes input as String[]. Only one method.
# [Java (OpenJDK 8)](http://openjdk.java.net/), 267 261 bytes
```
int f(String[]c){int s=0,i=4;c[0]=c[0].replace("_","")+c[5].replace("-","");c[5]="";for(;i>0;c[5]+=c[i--].substring(1,5))s+=c[i].charAt(0)-c[i].charAt(5);for(;c[5].trim().length()>0;i++)c[5]=c[5].replace(c[5].trim().substring(0,1),"");return i-c[0].length()+s;}
```
[Try it online!](https://tio.run/##rVZRb9s4DH62fwWXl1pz7KRDPWDn5YZid8C93O2h2DAgMAbFURI1tmRYcntB6v71jpKdOJnTdDscClYQP5EiqY90bukdDWTBxO18/cTzQpYablEXVppn4UeZZSzVXAoVuz30hukT2i9oIMvYdYtqlvEU0owqBX9TLmDruk6rVZpqXO4kn0OOmHejSy6W0wRouVTEHnXSFS2nifmDVN6xUsEEtuA4zmgEMynXoGheZEwB@n7zB1qWdKPQztluL75dDE9IPbTwxQPuvrYCrTwcoTvt15Po57O2n1vtv@2pDg1w15ca4TbsxxfDhh/k4Sxa79Ftq/nrp2079LEN9fG5sF@udoGyQVmgLHtXpyglSoZCe6hEYSgVCu@hc5QVikYRv17tvvxYsfP1/P/RZ6KqEa1jE7ptplmK3SDYvW0tj1hg10TYMKpFW9VVMn2bxHjEtd2D3fIRm4um2nSVlrtjCcILWYLHhYY1uhjHuLyHK1x8n5j49jBvYI7wW1xa2FHTdTLlCYJed7/X9G8DkSbY3VX7zr@G30BZJzcbpVkeykqHBYI6E94sDRfetTV1nfrJBLDYm6ZkaxRqMh7yyVWcTsfJxPwLS1ZkNGXe4NtgOBgQP51GB8rAKmOjnAwGMUbjxfz3sVX46IAHQRKqaqaaHC6HESHKAkloZtO19sYkONxGpPFi70Gr3CNhxsRSrzyCjk2R7G1HcRwe7m4bDy@JDa9kuioF8MBmtPPmq7h@ckzW/3QVTHFwwmiUyjxnQrM51tLWxbzU0D7YZeyORjhZ0RX4EzBXx8aCCtB0zYDe0w3wBQipoVLo1R6xNvaxYv7@MiZ27xxV@OCtPVMM4r2L/Gj82qTc5OE2FicfZgf6k5MvZNHIcAqfCcO9l5iVYGzeDxWoAlVIvWNXQ9AobkCbMobUe1Z0ip@k0rCaaoiAijksJczlvTDtIQUzS8ly5DHoFYMgMl@d5m0@GM6q1vkBNSA4UlwRE3uXHNjkXOxHp0@KFjUWhhrAaLqCUlZi/gFafh0Ta3hAI9Jl/wwTbb@i71cW5@rPvNAbj5jh0MXSmBldeEezin1aNFzdJ2ib9ZcJbfhm@IcBUrFpWdN81q3lsQlesesArGdka3rQB@AD/jZxapwKhuqi1wyVWMps0fVCOyPOsfH0mBiNWhqaWbEv8EvzwlLjpZmx93ZmbvynUh8Urzc@bNHqp@8 "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) + `-p0 -MList::Util+uniq`, 55 bytes
```
s/^.{5}|.
.|.{5}$/$\-=$&=~y!~{}!!;""/ge;$\+=uniq/\S/g}{
```
[Try it online!](https://tio.run/##K0gtyjH9/79YP06v2rS2Ro9LrwbEUNFXidG1VVGzratUrKuuVVS0VlLST0@1VonRti3NyyzUjwnWT6@t/v8/Hgy4amLiVBxquGosLcwVgJSCiakZkNLPyFSs4dIFg3/5BSWZ@XnF/3ULDP7r@vpkFpdYWYWWZOZog8wDAA "Perl 5 – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~104~~ 93 bytes
Original code from yesterday:
```
while($s<35+$c=ord($b[$t=$s++]))$p-=$t>5&$s<31?$t%6?$s%6?0&$i[$c]=1:$c:-$c:$c%5;echo$p+count($i)-$i[32];
```
[Try it online!](https://tio.run/##lZRtb9owEMff91NcKxcBWRIeCusaAu0mtKFVIG2V9oIxFIIh2WhsJUZVFSdfnZ0TBgJaWE/K@aScf/fP@WLu8VWrwz0OpgmuE8CEAnv0haDTMxqGLByHlLNQ@MG82B3f3d9DAdLuuD946H3q5vGPu2/9Xv9zyQLF8CNYRktnsXgG7oQC2AyERwErGH7gn5GPg8HX4ci@GGcmAU0eej2zC8s09TZARYEFjQQqjOgB46cJppQmLrgbF4xx2WPUjjMgZ0DO2MS7jOoJHb/I7UbHVaP5oo7r44xzNCk1AA0Z5TKSWuVye4/R@B8dH67fb3V4/vkuo3p1nGGiyUP/pn44E3cqJZ3NPSn9338WUj4GjO/paB5nxAYkWNvITgR9kse7OupHGfF6rgxjPV1JvJ6xNN0w9Nf6kWYWb/ft@PxtztBrJ@ZUpUppqNqxgZbk8ZtmPU7T5OT/8no/0vQlRrxlpP/6ceJsH770vuNu/NvRO6qzKmHvbPcYMxZSx/WKGQucCMikFJPIrliEK@fbw5FFHAyzm2TBGMe7I2TLuZfdIRtS9A4CJnbuF5dN6erJ8xe0SKJWvakR12bhtEgmQyJsEmnaqFQiXLeJaDcKKqXaIeKy2SERukqB@EPijuzqDXFvdHyIe9mwqOsxwjWXLQNRJH5Jx6x6bWStEqWPBlNVff1VupK7@gs "PHP – Try It Online")
Improved with a `mod`-expression from @Arnauld, cf. [his solution.](https://codegolf.stackexchange.com/a/205331/95500)
```
for(;$s<36;$s++)$p-=$s*9%56%37%9&1?!$i[$b[$s]]=1:ord($b[$s])%29%8>0;echo$p+count($i)-$i[" "];
```
[Try it online!](https://tio.run/##lZTfj5pAEMff768YzXJBLOCP09Mi3l0b05peNGkv6YO1BmEVWo/dAD40LPzrdgCrUe@0Nw@zQ2A/82V2drjLN7077nLQdbAtH@YU2LMXRdS5okHAgllAOQsiz1/Kg9nD4yNcQzqYjcZPw4@DIv7@8HU0HH2qGJAxvBDW4dparf4At4II2AIilwJm0DzfuyIfxuMvk6lZnuUmAE2cejW3sqHrah@gloEjGkaoMKQnjB866ELouOBuXDDG5YjROM@AggEFYxcfMuoXdPwk9zsdN632izo65xklNCGqAFVkKAqSeorSP2K0/kdHt3O71@F6pUNG/eY8Q0cTp/5N9bDmtiMEXSxdIbxfv1dCPPuMH@lon2fEGiSYW8tPBH1SxIc6mmcZ8bavNG3bXUm87bE03THU1@qR5hbv9x344m3BUBsX@jT7VAgtyx1raEkRv6nX4zRNLt6X1@uRpi8x4j0j/VePC2f79Hn4DXfjbUdvZZXNPjg62yPGggXUsl05Z4EVAplXYhKaNYPwzHnmZGoQC8N8kqwY4zg7ArZeuvkM2ZHCd@Cz6GC@2MyhG0wgGyTsNdvoq9UK4apJQqUrtdpS81bqXtfvSsSbkPmEhNOpWX/PAkcunipSoyt1@jWD2i4jvGqztR/JxKuouKEM5amxSTJR1HeylNtfUTONm78 "PHP – Try It Online")
## Explanation
* I was using the fact that char codes of intact top and bottom edges are `%5=0`, and left and right edges have char codes that are in sequence.
* I've now researched the char codes of the six edge chars a little better.
Try `[45,95,124,123,125,126]%18%15`. There are also other options like `$c%29%8==0` and so on.
## Please Help Me Get Better
I appreciate any comments or suggestions.
[Answer]
## [Bash](https://www.gnu.org/software/bash/) + standard tools 121 Bytes
```
bc<<<$(sed '1d;$d;s/.//;s/.$//' $1|grep -o '[^ ]'|sort -u|wc -l)-$(sed -E '2,${$!s/(.)..../\1/}' $1|tr -cd '[~{}]'|wc -c)
```
Input is a file of the book.
[Try it online!](https://tio.run/##LY1BC4JAFITv/oonLKxCz8dGWaGHLv0KzchVMggM1@jgs7@@7VrfYeYwzEx9NZ21tc7zXESmbUCqJhNNZigh8iqIpA8V34b2CdiDLCo4Szb9MAK@@K0BHzH@2ngCuV6JSYSGoiROHFQqmv8T4wCo3UfxmWY34as6ttZeFgIuK3HkgA/7HTiDzTZ1Rt095AAXvg "Bash – Try It Online") (+6 bytes because input needs to be a string here)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 174 bytes
```
//N(c)=p-=*s++!=c
p,v,i,j,k;f(char*s){char u[16]={};for(v=p=0,i=6;i--;N(95));for(j=4;j--;N(124))for(N(124),i=4;i--;)strchr(u,k=*s++-32)||(u[v++]=k);for(i=6;i--;N(45));s=p+v;}
```
[Try it online!](https://tio.run/##fZTfb9owEMff81eYbqhxflKaslVu0DTtYdOk9mF7A1ZlDgEDTaI4ZA9x8qcvO9u0lBTtHs7H3ee@Pl8kqLuitOt8/96kOMzd0OK2PQipkTuVw5yNsyWJSddRYXFcyxPtZ1eTRVg3JMkKswrzcOSwcEKY65J78/YGY1XYhAHZqNTVOMBYpnQIcKBgzMuCrgtz72zVpe71GAth7meVbS/CrZY5KgdSmYe5XZGme8dSutvHS3THy5hl3npqGDRLeYnUiFZesLR8pFm1LMzXeY5RbSDEy6hkVOcUNAvGCwIFTcWhSsoEyCBGDIj0NCNicWLbbDiBUa3YtsPLeXqJMVKxfIbsslw3BlS2FctyX6ToINgYhlR8ilhqVhmL9TjqVj4LRmqtz5eRZLUsucmdYOTIV6aYaBzmn13DJxgR9UO9NTEvhnxeutN5OYzn6YWDXq@AYwcl4LHsaIyme1QmZLt4611lxgGa@8gXwocDynBADEcPQhpCGnqJe0q/3n96UQpuJmeVBmBC2AjZAFkWoHeWNT2rdPvxw1FpzQY96OfXbz@gzLiEIg/854eH7z3IBxNv/SkU/aaxEMtktRaCbbY7IZ7SLO9BtYca6PbU48E3Oj6B6sOWPe@w66Y@bLxtAWqV1cfCidfV5@tkLIQnu2sPrNFxb6a2bf73gdv2HFQfofYvTXbRinfun8790vuP@Ac "C (gcc) – Try It Online")
Pretty standard: I count the number of unique characters in the cover (which is built up in a string), then deduct the amount of damage.
[Answer]
# [Erlang (escript)](http://erlang.org/doc/man/escript.html), 184 bytes
Just a port of Lyxal's Python answer. (Where's the unique function in Erlang?)
```
u([H|T])->[H]++u([I||I<-T,I/=H]);u(X)->X.
f(X)->length(u(lists:flatten([lists:droplast(tl(I))||I<-lists:droplast(tl(string:split(X,"
",all)))])))-21+length([I||I<-X,([I]--"_|-")==[]]).
```
[Try it online!](https://tio.run/##ZY5Bi4MwEIXv@RWS0wwapXt015713oMgQcJudANpKslID01/uw3WPe2DYd7HgzejvVVuFjp8e7PQxrYVhjZeJIrz0Mo8T9jF2H2JS9FVTSvxc4U@hX3Jpt1Y7Wb6hRWsCRTqySoi7WB444@/LVYFArLQIe5N/5NA3ri5Dos1BH3BGS@UtYgo04iPU34cOV7pi@SkEHyMgmPTDFJiuV2VcTBiJs4sSzK3@u4NaZiA8XEXi48ye0YWqzKrjvX8I7GLY2p6AQ "Erlang (escript) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~101~~ 98 bytes
```
->s{a,*b,c=s.lines;(b.flat_map{x,*y,z,_=_1.chars;a+=x+z;y}|[' ']).size-22+(a+c).tr('{}~','').size}
```
### 100 byte version because TIO doesn't support ruby 2.7
```
->s{a,*b,c=s.lines;(b.flat_map{|i|x,*y,z,_=i.chars;a+=x+z;y}|[' ']).size-22+(a+c).tr('{}~','').size}
```
[Try it online!](https://tio.run/##fZJvb5swEMbf8yku3TQIf5wma7tuGd06ddKmSsuL9V2aIYeY4JUEFBMpCZivnp0JBLRkOwk93N3Pjw/s1Xq63Qfu3rkTGbXNqe27gkR8ycTQmJIgoqm3oEmW83xjm1t7Z3suJ35IV2JILXdj7YZbmY910CddIviOOYOBZVDL75J0ZeiZLHRb1w8tuX@4f7onjPqhp3YgaexR9FovX5Q/77ifnpeSCBYxPzXefAj4SqRdgttjElH1rtbCLAbENQBuQwwuGHx8SQhx@hNTbeWH8SKxgY@xoLbgigwU6cIc8WDMJ1gCSNapgIvR4wVmLBKsVWSbBGdgM3iVxdKGeZzi21yW5HKmqUfzvK8/HjwPVYWWq9X5eXHK0C61I/zcgx62e6iKQlUZ6hEeNDBUMFRwK6vgfsv51@vPLeer65u/nW8buIOBbQvAUrBpqjUfTfPuCF@fOL@/fdd2DnmnGeOqoZ@@ff@pMC5KmhIlX0ajx4ZuTd3DyM/L6SfSqT/DNgvmIQr//RKhLJZx0sA3DZ0RkMqMHH4biqyzin57hLP62AipT0/WRccpCoQd/MaijENDnpcKcQatQ1cVdCWlXYZXlsg6O70hWVHI/1@ncuyi@BectWAcpL//Aw "Ruby – Try It Online")
] |
[Question]
[
Your challenge is to write a program or function that, when given two strings of equal length, swaps every other character and outputs/returns the resulting strings in either order.
## Examples
```
"Hello," "world!" --> "Hollo!" "werld,"
"code" "golf" --> "codf" "gole"
"happy" "angry" --> "hnpry" "aagpy"
"qwerty" "dvorak" --> "qvertk" "dworay"
"1, 2, 3" "a, b, c" --> "1, b, 3" "a, 2, c"
"3.141592653589" "2.718281828459" --> "3.111291623489" "2.748582858559"
"DJMcMayhem" "trichoplax" --> "DrMcMoylex" "tJichapham"
"Doorknob" "Downgoat" --> "Doonkoot" "Dowrgnab"
"Halloween" "Challenge" --> "Hhlloeegn" "Caallwnee"
```
## Rules
* The strings will only contain ASCII chars (32-126).
* The strings will always be the same length, and will never be empty.
* You may accept input in any suitable format: separate parameters, items in an array, separated by one or more newlines, even concatenated. The only restriction is that one string must come fully before the other (e.g. `a1\nb2\nc3` for `"abc", "123"` is invalid).
* The output may be **in either order** (i.e. you can start swapping from the first or the second char), and in any valid format mentioned above. (2-item array, separated by newline(s), concatenated, etc.)
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **the shortest code in bytes for each language wins.**
[Answer]
## Haskell, 37 bytes
```
l=(,):flip(,):l
(unzip.).zipWith3($)l
```
Zips the two strings, alternately swapping the characters, then unzips them.
A 37-byte recursive alternative:
```
(a:b)?(c:d)=a:d?b
e?_=e
a%b=(a?b,b?a)
```
[Answer]
## Python, 42 bytes with [I/O golfing](http://meta.codegolf.stackexchange.com/q/9501/20260)
```
def f(a,b):a[1::2],b[1::2]=b[1::2],a[1::2]
```
Swaps every other character of the two lists. Takes as input two [lists of characters](http://meta.codegolf.stackexchange.com/a/2216/20260), and outputs [by modifying them](http://meta.codegolf.stackexchange.com/a/4942/20260).
```
l=list('cat')
m=list('dog')
print l,m
def f(a,b):a[1::2],b[1::2]=b[1::2],a[1::2]
f(l,m)
print l,m
```
gives
```
['c', 'a', 't'] ['d', 'o', 'g']
['c', 'o', 't'] ['d', 'a', 'g']
```
[Answer]
# Vim, ~~18~~, 17 bytes
```
qqyljvPkvPll@qq@q
```
[Try it online!](http://v.tryitonline.net/#code=cXF5bGp2UGt2UGxsQHFxQHE&input=REpNY01heWhlbQp0cmljaG9wbGF4)
This uses the V interpreter because of backwards compatibility. Input comes in this format:
```
string1
string2
```
Explanation:
```
qq " Start recording in register 'q'
yl " Yank one letter
j " Move down a row
vP " Swap the yanked letter and the letter under the cursor
k " Move back up a row
vP " Swap the yanked letter and the letter under the cursor
ll " Move two letters to the right. This will throw an error once we're done
@q " Call macro 'q' recursively
q " Stop recording.
@q " Start the recursive loop
```
[Answer]
## Haskell, 41 bytes
```
(a:b)#(c:d)=(a,c):d#b
_#_=[]
(unzip.).(#)
```
Returns a pair with the strings. Usage example: `( (unzip.).(#) ) "Hello," "world!"`-> `("Hollo!","werld,")`.
Simple recursive approach: take the first char of each string as a pair and append a recursive call with the (rest of the) strings swapped. `unzip` makes a pair of lists out of the list of pairs.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~11~~ 10 bytes
```
øvyNFÀ}})ø
```
[Try it online!](http://05ab1e.tryitonline.net/#code=w7h2eU5Gw4B9fSnDuA&input=WyJIYWxsb3dlZW4iLCJDaGFsbGVuZ2UiXQ)
**Explanation**
input = `["code", "golf"]` used as example.
```
ø # zip strings into list of pairs
# STACK: ['cg', 'oo', 'dl', 'ef']
vy # for each pair
NFÀ # rotate left index times
}} # end-if, end-loop
# STACK: 'cg, 'oo', 'dl', 'fe'
)ø # wrap in list and zip
# OUTPUT: ['codf', 'gole']
```
[Answer]
## Perl, 48 bytes
Bytecount includes 47 bytes of code and `-p` flag.
```
say<>=~s%.\K(.)%"s/.{$-[0]}\\K(.)/$1/;\$1"%geer
```
Run with `-p` and `-E` flag. Expect each string on a different line :
```
perl -pE 'say<>=~s%.\K(.)%"s/.{$-[0]}\\K(.)/$1/;\$1"%geer' <<< "Hello
World"
```
**Explanations** :
`-p` : capture input in `$_` and prints it at the end. (to get and print the first string)
`<>` : get a line of input. (to get the second string).
`=~` : apply a regex to `<>` : `s%%%geer`, where thanks to `r` the modified string is returned (and then printed thanks to `say`).
The regex :
`.\K(.)` finds two characters, and will replace the second one with the result of the evaluation of this code `"s/.{$-[0]}\\K(.)/$1/;\$1"` :
The first part, `s/.{$-[0]}\\K(.)/$1/` applies a regex to `$_` : `.{$-[0]}` skips the first characters to get to the same point as the outer regex (since `$-[0]` contains the index of the first capture group, so in that case the index of the characters to substitute), and then we capture a char with `(.)` and replace it with the character of the outer regex (`$1`). And then we add `$1` so the result of `"s/.{$-[0]}\\K(.)/$1/;\$1"` is the character we captured in the inner regex.
You may have noticed that `$1` refer to the character we want to replace in both strings (so two different characters), so we play with `/ee` modifier of the regex which evaluates the right side of the regex twice : the first one will substitute only the `$1` that isn't preceded by the `\`.
[Answer]
## Python, 55 bytes
```
lambda a,b:[(-~len(a)/2*s)[::len(a)+1]for s in a+b,b+a]
```
Slicing!
58 bytes:
```
def f(a,b):n=len(a);print[(s*n)[:n*n:n+1]for s in a+b,b+a]
```
---
**64 bytes:**
```
f=lambda a,b,s='',t='':a and f(b[1:],a[1:],s+a[0],t+b[0])or[s,t]
```
Recursively accumulates the characters of the two strings into `s` and `t`, and outputs the pair of them at the end. The alternation is done by switching the input strings each recursive call. Outputting a space-separated string was the same length:
```
lambda a,b,s='',t=' ':a and f(b[1:],a[1:],s+a[0],t+b[0])or s+t
```
This narrowly beat out a different recursive strategy of alternately taking characters from each string, with each of the two possible strings as the first one. (65 bytes)
```
g=lambda a,b:a and a[0]+g(b[1:],a[1:])
lambda a,b:(g(a,b),g(b,a))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
żṚż¥/
```
Input is as separate arguments, output is concatenated.
[Try it online!](http://jelly.tryitonline.net/#code=xbzhuZrFvMKlLw&input=&args=RG9vcmtub2I+RG93bmdvYXQ) or [verify all test cases](http://jelly.tryitonline.net/#code=xbzhuZrFvMKlLwrDpzIvWQ&input=&args=IkhlbGxvLCIsICJ3b3JsZCEiLCAiY29kZSIsICJnb2xmIiwgImhhcHB5IiwgImFuZ3J5IiwgInF3ZXJ0eSIsICJkdm9yYWsiLCAiMSwgMiwgMyIsICJhLCBiLCBjIiwgIjMuMTQxNTkyNjUzNTg5IiwgIjIuNzE4MjgxODI4NDU5IiwgIkRKTWNNYXloZW0iLCAidHJpY2hvcGxheCIsICJEb29ya25vYiIsICJEb3duZ29hdCIsICJIYWxsb3dlZW4iLCAiQ2hhbGxlbmdlIg).
### How it works
```
żṚż¥/ Main link. Left argument: s (string). Right argument: t (string)
ż Zipwith; yield the array of pairs of corresponding characters of s and t.
¥ Combine the two links to the left into a dyadic chain:
Ṛ Reverse the chain's left argument.
ż Zip the result with the chain's right argument.
/ Reduce the return value of the initial ż by the quicklink Ṛż¥.
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~11~~ ~~10~~ ~~9~~ 8 bytes
*Thanks to ETHproductions for 1 byte off!*
```
"@X@YS&h
```
Input is a 2D array containing the two strings, such as: `['Halloween'; 'Challenge']`. The output strings are in reverse order.
[Try it online!](http://matl.tryitonline.net/#code=IkBYQFlTJmg&input=WydIYWxsb3dlZW4nOyAnQ2hhbGxlbmdlJ10)
### Explanation
```
% Input 2D array implicitly
" % For each column
@ % Push current column
X@ % Push iteration index, starting at 1
YS % Circularly shift the column by that amount
&h % Concatenate horizontally with (concatenated) previous columns
% End implicitly
% Display implicitly
```
---
## Old version: 9 bytes
```
tZyP:1&YS
```
### Explanation
```
% Take input implicitly
t % Duplicate
% STACK: ['Halloween'; 'Challenge'], ['Halloween'; 'Challenge']
Zy % Size
% STACK: ['Halloween'; 'Challenge'], [2 9]
P % Flip array
% STACK: ['Halloween'; 'Challenge'], [9 2]
: % Range. Uses first element of the array as input
% STACK: ['Halloween'; 'Challenge'], [1 2 3 4 5 6 7 8 9]
1&YS % Circularly shift each column by those amounts respectively
% STACK: [Caallwnee';'Hhlloeegn']
% Display implicitly
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~9~~ ~~8~~ 6 bytes
Thanks to *Dennis* for saving 2 bytes!
```
Zṙ"J$Z
```
Uses the [**Jelly** encoding](https://github.com/DennisMitchell/jelly/wiki/Code-page).
[Try it online!](http://jelly.tryitonline.net/#code=WuG5mSJKJFo&input=&args=IkhlbGxvIiwgIldvcmxkIg)
[Answer]
# [V](http://github.com/DJMcMayhem/V), 12 bytes
```
lòyljvPkvPll
```
[Try it online!](http://v.tryitonline.net/#code=bMOyeWxqdlBrdlBsbA&input=REpNY01heWhlbQp0cmljaG9wbGF4)
Nothing too interesting, just a direct port of my vim answer so I can compete with (but not beat) 05AB1E.
[Answer]
## Pyke, 9 bytes
```
,Fo2%I_(,
```
[Try it here!](http://pyke.catbus.co.uk/?code=%2CFo2%25I_%28%2C&input=%22code%22%2C+%22golf%22)
```
- o = 0
, - transpose(input)
F ( - for i in ^:
o2% - (o++ %2)
I_ - if ^: i = reverse(i)
, - transpose(^)
```
[Answer]
# JavaScript (ES6), 51 ~~54~~
*Edit* 3 bytes saved thx @Neil
Function with array input/output
```
p=>p.map((w,i)=>w.replace(/./g,(c,j)=>p[i+j&1][j]))
```
I like this one more, but it's 55 (2 strings in input, array in output)
```
(a,b)=>[...a].reduce(([p,q],c,i)=>[q+c,p+b[i]],['',''])
```
**Test**
```
f=
p=>p.map((w,i)=>w.replace(/./g,(c,j)=>p[i+j&1][j]))
function go() {
var a=A.value, b=B.value
if (a.length == b.length)
O.textContent = f([a,b]).join('\n')
else
O.textContent = '- different length -'
}
go()
```
```
<input id=A value='Hello,'><input id=B value='world!'>
<button onclick='go()'>go</button><pre id=O></pre>
```
[Answer]
# Pyth, 8 bytes
```
C.e_FbkC
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=C.e_FbkC&input=%5B%22Hello%2C%22%2C%20%22world%21%22%5D&debug=0)
Transposes the words, reverses each pair of letters 'current index'-times, transpose again.
[Answer]
## JavaScript (ES6), 55 bytes
```
f=([c,...s],[d,...t],o="",p="")=>c?f(t,s,o+c,p+d):[o,p]
```
I wanted to do something clever with using regexp to replace alternate characters but that ended up taking ~~67~~ 57 bytes:
```
a=>a.map((s,i)=>a[+!i].replace(/.(.?)/g,(_,c,j)=>s[j]+c))
```
[Answer]
# Perl, 40 bytes
Includes +1 for `-n`
Give strings as lines on STDIN
```
interlace.pl
hello
world
^D
```
`interlace.pl`
```
#!/usr/bin/perl -n
s/./${1&$.+pos}[pos]=$&/seg}{print@0,@1
```
[Answer]
## Java, 132 103 100 bytes
*Thanks to Kevin Cruijssen for suggesting returning the array (among other improvements) and saving 29 bytes! Also Olivier Grégoire for 3 bytes!*
```
char[]c(char[]s,int l){for(int o=l;o-->0;)if(o%2>0){char t=s[o];s[o]=s[l+o+1];s[l+o+1]=t;}return s;}
```
Called like this:
```
public static void main(String[] args) {
System.out.println(c("Hello,world!".toCharArray(), 5)); // 5 is the length of each "String"
}
```
Output:
`Hollo,werld!`
Takes advantage of the fact that input can basically be formatted in any way (in this case, a single char array of Strings that are delimited by a comma), and pretty lenient output rules as well.
[Answer]
# C, 124 bytes
```
main(c,v)char**v;{char a[99],b[99];for(c=0;v[1][c]^0;++c){a[c]=v[1+c%2][c];b[c]=v[2-c%2][c];}a[c]=0;b[c]=0;puts(a);puts(b);}
```
Call with:
```
program.exe string1 string2
```
String length is limited to 98 characters.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~64~~ 61 bytes
```
@(x)reshape(x((t=1:end)+(2*mod(t,2)-1).*(mod(t-1,4)>1)),2,[])
```
Anonymous function that inputs a 2D char array with each string in a row, and produces the output in the same format.
[Try it at Ideone](http://ideone.com/8WZ5EG).
[Answer]
## Racket 208 bytes
```
(let((sl string->list)(ls list->string)(r reverse))(let p((s(sl s))(t(sl t))(u'())(v'())(g #t))(if(null? s)
(list(ls(r u))(ls(r v)))(p(cdr s)(cdr t)(cons(car(if g s t))u)(cons(car(if g t s))v)(if g #f #t)))))
```
Ungolfed:
```
(define (f s t)
(let ((sl string->list) ; create short names of fns
(ls list->string)
(r reverse))
(let loop ((s (sl s)) ; convert string to lists
(t (sl t))
(u '()) ; create empty new lists
(v '())
(g #t)) ; a boolean flag
(if (null? s) ; if done, return new lists converted back to strings
(list (ls (r u))
(ls (r v)))
(loop (rest s)
(rest t) ; keep adding chars to new lists alternately
(cons (first (if g s t)) u)
(cons (first (if g t s)) v)
(if g #f #t)) ; alternate the boolean flag
))))
```
Testing:
```
(f "abcdef" "123456")
```
Output:
```
'("a2c4e6" "1b3d5f")
```
Above is recursive version.
Iterative version:
```
(let*((sl string->list)(ls list->string)(r reverse)(s(sl s))(t(sl t))(l'())(k'())(p(λ(a b g)(set! l(cons(if g a b)l))
(set! k(cons(if g b a)k)))))(for((i s)(j t)(n(in-naturals)))(p i j(if(= 0(modulo n 2)) #t #f)))(list(ls(r l))(ls(r k))))
```
Ungolfed:
```
(define (f s t)
(let* ((sl string->list) ; create short form of fn names
(ls list->string)
(r reverse)
(s (sl s)) ; convert strings to lists
(t (sl t))
(l '()) ; create empty lists for new sequences
(k '())
(p (λ(a b g) ; fn to add chars to one or other list
(set! l (cons (if g a b) l))
(set! k (cons (if g b a) k)))))
(for ((i s)(j t)(n (in-naturals))) ; loop with both strings
(p i j ; add to new lists alternately
(if (= 0 (modulo n 2)) #t #f)))
(list (ls (r l)) ; convert reversed lists to strings
(ls (r k)))))
```
[Answer]
## PowerShell v2+, 82 bytes
```
param($a,$b)$i=0;[char[]]$a|%{$c+=($_,$b[$i])[$i%2];$d+=($b[$i],$_)[$i++%2]};$c;$d
```
~~Still golfing...~~ Nope. Can't seem to golf this down any without using a regex like other answers (boo on copying algorithms).
So we take `$a` and `$b` as strings, set index `$i` to `0`, cast `$a` as a `char`-array, and send it through a loop `|%{...}`. Each iteration, we're string-concatenating onto `$c` and `$d` by indexing into an array-select (i.e., so it alternates back and forth). Then, we leave `$c` and `$d` on the pipeline, and output via implicit `Write-Output` happens at program completion.
[Answer]
# [Lithp](https://github.com/andrakis/node-lithp), 120 characters (+3 for -v1 flag)
Line split in 2 for readability:
```
#P::((invoke P "map" (js-bridge #W,I::(replace W (regex "." "g")
(js-bridge #C,J::(index (index P (& (+ I J) 1)) J))))))
```
Requires the `-v1` flag to `run.js` as some functions are not yet part of the standard library.
Sample usage:
```
(
(def f #P::((invoke P "map" (js-bridge #W,I::(replace W (regex "." "g")
(js-bridge #C,J::(index (index P (& (+ I J) 1)) J)))))))
(print (f (list "Hello," "world!")))
)
```
This sort of highlights that I haven't spent enough time on the standard library. Having to use `js-bridge/1` twice and the long regex form, as well as invoking map using `invoke/*` all contribute to this being much longer than it needs to be.
Time to work on my standard library more I think.
[Answer]
# PHP, 79 Bytes
```
for(;$i<=strlen(($a=$argv)[1]);$y.=$a[2-$i%2][$i++])echo$a[1+$i%2][+$i]??" $y";
```
Previous Version PHP, 82 Bytes
```
for(;$i<strlen(($a=$argv)[1]);$y.=$a[2-$i%2][$i++])$x.=$a[1+$i%2][$i];echo"$x $y";
```
[Answer]
# C, ~~54~~ 52 bytes
```
f(char*a,char*b,char*c){while(*c++=*a++,*c++=*b++);}
```
Assumes output `c` has already the desired length.
Usage:
```
main(){
char a[]="123456";
char b[]="abcdef";
char c[sizeof(a)+sizeof(b)-1];
f(a,b,c);
puts(c);
```
}
If you insist on creating the output, here is a **91 bytes** solution:
```
char*g(char*a,char*b){char*c=malloc(2*strlen(a)),*d=c;while(*c++=*a++,*c++=*b++);return d;}
```
Usage:
```
main(){
char a[]="123456";
char b[]="abcdef";
puts(g(a,b));
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~8~~ 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
yÈéY
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ecjpWQ&input=WyJIZWxsbywiLCJ3b3JsZCEiXQotUQ)
```
yÈéY :Implicit input of array U
y :Transpose
È :Map each element at 0-based index Y then transpose back
éY : Rotate right Y times
```
[Answer]
# [q](https://code.kx.com/home/), 32 bytes
```
{?[;x;y]each(not\)count[x]#10b}.
```
# k, 24 bytes
```
{?[;x;y]'(~:\)(#x)#10b}.
```
[Answer]
# C, 150 bytes
I used the typical omissions of header files and `main()`'s return type and return statement. It throws a warning, but compiles without issue. I also used a GCC-specific trick that allows array declarations with variable expressions.
The program expects the strings from the command line, and as such, the program should be run with `./a.out string1 string2`.
```
main(int a,char**v){int x=strlen(v[1]);char s[x],t[x],c;strcpy(s,v[1]);strcpy(t,v[2]);for(a=0;a<x;++a)if(a%2)c=s[a],s[a]=t[a],t[a]=c;puts(s),puts(t);}
```
Or more legibly,
```
main(int a,char**v){
int x=strlen(v[1]);
char s[x],t[x],c;
strcpy(s,v[1]);strcpy(t,v[2]);
for(a=0;a<x;++a)
if(a%2)c=s[a],s[a]=t[a],t[a]=c;
puts(s),puts(t);
}
```
[Answer]
# Mathematica, 51 bytes
Takes input as an array of two arrays of characters, with output in the same format. The function simply constructs the new array using a (mod 2) operation.
```
Table[#[[Mod[j+i,2]+1,j]],{i,2},{j,Length@#[[1]]}]&
```
[Answer]
# QBasic 4.5, 172 bytes
Ouch, this one gets painful with the ol' QBasic...
```
DEFSTR A-D:INPUT A,B
IF LEN(A)MOD 2=1 THEN A=A+" ":B=B+" "
FOR x=1 TO LEN(A) STEP 2
C=C+MID$(A,x,1)+MID$(B,x+1,1):D=D+MID$(B,x,1)+MID$(A,x+1,1):NEXT:?RTRIM$(C),RTRIM$(D)
```
Fun fact: Using `DEFSTR` saved more bytes than it cost because now I could use `A` instead of `a$`.
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ?usp=sharing), 112 bytes
QBIC can streamline a lot of the QBasic boilerplate, but the main `MID$`engine still needs to be done in QBasic because QBIC lacks a substring-function. Still, saves me 60 bytes.
```
;;_LA|~a%2=1|A=A+@ | B=B+C][1,a,2|X=X+$MID$(A$,b,1)+MID$(B$,b+1,1):Y$=Y$+MID$(B$,b,1)+MID$(A$,b+1,1)|]?_tX|,_tY|
```
] |
[Question]
[
## Challenge
Given two digits 0-9 as input, output a domino (from the [double-nine domino set](http://www.domino-games.com/domino-rules/double-nine.html)) with these number of pips (dots) on the two faces. The ten possible faces look like this (separated by pipes):
```
| | o| o|o o|o o|o o o|o o o|o o o|o o o
| o | | o | | o | | 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 on separate lines:
```
-----
o
-----
o
o
-----
o
o
o
-----
o o
o o
-----
o o
o
o o
-----
o o o
o o o
-----
o o o
o
o o o
-----
o o o
o o
o o o
-----
o o o
o o o
o o o
```
## Input formats
You may take input in any reasonable format, including but not limited to:
* Two separate integers, strings, or singleton arrays;
* A single integer from 0-99;
* An array of two integers;
* A string of two digits.
## Output formats
* The two faces may be horizontally aligned, separated by pipes like so:
```
o|o o
| o
o |o o
```
* Or they may be vertically aligned, separated by hyphens like so:
```
o
o
-----
o o
o
o o
```
* You may output a border around the domino if you wish.
* You may also choose to output a list of lines, a list of the two faces, or a combination of these.
* You may use any non-whitespace character for the pips (I used `o`).
* If you really wish, you can use `0` for whitespace and `1` for the pips, or `False`/`True` (or your language's equivalent) if outputting an array.
* You may remove the whitespace between columns; this is a valid output for 7, 7:
```
ooo|ooo
o | o
ooo|ooo
```
* Any of the faces may be rotated by 90 degrees. This is also a valid output for 7, 7:
```
o o|o o o
o o o| o
o o|o o o
```
* You may have as much/little leading/trailing whitespace as you like, as long as the main part of the output still fits the other constraints.
* Each face must be 3 lines tall, even if the lines are empty. For 0, 1 you could not output this:
```
-----
o
```
But you *could* output this:
```
-----
o
```
Similarly, if you were outputting a list of two lists of lines, you could do `[["", "", ""], ["", " o", ""]]`, but not `[[""], [" o "]]`.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **the shortest code in bytes in each language wins.**
[Answer]
# [Python 2](https://docs.python.org/2/), ~~101~~ ~~97~~ ~~92~~ ~~68~~ 64 bytes
```
lambda*a:[[[n>3,n>5,n>1],[n>7,n%2,n>7],[n>1,n>5,n>3]]for n in a]
```
[Try it online!](https://tio.run/##K6gsycjPM/pfahvzPycxNyklUSvRKjo6Os/OWCfPzhSIDWN1gDxznTxVIyDPHMwzhMoZx8am5Rcp5Clk5ikkxv6Hs4sS89JTNQwNNK24FIAAJJ6CRRwECooy80o0SjXydFI0Nf8DAA "Python 2 – Try It Online")
# Credits
* Reduced from 101 bytes to 92 by [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)
* Reduced from 92 bytes to 68 by [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) ([Dennis](https://codegolf.stackexchange.com/users/12012/dennis))
* Reduced from 68 bytes to 64 by [totallyhuman](https://codegolf.stackexchange.com/users/68615/totallyhuman)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~252~~ ~~242~~ ~~269~~ ~~262~~ ~~241~~ ~~235~~ 220 bytes
I was on stack overflow for sockets in python, when this popped up, said why not? first code golf, so i'm not entirely sure if I followed the rules 100% (and if not and someone wants to steal my proverbial cookie and fix it, so be it). With 'o' and ' ', ~~255 245 272 265 244 238~~ 228 bytes. replace +48 with \*79+32.
```
#define Q(P,R)(R>>P&1)+48
char a[11];i=0;f(char*c){char b=c[0];a[3]=a[7]='\n';a[5]=Q(0,b);a[1]=a[9]=Q(3,b);a[2]=a[8]=Q(2,b)|a[1];a[0]=a[10]=Q(1,b)|a[2];a[4]=a[6]=a[1]|Q(2,b)&Q(1,b);puts(a);if(i++<1){puts("---");f(c+1);}}
```
[Try it online!](https://tio.run/##Tc9NbsMgEAXgPadAiZRAbVdgu00qgs@QZOuyIPgnSCmtHKcbx2enDN6U1eN7gzSYrDfGr60zt0fT4sN9HKzrX68V@m@N/Q7k103bWdfiEzmmZ0rOVXXccJqUe2SuesC65lwJK5noCMCLoVMsLtLUTAldF0rqeqfk9tNtw/VNyRNh6YWGzKH6ACgWyAH2AHmAJ0wEZaCcAfOFc@AS@D126rm82CwT4ucx3ommwnbEJsmB0ynKKsuyFYVNE07FPHvrRvylrSMQ9NCbFMdPQP6tFaZoQjicjkTgigo0e1@Ufw "C (gcc) – Try It Online")
How it works:
I use a bit shift and bitwise and to find if a spot should be clear or a pip, then offset the 0 or 1 to the correct ASCII value. it messes up on 4 and 5, so they needed some fixing. actually added a few bytes. was able to remove several bytes by removing a mask and just using 1 (doh)
Special thanks to Mr. Xcoder for the 7 less bytes by removing an excess #define
Changes: removed memset -21 bytes. redid the bit logic for 6, 4, 2 to depend on 8|4&2, 8|4, 8|4|2, respectively. -6 bytes. removed extra newlines by using puts instead of printf, which is also shorter. shortened the array to 11, removing extra assignment. -15 bytes. NOW I think that's the best I can do.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
“¤o.ƤẸʠṚ’B¬s5ŒBị@s€3
```
[Try it online!](https://tio.run/##ATMAzP9qZWxsef//4oCcwqRvLsak4bq4yqDhuZrigJlCwqxzNcWSQuG7i0Bz4oKsM////zQsIDI "Jelly – Try It Online")
### Alternate version, original output, ~~33~~ ~~32~~ 31 bytes
```
“¤o.ƤẸʠṚ’ṃ⁾ os5ŒBị@s€3K€€Zj€”|Y
```
*Thanks to @user202729 for golfing off 1 byte!*
[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDS/L1ji15uGvHqQUPd8561DDz4c7mR437FPKLTY9Ocnq4u9uh@FHTGmNvIAFEUVkgumFuTeT///8NdBQMdRSMdBSMdRRMdBRMdRTMdBTMdRQsdBQsAQ "Jelly – Try It Online")
### How it works
First, `“¤o.ƤẸʠṚ’` – an integer literal in bijective base 250 – sets the return value to **1086123479729183**.
Then, `B¬` converts the return value to binary and takes the logical NOT of each digit, yielding the array
```
00001001000010110100101011110011101111101111100000
```
Next, `s5ŒB` splits that array into chunks of length **5**, then *bounces* each chunk, turning **abcde** into **abcdedcba**, yielding
```
000010000 001000100 001010100 101000101 101010101
111000111 111010111 111101111 111111111 000000000
```
Now, `ị@` retrieves the **j**th and **k**th item of this array, where **j, k** is the program's first argument. Note that indexing is 1-based and modular, so the zeroth element is also the tenth.
Finally, `s€3` splits each chunk of length nine into three chunks of length three.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
⁽½ÑD<;ḂŒBs3µ€
```
[Try it online!](https://tio.run/##ATYAyf9qZWxsef//4oG9wr3DkUQ8O@G4gsWSQnMzwrXigqz///9bMCwxLDIsMyw0LDUsNiw3LDgsOV0 "Jelly – Try It Online")
Combining [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)' idea of using `ŒB` (bounce) in [this answer](https://codegolf.stackexchange.com/a/151594) and [Xcali](https://codegolf.stackexchange.com/users/72767/xcali)'s observation in [this answer](https://codegolf.stackexchange.com/a/151598) to get 13 bytes.
---
# [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes
(with pretty printing)
Only now do I know that Jelly string literal is automatically terminated...
```
⁽½ÑD<;ḂŒBị⁾o Ks6Yµ€j“¶-----¶
```
[Try it online!](https://tio.run/##y0rNyan8//9R495Dew9PdLGxfrij6egkp4e7ux817stX8C42izy09VHTmqxHDXMObdMFgUPb/v//H22gY6hjpGOsY6JjqmOmY65joWMZCwA "Jelly – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), ~~107 76 70~~ 67 ~~+ 1 (`-a`)~~ = 67 bytes
```
$,="
---
";say map{'351
7 7
153'=~s/\d/$_>$&||0/ger=~s/ /$_%2/er}<>
```
[Try it online!](https://tio.run/##K0gtyjH9/19Fx1aJS1dXl0vJujixUiE3saBa3djUkMtcwZzL0NRY3bauWD8mRV8l3k5FrabGQD89tQgkpAAUUTXSTy2qtbH7/9@Yy@RffkFJZn5e8X9dX1M9A0MDAA "Perl 5 – Try It Online")
Uses 0 for whitespace and 1 for pips. Pretty simple method: observe that as the digit goes up, once a pip is "on", it never goes "off," except for the one in the middle. In the middle position, it is on for all odd numbers. Thus, for each position, it's a simple matter of checking if the digit is greater than the last digit for which it is off. The `||0` creates output when the condition is false. In Perl, false is `undef` which outputs as null.
[Answer]
# PHP ~~155~~, 150 bytes
```
function d($a){foreach($a as$n){$o="---";for($i=0;$x=2**$i,$i<9;++$i)$o.=([0,16,68,84,325,341,365,381,495,511])[$n]&$x?0:' ';echo chunk_split($o,3);}}
```
It takes an array of integers as the input. For testing:
```
d([1,2]);
echo "=========\n";
d([0,1,2,3,4,5,6,7,8,9]);
```
Output Format:
```
---
0
---
0
0
```
Check it out [live here](http://sandbox.onlinephpfunctions.com/code/55762d92e136678df328ecd8da411888a6335c80)
**My Solution**
For my solution I used a matrix consisting of [bitwise](http://php.net/manual/en/language.operators.bitwise.php) numbers ( powers of 2 ). It can be visualized like this:
```
1 | 2 | 4
8 | 16 | 32
64 | 128 | 256
```
And then a storage array consisting of the bit positions for the pips of each domino correlated by the numbered index:
```
[0,16,68,84,325,341,365,381,495,511]
```
So just to clarify:
* example 0: index `0` or value `0` would be the blank domino, which is always false.
* example 1: index `1` or value `16` would be the number one domino and in the matrix that is in the center `16`.
* example 2: index `2` or value `68` would be the number two domino and in the matrix that is top right `4` and bottom left `64` or `4|64`
* example 3: index `5` or value `341` would be the number five domino and in the matrix that is `1|4|16|64|256`
* example 4: index `9` or value `511` would be the number nine domino and in the matrix its the combination of all the bits.
Once that is established it's a fairly simple matter of looping for the 9 positions in the matrix, and setting `$x` to `2` to the [power](http://php.net/manual/en/function.pow.php) of `$i`
```
for($i=0;$x=2**$i,$i<9;++$i)
```
Then we do a bitwise And `&` as we iterate through those spots. So for examples sake will use example 2 from above and I will use `x`'s instead spaces for sake of visual clarity:
* iteration 1, `68 & 1 ? 0 : 'x'` which results in `'x'`
* iteration 2, `68 & 2 ? 0 : 'x'` which results in `'x'`
* iteration 3, `68 & 4 ? 0 : 'x'` which results in `0`
* iteration 4, `68 & 8 ? 0 : 'x'` which results in `'x'`
* iteration 5, `68 & 16 ? 0 : 'x'` which results in `'x'`
* iteration 6, `68 & 32 ? 0 : 'x'` which results in `'x'`
* iteration 7, `68 & 64 ? 0 : 'x'` which results in `0`
* iteration 8, `68 & 128 ? 0 : 'x'` which results in `'x'`
* iteration 9, `68 & 256 ? 0 : 'x'` which results in `'x'`
When the loop is complete we wind up with this string `"xx0xxx0xx"`.
Then we add the border `"---xx0xxx0xx"` to it *( I actually start with the border, but whatever)*.
And finally we [chunk\_split()](http://php.net/manual/en/function.chunk-split.php) it on 3's for:
```
---
xx0
xxx
0xx
```
Feel free to let me know what you think.
[Answer]
# JavaScript (ES6), ~~79~~ 78 bytes
*Saved 1 byte thanks to @ETHproductions*
Takes input in currying syntax `(a)(b)` and outputs a vertical ASCII domino.
```
a=>b=>(g=n=>`351
707
153`.replace(/./g,d=>' o'[(+d?n>d:n)&1]))(a)+`
---
`+g(b)
```
### Demo
```
let f =
a=>b=>(g=n=>`351
707
153`.replace(/./g,d=>' o'[(+d?n>d:n)&1]))(a)+`
---
`+g(b)
console.log(f(4)(2))
console.log(f(3)(7))
```
---
# Horizontal version, ~~80~~ 79 bytes
*Saved 1 byte thanks to @ETHproductions*
Takes input as an array of 2 integers and outputs a horizontal ASCII domino.
```
a=>`240|351
686|797
042|153`.replace(/\d/g,d=>' o'[(d<8?(x=a[d&1])>(d|1):x)&1])
```
### Demo
```
let f =
a=>`240|351
686|797
042|153`.replace(/\d/g,d=>' o'[(d<8?(x=a[d&1])>(d|1):x)&1])
console.log(f([4,2]))
console.log(f([3,7]))
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 25 bytes
```
2∘|(3 3⍴⊢,,∘⌽)¨>∘3 5 1 7¨
```
[Try it online!](https://tio.run/##jcw9SgNBHIbxfk8xZQIRMvOfz8Yb2HmBJW5CIGzEjYWorUhwxUawsdEmhaWWNjnKXGTdPGK0tHnmA35vebo4OLkoF8tZ15l8@3Q1ECW5fc/rl9Gof@e7z@F2c9jfRDmlVdhuutw@q6NyXqvpeT1ZzZd1UUxVvnlQ/xwoit3CcdWsqrM/GzM2LvP9Y3/m9i2vX7/v08H@b9jP/jw@rn@H1KRsqma3MVZjqqmhQi111NNAI019NVZjNVZjNVZjNVZjNVZjDdZgDdZgDdZgDdZgDdZgBStYwQpWsIIVrGAFK1iLtViLtViLtViLtViLtViHdViHdViHdViHdViHdViP9ViP9ViP9ViP9ViP9diADdiADdiADdiADdiADdiIjdiIjdiIjdiIjdiIjdiETdiETdiETdiETdiETSp1Xw "APL (Dyalog Unicode) – Try It Online")
-2 thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn).
The output format is a little bit weird: this function returns an array containing two shape-3,3 arrays each containing 0s and 1s.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~115~~ 113 bytes
-2 bytes thanks to ceilingcat
```
i;g(x){for(i=0;9/++i;)printf("%c%c",32+(i^5?x>" CEAG@GAEC"[i]%8:x%2),i%3?32:10);}f(a,b){g(a),puts("-----"),g(b);}
```
[Try it online!](https://tio.run/##dY7LCsJADEXX7VeEgYGEmWJtEWzHJyJ@hA@oIy1ZWMUHFEq/vaYu3BkCF@4huddHlfd9z67Chtry9kCexy4bGcOO7g@uXyUq7bVXNk0M8mmybBYKNtv1brVbbzdqz0c9zRudkGWdLtMkH8fkuhILe6a2woLs/f16ooqGUWQrPAvv5TNcC66RwjYMJBhwsBjmEDuRGWQixlAYCA9@VS6gL/mhVhZYFgyMyQ38m2EkwqivUeI/LseD1YVd/wE "C (gcc) – Try It Online")
[Answer]
# Javascript (ES6), 87 bytes
```
a=>b=>[(s=n=>[[n>3,n>5,n>1],[n>7,n%2,n>7],[n>1,n>5,n>3]].map(c=>c.map(b=>+b)))(a),s(b)]
```
```
f=a=>b=>[(s=n=>[[n>3,n>5,n>1],[n>7,n%2,n>7],[n>1,n>5,n>3]].map(c=>c.map(b=>+b)))(a),s(b)]
```
```
<div oninput="o.innerText=JSON.stringify(f(a.value)(b.value))"><input id=a type=number min=1 max=9 value=1><input id=b type=number min=1 max=9 value=1><pre id=o>
```
[Answer]
# Haskell - 88 characters
```
map$zipWith(zipWith($))[[(>4),(>5),(>1)],[(>7),odd,(>7)],[(>1),(>5),(>3)]].repeat.repeat
```
Takes a list of two numbers indicating the faces, returns a list of list of list of bool. Not that short but I find the solution interesting.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
>⁽¤xb8¤;ḂŒḄs3
Ç€
```
[Try it online!](https://tio.run/##ASwA0/9qZWxsef//PuKBvcKkeGI4wqQ74biCxZLhuIRzMwrDh@KCrP///1szLCA3XQ "Jelly – Try It Online")
Used [Neil's strategy](https://codegolf.stackexchange.com/a/151604/77748) and base decompression to generate the values; outputs as a binary array. Takes a list as input.
Explanation:
```
Ç€
€ for €ach input,
Ç execute the previous line.
>⁽¤xb8¤;ḂŒḄs3
⁽¤xb8¤ the array [3, 5, 1, 7]
> 1 if the input is greater than each element, 0 otherwise
;Ḃ append input % 2
ŒḄ bounce array
s3 split into chunks of 3
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~32~~ ~~27~~ ~~24~~ 21 bytes
-3 bytes thanks to @DLosc
```
FcgP[Yc>_M3517c%2RVy]
```
[Try it online!](https://tio.run/##K8gs@P/fLTk9IDoy2S7e19jU0DxZ1SgorDL2////Jv9NAQ "Pip – Try It Online")
### Explanation:
```
F For each
c character $c
g in the list of inputs:
P Print
[ ] an array consisting of
an array of bits representing whether
c> $c is greater than
_M each of
3517 3, 5, 1, and 7
Y (call this bit array $y),
c%2 $c mod 2,
RV and the reverse
y of $y.
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 57+3 = 60 bytes
```
>{:3)$:5)$:1)$:7)$:2%$\ao \
\?%cl999)3$)5:$)1:$)7:/nnn<rp
```
[Try It Online](https://tio.run/##DcNBCoAgEAXQfadoMS5mEaVmNhJ1ETcRREFYFLTp8D8fvHV/NmD8gmUKLte5z42iOJ9lLOKklkNE2BK7QKxzH@qU0nBfAKoXDTQMLFo4dPDoIWh@). Outputs as a vertical domino with 1s for dots, 0s for whitespace and 9s for separators like so:
```
001
000
100
999
111
111
111
```
Technically this can be extended to up to 12 inputted values.
## Old Version:
## [><>](https://esolangs.org/wiki/Fish), 76+3 = 79 bytes
```
>{:3)$:5)$:1)$a$:7)$:2%$:7)\&?o~?!n\
\?(*a3la"---"a)3$)5:$)1:$a$/$&:)9::<r~p
```
[Try It Online](https://tio.run/##S8sszvj/367aylhTxcoUiA01VRJVrMyBLCNVEB2jZp9fZ6@YF8MVY6@hlWick6ikq6urlKhprKJpaqWiaWgFVK@vomalaWllZVNUV/D//3/dsv9G/y0B). Outputs as a vertical domino with 1s for dots and 0s for whitespace like so:
```
001
000
100
---
111
111
111
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~46~~ ~~44~~ ~~43~~ 39 bytes
```
EE²℅§@APQTUVW^_NE⪪E⁹§ o÷ιX²↔⁻⁴λ³⪫λ M⁵↑⁵
```
[Try it online!](https://tio.run/##PY7BCsIwEETvfsWS0wbipVpEe7HgpUK1otWbkrYBAzEJbVr9@xhbcGAOs/Bmp37ytjZceV@0UjvMuR0dMTi2jdRcYeoy3YgPkm1anC7l9XZ/EAaZtr079K9KtEiDGPyws1VyKlkz@INgRsDt5CAbgZJBYd6BC0/SqsNc6r7DJQNF6VS1CN4bqVExIEDCLZnlZhAYM9iUNqRpbUwT76PZys8H9QU "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
EE²℅§@APQTUVW^_N
```
Read two integers and map them in the lookup table. Then map over the result. (This effectively captures the result in a temporary.)
```
E⁹ Loop `l` (!) from 0 to 8
⁻⁴λ Subtract from 4
↔ Absolute value
X² Power of 2
÷ι Divide into the looked-up value `i`
§ o Convert to space or o
⪪ ³ Split into (3) groups of 3
E Map over each group
⪫λ Join the 3 characters with spaces
```
The results are then implicitly printed on separate lines, with an extra blank line between each face because the results are nested.
```
M⁵↑⁵
```
Move up and draw the dividing line in between the faces.
Previous 43-byte horizontal version:
```
↶P³M⁷←FE²℅§@APQTUVW^_NF⁹«F¬﹪κ³⸿⸿§ o÷ιX²↔⁻⁴κ
```
[Try it online!](https://tio.run/##PY7LCsIwEEXX7VcMXU0hblQQdWPBjWC1go@NKNVGDMZMiUkVxG@PaQTvau487pnztdRnKqVzhWjIzPnFYDqOcyuNqLVQBnutpYbjgMGonXt/IQ2YlzV2GSx1JVQpMTMzVfEXJpOsWK03293hmDCYqdqahb2fuMbUC8LpMIV3HEWhXpDBnCorCW8Meu1OEcDJXu914mlR9Gv8CUAh2UxFIyqOgkFBTw/w32SnB@ZC2Qf2GdzSoHH8ca4bD1ynkV8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
↶
```
Work vertically.
```
P³
```
Print the dividing line.
```
M⁷←
```
Position to the start of the first face.
```
FE²℅§@APQTUVW^_N
```
Read two integers and map them in the lookup table.
```
F⁹«
```
Prepare to output up to 9 `o`s.
```
F¬﹪κ³⸿⸿
```
But start a new column every three `o`s.
```
§ o÷ιX²↔⁻⁴κ
```
Convert the lower 5 bits of the ASCII code to binary, and then mirror the output for the remaining 4 `o`s.
[Answer]
# [Chip](https://github.com/Phlarx/chip), ~~142~~ 135 bytes
```
! CvDvB
>v-]-x.
|Z-]-]e
|Z]xe|
|ZR(-'
|Zx.AD
|Zxx]x.
|Zx^-]e
|Z<,(-.
|Zx]xe|
|Zx-]-]e
|Zx-]-x'
|Z<C^D^B
|>x~s
|Zx.
|Zx<
|Zxb
|Z+^~f
`zd
```
[Try it online!](https://tio.run/##S87ILPj/X1HBucylzInLrkw3VrdCj6smCkjHpgLp2IrUGiAVpKGrDqQq9BxdQFRFLFhRRRxEkY2Ohi6YD1VdAdMNYlSANNo4x7nEOXHV2FXUFYPNARE2ICIJSGjH1aVxJVSl/P9vZAoA "Chip – Try It Online")
Input is a string of digits. Uses zeroes as the pips. Draws the pips for one number, reads next input byte. If no next byte, terminate, else draw the divider and go to start.
Each `Z` (or `z`) corresponds to one character of output, they are positioned to fire in order top to bottom. The capitalized `A`, `B`, `C`, and `D` correspond to the low four bits of the input (that's all we look at, so `"34" == "CD" == "st" ...`). The lowercase `b`, `d`, `e`, `f` correspond to various bits of the output.
Can make infinite-length dominoes too; try giving `0123456789` as input.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~150~~ ~~146~~ 145 bytes
* Saved ~~four~~ five bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
#define p(x)printf(" %c",33-(x)),
P(a){p(a<4)p(a<6)p(a<2)p(23)p(a<8)p(~a&1)p(a<8)p(23)p(a<2)p(a<6)p(a<4)p(23)0;}f(a,b){P(a),puts(" -----"),P(b);}
```
[Try it online!](https://tio.run/##XY3RCoJAEEWf8ytko5iBEXS1MrYv6MlfWDdXfEiWMggW/fVtVyPCeTjcOVxmVNIq5dz21uiub2IDbzSPrh80sHinGOV54hVSVIFEa0BeCgw8zuSePJ9j6TnJffZbvp7/1YtFp2LUIKlGG46SeQ1P/y0Jw5AqqFGM7i67Hq5oo42GjE4oltrEUASV0nmtDpSuVUGlD6P7AA "C (gcc) – Try It Online")
[Answer]
## Javascript (ES5), 103 characters
```
(a,b,h=(y=7)=>
' o o ooo'.slice(+y,+y+3))=>
['223355','242424245','221155'].map(z=>
h(z[a])+'|'+h(z[b]))
```
Linebreaks and whitespace inserted for readability.
[Answer]
# APL+WIN, ~~49~~ 47 bytes
```
4⌽'|',⌽⍉6 3⍴,⍉(9⍴2)⊤(+\∊0 241 52 24 114,¨16)[⎕]
```
Edited as per Adam's comment, thanks, to run with index origin zero.
Prompts for screen input as a vector of integers one for each face.
The output is of the form:
```
1 1 1 | 0 0 1 0 0 0 | 1 0 1
0 1 0 | 0 1 0 0 0 0 | 0 1 0
1 1 1 | 1 0 0 0 0 0 | 1 0 1
```
for an inputs of `7 3` and `0 5`
Explanation:
```
(+\∊0 241 52 24 114,¨16) create a vector of integers whose binaries
represent the dots on the domino faces
[1+⎕] take input integers as indices to select from above vector
⍉6 3⍴,⍉(9⍴2)⊤ convert selected integers to a 9x2 binary matrix and reshape
to match the orientation of the domino faces
4⌽'|',⌽ rotate, concatenate centre line markers and rotate again to centre
```
[Answer]
# [Python 2](https://docs.python.org/2/), 121 bytes
```
lambda x,y,d="001155777702020202570044557777":[("%03d"%int(bin(int(o))[2:]),"---")[o=="3"]for o in d[x::10]+"3"+d[y::10]]
```
[Try it online!](https://tio.run/##RctBCoMwEAXQvacIA0KCI0zUaBvISdIslCAV2kTEhZ4@tZXi/MXnfZh5X58xVGk0j/Tq34Pv2YY7egNEUirVHUfVGdURNc25gbYccqo95FNY@TAF/u0ohK20EwhlWYKw0RiowY1xYZFNgXm7aS3JFcdaeLv/4NK8HM9s5IS1yP5osLug8HZB4v1Ci63I0gc "Python 2 – Try It Online")
Reduced to 121 using a lambda after going back and re-reading the rules. Now outputs a list of lines.
Previous version with nicely formatted output:
# [Python 2](https://docs.python.org/2/), ~~156~~ ~~153~~ ~~147~~ 141 bytes
```
x,y=input()
d="001155777702020202570044557777"
a=["%03d"%int(bin(int(o))[2:])for o in d[x::10]+d[y::10]]
for x in a[:3]+["---"]+a[3:]:print x
```
[Try it online!](https://tio.run/##JYzBCoQgGITvPoUIgVLCnxWR4JP866FFlvWiEQb69G5uM4cZ5oM5SvrGoOplXjUPxfhwXIkL4gwDGMdlWW@BerysAPP8bIzsBlkHk2OdD4m/feAtoxCotBWfeNJIfaAOs9Yj2N5h@RdLGsuN7agn2yOTUjLb7zhpq4/zvqG5Vhi2Hw "Python 2 – Try It Online")
-3 with thanks to @NieDzejkob
Takes input as 2 integers and outputs in vertical format with 0=space and 1=dot.
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), ~~220~~ 154 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage)
Second attempt (154 bytes)
```
46281ᴇ8264áĐ9ř3%¬Đ¬2⁵*⇹1ᴇ*+03Ș←Đ3Ș≥Đ6²⁺3**⇹¬2⁵*+⇹9ř5=⇹2%*9²2-*+⇹9ř9<*Ž⇹ŕ⇹9ř3%¬Đ¬2⁵*⇹1ᴇ*+03Ș←Đ3Ș≥Đ6²⁺3**⇹¬2⁵*+⇹9ř5=⇹2%*9²2-*+⇹9ř9<*Ž⇹ŕ5⑴9△*Ƈǰ⇹Ƈǰ64ȘƇǰ6↔ŕ↔ŕ↔
```
Explanation:
```
46281ᴇ8264áĐ Pattern matching for every cell but the middle
9ř3%¬Đ¬2⁵*⇹1ᴇ*+03Ș Non-pip characters
←Đ3Ș≥Đ6²⁺3**⇹¬2⁵*+⇹9ř5=⇹2%*9²2-*+⇹9ř9<*Ž⇹ŕ⇹ Make top cell
9ř3%¬Đ¬2⁵*⇹1ᴇ*+03Ș Non-pip characters
←Đ3Ș≥Đ6²⁺3**⇹¬2⁵*+⇹9ř5=⇹2%*9²2-*+⇹9ř9<*Ž⇹ŕ Make bottom cell
5⑴9△*Ƈǰ⇹Ƈǰ64ȘƇǰ6↔ŕ↔ŕ↔ Make boundary and combine
```
---
First attempt (220 bytes):
```
2`↔←Đ4≥Đ6²⁺3**⇹¬5«+2⁵⇹3ȘĐ6≥Đ6²⁺3**⇹¬5«+2⁵⇹3ȘĐ2≥Đ6²⁺3**⇹¬5«+1ᴇ⇹3ȘĐ8≥Đ6²⁺3**⇹¬5«+2⁵⇹3ȘĐ2%Đ6²⁺3**⇹¬5«+2⁵⇹3ȘĐ8≥Đ6²⁺3**⇹¬5«+1ᴇ⇹3ȘĐ2≥Đ6²⁺3**⇹¬5«+2⁵⇹3ȘĐ6≥Đ6²⁺3**⇹¬5«+2⁵⇹3Ș4≥Đ6²⁺3**⇹¬5«+1ᴇ9△ĐĐĐĐ1ᴇ↔⁻łŕ↔ŕŕŕŕŕŕáƇǰ
```
Explanation:
```
2 Push 2 (this is how many 'cells' to make)
` ... ł While the top of the stack is not zero, loop
↔ Flip the stack (useless at the beginning, undoes the flip at the end of the loop)
←Đ4≥Đ6²⁺3**⇹¬5«+ Set top-left pip
2⁵⇹3Ș Space
Đ6≥Đ6²⁺3**⇹¬5«+ Set top-middle pip
2⁵⇹3Ș Space
Đ2≥Đ6²⁺3**⇹¬5«+ Set top-right pip
1ᴇ⇹3Ș New line
Đ8≥Đ6²⁺3**⇹¬5«+ Set middle-left pip
2⁵⇹3Ș Space
Đ2%Đ6²⁺3**⇹¬5«+ Set center pip
2⁵⇹3Ș Space
Đ8≥Đ6²⁺3**⇹¬5«+ Set middle-right pip
1ᴇ⇹3Ș New line
Đ2≥Đ6²⁺3**⇹¬5«+ Set bottom-left pip
2⁵⇹3Ș Space
Đ6≥Đ6²⁺3**⇹¬5«+ Set bottom-middle pip
2⁵⇹3Ș Space
4≥Đ6²⁺3**⇹¬5«+ Set bottom-right pip
1ᴇ New line
9△ĐĐĐĐ Add 5 dashes
1ᴇ New line
↔⁻ł Decrement counter (if >0, loop; otherwise, exit loop)
ŕ↔ŕŕŕŕŕŕ Remove all unnecessary items on the stack
áƇǰ Push stack to an array, get characters at unicode codepoints given by values in the array, join characters with empty string
```
[Try it online!](https://tio.run/##K6gs@f/fKOFR25RHbROOTDB51Ln0yASzQ5seNe4y1tJ61L7z0BrTQ6u1jR41bgVyjE/MAMoSocYIhxrDh1vaYWosiDFHlZAKCyJsMqKKr0zw2GT5aNrmIxMgEGwzMDwbdx9tOjoVyDo6FQEPLzzWfnwDMMi5jAE)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 34 bytes
```
•ΩõIº•R2ô¹2÷è¹È-bDg5s-ú.∞3ô»TR„ o‡
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UcOicysPb/U8tAvICjI6vOXQTqPD2w@vOLTzcIdukku6abHu4V16jzrmGQOldocEPWqYp5D/qGHh//@mAA "05AB1E – Try It Online")
---
This was difficult because 05AB1E has bad padding.
---
Basic explanation:
* There are 4 significant patterns here which are 2, 4, 6 and 8.
* 3,5,7 and 9 are the other patterns plus 1.
* 1 is not significant due to symmetry, if the input is even, subtract 1 to toggle the middle bit.
* Toggling the LSB allows the middle bit to be flipped due to mirroring.
[Answer]
# SmileBASIC, ~~92~~ 69 bytes
```
INPUT N,M
DEF Q?N>3;N>5;N>1?N>7;1AND N;N>7?N>1;N>5;N>3
END
Q?777N=M
Q
```
Example:
```
? 7,2
111
010
111
777
001
000
100
```
This is what happens when your rules aren't strict enough.
[Answer]
# FALSE, ~~116~~ ~~80~~ ~~78~~ ~~70~~ ~~69~~ ~~66~~ ~~63~~ ~~61~~ ~~59~~ 58 bytes
```
[$3[>_$.\$]$p:!5p;!1p;!"
"7p;!%1&.."
"..."
"]$s:!"---
"s;!
```
still working on this...
[Answer]
# PHP, 116 bytes
```
while($i<6)echo strtr(sprintf("%03b",[_011557777,_202020267,_044557777][$i/2][$argv[$i%2+1]]),10,"o "),"|
"[$i++%2];
```
requires PHP 5.5 or later. Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/cec3cd33beca4e0ccaf4bee58ee8b4afc7f1fba3).
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 41 bytes
```
»⟑-⁰ɖṄwi⁋ǏSżƛ»b9ẇ:£?i¥?i3(2p)Jƛ`o -`$i;3ẇ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=%C2%BB%E2%9F%91-%E2%81%B0%C9%96%E1%B9%84wi%E2%81%8B%C7%8FS%C5%BC%C6%9B%C2%BBb9%E1%BA%87%3A%C2%A3%3Fi%C2%A5%3Fi3%282p%29J%C6%9B%60o%20-%60%24i%3B3%E1%BA%87&inputs=1%0A3&header=&footer=)
A mess.
] |
[Question]
[
[Thanksgiving](https://en.wikipedia.org/wiki/Thanksgiving_(United_States)) in the United States is coming up on November 24th. Many people will have a large dinner with their families, traditionally including turkey and many side dishes. This typically means the family members must coordinate who's going to bring each of the various dishes. In this challenge, the goal is to **write a [polyglot](https://en.wikipedia.org/wiki/Polyglot_(computing)) that outputs a different dish in each language it's run in.**
## Menu
(Selected from [Wikipedia](https://en.wikipedia.org/wiki/Thanksgiving_dinner). In case it's not obvious, each line is one item.)
```
turkey
stuffing
dressing
cranberry sauce
mashed potatoes
gravy
winter squash
sweet potatoes
corn
green beans
green bean casserole
mac and cheese
macaroni and cheese
salad
rolls
biscuits
corn bread
pumpkin pie
apple pie
mincemeat pie
sweet potato pie
pecan pie
apple cider
sweet tea
```
## Rules
* Each submission must run in **at least 3 languages**, each of which must output a **different** item from the menu. You may not use multiple versions of the same language (e.g. Python 2 and Python 3 cannot be used in the same answer).
* Each entry must have the same bytes in each language's encoding. For example, `ɱ` is byte `0x1D` in [Jelly's encoding](https://github.com/DennisMitchell/jelly/wiki/Code-page), which corresponds to `¢` in [05AB1E's encoding](https://en.wikipedia.org/wiki/Windows-1252).
* Different languages may use different output methods, but **entries must be full programs in all languages**, and follow one of our [default allowed IO methods](https://codegolf.meta.stackexchange.com/q/2447/42545).
* No programs may take input, but any of the programs may print to STDERR or throw runtime/compile time errors and warnings as long as the correct output is still printed to STDOUT or a file.
* **Case and whitespace do not matter.** For example, an output of `GreenbeAN S` would still count as `green beans`.
* As the central dish of every1 American Thanksgiving meal is turkey, **one language must output `turkey`** (ignoring case and whitespace).
## Scoring
**The submission that produces unique valid outputs in the most languages wins.** In case of a tie, the shortest of the tied entries in bytes wins.
1. Yes, [turkey is not the only main dish](https://en.wikipedia.org/wiki/Thanksgiving_dinner#Alternatives_to_turkey), but we're going to pretend it is.
[Answer]
## Pyke, Pyth, Python 2, Foo, Brain\*\*\*\*, GolfScript, Actually, <><, Gol<><, Seriously, Befunge, Fission, Haystack, 13 languages, 546 bytes
When I saw [the other ~~10~~ ~~11~~ 12 language answer](https://codegolf.stackexchange.com/a/101196/32686), I had to add an extra ~~one~~ ~~two~~ 3. I'm also seriously considering dropping Pyth if only to save on bytes. (at the moment 162 of them)
```
#\ s[\g\r\a\v\y)w.q)\r\o\l\l\ssp00/;oooooooo'stuffing;oooooo~'`turkey'
print'corn'#))))))))))))))))))))))))]+[--------->++<]>+w.q++[->+++<]>++w.q+++++++++++w.q-----------w.q----------------;))!+f'!n'!i'!s'!s'!e'!r'!d'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))L
'bread'#)))\é'i'n'o'r'a+++++))))))))))))))))))))))))))))))))))))))))))))))))\♀1X'c'a'm++++'e's'e'e'h'c'd'n'a++++++++)+.&\�0\ó))))))))))))))))))
#\25*8*0+c25*6*9+c25*6*7+c25*6*5+c25*7*8+c25*8*0+c25*7*3+c25*6*9+c|000000
# ,,,,,,,,@0>00000000\#"biscuits"aetteews"
```
---
Pyke: [Try it here!](http://pyke.catbus.co.uk/?code=%23%5C+s%5B%5Cg%5Cr%5Ca%5Cv%5Cy%29w.q%29%5Cr%5Co%5Cl%5Cl%5Cssp00%2F%3Boooooooo%27stuffing%3Boooooo%7E%27%60turkey%27%0Aprint%27corn%27%23%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%5D%2B%5B---------%3E%2B%2B%3C%5D%3E%2Bw.q%2B%2B%5B-%3E%2B%2B%2B%3C%5D%3E%2B%2Bw.q%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2Bw.q-----------w.q----------------%3B%29%29%21%2Bf%27%21n%27%21i%27%21s%27%21s%27%21e%27%21r%27%21d%27%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29L%0A%27bread%27%23%29%29%29%5C%C3%A9%27i%27n%27o%27r%27a%2B%2B%2B%2B%2B%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%5C%E2%99%801X%27c%27a%27m%2B%2B%2B%2B%27e%27s%27e%27e%27h%27c%27d%27n%27a%2B%2B%2B%2B%2B%2B%2B%2B%29%2B.%26%5C%EF%BF%BD0%5C%C3%B3%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%0A%23%5C25%2a8%2a0%2Bc25%2a6%2a9%2Bc25%2a6%2a7%2Bc25%2a6%2a5%2Bc25%2a7%2a8%2Bc25%2a8%2a0%2Bc25%2a7%2a3%2Bc25%2a6%2a9%2Bc%7C000000%0A%23+%2C%2C%2C%2C%2C%2C%2C%2C%400%3E00000000%5C%23%22biscuits%22aetteews%22&warnings=0) `rolls`
Relevent line of code:
```
#s[\g\r\a \v\y)w.q)\r\o\l\l\ssp00/;oooooooo'stuffing;oooooo~'`turkey'
#s[\g\r\a \v\y)w.q) - effectively a comment because # doesn't do anything with an empty stack
\r\o\l\l\ss - sum("r", "o", "l", "l", "s")
p - print(^)
00/ - raise a ZeroDivisionError to stop running code
```
---
Pyth: [Try it here!](http://pyth.herokuapp.com/?code=%23%5C+s%5B%5Cg%5Cr%5Ca%5Cv%5Cy%29w.q%29%5Cr%5Co%5Cl%5Cl%5Cssp00%2F%3Boooooooo%27stuffing%3Boooooo%7E%27%60turkey%27%0Aprint%27corn%27%23%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%5D%2B%5B---------%3E%2B%2B%3C%5D%3E%2Bw.q%2B%2B%5B-%3E%2B%2B%2B%3C%5D%3E%2B%2Bw.q%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2Bw.q-----------w.q----------------%3B%29%29%21%2Bf%27%21n%27%21i%27%21s%27%21s%27%21e%27%21r%27%21d%27%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29L%0A%27bread%27%23%29%29%29%5C%C3%A9%27i%27n%27o%27r%27a%2B%2B%2B%2B%2B%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%5C%E2%99%801X%27c%27a%27m%2B%2B%2B%2B%27e%27s%27e%27e%27h%27c%27d%27n%27a%2B%2B%2B%2B%2B%2B%2B%2B%29%2B.%26%5C%EF%BF%BD0%5C%C3%B3%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%0A%23%5C25%2a8%2a0%2Bc25%2a6%2a9%2Bc25%2a6%2a7%2Bc25%2a6%2a5%2Bc25%2a7%2a8%2Bc25%2a8%2a0%2Bc25%2a7%2a3%2Bc25%2a6%2a9%2Bc%7C000000000%0A%23+%2C%2C%2C%2C%2C%2C%2C%2C%400%3E00000000%5C%23%22biscuits%22aetteews%22&debug=0) `gravy`
Relevent line of code:
```
#s[\g\r\a \v\y)w.q)\r\o\l\l\ssp00/;oooooooo'stuffing;oooooo~'`turkey'
#...) - while True:
s[\g\r\a \v\y) - sum(["g", "r", "a", "v", "y"])
w - input()
.q - quit
```
All the `)`'s are for Pyth to make it compile without erroring on no input.
---
Python 2: `corn`
Line 1 is a whole comment
Line 2 prints "corn" and then has a comment
Line 3 has a string literal and then a comment
Line 4 onwards are comments
---
Foo: [Try It Online!](http://foo.tryitonline.net/#code=I1wgc1tcZ1xyXGFcdlx5KXcucSlcclxvXGxcbFxzc3AwMC87b29vb29vb28nc3R1ZmZpbmc7b29vb29vfidgdHVya2V5JwpwcmludCdjb3JuJyMpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSldK1stLS0tLS0tLS0-Kys8XT4rdy5xKytbLT4rKys8XT4rK3cucSsrKysrKysrKysrdy5xLS0tLS0tLS0tLS13LnEtLS0tLS0tLS0tLS0tLS0tOykpIStmJyFuJyFpJyFzJyFzJyFlJyFyJyFkJykpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSlMCidicmVhZCcjKSkpXMOpJ2knbidvJ3InYSsrKysrKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpXOKZgDFYJ2MnYSdtKysrKydlJ3MnZSdlJ2gnYydkJ24nYSsrKysrKysrKSsuJlzvv70wXMOzKSkpKSkpKSkpKSkpKSkpKSkpCiNcMjUqOCowK2MyNSo2KjkrYzI1KjYqNytjMjUqNio1K2MyNSo3KjgrYzI1KjgqMCtjMjUqNyozK2MyNSo2KjkrY3wwMDAwMDAwMDAKIyAsLCwsLCwsLEAwPjAwMDAwMDAwXCMiYmlzY3VpdHMiYWV0dGVld3Mi&input=) `biscuits`
Foo prints out anything enclosed in double quotes (`"`). In this case I was careful to only include languages that could cope with other forms of string input (Special case for Befunge). If there was any text after the final `"`, that would be printed too.
---
Brain\*\*\*\*: [Try It Online!](http://brainfuck.tryitonline.net/#code=I1wgc1tcZ1xyXGFcdlx5KXcucSlcclxvXGxcbFxzc3AwMC87b29vb29vb28nc3R1ZmZpbmc7b29vb29vfidgdHVya2V5JwpwcmludCdjb3JuJyMpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSldK1stLS0tLS0tLS0-Kys8XT4rdy5xKytbLT4rKys8XT4rK3cucSsrKysrKysrKysrdy5xLS0tLS0tLS0tLS13LnEtLS0tLS0tLS0tLS0tLS0tOykpIStmJyFuJyFpJyFzJyFzJyFlJyFyJyFkJykpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSlMCidicmVhZCcjKSkpXMOpJ2knbidvJ3InYSsrKysrKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpXOKZgDFYJ2MnYSdtKysrKydlJ3MnZSdlJ2gnYydkJ24nYSsrKysrKysrKSsuJlzvv70wXMOzKSkpKSkpKSkpKSkpKSkpKSkpCiNcMjUqOCowK2MyNSo2KjkrYzI1KjYqNytjMjUqNio1K2MyNSo3KjgrYzI1KjgqMCtjMjUqNyozK2MyNSo2KjkrY3wwMDAwMDAwMDAKIyAsLCwsLCwsLEAwPjAwMDAwMDAwXCMiYmlzY3VpdHMiYWV0dGVld3Mi&input=) `salad`
I copied the output of constant string generator. I had to escape all `.` characters with `.q` so it would play with Pyth and `w.` so it would play with Pyke. I added some extra `-` characters so the cells would get to the right points before printing at another `.` character in the 3rd line
---
GolfScript: [Try It Online!](http://golfscript.tryitonline.net/#code=I1wgc1tcZ1xyXGFcdlx5KXcucSlcclxvXGxcbFxzc3AwMC87b29vb29vb28nc3R1ZmZpbmc7b29vb29vfidgdHVya2V5JwpwcmludCdjb3JuJyMpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSldK1stLS0tLS0tLS0-Kys8XT4rdy5xKytbLT4rKys8XT4rK3cucSsrKysrKysrKysrdy5xLS0tLS0tLS0tLS13LnEtLS0tLS0tLS0tLS0tLS0tOykpIStmJyFuJyFpJyFzJyFzJyFlJyFyJyFkJykpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSlMCidicmVhZCcjKSkpXMOpJ2knbidvJ3InYSsrKysrKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpXOKZgDFYJ2MnYSdtKysrKydlJ3MnZSdlJ2gnYydkJ24nYSsrKysrKysrKSsuJlzvv70wXMOzKSkpKSkpKSkpKSkpKSkpKSkpCiNcMjUqOCowK2MyNSo2KjkrYzI1KjYqNytjMjUqNio1K2MyNSo3KjgrYzI1KjgqMCtjMjUqNyozK2MyNSo2KjkrY3wwMDAwMDAwMDAKIyAsLCwsLCwsLEAwPjAwMDAwMDAwXCMiYmlzY3VpdHMiYWV0dGVld3Mi&input=) `cornbread`
In GolfScript, `#` is a comment until end of line.
What GolfScript interpreter sees:
```
#comment
print'corn'#comment
'bread'#comment
```
In GolfScript, for whatever reason, `print` takes a string and prints it without a newline. Just having `bread` is enough to print it as well.
---
Actually: [Try It Online!](http://actually.tryitonline.net/#code=I1wgc1tcZ1xyXGFcdlx5KXcucSlcclxvXGxcbFxzc3AwMC87b29vb29vb28nc3R1ZmZpbmc7b29vb29vfidgdHVya2V5JwpwcmludCdjb3JuJyMpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSldK1stLS0tLS0tLS0-Kys8XT4rdy5xKytbLT4rKys8XT4rK3cucSsrKysrKysrKysrdy5xLS0tLS0tLS0tLS13LnEtLS0tLS0tLS0tLS0tLS0tOykpIStmJyFuJyFpJyFzJyFzJyFlJyFyJyFkJykpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSlMCidicmVhZCcjKSkpXMOpJ2knbidvJ3InYSsrKysrKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpXOKZgDFYJ2MnYSdtKysrKydlJ3MnZSdlJ2gnYydkJ24nYSsrKysrKysrKSsuJlzvv70wXMOzKSkpKSkpKSkpKSkpKSkpKSkpCiNcMjUqOCowK2MyNSo2KjkrYzI1KjYqNytjMjUqNio1K2MyNSo3KjgrYzI1KjgqMCtjMjUqNyozK2MyNSo2KjkrY3wwMDAwMDAwMDAKIyAsLCwsLCwsLEAwPjAwMDAwMDAwXCMiYmlzY3VpdHMiYWV0dGVld3Mi&input=) `macandcheese`
Relevant line:
```
'bread'#)))\é'i'n'o'r'a+++++))))))))))))))))))))))))))))))))))))))))))))))))\♀1X'c'a'm++++'e's'e'e'h'c'd'n'a++++++++)+.&\�0\ó))))))))))))))))))
é - clears the stack of whatever junk was on it before.
'i'n'o'r'a+++++ - create string "aroni"
) - rotate entire stack (effectively comments as stack is only 1 long)
♀1X - pop stack (now empty)
'c'a'm++++ - constructs the string "mac"
'e's'e'e'h'c'd'n'a++++++++ - constructs the string "andcheese"
) - rotate stack (reverse)
+ - "mac" + "andcheese"
� - quit
```
---
<><: [Copy+Paste only](https://fishlanguage.com/playground) `turkey`
[![Animation of output](https://i.stack.imgur.com/mFCGI.gif)](https://i.stack.imgur.com/mFCGI.gif)
---
Gol<><: [Try It Online!](https://golfish.herokuapp.com/?code=%23s%5B%5Cs%5Cw%5Ce%5Ce%5Ct%5Cp%5Co%5Ct%5Ca%5Ct%5Co%5Cp%5Ci%5Ce%29w.q%22biscuits%22%29%5Cr%5Co%5Cl%5Cl%5Cssp00%2F%3Boooooooo%27stuffing%3Boooooo%7e%27%60turkey%27%0Aprint%27corn%27%23%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%5D%2B%5B---------%3E%2B%2B%3C%5D%3E%2Bw.q%2B%2B%5B-%3E%2B%2B%2B%3C%5D%3E%2B%2Bw.q%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2Bw.q-----------w.q%2B%2B%2Bw.q%3B%5Co%3B%0A%27bread%27%23%29%29%29%5C%C3%A9%27i%27n%27o%27r%27a%2B%2B%2B%2B%2B%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%5C%E2%99%801X%27c%27a%27m%2B%2B%2B%2B%27e%27s%27e%27e%27h%27c%27d%27n%27a%2B%2B%2B%2B%2B%2B%2B%2B%29%2B%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29%29&input=&debug=true&symbolic=true) `stuffing`
As <>< except ``` skips the first `'` and only outputs enough characters to print `stuffing`
---
Seriously: [Try It Online!](http://seriously.tryitonline.net/#code=I1wgc1tcZ1xyXGFcdlx5KXcucSlcclxvXGxcbFxzc3AwMC87b29vb29vb28nc3R1ZmZpbmc7b29vb29vfidgdHVya2V5JwpwcmludCdjb3JuJyMpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSldK1stLS0tLS0tLS0-Kys8XT4rdy5xKytbLT4rKys8XT4rK3cucSsrKysrKysrKysrdy5xLS0tLS0tLS0tLS13LnEtLS0tLS0tLS0tLS0tLS0tOykpIStmJyFuJyFpJyFzJyFzJyFlJyFyJyFkJykpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSlMCidicmVhZCcjKSkpXMOpJ2knbidvJ3InYSsrKysrKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpXOKZgDFYJ2MnYSdtKysrKydlJ3MnZSdlJ2gnYydkJ24nYSsrKysrKysrKSsuJlzvv70wXMOzKSkpKSkpKSkpKSkpKSkpKSkpCiNcMjUqOCowK2MyNSo2KjkrYzI1KjYqNytjMjUqNio1K2MyNSo3KjgrYzI1KjgqMCtjMjUqNyozK2MyNSo2KjkrY3wwMDAwMDAwMDAKIyAsLCwsLCwsLEAwPjAwMDAwMDAwXCMiYmlzY3VpdHMiYWV0dGVld3Mi&input=) `macaroniandcheese`
Relevant line:
```
'bread'#)))\é'i'n'o'r'a+++++))))))))))))))))))))))))))))))))))))))))))))))))\♀1X'c'a'm++++'e's'e'e'h'c'd'n'a++++++++)+.&\�0\ó))))))))))))))))))
é - clears the stack of whatever junk was on it before.
'i'n'o'r'a+++++ - create string "aroni"
) - rotate entire stack (effectively comments as stack is only 1 long)
♀1X - no-op
'c'a'm++++ - constructs the string "mac" + "aroni"
'e's'e'e'h'c'd'n'a++++++++ - constructs the string "andcheese"
) - rotate stack (reverse)
+ - "macaroni" + "andcheese"
. - print stack
0\ó - exit
```
---
Befunge: [Try It Online!](http://befunge.tryitonline.net/#code=I1wgc1tcZ1xyXGFcdlx5KXcucSlcclxvXGxcbFxzc3AwMC87b29vb29vb28nc3R1ZmZpbmc7b29vb29vfidgdHVya2V5JwpwcmludCdjb3JuJyMpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSldK1stLS0tLS0tLS0-Kys8XT4rdy5xKytbLT4rKys8XT4rK3cucSsrKysrKysrKysrdy5xLS0tLS0tLS0tLS13LnEtLS0tLS0tLS0tLS0tLS0tOykpIStmJyFuJyFpJyFzJyFzJyFlJyFyJyFkJykpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSlMCidicmVhZCcjKSkpXMOpJ2knbidvJ3InYSsrKysrKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpXOKZgDFYJ2MnYSdtKysrKydlJ3MnZSdlJ2gnYydkJ24nYSsrKysrKysrKSsuJlzvv70wXMOzKSkpKSkpKSkpKSkpKSkpKSkpCiNcMjUqOCowK2MyNSo2KjkrYzI1KjYqNytjMjUqNio1K2MyNSo3KjgrYzI1KjgqMCtjMjUqNyozK2MyNSo2KjkrY3wwMDAwMDAwMDAKIyAsLCwsLCwsLEAwPjAwMDAwMDAwXCMiYmlzY3VpdHMiYWV0dGVld3Mi&input=) `sweettea`
Code that is looked at
```
#s[\g\r\a \v - |
) - | - Directing the stack pointer to the correct place
é - |
# ,,,,,,,,@0>00000000\#"biscuits"aetteews"
> - change direction of travel
00000000\#"biscuits - a load of no-ops `#` skips the opening `"`
"aetteews" - add the chars to the stack in reverse order
,,,,,,,,@ - output 8 chars from the stack and exit.
```
---
Fission: [Try It Online!](http://fission.tryitonline.net/#code=I1wgc1tcZ1xyXGFcdlx5KXcucSlcclxvXGxcbFxzc3AwMC87b29vb29vb28nc3R1ZmZpbmc7b29vb29vfidgdHVya2V5JwpwcmludCdjb3JuJyMpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSldK1stLS0tLS0tLS0-Kys8XT4rdy5xKytbLT4rKys8XT4rK3cucSsrKysrKysrKysrdy5xLS0tLS0tLS0tLS13LnEtLS0tLS0tLS0tLS0tLS0tOykpIStmJyFuJyFpJyFzJyFzJyFlJyFyJyFkJykpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSlMCidicmVhZCcjKSkpXMOpJ2knbidvJ3InYSsrKysrKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpXOKZgDFYJ2MnYSdtKysrKydlJ3MnZSdlJ2gnYydkJ24nYSsrKysrKysrKSsuJlzvv70wXMOzKSkpKSkpKSkpKSkpKSkpKSkpCiNcMjUqOCowK2MyNSo2KjkrYzI1KjYqNytjMjUqNio1K2MyNSo3KjgrYzI1KjgqMCtjMjUqNyozK2MyNSo2KjkrY3wwMDAwMDAwMDAKIyAsLCwsLCwsLEAwPjAwMDAwMDAwXCMiYmlzY3VpdHMiYWV0dGVld3Mi&input=) `dressing`
Code looked at:
```
;))!+f'!n'!i'!s'!s'!e'!r'!d'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))L
```
Of which are used:
```
;!+f'!n'!i'!s'!s'!e'!r'!d'L
L - start an atom going left
!d' - create the character `d` and print it
...
; - exit
```
---
[Haystack (2015)](https://github.com/kade-robertson/haystack): `PECANPIE` (with EXTRA newlines!)
```
#\
r
b
\25*8*0+c25*6*9+c25*6*7+c25*6*5+c25*7*8+c25*8*0+c25*7*3+c25*6*9+c
```
Of which do something functional:
```
25*8*0+c25*6*9+c25*6*7+c25*6*5+c25*7*8+c25*8*0+c25*7*3+c25*6*9+c
```
I construct each upper case ascii codepoint for the letters in `PECANPIE` in uppercase because they're all below 100. I then print them all out as characters.
[Answer]
# [CJam](https://sourceforge.net/projects/cjam/), [05AB1E](https://github.com/Adriandmen/05AB1E), [Dip](https://github.com/mcparadip/Dip), [V](https://github.com/DJMcMayhem/V), 4 languages, ~~36~~ 34 bytes
*2 bytes saved thanks to @DrMcMoylex!*
```
"turkey"e#"corn"??"gravy"p&Ssalad
```
Original 36 byte code:
```
"turkey"e#"corn"??"gravy"p&ddisalad
```
After the `&` and before the `d` there is an `<ESC>`, which is 1 byte. So the code with the zero-width characters revealed looks like this:
```
"turkey"e#"corn"??"gravy"p&Ssalad
```
### CJam
(`<ESC>` is not shown)
```
"turkey"e#"corn"??"gravy"p&Ssalad
"turkey" e# push this string
e#"corn"??"gravy"p&Ssalad e# comment
e# implicit output
```
[Try it online!](http://cjam.tryitonline.net/#code=InR1cmtleSJlIyJjb3JuIj8_ImdyYXZ5InAmG1NzYWxhZA&input=) outputs `turkey`
### 05AB1E
(`<ESC>` is not shown)
```
"turkey"e#"corn"??"gravy"p&Ssalad
"turkey" # push this string
# STACK: ["turkey"]
e # calculates nPr for the last two values in the stack
# since there is only one value, this evaluates to nothing
# as a result, "turkey" is popped
# STACK: []
# # if true end, since this is false, the program doesn't end
"corn"? # push this string and print it without newlines
# STACK: []
? # prints nothing, since there is nothing in stack
"gravy"p&Ssalad # nothing happens here since the stack is already printed using a command and there is NO implicit print now, I think
```
[Try it online!](http://05ab1e.tryitonline.net/#code=InR1cmtleSJlIyJjb3JuIj8_ImdyYXZ5InAmG1NzYWxhZA&input=) outputs: `corn`
### V
(`<ESC>` is shown)
```
"turkey"e#"corn"??"gravy"p&<ESC>Ssalad
"turkey"e#"corn"??"gravy"p& Code that writes a newline followed by `rn"??"gravy"p&Ssalad`
<ESC> Enters normal mode
S Deletes line and enters insert mode
salad Writes salad
```
[Try it online!](http://v.tryitonline.net/#code=InR1cmtleSJlIyJjb3JuIj8_ImdyYXZ5InAmG1NzYWxhZA&input=) outputs a newline followed by `salad`
### Dip
(`<ESC>` is not shown)
```
"turkey"e#"corn"??"gravy"p&Ssalad
"turkey" push this string
STACK: ["turkey"]
e not in the language's database
# push str("turkey") --> "turkey"
STACK: ["turkey"]
"corn" push this string
STACK: ["turkey","corn"]
? pop "corn", if it is the boolean True (which it isn't) execute the following,
but since it is false, nothing until the next ? gets executed
STACK: ["turkey"]
? if-statement end
STACK: ["turkey"]
"gravy" push this string
STACK: ["turkey","gravy"]
p& print turkey and end program
Ssalad irrelevant since program has ended
```
Outputs `gravy`
>
> Note: You cannot run `python3 dip.py` and then type in code for this due to the Escape character literal. It appears as `^[`, which makes the Dip interpreter get confused and it thinks that `[` is a command, and it results in an error.
>
>
>
The best way to run this is to edit the source file, change the last line in `dip.py`
```
main(input(">>> "), stack.Stack())
```
to
```
main("\"turkey\"e#\"corn\"??\"gravy\"p&Ssalad", stack.Stack())
exit()
```
Be sure to include the escape character literal!. Now the code as it is is passed into the interpreter so that it can understand it (`"` have to be escaped like `\"` so). Now if you run it from the command-line, it interprets the actual code and outputs `gravy`.
[Answer]
# [MATL](https://github.com/lmendo/MATL) / [Golfscript](http://www.golfscript.com/golfscript/) / [05AB1E](https://github.com/Adriandmen/05AB1E) / [CJam](https://sourceforge.net/projects/cjam/): 4 languages, ~~34~~ 33 bytes
```
'TURKEY'%"rolls"#];"corn""bread"s
```
* In MATL this [outputs](http://matl.tryitonline.net/#code=J1RVUktFWSclInJvbGxzIiNdOyJjb3JuIiJicmVhZCJz&input=) `TURKEY`.
* In Golfscript it [outputs](http://golfscript.tryitonline.net/#code=J1RVUktFWSclInJvbGxzIiNdOyJjb3JuIiJicmVhZCJz&input=) `rolls`.
* In 05AB1E it [outputs](http://05ab1e.tryitonline.net/#code=J1RVUktFWSclInJvbGxzIiNdOyJjb3JuIiJicmVhZCJz&input=) `corn`.
* In CJam it [outputs](http://cjam.tryitonline.net/#code=J1RVUktFWSclInJvbGxzIiNdOyJjb3JuIiJicmVhZCJz&input=) `cornbread`.
[Answer]
# ferNANDo / ><> / Gol><> / 05AB1E / 2sable, 5 languages, 178 bytes
```
!v"`"v"!
<;ooooo"salad"
"<;oooooooo"dressing
1 0
0 1 1 1 0 1 0 0
0 1 1 1 0 1 0 1
0 1 1 1 0 0 1 0
0 1 1 0 1 0 1 1
0 1 1 0 0 1 0 1
0 1 1 1 1 0 0 1
")\"corn""ab"û"aba"Qi"rolls"
```
* [ferNANDo](http://fernando.tryitonline.net/#code=IXYiYCJ2IiEKICAgICA8O29vb29vInNhbGFkIgoiPDtvb29vb29vbyJkcmVzc2luZwoxIDAKMCAxIDEgMSAwIDEgMCAwCjAgMSAxIDEgMCAxIDAgMQowIDEgMSAxIDAgMCAxIDAKMCAxIDEgMCAxIDAgMSAxCjAgMSAxIDAgMCAxIDAgMQowIDEgMSAxIDEgMCAwIDEKIilcImNvcm4iImFiIsO7ImFiYSJRaSJyb2xscyI&input=): `turkey`
* [><>](https://fishlanguage.com/playground): `salad`
* [Gol><>](https://golfish.herokuapp.com/?code=%21v%22%60%22v%22%21%0A%20%20%20%20%20%3C%3Booooo%22salad%22%0A%22%3C%3Boooooooo%22dressing%0A1%200%0A0%201%201%201%200%201%200%200%0A0%201%201%201%200%201%200%201%0A0%201%201%201%200%200%201%200%0A0%201%201%200%201%200%201%201%0A0%201%201%200%200%201%200%201%0A0%201%201%201%201%200%200%201%0A%22%29%5C%22corn%22%22ab%22%C3%BB%22aba%22Qi%22rolls%22&input=): `dressing`
* [05AB1E](http://05ab1e.tryitonline.net/#code=IXYiYCJ2IiEKICAgICA8O29vb29vInNhbGFkIgoiPDtvb29vb29vbyJkcmVzc2luZwoxIDAKMCAxIDEgMSAwIDEgMCAwCjAgMSAxIDEgMCAxIDAgMQowIDEgMSAxIDAgMCAxIDAKMCAxIDEgMCAxIDAgMSAxCjAgMSAxIDAgMCAxIDAgMQowIDEgMSAxIDEgMCAwIDEKIilcImNvcm4iImFiIsO7ImFiYSJRaSJyb2xscyI&input=): `rolls`
* [2sable](http://2sable.tryitonline.net/#code=IXYiYCJ2IiEKICAgICA8O29vb29vInNhbGFkIgoiPDtvb29vb29vbyJkcmVzc2luZwoxIDAKMCAxIDEgMSAwIDEgMCAwCjAgMSAxIDEgMCAxIDAgMQowIDEgMSAxIDAgMCAxIDAKMCAxIDEgMCAxIDAgMSAxCjAgMSAxIDAgMCAxIDAgMQowIDEgMSAxIDEgMCAwIDEKIilcImNvcm4iImFiIsO7ImFiYSJRaSJyb2xscyI&input=): `corn`
[Answer]
# C, sh, Python 3, Nim, Julia, Brainf\*\*k -- 6 languages, ~~211~~ 209 bytes
```
#define println(x) main(){puts("turkey");}/*
#[
#=
a=''''
echo gravy
'''
println=lambda x:print("biscuits")
# ]#proc println[T](s:T)=echo"rolls"#--[----->+<]>---.++++++++++++.+++.----.
# =##*/
println("salad")
```
Languages to menu items:
* C outputs `turkey`
* sh outputs `gravy`
* Python 3 outputs `biscuits`
* Nim outputs `rolls`
* Julia outputs `salad`
* Brainf\*\*k outputs `corn`
*Added Julia thanks to @kvill!*
[Answer]
# [Befunge-98](http://esolangs.org/wiki/Befunge), [><>](http://esolangs.org/wiki/Fish), [V](https://github.com/DJMcMayhem/V), Python 2, [05AB1E](https://github.com/Adriandmen/05AB1E), [Gol><>](https://github.com/Sp3000/Golfish), [Foo](http://esolangs.org/wiki/Foo), [Haystack (the 2015 version)](https://github.com/kade-robertson/haystack), [GolfScript](http://www.golfscript.com/golfscript/index.html), BF, [Fission](http://esolangs.org/wiki/Fission), [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), [Seriously](https://github.com/Mego/Seriously/tree/v1), [Axo](https://esolangs.org/wiki/Axo): 14 languages, 381 bytes
### **This is a collaborative answer with [BlueEyedBeast](https://codegolf.stackexchange.com/users/32686/blueeyedbeast)**
I decided to do a 2D approach to this question... Yes, there are **7** 2D esolangs!
I have taken inspiration for additional languages to add by BlueEyedBeast's answer (Foo, GolfScript)
`<ESC>` is the character literal for [Escape](http://www.fileformat.info/info/unicode/char/1b/index.htm).
```
#>!>\'n\'r\'o\'c\,,,,,@'s'a'l'a'dJ,é'g'n+'i+'s+'s+'e+'r+'d+.ó[-]+[----->+++<]>.+++++++++++.+++[->+++<]>++.+[--->+<]>.+++H'turkey'~;oooooooo'sweettea.0-5++++++++fffffffff''`'
# >99*d1+c3-c89*4+dcc99*2+c!|$l9D3-O93++dOO8+O1+O1-O5+OO1+O95++O.
# >'p'()'u'()'m'()'p'()'k'()'i'()'n'()'p'()'i'()'e'()\
print'biscuits';'pecanpie'#"stuffing"R'c!'o!'r!'n!'b!'r!'e!'a!'d!*<ESC>ddddddSapplepie
```
### Befunge-98
```
#?!> nothing important
'n push 'n'
STACK: [110]
\ swap top two stack values (TBH, I'm not really sure what happens in this case)
STACK: [110, 0]
'r\'o\'c\ repeat the same for other characters
STACK: [110 114 111 99 0]
,,,,, output the next 5 top stack values, "corn"
@ end program
rest of the code is irrelevant
since program has already stopped
```
[Try it online!](https://tio.run/nexus/befunge-98#RYzNSsNAFIX3fQU3mVY4mtsEayw0VIILF@JmoC6TgunMpAyNk5AfRBDfx7WP0AerM6HRjzuHe@69c06zhCUZTIYmQ5VBZHPHA1rkKO2Tz/PjN/YwBE1oh1KEhiApPP6kwZbSwJEQ0f02Cekf16fjwtl0uDtfPaHrm4P6wNe6OoP2XamuU3l4EyzHlGIEeMVk5nleEse@XJCIArGK/TuSQtjJLQn2eVnGj1HA44hIcr4ivrAV8CVx18U2lIc2I0GNq2v0Tt6cDPbgRDsxf7PBKivZpG606bDTreh112KNWonc1FphNm27vii02U83EAwVQ8NgGHZDoxhyBsn8Cznwktd1qezH0@kX) outputs `corn`
### ><>
Commands are shown in the order they appear
```
enter from the left, direction = right
# mirror, now the direction will change to left
and it wraps around and comes to the right
and reads code from the right to the left
'`' push this
' ... 5-0.aetteews' push this too
oooooooo outputs the top 5 characters of the stack
; end program
```
[Try it online!](https://fishlanguage.com/playground) (Copy and Paste only) outputs `sweettea`
### V
```
...<ESC> writes stuff over three lines and enters normal mode
ddddddS deletes 3 lines, delete another line and enter insert mode
applepie writes "applepie"
```
[Try it online!](https://tio.run/nexus/v#RYzNSsNAFIX3fQU3mVY4mtsEayw0VIILF@JmoC6TgunMpAyNk5AfRBDfx7WP0AerM6HRjzuHe@69c06zhCUZTIYmQ5VBZHPHA1rkKO2Tz/PjN/YwBE1oh1KEhiApPP6kwZbSwJEQ0f02Cekf16fjwtl0uDtfPaHrm4P6wNe6OoP2XamuU3l4EyzHlGIEeMVk5nleEse@XJCIArGK/TuSQtjJLQn2eVnGj1HA44hIcr4ivrAV8CVx18U2lIc2I0GNq2v0Tt6cDPbgRDsxf7PBKivZpG606bDTreh112KNWonc1FphNm27vii02U83EAwVQ8NgGHZDoxhyBsn8Cznwktd1qezH0@kX "V – TIO Nexus") outputs `applepie` (it might take ˜20 seconds for it to run)
### Python 2
```
# first two lines are comments
print"biscuits"; # prints "biscuits" and ends statement
'pecanpie' # dangling (and ignored) string literal
```
[Try it online!](https://repl.it/languages/python) (Copy and Paste only) outputs `biscuits`
### 05AB1E
```
#>!> # does nothing important
\'n\ # push 'n' and delete it
'r\'o\'c\ # repeat for other characters
,,,,, # prints 5 times (since there is nothing in stack,
# prints nothing)
@ # push the index of the top of stack
's'a'l'a'd # push these characters
J, # join them and print them out
# the rest of the code does not matter
# since there is no implicit print
# because we used the print statement
```
[Try it online!](http://05ab1e.tryitonline.net/#code=Iz4hPlwnblwnclwnb1wnY1wsLCwsLEAncydhJ2wnYSdkSizDqSdnJ24rJ2krJ3MrJ3MrJ2UrJ3IrJ2QrLsOzWy1dK1stLS0tLT4rKys8XT4uKysrKysrKysrKysuKysrWy0-KysrPF0-KysuK1stLS0-KzxdPi4rKytIJ3R1cmtleSd-O29vb29vb29vJ3N3ZWV0dGVhLjAtNSsrKysrKysrZmZmZmZmZmZmJydgJwojICAgPjk5KmQxK2MzLWM4OSo0K2RjYzk5KjIrYyF8JGw5RDMtTzkzKytkT084K08xK08xLU81K09PMStPOTUrK08uCiMgPidwJygpJ3UnKCknbScoKSdwJygpJ2snKCknaScoKSduJygpJ3AnKCknaScoKSdlJygpXApwcmludCdiaXNjdWl0cyc7J3BlY2FucGllJyMic3R1ZmZpbmciUidjISdvISdyISduISdiISdyISdlISdhISdkISobZGRkZGRkU2FwcGxlcGll&input=&debug=on) outputs `salad`
### Gol><>
Commands are shown in the order they appear
```
enter from the left, direction = right
# mirror, now the direction changes to left
and it wraps around and comes to the right
and reads code from the right to the left
' starting parsing strings
` escape next character
' gets escaped
" stop string parsing
fffffffff pushes 15, 8 times
++++++++ adds up the numbers, resulting in 135
5- subtract 4 from it, 130
0 pushes 0
0 jumps to (130, 0)
#\'n\'r\'o\'c\,,,,,@'r'o'l'l'sJ, ... H'turkey'~;oooooooo"sweettea.0-5++++++++fffffffff""`"
^
we are here now
˜ removes value at top of stack, '"'
"yekrut" push this string
H Output stack as characters and halt program
```
[Try it online!](https://golfish.herokuapp.com/?code=%23%3E%21%3E%5C'n%5C'r%5C'o%5C'c%5C%2C%2C%2C%2C%2C%40's'a'l'a'dJ%2C%C3%A9'g'n%2B'i%2B's%2B's%2B'e%2B'r%2B'd%2B.%C3%B3%5B-%5D%2B%5B-----%3E%2B%2B%2B%3C%5D%3E.%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B.%2B%2B%2B%5B-%3E%2B%2B%2B%3C%5D%3E%2B%2B.%2B%5B---%3E%2B%3C%5D%3E.%2B%2B%2BH'turkey'%7e%3Boooooooo'sweettea.0-5%2B%2B%2B%2B%2B%2B%2B%2Bfffffffff''%60'%0A%23%20%20%20%3E99%2ad1%2Bc3-c89%2a4%2Bdcc99%2a2%2Bc%21%7C%24l9D3-O93%2B%2BdOO8%2BO1%2BO1-O5%2BOO1%2BO95%2B%2BO.%0A%23%20%3E'p'%28%29'u'%28%29'm'%28%29'p'%28%29'k'%28%29'i'%28%29'n'%28%29'p'%28%29'i'%28%29'e'%28%29%5C%0Aprint'biscuits'%3B'pecanpie'%23%22stuffing%22R'c%21'o%21'r%21'n%21'b%21'r%21'e%21'a%21'd%21%2a%1BddddddSapplepie&input=) outputs `turkey`
### Foo
Foo outputs anything in double quotes, that is why I have been careful to not use any double quotes in the other languages. Since `"stuffing"` is in double quotes, it will be printed.
[Try it online!](https://tio.run/nexus/foo#RYzNSsNAFIX3fQU3mVY4mtsEayw0VIILF@JmoC6TgunMpAyNk5AfRBDfx7WP0AerM6HRjzuHe@69c06zhCUZTIYmQ5VBZHPHA1rkKO2Tz/PjN/YwBE1oh1KEhiApPP6kwZbSwJEQ0f02Cekf16fjwtl0uDtfPaHrm4P6wNe6OoP2XamuU3l4EyzHlGIEeMVk5nleEse@XJCIArGK/TuSQtjJLQn2eVnGj1HA44hIcr4ivrAV8CVx18U2lIc2I0GNq2v0Tt6cDPbgRDsxf7PBKivZpG606bDTreh112KNWonc1FphNm27vii02U83EAwVQ8NgGHZDoxhyBsn8Cznwktd1qezH0@kX "Foo – TIO Nexus") outputs `stuffing` and then has an error
### Haystack (2015)
This uses Haystack's 2015 (not 2016) interpreter since the newer version is invalid. The interpreter for this is `haystack.py` and **not** `haystack_new.py`
Commands are shown in the order they appear
```
# ignored
\ reflection (now it moves downwards)
> set direction to right
99*d1+c Output 'R'
3-c Output 'O'
89*4+dcc Outputs 'L', newline, 'L'
99*2+c!| Outputs 'S' and ends the program
Note: '!' is ignored by the interpreter
```
This program outputs
```
R
O
L
L
S
```
and a newline after this output (hey, whitespace doesn't matter!)
### GolfScript
```
first 2 lines are comments
print'biscuits'; pushes "biscuits" to the stack and discards it
'pecanpie' push this
#... comment
implicit output
```
[Try it online!](https://tio.run/nexus/golfscript#RYzNSsNAFIX3fQU3mVY4mtsEayw0VIILF@JmoC6TgunMpAyNk5AfRBDfx7WP0AerM6HRjzuHe@69c06zhCUZTIYmQ5VBZHPHA1rkKO2Tz/PjN/YwBE1oh1KEhiApPP6kwZbSwJEQ0f02Cekf16fjwtl0uDtfPaHrm4P6wNe6OoP2XamuU3l4EyzHlGIEeMVk5nleEse@XJCIArGK/TuSQtjJLQn2eVnGj1HA44hIcr4ivrAV8CVx18U2lIc2I0GNq2v0Tt6cDPbgRDsxf7PBKivZpG606bDTreh112KNWonc1FphNm27vii02U83EAwVQ8NgGHZDoxhyBsn8Cznwktd1qezH0@kX "GolfScript – TIO Nexus") outputs `pecanpie`
### BF
I used <https://copy.sh/brainfuck/text.html> to convert text into BF. Although there are a lot of `,` input statements, the BF code runs independent of it.
[Try it online!](https://tio.run/nexus/brainfuck#RYzNSsNAFIX3fQU3mVY4mtsEayw0VIILF@JmoC6TgunMpAyNk5AfRBDfx7WP0AerM6HRjzuHe@69c06zhCUZTIYmQ5VBZHPHA1rkKO2Tz/PjN/YwBE1oh1KEhiApPP6kwZbSwJEQ0f02Cekf16fjwtl0uDtfPaHrm4P6wNe6OoP2XamuU3l4EyzHlGIEeMVk5nleEse@XJCIArGK/TuSQtjJLQn2eVnGj1HA44hIcr4ivrAV8CVx18U2lIc2I0GNq2v0Tt6cDPbgRDsxf7PBKivZpG606bDTreh112KNWonc1FphNm27vii02U83EAwVQ8NgGHZDoxhyBsn8Cznwktd1qezH0@kX "brainfuck – TIO Nexus") outputs `gravy`
### Fission
For a Fission program to begin, an atom has to be spawned. We see this happening the the third line:
```
..."stuffing" Blah blah blah
R Spawns an atom with direction right
'c Gives the atom the mass of 'c''s ASCII value
! Print the atom's mass
'o!'r!'n!'b!'r!'e!'a!'d! Do the same for other characters
* Destroy atom, end program
```
[Try it online!](https://tio.run/nexus/fission#RYzNSsNAFIX3fQU3mVY4mtsEayw0VIILF@JmoC6TgunMpAyNk5AfRBDfx7WP0AerM6HRjzuHe@69c06zhCUZTIYmQ5VBZHPHA1rkKO2Tz/PjN/YwBE1oh1KEhiApPP6kwZbSwJEQ0f02Cekf16fjwtl0uDtfPaHrm4P6wNe6OoP2XamuU3l4EyzHlGIEeMVk5nleEse@XJCIArGK/TuSQtjJLQn2eVnGj1HA44hIcr4ivrAV8CVx18U2lIc2I0GNq2v0Tt6cDPbgRDsxf7PBKivZpG606bDTreh112KNWonc1FphNm27vii02U83EAwVQ8NgGHZDoxhyBsn8Cznwktd1qezH0@kX "Fission – TIO Nexus") outputs `cornbread`
### Minkolang v0.15
```
# Doesn't really do anything
\ Reflect, moves downwards
> Changes direction to right
... !| Does stuff in stack, '!' ignores the '|'
$l9D3 ... ++O Uses ASCII character codes to print "applecider"
. Ends program
```
[Try it online!](https://tio.run/nexus/minkolang#RYzNSsNAFIX3fQU3mVY4mtsEayw0VIILF@JmoC6TgunMpAyNk5AfRBDfx7WP0AerM6HRjzuHe@69c06zhCUZTIYmQ5VBZHPHA1rkKO2Tz/PjN/YwBE1oh1KEhiApPP6kwZbSwJEQ0f02Cekf16fjwtl0uDtfPaHrm4P6wNe6OoP2XamuU3l4EyzHlGIEeMVk5nleEse@XJCIArGK/TuSQtjJLQn2eVnGj1HA44hIcr4ivrAV8CVx18U2lIc2I0GNq2v0Tt6cDPbgRDsxf7PBKivZpG606bDTreh112KNWonc1FphNm27vii02U83EAwVQ8NgGHZDoxhyBsn8Cznwktd1qezH0@kX "Minkolang – TIO Nexus") outputs `applecider`
### Seriously
```
é - clear stack
'g'n+'i+'s+'s+'e+'r+'d+ - load chars onto stack
. - print stack
ó - exit
```
[Try it online!](https://tio.run/nexus/seriously#RYzNSsNAFIX3fQU3mVY4mtsEayw0VIILF@JmoC6TgunMpAyNk5AfRBDfx7WP0AerM6HRjzuHe@69c06zhCUZTIYmQ5VBZHPHA1rkKO2Tz/PjN/YwBE1oh1KEhiApPP6kwZbSwJEQ0f02Cekf16fjwtl0uDtfPaHrm4P6wNe6OoP2XamuU3l4EyzHlGIEeMVk5nleEse@XJCIArGK/TuSQtjJLQn2eVnGj1HA44hIcr4ivrAV8CVx18U2lIc2I0GNq2v0Tt6cDPbgRDsxf7PBKivZpG606bDTreh112KNWonc1FphNm27vii02U83EAwVQ8NgGHZDoxhyBsn8Cznwktd1qezH0@kX "Seriously – TIO Nexus") outputs `dressing`
### Axo
(Commands are shown the order they are encountered)
```
#> blah blah
! rotate direction 90 degrees clockwise
> go right
'p'() push char and output
'u'() ... 'e'() repeat for other characters
\ end program
```
[Try it online!](https://tio.run/nexus/axo#RYzNSsNAFIX3fQU3mVY4mtsEayw0VIILF@JmoC6TgunMpAyNk5AfRBDfx7WP0AerM6HRjzuHe@69c06zhCUZTIYmQ5VBZHPHA1rkKO2Tz/PjN/YwBE1oh1KEhiApPP6kwZbSwJEQ0f02Cekf16fjwtl0uDtfPaHrm4P6wNe6OoP2XamuU3l4EyzHlGIEeMVk5nleEse@XJCIArGK/TuSQtjJLQn2eVnGj1HA44hIcr4ivrAV8CVx18U2lIc2I0GNq2v0Tt6cDPbgRDsxf7PBKivZpG606bDTreh112KNWonc1FphNm27vii02U83EAwVQ8NgGHZDoxhyBsn8Cznwktd1qezH0@kX "axo – TIO Nexus") outputs `pumpkinpie`
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), Python and Brainfuck
This is my first polyglot, so don't go too hard on me...
For those whining about byte count, it's 77 bytes, but that's only relevant for the tiebreaker.
```
"`turkey`"
print('gravy')
#++++++++++[>++++++++++<-]>-.++++++++++++.+++.----.
```
Pushy prints **'turkey'** with a leading newline (as well as a message to `STDERR`):
```
" % Print current stack: just a newline as stack is empty
`turkey` % Push to stack
" % Print the stack: 'turkey'
p % Primality check on 'y' (121): pushes 0
r % Integer root of 0: throws error and exits
```
Python prints **'gravy'**, as the first and last lines are treated as comments.
Brainfuck ignores all other characters and except for those on the final line, which create and print the word **'corn'**.
[Answer]
## [Pip](http://github.com/dloscutoff/pip), [BF](http://esolangs.org/wiki/BF), [oOo CODE](http://esolangs.org/wiki/OOo_CODE), [><>](http://esolangs.org/wiki/Fish), [Befunge-93](http://esolangs.org/wiki/Befunge) ([Quirkster](http://www.quirkster.com/iano/js/befunge.html) implementation), [Ouroboros](http://esolangs.org/wiki/Ouroboros), [///](http://esolangs.org/wiki////): 7 languages, 175 bytes
```
/'//bisCuItS/`f(>-[--[<]>+>-]<.++++++++++++.+++.----.O@,,,,,,"tuRkey"
"saLaD"1/ooooo;1(
>"YVaRg"^(OoooOoOOoooOoooOOoooOOoOooOooOooOOoOooOooOooOOoOOoOoOOoOOoOOoOOo`OO"sTUfFINg"
```
### Pip
[Try it online](http://pip.tryitonline.net/#code=LycvL3R1cmtleS9gQCwsLCwiY29ybiIKLyJ5dmFyZyJsPyE7bzcxLmAic2FsYWQi&input=)
A bunch of expressions that get silently discarded (most of which generate warnings, if warnings are enabled), with the expression `"sTufFINg"` at the end which gets printed.
```
/ '/ / b Invert the string "/" and divide it by nil
i s Two different variables
Cu Chr(nil)
It If 10:
S / `...` OO Invert a Pattern literal and swap it with undefined variable OO
"sTufFINg" Autoprint this last expression
```
### BF
[Try it online](http://brainfuck.tryitonline.net/#code=LycvL3R1cmtleS9gNTEoLS1bLS0tLS0-KzxdPi0tLS4rKysrKysrKysrKysuKysrLi0tLS0uQCwsLCwsInNhbGFkIgoicm9sbHMiMS9vb29vbzsxKAo-Inl2YXJnIl4oYCJzdHVmZmluZyI&input=)
Everything except `>-[--[<]>+>-]<.++++++++++++.+++.----.,,,,` is comments. This code generates `99` (the character code for `c`) via the shortest method listed on [esolangs.org](http://esolangs.org/wiki/Brainfuck_constants#90), then modifies it for `o`, `r`, and `n`. The `,,,,` tries to input four characters, but that doesn't affect anything.
### oOo CODE
Everything except letters is ignored. Grouping the letters into threes, the codes reads like this:
```
bis CuI tSf Otu Rke ysa LaD ooo ooY VaR gOo ... OsT UfF INg
```
and translates to this BF code ([try it](http://retina.tryitonline.net/#code=aWBbXmEtel0KCk0hYC4uLgptYF4KOworYCguKik7KC4pCiQxJDEkMjsKVGBsCi4rCiQuJgpUYGRgXz48W11cLSsuLArCtgo&input=LycvL2Jpc0N1SXRTL2BmKD4tWy0tWzxdPis-LV08LisrKysrKysrKysrKy4rKysuLS0tLS5PQCwsLCwsLCJ0dVJrZXkiCiJzYUxhRCIxL29vb29vOzEoCj4iWVZhUmciXihPb29vT29PT29vb09vb29PT29vb09Pb09vb09vb09vb09Pb09vb09vb09vb09Pb09Pb09vT09vT09vT09vT09vYE9PInNUVWZGSU5nIg) using [Martin's Retina translator](https://codegolf.stackexchange.com/a/74411/16766)):
```
>+[-->+><+[<]>-]>.---.---..+++++++.
```
which [outputs `rolls`](http://brainfuck.tryitonline.net/#code=PitbLS0-Kz48K1s8XT4tXT4uLS0tLi0tLS4uKysrKysrKy4&input=). (And, interestingly enough, is shorter than the above BF for outputting `corn`, even with a `><` no-op added to make the capitalization line up correctly.)
### ><>
[Run ><> code here](https://fishlanguage.com/playground)
The important part of the code:
```
/
/ooooo;
>"YVaRg"^
```
The IP gets reflected upward, wraps around, and gets sent rightward. `"YVaRg"` pushes the character codes of `gRaVY`. `ooooo` outputs five letters and `;` terminates the program.
### Befunge-93
The code depends on undefined behavior and probably only works in [this implementation](http://www.quirkster.com/iano/js/befunge.html).
The important part of the code:
```
/' @,,,,,,"tuRkey"
```
`/` is division. The stack is empty, so the JavaScript implementation I'm using divides `0` by `0` and pushes `NaN`.
`'` is an unrecognized character. The implementation I'm using, conveniently, treats unrecognized characters as Reflect commands. (For a less implementation-dependent version, one possible replacement would be `1_`.) So the IP goes left again, divides `NaN` by `0` (getting `NaN`), and wraps to the other end of the line.
Now `"yekRut"` (moving RTL) pushes the character codes of `tuRkey` and `,,,,,,` outputs them. Finally, `@` terminates the program.
### Ouroboros
[Try it here](http://dloscutoff.github.io/Esolangs/)
Each line of the code is a "snake" that executes independently.
**Snake 1**
Since there are no output instructions, the only important part of the code is `f(`: `f` pushes `15` and `(` swallows that many characters from the end of the snake. The code is now considered to end after `.O`. Execution continues until the end of the snake and loops back to the beginning. Each time through, the snake gets shorter, until eventually the `(` is swallowed. Since the IP just got eaten, the snake halts execution.
**Snake 2**
`"saLaD"` pushes its character codes last-to-first; `1/` divides the charcode of `r` by `1`, leaving it unchanged, and `ooooo` outputs five characters. `;` drops an item (no-op because the stack is already empty). `1(` swallows the instruction pointer and halts.
**Snake 3**
`"YVaRg"` pushes some charcodes; then `(` swallows a number of characters equal to the top of the stack, which happens to be `89`, the character code of `Y`. Eating 89 characters is enough to swallow the IP and halt execution.
### ///
[Try it online](http://pip.tryitonline.net/#code=aTpnSm5mOnthOnhXI2kmJy9ORSBZUE9pYS46eVEnXD9QT2l5YX1XI2lJJ1xRIFlQT2lPUE9pRUl5UScve3A6VmZZMHM6VmZJeVEnL1dwTmkmWXZpUjpYcHsrK3k_cHN9fUUgT3k&input=LycvL3R1cmtleS9gQCwsLCwiY29ybiIKLyJ5dmFyZyJsPyE7bzcxLmAic2FsYWQi&args=LXI) using [my Pip implementation of ///](https://codegolf.stackexchange.com/a/95651/16766)
`/'//` deletes all single quotes from the rest of the program (which does nothing because there aren't any). Next, `bisCuItS` outputs as-is. Finally, the rest of the code is an incomplete substitution--there's only two of the three requisite slashes--so it does nothing.
[Answer]
# Cubix, Pushy, Brainfuck, V, Python 2 - 5 languages, ~~89~~ 85 bytes
My second ever polyglot - not very golfed, but it works:
```
"`turkey`";print'salad'#;"nroc"w!@o;"-[--";;;;{{->+<]>---.---.---..+++++++.␛ddgigravy
```
(note that `␛` represents the literal escape byte, `x1B`)
* Cubix prints `corn`
* Pushy prints `turkey`
* Brainfuck prints `ROLLS`
* V prints `gravy`
* Python prints `salad`
---
## Cubix
[**Test the program online!**](http://ethproductions.github.io/cubix/?code=ImB0dXJrZXlgIjtwcmludCdzYWxhZCcjOyJucm9jInchQG87Ii1bLS0iOzs7O3t7LT4rPF0+LS0tLi0tLS4tLS0uLisrKysrKysuG2RkZ2lncmF2eQ==&input=&speed=20)
Cubix is a language by the challenge author, ETHproductions. The Cubix Interpreter reads the code like this:
```
" ` t u
r k e y
` " ; p
r i n t
' s a l a d ' # ; " n r o c " w
! @ o ; " - [ - - " ; ; ; ; { {
- > + < ] > - - - . - - - . - -
- . . + + + + + + + . d d g i ␛
g r a v
y . . .
. . . .
. . . .
```
The code is executed like so:
* `'salad` - does some irrelevant XOR operations on stack, results in `115, 0, 0`
* `'#;` - push the charcode of `#`, then pop it again (no-op)
* `"nroc"` - push the charcodes for "corn"
* `w` - moves the IP to loop on the next line below:
+ `!@o;` - print and pop last item (terminate if item is 0)
+ `"-[--";;;;` - push these chars and delete them (no-op)
+ `{{` - no-op
---
## Pushy
[**Test the program online!**](https://tio.run/nexus/pushy#@6@UUFJalJ1amaBkXVCUmVeiXpyYk5iirmytlFeUn6xUruiQb62kG62rq2QNBNXVunbaNrF2urq6ejCspw0BetIpKemZ6UWJZZX//wMA)
Pushy is my own language, and it runs the code like this:
```
" \ Print stack. Empty, so prints newline.
`turkey` \ Push this string
" \ Print this string
; \ "End loop": Ignored as there is no loop in progress.
pr \ Irrelevant stack operations
i \ "interrupt": exit program.
```
---
## Brainfuck
[**Test the program online!**](http://brainfuck.tryitonline.net/#code=ImB0dXJrZXlgIjtwcmludCdzYWxhZCcjOyJucm9jInchQG87Ii1bLS0iOzs7O3t7LT4rPF0-LS0tLi0tLS4tLS0uLisrKysrKysuG2RkZ2lncmF2eQ&input=)
Brainfuck ignores all characters that are not in its list of instructions, resulting in:
```
-[--->+<]>---.---.---..+++++++.
```
Which prints `ROLLS`. Note that this requires an interpreter with wrapping cells, such as the one provided.
---
## V (Vim language)
[**Test the program online!**](http://v.tryitonline.net/#code=ImB0dXJrZXlgIjtwcmludCdzYWxhZCcjOyJucm9jInchQG87Ii1bLS0iOzs7O3t7LT4rPF0-LS0tLi0tLS4tLS0uLisrKysrKysuG2RkZ2lncmF2eQ&input=)
V was created by DJMcMayhem, one of our top code-golfers.
V is a program-based version of the text editor Vim. Most characters before the `ESC` get written into the "file", but `␛ddgigravy` deletes all of that and inserts "gravy" instead. The content of the file at the end of the program is printed.
---
## Python 2
[**Test the program online!**](https://tio.run/nexus/python2#@6@UUFJalJ1amaBkXVCUmVeiXpyYk5iirmytlFeUn6xUruiQb62kG62rq2QNBNXVunbaNrF2urq6ejCspw0BetIpKemZ6UWJZZX//wMA)
Python is one of my favorite practical languages. Because `#` is a comment in Python, most of the program is ignored. The code is read like this:
```
"`turkey`"; # Unused string literal
print'salad' # Print statement
#... # Comment (everything else is ignored)
```
---
[Answer]
## Python/QBasic/[Pip](http://github.com/dloscutoff/pip), 3 languages, 41 bytes
More languages possibly TBA.
```
1#print"corn":end
print("turkey");"salad"
```
**Python**
`1` is just an expression that gets discarded. `#` starts a comment. `print("turkey")` does what it says, and `"salad"` is another expression that gets discarded.
**QBasic**
`1#` is a (double-precision) line number. `print"corn"` does what it says. `end` terminates the program. The second line is syntactically valid but never executed.
**Pip**
Most everything is expressions that get discarded. `"corn":e` tries to assign to a literal string, which fails silently (unless warnings are enabled). `"salad"` is the last expression in the program and therefore is printed.
[Answer]
# PHP, JavaScript and BrainF\*ck, 178 Bytes
*First time I've ever tried a Polyglot - not going to lie, I'm in over my head here...*
Golfed:
```
<!DOCTYPE html><html><body><?php echo "turkey";?></body><script>function A(){alert("stuffing");}//`--[----->+<]>-++.+++++++++++.-----------------.-----------.+++.`
</script></html>
```
*(I didn't dare to write a Thanksgiving food in the HTML code and count that as another language...)*
**Explanation:**
The code needs to be saved into a .php file for the PHP and JavaScript parts.
**PHP:**
When ran on a PHP server, the PHP part of the code is read:
```
<?php echo "turkey";?>
```
This outputs:
[![enter image description here](https://i.stack.imgur.com/T1rvo.png)](https://i.stack.imgur.com/T1rvo.png)
**JavaScript:**
You can call the JavaScript `A()` function from the browser console:
```
function A(){alert("stuffing");}
```
This outputs:
[![enter image description here](https://i.stack.imgur.com/tKDY6.png)](https://i.stack.imgur.com/tKDY6.png)
**Brainf\*cK**
The Brainf\*ck part is nicely hidden in the comments in the JavaScript section, so it is ignored by the PHP and JavaScript parts:
```
--[----->+<]>-++.+++++++++++.-----------------.-----------.+++.
```
When the whole file pasted into an [IDE](https://copy.sh/brainfuck/), this outputs:
[![enter image description here](https://i.stack.imgur.com/llcWS.png)](https://i.stack.imgur.com/llcWS.png)
I couldn't have done the Brainf\*ck part without [this](https://copy.sh/brainfuck/text.html) text-to-BF website. I originally got it to generate code for "corn" and then in an attempt to learn something about this crazy language, I converted it to "gravy"...or rather "graVY"...
[Answer]
# Python, Clojure, Javascript, Ruby: 4 languages, 113 bytes
```
1;''''/*
#_(
puts("turkey")
__END__
);'''
1;1//2;'''
1;*/alert("gravy")/*
(print "salad");'''
#_
print "corn";#*/
```
Thanks to @Sp3000 for most of the code. Surprisingly, I didn't even have to do anything to his original, I just had to prepend the Ruby code.
[Answer]
## ///, SQL and JavaScript
```
/*//turkey/\*/select('corn')
--a;function select(){alert('salad')}
```
Same construction as with that other holiday-oriented polyglot:
**///**
```
/*//turkey/../.. Simply prints 'turkey', does no replaces, stops execution because the second /// block is incomplete
```
**SQL**
```
/*//turkey/\*/ //turkey/\ is seen as a block comment
That last \ was added to set apart the following */, completing the block
select('corn') SQL Select statement, yielding 'corn'
--a;... Seen by SQL as a comment, ignored
```
**Javascript**
```
/*//turkey/\*/ //turkey/\ is seen as a block comment
select('corn') Function call to the function 'select', defined below
--a; Decrement a, effectively a NOP
function select(){alert('salad')}
Defines the function select(), giving us 'salad'
```
[Answer]
# Clojure / Common Lisp / PicoLisp, 39 bytes
```
(print(if '()'turkey(if""'rolls'corn)))
```
Lisp family here. `'()` evaluates to true in Clojure so it proceeds to outputing a symbol `turkey`. PicoLisp and Common Lisp goes into false branch; `""` is true in Common Lisp and thus it prints symbol `rolls`, empty string is false in PicoLisp and so it goes to printing `corn` symbol.
Check it online:
<https://ideone.com/OD65LB> - Clojure
<https://ideone.com/M1H5gf> – Common Lisp
<https://ideone.com/B4x3ns> – PicoLisp
[Answer]
## CJam, Underload, ><>, 39 bytes
```
'v;"(Turkey)S";"Gravy""
>'nroC'oooo;";
```
### What CJam sees
* `'v;`: A character literal that is immediately discarded
* `"(Turkey)S";`: A string literal that is immediately discarded
* `"Gravy"`: Pushes the string `Gravy` to the stack
* `"\n'nroC'oooo;";`: A string literal that is immediately discarded.
At the end of execution, the stack is output, which means that "Gravy" is printed.
### What Underload sees
* `'v;"`: Some invalid commands that are ignored
* `(Turkey)S`: Pushes the string "Turkey" and outputs it
* `";"Gr`: Some invalid commands that are ignored
* `a`: This causes a segfault on the TIO interpreter since the stack is empty. Execution is terminated.
### What ><> sees
* `'v;"(Turkey)S";"Gravy""` pushes a bunch of characters to the stack (which are ignored). The IP then wraps back around.
* `v` sends the IP downwards.
* `>'nroC'oooo` pushes the characters in the string "Corn" and outputs them.
* `;` terminates execution. All other characters are ignored.
] |
[Question]
[
GolfScript gets its own way far too often and I feel that a repository of handy hints for golfing in J might help in the fight against the evil empire. What tips do you have for making this already terse language shorter?
For those wanting to learn J, the obvious place to begin is the [jsoftware](http://jsoftware.com/) site and particularly the [vocabulary](http://jsoftware.com/help/dictionary/vocabul.htm), the [Learning J](http://jsoftware.com/help/learning/contents.htm) guide and the [J for C programmers](http://jsoftware.com/help/jforc/contents.htm) guide.
[Answer]
There are a number of subtleties to squeezing out the last few characters in J. For the following, assume that each capital letters is a primitive verb (i.e. I am removing the spaces that would otherwise be required to delimit names).
* When you have a train going, and you need to apply a function atop another partway through, `([:FLGR)` and `(LF@:GR)` have the same number of characters, but `(LF@GR)` saves one. If the frame of G is greater than or equal to the monad rank of F, this is a valid transformation. Notably, all trains have infinite rank, as do `, ,. ,: ~. /: \: [ ]` and most uses of `#` and `|.`.
* If you have to pick strings out of a list, and these strings have no spaces, use `>i{ab`cd`ef`. It's dirty, but it saves characters for each new string you have to deal with, unless you're just pulling single characters, and even then the charlist has to be length 4 to be shorter. What's happening is that undefined names are treated as references to verbs, and when you take the gerunds of those verbs you get a boxed string of the name. Any names that are already defined as having type noun, adverb, or conjunction cannot be used in this fashion, because those names get resolved before ``` can have at them.
* If you're lucky enough to have an expression to work with and not just a tacit verb, it's almost always worth it to assign any bits you reuse to variables, be they nouns, verbs, or adverbs. The parens will sometimes pay themselves back by fitting right into where you had spaces before, and most such definitions are worth it if they're reused even once more.
* Conjunctions like `(FGH)^:(u`v`w)` can be rewritten `u`v`w(FGH^:)`. This works for any length of train, even 1, though you only save anything if this trick removes parens from the right argument. This trick only works when you preload the left operand. (Have no idea what just happened? Look up 'tacit adverbs', and study the [Parsing and Execution](http://www.jsoftware.com/help/dictionary/dicte.htm) section of the J Dictionary.)
* Don't use `a.&i.`, use `u:`! `{&a.` and `3&u:` are equivalent on length, though, and the former might be more useful in a conjunction (depending on the conjunction).
* Things like `(2%~F)` and `(F%2:)` are equivalent in length. This is useful because sometimes, depending on what the rest of your train looks like, you can restructure it with `@` tricks as written in the first point, to save some desperate characters. (And of course, if `F` is `]` and the train is a monad, using `%&2` saves a char, duh.)
* Hook-like trains with `]` or `[` as the leftmost verb, e.g. `(]FGH)`.
+ `]` lets you break up a dyadic application and use the right argument only. (Swap to left with `(]FGH)~`, at a penalty of at least 1 character, maybe more.) Saves a char over `(FGH)@]`, and is very handy in gerunds!
+ `[` in a hook applied monadically allows you to do something for the side effects on the right side, then return the argument again. Most common usage is with `1!:2`, possibly with formatting junk.
* I/O sucks. Speed up the process by making loops out of everything you can. `1!:1` has rank `0`, and both of `1!:2 3` have rank `_ 0`, for example, so utilise this by making arrays of 1s and run `1!:1` directly over them. Note that `".` also has rank 1, so you can usually just put that directly after `1!:1`, too, and not have to attach it via `@` or rank shenanigans.
* It's not easy to find places to put this, but `::` can be useful.
+ `::]^:_` is a particularly powerful combination, for example, that lets you do something dangerous until you can't do it anymore. (Subject to the usual `^:_`-as-a-loop caveats.)
+ This also lets you use `{` on lists that don't have the desired index, because it throws a domain error when that happens. Useful to e.g. take the head of a list only if it exists (try using `::]` to return the empty list, or `::_1:` to return an error code, and so on).
* `]`($:@u)@.v` can usually be made shorter than `u^:v^:_`, especially on definitions of `u` and `v` that can be played around with. A similar case holds for the conditional-like `u^:(1-v)` vs. `]`[[email protected]](/cdn-cgi/l/email-protection)`. Consider your options, especially when you have lots of named verbs floating about. It's also a little more flexible, but remember, if using `$:`, there is a recursion depth that it's easy to bump up against. (Usually something like 1800 iterations?)
[Answer]
**Be wary of using loops.**
While J has looping structures (`for. do. end.`, `while. do. end.` and variations), if you find yourself using them there's a possibility that your algorithm is not playing to J's golfing strengths and that there are character savings to be made.
`^:` the power conjunction is your friend. To execute a verb `x` times:
```
verb^:x
```
If you need the result of each iteration in a list:
```
verb^:(i.x)
```
You can also use `^:` to execute a verb conditionally:
```
+:^:(3<])"0[ 1 2 3 4 5 6
1 2 3 8 10 12
```
Double `+:` if `^:` the item is greater than 3 `3<]` (the `"0` changes the rank of the verb so it works an item at a time).
[Answer]
The most important thing when golfing in J is to not only understand the problem, but to reduce the problem to a series of array transformations. You need to understand this way of thinking to have any success with J code.
For example, a recent challenge asked to solve the *[largest subarray problem](https://codegolf.stackexchange.com/q/3059/134).* The stock algorithm to solve this problem is Kadane's algorithm has the following informal description:
>
> Go through the array and at each position and find the sum of the largest subarray ending here, which is the maximum of 0 or the value at the current index plus the sum of the largest subarray ending at the previous position. Compute the maximum of these subarrays as you go to find the largest subarray in the entire array.
>
>
>
A translation into imperative code is straightforward:
1. let A be the input array.
2. *h* ← *m* ← *i* ← 0.
3. **if** *i* ≥ len(A) **return** *m*.
4. *h* ← max(0, *h* + A[*i*]).
5. *m* ← max(*m*, *h*).
6. *i* ← *i* + 1.
7. **goto** 3.
This algorithms seems complicated for J at a glance as there is an explicit loop that doesn't look like a reduction at first. If you realize what the algorithm is doing you can untangle the individual steps and see that it actually performs two simple array operations:
1. *Scan* through the array to compute the lengths of the largest subarrays ending at each index.
2. *Reduce* these lengths with the max function to find the maximum.
Now these two steps are very easy to implement in J. Here is a translation:
1. `(0 >. +)/\. y , 0` – This step operates from the other end of the array to better fit J's paradigm. `0 >. +` is tacit for `0 >. x + y`.
2. `>./ y`
Put together, we get a very terse implementation of the algorithm:
```
>./ (0 >. +)/\. y , 0
```
If you learn this way of approaching the implementation of algorithms, your solutions will be as terse as this code.
Here are some tricks I accumulated over time. This list will be expanded as I get more knowledge in J golfing.
* Learn the dictionary. It contains a lot of really obscure verbs that don't make any sense until you see how useful they are. For instance, monadic `=` is strange at first but is very useful in ASCII art challenges.
* Use dyadic `&` in tacit contexts when you want a power conjunction. The vocabulary suggests `u@[&0` as a tacit replacement to `4 : 'u^:x y` and so do I.
* In many cases you can avoid a `[:` or `@:` in a sequence like `u@v` by choosing a variant of `u` that has a left argument. For instance, to drop the first item of the result of `v`, use `1}.v` instead of `[:}.v` if `}.@v` isn't possible for some reason.
* `] v` is often shorter than `v@]` if you want to use monadic `v` in a dyadic context. This comes in useful especially when `v` is a long train of verbs.
* Sometimes you can write `m (n v w) y` instead of `(n v m&w) y`. This may make it possible to avoid spaces and parentheses.
* `#\` instead of `>:@i.@#`.
* `u &. v` is useful when `v` has an obverse. When not, you might want to use `[: vinv u & v` or `u & (v :. vinv)` instead.
* Understand rank and how to use it. Try to fiddle around with the rank conjunction until you get something that fits. It helps understanding how rank influences your code.
* `^:_` is extremely useful for algorithms where you want to reach convergence, like a flood-fill or simulations.
* Know your standard library. It contains very useful functions that save you tons of characters.
* The copulæ `=.` and `=:` can be embedded anywhere in a phrase. Use this to make one-liners where tacit notation isn't enough.
* Use monadic `,` instead of multiple reductions when reducing multi-dimensional arrays.
* Understand what phrases are supported by special code when the challenge imposes runtime boundaries. Some useful things operate in O(*n*) instead of O(*n*2) counter-intuitively.
* Boxes are useful for trees.
[Answer]
**Input**
`1!:1[1` will take one line of input terminated by pressing the enter key.
`1!:1[3` will take a number of lines of input (terminated by Ctrl-D on my Mac, Ctrl-C on Windows).
If you're trying to input numbers, using `".` will evaluate the string and return a list of numbers ready to be manipulated. If you're taking in one number but need to operate on the digits individually, `".,.` (thanks to Jan Dvorak's comment for this) or `"."0` will split the string into separate digits:
```
"."0[1!:1[1
12345
1 2 3 4 5
".,.1!:1[1
12345
1 2 3 4 5
```
If you're reading in strings, the shortest way to get a boxed list of separate strings is to use `;:`. This works best for space separated strings:
```
;:1!:1[1
hello world
┌─────┬─────┐
│hello│world│
└─────┴─────┘
```
[Answer]
Consider using [explicit definition](http://www.jsoftware.com/help/phrases/explicit_def.htm) instead of writing a tacit verb; sure the `3 :'` and `'` cost 5 bytes, but you can save a lot of `@`, `@:` and `[:` that way.
[Answer]
## Using iteration to compute sequences
Typically, solving an OEIS sequence challenge will require using one of the formulas given on its page. Some of these adapt well for J, and others not so much. Recursive formulas are straight-forward, however, iteration might not be simple. A pattern I've begun to use is
```
(s(]f)^:[~]) n
] Gets n
s The first value in the sequence
~ Commute the argument order, n is LHS and s is RHS
[ Gets n
^: Nest n times with an initial argument s
(]f) Compute f s
Returns (f^n) s
```
where `s` is the first value in the sequence, `f` is a verb that will compute the next term given the previous term, and `n` is the zero-based index of the term you want to compute. This method relies on the fact that when computing the power of a dyad, the LHS is bound to the dyad to form a new monad, and that monad is nested on the initial value. The dyad given to the power adverb is a hook where `(]f)` is given the index `n` on the LHS and the value of a term in the sequence `s`. The hook will apply `f` on `s` as a monad, and then ignore `n` to return the result of `f s`.
## Standard library
Sometimes, you might find that J will have support for a verb in its [standard library](http://www.jsoftware.com/help/user/library.htm). For example, most of the bitwise integer operations are bound to names which are shorter than using the primitive call.
```
AND =: (17 b.) NB. it is actually '$:/ :(17 b.)'
```
Date and time builtins are also available.
## Ranges
If you have a set of values `[a, b, c]` and you want to form a range based on their product like `[0, 1, 2, ..., a*b*c-1]`, the typical approach would be to find their product and then form a range which might be `[:i.*/` which costs 6 bytes. A shorter way is `,@i.` for 4 bytes since `i.` can form multidimensional arrays while still counting up, and flattening it will produce an equivalent range.
# Printing continuously
A tacit way to print a value and continue to use it without an explicit loop is `([echo)` for a monadic case. `echo` is a verb in the standard library that prints its contents to `stdout` in the same format used in the interpreter. The hook then passes the same input value out using the left `[` verb.
# Base 10 digits of an integer
The standard way of acquiring the base 10 digits of an integer is `10#.inv]` which costs 8 bytes, too much! An alternative is to convert it to a string and parse it at rank 0 `"."0@":` which saves a byte, but an even better way is `,.&.":` which saves another byte making the final cost 6 bytes instead of 8.
[Answer]
# Shorter ways to mess with ranks
Sometimes, you'll have code like `<"0 i.3 3`, where you want to apply a verb `v` at rank `r`. However, if you use a noun (like `0`), you'll often have to include a space. To avoid this, you can use another verb `u` of equivalent rank and use `u"v` instead. For example, since `+` has rank `0 0 0`, we can use `<"+` instead of `<"0`.
Here is a table of all verbs and their ranks (obtainable by using `v b. 0`):
```
0 0 0 > + * - % ^ | ! ? <. <: >. >: +. +: *. *: %: ^. j. o. q: r.
0 _ _ -. -: E. i: p:
1 0 1 p..
1 0 _ { A.
1 1 0 p.
1 1 1 #.
1 1 _ C.
1 _ _ ;: ". i. I.
2 _ 2 %.
_ 0 0 = < ~. ~: {: }: ?. L.
_ 1 0 #:
_ 1 _ $ # |. |: {. }. ": {::
_ _ _ , ; [ ] _: $. $: ,. ,: /: \: [: e. s: u: x: 0:
```
To use this table, find the desired rank `r` on the left hand side, then choose an appropriate verb `v` from the right hand side. E.g., if I need to vectorize a verb `v` at depth `2 _ 2`, then I find that rank on the left and choose `%.` from the right. Then I use `v"%.` instead of `v"2 _ 2`.
[Answer]
# Some (fairly) common tricks I've seen
I'm sharing a few things that have come in handy for me. Basically all of these are tips I've received myself, but I don't have credits for most.
### Sum of a rank one array
Instead of using `+/@:(FGH)` use `(1#.FGH)`. This means debase to base 1, which effectively means summing an array. Although it's longer than `+/`, it doesn't require a cap or composition, which often makes it much shorter than using `+/`.
### Counting trailing truths
If you have a boolean list and you want to count the number of trailing truths, use `#.~`. [See here](https://codegolf.stackexchange.com/a/98765/42833). The [APL answer](https://codegolf.stackexchange.com/a/98764/42833) provides a good explanation for how this works. Granted, this has only been helpful to me twice but I figured I'd share it anyways.
### Under (&.)
Not a specific trick, but just a general suggestion: the adverb `&.`-under often leads to elegant and (more importantly) short solutions. Keep it in mind when you're golfing.
Often times it's useful for [binary](/questions/tagged/binary "show questions tagged 'binary'") and other base conversion challenges, e.g. this code which removes the most significant bit from a number: `}.&.#:` (convert to list of binary digits, remove the first digit, then undo the conversion to a list of binary digits and convert back to decimal). The straightforward solution is two more bytes: `#.@}.@#:`.
Under is also helpful for challenges where you need to work with decimal digits, since you can use `u&.":`. For example, the short way miles gives to split to decimal digits uses under: `,.&.":`.
A final example is finding the magnitude of a vector: `+/&.:*:`, note that you need to collect all of the results from `*:`-square with `&.:`-under since `*:`-square is rank zero.
[Answer]
# Tacit programming
## Basics
### Dyadic verb
```
x (F G H) y == (x F y) G (x H y)
x (F G) y == x F (G y)
x ([: G H) y == G (x H y) NB. G is called monadically
NB. Verbs are grouped from the right by units of 3.
NB. For the following, think like G, I, K are replaced by the results of (x G y) etc.
NB. and then the sentence is run as usual.
x (F G H I J K) y == x (F (G H (I J K))) y
== x F ((x G y) H ((x I y) J (x K y)))
NB. Using conjunctions for dyadic verb
x F@G y == F (x G y) NB. Atop; Same as x ([: F G) y; Consider as golfing alternatives
x F&G y == (G x) F (G y) NB. Compose; G is applied monadically to both arguments
```
### Monadic verb
```
(F G H) y == (F y) G (H y)
(G H) y == y G (H y) NB. Note that this is different from APL
([: G H) y == G (H y)
(F G H I J K) y == (F (G H (I J K))) y
== y F ((G y) H ((I y) J (K y)))
F@G y == F (G y)
```
### Misc
```
x&F y == x F y
F&y x == x F y
y F~ x == x F y
F~ y == y F y
```
## Tricks
### `(F x) G (H y)`
Tacit solution: `(G~F)~H`; depending on the actual verbs, consider rearranging the left and right arguments to remove `~`.
```
x ((G~F)~H) y
x (G~F)~ (H y)
(H y) (G~F) x
(H y) G~ (F x)
(F x) G (H y)
```
### Monadic-Dyadic replacements
```
>:y == 1+y
<:y == 1-~y or _1+y
+:y == 2*y
-.y == 1-y
-:y == 2%~y
*:y == 2^~y
#.y == 2#.y
#.inv y == 2#.inv y NB. #: doesn't work this way
{.y == 0{y
{:y == _1{y
}.y == 1}.y
+/y == 1#.y NB. Vectors only
+/"1 y == 1#.y NB. Higher-dimension arrays
```
[Answer]
# [`strings`](http://www.jsoftware.com/docs/help602/user/script_strings.htm) library: golfing tips
The strings library is vastly helpful for doing anything with string manipulation. Sure, it takes `include'strings'` (which is very costly, considering J), but you may at times reap the benefits.
## `stringreplace`
Find yourself using string replace? Observe that `A stringreplace B` is the same as `B rplc A`.
In fact, this is how `rplc` is implemented:
```
rplc
stringreplace~
```
## `cuts`
The verb `cuts` provides thus:
>
>
> ```
> cut y at x (conjunction)
> string (verb cuts n) text
> n=_1 up to but not including string
> n= 1 up to and including string
> n=_2 after but not including string
> n= 2 after and including string
> ```
>
>
So it's really slicing a string.
[Answer]
### Getting numbers from 0 to 4
If there’s a restriction on using numbers in your code:
**0** `%_`: one divided by infinity.
**1** `#_`: how many infinities?
**2** `#_ _`: two infinities.
**3** `verb`: there’s a built-in.
**4** `dyad`: another built-in.
### Getting numbers from 10 to 35
Base-inifinity literals: **11**:`_bb`, **26**:`_bq` etc.
[Answer]
# Miscellaneous ideas
[Cross-post of my own APL tip](https://codegolf.stackexchange.com/a/205354/78410), because APL and J are so closely related that the two can share many ideas.
## If you're facing `[:-~/`, use `_1#.` instead
A common reason to use `-~/` is to reverse-subtract over a length-2 axis, e.g. given a 2-element array `x y`, compute `y-x`.
If this is the case, `_1#.` is an equivalent expression; just like `2#.x y` computes `2x+y`, `_1#.x y` computes `-x+y`. While `-~/` most likely requires the use of `[:` (capped fork) or `@` (atop), `_1#.` is likely to fit just well in trains as-is.
Note that, if you apply it to longer axis, `_1#.` gives you more similar result to `-/` (alternating sum), with negated result when the length is even.
## Construct a boolean square matrix where the border is ones/zeros and the interior is the opposite
This is mainly for large fixed-size matrices, say 6 by 6.
The matrix
```
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 0 0 0 0 1
1 1 1 1 1 1
```
can be generated by `+./~` -ing the boolean vector `1 0 0 0 0 1`. The shortest known way to generate that vector is `#:33`, so we can get the matrix above in just **8 bytes**:
```
+./~#:33
```
If we're to put this in a train, a constant function `+./~@#:@33` and parenthesized noun left arg `(+./~#:33)` have equal length of **10 bytes**. The two forms have their own pros and cons: the former can be placed at the right end of a train, while the latter may serve better by not messing up with something that comes on its right (e.g. `33e.` is a syntax error).
We can also get negation of it at no extra cost, by swapping `+.` with `+:`! (Remember that J, like APL, has NOR `+:` and NAND `*:`; they are rarely needed, but definitely are a byte saver when we do need them.)
[Answer]
# `&` is your friend, use it wisely
`v` is a verb, `n` is a noun, `x` and `y` are left and right arguments, respectively.
### Monad `&`: Introduce `~` inside adverb/conjunction chain
An adverb/conjunction chain evaluates from the left. So something like `_2&+/\&.>` won't work because it parses like `(_2&+)/\&.>` while we want `_2&(+/\)&.>`. In this case, swapping the left/right of `+/\` can save a byte, as in `+/\~&_2&.>` because this one parses as `((+/\)~)&_2&.>`. To see why this works:
```
+/\~&_2 y
is equivalent to
y +/\~ _2
is equivalent to
_2 +/\ y
is equivalent to
_2&(+/\) y
```
### Dyad `&`: Repeat `x` times
Did you know that [if you give a left argument `x` to `&`, the function applies it `x` times to `y`](https://code.jsoftware.com/wiki/Vocabulary/ampm)? Quite a few challenges ask you to do certain operation `x` times. It is mainly achievable in two ways:
* Use the power operator `^:` without right operand
If the operation is `v`, then `v^:` becomes an adverb train that, when given a left operand, becomes a monadic verb. So `v` is applied to `y`, `x` times.
```
x(v^:)y
is equivalent to
(v^:x)y
```
* Use the dyadic `&` as the outermost conjunction
To use this, you need to identify a constant `n` and a dyadic verb `u`, so that either `n u y` or `y u n` is equivalent to `v`. Then you can write `n&u` or `u&n` to solve the entire task. This form is most effective when the choice of the constant is obvious, e.g. 3 in `3 u:` (convert chars to ASCII values).
Also, `u&n` is slightly preferred over `n&u` when the outermost structure of `u` is a conjunction or adverb (in which case `n&u` should be `n&(u)`; you can do `u~&n` instead).
Note that you can place the dyadic `&` anywhere in a train to achieve repeating arbitrary function to arbitrary argument, in the similar sense to dynamic `^:`.
[Answer]
# `x$y` does something different than you think
Dyadic `$` is called *reshape*. If you're coming from APL, you'd know `⍴` under the same name which lists down all elements of `y` before creating the `x`-shaped array.
J handles it differently: it does not flatten `y`; instead it uses `y`'s items, or major cells, to fill in each cell of the `x`-shaped array. So the resulting shape becomes `x,}.$y`. It doesn't look very useful by this description.
There is one use case where this becomes useful in code golf: when `x` is a positive singleton. Then `x$y` acts like a **take** or **repeated overtake**.
* When `x <: #y` (`x` is smaller than or equal to length of `y`), the result of `x $ y` is exactly same as `x {. y`, directly shaving one byte no matter what. The verb ranks are identical (`1 _`), so the replacement is safe even in a rank-sensitive context (e.g. `@`/`&`).
* When `x > #y`, the result becomes `y` cyclically extended to length `x`. This is different from `x {. y` (which would fill the missing places with zeros/blanks), but it could have its own uses.
Note that, in both cases, the result *is* equivalent to using the individual elements to fill in `x,}.$y`-shaped array.
[Answer]
# Know (and abuse) J's truthy/falsy ([decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'"))
When truthy/falsy is not defined by the language spec, it is defined as the one that is accepted by an `if` statement. Truthy ones are those that make the `if` clause run, and falsy ones are the opposite.
Unlike APL (where only 1/0 are truthy/falsy respectively), J is quite liberal. J's `if.` clause accepts any array, and evaluates to falsy if and only if the array is nonempty and its first atom is a numeric zero. Any other arrays (including empty arrays, character or boxed arrays) are truthy.
Demonstration:
```
f =: 3 : 0
if. 0 do. echo 'yes 0' end.
if. 1 do. echo 'yes 1' end.
if. 2 do. echo 'yes 2' end.
if. 0 1 2 3 4 do. echo 'yes 3' end.
if. 2 0 0 1 3 do. echo 'yes 4' end.
if. 0$0 do. echo 'yes 5' end.
if. 'abcd' do. echo 'yes 6' end.
if. '';'def' do. echo 'yes 7' end.
)
f ''
```
Output:
```
yes 1
yes 2
yes 4
yes 5
yes 6
yes 7
```
`yes 0` and `yes 3` were not printed because the array is nonempty and the first element is zero. Having zeros at any other positions does not affect the truthy/falsy interpretation. [Try it online!](https://tio.run/##ddCxCoNAEITh3qeYQhjSHOudRjD4MMa7I6aIRSqfXo0YWC9x649/YJ/zHNE2cGgg2RANBN/zo0HoHyM4hTeECC9vNlOcmEIZe2KsMrKW7LpdJsYdOrI5l5hSd3L5u1Upw@7ee/6aqza80YfI1NS7uXy@RS4)
] |
[Question]
[
# 4-state barcodes
Many postal services (Royal Mail UK, Canada Post, US Mail, etc) use a 4-state barcode to encode information about their mail. Rendered in ASCII, it may look something like this:
```
| | | | | | | | | |
| | | | | | | | | | | | | | | | |
| | | | | | | |
```
A 4-state barcode is a row of bars. Each bar can be extended upwards, downwards, or both, allowing 4 possibilities. This means that each bar essentially represents a base 4 digit:
```
| |
Bar: | | | |
| |
Digit: 0 1 2 3
```
The problem with this symbology is that it each barcode is a valid, different barcode upside down: drastically changing the meaning if the orientation is incorrect. Therefore, a *start* and *stop* sequence are normally implemented so the scanner can calculate which way it is supposed to be read.
For the purpose of this challenge, we will be using the start/stop sequence specified by Australia Post: **each barcode begins and ends with a `1 0` sequence.**
---
# The Challenge
Your task is to write a program or function which, given a positive integer `N`, converts it to an ASCII 4-state barcode, where each bar (except for the start/stop sequences) represents a digit in the base-4 representation of `N`.
### Example:
Given the integer `19623`, we would first convert it to its base-4 representation, `10302213`.
We would then map each digit to the corresponding bar:
```
1 0 3 0 2 2 1 3
| | | |
| | | | | | | |
| | | |
```
Finally, we would add the start/stop sequences:
```
Start: End:
1 0 1 0
| | | | | |
| | | | | | | | | | | |
| | | |
```
The resulting barcode should be the program's output.
---
# Rules:
* The input will be a positive integer, within the range of your language's standard integer size.
* The output:
+ May be either a list of lines, or a string containing newlines.
+ May contain leading or trailing newlines/spaces, as long as the shape remains intact.
+ Should show the barcode with the above format - it must use the pipe character (`|`) and space character () when drawing bars, and there should be 1 space in between each upright bar.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program (in bytes) wins!
---
# Test Cases
**4095:**
```
| | | | | | | |
| | | | | | | | | |
| | | | | |
```
**4096:**
```
| | |
| | | | | | | | | | |
```
**7313145:**
```
| | | | | | | | | |
| | | | | | | | | | | | | | | |
| | | | | | | |
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~103~~ ~~99~~ 96 bytes
```
def f(i,r=[]):
while i:r=[' | ||||| ||'[i%4::4]]+r;i//=4
k='|| ',' | ';[*map(print,*k,*r,*k)]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI1OnyDY6VtOKS6E8IzMnVSHTCshXV6hRqAEBBSClHp2pamJlZRIbq11knamvb2vCpZBtqw6UVNcBKVS3jtbKTSzQKCjKzCvR0crW0SoCkpqx/9M0DC3NjIw1/wMA "Python 3 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~34~~ ~~30~~ ~~29~~ 28 bytes
```
TFiK_YAyhhH&\EQE+t~vB!P'|'*c
```
[Try it online!](https://tio.run/##y00syfn/P8Qt0zs@0rEyI8NDLcZbS9tDu6SuzEkxQL1GXSv5/39DSzMjYwA)
### Explanation
```
TF % Push array [1 0] (start sequence)
i % Push input
K_YA % Convert to base 4. Gives an array of 4-ary digits
y % Duplicate from below: pushes [1 0] again (stop sequence)
hh % Concatenate horizontally twice. Gives array of 4-ary digits
% including start and stop sequences
H&\ % Two-output modulo 2: pushes array with remainders and array
% with quotients of dividing by 2
EQE % Times 2, plus 1, times 2, element-wise. This effectively
% multiplies each entry by 4 and adds 2
+ % Add element-wise to the array of remainders. The stack now
% contains an array of numbers 2, 3, 6 or 7. Each number
% encodes, in binary form, a column of the output. The
% previous multiplication of the quotients by 4 will have the
% effect of shifting one row down (one binary digit upwards),
% to make room for the central row. The addition of 2 will
% create the central row, which is always full
t~ % Duplicate, logical negate. Gives an array of zeros of the
% same length
v % Concatenate vertically into a 2-row matrix
B % Convert to binary. Gives a matrix, where each row is the
% binary representation of one of the numbers of the input
% matrix, read in column-major order
!P % Transpose, flip vertically
'|'* % Multiply by '|'. This transforms 1 into 124 (ASCII code of
% '|') and leaves 0 as is
c % Convert to char. Char 0 is shown as space. Implicitly display
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 15 bytes
```
4;jƓb|ṃ⁾| ẎZṙ2G
```
[Try it online!](https://tio.run/##ASgA1/9qZWxsef//NDtqxpNifOG5g@KBvnwg4bqOWuG5mTJH//83MzEzMTQ1 "Jelly – Try It Online")
### How it works
```
4;jƓb|ṃ⁾| ẎZṙ2G Main link. No arguments.
4 Set the argument and the return value to 4.
; Concatenate the return value with the argument, yielding [4, 4].
Ɠ Read an integer n from STDIN.
j Join, yielding [4, n, 4].
b Convert 4, n, and 4 to base 4. Note that 4 is [1, 0] in base 4.
| Perform bitwise OR of each resulting quaternary digit and 4.
This pads the binary representation of a digit d to three digits:
[1, d:2, d%2]
ṃ⁾| Convert the results to base " |", i.e., binary where ' '
represents 0 and '|' represents 1.
Ẏ Concatenate the resulting arrays that correspond to 4, n, and 4.
Z Zip; transpose rows and columns.
ṙ2 Rotate 2 units yo the left, correcting the order of [1, d:2, d%2]
to [d%2, 1, d:2].
G Grid; separate columns by spaces, rows by linefeeds.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
;4⁺;b4Fd2Uj€1Zị⁾| G
```
[Try it online!](https://tio.run/##y0rNyan8/9/a5FHjLuskE7cUo9CsR01rDKMe7u5@1LivRsH9////hpZmRsYA "Jelly – Try It Online")
-1 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder).
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~78 77 75 74 70~~ 69 bytes
```
@(x)' |'(dec2bin([2 6 3 7;~(1:4)](:,[2 1 dec2base(x,4)-47 2 1]))-47)'
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0JTXaFGXSMlNdkoKTNPI9pIwUzBWMHcuk7D0MpEM1bDSgcoZKgAlk8sTtWo0DHR1DUxVwAKxmqCWJrq/9M0DC3NjIw1udI0TAwsTaG0GYg2NzY0NjQx1fwPAA "Octave – Try It Online")
Unlike the original approach, this one uses a simple lookup table to map the base-4 values onto their binary equivalent. The lookup table also adds the spacing between each bar by adding a zero in between each number (which maps to a bar of all spaces).
The lookup table directly maps to bars as:
```
base4: 0 1 2 3 -
lookup: 2 6 3 7 0
binary: 0 1 0 1 0
1 1 1 1 0
0 0 1 1 0
```
Conversion from binary to `|` and is now done by indexing into a string of those two characters - basically the same principle as the lookup table for binary conversion.
---
\*Saved 1 byte, thanks @LuisMendo
---
### Original:
```
@(x)['' circshift(dec2bin([a=[5 4 dec2base(x,4)-44 5 4];a*0](:))'*92,1)-4384]
```
[Try it online!](https://tio.run/##HcjRCkAwFADQX9nb7hWLuWSk/Mfaw8yWvVBI/n7k8ZzdXfb2KYxCiDTBg5pz5uLhzjWGCxbv5Bw30HbUDSP2254enpywIGJfmsFmpYEekWdK5tX3dUcmBahUK2tMLw "Octave – Try It Online")
Anonymous function which returns the barcode as a string.
This is based on the fact that if we add 4 to the base4 digits, then we can represent bar/space by the number converted to binary with bits 1 and 2 swapped:
```
base4: 0 1 2 3
add4: 4 5 6 7
binary: 0 1 0 1
0 0 1 1
1 1 1 1
swap 2/1: 0 1 0 1
1 1 1 1
0 0 1 1
```
The tricky bit from a golfing perspective is adding the spaces between the bars and converting from `0/1` to `'|'/' '`.
[Answer]
# JavaScript (ES6), ~~89~~ ~~87~~ 83 bytes
```
n=>`| ${(g=(a,k=n)=>k?g(a,k>>2)+(k&a?'| ':' '):' ')(1)}|
| |${g(~0)}| |
`+g(2)
```
### Test cases
```
let f =
n=>`| ${(g=(a,k=n)=>k?g(a,k>>2)+(k&a?'| ':' '):' ')(1)}|
| |${g(~0)}| |
`+g(2)
console.log(f(4095))
console.log(f(4096))
console.log(f(7313145))
```
### How?
*NB*: In the version below, [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) have been replaced with standard strings so that the code can be indented properly.
```
n => // given the input n
'| ' + // append the top leading pattern
(g = (a, // g is a recursive function taking a = mask
k = n) => // and using k = value, initially set to n
k ? // if k is not zero:
g(a, k >> 2) + // do a recursive call for the next group of 2 bits
(k & a ? '| ' : ' ') // append '| ' if the bit is set or ' ' otherwise
: // else:
' ' // append an extra leading space and stop the recursion
)(1) + // invoke g() with mask = 0b01
'|\n' + // append the top leading pattern and a linefeed
'| |' + // append the middle leading pattern
g(~0) + // invoke g() with all bits set in the mask
'| |\n' + // append the middle trailing pattern and a linefeed
' ' + // append the bottom leading pattern
g(2) // invoke g() with mask = 0b10
```
[Answer]
# [R](https://www.r-project.org/), ~~154~~ 109 bytes
```
function(n,d=c(1,0,n%/%4^floor(log(n,4):0)%%4,1,0),o=c(" ","|"))cat("",o[1+d%%2],"
",o[2+0*d],"
",o[1+(d>1)])
```
[Try it online!](https://tio.run/##NcrBCsIwDIDhu08xAoHERmy2iiCbLyITpKUijAbGvPnutR48/nz/WnM3Hmp@l7i9rFCRNEVS8VLwiOGeF7OVFns2CXzxjBikMYu1DzoQ@ABzfGwEIHZTlxD7WWD3q975ffqHOkpX5ZlrpvOgg4YT1y8 "R – Try It Online")
Saved a whole bunch of bytes by indexing and using `cat` rather than constructing a matrix and using `write`, as well as 6 from a slightly different conversion to base 4. Prints with a leading space in each row and no trailing newlines.
The indexing takes place using some modular arithmetic, not unlike some other answers, but since R uses 1-based indexing, the arithmetic is somewhat different.
Explanation:
```
function(n,
d=c(1,0, # d contains the padding and
n%/%4^floor(log(n,4):0)%%4, # the base 4 digits
1,0), #
o=c("|"," ") # the vector to index into
cat("", # cat separates things with spaces by default
# so the empty string will print a leading space
o[1+d%%2]," # odds have a | above
", # literal newline, a space will follow it (hence leading spaces)
o[2+0*d]," # array of 2s since the middle is always |
", # another literal newline
o[1+(d>1)]) # digits greater than 1 have a | below
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes
```
NθF²⊞υι¿θWθ«⊞υ﹪θ⁴≧÷⁴θ»⊞υθF²⊞υιE⟦ |¦|¦ ||⟧⪫E⮌υ§ιλω
```
[Try it online!](https://tio.run/##dY47C8JAEIRr8yuWVHtwFr6wsBJsIihiKxbRrGbhvNN7RMH4288zoJ3NsrPfMLPHurRHU6oYC30Nfh0uB7J4E7PsZCzgUMAmuBqDBE43PkFicK9ZUbc9s96Xr0wVlMGbhLFI1t6qvM6d47Pe8rn2WGi/4IYrSlzCp@CVkXL0y//XubGsPaY03OXQ5hLybgC0bb6XsDSsO7qlhqwjDELC3Be6ogeyBCWSvqePYpyOBqPBeBL7jXoD "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input a number.
```
F²⊞υι
```
Push the stop sequence to the predefined empty list.
```
¿θ
```
If the number is positive,
```
Wθ«⊞υ﹪θ⁴≧÷⁴θ»
```
repeatedly apply divmod to convert it to reversed base 4,
```
⊞υθ
```
otherwise just push it.
```
F²⊞υι
```
Push the start sequence to the list.
```
E⟦ |¦|¦ ||⟧
```
Map over three strings. Each string represents barcode translation for the digits `0123` for each row.
```
⪫E⮌υ§ιλω
```
Map over the digits (reversed back into usual order), convert them to bars or spaces using the translation, then join the results into three strings which are then implicitly printed on separate lines.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~32~~ 31 bytes
```
A¤i2Us4)¬®n s|iS)ù2 w i|1ÃqR² y
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=QaRpMlVzNCmsrm4gc3xpUyn5MiB3IGl8McNxUrIgeQ==&input=MTk2MjM=)
Not really satisfied with this yet, but it's a start...
### Explanation
```
A¤ i2Us4)¬ ® n s |iS)ù2 w i |1Ã qR² y
As2 i2Us4)q mZ{Zn s'|iS)ù2 w i'|1} qRp2 y
Implicit: U = input, A = 10, R = newline, S = space
As2 Convert 10 to a binary string.
i2 ) At index 2, insert
Us4 the input converted to base 4.
q Split into chars.
mZ{ } Map each char Z to
Zn Z converted to a number,
s'|iS) converted to base " |" (binary using ' ' as 0 and '|' as 1),
ù2 left-padded to length 2 with spaces,
w reversed,
i'|1 with another pipe inserted at index 1.
q Join the resulting list on
Rp2 a newline repeated twice (adds in blank columns).
y Transpose the entire string.
Implicit: output result of last expression
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~91~~ 90 bytes
```
h s=[do a<-4%s++0%0;x!!a:" "|x<-[" | |","||||"," ||"]]
_%0=[1,0]
b%n=b%div n b++[mod n b]
```
[Try it online!](https://tio.run/##bYxRC4IwAITf9yvO0Z7UmBVB5X7JkJhtoKQTnIXQ@u1rifTUHcd3D8c1yt1N14XQwAmpB6gyPzCXppzxy5wk6kxB/VzmksLD04z6qAggoqrIlXEhi4xXpGZW1Ey3T1jUaSr7QX9bFXrVWgi0djKjuk3Y4GG71hqHLZqY0ShNXjnxiKdrsNAvnXj8N8FviXXrSf4Oxem4238A "Haskell – Try It Online") Returns a list of lines.
---
Same byte count alternative for first line:
```
h s=[do a<-4%s++0%0;" | | ||||"!!(x+a):" "|x<-[0,6,4]]
```
[Answer]
# [J](http://jsoftware.com/), 57 49 47 bytes
10 bytes thanks to FrownyFrog!
```
[:,.2{."0[:|:' |'{~#:@2 6 3 7{~1 0,4&#.inv,1,0:
```
How it works:
`1 0,4&#.inv,1,0:` - converts the number to a list of base-4 digits, adds 1 0 to the beginning and the end of the list
`((#:2 6 3 7){' |')` - lookup table for the encryption, binary 0 corresponds to space, 1 to '|'
`{~` - encrypts the base 4 digit by selecting a string from the lookup table above (argument reversed)
`|:` - transposes the resulting array from 3 columns to 3 rows
`[:` - caps the fork
`,.2{."0` - puts spaces between the bars
[Try it online!](https://tio.run/##DcNBCoAgEAXQvaf4FCTBMKhF0UDQPVxGUi1qEbTRurr14O05XKPA4J@9ELvIhfGSRCPp@JYyOXRo0MfXwlBblbwdN1kykmtVMHQYWYPwCMKl1DKvJwLs0Lkmfw "J – Try It Online")
[Answer]
# APL+WIN, 63 bytes
```
(⍉5 3⍴' | || ||||| ')[;,⍉(2 1,(1+((⌈4⍟n)⍴4)⊤n←⎕),2 1),[.1]5]
```
Explanation:
```
(⍉5 3⍴' | || ||||| ') create a matrix where columns represent bars plus one for separator spaces
(1+((⌈4⍟n)⍴4)⊤n←⎕) prompt for screen input and convert to base 4 and add 1 to convert to index origin 1
2 1,...,2 1 concatenate start stop
,[.1]5 concatenate separator space indices
(.....)[.....] index into bar matrix to display
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~116~~ 114 bytes
-2 bytes thanks to notjagan
```
c=a=0,1
n=input()
while n:c+=n%4,;n/=4
for l in zip(*[' |'[n%2]+'|'+' |'[n/2]for n in c+a][::-1]):print' '.join(l)
```
[Try it online!](https://tio.run/##JcrRCsIgFADQd7/ivgw1V0s3ggy/RHwYUuyGXGUYUezfjdHjgVM@dclkWotududeM3JI5VWFZO8F0x3IRuWom/obDW5ij7xCAiT4YhEHz2HjnjoTFN@4@mswYV@0r6jm4K096iBtWZEqB356ZiSRZGv6ejHjDw "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes
```
4BT.øS4~bT„| ‡øÁ€S»
```
[Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//zRCVC7DuFM0fmJU4oCefCDigKHDuMOB4oKsU8K7//83MzEzMTQ1 "05AB1E – Try It Online")
This is a half-port of Dennis' approach, which is just one byte shorter than the method I used before (which I am quite happy with):
# [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes
```
4BT.øS2‰í1ýøT„| ‡€S»
```
[Try it online!](https://tio.run/##ATAAz/8wNWFiMWX//zRCVC7DuFMy4oCww60xw73DuFTigJ58IOKAoeKCrFPCu///MTk2MjM "05AB1E – Try It Online")
### How it works?
```
4BT.øS2‰í1ýøT„| ‡€S» | Full program. Takes input from STDIN, outputs to STDOUT.
4B | Convert to base 4.
T | Push a 10 to the stack.
.ø | Surrond (prepend and append the 10 to the base 4 representation).
S | Split into individual characters/digits.
+---------------------------------------------------------------
| This part used to be ¸4.ø4в˜ in the previous version, which
| means: surround with 4's, convert each to base 4 (4 -> [1, 0])
| and finally deep-flatten the list.
+---------------------------------------------------------------
2‰ | Divmod 2 ([N // 2, N % 2]).
í | Reverse (element-wise).
1ý | Add a 1 in the middle (element-wise).
ø | Transpose.
T„| ‡ | Translate (‡) from "10" (T) to "| " („| ).
€S» | Format as a grid.
€S | Push the characters of each.
» | Join by newlines, while joining inner lists by spaces.
```
I have asked [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) (the creator of 05AB1E) about the grid thingy in [chat](https://chat.stackexchange.com/transcript/message/41494031#41494031), and they helped me save 2 bytes, by pointing out a feature of 05AB1E: when joining multi-dimenisional lists by newlines, the inner lists are joined using spaces too, so `ðý` is unnecessary.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 33 bytes
```
' |'[≠\2/2⊖1⍪2 2⊤1 0(,,⊣)4⊥⍣¯1⊢⎕]
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/6rK9SoRz/qXBBjpG/0qGua4aPeVUYKQNYSQwUDDR2dR12LNU0edS191Lv40HrDR12LgNpj/wN1/k/jMjGwNOVSV@cCs8wgLHNjQ2NDE1MA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~42 40~~ 39 bytes
```
' |'{~[:#:4#.2|.0|:4#:@+1 0(,,[)4#.inv]
```
Shaved 2 bytes thanks to Dennis. 1 byte thanks to ngn.
[Try it online!](https://tio.run/##y/r/P81WT0FdoUa9ui7aStnKRFnPqEbPoAbIsHLQNlQw0NDRidYEimbmlcX@T03OyFdIUzC0NDMy5oJyTAwszWBsc2NDY0MT0/8A)
### How it works
```
4#.inv] to base 4
1 0(,,[) append (1 0) on both sides
4#:@+ add 4 to each digit and convert to binary
0|: transpose
2|. rotate the rows
[:#:4#. from base 4 to base 2, it's supposed to separate the columns
' |'{~ to characters
```
[Answer]
# JavaScript (ES6) 79 bytes
Uses .toString to convert the number to base 4, and then casework with each line and bitwise OR to build the output line by line. Outputs a list of lines.
```
n=>[2,3,1].map(d=>[...'10'+n.toString(4)+'10'].map(q=>(q|d)>2?"|":" ").join` `)
```
```
f = n=>[2,3,1].map(d=>[...'10'+n.toString(4)+'10'].map(q=>(q|d)>2?"|":" ").join` `)
console.log(f(19623))
console.log(f(4095))
console.log(f(4096))
console.log(f(7313145))
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/)+coreutils, 71 67 bytes
```
dc -e4ddon?np|sed 's/./& /g;h;y/01/23/;G;y/12/21/;H;x;y/0123/ | |/'
```
[Try it online!](https://tio.run/##S0oszvj/PyVZQTfVJCUlP88@r6CmODVFQb1YX09fTUE/3TrDulLfwFDfyFjf2h3INDTSNzLUt/awrgCLA4UVahRq9NX//ze0NDMyBgA "Bash – Try It Online")
# Explanation
The `dc` bit converts to base 4, prepending and appending with a `4` (turns into `10` in the output) and using `n` to keep everything on one line.
The rest happens in `sed`:
```
s/./& /g; Add a space after each digit
h; Make a copy in hold space
y/01/23/; Prepare up the second row (2/3 will turn to pipes)
G;y/12/21/; Append what will be the third row and prep it (1/3 will turn to pipes)
H;x; Prepend hold space
y/0123/ | |/ Make 1 and 3 pipes, 0 and 2 spaces
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 83 bytes
```
.+
$*
+`(1+)\1{3}
${1};
^
1;;
$
;1;;
1*;
$.&
.+
$&¶$&¶$&
T`13` `^.+
T`12` `.+$
\d
|
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLSztBw1BbM8aw2riWS6XasNaaK47L0NqaS4XLGkQZagGZempcIMVqh7ZBMFdIgqFxgkJCHFAUyDQCMvW0VbhiUrhq/v83tDQzMuYyMbA0BRFmAA "Retina – Try It Online") Link includes the faster test cases. Explanation:
```
.+
$*
```
Convert to unary.
```
+`(1+)\1{3}
${1};
```
Convert to base 4 as unary numbers separated by `;`s.
```
^
1;;
```
Prepend the start sequence.
```
$
;1;;
```
Append a `;`, turning it into a digit terminator rather than a separator, and the stop sequence.
```
1*;
$.&
```
Convert to decimal, but adding 1 to each digit.
```
.+
$&¶$&¶$&
```
Triplicate it.
```
T`13` `^.+
```
On the first row, `1`s and `3`s (representing `0`s and `2`s) become spaces.
```
T`12` `.+$
```
On the last row, `1`s and `2`s (representing `0`s and `1`s) become spaces.
```
\d
|
```
All other digits become bars.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~33~~ ~~31~~ ~~29~~ ~~27~~ 26 bytes
25 bytes of code, +1 for `-S` flag.
```
Y^aTB4WRt" |"@[y%2oMyy/2]
```
[Try it online!](https://tio.run/##K8gs@P8/Mi4xxMkkPKhESaFGySG6UtUo37eyUt8o9v///7rB/82NDY0NTUwB "Pip – Try It Online")
### Explanation
We observe a pattern in the four bar types:
* The first row is a space if the digit is even, pipe if odd.
* The second row is always a pipe.
* The third row is a space if the digit is 0 or 1, pipe if 2 or 3.
So:
```
a is cmdline arg; o is 1; t is 10 (implicit)
aTB4 Convert a to base 4
WRt Wrap it before and after with 10
^ Split into a list of digits
Y and yank into y
[ ] List of:
y%2 0 if even, 1 if odd for each item in y
oMy 1 mapped to y, i.e. constant 1 for each item in y
y/2 Each item in y divided by 2 (0, 0.5, 1, or 1.5)
" |"@ Use the elements of that list as indices into this string
Note that indices are truncated to integers!
Autoprint, separating rows with newline and elements of
each row with space (-S flag)
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 28 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
4─10¹:h++{»1F2%¹{Ƨ| W}¹∑ā}⁰H
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=NCV1MjUwMDEwJUI5JTNBaCsrJTdCJUJCMUYyJTI1JUI5JTdCJXUwMUE3JTdDJTIwVyU3RCVCOSV1MjIxMSV1MDEwMSU3RCV1MjA3MEg_,inputs=NzMxMzE0NQ__)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 176 bytes
```
#include<stdio.h>
int n,m;f(n,r){if(n)f(n>>2);printf("%c%c",n?32:10,(n&r||!r)&&n?'|':32);}main(){scanf("%d",&n);m=(n+(4<<(32-__builtin_clz(n)/2*2)))*16+4;f(m,1);f(m,0);f(m,2);}
```
[Try it online!](https://tio.run/##JY1LDoIwFEXnrkIxlD4oSlvUBBCXQrCINoGnKTARXDsWHdycwf2p8K7UPG81qmaoblnXV/q5e@Qrjf0aWZvWFJmBUVuCVZ4LSF/GujV1XOUqh@FFioRHjCIx07QxQAhevMlLpI1@2lIjhbFTJS6NymEEIW3PFAMaZxmVIiyK66CbXmOhmre92QtfAIDPj0Fs/1vG4Yfoj2V1nk@SSx4fvg "C (gcc) – Try It Online")
Slightly less terribly formatted (less golfed):
```
#include<stdio.h>
int n,m;
f(n,r) {
if(n)
f(n>>2);
printf("%c%c",n?32:10,(n&r||!r)&&n?'|':32);
}
main() {
scanf("%d",&n);
m=(n+(4<<2*(16-__builtin_clz(n)/2)))*16+4;
f(m,1);
f(m,0);
f(m,2);
}
```
## Explanation
First, consider the following code to read an integer and output the base 4 version:
```
#include <stdio.h>
int n;
f(n) {if(n)printf("%d\n",n&3,f(n>>2));}
main(){scanf("%d",&n);f(n);}
```
This uses tail recursion to reverse the order of the output. Each recursive step bitshifts by 2 (lops off the last 2 bits and divides by 4). It outputs the result bitmasked with 3 (0b11), which only shows the last two bits, which is the last digit base 4.
The function call is included in the `printf` as a trailing argument (it isn't printed, but it is evaluated) to avoid needing to use {} (+2 bytes) to group the `printf` and the function call.
The solution here extends this base-4 code. First, m is defined as n, but such that in base 4 it will have 10 prepended and appended to it. We then print m.
In printing base 4 regularly, we used a bitmask of 3 to get the digit. In the mail code, the top line is that digit's low-order bit (a bitmask of 1) and the bottom line is the high order bit (a bitmask of 2). Accordingly, the `r` in `f(n,r)` is the bitmask - our main function calls `f(m,1)` for the first line and `f(m,2)` for the last line.
To make the middle line work (always print "|"), we add `||!r` to the conditional - if r is 0, it will always evaluate to true and print a "|". Then we call `f(m,0)` for the middle line.
Finally, we want newlines to behave. Including an extra `printf` is expensive as far as bytes of source code goes, so instead we add another %c specifier to the existing `printf`. `n?32:10` prints a newline if n is 0 (false), and a space otherwise. 32 and 10 are used instead of '\n' and ' ' to save bytes.
[Answer]
# Common Lisp, 191 bytes
```
(lambda(n &aux(k`(1 0,@((lambda(n &aux r f)(do()((= n 0)f)(setf(values n r)(floor n 4))(push r f)))n)1 0)))(format t"~3{~{~:[ ~;| ~]~}~%~}"`(,(mapcar'oddp k),k,(mapcar(lambda(c)(> c 1))k))))
```
[Try it online!](https://tio.run/##VY7dCoJAFIRf5SBUc8ALJbuoKHqPCNxWl8KflV2NwDyvbkvgRVcz88EMo@un72bMqFVzLxRaWqvhjSpHSkl8wT8nR4ZRWDBwopYSDtGXvcFL1UPpA3IMU1vrgs2Y0Q3@8Wsxtxwmg8JY16ie@ki2o4xyuBLJ8UNyk0lWMkU5YjSq08ptbFF0VHFcLWT5oxln0pQyV2GS5yzZ73j@Ag)
[Answer]
# PHP, 99+1 bytes
```
for($n=10 .base_convert($argn,10,4). 104;(~$c=$n[$i++])||3>$y+=$i=1;)echo" | || |||||
"[$c*3+$y];
```
requires PHP >= 5.5 for literal string indexing and < 7.1 for the indexing to not yield a warning.
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/64c726c8d339340ae88c07c24b517553dce9feb3).
Insert one more newline to get a trailing one.
[Answer]
# Python 2, 142 126 bytes
```
B=lambda n:n<4and`n`or B(n/4)+`n%4`
def F(i):
for r in 0,1,2:print' '.join(" |"[(int(x)%2,1,x>'1')[r]]for x in'10'+B(i)+'10')
```
Big thanks to ovs!
I tried to not copy the other answers' methods and... yuck.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 160 bytes
```
i=>{string s=$"10{B(i)}10",a="";for(int y=0;y<3;y++,a+="\n")foreach(var t in s)a+=t<51&y!=1&t-(y>>1)!=49?" ":"| ";return a;string B(int n)=>n>0?B(n/4)+n%4:"";}
```
[Try it online!](https://tio.run/##jY9BS8MwGIbP9ld8CzoS2mlDO2VL00GFnRSEHbx4CVnUwPwCSTootb@9ljkvnnZ@Ht6HV4eFdt6MbbD4AbsuRPMlEn1QIcBLn4SootWwbVFXFmMGIfpJrGHrWr@boGmU125vQMJoZd3/cgjymvC8b6hlA89JpiQh4t15Oo1AJ3PRVYXo0jRTqSRvSNjEjNKf9Kg8RLAIgU0oVks@72aSz@OCdnXN2UyWqw0BIGvyDUR4E1uPoMS525wCyGSNdb5pKN6VLMWbcj3lh1Ekf4eOzu7hWVmkLOmTq0eHwR3M7au30TxZNPT/P1rmqyVj4lL3/lL3oeAFL0/TQzKMPw "C# (.NET Core) – Try It Online")
I'm sure I've missed some improvements.
### DeGolfed
```
i=>{
string s = $"10{B(i)}10", // prepend and append 10 to the base 4 number
a="";
for (int y=0; y<3; y++, a+="\n") // go through each row
foreach (var t in s) // go through each char digit
a += t<51 & y != 1 & t-(y>>1) != 49 ? " " : "| "; // check if bar or space occurs
return a;
string B(int n) => n>0? B(n/4) + n%4 : ""; // convert int to base 4
}
```
`t<51 & y != 1 & t-(y>>1) != 49` checks that the char isn't '3', not the second row, and then some binary magic to see if the first or third row should contain the space.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 42 bytes
```
s4 +A iA)d1"|| "0" | "2" ||"3'|³ ò3 miR ·y
```
[Try it online!](https://tio.run/##y0osKPn/v9hEQdtRIdNRM8VQqaZGQclASQFIGgHJGiVj9ZpDmxUObzJWyM0MUji0vfL/f0NLMyNjAA "Japt – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 32 bytes
```
jjL;CmXX1jk_d1`T"| ".DR2sj[4Q4)4
```
**[Try it here!](https://pyth.herokuapp.com/?code=jjL%3BCmXX1jk_d1%60T%22%7C+%22.DR2sj%5B4Q4%294&input=19623&debug=0)**
[Answer]
# C, 120 bytes
Sadly only works on Windows, since `itoa` is too much of a convenience to be standard.
```
char*p,s[21]="10";g(a){for(p=s;*p;)printf(!a|*p++&a?" |":" ");puts(p);}f(n){strcat(itoa(n,s+2,4),"10");g(1);g(0);g(2);}
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 50 bytes
```
{↑,/(' |',¨' ')[⍉↑¯1⌽¨(3⍴2)∘⊤¨4+1 0,1 0,⍨4⊥⍣¯1⊢⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OAZPWjtok6@hrqCjXqOodWqCuoa0Y/6u0ECh5ab/ioZ@@hFRrGj3q3GGk@6pjxqGvJoRUm2oYKBjog/Kh3hcmjrqWPeheDlHYtetS7Nbb2//80BXNjQ2NDE1MA "APL (Dyalog Unicode) – Try It Online")
] |
[Question]
[
Everybody knows *pi* the mathematical constant, the ratio of a circle's circumference to its diameter.
```
3.14159265358979323846264338327950288419716939937510...
```
You probably also know *e* the mathematical constant, the base of a natural logarithm.
```
2.71828182845904523536028747135266249775724709369996...
```
But... do you know *pie*? It is one of the most important constants (to me). It is the digits of *pi* and *e* interleaved.
```
32.1741185298216852385485997094352233854366206248373...
```
As a decimal expansion:
```
3, 2, 1, 7, 4, 1, 1, 8, 5, 2, 9, 8, 2, 1, 6, 8, 5, 2...
```
This is [OEIS sequence A001355](https://oeis.org/A001355 "A001355 - OEIS").
>
> KEYWORD: nonn,base,**dumb**,easy
>
>
>
It is a very dumb sequence.
## Challenge
Write a **program/function** that takes a **non-negative integer n** and outputs the **nth digit of pie**.
### Specifications
* [Standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods "Default for Code Golf: Input/Output methods") **apply**.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default "Loopholes that are forbidden by default") are **forbidden**.
* Your solution must work for at least 50 digits of each constant which means it should work for at least a **100 terms of the sequence** (please, *try* not to hardcode :P).
* The output for 2 or 3 is **not a decimal point**.
* Your solution **can either be 0-indexed or 1-indexed** but please specify which.
* This challenge is not about finding the shortest approach in all languages, rather, it is about finding the **shortest approach in each language**.
* Your code will be **scored in bytes**, usually in the encoding UTF-8, unless specified otherwise.
* Built-in functions that compute this sequence are **allowed** but including a solution that doesn't rely on a built-in is encouraged.
* Explanations, even for "practical" languages, are **encouraged**.
### Test cases
These are 0-indexed.
```
Input Output
1 2
2 1
11 8
14 6
21 4
24 9
31 5
```
In a few better formats:
```
1 2 11 14 21 24 31
1, 2, 11, 14, 21, 24, 31
2 3 12 15 22 25 32
2, 3, 12, 15, 22, 25, 32
```
[Answer]
# Mathematica, 50 bytes
1-indexed
```
(Riffle@@(#&@@RealDigits[#,10,5!]&/@{Pi,E}))[[#]]&
```
[Answer]
# Haskell, ~~154~~ ~~147~~ 146 bytes, NO HARDCODING OR USE OF BUILTIN CONSTANTS
This solution calculates *e* and *pi* using infinite series and stores them in arbitrary-precision fixed-point integers (Haskell's built-in `Integer` type and its `Rational` extension).
```
import Data.Ratio
s n=product[n,n-2..1]
r=[0..164]
f n=(show$round$(*10^50)$sum[[2*s(2*k)%(2^k*s(2*k+1)),1%product[1..k]]!!mod n 2|k<-r])!!div n 2
```
Ungolfed:
```
import Data.Ratio
semifact :: Integer -> Integer
semifact n = product [n, n-2..1]
pi_term :: Integer -> Rational
pi_term i = semifact (2*i) % (2^i * semifact (2*i+1))
--requires 164 terms to achieve desired precision
pi_sum :: Rational
pi_sum = 2 * (sum $ map (pi_term) [0..164])
--requires 40 terms to achieve desired precision
e_sum :: Rational
e_sum = sum [1 % product [1..k] | k<-[0..40]]
-- 51 digits are required because the last one suffers from rounding errors
fifty1Digits :: Rational -> String
fifty1Digits x = show $ round $ x * 10^50
pi51 = fifty1Digits pi_sum
e51 = fifty1Digits e_sum
-- select a string to draw from, and select a character from it
pie_digit n = ([pi51, e51] !! (n `mod` 2)) !! (n `div` 2)
```
0-indexed. Accurate for input 0-99, inaccurate for input 100-101, out-of-bounds otherwise.
Explanation:
Calculates *pi* using [this infinite series](https://math.stackexchange.com/a/14116/63189). Calculates *e* using the classical [inverse factorial series](https://en.wikipedia.org/wiki/E_(mathematical_constant)). Theoretically these aren't the ideal formulas to use, as they aren't very terse in terms of bytecount, but they were the only ones I could find that converged quickly enough to make verification of accuracy feasible (other sums required hundreds of thousands if not millions of terms). In the golfed version, *e* is calculated to a much higher precision than necessary in order to minimize bytecount. Both constants are calculated to slightly more digits than necessary to avoid rounding errors (which are responsible for the awkward tail of incorrect values).
The constants are calculated as arbitrary precision integer ratios (`Rational`), then multiplied by 10^50 so that all necessary digits remain intact when the ratio is converted to an (arbitrary precision) integer (`Integer`). This also avoids the issue of avoiding the decimal point in the numbers' string representations, which the function alternatively draws characters from.
[Answer]
# [Taxi](https://bigzaphod.github.io/Taxi/), 749 bytes
```
'3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919' is waiting at Writer's Depot.Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to The Underground.Go to Writer's Depot:n 1 l 1 l 2 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 3 r 3 r.[a]Pickup a passenger going to Narrow Path Park.Go to The Underground:s 1 r 1 l.Switch to plan "b" if no one is waiting.Pickup a passenger going to The Underground.Go to Narrow Path Park:n 4 l.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan "a".[b]Go to Narrow Path Park:n 4 l.Pickup a passenger going to Post Office.Go to Post Office:e 1 r 4 r 1 l.
```
[Try it online!](https://tio.run/##nZJPb8IgGMa/yhsv3hr50wI9bst220yc2cF4QKUtsYEGaLp9@o5qXVyzaLIDEJ68/HieF4L81H0/JxgxihBPseAYZXElPKU8FYItBCUpxmQQSJbhRYYpJ4xQzgjChKUCp1kUMadcUIaYSBlDOKOCkYUQgpAsSgKJOWgPndRBmxJkgA@ng3JzD0@qsSF5sRAsLK0P8FYUeq/yDhDUcbhhTZZ6f2wbkNBI75UplYPSDqh46r1S8CB3qi60r5T7GmFTOfcX4l3a2hyUK51tzWGE/babmxFVA75j7rGyDaxadXH1s48MEsPFkWzk9hbiVTpnO1jKUMXJHa/yXRk9xTs3a9XpsK@GmqaWBma7GegCjAVr1NUz/KMNz62qY9W6yf2oTM3FWDRamIZVF3On/k8Nylmy2W1vAm95vfo2f3yk89V07E3fY/4N "Taxi – Try It Online")
Trying to compute pi or e programmatically in Taxi would be a nightmare, although I'm sure it can be done. Thus, it's *far* shorter to just hardcode the first 100 digits in the sequence. It feels pretty cheap but it's definitely the shortest Taxi code that meets the challenge.
It hard-codes the sequence as strings, takes in `n`, then iterates `n` down and removes the first character in the string each time. When `n=0`, output the first character. This is one-indexed.
Un-golfed / formatted:
```
'3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919' is waiting at Writer's Depot.
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to The Underground.
Go to Writer's Depot: north 1st left 1st left 2nd left.
Pickup a passenger going to Chop Suey.
Go to Chop Suey: north 3rd right 3rd right.
[a]
Pickup a passenger going to Narrow Path Park.
Go to The Underground: south 1st right 1st left.
Switch to plan "b" if no one is waiting.
Pickup a passenger going to The Underground.
Go to Fueler Up: south.
Go to Narrow Path Park: north 4th left.
Go to Chop Suey: east 1st right 1st left 1st right.
Switch to plan "a".
[b]
Go to Narrow Path Park: north 4th left.
Pickup a passenger going to Post Office.
Go to Post Office: east 1st right 4th right 1st left.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
žsтžtøJþsè
```
Explanation:
```
žs Get the first input digits of pi
тžt Get 100 digits of e
√∏ Zip them together
J Join into a string
þ Remove non-digits
sè 0-indexed index of input in the resulting list
```
0-indexed.
[Try it online!](https://tio.run/##ARwA4/8wNWFiMWX//8W@c9GCxb50w7hKw75zw6j//zEx "05AB1E – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 88 bytes
*-4 bytes thanks to the base conversion idea of [@EriktheOutgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer).*
```
lambda n:`int("SVBPXJDZK00YCG3W7CZRA378H4AM5553D52T52ZKAFJ17F4V1Q7PU7O4WV9ZXEKV",36)`[n]
```
[Try it online!](https://tio.run/##Zc/BS8MwGAXw@/6Kz4DQsghN0iw66KFuTlkRq85uVoVW2qwfzHS08eBfX@NBqHh7j/e7vOOXbVrDBx29Dofy470qwcwLNNYjj9llulsv8yQInhfXYqsW@UMs1PlNGN9KKcVS8o3keRKv1kytwozdq/RJ3YXb7CLfXSUZoWLmFy/mbdBtBwhooCvNvvYYZQHz5xPoPzVEQGxDJoDakVNgAUQRMChN5fqJi8zBX9lbJ@vDH8tHlo@sqf5bMbJiZLsfe@zcbSCbpia0wGLqNkoq3KOFVkOKNWBPqPbwjPnDNw "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/) + [sympy](http://docs.sympy.org/latest/index.html), 92 bytes
0-indexed. Thanks to Rod for reminding me to switch to `from sympy import*`, which I formerly forgot.
```
lambda n:sum([('3','2')]+zip(`N(pi,50)`,`N(E,50)`[:47]+'6996')[2:],())[n]
from sympy import*
```
[Try it online!](https://tio.run/##HcZLCsIwEADQvaeY3czYCLVqpQHdufUCMdCKRgfMh7Qu6uWj@FYvzdMzhqa4w6W8Bn@9DRD0@PZkCDeosEG21UcS9WdKonY19@rX039Gb/e2wrbrWmTTaKuI2QS7cDl6GGefZhCfYp6WxcUMAhIgD@Fxp3Vds15AyhImEIWrIypHwuUL "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 114 bytes
~~I honestly think the shortest solution is hardcoding, since Python doesn't have useful built-ins.~~
```
lambda n:"3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919"[n]
```
[Try it online!](https://tio.run/##FchLCsIwEADQq4Ru2kKFzCeZmYJeRF1UtBrQtIRuPH2sqwdv/W6vJWOdj5f6nj63@@Ty2BCCMIAGNEWIu6SBNZiJN6aASP@gGNFHZCUhViFAkmAY4p6orMYCYkEEMLIJeTMjinsZWHPO1zovxSWXsitTfj46P4D3/ejWkvLm0tAeTu0wd6mvPw "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 114 bytes
Equivalent solution by [@totallyhuman](https://codegolf.stackexchange.com/users/68615/totallyhuman).
```
'3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919'.__getitem__
```
[Try it online!](https://tio.run/##FchLCsIwEADQq2SXFqpkPsnMCHoSIbhoaxampWTj6WNdPXj7t723in25P7snBGEAjWiKkE5JI2s0k2BMEZH@QSlhSMhKQqxCgCTRMKYzUVmNBcSiCGBiEwpmRpTOMjB/zXmdW2nzJ@e@bIcrrlR3vOo6D2GCEMab249SmyuTvzz8tAxl7D8 "Python 2 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~83~~ 80 bytes
0-indexed.
```
lambda n:('%d'*51%(*b' )4bD4&6UcF^#!U+B>0%"WK\<>
0^GO9~1
c]$O;',))[n]
```
[Try it online!](https://tio.run/##RVC5TsNAEK1QJHfcDYLhCN4Ng@QrNhtwCoSgoEgVUeSQ1kkMKyWO5aSBgl83M4ul7EhvjvfmabTl9/ZrXYR1no7rpV5lcw1FT7jtudvp@m3RyVzYlwdRdvwS3cbD2ev0@uRyePd81PfaVx8Xp@/jvaf@mTd9G6jWr986n01uBo@HLko5Kib1emE2kMIoxAB9TDAi9PEBu9QryjyNmz60ObKoKBL0CCOaM8s8KxxoXtdSMUVAQkZeDWkttBVn364l1jAgjBtlQDxr2D7ZWfKFimQJBa/GRCtr5NmLlL0hblSKNGrilJUptkIvl2KzrYSWkKaQQb6uQCMVpoAfUwr@CISVLkWOUOnicyF8z5P8HIfFhpU7ogf/vgbBve@7CLkwUtZ/ "Python 3 – Try It Online")
There are some non-printable characters in there that can't be seen properly in a browser.
This works by building the tuple `(32, 17, 41, 18, 52, ...)` from the ASCII codes of the characters in the hardcoded bytestring. The tuple is converted to the string `'3217411852...'`, from which we select the right digit.
[Answer]
# [Seed](https://esolangs.org/wiki/Seed), 6015 bytes
```
105 41100973201674650461227976639700390615120600528953176107701316721890649738810349651490948904154731057172335535600875054878204557287393379815378680878571406244365932330202793040308312687924242319799562985464135998860369933720376853281630432469462831217924775601393232895404104191613314969008627719099002734936685651970933027922574843126481552407811220371545812798263882325951724505132794956253992779856191832909434513683936955184871247159313261417328850445886987045814618325821125417040265540589403338721758954467831926977078444612065747526326682314711350486782090838673475876960125016098416460032667015813053483457246043486676622061645094043655351781242050448580132075920324099742699960838361839038297355120817832056960516761862493176616153258281345538652844974811030063414112136642097000574165433957710342430709643110444042577685157477268110199017600011209827070311299268347100419887111107237908884608557593677163764286026624394674781868689858494991328505977301270068505397030743037416430245399054325956185200430657008806539374392625804513081295070438243600044274289109395357299275275193717501822777898664715885427884193864182834402097958423697356485767670945673525604620701482288023981110598866625872386643941558021439168402392304238271452444124214301243311025121833097491087918320170873313832323794851508364788578530614246140801266858481189449278157296335592848066512127882306035576754122325822200069362884409931190620435627809384380203617488253034370361172908245852012086081807945576657014184275798330804532115103840313004678040210379846666674881048346897213048386522262581473085489039138251061251160730845385869281787222083186331344552658814775998639661361866503862291670619153718574270905089351133527806484519543645501497150560454761284099358123613642350160410944676702481576280832672884549762767667090615809061739499629798396737503512011645776394176807352443544839957773371384141101627375926404212619777658374366513665083032140398814384622434755543347503025479743718569310129255927244046638238401670388409731849963600790867434678993019370132638962549859363736476668247251402420832876258626149639101811361047924632565285870213656416957893835899254928237592711662454838295046528789720146967061486405916116778722736283489123195985053535189375957277052428901645131462087039117212488839670735246752589931585405440449333046667938628384693216121067951290025349082277568986632815062532963505690244579740140120806885104683071514922412748240497612209609661707922754236180441892543545377867355182682381812487973645406703590150722720330526173957597156314579144484166520730013480681064941752984345205140917291104888971742824066713606933406657345121342075268990055328274845008936364502884461548416337689565392911129757761902576946104722487260155373897552821908338346641549478063474748830482136404008215583192489320750526753663943267086203954602839906762640389978523894333743126288529975769945319614142422443068420170103245659109689433597701350198280212250954698442638475209618790055335813263132865176791663235801963797561493995544185124734214257034901773781134331460320221759556924556747571745834582344275416625351302153332814233497096345055392255809024712740720006219615340819493781244665414077298346378966540544979367367978334759985048507214749726072645238624803791884339024844989975370042133733339339038567691571361407296615851372112592532463329778465699812822089846474961581380707849259093905314170108054540333209088059730272087864344697983074458088984533095183089310714804468718319244214535941276969904638763288063417624586766891798378622613765728303031397998644194508610598078718347204813844240434145846888722334194516524032354042557957058092854659539699310565707914118281251563405735083553254856313838760124953245573676126601070861004186509621892263623745673900572829301771299438501543213489182375655869072568437776298051260531944785904157204006430131566234389896821642210616326951771496269255716808352415001187083781128619236455170025989777631182990311607133740812107138446626302353752098982590371714623080450836912706275397973009559314275978915463843159370230629290376520494894845680706499809017211545204670148071902560908658269183779180493590025891585269507219866461550160579656755846447951259951641828495549544791046179035585611272240116822105364823082512055639047431280117805724371019657801828634946412396263504315569042536942671358095826696817513115447079645898107923447321583282886740680340887700198072304400536529418546232473450984945589794448490331085275232352881571706521961358975744067916422124670374397682877259664913100427726059898474024964867713698696116581478101206003313106174761699804016604950094008714907179862448792216891309734208815522069346791369498202430302292199779590583788518283934542807403049256936179914953814019565550264909025345322516061595136601312434888871667940394250767164496543418483237896796108764367721411969986710930448108645039275082356457263454340220118278471652962484104099512207532103709146426640958406853240342441810465024550617909657901698718289260589269758398513490424434162831332785821428006396653475356712733072469052427934231406388810607688824035522285626563562286337967271308076321307276537761026788485320280603487776428017017298356181654076403306265118978333909378403193559129146468182910851996415072056976175613473847242292911071040966109905552914332596680497156169349277079292398091020434667210493868422848588893205157133171899819212153010393580099455957808703428739456223073813663954919146593698106305501988107196273527346690785289909397140611634970017071011599022429384594426022933102487171920965595473754661194965266230932928905708783854897164127767575976566931916632077914904360565095752466049885656187054491320449776951484812738806536727562344348761718424255018794271994537719709226236497935053971406685810778014002594041715040546776952342303797267458880802314841325359844565479173256964507237937290466116935912176054052746039378370966040054779443633371806403649852746347690237831260027483859907620684197542069045517397230169577918374265220969534695931904
```
The Seed equivalent to my Befunge answer. Like I mentioned there, the Befunge program this outputs does not work on TIO because TIO seems to have internal line wrapping at 80 characters.
[Answer]
# Polyglot, 108 bytes
```
n=>"3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919"[n]
```
Works in:
* C#
* JavaScript
---
I think this is the shortest you can do in C# seeing as it is 252 bytes to find the [Nth decimal of pi](https://codegolf.stackexchange.com/a/138560/38550).
[Answer]
# Java 8, ~~420~~ ~~417~~ ~~413~~ ~~404~~ ~~380~~ 358 (calculated) & ~~115~~ 110 (hardcoded) bytes
Calculated (**~~420~~ ~~417~~ ~~413~~ ~~404~~ ~~380~~ 358**):
```
import java.math.*;n->{int i=1,x=99;BigDecimal e,f=e=BigDecimal.ONE;BigInteger p,a=BigInteger.TEN.pow(x);for(p=a=a.add(a);i<x;)e=e.add(e.ONE.divide(f=f.multiply(f.valueOf(i++)),new MathContext(x,RoundingMode.HALF_UP)));for(i=1;a.compareTo(a.ZERO)>0;)p=p.add(a=a.multiply(a.valueOf(i)).divide(a.valueOf(i+++i)));return n==1?50:((n%2<1?p:e)+"").charAt(-~n/2);}
```
[Try it here.](https://tio.run/##hVFdTxsxEHy/X2EhVfI2F8OF9gGMQRRStRIkiI@XVlW13O0lDne25fjCIZT@9dRH2qYvhMed0ezMzs5wgX3ryMyKh5WunfWBzSImagxT8V4meYXzObtEbZ4Tpk0gX2JObBQnlk/Rs5xHlBmQCVsmbB4w6JyNmFFsZfrHzx2pVZa26uBAftKTc8p1jRWjtFSkNoAYj4Yd/zVaTMgzl6LajOJ2OBLOPvIWZGk9dwoVCiwKjiD1USuBFL3M1C0ShV7ognipSlE3VdCueuKlWGDV0LjkutcDSA09xrvC9MxGjzbwNr22jSm0mVzagsSX04vPP@@uANaO8QaJIre1Q0@3lqP4Nrwew/GeBKfcOkqM9M8NN24Af/Pg/xF6utvtKTTexLpUdvJx75Bz825wlJ24Q4Lezg6IruPTwPu/zO4A5HIVa3bNfRU7/lP1wuqC1fE//Cb4GP77D4TuOTdP80C1sE0QLuKhMtyInGfQfeo1drCVzbaLsw/bd79hvV29v1Yvk@XqNw)
[Prove it outputs correct result for required 100 items.](https://tio.run/##fVNrT9swFP3Or7iqNMleW5N3YoJBMJg2abSIsS97aDKJQ80SJ0ucUoS6v945TUcrQJOSWPfE955z7rXv@JyPy0qou/TXShZVWWu4MxgpuJ6RtzEA7O/DJTdwmYGeCbh50GKclK3Se0nOmwYuuFSPewBSaVFnPBEw6UKAZMZrSJDBQeHYQEvzmqfRXMsEJqCAwUqNjx67LZLZowWjND6Vt2cikQXPQYwyJtgWINPJeff/o6G6FTVUI862Ibk@n5CqvEcLHGdljSrGGSc8TRHHsTxcxFgwsY5FV4ikci5TgTKWkaLNtazyB5SROc9bMc2QHA4xHilxbwzq2bvScCw0WoyujPVUqtuLMhXkw8mn9z@/XGLcMxoPMSdJWVS8Ftcl4uTr@dUUH1kxrljVSzGSntj4lg3jf3r4roSh7GrXQre1AsWYfexbBwipN86hfVwdCDwcDDDpOn2i0fiP2ndwvFzFfaOr9iY3jd70e17KFAozLPRZ18bAtx/AcT@pHgBTJU2MrfRKNEaimc7AdezQs@3Id2jk2IFZ3cj3Ip/S0KKe6zuO2wFuEDhW4HiRG7peFLq244Y@dfzAgE7kRdQL7ZD6YWg7gUdD16KUum5gIGrTQbwrIuF50uZc76rY7Fi3eH1ULDNP2zJfM6TeArxMHDJQxJw/3Gcve5aHRouClK0mleHTuUKDJ98H3/UAhs/7sMl/LXPLuUl9LuI/uaelnq1vVMMLcfwqMxG/W5436EXVzXVarv4C)
Hardcoded: (**~~115~~ 110 bytes**):
```
"3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919"::charAt
```
[Try it online.](https://tio.run/##hY/PTsMwDIfvfQprpxaJqonzz5s48ADssiPiELLCUtq0arNJCPXZSyq4Uk6WP@tnf27szd73Qx2a88fiu6EfIzSJlZ2Nl/LukLnWThM8WR@@MvAh1uObdTUcUwfuYkdweaIQikMGcwZTtNE7OEJ4gGWHnGnBmJGcDGcqVTRSGEmkKxIoOccVoFK8UlwY1CiMRsZRS@JSJciNMCQ00yS1ZlwJ0lgREaJKiBjt9vvV4zEuyWC4vrbp/K/Frfdn6JJ6foqjD@/PL7ZYvU@fU6y7sr/Gckg8tiEPpctZsT7x15RvTtl2mInt3f@c3k7jT3rO5uUb)
0-indexed
-9 and -5 bytes thanks to *@Nevay*.
-24 bytes thanks to *@ceilingcat*.
>
> * Your solution must work for at least 50 digits of each constant which means it should work for at least a **100 terms of the sequence** (please, *try* not to hardcode :P)
> * Built-in functions that compute this sequence are **allowed** but including a solution that doesn't rely on a built-in is encouraged
>
>
>
You've asked for it.. ;)
Java's built-in `Math.PI` and `Math.E` are doubles, which have a max precision of just 16. Therefore, we'll have to calculate both values ourselves using `java.math.BigInteger` and/or `java.math.BigDecimal`.
Since I've already [calculate PI before in another challenge](https://codegolf.stackexchange.com/a/97365/52210), I've used that same code using `BigInteger`. The algorithm for Euler's number uses `BigDecimal` however.
The resulting `p` and `e` are therefore: `31415...` and `2.718...`.
Could probably golf it by only using `BigDecimal`, but was giving some incorrect answers for PI, so I now use both `BigDecimal` and `BigInteger`.
**Explanation:**
```
import java.math.*; // Required import for BigDecimal and BigInteger
n->{ // Method with integer as parameter and char as return-type
int i=1, // Start index-integer at 1
x=99; // Large integer we use three times
BigDecimal e, // Euler's number
f=e=BigDecimal.ONE;
// Temp BigDecimal (both `e` and `f` start at 1)
BigInteger p, // PI
a=BigInteger.TEN.pow(x);for(p=a=a.add(a);
// Temp BigInteger (where both `p` and `a` starts at 10^99*2)
i<x;) // Loop (1) 99 times (the higher the better precision)
e=e.add( // Add the following to `e`:
e.ONE.divide(f=f.multiply(f.valueOf(i++)),
// First change `f` by multiplying it with `i`
new MathContext(x,RoundingMode.HALF_UP))))
// And then add 1/`f` to `e`
// (RoundingMode is mandatory for BigDecimal divide)
for(i=1; // Reset `i` back to 1
a.compareTo(a.ZERO)>0;) // Loop (2) as long as `a` is not 0
p=p.add( // Add the following to `p`:
a=a.multiply(a.valueOf(i))
// First change `a` by multiplying it with `i`,
.divide(a.valueOf(i+++i)));
// and dividing it by `2*i+1`
// And then add this new `a` to `p`
// We now have `p`=31415... and `e`=2.718...
return n==1? // If the input (`n`) is 1:
50 // Return 2
: // Else:
((n%2<1? // If `n` is divisible by 2:
p // Use `p`
: // Else:
e) // Use `e` instead
+"") // Convert BigDecimal/BigInteger to String:
.charAt(-~n/2);} // And return the `(n+1)//2`'th character in this string
```
[Answer]
# Excel, 113 bytes
1-indexed
```
=MID("3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919",A1,1)
```
`PI()` is only accurate up to 15 digits. Similar for `EXP(1)`.
~~60~~ 42 byte solution that works for Input `<=30`
(-18 bytes thanks to @Adam)
```
=MID(IF(ISODD(A1),PI(),EXP(1)/10)/10,A1/2+3,1)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
žssžt‚øJ'.Ks<è
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6L7i4qP7Sh41zDq8w0tdz7vY5vCK//8NTQE "05AB1E – Try It Online")
---
This answer is 0-indexed.
```
žs # pi to N digits.
sžt # e to N digits.
‚Äö√∏J # Interleave.
'.K # No decimal points.
s<è # 0-indexed digit from string.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
```
Éi<;žtë;žs}þθ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cGemjfXRfSWHVwPJ4trD@87t@P8fAA "05AB1E – Try It Online")
Similar to Magic's answer, but kinda different.
Explanation:
```
Éi<;žtë;žs}þθ Supports 9842 digits of e and 98411 digits of π
É a % 2
i ë } if a==1
< a - 1
; a / 2
žt e to a digits
else
; a / 2
žs π to a digits
þ keep chars in [0-9] in a
θ a[-1]
```
[Answer]
# [Python 2](https://docs.python.org/2/) + [SymPy](http://docs.sympy.org/latest/index.html), ~~70~~ 63 bytes
```
lambda n:int(N([pi,E][n%2],50)*10**(n/2)%10)
from sympy import*
```
[Try it online!](https://tio.run/##NVBLboQwDN1zimxGkyBXzYeBZiS667YXoCyCOrSRIEQMG3p5arvTWHr@Pdux8759L8keY/txTGEePoNI15g2@S67HOGt79LJ9nDRqjS6LGV6tupktCrGdZnFfZ/zLuKcl3Urj3FZRRQxiU6DAQvGgKnAolmBM@Dr/ppX6i0inJ9ezzDKqFRRLLd4bztHFdBAhWjgBS7oe9QUrR@@Y10xepQGNCJ25yzl/xkOa2qMaEaqcMh2bJE2zG64j0WsH0yLeeJQ14b/4zHbsG2RUfFUx3NJHE/6Y3nk@L7gHUWYJhnadhB0lQAD3eUnZknLgphDliOsIX3dpNFa4Tt@AQ "Python 2 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 55 bytes
```
" ®v4bØUî6UcF^#ß&6$Îø%\"Wí;<>0^GO9G1c]$O;"cs gU
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=IiCudjRi2FXuNlVjRl4j3yY2JAbO+CVcIlcf7TsZPD4cMF5HTzlHGjEHHmNdJE87EyJjcyBnVQ==&input=MTE=) Contains a few unprintables.
Works by replacing each character in the string with its charcode, then returning the digit at the correct index. The string was generated by this program:
```
r"..(?=[^0]0)|25[0-5]|2[0-4].|1..|.(?=[^0]0)|..|."_n d
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=ciIuLig/PVteMF0wKXwyNVswLTVdfDJbMC00XS58MS4ufC4oPz1bXjBdMCl8Li58LiJfbiBk&input=IjMyMTc0MTE4NTI5ODIxNjg1MjM4NTQ4NTk5NzA5NDM1MjIzMzg1NDM2NjIwNjI0ODM3MzQ4NzMxMjM3NTkyNTYwNjIyODQ4OTQ3MTc5NTc3MTI2NDk3MzA5OTkzMzY3OTU5MTki)
[Answer]
# Julia, 63 bytes
1-indexed
```
a(n)=replace(string(BigFloat(n%2>0?π:e)),'.',"")[ceil(Int,n/2)]
```
Converts pi or e to a string, removes the decimal place, and then calls the appropriate digit. Returns a character representation of the digit.
[Answer]
# Seed, ~~5852~~ 5794
Based on TehPers Befunge answer.
```
105 113002164871590739314987829049307960037656198834866427236905121954115803425132377811017261267508985918460516699110604069383390959259813211529503372875273808710588124346256307646667819637622583266174711430236542978713371651111138161258814014430791036278292414499656452941169156830257154682891945427168323349789659414918954432721496930284898425790960909241894284781315857049329769224542864680353681534575933422424767707487267105729647869707615701969946632447899025935146610872657847217500147458582162977840688029783675330301220720997622926460983429318136766448664249339408547350925381367609377956773869746595751981270619213926147211890869963881664082555405185043676206172128177189246682247058574292315899935090905437591661266740559405162222996969611028558290091641009922497490272073602109698144136237139892288758564286335997806260176733841267995620802629495311018527105600614517192092649739617993355354764787635487444533658359428565687080154517757890270592773372024921163684788486949109705417597693762970920021249476121718487310885214065572289535961346215683364612315264822079329585462764945219095679916070353286147709600972570614120233113128790126662286156057686903720942137873912511576516301011227356138489027470697247933585954842450741358944012216071769761815733661875419652839052931663415505744712631746787832014322014868591150702573172166945669229230913363344728435313054200429998131904807363769656763488962394934163037250505543518966376704416506376321611183458869639917973770286152983694797090148271251013631504215211063321591324191669491956643311240521006341404267009756225607360091610388650359124819175883509292439414777620417167522685091490259040136036034579692518124798164708926188495203908126898658681865909050531795557967108988591574556866175888346903123079427257115921330028144573070329426929531076740133942295248077792078687841078079268719526879909788542680179524275827358784127273168527872136974672731344708599614215281119934065639520745234349293757970245111171645337101665479132283486591886003364231440299524048129365242579269735889557760669994751103041672868435202250671067797684169074938720299249334705611438978473321117244865600759558291122236484729311642571499634395815652244856036306309426007390684666411239172295850545146441402560560341332328380709310752195557971123590340315335700317013293851268994688275799911771016064582194514876381367454879798122437554725457606331047947374904420197286393544275845842428580614721866647174706186991857454507274563175804998237200744486630048509506143395191487837350195267021654643538881849734231141725424601330485671509495305148131743810493387517147034390010671970517110205867361059474884617856208037099248888176490940290206562546475055852738977573593904440085870522989324367348662198800983879197171460362503731088514814079681375712029106737219687292822832109515671205430310190195987438406367288649547279607011336560384368751332286717619791748985553772693409536049147249735256714714024639568250305940497144973962564739882059896415826530266878391650198495604496902130260192048771738287910630368379535990532534781447331851939134456545892027046327917478474665636031407046424166662224021038524518495928222266639887065627494062967545357424609779938336142901480061872078034629454218589211641784224052477683545808790001800789690114038324361179370588354779145068239226196064382427132818933211646651925556744151561592584028445615402230429197821863456537957514864271133762278972184204869644394521345416271355631691230134619361522785486931887108980824977655507783434249228188856167617108716815094123730600710952108190016969333162591813869968264515792463284254698981261829244948079958090972029228009509584596285072135655480768099128872214767174088557681133949254945492690159492733827441038586327672595878146092413446635826008953390852510674046712247097336867698827720756888212247984007467030021498051100766545723521829074239408920419228250849112577718015149186696163811124496295326839833968618977237298392606857935004740275480306823203459402487279114142809512031125908797313635314972863814303513678473099927026607274900456721755543827098812499754976223002068988166928549986537496305328253011857088410803897580533534109872057730526662956704744519240370047288779478242394065841217642437006215862683465340567540141567908382219161706192517414918920335949928316037480173726078040746055914732675899449554957974703336123447175047024451331108027464919186072451108622235369696655603590410141636686651842707160470522293863594778186952018113745140884964015958604111363959827254006218576819095970777536217638180423889634131748541027983145892759706009491393182243795048903475541887656616509860914555116317017006096855080419242968307668243354850411304416190687499212061972410926839498652918205097786610428363995506942432312411823427047186868840577006626729855054434535548056834448216246518404910539196129433524592691043628016754842890872507304906318742343175154206452151706945249818234640798419739099879992464416047867973147679669193814805760372826774933145903193782399649588923478706079107924185454258124307881293104633301338073776691416142537130145576268465288334517657616632085092685517319761353655436962877242874726395604578641629542918465198557048233824201655936372542110027024362703019743929091896294865287339787424383206745979183701439427840308590723461600323162160013212640322512322745821468600689724015806074498945821524378781714871793675698107420867876597774494057787557965469877984960511884501039590623229374018088813765629152405059007172424233594237883453270762239632440547727976805269692785605606401953257035710157327757004025470677546239616027587603888642814609779889799831508662735822095183804904610021893861075323086016909910447437995018169256183487254051119590377469311351028312018776850026116029689211988391328901764154505776555092490963288792
```
[Answer]
# Malbolge Unshackled (20-trit rotation variant), 3,64E6 bytes
Size of this answer exceeds maximum postable program size (eh), so the code is [located in my GitHub repository](https://github.com/KrzysztofSzewczyk/codegolf-submissions/raw/master/138547.mu) (note: Don't copy the code using CTRL+A and CTRL+C, just rightclick and click "Save destination element as...").
## How to run this?
This might be a tricky part, because naive Haskell interpreter will take ages upon ages to run this. TIO has decent Malbogle Unshackled interpreter, but sadly I won't be able to use it (limitations).
The best one I could find is the fixed 20-trit rotation width variant, that performs very well, **calculating (pretty much) instantly**.
To make the interpreter a bit faster, I've removed all the checks from Matthias Lutter's Malbolge Unshackled interpreter.
```
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* translation = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72Fh"
"OA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@";
typedef struct Word {
unsigned int area;
unsigned int high;
unsigned int low;
} Word;
void word2string(Word w, char* s, int min_length) {
if (!s) return;
if (min_length < 1) min_length = 1;
if (min_length > 20) min_length = 20;
s[0] = (w.area%3) + '0';
s[1] = 't';
char tmp[20];
int i;
for (i=0;i<10;i++) {
tmp[19-i] = (w.low % 3) + '0';
w.low /= 3;
}
for (i=0;i<10;i++) {
tmp[9-i] = (w.high % 3) + '0';
w.high /= 3;
}
i = 0;
while (tmp[i] == s[0] && i < 20 - min_length) i++;
int j = 2;
while (i < 20) {
s[j] = tmp[i];
i++;
j++;
}
s[j] = 0;
}
unsigned int crazy_low(unsigned int a, unsigned int d){
unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
int position = 0;
unsigned int output = 0;
while (position < 10){
unsigned int i = a%3;
unsigned int j = d%3;
unsigned int out = crz[i+3*j];
unsigned int multiple = 1;
int k;
for (k=0;k<position;k++)
multiple *= 3;
output += multiple*out;
a /= 3;
d /= 3;
position++;
}
return output;
}
Word zero() {
Word result = {0, 0, 0};
return result;
}
Word increment(Word d) {
d.low++;
if (d.low >= 59049) {
d.low = 0;
d.high++;
if (d.high >= 59049) {
fprintf(stderr,"error: overflow\n");
exit(1);
}
}
return d;
}
Word decrement(Word d) {
if (d.low == 0) {
d.low = 59048;
d.high--;
}else{
d.low--;
}
return d;
}
Word crazy(Word a, Word d){
Word output;
unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
output.area = crz[a.area+3*d.area];
output.high = crazy_low(a.high, d.high);
output.low = crazy_low(a.low, d.low);
return output;
}
Word rotate_r(Word d){
unsigned int carry_h = d.high%3;
unsigned int carry_l = d.low%3;
d.high = 19683 * carry_l + d.high / 3;
d.low = 19683 * carry_h + d.low / 3;
return d;
}
// last_initialized: if set, use to fill newly generated memory with preinitial values...
Word* ptr_to(Word** mem[], Word d, unsigned int last_initialized) {
if ((mem[d.area])[d.high]) {
return &(((mem[d.area])[d.high])[d.low]);
}
(mem[d.area])[d.high] = (Word*)malloc(59049 * sizeof(Word));
if (!(mem[d.area])[d.high]) {
fprintf(stderr,"error: out of memory.\n");
exit(1);
}
if (last_initialized) {
Word repitition[6];
repitition[(last_initialized-1) % 6] =
((mem[0])[(last_initialized-1) / 59049])
[(last_initialized-1) % 59049];
repitition[(last_initialized) % 6] =
((mem[0])[last_initialized / 59049])
[last_initialized % 59049];
unsigned int i;
for (i=0;i<6;i++) {
repitition[(last_initialized+1+i) % 6] =
crazy(repitition[(last_initialized+i) % 6],
repitition[(last_initialized-1+i) % 6]);
}
unsigned int offset = (59049*d.high) % 6;
i = 0;
while (1){
((mem[d.area])[d.high])[i] = repitition[(i+offset)%6];
if (i == 59048) {
break;
}
i++;
}
}
return &(((mem[d.area])[d.high])[d.low]);
}
unsigned int get_instruction(Word** mem[], Word c,
unsigned int last_initialized,
int ignore_invalid) {
Word* instr = ptr_to(mem, c, last_initialized);
unsigned int instruction = instr->low;
instruction = (instruction+c.low + 59049 * c.high
+ (c.area==1?52:(c.area==2?10:0)))%94;
return instruction;
}
int main(int argc, char* argv[]) {
Word** memory[3];
int i,j;
for (i=0; i<3; i++) {
memory[i] = (Word**)malloc(59049 * sizeof(Word*));
if (!memory) {
fprintf(stderr,"not enough memory.\n");
return 1;
}
for (j=0; j<59049; j++) {
(memory[i])[j] = 0;
}
}
Word a, c, d;
unsigned int result;
FILE* file;
if (argc < 2) {
// read program code from STDIN
file = stdin;
}else{
file = fopen(argv[1],"rb");
}
if (file == NULL) {
fprintf(stderr, "File not found: %s\n",argv[1]);
return 1;
}
a = zero();
c = zero();
d = zero();
result = 0;
while (!feof(file)){
unsigned int instr;
Word* cell = ptr_to(memory, d, 0);
(*cell) = zero();
result = fread(&cell->low,1,1,file);
if (result > 1)
return 1;
if (result == 0 || cell->low == 0x1a || cell->low == 0x04)
break;
instr = (cell->low + d.low + 59049*d.high)%94;
if (cell->low == ' ' || cell->low == '\t' || cell->low == '\r'
|| cell->low == '\n');
else if (cell->low >= 33 && cell->low < 127 &&
(instr == 4 || instr == 5 || instr == 23 || instr == 39
|| instr == 40 || instr == 62 || instr == 68
|| instr == 81)) {
d = increment(d);
}
}
if (file != stdin) {
fclose(file);
}
unsigned int last_initialized = 0;
while (1){
*ptr_to(memory, d, 0) = crazy(*ptr_to(memory, decrement(d), 0),
*ptr_to(memory, decrement(decrement(d)), 0));
last_initialized = d.low + 59049*d.high;
if (d.low == 59048) {
break;
}
d = increment(d);
}
d = zero();
unsigned int step = 0;
while (1) {
unsigned int instruction = get_instruction(memory, c,
last_initialized, 0);
step++;
switch (instruction){
case 4:
c = *ptr_to(memory,d,last_initialized);
break;
case 5:
if (!a.area) {
printf("%c",(char)(a.low + 59049*a.high));
}else if (a.area == 2 && a.low == 59047
&& a.high == 59048) {
printf("\n");
}
break;
case 23:
a = zero();
a.low = getchar();
if (a.low == EOF) {
a.low = 59048;
a.high = 59048;
a.area = 2;
}else if (a.low == '\n'){
a.low = 59047;
a.high = 59048;
a.area = 2;
}
break;
case 39:
a = (*ptr_to(memory,d,last_initialized)
= rotate_r(*ptr_to(memory,d,last_initialized)));
break;
case 40:
d = *ptr_to(memory,d,last_initialized);
break;
case 62:
a = (*ptr_to(memory,d,last_initialized)
= crazy(a, *ptr_to(memory,d,last_initialized)));
break;
case 81:
return 0;
case 68:
default:
break;
}
Word* mem_c = ptr_to(memory, c, last_initialized);
mem_c->low = translation[mem_c->low - 33];
c = increment(c);
d = increment(d);
}
return 0;
}
```
[Answer]
# [Nim](https://nim-lang.org/), ~~124~~ 97 bytes
```
import sugar
t(x=>($(7*"""L?J$rg$"79n*i.71&<B@[>)!Y8l:.pUo4GZ9c0a%"""[x/%2].ord))[x%%2+1])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m704LzN3wc34gqL8ZIUSjTQrBTBLo8JKITOvRNNKITkjsUhTwZZLQSE1OSNfIU3DUBPBNkJiGyNLGKKoMtFcWlqSpmtxMyUztyC_qEShuDQ9sYirRKPC1k5DRcNcS0lJyUfe3kulKF1CRUnM3DJPK1NP2NxQzcbJIdpOUzFS0iLHSq9AWlQ-NF_AxD3KMtkgUVUQqCm6Ql_VKFYvvyhFUzO6QlXVSNswFmrXAigFpQE)
*-27 thanks to @Steffan*
[Answer]
# Python 3 + [SymPy](http://docs.sympy.org/0.7.1/modules/mpmath/functions/constants.html), 109 Bytes
0-indexed
[Try it online!](https://tio.run/##Xcw9CsMwDEDhuT6FNstNCfkhS6EnMR4CsRsVLAvFS0/v4rXbBw@efOtZeG0tacmQJe/1BMpStN5NlvGQ67XN5ogJErJ7mpsocUVrx08hRm/XxYbBX1VRyHkKQ2fsSkWBgBh053fE5bHNLjjPwbW/NE9TXyck134 "Python 3 – Try It Online")
```
from mpmath import*
mp.dps=51
print(''.join(['32']+[str(pi)[i]+str(e)[i]for i in range(2,51)])[int(input())])
```
Beat hardcoding by 5 bytes!!
But could probably be better. But beating hardcoding makes me feel good :)
[Answer]
# Pyth, 35 bytes
```
@.i`u+/*GHhyHyK^T99rJ^2T0Z`sm/K.!dJ
```
[Test suite](https://pyth.herokuapp.com/?code=%40.i%60u%2B%2F%2aGHhyHyK%5ET99rJ%5E2T0Z%60sm%2FK.%21dJ&test_suite=1&test_suite_input=1%0A2%0A11%0A14%0A21%0A24%0A31&debug=0)
Since Pyth doesn't have built-in arbitrary precision pi and e constants, I calculate them directly.
Calculating pi:
```
u+/*GHhyHyK^T99rJ^2T0
```
This uses the following recurrence continued fraction to compute pi: `2 + 1/3*(2 + 2/5*(2 + 3/7*(2 + 4/9*(2 + ...))))`. I got it from [another PPCG answer](https://codegolf.stackexchange.com/a/512/20080). It is derived in equations 23-25 [here](http://mathworld.wolfram.com/PiFormulas.html).
I calculate it from the inside out, ommitting all terms beyond the 1024th, since the later terms have little effect on the number, and I maintain 99 digits of precision to make sure the first 50 are correct.
Calculating e:
```
sm/K.!dJ
```
I sum the reciprocals of the first 1024 numbers, to 99 digits of precision.
Then, I convert both numbers to strings, interlace them, and index.
[Answer]
**MATLAB, 93 Bytes**
```
n=input('');
e=num2str(exp(1));
p=num2str(pi);
c=[];
for i=1:length(p)
c=[c p(i) e(i)];
end;
c(n)
```
A simple explanation is that this first converts e and pi to strings, then goes through a for loop concatenating the digits. Here, c is pie, p is pi, and e is e.
I have also broken this up into several lines for readability, but the actual code is all on one line with minimal spacing.
[Answer]
# C# + [BigDecimal](https://github.com/CognitioConsulting/BigDecimal), ~~377~~ 372 bytes
```
d=>{if(d%2<1){d/=2;int l=++d*10/3+2,j=0,i=0;long[]x=new long[l],r=new long[l];for(;j<l;)x[j++]=20;long c,n,e,p=0;for(;i<d;++i){for(j=0,c=0;j<l;c=x[j++]/e*n){n=l-j-1;e=n*2+1;r[j]=(x[j]+=c)%e;}p=x[--l]/10;r[l]=x[l++]%10;for(j=0;j<l;)x[j]=r[j++]*10;}return p%10;}else{CognitioConsulting.Numerics.BigDecimal r=1,n=1,i=1;for(;i<99;)r+=n/=i++;return(r+"").Remove(1,1)[d/2]-48;}}
```
*Saved 5 bytes thanks to @Kevin Cruijssen.*
No TIO link because of the external library, unfortunately C# doesn't have a built in `BigDecimal` class so this external one will have to do. Probably some golfing still possible but no time right now.
Full/Formatted Version:
```
namespace System.Linq
{
class P
{
static void Main()
{
Func<int, long> f = d =>
{
if (d % 2 < 1)
{
d /= 2;
int l = ++d * 10 / 3 + 2, j = 0, i = 0;
long[] x = new long[l], r = new long[l];
for (; j < l;)
x[j++] = 20;
long c, n, e, p = 0;
for (; i < d; ++i)
{
for (j = 0, c = 0; j < l; c = x[j++] / e * n)
{
n = l - j - 1;
e = n * 2 + 1;
r[j] = (x[j] += c) % e;
}
p = x[--l] / 10;
r[l] = x[l++] % 10;
for (j = 0; j < l;)
x[j] = r[j++] * 10;
}
return p % 10;
}
else
{
CognitioConsulting.Numerics.BigDecimal r = 1, n = 1, i = 1;
for (; i < 99;)
r += n /= i++;
return (r + "").Remove(1,1)[d/2] - 48;
}
};
for (int i = 0; i < 100; ++i)
{
Console.Write(f(i));
}
Console.WriteLine();
Console.ReadLine();
}
}
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 82 bytes
```
lambda n:`7*ord('L?J$rg$"79n*i.71&<B@[>)!Y8l:.pUo4GZ9c0a%'[n/2])`[n%2+1]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKsFcK78oRUPdR97eS6UoXUJFSczcMk8rU0/Y3FDNxskh2k5TMVLSIsdKr0BaVD40X8DEPcoy2SBRVVA9Ok/fKFYzITpP1UjbMPZ/QVFmXolCbmKBRpqOQlFiXnqqhqGBgabmfwA "Python 2 – Try It Online")
Contains some unprintable ASCII characters. flornquake saved two bytes.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 402 bytes
```
--->+>->+>>+>+>>->->+>+>+>-->->+>+>>>->->+>+>>+>+>->+>>+>+>>+>->->>-->>>->+>>+>->->->->+>+>>->+>->+>>->>-->->>>->>>+>->->->->>->>+>-->+>+>+>>+>>>+>->->>+>>->->+>+>->>+>->->>+>->->++[[>+++<-]<+++]>>+>->+>>+>->+>+>+>+>+>+>+>+>->+>->+>>->->->>+>->->->->+>>->>>>+>+>+>>>+>>->+>>->+>->>->+>->+>>->>+>+>>+>+>+>->>>+>+>>>>+>->+>+>->+>+>>>->>>+>>>>+>->>>+>>>>->->->->->>+>,[<[-]>[<+>-]<-]++++[<+++++++++++>-]<.
```
[Try it online!](https://tio.run/##VVBLCkMxCDyQnZ4gCD2HZPFaKJRCF4WeP08TjTbmI5PJOOb@PV6f5@/xHgMAE9vSqRtmboFIE1z45tK8MCIHCg/XcvYiLVpl2ZyFKAS3aLGCAk6MRHSjht706JymQimjeCgS2L44aodhf/FnfvdO3gAxZ7n8Jc4LT5G9El@kCTpLU0JX92qexFqIYfB1jNsJ "brainfuck – Try It Online")
Input as character code (e.g. "A" = 65)
[Try it online with digit input!](https://tio.run/##VVBBDgIxCHwQO970RPgI6UFNTIyJBxPfX4HSUqFbKJ0Ow94@1@f78b2/egcgJP7Zsg2Ru2OmVRz1haW4cKDMKtKTK9EDNGA7ylc0okm4SDcp2IpRI1XbiNHYQpMSNZnKNw0bBZYumb2n4HzxJ37NTjkAiVS7@ktSF5miZiU5QraZMtIETZRpmZ3ZUBzBoiWHDajMrqQxK@t44ie0wUb/BKfeL@cf "brainfuck – Try It Online")
code:
```
build a value list (3217411852... reversed and each digit incremented by four)
--->+>->+>>+>+>>->->+>+>+>-->->+>+>>>->->+>+>>+>+>->+>>+>+>>+>->->>-->>>->+>>
+>->->->->+>+>>->+>->+>>->>-->->>>->>>+>->->->->>->>+>-->+>+>+>>+>>>+>->->>+>
>->->+>+>->>+>->->>+>->->++[[>+++<-]<+++]>>+>->+>>+>->+>+>+>+>+>+>+>+>->+>->+
>>->->->>+>->->->->+>>->>>>+>+>+>>>+>>->+>>->+>->>->+>->+>>->>+>+>>+>+>+>->>>
+>+>>>>+>->+>+>->+>+>>>->>>+>>>>+>->>>+>>>>->->->->->>+
>, get input
[ while input > 0
<[-] set next previous cell = 0
>[<+>-] copy input cell to that cell
<- and decrement it
]
++++[<+++++++++++>-] add 44 to it
<. print it
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `H`, ~~8~~ 7 bytes
```
∆I₁∆ĖYi
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQSCIsIiIsIuKIhknigoHiiIbEllnigbBpIiwiIiwiMzEiXQ==)
-1 thanks to tybocopperkettle
Interleaves the first 100 digits of pi and e, then prints the value at the index
[Answer]
# [Ruby](https://www.ruby-lang.org/), 52 bytes
Uses `-rbigdecimal/math` flag to require BigMath.
```
->n{BigMath.send([:PI,:E][n%2],n*2).to_s(?E)[n/2+2]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcmu0km5RUmZ6SmpyZm5ijn5uYkmGUuwiN9ulpSVpuhY3TXTt8qqdMtN9geJ6xal5KRrRVgGeOlausdF5qkaxOnlaRpp6JfnxxRr2rprRefpG2kaxtVC9lgWlJcUKbtGGsQrKCkZcUJ4RiGcI4xmCJS3gXBMQ1wxiwIIFEBoA)
## Explanation
Ungolfed:
```
->n{
BigMath.send([:PI, :E][n%2], n*2)
.to_s(?E)[n/2+2]
}
```
`[:PI, :E][n%2]` chooses which method to send to BigMath, `PI` or `E`. We call that method with `n*2` as the precision argument because of a quirk when n=1 (it returns an Integer instead of a BigDecimal, and the former doesn’t take a string argument to `to_s`).
`to_s(?E)` converts the number to a string in engineering notation, then we get the `n/2+2`th character (+2 to skip over the `0.`), which is the digit we want.
[Answer]
# [Neim](https://github.com/okx-code/Neim), 45 bytes
```
(‚ÇÉŒ≤ùêíùï£{ùïÄùîºùêçNùê≠hj\CŒì‚ÑöùïòùïéùêìœÜ·ö∫ùê≤K$m·ö†"2ùïéoŒæ:{rm(ùïä/ùïö·õÇùêó})ùïï
```
neim isn't made for decimal numbers
[Try it online!](https://tio.run/##y0vNzP3/X@NRU/O5TR/mTpj0Ye7UxdVAouHD3Cl7gAK9fkBibUZWjPO5yY9aZgFlZgBxH1Bw8vm2h7N2ARmbvFVyH85aoGQEksg/t8@quihXA8ju0gcSsx7ObgKqmV6rCeRM/f/f0BAA "Neim – Try It Online")
[Answer]
# [Befunge](https://esolangs.org/wiki/Befunge), 105 bytes
```
3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919&0g,@
```
Does not work on TIO because it seems to wrap lines internally at 80 characters for some reason. You can get it to work on TIO by putting each digit on a new line, and having the `&0g,@` after the `3` on the first line.
[Answer]
# JavaScript (ES6) + [mathjs](http://mathjs.org/), 78 bytes
```
(n,m=math.create({number:"BigNumber"}))=>`${n%2?m.e:m.pi}`.match(/\d/g)[n/2|0]
```
Zero indexed and works up to 128 numbers (max input of 127).
## Test Snippet
```
let f=
(n,m=math.create({number:"BigNumber"}))=>`${n%2?m.e:m.pi}`.match(/\d/g)[n/2|0]
```
```
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.16.0/math.min.js"></script>
<input type=number min=0 value=0 oninput="O.innerHTML=this.value.length>0?f(+this.value):''"><pre id=O>3
```
[Answer]
# MATLAB (w/ Symbolic Toolbox), ~~89~~ 82 bytes
By making use of the Symbolic Toolbox, this answer provides an output without hardcoding the values of pi and e.
As a fun bonus this code as an input can take either a single index, or an array of indices and will simultaneously provide the output value for all index values provided (e.g. providing 1:10 will output the first 10 values).
```
a=char(vpa({'exp(1)';'pi'},51));
a(a=='.')=[];
n=input('');
a(9+fix(n/2)+56*mod(n,2))
```
(new lines added for readability, not required for execution so not included in byte count)
Unfortunately the Octave version used by TIO doesn't support symbolic inputs to the `vpa` function, so can't provide at TIO link.
In MATLAB indexing into the return vector from a function is not possible in the same way as with Octave which means this is a full program rather than just an anonymous function. The program will ask for an input `n` during execution - this is a one indexed value for which element is required. At the end of the program the value is implicitly printed.
For the program we use the `vpa` function which provides to 51 decimal places the value of `pi` and `exp(1)` (e). This is done symbolically to allow theoretically infinite precision. To expand for more than 100 elements, simply increase the value `51` in the code to increase the range.
Wrapping `vpa` in `char` (i.e. `char(vpa(...))` ) is necessary to convert the output of the function to a string rather than a symbolic value. The resulting output is the string:
```
matrix([[2.71828182845904523536028747135266249775724709369996], [3.14159265358979323846264338327950288419716939937511]])
```
This includes both e and pi to 51 decimal places - enough to allow 100 digits of our output (we have to do a little extra dp than required to avoid printing out rounded values)
In order to index in to this mess, we need to at least get rid of the decimal points so that both strings of digits are contiguous. Originally I used a simple regex replacement of anything which is not a digit with nothing. However I can save 7 bytes by only getting rid of the decimal point using the code:
```
a(a=='.')=[];
```
resulting string is now:
```
matrix([[271828182845904523536028747135266249775724709369996], [314159265358979323846264338327950288419716939937511]])
```
This contains all the digits we need with both pi and e chunks in consecutive indexes.
We can then convert the supplied index such that odd numbers access the pi chunk and even numbers access the e chunk using the calculation:
```
9+fix(n/2)+56*mod(n,2)
```
Accessing that (those) index (indices) in the above string will provide the correct output.
] |
[Question]
[
Your program must take as input a line of characters, like this:
```
@+.0
```
And output the characters sorted by how dark they are, like this:
```
.+0@
```
Requirements:
* You must use a monospaced font for darkness detection.
* You must find out how many pixels each character takes up. You must actually draw the character and count pixels, i.e. you can't just hardcode pixel amounts.
+ As a more concrete rule: if you switched fonts, your program should still work. Furthermore, your program should be able to switch fonts by simply changing a variable or value or string in the code.
* If you use antialiasing, you must count pixels as percentages of a fully black pixel. For example, an `rgb(32, 32, 32)` pixel will count as 1/8 of a full pixel. Disregard this rule if your characters are not antialiased.
* After counting pixels, you must sort the characters by the amount of pixels, and output them in order.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win.
[Answer]
# Bash + ImageMagick: ~~164~~ ~~147~~ 148 characters
```
while read -n1 c
do
o=`convert -size 20x15 xc: +antialias -font cour.ttf -draw "text 0,10 '$c'" xpm:-`
o=${o//[^ ]}
a[${#o}]+=$c
done
echo "${a[@]}"
```
Sample run:
```
bash-4.1$ echo -n '@+.0' | bash graysort.sh
. + 0 @
```
Separators are inserted between grayness groups. Characters with identical grayness level are not separated:
```
bash-4.1$ echo -n 'abcdefghijklmnopqrstuvwxyz' | bash graysort.sh
i cl jortz esv ax u df bgnpq y hk w m
```
[Answer]
## Mathematica, 112 110 108 bytes
This can still likely be golfed further. Assumes the string is in variable s.
And now uses a correct syntax to sort one list by another list.
Lucky test cases -> "Oh yeah, that works" -> *Facepalm*
Thanks for the sharp eyes, David Carraher.
**Update:** Replaced OCR A with Menlo because I realized that on OSX the OCR A font family name is actually OCR A Std. So I was sorting a default font instead of the real deal. Menlo is also monospaced with the same byte count, so no net gain or loss.
I've put up a [hosted CDF export of the notebook](http://www.jonathanvanmatre.com/blog/mathematica-notebooks/), so you can see the code in action if you wish. I'm still figuring out how to add some interactivity to web-hosted CDFs, so for now it's just static.
```
c=Characters@s;Last/@Sort[Transpose@{Total[1-#&/@ImageData@Rasterize@Style[#,FontFamily->"Menlo"],3]&/@c,c}]
```
Output for `s = FromCharacterCode /@ Range[33, 135];` with "Courier"
![enter image description here](https://i.stack.imgur.com/ZYOs7.png)
Output for same, but with FontFamily "Monospace":
![enter image description here](https://i.stack.imgur.com/RKTGl.png)
Note that the final results are shown in MM's internal font, not in the font being sorted. Hence, you see the differences in the font chosen reflected in the sort. The CDF link shows both, though, for the completists.
Ungolfed code:
```
s = FromCharacterCode /@ Range[33, 135];
c = Characters@s;
Last /@ Sort[
Transpose@{Total[1 - # & /@
ImageData@Rasterize@Style[#, FontFamily -> "Menlo"], 3] & /@ c, c}]
```
[Answer]
## QBasic, 259 bytes
```
SCREEN 1
DIM a(255)
FOR i = 32 TO 255
CLS
PRINT CHR$(i);
FOR p = 0 TO 64
a(i) = a(i) + POINT(p MOD 8, p \ 8)
NEXT p
NEXT i
FOR p = 0 TO 96
FOR i = 32 TO 255
IF a(i) = p THEN PRINT CHR$(i);
NEXT i
NEXT p
```
I did this for fun, so it's technically non-compliant to the rules in one way. It doesn't take a list of characters, but instead prints all characters from 32-255 and uses that instead. If you really want to see a version which complies with this rule, please tell me.
It also fails another technicality: "Furthermore, your program should be able to switch fonts by simply changing a variable or value or string in the code." There is no easy way to do this from within QBasic. However, the program will of course work fine with any codepage of your choosing.
Lastly, I could squeeze away a few characters (mostly whitespace that the QBasic IDE helpfully inserts,) but it's probably not worth it since this answer stands no chance of winning anyway.
![QBasic sort characters by darkness](https://i.stack.imgur.com/EulXY.png)
[Answer]
# Javascript + Canvas and Browser DOM (280 237 235 bytes)
*Updated version with suggetions from Fors and toothbrush in comments:*
```
function m(x){a=document.createElement('canvas').getContext('2d');a.font='9px Monaco';a.fillText(x,y=i=0,20);for(;i<3600;)y+=a.getImageData(0,0,30,30).data[i++];return y}alert(s.split('').sort(function(a,b){return m(a)-m(b)}).join(''))
```
More readable version:
```
// Scoring function - Calculates darkness for single character
function m(x) {
a = document.createElement('canvas').getContext('2d');
a.font = '9px Monaco';
a.fillText(x, y = i = 0, 20);
for (; i < 3600;) y += a.getImageData(0, 0, 30, 30).data[i++];
return y
}
// Assume input is in variable s and alert as output. Comparison function now expression.
alert(s.split('').sort(function (a, b) {
return m(a) - m(b)
}).join(''))
```
Can maybe be golfed more.
I'm new to this site, so I am unsure how input is normally read for Javascript answers. I assume input is contained in a variable named `s`. If this is not OK, I will update the answer and the char count.
[JSFiddle of updated version.](http://jsfiddle.net/waxwing/ABXEU/4/)
[JSFiddle of first version](http://jsfiddle.net/waxwing/ABXEU/).
[Answer]
# PHP, 298 characters
I've added a few line breaks so you can see it in all its hideousness:
```
<?php
$s=@$_GET[s];$a=array();$v=imagecreate(16,16);$f='imagecolorallocate';
$f($v,0,0,0);for($i=0;$i<strlen($s);$i++){$c=$f($v,$i,0,1);
imagechar($v,5,2,$n=0,$s[$i],$c);for($y=16;$y--;)
for($x=16;$x--;)$n+=($c==imagecolorat($v,$x,$y));
$a[]=ord($s[$i])+($n<<8);}sort($a);foreach($a as $v)echo chr($v);
```
This code uses the GD fonts that come built-in with PHP. The second argument of `imagechar()` selects the font (numbers from 1 to 5 are valid).
**Example:**
```
Input: !@#$%^&*-=WEIX,./'
Output: '-.,^=!/*IE%X#$&@W
```
If you insert the following on top of the code shown above, then you'll be able to supply the list of characters in your web browser.
```
<?php
define("FONT_SIZE",5);
if(@$_SERVER['PATH_INFO']=='/a.png') {
$s = $_GET['s'];
$im = imagecreate(strlen($s)*(FONT_SIZE+4)+4,FONT_SIZE+12);
imagecolorallocate($im,255,255,128);
$c = imagecolorallocate($im,0,0,0);
imagestring($im,FONT_SIZE,2,0,$s,$c);
header("Content-Type: image/png");
imagepng($im);
imagedestroy($im);
exit();
}
$me = $_SERVER['PHP_SELF'];
$t1 = $img = "";
if ($t1=htmlspecialchars(@$_GET['s'])) {
$t2=urlencode($_GET['s']);
$img="<p><img src=\"$me/a.png?s=$t2\" /></p>";
}
echo <<<END_HTML
<html>
<body>
$img
<form action="$me" method="get">
<input type="text" name="s" size="40" value="$t1" />
<input type="submit" value="Go" />
</form>
END_HTML;
if(!isset($_GET['s'])) exit();
?>
```
[Answer]
## [GTB](http://timtechsoftware.com/gtb "GTB")
This has code to be the second hardest code I've ever written for a calculator. No hard-coded pixel values, it actually draws the text on a graph and loops to count each pixel.
```
0→I`_%I<l?_T;1,1,s;_,I,1
C;pT;{0,1,2,3,4,5},{0,1,2}→L1(I
0→I%I<l?_T;1,C;L1(I)>L1,I
```
**Input**
```
,O.i
```
**Output**
```
.,iO
```
[Answer]
## Java - ~~468 450~~ 444
```
public static void main(String[]a){class c implements Comparable<c>{char d;c(char e){d=e;}public int compareTo(c o){return e(d)>e(o.d)?1:-1;}int e(char f){int a=0,x,y;BufferedImage img=new BufferedImage(99,99,1);img.getGraphics().drawString(""+f,9,80);for(y=0;y<99;y++)for(x=0;x<99;x++)a+=img.getRGB(x,y);return a;}}c[]s=new c[a[0].length()];int i=0;for(char d:a[0].toCharArray())s[i++]=new c(d);Arrays.sort(s);for(c d:s)System.out.print(d.d);}
```
`@+.0abcdefghijklmnopqrstuvwxyz`
->
`.irl+jcvtfxyzsuonkheaqpdb0wgm@`
Ungolfed:
```
public static void main(String[] a) {
a = new String[]{"@+.0abcdefghijklmnopqrstuvwxyz"};
class c implements Comparable<c> {
char d;
c(char e) {
d = e;
}
@Override
public int compareTo(c o) {
return e(d) > e(o.d)? 1 : -1;
}
int e(char f) {
int a = 0, x, y;
BufferedImage img = new BufferedImage(99, 99, 1);
img.getGraphics().drawString("" + f, 9, 80);
for (y = 0; y < 99; y++)
for (x = 0; x < 99; x++)
a += img.getRGB(x, y);
return a;
}
}
c[] s = new c[a[0].length()];
int i = 0;
for (char d : a[0].toCharArray())
s[i++] = new c(d);
Arrays.sort(s);
for (c d : s)
System.out.print(d.d);
}
```
[Answer]
## Postscript, 381
Here's something completely different, just for fun. As most fonts are vector anyway, 'counting pixels' is a little odd, isn't it. Calculating glyph shape area, while being correct way, is not that easy. An alternative can be scanning a rectangle and counting 'hits' when a point is inside a glyph shape, and Postscript has operators for this kind of checks. Though, true, scanning and insideness-testing is just a weird way of counting pixels.
```
(%stdin)(r)file token pop/Courier 99 selectfont[1 index length{0}repeat]0 1 99{0 1 99{0 1 5 index length 1 sub{newpath 9 19 moveto 3 copy 7 index exch 1 getinterval false charpath infill{3 index exch 2 copy get 1 add put}{pop}ifelse}for pop}for pop}for 0 1 99 dup mul{0 1 3 index length 1 sub{dup 3 index exch get 2 index eq{3 index exch 1 getinterval print}{pop}ifelse}for pop}for
```
.
```
(%stdin) (r) file token pop
/Courier 99 selectfont
%/DejaVuSansMono 99 selectfont
%/UbuntuMono-Regular 99 selectfont
[ 1 index length {0} repeat ] % str []
0 1 99 {
0 1 99 {
0 1 5 index length 1 sub {
newpath
9 19 moveto
3 copy % str [] n m i n m i
7 index exch % str [] n m i n m str i
1 getinterval % str [] n m i n m s
false charpath % str [] n m i n m
infill % str [] n m i bool
{3 index exch 2 copy get 1 add put} {pop} ifelse
} for
pop
} for
pop
} for
% un-comment next line to print number of 'hits' for each glyph
%
% dup {=} forall
%
% next is 'lazy sort'
0 1 99 dup mul { % str [] i
0 1 3 index length 1 sub { % str [] i j
dup 3 index exch % str [] i j [] j
get 2 index eq % str [] i j bool
{3 index exch 1 getinterval print} {pop} ifelse
} for
pop
} for
()=
```
And here are results for 3 different fonts (selection of which can be un-commented, above):
```
$ echo '(.-?@AByz01)' | gs -q -dBATCH d.ps
.-?1z0yA@B
$ echo '(.-?@AByz01)' | gs -q -dBATCH d.ps
.-?z1yA0B@
$ echo '(.-?@AByz01)' | gs -q -dBATCH d.ps
.-?1zyA0B@
```
[Answer]
# Perl (with GD) (159)
```
use GD;sub i{$i=new GD'Image 5,8;$B=colorExact$i 9,9,9;colorExact$i 0,0,0;char$i gdTinyFont,0,0,@_,1;$_=unpack"B*",wbmp$i 0;y/0//c}print+sort{i($a)-i($b)}@ARGV
```
usage:
```
> perl dark.pl 1 2 3 @ # . , : ~ $ M i I s S
.,~:i13Is2S$M@#
```
edit: shortened to 159 chars
[Answer]
# Java, 584
Wow... This was not a good language to do this in.
```
import java.awt.geom.*;import java.util.*;class F{static void n(final String f,List<Character> s){Collections.sort(s,new Comparator<Character>(){public int compare(Character a,Character b){return d(f,""+a) - d(f,""+b);}});}static int d(String f,String s){int i=0;PathIterator p=new java.awt.Font(f,0,12).createGlyphVector(((java.awt.Graphics2D)new java.awt.image.BufferedImage(8,8,2).getGraphics()).getFontRenderContext(),s).getGlyphOutline(0).getPathIterator(AffineTransform.getRotateInstance(0.0, 0.0));while(!p.isDone()){i+=p.currentSegment(new double[99])/2;p.next();}return i;}}
```
Usage:
```
import java.awt.geom.*;
import java.util.*;
public class F {
public static void main(String[]args){
List<Character> s = new ArrayList<Character>(0);
s.add('@');
s.add('+');
s.add('.');
s.add('0');
n("Calibri", s);
System.out.println(s);
}
static void n(final String f,List<Character> s){
Collections.sort(s,new Comparator<Character>(){
public int compare(Character a,Character b){
return d(f,""+a) - d(f,""+b);
}
});
}
static int d(String f,String s){
int i=0;
PathIterator p=new java.awt.Font(f,0,12).createGlyphVector(((java.awt.Graphics2D)new java.awt.image.BufferedImage(8,8,2).getGraphics()).getFontRenderContext(),s).getGlyphOutline(0).getPathIterator(AffineTransform.getRotateInstance(0.0, 0.0));
while(!p.isDone()){
i+=p.currentSegment(new double[99])/2;
p.next();
}
return i;
}
}
```
This setup results in:
```
[., +, 0, @]
```
---
The only line here that needs explanation:
```
PathIterator p=new java.awt.Font(f,0,12).createGlyphVector(((java.awt.Graphics2D)new java.awt.image.BufferedImage(8,8,2).getGraphics()).getFontRenderContext(),s).getGlyphOutline(0).getPathIterator(AffineTransform.getRotateInstance(0.0, 0.0));
```
* Initialize the 12pt font object with the passed font.
* Create a new BufferedImage obejct to create a Graphics2D object linked to a GraphicsContext.
* Get the font rendering context of the 2D graphics context for the string s.
* Get the first glyph (only glyph) in the string.
* Get the path iterator (list of points).
Then this final piece brings it together...
```
while(!p.isDone()){
i+=p.currentSegment(new double[99])/2;
p.next();
}
```
By iterating through all points and summing count of points. This density information is passed back up to the comparator and is used for sorting.
[Answer]
### R, 195 characters
```
A=strsplit(scan(,""),"")[[1]];cat(A[order(sapply(A,function(x){png('a',a='none',fa='monospace');frame();text(0,0,x);dev.off();sum(apply(png::readPNG('a'),c(1,2),function(x)any(x!=1)))}))],sep="")
```
Indented with comments:
```
A=strsplit(scan(,""),"")[[1]] #Take characters as strings and split into single chars
cat(A[order(sapply(A,function(x){ #Apply the following function to each char and order accordingly
png('a',a='none',fa='monospace'); #Open empty png without antialiasing and with monospace font
frame(); #create empty plot
text(0,0,x); #add the char as text to the plot
dev.off(); #close png device
sum(apply(png::readPNG('a'), #read it back as rbga 3d matrix
c(1,2), #check every layer (R, G, B, A)
function(x)any(x!=1))) #if any are not 1, send TRUE
}))], #Sum all TRUEs
sep="") #Prints to output
```
Example:
```
> A=strsplit(scan(,""),"")[[1]];cat(A[order(sapply(A,function(x){png('a',a='none',fa='monospace');frame();text(0,0,x);dev.off();sum(apply(png::readPNG('a'),c(1,2),function(x)any(x!=1)))}))],sep="")
1: @+.0
2:
Read 1 item
.+0@
> A=strsplit(scan(,""),"")[[1]];cat(A[order(sapply(A,function(x){png('a',a='none',fa='monospace');frame();text(0,0,x);dev.off();sum(apply(png::readPNG('a'),c(1,2),function(x)any(x!=1)))}))],sep="")
1: 1234567890
2:
Read 1 item
1723450689
```
The gestion of fonts in R plots being platform-dependent, I cannot guarantee that it works on PC, but it does on a Mac (OS X 10.7.5, R 2.14.2).
[Answer]
# SmileBASIC, ~~179~~ ~~176~~ 173 bytes
```
INPUT S$DIM Q$[0],A[0],Z[0]WHILE""<S$C$=POP(S$)GCLS
PUSH Q$,C$
GPUTCHR.,0,C$
GSAVE.,0,8,8,A,0S=0FOR I=0TO 63S=S+A[I]NEXT
PUSH Z,S
WEND
RSORT Z,Q$
WHILE LEN(Q$)?POP(Q$);
WEND
```
Uses the currently loaded font.
Fonts can be loaded with `LOAD"GRPF:filename"`.
More readable code:
```
INPUT STRING$
DIM CHARS$[0],PIXELS[0],SIZES[0]
WHILE STRING$>""
CHAR$=POP(STRING$)
PUSH CHARS$,CHAR$
GCLS
GPUTCHR 0,0,CHAR$
GSAVE 0,0,8,8,PIXELS
SIZE=0
FOR I=0 TO 63
INC SIZE,PIXELS[I]
NEXT
PUSH SIZES,SIZE
WEND
RSORT SIZES,CHARS$
WHILE LEN(CHARS$)
PRINT POP(CHARS$);
WEND
```
[Answer]
# PHP - 485
Demo:
```
$ php pcg-23362.php "@+.0"
.+0@
```
Code:
```
<?php $f='x.ttf';$d=array();foreach(str_split($argv[1]) as$_){$B=imagettfbbox(50,0,$f,$_);$w=abs($B[4]-$B[0]);$h=abs($B[5]-$B[1]);$im=imagecreate($w,$h);imagecolorallocate($im,255,255,255);imagettftext($im,50,0,0,$h-$B[1],imagecolorallocate($im,0,0,0),$f,$_);$b=$w*$h;for($x=0;$x<$w;$x++)for($y=0;$y<$h;$y++){$z=imagecolorsforindex($im,imagecolorat($im,$x,$y));$color=$z['red']*$z['green']*$z['blue'];$b-=$color/0x1000000;}$d[$_]=$b / ($w * $h);}asort($d);echo implode(array_keys($d));
```
[Answer]
## Python + freetype-py: 147
```
import sys,freetype as F;f=F.Face('m.ttf');f.set_char_size(99);print(sorted([(f.load_char(c)or sum(f.glyph.bitmap.buffer),c)for c in raw_input()]))
```
] |
[Question]
[
We all know the age-old debate - should strings be length-prefixed or should they be null-terminated? Well, you've run into a blob of binary data and apparently whoever made it decided that the best solution would be a compromise and length-terminated their strings.
For the purposes of this challenge, a length-terminated sequence is a series of one or multiple integers such that the last item in the sequence is equal to the number of items in the sequence, and no prefix of the sequence is also a valid length-terminated sequence. For example, `[1]`, `[15, 2]`, and `[82, 19, 42, 111, 11, 6]` are all valid length-terminated sequences. `[15]` is *not* a valid length-terminated sequence (it hasn't been terminated), and neither is `[15, 2, 3]` (it should have ended at the `2`).
Your task is to write a program or function that takes a list of integers, and outputs all the valid length-terminated sequences within that list. For example, for the input list `[7, 6, 5, 4, 3, 2, 1]`, valid length-terminated sequences would be `[1]`, `[3, 2]`, `[5, 4, 3]` and `[7, 6, 5, 4]`.
* You must output *all* valid length-terminated sequences found in the input, in any order. The order may vary between runs of your program. You must output *no* length-terminated sequences not found within the input, and *no* sequences found within the input that aren't valid length-terminated sequences.
* If some length-terminated sequence occurs multiple times within the input, it should also be output multiple times. The sequence `[9, 8, 3]` occurs twice in the input `[9, 8, 3, 9, 8, 3]` (once starting with the first number, and again starting at the fourth number) and should thus be output twice.
* A number may be part of more than one length-terminated sequence. For example, the input `[9, 9, 2, 4]` contains both the length-terminated sequences `[9, 9, 2, 4]` and `[9, 2]` and they should both be output.
* You may assume all numbers are between 0 and 127 (both inclusive).
* You may assume the input contains no more than 126 numbers.
* You may *not* make any further assumptions about the input, including the assumption that the input contains at least one valid length-terminated sequence.
* You may take input or produce output by any of the [default methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Input and output formats are flexible (within reason) and the input format need not be the same as the output format. However, the your input and output formats must not depend on the input, and must not vary between runs of your program.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - make your code as small as possible.
# Examples
```
[input] -> [output], [output], ...
[7, 6, 5, 4, 3, 2, 1] -> [7, 6, 5, 4], [5, 4, 3], [3, 2], [1]
[90, 80, 70] -> (no output)
[1, 2, 3, 4, 5] -> [1]
[100, 0, 2, 2, 2, 0, 0, 2, 4] -> [0, 2], [2, 2], [2, 2], [0, 0, 2, 4], [0, 2]
[] -> (no output)
[54, 68, 3, 54, 68, 3] -> [54, 68, 3], [54, 68, 3]
[4, 64, 115, 26, 20, 85, 118, 9, 109, 84, 64, 48, 75, 123, 99, 32, 35, 98, 14, 56, 30, 13, 33, 55, 119, 54, 19, 23, 112, 58, 79, 79, 45, 118, 45, 51, 91, 116, 7, 63, 98, 52, 37, 113, 64, 81, 99, 30, 83, 70] -> [85, 118, 9, 109, 84, 64, 48, 75, 123, 99, 32, 35, 98, 14], [118, 9, 109, 84, 64, 48, 75, 123, 99, 32, 35, 98, 14, 56, 30, 13, 33, 55, 119, 54, 19, 23, 112, 58, 79, 79, 45, 118, 45, 51, 91, 116, 7, 63, 98, 52, 37], [109, 84, 64, 48, 75, 123, 99, 32, 35, 98, 14, 56, 30, 13, 33, 55, 119, 54, 19], [84, 64, 48, 75, 123, 99, 32, 35, 98, 14, 56, 30, 13], [14, 56, 30, 13, 33, 55, 119, 54, 19, 23, 112, 58, 79, 79, 45, 118, 45, 51, 91, 116, 7, 63, 98, 52, 37, 113, 64, 81, 99, 30], [45, 118, 45, 51, 91, 116, 7]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 67 bytes
```
f=lambda l:l and[l[:x]for i,x in enumerate(l)if-~i==x][:1]+f(l[1:])
```
[Try it online!](https://tio.run/##LVDLboQwDDx3vyJHUKdSnAckSHxJlAPVgoqUZVcsleilv05ttsrD9tgeJ/P42b7uizmOqS/D7fM6qNIVNSzXVFK35@m@qhm7mhc1Lt@3cR22sSr1PH38zn2/59RRfp@qkqjL9bGNz@2pepVSiwYeDhYGlKFS1AgarRafGLSc9GegNTQDsl6eE1iOd2gCV/5bgdhzIPIwDQxTeg4CIkhHhDPpAlpGjUWMsDzIIwYQT2tgNcjCMqP0RSHmm0uJDDw3RtnuRcrGEyJx0ID/Y4XHM2HLiJVRgc4Z/AwrP8uXi8glIohepxjd5e2xzsumpkri@vgD "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ẇ=J$Ḅ⁼ɗƇ1
```
A monadic Link accepting a list of integers which yields a list of lists of integers.
**[Try it online!](https://tio.run/##y0rNyan8///hrjZbL5WHO1oeNe45Of1Yu@H///@jDQ0MdBSAyAiG4FyTWAA "Jelly – Try It Online")**
Or `ẆĖE€Ḅ⁼ʋƇ1` - [Try it](https://tio.run/##y0rNyan8///hrrYj01wfNa15uKPlUeOeU93H2g3///8fbWhgoKMAREYwBOeaxAIA "Jelly – Try It Online").
### How?
```
Ẇ=J$Ḅ⁼ɗƇ1 - Link: list of integers
Ẇ - all sublists
1 - set right argument to 1
Ƈ - filter keep those (sublists) for which:
ɗ - last three links as a dyad - i.e. f(sublist, 1):
$ - last two links as a monad i.e. g(sublist)
J - range of length = [1,2,3,...,length]
= - (sublist) equals (that)? (vectorises)
Ḅ - from binary
⁼ - (that) equals (1)?
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 65 bytes
Prints the results.
```
a=>a.map((_,i)=>a.every((v,j)=>j<i|v-++j+i||print(a.slice(i,j))))
```
[Try it online!](https://tio.run/##LVDLboMwELz3Kzj04CgTZGMMdlNy66HfQKPGQolq1FJEUqQq5NvpONSv3ZndnbXd@tGfmyH0l81o51M1@2rn0y/fC/GOsIrgOB6HXyFGtITtc5jGzXrdrsM09UPoLsKn58/QHEVgAse8resSBQxyaGRQeyS1k7ASpYy@IqkZNHcgJSSJOBcvj3TcJkdhmflvI0Uvh1IGWYGMkobAwkFJB3sP5hYl2UzDOWg2MnAWit0KaAmloakY61wU5slUpTIYFrq48kWUxig4RVCA79FRx1CwJKNjK6vuPXgNHV@2f0hP38OLbz6ET6pdck2W7zm8dv3P5SmpH6/@tn/rDqttchKe5xKnc1vNfw "JavaScript (V8) – Try It Online")
### Commented
```
a => a.map((_, i) => // for each value at position i in a[]:
a.every((v, j) => // for each value v at position j in a[]:
j < i | // yield true and go on with the next iteration if j < i
v - ++j + i // or v is not equal to j - i + 1 (increment j)
|| print( // otherwise, print ...
a.slice(i, j) // ... the sublist of a[] from i to j - 1
) // and break (print() returns undefined)
) // end of every()
) // end of map()
```
[Answer]
# [Python](https://docs.python.org/2/), 62 bytes
```
f=lambda l:l and[l[:x]for x in l if[x]==l[x-1:x]][:1]+f(l[1:])
```
[Try it online!](https://tio.run/##LVBJbsMwDDzXr9AxQaeAqMWWBPglgg4uUqEGVCdIfHBf75BOoIXkkBxKc/tff6@L2fc6tunv@zKplpqalktuOW2lXu9qU/Oimppr3so4trx9EWdKTlQ@66llSuW8rz@P9aFGlfOAHh4OFgZUoHLUCBqDFp8YtJz0R6A1NAOyXp4TWI536ANXvq1A7DkQeZgehik9BwERpCPCkXQBA6PGIkZYHuQRA4in9bAaZGGZUfqiEPPNpUQGnhujbPciZeMJkTjowf@xwuOZcGDEyqhAxwx@hpWfla4TpUQEEesQI3Uft/u8rKqeJD7vTw "Python 2 – Try It Online")
This is a subtle improvement on [@xnor's solution](https://codegolf.stackexchange.com/a/194242/20080).
The solution we wish we could use is
```
f=lambda l:l and[l[:x]for x in l if x==l[x-1]][:1]+f(l[1:])
```
However, this will crash on an out-of-bounds index. xnor avoided this problem by using the index at which the value `x` appeared rather than actually indexing into `l`, but this required using the expensive `enumerate` function.
Instead, I used `[x-1:x]` to slice out the length-1 slice including the index we're interested in. Slicing in Python is much more permissive with respect to out of bounds errors. Now, we only need to check that the part of the list sliced out is `[x]`.
Works in Python 2 or 3.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes
```
a₁ᶠ{a₀.l~t}ˢ
```
[Try it online!](https://tio.run/##PVBBTsMwEPzKqmcLee24ibnwkKiH0AMgVa0ElRCqWrU5VHDjCaiXXrlQIb7AK5KPhBm7VMpm1zO7M2vfPjbT@5fZ4s4Nq@eRTBfzZfMwf7oedT9vN/3@s29bVN3Xe/967L5PqNc4DE3f7rrTxwp5ezXbLNe/h2GopS6NjI0EI4URb8QZ0YmROlojFaK0PGkifGoKCbDgbELzdzkWpBkBveMqTV1K4qwRqvB0sHZ0CgTQEZEtftW5qwBWknSQiSA89wAQQSi3gYKHgoL3tEpKMXsyc1AVU4FSMUfx78ci4HZRCUCLz@GzfKBVSdznZSo978CNfXobmfwB "Brachylog – Try It Online")
```
a₁ᶠ{ }ˢ For every suffix of the input, if possible,
a₀. find the shortest prefix
l the length of which is
. ~t its last element.
```
An alternate [generator](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) solution using `s`, taking inspiration from Jonathan Allan's Jelly solution:
# [Brachylog](https://github.com/JCumin/Brachylog), ~~13~~ 12 bytes
```
s.i₁ᶠ=ˢ~gh~l
```
[Try it online!](https://tio.run/##PVBBagJBEPxK43kI0zM77k4g5CGLB/WggijEQAghgnuQ5JYniBevuURCvpBX7H5kUzVjhO2d7qruqp6ZPIyn8@fleub6l6eBTNerx/FitbkdtD/v993@s2ua9nxA0X59dG@n9vuM/BVFv7lZdM0O5N3vcTubb5d9X0tdGhkaCUYKI96IM6IjI3W0RipEaVlpInxqCgmw4GxC83ctC9KMgN5hlaauKXHmCFV4Olg7OgUC6Ig4LX7VpasAVpJ0kIkgPPcAEEEot4GCh4KC97RKSjF78uSgKqYCpWKO4t@PScDtohKAFp/DZ/lAq5K4z8tUetmBG/v0NjL6Aw "Brachylog – Try It Online")
```
. The output is
s any substring of the input
i₁ᶠ such that a list of all elements paired with their 1-indices
=ˢ filtered by equality
~g has only one element, of which
h the first element
~l is the length of the output.
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 67 bytes
```
X-Y:-X+Y+1.
[_|X]-Y:-X-Y.
[H|T]+[H|X]+N:-X=[],N=H,!;M is N+1,T+X+M.
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P0I30ko3QjtS21CPKzq@JiIWzNeNBPI8akJitYFkRKy2H1DMNjpWx8/WQ0fR2lchs1jBT9tQJ0Q7QttX7///aEMdIx1jHRMd01jdCD0uaxgEAA "Prolog (SWI) – Try It Online")
Uses the `-/2` predicate.
There are two parts to the code.
```
[H|T]+[H|X]+N:-X=[],N=H,!;M is N+1,T+X+M.
```
Essentially computes the shortest prefix that end in its length. However it only does this when called with `X+Y+1`.
Then we have the main predicate `-/2`
```
X-Y:-X+Y+1.
[_|X]-Y:-X-Y.
```
This matches all the prefixes of `X` than end in their length:
```
X-Y:-X+Y+1.
```
and anything that matches the tail of `X`.
```
[_|X]-Y:-X-Y.
```
That turns our predicate over prefixes to a predicate over sublists.
[Answer]
## Haskell, ~~69~~ 64 bytes
```
((1#)=<<).scanr(:)[]
l#(a:b)|l==a=[[a]]|m<-l+1=(a:)<$>m#b
_#_=[]
```
Edit: -5 bytes thanks to @Sriotchilism O'Zaic
[Try it online!](https://tio.run/##PVDLboMwELzzFSvRA1adiMU44Aj30nOlHCu5KHKi0kY1KAo95ttLd20UifVjZnZm8beffz5DWAb7sRQF5sJ2ndjOZz/dir1wfRbywu9P4h6s9dY53/f3sduEZ7SEi@7pZcxP2TE/Wtcvo79MYGH01zcorrfL9AtbGAS4DMA1EnYStIRagpJQScBeMmFKCS1VU6Y7RlJFoV6hkvgy4ul7XOskSKumjl0bex/HxPCNCpHyKxqj4kzNAGkM7SUt7aqqCWuYrMjIEKF4Hs1GYIhDHoxMFJkgSRTnRTOTgnnnXkRq1OxmUtVrJDvxWdO/GmSM7PiBOJD0mgMbxlUaqcV1Ep5bxbfqs@XvPAT/NS@b99fD4R8 "Haskell – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 59 bytes
```
(>>= \l->take 1[take x l|(i,x)<-zip[1..]l,i==x]).scanr(:)[]
```
[Try it online!](https://tio.run/##LU/LboMwEPwVH3oI0oC8GIMdFf6gX@BwsFBoURyEQg6o6reX7pLKj92Z3Z2xv@J6u6a0j@1lP3Vdqy4p757xdlUUjrCp9HOasGXv@fe0BCqKPmFq263PinWI8@N0zkK/3@M0q1bd4/Khlsc0P9WbADWqEBrUsKhgUIJ6qOA1nEajJScmDRftAbSGZkLWK6uElmMr1I47/6NQnFUgsihrlCxpGTh4kPZwR7FyaJgtDbyHYSML70DsVsNokIFhRZnzIsw3txKVsDzoZVcvUQ6W4IlBDf6PER3Lgg0zRqwcHR78DCM/6/ffYUzxc93zYVn@AA "Haskell – Try It Online")
**60 bytes**
```
f l@(h:t)=take 1[take x l|(i,x)<-zip[1..]l,i==x]++f t
f _=[]
```
[Try it online!](https://tio.run/##LU/LasMwELz3K/bQQ0ImQWs9LJUa@gP9AmGKCXFjogTT@GBKv73urlP02J3Z3Rnp3N0vp1KWpafytjm/TNtm6i4n4ryGmcrPZsC8fd1/D2Pmw6EtGJpmbne7nqannj6a3C7XbrhRQ9dufKfxa7hN9KyAesq5RoCHg0UFbkE5GUSD2mjOQlop@hUYAyOErkfmlNbjHUKUzv@olGQOzB5VQCWSXkBEApuEuBZdRC1sZZESrBh5pAgWtwBrwBZWFHUuqbDc0spcwctg0u0eohI8I7GAAPmPVR0vgrUwVq0irx7yDKs/a5ffY1@6z/uyP47jHw "Haskell – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 59 bytes
```
/(?<!\d).*?\b(\d++)(??{$1^1+$&=~y, ,,||"(*PRUNE)".say$&})^/
```
[Try it online!](https://tio.run/##NU/LasMwELz7K6bGBDt2HK0l2VIf@NRjSyn0ZhIS0kMgOKHpJTTtp1cdJRQJ7c7s7oz28P6xs@G4OiHdjrfIluldmOf9/c2wKeppP6zzYVOWRd73X5kspMwmDz@nClV1Pqf59OX17fmxSGvOZ5PvYjEPoUMLCwONBoLEKziFTiEREpoFy1QpKMJ4rplBgsQatI49/zFhNBCxaFo0FLIEDh6iPNylaBw6so2G99A0sPAOQpcWWkE0NPXinI@yfNkq0sBy0MdrrqIMVuCFoAV30FHHUrAjo6OVk4sHv6HjPr/7w@d2Px7DbLUbw@zJ1kr@AA "Perl 5 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
IEΦLθ∧‹§θι⁺²ι⬤✂θ⁻⊕ι§θιι¹⁻λ⊕μ✂θ⁻⊕ι§θι⊕ι
```
[Try it online!](https://tio.run/##lU/BasMwDP0VHxXwIIrjJmGnMhgUVijsWHoIiWkNrrcm3tjfe09LC@uxAtnWe09P8nDqp@GjDznvJh8TvfRzom3/Sa8@JDfRm4vHdKJLodU6jijnmdZpE0f3QxetPPBd@JqpkreIQqD34Acn7NZHUJs4TO7sYnIjif6uHbXXioubOGj1X38uJLR60PKel3jOeb@vtVohma1W1QpZatVaAVqtOtwljvaqqoE1QlYGJAiDPxoAHQiGwMLBwIHBG6T9c4LQygzc0siMLitW3ZL1bZ48LMOOBYBXg7lmsbcyqhHcLMu0fN1BNgbWlIdDfvoOvw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input array
L Length
Φ Filter over implicit range
§θι Value at current index
‹ Is less than
⁺²ι Current index plus 2
∧ And
⬤ For all elements of
✂θ Slice of input array
⁻⊕ι§θι From potential sequence start
ι¹ To current index
λ Value
⁻ Does not equal
⊕μ 1-indexed index
E Map over matching indices
✂θ⁻⊕ι§θι⊕ι Extract sequence including length
I Cast to string for implicit print
```
[Answer]
# [J](http://jsoftware.com/), ~~28~~ 22 bytes
```
a:-.~((#={:)\{.@#<\)\.
```
[Try it online!](https://tio.run/##xVDLSsRAELzvVxTuYRJIwjyTeeyCIHjy5DkXEYN48QMW/PVYM3mIB0ERkTy6p7qruqZf5qtOTDhHCDSQiPzaDjf3d7fzQ2y7t6o6ni@xHi/d9fE01mM314fD0@PzK6oJA3o4WBhoqBpt3JC0wClXEqomsrqwhMhtE4KElxjkrqWoYUhyRaeJJ5I@ilLSmC7PktnSVtKEgjOuYe3IhZx8HizEruoses@hayyKG0bylu79PFso5aB7aPp3PHgEugvwpWg9BqLaIAQYXsgheCjeqoeRUAaG4zIvZHn@2aqUhiMx5NcuogxOISge@rxUk3UcBQciJo/yqsygDcM11sjmf@CIu/kH8@k349J3ielvN56@oMzv "J – Try It Online")
Take the empty boxes `a:` away from `-.~` the following result:
For each postfix of the input `\.` do the following:
Filter `#` the boxed prefixes of the current input `<\` using the boolean mask which asks, also for each prefix of the current input, "Is the length equal to the last item?" `(#={:)\`.
From those boxed prefixes that *do* pass the filter, take the first one `{.@`. If *no* prefixes pass the filter, this will return the empty box `a:` (ie, the zero value of a list of boxes).
Note for J-ers: The function always returns a list of boxes, each of which contains a list of numbers. This (desirable) consistency is what creates some of the seeming inconsistencies required to correctly specify the expected values of the test cases:
* `(,:1)` -- a list containing 1
* `,:<,:1` -- a boxed list containing the list containing 1 (remember: a single box is an atom)
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~101~~ ~~98~~ ~~97~~ 95 bytes
```
j;f(*l,z){for(l+=z;z;)if((j=-*--l)&&j>~z--&&j-~l[-1]|!z)for(puts("");printf("%d ",l[++j])*j;);}
```
[Try it online!](https://tio.run/##TVLbTuMwEH3PV3iDQHYzYeM4V0z5kWweUC/gKKSoFwmllF8vM3bXchTXM3POnDlxvUpX4@v0dr0OessXI8zivN3t@ZgsZz1rYbacD8t0kaajeHgYXn7mNMU9/Rm7VPbff2ZB7M/T8cDjWOjPvZmOWx7fr1kMY5ckQy8Wgxb6cr0z02o8rTfs@XBcm93j@0uEXDadPg6y65dnCQUoXBVUF@2hnKAaWAWsBFYAU8ByYDKgKKK0GbAGV50FSOF0qUHZ5jIASwtm2JNZhnt9WgTUiqhBXlNeol7VWGUfBpyGOFTHJSV6z/ETcnJZUgHZLe4Z/jQ3VoG1msAcJVsEFPnGQouAJPeooFBBIq5orFVq3XzaqVFK7CpJqnWr@D@PghJPo5VUQC06VuXkSxpVU105M428eSDH6nau0RtffMHBzBtxth9qlpmO3H/OeNzhBYjoOlDZPBMvlTpJDLI96X4NMXx1pkfuJcLrZUQIeszXevZkdfltcgD9m2KrElkzH69m4oKdyaa9VVAh6uIcah8rUD4uoPBxCa2PK8h8XAc6jfWww@E2Y@KvyzkaEMiKIobPfnM87SeGZ3O5/gI "C (clang) – Try It Online")
-1 thanks to @ceilingcat
```
j;
f(*l,z){ // function taking a pointer and size
for(l+=z;z;) // move pointer to the end for backward iteration
if( // cascaded conditions :
(j=-*--l) // skip if value is 0 while assigning to j its negation
&&j>~z-- // skip if j>z ( before array begins)
&&j-~l[-1] // skip if previous value is 1 less than value
|!z // if z =0 previous value doesn't care
)
for(puts("") // newline to separate lists obtained
;printf("%d ",l[++j]) // print each value from j before l position
*j;);} // to l (j=0)
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 40 bytes
```
{~<<m:ov/(<<\d+>>)+?%\s<!{$0-$0.tail}>/}
```
[Try it online!](https://tio.run/##PU/tasMwDPyfp7jRbEmWrrXij9jDS18kUApboKVdRjMGpXSvnklJGf6QdDrd2V8f56MbTxc8dXgbr78xnl77n3UeY/teNk1Rbh7bIT5cU/WSqtX3bn@8NevbuPhnxpgzsx2K500@j9zZVJJQk2TYXdDl6bZYHfr9Z54tkRXo@nOS1XCwMNCoQNkyyYKCV6iV5MSg5qadCqWgGJA1Z0ZgOdbAeWbeo0CcGRBZVA4VS1ouPAJIBfipaTxqRiuNEKDZyCJ4ELs5aAXS0Kwoc0GE@WYqUQXLg0G2mUU5WEIgLhz4P1p0LAvWjGix8jR58DO0/Gz8Aw "Perl 6 – Try It Online")
Regex-based approach working with strings of space-separated numbers.
**35 bytes** when working directly with ASCII strings:
```
{~<<m:ov/(.)+?<!{$0-$0.tail.ord}>/}
```
[Try it online!](https://tio.run/##PU/tbsIwDPzfp7gJtLYrC3Hz0WTqyovwB8GqgWCd2mkTQuzVO7ugKR/2nc/n5POtP/rxdMZji9fx8lvXp5fue5mpvFjVD5e5fp5r9bXZH1XX767N8jrO/kV1na13xXrIn1aSNE1@76CCRJokw@aMNlM/3Duo7Xs/5E2jJnDo9h9ZukCao@36JK3g4WBhUILSRZJGjaBRacmJScNFNwGtoZmQdcus0HKchQ@svEehOLMgcig9SrZ0DAIiSEeEqWgDKmZLgxhheJBDDCCe5mE0yMCwo/RFMeabpUQlHDdG2fZmysERIjHw4P8Y8XFsWDFjZFSgaQY/w8jPxj8 "Perl 6 – Try It Online")
### Explanation
```
{ } # Anonymous block
m:ov/ / # Find all overlapping matches
<< # Left word boundary
\d+ # One or more digits
>> # Right word boundary
( )+? # One or more numbers, lazy
%\s # Separated by space
<!{ }> # Negative boolean condition check
$0-$0.tail # Count of numbers minus last number
~<< # Stringify matches
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~72~~ 70 bytes
-2 bytes by somehow typing `a.length` instead of `a.size` when constructing the range, but still using the correct function later down the line when checking the sequences.
```
->a{(r=0..a.size).map{|i|r.map{|j|a[i,j]}.find{|s|s[-1]==s.size}}-[p]}
```
[Try it online!](https://tio.run/##PVDLboQwDLzzFT700EoBxYQs5EB/JEIV1ULLaneFoA@1wLfTcbJdKSb2jD1jMn2@/ux9vafP7fI41TrL2mwefrun7NKOyzqsU0xOa@sHdWq2rB@ux2Wd19mn3NT1HNq3LfVjs@3f78O5o7fuY06IRup999We6eGlSbrrcfelooMiq6hQZBTlirhJvNOKKkSpUXCATWixUmswOoDx3MsCLI5F46EKI/cUsKQIZrjlMM3FxAqABodb41PdugpgpZA5VBwIIzsAcCBYNoGCgQKDN@IUlFy0lFsGmTFlRcrFKP79JLH4M8cCQEsewkR5K1al4CYuU/FtB9nYhGf5Aw "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-mR`](https://codegolf.meta.stackexchange.com/a/14339/), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
WsV
¯ÒUbÈɶY
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1S&code=V3NWCq/SVWLIybZZ&input=WzQsIDY0LCAxMTUsIDI2LCAyMCwgODUsIDExOCwgOSwgMTA5LCA4NCwgNjQsIDQ4LCA3NSwgMTIzLCA5OSwgMzIsIDM1LCA5OCwgMTQsIDU2LCAzMCwgMTMsIDMzLCA1NSwgMTE5LCA1NCwgMTksIDIzLCAxMTIsIDU4LCA3OSwgNzksIDQ1LCAxMTgsIDQ1LCA1MSwgOTEsIDExNiwgNywgNjMsIDk4LCA1MiwgMzcsIDExMywgNjQsIDgxLCA5OSwgMzAsIDgzLCA3MF0)
```
-mR //Map each element in the input to the following program, and join with newlines
//U is the element being mapped over
//V is the index
//And W is the original array
WsV //Set U to the original array, removing the first V(index) elements
¯ //Take the first n elements, where n is the following:
Ub // The first index in U which satisfies the following condition
郦Y // Where the element at that index minus one equals the index
Ò // Add 1 to that result
```
[Answer]
# Curry, 33 bytes
Tested in both [KiCS2](https://www-ps.informatik.uni-kiel.de/kics2/) and [PAKCS](https://www.informatik.uni-kiel.de/%7Epakcs/).
```
f(_++u++x:_)|x==1+length u=u++[x]
```
Curry's powerful patterns let it beat [the Haskell answer](https://codegolf.stackexchange.com/a/194326/56656) once again!
To test it you can use [Smap](https://smap.informatik.uni-kiel.de/smap.cgi?new/curry). Just select `KiCS2 2.2.0` or `PAKCS 2.2.0` with the `/all-values` option and paste the following complete code:
```
f(_++u++x:_)|x==1+length u=u++[x]
main=f [7, 6, 5, 4, 3, 2, 1]
```
[Answer]
# [PHP](https://php.net/), 90 bytes
```
for(;++$i<$c=count($argv);)for($j=$i;$c>$j;$j-$i-$n?:$c=print_r($$i))$$i[]=$n=$argv[$j++];
```
[Try it online!](https://tio.run/##ZVHRToMwFH3nK25IH0A6pRTGsEOffTLxFYkhBDfI7AgDE2P89npvgfkgo/T23NNzTrv@2Jv9Y3/sHYeNzWW8QA6FA/gUKYcth4RDzEFyiDiIks@tLOSww5GGKyIsQVpycgVD5IS2M7/XZbxS1jnBfdudVbiWa4/WOITALBFGisg9IQBZGc4hfnYLK0YspWaEUhk2JOVCIMOGoHSoIFFBYF@SnVXKZl@aaaMQuCshqWwe8epHRYKnzQQBqEXXJGf5hKxSwuUcZieWDJRYLvdVKsd5Pw9NVR/BWy69uoCtfPi2Z2bVcPjEv6Iahurr7aMZDo1X6Ol0KvlCVJbX1MczuE@6n8Z7cOEWunOrPZeDu/IQc1/18zQS5VW7yqC3p4KAtXtW5/V50qNn7XzlU4t1OWsVqx9Yp1i3Ye2G6cd7pPZDq8c3JLDW9/FTlDnTud1asC4ISmX@Im3g34/Mbei7G3hpLs0Ijf6EmzuLoTNeRotHFgpw3mMRbakMAh8mjXRrPCssa1r@GJOarUlMbKSJjPgF "PHP – Try It Online")
Input sequence is sent using command arguments (each number is one argument) and output is string representation of arrays using PHP's [print\_r](https://www.php.net/manual/en/function.print-r.php).
```
for(; // outer loop on $argv input items
++$i< // $i is current index, starts from second item as PHP fills first item with script's name
$c=count($argv); // $c is total number of input items
)
for( // inner loop on input items
$j=$i; // $j is inner loop's index, always starts from outer loop's index
$c>$j; // continue while inner index is less than $c
$j-$i-$n?: // THIS IS RUN LAST: if current number ($n) is equal to $j-$i ($j is incremented by one already, so $j-$i gives a position starting from 1 in the $$i)
$c=print\_r($$i) // THIS IS RUN LAST: print the $$i array and set $c to 1 to break the inner loop
)
$$i[]= // THIS IS RUN FIRST: push into an array named by value of $i (if $i=2, variable name is 2)
$n=$argv[$j++]; // THIS IS RUN FIRST: current number in index of inner loop and increment the index ($j) by one, $n also keeps current number
```
[Answer]
# [Red](http://www.red-lang.org), ~~149~~ 121 bytes
```
func[b][j: i: 0 until[if(i: i + 1)> n: length? b[j: j + 1 i: 1]if
b/(j + i) = i[print[copy/part at b j + 1 i]i: n]j = n]]
```
[Try it online!](https://tio.run/##ZVDLboMwELzzFaOcElVRvBiDjdT2H3q1fAhJaI0iFyFy6NfTMWlPCAt757VrT7fr8nG7@lD0LZb@kS6@C35oEVsoPNIc7z72e1YRL5DDG1KL@y19zl/v6LJwyHiWS4h90Z32GYgHvCL6cYpp9pfv8ec0nqcZ5xndvyHQksJAXQph6eEb1DCooFEyC6sXu@PxuCvIOgWr0KgNIZRr2syWUYp3KNfveao2GlOhtvT/7RuecAURg7JGyREMCwsHUQ52JSuLhmip4Rw0ZzFwFsKBamgF0dCMzz6Xu/BPqUgJQ6PLq3qGcjMCJyxq8DF0zjEMbIjo3MrK2oNj6PwSyy8 "Red – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 98 bytes
```
lambda s,e=enumerate:[s[i-n:i]for i,n in e([9]+s)if all(m+~j for j,m in e(s[i-n:i-1]))>0<n<=i]
```
[Try it online!](https://tio.run/##VVBBboMwELz3FXsExZG8GAcchX6EcqCqUR2BEwE59NKv012bIllisT0zOzva58/6/fBqG5qPbeynz68eFmEb61@TnfvVXtuldWd/dd3wmMEJD86DzVrTnZbcDdCPYzadfu/A9F1Mkd57ztjl@bu8@Vvjuu05O79mQ9ZWAi4CtIBSgBJQCGDd28EbKaCmqmQCY5Cq0KZTRpJaBjp@x7NMdMlDk82lDobHNREwSIVISQsKXHAszQBJDZ2SfvWuKgmrmCzIzxChOCsBhgjkxOSgyAGJVzwzOJk4nE9uRKQuzVYmVvk/jy@aNmCQAfLiJapor3lUxbiKYWrcM3BitS9y@wM "Python 3 – Try It Online")
Takes the input as a list and maps it to a list of lists where each item is a sublist of length `n` ending with item `n` for each item. Then it is filtered so that no list contains other valid length terminators.
-4 bytes thanks to Jonathan Frech
[Answer]
# [Zsh](https://www.zsh.org/), ~~35~~ 37 bytes
*+2 bytes to suppress zero-length lists*
```
for x;((s=++i-x+1,x*s>0))&&<<<$@[s,i]
```
[Try it online!](https://tio.run/##qyrO@J@moanxPy2/SKHCWkOj2FZbO1O3QttQp0Kr2M5AU1NNzcbGRsUhulgnM/a/JleagiEQGimYKRhDSJCIgYGCAZAHghCWyX8A "Zsh – Try It Online")
For each element in the input, calculate the index of where the sequence would have to start. If the start index and the element are both `>0`, then print the elements from there to the current index, inclusive.
[Answer]
# Ruby 2.7-preview1, 50 bytes
Uses Ruby 2.7's new [`Enumerable#filter_map`](https://codegolf.stackexchange.com/a/187015/11261) method. (Sorry for no TiO link; TiO is still on Ruby 2.5.5.)
```
->a{i=0
a.filter_map{|c|i+=1
c>0&&c<=i&&a[i-c,c]}
```
[Answer]
# [Icon](https://github.com/gtownsend/icon), 121 bytes
```
procedure f(b)
r:=[];i:=j:=0
while j<*b do{if*b<(i+:=1)then j+:=1&i:=0 else b[j+i]=i&put(r,b[j+1+:i])&i:=*b}
return r
end
```
[Try it online!](https://tio.run/##rVLBjoIwEL3zFaMHA9pDS6lA1/6Bf2A4LFhjiaKpuGZj/HZ3prjGs5FQOn0zffP6qGsO3f1@9IfGrs/ewiauk8hrs6q@nDatNjy6bN3OQruY1rA@XN1mWi9iN9NGJP3WdtBSOMFiDnZ3slCv2pmrjJscz33sGS3FTLsqoZppfYu87c@@Ax/Zbv3Sef/tujiJAJ@lNpt4lTOYM1AMMgaSQcpAVEPe/lj/C402oyVM4OJdb@MEI9Q9alAkXAN2wvYwhnFyC7sedS8dRGCVoYP6MLdCznkR2J/huy3gVTPnDHgQPrzPZfYJepKKQwj0PUX7U@QuFAF4gBJnjp/iUZUhllMyxVOWmJBkJwIlJgSZigwSGQTmJTkRmMrBEpppoxC4SxFVOYzsvx8FCn9SKQhALroScqBX1ConXA5iCvHQQIoRy/n7ftDN/AM "Icon – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 64 bytes
```
->a,*s{(r=0;a.find{|x|(x==r+=1)&&s<<a[0,x]};w,*a=a)while a[0];s}
```
[Try it online!](https://tio.run/##PVDRasMwDHzPV@hhlLbzhhXHTUzq/UgIw6PJVihlJNua0fbbs5PdFaxYupPuFA/fb79z7@enl6DW43k5eF2H535/3J0v02U5eT88el4tFuN2GxqtpvZan9Q6@LA6fewPHQFs6/E6p@q9@xozok/qm@4nHOjhtc26425uSkUbRVZRocgoyhVxmzVOK6oQpUbBETaxxUqtwegIpnMvC7A4Fo2bKo7cU8CSIpjhlsM0FxMrABocbo1PdesqgJVC5lBxIIzsAMCBYNkECgYKDN6IU1RyyVJuGWTGlBUpl6L495PE4s8cCwAteQiT5K1YlYKbtEzFtx1kYxOf5Q8 "Ruby – Try It Online")
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 135 bytes
```
A*B:-reverse(A,B).
[]-_. [A|Q]-[A|R]:-Q-R.
+[Q|R]:-length([Q|R],Q),\+((R*Z,X-Z,S*X,+S)).
Q/R:-N-Q,N*Z,X-Z,R*X,+X.
X//Y:-bagof(R,X/R,Y).
```
[Try it online!](https://tio.run/##vVPLbptAFN3zFVZWM/YZYHgZiFrJ@QBLwAZnOqrSiDqWKKCB1Jv8u3sHYvW5aCu1At33PedwJQbTt/1RjOfT5bJb3@XCNJ8bMzZshzvuOkqL9@5K7V4KLciWOheFKF1no4o5aZvuOD2xOUPB8W7DWLm@Ry3uUa1rbCpOKIVX5mIvCuxfW6Vt1a5Te94hFx8ejv1HVqL2Shy4e3lq2qExTO1fKs1zwQZz6ia25zib09Swm5V4u7rhYHvaxtibiR1wGPkSVja8rd6oru@fp@F50hwLwGNvTPM48dslPZu@O3KOrnUvSiJAiAix9rzKdT49DO1pnNiiBCul1BYJYpoIaVJqXHOK5ip56pCVmozKfKQ@tr4Gu@rgtv6V5zopfR8@Ve2zRBbTn7GCb@z3Pbv5I3YcIUkJ/dVbZT9Fdo7CCFLGCBIEpDOmJEUG6WdI52aUYkvVIESWISTFMbIUkmQnCH3IECHR2L3MspGlUSkDxLSY2TdaQMnFEpmkJAFdLLQ4MQFuqRJaqlTOHCQjnM@l/kCOveH/V25Z/57PfuHvbVqef3lxwv/ljtaaflnnCw "Prolog (SWI) – Try It Online")
`A*B` is `reverse(A,B)`
`A-B` is true if A is a prefix of B
`+A` is true if A is a valid encoding, i.e. length-terminated list
`A/B` is true if, given list A, B is contained within A and B is a valid encoding
`A//B` is true if, given list A, Y is the list of all valid encodings in A (if there are no valid encodings in A, `A//B` fails)
Calling predicate `///2` with the left argument a list and the right argument a variable unifies the variable with the required result. For example, `[7,6,5,4,3,2,1]S.` will unify S with the `[[7, 6, 5, 4], [5, 4, 3], [3, 2], [1]]`. The TIO link contains a helper predicate that runs all inputs with against this predicate.
### Verbose
```
prefix([],_).
prefix(_,[]):-1<0.
prefix([A|Q], [A|R]):-
prefix(Q,R).
suffix(A, B):-
reverse(B, Q),
prefix(P, Q),
reverse(A, P).
encoded([H|T]):-
length([H|T], H),
\+((suffix(P,T), encoded(P))).
f(Q, R):-
prefix(N, Q),
suffix(R, N),
reverse(R, T),
encoded(T).
g(List, All):-
bagof(Encoding, f(List, Encoding), All).
```
[Try it online!](https://tio.run/##TU7LaoNAFF03X3GXM/REah4NlG4MBLIIQcVNmYrkMTMVRIOTPhb5dzujY8jqct730jZVo6fmt@y6SytV@cdEjoIHE48KiJy/TcP3lzsloluSg@xJnTR58nyC1ObMt3IgAq17sZU/sjWSrUEJx90cezjK1h/btKxPzVmemdjesqG8krW@fg0EaOsyn8@M@ZkYGQeNqZhz26HsJ5Q@frb3Yz6UgvaP2xZnDo81mS3RbFeaKyiqqr7peNCNYhvnKGsNUl4fGT5Yg67TTISYYY4FlnnPFtKbTF8sVqBX0BK0AM1BM1BojR88@Ac "Prolog (SWI) – Try It Online")
The tricks used from this verbose solution is to first create another predicate for `reverse` because it is repeated many times. Then operators are used in place of predicate names. The predicate for suffix turns out to only be used once, so it can be removed, replacing its call in `f` with its conditions. Doing this removes the need to use `reverse(R, T)` as the suffix predicate already has the same condition.
[Answer]
# [T-SQL](https://www.microsoft.com/en-in/sql-server/sql-server-2019), 175 bytes
```
with s(r,i)as(select row_number()over(order by(rand())),*from string_split(<Comma delimited integer string>,','))select string_agg(l.i,',')from s,s l where l.r>s.r-s.i and l.r<=s.r and s.r-s.i>=0group by s.i
```
[Try it online!](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=cf7c70794e819fa77afbe78dae66c89c)
---
**Verbose version**
```
with s(r,i) as
(
select row_number() over (order by (rand())) -- Add a row number for sorting
,*
from string_split('7,6,5,4,3,2,1',',') -- to the split out integer list
)
select string_agg(l.i,',') -- then aggregate back together
from s,s l -- joining to itself
where l.r > s.r - s.i -- where the previous numbers sit in rows between [current int value] rows before
and l.r <= s.r -- and the current row
and s.r - s.i >= 0 -- and there are enough list items for the current integer value
group by s.i -- grouped to each output string
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŒʒDη.Δ¤sgQ}Q
```
[Try it online](https://tio.run/##yy9OTMpM/f//6KRTk1zObdc7N@XQkuL0wNrA//@jDXUUjHQUjHUUTHQUTGMB) or [verify all test cases](https://tio.run/##LU8xbgIxEOx5Bbp6FHm9Xp83TRoaqoj6RAFSFKVJkA4ipeATiCfwhtAj0aTgS8f4iLzyzszuztpf/Wr98TZ8N/PPzW77PG3wg0nzutuS9SMdroe/w@x2frodL6f@fbFfDHtcfl@GrmuRYUhQRMgSnQeUgDYQCiVlySoOAYG8ngdKVBmWkAvb/jMVggQRQ8yIdDOSAocERxmLqaClGhXuUC4xeIFwU4YGiEJpWOe8@vJmq0iEcdBrpIcpkwlcSDL4E60@RsOWitZVRcYdfIbWTy3v).
**Explanation:**
```
Œ # Get all sublists of the (implicit) input-list
ʒ # Filter it by:
D # Duplicate the current sublist
η # Pop the copy and push its prefixes
.Δ # Find the first prefix that's truthy for:
# (or -1 if none are)
¤ # Push the last value (without popping the list itself)
s # Swap so the list is at the top
g # Pop and push its length
Q # Check if the two values are the same
}Q # After the find_first: Check if both are the same
# (after which the filtered list is output implicitly)
```
The `¤sgQ` could alternatively be `DgÅ¿` or `Ðθ∍Q` for the same byte-count.
```
D # Duplicate the list
g # Pop the copy and push its length
Å¿ # Check if the list ends with this length as trailing value
Ð # Triplicate the list
θ # Pop one copy and push its last value
∍ # Extend/shorten another copy to this length
Q # Check if the two lists are still the same
```
[Answer]
# APL(NARS), chars 148, bytes 296
```
r←f w;i;j;v;q
k←≢w⋄r←⍬⋄i←0⋄w←(⍳k),¨w
→4×⍳k<i+←1⋄→2×⍳(j>q←≢v←i↑w)∨0=j←2⊃i⊃w⋄v←v↓⍨q-j⋄→3×⍳r≡⍬⋄→2×⍳∨/{(⍵[1]≡v[1])∧⍵⊆v}¨r
r←r,⊂v⋄→2
→0×⍳r≡⍬⋄r←{⍵[2]}¨¨r
```
because of the problem one has to know index of the element, the input set is elaborate as one set with indices (`w←(⍳k),¨w`) that in the end were removed (in `r←{⍵[2]}¨¨r`) test:
```
⎕fmt f 90 80 70
┌0─┐
│ 0│
└~─┘
⎕fmt f 100 0 2 2 2 0 0 2 4
┌5─────────────────────────────────────┐
│┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌4───────┐│
││ 0 2│ │ 2 2│ │ 2 2│ │ 0 2│ │ 0 0 2 4││
│└~───┘ └~───┘ └~───┘ └~───┘ └~───────┘2
└∊─────────────────────────────────────┘
⎕fmt f 7 6 5 4 3 2 1
┌4──────────────────────────────┐
│┌4───────┐ ┌3─────┐ ┌2───┐ ┌1─┐│
││ 7 6 5 4│ │ 5 4 3│ │ 3 2│ │ 1││
│└~───────┘ └~─────┘ └~───┘ └~─┘2
└∊──────────────────────────────┘
⎕fmt f 1 2 3 4 5
┌1───┐
│┌1─┐│
││ 1││
│└~─┘2
└∊───┘
⎕fmt f ⍬
┌0─┐
│ 0│
└~─┘
```
] |
[Question]
[
Write a program that, for the numbers 1 through 255, prints out BF code that will produce the given number in some byte of the array, plus a newline.
For example, the first four lines of the output could (and most likely will) be:
```
+
++
+++
++++
```
The winner will be the smallest: `source code + output` (in bytes).
**Clarifications & Revisions**:
* BF programs use wrapping cells.
* The output BF program must terminate with the only non-zero cell being the cell containing the number.
* Programs must be output in ascending order.
* Outputting a program for 0 is optional.
* Negative data pointers are not allowed. `<` at the first pointer will do nothing. (leave a comment if it would be more appropriate to have it throw)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 224 + 3964 = ~~5834~~ 4188 bytes
```
map {say (.[0]~'['~.[3]~'>'~.[1]~'<]')x?.[1],'>'x?.all,.[2]}o*.min({$_>>.abs.sum+6*?.[1]})>>.&{<- +>[.sign>0]x.abs},classify({0+|(grep(*%%1,(((256 X*^4)X+.[0]%256)X/-.[3]))[0]*.[1]+.[2])%256},[X] |(^27-13 xx 3),-7..-1){^256}
```
[Try it online!](https://tio.run/##RZDJboMwEIbvPMUoComNjcuSkgMJzWMgWQYRRCMktrJIIJZXp3bVqrfvX@wZTZO1hbeXExzTeqh6uIPla1KeumSSYm6GHpZH7P/G5A424ZtAjxiztC6fq699DXnWF9NeJg3M6hli3BLbmZ83xl0JgQJbwk2c8fihmEpTUlIUlHFHrLXByrxC8zEOApY8O9YNJfGMn@6KpXeabyaQgLMuf1WBJUbVWmlaJF2Xf05otsiCXm3WIEPXbYoQct49CI3ogkOi9tGlxuGbqVbCWBqG@puo6VhlK@WhgAVFztW0XRhHcDE1r4yZNp4jVdh9rWlzeYSD41yA/F/sQP@YgIx8bf8G "Perl 6 – Try It Online") (may timeout. Change the [`^27-13` to `^25-12`](https://tio.run/##RZDJboMwEIbvPMUoCsHGxgUnoQcSmsdAsgARRCMktrJIIJZXp3bVqrfvX@wZTZO1hbuXExzTeqh6uIPtaVKeumSSYm6GHpZH7P3G5A4OEVuIHjFmaV0@V0/7GvKsL6a9TBqY1TPEhB1uhjA2Js4SfAWOhFto4PFDMZWmpKQoKBM8XGuTlXmF5mPs@yx5dqwbSuKaP90VS@803ywgvmBd/qp8OxxVa6VpkXRd/jmh2SYLerVZg0xddyhCiF9dCMzoggOi9tGlxsGbpVbCWBqm@puo6VhlKxVBCAuK@NVyOIwjnDG13hmzHDxHqrB7WtPm8ggHzi9A/i92oH9MQEaetn8D) to speed up slightly at the cost of some extra output)
Outputs the shortest code in the form `*>[*>*<]>*`, where each `*` is a certain number of `+`s or `-`s. There are some extra tweaks like removing the loop if it is not needed, as well as trailing `>`s.
As far as I can tell, the output is the most golfed for this particular format.
### Explanation:
```
([X] |(^27-13 xx 3),-7..-1) # Define the search space as the cross product of:
# -13 to 13 for:
# Initialisation +++>
# Change in target [*>+++<]
# Last change >+++
# And -7 to -1 for the change in start [-->*<]
.classify({ }) # Group them by calculating
(256 X*^4) # Each of the multiples of 256
( X+.[0]%256) # Plus the initialisation
( X/-.[3]) # Divided by the change in start
grep(*%%1, ) # Filter out the whole numbers
[0] # And take the first value
# This is the amount of times the inner loop will execute
# Being Nil, converted to 0 if it is an infinite loop
*.[1] # Multiply by the change to the target cell
+.[2] # And add the final section
( )%256 # And modulo the whole lot by 256
+|0 # And floor it just to keep the .0 out
classify( ){^256} # Take the corresponding groups in order
.map( ) # And map each to
*.min({ }) # Find the minimum by:
$_>>.abs.sum # The sum of the absolute values
+6*?.[1] # Plus 6 if it loops
>>.*{ } # Then map each value to
<- +>[.sign>0] # + or - depending on the sign
x.abs # Repeated by the absolute value
{ }o # And pass this to the next code block
say # Print
(.[0]~'['~.[3]~'>'~.[1]~'<]') # The loop section
x?.all # If it is needed
,.[2] # And the final part
```
[Answer]
# Brainfuck, ~~77~~ ~~75~~ 73 + 32894 = 32967 ~~32969~~ ~~32971~~ bytes
```
++++++[->+++++++<]>+>++++++++++>+[>+[-<<<.>>>]<<.>[->+>+<<]>>[-<<+>>]<<+]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fGw7sIFS0LpShbRNrBxSMBiJdGxs9O7tYGxswbQdSYqdtA5S3A0lpg6W0Y///BwA "brainfuck – Try It Online")
output is the simplest possible
```
+
++
+++
++++
...
```
---
explanation:
```
++++++[->+++++++<]>+ set cell 2 to 43 (ascii of plus)
>++++++++++ set cell 3 to 10 (ascii of new line)
>+ set cell 4 to 1
[
>+ increment cell 5
[
-<<<.>>> decrement cell 5 and print a plus (content of cell 2)
] until cell 5 == 0
<<.> print a new line (content of cell 3)
[
->+>+<< move value of cell 4 to cell 5 & 6, setting cell 4 to 0
]
>> goto cell 6
[
-<<+>> move it's value to cell 4, setting cell 6 to 0
]
<<+ increment cell 4
] exit when cell 4 goes beyond 255 because cell contains C uchar meaning 255 + 1 == 0
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), score ~~4751~~ 4783 (812 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) + 3971)
```
ç♥←ħòqε↓F"QS₧9(2╤↑▌T~│áZk♣☺nàK╬l•▼2≡→fZ⌂▼├▄<ÖΘá6≈¡K"B∩₧∟µ#°ôQí⌡B2ô§↕*∩)V╕EôD=)O╥T⌠û◘¬dⁿ┤☻∞ô↓♫√○¬z.â\²╕ùHÑ~≡M√☻:EzLƒ→B{O◙ΔΦ_S┼╤g°▓─+dï-┌└α½╥ôRù♠3f½⌐▀Pösúô₧f☻■Aε→τΓ£╒fε▬▬►EÜ%¬╧←y═←{╤╒öú5Ñ╡♀^α☺╨▼$kEÑ■µjh≈↕█Cªü←Z#∟gV↓►S3≥╟╗K‼╞.N|⌠↨╣}5H↕ê;±↓♣≤Tj█'x╒·±ΩßL;ª$Å÷ÑPIδ`◘▌╦┼╡<√▌{òE√PPQ/h@8kq/ÖΓb6╡]≈╤æ░╣{┌‼¢ÜαT├#ΓCN∞*╬⌡↕ÜVX←Ä)◘ù⌂ëøön╗)ôö∙╬⌠☻↨F¢X╓Sż9¡φö^⌂iøFB/┌º▼┤3¶☼Zëôû⌡ôΣfcäéi╣⌠"↨√$,.ë═┴↨Φz⌡τ¢S╜{╨)z:╦@}♦*│P±Æ1x╒ΦP▄◄·╢∙xF╢cá<T╗7;▐≤←÷╛╢;½▲§║│≈⌂ƒ*'F♂☼ùrT╞·╨nG∙=♦`;á$≥┼Ω▬≡aû┼☺╥ò♥R╧╖█▓uìf↕ñ∟φÖ♣°≥←▐G▀╗┘┴÷a*▐♂9╝┬çG─⌠ñ≈☻K·⌐α⌠╡↑!≤≡¡qßτú=Θ≤C░°¡ƒ╛>╨RP○v¡I♦◘╣ô6â₧scÉ♀╣+HO┌☼<♀»?£┴≥ï½.ohaë║ëb┼âù²┌─┬]░ΘQ¥τ┘q▼$v╞Ñ╒æ±tXƒ♪>SC▌LVWª■z↑¶ßΩû↕'L╓BÅï;↑ΦB2.G╞╜&╓π♥1¥0^B0ª≤5e|☼τ5╩╘µåΩ╬◙☻xª└í∞$┐☻∙d▼}╒R⌠AU@Ω♥δÇi0î┴ ↕ù‼☼ƒ┌Aw£╧à7û«W3ùΦ╚A)P○♥Xn⌂øôEΦGB≥╢g[∟a(◘&¥◙─♂→A@┴ö≡↕9PZK║î⌂eóë≥─Åⁿ1‼╢▀ó╙ª▲╒π╗tΣ4○√;■<ä║äqñ8╠T/»q\→↔1ç°ΘZδV♀EçZ▄g┤Å╤ ┴àúJ║wµ$▄«N
```
[Run and debug it](https://staxlang.xyz/#p=87031b8e159571ee19462251539e392832d118dd547eb3a05a6b05016e854bce6c071f32f01a665a7f1fc3dc3c99e9a036f7ad4b2242ef9e1ce623f89351a1f542329315122aef2956b84593443d294fd254f49608aa64fcb402ec93190efb09aa7a2e835cfdb89748a57ef04dfb023a457a4c9f1a427b4f0affe85f53c5d167f8b2c42b648b2ddac0e0abd2935297063366aba9df509473a3939e6602fe41ee1ae7e29cd566ee161610459a25aacf1b79cd1b7bd1d594a335a5b50c5ee001d01f246b45a5fee66a68f712db43a6811b5a231c675619105333f2c7bb4b13c62e4e7cf417b97d354812883bf11905f3546adb2778d5faf1eae14c3ba6248ff6a55049eb6008ddcbc5b53cfbdd7b9545fb5050512f6840386b712f99e26236b55df7d191b0b97bda139b9ae054c323e2434eec2acef5129a56581b8e2908977f8900946ebb299394f9cef40217469b58d6538fac39aded945e7f690046422fdaa71fb433140f5a899396f593e46663848269b9f42217fb242c2e89cdc117e87af5e79b53bd7bd0297a3acb407d042ab350f1923178d5e850dc11fab6f97846b663a03c54bb373bdef31bf6beb63bab1e15bab3f77f9f2a27460b0f977254c6fad06e47f93d04603ba024f2c5ea16f06196c501d2950352cfb7dbb2758d6612a41ced9905f8f21bde47dfbbd9c1f6612ade0b39bcc28747c4f4a4f7024bfaa9e0f4b51821f3f0ad71e1e7a33de9f343b0f8ad9fbe3ed052500976ad490408b99336839e7363900cb92b484fda0f3c0caf3f9cc1f28bab2e6f686189ba8962c58397fddac4c25db0e9519de7d9711f2476c6a5d591f174589f0d3e5343dd4c5657a6fe7a1814e1ea9612274cd6428f8b3b18e842322e47c6bd26d6e303319d305e4230a6f335657c0fe735cad4e686eace0a0278a6c0a1ec24bf02f9641f7dd552f4415540ea03eb8069308cc1201297130f9fda41779ccf853796ae573397e8c84129500903586e7f009345e84742f2b6675b1c612808269d0ac40b1a4140c194f01239505a4bba8c7f65a289f2c48ffc3113b6dfa2d3a61ed5e3bb74e43409fb3bfe3c84ba8471a438cc542faf715c1a1d3187f8e95aeb560c45875adc67b48fd120c185a34aba77e624dcae4e&i=)
I started with the [optimal published programs](https://esolangs.org/wiki/Brainfuck_constants).
I used some regex-fu, to limit it to the shortest programs that use at most 2 cells. Then I trimmed any trailing `<` or `>` characters. I think this is a possibly conservative way to ensure that there are no extraneous non-zero cells at program termination.
Then I ran it through an [experimental stax program](https://staxlang.xyz/#c=Ld_X%09store+input+in+X%0Ac%22Initial+size%3A+%60%25%22P%0A%7B%0A++xx2B%0A++xVp%3ASY%7B%7BVpxaz%3Ar-f%7DM%09keep+only+substrings+that+leave+an+unused+ascii+char+after+their+removal%0A++%7C%3Dh%23%7E%0A++%25RD%7Bd%09find+the+length+of+the+longest+substring+that+occurs+the+most+times%0A++++xx_B%0A++++y%7B%7BVpxaz%3Ar-f%7DM%09keep+only+substrings+that+leave+an+unused+ascii+char+after+their+removal%0A++++%7C%3Dh%23%0A++++%3B%3D%0A++%7DhH,d%0A++xsB%0A++y%7B%7BVpxaz%3Ar-f%7DM%09keep+only+substrings+that+leave+an+unused+ascii+char+after+their+removal%0A++%7C%3Dh%0A++xn%23vn%25v*2-%0A++2l+++%09build+[excerpt,+estimated+savings]%0A++cH0%3CC%09stop+looping+when+estimated+savings+of+best+option+is+%3C+0%0A++xnhz%3ArG%0A++c%27%7E%3DlC%0A++%22Replacing+%22p+nhA].%5Cn%3Ar%3A%7Dp+%22+with+%22p+c]%3A%7Dp.++p%0A++c%7E]%2B%0A++xnh,%3ArX%0A++c%22Current+size%3A+%60%25%22P%0AWd%0AzP%27-80*P%0AL%7B%3AEr%24mY%0Ac%24Gc%7E*%0Axs%0A2l%7B%09build+literal%0A++A]_G%3Ar%0A++%22%28[%60%60%60%22]%29%22%22%60%60%241%22R%0A++%27%22%7CS%0A++_A%23%7B_%22%601%27%60GA]%3Ar%22%2B%7DM%0Am%0Az%7E%0AEs,s%2BA%2B%7E%0Ac%252%3E%7B%09are+any+replacements%3F%0A++y%251%3D%0A++%7B%09only+one+replacement%0A++++,s%2BA%2B%7E%0A++++%221%25%3Ar%22,s%2BA%2B%7E%0A++%7D%0A++%7B%0A++++yM%253%3D%0A++++%7B%09all+replacements+are+2+chars%0A++++++y%24G-,s%2BA%2B%7E%0A++++++%223%2FF1%25%3Ar%22,s%2BA%2B%7E%0A++++%7D%0A++++%7B%09general+replacements%0A++++++,s%2BA%2B%7E%0A++++++ss%7E%7E%0A++++++%22%27%60+%2FF1%25%3Ar%22,s%2BA%2B%7E%0A++++%7D%0A++++%3F%0A++%7D%0A++%3F%0A%7DM%0A,q%0A%27-80*P%0AA-%22Total+golfed+size%3A+%60%25%22P%0A%7D%09get+next+substition+char%0A%22etaoinsrhldcumfpgwybvkxjqz%22c%5E%2B%22+%21%27,-.%3A%3F%22%2BVp%2B%22%60%22%60%60%5C.*%2B%28%29[%5E%24%22-Vp%2Bs-h]%0A&i=%2B%0A%2B%2B%0A%2B%2B%2B%0A%2B%2B%2B%2B%0A%2B%2B%2B%2B%2B%0A%2B%2B%2B%2B%2B%2B%0A%2B%2B%2B%2B%2B%2B%2B%0A%2B%2B%2B%2B%2B%2B%2B%2B%0A%2B%2B%2B%2B%2B%2B%2B%2B%2B%0A%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%0A%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%0A%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%0A%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%0A%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%0A%2B%2B%2B[%3E%2B%2B%2B%2B%2B%3C-]%0A%2B%2B%2B%2B[%3E%2B%2B%2B%2B%3C-]%0A%2B%2B%2B%2B[%3E%2B%2B%2B%2B%3C-]%3E%2B%0A%2B%2B%2B[%3E%2B%2B%2B%2B%2B%2B%3C-]%0A%2B%2B%2B[%3E%2B%2B%2B%2B%2B%2B%3C-]%3E%2B%0A%2B%2B%2B%2B[%3E%2B%2B%2B%2B%2B%3C-]%0A%2B%2B%2B[%3E%2B%2B%2B%2B%2B%2B%2B%3C-]%0A%2B%2B%2B[%3E%2B%2B%2B%2B%2B%2B%2B%3C-]%3E%2B%0A%2B%2B%2B%2B[%3E%2B%2B%2B%2B%2B%2B%3C-]%3E-%0A%2B%2B%2B%2B[%3E%2B%2B%2B%2B%2B%2B%3C-]%0A%2B%2B%2B%2B%2B[%3E%2B%2B%2B%2B%2B%3C-]%0A%2B%2B%2B%2B%2B[%3E%2B%2B%2B%2B%2B%3C-]%3E%2B%0A%2B%2B%2B[%3E%2B%2B%2B%2B%2B%2B%2B%2B%2B%3C-]%0A%2B%2B%2B%2B[%3E%2B%2B%2B%2B%2B%2B%2B%3C-]%0A%2B%2B%2B%2B[%3E%2B%2B%2B%2B%2B%2B%2B%3C-]%3E%2B%0A%2B%2B%2B%2B%2B[%3E%2B%2B%2B%2B%2B%2B%3C-]%0A%2B%2B%2B%2B%2B[%3E%2B%2B%2B%2B%2B%2B%3C-]%3E%2B%0A%2B%2B%2B%2B[%3E%2B%2B%2B%2B%2B%2B%2B%2B%3C-]%0A%2B%2B%2B%2B[%3E%2B%2B%2B%2B%2B%2B%2B%2B%3C-]%3E%2B%0A--[%3E--%3C%2B%2B%2B%2B%2B%2B%2B]%3E--%0A--[%3E--%3C%2B%2B%2B%2B%2B%2B%2B]%3E-%0A--[%3E--%3C%2B%2B%2B%2B%2B%2B%2B]%0A---[%3E%2B%3C%2B%2B%2B%2B%2B%2B%2B]%0A---[%3E%2B%3C%2B%2B%2B%2B%2B%2B%2B]%3E%2B%0A---[%3E%2B%3C%2B%2B%2B%2B%2B%2B%2B]%3E%2B%2B%0A--[%3E%2B%3C%2B%2B%2B%2B%2B%2B]%3E---%0A--[%3E%2B%3C%2B%2B%2B%2B%2B%2B]%3E--%0A--[%3E%2B%3C%2B%2B%2B%2B%2B%2B]%3E-%0A--[%3E%2B%3C%2B%2B%2B%2B%2B%2B]%0A--[%3E%2B%3C%2B%2B%2B%2B%2B%2B]%3E%2B%0A--[%3E%2B%3C%2B%2B%2B%2B%2B%2B]%3E%2B%2B%0A--[%3E%2B%3C%2B%2B%2B%2B%2B%2B]%3E%2B%2B%2B%0A-[%3E%2B%3C-----]%3E----%0A-[%3E%2B%3C-----]%3E---%0A-[%3E%2B%3C-----]%3E--%0A-[%3E%2B%3C-----]%3E-%0A-[%3E%2B%3C-----]%0A-[%3E%2B%3C-----]%3E%2B%0A-[%3E%2B%3C-----]%3E%2B%2B%0A-[%3E%2B%3C-----]%3E%2B%2B%2B%0A-[%3E%2B%3C-----]%3E%2B%2B%2B%2B%0A-[%3E%2B%3C-----]%3E%2B%2B%2B%2B%2B%0A-[%3E%2B%3C%2B%2B%2B%2B%2B%2B%2B%2B%2B]%0A-[%3E%2B%3C%2B%2B%2B%2B%2B%2B%2B%2B%2B]%3E%2B%0A----[%3E%2B%3C----]%3E----%0A----[%3E%2B%3C----]%3E---%0A----[%3E%2B%3C----]%3E--%0A----[%3E%2B%3C----]%3E-%0A----[%3E%2B%3C----]%0A----[%3E%2B%3C----]%3E%2B%0A----[%3E%2B%3C----]%3E%2B%2B%0A----[%3E%2B%3C----]%3E%2B%2B%2B%0A----[%3E---%3C----]%0A----[%3E---%3C----]%3E%2B%0A----[%3E---%3C----]%3E%2B%2B%0A-[%3E%2B%3C-------]%3E---%0A-[%3E%2B%3C-------]%3E--%0A-[%3E%2B%3C-------]%3E-%0A-[%3E%2B%3C-------]%0A-[%3E%2B%3C-------]%3E%2B%0A-[%3E%2B%3C-------]%3E%2B%2B%0A-[%3E%2B%3C-------]%3E%2B%2B%2B%0A-[%3E%2B%3C---]%3E--------%0A-[%3E%2B%3C---]%3E-------%0A-[%3E%2B%3C---]%3E------%0A-[%3E%2B%3C---]%3E-----%0A-[%3E%2B%3C---]%3E----%0A-[%3E%2B%3C---]%3E---%0A-[%3E%2B%3C---]%3E--%0A-[%3E%2B%3C---]%3E-%0A-[%3E%2B%3C---]%0A-[%3E%2B%3C---]%3E%2B%0A-[%3E%2B%3C---]%3E%2B%2B%0A-[%3E%2B%3C---]%3E%2B%2B%2B%0A-[%3E%2B%3C---]%3E%2B%2B%2B%2B%0A-[%3E%2B%3C---]%3E%2B%2B%2B%2B%2B%0A-[%3E%2B%3C---]%3E%2B%2B%2B%2B%2B%2B%0A-[%3E%2B%3C---]%3E%2B%2B%2B%2B%2B%2B%2B%0A-[%3E%2B%3C---]%3E%2B%2B%2B%2B%2B%2B%2B%2B%0A-[%3E%2B%3C---]%3E%2B%2B%2B%2B%2B%2B%2B%2B%2B%0A-[%3E%2B%2B%3C-----]%3E-------%0A-[%3E%2B%2B%3C-----]%3E------%0A-[%3E%2B%2B%3C-----]%3E-----%0A-[%3E%2B%2B%3C-----]%3E----%0A-[%3E%2B%2B%3C-----]%3E---%0A-[%3E%2B%2B%3C-----]%3E--%0A-[%3E%2B%2B%3C-----]%3E-%0A-[%3E%2B%2B%3C-----]%0A-[%3E%2B%2B%3C-----]%3E%2B%0A-[%3E%2B%2B%3C-----]%3E%2B%2B%0A-[%3E%2B%2B%3C-----]%3E%2B%2B%2B%0A-[%3E%2B%2B%3C-----]%3E%2B%2B%2B%2B%0A-[%3E%2B%2B%3C-----]%3E%2B%2B%2B%2B%2B%0A-[%3E--%3C-------]%3E--%0A-[%3E--%3C-------]%3E-%0A-[%3E--%3C-------]%0A-[%3E--%3C-------]%3E%2B%0A-[%3E--%3C-------]%3E%2B%2B%0A-[%3E%2B%2B%3C%2B%2B%2B%2B%2B%2B%2B%2B%2B]%3E-%0A-[%3E%2B%2B%3C%2B%2B%2B%2B%2B%2B%2B%2B%2B]%0A-[%3E%2B%2B%3C%2B%2B%2B%2B%2B%2B%2B%2B%2B]%3E%2B%0A--------[%3E%2B%2B%2B%3C--]%0A----[%3E%2B%2B%2B%2B%2B%3C--]%3E-%0A----[%3E%2B%2B%2B%2B%2B%3C--]%0A------[%3E%2B%2B%2B%3C--]%0A----[%3E%2B%2B%2B%3C--]%3E--%0A----[%3E%2B%2B%2B%3C--]%3E-%0A----[%3E%2B%2B%2B%3C--]%0A--[%3E%2B%3C--]%3E----%0A--[%3E%2B%3C--]%3E---%0A--[%3E%2B%3C--]%3E--%0A--[%3E%2B%3C--]%3E-%0A--[%3E%2B%3C--]%0A--[%3E-%3C--]%3E-%0A--[%3E-%3C--]%0A--[%3E-%3C--]%3E%2B%0A--[%3E-%3C--]%3E%2B%2B%0A--[%3E-%3C--]%3E%2B%2B%2B%0A--[%3E-%3C--]%3E%2B%2B%2B%2B%0A----[%3E---%3C--]%0A----[%3E---%3C--]%3E%2B%0A----[%3E---%3C--]%3E%2B%2B%0A------[%3E---%3C--]%0A----[%3E-----%3C--]%0A----[%3E-----%3C--]%3E%2B%0A--------[%3E---%3C--]%0A-[%3E--%3C%2B%2B%2B%2B%2B%2B%2B%2B%2B]%3E-%0A-[%3E--%3C%2B%2B%2B%2B%2B%2B%2B%2B%2B]%0A-[%3E--%3C%2B%2B%2B%2B%2B%2B%2B%2B%2B]%3E%2B%0A-[%3E%2B%2B%3C-------]%3E--%0A-[%3E%2B%2B%3C-------]%3E-%0A-[%3E%2B%2B%3C-------]%0A-[%3E%2B%2B%3C-------]%3E%2B%0A-[%3E%2B%2B%3C-------]%3E%2B%2B%0A-[%3E--%3C-----]%3E-----%0A-[%3E--%3C-----]%3E----%0A-[%3E--%3C-----]%3E---%0A-[%3E--%3C-----]%3E--%0A-[%3E--%3C-----]%3E-%0A-[%3E--%3C-----]%0A-[%3E--%3C-----]%3E%2B%0A-[%3E--%3C-----]%3E%2B%2B%0A-[%3E--%3C-----]%3E%2B%2B%2B%0A-[%3E--%3C-----]%3E%2B%2B%2B%2B%0A-[%3E--%3C-----]%3E%2B%2B%2B%2B%2B%0A-[%3E--%3C-----]%3E%2B%2B%2B%2B%2B%2B%0A-[%3E--%3C-----]%3E%2B%2B%2B%2B%2B%2B%2B%0A-[%3E-%3C---]%3E---------%0A-[%3E-%3C---]%3E--------%0A-[%3E-%3C---]%3E-------%0A-[%3E-%3C---]%3E------%0A-[%3E-%3C---]%3E-----%0A-[%3E-%3C---]%3E----%0A-[%3E-%3C---]%3E---%0A-[%3E-%3C---]%3E--%0A-[%3E-%3C---]%3E-%0A-[%3E-%3C---]%0A-[%3E-%3C---]%3E%2B%0A-[%3E-%3C---]%3E%2B%2B%0A-[%3E-%3C---]%3E%2B%2B%2B%0A-[%3E-%3C---]%3E%2B%2B%2B%2B%0A-[%3E-%3C---]%3E%2B%2B%2B%2B%2B%0A-[%3E-%3C---]%3E%2B%2B%2B%2B%2B%2B%0A-[%3E-%3C---]%3E%2B%2B%2B%2B%2B%2B%2B%0A-[%3E-%3C---]%3E%2B%2B%2B%2B%2B%2B%2B%2B%0A-[%3E-%3C-------]%3E---%0A-[%3E-%3C-------]%3E--%0A-[%3E-%3C-------]%3E-%0A-[%3E-%3C-------]%0A-[%3E-%3C-------]%3E%2B%0A-[%3E-%3C-------]%3E%2B%2B%0A-[%3E-%3C-------]%3E%2B%2B%2B%0A----[%3E%2B%2B%2B%3C----]%3E--%0A----[%3E%2B%2B%2B%3C----]%3E-%0A----[%3E%2B%2B%2B%3C----]%0A----[%3E-%3C----]%3E---%0A----[%3E-%3C----]%3E--%0A----[%3E-%3C----]%3E-%0A----[%3E-%3C----]%0A----[%3E-%3C----]%3E%2B%0A----[%3E-%3C----]%3E%2B%2B%0A----[%3E-%3C----]%3E%2B%2B%2B%0A----[%3E-%3C----]%3E%2B%2B%2B%2B%0A-[%3E-%3C%2B%2B%2B%2B%2B%2B%2B%2B%2B]%3E-%0A-[%3E-%3C%2B%2B%2B%2B%2B%2B%2B%2B%2B]%0A-[%3E-%3C-----]%3E-----%0A-[%3E-%3C-----]%3E----%0A-[%3E-%3C-----]%3E---%0A-[%3E-%3C-----]%3E--%0A-[%3E-%3C-----]%3E-%0A-[%3E-%3C-----]%0A-[%3E-%3C-----]%3E%2B%0A-[%3E-%3C-----]%3E%2B%2B%0A-[%3E-%3C-----]%3E%2B%2B%2B%0A-[%3E-%3C-----]%3E%2B%2B%2B%2B%0A--[%3E-%3C%2B%2B%2B%2B%2B%2B]%3E---%0A--[%3E-%3C%2B%2B%2B%2B%2B%2B]%3E--%0A--[%3E-%3C%2B%2B%2B%2B%2B%2B]%3E-%0A--[%3E-%3C%2B%2B%2B%2B%2B%2B]%0A--[%3E-%3C%2B%2B%2B%2B%2B%2B]%3E%2B%0A--[%3E-%3C%2B%2B%2B%2B%2B%2B]%3E%2B%2B%0A--[%3E-%3C%2B%2B%2B%2B%2B%2B]%3E%2B%2B%2B%0A---[%3E-%3C%2B%2B%2B%2B%2B%2B%2B]%3E--%0A---[%3E-%3C%2B%2B%2B%2B%2B%2B%2B]%3E-%0A---[%3E-%3C%2B%2B%2B%2B%2B%2B%2B]%0A--[%3E%2B%2B%3C%2B%2B%2B%2B%2B%2B%2B]%0A--[%3E%2B%2B%3C%2B%2B%2B%2B%2B%2B%2B]%3E%2B%0A--[%3E%2B%2B%3C%2B%2B%2B%2B%2B%2B%2B]%3E%2B%2B%0A----[%3E--------%3C%2B]%3E-%0A----[%3E--------%3C%2B]%0A-----[%3E------%3C%2B]%3E-%0A-----[%3E------%3C%2B]%0A----[%3E-------%3C%2B]%3E-%0A----[%3E-------%3C%2B]%0A---[%3E---------%3C%2B]%0A-----[%3E-----%3C%2B]%3E-%0A-----[%3E-----%3C%2B]%0A-----[%3E------%3C%2B]%0A-----[%3E------%3C%2B]%3E%2B%0A----[%3E-------%3C%2B]%3E-%0A----[%3E-------%3C%2B]%0A-----[%3E-----%3C%2B]%0A----[%3E------%3C%2B]%3E-%0A----[%3E------%3C%2B]%0A-----[%3E----%3C%2B]%3E-%0A-----[%3E----%3C%2B]%0A----[%3E-----%3C%2B]%0A--------------%0A-------------%0A------------%0A-----------%0A----------%0A---------%0A--------%0A-------%0A------%0A-----%0A----%0A---%0A--%0A-) I wrote to generate stax programs for fixed kolmogorov-type output.
This program works by repeatedly applying string replacements. At each step, it looks for >1 length substring that occurs most frequently and replaces it with an unused character.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~707~~ ~~698~~ 410 + 3627 = ~~4334~~ ~~4325~~ 4037 bytes
```
UT≔”}⊞J5±)↷γ²⁼⎇⦃<✂f^⊗L…¬⁻←«θ↥v⊙^≔¶υSψVτ16⁷·9I⌕↘;⦃@Pmt↙ |TL ‹.bE^↷Am⟧←⪫✂«GIχ¤⟲V⁻PÀ$χ¹'$↙‖%S³6◧N=$kHIpQ×ïu|%÷I↖➙⁸≔Wλ¹ê8⌕dNK‽3H∨↥γh➙↘⊙⊕“~Oj↨-⬤…⊟⁺§◨CB℅P⌕KNEAR№K⬤X"¬S⎇⧴V⁻±6⁼✂kι×CÀ⊞‴≡w↓γ=`→P5η1C⊖OSoNυs⊘$M↙êαη↖φ¡¿:θ-γ“rJW%E(7<w¤Uφ´ρHπ←SX↔τ↧%<Tº⎇0gθμ↓⌕;σw⌈pL;Y↘YΠ⊙>ξLzλ↓⁸ι⎚|⌕ΠP″M³⧴⬤¦➙⟧⌕/δ;↥⁻ºJK⌊≡<⊖λ✳Jκ⟲➙ξ⭆|^Σ*βMπ⍘⊟;ÀU÷‹⭆◧�ωκ?σηkYOδO/Bº?lAnaK{*Kaκ◨+↧aSφ0q‖B/φx⊘⌕«³ψü✂‹º≡/yc⁴&J↙S²~⎇z§‖$SP≧”θG↘←¹⁴+⮌⪪θ⸿↑Fθ§⁺+-ι⌕-+ιG→↙¹⁴-
```
[Try it online!](https://tio.run/##dVVRa9wwDH7frwj35KDTQ2FPN2MojMGgg9J1T14eSpumgSzp5W637ddnsmUnttwegcv3yZI/S7Ly@PIwP04Pw7LcT103tPdz/0vVnz5cn059N6odgDWgARoDP@cVJK8GMyCQhB57BtZACTRYEIF52@cdwoVBC5aJxhi3xoBFpDWWCPTHyRnvwjEcAU2M4azENxokQxtbUqhZYImdDuMc6DGN1hC3TRjngwa9BpaVYmFFv4M/JMSaJFhY5WqXS4qFPhyYEJ0wuhwVUAf1vnxENQL607kEupzELPsc@vhRELq6W9xyHBc7WZIQOIN8Gs0HhwwlIOUxAwJJiLEBuMCNgByMPPzxMaSDzJbThSE9mnGmBArNIHUDvOGBBREa2@nVoUm5QRBDW0PBCIIioOu@tct9Ab1mHZueXrfoAaFArC7FMYOWbx0mscN1MehbnzeL2DDDdyMlpD1Lh@8wSQicwdwmYmGBMd6GtbrhbNtsWNE2A9H/kmEZCGkvHBDXeVQMKLslM7HzZRb9xnWOhTai0GgxrNYx2xsh7VgQUWJolkTjykS8tYy7QZym0AIZ1nG8x@mN@TQPMdHGsYwmBkmx69mQhuJ7ECImAbk6@Rabx7ZgI9L1Hu721ZG@krfT8K@bRnX4PP0Z7/ru5byvDjftM/1dfdxXO9i5RXM/ntVde2nnU6u@vw79WR3JSFHqmuzfpkurDj9e6fV5mit1rCt2uT5/HZ/av@p2@H2iLzHSpn29r77045PaIXhYpyqiAqcmUYGkYlkWvAz/AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
UT
```
Turn off space padding.
```
≔”...”θ
```
Assign a large compressed string consisting of @JonathanAllen's answers for `-128`..`-15` but with `+` and `-` signs transposed.
```
G↘←¹⁴+
```
Draw a triangle of `+`s of side 14, which generates the correct results for 1 to 14. The cursor is left in the bottom corner, although the trailing return on the compressed string will move the next output to the next line.
```
⮌⪪θ⸿
```
Split the large string on return characters and print each substring in reverse order, thus generating the results from 15 to 128.
```
↑
```
Move up a line so that the result for 128 is overwritten by the negated result for 128.
```
Fθ§⁺+-ι⌕-+ι
```
Loop through the string transposing `+` and `-` back again so that they generate the correct results for 128 to 241.
```
G→↙¹⁴-
```
Draw a triangle of `-`s of side 14, which generates the correct results for 242 to 255.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1224 + 3716 = 4940 bytes
```
⁾+-ẋ€Ɱ14ZY€U0¦j“6VⱮ×ė7¬(Ị¢ẋṀⱮM⁵Ѭkbvœ⁸½ẋƓ0⁽ṖçḟŻßɓẉḷ0Ƙ¥@ⱮZĊⱮ{ṫṇØ"ỵðẓ⁵!ḳqḄƬiỴƥṇØm@ɗẆḅƥƲ⁴ŀ-5¦€ÑɓZĖ/gPṄḌ!ẹ$ḞıƒĿỵ⁷£Q.%¦ẊiUı-M⁹ƈxṁ,CsḲtÆƇỴṄĿiæEṛⱮẒʠþƘ%ƘƙṾ ('ȥ€½⁵ḥ+,þ@ẇ&ạV|ĊuAYḃfṖƘLƥQtPƬivxHj)Ṇɓ5JṘØẓæĿøɗjḥrñþa®OṅḍṪ¥=ɼġċṫßṬỌƈrUẉçŻ½\=]€ʂ_ⱮṖ¥Ƥȥ6SṡÆcạdn;ṅⱮDɦ⁹ṢAy)~Ḷ`ẒẓMTİṂḋ|ẉ]Wɠ¿⁾Ṣ|ḷ6hẸƒⱮQ1ẏƝC@Ŀ!ʠ⁽ṃ@ƓŒQ3@ƝḊñçcZ\¥3Z¤~çD>ċọuⱮȦAẈⱮ%L3Æ¢ḞtĖė!ƇtñṪɓẓ¥Fṅ⁵shB'wṪẸ¦ṄÞṭ³ʂḶƊ³iȧṂRœŒƤ\r1Çwi6ŀỵɼḃa⁵Ṣ_Q⁸Ẹ'{|\+Æ®|ḤcʂÑ/Ɓz¶ɦÄ!ʂ"Ẋ ẓĠĠ⁷⁵QƝ¶%ṙƇḋ[^j&W×*°ḳçʂSżḊⱮ⁻IȦṄXȥlẋḅ7;⁺ḃİÞÆðLX¢1K£€Ä&X½VȮ(;Q£ḞḢ¹zG+ṅ¹LḥW³ḅd@^ẊḶJ¹T8ṛ($ȧṢzq,Ṫ⁻ȥ{Ṛ"Ḍ®Ä8QḋþɼȮhỵB"Ḍ⁶ȧZ⁵ẒNɓḃȧ¶Ƒð$Ẇ/"Eṭ*I:ØḃL}<KȦ+ṣ¥x&Ṇ£Œṫḋġ0lİḍ¿H£(ỌƝ×^Ḃ°⁽⁼UƭĠḥkQð7ṫƤżȷƘxjƑRḣqƒ$HƬ7ḳ-JµnṇṣðXŻİẉbSu×]bṾ0ƊHßçQh⁸°ƒɦSCñ_⁾ʂC⁼Ġø⁵SAʋƊİ¡⁴ÄḋẸḶwȧZẈĠ7rṀẏẉṖa¤ɱELƝȧẈṣṄk]d⁹øṇÞṡ.ạtƥṢḅ⁺ṂLpÑƘṄṡḍ⁵,Ǥ$Ọ8ṛuṚvAṖÑ1!vƤD3߶ʂа]EÞUĠ€ḋḲ⁸¬r`YḊ0ṙ5ċmṅȯ*ɲU÷pƭẉṭȦB¹ɦSNɱ)]ĠṾʋ³Øḟ23ṭð#ẆuẎṬṫVɠ(ỊỊQɼF}ịƒ$Ẏ_Ṡ'ḳOLc?ṾŀẊẎṆ⁵p"VẏAȮ⁴ⱮȦ®e®Ɱi"ÇJẊ4ñḍḲY]ḌḌẓ⁺ƙ"iṄḅoLṙfOS&}HGɼĖİĠḷuḃ³ṡıḳỊẹzq⁶ƈ£ċHZɱ.#⁶ḟUṗŀȮṘḶḲ]@¶+ḊĖ8ĖṆɗçŻŀ®ṭẇƓḄḷıM@⁷²36ɲṗ¡ḂḊ'Ṿ⁵ėƙṘ-⁺µʠṡṂ[_¤ḥṢ]ṘÐḤ½ḟ4ȷ}E¹Ṙb⁹ḅḢ¹hƬZ§Ẏẹ÷Æ$ḅoĖẉ⁹ịJ.ȥḊẋʋṄȯ1<ẎṄḲṛœ"æ)ḥ8)ḤlñA⁾%⁶LỴ⁶M4Ṙ\`ỵƊȥŀƒ⁷ḌƬƙḳƑ⁴vʂ⁻ðQpñḷḳṄœ>ṪỴƭƙɓ3[&Ḅzḅ<⁾µİṪȧ⁹C>ẹ{ẈÐlC&j?LṆṛ⁽æȤið<⁽$Ḋ7⁻FṡḅɓɱḂJoPŻẆṃṛḂ¹ẓð[1eƘ2T⁶ḟɼ7P~©ṚṙE8RƒṬẹLœẇẸịøḷ*⁾²ÄƓy€VƈɱNSẏẓѶpƲḞḅX⁹ọaœ<aỴTĠ^ðƑṙẊḅOḥŀG4ị¤ÑėÐịʠɗ=YṚċẋĠżẉịṪṁtḳṪ{ṬṃıızD/ĊvȤpḣðСþfÞ⁶ỵỊµṅḷÄ÷Vẇ\Ạ$-§OẠn^ȯfẎlḊd⁶ni¥ẓɱn¶’ṃ“¶><-][+”¤⁷
```
A full program.
**[Try it online!](https://tio.run/##JVYLUxPJGv0rC8tLEYUFgbqiG0SUZaMYEUQgIL4uIMsiC6j4qCQEgsl6ryFVJN69QIA8ajXgJEgyPeFR1T3TNZN/0fkj3tO5Vak8Zqb7O@d85zudySdTU6@@fy@6T2rrhBYoelLF9H5D0@B9fOurp4nJouu/zf24xsJ6uIWmakTeT3fwpCAuXL1ZdB@yIE09e7hghIpulR7jFg/VF93HgqyzpFC3jDzbskJCey/UXD2P0LgN6wZ1P95fC/JFEB@LlIv8IVOEhi0Oy4R68FyoXp6aEPlvPF564DebFRbailCXeZxniu5vhqvuIk0AJAtaoUF9/cI/bwviFeqfZUIjFULd1NN8TT/FvkV3ju46zlfShND8E316ug6gCV99KYj7XMcfQs3MsRXuQy1soJ9OsESnIH8BndDWClF2wiOVPMI/CXLyQ021GUdJegyYQo3XnmMnNqH5qoS23f9G98@33xfq0lMQ5xE7jzvmboPDwsuuyTOCrFihi92CRFgELFlCP2WqFZ7EJrMszU7G6H6PIMtC/SDIZxq/bB3p2zok/sK2BEmJ/J98dbYPErKkkafHw5edQFHwjEqQZJ3GecyMN/cKss1WHgHL4@lL2Aw3r1kJUBVkp/3VmXdCzT4AJZS/eVdXBPEINfAGezrvWVF6CgPguTfoUfO40FS@huWOBqH9m2902PTTskK01NIlGw8Za45GG98Qqh/Qk48Gh2m8cZDG3rHktSsAnf8wj7Vmol1oq/hSaW9kK3CMujmnr@vhMu6bY2mwlJYI0fh1idR9@Mf41eoXuIrS6BPxsk1B9uhBASCz3E8PJswkEN8xUJzHhmcbmO/FRLPhQnutI2g@JhtCdkYdsCC2qH79ZrgWVffBJ/ao4GHBC9y9SLNWgnnLCp5yGOEHVNejOljlsNbBN2i2UpBP8IEaGBqZrLrHwmepAiuyZMHTa6CINGzRnf/FlPgGzPiUHAJ1ueVS0a0Bgq6wTbbCFPsA3Wn4le5Ka3qrBuhxv7lfc8lBd6GAUHcoWbxRC86U2NH8e/QAWzy2jQARmHZTcrcV5qupkHR3Fp@fgySoacYxKf8ph7vpPvO2OoCRnVhH5v44BLgqrxfdWTM5KFXQ1m5BWnXJTNIsDzKlAmNzoRyW3jv7yz/gPnXJ/rbtVzMBELs0/rIK1qS7xpqcRDWgb9dPwRvqB3raRXdrpPE2WHhEqB6qoP9F91Ef39OjQP7MwZQWLOIx48jM8cjLSR68I9Td53ytoounWqBcXTc9nMb0ohBTBow8NtbeP@ydZ2HnQ0xTPfd3sS2WdIzL3FD4mpXo7WDpUTix4OlAKT3KVDDqbS8EuF9X6DbGnmHEA@gwxHoBwrCYHm2ZRRbBqTJiyPoYjVnpTjvfgITaKmqjW8@cjzEHTJVRAmNtn8eQzMlkgS2XZfuIxz7DgjwiI4Rsgz/qnmM@GquABLIj89B/oV1GWrChbIHHrjWyLZqFsz5SxdnJNvvgJE9KYlMzkk5q9gGywF8PS13UA7@h4ebXs1amj@Vm@F4J6J6ZuEoJON@y0mec0JScFAL0QHZo66dG3GfKj2jdvND@JSOAfOm3ojJ88XJYR9ffinwAUuPuqCDRasjdY3/0MzbBUMBLctEKSMyU90OZdhPO/VaaSrr/hO7j20Q583XjySYMI1JHzdx3wkbyJUNY45/KJ0p5uvy7HRye9vRWve26gVha1xXZ/9w8jATzkm0d6w8kLo0sPocN@Srd1QNdg1b6/I/4CTZ9goQNl4moAjdcyDhtNFsLdfT1Vn1dRmNY5prhongE4vg4/IvSOT190ybTO9PYbGWwCUVnEAj@atAENz0sUzlSB7j0sBCVjSOeoVEagz3RWqdM248IAJxJ6laTmXvbSZGFkYcyEtXl0iyO89QgTUq1NMJybKVCEgYm7b18KB/oPm/GURCTXkAae82vDW0laYEOgP4yQuUscQblWvEWm2Lpdpi3EqztOE3wcbMJ9YYfYEi534wbLqSqOweNeQrI1QMeRFcWCh5MOFMcM7ITOSkm8RqhKzIMcfzt8U9WqHGoCoosAlwbCtBDGd@fzSQwdlwB8tcwOvs41VE1@TOatSJPL/cxS5ixCaZgwTFY@VtQ5HrJ28tWyEIlT/fvt428PFPJElbIESfyaFKGGp7wyE93/98766jl9jv6N9wPF3S23uFr0owasRuIb58cxHwAc6XmzkpgGebloVcYhH6@aqVv9ZaGMoT/B9kZninl3/JASdgPY0aobQz87urREabwIHYvReByD9Q0XDeasC@NsaAeRgvzgULUCl@@DxQ4X7SAHkUeY4byASkScc@VRPv8ujQnS3paTy9eu6D7F8zYDBKJKRjSbXbylG1KTvlD@Q/msHTa5piX5TAgvmGhRSvqaLIHn9Mj5ten6PIUVENsZKcnaBwsrPQ0zRZdcNwS/hLR7JW2OudQbdG1QWNo6vfv/wM "Jelly – Try It Online")**
### How?
Almost entirely compression of current bests on [esolangs](https://esolangs.org/wiki/Brainfuck_constants) which leave only a single non-zero, with trailing tape moves removed. There is probably a way to evaluate a subset of BF programs such that they will terminate and yield the shortest solutions that'd beat this naive program. There may well also be a way to beat this by a smarter pattern-based or factorisation-building program.
```
⁾+-ẋ€Ɱ14ZY€U0¦j“ ... ’ṃ“¶><-][+”¤⁷ - Link: no arguments
⁾+- - list of characters ['+','-']
€ - for each:
ẋ - repeat
Ɱ14 - mapped across [1..14]
Z - transpose
Y€ - join each with newline characters
U0¦ - reverse the rightmost
- (now we have ["+\n++\n+++\n ...","... \n---\n--\n-"]
¤ - nilad followed by link(s) as a nilad:
“ ... ’ - a really big number compressed as base 250
“¶><-][+” - list of characters ['\n','>','<','-',']','[','+']
ṃ - decompress - use as base 7 digits [1,2,3,4,5,6,0]
j - join (the list ["+\n++...","...--\n-"]) with that
- implicit print
⁷ - a newline character
- implicit print
```
[Answer]
# [SuperMarioLang](https://github.com/charliealejo/SuperMarioLang), 231 + 32894 bytes
```
)
))++>(>+)*>[!((&(>[!*>-)-[!([!
===+"="==="=#===="=#="====#==#
+++<( ) !+< ! ( <
+===+ ( - . #=" #===="
>[!+( ( !(<
"=#++ ( #="
- (++ !.)) ))) <
) +++ #======================"
+ +++
+ ++!
!+<=#
#="
```
[Try it online!](https://tio.run/##ZU7LDsMwCLvzFZBKExSlXxDyIz31ME2T9lKnfX8GSXeaD1iWweb9eZ33@7Zfn7ftcWlNQES1clWZ60rMJ3aaa5bsaiUwM02WnJJNdlDIUBOoamEckBikBQmRsYDGLYabcQnPD3FkgJcod4@4gGfq2PQVyMiuaJEeKIN@KCDopSPnHwk07D4J/Bn/0TNb@wI "SuperMarioLang – Try It Online")
This sure can be golfed more, as the output is the most basic for brainfuck, but it took me all day to write this answer (my three children leave me little time to spare) and I'm proud that at least I managed to achieve this.
[Answer]
# Python 2, 70 + 8428 = 8498
-2 Bytes Thanks to A\_\_!
-20 Bytes Thanks to Jonathan Allan!
-229 Bytes by putting the number in the second cell
-1000ish bytes by switching from 16 to 9
```
p='+'
i=1
exec"print[p*i,i/9*p+'[>'+p*9+'<-]>'+i%9*p][i>20];i+=1;"*255
```
[Try it Online!](https://tio.run/##K6gsycjPM/r/v8BWXVudK9PWkCu1IjVZqaAoM68kukArUydT31KrQFs92k5du0DLUlvdRjcWyMxUBYrGRmfaGRnEWmdq2xpaK2kZmZr@/w8A)
[Output](https://tio.run/##ndE7TgMBFEPRnq2MaKhRNoLoqYCChtUPypdk8mxfR4Ik80LBPf7@/fn4@nxZ1@Vp2f8cfo8vp9fz2@X9/8PVp@uPN59vHzZP28e75/vDcJlO421/fNtdnl6f33fqKK7qLO/6i8N/uPlqOE1/tsxHcVVneddfmG@O4EPPGDQXiSTVJKN0lcmyXWPYXCbSVJuM03Umz/X5wLlQJKpGGakrTabrtKGhVKSqVhmra02u67XBvjglq2YZratNtuu24b48pMd2Ga/rTb7rtwBeIBAkg4ygFQyDc7AQXiJQJIuIATQMh/OwIF4kkCSTiJJVCItzsTBeJtAkm4iTdQAP8rFAXigQJaOIlJUAE3FiUF4qUCWriJW1ABfxQmBQLJAls4iW1QAbcUNwTI7SJbuIl/UAH/FDgEwQEmLDiJgVASNxRJBMElJSS46ZNQEn8USgTBSSUlOMWqgCVuKKYJkspKW2GJfrNrzEFwEzYUhMjTEyVy6YK2cEzaQhNbXG2Fy74G68O3AmDsmpOUbn6gV7417Bl/KQntpjfK5f8Df@1QDdAu0EdAM8Al@hmKHZoRqiW6Kcot4Cj8HXKOZo9qgG6RYpJ2k36UfhqxSzNLtUw3TLlNO029TjPLBOMU@zTzVQt1A5UbtRPVK/0iMzNTtVQ3VLTVOt6x8)
[Answer]
# Ruby 271 + 5363 = 5634
```
1.upto(255){|n|r=n>(o=n>128?256-n:n)??-:?+;puts o>20?(s=o.to_s(i=(3..9).find{|i|!(s=o.to_s i)[1..-2][s[0]]}).bytes;s[-1]+=s[0]%8;(s[1,9].reverse.map{|c|(c-=s[0])<0??-*-c:c>0??+*c:?-}*?>+'[>'+?+*(s[0]%8)).tr(n>o ?'+-':'','-+')+'[-<'+?+*i+'>]<<]'+(s[-1]>s[0]?'':?>+r)):r*o}
```
[Try it online!](https://tio.run/##PY7RaoQwEEV/xX0okzGboBbLbtTkQ0IoXdeCD00k0cJi/HY3a6Evw3Dn3HvHL7fHvpd8mWZHqrrGNdroOyuJS6OsLqqqP5gVFpViQtFmWuaQOVkVioTO8dl9BjJ25J3zK/Lv0d7XOMbT/y0bUZecs8rooAtjNuS3xzyEJmhWGtq9xLdLQ4Iuz1fD/fA7@DDwn69pjX0kPTsIbItUn7Ne9DJtNO@FYluuJAUtgSaB/AUh8tkTK12mgDIQAGdgFDBxrD3AkYI0bWuAkuMF@TIqAJHCPKLwudv2/Qk "Ruby – Try It Online")
Converts each value to the smallest base which doesn't contain ~~a zero~~ its initial digit at any other place, and then converts from that base. Values greater than 127 are calculated as their inverses.
---
**Non-Wrapping, 221 + 5888 = 6109**
```
1.upto(255){|n|puts n>20?(s=n.to_s(i=(3..9).find{|i|!(s=n.to_s i)[1..-2][s[0]]}).bytes;s[-1]+=s[0]%8;s[1,9].reverse.map{|c|(c-=s[0])<0??-*-c:c>0??+*c:?+}*?>+'[>'+?+*(s[0]%8)+'[-<'+?+*i+'>]<<]'+(s[-1]>s[0]?'':?>+?-)):?+*n}
```
Using the same approach as above, with non-wrapping cells.
[Try it online!](https://tio.run/##PY3RCoIwGIVfpS5im2s/aghpuj3IGJHLYBdNcRqI89ltGnR3/u@c/5x@rKd1TWDshhanWUZmb303Du5geRoL7CoLQ3t32FT4ApATeBn7nL3xx793MEQmACxV0slYqYVAPQ2NuznJEkWrDZ6u4UrOuYK@@TS9a@D96GavPdZsD5AyFoJFTBeaB0UjXQi6RIJTJDmiAeBfDwmAlTsxFHFVlgpRvE/xLSEQKsKXYISEhsgu6/oF "Ruby – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 691 + 3627 = 4318
Using the same approach as [@Neil's Charcoal answer](https://codegolf.stackexchange.com/a/189709/58563), and therefore also based on [@JonathanAllan's Jelly answer](https://codegolf.stackexchange.com/a/189701/58563).
```
_=>(a=require('zlib').inflateRawSync(Buffer('bZXRsQMhCEX/0wpDB4yNOPbfxoMLKLAvs8lyQBEBDf2I9MHXf+I3X/f9hCJVsckdBgH3gih8YHT80Kpj01zQ7dUZb9osZ0Fzfvra+qiCl6GaqTB9vTdvNn2TjiaVjvBQKG5mHS/mMBGrywc1Vl2eIzqbwFPReVjJo1+I3mLfbAOYY201Sm491vaxDM+Vh9WSaJtgfBDYUHQeVrKkqzMEaYMrWpgbMS7MtIlIry3DgztWahbqNPElykKItD4e1hgN8qyrHA1CJ/dC5Imz3WS5PeDKDdGKDvS8WqBq+reSd4lH2Gtjcr9W95ydm/8kcaaRPsNpMiHS1kjW8qWAOsFmWEdHeiw/kenG1zdqzR0bVXhy0VKVPQVesFNloU4TI5nsp4qzunLytsCheK4B2Gz0UeXobM+M3Q2NcXhx+GlF389GH53eWr31utUf90W02MVu89LZs45IhP/Qc6jx9dYoCs8W1d4vKHHO8wJ9l8y4Vd614g788IzrViKArok/CmguX/KLqSl+c7h3STZcxUYVnvwH','base64'))+'')+`
--[>-<--]>-
`+[...a.split`
`].reverse().map(s=>s.replace(/[-+]/g,c=>c>','?'+':'-')).join`
`
```
[Try it online!](https://tio.run/##XZJJk5pQAITv8yu8gUXYBGcgiabEBRBxVBTUqanMAx6brO8hCn9@wjnH7uqv@9IJaAD2UFzWdF748DuYfP@dTEkwQbC6xwiSRJfGLjFk4jxIQQ0P4GG1uUcq9yCAiCTc6/mA92Y0X55Z7lEuFLHdvu/c4FmYG2Mza7CUtntlqSyCkS6b2jmgdOHMBnI0X9vYu/lKqAlhHEkX7ShxRplwfLd/809XVy7wlVt1QYMAVcXz9FUF1VGRm6PfbPPRMYmBnTTK3lDHmWaxmamoqH14vJ2OoN5V7mO1O0A7WRd8P5htAnf2frmMON7KRJlvwHNhUnYkOxZY12GgLC4nbQ9tZNyqzlyCi4mcMnRN682s9VRHrbAIu9oBkVttd8u0vRl6vRAhH4VbqWqRNuPna9afj/WsExxrvIMLY@GrxqKxJKdSKgpByxdTbaTWiYdkRx63fsZKNw@Aww5vSzPWLP6WOFLlzN7xKnOWvgbjB3uDucp3ftUdONc@Ry1nG/Zub0O82qbFSTzq4xyXYtXd801b43kEDVEZqR13gufCNSlT2I@23jl6Umq6EiRZ1cYCdJDA3@tTIHMONzLtuyRvrlgc69GO3XuvyVP2L8UcSw7vi42hae/SYy2nUiva/isvhm@SpHfIjo0ZKm7sPAvvZ9bYVFZKeW@RYB2v3vN0sfPmoRE/CBdg@CoSwyFFEEPq64WmP6b0b5r@nNIvX9QHwzCAwWUa118vX58Mgg1EGJJDJgMliSdT3FtlCjxIsh809cmGP7zJ1Jv2xX8IivhJ0H0zkxRx3uPfCOLBZBCQw18vXpHjIoVMWoQkoawGXn/rnwNiQA36EJPCPKyjXhADt60hJv4j@szw1/c/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 3785 + 4120 = 7905 bytes
```
-->>>->>->>->>+>>->>->>->>-->+>->>->>->>->+>->>->>->>>+>->>->>->>->>>>-->+>->->>>>>-->+>->->->>>>->+>->->->>>>-->+>>->>>>>-->+>>->+>>>>-->+>>->->>>>->+>>->>>>>->+>>->+>>>>->+>>->->>>>>+>>->->>-->->->+>->+>>>-->->->+>->+>->>-->->+>+>-->+>>>-->->+>+>-->+>->>-->->>+>->+>->>-->->++>+>-->+>>>-->->++>+>-->+>-->->-->->+>+>->+>->>-->->+>+>->+>->>-->->>+>>+>>>-->->>+>>+>->>-->->++++>+>-->+>->>-->->++>+>->+>>>-->->++>+>->+>->>-->->+>+>>+>>>-->->+>+>>+>->>-->->+++>+>->+>>>-->->+++>+>->+>->->>++>->->+>>-->->>++>->->+>>->>>++>->->+>>->>>++>>>-->+>>>>++>>>-->+>+>>>++>>>-->+>>->->++>>>+>>->->->++>>>+>>-->->->++>>>+>>->>->++>>>+>>>>->++>>>+>>+>>->++>>>+>>-->+>->++>>>+>>+>->>+>>>>>>->>+>>>>>->->>+>>>>>-->->>+>>>>>->>>+>>>>>>>>+>>>>>+>>>+>>>>>-->+>>+>>>>>->+>>+>>>>>>+>>+>>>>>->>++>++>>>>>>>++>++>>>>>+>->->+>>>->+>>->->+>>>->+>->->->+>>>->+>-->->->+>>>->+>->>->+>>>->+>>>->+>>>->+>+>>->+>>>->+>-->+>->+>>>->+>->>->+>>->->+>>>->+>>->->+>+>>->+>>->->+>>->++>+>>>>>->->++>+>>>>>-->->++>+>>>>>->>++>+>>>>>>>++>+>>>>>+>>++>+>>>>>-->+>++>+>>>>>+>++>-->+>>>>>>++>-->+>>>>>->++>-->+>>>>>++>->-->+>>>>>+>->-->+>>>>>>->-->+>>>>>->->-->+>>>>>-->->-->+>>>>>->>-->+>>>>>>>-->+>>>>>+>>-->+>>>>>-->+>-->+>>>>>->+>-->+>>>>>>+>-->+>>>>>+>+>-->+>>>>>++>+>-->+>>>>>+++>+>-->+>>>>>++++>+>-->+>>>>>>++>>+>+>>>>->++>>+>+>>>>++>->>+>+>>>>+>->>+>+>>>>>->>+>+>>>>->->>+>+>>>>-->->>+>+>>>>->>>+>+>>>>>>>+>+>>>>+>>>+>+>>>>-->+>>+>+>>>>->+>>+>+>>>>>+>>+>+>>>>->->++>+>->->>>-->->++>+>->->>>->>++>+>->->>>>>++>+>->->>>+>>++>+>->->>>-->->++>++>+>>>>->>++>++>+>>>>>>++>++>+>>>>->>+>>-->+>+++>+>-->->+>>>+>->+>->>+>>>+>->+>->>+>>-->+>+>+>->->+>>-->+>->+>-->->+>>-->+>->+>->>+>>-->+>->+>+>->+>>>>+>>>->+>>>>+>>->->+>>>>+>>-->->+>>>>+>>->>+>>>>+>>>>+>>>>+>>->>+>>-->->+>>>>+>>-->->+>>+>>+>>-->->+>>-->+>+>>-->->+>>->+>+>>-->->+>>->>+>>>->->+>>>+>>>->->+>+>>+>>>->->+>->>+>>>->+>+>->>+>>++>->->+>>>+>>++>->->+>->>+>>>->+++>+>-->->++>++>->->>>->>++>++>->->>>>>++>++>->->>>->->++>+>+>>>>-->->++>+>+>>>>->>++>+>+>>>>>>++>+>+>>>>+>>++>+>+>>>>++>->>+>->->>>+>->>+>->->>>>->>+>->->>>->->>+>->->>>-->->>+>->->>>->>>+>->->>>>>>+>->->>>+>>>+>->->>>-->+>>+>->->>>->+>>+>->->>>>+>>+>->->>>+>+>>+>->->>>++>+>>+>->->>>++>++>-->+>-->->>>+>++>-->+>-->->>>>++>-->+>-->->>>->++>-->+>-->->>>++>->-->+>-->->>>+>->-->+>-->->>>>->-->+>-->->>>->->-->+>-->->>>-->->-->+>-->->>>->>-->+>-->->>>>>-->+>-->->>>+>>-->+>-->->>>-->+>-->+>-->->>>->+>-->+>-->->>>>+>-->+>-->->>>+>+>-->+>-->->>>++>+>-->+>-->->>>+++>+>-->+>-->->>>>->++>+>-->->>>->->++>+>-->->>>-->->++>+>-->->>>->>++>+>-->->>>>>++>+>-->->>>+>>++>+>-->->>>-->+>++>+>-->->>>->->->+>-->+>->+>-->->->+>-->+>->+>->>->+>-->+>->+>>->->+>-->->->+>->->->+>-->->->+>-->->->+>-->->->+>->>->+>-->->->+>>>->+>-->->->+>+>>->+>-->->->+>-->+>->+>-->->->+>->+>->+>-->->->+>-->->++>++>-->->>>->>++>++>-->->>>++>->>+>-->->>>+>->>+>-->->>>>->>+>-->->>>->->>+>-->->>>-->->>+>-->->>>->>>+>-->->>>>>>+>-->->>>+>>>+>-->->>>-->+>>+>-->->>>->+>>+>-->->>>>->->++>-->->+>>->->->++>-->->+>>-->->->++>-->->+>>->>->++>-->->+>>>>->++>-->->+>>+>>->++>-->->+>>-->+>->++>-->->+>>->->>++>-->->-->+>-->->>++>-->->-->+>->>>++>-->->-->+>->>>++>+>>+>>>>>++>+>>+>>+>>>++>+>>+>>-->->>>+>++>+>->->>>>+>++>+>->-->->>>->++>++>->->>>>->++>++>->-->->>>>++>+>->->>>>>++>+>->->>>>++>++>>->-->->>>++>->++>->->>>>++>->++>->->>>>->++>+>->>>>>->++>+>->-->->>>>++>>->->>>>>++>>->->>>>++>->+>->-->->>>->++>>->->>>>->++>>->-->->>>+>->+>->->>>>+>->+>->->>>>++>->>->->->>>+>->>->-->->>>+>->>->->>>>+>->>->->->>>>->>->-->->>>>->>->->>>>>->>->->>>>+>->->->-->->>>>->->->->>>>>->->->++>->->>->>->>+>->->>->>->>>->->>->>->>->->->>->>->>-->->->>->>->>>+++++[>++++++<-]>+[>+++>++>>++>>+++>++>+<<<<<<<<-]>-->>>-->>>>-[>+<---]<[[<]<]<<++[>>[-]--[<+>++++++]+<<<+++>-[>++<<-->-[<++++>-[>--<<++>-]]]<[>>.<<-]>+[>]->[.>]>[<<[<]>>[-]]<<[<+<<<+<<+<<<+<[<]]>>+<<<++]
```
[Try it online!](https://tio.run/##fVddit4wDDzQMHuCoIuEPHQXCqXQh8Ke/2vyxZZm5NBu2dVYP5blsex8/v3x68/P76/frxcZEZz/IfKpgSAFroi0fcsFbpUBjilEhoJ0mUZqIyYp8o6NYWRwqnHJok88Dbr94lAe7/gZpE/iMSvADSo@lhQAXwOe4vsSPGJ3L/9reoyyzHQKxwOa@6EArho55kYIajAEqIxwJ5iOwz5KoogqR5pOIWcbyaK4hLRL76tUM0DJWZPiHYzOiRoMdZPfCHfCg9PDlHDVYMasRwFHUbKICHOAapCUH4xglU3QzZVEClSmAUchLhrKHDwBTU1dPDFDHSLaAgenB@uQfGcBkUWkygaizCWIGtu0ZQ0LPs4uWy@gbGy2wQKIR8fKTVB0VfIBk9EIaYsdjI6gXQV1GGzAjneSXs6G8j77RynKvA3yyQmGZuNiHR6HIw1mx/BOq8uf2Y86i1OispQyYuplD3T3Sjk2Gn6cdfd083LpAjDvMhZ7804Nncl5ovQScim11AHqIEBlGFiQXqfafTgjOebikZ2HtVqLwBag4WUg3L0F785Lei39vryefB/oI/LoMHJwaQutL3hjaJ1B0u/R7VLiOtKvLTbDZWAVnq9L@j3H/yTzkB2LTX7ChCZOEqux16DV16qrtbXKtro6KZyPmZi@magPs2biuEHEEgDrHImFXT4UzwP5QkoZCvTkyvmfSI4tpAclrGP@eJfNdxhtI6FqLoHrk8GSmIGiycj3sSRrEWX6oK6S4ZnkB84EjkLlyTwqDbPpmD3NiGJFWT61uY8PMur3Ge2bTs2uZxH2@w82HnGD@0GEmDK28e@04GD69fs03kge275vx/mzXcFi50HuG0bY4/K@Al3mp3ylsG8YI@SlDB7HGSXiYxtZHIz9I47Yt@2M/Q56XOI72Db@nJpTdcc/Xq9/ "brainfuck – Try It Online")
This code reads a list of values and produces output in the pattern `a [> b < c ]> d`, where a, b, c and d stand for a number of '+' or '-' characters.
Except for the first and last 15 numbers, it uses the shortest constants from <https://esolangs.org/wiki/Brainfuck_constants> that follow the specified pattern.
```
[
Tape: -2 (end of values), [List of values], 0, 0, "\0 [> \0 < \0 ]> \0 \n" (the spaces are only for better readability.
Not in the actual string.
Zeroes are "not printed yet" markers.
Printed sequences will be prepended by -1.)
List of Values: charCount, class
class: -2 = end of values,
-1 = (char "+", offset 3),
0 = (char "-", offset 1),
1 = (char "-", offset 5),
2 = (char "+", offset 7)
Ascii:
] 93
[ 91
> 62
< 60
+ 43
- 45
]
[values]
-->>>->>->>->>+>>->>->>->>-->+>->>->>->>->+>->>->>->>>+>->>->>->>->>>>-->+>->->>>>>-->+>->->->>>>->+>->->->>>>-->+>>->>>>>-->+>>->+>>>>-->+>>->->>>>->+>>->>>>>->+>>->+>>>>->+>>->->>>>>+>>->->>-->->->+>->+>>>-->->->+>->+>->>-->->+>+>-->+>>>-->->+>+>-->+>->>-->->>+>->+>->>-->->++>+>-->+>>>-->->++>+>-->+>-->->-->->+>+>->+>->>-->->+>+>->+>->>-->->>+>>+>>>-->->>+>>+>->>-->->++++>+>-->+>->>-->->++>+>->+>>>-->->++>+>->+>->>-->->+>+>>+>>>-->->+>+>>+>->>-->->+++>+>->+>>>-->->+++>+>->+>->->>++>->->+>>-->->>++>->->+>>->>>++>->->+>>->>>++>>>-->+>>>>++>>>-->+>+>>>++>>>-->+>>->->++>>>+>>->->->++>>>+>>-->->->++>>>+>>->>->++>>>+>>>>->++>>>+>>+>>->++>>>+>>-->+>->++>>>+>>+>->>+>>>>>>->>+>>>>>->->>+>>>>>-->->>+>>>>>->>>+>>>>>>>>+>>>>>+>>>+>>>>>-->+>>+>>>>>->+>>+>>>>>>+>>+>>>>>->>++>++>>>>>>>++>++>>>>>+>->->+>>>->+>>->->+>>>->+>->->->+>>>->+>-->->->+>>>->+>->>->+>>>->+>>>->+>>>->+>+>>->+>>>->+>-->+>->+>>>->+>->>->+>>->->+>>>->+>>->->+>+>>->+>>->->+>>->++>+>>>>>->->++>+>>>>>-->->++>+>>>>>->>++>+>>>>>>>++>+>>>>>+>>++>+>>>>>-->+>++>+>>>>>+>++>-->+>>>>>>++>-->+>>>>>->++>-->+>>>>>++>->-->+>>>>>+>->-->+>>>>>>->-->+>>>>>->->-->+>>>>>-->->-->+>>>>>->>-->+>>>>>>>-->+>>>>>+>>-->+>>>>>-->+>-->+>>>>>->+>-->+>>>>>>+>-->+>>>>>+>+>-->+>>>>>++>+>-->+>>>>>+++>+>-->+>>>>>++++>+>-->+>>>>>>++>>+>+>>>>->++>>+>+>>>>++>->>+>+>>>>+>->>+>+>>>>>->>+>+>>>>->->>+>+>>>>-->->>+>+>>>>->>>+>+>>>>>>>+>+>>>>+>>>+>+>>>>-->+>>+>+>>>>->+>>+>+>>>>>+>>+>+>>>>->->++>+>->->>>-->->++>+>->->>>->>++>+>->->>>>>++>+>->->>>+>>++>+>->->>>-->->++>++>+>>>>->>++>++>+>>>>>>++>++>+>>>>->>+>>-->+>+++>+>-->->+>>>+>->+>->>+>>>+>->+>->>+>>-->+>+>+>->->+>>-->+>->+>-->->+>>-->+>->+>->>+>>-->+>->+>+>->+>>>>+>>>->+>>>>+>>->->+>>>>+>>-->->+>>>>+>>->>+>>>>+>>>>+>>>>+>>->>+>>-->->+>>>>+>>-->->+>>+>>+>>-->->+>>-->+>+>>-->->+>>->+>+>>-->->+>>->>+>>>->->+>>>+>>>->->+>+>>+>>>->->+>->>+>>>->+>+>->>+>>++>->->+>>>+>>++>->->+>->>+>>>->+++>+>-->->++>++>->->>>->>++>++>->->>>>>++>++>->->>>->->++>+>+>>>>-->->++>+>+>>>>->>++>+>+>>>>>>++>+>+>>>>+>>++>+>+>>>>++>->>+>->->>>+>->>+>->->>>>->>+>->->>>->->>+>->->>>-->->>+>->->>>->>>+>->->>>>>>+>->->>>+>>>+>->->>>-->+>>+>->->>>->+>>+>->->>>>+>>+>->->>>+>+>>+>->->>>++>+>>+>->->>>++>++>-->+>-->->>>+>++>-->+>-->->>>>++>-->+>-->->>>->++>-->+>-->->>>++>->-->+>-->->>>+>->-->+>-->->>>>->-->+>-->->>>->->-->+>-->->>>-->->-->+>-->->>>->>-->+>-->->>>>>-->+>-->->>>+>>-->+>-->->>>-->+>-->+>-->->>>->+>-->+>-->->>>>+>-->+>-->->>>+>+>-->+>-->->>>++>+>-->+>-->->>>+++>+>-->+>-->->>>>->++>+>-->->>>->->++>+>-->->>>-->->++>+>-->->>>->>++>+>-->->>>>>++>+>-->->>>+>>++>+>-->->>>-->+>++>+>-->->>>->->->+>-->+>->+>-->->->+>-->+>->+>->>->+>-->+>->+>>->->+>-->->->+>->->->+>-->->->+>-->->->+>-->->->+>->>->+>-->->->+>>>->+>-->->->+>+>>->+>-->->->+>-->+>->+>-->->->+>->+>->+>-->->->+>-->->++>++>-->->>>->>++>++>-->->>>++>->>+>-->->>>+>->>+>-->->>>>->>+>-->->>>->->>+>-->->>>-->->>+>-->->>>->>>+>-->->>>>>>+>-->->>>+>>>+>-->->>>-->+>>+>-->->>>->+>>+>-->->>>>->->++>-->->+>>->->->++>-->->+>>-->->->++>-->->+>>->>->++>-->->+>>>>->++>-->->+>>+>>->++>-->->+>>-->+>->++>-->->+>>->->>++>-->->-->+>-->->>++>-->->-->+>->>>++>-->->-->+>->>>++>+>>+>>>>>++>+>>+>>+>>>++>+>>+>>-->->>>+>++>+>->->>>>+>++>+>->-->->>>->++>++>->->>>>->++>++>->-->->>>>++>+>->->>>>>++>+>->->>>>++>++>>->-->->>>++>->++>->->>>>++>->++>->->>>>->++>+>->>>>>->++>+>->-->->>>>++>>->->>>>>++>>->->>>>++>->+>->-->->>>->++>>->->>>>->++>>->-->->>>+>->+>->->>>>+>->+>->->>>>++>->>->->->>>+>->>->-->->>>+>->>->->>>>+>->>->->->>>>->>->-->->>>>->>->->>>>>->>->->>>>+>->->->-->->>>>->->->->>>>>->->->++>->->>->>->>+>->->>->>->>>->->>->>->>->->->>->>->>-->->->>->>->
>>+++++[>++++++<-]>+ 31
[>+++>++>>++>>+++>++>+<<<<<<<<-] 93 62 0 62 0 93 62 31
>-->>>-->>>>-[>+<---] complete string 0 0 91 62 0 60 0 91 62 0 10
<[[<]<]<< go to first class cell
++[ repeat for each value pair
>>[-]--[<+>++++++]+< ascii plus
<<+++ add offset 3 to value
>-[ if not class = "plus 3"
>++ change charater to minus
<<-- set offset to 1
>-[ if not class = "minus 1"
<++++ set offset to 5
>-[ if not class = "minus 5"
>-- set charater to plus
<<++ set offset to 7
>- delete class value
]
]
]
<[>>.<<-] print char value plus offset times
>+[>] go to next string
- set printed marker
>[.>] print string
>[ if not end of chars
<<[<] go to cell next to next class cell
>>[-] empty two cells right (for exit if)
]<<[ else
<+<<<+<<+<<<+ reset printed markers
<[<] go to exit if cell
]
>>+ set empty cell = 1 (for scanning over non null cells)
<<< go to class cell
++ repeat if not end of values
]
```
# [brainfuck](https://github.com/TryItOnline/brainfuck) (the easy way), 41 + 32895 = 32936 bytes
```
+[>>++++++++++.+[<++++>-]<-<[>.>+<<-]>>+]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fO9rOThsO9LSjbUC0nW6sja5NtJ2enbaNjW4sUEns//8A "brainfuck – Try It Online")
```
+[ start loop (loop until overflow)
>> go to newline position
++++++++++. print newline
+[<++++>-]<- store 43 (plus)
<[ for each count
>. print plus
>+ increment next count
<<- decrement current count
]
>>+ increment next count
]
```
[Answer]
## Unofficial [Keg](https://esolangs.org/wiki/Keg) 16 + 32895 = 32911 bytes
A baseline solution for a golfing language. This is the simplest I can think of.
```
ÿï((:|\+$;)_\
')
```
[Try it online!](https://tio.run/##y05N////8P7D6zU0rGpitFWsNeNjuNQ1//8HAA)
[Answer]
# Ruby 23 + 32895 = 32918 bytes
```
256.times{|n|puts ?+*n}
```
As a baseline. This is the simplest solution I can think of.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 28 + 16640 = 16668 bytes
```
127$*+128$*-
\+
¶$`+
-
¶$'-
```
[Try it online!](https://tio.run/##K0otycxL/P@fy9DIXEVL29DIQkVLlytGm@vQNpUEbS5dEK2u@/8/AA "Retina 0.8.2 – Try It Online") Includes output for `0`. Just outputs using `+`s up to 127 and `-`s up to 255.
[Answer]
# [Scala](http://www.scala-lang.org/), 95 + 16639 = 16734 bytes
```
object M extends App{(1 to 127).map(x=>println("+"*x));(0 to 127).map(x=>println("-"*(128-x)))}
```
[Try it online!](https://tio.run/##K05OzEn8/z8/KSs1uUTBVyG1oiQ1L6VYwbGgoFrDUKEkX8HQyFxTLzexQKPC1q6gKDOvJCdPQ0lbSatCU9NawwCnCl0lLQ1DIwtdoDLN2v//AQ "Scala – Try It Online")
A simple answer which obviously is not going to win. Uses only the fact that the `-` operator (decreasing a byte) wraps back to 255.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: 4848 (1219 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) source code + 3629 bytes output)
```
'+14L×»Â'+'-:•тômG‚ΣP;e3₃ìèÕwƵÜè-½;¨Z±µΛé±V™NkKJžšë₅ušΘ(M₄+ܧ‘мoÕθÚzÇYï#J×¢θýει™₃tQØËв¿U®GƵ´GZ’¯ε¨jjØÛλÄ₅X∍µxθÆvËjS¹∊f˜«VÐZ<ÇĆ’Š2&ØÍäßÍĆlΓV₆ëßê©Œ‡ÛiyĆ=*÷Í´¢‹j,3½íµ'ž4‘û29ôãζм§x…1P|ÛéΣ=~çš5Œ±€Ô“q òǝ?ó¬Æí5¢G‘°êóÿв4LFÍK&zζb2Ó∍æïι8₃4XƵÜÙôt₁‘,Ö…6₅ÞαÇø†c÷Ûλ9…F;ĆA¬iмéλ8ä¶×ƶYΔè¡aû
v=M„ûñ]C₅Õ¶Þ*Ú`Úˆ/₃UιΩW¾eTεvˆ£nYõ¶S¼ÿ{õN9Ω¨£1w‚Ï”Xd;¹OýŒéDнĀvÌ–d=±ΛΣÃÊîD—GR>~ºD‹K¥‘l×yz.éFE1Í©ØM/ƒœOαU‘KΓO‰∍Aм‚œ2нƶþøÌ×¼āHgΩC'Λê¡-߅̾Ā–м–¿<₂δ¡áтgö¬Í~θFíнā‹°ü8[À(xï¸.›*W©¹º₅ÇмδçΛλÉFÕL4†EćÛ´ǝ{тÀ¯†ª™ŽćÉuè¬ƵÀSìFÙη¶1ȸ֛GÜlRv˜jy5mfè∞_åEηŠyo‡xÐ/™¥òÜ#Áx#м6r&₁cÿX۬ƄÌƵ₅∊бγ²Θj∞;6o·¼ýŠΩÚò›c[>ö₅¥=—ªÃ±¿ecSBÐ6Ê!ú¢E¡âìþ߃¿;Ò;„Xoƶ*∍Σǝñ"Tµ†8s®βµ4ìA|«÷γt³+<B¤špTp¸ï7Ëo[>–îiTôó檂?É8zн²ìC1ãl6+ƶå4sЌÚb(°·8ˆ´ˆŸ²ÚÌY3ŸËîÿ‘àUāçh9im„ÝĆm3ŠC×η“åX¨₄|ëPô3O<6Mþ'Ì-s{e`ζQΔ¹œP@l%¥‹èδcsÎcΘÂþ®i₅∞ð¡@`¸¿…BÎN2н>g;ΛSníÐ^Rαθ₆ΣÕ3¹ÐÔCfrQ¦7¨gfŒ|v||þÚÜvz≠pệT˜ǝ=ß·„®¡xи™#?†-Aʒ2åβ₃A¬Ão6ºтõ}Ë.&QηÕ~Δ4€@-5î^a̬.»Èõ4áL¾ò¥n
¶p›éŽžgǝSZγāmεålz₅°dβÂ~λà€Ê%zmŠиˆRη≠éwüǝΛζƵмƶdζ`SÖ₅\≠³äŸj!"(†Üćí“ŠxVöÇe#‡PÏɇ"xð®6ÊεGиe"NÊ›i.k…’Ú8:ǝ/₂ÌÜkãŽo™Áā‚ζΩ«мÁp=}ÂýõλиëÆζиîSÖt¶‚wĀθºd“
₆ŽsLвQ”ÖÜvGõƶiò{÷ÀPy/‹θÑè}¿Á5º˜¯sëØSËƶK_ÍyX∊3Øå4IOθ I+∊ÌñÙçakÞŸŒʒ椱,mεjæ‰O%<ÅtƒVöV=³ÇƶƒC¬‰xðȬM4Ïóä)∍Êfa§õØÂ,“X¾₆₄Ö¦ÈJµÿmȾÎ∍=¡YнŸV!¨J£ü|&¢cUg4e±6w™¼“fÊÙ ,Ž|šP·ùèd}ãŠÅ#GγhYÇN´¼ÁÌMGʒ§Æ1¸‚Δ:j7ΩƵAqá¢<äò´Θ•“-+>][<
“ÅвJs»
```
Output is a port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/189709/52210), so make sure to upvote him as well!
[Try it online.](https://tio.run/##HZV5U1PpEsb/91OolOCVxQICoiyKjDDDjiwDemdGZBsQhBkYNpE6BAm7ww2gGAImhEACIZCQcziBJFT1kxOqpOqtzFc4X8Tbmb@yvEt3//rp5@0fbH3d3fH9e0pqpqESn@kCxpTUlPRHurTzjxGBvjJdsghHbX5Htm6chgcurI/EZFjhSqdwPrlekI9ksQk3@Zr0DzvVbyrKtYhmx6FunPlLs4uNu1W68UMqrLSvSxvxUD/WhQrLOGZbcJxUzhF3@HdYyCLIxznGUB02sBj302UjectiMgXKXujSFzoWMrl6enhxU1zgA1/frM8tkzzKx03DWOypp6A@t9B5baXDJqy8KMBs1MQHNVtWMh9axi6@Yjlq6hWrTbrRhEP@eUBuzaxLdmx2j0VNhfdwhmUK0I4uBXvSsimMI5JTtIiBM8dF1kME4BBKPET7o7q0l1k7Aa5bOAonsa/ZczQz@XSjB2u6ZP3jJvxXW49xSh6YcJRDO8xxg05wgFNcxv2GylIsVySPC@V1Fla5DuzhWATzuH5D8794vyAwpBun@FQaPnG0XC4Y28KHWai6ZGvjVJnDQ14pzY@aisnTHQ9xMhd52CUFn2NKi1iDi@ytuLgxXFilS9u4gO@XksQ167xj@x4sr2C5Nt3nmI0iKNw/U6SjQcjD1yZyvG2BTEo9hXD5DnL1Q@EmFzkyR1gM@FuXtprb8ylYg7BmhvuHeDgqDWNJl1bbC8knNoUD01iA9wddWit7XjRJ5/wtWEFOLqYXn8fGM@AufZbJqN3YqLofM2urNcLXyKsVYrVGl06YR3E8xLG01ax4OKYgAhVLLJVQdOrHLuEuSWHBHZA9HV@5fixRJCpx9MSRVbos0I1GESA77P8Yu6BwB5YnhVqKI86TeQa5C6G8l5DujuKY1AxdOr/3M7kpSOcJNrPxkAhgXyRENl@K9Upuvu1ZdBabFLjaesczIdEx/0UHLFctzAvzfzFnDzdNqoenFF/EGSmZmCM10bfzMlh7nw9fW3vGcvo64dLntn@D85k402xj/ay8Uazc54vICT@sSZgaTYqHcv9M5s634bKZg7J@Er1bismcHesbK4z4lPxio4fvys/tpzPuUlizCTcs8HPEtpdFUHgzOQu5AXSAaR7Ry462@qdYycXCLZzTzjPGs8PTHMHXmJku82HO5yjN/THlHsMXjqst@G43kMyF5g2SV/hJNsBTPEGHOBOnQ3SaWvCUdjX7QMMA13n8AIv9L4uYPrzdDTwlp0JhPpLlMebzxuNh8sNTkglHb24qN9NpGMQKC2das7@@Syd0lseKC1ybNJX3WbDUkq2pWOSsvbhMDJ6tMTqF/d8fdvclQGxFTX3Zmq0En8UZDxqczeRig5nAYS0C2TUFuVWIpGApffBdxyuh1Ik1CmqrtU967yTkF4RLBNoG8bFNbMCICHm7/6W6jROyP3lFKnHEvaf4WM26K@rKF5v1b3GElV@fC59Q2TVY2uvZFMQK1ko6/6yjvQfk6urUzBPDExMM0wLr8Lg@bxuAnS64uw3X1qutQnwlTnWbvGQfjavc7aTHzDW9@Js5C07h5/nj8cV0fy6ds7zk91jMSK4TZ1ifFGsGdpQn6Tnw/trKOvdksD/PgXthr6QI/OR8e4OUAW463FpYi3RdbdW/EKfRqT4hw9k7nlDBSbvwwzjJcrYl3GnhznifZour16bnDHDeBvcIQldbrHclJsdDMaVdKK/qWbrGmf/yMp1iV1N7bt2@yynDynI/YuqabbQJCmY7krjIWvyNef68PcoUvawwIZfF1Y7b1VjgxLoz3jBS9mFY8h5dbbHbGHmUrW/g0ML9zAJTiaG0CIUt5pAtbGqg8D23JgxZXMRVdmkTO64KL6c0RArvHIlKQqXzdk7jBndECw9Wxv117En4xPTLIMeUbvjfsT9KtWP3uef8PvwPrvd0iakcOufn4XiQr92ox2JMqfgNy2P8jixk8xPhNPxUI9SbP6UmxmwJPvbg/dY32NZUzfzNzJLeJV8ak@0B13NSc6cAM0MxM4NoKmRMszElZi4hDy8xCJ5/T5WByTC//yT8faGzlfYhcxhjGqfeTBFOnoWLT7SHuXKScdnHhyL4yLsLyd4SD2tq0y1ylZMDoYlk2mlr7DJ0kC93JOEXbHXWTjbZLzfTtPCEZq@lM7C6298zVxtmksrE6e8tmK3m14yZYqmq7JuZ45sySU3QXnvU80C4Y3LxH6zUnQJ@G/0UEBv86PO96alFv7wsuJGYrpm4v3yQLr5//z8)
**Explanation:**
```
'+ '# Push a "+"
14L # Push a list in the range [1,14]
× # Repeat the "+" that many times as string: ["+","++","+++",...]
» # Join these strings by newlines
 # Bifurcate it (short for Duplicate & Reverse copy)
'+'-: # Replace all "+" for "-"
•тôm...ò´Θ• # Push compressed integer 18302226724133383998250107335646038608225046109581810887431446835557987256955354954509163336111304735021044106950262344427892947550841899099611054599885158084492762836812161427050275372983896356189873217422270707048679161884382784973706990123491668808316983431947218815813441209357230471947480445527653281307616982417034289994948061000591427114479102114229222423495882782326672492922269629953210111953959859902281658658439835047182218017657439552630082372181376525413759195763958434475193943488791777228373958162363214252781530693967200164833437881609482421594458966138936433283311419810119896020066082377462298326514652481546557215787238749539873039910952003326954299252586309028025200870623285261199142261807190771369911425142504345271105103035478661301795311828767848235694787283635190364512722037791815037475799545052058894119573664059402985074146226606245848663046901585891882552845134633210352731812274795773552227786140415336764040421001184646630833787917147474644077938952053956874031774587527717793206158934471919975714697099518810712871948398923739276321843455690477328633199064849928974478179435369018512187592263559949835435473650276637191671401061097340919482725489354844550472281209666291367830643727358624135371626379451084552903536762775083445643853806852513122856150361979701049267928548063465967555886420646898485890108420374549485423234679327438138302730692296669063696581268627535131608200283731275951916433249161017999011290215932205767570177905442947203826039265793694687731078121685736352831955773450680945121984143563963149079990880719573067270197057276219243821370885160589340870891346257233778661271435191351926058080186177296974642815621539128350975752011448032262905976766027084285390087966682234081285502231618383962136055937741758125210487103109250885525370548106186539295203084216890820183575639032509902729248016346072449636148699098049659529168757116706057794418245039559549604674043961198447420311513558044229534569679723496972989178091506175996419296780639212192856671882116470677803387276814324094247508763467887301684211112080372036284371596072213153957411329532202432808677726223798116216330275138697515009114689489577370759238857602332613821627667530873656034962827810927061440822808985980383150080767015247752949877604372029666921293343149038246728649404223795601960991061986482063744094221616603849190547637439116347239768975065217383194655478092271791087679802480625740835053103772632489195507735140119501008503485917456615266596210333924964188989678201446160111091052524780358620148464886929989973412559470628329156848340802659185674541202787279386158230228148429451357621709967247567009904339076971643378255946241011579618610095231079053137553024558887196808709177094386352264708730475553352082713138948975317023830903305435434148828341201637230241697870602236452176330225025183518037443992277303117971849493548326433875
"-+>][<\n" # Push string "-+>][<\n"
Åв # Convert the integer with this string as custom base
J # Join all characters together to a single string
s # Swap so the triangle of "-" we created it as the top of the stack
» # Join the strings on the stack by newlines
# (and output implicitly as result)
```
[See this 05AB1E tip of mine (section *How to compress large integers*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•тôm...ò´Θ•` is `183...875`.
[Answer]
# [Rust](https://www.rust-lang.org/) + `-O`, ~~618~~ 576 + 3953 = ~~4571~~ 4529 bytes
`-O` to turn on optimizations, otherwise TIO times out because it's too slow. If you're using cargo, use `--release` instead.
```
||{let r=|s:&str,n:i64|s.repeat(n as usize);let f=|n:i64|if n<0{r("-",-n)}else{r("+",n)};let w=|n:i64|n as u8 as i64;print!("{}",(0..256).flat_map(|n|(0..9).flat_map(|a|(-9..=a).map(move|b|(a,b))).flat_map(|x|(-9..9).map(move|c|(x,c))).flat_map(|x|(-9..10).map(move|d|(x,d))).filter_map(|(((a,b),c),d)|match(0..256).scan(a,|s,_|if *s>0{*s=w(*s+d);Some(1)}else{None}).sum(){256=>None,r if w(r*b+c)==n=>Some(format!("{}[>{}<{}]{}{}",f(a),f(b),f(d),if c!=0{">"}else{""},f(c))),_=>None}).chain(vec![r("+",n),r("-",256-n)]).min_by_key(|s|s.len())).fold(format!(""),|a,b|a+&b+"
"))}
```
[Try it online!](https://tio.run/##bVLtbtowFP2fp7h4VWtDSOnHqhYapL1AK237V1WRcRywljjIdkpZnFcfuybQMmmWZelen3PP/TKNdbvLS/i5UhbwFupd5qA0VLWRYKSQ2sGbNFbV2kJdwHckRF8GL267llkp9dKtslJVyqXk/vbm6ubmmrxGEUZ8RpZRuQS3krA2SrsBVFyYGlyNAqJs8K9u3Lpx0MeJ9t@ZaUppBz0F2gjw0DN6xs1y6hwbMkjnB3c4qPStLOsNFLUBjcENV6XSS7iYXcBiC40NBgdR1rYx8oNHvT@JEk4pHVhIQ6CKu8FBEwVn/8Csy6fTvh5K2u7l@bSEKbTdK4nB4k3QRRn7IHeM9kYXdVEEBfaYK0Qc0gjyRaMFZrDzvg2mSb2dnltnYj1Vd7feJkauJXdUA7ehst@Szfa81PcIVYB@nLSGkjGJx5p1srQymCMSo7UHb47gPsp9eNGcfdZEYjpJkuuvdywpSu6yiq@p1z44H05d3NPxQ5KknCXBruo36Ree8njB2Cnuvcc9nMCEp@@x@C/sanKCywMu3@NU6aTpkZTuRTAA/nmcllh9ZGwF1/jrbZyFdgztfNIObbqhQzvK2exHXUl6dWjMU61lh5SmoqxFdjoPntgAEjfUDBcjwdJUp/M967gYYerztnvEUbdd6FZBOcNnEZ6cxUgWg3TSkjnpZQjp8CdUG2e9BIqKVZj@mxSDl@N84n5umAiO7hW7oHS22Ga/5JZ6648Lha2oy/wzG8Jij93wfHS@GJGIMNbtwkL1axtWiuIKd7s/Alu9tLvx818)
This generates programs in the shortest of the following 3 forms:
* `+++...`
* `---...` (using underflow)
* `a[>b<c]d`, where a, b, c, and d are some number of '+' or '-' characters
Full explanation:
```
// Closure
|| {
// Repeats a string (shorthand)
let r = |s: &str, n: i64| s.repeat(n as usize);
// Formats a constant as a sequence of '+' or '-' characters (depending on sign)
let f = |n: i64| if n < 0 { r("-", -n) } else { r("+", n) };
// Wraps an i64 around a u8 cell
let w = |n: i64| n as u8 as i64;
// Print the solution
print!("{}",
// For rows [0, 255]
(0..256)
// ... map each row to its solution
// For a in [0, 8]
.flat_map(|n| (0..9)
// For b in [-9, a] (flattened to `(a, b)`)
.flat_map(|a| (-9..=a).map(move |b| (a, b)))
// For c in [-9, 8] (flattened to `((a, b), c)`)
.flat_map(|x| (-9..9).map(move |c| (x, c)))
// For d in [-9, 9] (flattened to `(((a, b), c), d)`)
.flat_map(|x| (-9..10).map(move |d| (x, d)))
// Calculate result of `a[>b<d]c`
.filter_map(|(((a, b), c), d)| {
// Loop up to 256 times to calculate the number of times X will run in `a[>X<d]`
match (0..256)
.scan(a, |s, _| {
if *s > 0 {
*s = w(*s + d);
Some(1)
} else {
None
}
})
.sum()
{
// Assume infinite loop
256 => None,
// Finite loop, ends in the value we want, now format the values
r if w(r * b + c) == n => Some(format!("{}[>{}<{}]{}{}", f(a), f(b), f(d), if c != 0 { ">" } else { "" }, f(c))),
// Finite loop, doesn't end in what we want
_ => None,
}
})
// Append the trivial cases of all '+' or '-' characters
.chain(vec![r("+", n), r("-", 256 - n)])
// Find the shortest solution
.min_by_key(|s| s.len())
)
// Join each row
.fold(format!(""), |a, b| a + &b + "
")
)
}
```
Decompressing a solution would definitely be shorter, but this was more fun in my opinion :)
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 296 + 3628 = 3924 bytes
```
12.?:&{{}if}:i{&6base:c[0:x:^:h]25:e*:|"(":a")":b{["x(:x|,,?):e".a/b*"|x=(256%|x<\\|x)>++:|".a/b*"{1{c^):^=.4={;)}{5={b}i}if.c,,^)?1+:e*}do"."^)c,-"\"b"/a*+"!{e):e}i^(:^}i"+"|x="@b/a*"b"/b*"}i"++]c^==~];^):^c,=!6.?,h):h?)e*:e*}do|$)\{+}*!*.e*{c':c'@+~}i&(:&}do];255,{n'c'@)+~{'<>-+[]'1/\=}/}/"":n
```
[Try it online!](https://tio.run/##JY5BboMwEEXPklELGDumoMJiiEPuAVjCDimWqqRqukAazNWpabf/zf9vPh6ft6f9dl8/25YXssGIyLubR0dRZYbniLZ9wxk1Tn1R4pjiAgngAAzQUAtzgvMiRMNwBDlkJoVlVklRVq/LfOq6ZWZnzkPnn1FOVjPUSr4rqpmnUpHxLgilFUKzJudB4a8PkKCZFUfowEA2pBwONAaHdzpB7R3w3QMXE9h@Ebb3kPdWK7X29S6xQh0q2YiJ4dSw8Pnf8vLCOuI@PaRyTMnGaOMLX72LEowC7uuiLAXd4xAzvlJ8Oh9528d51imf@QwA79v2Cw "GolfScript – Try It Online")
The extra byte in the output is a newline for the code for 0, removing it requires more than one byte.
This program passes through 8 916 100 448 256 BF codes, tests if it produces only one number and stores the code. In the end the shortest code for each number is printed. This is not effitient at all, it would take millions of years to end, the estimated number of bytes in the solution assumes the shortest codes are all listed in this [esolang](https://esolangs.org/wiki/Brainfuck_constants) page. This doesn't reach the memory limit or any other errors I know, it is just very slow.
```
12.?:& # Assign 12^12 = 8916100448256 to &, this represents the current BF code
{{}if}:i # This will be used to go from {code}{}if to {code}i
{ ... }do # Main loop, will be explained later
]; # Clean the stack
255,{ ... }/ # Go through every number
"":n # This removes the automatic newline that is printed
```
What is inside the `255,{ ... }/`:
```
n # Newline
'c'@+ # For the N-th number push 'cN'
~ # Execute the string, this will push the value stored in the variable, it will be an array with the shortest code for N
{'<>-+[]'1/\=}/ # Translate the array to a BF code
```
Main loop:
In the main loop there is a BF interpreter that can avoid errors. There are 3 ways something can go wrong:
1 It doesn't halt. This can be avoided by putting an operation limit. Here the limit is 14889 for the numbers 78 and 178, this means that if the code doesn't halt in 14889 operations, it is not one of the optimal codes.
2 Unpaired `[ ]`. We test if the instruction pointer left the code while searching for the pair. If it isn't necessary to look for the pair (Eg `>>]+-`), it means that that instruction is not necessary and the code will be replaced by a better one later.
3 The data pointer leaves the tape. We test if it left the tape using the same strategy used above. The tape here is only 25 bytes long, if the code needs more, it means it isn't optimal. The numbers 78 and 178 need 24 cells.
This interpreter doesn't have the `,` and `.` operations, so every BF code can be represented by a base 6 number. The problem is that a number can't start with 0, but here it isn't a problem because 0 represents `<`, which doesn't do anything at the start.
```
&6base:c # Convert & to base 6 and store the resulting array in c.
[0:x:^:h] # Push [0] and assign 0 to x, ^ and h. x= data pointer ^= instruction pointer h= operation counter
25:e # Assign 25 to e, this will be the error variable, if it is 0 something went wrong
*:| # Multiply [0] and 25 to get the tape called |
"(":a")":b # Assign "(" to a and ")" to b
{[ # Start a loop and an array
```
In this array we will have the 6 functions written as strings for easier manipulation:
```
op string
0 < x(:x|,,?):e
x(:x # Decrement x
|,,?):e # Test if the result is within the tape
1 > x):x|,,?):e # Same thing as before but with ")" instead of "("
2 - |x=(256%|x<\\|x)>++:|
|x= # Get the value from the tape
(256% # Decrement mod 256
|x<\\|x)>++:| # Replace the old value in the array, the \\ is a \ but inside a string
3 + |x=)256%|x<\\|x)>++:| # Same thing as before but with ")" instead of "("
4 [ ^)c,-{1{c^):^=.4={;)}{5={(}i}if.c,,^)?1+:e*}do!{e):e}i^(:^}i
^)c,-{ }i # If it isn't the last byte of the code
1{ .c,,^)?1+:e*}do # While the pair has not been found and the next byte to be tested is within the code
c^):^= # Get next byte
.4= if # Is it a [ ?
{;)} # Increment the counter
{5={(}i} # Decrement the counter if it is a ]
!{e):e}i # If the code ends with ] it will be counted as an error and this part solves the problem
^(:^ # Move the instruction pointer to the left, later it will be moved to the right and the ] will be read
5 ] |x={1{c^(:^=.4={;(}{5={)}i}if.c,,^(?1+:e*}do}i
|x={ }i # If the current cell is not 0
1{c^(:^=.4={;(}{5={)}i}if.c,,^(?1+:e*}do # Same thing as before but with ( and ) swapped
```
`[` always jumps to the `]` and there it decides if the things inside should be executed.
This array is very repetitive, so we replace `"x):x|,,?):e"` by `.a/b*`, this copies the code for `<` and replaces the `(` by `)`. The code for `+` is also replaced by `.a/b*`, but the code for `]` is a bit more complex. The code for `[` and `]` will be replaced by:
```
"{1{c^):^=.4={;)}{5={b}i}if.c,,^)?1+:e*}do"."^)c,-"\"b"/a*+"!{e):e}i^(:^}i"+"|x="@b/a*"b"/b*"}i"++
"{1{c^):^=.4={;)}{5={b}i}if.c,,^)?1+:e*}do" # Repeated part
."^)c,-"\ # Make a copy of it and push ^)c,- under that long string
"b"/a*+ # Replace the b by ( and concatenate the result with the ^)c,-
"!{e):e}i^(:^}i"+ # Add this to the end of the string
"|x="@ # Push |x= and get that original string
b/a*"b"/b* # Replace the ) by ( and the b by )
"}i"++ # Push }i and concatenate the 3 parts
```
Now comes the part that executes these functions, remember that this array was created inside the loop, this means it will be recreated every time it reads a byte from the code.
```
] # End the array
c^= # Get current instruction
=~ # Get the function for it and execute it
]; # Clean the stack, this replaces the ; that would have to be in every function
^):^ # Go to next instruction
c,=! # Is it NOT the last instruction?
6.?,h):h?) # Increment h and test if it is within the operation limit. It actually uses 6^6=46656 instead of 14889 to save 2 bytes.
e*:e # Updates e
*}do # Repeats everything if there were no errors
```
Now we just have to test if the output is valid and store it if it is.
```
|$ # Sort the tape
) # Separate the last number
\{+}* # Add all other numbers in the array
! # Is the sum 0?
* # This will be the only non-zero cell or 0 if the output is invalid
.e* # Change it to 0 if there was an error
{ }i # If it isn't 0 it is the code for some number, let this number be N
c # Push the code
':c'@+~ # Store it in the variable cN
&(:&}do # Go to the next code and repeat untill it gets to 0
```
The codes are tested in decreasing order, that way the shortest solutions will automatically replace the longer ones. The longest code is number 6774727080140 and that's why we started at such a big number.
Here are some versions of the code using other constants so we can see the output (only the found codes are outputted):
[Starting at 216, this tests every 3 byte code.](https://tio.run/##JY5RboMwEETPwqoFjB0ItFBpiUPuAVjCLimWqqRq@oG0mKtT0/7O25m3H/fP68N826@fbSvyCkMiZ68OLYWVHh4jmvaIMyqc@hccE1wgBhyAAWpqYY5xXoRoGI6QDplOYJllXJTV8zKfum6Z2Zlz3/lnlJNRDJVMXyXVzFEpSTvrfakRQrEm517h3u@QgmJGHKADDdmQcAho9A5nVYzKWeC7By7as/3Cb@8h742Scu3rXWKEDPLi7SgmhlPD/Ot/08sT64i7JEjSMSEToYkufHU2jDH0uK@LshR0i3zM@ErR6XzgbR/lWSdd5jIAvG3bLw "GolfScript – Try It Online")
[From 6774727080145 to 6774727080135, includes the solution for 117.](https://tio.run/##TZDBboMwEES/hVULGDsQUgjNEof8B2AJXNJYqpKq6QFpMb9OTXvpHndm5432/f5xeegv8/m9LPuiyIpdsX3dplmOPpE1F4uG/H3fPQbU9RZHVHhtDzhEOEEI2AED7KmGMcRxEqJiOEDcJX0E0yjDXb5/nsZj00wjO3Hubv40SkkrhkrGmaSSWcol9dY4XqyFUKxKuUPYtzvEoJgWG2igh6SLOHg0OIY1KkRlDfCVA@feaavDZa9L3mol5dyWK0QL6R3ciCvDa8Vc9d/o6Yk1xG3kRfEQkQ5QB2c@W@OH6P/7xEu2cea23OW5oFvgTIzPFBxPG163QZo00iY2AcDbsvwA "GolfScript – Try It Online")
[30 codes starting at a random number](https://tio.run/##JZDdjoIwEIVfZZnsAqXlz4iJo1XfQ2gCFZcmG9yAFyRDfXW2uOdyzpnzTeb78XMf9WB@n8uSZ28NdX/D8VkPT/SJrLlbNOTvmnpsUV8znFBhV@2xjXCGELAGBtjQFaYQp1mIM8MWkjptIpgnGW6K3dc8HctyntiJc7fz71FOWjFUMtlKOjBLhaTGGsdLtBCKnXPuEPb2gAQU0yKGEhpI64iDR61jWKNCVNYAXzlwaZy3Jlz3OuSVVlK@qsMK0UJ6eyfRMezOzJ3@rp4/WUncRl6UtBHpAHVw4S9r/BD99wc@tlkcu2B12BSFoD5wAcZfFBxPMb9WQZ6W0qY2BcB@Wf4A "GolfScript – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 80 + 9839 = 9919 bytes
```
for n in range(1,256):m=int(n**.5);s='+'*m;print(f">{s}[<{s}>-]<{'+'*(n-m**2)}")
```
[Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFPITNPoSgxLz1Vw1DHyNRM0yrXNjOvRCNPS0vPVNO62FZdW10r17qgCCSYpmRXXVwbbQMk7HRjbapBchp5urlaWkaatUqa//8DAA "Python 3 – Try It Online")
Expanded:
```
for n in range(1, 256):
m = int(n ** 0.5);
s = '+' * m;
print(f">{s}[<{s}>-]<{'+'*(n - m**2)}")
```
Process:
* try to do a square number amount of increments
* add the remaining +'s to the end
The program loops for 1 - 255, not including 0 because while that saves 2 bytes in the input, it adds >2 bytes to the output.
The brainfuck memory is laid out so that we have [num, square\_counter].
And it puts m +'s in square\_counter, then m +'s every time that decrements up to 0.
Then we just add n - m^2 more pluses at the end.
] |
[Question]
[
Given a positive integer ***N***, your task is to return the number of steps required by the following algorithm to reach ***N***:
1. Find the smallest triangular number ***Ti*** such that ***Ti ≥ N***. Build the corresponding list ***L = [ 1, 2, ..., i ]***.
2. While the sum of the terms of ***L*** is greater than ***N***, remove the first term from the list.
3. If the sum of the terms of ***L*** is now less than ***N***, increment ***i*** and append it to the list. Go on with step #2.
We stop as soon as ***N*** is reached. Only the first step is systematically executed. Steps #2 and #3 may not be processed at all.
### Examples
Below is an example for ***N = 11***:
[![Example](https://i.stack.imgur.com/oBofU.png)](https://i.stack.imgur.com/oBofU.png)
So the expected output for ***N = 11*** is ***4***.
Other examples:
* ***N = 5*** - We start with ***T3 = 1 + 2 + 3 = 6***, followed by ***2 + 3 = 5***. Expected output: ***2***.
* ***N = 10*** - Only the first step is required because ***10*** is a triangular number: ***T4 = 1 + 2 + 3 + 4 = 10***. Expected output: ***1***.
### First 100 values
Below are the results for ***1 ≤ N ≤ 100***:
```
1, 2, 1, 4, 2, 1, 2, 10, 2, 1, 4, 2, 6, 2, 1, 22, 8, 2, 10, 2,
1, 2, 12, 6, 2, 4, 2, 1, 16, 2, 18, 50, 2, 6, 2, 1, 22, 6, 2, 4,
26, 2, 28, 2, 1, 8, 30, 16, 2, 6, 4, 2, 36, 2, 1, 2, 4, 12, 40, 2,
42, 14, 2,108, 2, 1, 46, 2, 6, 4, 50, 2, 52, 18, 2, 4, 2, 1, 56, 12,
2, 20, 60, 4, 2, 22, 10, 2, 66, 2, 1, 4, 10, 24, 2, 40, 72, 8, 2, 6
```
### Rules
* You may write either a full program or a function, that either prints or returns the result.
* You're *required* to process any ***N ≤ 65536*** in less than one minute on mid-range hardware.
* Given enough time, your program/function *should* theoretically work for any value of ***N*** that is natively supported by your language. If it doesn't, please explain why in your answer.
* This is code golf, so the shortest answer in bytes wins!
[Answer]
## Mathematica, 79 bytes
```
Min[2#/(d=Divisors@#~Cases~_?OddQ)+d]-2⌊(2#)^.5+.5⌋+⌈Sqrt[8#+1]~Mod~1⌉&
```
### Explanation
I couldn't be bothered to implement the algorithm in the challenge, so I wanted to look for a shortcut to the solution. While I found one, unfortunately it doesn't beat the Mathematica answer that does implement the algorithm. That said, I'm sure this isn't optimally golfed yet, and there might be other languages who can benefit from this approach or some of the insights gained in the process.
So I claim that the sequence we're supposed to compute is:
**f(n) = 2\*([A212652](https://oeis.org/A212652)(n) - [A002024](https://oeis.org/A002024)(n)) + 1 + [A023532](https://oeis.org/A023532)(n-1)**
Alternatively, it's **f(n) = 1** if **n** is a triangular number and **f(n) = 2\*([A212652](https://oeis.org/A212652)(n) - [A002024](https://oeis.org/A002024)(n) + 1)** otherwise.
In the first expression, **[A023532](https://oeis.org/A023532)** simply encodes these two different cases. The other two sequences (plus 1) are the difference between the the largest integer **k** in the longest decomposition of **n** into consecutive integers **(k-i+1) + (k-i+2) + ... + k = n** and the largest integer **j** so that **1 + 2 + ... + j < n**.
In somewhat simpler words, here is how we find the answer for non-triangular numbers: first, find the largest triangular number **Tj** which is *less* than **n**. Then **j** is the penultimate integer that gets added during step **1** (because after adding **j+1** we will have exceeded **n**). Then decompose **n** into as many (or as small) consecutive integers as possible and call the maximum among these numbers **k**. The result is simply **2\*(k-j)**. The intuitive reason for this is that the maximum in the decomposition grows by **1** every other step and we stop when we reach **k**.
We need to show four things to prove that this works:
1. **f(n) = 1** for triangular numbers. This is trivially the case, because the first step simply iterates through all triangular numbers. If we hit **n** exactly during this process we're done and there was only one step to compute.
2. For all other numbers, we always end after a deletion step, never after an insertion step. That means all other **f(n)** are even.
3. In each insertion step after the first, we only add a single number. This guarantees that we'll reach a decomposition including **k** after **k-j** pairs of steps.
4. The final decomposition of **n** that we obtain is always the longest possible decomposition of **n** into consecutive integers, or in other words, it's always the decomposition of **n** with the lowest maximum among the summed numbers. In other words, the last number we add to the sum is always **[A212652](https://oeis.org/A212652)(n)**.
We've already shown why (1) is true. Next, we prove that we can't end on an insertion step except the initial one (which doesn't happen for non-triangular numbers).
Suppose we ended on an insertion step, reaching **n** after adding a value **p** to the sum. That means that before this insertion step, the value was **n-p** (*or less* if we added multiple values at once). But this insertion step was preceded by a deletion step (since we couldn't have hit **n** during step 1). The last value **q** we removed during this deletion step was necessarily less than **p** due to the way the algorithm works. But that means before we removed **q** we had **n-p+q** (*or less*) which is less than **n**. But that's a contradiction, because we would have had to stop removing integers when we hit **n-p+q** instead of removing another **q**. This proves point (2) above. So now we know that we always end on a deletion step and that therefore all non-triangular numbers have even outputs.
Next we prove (3), that each insertion step can only insert one value. This is essentially a corollary of (2). We have shown that after adding one value we cannot hit **n** exactly and since the prove was using an inequality, we also cannot end up below **n** (since then **n-p+q** would still be less than **n** and we shouldn't have removed that many values in the first place). So whenever we add a single value, we're guaranteed to exceed **n** because we went below **n** by removing a smaller value. Hence, we know that the upper end of the sum grows by **1** every other step. We know the initial value of this upper end (it's the smallest **m** such that **Tm > n**). Now we just need to figure out this upper end once we've reached the final sum. Then the number of steps is simply twice the difference (plus 1).
To do this, we prove (4), that the final sum is always the decomposition of **n** into as many integers as possible, or the decomposition where the maximum in that decomposition is minimal (i.e. it's the earliest possible decomposition). We'll again do this by contradiction (the wording in this part could be a bit more rigorous, but I've already spent way too much time on this...).
Say the earliest/longest possible decomposition of **n** is some **a + (a+1) + ... (b-1) + b**, **a ≤ b**, and say the algorithm skips it. That means at the time that **b** gets added, **a** must no longer be part of the sum. If **a** was part of the sum **s**, then we'd have **n ≤ s** at that moment. So either the sum only contains the values from **a** to **b**, which equals **n** and we stop (hence we didn't skip this decomposition), or there is at least one value less than **a** in the sum, win which case **n < s** and that value would get removed until we hit the exact sum (again, the decomposition wasn't skipped). So we'd have to get rid of **a** before adding **b**. But that means we'd have to reach a situation in which **a** is the smallest component of the sum, and the largest isn't **b** yet. However, at that point we can't remove **a**, because the sum is clearly less than **n** (since **b** is missing), so we're required to add values first until we add **b** and hit **n** exactly. This proves (4).
So taking these things together: we know that the first pair of steps gives us a maximum value of **[A002024](https://oeis.org/A002024)(n)**. We know that the maximum value of the final decomposition is **[A212652](https://oeis.org/A212652)(n)**. And we know that this maximum is incremented once in every pair of steps. Hence, the final expression is **2\*([A212652](https://oeis.org/A212652)(n) - [A002024](https://oeis.org/A002024)(n) + 1)**. This formula almost works for triangular numbers, except that for those we only need 1 step instead of 2, which is why we correct the result with the indicator function of the triangular numbers (or its inverse, whichever is more convenient).
Finally, as for the implementation. For the former sequence, I'm using the formula **MIN(odd d|n; n/d + (d-1)/2)** from OEIS. It turns out to save a few bytes if we take the factor of **2** into this expression to get **MIN(odd d|n; 2n/d + d-1)**, because that **-1** then cancels with the **+1** in my first version of **f(n)** which directly encodes the two cases for triangular and non-triangular numbers. In the code, this is:
```
Min[2#/(d=Divisors@#~Cases~_?OddQ)+d]
```
For the latter sequence (`1, 2, 2, 3, 3, 3, ...`), we can use a simple closed form:
```
⌊(2#)^.5+.5⌋
```
And finally, the inverse indicator function of the triangular numbers is **0** whenever **8n+1** is a perfect square. This can be expressed in Mathematica as
```
⌈Sqrt[8#+1]~Mod~1⌉
```
There are a lot of ways to express these last two sequences and to shift some constant offset between them, so I'm sure this is not an optimal implementation yet, but I hope this might give others a starting point to look into new approaches in their own languages.
Since I went to all this trouble, here is a plot of the sequence up to **n = 1000** (I could also compute 100k in a couple of seconds, but it doesn't really show any additional insights):
[![enter image description here](https://i.stack.imgur.com/e8IqN.png)](https://i.stack.imgur.com/e8IqN.png)
It might be interesting to look into the variations about those very straight lines, but I'll leave that to someone else...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~29 31~~ 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-3 thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833) (save a `$`, use the newer `Ä`, and use the newer `Ƒ`)
```
ÆDµ’H+ṚḞƑƇṂ
>TḢ_@Ç}‘Ḥ
RÄðċȯç
```
A monadic link that returns the result (N=65536 takes less than two seconds).
**[Try it online!](https://tio.run/##AUMAvP9qZWxsef//w4ZEwrXigJlIK@G5muG4nsaRxofhuYIKPlThuKJfQMOHfeKAmOG4pApSw4TDsMSLyK/Dp////zY1NTM2 "Jelly – Try It Online")**
### How?
For a thorough explanation of the algorithm see the [fantastic post by Martin Ender](https://codegolf.stackexchange.com/a/120570/53748).
```
ÆDµ’H+ṚḞƑƇṂ - Link 1, smallest natural number, M, that satisfies the below*, N
- * N = T(M) - T(i) for some non-negative integer i <= M
ÆD - divisors of N
µ - monadic chain separation, call that d
’ - increment d (vectorises)
H - halve (vectorises
Ṛ - reverse d
+ - add (vectorises)
Ƈ - filter keep if:
Ƒ - is invariant under:
Ḟ - floor (i.e. those which are the result of even divisors)
Ṃ - minimum
>TḢ_@Ç}‘Ḥ - Link 2, evaluate result for non-triangular: list of T(1) to T(N), N
> - T(i) > N
T - truthy indexes
Ḣ - head (yields the first i for which T(i) > N)
Ç} - call last link (1) as a monad converted to a dyad using the right argument
_@ - subtract with reverse @rguments
‘ - increment
Ḥ - double
RÄðċȯç - Main link: N
R - range -> [1,2,...,N]
Ä - reduce with addition -> [1,3,6,10,...T(N)]
ð - dyadic chain separation, call that t
ċ - count occurrences of N in t (1 if N is triangular else 0)
ç - call last link (2) as a dyad(t, N)
ȯ - or
```
---
The 29 byte full-program implementation I created of the algorithm described takes 4 min 30 for N=65536 on my laptop, so I suppose it does not count.
```
Ṁ‘ṭµS<³µ¿
ḊµS>³µ¿
0®Ḃ‘©¤ĿÐĿL’
```
[Answer]
# Mathematica, 72 bytes
```
(For[l=u=c=k=0,k!=#,c++,If[#>k,While[#>k,k+=++u],While[#<k,k-=l++]]];c)&
```
Pure function taking an integer argument.
## How it works
```
For[ ... ]
```
A `For` loop.
```
l=u=c=k=0
```
Initialization; set `l` (lower), `u` (upper), `c` (counter), and `k` (sum) to 0.
```
k!=#
```
Condition; repeat while `k` is not equal to the input.
```
c++
```
Increment; increment the counter `c`.
```
If[#>k,For[,#>k,,k+=++u],For[,#<k,,k-=l++]]
```
Body
```
If[#>k, ... ]
```
If the input is greater than `k`:
```
While[#>k,k+=++u]
```
While the input is greater than `k`, increment `u` and increment `k` by `u`.
If the input is not greater than `k`:
```
While[#<k,k-=l++]
```
While the input is less than `k`, decrement `k` by `l` and increment `l`.
```
( ... ;c)
```
Return `c` after the loop.
[Answer]
# [Python 2](https://docs.python.org/2/), 104 bytes
```
N=input();i=s=0;l=()
while N!=sum(l):exec'while sum(l)'+['<N:i+=1;l+=i,','>N:l=l[1:]'][s%2];s+=1
print s
```
[Try it online!](https://tio.run/nexus/python2#JckxCoAwDADA3VfoIGmpg3VsjU/oB0onKRiIIkbR31fB9a4EpG2/TqU9oWDvGZWu7oU416FBuVbF2uUnz/DjL2AijMGRQevZIHXQwRQcI0frEqQo7ZC8fF3tB21nLaVY@wI "Python 2 – TIO Nexus")
Alternates between adding terms to the end of the list, and removing terms from the beginning.
[Answer]
# PHP>=7.0, 74 Bytes
```
while($i=$r<=>$argn)for($s++;($r<=>$argn)==$i;)$r+=$i+1?-++$y:++$x;echo$s;
```
use the [spaceship operator](http://php.net/manual/en/migration70.new-features.php#migration70.new-features.spaceship-op)
[Try it online!](https://tio.run/nexus/php#s7EvyCjgSi0qyi@KL0otyC8qycxL16hzjffzD/F0dtW05lJJLErPszUzNTU2s/5fnpGZk6qhkmmrUmRjaweW0kzLL9JQKdbWttZAErS1Vcm01lQp0gbS2ob2utraKpVWQKLCOjU5I1@l2Pr/fwA "PHP – TIO Nexus")
Expanded
```
while($i=$r<=>$argn) # if input is not equal sum of array
for($s++; # raise count steps
($r<=>$argn)==$i;)
# so long as value compare to input has not change to lower/higher to higher/lower or equal
$r+=$i+1
?-++$y # if $i was higher remove the first integer
:++$x;} # if $i was lower add the next highest integer
echo$s; # Output steps
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~70 63 68~~ 64 bytes
EDIT:
* -7 bytes: Got rid of a space, two signs, and some parentheses by negating the sense of `a`. Fixed off-by-one errors in the explanation.
* +5 bytes: Argh, completely missed that 65536 requirement, and it turns out (1) powers of 2 are particularly expensive, because they only get hit when you get to the number itself (2) so is summing long ranges (that wrap *around* zero) all the time. Replaced the sum with a mathematical formula.
* -4 bytes: Adjusted `a` and `b` linearly to get terms in the summation formula to cancel.
`1#1` is an anonymous function taking and returning an integer.
Use as `(1#1) 100`.
```
1#1
(a#b)n|s<-a*a-b*b=sum$[a#(b+2)$n|s>8*n]++[(b#a)(-n)+1|s<8*n]
```
[Try it online!](https://tio.run/nexus/haskell#FZBNbuMwDIX3PcWHJgs7hgOTEiUKaHKRzizsNsUEmKhF3KKb3j1VliTf4/u5zOd6ONfP03V@@dx@1f/nelr3l/mj6/7U8bj@e/@mDsMj45HHYbjP3Ru17/fX0/za77/fr6/r7e0gG3no5s3S15/1aZx387jslsP6ddk@z5tuGbTftsvRd/XvMDx3y2buu7H2gzT4fXm7CUogYiQyTkEmRBBFAhIRQxKSEUcKOqGNo2hAI2poQjPqaCFMBCG0l4EQCUZIhExwQiFORCEqsSlGohETMROdWLAJE0yxgDVDhiUsY44V0kQSkpICKZKa30TKJCcV8kQWspIDOZKN3OJkspMLPuGCKx7wiBue8JbW8UKZKEJRSqBEilESJVNaGfc2mrBZSL8 "Haskell – TIO Nexus")
# How it works
* `(a#b)n` represents the current step of calculation. `a, b` are numbers in `1, 3, 5, ..`, while `n` can be either positive or negative depending on the step.
+ When in step 1 or 3, it represents the list `[(a+1)/2,(a+3)/2..(b-1)/2]` and goal number `-n`.
+ When in step 2, it represents the list `[(b+1)/2,(b+3)/2..(a-1)/2]` and goal number `n`.
* The strange correspondence between `a, b` and the lists is in order to be able to do summation with the short expression `s=a*a-b*b`.
+ In step 1 and 3, this is the same as `s= -8*sum[(a+1)/2..(b-1)/2]`.
+ In step 2, this is the same as `s=8*sum[(b+1)/2..(a-1)/2]`.
* Branching is done by having list comprehensions that produce elements in only one case each, and summing the results.
+ If `s>8*n`, then `b` is incremented by 2 before recursing.
- In step 1 and 3, this grows the list, while in step 2, this shrinks it.
+ If `s<8*n`, then recursion changes the step by swapping `a` and `b`, and negating `n`, and 1 is added to the result.
+ If `s==8*n`, then neither of the two list comprehensions gives any elements, so the sum is `0`.
* `(1#1) n` represents a dummy "stage 2" before starting, that immediately gets changed to step 1, building the list from `[1..0]=[]`.
[Answer]
# C, ~~94~~ 91 bytes
[**Try Online**](http://ideone.com/bIiKpU)
```
c;s;m;M;f(n){while(s-n){while(s<n)s+=++M;c++;if(s==n)break;while(s>n)s-=++m;c++;}return c;}
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 61 bytes
```
dsN[ddd9k4*d2*1+dv-0k2/-d1+*2/-d[q]s.0=.-lN-0lN-sNlFx]dsFxz2-
```
[Try it online!](https://tio.run/nexus/dc#HZC9bhtBDIT771FknLP8XbII0rmz4F5QleusIsEBhuCXV1YpiCk4Q87M5bEf58u@7/3pp11P8rJ/beNTf2y7vJyecPl7PV7Hz9ftdt7GmuN8e7tf9@Pt/q3b43p8XH7/@t7/U24f9z@39@fy/f4QFMMJkknRyEAEUcQQRwJJZCKFNDrQpVHUUEcDTXSihTY2MMHWScMcCyyxiRXW@MAFV3x9dDzwxCdeeBODEEIJI5ahIJKYRBFNDlJIJY10cvlNcpJFNnMwhalMYzozmCvOZBazqUEJpZRRTgWV1EpbVNODFlppo50OOulJrzKebYx/ "dc – TIO Nexus")
## Explanation
Main recursive macro:
```
ddd9k4*d2*1+dv-0k2/-d1+*2/-d[q]s.0=.-lN-0lN-sNlFx
9k4*d2*1+dv-0k2/- # Compute triangular root
d1+*2/ # Compute triangular number
d -d[q]s.0=. # Check if sum is exact
d -lN- # Compute S-N or S+N
0lN-sN # Update N := -N
d lFx # Leave the trail and recurse
```
This macro:
1. Finds minimum triangular number that exceeds the current number on the stack (using the modified [triangular root](https://en.wikipedia.org/wiki/Triangular_number#Triangular_roots_and_tests_for_triangular_numbers) formula).
2. Checks if triangular sum `S` represents the current number exactly. Exits if it does.
3. Proceeds to step 1 with either `S+N` (over-approximation) or `S-N` (under-approximation), the choice alternates between iterations.
When it does exit, the trail left on the stack tells the main program how many iterations it took.
[Answer]
# Python 3, ~~150~~ 138 bytes
```
n=int(input())
S=sum
l=[1]
i=s=1
while S(l)<n:i+=1;l+=[i]
while S(l)!=n:
while S(l)>n:l.pop(0)
s+=1
if S(l)<n:i+=1;l+=[i];s+=1
print(s)
```
Changelog:
* Changed append to +=, removed else (thanks musicman523, Loovjo; -12 bytes)
[Answer]
## Batch, 126 bytes
```
@echo off
set/an=s=l=u=0
:l
if %s% lss %1 set/as+=u+=1,n+=!!l&goto l
if %s% gtr %1 set/as-=l+=1&goto l
cmd/cset/an+n+2-!l
```
Explanation: `l` is zero if step 2 has never executed. This allows `n` to track number of iterations of step 3. Since the algorithm never stops at step 3, it must therefore have run step 1 once and step 2 `n+1` times for a total of `n+n+2` steps. However if the parameter is a triangular number then step 2 never executes so we need to subtract one step.
[Answer]
# Python 2, ~~86~~ 81 bytes
```
n=input()
l=u=i=s=0
while n:k=n>0;i+=k^s;s=k;l+=k;n-=l*k;u+=k^1;n+=u*-~-k
print i
```
[Try it online!](https://tio.run/nexus/python2#FcgxCoAwDAXQvafoqJVCuhq@R3ETDCmh2BY3r151e7xhECu9TbPL6BBUkLtPyYe3VWEbsSzQvXKFcv7IFpGDcv87sS3oIT5RXbnEmpcxEtEL "Python 2 – TIO Nexus")
Computes the *65536* test case in `0.183s` on TIO.
---
**This recursive version at 84 bytes is not able to compute all values up to 65536:**
```
def f(n,l=[0],m=1):k=n>sum(l);return n==sum(l)or f(n,[l[1:],l+[l[-1]+1]][k],k)+(m^k)
```
[Try it online!](https://tio.run/nexus/python3#JYtBCgIxDAC/0mNiI2yuK/UjIYJgK6VtlLj7/rrobRhm5iOXUMCoJ1mURmJcW7LrZx/Q8eJ5292CpfQXL//F0oVXpR4POLNGVpWm1DDCuDWcb6@2wUkKVCzHU0O14Hd7ZmDihVFxfgE "Python 3 – TIO Nexus")
[Answer]
# Mathematica, 92 bytes
```
(For[q=a=b=0;t={},t~AppendTo~q;q!=#,If[q<#,q+=++b,q-=++a]];Length@Split@Sign@Differences@t)&
```
Pure function taking an integer argument and returning an integer.
The variables `a` and `b` stand for the (constantly changing) beginning and end numbers in the sum under consideration, while `q` stands for the running total (of the numbers from `a+1` to `b`); `t` keeps track of all the values of `q` encountered so far. After initializing these variables, the `For` loop keeps executing `If[q<#,q+=++b,q-=++a]`, which either adds a new number on to the end or subtracts the number at the front as dictated by the spec, until `q` equals the input.
Now we just have to extract the number of steps from `t`, the list of `q` values encountered along the way. For example, when the input is `11`, the `For` loop exits with `t` equaling `{0,1,3,6,10,15,14,12,9,15,11}`. The best way I found to calculate the number of steps from this is to count how many times the differences switch from going up to going down; that's what the verbose command `Length@Split@Sign@Differences@t` does, but I suspect that can be improved.
[Answer]
# C (tcc), 71 bytes (61+10)
Command-line arguments (including a space):
```
-Dw=while
```
Source:
```
c,m,M,s;f(n){w(++c,s-n){w(c&s<n)s+=++M;w(~c&s>n)s-=m++;}--c;}
```
How it works:
`c` counts the number of steps. `m` and `M` store the minimum and maximum of the range, `s` the sum. Initially, they're all zero.
Continuously, `c` is increased, and `s` is compared to `n`. As long as they're unequal:
* If `c` is odd, then as long as `s<n`, add an integer to the end of the range: increase `M` by one, and `s` by `M`.
* If `c` is even, then as long as `s>n`, remove an integer from the start of the range: decrease `s` by `m`, and increase `m` by one.
When the loop exits, `c` has been increased one too many times. Decrementing it produces the correct result, and it happens to be calculated in the correct register to act as the return value.
Amusingly happens to use the exact same variable names as [Khaled.K's C answer](https://codegolf.stackexchange.com/a/120523). They aren't copied.
[Answer]
## PHP 7, 59 Bytes
(7.0.1 or later)
```
for(;$d=$argn<=>$s;$x+=$d!=($argn<=>$s))$s+=$$d+=$d;echo$x;
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/f4fb3281ef1360cceecd0b16b1dd8042a6b75489).
### breakdown:
```
for(;$d=$argn<=>$s; # $s<N: $d=+1, $s>N: $d=-1, $s==N: 0 -> falsy -> break
$x+=$d!=($argn<=>$s)) # 3. if sign of difference changed, increment counter
$s+= # 2. add to sum
$$d+=$d; # 1. increment ${1} or decrement ${-1}
echo$x; # print step counter
```
uses the spaceship operator `<=>` ([introduced in PHP 7.0](https://www.php.net/migration70.new-features#migration70.new-features.spaceship-op)) and variable variables ([introduced in PHP/FI](https://www.php.net/manual/phpfi2.php#varvars)).
Thanks [@Jörg](https://codegolf.stackexchange.com/a/120495/55735) for reminding me of the spaceship.
Without the parentheses around the spaceship in the post condition, PHP wouldn not know what comparison to evaluate first (and throw a syntax error).
## PHP 7 (unary output), 53 bytes
```
for(;$d=$argn<=>$s;print$d!=($argn<=>$s))$s+=$$d+=$d;
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~28~~ 27 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Commands)
```
ÅTθÊiÑÂ<;+ʒ.ï}ßI·t2z+ï->·ë1
```
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/120519/52210), which is using [*@MartinEnder*'s Mathematica formula](https://codegolf.stackexchange.com/a/120570/52210), so make sure to upvote both of them!
[Try it online](https://tio.run/##ATcAyP9vc2FiaWX//8OFVM64w4ppw5HDgjw7K8qSRMOvUX3Dn0nCt3QyeivDry0@wrfDqzH//zY1NTM2) or [verify the first 100 test cases](https://tio.run/##AUoAtf9vc2FiaWX/MTAwRU4/IiDihpIgIj9Ow5DCqf/DhVTOuMOKacORw4I8OyvKkkTDr1F9w5/CrsK3dDJ6K8OvLT7Ct8OrMf99w68s/w). (NOTE: The `.ï` has been replaced with `DïQ` in the TIOs, because [this `.ï` bug on floating values, which was fixed on October 23rd](https://github.com/Adriandmen/05AB1E/issues/160), hasn't been pushed to TIO yet.)
**Explanation:**
```
ÅT # Push a list of triangular numbers smaller than or equal to the
# (implicit) input-integer
θ # Pop and only leave the last value in this list
Êi # If it's NOT equal to the (implicit) input, so the input isn't a
# triangular number:
Ñ # Get all divisors of the (implicit) input
 # Bifurcate this list (short for Duplicate & Reverse copy)
< # Decrease each by 1 in the reversed list
; # Then halve each
+ # And add the values at the same positions in the lists together
ʒ # Filter it by:
.ï # Where the decimal value is an integer
}ß # After the filter: pop and leave the minimum
I· # Push the input again and double it
t # Take the square-root of this
2z+ # Add 1/2 to it
ï # Floor it to an integer
- # Subtract it from the earlier minimum
> # Increase it by 1
· # Double it
ë # Else (the input is a triangular number):
1 # Simply push a 1
# (after which the top of the stack is output implicitly as result)
```
[Answer]
# [Perl 6](https://perl6.org), 114 bytes
```
{((0,0,1),->(\a,\b,\c){b,(a..*).first(->\d{(d,b).minmax.sum*c>=$_*c}),-c}...->(\a,\b,\c){(a,b).minmax.sum==$_})-1}
```
(inspired by an earlier [Haskell](https://codegolf.stackexchange.com/questions/120487/11-12345-123-6-4/120502#120502) implementation)
[Try it](https://tio.run/nexus/perl6#dVBLboMwEN1zilnQxo7MyDbgRkLkJEiRA6FKVULEp2oVcbLuejFqPhEmalczHr/fTFuf4ENhGjnFFzynZXaCuL8RwhlngjJvTxLNkiNLUno7MqIRtxTzc1U3xNsn2Y1k7EixOF8K/Yl1W2zTfewetmlnuGmHiCsFotfo2GA76omuN@7uu65ejT3Uja4aGLOoMPRV5FzbBtzDzzfmRUM2T37GNhTfyvMF8rICIhAF50ZYX8m4A8WqbMqKSE6jHkAwAMmmGli9qYL/8aeWmRzqboV1FrINtoTFPBOGGPJ/RBeeA3J@yJ2VxvQ@X8RGwmziq/UWw3wIE9wTBoP7BBbcEg0exO7pwjnt4yahGoWdKZ0BK74ApHU/pdZ3HOZyxg2pXqw7gvoF "Perl 6 – TIO Nexus")
It runs with an input of 65536 in under 45 seconds on my computer, but I have been unable to get it to run in under 60 seconds with TIO.run.
I have Rakudo v2017.04+ , where it has [v2017.01](https://tio.run/nexus/perl6#@19QlJlXoqCiFeAa5KOXnJ9bkJmTWqSXnllc8v//17x83eTE5IxUAA "Perl 6 – TIO Nexus").
Rakudo/NQP/MoarVM gets optimizations almost daily, so there could be any number of them from the interim that are needed to get it in under time.
---
## Expanded
```
{
(
# generate a sequence
(0,0,1), # initial value
-> (\a,\b,\c) {
b, # swap the first two values
(a..*)
.first( # find the first number that brings us to or past the input
-> \d {
(d,b).minmax # get a Range object regardless of which is larger
.sum * c # sum it, and negate it every other time
>= # is it equal to or greater than
$_ * c # negate the original input every other time
}
),
-c # invert for next round
}
... # keep doing that until
-> (\a,\b,\c) {
(a,b).minmax.sum == $_ # it finally reaches the input
}
) - 1 # count the number of elements in the sequence
# and subtract one for the initializer
}
```
Note that Rakudo has an optimization for `Range.sum` so that it doesn't have to iterate through all of the values.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 32 bytes
```
→L↑o≠⁰Σ¡?oḟo≤⁰ΣṫS:o→→o>⁰Σḟo>⁰ΣḣN
```
[Try it online!](https://tio.run/##yygtzv7//1HbJJ9HbRPzH3UueNS44dziQwvt8x/umA/kLwHzH@5cHWyVD1QFRPl2ECGgNIy12O////@GhgA "Husk – Try It Online")
Not that this will *not* run in 1 minute for n-65536, hence it cannot compete.
However, it can theoretically calculate for any given n.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes
```
S>³
RÄ<i0RḊÇ¿Ṃ;‘ƊÇ?S⁻³ƊпL
```
[Try it online!](https://tio.run/##y0rNyan8/z/Y7tBmrqDDLTaZBkEPd3Qdbj@0/@HOJutHDTOOATn2wY8adx/aDGROOLTf5////4aGAA "Jelly – Try It Online")
Full program only, because [`¿` handles dyads in an... interesting way.](https://github.com/DennisMitchell/jellylanguage/blob/70c9fd93ab009c05dc396f8cc091f72b212fb188/jelly/interpreter.py#L1278)
Directly implements the given algorithm.
```
S>³ Monadic helper link:
S the sum of the argument,
> is it greater than
³ the input (to the entire program)?
RÄ<i0RḊÇ¿Ṃ;‘ƊÇ?S⁻³ƊпL Main link:
Ä cumulative sums of
R [1 .. input],
i0 first index of 0 in
< whether or not each sum is less than the input,
R starting with [1 .. that index]:
¿ while
S⁻³Ɗ the sum is not equal to the input,
? if
Ç (helper link) the sum is greater than the input,
Ḋ then remove the first element
Ç¿ while the sum is greater than the input,
; ? else concatenate
Ṃ the smallest element to
‘Ɗ the list incremented.
пL Output the number of iterations this took.
```
I haven't finished verifying execution times, but specifically for N = 65536 TIO takes 9 seconds while my computer takes 15.
EDIT: My machine seems to have taken more than a minute for N = 32924, 32933, and 32941. TIO computes each result in less than 5 seconds, however, so I suspect this may be because the lid of my laptop was closed for eight hours.
N = 45596 also just now took a minute and 9 seconds, but this also coincided with my laptop going to sleep, and TIO takes less than 2 seconds for it.
] |
[Question]
[
There's something wrong with your keyboard. The `Shift` key has a mind of its own. Every time you type a character you have no idea whether it will come out shifted or not (though it is 50-50). Besides the standard character keys, nothing on the keyboard is functional. There is no mouse or other means of input.
Somehow you know the only way to fix things is to write a program that outputs `Dear Computer, please stop giving me shift!` to stdout. Luckily your IDE is open and you are capable of running a program, but of course as you type it you won't know which characters will be shifted.
*What sequence of key-presses would you use to write a program that has the best possible chance of working on the first try?*
# Details
You are using a [standard QWERTY keyboard](http://upload.wikimedia.org/wikipedia/commons/3/3a/Qwerty.svg), so there are 50 character keys you can press.
Unshifted versions (47 only):
```
`1234567890-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./
```
Shifted versions (47 only):
```
~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?
```
The last 3 keys are `Enter`, `Tab`, and `Space`, which are the same shifted and unshifted.
A sequence of N of these characters has 2N - (whitespace char count) ways it might have been output if you had typed them with your faulty keyboard. For example, typing `A` `Space` `m` might have yielded
`a m` or `A m` or `a M` or `A M`.
Write a program these characters and look at all of its 2N - (whitespace char count) possible shift combinations. The more combinations that output `Dear Computer, please stop giving me shift!` the better. Your score is the number of working combinations (valid programs) divided by the total number of combinations. The highest score wins.
# Notes
* For valid programs, printing precisely `Dear Computer, please stop giving me shift!` and nothing else to stdout should be the only side effect.
* Valid programs should not take input.
* Invalid programs can do anything whatsoever.
* Comments may be used anywhere.
* [Whitespace](http://en.wikipedia.org/wiki/Whitespace_(programming_language)) answers cannot win because getting a 100% score is (relatively) trivial. You may still submit a Whitespace solution for fun.
* Your program must be at most 1024 characters long.
***Update:* Changed `Stop giving me shift!` to `Dear Computer, please stop giving me shift!` to allow for more complex answers. Existing answers may stay the way they are if desired.**
[Answer]
# Applescript, 20 (100%)
I believe I can claim a perfect score here:
* The Applescript Editor (my IDE) automatically converts all keywords to lower case upon compiling/running
* Furthermore, defined variable and handler names are case insensitive - For example if a handler `myFunc` is defined, then the IDE will automatically convert `MYFUNC`, `myfunc`, `MyFuNc`, etc references to `myFunc`
* I have only used alphabetic characters, spaces and newlines, so I don't need to worry about shifted numbers and punctuation characters.
Here is is:
```
global f
on j at a
set end of a to j
end
on c at a
j at a
j at a
end
on k at a
repeat with q in system info
j at a
end
end
on w at a
set d to count a
j at a
return string id d
end
on z at a
set end of f to a
end
set h to space
set y to h as list
k at y
k at y
set x to w at y
c at y
c at y
c at y
c at y
c at y
set q to w at y
k at y
c at y
c at y
copy y to b
c at y
set s to w at y
set d to w at y
set f to d as list
k at b
k at b
set a to w at b
c at b
j at b
set e to w at b
set y to w at b
set g to w at b
set d to w at b
set i to w at b
c at b
set l to w at b
set m to w at b
set n to w at b
set o to w at b
set p to w at b
j at b
set r to w at b
z at e
z at a
z at r
z at h
z at s
set s to w at b
set t to w at b
set u to w at b
set v to w at b
z at o
z at m
z at p
z at u
z at t
z at e
z at r
z at q
z at h
z at p
z at l
z at e
z at a
z at s
z at e
z at h
z at s
z at t
z at o
z at p
z at h
z at g
z at i
z at v
z at i
z at n
z at g
z at h
z at m
z at e
z at h
z at s
z at d
z at i
z at y
z at t
z at x
f as text
```
Thanks to the help of @kernigh and @paradigmsort, this is now 1020 bytes, just squeaking in under the 1024 byte limit!
### Explanation:
* The characters for output string are generated using `string id <n>`, which returns the character corresponding to the ascii value `n`
* Because we are avoiding digits, each `n` has has to be generated by more fundamental means. Specifically we generate each `n` by counting a list, and then adding another item to that list. The `repeat with q in system info` allows us to do this 16 times, as `system info` always returns a 16-item list.
* Using a similar technique, we add each character of the final string in turn to a list.
* Finally that last list is coerced to `text` and printed.
### Output:
Using the `osascript` interpreter, but the Applescript Editor works just as well:
```
$ # Interpret as-is:
$ osascript dearcase.scpt
Dear Computer, please stop giving me shift!
$
$ # Interpret all lower case:
$ tr A-Z a-z < dearcase.scpt | osascript
Dear Computer, please stop giving me shift!
$
$ # Interpret all upper case:
$ tr a-z A-Z < dearcase.scpt | osascript
Dear Computer, please stop giving me shift!
$
$ # Interpret random case for each letter:
$ while read; do for ((i=0;i<${#REPLY};i++)); do c="${REPLY:i:1}"; if ((RANDOM%2)); then printf "%s" "$(tr a-z A-Z <<< "$c")"; else printf "%s" "$(tr A-Z a-z <<< "$c")"; fi; done; echo; done < dearcase.scpt | osascript
Dear Computer, please stop giving me shift!
$
```
[Answer]
# PHP, 2^-12
```
echo ucwords(strtolower('Dear Computer, ')).strtolower('please stop giving me shift!');
```
PHP being PHP, capitalization of `echo`, `ucwords`, and `strtolower` don't matter. The calls to `ucwords` and `strtolower` ensure that the case of the strings won't change the output.
Therefore, the only characters that can't be changed are `((,)).(!);` (10 characters).
Each pair of quotes also has a 50% chance of being valid (`''` and `""` are valid, but `'"` and `"'` are not), therefore each adding another power of two.
[Answer]
# CJam, 2-7 2-12 chance
```
'D"ear Komputer, please stop giving me shift!"el4'Ct
```
It has similar idea as [Quincunx's first answer](https://codegolf.stackexchange.com/a/39955/), but in CJam.
[Answer]
# Whitespace (645 bytes, 2^0 probability)
Since this program *only* uses tabs, spaces and newlines (which are all unaffected by shifting), it gives a 100% success rate.
```
```
[Program run](http://ideone.com/aEvmfj)
[Answer]
# CJam, 2-9 chance, [739 bytes](https://mothereff.in/byte-counter#%22%20%09%20%20%20%20%09%20%09%09%20%20%20%09%20%20%0A%20%20%20%09%20%09%09%20%20%20%09%09%09%09%20%09%0A%09%09%09%09%20%09%20%20%09%09%20%09%09%20%20%09%0A%20%09%20%20%20%20%09%20%09%09%20%20%20%20%09%20%0A%20%20%20%09%20%09%09%20%20%09%20%20%20%20%20%20%0A%20%09%09%09%09%20%09%20%20%09%09%20%09%20%09%09%0A%09%09%09%20%09%20%20%09%09%20%09%09%20%09%09%09%0A%20%09%20%09%09%20%20%09%20%20%20%20%20%09%20%09%0A%09%20%09%09%20%20%09%20%20%20%20%09%20%20%20%20%0A%09%20%20%09%09%20%09%09%09%09%20%20%09%09%20%09%0A%09%09%20%09%20%20%09%09%20%09%09%09%20%09%20%20%0A%20%20%20%09%20%09%09%20%20%20%09%09%09%09%20%09%0A%20%09%20%20%20%20%09%20%09%09%20%20%20%20%09%20%0A%20%09%09%09%09%20%09%20%20%09%09%20%09%09%20%20%0A%20%20%20%09%20%09%09%20%20%09%20%20%20%20%20%20%0A%09%20%09%09%20%20%09%20%20%20%20%09%20%20%20%20%0A%09%20%20%09%20%20%20%20%09%20%09%20%09%09%20%20%0A%20%20%20%09%20%09%09%20%20%20%09%09%09%09%20%09%0A%09%09%09%09%20%09%20%20%09%09%20%09%09%20%20%09%0A%20%20%20%20%09%20%09%09%20%20%20%09%09%20%09%09%0A%20%20%20%09%20%09%09%20%20%20%09%09%09%09%20%09%0A%20%20%20%09%20%09%09%20%20%09%20%20%20%20%20%20%0A%20%20%20%20%09%20%09%09%20%20%20%09%09%20%09%09%0A%09%09%20%09%20%20%09%09%20%09%09%09%20%09%20%20%0A%09%09%09%20%09%20%20%09%09%20%09%09%20%09%09%09%0A%09%20%09%09%20%20%09%20%20%20%20%09%20%20%20%20%0A%20%20%20%09%20%09%09%20%20%09%20%20%20%20%20%20%0A%09%20%09%20%20%09%09%20%09%09%09%20%09%09%09%09%0A%20%20%09%09%20%09%09%09%09%20%09%20%20%20%20%09%0A%20%09%09%20%20%09%20%20%20%20%09%20%20%09%09%20%0A%20%20%09%09%20%09%09%09%09%20%09%20%20%20%20%09%0A%20%20%09%20%20%20%20%09%20%09%20%09%09%09%09%20%0A%09%20%09%20%20%09%09%20%09%09%09%20%09%09%09%09%0A%20%20%20%09%20%09%09%20%20%09%20%20%20%20%20%20%0A%20%09%20%09%09%20%20%09%20%20%20%20%20%09%20%09%0A%20%20%20%09%20%09%09%20%20%20%09%09%09%09%20%09%0A%20%20%20%09%20%09%09%20%20%09%20%20%20%20%20%20%0A%20%20%20%20%09%20%09%09%20%20%20%09%09%20%09%09%0A%20%09%09%20%09%09%09%09%20%09%20%20%09%20%20%20%0A%20%20%09%09%20%09%09%09%09%20%09%20%20%20%20%09%0A%09%09%20%09%09%09%09%20%09%20%20%09%20%09%09%20%0A%09%09%20%09%20%20%09%09%20%09%09%09%20%09%20%20%0A%09%09%20%09%09%09%09%20%09%20%20%09%09%20%20%09%22N%2F2fb%3Ac)
```
"
(lines of space characters)
"N/2fb:c
```
base64:
```
IiAJICAgIAkgCQkgICAJICAKICAgCSAJCSAgIAkJCQkgCQoJCQkJIAkgIAkJIAkJICAJCiAJICAg
IAkgCQkgICAgCSAKICAgCSAJCSAgCSAgICAgIAogCQkJCSAJICAJCSAJIAkJCgkJCSAJICAJCSAJ
CSAJCQkKIAkgCQkgIAkgICAgIAkgCQoJIAkJICAJICAgIAkgICAgCgkgIAkJIAkJCQkgIAkJIAkK
CQkgCSAgCQkgCQkJIAkgIAogICAJIAkJICAgCQkJCSAJCiAJICAgIAkgCQkgICAgCSAKIAkJCQkg
CSAgCQkgCQkgIAogICAJIAkJICAJICAgICAgCgkgCQkgIAkgICAgCSAgICAKCSAgCSAgICAJIAkg
CQkgIAogICAJIAkJICAgCQkJCSAJCgkJCQkgCSAgCQkgCQkgIAkKICAgIAkgCQkgICAJCSAJCQog
ICAJIAkJICAgCQkJCSAJCiAgIAkgCQkgIAkgICAgICAKICAgIAkgCQkgICAJCSAJCQoJCSAJICAJ
CSAJCQkgCSAgCgkJCSAJICAJCSAJCSAJCQkKCSAJCSAgCSAgICAJICAgIAogICAJIAkJICAJICAg
ICAgCgkgCSAgCQkgCQkJIAkJCQkKICAJCSAJCQkJIAkgICAgCQogCQkgIAkgICAgCSAgCQkgCiAg
CQkgCQkJCSAJICAgIAkKICAJICAgIAkgCSAJCQkJIAoJIAkgIAkJIAkJCSAJCQkJCiAgIAkgCQkg
IAkgICAgICAKIAkgCQkgIAkgICAgIAkgCQogICAJIAkJICAgCQkJCSAJCiAgIAkgCQkgIAkgICAg
ICAKICAgIAkgCQkgICAJCSAJCQogCQkgCQkJCSAJICAJICAgCiAgCQkgCQkJCSAJICAgIAkKCQkg
CQkJCSAJICAJIAkJIAoJCSAJICAJCSAJCQkgCSAgCgkJIAkJCQkgCSAgCQkgIAkiTi8yZmI6Yw==
```
Based on the idea of Optimizer and Quincunx's answer.
[Answer]
# Python 2, 2-20 chance
```
print'S'+'top giving me shift!'.lower()
```
`print`, `S`, `+`, `!`, and `.lower()` must all be the correct version; that's 18 chars. The two quotes for the strings must also align, that makes two more powers of two.
For any of the `top giving me shift`, if it is converted to the capital version, we convert it to lowercase and it works properly.
Sadly, I can't make use of Python's nifty `capitalize()`, because that takes one more character.
[Answer]
# VisualBasic.net 2^-18
Critical chars: .("DearC"+",!".())
```
Sub Main
console.write("Dear C"+"omputer, please stop giving me shift!".tolower())
End Sub
```
Tested in LINQPad, Language = "VB Program"
[Answer]
# Pyth, 2\*\*-15
```
+"S"$"top giving me shift!".lower()
```
I can't seem to find Pyth's version of `lower()`, so I'll borrow from Python. The characters that can't be swapped are `+"S"$`, `!`, and `.lower()`, for a total of 14 chars. The quotes after the `$` must match, adding another power of 2.
[Answer]
# Rant, 2-21
```
[caps:first][?[caps:word][?[caps:lower]Dear Computer][caps:lower], please stop giving me shift!]
```
A series of metapatterns and `caps` calls force proper formatting. Function names and arguments are case insensitive.
[Online version](http://berkin.me/rantbox#3DE47998427FD034A1942F449E237163585C58AE)
[Answer]
## CJam, 2-13 chance
As per the updated string ([696](https://mothereff.in/byte-counter#%22%20%20%20%0A%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%0A%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%0A%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%0A%20%20%20%20%0A%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%0A%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%0A%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%0A%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%0A%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%0A%20%20%0A%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%22N%2F%3A%2C2%2FKfb%3Ac) bytes).
```
"
"N/:,2/Kfb:c
```
Only `""N/:,2/Kfb:c` are at risk right now.
[Try it online here](http://cjam.aditsu.net/) and since this text editor is eating up all the spaces, here is the [gist](https://gist.github.com/scrapmac/0b2057a2211e2c25fde0) with the correct code.
[Answer]
## VB.NET, ~~2^-12~~ 2^-11
**2-12**
```
Module All
Sub Main
Console.WriteLine StrConv("Dear Computer, ", vbTuesday) & "please stop giving me shift!".ToLower
End Sub
End Module
```
**2-11**
```
Imports System.Console
Module All
Sub Main
Write StrConv("Dear Computer, ", vbTuesday)
WriteLine "please stop giving me shift!".ToLower
End Sub
End Module
```
[Answer]
I thought about my answer before getting to the '50 characters including only Enter, Tab, Space' rule. So mine is not valid.
Seems having case insensitive programming languages is the key here. Alternatively, if you could use a Real standard QWERTY keyboard (including Caps Lock, the other Shift, Backspace, and the Numpad Period) there would only be 2 necessary 50% chances which would only result in 2 additional key presses per failure. My invalid answer for a C# Console Application pointing out actual key presses:
```
HoldShift(C CpsLockOn onsole)
NumPadPeriod
HoldShift(
CpsLockOff W CpsLockOn rite("
CpsLockOff D CpsLockOn ear space
CpsLockOff C CpsLockOn omputer
)
, (repeat with Backspace until correct)
HoldShift( please stop giving me shift!"))
; (repeat with Backspace until correct)
```
---
76 minimum presses with only 2 necessary 50% chances
[Answer]
# Excel, 2-11
```
=PROPER("Dear Computer, ")&LOWER("please stop giving me shift!")
```
Case of `PROPER` and `LOWER` don't matter.
Entering a formula starting with `+` automatically inserts required `=`.
So only `(`, `"`, `,`, `)`, `&`, `!` can break.
] |
[Question]
[
In this challenge, you need to solve 4 different tasks using the same set of characters. You can rearrange the characters, but you can't add or remove characters.
The winner will be the submission that solves all tasks using the smallest number of characters. All tasks must be solved in the same language.
Note that it's the smallest number of characters, not the smallest number of *unique* characters.
**Task 1:**
Output the first `N` numbers of every third [composite number](https://en.wikipedia.org/wiki/Composite_number). The codeblock below shows the first 19 composite numbers in the first row, and every third composite number on the row below.
```
4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30
4, 9, 14, 18, 22, 26, 30
```
If `N=5` then the output should be `4, 9, 14, 18, 22`. You must support `1<=N<=50`.
Composite numbers are positive numbers that aren't prime numbers or 1.
The result for `N=50` is:
```
4, 9, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50, 54, 57, 62, 65, 69, 74, 77, 81, 85, 88, 92, 95, 99, 104, 108, 112, 116, 119, 122, 125, 129, 133, 136, 141, 144, 147, 152, 155, 159, 162, 166, 170, 174, 177, 182, 185, 188, 192
```
**Task 2:**
Output a `N-by-N` multiplication table. You must support `1<=N<=20`
Example:
```
N = 4
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
```
The output format is optional, the following is acceptable output `[[1,2,3,4],[2,4,6,8],[3,6,9,12],[4,8,12,16]]`.
**Task 3:**
Determine if a number is a [Fibonacci number](https://en.wikipedia.org/wiki/Fibonacci_number). You must support positive `N` up to the default integer limit of your language. If there are both 32-bit integers and 64-bit integers then you can choose to use the one that requires the shortest code. For instance, use `int` instead of `long int` if you have the choice. You can not choose a smaller integers than 32-bit unless that's default (you can't use 8-bit integers if 32-bit is default).
`true/false`, `false/true`, `1/0`, `1/-1`, `a/b` are all acceptable output as long as it's consistent.
**Task 4:**
Take `N` as input and output the result of `1^1+2^2+3^3+...N^N`. You must support `1<=N<=10`.
The 10 different results are:
```
1, 5, 32, 288, 3413, 50069, 873612, 17650828, 405071317, 10405071317
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission in each language wins!
This Stack Snippet will help check your solution. It measures the minimum set of characters needed to include all four solutions, and shows the leftover characters.
```
function update() {
var m = {};
var a = [q1.value, q2.value, q3.value, q4.value];
var o = [{}, {}, {}, {}]
for (var i = 0; i < 4; i++) {
for (var j = 0; j < a[i].length; j++) o[i][a[i][j]] = -~o[i][a[i][j]];
for (var c in o[i]) if (!(o[i][c] < m[c])) m[c] = o[i][c];
}
var t = 0;
for (var c in m) t += m[c];
for (var i = 0; i < 4; i++) {
t += "\n";
for (var c in m) t += c.repeat(m[c] - ~~o[i][c]);
}
p.textContent = t;
}
```
```
<div oninput="update();">
<textarea id="q1"></textarea>
<textarea id="q2"></textarea>
<textarea id="q3"></textarea>
<textarea id="q4"></textarea>
</div>
<pre id="p"></pre>
```
[Answer]
# Python, 88 87 bytes
```
lambda n:[a for a in range(11*n)if any(a%b<1for b in range(2,a))][:3*n:3]#1,,,=====bd++
lambda n:[[a*b for b in range(1,n+1)]for a in range(1,n+1)]#,,::ybaaa(*i%n< =====2)d33f
f=lambda n,a=1,b=1:a<n and f(n,b,a+b)or n==a#2eerrrfo::((**iii11[[aannn+ ]]y))%33gg
f=lambda n,a=1:a<=n and a**a+f(n,a+1)#::ooeeiii]] y))bbbgg,,rrrra((11[[nnnnf==2%33
```
Didn't put too much effort into sharing characters or the golfs themselves, this will almost surely be beat.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ ~~18~~ 17 characters
### Task 1
```
Ḟþe*S
×5µḊḟÆRm3ḣ³
```
[Try it online!](https://tio.run/nexus/jelly#ASMA3P//4biew75lKlMKw5c1wrXhuIrhuJ/DhlJtM@G4o8Kz////NQ "Jelly – TIO Nexus")
### Task 2
```
5µḊḟÆRm3ḣ³Ḟe*S
×þ
```
[Try it online!](https://tio.run/nexus/jelly#ASMA3P//NcK14biK4bifw4ZSbTPhuKPCs@G4nmUqUwrDl8O@////NA "Jelly – TIO Nexus")
### Task 3
```
5µḊḟmḣþ*S
×3RÆḞ³e
```
[Try it online!](https://tio.run/nexus/jelly#ASQA2///NcK14biK4bifbeG4o8O@KlMKw5czUsOG4biewrNl////NTU "Jelly – TIO Nexus")
### Task 4
```
×5ḊḟÆm3ḣ³þe
Rµ*ḞS
```
[Try it online!](https://tio.run/nexus/jelly#ASMA3P//w5c14biK4bifw4ZtM@G4o8Kzw75lClLCtSrhuJ5T////NQ "Jelly – TIO Nexus")
## How it works
Every line in a Jelly program defines a separate *link* (function). The last one is the *main link* and is called automatically when the program is executed. Unless that main link references the others somehow, they have no effect. Note that even uncalled links may not contain parser errors.
### Task 1
```
×5µḊḟÆRm3ḣ³ Main link. Argument: n
×5 Yield 5n.
µ Begin a new chain, with argument 5n.
Ḋ Dequeue; yield [2, ..., 5n].
ÆR Prime range; yield all primes in [1, ..., 5n].
ḟ Filter; remove the elements to the right from the ones to the left.
m3 Pick every third element.
ḣ³ Keep the first n results.
```
### Task 2
This one's trivial: `×` is the multiplication atom, and the quick `þ` (table) applies `×` to each combination of elements in the left and in the right argument. If the arguments are integers (which they are here), it also casts them to range first.
### Task 3
```
×3RÆḞ³e Main link. Argument: n
×3 Yield 3n.
R Range; yield [1, ..., 3n].
ÆḞ Fibonacci; yield [F(1), ... F(3n)].
³e Test if n exists in the result.
```
### Task 4
```
Rµ*ḞS Main link. Argument: n
R Range; yield [1, ..., n].
µ Begin a new chain with argument [1, ..., n].
Ḟ Floor; yield [1, ..., n].
* Yield [1**1, ..., n**n].
S Take the sum.
```
[Answer]
## Mathematica, 60 characters
### Task 1: Composites
```
#/AFF^abcinoruy{};Select[Range[2,9#],!PrimeQ@#&][[;;3#;;3]]&
```
### Task 2: Multiplication Table
```
!29;F@FPQRS[];a^b;c[c[e]];eeegiilmnnotu;Array[3##&,{#,#}]/3&
```
### Task 3: Fibonacci
```
##&;239;A/PS[]^e[];lmrtuy;{,};!FreeQ[Fibonacci@Range[3#],#]&
```
### Task 4: Sum of powers
```
!###&;23/39;A@F;F[P[Q[]]];Raabccegiilnnorrty;Sum[e^e,{e,#}]&
```
Each submission is a set of expressions that are ignored, followed by an unnamed function which implements the given task.
I wrote [a simple CJam script](https://tio.run/nexus/cjam#JYyxDoIwGIR334LWoNCqCC5CILgwGitupRokfw2JoBYdlOCrY9Xhkst9l6@/rWc@G70t6rlRJtv5UELoQ8Tcb5ETaXevgxMyJyQNXZArm7ZobKOYINtCJCN11/cpnKG4821en4C7dIkFNTaqrIDF2BScB4GHdYQwByul8iffadbQFlPc6c1IFADjSXm81HlRlPFf5GkN1jh9VBz2QFv43T8) which "optimally" combines raw solutions by prepending a comment. I then ended up saving three bytes on top of that by manually getting rid of each comment (which required some rearranging to get valid syntax in each case). The script made it a lot easier to try out simple variations of the solutions to see if they would bring down the overall score. Feel free to use the script yourself.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~29~~ ~~28~~ 26 characters
### Task 1 (every third composite number)
```
6*:tZp~)G:3*q)%G"$]vwm^sl+
```
[Try it online!](https://tio.run/nexus/matl#@2@mZVUSVVCn6W5lrFWoqequpBJbVp4bV5yj/f@/qQEA)
### Task 2 (multiplication table)
```
:l$*%6*tZp~)G:3q)G"]vwm^s+
```
[Try it online!](https://tio.run/nexus/matl#@2@Vo6KlaqZVElVQp@luZVyo6a4UW1aeG1es/f@/oQEA)
### Task 3 (Fibonacci detector)
```
l6Zp~G:"3q$t+]vGwm%):*)^s*
```
This displays `1` / `0` for Fibonacci / non-Fibonacci respectively.
[Try it online!](https://tio.run/nexus/matl#@59jFlVQ526lZFyoUqIdW@ZenquqaaWlGVes9f@/oTEA)
### Task 4 (sum of powers)
```
:t^s%6*Zp~)G:3*q)G"$]vwml+
```
[Try it online!](https://tio.run/nexus/matl#@29VElesaqYVVVCn6W5lrFWo6a6kEltWnpuj/f@/KQA)
### Check
[This program](https://tio.run/nexus/matl#RcyxCoMwFEDRPV/xkGRI4iY4vLkQOtupYKhgCilPTUxQuvTXU6EtnS/nltujO10ABJznu599dkDLEhBWN4xAfnY1pGXNNYw@BRqepbQK8zW8pMFGRSlMxfttn2wizag9gsGqiTzrfjP7JCQqaZNiSFyJVv1klKb6MM0w23Sk//O7JP0G) inputs the four strings and displays them sorted, to visually check that they use the same characters.
## Explanations
`%` is the comment symbol. Everything to its right is ignored.
### Task 1 (every third composite number)
```
6* % Input N. Multiply by 6
: % Range [1 2 ... 6*N]. This is enough because every even number is composite,
% so this contains at least 3*N composite numbers
t % Duplicate
Zp % Isprime
~ % Negate
) % Use as index to select composite numbers, including 1, from [1 2 ... 6*N]
G: % Push [1 2 ... N]
3*q % Multiply by 3 and subtract 1: gives [2 5 ... 3*N-1]
) % Pick those composite numbers. Implicitly display
```
### Task 2 (multiplication table)
```
: % Input N. Range [1 2 ... N]
l % Push 1
$ % Specify that next function will take 1 input
* % Product of array. With 1 input it produces all pair-wise products
% Implicitly display
```
### Task 3 (Fibonacci detector)
```
l % Push 1
6 % Push 6
Zp % Isprime. Gives false
~ % Negate. Gives true, or 1
G: % Push [1 2 ... N], where N is the input
" % For each
3q % 3, subtract 1
$ % Specify that next function will take 2 inputs
t % Duplicate the top two elements of the stack
+ % Add
] % End
v % Vertically concatenate the entire stack. This produces a column vector
% with a sufficient amount of Fibonacci numbers
G % Push input N
w % Swap
m % Ismember. Gives true if input is in the vector of Fibonacci numbers
% Implicitly display
```
### Task 4 (sum of powers)
```
: % Implicitly input N. Push [1 2 ... N]
t % Duplicate
^ % Power, element-wise
s % Sum of array. Implicitly display
```
[Answer]
# [Perl 6](https://perl6.org), 61 bytes
```
{(4..*).grep(!*.is-prime)[0,3...^*>=$_*3]}#$$&+1==>X[]__oot{}
```
```
{[X*](1..$_,!0..$_).rotor($_)}#&***+-..334===>>[]^eegiimpps{}
```
```
{(1,&[+]...*>=$_)[*-!0]==$_}#$()**....334>X^_eegiimoopprrst{}
```
```
{[+]((1..$_)>>.&{$_**$_})}#!**,-....0334===X[]^eegiimoopprrst
```
---
The second one returns `((1,2,3,4),(2,4,6,8),(3,6,9,12),(4,8,12,16))` when given `4`
Perl 6 doesn't really have a maximum integer, but the third one works instantly with an input of `15156039800290547036315704478931467953361427680642`. The only limiting factors would be memory and time.
Otherwise they will all run "instantly" for inputs well beyond what is necessary.
[Try it online](https://tio.run/nexus/perl6#XZDbioMwEEDf@xWRul6ihtxMzBb9DkGslGKLD6KoXSil396dKC3sQiCTTHLmzNzmFv0ocj68@jvyzgzl6BFIQnBIrlM7Bg4m3ZyMU9e3YUVjQQg54iJ3Gyzq5951vYjleVFWddMMw/J47lYMt5iqxHXACHGb2KF2C8k0LMMUQPTcexjjKCFECJkDoajqY9teu64fx/mNEasNi70qqqHwWjescOLQOocQ6gchxpCxlKI8NhthGMZxmuaPjVxtojrYbMKiIN4DOsCAABMH4zixELq5lB@VN@g1n@4IZpPSw2433hbk@xCQS78E/peY/ZDYy8swIeic/3lkf9qyjFK6jfTbNnZYE9Agk4YJpoySlAuuJWVcZ1ynjNNUC8qZzKgSSmYqpZrBrYEnRimWQs4YrlKptDbKaJPBklybVFMKB5VpoY0xKmP/hfrTaMcSo1Xs9Qs "Perl 6 – TIO Nexus")
[Answer]
## JavaScript (ES6), ~~101~~ ~~100~~ ~~95~~ ~~93~~ 91 bytes
```
(n,r=[],a=(y,m)=>n?y%m?a(y,++m):a(y+1,2,y==m||n--%3||r.push(y)):r)=>a(4,2,n*=3)//>....p*A&&
n=>[...Array(n)].map((r,y,m)=>m.map((s,n)=>y*++n,y+=1))//22334(,,,,===ayy)??%%::||||--uh*&&
r=(n,y=1,a=2)=>n==y||n>y&&r(n,a,y+a)//2334((((,,,,r=[]ayymmmm))))>??%%++::||--.....ppush**A
r=y=>y&&y**y+r(y-1)//22334(((((nnnn,,,,,,,,r=====[]aaaaymmmm)))))>>??%%++::||||-.....ppushA
```
Edit: Saved 1 byte by not supporting `0` as a Fibonacci number. Saved 5 bytes plus a further 2 bytes (1 thanks to @Arnauld) by renaming variables. Saved 2 bytes by switching between `+1`, `++` and `+=1`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 30 characters
The character set I went with is:
```
!%))*+001233::<=GGQZ\]^`pstvyy~
```
I couldn't outgolf the other MATL answer, but I had fun coming up with this solution.
**Task 1:**
Third composite numbers.
```
4t^:QtZp~)G3*:3\1=)%!`yy+<]vGs
```
[Try it online!](https://tio.run/nexus/matl#@29SEmcVWBJVUKfpbqxlZRxjaKupqphQWaltE1vmXvz/vykA "MATL – TIO Nexus")
**Task 2:**
Multiplication table. Definitely the easiest task, due to the way MATL works
```
:t!*%4QZp~)G3:3\1=)`yy+<]vGs^t
```
[Try it online!](https://tio.run/nexus/matl#@29VoqilahIYVVCn6W5sZRxjaKuZUFmpbRNb5l4cV/L/vykA "MATL – TIO Nexus")
**Task 3:**
Fibonacci tester. Prints a positive integer (1 or 2) for truthy inputs, and 0 for falsy inputs.
```
1t`yy+tG<]vG=s%4:QZp~)3*:3\)!^
```
[Try it online!](https://tio.run/nexus/matl#@29YklBZqV3ibhNb5m5brGpiFRhVUKdprGVlHKOpGPf/vykA "MATL – TIO Nexus")
**Task 4:**
Sum of powers
```
:t^s%1`yy+tG<]vG=4QZp~)3*:3\)!
```
[Try it online!](https://tio.run/nexus/matl#@29VElesaphQWald4m4TW@ZuaxIYVVCnaaxlZRyjqfj/vykA "MATL – TIO Nexus")
I'll post a more thorough explanation later, but for now, you should note that `%` is the comment character, so the programs are really:
```
4t^:QtZp~)G3*:3\1=)
:t!*
1t`yy+tG<]vG=s
:t^s
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes
**Task 1**
```
3ÅFOL¦DâPÙï{3ôø¬¹£qåm
```
[Try it online!](https://tio.run/nexus/05ab1e#ASQA2///M8OFRk9MwqZEw6JQw5nDr3szw7TDuMKswrnCo3HDpW3//zU)
**Task 2**
```
LDâP¹ôq3m¦Ùï{3ø¬£ÅFåO
```
[Try it online!](https://tio.run/nexus/05ab1e#ASQA2///TETDolDCucO0cTNtwqbDmcOvezPDuMKswqPDhUbDpU///zU)
**Task 3**
```
3mÅF¹åqL¦DâPÙï{3ôø¬£O
```
[Try it online!](https://tio.run/nexus/05ab1e#ASQA2///M23DhUbCucOlcUzCpkTDolDDmcOvezPDtMO4wqzCo0///zU)
**Task 4**
```
LDmOq3¦âPÙï{3ôø¬¹£ÅFå
```
[Try it online!](https://tio.run/nexus/05ab1e#ASUA2v//TERtT3EzwqbDolDDmcOvezPDtMO4wqzCucKjw4VGw6X//zEw)
**Explanations**
For all tasks, the `q` ends the program so the code that follows never gets executed.
**Task 1**
This is the biggest byte-hog. An small improvement here could go a long way.
```
3ÅFO # sum the first 4 fibonacci numbers
L¦ # range [2 ... above]
Dâ # cartesian product with itself
P # product
Ù # remove duplicates
ï{ # sort
3ô # split in pieces of size 3
ø # transpose
¬ # get the first lits
¹£ # get the first input-nr elements of the list
```
**Task 2**
```
L # range [1 ... input]
D # duplicate
â # cartesian product
P # product
¹ô # split in pieces of input size
```
**Task 3**
```
3m # input**3
ÅF # get a list of that many (+1) fibonacci numbers
¹å # check if input is in that list
```
**Task 4**
```
L # range [1 ... input]
D # duplicate
m # elementwise power of ranges
O # sum
```
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), ~~95~~ 94 bytes
([TimmyD](https://codegolf.stackexchange.com/users/42963/timmyd) savin' my bacon yet again)
### Task 1:
```
(""..999|?{'1'*$_-match'^(?=(..+)\1+$)..'})[(0..("$args"-1)|%{$_*3})]#|$$$$===ss%``iiex!!nnnq;
```
[Try it online!](https://tio.run/nexus/powershell#@6@hpKSnZ2lpWWNfrW6orqUSr5ubWJKcoR6nYW@roaenrRljqK2iqaenXqsZrWGgp6ehpJJYlF6spGuoWaNarRKvZVyrGatcowIEtra2xcWqCQmZmakViop5eXmF1v///zc1AAA "PowerShell – TIO Nexus")
---
### Task 2:
```
($s=1.."$args")|%{"`$s|%{$_*`$_}"|iex}#0113999((((......??''''*$$$--match^===++))))\[]i!!nnnq;
```
[Try it online!](https://tio.run/nexus/powershell#@6@hUmxrqKenpJJYlF6spFmjWq2UoFIMpFTitRJU4muVajJTK2qVDQwNjS0tLTWAQA8M7O3VgUBLRUVFVzc3sSQ5I87W1lZbWxMIYqJjMxUV8/LyCq3///9vAgA "PowerShell – TIO Nexus")
---
### Task 3:
```
!!(($i="$args")..($s=1)|?{($n=($s+=$n)-$n)-eq$i})#0113999......||?{''''**__match^+\}[""%%]``x;
```
[Try it online!](https://tio.run/nexus/powershell#@6@oqKGhkmmrpJJYlF6spKmnp6FSbGuoWWNfraGSZwvkaNuq5GnqgnBqoUpmraaygaGhsaWlpR4Y1AAVqgOBllZ8fG5iSXJGnHZMbbSSkqpqbEJChfX///8NTUwA "PowerShell – TIO Nexus")
---
### Task 4:
```
"$args"..1|%{$s+="$_*"*$_+1|iex};$s#013999(((((......|??{''''$$$--match^===)))))\}[%]``i!!nnnq
```
[Try it online!](https://tio.run/nexus/powershell#@6@kkliUXqykp2dYo1qtUqxtq6QSr6WkpRKvbViTmVpRa61SrGxgaGxpaakBAnpgUGNvX60OBCoqKrq6uYklyRlxtra2miAQUxutGpuQkKmomJeXV/j//39DAwA "PowerShell – TIO Nexus")
[Answer]
# [Haskell](https://www.haskell.org/), ~~77~~ 76 characters
```
m n=[[x|x<-[1..],2/=sum[1|0<-mod x<$>[1..x]]]!!y|y<-[1,4..3*n]]--2 n===y();^
s n=[(*y)<$>[1..n]|y<-[1..n]]--0112234mmm ====[[[xxxx||<<--..]]],,/uod!!y;^
n x|x<2=1|1<3=sum(n<$>[x-1,x-2]);d y=[0|m<-[1..y],y==n m]--4[[[....]]]/o!!*^
o n=sum[x^x|x<-[1..n]]--01112234mm n====[[[[x||<<<--....]]]],,/d$>!!yyy*();
```
[Try it online!](https://tio.run/nexus/haskell#dY9Ba4MwGIbv/orP0oNakzbqLmtSGLv2tt0kBVkKkzWJqN0S8L93X@w2KKw5GXzyvs/b6s72IzxbM/b2RJ@67tS@NWP7eYx00xoQoGwEAAY4gf7YqL0J1@48voz93sASFq/N8AHsERawWsHwbr8g0WDSf7HiBhvuYeUNpu5h1Q1mEbtgs6hrNzlOakapzIu1GM66ZtOGE20VOL7chT9OShnHfvIBzCtKy8xISUiBAUL4JN0eoiGEJZlPf94YecXDF6IbxoqirLTWAPgGe2uHZ5o4JwS7pczz9dkqrMEwA8GqEGxivAxOiQmxjrDckUKmWwVe1JtJXxu8zL0QBjQWVZhM6Zy4tnGcHSLcOs9yh7@pv0o/TjDvCE71bDQrzRHBSi13aOV9hjsvl4dv "Haskell – TIO Nexus")
`--` starts a line comment, so all four programs are of the form `<program>--<unused chars>`.
**Task 1:**
```
m n=[[x|x<-[1..],2/=sum[1|0<-mod x<$>[1..x]]]!!y|y<-[1,4..3*n]]
```
The longest program. `[x|x<-[1..],2/=sum[1|0<-mod x<$>[1..x]]]` yields a infinite list of composite numbers plus a starting `1` which corrects the 0-indexing. Usage:
```
Prelude> m 5
[4,9,14,18,22]
```
**Task 2:**
```
s n=[(*y)<$>[1..n]|y<-[1..n]]
```
Usage:
```
Prelude> s 5
[[1,2,3,4,5],[2,4,6,8,10],[3,6,9,12,15],[4,8,12,16,20],[5,10,15,20,25]]
```
**Task 3:**
```
n x|x<2=1|1<3=sum(n<$>[x-1,x-2]);d y=[0|m<-[1..y],y==n m]
```
Returns `[0]` for truthy and `[]` for falsy. Usage:
```
Prelude> d 5
[0]
Prelude> d 6
[]
```
**Task 4:**
```
o n=sum[x^x|x<-[1..n]]
```
Usage:
```
Prelude> o 5
3413
```
[Answer]
## Ruby, ~~83 82 80~~ 78 characters
```
->m{'*+-=';[*0..m-1].map{|b|(4..516).select{|p|(2...p).any?{|n|p%n==0}}[3*b]}}
->n{'()%**+--......00123456==?[[]]clmnsty{||}';(b=1..n).map{|e|b.map{|p|e*p}}}
->m{'%+-......001236bclnnpt[[]]{{||||}}';(1..e=m*m).any?{|p|(p*p-5*e).abs==4}}
->n{'%*.......023456=?[]abbceelnsty{{||||}}';((m=0)..n).map{|p|m+=p**p}[-1]-1}
```
Note: Fibonacci numbers detector using the perfect square method described on Wikipedia:
<https://en.wikipedia.org/wiki/Fibonacci_number#Recognizing_Fibonacci_numbers>
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
**Bytes used:**
```
δн3FILOPQm£¦ÅÐãêô
```
**Task 1 - every 3rd composite number:**
```
QÅmFÐOL¦ãPê3ôI£δн
```
[Try it online](https://tio.run/##ATAAz/9vc2FiaWX//1HDhW1Gw5BPTMKmw6NQw6ozw7RJwqPOtNC9//8xMP8tLW5vLWxhenk) or [verify all \$[1,50]\$ inputs](https://tio.run/##AUYAuf9vc2FiaWX/NTBFTj8iIOKGkiAiP07CqcOQ/1HDhW1Gw5BPTMKmw6NQw6ozw7TCrsKjwq5zzrTQvf99LP//LS1uby1sYXp5).
**Task 2 - multiplication table:**
```
ÅFOQmê3ôãн¦£ILÐδP
```
[Try it online](https://tio.run/##ATAAz/9vc2FiaWX//8OFRk9RbcOqM8O0w6PQvcKmwqNJTMOQzrRQ//8xMP8tLW5vLWxhenk) or [verify all \$[1,20]\$ inputs](https://tio.run/##AToAxf9vc2FiaWX/NTBFTj8iIOKGkiAiP07CqcOQ/8OFRk9RbcOqM8O0w6PQvcKmwqPCrkzDkM60UP8s/zIw).
**Task 3 - Fibonacci check:**
```
£3ôδнã¦LPmIÐÅFQêO
```
[Try it online](https://tio.run/##ATAAz/9vc2FiaWX//8KjM8O0zrTQvcOjwqZMUG1Jw5DDhUZRw6pP//8xMP8tLW5vLWxhenk) or [verify the first \$[0,1000]\$ inputs](https://tio.run/##AToAxf9vc2FiaWX/4oKExpJOPyIg4oaSICI/TsKpw5D/wqMzw7TOtNC9w6PCpkxQbcKuw5DDhUZRw6pP/yz/).
**Task 4 - exponentiation sum:**
```
ÅFPQê3ôãδн¦£ILÐmO
```
[Try it online](https://tio.run/##ASYA2f9vc2FiaWX//8OFRlBRw6ozw7TDo8600L3CpsKjSUzDkG1P//8xMA) or [verify all \$[1,10]\$ inputs](https://tio.run/##ATcAyP9vc2FiaWX/VEVOPyIg4oaSICI/TsKpw5D/w4VGUFHDqjPDtMOjzrTQvcKmwqPCrkzDkG1P/yz/).
[Try all four at once.](https://tio.run/##yy9OTMpM/f8/8HBrrtvhCf4@h5YdXhxweJXx4S2ehxaf23Jhr0KtjmYM1@FWN//AXLD44cUX9h5admixp8/hCee2BCiApA8tBkqAVB9efGiZT0Cu5@EJQB2Bh1f5K0B1BwRCNYNUwbTnAqX//zcFAA)
### Explanation:
**Task 1 - every 3rd composite number:**
This one takes up most bytes. Not only in general, but also to get a list large enough for input \$n=1\$.
```
# No-ops:
Q # Check if the (implicit) input is equal to the (implicit) input: 1
Åm # Get the mean of that (remains 1)
F # Loop that many times:
# Main part of the program:
Ð # Triplicate the (implicit) input
O # Sum all values on the stack
L # Take a list in the range [1,3*input]
¦ # Remove the first to make the range [2,3*input]
ã # Cartesian product with itself, to create all possible pairs
P # Take the product of each pair
ê # Sort & uniquify all values
3ô # Split it into parts of size 3
I£ # Leave the first input amount of parts
δн # And then leave the first item of each part
# (after the no-op loop, the result is output implicitly)
```
**Task 2 - multiplication table:**
```
# No-ops:
ÅF # Get all Fibonacci numbers below or equal to the (implicit) input
O # Take the sum of those
Q # Check if it's equal to the (implicit) input (which will always be 0)
m # Push the input to the power that 0 (which will always be 1)
ê # Sort and uniquify those digits (remains 1)
3ô # Split it into parts of size 3 (which wraps the 1 into a list: [1])
ã # Take the cartesian product of that list with itself (which becomes [[1,1]])
н # Leave the first item of that (which becomes [1,1])
¦ # Remove the first value (which becomes [1])
£ # Keep that many digits of the input
# (which becomes the first digit of the input, wrapped in a list)
# Main part of the program:
IL # Push a list in the range [1,input]
Ð # Triplicate this list
δ # Using the top two lists, apply double vectorized:
P # Take the product of the two values
# (after which the resulting multiplication table is output implicitly)
```
**Task 3 - Fibonacci check:**
```
# No-ops:
£ # Keep the first (implicit) input amount of digits of the (implicit) input
3ô # Split this input into parts of size 3
δн # Take the first digit of each part (let's call this digit d)
ã # Take the cartesian product with itself (which becomes [[d,d]])
¦ # Remove the first item (which becomes [])
L # Push a list in the range [1,[]] (which remains [])
P # Take the product of that list (which becomes 1)
m # Push the (implicit) input to the power this 1 (which becomes the input)
# Main part of the program:
I # Push the input
Ð # Triplicate it
ÅF # Get a list of Fibonacci numbers equal to or below this input
Q # Check for each whether it's equal to the input
ê # Sort and uniquify these checks
O # Sum the remaining checks (which will either be [0] or [0,1])
# (after which this 0/1 is output implicitly as result)
```
**Task 4 - exponentiation sum:**
```
# No-ops:
ÅF # Get all Fibonacci numbers below or equal to the (implicit) input
P # Take the product of those (which will always be 0)
Q # Check if it's equal to the (implicit) input (remains 0)
ê # Sort and uniquify those digits (remains 0)
3ô # Split it into parts of size 3 (which wraps the 0 into a list: [0])
ã # Take the cartesian product of that list with itself (which becomes [[0,0]])
δн # Leave the first item for each of those (which becomes [0])
¦ # Remove the first value (which becomes [])
£ # Keep that many digits of the input (remains [])
# Main part of the program:
IL # Push a list in the range [1,input]
Ð # Triplicate this list
m # Take the power of the values at the same indices of the top two lists
O # And sum those
# (after which this sum of exponents is output implicitly as result)
```
] |
[Question]
[
**This question already has answers here**:
[Analog is Obtuse!](/questions/187245/analog-is-obtuse)
(19 answers)
Closed 4 years ago.
Given the time in 24 hour format (`2359` = `11:59pm`) return the angle between the minute and hour hands on a standard clock (*on the face plane, so don't just output 0*).
Angles are to be returned in the unit of your choice, should be the smallest possible, and should be a positive number (negative angle converted to a positive value), i.e. you will never have an answer greater than 180 degrees or pi radians.
Some examples to check against (in degrees)
* `0000` = `0.0`
* `0010` = `55.0`
* `0020` = `110.0`
* `0030` = `165.0`
* `0040` = `140.0`
* `0050` = `85.0`
* `0150` = `115.0`
* `0240` = `160.0`
* `0725` = `72.5`
* `1020` = `170.0`
* `1350` = `115.0`
* `1725` = `12.5`
Note: There are a few that have rounding errors, I'm not sure how that should be handled; if we should force consistency across all values.
[Answer]
## Haskell - 78 characters
```
q[h,i,m,n]=abs$((600*h+60*i-110*m-11*n-312)`mod`720)-360
c s=q$map fromEnum s
```
Note: My "unit of choice" is the "half-degree", of which there are 720 to the circle. With these units, the answer to the problem is always integral! :-)
Ex.:
```
> map c $ words "0000 0001 0010 0630 0633 2325 2345 2355 2359"
[0,11,110,30,3,335,165,55,11]
> map c $ words "0930 1845 0315 1742 2359"
[210,135,15,162,11]
```
[Answer]
# Golfscript, 42 bytes
```
2/~~\~60*+55*3600%.3600\-]{}$~;.10/'.'@10%
```
Outputs whole-a-degrees in float format.
[Answer]
# TI-BASIC, 22 bytes
```
expr(Ans
sin⁻¹(sin(πfPart(11/6!(Ans-40int(sub(Ans
```
My unit is the "πth of a revolution", equal to 2 radians. The TI-83+ was introduced in 1996, making it much older than this challenge and thus eligible.
First we evaluate the string using `expr(`, then:
```
sub(Ans input/100. Don't ask why.
int(sub(Ans Number of hours
40 Times 40
Ans- Subtract from input. This converts to minutes.
11/6!( Multiply by 11/720 since 720/11 is the period.
fPart( Take fractional part
sin⁻¹(sin(π Map [0,½] to [0,π/2] and [½,1] to [π/2,0].
```
All test cases have been verified.
[Answer]
## ES6, ~~52~~ 50 bytes
```
t=>(t=(t-t.match`..`*40)*11%720,(t>360?720-t:t)/2)
```
Input string, output in degrees. If half degrees is acceptable, 46 bytes:
```
t=>(t=(t-t.match`..`*40)*11%720,t>360?720-t:t)
```
Edit: Saved 2 bytes by using a template string parameter to `match`.
[Answer]
## Perl, 58 characters
Perl is fun
```
perl -nlE "/(..)(..)/;$r=abs$1%12*30-5.5*$2;say+($r,360-$r)[$r>180]"
```
[Answer]
# C99, 86 78 bytes
My units are twelfths of revolutions (so `3` corresponds to 90°)
```
#include<math.h>
float f(int t){return fabs(remainder((t+t%100/1.5)*.11,12));}
```
Equivalently, in C++14, for 76 bytes:
```
#include<cmath>
auto f(int t){return fabs(remainder((t+t%100/1.5)*.11,12));}
```
BSD and SVID platforms have `remd` as an alias for `remainder` (to save 5 more), but I'm sticking with standard C and C++.
## Explanation
We convert sexagesimal seconds to centihours by adding `t%100/1.5` (so 0030 becomes 0050 etc), and divide by 100 to get hours. Coincidence of hands occurs 11 times every 12 hours, so multiply by 11 and divide by 12; we take the remainder in the range [-6,+6], and return its absolute value.
## Test program
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char**argv)
{
int i;
for (i = 1; i < argc; ++i)
printf("%4s: %f\n", argv[i], f(atoi(argv[i])));
return 0;
}
```
# Test output:
A minimum around 12:00:
```
1150: 1.833333
1151: 1.650000
1152: 1.466667
1153: 1.283333
1154: 1.100000
1155: 0.916667
1156: 0.733333
1157: 0.550000
1158: 0.366667
1159: 0.183333
1200: 0.000000
1201: 0.183333
1202: 0.366667
1203: 0.550000
1204: 0.733333
1205: 0.916667
1206: 1.100000
1207: 1.283333
1208: 1.466667
1209: 1.650000
1210: 1.833333
```
And a maximum around 6:00:
```
0555: 5.083333
0556: 5.266667
0557: 5.450000
0558: 5.633333
0559: 5.816667
0600: 6.000000
0601: 5.816667
0602: 5.633333
0603: 5.450000
0604: 5.266667
0605: 5.083333
```
[Answer]
# [Dyalog APL](https://www.dyalog.com/), ~~34~~ ~~32~~ ~~27~~ 25 characters
Full program. Prompts for 4-character string from stdin. Prints radians to stdout.
```
¯2○2○○360÷⍨11×60⊥⍎¨↓2 2⍴⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94P@h9UaPpneDMBAZmxkc3v6od4Wh4eHpZgaPupY@6u07tOJR22QjBaNHvVse9U0FafqvAAYFXOpGxqaW6gA "APL (Dyalog Unicode) – Try It Online")
The angle changes linearly with the time, going through 22×360° every 1440 minutes, or 5.5°/min.
Method:
1. Take input: `⎕`
2. Make into 2-by-2 table: `2 2⍴`
3. Split into rows: `↓`
4. Evaluate each: `⍎¨`
5. Convert to minutes: `60⊥`
6. Convert to degrees and then to radians (5.5t × π/180 = 11t × π/360): `○360÷⍨11×`
7. arccos cos to invert after π/2: `¯2○2○`
Test cases can be verified by converting the result into degrees:
```
angle← {¯2○2○○360÷⍨11×60⊥⍎¨↓2 2⍴⍵}
rads2degs←{180×⍵÷○1}
rads2degs angle ¨ '0000' '0010' '0020' '0030' '0040' '0050' '0150' '0240' '0725' '1020' '1350' '1725'
0 55 110 165 140 85 115 160 72.5 170 115 12.5
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///PzEvPSf1UduE6kPrjR5N7wZhIDI2Mzi8/VHvCkPDw9PNDB51LX3U23doxaO2yUYKRo96tzzq3VrLVZSYUmyUkppeDNJtaGFweDpQGKhrerdh7f//cFkFsA0Kh1YoqBsAgTqIMoRQRhDKGEKZQChTMGUIoYwgguZGpkDKEKLB0BgsZwgSBAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
## Ruby 1.9.2p136 : 78 74
```
def a(t)m=t[2,2].to_f
180-((m*6-(m/60+t[0,2].to_f%12)*30).abs-180).abs
end
```
Sample output:
```
["0000", "0010", "0020", "0030", "0040",
"0050", "0150", "0240", "0725", "1020",
"1350", "1725"].each do |time|
puts "#{time} = #{a(time)}"
end
# Output
0000 = 0.0
0010 = 55.0
0020 = 110.0
0030 = 165.0
0040 = 140.0
0050 = 85.0
0150 = 115.0
0240 = 160.0
0725 = 72.5
1020 = 170.0
1350 = 115.0
1725 = 12.5
```
[Answer]
# Perl, 91 chars
```
#!perl -n
($h,$m)=/(..)(..)/;$h=$h%12+$m/60;$h=abs($h*30-$m*6);printf'%f
',$h>180?360-$h:$h
```
[Answer]
## Perl, 61 characters:
```
sub f{$a=abs(int($_[0]/200)-($_[0]%60)/5);($a>6?12-$a:$a)*30}
```
[Answer]
# Matlab/Octave, 56 bytes
An anonymous function accepting a string, output is in degrees.
```
@(i)180-abs(mod((i-48)*[600;60;10;1],720/11)-360/11)*5.5
```
[Answer]
# Python, 82 bytes
```
def a(t):
o=abs(30*(int(t[:1])%12)-5.5*int(t[2:]));return o if o<=180 else 360-o
```
With some help from the python golfing question I've brought it down to 76:
```
def a(t):
o=abs(30*(int(t[:1])%12)-5.5*int(t[2:]));return [o,360-o][o>180]
```
[Answer]
# Mathematica
```
Grid@Prepend[
Table[{Row[{Quotient[x, 60] /. {0 -> 12}, ":", If[Mod[x, 60] < 10, "0", ""], Mod[x, 60]}],
x, N[x/2, 3], Mod[6 x, 360],
IntegerPart[Min[Abs[x/2 - Mod[6 x, 360]], 360 - Abs[x/2 - Mod[6 x, 360]]]]},
{x, 0, 12*60}], {"time", "elapsed min", "hourhand deg", "min deg", "diff deg"}]
```
**Partial output in table**
![table](https://i.stack.imgur.com/3MmCi.png)
**Graphs**
```
Plot[{ x/2, Mod[6 x, 360], Min[Abs[x/2 - Mod[6 x, 360]], 360 - Abs[x/2 - Mod[6 x, 360]]]}, {x, 0, 12*60},PlotStyle -> {Green, Blue, {Thick, Red}},AxesLabel -> {"time (hs)", "degrees"},GridLinesStyle -> Directive[Dotted, Gray],Ticks -> {Table[{60 k, k}, {k, 0, 12}], Table[30 k, {k, 0, 12}]},GridLines -> {Table[60 k, {k, 0, 12}], None}]
```
The green line shows the angle of the hour hand, as measured in degrees from 12 o'clock, clockwise. The blue line shows the corresponding angle for the minute hand.
The red curve shows the difference between the minute and hour hands in degrees; it always uses the interior angle.
![graphs](https://i.stack.imgur.com/uH0CN.png)
[Answer]
## PHP, 80 Characters
```
<?=($i=$argv[1])&&($n=abs(($i[0].$i[1])%12*30-($i[2].$i[3])*5.5))>180?360-$n:$n;
```
Can be run from CLI `php /script_name input`
### Explanation:
```
<?= // output result to console
($i = $argv[1]) && ( // $argv is an array containing CLI parameters (0: script name, 1: first parameter, etc.)
$n = abs( // absolute value to deal with negative numbers
($i[0] . $i[1]) // get hours - the first two characters from the input (0 and 1)
% 12 * 30 // modulus 12 to deal with PM hours (13-23) multiplied by 360/12 = 30 degrees
- ($i[2] . $i[3]) // get minutes - the subsequent characters from the input (2 and 3)
* 5.5) // multiply minutes by 5.5 (1 minute is 360/60 = 6 degrees
// and the hour hand moves every minute by 30/60 = 0.5 degrees which we subtract)
) > 180 // compare obtained result to 180
? 360 - $n // if the result is greater subtract it from 360
: $n; // if it's less - output as it is
```
### Test cases (input output)
```
0000 0
0010 55
0155 87.5
0240 160
1234 173
2155 32.5
2222 179
```
[Answer]
# Python, 106 bytes
Non-golf solution:
```
def angle_24hr(time_str):
hour, minute = int(time_str[0:1]) % 12, int(time_str[2:3]) % 60
angle_dist = lambda a, b: ((a + (180 - b)) % 360) - 180
return angle_dist(((hour * 30) + (minute * 0.5)), minute * 6) * 10
```
In a more obscure/obfuscated form (admittedly, one of my first code golfs):
```
ad=lambda a,b:((a-b+180)%360)-180;x=int;ag=lambda t:10*ad((x(t[0:1])%12)*60+x(t[2:3]),(x(t[2:3]*12)%60)*6)
```
(what's the point of obfuscating Python?)
If it's necessary for the angles to be purely positive you can remove the -180 term.
[Answer]
## c99 -- 204 necessary characters (keeps getting worse as I fix bugs)
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){char b[5]={0};fgets(b,5,stdin);int a,h,m=atoi(b+2);b[2]=0;
h=(atoi(b)*60+m)%720;m*=12;a=abs((h-m)%720);a=a>360?720-a:a;printf("%i\n",a);}
```
**Discussion:**
The problem turns out to be harder than it looks. The critical issue is what is meant by "smallest positive angle". I've interpreted that the mean a value between [0,180] degrees inclusive (because the problem does not specify which hand to start from when measuring).
To validate this behavior look for places when the hands pass the straight-apart position (such as around 00:33-00:35), and places where they cross-over as around 06:33.
I've also chosen to have a steadily sweeping hour hand, as most modern clocks seem to use that method.
I've [adopted MtnViewMark clever trick of using half-degrees as the base unit](https://codegolf.stackexchange.com/questions/26/angle-between-the-hands-on-a-clock/107#107).
I've suffered the usual problem with c: the preprocessor commands to get the libraries eat up a lot of characters.
**Readable and commented:**
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
char b[5]={0};
fgets(b,5,stdin); /* assumes single byte charaters */
/* printf("'%s'\n",b); */
int a,h,m=atoi(b+2); /* minutes */
b[2]=0;
h=(atoi(b)*60+m)%720; /* hour had position in hald-degrees */
m*=12; /* minute hand position in half degrees */
/* printf("%3i\t%3i\n",h,m); */
/* printf("%i\n", h-m ); */
/* printf("%i\n",(h-m)%720 ); */
a=abs((h-m)%720);
/* printf("%i\n", a ); */
a=a>360?720-a:a;
printf("%i\n",a);
}
```
**Validation:**
```
$gcc -c99 golf_clock_angle.c
$wc golf_clock_angle.c
5 11 206 golf_clock_angle.c
$!for
for t in $(cat clock_test_times.txt); do echo $t $(echo $t|./a.out); done
0000 0
0001 11
0002 22
0010 110
0015 165
0030 330
0033 357
0034 346
0035 335
0045 225
0630 30
0633 3
0634 14
2324 324
2325 335
2355 55
2359 11
```
[Answer]
# C++, 175 174 166 156 Characters
```
#include <iostream>
#include <cmath>
int main(){int m,h;std::cin>>h;m=h%100;h=(h-m)/100;h=h>11?h=h-12:h;h=std::abs(h*60-m*11);std::cout<<std::min(720-h,h);}
```
Using "half degree's" as my unit of choice :D
[Try it Online!](http://cpp.sh/8cxg)
[Answer]
# JavaScript (ES6), 75 bytes
```
x=>Math.min(x=((x=x.match(/\d\d/g))[0]*60+x[1]*1)*5.5%360,360-x).toFixed(1)
```
This question needed a JavaScript solution.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 87 bytes
```
t=>{var i=int.Parse(t);double d=i/100%12*30-i%100*5.5,r=d<0?-d:d;return r>180?360-r:r;}
```
[Try it online!](https://tio.run/##pZFRa8IwEMff8ykOQWjFZklrVEyriLKnCcIGe45tcGE1ZUkqDPGzd7K2G3vbsre7y/34/47kNsorI5vaKn2Ex3fr5ImjtttmbY@3wskndZL9Qzd@UPqNo7wU1sL@gqwTTuVwX@s8tc7cFsdQVPWhlEvYlFX@utbHUkIGjcuWl7MwoDKlHd4LY2XgQt4uQ5GpO0rIkMajhERqeKtHDLOxyYqUrKJiUXAjXW00mCWdk1UyJZFZGH5tOOolzpUqYCeUDkJ0QZtK26qU@NkoJ2/WMtgJ94LXBxt8iwUDQigZhBABY5iEkAKVURzy3@Nxi1NK/Pik46ee@ZOOn3jms5af@8VT1p/vx8e9/tRPfxazT34WY/Z3nH793swrnib/O5/2@vSn/hVdmw8 "C# (.NET Core) – Try It Online")
I'm sure there are possible improvements that I have missed.
### DeGolfed
```
t=>{
var i = int.Parse(t);
// The hour angles minus the minute angles
double d = i / 100 % 12 * 30 -
i % 100 * 5.5,
// account for this possibly being a negative angle
r = d < 0? -d : d;
// Get the smaller of the two possible rotational angles
return r > 180? 360-r : r;
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2ôć12%30*s11;*αD360α)˜ß
```
Outputs degrees like the challenge description.
Port of [*@Juan*'s Python answer](https://codegolf.stackexchange.com/a/67/52210).
[Try it online](https://tio.run/##ASsA1P8wNWFiMWX//zLDtMSHMTIlMzAqczExOyrOsUQzNjDOsSnLnMOf//8wMTUw) or [verify all test cases](https://tio.run/##MzBNTDJM/W9o5ObpYq@k8KhtkoKS/X@jw1uOtBsaqRobaBUbGlprndvoYmxmcG6j5uk5h@f/1/lvAARcBgaGIMIIRBiDCBMQYQokDEGEEYhrbmTKZQhSYmgMFDMEcgE).
**Explanation:**
```
2ô # Split the (implicit) input in pieces of 2
# i.e. "0150" → ['01','50']
ć # Head extracted
# i.e. ['01','50'] → ['50'] and '01' are pushed to the stack
12% # Take the hours modulo 12
30* # Multiplied by 30
# i.e. '01' → 30
s # Swap so the minutes are now at the top of the stack
11;* # And multiple it by 5.5
# i.e. ['50'] → [275.0]
α # Calculate the absolute difference between the two values
# 30 and [275.0] → [245.0]
D # Duplicate this value
360α # Calculate the absolute difference between this value and 360
# i.e. [245.0] → [115.0]
) # Wrap the entire stack to a list
# i.e. [245.0] and [115.0] → [[245.0],[115.0]]
˜ # Flatten this list (necessary due to the head extracted)
# i.e. [[245.0],[115.0]] → [245.0,115.0]
ß # And take the smallest value of the two (output implicitly)
# i.e. [245.0,115.0] → 115.0
```
[Answer]
# SmileBASIC, 60 bytes
```
INPUT T
A=ABS(T DIV 100*60-T MOD 100*11)?A/2+(360-A)*(A>360)
```
] |
[Question]
[
**The Problem**
A doomsday scenario is described by three numbers on a single line, `n`, `m`, and `p`. Following that line are `n` lines with `m` values per line. Each value represents the total units of water each cell can hold.
The following `p` lines describe the weather for the next `p` days. 1 unit of rain falls on a single cell each day. If the amount of water in a cell exceeds the amount it can hold, that cell floods. If multiple adjacent cells are at full capacity, they are treated as one cell that share common neighbors (think Minesweeper when you click on a group of blanks).
* A single middle cell has 4 neighbors
* Two adjacent, full capacity middle cells are treated as one cell that has 6 neighbors
* A single corner cell has 2 neighbors
* A single wall cell has 3 neighbors
When a cell floods, a flood event occurs. All excess water is evenly distributed to its neighbors. If that causes one or more neighbors to flood, then another flood event occurs. This continues until the water has settled, or the city has completely flooded.
**Example Input**
>
> 7 5 3
>
> 3 2 3 4 5
>
> 2 2 0 3 4
>
> 1 1 2 3 3
>
> 4 1 2 2 2
>
> 4 1 1 2 2
>
> 4 4 1 2 2
>
> 4 4 2 2 2
>
> 0 0
>
> 1 2
>
> 4 3
>
>
>
>
* `0 0` means it rained on row 1, col 1
* `1 2` means it rained on row 2, col 3 (which can hold zero water and immediately floods!)
After `p` days of rain, if the city is completely flooded, output **Sink**. Otherwise, output **Swim**.
**Example Output**
>
> Swim
>
>
>
**Assumptions**
* Input may be provided through stdin, read from "city.txt", or accepted as an argument. All three are allowed so as not to invalidate any answers already posted.
* Water capacities will be non-negative integers.
40+ teams of undergrad college students (from A&M, UT, LSU, Rice, Baylor, etc.) competing in a programming contest with a variety of languages available could not solve this problem in 5 hours. Because of that, I can't help but mention that there is a catch to this puzzle that makes the solution trivial. Shortest code still wins, because I am that confident that the shortest code will also solve the puzzle.
[Answer]
# C: ~~100~~ ~~96~~ 95 characters
```
n,m;main(p){scanf("%d%d%d",&n,&m,&p);for(n*=m;n--;scanf("%d",&m))p-=m;puts(p>0?"Sink":"Swim");}
```
Five hours? Took me five minutes. :)
Aragaer, thank you for the simplifications! I did however rearrange the variable declarations and arguments to main, seeing as Clang throws an error if the second argument to main is of any other type than `char **`.
[Answer]
# Golfscript, ~~37~~ [30](http://golfscript.apphb.com/?c=OyI3IDUgMwozIDIgMyA0IDUgCjIgMiAwIDMgNCAKMSAxIDIgMyAzIAo0IDEgMiAyIDIgCjQgMSAxIDIgMiAKNCA0IDEgMiAyIAo0IDQgMiAyIDIgMCAwIDEgMiA0IDMgIgp%2BXShcKEAqXChAQDx7K30qPiJTd2ltU2luayI0Lz0%3D) characters
New and improved, thanks to [PeterTaylor](https://codegolf.stackexchange.com/questions/23259/do-we-sink-or-swim/23270#comment48415_23270) for tips:
```
~](\(@*\(@@<{+}*>"SwimSink"4/=
```
**Explanation**:
```
Code - - Stack
~] - parse input into an array of integers - []
( - pop first number and put on stack - [] 7
\( - \ swaps top two, then pop first num again - 7 [] 5
@ - bring 3rd down from stack to front - [] 5 7
* - mult. this is grid size - [] 35
\(@ - bring next # out - the days of rain - [] 3 35
@ - bring array out - 3 35 []
< - take first 35 elements out of array.
this extracts just the capacities and
consumes the rest - 3 []
{+}* - fold the array using plus - this sums the
entire thing - 3 86
< - greater-than comparison: 3 > 86? - 0
"SwimSink"4/ - push a string and split it to groups of 4 - 0 ["Swim" "Sink"]
= - index into the array using the result of
the comparison. if rain > capacity, then
sink, else swim - "Swim"
```
Program then terminates, outputting the stack.
---
Old version + explanation:
```
[~](\(@*\(@{\(@\-}*\;0>"Sink""Swim"if
```
Same approach as [Fors](https://codegolf.stackexchange.com/a/23263/4800), just Golfscripted =). Can likely be made more efficient. Input is from stdin.
**Explanation**:
```
Code - - Stack
[~] - parse input into an array of integers - []
( - pop first number and put on stack - [] 7
\( - \ swaps top two, then pop first num again - 7 [] 5
@ - bring 3rd down from stack to front - [] 5 7
* - mult. this is grid size - [] 35
\(@ - bring next # out - the days of rain - [] 3 35
{ - define a block which...
\(@ - brings next number out
\- - swaps and subtracts 2nd down from top
} - [] 3 35 {}
* - repeat that block 35 times. this ends up
pulling the capacities out one by one
and decrementing our number-of-days
number by each one - [] -84
\; - swap and kill the array to get rid of
unused input - -84
0>"Sink""Swim"if - if the num > 0, evaluate to "Sink",
otherwise to "Swim" - "Swim"
```
Program then outputs the stack, which is just the answer.
[Answer]
# Python, 4 lines, 175 characters
```
import sys
F=sys.stdin
n,m,p=[int(a) for a in F.readline().split()]
print("sink") if p > sum([sum(int(x) for x in F.readline().split()) for a in range(n)]) else print("swim")
```
Lol, I wonder if the 40+ teams ended up finding the catch... after working it out the hard way.
[Answer]
# J (50 char) and K (40) double feature
Turns out, as usual, these two have the exact same structure in their solutions, so they're both here. K is a whole lot shorter, though, which is a pleasant surprise.
```
>Sink`Swim{~(]<[:+/[+/@".@$+1!:1@#1:)/0 2{".1!:1]1
```
Explanation:
* `".1!:1]1` - Read in the first line, and convert to integers.
* `(...)/0 2{` - Take the items at index 0 and 2 (`n` and `p` respectively), and use them as the left and right arguments to the verb `(...)`, respectively.
* `+1!:1@#1:` - Read in `n+p` lines.
* `[+/@".@$` - Take (`$`) the first `n` rows (`[`), discarding the rest, and then convert to integers (`".`) and sum on each row (`+/`).
* `]<[:+/` - Add together the row sums, and then compare this value to the right argument, `p`. We produce true if `p` is less than the sum.
* `>Sink`Swim{~` - Select `Swim` if the above comprasion resulted in true, or `Sink` if false.
Usage:
```
>Sink`Swim{~(]<[:+/[+/@".@$+1!:1@#1:)/0 2{".1!:1]1
7 5 3
3 2 3 4 5
2 0 3 3 4
1 1 2 3 3
4 1 2 2 2
4 1 1 2 2
4 4 1 2 2
4 4 2 2 2
0 0
1 2
4 3
Swim
```
And now the K:
```
`Sink`Swim@{z<+//.:'x#0::'(x+z)#`}.. 0:`
```
Explained:
* `. 0:`` - Read in a line of input, and convert to an array of integers.
* `{...}.` - Use these three numbers `n m p` as the arguments `x y z` to this function.
* `0::'(x+z)#`` - Create `x+z` copies of the input file handle ```, and then read in a line for each of them (`0::'`).
* `.:'x#` - Take the first `x` items, and convert each to a vector of numbers.
* `z<+//` - Sum the entire matrix together, and then test to see if it is greater than `z`.
* ``Sink`Swim@` - Return `Sink` or `Swim` according to whether the test returned true.
Usage:
```
`Sink`Swim@{z<+//.:'x#0::'(x+z)#`}.. 0:`
7 5 3
3 2 3 4 5
2 2 0 3 4
1 1 2 3 3
4 1 2 2 2
4 1 1 2 2
4 4 1 2 2
4 4 2 2 2
0 0
1 2
4 3
`Swim
```
[Answer]
## APL, 35
```
4↑'SwimSink'⌽⍨4×x[3]>+/{+/⎕}¨⍳1⌷x←⎕
```
Not sure if allowed but it stops accepting input after the "city"
`x←⎕` Takes input and store it in variable `x` (space-delimited numbers are interpreted as a numerical array)
`1⌷` Extract index 1 (APL arrays are one-based)
`⍳` Generate an array from 1 to the argument (`1⌷x←⎕` in this case)
`¨` "Map" operation
`{+/⎕}` Take array from input and return the sum
`+/` Sum the array generated by the map operation
`4×x[3]>` Test if the sum < `x[3]` (returns 1 or 0), then multiply 4
`'SwimSink'⌽⍨` Rotate the string `'SwimSink'` by that amount
`4↑` Finally, extract the first 4 characters of the string
[Answer]
# AWK, 70
```
n{for(;NF;NF--)s+=$NF;n--}NR==1{n=$1;p=$3}END{print p<s?"Swim":"Sink"}
```
This is an imrovement by laindir on my submission (86):
```
NR==1{h=$1;w=$2;r=$3;next}NR<=h{for(i=1;i<=w;++i)c+=$i}END{print(c>r?"Swim":"Sink")}
```
[Answer]
# CoffeeScript - 128 113
A function that takes the string as the only argument:
```
s=(l)->l=l.split /\n/;[n,m,p]=l[x=0].split /\s/;x+=c|0 for c in r.split /\s/ for r in l[1..n];`p>x?"Sink":"Swim"`
```
[Answer]
# SED, 128
It was fun to write a `sed` version of this. It has the following
short-comings:
* It assumes the city has more than two columns, to easily recognise
rain lines.
* It assumes that the capacity of each city is in the range 0-9.
Here it is:
```
1d
s/^. .$/R/
G
:a
s/[\n 0]//
/[2-9]/{s/^/C/
y/23456789/12345678/}
s/1/C/
s/0//
s/RC//
h
ta
${s/R//g
s/^Sink//
s/.*C$/Swim/
p}
```
Call with the `-n` flag.
[Answer]
# SWI-Prolog 79
If you don't mind the fact that this answer takes input by query, rather than via stdin:
```
s(A,L):-append(A,B),sumlist(B,C),length(L,D),(D>C->E='Sink';E='Swim'),print(E).
```
The answer doesn't validate input format, but I don't think it is a problem, since programming contest also doesn't require you to do so.
Sample query (using example in the question):
```
s([[3,2,3,4,5],
[2,2,0,3,4],
[1,1,2,3,3],
[4,1,2,2,2],
[4,1,1,2,2],
[4,4,1,2,2],
[4,4,2,2,2]],
[(0,0),
(1,2),
(4,3)]).
```
[Answer]
# Python - 152
```
import numpy
n, m, p = map(int,raw_input('').split())
print 'swim' if p<numpy.sum(numpy.matrix(';'.join([raw_input('') for i in range(n)]))) else 'sink'
```
[Answer]
# Scala - 128
```
val a=readLine.split(' ')map(_.toInt);println(if((1 to a(0)map(x=>readLine.split(' ')map(_.toInt)sum)sum)>a(2))"swim"else"sink")
```
It might be possible to omit some parentheses or something but Scala is really fickle about punctuation and point-free style and () vs {} and whatnot.
[Answer]
# Javascript - 73 Characters
```
for(i=c=0,a=s.split(/\s/);i++<a[0]*a[1];)c+=a[2+i]*1;c>a[2]?"Swim":"Sink"
```
Assumes the input is in the variable `s` and outputs `Swim` or `Sink`.
**Example:**
From the original question - entering this into the browser console:
```
s="7 5 3\n3 2 3 4 5\n2 2 0 3 4\n1 1 2 3 3\n4 1 2 2 2\n4 1 1 2 2\n4 4 1 2 2\n4 4 2 2 2\n0 0\n1 2\n4 3";
for(i=c=0,a=s.split(/\s/);i++<a[0]*a[1];)c+=a[2+i]*1;c>a[2]?"Swim":"Sink"
```
Outputs:
```
Swim
```
] |
[Question]
[
A simple but hopefully not quite trivial challenge:
Write a program or function that adds up the `k`th powers dividing a number `n`. More specifically:
* Input: two positive integers `n` and `k` (or an ordered pair of integers, etc.)
* Output: the sum of all of the positive divisors of `n` that are `k`th powers of integers
For example, 11! = 39916800 has six divisors that are cubes, namely 1, 8, 27, 64, 216, and 1728. Therefore given inputs `39916800` and `3`, the program should return their sum, `2044`.
Other test cases:
```
{40320, 1} -> 159120
{40320, 2} -> 850
{40320, 3} -> 73
{40320, 4} -> 17
{40320, 5} -> 33
{40320, 6} -> 65
{40320, 7} -> 129
{40320, 8} -> 1
{46656, 1} -> 138811
{46656, 2} -> 69700
{46656, 3} -> 55261
{46656, 4} -> 1394
{46656, 5} -> 8052
{46656, 6} -> 47450
{46656, 7} -> 1
{1, [any positive integer]} -> 1
```
This is code golf, so the shorter your code, the better. I welcome golfed code in all kinds of different languages, even if some other language can get away with fewer bytes than yours.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
DLImDŠÖÏO
```
[Try it online!](https://tio.run/nexus/05ab1e#@@/i45nrcnTB4WmH@/3//zcxMzM14zIGAA "05AB1E – TIO Nexus")
**Explanation**
Example input `46656, 3`
```
D # duplicate first input
# STACK: 46656, 46656
L # range [1 ... first input]
# STACK: 46656, [1 ... 46656]
Im # each to the power of second input
# STACK: 46656, [1, 8, 27 ...]
D # duplicate
# STACK: 46656, [1, 8, 27 ...], [1, 8, 27 ...]
Š # move down 2 spots on the stack
# STACK: [1, 8, 27 ...], 46656, [1, 8, 27 ...]
Ö # a mod b == 0
# STACK: [1, 8, 27 ...], [1,1,1,1,0 ...]
Ï # keep only items from first list which are true in second
# STACK: [1, 8, 27, 64, 216, 729, 1728, 5832, 46656]
O # sum
# OUTPUT: 55261
```
[Answer]
## Mathematica, 28 bytes
```
Tr[Divisors@#⋂Range@#^#2]&
```
Unnamed function taking `n` and `k` as inputs in that order.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-Page)
-1 byte thanks to Dennis (traverse an implicit range)
A clever efficiency save **also** by Dennis at **0-byte cost**
(Previously `ÆDf*€S` would filter keep those divisors that are a power of **k** of any natural number up to **n**. But note that **n** can only ever have a divisor of **ik** if it has a divisor of **i** anyway!)
```
ÆDf*¥S
```
**[Try it online!](https://tio.run/nexus/jelly#@3@4zSVN69DS4P///5uYmZma/TcGAA)**
### How?
```
ÆDf*¥S - Main link: n, k
ÆD - divisors of n -> divisors = [1, d1, d2, ..., n]
¥ - last two links as a dyadic chain
f - filter divisors keeping those that appear in:
* - exponentiate k with base divisors (vectorises)
- i.e. [v for v in [1, d1, d2, ..., n] if v in [1^k, d1^k, ..., n^k]]
S - sum
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~37 35~~ 34 bytes
```
n!k=sum[x^k|x<-[1..n],n`mod`x^k<1]
```
[Try it online!](https://tio.run/nexus/haskell#@5@nmG1bXJobXRGXXVNhoxttqKeXF6uTl5Cbn5IAFLMxjP2fm5iZp2CrUFCUmVeioKJgYmBsZKBo9B8A "Haskell – TIO Nexus") Usage:
```
Prelude> 40320 ! 1
159120
```
The code is quite inefficient because it always computes `1^k, 2^k, ..., n^k`.
**Edit:** Saved one byte thanks to Zgarb.
**Explanation:**
```
n!k= -- given n and k, the function ! returns
sum[x^k| -- the sum of the list of all x^k
x<-[1..n], -- where x is drawn from the range 1 to n
n`mod`x^k<1] -- and n modulus x^k is less than 1, that is x^k divides n
```
[Answer]
# Python 2, ~~54~~ 52 bytes
```
lambda x,n:sum(i**n*(x%i**n<1)for i in range(1,-~x))
```
Thanks @Rod for cutting off 2 bytes.
[Answer]
## Ruby, 45 bytes
```
->n,m{(1..n).reduce{|a,b|n%(c=b**m)<1?a+c:a}}
```
Would be shorter using "sum" in Ruby 2.4. Time to upgrade?
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
t:i^\~5M*s
```
[Try it online!](https://tio.run/nexus/matl#@19ilRkXU2fqq1X8/7@JmZmpGZcZAA "MATL – TIO Nexus")
### How it works
Example with `46656`, `6`.
```
t % Implicitly input n. Duplicate
% STACK: 46656, 46656
: % Range
% STACK: 46656, [1 2 ... 46656]
i % Input k
% STACK: 46656, [1 2 ... 46656], 6
^ % Power, element-wise
% STACK: 46656, [1 64 ... 46656^6]
\ % Modulo
% STACK: [0 0 0 1600 ...]
~ % Logically negate
% STACK: [true true true false ...]
5M % Push second input to function \ again
% STACK: [true true true false ...], [1^6 2^6 ... 46656^6]
* % Multiply, element-wise
% STACK: [1 64 729 0 ...]
s % Sum of array: 47450
% Implicitly display
```
[Answer]
# [Perl 6](http://perl6.org/), 39 bytes
```
->\n,\k{sum grep n%%*,({++$**k}...*>n)}
```
### How it works
```
->\n,\k{ } # A lambda taking two arguments.
++$ # Increment an anonymous counter
**k # and raise it to the power k,
{ }... # generate a list by repeatedly doing that,
*>n # until we reach a value greater than n.
grep n%%*,( ) # Filter factors of n from the list.
sum # Return their sum.
```
[Try it](https://tio.run/nexus/perl6#TZC7boMwGEZ3nuIfSAk3FzDmUhqkbh26NWOkCoGbIIJBIUSNEI/dOTV2Al2wv@PP9jF9R@ESoDxRej7b0u6cKEp9hae8KShsbna6Y9auGrq@hv2JtsBWK8NaD6apGkY1IoSMlOnj7bs5wbFktFvrMCgA9Us3DQDaoIkRQH1lKWxgV5iCW5qE1R3K9iioZqf3VfrT0vxMi6U0JvyjPvOsPqM2K08dqrN2PQCq6BU2KZjokh17CqOO3rPuwN8DUHYwPWg9OVjTnbr1/3AevkTv4@1zC0XDqH3mv6Jk@0QZb4PvYM@xwB3BTsElses5ygN6AkZkIViQEM/Al/vCGRAB8NIIBAjIDEK5xYtnEknCcxCQYJbBUeQuUMoEceg4M5M6hHjB0rsb4difkXSKHOLNSFr5oU@W08KHhssVMOZR5F/W2HmWH@gf "Perl 6 – TIO Nexus")
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
```
f=lambda n,k,i=1:n/i and(n%i**k<1)*i**k+f(n,k,i+1)
```
[Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJCnk62TaWtolaefqZCYl6KRp5qppZVtY6ipBaK10zTACrQNNf8XFGXmlSikaRjrGGpywTlmOkYInrmRpY6x5n8A "Python 2 – TIO Nexus") Large inputs may exceed the recursion depth depending on your system and implementation.
[Answer]
# JavaScript (ES7), ~~56 53~~ 47 bytes
Expects `(n)(k)`.
```
n=>k=>eval("for(i=t=0;i++<n;)t+=n%i**k?0:i**k")
```
[Try it online!](https://tio.run/##ddDRDoIgFIDh@57CubWBzkLgAFbYszjTRjpo5np9WzdiDa7Ozbdzzv5H825e7WSec2HdrVt6vVhdD7ru3s2I0t5NyOhZk7PJ84s94znXdm@ybLiS03ekeGmdfbmxO4zujnrECaMEoxLj5HhMijopoSop2QUVXZWCCGErkSwsuD8lwwJWwSI7xCoEhIX0V2gVJsqTfyAEiJ8oTKkyonwUUUlCwshnAaAismlThlU8bHwbRYCGja/DJYfIR5tAywc "JavaScript (Node.js) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 bytes
*Saved lots of bytes thanks to @ETHproductions*
```
òpV f!vU x
```
## Explanation
```
òpV f!vU x
ò // Creates a range from 0 to U
pV // Raises each item to the power of V (Second input)
f // Selects all items Z where
!vU // U is divisible by Z
// (fvU would mean Z is divisible by U; ! swaps the arguments)
x // Returns the sum of all remaining items
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=8nBWIGYhdlUgeA==&input=NDAzMjAsMg==)
[Answer]
# Scala 63 bytes
```
(n:Int,k:Int)=>1 to n map{Math.pow(_,k).toInt}filter{n%_==0}sum
```
[Answer]
## JavaScript (ES7), ~~49~~ 46 bytes
```
n=>g=(k,t=i=0,p=++i**k)=>p>n?t:g(k,t+p*!(n%p))
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 14 bytes
```
+/*⍨∘⍳(⊣×0=|)⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6pb0KO2CYZGFub/tfW1HvWueNQx41HvZo1HXYsPTzewrdF81LXofxpQyaPevkddzYfWGz9qmwjUFhzkrACkQjw8g/8bKqQpmBgYGxlwGcFZxnCWCZxlCmeZwVnmcJYFnAU2z8zM1AxiHphlDGeZwFmmcJYZnGUOZwEA "APL (Dyalog Classic) – Try It Online")
Takes the power as the left argument and the number as the right. Even at 128-bit precision, the last couple of test cases exceed the max int size.
### Explanation:
```
⍳ ⍝ The range 1 to right argument
*⍨∘ ⍝ Each raised to the power of the left argument
( )⊢ ⍝ Apply the train to this and the right argument
⊣× ⍝ Multiply each power
0=| ⍝ By if the right argument is divisible by it
+/ ⍝ And sum
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 15 bytes
```
$+Ya%_FN(\,a)Eb
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCIkK1lhJV9GTihcXCxhKUViIiwiIiwiMzYwIDIiLCItcCJd)
[Answer]
# PHP, 86 bytes
```
$n=$argv[1];$k=$argv[2];for($i=1;$i<=$n**(1/$k);$i++)if($n%$i**$k<1)$s+=$i**$k;echo$s;
```
[Try it here !](https://eval.in/734616)
**Breakdown :**
```
$n=$argv[1];$k=$argv[2]; # Assign variables from input
for($i=1;$i<=$n**(1/$k);$i++) # While i is between 1 AND kth root of n
if($n%$i**$k<1) # if i^k is a divisor of n
$s+=$i**$k; # then add to s
echo$s; # echo s (duh!)
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 20 bytes
Probably not optimally golfed, but I don't see any obvious changes to make...
```
ri:N,:)rif#{N\%!},:+
```
[Try it online!](https://tio.run/nexus/cjam#@1@UaeWnY6VZlJmmXO0Xo6pYq2Ol/f@/iZmZqZmCCQA "CJam – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
R*³%$ÐḟS
```
[Try it online!](https://tio.run/nexus/jelly#@x@kdWizqsrhCQ93zA/@//@/iZmZqdl/cwA "Jelly – TIO Nexus")
([Credit not mine.](/a/109659/41024))
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 44 bytes
```
bc<<<`seq "-fx=%.f^$2;s+=($1%%x==0)*x;" $1`s
```
[Try it online!](https://tio.run/nexus/bash#@5@UbGNjk1CcWqigpJtWYauqlxanYmRdrG2roWKoqlpha2ugqVVhraSgYphQ/P//fxMzM1Oz/2YA "Bash – TIO Nexus")
Test runs:
```
for x in '40320 1' '40320 2' '40320 3' '40320 4' '40320 5' '40320 6' '40320 7' '40320 8' '46656 1' '46656 2' '46656 3' '46656 4' '46656 5' '46656 6' '46656 7' '1 1' '1 2' '1 3' '1 12' ; do echo -n "$x "; ./sumpowerdivisors $x; done
40320 1 159120
40320 2 850
40320 3 73
40320 4 17
40320 5 33
40320 6 65
40320 7 129
40320 8 1
46656 1 138811
46656 2 69700
46656 3 55261
46656 4 1394
46656 5 8052
46656 6 47450
46656 7 1
1 1 1
1 2 1
1 3 1
1 12 1
```
[Answer]
# [Python](https://docs.python.org/), 56 bytes
```
lambda n,k:sum(j*(j**k**-1%1==n%j)for j in range(1,n+1))
```
[Try it online!](https://tio.run/nexus/python3#bctBCsIwFIThvaeYzaN5MYVGbdBCPImbSqy0aaOkuhLPXiOoiAiz@BfzNbDYTX097F2NoHw1XgfRyTTppcw1aWsDddycIjq0AbEOx4PQKsw18zQmnt2odArk7si3IOOy2fPtv9/YcIVzbMNFjCCIVbFcFApeofk0M/@B6x9oTGne8NUJTg8 "Python 3 – TIO Nexus")
Fairly straightforward. The only noteworthy thing is that `j**k**-1%1` always returns a float in **[0,1)** while `n%j` always returns a non-negative integer, so they can only be equal if both are **0**.
[Answer]
## Batch, 138 bytes
```
@set s=n
@for /l %%i in (2,1,%2)do @call set s=%%s%%*n
@set/at=n=0
:l
@set/an+=1,p=%s%,t+=p*!(%1%%p)
@if %p% lss %1 goto l
@echo %t%
```
Since Batch doesn't have a power operator, I'm abusing `set/a` as a form of `eval`. Very slow when `k=1`. 32-bit integer arithmetic limits the supported values of `n` and `k`:
```
n k
(too slow) 1
<1366041600 2
<1833767424 3
<2019963136 4
<2073071593 5
<1838265625 6
<1801088541 7
<1475789056 8
<1000000000 9
<1073741824 10
<1977326743 11
<244140625 12
<1220703125 13
<268435456 14
<1073741824 15
<43046721 16
<129140163 17
<387420489 18
<1162261467 19
<1048576 20
...
<1073741824 30
```
[Answer]
# [R](https://www.r-project.org/), 35 bytes
```
function(n,k)sum((a=(1:n)^k)*!n%%a)
```
[Try it online!](https://tio.run/##K/pfXJobX5KRGl@QX55aVAxkJpbEJ6Xa/k8rzUsuyczP08jTydYEKtLQSLTVMLTK04zL1tRSzFNVTdT8X5xYUJBTCRS10MFujE6erYmBsZGBJhdcqTkepWZmpmZApVjlNQx1DA0MNP8DAA "R – Try It Online")
3 years later, but 6 bytes shorter than the [previous R answer](https://codegolf.stackexchange.com/questions/109657/sum-the-powers-that-be/109804#109804).
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~10 9~~ 8 bytes
```
ΣnḊ³m^⁰ḣ
```
[Try it online!](https://tio.run/##ASAA3/9odXNr///Oo27huIrCs21e4oGw4bij////NDAzMjD/Mg "Husk – Try It Online")
-1 byte from Jo King.
-1 more byte from Jo King.
## Explanation
```
ΣnḊ³m^⁰ḣ
ḣ range 1..n
m^⁰ each raised to power k
n set intersection with
Ḋ³ divisors of n
Σ sum the list
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
K:?e↔∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJLOj9l4oaU4oiRIiwiIiwiNDY2NTZcbjMiXQ==)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÆvX=pV)*X
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=xnZYPXBWKSpY&input=NDAzMjAKMw)
## 8 bytes
My first pass. Realised as I was about to post it that it's pretty much identical to Oliver's existing solution.
```
opV f@vX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=b3BWIGZAdlg&input=NDAzMjAKMw)
```
ÆvX=pV)*X :Implicit input of integers U=n & V=k
Æ :Map each X in the range [0,U)
v : Is U divisible by
X= : Reassign to X
pV : X raised to the power of V
) : End divisibility check
*X : Multiply by X
:Implicit output of sum of resulting array
```
[Answer]
# R, 28 bytes direct, 43 bytes for function
if n,k in memory:
```
sum((n%%(1:n)^k==0)*(1:n)^k)
```
for a function:
```
r=function(n,k)sum((n%%(1:n)^k==0)*(1:n)^k)
```
] |
[Question]
[
Write a program or function that takes in a string guaranteed to only contain [printable ASCII](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters except for space, and to be a positive [triangular number](https://en.wikipedia.org/wiki/Triangular_number) (1, 3, 6, 10, 15, ...) in length.
Print or return the same string, but shaped into a triangle using spaces. Some examples will best show what I mean:
If the input is `R` then the output will be
```
R
```
If the input is `cat` then the output will be
```
c
a t
```
If the input is `monk3y` then the output will be
```
m
o n
k 3 y
```
If the input is `meanIngfu1` then the output will be
```
m
e a
n I n
g f u 1
```
If the input is `^/\/|\/[]\` then the output will be
```
^
/ \
/ | \
/ [ ] \
```
If the input is
```
Thisrunofcharactersismeanttohavealengththatcanbeexpressedasatriangularnumber.Diditwork?Youtellme,Ican'tcountverywell,ok?
```
then the output will be
```
T
h i
s r u
n o f c
h a r a c
t e r s i s
m e a n t t o
h a v e a l e n
g t h t h a t c a
n b e e x p r e s s
e d a s a t r i a n g
u l a r n u m b e r . D
i d i t w o r k ? Y o u t
e l l m e , I c a n ' t c o
u n t v e r y w e l l , o k ?
```
Basically, newlines are inserted between the substrings of triangular length, spaces are added between all characters, and each line is indented with spaces to fit the triangle shape.
A single trailing newline and lines with trailing spaces are optionally allowed, but otherwise your output should exactly match these examples. The last line of the triangle should not have leading spaces.
**The shortest code in bytes wins.**
[Answer]
## Python, 81 bytes
```
def f(s,p=''):
i=-int(len(2*s)**.5)
if s:f(s[:i],p+' ');print p+' '.join(s[i:])
```
A recursive function. Goes from the end of `s`, chopping off and printing characters. The number of characters to take is computed from the length of `s`. The function is set up to prints in reverse order of the recursive calls, which terminate when `s` is empty and then resolve back up the line. Each layer, the prefix `p` has an extra space added.
In Python 3, the `if` can be done via short circuiting, though this doesn't seem to save chars:
```
def f(s,p=''):i=-int(len(2*s)**.5);s and[f(s[:i],p+' '),print(p+' '.join(s[i:]))]
```
An equally-long alternative with inequality chaining:
```
def f(s,p=''):i=-int(len(2*s)**.5);''<s!=f(s[:i],p+' ')!=print(p+' '.join(s[i:]))
```
Both `print` and `f` return `None`, which is hard to use.
[Answer]
# Pyth, 22 bytes
```
jua+L\ GjdHfTczsM._UzY
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=jua%2BL%5C%20GjdHfTczsM._UzY&test_suite=0&test_suite_input=R%0Acat%0Amonk3y%0AmeanIngfu1%0A%5E/%5C/%7C%5C/%5B%5D%5C%0AThisrunofcharactersismeanttohavealengththatcanbeexpressesasatriangularnumber.Diditwork%3FYoutellme%2CIcan%27tcountverywell%2Cok%3F&input=%5E/%5C/%7C%5C/%5B%5D%5C) or [Test Suite](http://pyth.herokuapp.com/?code=jua%2BL%5C%20GjdHfTczsM._UzY&test_suite=1&test_suite_input=R%0Acat%0Amonk3y%0AmeanIngfu1%0A%5E/%5C/%7C%5C/%5B%5D%5C%0AThisrunofcharactersismeanttohavealengththatcanbeexpressesasatriangularnumber.Diditwork%3FYoutellme%2CIcan%27tcountverywell%2Cok%3F&input=%5E/%5C/%7C%5C/%5B%5D%5C)
### Explanation:
```
jua+L\ GjdHfTczsM._UzY implicit: z = input string
Uz create the list [0, 1, ..., len(z)-1]
._ all prefixes of this list: [[0], [0,1], [0,1,2], ...]
sM sum up each sublist: [0, 1, 3, 6, 10, ...]
cz split z at these indices
fT remove all the unnecessary empty strings
this gives us the list of strings of the triangle
u Y reduce this list, with the initial value G = []
+L\ G prepend a space to each string in G
jdH join the current string with spaces
a and append it to G
j print each string on a separate line
```
[Answer]
## [Retina](https://github.com/mbuettner/retina), ~~108~~ ~~102~~ ~~94~~ ~~87~~ ~~82~~ ~~64~~ 63 bytes
Thanks to Sp3000 for making me pursue my original approach, which brought the byte count from 108 down to 82.
*Massive thanks to Kobi who found a much more elegant solution, which allowed me to save another 19 bytes on top of that.*
```
S_`(?<=^(?<-1>.)*(?:(?<=\G(.)*).)+)
.
$0
m+`^(?=( *)\S.*\n\1)
<space>
```
Where `<space>` represents a single space character (which would otherwise be stripped by SE). For counting purposes, each line goes in a separate file and `\n` should be replaced with an actual linefeed character. For convenience, you can run the code as is from a single file with the `-s` flag.
[Try it online.](http://retina.tryitonline.net/#code=U19gKD88PV4oPzwtMT4uKSooPzooPzw9XEcoLikqKS4pKykKLgokMCAKbStgXig_PSggKilcUy4qXG5cMSkKIA&input=VGhpc3J1bm9mY2hhcmFjdGVyc2lzbWVhbnR0b2hhdmVhbGVuZ3RodGhhdGNhbmJlZXhwcmVzc2VkYXNhdHJpYW5ndWxhcm51bWJlci5EaWRpdHdvcms_WW91dGVsbG1lLEljYW4ndGNvdW50dmVyeXdlbGwsb2s_)
### Explanation
Well... as usual I can't give a full introduction to balancing groups here. For a primer [see my Stack Overflow answer](https://stackoverflow.com/a/17004406/1633117).
```
S_`(?<=^(?<-1>.)*(?:(?<=\G(.)*).)+)
```
The first stage is a `S`plit stage, which splits the input into lines of increasing length. The `_` indicates that empty chunks should be omitted from the splitting (which only affects the end, because there will be a match in the last position). The regex itself is entirely contained in a look-around so it won't match any characters, but only positions.
This part is based on Kobi's solution with some additional golfitude I found myself. Note that lookbehinds are matched right-to-left in .NET, so the following explanation should best be read bottom to top. I've also inserted another `\G` in the explanation for clarity, although that isn't necessary for the pattern to work.
```
(?<=
^ # And we ensure that we can reach the beginning of the stack by doing so.
# The first time this is possible will be exactly when tri(m-1) == tri(n-1),
# i.e. when m == n. Exactly what we want!
(?<-1>.)* # Now we keep matching individual characters while popping from group <1>.
\G # We've now matched m characters, while pushing i-1 captures for each i
# between 1 and m, inclusive. That is, group <1> contains tri(m-1) captures.
(?:
(?<=
\G # The \G anchor matches at the position of the last match.
(.)* # ...push one capture onto group <1> for each character between here
# here and the last match.
) # Then we use a lookahead to...
. # In each iteration we match a single character.
)+ # This group matches all the characters up to the last match (or the beginning
# of the string). Call that number m.
) # If the previous match was at position tri(n-1) then we want this match
# to happen exactly n characters later.
```
I'm still admiring Kobi's work here. This is even more elegant than the prime testing regex. :)
Let's move on to the next stage:
```
.
$0
```
Simple: insert a space after every non-linefeed character.
```
m+`^(?=( *)\S.*\n\1)
<space>
```
This last stage indents all the lines correctly to form the triangle. The `m` is just the usual multiline mode to make `^` match the beginning of a line. The `+` tells Retina to repeat this stage until the string stops changing (which, in this case means that the regex no longer matches).
```
^ # Match the beginning of a line.
(?= # A lookahead which checks if the matched line needs another space.
( *) # Capture the indent on the current line.
\S # Match a non-space character to ensure we've got the entire indent.
.*\n # Match the remainder of the line, as well as the linefeed.
\1 # Check that the next line has at least the same indent as this one.
)
```
So this matches the beginning of any line which doesn't have a bigger indent than the next. In any such position we insert a space. This process terminates, once the lines are arranged in a neat triangle, because that's the minimal layout where each line has a bigger indent than the next.
[Answer]
# [Candy](https://github.com/dale6john/candy), ~~67~~ ~~59~~ 57 bytes
~~`&iZ1-=yZ1+Z*2/>{0g}0=z@1i&{|.}bYR(" ";=)ZR(=a&{;}" ";)"\n";Y1-=ya1j`~~
~~`&1-8*1+r1-2/=y@1i&{|.}bYR(" ";=)ZR(=a&{;}" ";)"\n";Y1-=ya1j`~~
`&8*7-r1-2/=y@1i&{|.}bYR(" ";=)ZR(=a&{;}" ";)"\n";Y1-=ya1j`
or:
```
&
8 *
7 - r
1 - 2 /
= y @ 1 i
& { | . } b
Y R ( " " ;
= ) Z R ( = a &
{ ; } " " ; ) "
\ n " ; Y 1 - = y a
1 j
```
long form:
```
stackSz
digit8 # Y = (sqrt((numCh - 1) * 8 + 1) - 1) / 2 using pythagorean
mult # Y = (sqrt(numCh * 8 - 7) - 1) / 2 equivalent but shorter
digit7
sub
root
digit1
sub
digit2
div
popA
YGetsA
label digit1
incrZ
stackSz # bail if we're out of letters
if
else
retSub
endif
stack2
pushY # print the leading spaces (" " x Y)
range1
while
" " printChr
popA
endwhile
pushZ
range1 # output this row of characters (Z of them)
while
popA
stack1
stackSz
if
printChr # bail on unbalanced tree
endif
" " printChr
endwhile
"\n" printChr
pushY
digit1
sub
popA
YGetsA
stack1
digit1 jumpSub # loop using recursion
```
[Answer]
## CJam, ~~27~~ 26 bytes
*Thanks to Sp3000 for saving 1 byte.*
```
Lq{' @f+_,)@/(S*N+a@\+\s}h
```
~~Surprisingly close to Pyth, let's see if this can be golfed...~~
[Test it here.](http://cjam.aditsu.net/#code=Lq%7B'%20%40f%2B_%2C)%40%2F(S*N%2Ba%40%5C%2B%5Cs%7Dh&input=Thisrunofcharactersismeanttohavealengththatcanbeexpressesasatriangularnumber.Diditwork%3FYoutellme%2CIcan'tcountverywell%2Cok%3F)
### Explanation
```
L e# Push an empty array to build up the lines in.
q e# Read input.
{ e# While the top of the stack is truthy (non-empty)...
' @f+ e# Prepend a space to each line we already have.
_,) e# Get the number of lines we already have and increment.
@/ e# Split the input into chunks of that size.
(S* e# Pull off the first chunk (the next line) and join with spaces.
N+ e# Append a linefeed.
a@\+ e# Append it to our list of lines.
\s e# Pull up the other chunks of the input and join them back into one string.
}h
```
[Answer]
# Ruby, ~~84~~ ~~77~~ 73 bytes
```
->v{1.upto(n=v.size**0.5*1.4){|i|puts" "*(n-i)+v[i*(i-1)/2,i].chars*" "}}
```
**77 bytes**
```
->v{0.upto(n=(v.size*2)**0.5-1){|i|puts" "*(n-i)+v[i*(i+1)/2,i+1].chars*" "}}
```
Reduced few more bytes by removing variable `r` as suggested by steveverrill.
**84 bytes**
```
->v{n=(v.size*2)**0.5-1;0.upto(n){|i|puts" "*(n-i)+v[(r=i*(i+1)/2)..r+i].chars*" "}}
```
**Ungolfed:**
```
->v {
1.upto(n=v.size**0.5*1.4) { |i|
puts" "*(n-i)+v[i*(i-1)/2,i].chars*" "
}
}
```
First calculating triangular number from the input string
```
n=v.size**0.5*1.4
```
i.e. for example input string size is 120 and our triangular number n, will be 15.
```
puts" "*(n-i)+v[i*(i-1)/2,i].chars*" "
```
In the above line, it prints spaces followed by series of string which are fetched from the input string using following pattern
`[[0,0],[1,2],[3,5],[6,9]]`
**Usage:**
```
f=->v{1.upto(n=v.size**0.5*1.4){|i|puts" "*(n-i)+v[i*(i-1)/2,i].chars*" "}}
f["Thisrunofcharactersismeanttohavealengththatcanbeexpressesasatriangularnumber.Diditwork?Youtellme,Ican'tcountverywell,ok?"]
T
h i
s r u
n o f c
h a r a c
t e r s i s
m e a n t t o
h a v e a l e n
g t h t h a t c a
n b e e x p r e s s
e s a s a t r i a n g
u l a r n u m b e r . D
i d i t w o r k ? Y o u t
e l l m e , I c a n ' t c o
u n t v e r y w e l l , o k ?
```
[Answer]
# Pyth, 27 bytes
```
Js.IsSGlzWz+*-J=hZdjd<~>zZZ
z = input()
Z = 0
d = ' '
sSG G -> tri(G)
.I lz Find the (float) input whose output is len(z).
s Convert to int.
J Save as J.
Wz while z:
=hZ Z += 1
*-J Zd Generate J-Z spaces.
~>zZ Remove the first Z characters from z.
< Z Generate those first Z characters.
jd Join on spaces.
+ Add the two together and print.
```
[Test Suite](https://pyth.herokuapp.com/?code=Js.IsSGlzWz%2B%2a-J%3DhZdjd%3C~%3EzZZ&input=%5E%2F%5C%2F%7C%5C%2F%5B%5D%5C&test_suite=1&test_suite_input=R%0Acat%0Amonk3y%0AmeanIngfu1%0A%5E%2F%5C%2F%7C%5C%2F%5B%5D%5C%0AThisrunofcharactersismeanttohavealengththatcanbeexpressesasatriangularnumber.Diditwork%3FYoutellme%2CIcan%27tcountverywell%2Cok%3F&debug=0)
An interesting approach - imperative, and uses `.I`. Probably golfable.
[Answer]
# C, ~~138~~ ~~136~~ 134 bytes
Takes a string as an input :
```
j,r,k,a;f(char*s){j=strlen(s);r=k=sqrt(1+8*j)/2;for(;r--;printf("\n")){for(j=r;j--;)printf(" ");for(j=k-r;j--;)printf("%c ",s[a++]);}}
```
[Answer]
# Ruby approach 2 rev 1, 76 bytes
```
->s{s=s.chars*' '
0.upto(w=s.size**0.5-1){|i|puts' '*(w-i)+s[i*i+i,i*2+2]}}
```
Optimized using syntax ideas from Vasu Adari's answer, plus a few twists of my own.
# Ruby approach 2 rev 0, 93 bytes
```
->s{s=s.chars.to_a.join(' ')
w=(s.size**0.5).to_i
w.times{|i|puts' '*(w-i-1)+s[i*i+i,i*2+2]}}
```
Completely different approach. First we add spaces in between the characters of the input. Then we print out the rows line by line.
# Ruby approach 1, 94 bytes
```
->s{n=-1;w=((s.size*2)**0.5).to_i
(w*w).times{|i|print i/w+i%w<w-1?'':s[n+=1],-i%w==1?$/:' '}}
```
this ended up far longer than anticipated.
`w` contains the number of printable characters in the bottom row, or equivalently, the number of lines.
Every line contains `w` whitespace characters (the last of which is the newline) so the idea is to print these whitespace characters and insert the printable characters where necessary.
[Answer]
## [Minkolang 0.14](https://github.com/elendiastarman/Minkolang), 42 bytes
```
(xid2;$I2*`,)1-[i1+[" "o]lrx" "$ii-1-D$O].
```
[Try it here.](http://play.starmaninnovations.com/minkolang/?code=%28xid2%3B%24I2*%60%2C%291-%5Bi1%2B%5B%22%20%22o%5Dlrx%22%20%22%24ii-1-D%24O%5D%2E&input=Thisrunofcharactersismeanttohavealengththatcanbeexpressesasatriangularnumber%2EDiditwork%3FYoutellme%2CIcan%27tcountverywell%2Cok%3F)
### Explanation
```
( Open while loop
x Dump top of stack
i Loop counter (i)
d2; Duplicate and square
$I2* Length of input times two
`, Push (i^2) <= (length of input)
) Close for loop; pop top of stack and exit when it's 0
1-[ Open for loop that repeats sqrt(len(input))-1 times
i1+[ Open for loop that repeats (loop counter + 1) times
" "o Push a space then read in character from input
] Close for loop
l Push 10 (newline)
r Reverse stack
x Dump top of stack
" " Push a space
$i Push the max iterations of for loop
i- Subtract loop counter
1- Subtract 1
D Pop n and duplicate top of stack n times
$O Output whole stack as characters
]. Close for loop and stop.
```
[Answer]
# Python 2, ~~88~~ 85 bytes
```
s=t=raw_input()
i=1
while s:print' '*int(len(t*2)**.5-i)+' '.join(s[:i]);s=s[i:];i+=1
```
Thanks xnor for saving 3 bytes.
[Answer]
# CJam, 50 Bytes
```
q:QQ,1>{,{),:+}%:RQ,#:IR2ew<{~Q<>:LS*L,I+(Se[N}%}&
```
[Try it here.](http://cjam.aditsu.net/#code=q%3AQQ%2C1%3E%7B%2C%7B)%2C%3A%2B%7D%25%3ARQ%2C%23%3AIR2ew%3C%7B~Q%3C%3E%3ALS*L%2CI%2B(Se%5BN%7D%25%7D%26&input=Thisrunofcharactersismeanttohavealengththatcanbeexpressesasatriangularnumber.Diditwork%3FYoutellme%2CIcan'tcountverywell%2Cok%3F)
Explanation
```
q:QQ,1>{ e# Only proceed if string length > 1, otherwise just print.
,{),:}%:R e# Generates a list of sums from 0 to k, where k goes from 0 to the length of the string [0,1,3,6,10,15,21,...]
Q,#:I e# Find the index of the length of the string in the list
R2ew< e# Make a list that looks like [[0,1],[1,3],[3,6],...,[?,n] ]where n is the length of the string
{~Q<>:L e# Use that list to get substrings of the string using the pairs as start and end indices
S* e# Put spaces between the substrings
L,I+(Se[N e# (Length of the substring + Index of string length in sum array -1) is the length the line should be padded with spaces to. Add a new line at the end.
%}&
```
[Answer]
# JavaScript (ES6), 135 bytes
```
w=>{r='';for(s=j=0;j<w.length;j+=s++);for(i=j=0;w[j+i];j+=++i)r+=Array(s-i-1).join` `+w.slice(j,i+j+1).split``.join` `+'<br>';return r}
```
De-golf + demo:
```
function t(w) {
r = '';
for (s = j = 0; j < w.length; j += s++);
for (i = j = 0; w[j + i]; j += ++i) r += Array(s - i - 1).join` ` + w.slice(j, i + j + 1).split``.join` ` + '<br>';
return r;
}
document.write('<pre>' + t(prompt()));
```
[Answer]
# Java, 258 194
Golfed:
```
String f(String a){String r="";int t=(((int)Math.sqrt(8*a.length()+1))-1)/2-1;int i=0,n=0;while(n++<=t){for(int s=-1;s<t-n;++s)r+=" ";for(int j=0;j<n;++j)r+=a.charAt(i++)+" ";r+="\n";}return r;}
```
Ungolfed:
```
public class TriangulatingText {
public static void main(String[] a) {
// @formatter:off
String[] testData = new String[] {
"R",
"cat",
"monk3y",
"meanIngfu1",
"^/\\/|\\/[]\\",
"Thisrunofcharactersismeanttohavealengththatcanbeexpressedasatriangularnumber.Diditwork?Youtellme,Ican'tcountverywell,ok?",
};
// @formatter:on
for (String data : testData) {
System.out.println("f(\"" + data + "\")");
System.out.println(new TriangulatingText().f(data));
}
}
// Begin golf
String f(String a) {
String r = "";
int t = (((int) Math.sqrt(8 * a.length() + 1)) - 1) / 2 - 1;
int i = 0, n = 0;
while (n++ <= t) {
for (int s = -1; s < t - n; ++s)
r += " ";
for (int j = 0; j < n; ++j)
r += a.charAt(i++) + " ";
r += "\n";
}
return r;
}
// End golf
}
```
Program output:
```
f("R")
R
f("cat")
c
a t
f("monk3y")
m
o n
k 3 y
f("meanIngfu1")
m
e a
n I n
g f u 1
f("^/\/|\/[]\")
^
/ \
/ | \
/ [ ] \
f("Thisrunofcharactersismeanttohavealengththatcanbeexpressedasatriangularnumber.Diditwork?Youtellme,Ican'tcountverywell,ok?")
T
h i
s r u
n o f c
h a r a c
t e r s i s
m e a n t t o
h a v e a l e n
g t h t h a t c a
n b e e x p r e s s
e d a s a t r i a n g
u l a r n u m b e r . D
i d i t w o r k ? Y o u t
e l l m e , I c a n ' t c o
u n t v e r y w e l l , o k ?
```
[Answer]
# JavaScript (ES6), 106 bytes
```
a=>(y=z=0,(f=p=>p?" ".repeat(--p)+a.split``.slice(y,y+=++z).join` `+`
`+f(p):"")(Math.sqrt(2*a.length)|0))
```
Uses recursion instead of a for loop to build the string.
To find the length of the longest row, use the formula for the nth triangular number `T_n` is `T_n = (n^2 + n)/2`. Given `n` and solving for `T_n` using the quadratic formula, we have:
```
1/2 * n^2 + 1/2 * n - T_n = 0
a = 1/2, b = 1/2, c = -T_n
-1/2 + sqrt(1/2^2 - 4*1/2*-T_n)
------------------------------- = sqrt(1/4 + 2*T_n) - 1/2
2*1/2
```
It turns out that after flooring, adding 1/4 inside the square root doesn't change the result, hence the formula for the longest row is `Math.sqrt(2*a.length)|0`.
[Answer]
# [TeaScript](https://github.com/vihanb/TeaScript), 44 [Bytes](https://en.m.wikipedia.org/wiki/ISO/IEC_8859)
```
r(m=$s(2*xn)|0)ßp.R(m-i)+x·.S(v,v+=Æw)jø+§)µ
```
This uses the same method as my [JavaScript answer](https://codegolf.stackexchange.com/a/65505/45393), but is a lot shorter.
### Ungolfed
```
r(m=$s(2*xn)|0)m(#p.R(m-i)+xs``.S(v,v+=++w)j` `+`
`)j``
```
[Answer]
# Powershell, 69 bytes
```
($args|% t*y|?{$r+="$_ ";++$p-gt$l}|%{$r;rv r,p;$l++})|%{' '*--$l+$_}
```
Less golfed test script:
```
$f = {
(
$args|% t*y|?{ # test predicate for each char in a argument string
$r+="$_ " # add current char to the result string
++$p-gt$l # return predicate value: current char posision is greater then line num
}|%{ # if predicate is True
$r # push the result string to a pipe
rv r,p # Remove-Variable r,p. This variables will be undefined after it.
$l++ # increment line number
}
)|%{ # new loop after processing all characters and calculating $l
' '*--$l+$_ # add spaces to the start of lines
} # and push a result to a pipe
}
@(
,("R",
"R ")
,("cat",
" c ",
"a t ")
,("monk3y",
" m ",
" o n ",
"k 3 y ")
,("meanIngfu1",
" m ",
" e a ",
" n I n ",
"g f u 1 ")
,("^/\/|\/[]\",
" ^ ",
" / \ ",
" / | \ ",
"/ [ ] \ ")
,("Thisrunofcharactersismeanttohavealengththatcanbeexpressedasatriangularnumber.Diditwork?Youtellme,Ican'tcountverywell,ok?",
" T ",
" h i ",
" s r u ",
" n o f c ",
" h a r a c ",
" t e r s i s ",
" m e a n t t o ",
" h a v e a l e n ",
" g t h t h a t c a ",
" n b e e x p r e s s ",
" e d a s a t r i a n g ",
" u l a r n u m b e r . D ",
" i d i t w o r k ? Y o u t ",
" e l l m e , I c a n ' t c o ",
"u n t v e r y w e l l , o k ? ")
,("*/\/|\/|o\/|o|\/o|o|\/||o|o\/o|||o|\/o||o|||\/||o|||o|\/|o|||o||o\",
" * ",
" / \ ",
" / | \ ",
" / | o \ ",
" / | o | \ ",
" / o | o | \ ",
" / | | o | o \ ",
" / o | | | o | \ ",
" / o | | o | | | \ ",
" / | | o | | | o | \ ",
"/ | o | | | o | | o \ ")
) | % {
$s,$expected = $_
$result = &$f $s
"$result"-eq"$expected"
$result
}
```
Output:
```
True
R
True
c
a t
True
m
o n
k 3 y
True
m
e a
n I n
g f u 1
True
^
/ \
/ | \
/ [ ] \
True
T
h i
s r u
n o f c
h a r a c
t e r s i s
m e a n t t o
h a v e a l e n
g t h t h a t c a
n b e e x p r e s s
e d a s a t r i a n g
u l a r n u m b e r . D
i d i t w o r k ? Y o u t
e l l m e , I c a n ' t c o
u n t v e r y w e l l , o k ?
True
*
/ \
/ | \
/ | o \
/ | o | \
/ o | o | \
/ | | o | o \
/ o | | | o | \
/ o | | o | | | \
/ | | o | | | o | \
/ | o | | | o | | o \
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
ā£õKεSðý}.c
```
[Try it online!](https://tio.run/##DcsxDsIwDADA57BU/UIXFsQIC6ObmiZqYiPbaWFg4C18gKUjC2XmS6HrSccKbcBSvo/Pc5n3v/mwvJb3vXalHH1QycRn50HAGYoGTQhkxh5GhIjUmzcP5oBaxOtFUBU7UDAJQH2OIJRTi1JvQxdsYhmaE2fDGBNWu7VtzHEmG1Fu06oVD80f "05AB1E – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `C`, 5 bytes
```
KÞṁvṄ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJDIiwiIiwiS8Oe4bmBduG5hCIsIiIsIltcIm1cIixcIm9cIixcIm5cIixcImtcIixcIjNcIixcInlcIl0iXQ==)
```
Þṁ # Mold (without repeating elements) to...
K # Prefixes
vṄ # Join each on spaces
# (C flag) center the result
```
[Answer]
## C#, 202
```
string r(string s,List<string> o,int i=1){o=o.Select(p=>" "+p).ToList();o.Add(String.Join(" ",s.Substring(0,i).ToCharArray()));return s.Length==i?String.Join("\n",o):r(s.Substring(i,s.Length-i),o,i+1);}
```
I don't know if this is legal in code-golf but, does passing a list in the function count? I can't find a way to recurse this without a List< string > declared outside the function so I put it as a parameter.
Usage:
```
r("1",new List<string>());
r("123", new List<string>());
r("123456", new List<string>());
r("Thisrunofcharactersismeanttohavealengththatcanbeexpressedasatriangularnumber.Diditwork?Youtellme,Icanstcountverywell,ok?",new List<string>());
```
[Answer]
# C, 102 bytes
```
i,j;main(n,s){for(n=sqrt(strlen(gets(s))*2);j<n;printf("%*.1s",i>1?2:i*(n-j),i++>j?i=!++j,"\n":s++));}
```
[Answer]
# Bash + sed, 87
```
for((;i<${#1};i+=j));{
a+=(${1:i:++j})
}
printf %${j}s\\n ${a[@]}|sed 's/\S/ &/g;s/.//'
```
[Answer]
# R, 142 bytes
Pretty sure I can get this down more. Still working on that though. I feel like I'm missing an easy recursion -- but I haven't been able to shorten it right.
```
f=function(a){n=nchar(a);l=which(cumsum(1:n)==n);w=strsplit(a,c())[[1]];for(i in 1:l){cat(rep(" ",l-i),sep="");cat(w[1:i],"\n");w=w[-(1:i)]}}
```
ungolfed
```
f=function(a){
n = nchar(a) #number of characters
l= which(cumsum(1:n)==n) #which triangle number
w= strsplit(a,c())[[1]] #Splits string into vector of characters
for (i in 1:l) {
cat(rep(" ",l-i),sep="") #preceeding spaces
cat(w[1:i],"\n") #Letters
w=w[-(1:i)] #Shifts removes letters (simplifies indexing)
}
}
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 24 bytes
```
{:|&›:¥Ẏ⅛¥ȯ}¾ƛfṄ¾LnL-ð*p
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%7B%3A%7C%26%E2%80%BA%3A%C2%A5%E1%BA%8E%E2%85%9B%C2%A5%C8%AF%7D%C2%BE%C6%9Bf%E1%B9%84%C2%BELnL-%C3%B0*p&inputs=Thisrunofcharactersismeanttohavealengththatcanbeexpressedasatriangularnumber.Diditwork%3FYoutellme%2CIcan%27tcountverywell%2Cok%3F&header=&footer=)
] |
[Question]
[
# Input
no input for this challenge
# The Challenge
Write a code that outputs:
**The first 10 prime numbers whose sum of their digits equal the number of bytes of your code**
# Examples
Let's say your code is `Co&%423@k"oo"` which is `13 bytes`
your code must output `[67, 139, 157, 193, 229, 283, 337, 373, 409, 463]`
If your code is `8 bytes`, you must output `[17, 53, 71, 107, 233, 251, 431, 503, 521, 701]`
# Rules
You must **only use the first 10^8 prime numbers**
***which means all your numbers must be <2038074743=10^8th prime***
If you **can't find 10 prime numbers in this range** that fit your bytes, then you will have to adjust your code (you may even have to add some bytes!) in order to find a "***working number of bytes***"
Just **output the 10 primes** in any way you like
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes win!
[Answer]
# [Neim](https://github.com/okx-code/Neim), ~~10~~ ~~8~~ 7 [bytes](https://github.com/okx-code/Neim/wiki/Code-Page)
*-1 byte thanks to ASCII-only.*
```
œÄ·õ¶ùêãŒõùê¨7ùîº
```
[Try it online!](https://tio.run/##y0vNzP3//3zDw9nLPsyd0H1uNpBcY/5h7pQ9//8DAA "Neim – Try It Online")
Outputs:
```
[7 43 61 151 223 241 313 331 421 601]
```
This (well, at least the approach) is ungolfable.
## Explanation
```
œÄ·õ¶ùêãŒõùê¨7ùîº
π push 13 (yes, very unintuitive :P)
ᛦ square (13² = 169)
ùêã push the first 169 primes
Λ filter those that when the following are executed, evaluate to 1
ùê¨ sum its digits and...
7ùîº check for equality against 7
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
‘ÆNDS=14ø⁵#‘ÆN
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw4zDbX4uwbaGJod3PGrcqgwR@P8fAA "Jelly – Try It Online")
This prints:
```
[59, 149, 167, 239, 257, 293, 347, 383, 419, 491]
```
**How it works**
```
‘ÆNDS=14ø⁵#‘ÆN
# Count the first
⁵ 10
Non-negative integers which meet:
‘ÆN the (z+1)-th prime (1-indexed :*()
D digits
S sum
= equals
14 14
‘ÆN Get those primes
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 14 bytes
```
.f&qsjZT14P_ZT
```
**[Try it here.](https://pyth.herokuapp.com/?code=.f%26qsjZT14P_ZT&debug=0)**
This is 14 bytes and prints:
```
[59, 149, 167, 239, 257, 293, 347, 383, 419, 491]
```
# [Pyth](https://pyth.readthedocs.io), 16 bytes
```
.f&qssM`Z16P_ZTZ
```
**[Try it here!](https://pyth.herokuapp.com/?code=.f%26qssM%60Z16P_ZTZ&debug=0)**
Note that this could be 15 bytes: `.f&qssM`Z16P_ZTZ`, but there are no primes that have 15 as the sum of their digits, since `15` is divisible by `3`, which would imply the number would also be divisible by `3`, hence not being prime.
This is 16 bytes long and prints:
```
[79, 97, 277, 349, 367, 439, 457, 547, 619, 673]
```
---
# How?
### Explanation 1
```
.f&qsjZT16P_ZT - Full program.
.f& T - First 10 numbers that satisfy the following:
P_Z - Are prime and
sjZT - And their sum of digits
q 14 - Equals 14.
```
### Explanation 2
```
.f&qssM`Z16P_ZTZ - Full program.
.f& T - First 10 numbers that satisfy the following:
P_Z - Are prime and
ssM`Z - And their sum of digits
q 16 - Equals 16.
```
[Answer]
## [Husk](https://github.com/barbuz/Husk), 13 bytes
```
↑10fȯ=13ΣdfṗN
```
[Try it online!](https://tio.run/##yygtzv7//1HbREODtBPrbQ2Nzy1OSXu4c7rf//8A "Husk – Try It Online")
### Explanation
```
N Take the (infinite) list of all natural numbers.
f·πó Select only the primes.
fȯ Filter again by the result of composing the following three functions:
d Get the decimal digits.
Σ Sum them.
=13 Check whether the sum equals 13.
‚Üë10 Take the first 10 primes in the result.
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~77~~ 71 bytes
```
x=take 10[i|i<-[1..],sum(read.pure<$>show i)==71,all((>0).rem i)[2..i-1]]
```
[Try it online!](https://tio.run/##DcixCoAgEADQX7mhwcCObGnJfkQcDjroUCu0qKF/t974ViqBY6z1sScFBtM7eWXqnEH0ulxJZaYFjyvz1Mxl3W@Q1trRaIpRqblvMXP6zw2I0hnvayLZwMKRZTvhqR8 "Haskell – Try It Online")
*Saved 6 bytes thanks to Laikoni*
*For 71 bytes:*
```
[89999999,99899999,99998999,99999989,189989999,189998999,189999989,197999999,199898999,199979999]
```
>
> all your numbers must be <2038074743
>
>
>
1999999999 is the number with the maximum sum of digits in the allowed range, and that sum is 82. Any program that is beyond 82 bytes will not satisfy the condition. I hope that 77 bytes is ok, but I don't know (it's still running on my computer).
**EDIT:** a slightly optimized version gave for 77 bytes:
```
[699899999,779999999,788999999,789999989,797999999,798899999,799898999,799899899,799999799,879999899]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~ 14 ~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
DS⁼13
.ȷÆRÇÐf
```
**[Try it online!](https://tio.run/##y0rNyan8/98l@FHjHkNjLr0T2w@3BR1uPzwh7f9/AA "Jelly – Try It Online")**
### How?
```
DS⁼13 - Link 1, test digit sum equals thirteen: number, n
D - get a list of the decimal digits of n
S - sum them
⁼13 - equals thirteen?
.ȷÆRÇÐf - Main link: no arguments
.»∑ - literal 500
ÆR - prime range (all primes less than or equal to 500)
Ðf - filter keep if:
Ç - call last link (1) as a monad
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes
```
{.≜ṗẹ+13∧}ᶠ¹⁰
```
[Try it online!](https://tio.run/##ASoA1f9icmFjaHlsb2cy//97LuKJnOG5l@G6uSsxM@KIp33htqDCueKBsP///1o "Brachylog – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
83L√ò íSOTQ}
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fwtjn8IxTk4L9QwJr//8HAA)
The `}` is used as a filler, since 9 is an invalid byte count.
Output: `[19, 37, 73, 109, 127, 163, 181, 271, 307, 433]`
## Explanation
```
83L Push array [1, ..., 83], since 433 is the 83rd prime
√ò Map each to the nth prime
í Get elements that return 1
SO When the sum of the digits
Q Equals
T 10
```
---
# Almost 8 bytes
This would be valid if one more byte could be golfed off.
```
≈æyL√ò íSO8Q
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6L5Kn8MzTk0K9rcI/P8fAA)
Output: `[17, 53, 71, 107, 233, 251, 431, 503, 521, 701]`
## Explanation
```
žy Push number 128, since 701 is the 125th prime
L Push array [1, ..., 128]
√ò íSO8Q Map to nth primes and filter to those with a digit sum of 8 (see above)
```
[Answer]
# Mathematica, 52 bytes
```
Select[Prime@Range[10^6],Tr@IntegerDigits@#==52&,10]
```
>
> {799999,998989,999979,1789999,1798999,1979899,1989979,1997899,1999969,2599999}
>
>
>
thanx to @Not a tree for -6 bytes
[Answer]
# J, 29 bytes
```
(#~(29=[:+/"."0@":)"0)p:i.872
```
[Try it online!](https://tio.run/##y/r/PzU5I19BQ7lOw8jSNtpKW19JT8nAQclKU8lAs8AqU8/C3Oj/fwA)
Definitely works on the REPL, probably works a regular program too (not sure how J does output for programs to be honest).
First pass, not particularly ideal but I can't think of any more clever approaches. Going to investigate hardcoding a smaller sequence.
# Explanation
```
(#~(29=[:+/"."0@":)"0)p:i.872
p:i.872 First 872 primes
#~ Filter by
(29=[:+/"."0@":)"0 Digital sum = 29
"0 For each
": Convert to string
"."0 Convert each character to a number
+/ Sum results
29= Equate to 29
```
872 guarantees that only the first 10 primes whose digital sum is 29 will be used.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 73 71 bytes
```
i8aa9
998a99
a98a
aa89
18998a9
18a8a
18a9989
197aa
199898a
1a7a9Ía/999
```
[Try it online!](https://tio.run/##HckxFYBADATRPhYQwbvqMnKmxAAuUIWwkFDt7t@76kolIIWwIzSJlT912rTmHWXba/qoW4738QSqPg "V – Try It Online")
Simple substring replacement compression - I checked all the possible answer outputs, and then did some "which one has a simple string replacement that saves most characters" testing. e.g. [generating this table](https://gist.github.com/anonymous/08cd1a2d18e636af29d3c7682ede480b). [edit: I looked again at the table and saw I could do the 71 byte version instead].
The higher primes have more long runs of 9 in them, and the best I found was where the digits add up to 73, the pattern 89999 -> 1 char brings the text down from 99 bytes to 63 bytes. Finding a way to undo 'a' -> '89999' in the remaining 10 bytes led me to V.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 19 bytes
```
AÆ_j ©19¥Zì x «X´}a
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=QcZfaiCpMTmlWuwgeCCrWLR9YQ==&input=LVE=) with the `-Q` flag to format the array.
Outputs the first 10 primes whose digits add to `19`:
```
[199, 379, 397, 487, 577, 739, 757, 829, 883, 919]
```
Note that this could be golfed to 18 bytes (`√¨ x` → `√¨x`), but no primes with a digit sum of 18 exist.
## Explanation
```
AÆ
```
Map the array `[0, ..., 9]` by the following function, where `X` is the current value.
```
_ }a
```
Return the first integer that returns true from the following function, where `Z` is the current value
```
j ©
```
Check if this number is prime, and...
```
19¥Zì x
```
The sum (`x`) of the digits (`ì`) in `Z` equals (`¥`) 19,
```
«X´
```
And `X` is falsy (`«` is "and not", or `&&!`). This also decrements `X` (`´`).
Resulting array is implicitly outputted.
[Answer]
# PARI/GP, 40 bytes
```
select(x->sumdigits(x)==40,primes(8600))
```
Not much golf about it (select those `x` with sum of digits 40 among first 8600 primes). Output is:
```
[49999, 68899, 69997, 77899, 78889, 78979, 79699, 79987, 85999, 88789]
```
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 10 bytes
```
~p#.cTq)T>
```
[Try it here!](http://pyke.catbus.co.uk/?code=%7Ep%23.cTq%29T%3E&input=&warnings=1&hex=0)
```
~p - primes
#.cTq) - filter(^)
.c - digit_sum
Tq - ^ == 10
T> - [:10]
```
[Answer]
# Ruby 2.4.1, 74 Bytes
I was never going to beat one of the Codegolf optimised languages, but it was still fun to do it in Ruby. Frustrating that Prime is not in Core but in instead in the standard library. I am also frustrated that I can't beat Haskell.
```
2.4.1 :014 > require'prime';2.step.lazy.select{|n|n.digits.sum==74&&n.prime?}.first(10)
=> [389999999, 398999999, 498989999, 498998999, 499898999, 499899989, 499979999, 499989989, 579989999, 588999899]
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-rprime`, 49 bytes
```
p *Prime.lazy.select{_1.digits.sum==49}.take(10)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7IKlpSVpuhY3DQsUFLQCQGJ6OYlVlXrFqTmpySXV8YZ6KZnpmSXFesWluba2Jpa1eiWJ2akahgaaEI1Q_QugNAA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
æ*∑8=)₀ȯ
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDpiriiJE4PSnigoDIryIsIiIsIiJd)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~19~~ 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Would be 12 if not for a bug in Japt's `j` function method, which would have necessitated padding it out to 13 as there are no primes with a digit sum of 12.
```
Èj «BaXìx}j
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yGogq0JhWOx4fWo)
```
Èj «BaXìx}j
È :Function taking an integer X as argument
j : Is prime?
¬´ : Logical AND with logical NOT of
B : 11
a : Absolute difference with
Xì : Digit array of X
x : Reduced by addition
} :End function
j :Get the first 10 integers >=0 that return true
```
[Answer]
# [Paradoc](https://github.com/betaveros/paradoc) (v0.2.7+), 10 bytes (CP-1252)
```
5h¶fφTBŠT=
```
[Try it online!](https://tio.run/##K0gsSkzJT/7/3zTj0La0820hTkcXhNj@/w8A "Paradoc – Try It Online")
```
5h .. 5 hundred
¶ .. Check if a number is prime...
f .. ...filter by the preceding block; converts 500
.. to the range [0, 1, ..., 499]
φ .. Filter by the following block:
T .. Ten
B .. Base; convert to base-10 digits
Š .. Sum, resulting in the digit sum
T .. Ten
= .. Check if (the digit sum and ten are) equal
```
Somewhat questionable since it prints all the numbers with no separator between them. An 11-byte program that prints each number on a separate line:
```
nIè¶fφTBŠE=
```
The only thing worth mentioning about it is the upper bound that's slightly more difficult to construct: `Iè` is 18² = 324.
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 37 bytes
```
00000000: 0dc6 3901 4031 0c80 5043 9dfe 9180 7f63 [[email protected]](/cdn-cgi/l/email-protection)
00000010: 6579 f028 9ed7 352d e7a3 4f48 37ff 9164 ey.(..5-..OH7..d
00000020: 4c96 04f7 02 L....
```
[Try it online!](https://tio.run/##fc2hDgIxEIRhz1OMxLDZdtvuFUWCQZDAK3BtFwPyBE9feuE0vxvzzbzM86s9l3fvvHUE15IgmR0CiwOXiRE5CHK1huzGVEsCEGU6OaL7mdbK7ie4YaSoGcZ@Qm5VIdFXNH0IgoUJomYDSgFoH9oTxQPR7aJEdTP8MELJCRxMwR7/uq7vvX8B "Bubblegum – Try It Online")
Output is `29989,39799,39979,48799,48889,49789,56989,58699,58789,58897`
] |
[Question]
[
This question will be a twist on finding the `n`th prime number.
# Challenge
You must write a program that will take one input `n`, and output the `n`th prime number whose decimal representation contains the decimal representation of `n` as a subtring.
Confused? Here are some examples.
```
n=1
Primes: 2, 3, 5, 7, 11
^1 first prime that contains a 1
Output: 11
n=2
Primes: 2, 3, 5, 7, 11, 13, 17, 19, 23
^1 ^2 second prime that contains a 2
Output: 23
n=3
Primes: 2, 3, 5, 7, 11, 13, 17, 19, 23
^1 ^2 ^3 third prime that contains a 3
Output: 23
n=10
Primes: 2, 3, 5, 7, 11, ..., 97, 101, 103, 107, 109, ..., 997, 1009, 1013, 1019, 1021, 1031, 1033
^1 ^2 ^3 ^4 ^5 ^6 ^7 ^8 ^9 ^10 tenth prime that contains a 10
Output: 1033
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte count wins.
If something is confusing, please leave a comment.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 8 bytes
Code:
```
µN¹åNp*½
```
Explanation:
```
µ # Run this until the counting variable has reached the input value.
N¹å # Check if the input number is in the range variable.
Np # Check if the range variable is prime.
* # Multiply those two numbers (which is basically an AND operator).
¬Ω # If true, increment the counting variable.
# After the loop, the stack is empty and implicitly prints N.
```
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=wrVOwrnDpU5wKsK9&input=MTA).
[Answer]
# Pyth - 11 bytes
```
e.f&P_Z}`Q`
```
[Test Suite](http://pyth.herokuapp.com/?code=e.f%26P_Z%7D%60Q%60&test_suite=1&test_suite_input=1%0A2%0A3%0A10&debug=0).
[Answer]
# Python 2, ~~67~~ ~~65~~ 62 bytes
```
f=lambda n,k=0,m=2,p=1:k/n or-~f(n,k+p%m*(`n`in`m`),m+1,p*m*m)
```
Test it on [Ideone](http://ideone.com/epHD9u).
### How it works
We use a corollary of [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem):
![corollary of Wilson's theorem](https://i.stack.imgur.com/mPJHD.png)
At all times, the variable **p** is equal to the square of the factorial of **m - 1**.
If **k < n**, `k/n` will yield **0** and **f** is called recursively. **m** is incremented, **p** is updated, and **k** is incremented if and only if **m** is a prime that contains **n**.
The latter is achieved by adding the result of `p%m*(`n`in`m`)` to **k**. By the corollary of Wilson's theorem if **m** is prime, `p%m` returns **1**, and if not, it returns **0**.
Once **k** reaches **n**, we found **q**, the **n**th prime that contains **n**.
We're in the next call during the check, so **m = q + 1**. `k/n` will return **1**, and the bitwise operators `-~` will increment that number once for every function call. Since it takes **q - 1** calls to **f** to increment **m** from **2** to **q + 1**, the outmost call to **f** will return **1 + q - 1 = q**, as intended.
[Answer]
## Bash, 27 bytes
```
primes 0|grep $1|sed $1q\;d
```
`primes` comes from bsdgames.
Takes input as a command line argument, and outputs on STDOUT.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
×ÆP,³Dœṣ/Ṗµ#Ṫ
```
[Try it online!](http://jelly.tryitonline.net/#code=w5fDhlAswrNExZPhuaMv4bmWwrUj4bmq&input=&args=MTA)
[Answer]
# Mathematica, 75 bytes
```
Nest[NestWhile[b=NextPrime,b@#,!StringContainsQ@@ToString/@{#,a}&]&,1,a=#]&
```
May still be golfable.
[Answer]
# Java, 194 180 173 ~~171~~ 112 Bytes
Code:
```
a->{int i=1,j,n,r=0;for(j=n=new Integer(a);(r+=++i>=j&(""+j).contains(""+n)?1:0)!=n;j+=j%i==0?i=1:0);return j;}
```
Ungolfed:
```
class P{
static int i=1,j,n,r;
public static void main(String[]s) {
for(
j=n=new Integer(s[0]); //executes once before first iteration
(r+=++i>=j&(""+j).contains(""+n)?1:0)!=n; //executes on first and every iteration
j+=j%i==0?i=1:0 //executes after first and every iteration
) {
;
}
System.out.print(j);
}
}
```
[Answer]
## Ruby, ~~62~~ 61 bytes
```
->i{Prime.lazy.map(&:to_s).grep(/#{i}/).first(i)[-1]}
```
Requires the `-rprime` flag (+8 bytes).
```
->i{ # lambda with one argument
Prime # iterator over all primes
.lazy # make the iterator lazy (can't evaluate infinite primes)
.map(&:x.to_s) # convert the primes to strings
.grep(/#{i}/) # find primes that regex match on the input (contain it)
.first(i) # take the first (input) primes that satisfy this
[-1] # take the last of those
}
```
[Answer]
# Julia, ~~61~~ 60 bytes
```
f(n,k=0,m=1)=k<n&&f(n,k+isprime(m)contains("$m","$n"),m+1)+1
```
[Try it online!](http://julia.tryitonline.net/#code=ZihuLGs9MCxtPTEpPWs8biYmZihuLGsraXNwcmltZShtKWNvbnRhaW5zKCIkbSIsIiRuIiksbSsxKSsxCgpmb3IgbiBpbiAxOjIwCiAgICBAcHJpbnRmKCIlMmQgJTRkXG4iLCBuLCBmKG4pKQplbmQ&input=)
[Answer]
# [MATL](http://github.com/lmendo/MATL), 18 bytes
```
`@YqVGVXf?3M]NG<]&
```
[**Try it online!**](http://matl.tryitonline.net/#code=YEBZcVZHVlhmPzNNXU5HPF0m&input=MTA)
### Explanation
This generates primes in order using a `do...while` loop. For each prime, the condition is tested (and the prime is consumed). If satisfied, that prime is pushed to the stack again. The number of elements in the stack is used as count of how many qualifying primes we have found. When there are enough of them, the last one is displayed.
```
` % Do...while
@ % Push iteration index, k. Starts at 1
YqV % k-th prime. Convert to string
GV % Push input, n. Convert to string
Xf % Find string within another
? % If non-empty
3M % Push k-th prime again (increase stack size by 1)
] % End if
NG< % Is stack size less than input number? If so proceeed with
% a new iteration; else exit do...while loop
] % End do...while
& % Implicitly display only top number in the stack
```
[Answer]
## Pyke, 15 bytes
```
Q.fD_P.I`Q`R{(e
```
[Try it here!](http://pyke.catbus.co.uk/?code=Q.fD_P.I%60Q%60R%7B%28e&input=3)
[Answer]
# Bash + GNU coreutils, 66 Bytes
In contrast to @Doorknob's solution, this one only needs things that are installed on every GNU/Linux:
```
for((n=2;;n++)){
[ `factor $n|wc -w` -eq 2 ]&&grep $1<<<$n&&exit
}
```
[Answer]
# [Perl 6](http://perl6.org), 41 bytes
```
->$n {grep({.is-prime&&/$n/},2..*)[$n-1]}
```
### Explanation:
```
-> $n { # has one parameter
grep(
{
.is-prime # check that it is prime
&& # and
/ $n / # that it contains the argument in the "string"
},
2 .. * # for all numbers starting with 2
)[ $n - 1 ] # only take the $n-th one
# ( accounting for 0 based array access )
}
```
### Test:
```
#! /usr/bin/env perl6
use v6.c;
use Test;
my &prefix:<‚Ñôùïü> = ->$n {grep({.is-prime&&/$n/},2..*)[$n-1]}
my @test = (
1 => 11,
2 => 23,
3 => 23,
10 => 1033,
);
plan +@test;
for @test {
is ‚Ñôùïü.key, .value, .gist
}
```
```
1..4
ok 1 - 1 => 11
ok 2 - 2 => 23
ok 3 - 3 => 23
ok 4 - 10 => 1033
```
[Answer]
# Java 8, ~~192~~ ~~183~~ ~~181~~ 171 bytes (full program)
```
interface M{static void main(String[]a){long n=new Long(a[0]),c=0,r=1,m,i;for(;c<n;c+=m>1&(r+"").contains(a[0])?1:0)for(m=++r,i=2;i<m;m=m%i++<1?0:m);System.out.print(r);}}
```
[Try it online.](https://tio.run/##JY7LDsIgFAV/hTTRQMAGXJaiP6Arl00XhD5yqxcMRY0x/XascXcWM5Mz2afdTd01Z/Cpj4N1PTl/5mQTOPIM0BG04OklRfBj01r2uQU/Em98/yKndVLbyJYJZ6SIRgkUoIcQqXa1144bPKgtjbwoWOmCT2tr/htHVUn2I9FwHgWYvYYaNRrcAOe1OsoKmb6859RjGR6pvK8PEo1ML0vOWckv)
**Explanation:**
```
interface M{ // Class
static void main(String[]a){ // Mandatory main-method
long n=new Long(a[0]), // Input argument as number
c=0, // Counter, starting at 0
r=1, // Result-number, starting at 1
m,i; // Temp number
for(;c<n; // Loop as long as `c` does not equals `n`
c+= // After every iteration: increase `c` by:
m>1 // If the current `r` is a prime,
&(r+"").contains(a[0])?
// and this prime contains the input `n`
1 // Increase `c` by 1
: // Else:
0) // Leave `c` the same
for(m=++r, // Increase `r` by 1 first with `++r`, and set `m` to it
i=2;i<m; // Inner loop `i` in the range [2, `m`)
m=m%i++<1? // If `m` is divisible by `i`
0 // Change `m` to 0 (so it's not a prime)
: // Else:
m); // Leave `m` unchanged
System.out.print(r);}} // Print `r` as result
```
---
# Java 8, 105 bytes (lambda function)
```
n->{int c=0,r=1,m,i;for(;c<n;c+=m>1&(r+"").contains(n+"")?1:0)for(m=++r,i=2;i<m;m=m%i++<1?0:m);return r;}
```
[Try it online.](https://tio.run/##hVBNi8IwEL37KwbBJSG1NO7NafQXrBePyx6ysUq0mUqSCov0t3eT6lW8DLwP5r2Zs77p5flwGU2rQ4Avbek@A7AUG3/UpoFdhhMBhuVJHBMzzNIIUUdrYAcECkZabu6TTVWFV7JwhcVj5xmamtAI5Tbyg3kxn/PSdBRTUmCU4VauK56dTgnhC6tWaGuHTrmFFaKW22rtOPom9p7A4zBiDr/2v20Kf3a4dfYALu1k@@gtnb5/QPNH9f1fiI0ruz6W1yTFlhiVhkk@HfJSX73RP9/osuLPTw3jPw)
Same as above, but with `n` as integer input and without the verbose class stuff.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), ~~15~~ ~~13~~ 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
_j ©ZsèU}jU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=X2ogqVpz6FV9alU&input=OA)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
!fo`€d¹dİp
```
[Try it online!](https://tio.run/##yygtzv7/XzEtP@FR05qUQztTjmwo@P//v6EBAA "Husk – Try It Online")
## Explanation
```
!fo`€d¹dİp
fo İp filter the infinite list of primes by the following:
d¬π are the digits of n
`€ a sublist of('`' switches the arguments)
d the digits of the number?
! get nth element
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~14~~ 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
éâ^^εîï5~8<IM
```
[Run and debug it](https://staxlang.xyz/#p=82835e5eee8c8b357e383c494d&i=1%0A2%0A3%0A10&m=2)
A good question for a generator.
-1 byte from recursive.
## Explanation
```
Z{|p_$yI^*}{gnH input: single number, n
n generator mode: count(stops after n values are found)
Z push a 0 under the input(start value)
{ } filter block:
|p number is prime?
* and
_$ string representation of number
yI^ contains n?
{g generator block:
implicit increment to get next number
H get last generated value
```
[Answer]
# [Haskell](https://www.haskell.org/), 97 bytes
```
import Data.List
p n=[z|z<-[2..],all((>0).mod z)[2..z-1],show n`elem`subsequences(show z)]!!(n-1)
```
[Try it online!](https://tio.run/##HclLCsIwEADQvaeY7hJoh8a1deWyniAEOupAg/nZpAjBu0d0@95K@cnOtWZ9iluBCxXC2eZySBAmXT/1NOgjounJOSHOo0QfH1DlD@ugTJ/X@IawsGO/5P2W@bVzuHMW/6jSdJ0Ig5LNkw0wgad0BZE2GwogJAlaIarRtC8 "Haskell – Try It Online")
"subsequences" is an annoyingly long word.
Thanks to @xnor for saving a byte.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
‹Þp'?c;i
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigLnDnnAnP2M7aSIsIiIsIjEwIl0=)
[Answer]
## Clojure, 118 bytes
```
(defn s[n](nth(filter(fn[x](if(.contains(str x)(str n))(not-any? #(=(mod x %)0)(range 2 x))))(drop 2(range)))(dec n)))
```
Just gets the nth element of lazy infinite sequence of numbers which are prime and have `n` in their string representation.
You can try it here : <https://ideone.com/ioBJjt>
[Answer]
## Actually, 16 bytes
```
;$╗`P$╜@íu`╓dP.X
```
[Try it online!](http://actually.tryitonline.net/#code=OyTilZdgUCTilZxAw611YOKVk2RQLlg&input=MTA)
Explanation:
```
;$╗`P$╜@íu`╓dP.X
;$‚ïó make a copy of n, push str(n) to reg0
` `‚ïì push the first n values where f(k) is truthy, starting with k=0:
P$ kth prime, stringified
╜@íu 1-based index of n, 0 if not found
d remove last element of list and push it to the stack (dequeue)
P nth prime
. print
X discard rest of list
```
[Answer]
## PowerShell v2+, ~~108~~ 99 bytes
Ooof. The lack of any sort of built-in prime calculation/checking really hurts here.
```
param($n)for(){for(;'1'*++$i-match'^(?!(..+)\1+$)..'){if("$i"-like"*$n*"){if(++$o-eq$n){$i;exit}}}}
```
Takes input `$n`, enters an infinite `for()` loop. Each iteration, we use a `for` loop wrapped around the [PowerShell regex prime checker](https://codegolf.stackexchange.com/a/57636/42963) (h/t to Martin) to turn it into a prime generator by incrementing `$i` each time through the loop. (For example, running just `for(){for(;'1'*++$i-match'^(?!(..+)\1+$)..'){$i}}` will output `2, 3, 5, 7...` separated by newlines).
Then a simple `-like` check to see if `$n` is somewhere in `$i`, and increment our counter `$o`. If we've reached where `$n` and `$o` are equal, output `$i` and `exit`. Otherwise we continue through the `for` to find the next prime and the process repeats.
[Answer]
# APL(NARS), 39 chars, 78 bytes
```
{s←⍕w←⍵⋄2{(w≤⍵)∧k←∨/s⍷⍕⍺:⍺⋄(1π⍺)∇⍵+k}1}
```
1π is the next prime number...; test:
```
f←{s←⍕w←⍵⋄2{(w≤⍵)∧k←∨/s⍷⍕⍺:⍺⋄(1π⍺)∇⍵+k}1}
f¨1 2 3 10
11 23 23 1033
```
but that already at 20 goes out the stack space...
Instead this below seems ok even if has lenght a little more long (61 chars)
```
‚àár‚Üêf w;i;k;s
r←2⋄s←⍕w⋄i←1
→0×⍳(w≤i)∧k←∨/s⍷⍕r⋄r←1πr⋄i+←k⋄→2
‚àá
f¨1 2 3 10 20 100
11 23 23 1033 4201 100999
```
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 36 bytes
```
L,5*2^RßÞPABDBJVB]dG€Ωezߣ*BZB]A1_$:
```
[Try it online!](https://tio.run/##S0xJKSj4/99Hx1TLKC7o8PzD8wIcnVycvMKcYlPcHzWtObcyterw/EOLtZyinGIdDeNVrP5XWBkbcLlW6HBxquQk5ialJCoY2mUCeSkgwv8/AA "Add++ – Try It Online")
Fairly inefficient. Iterates over each integer \$i\$ such that \$i \le 25x^2\$ and filters out composites and primes that don't contain \$n\$. Finally, we take the \$n\$th value of the remaining integers.
] |
[Question]
[
This is perhaps one of the classical coding challenges that got some resonance in 1986, when columnist Jon Bentley asked Donald Knuth to write a program that would find k most frequent words in a file. [Knuth implemented a fast solution](https://www.cs.tufts.edu/~nr/cs257/archive/don-knuth/pearls-2.pdf) using hash tries in an 8-pages-long program to illustrate his literate programming technique. Douglas McIlroy of Bell Labs criticized Knuth's solution as not even able to process a full text of the Bible, and replied with a one-liner, that is not as quick, but gets the job done:
```
tr -cs A-Za-z '\n' | tr A-Z a-z | sort | uniq -c | sort -rn | sed 10q
```
In 1987, a [follow up article](https://www.cs.upc.edu/~eipec/pdf/p583-van_wyk.pdf) was published with yet another solution, this time by a Princeton professor. But it also couldn't even return result for a single Bible!
## Problem description
Original problem description:
>
> Given a text file and an integer k, you are to print the k
> most common words in the file (and the number of their
> occurrences) in decreasing frequency.
>
>
>
Additional problem clarifications:
* Knuth defined a words as a string of Latin letters: `[A-Za-z]+`
* all other characters are ignored
* uppercase and lowercase letters are considered equivalent (`WoRd` == `word`)
* no limit on file size nor word length
* distances between consecutive words can be arbitrarily large
* fastest program is the one that uses least total CPU time (multithreading probably won't help)
## Sample test cases
**Test 1:** *Ulysses* by James Joyce concatenated 64 times (96 MB file).
* Download [*Ulysses*](http://www.gutenberg.org/files/4300/4300-0.txt) from Project Gutenberg: `wget http://www.gutenberg.org/files/4300/4300-0.txt`
* Concatenate it 64 times: `for i in {1..64}; do cat 4300-0.txt >> ulysses64; done`
* Most frequent word is “the” with 968832 appearances.
**Test 2:** Specially generated random text `giganovel` (around 1 GB).
* Python 3 generator script [here](https://gist.github.com/amakukha/d519f9b09ed593bab9632bf12176c151).
* The text contains 148391 distinct words appearing similarly to natural languages.
* Most frequent words: “e” (11309 appearances) and “ihit” (11290 appearances).
**Generality test:** arbitrarily large words with arbitrarily large gaps.
## Reference implementations
After looking into [Rosetta Code](http://rosettacode.org/wiki/Word_frequency) for this problem and realizing that many implementations are incredibly slow (slower than the shell script!), I tested a few good implementations [here](https://stackoverflow.com/a/56958255/5407270). Below is the performance for `ulysses64` together with time complexity:
```
ulysses64 Time complexity
C++ (prefix trie + heap) 4.145 O((N + k) log k)
Python (Counter) 10.547 O(N + k log Q)
GNU awk + sort 20.606 O(N + Q log Q)
McIlroy (tr + sort + uniq) 43.554 O(N log N)
```
Can you beat that?
## Testing
Performance will be evaluated using 2017 13" MacBook Pro with the standard Unix `time` command ("user" time). If possible, please, use modern compilers (e.g., use the latest Haskell version, not the legacy one).
## Rankings so far
Timings, including the reference programs:
```
k=10 k=100K
ulysses64 giganovel giganovel
Rust (trie-32) by Tethys Svensson 0.524 3.576 3.593
Rust (trie-32) by test9753 0.622 4.139 4.157
C++ (trie-32) by ShreevatsaR 0.671 4.227 4.276
C (trie + bins) by Moogie 0.704 9.568 9.459
C (trie + list) by Moogie 0.767 6.051 82.306
C++ (hash trie) by ShreevatsaR 0.788 5.283 5.390
C (trie + sorted list) by Moogie 0.804 7.076 x
Rust (trie) by Anders Kaseorg 0.842 6.932 7.503
J by miles 1.273 22.365 22.637
mawk-2 + sort 2.763 28.488 29.329
OCaml by test9753 3.615 47.432 262.714
C# (trie) by recursive 3.722 25.378 24.771
C++ (trie + heap) 4.145 42.631 72.138
APL (Dyalog Unicode) by Adám 7.680 x x
Scala (mutable.Map) by lprakashv 9.269 56.019 54.946
Python (dict) by movatica 9.387 99.118 100.859
Python (Counter) 10.547 102.822 103.930
Ruby (tally) by daniero 15.139 171.095 171.551
gawk + sort 20.529 213.366 222.782
McIlroy (tr + sort + uniq) 43.554 715.602 750.420
```
Cumulative ranking\* (%, best possible score – 300):
```
# Program Score Generality
1 Rust (trie-32) by Tethys Svensson 300 Yes
2 Rust (trie-32) by test9753 350 Yes
3 C++ (trie-32) by ShreevatsaR 365 Yes
4 C++ (hash trie) by ShreevatsaR 448 x
5 Rust (trie) by Anders Kaseorg 563 Yes
6 C (trie + bins) by Moogie 665 x
7 J by miles 1498 Yes
8 C# (trie) by recursive 2109 x
9 mawk-2 + sort 2140 Yes
10 C (trie + list) by Moogie 2606 x
11 C++ (trie + heap) 3991 x
12 Scala (mutable.Map) by lprakashv 4865 Yes
13 Python (dict) by movatica 7370 Yes
14 Python (Counter) 7781 Yes
15 OCaml by test9753 9328 Yes
16 Ruby (tally) by daniero 12448 Yes
17 gawk + sort 16085 Yes
18 McIlroy (tr + sort + uniq) 49209 Yes
```
\*Sum of time performance relative to the best programs in each of the three tests.
Best program so far: [**here**](https://codegolf.stackexchange.com/a/200206/87954)
[Answer]
# C++ (a la Knuth)
I was curious how Knuth's program would fare, so I translated his (originally Pascal) program into C++.
Even though Knuth's primary goal was not speed but to illustrate his WEB system of literate programming, the program is surprisingly competitive, and leads to a faster solution than any of the answers here so far. Here's my translation of his program (the corresponding "section" numbers of the WEB program are mentioned in comments like "`{§24}`"):
```
#include <iostream>
#include <cassert>
// Adjust these parameters based on input size.
const int TRIE_SIZE = 800 * 1000; // Size of the hash table used for the trie.
const int ALPHA = 494441; // An integer that's approximately (0.61803 * TRIE_SIZE), and relatively prime to T = TRIE_SIZE - 52.
const int kTolerance = TRIE_SIZE / 100; // How many places to try, to find a new place for a "family" (=bunch of children).
typedef int32_t Pointer; // [0..TRIE_SIZE), an index into the array of Nodes
typedef int8_t Char; // We only care about 1..26 (plus two values), but there's no "int5_t".
typedef int32_t Count; // The number of times a word has been encountered.
// These are 4 separate arrays in Knuth's implementation.
struct Node {
Pointer link; // From a parent node to its children's "header", or from a header back to parent.
Pointer sibling; // Previous sibling, cyclically. (From smallest child to header, and header to largest child.)
Count count; // The number of times this word has been encountered.
Char ch; // EMPTY, or 1..26, or HEADER. (For nodes with ch=EMPTY, the link/sibling/count fields mean nothing.)
} node[TRIE_SIZE + 1];
// Special values for `ch`: EMPTY (free, can insert child there) and HEADER (start of family).
const Char EMPTY = 0, HEADER = 27;
const Pointer T = TRIE_SIZE - 52;
Pointer x; // The `n`th time we need a node, we'll start trying at x_n = (alpha * n) mod T. This holds current `x_n`.
// A header can only be in T (=TRIE_SIZE-52) positions namely [27..TRIE_SIZE-26].
// This transforms a "h" from range [0..T) to the above range namely [27..T+27).
Pointer rerange(Pointer n) {
n = (n % T) + 27;
// assert(27 <= n && n <= TRIE_SIZE - 26);
return n;
}
// Convert trie node to string, by walking up the trie.
std::string word_for(Pointer p) {
std::string word;
while (p != 0) {
Char c = node[p].ch; // assert(1 <= c && c <= 26);
word = static_cast<char>('a' - 1 + c) + word;
// assert(node[p - c].ch == HEADER);
p = (p - c) ? node[p - c].link : 0;
}
return word;
}
// Increment `x`, and declare `h` (the first position to try) and `last_h` (the last position to try). {§24}
#define PREPARE_X_H_LAST_H x = (x + ALPHA) % T; Pointer h = rerange(x); Pointer last_h = rerange(x + kTolerance);
// Increment `h`, being careful to account for `last_h` and wraparound. {§25}
#define INCR_H { if (h == last_h) { std::cerr << "Hit tolerance limit unfortunately" << std::endl; exit(1); } h = (h == TRIE_SIZE - 26) ? 27 : h + 1; }
// `p` has no children. Create `p`s family of children, with only child `c`. {§27}
Pointer create_child(Pointer p, int8_t c) {
// Find `h` such that there's room for both header and child c.
PREPARE_X_H_LAST_H;
while (!(node[h].ch == EMPTY and node[h + c].ch == EMPTY)) INCR_H;
// Now create the family, with header at h and child at h + c.
node[h] = {.link = p, .sibling = h + c, .count = 0, .ch = HEADER};
node[h + c] = {.link = 0, .sibling = h, .count = 0, .ch = c};
node[p].link = h;
return h + c;
}
// Move `p`'s family of children to a place where child `c` will also fit. {§29}
void move_family_for(const Pointer p, Char c) {
// Part 1: Find such a place: need room for `c` and also all existing children. {§31}
PREPARE_X_H_LAST_H;
while (true) {
INCR_H;
if (node[h + c].ch != EMPTY) continue;
Pointer r = node[p].link;
int delta = h - r; // We'd like to move each child by `delta`
while (node[r + delta].ch == EMPTY and node[r].sibling != node[p].link) {
r = node[r].sibling;
}
if (node[r + delta].ch == EMPTY) break; // There's now space for everyone.
}
// Part 2: Now actually move the whole family to start at the new `h`.
Pointer r = node[p].link;
int delta = h - r;
do {
Pointer sibling = node[r].sibling;
// Move node from current position (r) to new position (r + delta), and free up old position (r).
node[r + delta] = {.ch = node[r].ch, .count = node[r].count, .link = node[r].link, .sibling = node[r].sibling + delta};
if (node[r].link != 0) node[node[r].link].link = r + delta;
node[r].ch = EMPTY;
r = sibling;
} while (node[r].ch != EMPTY);
}
// Advance `p` to its `c`th child. If necessary, add the child, or even move `p`'s family. {§21}
Pointer find_child(Pointer p, Char c) {
// assert(1 <= c && c <= 26);
if (p == 0) return c; // Special case for first char.
if (node[p].link == 0) return create_child(p, c); // If `p` currently has *no* children.
Pointer q = node[p].link + c;
if (node[q].ch == c) return q; // Easiest case: `p` already has a `c`th child.
// Make sure we have room to insert a `c`th child for `p`, by moving its family if necessary.
if (node[q].ch != EMPTY) {
move_family_for(p, c);
q = node[p].link + c;
}
// Insert child `c` into `p`'s family of children (at `q`), with correct siblings. {§28}
Pointer h = node[p].link;
while (node[h].sibling > q) h = node[h].sibling;
node[q] = {.ch = c, .count = 0, .link = 0, .sibling = node[h].sibling};
node[h].sibling = q;
return q;
}
// Largest descendant. {§18}
Pointer last_suffix(Pointer p) {
while (node[p].link != 0) p = node[node[p].link].sibling;
return p;
}
// The largest count beyond which we'll put all words in the same (last) bucket.
// We do an insertion sort (potentially slow) in last bucket, so increase this if the program takes a long time to walk trie.
const int MAX_BUCKET = 10000;
Pointer sorted[MAX_BUCKET + 1]; // The head of each list.
// Records the count `n` of `p`, by inserting `p` in the list that starts at `sorted[n]`.
// Overwrites the value of node[p].sibling (uses the field to mean its successor in the `sorted` list).
void record_count(Pointer p) {
// assert(node[p].ch != HEADER);
// assert(node[p].ch != EMPTY);
Count f = node[p].count;
if (f == 0) return;
if (f < MAX_BUCKET) {
// Insert at head of list.
node[p].sibling = sorted[f];
sorted[f] = p;
} else {
Pointer r = sorted[MAX_BUCKET];
if (node[p].count >= node[r].count) {
// Insert at head of list
node[p].sibling = r;
sorted[MAX_BUCKET] = p;
} else {
// Find right place by count. This step can be SLOW if there are too many words with count >= MAX_BUCKET
while (node[p].count < node[node[r].sibling].count) r = node[r].sibling;
node[p].sibling = node[r].sibling;
node[r].sibling = p;
}
}
}
// Walk the trie, going over all words in reverse-alphabetical order. {§37}
// Calls "record_count" for each word found.
void walk_trie() {
// assert(node[0].ch == HEADER);
Pointer p = node[0].sibling;
while (p != 0) {
Pointer q = node[p].sibling; // Saving this, as `record_count(p)` will overwrite it.
record_count(p);
// Move down to last descendant of `q` if any, else up to parent of `q`.
p = (node[q].ch == HEADER) ? node[q].link : last_suffix(q);
}
}
int main(int, char** argv) {
// Program startup
std::ios::sync_with_stdio(false);
// Set initial values {§19}
for (Char i = 1; i <= 26; ++i) node[i] = {.ch = i, .count = 0, .link = 0, .sibling = i - 1};
node[0] = {.ch = HEADER, .count = 0, .link = 0, .sibling = 26};
// read in file contents
FILE *fptr = fopen(argv[1], "rb");
fseek(fptr, 0L, SEEK_END);
long dataLength = ftell(fptr);
rewind(fptr);
char* data = (char*)malloc(dataLength);
fread(data, 1, dataLength, fptr);
if (fptr) fclose(fptr);
// Loop over file contents: the bulk of the time is spent here.
Pointer p = 0;
for (int i = 0; i < dataLength; ++i) {
Char c = (data[i] | 32) - 'a' + 1; // 1 to 26, for 'a' to 'z' or 'A' to 'Z'
if (1 <= c && c <= 26) {
p = find_child(p, c);
} else {
++node[p].count;
p = 0;
}
}
node[0].count = 0;
walk_trie();
const int max_words_to_print = atoi(argv[2]);
int num_printed = 0;
for (Count f = MAX_BUCKET; f >= 0 && num_printed <= max_words_to_print; --f) {
for (Pointer p = sorted[f]; p != 0 && num_printed < max_words_to_print; p = node[p].sibling) {
std::cout << word_for(p) << " " << node[p].count << std::endl;
++num_printed;
}
}
return 0;
}
```
Differences from Knuth's program:
* I combined Knuth's 4 arrays `link`, `sibling`, `count` and `ch` into an array of a `struct Node` (find it easier to understand this way).
* I changed the literate-programming (WEB-style) textual transclusion of sections into more conventional function calls (and a couple of macros).
* We don't need to use standard Pascal's weird I/O conventions/restrictions, so using `fread` and `data[i] | 32 - 'a'` as in the other answers here, instead of the Pascal workaround.
* In case we exceed limits (run out of space) while the program is running, Knuth's original program deals with it gracefully by dropping later words, and printing a message at the end. (It's not quite right to say that McIlroy "criticized Knuth's solution as not even able to process a full text of the Bible"; he was only pointing out that sometimes frequent words may occur very late in a text, such as the word "Jesus" in the Bible, so the error condition is not innocuous.) I've taken the noisier (and anyway easier) approach of simply terminating the program.
* The program declares a constant TRIE\_SIZE to control the memory usage, which I bumped up. (The constant of 32767 had been chosen for the original requirements -- "a user should be able to find the 100 most frequent words in a twenty-page technical paper (roughly a 50K byte file)" and because Pascal deals well with ranged integer types and packs them optimally. We had to increase it 25x to 800,000 as test input is now 20 million times larger.)
* For the final printing of strings, we can just walk the trie and do a dumb (possibly even quadratic) string append.
Apart from that, this is pretty much exactly Knuth's program (using his hash trie / packed trie data structure and bucket sort), and does pretty much the same operations (as Knuth's Pascal program would) while looping through all characters in the input; note that it uses no external algorithm or data structure libraries, and also that words of equal frequency will be printed in alphabetical order.
## Timing
Compiled with
```
clang++ -std=c++17 -O2 ptrie-walktrie.cc
```
When run on the largest testcase here (`giganovel` with 100,000 words requested), and compared against the fastest program posted here so far, I find it slightly but consistently faster:
```
target/release/frequent: 4.809 ± 0.263 [ 4.45.. 5.62] [... 4.63 ... 4.75 ... 4.88...]
ptrie-walktrie: 4.547 ± 0.164 [ 4.35.. 4.99] [... 4.42 ... 4.5 ... 4.68...]
```
(The top line is Anders Kaseorg's Rust solution; the bottom is the above program. These are timings from 100 runs, with mean, min, max, median, and quartiles.)
## Analysis
Why is this faster? It is not that C++ is faster than Rust, or that Knuth's program is the fastest possible -- in fact, Knuth's program is slower on insertions (as he mentions) because of the trie-packing (to conserve memory). The reason, I suspect, is related to something that Knuth [complained about in 2008](https://cs.stanford.edu/%7Eknuth/news08.html):
>
> A Flame About 64-bit Pointers
>
>
> It is absolutely idiotic to have 64-bit pointers when I compile a program that uses less than 4 gigabytes of RAM. When such pointer values appear inside a struct, they not only waste half the memory, they effectively throw away half of the cache.
>
>
>
The program above uses 32-bit array indices (not 64-bit pointers), so the "Node" struct occupies less memory, so there are more Nodes on the stack and fewer cache misses. (In fact, there was [some work](http://blog.reverberate.org/2011/09/making-knuth-wish-come-true-x32-abi.html) on this as the [x32 ABI](https://en.wikipedia.org/w/index.php?title=X32_ABI&oldid=921754052), but it seems to be [not in a good state](https://www.phoronix.com/scan.php?page=news_item&px=Linux-Potentially-Drops-x32) even though the idea is obviously useful, e.g. see the [recent announcement](https://v8.dev/blog/v8-release-80) of [pointer compression in V8](https://bugs.chromium.org/p/v8/issues/detail?id=7703). Oh well.) So on `giganovel`, this program uses 12.8 MB for the (packed) trie, versus the Rust program's 32.18MB for its trie (on `giganovel`). We could scale up 1000x (from "giganovel" to "teranovel" say) and still not exceed 32-bit indices, so this seems a reasonable choice.
# Faster variant
We can optimize for speed and forego the packing, so we can actually use the (non-packed) trie as in the Rust solution, with indices instead of pointers. This gives something that's faster *and* has no pre-fixed limits on number of distinct words, characters etc:
```
#include <iostream>
#include <cassert>
#include <vector>
#include <algorithm>
typedef int32_t Pointer; // [0..node.size()), an index into the array of Nodes
typedef int32_t Count;
typedef int8_t Char; // We'll usually just have 1 to 26.
struct Node {
Pointer link; // From a parent node to its children's "header", or from a header back to parent.
Count count; // The number of times this word has been encountered. Undefined for header nodes.
};
std::vector<Node> node; // Our "arena" for Node allocation.
std::string word_for(Pointer p) {
std::vector<char> drow; // The word backwards
while (p != 0) {
Char c = p % 27;
drow.push_back('a' - 1 + c);
p = (p - c) ? node[p - c].link : 0;
}
return std::string(drow.rbegin(), drow.rend());
}
// `p` has no children. Create `p`s family of children, with only child `c`.
Pointer create_child(Pointer p, Char c) {
Pointer h = node.size();
node.resize(node.size() + 27);
node[h] = {.link = p, .count = -1};
node[p].link = h;
return h + c;
}
// Advance `p` to its `c`th child. If necessary, add the child.
Pointer find_child(Pointer p, Char c) {
assert(1 <= c && c <= 26);
if (p == 0) return c; // Special case for first char.
if (node[p].link == 0) return create_child(p, c); // Case 1: `p` currently has *no* children.
return node[p].link + c; // Case 2 (easiest case): Already have the child c.
}
int main(int, char** argv) {
auto start_c = std::clock();
// Program startup
std::ios::sync_with_stdio(false);
// read in file contents
FILE *fptr = fopen(argv[1], "rb");
fseek(fptr, 0, SEEK_END);
long dataLength = ftell(fptr);
rewind(fptr);
char* data = (char*)malloc(dataLength);
fread(data, 1, dataLength, fptr);
fclose(fptr);
node.reserve(dataLength / 600); // Heuristic based on test data. OK to be wrong.
node.push_back({0, 0});
for (Char i = 1; i <= 26; ++i) node.push_back({0, 0});
// Loop over file contents: the bulk of the time is spent here.
Pointer p = 0;
for (long i = 0; i < dataLength; ++i) {
Char c = (data[i] | 32) - 'a' + 1; // 1 to 26, for 'a' to 'z' or 'A' to 'Z'
if (1 <= c && c <= 26) {
p = find_child(p, c);
} else {
++node[p].count;
p = 0;
}
}
++node[p].count;
node[0].count = 0;
// Brute-force: Accumulate all words and their counts, then sort by frequency and print.
std::vector<std::pair<int, std::string>> counts_words;
for (Pointer i = 1; i < static_cast<Pointer>(node.size()); ++i) {
int count = node[i].count;
if (count == 0 || i % 27 == 0) continue;
counts_words.push_back({count, word_for(i)});
}
auto cmp = [](auto x, auto y) {
if (x.first != y.first) return x.first > y.first;
return x.second < y.second;
};
std::sort(counts_words.begin(), counts_words.end(), cmp);
const int max_words_to_print = std::min<int>(counts_words.size(), atoi(argv[2]));
for (int i = 0; i < max_words_to_print; ++i) {
auto [count, word] = counts_words[i];
std::cout << word << " " << count << std::endl;
}
return 0;
}
```
This program, despite doing something a lot dumber for sorting than the solutions here, uses (for `giganovel`) only 12.2MB for its trie, and manages to be faster. Timings of this program (last line), compared with the earlier timings mentioned:
```
target/release/frequent: 4.809 ± 0.263 [ 4.45.. 5.62] [... 4.63 ... 4.75 ... 4.88...]
ptrie-walktrie: 4.547 ± 0.164 [ 4.35.. 4.99] [... 4.42 ... 4.5 ... 4.68...]
itrie-nolimit: 3.907 ± 0.127 [ 3.69.. 4.23] [... 3.81 ... 3.9 ... 4.0...]
```
I'd be eager to see what this (or the hash-trie program) would like if [translated into Rust](http://cliffle.com/p/dangerust/). :-)
## Further details
1. About the data structure used here: an explanation of "packing" tries is given tersely in Exercise 4 of Section 6.3 (Digital Searching, i.e. tries) in Volume 3 of TAOCP, and also in the thesis of Knuth's student Frank Liang about hyphenation in TeX: [Word Hy-phen-a-tion by Com-put-er](https://www.tug.org/docs/liang/).
2. The context of Bentley's columns, Knuth's program, and McIlroy's review (only a small part of which was about the Unix philosophy) is clearer in light of [previous and later columns](https://shreevatsa.net/post/programming-pearls/), and Knuth's previous experience including compilers, TAOCP, and TeX.
3. [There's an entire book](https://henrikwarne.com/2018/03/13/exercises-in-programming-style/) *Exercises in Programming Style*, showing different approaches to this particular program, etc.
I have an unfinished blog post elaborating on the points above; might edit this answer when it's done. Meanwhile, posting this answer here anyway, on the occasion (Jan 10) of Knuth's birthday. :-)
[Answer]
## [Rust] Optimized version of test9753's code
I changed a few details (e.g. pre-processing the data and splitting up the parent links from child links) while also making the code a bit more idiomatic.
On my machine this runs the giganovel about 20% faster.
```
use std::env;
use std::io::{Error, ErrorKind};
type Pointer = i32;
type Count = i32;
type Char = u8;
#[derive(Copy, Clone)]
struct Node {
link: Pointer,
count: Count,
}
fn word_for(parents: &[Pointer], mut p: Pointer) -> String {
let mut drow = Vec::with_capacity(25); // sane max length
while p != -1 {
let c = p % 26;
p = parents[(p / 26) as usize];
drow.push(b'a' + (c as Char));
}
drow.reverse();
String::from_utf8(drow).unwrap()
}
fn create_child(
parents: &mut Vec<Pointer>,
children: &mut Vec<Node>,
p: Pointer,
c: Char,
) -> Pointer {
let h = children.len();
children[p as usize].link = h as Pointer;
children.resize(children.len() + 26, Node { link: -1, count: 0 });
parents.push(p);
(h as u32 + c as u32) as Pointer
}
fn find_child(
parents: &mut Vec<Pointer>,
children: &mut Vec<Node>,
p: Pointer,
c: Char,
) -> Pointer {
let elem = children[p as usize];
if elem.link == -1 {
create_child(parents, children, p, c)
} else {
(elem.link as u32 + c as u32) as Pointer
}
}
fn error(msg: &str) -> Error {
Error::new(ErrorKind::Other, msg)
}
fn main() -> std::io::Result<()> {
let args = env::args().collect::<Vec<String>>();
if args.len() != 3 {
return Err(error(&format!(
"Usage: {} file-path limit-num",
env::args().next().unwrap()
)));
}
let mut data: Vec<u8> = std::fs::read(&args[1])?;
for d in &mut data {
*d = (*d | 32) - b'a';
}
let mut children: Vec<Node> = Vec::with_capacity(data.len() / 600);
let mut parents: Vec<Pointer> = Vec::with_capacity(data.len() / 600 / 26);
parents.push(-1);
for _ in 0..26 {
children.push(Node { link: -1, count: 0 });
}
let mut data = data.iter();
while let Some(&c) = data.next() {
if c < 26 {
let mut p = c as Pointer;
while let Some(&c) = data.next() {
if c < 26 {
p = find_child(&mut parents, &mut children, p, c);
} else {
break;
}
}
children[p as usize].count += 1;
}
}
let mut counts_words: Vec<(i32, String)> = Vec::new();
for (i, e) in children.iter().enumerate() {
if e.count != 0 {
counts_words.push((-e.count, word_for(&parents, i as Pointer)));
}
}
counts_words.sort();
let limit = args[2]
.parse()
.map_err(|_| error("ARGV[2] must be in range: [1, usize_max]"))?;
for (count, word) in counts_words.iter().take(limit) {
println!("{word} {count}", word = word, count = -count);
}
Ok(())
}
```
[Answer]
# Rust
On my computer, this runs giganovel 100000 about 42% faster (10.64 s vs. 18.24 s) than Moogie’s C “prefix tree + bins” C solution. Also it has no predefined limits (unlike the C solution which predefines limits on word length, unique words, repeated words, etc.).
### `src/main.rs`
```
use memmap::MmapOptions;
use pdqselect::select_by_key;
use std::cmp::Reverse;
use std::default::Default;
use std::env::args;
use std::fs::File;
use std::io::{self, Write};
use typed_arena::Arena;
#[derive(Default)]
struct Trie<'a> {
nodes: [Option<&'a mut Trie<'a>>; 26],
count: u64,
}
fn main() -> io::Result<()> {
// Parse arguments
let mut args = args();
args.next().unwrap();
let filename = args.next().unwrap();
let size = args.next().unwrap().parse().unwrap();
// Open input
let file = File::open(filename)?;
let mmap = unsafe { MmapOptions::new().map(&file)? };
// Build trie
let arena = Arena::new();
let mut num_words = 0;
let mut root = Trie::default();
{
let mut node = &mut root;
for byte in &mmap[..] {
let letter = (byte | 32).wrapping_sub(b'a');
if let Some(child) = node.nodes.get_mut(letter as usize) {
node = child.get_or_insert_with(|| {
num_words += 1;
arena.alloc(Default::default())
});
} else {
node.count += 1;
node = &mut root;
}
}
node.count += 1;
}
// Extract all counts
let mut index = 0;
let mut counts = Vec::with_capacity(num_words);
let mut stack = vec![root.nodes.iter()];
'a: while let Some(frame) = stack.last_mut() {
while let Some(child) = frame.next() {
if let Some(child) = child {
if child.count != 0 {
counts.push((child.count, index));
index += 1;
}
stack.push(child.nodes.iter());
continue 'a;
}
}
stack.pop();
}
// Find frequent counts
select_by_key(&mut counts, size, |&(count, _)| Reverse(count));
// Or, in nightly Rust:
//counts.partition_at_index_by_key(size, |&(count, _)| Reverse(count));
// Extract frequent words
let size = size.min(counts.len());
counts[0..size].sort_by_key(|&(_, index)| index);
let mut out = Vec::with_capacity(size);
let mut it = counts[0..size].iter();
if let Some(mut next) = it.next() {
index = 0;
stack.push(root.nodes.iter());
let mut word = vec![b'a' - 1];
'b: while let Some(frame) = stack.last_mut() {
while let Some(child) = frame.next() {
*word.last_mut().unwrap() += 1;
if let Some(child) = child {
if child.count != 0 {
if index == next.1 {
out.push((word.to_vec(), next.0));
if let Some(next1) = it.next() {
next = next1;
} else {
break 'b;
}
}
index += 1;
}
stack.push(child.nodes.iter());
word.push(b'a' - 1);
continue 'b;
}
}
stack.pop();
word.pop();
}
}
out.sort_by_key(|&(_, count)| Reverse(count));
// Print results
let stdout = io::stdout();
let mut stdout = io::BufWriter::new(stdout.lock());
for (word, count) in out {
stdout.write_all(&word)?;
writeln!(stdout, " {}", count)?;
}
Ok(())
}
```
### `Cargo.toml`
```
[package]
name = "frequent"
version = "0.1.0"
authors = ["Anders Kaseorg <[[email protected]](/cdn-cgi/l/email-protection)>"]
edition = "2018"
[dependencies]
memmap = "0.7.0"
typed-arena = "1.4.1"
pdqselect = "0.1.0"
[profile.release]
lto = true
opt-level = 3
```
### Usage
```
cargo build --release
time target/release/frequent ulysses64 10
```
[Answer]
**Rust translation of ShreevatsaR's "Faster variant"**
**Uses:**
```
$ cargo --version
cargo 1.41.0 (626f0f40e 2019-12-03)
$ rustc --version
rustc 1.41.0 (5e1a79984 2020-01-27)
```
**src/main.rs:**
```
use std::env;
use std::fs::File;
use std::io::{Error, ErrorKind, Read};
use std::string::String;
use std::vec::Vec;
type Pointer = u32;
type Count = i32;
type Char = u8;
#[repr(packed(8))]
#[derive(Copy, Clone)]
struct Node {
link: Pointer,
count: Count,
}
const MAX_STRING_LEN: usize = 25;
const ORD_A: Char = 97; // 'a'
fn word_for(nodes: &[Node], p: Pointer) -> String {
let mut p = p;
let mut drow = String::with_capacity(MAX_STRING_LEN);
while p != 0 {
let c = p % 27;
drow.push(char::from(ORD_A - 1 + (c as Char)));
let index = (p - c) as usize;
if index != 0 {
if let Some(elem) = nodes.get(index) {
p = elem.link;
} else {
unreachable!();
}
} else {
p = 0;
}
}
drow.chars().rev().collect()
}
fn create_child(nodes: &mut Vec<Node>, p: Pointer, c: Char) -> Pointer {
let h = nodes.len();
nodes.resize(nodes.len() + 27, Node { link: 0, count: 0 });
if let Some(elem) = nodes.get_mut(h) {
*elem = Node { link: p, count: -1 };
} else {
unreachable!();
}
if let Some(el) = nodes.get_mut(p as usize) {
el.link = h as Pointer;
}
(h as u32 + c as u32) as Pointer
}
fn find_child(nodes: &mut Vec<Node>, p: Pointer, c: Char) -> Pointer {
assert!(1 <= c && c <= 26);
if p == 0 {
return c as Pointer;
}
if let Some(elem) = nodes.get(p as usize) {
if elem.link == 0 {
create_child(nodes, p, c)
} else {
(elem.link as u32 + c as u32) as Pointer
}
} else {
unreachable!();
}
}
fn error(msg: &str) -> Error {
Error::new(ErrorKind::Other, msg)
}
fn main() -> std::io::Result<()> {
if env::args().count() != 3 {
return Err(error(&format!("Usage: {} file-path limit-num",
env::args().next().unwrap())));
}
let fname = env::args().nth(1).ok_or_else(|| error("Invalid ARGV[1]"))?;
let mut file = File::open(fname)?;
let file_size = file.metadata()?.len() as usize;
let mut data: Vec<u8> = Vec::with_capacity(file_size);
file.read_to_end(&mut data)?;
let mut nodes: Vec<Node> = Vec::with_capacity(file_size / 600);
for _ in 1..=27 {
nodes.push(Node { link: 0, count: 0 });
}
{
let mut p: Pointer = 0;
for i in 0..file_size {
if let Some(elem) = data.get(i) {
let c: Char = (*elem | 32) - ORD_A + 1;
if 1 <= c && c <= 26 {
p = find_child(&mut nodes, p, c);
} else if let Some(el) = nodes.get_mut(p as usize) {
el.count += 1;
p = 0;
} else {
unreachable!();
}
} else {
unreachable!();
}
}
if let Some(e) = nodes.get_mut(p as usize) {
e.count += 1;
} else {
unreachable!();
}
if let Some(e) = nodes.get_mut(0) {
e.count = 0;
} else {
unreachable!();
}
}
struct Pair {
count: i32,
word: String,
}
let mut counts_words: Vec<Pair> = Vec::new();
for i in 1..nodes.len() {
if let Some(e) = nodes.get(i) {
let count = e.count;
if !((count == 0) || (i % 27 == 0)) {
counts_words.push(Pair {
count,
word: word_for(&nodes, i as Pointer),
});
}
} else {
unreachable!();
}
}
let cmp = |x: &Pair, y: &Pair| -> std::cmp::Ordering {
if x.count != y.count {
return y.count.cmp(&x.count);
}
x.word.cmp(&y.word)
};
counts_words.sort_by(cmp);
let argv_2 = env::args().nth(2).ok_or_else(|| error("Invalid ARGV[2]"))?;
let limit = usize::from_str_radix(&argv_2, 10)
.map_err(|_| error("ARGV[2] must be in range: [1, usize_max]"))?;
let max_words_to_print = std::cmp::min(counts_words.len(), limit);
for cw in counts_words.iter().take(max_words_to_print) {
println!("{word} {count}", word = cw.word, count = cw.count);
}
Ok(())
}
```
**Building:**
```
$ cargo build --release
```
**Testing:**
```
$ time ./target/release/bentley golf/ulysses64 10
the 968832
of 528960
and 466432
a 421184
to 322624
in 320512
he 270528
his 213120
i 191808
s 182144
real 0m1.408s
user 0m1.240s
sys 0m0.157s
```
**C++ "Faster variant" testing**
```
$ time golf/faster-variant golf/ulysses64 10
the 968832
of 528960
and 466432
a 421184
to 322624
in 320512
he 270528
his 213120
i 191808
s 182144
real 0m1.533s
user 0m1.411s
sys 0m0.109s
```
[Answer]
# [C]
The following runs in under 1.6 seconds for **Test 1** on my 2.8 Ghz Xeon W3530. Built using MinGW.org GCC-6.3.0-1 on Windows 7:
It takes two arguments as input (path to text file and for k number of most frequent words to list)
It simply creates a tree branching on letters of words, then at the leaf letters it increments a counter. Then checks to see if the current leaf counter is greater than the smallest most frequent word in the list of most frequent words. (list size is the number determined via the command line argument) If so then promote the word represented by the leaf letter to be one of the most frequent. This all repeats until no more letters are read in. After which the list of most frequent words are output via an inefficent iterative search for the most frequent word from the list of most frequent words.
It currently defaults to output the processing time, but for purposes of conistency with other submissions, disable the TIMING definition in the source code.
Also, I have submitted this from a work computer and have not been able to download Test 2 text. It should work with this Test 2 without modification, however the MAX\_LETTER\_INSTANCES value may need to be increased.
```
// comment out TIMING if using external program timing mechanism
#define TIMING 1
// may need to increase if the source text has many unique words
#define MAX_LETTER_INSTANCES 1000000
// increase this if needing to output more top frequent words
#define MAX_TOP_FREQUENT_WORDS 1000
#define false 0
#define true 1
#define null 0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef TIMING
#include <sys/time.h>
#endif
struct Letter
{
char mostFrequentWord;
struct Letter* parent;
char asciiCode;
unsigned int count;
struct Letter* nextLetters[26];
};
typedef struct Letter Letter;
int main(int argc, char *argv[])
{
#ifdef TIMING
struct timeval tv1, tv2;
gettimeofday(&tv1, null);
#endif
int k;
if (argc !=3 || (k = atoi(argv[2])) <= 0 || k> MAX_TOP_FREQUENT_WORDS)
{
printf("Usage:\n");
printf(" WordCount <input file path> <number of most frequent words to find>\n");
printf("NOTE: upto %d most frequent words can be requested\n\n",MAX_TOP_FREQUENT_WORDS);
return -1;
}
long file_size;
long dataLength;
char* data;
// read in file contents
FILE *fptr;
size_t read_s = 0;
fptr = fopen(argv[1], "rb");
fseek(fptr, 0L, SEEK_END);
dataLength = ftell(fptr);
rewind(fptr);
data = (char*)malloc((dataLength));
read_s = fread(data, 1, dataLength, fptr);
if (fptr) fclose(fptr);
unsigned int chr;
unsigned int i;
// working memory of letters
Letter* letters = (Letter*) malloc(sizeof(Letter) * MAX_LETTER_INSTANCES);
memset(&letters[0], 0, sizeof( Letter) * MAX_LETTER_INSTANCES);
// the index of the next unused letter
unsigned int letterMasterIndex=0;
// pesudo letter representing the starting point of any word
Letter* root = &letters[letterMasterIndex++];
// the current letter in the word being processed
Letter* currentLetter = root;
root->mostFrequentWord = false;
root->count = 0;
// the next letter to be processed
Letter* nextLetter = null;
// store of the top most frequent words
Letter* topWords[MAX_TOP_FREQUENT_WORDS];
// initialise the top most frequent words
for (i = 0; i<k; i++)
{
topWords[i]=root;
}
unsigned int lowestWordCount = 0;
unsigned int lowestWordIndex = 0;
unsigned int highestWordCount = 0;
unsigned int highestWordIndex = 0;
// main loop
for (int j=0;j<dataLength;j++)
{
chr = data[j]|0x20; // convert to lower case
// is a letter?
if (chr > 96 && chr < 123)
{
chr-=97; // translate to be zero indexed
nextLetter = currentLetter->nextLetters[chr];
// this is a new letter at this word length, intialise the new letter
if (nextLetter == null)
{
nextLetter = &letters[letterMasterIndex++];
nextLetter->parent = currentLetter;
nextLetter->asciiCode = chr;
currentLetter->nextLetters[chr] = nextLetter;
}
currentLetter = nextLetter;
}
// not a letter so this means the current letter is the last letter of a word (if any letters)
else if (currentLetter!=root)
{
// increment the count of the full word that this letter represents
++currentLetter->count;
// ignore this word if already identified as a most frequent word
if (!currentLetter->mostFrequentWord)
{
// update the list of most frequent words
// by replacing the most infrequent top word if this word is more frequent
if (currentLetter->count> lowestWordCount)
{
currentLetter->mostFrequentWord = true;
topWords[lowestWordIndex]->mostFrequentWord = false;
topWords[lowestWordIndex] = currentLetter;
lowestWordCount = currentLetter->count;
// update the index and count of the next most infrequent top word
for (i=0;i<k; i++)
{
// if the topword is root then it can immediately be replaced by this current word, otherwise test
// whether the top word is less than the lowest word count
if (topWords[i]==root || topWords[i]->count<lowestWordCount)
{
lowestWordCount = topWords[i]->count;
lowestWordIndex = i;
}
}
}
}
// reset the letter path representing the word
currentLetter = root;
}
}
// print out the top frequent words and counts
char string[256];
char tmp[256];
while (k > 0 )
{
highestWordCount = 0;
string[0]=0;
tmp[0]=0;
// find next most frequent word
for (i=0;i<k; i++)
{
if (topWords[i]->count>highestWordCount)
{
highestWordCount = topWords[i]->count;
highestWordIndex = i;
}
}
Letter* letter = topWords[highestWordIndex];
// swap the end top word with the found word and decrement the number of top words
topWords[highestWordIndex] = topWords[--k];
if (highestWordCount > 0)
{
// construct string of letters to form the word
while (letter != root)
{
memmove(&tmp[1],&string[0],255);
tmp[0]=letter->asciiCode+97;
memmove(&string[0],&tmp[0],255);
letter=letter->parent;
}
printf("%u %s\n",highestWordCount,string);
}
}
free( data );
free( letters );
#ifdef TIMING
gettimeofday(&tv2, null);
printf("\nTime Taken: %f seconds\n", (double) (tv2.tv_usec - tv1.tv_usec)/1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
#endif
return 0;
}
```
For Test 1, and for the top 10 frequent words and with timing enabled it should print:
```
968832 the
528960 of
466432 and
421184 a
322624 to
320512 in
270528 he
213120 his
191808 i
182144 s
Time Taken: 1.549155 seconds
```
[Answer]
# [C] Prefix Tree + Bins
***NOTE: The compiler used has a significant effect on program execution speed!***
I have used gcc (MinGW.org GCC-8.2.0-3) 8.2.0. When using the ***-Ofast*** switch, the program runs almost 50% faster than the normally compiled program.
**Algorithm Complexity**
I have since come to realise that the Bin sorting I am performing is a form of [Pigeonhost sort](https://en.wikipedia.org/wiki/Pigeonhole_sort) this means that i can derrive the Big O complexity of this solution.
I calculate it to be:
```
Worst Time complexity: O(1 + N + k)
Worst Space complexity: O(26*M + N + n) = O(M + N + n)
Where N is the number of words of the data
and M is the number of letters of the data
and n is the range of pigeon holes
and k is the desired number of sorted words to return
and N<=M
```
The tree construction complexity is equivalent to tree traversal so since at any level the correct node to traverse to is O(1) (as each letter is mapped directly to a node and we are always only traverse one level of the tree for each letter)
Pigeon Hole sorting is O(N + n) where n is the range of key values, however for this problem, we do not need to sort all values, only the k number so the worst case would be O(N + k).
Combining together yields O(1 + N + k).
Space Complexity for tree construction is due to fact that the worst case is 26\*M nodes if the data consists of one word with M number of letters and that each node has 26 nodes (i.e. for the letters of the alphabet). Thus O (26\*M) = O(M)
For the Pigeon Hole sorting has space complexity of O(N + n)
Combining together yields O(26\*M + N + n) = O(M + N + n)
**Algorithm**
It takes two arguments as input (path to text file and for k number of most frequent words to list)
Based on my other entries, this version has a very small time cost ramp with increasing values of k compared to my other solutions. But is noticeably slower for low values of k however it should be much faster for larger values of k.
It create a tree branching on letters of words, then at the leaf letters it increments a counter. Then adds the word to a bin of words of the same size (after first removing the word from bin it already resided in). This all repeats until no more letters are read in. After which the bins are reverse iterated k times starting from the largest bin and the words of each bin are output.
It currently defaults to output the processing time, but for purposes of conistency with other submissions, disable the TIMING definition in the source code.
```
// comment out TIMING if using external program timing mechanism
#define TIMING 1
// may need to increase if the source text has many unique words
#define MAX_LETTER_INSTANCES 1000000
// may need to increase if the source text has many repeated words
#define MAX_BINS 1000000
// assume maximum of 20 letters in a word... adjust accordingly
#define MAX_LETTERS_IN_A_WORD 20
// assume maximum of 10 letters for the string representation of the bin number... adjust accordingly
#define MAX_LETTERS_FOR_BIN_NAME 10
// maximum number of bytes of the output results
#define MAX_OUTPUT_SIZE 10000000
#define false 0
#define true 1
#define null 0
#define SPACE_ASCII_CODE 32
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef TIMING
#include <sys/time.h>
#endif
struct Letter
{
//char isAWord;
struct Letter* parent;
struct Letter* binElementNext;
char asciiCode;
unsigned int count;
struct Letter* nextLetters[26];
};
typedef struct Letter Letter;
struct Bin
{
struct Letter* word;
};
typedef struct Bin Bin;
int main(int argc, char *argv[])
{
#ifdef TIMING
struct timeval tv1, tv2;
gettimeofday(&tv1, null);
#endif
int k;
if (argc !=3 || (k = atoi(argv[2])) <= 0)
{
printf("Usage:\n");
printf(" WordCount <input file path> <number of most frequent words to find>\n\n");
return -1;
}
long file_size;
long dataLength;
char* data;
// read in file contents
FILE *fptr;
size_t read_s = 0;
fptr = fopen(argv[1], "rb");
fseek(fptr, 0L, SEEK_END);
dataLength = ftell(fptr);
rewind(fptr);
data = (char*)malloc((dataLength));
read_s = fread(data, 1, dataLength, fptr);
if (fptr) fclose(fptr);
unsigned int chr;
unsigned int i, j;
// working memory of letters
Letter* letters = (Letter*) malloc(sizeof(Letter) * MAX_LETTER_INSTANCES);
memset(&letters[0], null, sizeof( Letter) * MAX_LETTER_INSTANCES);
// the memory for bins
Bin* bins = (Bin*) malloc(sizeof(Bin) * MAX_BINS);
memset(&bins[0], null, sizeof( Bin) * MAX_BINS);
// the index of the next unused letter
unsigned int letterMasterIndex=0;
Letter *nextFreeLetter = &letters[0];
// pesudo letter representing the starting point of any word
Letter* root = &letters[letterMasterIndex++];
// the current letter in the word being processed
Letter* currentLetter = root;
// the next letter to be processed
Letter* nextLetter = null;
unsigned int sortedListSize = 0;
// the count of the most frequent word
unsigned int maxCount = 0;
// the count of the current word
unsigned int wordCount = 0;
////////////////////////////////////////////////////////////////////////////////////////////
// CREATING PREFIX TREE
j=dataLength;
while (--j>0)
{
chr = data[j]|0x20; // convert to lower case
// is a letter?
if (chr > 96 && chr < 123)
{
chr-=97; // translate to be zero indexed
nextLetter = currentLetter->nextLetters[chr];
// this is a new letter at this word length, intialise the new letter
if (nextLetter == null)
{
++letterMasterIndex;
nextLetter = ++nextFreeLetter;
nextLetter->parent = currentLetter;
nextLetter->asciiCode = chr;
currentLetter->nextLetters[chr] = nextLetter;
}
currentLetter = nextLetter;
}
else
{
//currentLetter->isAWord = true;
// increment the count of the full word that this letter represents
++currentLetter->count;
// reset the letter path representing the word
currentLetter = root;
}
}
////////////////////////////////////////////////////////////////////////////////////////////
// ADDING TO BINS
j = letterMasterIndex;
currentLetter=&letters[j-1];
while (--j>0)
{
// is the letter the leaf letter of word?
if (currentLetter->count>0)
{
i = currentLetter->count;
if (maxCount < i) maxCount = i;
// add to bin
currentLetter->binElementNext = bins[i].word;
bins[i].word = currentLetter;
}
--currentLetter;
}
////////////////////////////////////////////////////////////////////////////////////////////
// PRINTING OUTPUT
// the memory for output
char* output = (char*) malloc(sizeof(char) * MAX_OUTPUT_SIZE);
memset(&output[0], SPACE_ASCII_CODE, sizeof( char) * MAX_OUTPUT_SIZE);
unsigned int outputIndex = 0;
// string representation of the current bin number
char binName[MAX_LETTERS_FOR_BIN_NAME];
memset(&binName[0], SPACE_ASCII_CODE, MAX_LETTERS_FOR_BIN_NAME);
Letter* letter;
Letter* binElement;
// starting at the bin representing the most frequent word(s) and then iterating backwards...
for ( i=maxCount;i>0 && k>0;i--)
{
// check to ensure that the bin has at least one word
if ((binElement = bins[i].word) != null)
{
// update the bin name
sprintf(binName,"%u",i);
// iterate of the words in the bin
while (binElement !=null && k>0)
{
// stop if we have reached the desired number of outputed words
if (k-- > 0)
{
letter = binElement;
// add the bin name to the output
memcpy(&output[outputIndex],&binName[0],MAX_LETTERS_FOR_BIN_NAME);
outputIndex+=MAX_LETTERS_FOR_BIN_NAME;
// construct string of letters to form the word
while (letter != root)
{
// output the letter to the output
output[outputIndex++] = letter->asciiCode+97;
letter=letter->parent;
}
output[outputIndex++] = '\n';
// go to the next word in the bin
binElement = binElement->binElementNext;
}
}
}
}
// write the output to std out
fwrite(output, 1, outputIndex, stdout);
// fflush(stdout);
// free( data );
// free( letters );
// free( bins );
// free( output );
#ifdef TIMING
gettimeofday(&tv2, null);
printf("\nTime Taken: %f seconds\n", (double) (tv2.tv_usec - tv1.tv_usec)/1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
#endif
return 0;
}
```
EDIT: now deferring populating bins until after tree is constructed and optimising construction of output.
EDIT2: now using pointer arithmetic instead of array access for speed optimisation.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/)
The following runs in under 8 seconds on my 2.6 Ghz i7-4720HQ using 64-bit Dyalog APL 17.0 on Windows 10:
```
⎕{m[⍺↑⍒⊢/m←{(⊂⎕UCS⊃⍺),≢⍵}⌸(⊢⊆⍨96∘<∧<∘123)83⎕DR 819⌶80 ¯1⎕MAP⍵;]}⍞
```
It first prompts for the file name, then for k. Note that a significant part of the running time (about 1 second) is just reading the file in.
To time it, you should be able to pipe the following into your `dyalog` executable (for the ten most frequent words):
```
⎕{m[⍺↑⍒⊢/m←{(⊂⎕UCS⊃⍺),≢⍵}⌸(⊢⊆⍨96∘<∧<∘123)83⎕DR 819⌶80 ¯1⎕MAP⍵;]}⍞
/tmp/ulysses64
10
⎕OFF
```
It should print:
```
the 968832
of 528960
and 466432
a 421184
to 322624
in 320512
he 270528
his 213120
i 191808
s 182144
```
[Answer]
# [J](http://jsoftware.com/)
```
9!:37 ] 0 _ _ _
'input k' =: _2 {. ARGV
k =: ". k
lower =: a. {~ 97 + i. 26
words =: ((lower , ' ') {~ lower i. ]) (32&OR)&.(a.&i.) fread input
words =: ' ' , words
words =: -.&(s: a:) s: words
uniq =: ~. words
res =: (k <. # uniq) {. \:~ (# , {.)/.~ uniq&i. words
echo@(,&": ' ' , [: }.@": {&uniq)/"1 res
exit 0
```
Run as a script with `jconsole <script> <input> <k>`. For example, the output from the `giganovel` with `k=100K`:
```
$ time jconsole solve.ijs giganovel 100000 | head
11309 e
11290 ihit
11285 ah
11260 ist
11255 aa
11202 aiv
11201 al
11188 an
11187 o
11186 ansa
real 0m13.765s
user 0m11.872s
sys 0m1.786s
```
There's no limit except for the amount of available system memory.
[Answer]
# Java
I though it would be nice to get Java represented. There i nothing novel in the approach, just porting what others have done.
```
package trie;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class ByteTrie {
static class Node {
public Node parent;
public int index;
public Node[] nodes = null;
public int count;
public Node(Node parent, int index) {
this.parent = parent;
this.index = index;
Trie.allNodes.add(this);
}
public String getWord() {
if (this.index >= 0) {
return this.parent.getWord() + (char) (this.index + 97);
} else {
return "";
}
}
public Node traverse(int b) {
if (this.nodes == null) {
this.nodes = new Node[26];
return this.nodes[b] = new Node(this, b);
}
if (this.nodes[b] == null) return this.nodes[b] = new Node(this, b);
return this.nodes[b];
}
}
static class Trie {
public static List<Node> allNodes = new ArrayList<>();
private final Node root = new Node(null, -1);
}
public static class App {
private final String filename;
private final int k;
public App(String filename, int k) {
this.filename = filename;
this.k = k;
}
public void run() throws IOException {
Trie trie = new Trie();
Path path = Paths.get(filename);
Node current = trie.root;
InputStream inputStream = Files.newInputStream(path);
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
int b;
boolean inWord = false;
while ((b = bufferedInputStream.read()) != -1) {
int u = ((b | 32) - 97);
if (u >= 26 || u < 0) {
if (inWord) {
++current.count;
}
inWord = false;
} else {
if (!inWord) {
current = trie.root;
}
inWord = true;
current = current.traverse(u);
}
}
bufferedInputStream.close();
inputStream.close();
Trie.allNodes.sort((o1, o2) -> Integer.compare(o2.count, o1.count));
List<Node> finalList = Trie.allNodes.subList(0, k);
for (Node node : finalList) {
System.out.println(node.getWord() + "\t" + node.count);
}
}
}
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.out.println("Filename required");
System.exit(1);
}
String filename = args[0];
int k = args.length > 1 ? Integer.parseInt(args[1]) : 10;
App app = new App(filename, k);
app.run();
}
}
```
The fun part is compiling it to a native image using GraalVM with PGO (which unfortunately requires GraalVM Enterprise Edition) which roughly cuts the runtime in half.
java:
```
time java -jar build/libs/trie-1.0-all.jar ../giganovel 100000
8.02s user 0.27s system 101% cpu 8.186 total
java -jar build/libs/trie-1.0-all.jar ../ulysses64 10
0.82s user 0.03s system 111% cpu 0.763 total
```
native image:
```
time ./trie-1.0-all ../giganovel 100000
4.14s user 0.26s system 96% cpu 4.582 total
time ./trie-1.0-all ../ulysses64 10
0.35s user 0.02s system 99% cpu 0.366 total
```
Full solution at <https://github.com/dillon-sellars/MultiTrie>
[Answer]
# Scala Simple Implementation (using mutable.Map)
```
val map = scala.collection.mutable.Map.empty[String, Int]
def wordsFromFile(filePath: String) = {
val file = scala.io.Source.fromFile(filePath)
val regex = "[a-z]+".r()
file
.getLines()
.flatMap(line => (regex findAllIn line.toLowerCase))
.foreach { word =>
val v = map.getOrElse(word, 0)
map.put(word, v + 1)
}
file.close()
}
def freq(filePath: String, k: Int) = {
wordsFromFile(filePath)
map.toSeq
.sortBy(a => -a._2)
.take(k)
}
val start = System.currentTimeMillis()
freq("ulysses64", 10)
.foreach {
case (word, count) => println(s"$word\t$count")
}
val end = System.currentTimeMillis()
println(s"Time taken: ${end - start} ms")
```
Result:
```
the 968832
of 528960
and 466432
a 421184
to 322624
in 320512
he 270528
his 213120
i 191808
s 182144
Time taken: 3973 ms
```
[Answer]
**RUST Hashmap with FNV hasher**
Managed to get around ~95% of the top performer's performance without a custom data structure by just using a good hashmap.
EDIT: This doesn't scale well to giganovel - which it is performing much worse on (2-3 times slower).
```
❯ time "./target/release/current ulysses64.txt 10"
Benchmark #1: ./target/release/current ulysses64.txt 10
Time (mean ± σ): 718.8 ms ± 26.8 ms [User: 643.0 ms, System: 66.2 ms]
Range (min … max): 676.5 ms … 763.6 ms 10 runs
❯ time "./target/release/mine ulysses64.txt 10"
Benchmark #1: ./target/release/mine
Time (mean ± σ): 760.8 ms ± 26.7 ms [User: 660.5 ms, System: 90.0 ms]
Range (min … max): 730.0 ms … 800.2 ms 10 runs
```
in cargo.toml:
```
[dependencies]
fnv = "1.0"
```
Code:
```
use std::env::args;
use std::fs::File;
use std::io::Read;
use std::str::from_utf8_unchecked;
use fnv::FnvHashMap;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
struct WordServer<'a> {
data: &'a [u8],
index: usize,
}
impl<'a> Iterator for WordServer<'a> {
type Item = &'a [u8];
fn next(&mut self) -> Option<Self::Item> {
let start = self.index;
let end = loop {
let b = match self.data.get(self.index) {
Some(b) => *b,
None => return None,
};
match b {
0..=25 => self.index += 1,
_ => break self.index,
}
};
loop {
let b = match self.data.get(self.index) {
Some(b) => *b,
None => return None,
};
match b {
0..=25 => break,
_ => self.index += 1,
}
}
Some(&self.data[start..end])
}
}
fn go(file: &str, topn: usize) -> Result<()> {
let mut file = File::open(file)?;
let file_len = file.metadata()?.len();
let mut data = Vec::with_capacity(file_len as usize);
file.read_to_end(&mut data)?;
// Convert all data into lowercase and nulls
let data = data
.iter()
.map(|b| (b | 0b100000).wrapping_sub(b'a'))
.collect::<Vec<_>>();
let word_server = WordServer {
data: data.as_slice(),
index: 0,
};
let cap = file_len >> 35;
// let mut collection: HashMap<&[u8], u32> = HashMap::with_capacity(cap as usize);
// let mut collection: HashMap<&[u8], u32> = HashMap::with_hasher();
let mut collection = FnvHashMap::with_capacity_and_hasher(cap as usize, Default::default());
// Add words to our collection
for word in word_server {
match collection.get_mut(word) {
Some(num) => *num += 1,
None => {
collection.insert(word, 1);
}
}
}
// Now get top n words
let mut all = collection.iter().collect::<Vec<(&&[u8], &u32)>>();
all.sort_unstable_by(|a, b| b.1.partial_cmp(a.1).unwrap());
for (b, c) in all.iter().take(topn) {
let changed = b.iter().map(|b| b + b'a').collect::<Vec<u8>>();
let string = unsafe { from_utf8_unchecked(&changed) };
println!("Count: {}: {}", c, string);
}
Ok(())
}
fn main() {
let mut args = args();
let file = args.nth(1).unwrap();
let topn = args.next().unwrap().parse::<usize>().unwrap();
go(&file, topn).unwrap()
}
```
```
[Answer]
# OCaml
**Pre-requisites:**
1. [Install Opam](https://opam.ocaml.org/doc/Install.html)
2. `$ opam install core dune`
```
$ opam --version
2.0.6
$ ocamlc --version
4.10.0
$ dune --version
2.3.1
$ opam show -f version core
v0.13.0
```
**File: main.ml**
```
open Core;;
let () =
let argv = Sys.get_argv () in
match argv with
| [| _prog_name; file_name; limit |] ->
let limit = Int.of_string limit in
assert (limit > 0);
In_channel.with_file file_name ~f:(fun in_ch -> (
let word_counts = String.Table.create () in
let update_word_counts current_chars =
if not (List.is_empty current_chars) then (
let current_word = String.of_char_list @@ List.rev current_chars in
String.Table.update word_counts current_word
~f:(fun v -> 1 + (Option.value v ~default:0))) in
let buf_size = 1048576 in
let buf = Bytes.create buf_size in
let finished = ref false in
let current_chars = ref [] in
while not !finished do
let len = In_channel.input in_ch ~buf ~pos:0 ~len:buf_size in
if len > 0 then (
for i = 0 to (len - 1) do
let ch = Caml.Bytes.get buf i in
current_chars := (
if Char.is_alpha ch then ((Char.lowercase ch) :: !current_chars)
else (update_word_counts !current_chars; []))
done
) else finished := true
done;
update_word_counts !current_chars;
let count = Int.min limit (String.Table.length word_counts) in
let max_word, max_count, max_wcs = ref "", ref 0, ref [] in
for _i = 1 to count do
String.Table.iteri word_counts ~f:(fun ~key ~data ->
if data > !max_count then (max_word := key; max_count := data));
String.Table.remove word_counts !max_word;
max_wcs := (!max_word, !max_count) :: (!max_wcs);
max_word := ""; max_count := 0
done;
max_wcs := List.sort (!max_wcs) ~compare:(fun (w1, c1) (w2, c2) ->
if phys_equal c1 c2 then String.compare w1 w2 else Int.compare c2 c1);
List.iter (!max_wcs) ~f:(fun (word, count) ->
Printf.printf "%s %d\n" word count)))
| _ -> Printf.eprintf "Error: Usage: %s file-name limit\n" argv.(0)
```
**File: dune**
```
(executable
(name main)
(libraries core))
```
**Build:**
```
$ dune build main.exe
```
**Run:**
```
$ time ./_build/default/main.exe ulysses64 10
the 968832
of 528960
and 466432
a 421184
to 322624
in 320512
he 270528
his 213120
i 191808
s 182144
real 0m6.143s
user 0m6.047s
sys 0m0.068s
```
[Answer]
Since only latin words are searched for, don't forget to export LC\_ALL=C:
```
$ time ./wordcount.sh /tmp/ulysses64.txt 10
...
./wordcount.sh /tmp/ulysses64.txt 10 31.48s user 0.63s system 103% cpu 31.016 total
$ time ./wordcount.mawk /tmp/ulysses64.txt 10
...
./wordcount.mawk /tmp/ulysses64.txt 10 3.68s user 0.14s system 104% cpu 3.653 total
$ export LC_ALL=C
$ time ./wordcount.sh /tmp/ulysses64.txt 10
...
./wordcount.sh /tmp/ulysses64.txt 10 8.64s user 0.42s system 113% cpu 7.979 total
$ time ./wordcount.mawk /tmp/ulysses64.txt 10
...
./wordcount.mawk /tmp/ulysses64.txt 10 3.58s user 0.12s system 104% cpu 3.541 total
```
wordcount.sh:
```
#!/bin/sh
tr -cs A-Za-z '\n' <"$1" | tr A-Z a-z | sort | uniq -c | sort -rn | head -n"$2"
```
wordcount.mawk:
```
#!/bin/sh
tr A-Z a-z <"$1" | mawk -vRS='[^a-z]+' '
{++count[$0]}
END {for (w in count) print count[w], w}' | \
sort -k1,1 -rn | head -n"$2"
```
By the way, here's a simpler and faster wordcount.py:
```
#!/usr/bin/env python3.9
import collections, re, sys
filename = sys.argv[1]
k = int(sys.argv[2])
reg = re.compile('[a-z]+')
counts = collections.Counter()
counts.update(reg.findall(open(filename).read().lower()))
for i, w in counts.most_common(k):
print(i, w)
```
Result:
```
$ time ./wordcount_SE.py /tmp/ulysses64.txt 10
...
./wordcount_SE.py /tmp/ulysses64.txt 10 16.28s user 0.22s system 99% cpu 16.508 total
$ time ./wordcount.py /tmp/ulysses64.txt 10
...
./wordcount.py /tmp/ulysses64.txt 10 10.65s user 0.96s system 99% cpu 11.607 total
```
My favourite scripting language is quite slow, sadly:
```
$ time ./wordcount.tcl /tmp/ulysses64.txt 10
...
./wordcount.tcl /tmp/ulysses64.txt 10 24.13s user 0.87s system 99% cpu 25.000 total
```
wordcount.tcl:
```
#!/usr/bin/env tclsh
proc wordcount {path head} {
set data [string tolower [read [open $path]]]
foreach word [regexp -all -inline {[a-z]+} $data] {
dict incr wordcount $word
}
set sorted [lsort -stride 2 -index 1 -int -decr $wordcount]
lrange $sorted 0 [expr {$head * 2 - 1}]
}
foreach {count word} [wordcount {*}$argv] {
puts "$word\t$count"
}
```
Everything done on Gentoo -O3 -march=native with an AMD 2700X, mawk-20200106, python 3.9, tcl-8.6.8 and coreutils 8.32.
PS: some interesting additions would be Pypy and LuaJIT
[Answer]
# [Python 3](https://docs.python.org/3/)
This implementation with a simple dictionary is slightly faster than the one using `Counter` one on my system.
```
def words_from_file(filename):
import re
pattern = re.compile('[a-z]+')
for line in open(filename):
yield from pattern.findall(line.lower())
def freq(textfile, k):
frequencies = {}
for word in words_from_file(textfile):
frequencies[word] = frequencies.get(word, 0) + 1
most_frequent = sorted(frequencies.items(), key=lambda item: item[1], reverse=True)
for i, (word, frequency) in enumerate(most_frequent):
if i == k:
break
yield word, frequency
from time import time
start = time()
print('\n'.join('{}:\t{}'.format(f, w) for w,f in freq('giganovel', 10)))
end = time()
print(end - start)
```
[Answer]
# [C] Prefix Tree + Sorted Linked List
It takes two arguments as input (path to text file and for k number of most frequent words to list)
Based on my other entry, this version is much faster for larger values of k but at a minor cost of performance at lower values of k.
It create a tree branching on letters of words, then at the leaf letters it increments a counter. Then checks to see if the current leaf counter is greater than the smallest most frequent word in the list of most frequent words. (list size is the number determined via the command line argument) If so then promote the word represented by the leaf letter to be one of the most frequent. If already a most frequent word, then swap with the next most frequent if the word count is now higher, thus keeping the list sorted. This all repeats until no more letters are read in. After which the list of most frequent words are output.
It currently defaults to output the processing time, but for purposes of conistency with other submissions, disable the TIMING definition in the source code.
```
// comment out TIMING if using external program timing mechanism
#define TIMING 1
// may need to increase if the source text has many unique words
#define MAX_LETTER_INSTANCES 1000000
#define false 0
#define true 1
#define null 0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef TIMING
#include <sys/time.h>
#endif
struct Letter
{
char isTopWord;
struct Letter* parent;
struct Letter* higher;
struct Letter* lower;
char asciiCode;
unsigned int count;
struct Letter* nextLetters[26];
};
typedef struct Letter Letter;
int main(int argc, char *argv[])
{
#ifdef TIMING
struct timeval tv1, tv2;
gettimeofday(&tv1, null);
#endif
int k;
if (argc !=3 || (k = atoi(argv[2])) <= 0)
{
printf("Usage:\n");
printf(" WordCount <input file path> <number of most frequent words to find>\n\n");
return -1;
}
long file_size;
long dataLength;
char* data;
// read in file contents
FILE *fptr;
size_t read_s = 0;
fptr = fopen(argv[1], "rb");
fseek(fptr, 0L, SEEK_END);
dataLength = ftell(fptr);
rewind(fptr);
data = (char*)malloc((dataLength));
read_s = fread(data, 1, dataLength, fptr);
if (fptr) fclose(fptr);
unsigned int chr;
unsigned int i;
// working memory of letters
Letter* letters = (Letter*) malloc(sizeof(Letter) * MAX_LETTER_INSTANCES);
memset(&letters[0], 0, sizeof( Letter) * MAX_LETTER_INSTANCES);
// the index of the next unused letter
unsigned int letterMasterIndex=0;
// pesudo letter representing the starting point of any word
Letter* root = &letters[letterMasterIndex++];
// the current letter in the word being processed
Letter* currentLetter = root;
// the next letter to be processed
Letter* nextLetter = null;
Letter* sortedWordsStart = null;
Letter* sortedWordsEnd = null;
Letter* A;
Letter* B;
Letter* C;
Letter* D;
unsigned int sortedListSize = 0;
unsigned int lowestWordCount = 0;
unsigned int lowestWordIndex = 0;
unsigned int highestWordCount = 0;
unsigned int highestWordIndex = 0;
// main loop
for (int j=0;j<dataLength;j++)
{
chr = data[j]|0x20; // convert to lower case
// is a letter?
if (chr > 96 && chr < 123)
{
chr-=97; // translate to be zero indexed
nextLetter = currentLetter->nextLetters[chr];
// this is a new letter at this word length, intialise the new letter
if (nextLetter == null)
{
nextLetter = &letters[letterMasterIndex++];
nextLetter->parent = currentLetter;
nextLetter->asciiCode = chr;
currentLetter->nextLetters[chr] = nextLetter;
}
currentLetter = nextLetter;
}
// not a letter so this means the current letter is the last letter of a word (if any letters)
else if (currentLetter!=root)
{
// increment the count of the full word that this letter represents
++currentLetter->count;
// is this word not in the top word list?
if (!currentLetter->isTopWord)
{
// first word becomes the sorted list
if (sortedWordsStart == null)
{
sortedWordsStart = currentLetter;
sortedWordsEnd = currentLetter;
currentLetter->isTopWord = true;
++sortedListSize;
}
// always add words until list is at desired size, or
// swap the current word with the end of the sorted word list if current word count is larger
else if (sortedListSize < k || currentLetter->count> sortedWordsEnd->count)
{
// replace sortedWordsEnd entry with current word
if (sortedListSize == k)
{
currentLetter->higher = sortedWordsEnd->higher;
currentLetter->higher->lower = currentLetter;
sortedWordsEnd->isTopWord = false;
}
// add current word to the sorted list as the sortedWordsEnd entry
else
{
++sortedListSize;
sortedWordsEnd->lower = currentLetter;
currentLetter->higher = sortedWordsEnd;
}
currentLetter->lower = null;
sortedWordsEnd = currentLetter;
currentLetter->isTopWord = true;
}
}
// word is in top list
else
{
// check to see whether the current word count is greater than the supposedly next highest word in the list
// we ignore the word that is sortedWordsStart (i.e. most frequent)
while (currentLetter != sortedWordsStart && currentLetter->count> currentLetter->higher->count)
{
B = currentLetter->higher;
C = currentLetter;
A = B != null ? currentLetter->higher->higher : null;
D = currentLetter->lower;
if (A !=null) A->lower = C;
if (D !=null) D->higher = B;
B->higher = C;
C->higher = A;
B->lower = D;
C->lower = B;
if (B == sortedWordsStart)
{
sortedWordsStart = C;
}
if (C == sortedWordsEnd)
{
sortedWordsEnd = B;
}
}
}
// reset the letter path representing the word
currentLetter = root;
}
}
// print out the top frequent words and counts
char string[256];
char tmp[256];
Letter* letter;
while (sortedWordsStart != null )
{
letter = sortedWordsStart;
highestWordCount = letter->count;
string[0]=0;
tmp[0]=0;
if (highestWordCount > 0)
{
// construct string of letters to form the word
while (letter != root)
{
memmove(&tmp[1],&string[0],255);
tmp[0]=letter->asciiCode+97;
memmove(&string[0],&tmp[0],255);
letter=letter->parent;
}
printf("%u %s\n",highestWordCount,string);
}
sortedWordsStart = sortedWordsStart->lower;
}
free( data );
free( letters );
#ifdef TIMING
gettimeofday(&tv2, null);
printf("\nTime Taken: %f seconds\n", (double) (tv2.tv_usec - tv1.tv_usec)/1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
#endif
return 0;
}
```
[Answer]
# C#
This one should work with the lastest [.net SDKs](https://dotnet.microsoft.com/download/visual-studio-sdks).
```
using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using static System.Console;
class Node {
public Node Parent;
public Node[] Nodes;
public int Index;
public int Count;
public static readonly List<Node> AllNodes = new List<Node>();
public Node(Node parent, int index) {
this.Parent = parent;
this.Index = index;
AllNodes.Add(this);
}
public Node Traverse(uint u) {
int b = (int)u;
if (this.Nodes is null) {
this.Nodes = new Node[26];
return this.Nodes[b] = new Node(this, b);
}
if (this.Nodes[b] is null) return this.Nodes[b] = new Node(this, b);
return this.Nodes[b];
}
public string GetWord() => this.Index >= 0
? this.Parent.GetWord() + (char)(this.Index + 97)
: "";
}
class Freq {
const int DefaultBufferSize = 0x10000;
public static void Main(string[] args) {
var sw = Stopwatch.StartNew();
if (args.Length < 2) {
WriteLine("Usage: freq.exe {filename} {k} [{buffersize}]");
return;
}
string file = args[0];
int k = int.Parse(args[1]);
int bufferSize = args.Length >= 3 ? int.Parse(args[2]) : DefaultBufferSize;
Node root = new Node(null, -1) { Nodes = new Node[26] }, current = root;
int b;
uint u;
using (var fr = new FileStream(file, FileMode.Open))
using (var br = new BufferedStream(fr, bufferSize)) {
outword:
b = br.ReadByte() | 32;
if ((u = (uint)(b - 97)) >= 26) {
if (b == -1) goto done;
else goto outword;
}
else current = root.Traverse(u);
inword:
b = br.ReadByte() | 32;
if ((u = (uint)(b - 97)) >= 26) {
if (b == -1) goto done;
++current.Count;
goto outword;
}
else {
current = current.Traverse(u);
goto inword;
}
done:;
}
WriteLine(string.Join("\n", Node.AllNodes
.OrderByDescending(count => count.Count)
.Take(k)
.Select(node => node.GetWord())));
WriteLine("Self-measured milliseconds: {0}", sw.ElapsedMilliseconds);
}
}
```
Here's a sample output.
```
C:\dev\freq>csc -o -nologo freq-trie.cs && freq-trie.exe giganovel 100000
e
ihit
ah
ist
[... omitted for sanity ...]
omaah
aanhele
okaistai
akaanio
Self-measured milliseconds: 13619
```
At first, I tried to use a dictionary with string keys, but that was way too slow. I think it's because .net strings are internally represented with a 2-byte encoding, which is kind of wasteful for this application. So then I just switched to pure bytes, and an ugly goto-style state machine. Case conversion is a bitwise operator. Character range checking is done in a single comparison after subtraction. I didn't spend any effort optimizing the final sort since I found it's using less than 0.1% of the runtime.
Fix: The algorithm was essentially correct, but it was over-reporting total words, by counting all prefixes of words. Since total word count isn't a requirement of the problem, I removed that output. In order to output all k words, I also adjusted the output. I eventually settled on using `string.Join()` and then writing the whole list at once. Surprisingly this is about a second faster on my machine that writing each word separately for 100k.
[Answer]
# Ruby 2.7.0-preview1 with `tally`
The latest version of Ruby has a new method called `tally`. From the [release notes](https://www.ruby-lang.org/en/news/2019/05/30/ruby-2-7-0-preview1-released/):
>
> `Enumerable#tally` is added. It counts the occurrence of each element.
>
>
>
```
["a", "b", "c", "b"].tally
#=> {"a"=>1, "b"=>2, "c"=>1}
```
This almost solves the entire task for us. We just need to read the file first and find the max later.
Here's the whole thing:
```
k = ARGV.shift.to_i
pp ARGF
.each_line
.lazy
.flat_map { @1.scan(/[A-Za-z]+/).map(&:downcase) }
.tally
.max_by(k, &:last)
```
*edit: Added `k` as an command line argument*
It can be run with `ruby k filename.rb input.txt` using the 2.7.0-preview1 version of Ruby. This can be downloaded from various links on release notes page, or installed with rbenv using `rbenv install 2.7.0-dev`.
Example run on my own beat-up, old computer:
```
$ time ruby bentley.rb 10 ulysses64
[["the", 968832],
["of", 528960],
["and", 466432],
["a", 421184],
["to", 322624],
["in", 320512],
["he", 270528],
["his", 213120],
["i", 191808],
["s", 182144]]
real 0m17.884s
user 0m17.720s
sys 0m0.142s
```
[Answer]
## AWK + sort
Just for the sake of completeness, here are two solutions that work best for different versions of AWK.
This one works best with Michael Brennan's AWK (both `mawk-2` and `mawk 1.3.4`). It outperforms GNU awk by a factor of x7.5.
```
mawk -v RS="[^A-Za-z]+" '
{
freq[tolower($0)]++;
}
END {
for (word in freq)
print(freq[word] " " word)
}
' filename | sort -rn | head -10
```
This version works best for the "one true awk" (`nawk`) and GNU awk (`gawk`).
```
awk -v FS="[^a-zA-Z]+" '
{
for (i=1; i<=NF; i++)
freq[tolower($i)]++;
}
END {
for (word in freq)
print(freq[word] " " word)
}
' filename | sort -rn | head -10
```
P.S. Bounty to anyone, who can find even faster AWK solution.
] |
[Question]
[
Given a natural number \$n\$, return the \$n\$-th [Leyland number](https://en.wikipedia.org/wiki/Leyland_number).
### Leyland Number
Leyland numbers are positive integers \$k\$ of the form
$$k = x^y + y^x$$
Where \$x\$ and \$y\$ are integers strictly greater than 1.
They are enumerated in ascending order.
**EDIT:** @DigitalTrauma suggested I include following "definition":
>
> Imagine we throw \$x^y+y^x\$ in a bag for all possible values of \$x\$ and \$y\$, and avoid throwing in duplicates. Then we sort that bag. The sorted bag is our sequence.
>
>
>
### Details
You may use 0 or 1 based indexing, whatever suits you best.
Your program must be able to output at least all Leyland numbers less than the maximum of signed 32-bit integers. (The last Leyland number below this limit is `1996813914`, at index `82`.)
### Test cases
The first few terms are following:
```
8, 17, 32, 54, 57, 100, 145, 177, 320, 368, 512, 593, 945, 1124
```
[A076980](https://oeis.org/A076980) in OEIS, except for the first entry. Note that because of that additional first entry, the indices on OEIS are shifted by one.
More can be found in the [OEIS b-file](https://oeis.org/A076980/b076980.txt)
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~16~~ ~~15~~ 13 bytes
```
Q:Qt!^t!+uSG)
```
Output is 1-based.
[**Try it online!**](http://matl.tryitonline.net/#code=UTpRdCFedCErdVNHKQ&input=ODI)
### Explanation
```
Q % Take input n. Add 1
:Q % Range [2 ... n+1]. This is enough to be used as x and y
t! % Duplicate and transpose
^ % Power, element-wise with broadcast. Gives 2D, square array with x^y
% for all pairs of x and y
t! % Duplicate and transpose. Gives square array with y^x
+ % Add, element-wise
u % Keep unique elements. This linearizes (flattens) the 2D array
S % Sort
G) % Get the n-th entry. Implicitly display
```
[Answer]
# Java 10, ~~225~~ ~~221~~ ~~219~~ ~~216~~ ~~206~~ ~~204~~ ~~193~~ ~~192~~ ~~130~~ 129 bytes
```
n->{var S=new java.util.TreeSet();for(int i=56,t;i<840;)S.add(Math.pow(i/28,t=i%28+2)+Math.pow(t,i++/28));return S.toArray()[n];}
```
0-indexed
-2 bytes (221 → 219) saved by replacing `1996813915` with `(1L<<31)` thanks to *@LeakyNun*.
-3 bytes (219 → 216) thanks to *@LeakyNun* and *@Frozn* with something I forgot myself..
-10 bytes (216 → 206) by changing Java 7 to 8.
-2 bytes (206 → 204) by replacing `ArrayList` with `Vector` thanks to *@TAsk*.
-11 bytes (204 → 193) by removing `s<(1L<<31)&`, since the question states "***at least** all Leyland numbers less than the maximum of signed 32-bit integers*".
-1 byte (193 → 192) by changing `Vector` to `Stack`.
-62 bytes (192 → 130) by switching to Java 10 and using `var`; removing the `Collection.sort`, `import java.util.*;`, if-statement and temp-long `s` by using a `java.util.TreeSet` (which is a set of unique values and sorts automatically); and using `Double` and `Object` return-type instead of `Long` so we can remove the `(int)(...)` cast and `<Long>`.
-1 byte (130 → 129) thanks to *@ceilingcat* by changing the two nested `[2,30]` loops to a single `[56,840]` loop.
[Try it here](https://tio.run/##PVDBbsIwDL3zFRbSpEQpgVVsqhY6aR8AO5Qb4hDasKWUNEpdEEJ8e@cWxiG2/Bz7@b1Sn/SkLA6db3eVzSGvdNPAUlt3HQFYhybsdW5g1ZcA37vS5Ag5ow44rgi8jSg0qJGmV@Aghc5NPq8nHSBLnTlDSRSyRVvJdTAmM8i42tdhWGHTt/cIlV0k85nimdRFwZYaf6Wvz8xO4yTC1L7EiYi5eOIYWSGox7kKBtvgIJNYf4WgL4xv3FbdOtUf9ZD0uO1U2wKOJIxlGKz72WxBc7jLmk5hbRrSVRcG6DbQFQmnT1C36FsEVtjGV/oyQM5E0Bys98/KYC75sKkfvisjI2aK0gJe530WKcT/fADZpUFzlLReeiLCyjErxh8wFk6Su3ywtje3f7fuDw)
**Explanation:**
```
n->{ // Method with integer parameter and Object return-type
var S=new java.util.TreeSet(); // Create a sorted Set, initially empty
for(int i=56,t;i<840) // Loop `i` in the range [56,840]
t.add( // Add to the Set:
Math.pow(i/28, // `i` integer-divided by 28
t=i%28+2) // to the power `i` modulo-28 + 2
+Math.pow(t, // And add `i` modulo-28 + 2
i++/28)); // to the power `i` integer-divided by 28
// (and increase `i` by 1 afterwards with `i++`)
return S.toArray() // Convert the sorted Set to an Object-array
[n];} // And return the value at the input-integer index
```
[Answer]
## Haskell, 52 bytes
```
r=[2..31]
([k|k<-[0..],elem k[x^y+y^x|x<-r,y<-r]]!!)
```
Really inefficient. Tests each natural number for being a Leyland number, making an infinite list of those that are. Given an input, takes that index element of the list. Uses that only `x,y` up to 31 need to be checked for 32 bit integers.
Same length with `filter`:
```
r=[2..31]
(filter(`elem`[x^y+y^x|x<-r,y<-r])[0..]!!)
```
[Answer]
# Pyth, 17 bytes
0-indexed.
```
@{Sms^M_Bd^}2+2Q2
```
[Try it online!](http://pyth.herokuapp.com/?code=%40%7BSms%5EM_Bd%5E%7D2%2B2Q2&input=96&debug=0) (Please, keep it at 100.)
## How it works
```
@{Sms^M_Bd^}2+2Q2
@{Sms^M_Bd^}2+2Q2Q implicit filling. Input:Q
}2+2Q Yield the array [2,3,4,...,Q+2]
^ 2 Cartesian square: yield all the
pairs formed by the above array.
m d Map the following to all of those pairs (e.g. [2,3]):
_B Create [[2,3],[3,2]]
^M Reduce by exponent to each array:
create [8,9]
s Sum: 17 (Leyland number generated)
S Sort the generated numbers
{ Remove duplicate
@ Q Find the Q-th element.
```
## Slower version
1-indexed.
```
e.ffqZs^M_BT^}2Z2
```
[Try it online!](http://pyth.herokuapp.com/?code=e.ffqZs%5EM_BT%5E%7D2Z2&input=3&debug=0) (Please, keep it at 3.)
[Answer]
# MATLAB, 58 bytes
1-indexed
```
n=input('');[A B]=ndgrid(2:n+9);k=A.^B;x=unique(k'+k);x(n)
```
`unique` in MATLAB flattens and sorts the matrix.
---
Thanks for help to [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) and [@flawr](https://codegolf.stackexchange.com/users/24877/flawr).
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~13~~ 12 bytes
```
!uΞ´Ṫ§+^`^tN
```
[Try it online!](https://tio.run/##yygtzv7/X7H03LxDWx7uXHVouXZcQlyJ3////y2MAA "Husk – Try It Online")
~~Tied with MATL, with a similar method.~~
-1 byte from Zgarb!
## Explanation
```
!uΞ´Ṫ§+^`^tN
N list of all natural numbers
t tail: remove 1
´ double: f x = f x x
Ṫ cartesian product with the following function
§ fork: f g h x y = f (g x y) (h x y)
^ x^y
+ plus
` reverse: f x y = f y x
`^ y^x
Ξ merge all results together
u uniquify
! take element at input index
```
[Answer]
## 05AB1E, ~~20~~ 19 bytes
0-indexed
```
ÝÌ2ãvyÂ`ms`m+}){Ù¹è
```
**Explained**
```
ÝÌ # range(2,N+2)
2ã # get all pairs of numbers in the range
v # for each pair
yÂ`ms`m+ # push x^y+y^x
} # end loop
){Ù # wrap to list, sort and remove duplicates
¹è # get Nth element of list
```
[Try it online](http://05ab1e.tryitonline.net/#code=w53DjDLDo3Z5w4JgbXNgbSt9KXvDmcK5w6g&input=Nzc)
Saved 1 byte thanks to @Adnan
[Answer]
# Mathematica, ~~60~~ ~~48~~ 40 bytes
```
(Union@@Array[#^#2+#2^#&,{#,#},2])[[#]]&
```
Uses one-based indexing. `Union` is used by applying it between each row of the 2D matrix created by the `Array`. There, `Union` will flatten the 2D matrix into a list while also removing any duplicates and placing the values in sorted order.
Saved 8 bytes thanks to @[LLlAMnYP](https://codegolf.stackexchange.com/users/46206/lllamnyp).
## Usage
![Example](https://i.stack.imgur.com/YXvHg.png)
[Answer]
# Jelly, 14 bytes
2 bytes thanks to Dennis.
```
R‘*€¹$+Z$FṢQị@
```
[Try it online!](http://jelly.tryitonline.net/#code=UuKAmCrigqzCuSQrWiRG4bmiUeG7i0A&input=&args=OTc&debug=on) (Takes ~ 1s for 82 for me) (O(n^2) time)
### Original 16-byte answer
```
2r30*€¹$+Z$FṢQị@
```
[Try it online!](http://jelly.tryitonline.net/#code=MnIzMCrigqzCuSQrWiRG4bmiUeG7i0A&input=&args=ODI) (Takes < 1s for me) (Constant time)
[Answer]
## Python 3, ~~76~~ 69 bytes
```
r=range(2,32);f=lambda n:sorted({x**y+y**x for x in r for y in r})[n]
```
0-indexed.
<https://repl.it/C2SA>
[Answer]
# Bash + GNU utilities, 63
```
printf %s\\n x={2..32}\;y={2..32}\;x^y+y^x|bc|sort -nu|sed $1!d
```
1-based indexing. It looks like this is pretty much the same approach as [@TimmyD's answer](https://codegolf.stackexchange.com/a/82986/11259). Instead of nested loops, bash brace expansion is used to generate arithmetic expressions that are piped to `bc` for evaluation.
[Ideone.](https://ideone.com/4CvMCI)
[Answer]
# [Perl 6](http://perl6.org), ~~60 58~~ 56 bytes
```
~~{sort(keys bag [X[&({$^a\*\*$^b+$b\*\*$a})]] (2..$\_+2)xx 2)[$\_]}
{sort(keys set [X[&({$^a\*\*$^b+$b\*\*$a})]] (2..$\_+2)xx 2)[$\_]}
{sort(unique [X[&({$^a\*\*$^b+$b\*\*$a})]] (2..$\_+2)xx 2)[$\_]}
{squish(sort [X[&({$^a\*\*$^b+$b\*\*$a})]] (2..$\_+2)xx 2)[$\_]}~~
{squish(sort [X[&({$^a**$^b+$b**$a})]] (2..31)xx 2)[$_]}
{squish(sort [X[&({$^a**$^b+$b**$a})]] 2..31,2..31)[$_]}
```
### Test:
```
#! /usr/bin/env perl6
use v6.c;
my &Leyland = {squish(sort [X[&({$^a**$^b+$b**$a})]] 2..31,2..31)[$_]}
say ^14 .map: &Leyland;
time-this {Leyland 81};
sub time-this (&code) {
my $start = now;
my $value = code();
printf "takes %.3f seconds to come up with $value\n", now - $start;
}
```
```
(8 17 32 54 57 100 145 177 320 368 512 593 945 1124)
takes 0.107 seconds to come up with 1996813914
```
### Explanation:
```
{
squish( # remove repeated values
sort
[X[&( # cross reduce with:
{ $^a ** $^b + $b ** $a }
)]]
( 2 .. $_+2 ) # 「Range.new(2,$_+2)」 (inclusive range)
xx 2 # repeat list
)[$_]
}
```
[Answer]
# F#, ~~117~~, 104
Welp, it's shorter than my C# answer at least.
Saved 13 bytes thanks to Reed Copsey in the F# chatroom.
```
let f n=[for x in 2I..32I do for y in 2I..32I->x**(int y)+y**(int x)]|>Seq.sort|>Seq.distinct|>Seq.nth n
```
[Answer]
## PowerShell v2+, ~~84~~ ~~73~~ 68 bytes
```
(2..30|%{2..($x=$_)|%{"$x*"*$_+'1+'+"$_*"*$x+1|iex}}|sort)[$args[0]]
```
*Saved 11 bytes thanks to @Neil ... saved additional 5 bytes by reorganizing how the `iex` expression is evaluated.*
Naïve method, we simply double-for loop from `x=2..30` and `y=2..x`. Each loop we put `x^y + y^x` on the pipeline. The `30` was chosen experimentally to ensure that we covered all cases less than `2^31-1` ;-). We pipe those to `Sort-Object` to order them ascending. Output is zero-indexed based on the input `$args[0]`.
Yes, there are a *lot* of extraneous entries generated here -- this algorithm actually generates 435 Leyland numbers -- but things above index `81` are not guaranteed to be accurate and in order (there may be some that are skipped).
### Examples
```
PS C:\Tools\Scripts\golfing> .\leyland-numbers.ps1 54
14352282
PS C:\Tools\Scripts\golfing> .\leyland-numbers.ps1 33
178478
PS C:\Tools\Scripts\golfing> .\leyland-numbers.ps1 77
1073792449
```
[Answer]
# R, ~~58~~ 54 bytes
1-indexed. Eliminated 4 bytes by using `pryr::r` instead of `function`.
```
unique(sort(outer(2:99,2:9,pryr::f(x^y+y^x))))[scan()]
```
### Explanation
For all numbers from 2 to 99, and 2 to 9,
```
2:99,2:9
```
apply the function `x^y+y^x`. This generates a 98x8 matrix.
```
outer(2:99,2:9,pryr::f(x^y+y^x))
```
Sort this matrix (coercing it to a vector):
```
sort(outer(2:99,2:9,pryr::f(x^y+y^x)))
```
Remove all non-unique values:
```
unique(sort(outer(2:99,2:9,pryr::f(x^y+y^x))))
```
Read `n` from stdin, and fetch the `n`th number from the list:
```
unique(sort(outer(2:99,2:9,pryr::f(x^y+y^x))))[scan()]
```
[Answer]
## JavaScript (Firefox 42-57), 94 bytes
```
n=>[for(x of Array(32).keys())for(y of Array(x+1).keys())if(y>1)x**y+y**x].sort((x,y)=>x-y)[n]
```
Needs Firefox 42 because it uses both array comprehensions and exponentiation (`[for(..of..)]` and `**`).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
‘€p`*U$§QṢị@
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw4xHTWsKErRCVQ4tD3y4c9HD3d0O/w1NrA@3qwAl3P8DAA "Jelly – Try It Online")
Similar algorithm to [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun)'s [Jelly answer](https://codegolf.stackexchange.com/a/82998/66833) but with a few improvements
## How it works
```
‘€p`*U$§QṢị@ - Main link. Takes n on the left
€ - Yield [1, 2, ..., n]
‘ - Increment each to [2, 3, ..., n+1]
p` - Take the Cartesian product with itself, yielding all pairs [[2, 2], [2, 3], ..., [n+1, n+1]]
$ - Run the previous two commands over each pair, [x, y]:
U - Reverse the pair to yield [y, x]
* - Raise to the power to yield [x*y, y*x]
§ - Take the sum of each, yielding [8, 17, ..., 2(n+1)*(n+1)]]
Q - Deduplicate
Ṣ - Sort in ascending order
ị@ - Take the nth element in this list
```
[Answer]
# Haskell, ~~99~~ ~~98~~ ~~96~~ ~~95~~ 94 bytes
It is probably easily outgolfed, but that was the best *I* was able to come up with.
```
import Data.List
f n|n<2=[]|n>1=sort.nub$f(n-1)++[x^n+n^x|x<-[2..n]]
g n=(f.toInteger$n+3)!!n
```
[Answer]
# C#, ~~141~~, 127 bytes.
Oh c#, you are such a long language.
```
n=>(from x in Enumerable.Range(2,32)from y in Enumerable.Range(2,32)select Math.Pow(x,y)+Math.Pow(y,x)).Distinct().ToList()[n];
```
This is a lambda that needs to be assigned to `delegate double del(int n);` to be run, as such:
```
delegate double del(int n);
del f=n=>(from x in Enumerable.Range(2,32)from y in Enumerable.Range(2,32)select Math.Pow(x,y)+Math.Pow(y,x)).OrderBy(q=>q).Distinct().ToList()[n];
```
[Answer]
# SQL (PostgreSQL 9.4), 171 bytes
Done as a prepared statement. Generate a couple of series 2 - 99, cross join them and do the equation. Densely rank the results to index them and select the first result that has the rank of the integer input.
```
prepare l(int)as select s from(select dense_rank()over(order by s)r,s from(select x^y+y^x from generate_series(2,99)x(x),generate_series(2,99)y(y))c(s))d where r=$1limit 1
```
Executed as follows
```
execute l(82)
s
-----------------
1996813914
```
This ended up running a lot quicker than I expected
[Answer]
# J, 29 bytes
```
<:{[:/:~@~.@,[:(^+^~)"0/~2+i.
```
Uses one-based indexing. Conversion from my Mathematica [solution](https://codegolf.stackexchange.com/a/83058/6710).
The true secret here is that I have `:(^+^~)` on my side.
## Usage
```
f =: <:{[:/:~@~.@,[:(^+^~)"0/~2+i.
f 7
145
(,.f"0) >: i. 10 NB. Extra commands for formatting
1 8
2 17
3 32
4 54
5 57
6 100
7 145
8 177
9 320
10 368
```
## Explanation
```
<:{[:/:~@~.@,[:(^+^~)"0/~2+i. Input: n
2+i. Step one
"0/~ Step two
:(^+^~) ???
<:{[:/:~@~.@,[ Profit
```
More seriously,
```
<:{[:/:~@~.@,[:(^+^~)"0/~2+i. Input: n
i. Create the range [0, 1, ..., n-1]
2+ Add 2 to each
(^+^~)"0 Create a dyad (2 argument function) with inputs x, y
and returns x^y + y^x
[: /~ Use that function to create a table using the previous range
[: , Flatten the table into a list
~.@ Take its distinct values only
/:~@ Sort it in ascending order
<: Decrement n (since J is zero-indexed)
{ Select the value at index n-1 from the list and return
```
[Answer]
# Swift 3, 138 bytes
```
import Glibc;func l(n:Int)->Int{let r=stride(from:2.0,to:50,by:1);return Int(Set(r.flatMap{x in r.map{pow(x,$0)+pow($0,x)}}).sorted()[n])}
```
**Ungolfed code**
[Try it here](http://swiftlang.ng.bluemix.net/#/repl/57626383047269a43fc085c0)
```
import Glibc
func l(n: Int) -> Int {
// Create a Double sequence from 2 to 50 (because pow requires Double)
let r = stride(from: 2.0, to: 50.0, by: 1.0)
return Int(Set(r.flatMap {
x in r.map {
pow(x, $0) + pow($0, x)
}
}).sorted()[n])
```
[Answer]
**Axiom 148 bytes**
```
w(n)==(v:List INT:=[];for i in 2..31 repeat for j in i..31 repeat(a:=i^j+j^i;if a>1996813914 then break;v:=cons(a,v));v:=sort v;~index?(n,v)=>0;v.n)
```
some example
```
w(n)==
v:List INT:=[];for i in 2..31 repeat for j in i..31 repeat
(a:=i^j+j^i;if a>1996813914 then break;v:=cons(a,v));v:=sort v;~index?(n,v)=>0
v.n
(2) -> [w(i) for i in 0..85]
Compiling function w with type NonNegativeInteger -> Integer
(2)
[0, 8, 17, 32, 54, 57, 100, 145, 177, 320, 368, 512, 593, 945, 1124, 1649,
2169, 2530, 4240, 5392, 6250, 7073, 8361, 16580, 18785, 20412, 23401,
32993, 60049, 65792, 69632, 93312, 94932, 131361, 178478, 262468, 268705,
397585, 423393, 524649, 533169, 1048976, 1058576, 1596520, 1647086,
1941760, 2012174, 2097593, 4194788, 4208945, 4785713, 7861953, 8389137,
9865625, 10609137, 14352282, 16777792, 16797952, 33554432, 33555057,
43050817, 45136576, 48989176, 61466176, 67109540, 67137425, 129145076,
134218457, 177264449, 244389457, 268436240, 268473872, 292475249,
364568617, 387426321, 536871753, 774840978, 1073742724, 1073792449,
1162268326, 1173741824, 1221074418, 1996813914, 0, 0, 0]
```
## Type: List Integer
[Answer]
# [Perl 5](https://www.perl.org/), 70 + 1 (-p) = 71 bytes
```
for$x(2..32){$r{$x**$_+$_**$x}++for$x..32}$_=(sort{$a<=>$b}keys%r)[$_]
```
[Try it online!](https://tio.run/##K0gtyjH9/z8tv0ilQsNIT8/YSLNapahapUJLSyVeWyUeSFXUamuD5UGytSrxthrF@UUl1SqJNrZ2Kkm12amVxapFmtEq8bH//xv/yy8oyczPK/6v62uqZ2Bo8F@3AAA "Perl 5 – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 136 bytes
```
n->java.util.stream.IntStream.range(0,900).map(l->l+=Math.pow(l%30+2,l/30+2)+Math.pow(l/30+2,l%30+2)-l).sorted().distinct().toArray()[n]
```
[Try it online!](https://tio.run/##RVA9b8IwEN37K05IkWwlcSJY2lKQOnaAhW6IwY0NNTi2FV@oUMVvT8@BtoPv4/m@3jvKsyyP6jSE/sOaBhorY4SVNO77AcA41N1eNhrWKR0BaFiyjs8JuT6QiSiRWtfgYAGDK5dHGip6NFZE7LRsxZvDzS3qpDtoVhdPdc1FKwOz5dLmi5XETxH8F7PZrM6nha2S4/k/Xt3w8ZuXlovoO9SKcaFMROMapBD9a9fJC@Nbtxvm6bY7rfuJZ28UtESO0TnGHbY7kBxu1KoK3nUkel5p2PsOpCXyVAS@x9AjMFoUrLyMkNMFxJMJ4S/T2Ag@TkrNo0aG9Kjn5F7gcUo@z3@XAWwuEXUraLYItAX3bJLN1DNkKnOTAkwBTpDSfJQ5CZ3edfgB "Java (JDK) – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 28 bytes
```
^₂g{∧{Ċ≥₁>ᵛ1&≜↔;?^ᵐ+}}ᶠ⁽o∋↙?
```
[Try it online!](https://tio.run/##AUYAuf9icmFjaHlsb2cy//9e4oKCZ3viiKd7xIriiaXigoE@4bWbMSbiiZzihpQ7P17htZArfX3htqDigb1v4oiL4oaZP///N/9a "Brachylog – Try It Online")
### How it works
```
^₂g{∧{Ċ≥₁>ᵛ1&≜↔;?^ᵐ+}}ᶠ⁽o∋↙?
^₂g 7 -> [49]
{∧{ }}ᶠ⁽ find first 49 outputs whose …
Ċ≥₁>ᵛ1 inputs are of form [X,Y],
≥₁ are ordered
>ᵛ1 and strictly greater than 1
&≜ force labels on input
↔;? [2,3] -> [[3,2],[2,3]]
^ᵐ -> [9, 8]
+ -> 17
o∋↙? order outputs and take the Nth element
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 12 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
R⁺2ẉıḲ*S;ṠUi
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPVIlRTIlODElQkEyJUUxJUJBJTg5JUM0JUIxJUUxJUI4JUIyKlMlM0IlRTElQjklQTBVaSZmb290ZXI9JmlucHV0PTUmZmxhZ3M9)
0-indexed.
#### Explanation
```
R⁺2ẉıḲ*S;ṠUi # Implicit input
R⁺ # Range [2..input+1]
2ẉ # Cartesian power of 2
ı ; # Map over each pair:
Ḳ # Bifurcate: push reverse
* # Exponentiation
S # Sum the pair
Ṡ # Sort the list
U # And uniquify it
i # Index in
# Implicit output
```
[Answer]
# J, ~~38~~ 31 bytes
0-indexed.
```
~~[{[:(#~~:)@/:~@,/[:(+|:)[:^/~2+i.@>:@]~~
((#~~:)/:~,/(+|:)^/~2+i.29x){~[
```
## Usage
```
>> f =: ((#~~:)/:~,/(+|:)^/~2+i.29x){~[
>> f 81
<< 1996813914
```
[Answer]
# Python 3, 129->116 bytes
I know there is a shorter python 3 answer, but I still wanted to contribute my solution.
```
t=[]
for k in range(100):a,b,q=k//10,k%10,a**b+b**a;f=lambda q:0if q in t else t.append(q);f(q)
print(sorted(t)[7:])
```
This was the best way that I could to think of to handle going through all values for x and all values for y.
If anyone can golf my approach it would be appreciated
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~62~~ 58 bytes
```
->n{a,*b=c=2;c+=1while(b<<a**c+c**a;c<32||32>c=a+=1);b[n]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOlFHK8k22dbIOlnb1rA8IzMnVSPJxiZRSytZO1lLK9E62cbYqKbG2Mgu2TYRqELTOik6L7b2f4FCWrRBLBeIMoJQhqax/wE "Ruby – Try It Online")
] |
[Question]
[
# Context
If `a0` and `b0` are two decimal numbers, with `a` and `b` representing the decimal expansion of all digits but the least significant one, then we know that
$$\frac{a0}{b0} = \frac{a{\not\mathrel0}}{b{\not\mathrel0}}= \frac{a}{b}$$
# Phony fraction
A *phony fraction* is a fraction where the numerator and denominator share a digit (other than a 0 in the units place) and, when that digit is erased from both numerator and denominator, the simplified fraction happens to be equal to the original one.
## Example
\$16/64\$ is a *phony fraction* because if we remove the \$6\$, we get \$16/64 = 1{\not\mathrel6}/{\not\mathrel6}4 = 1/4\$, even though the intermediate step of removing both sixes is wrong.
# Task
Given a fraction, determine if it is *phony* or not.
## Note
Notice that `10/20` is not a *phony fraction*. Even though `10/20 = 1/2`, the simplification here was mathematically sound, you divided numerator and denominator by `10`, which amounts to "crossing out a 0 on the num. and the den.".
On the other hand, `102/204 = 12/24` is a phony fraction, because supposedly we can't cross out the 0s.
Because of this, when the input fraction is such that crossing out 0 gives an equivalent fraction to the original, the behaviour is unspecified.
# Input
The fraction we care about, with positive numerator and denominator, in any sensible format. Some examples of sensible formats include:
* a list `[num, den]` or `[den, num]`
* a string of the form `"num/den"`
* the exact fraction, if your language supports it
* two different arguments to your function
Assume both are greater than 9. You can also assume the denominator is strictly larger than the numerator.
# Output
A Truthy value if the fraction is *phony* and a Falsy value if it is not.
# Test cases
(Please keep an eye out for the comments, as some people have really nice test case suggestions! I'll edit them in, but sometimes I don't do it immediately.)
## Truthy
```
69/690 = 9/90
99/396 = 9/36
394/985 = 34/85
176/275 = 16/25
85/850 = 5/50
59/295 = 5/25
76/760 = 6/60
253/550 = 23/50
52/520 = 2/20
796/995 = 76/95
199/796 = 19/76
88/583 = 8/53
306/765 = 30/75
193/965 = 13/65
62/620 = 2/20
363/561 = 33/51
396/891 = 36/81
275/770 = 25/70
591/985 = 51/85
165/264 = 15/24
176/671 = 16/61
385/781 = 35/71
88/484 = 8/44
298/596 = 28/56
737/938 = 77/98
495/594 = 45/54
693/990 = 63/90
363/462 = 33/42
197/985 = 17/85
462/660 = 42/60
154/451 = 14/41
176/374 = 16/34
297/990 = 27/90
187/682 = 17/62
195/975 = 15/75
176/473 = 16/43
77/671 = 7/61
1130/4181 = 130/481
```
## Falsy
```
478/674
333/531
309/461
162/882
122/763
536/616
132/570
397/509
579/689
809/912
160/387
190/388
117/980
245/246
54/991
749/892
70/311
344/735
584/790
123/809
227/913
107/295
225/325
345/614
506/994
161/323
530/994
589/863
171/480
74/89
251/732
55/80
439/864
278/293
514/838
47/771
378/627
561/671
43/946
1025/1312
```
You can check [this reference implementation](https://tio.run/##bVPBjpswEL37K6ac7MTdgnKIgsoe@wPdWxRFbBiKo2CQAWVXUb49nTGGZNNKJLZnnh9v3gztZ181dnW7la6pweW2oMXUbeN66KqhLE@ooUMstE8a2ws@ydVaCVFgCabbt8TwKTtLwEKlAsrGgdFwqHJaLaAdanR5jwThNJhyzGUZRHHEETg0tjd2wIcs3ewKnzxCRtsXYwv8kJxTHLV43hMz5UgUUW9Ts1vSYpZJupsRBdoJUWzTIyGK7XFG0Lti@JZNXAuPzqaLCwp5AeCwH5yFNzeQGwGsJ5gAPHXIwAD7ldNZQ0yPEGyOwY5EbHdCsDUsmoojO/@gTGKdxHHMvnSstOudJIAaXWQ9M5TCy2RGkyMBTiAuxnfhX3Vc/VOLRpN9yJcXJL7kbYu2kJLfpJlVy4ktkCmlvlRUepUla5yigZn5Ds1AvpeKLU2o@NZxH8rorUKHkNPvckIrA1xdZ46z6SvgQuHVW/DKnkUqEKiJKfrd1DhdSikfBnZm9HaP5YCvB@SzPUo9iN@mq/WOLJmEXgh5/XEh2JWqvYS7FAmXr9FdyyJarOK7xEeFtrHfH1R6W4gvFjn9v/vduTInhDHzE1ZrEjGGcjbvnduUa48NX6FM9GazUfrpLGAqlqC1sZJvEarOP8atENOg7On5Mhxh8vQ8VMRG3bRNf5@V/zgT8TyNypfUZ1bKZd1ufwE) that I used to generate some *phony fractions* by brute-force.
---
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]
# [J](http://jsoftware.com/), 22 bytes
```
%&".e.=/#&,%/&(1".\.])
```
[Try it online!](https://tio.run/##ZVRNbxQxDL33V0SLukOldjqOkziu1AMgcQH1wBkOVdkKECoSEvz9JTt27DBbaVXpTWy/Dyc/jrt5eg73d2EK12EJd@13M4d3nz6@P17ud/Nhvr99tb@@vN2/ht38ef5ydby6ODx9@xWmwlN4Pv1bJkVYEOTSEeS0Qlxzh4DKCkUyqH08ITVbpyydItsZraJiZ2LGFcpDWRQkGkIsdeydQGmS06xV6ioa8aXPG@pkHjtUZF7xeViUVAH3QFpVNuikfe1Og2I4c6rIqVjS1rxC3l7dowobOalaXWRV6JoJSQZi7VDirKessHTRfCYxNfVmDW3Jp@6NBwZZliFl2OpBGqjSdiJUgUodJgpVprPFSmQpErlb/RTgIsegGRYe3s7hw@Hv95f@/ab92eFEVRsYPUQNGD2BhdUQ16Xq68A4Rt0oo5dR0wRLBVBX2DcD1ZDcxvRC0rtXDapKgsEnFlGKzT6zrUMWOkDPzm9W0sVLxkujY99hSqxrbQNJm4Nbk6SO0GLKVaEh3yieVlcYo7ICcwsW2j4KMQpRjNknZvXUIstLfwP8HhXQwiGMZXsqV5XokQGB3i1/YpL64A8TqGhzJusLZ0UJe2tffF22yM4JtPdwR0lfDve4L2mzrC9uVn2nzV93/M3vl8c/P7/adJHa8g3/fb44/gM "J – Try It Online")
quick explanation for now:
1. take the input as strings
2. `%/&(1".\.])` creates a function table `%/` whose axes are the integer `".` lists formed by the 1-outfixes `\.` (remove 1 digit at a time) of both args, and whose cells are the quotients of those numbers
3. `=/` forms a corresponding function table of the same shape, which acts as a boolean mask which is only `1` when corresponding "removed" digits are equal
4. `#&,` Flattens `,` both function tables into lists and uses the boolean mask to filter `#` the quotients, since cancelling is only valid when the digits are equal
5. `%&".` the true quotient of the inputs after converting to ints
6. `e.` is that true quotient an element of the filtered list from step 4.
[Answer]
# [Python 3](https://docs.python.org/3/), 86 bytes
```
lambda a,b:g(a)&g(b)
g=lambda s:{(int(s[:i]+s[i+1:])/int(s),x)for i,x in enumerate(s)}
```
[Try it online!](https://tio.run/##RVLBbtswDL3zK3xabTQYJVEUpQA9ttddhl26HpzNbYylSeA4WIth3549OQV2sSLy6b3Hxxzf5@1hL5fnu@@XXf@6@dk3/Wqzfmn77tNLu@no5e6jfFr/acf93J4e1@PT7elxvPXrp46XUrd6654PUzOu3ppx3wz78@sw9fOAzt/L7@24G5qv03lYUzNP7/g2QB2bu/o9z21XC1C9Fj6fjrtxbm/4Zqkfp6rw3KLfoTC8/RiOc/Ot352H@2k6TOsPBF7@b99/efhobqah/3WB@LyFsPfiOPrsKRVOxVEpLCWRlMglK3lLHEwpK2d1pIVDUULRkqOgwlqrgTU4spK4oOvBgd@UM2sWElfRtSxccKbACWhJeJw8lBLn4gkqbFYl/FU5KYcUFwfJgIMFg0@wxhwpFLBDxMS4SKZYFPeIMaBSrvQxBajaQherLDx7jRzVL7RilccWvM/GKVe8crHr4NGEzBb1h353qnG5oOzFB4L1pREhFxNFy7hGEsFUAreuQB4ykM2VNgSEIKSCaXwiL8gM0wrk1RVSQ/y5UMa7AnqfHEs22Klnxp7qGIg8IhXoYYqC0CwWhBfIgPJQjZFNlDTjrEMFYTBSCHjtBfZt2V/AFBIUeIWbSOrq5pA1hpJQXbrlrhn0cO3NI3RsOEINa/dQQQT4TzgEUDEIEgmEgrceoLoQwzphqQYT7B8 "Python 3 – Try It Online")
*-8 bytes thanks to ovs*
Making use of the fact that the boolean value for `a0/b0==a/b` is equivalent to `a0/a==b0/b`. The helper function `g` generates all ratios `a0/a` and keeps track of the removed digit. Then it does the same for `b0/b`. The main function determines the intersection of the two sets.
Returns a non-empty set (boolean True in Python) if a match is found, and an empty set (boolean False in Python) otherwise.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~26~~ ~~23~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
€æ`âεR*Ë9ݺIJySõ.;å*}à
```
-3 bytes thanks to *@Grimmy*.
Input as a pair `[numerator, denominator]`.
[Try it online](https://tio.run/##ATYAyf9vc2FiaWX//@KCrMOmYMOizrVSKsOLOcOdwrpJSnlTw7UuO8OlKn3DoP//WzExMzAsNDE4MV0) or [verify all test cases](https://tio.run/##NVK7ipRRDH6VYcslyMntJMFie0sthwUVLKwsBGELGwsbO3tBBAVBttvGcv7eh9gXGZOcf7qQy3dJ8u79q9dv35w/3N1cHR4/fz1c3dydfp8fP/3Zfr3cfvx7eH66v96@xPbt9Pd0/@zuxfbw5On28/rj9v0M5@NxBswYt3CMAI6ZAYdAuGaENoGsIldwrS4NoKhMlmxWhpRBV41AqQKLCdFdmKjWqO6gzgU/anIVGaKjSTB7kmeCTWwVEzwqSgVgtsjxomwq0JRd47SeSJHmuLjEq0iRrE1vbBDsGUlo5qo6iz8utDKpNdlOISWqHaIKiOJOxraQbZ9FN5i@ZhXCLosTK7dmuzpEHiDY@nBAuT0cxTzLhcecxrltjEgt3ZYKfCET5c4KTzntYjlCznX3Wji16IiqWl7TK/JECezZOYDdWl9F3mLKZV9PcpFSeGkyet8mkZuvUct@bE0iYFzO1DNavonBm5Uo0ZDbmO3vQaTApD2rqbg86qi36KNNzOryM/acetK2RzTM@/UjCbQbUkz@kqT5iFURru6@RO6QorEw29eNLT@mhdeCqcznV@2XkLx6O8aRIpFzS7f/AQ).
**Explanation:**
```
۾ # Get the powerset of each number in the (implicit) input-pair
` # Push both lists separated to the stack
â # Create all possible pairs by taking the cartesian product
ε # Map each pair to:
R # Reverse the pair
* # Multiply it by the (implicit) input-pair
Ë # Check if both values are the same
9Ý # Push a list in the range [0,9]
º # Mirror each horizontally: [00,11,22,33,44,55,66,77,88,99]
IJ # Push the input, joined together
y # Push the pair we're mapping again
S # Convert it to a flattened list of digits
õ.; # Remove the first occurrence of those digits in the joined input,
# by replacing each first occurrence with an empty string
å # Check if what remains is in the list of doubled digits
* # And check if both that and the earlier check are truthy
}à # After the map: check if any where truthy by taking the maximum
# (after which this is output implicitly as result)
```
The `R*Ë` checks with input-pair \$[a,b]\$ and potentially reduced pair \$[c,d]\$ whether \$a×d=b×c\$ ([source](https://www.helpwithfractions.com/math-homework-helper/equivalent-fractions)).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
DḌ-Ƥż$€÷þ/Ẏċ÷/,1Ɗ
```
A monadic Link accepting a list, `[numerator, denominator]` which yields zero (falsey) if not reducible, or a positive integer (truthy) if reducible.
**[Try it online!](https://tio.run/##ATQAy/9qZWxsef//ROG4jC3GpMW8JOKCrMO3w74v4bqOxIvDty8sMcaK////WzExMzAsIDQxODFd "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##RZMxjhRBDEWv0gFho23bVWU75xatCUnQXoCUBAkQpyAk3xVCJLO791gu0vjbRY80gcfj@n7@9nx4f3//8TjevT5@e/vy4/n3m7@ffl4frn/uXn99f/p6fbhb6eXLcf0c6fgcx77vw9dl@HZZl90jFB8Ixdu6uHXEpGNdWDO2vi7Ws7pHNXtmUaAjs9xlXfqs4Ag5Q/Uo8aom9NHqYxYlJtlyS5VZEipe8QiVUSoyID6oCKPcPOOAi6c6sehGPiLPo51TDK23GEON/hM0yxJ20BSYioaMGOLmHfmsGUnmN5w2uIj1bNsSufygHka2TieC6Oylpw5ZxMOmTvRyvRnfNN1RPemJZIs8BT@@7k0Nv6WsCBySmnJz4NUbINlswQyjU7YLXKEcmQT7KhcFeH3zrFGciGVs0HQqnREYYlrYGVvxpRV1Dg0baKkPJ7wWps2xvJRRvKQiblGiksN3QzwN4pjKioYZ6pT0tOl5g8zRSbiXTsdU6Ujf8vLqBgahZk6@nfluwClHSAkHUVfbQFlnTSBL4I7/QP7eJN/VQrEF9tImPJzHozjNGi8XxWlYB8pcaMNJlUe0YQyScPhy@Qc "Jelly – Try It Online").
### How?
```
DḌ-Ƥż$€÷þ/Ẏċ÷/,1Ɗ - Link: [n, d]
D - decimal digits (vectorises)
$€ - last two links as a monad for each:
-Ƥ - for overlapping 1-outfixes (i.e. less 1 digit):
Ḍ - un-decimal
ż - zip (with digits - these are in the same order)
/ - reduce by:
þ - outer-product with:
÷ - division -> [outfixesDivided, digitsDivided]
Ẏ - tighten (to a list of pairs)
Ɗ - last three links as a monad:
/ - reduce ([n, d]) by:
÷ - division
1 - one
, - pair -> [n÷d, 1] i.e. digitsDivided must be 1
ċ - count occurrences
```
Unfortunately enumerate, `Ė`, given a number, `n`, yields `[[1, n]]` not simply the first pair `[1, n]`, which would save a byte with `...ċ÷/Ė$`.
[Answer]
# JavaScript (ES6), ~~100~~ 93 bytes
*Saved 7 bytes by using [@Jitse's method](https://codegolf.stackexchange.com/a/199759/58563)*
Takes input as `('numerator')('denominator')`. Returns a Boolean value.
```
n=>d=>(g=n=>[...n].map((x,i)=>x+-(n.slice(0,i)+n.slice(i+1))/n))(n).some(v=>g(d).includes(v))
```
[Try it online!](https://tio.run/##lVPLctpAELzzFbqxW8iKZl@zexA/QjhQCLvkwitXSCj/PZmHLCrHnBiG3p6enub9dD/dzr@mz98vdR4vj9fhUYf9OOzN20DFoeu6euw@Tp/GfLWTHfZfuxdTu9t1Ol9MT53d95dpB9b@qNaaarvb/HEx92H/ZkbbTfV8/TNebuZu7eM819t8vXTX@c0cDqm0TSr9sW0OhUpfEpe@hLYpOXINmNrGodQ5tk2Ogo6EdkW6DMAkXRd928QF4ah0UmIhSFE08BzUOTkTJHsZ2QvLAiGWonUilqQsPjF5AlVI8FykJnH0FBdZ8FSeqO9SWLdIqG95DczwrSBkgbjCalQYeiQan7kOJXJfMEmUlaeckJwqxnVsEMnqB0QyMkRYJXhcZuHKA5nqlBcemlXwaXxAcQdxVQ/ge@oD6d8swTjUthmPthn2zaupza7Zbq0Z9dN27/NUzbbdWm78rFu72fybgYCZ2UWY9@yxV5/6wgvqVF4qLyKd41OJsOjZVxDTwPPF9Q6eF4x9EQxyyLLUmTkLKE@iRXxGXVzqrBuKmRqowDcMws9eFj05hsLnFxrkl6CKA0HQi30xc71Y7GirrGqcY3YQ9dDjmmLnaJJ3UXkibyWOxF6yqylKwJhl837tx8xy1BFA4Ehp7gOr1D8GsDIRHPlfJL8HL@80EnwFV5Qb@OESP@Rw63pyKCeGRZayRCJwKNUj6HkN8OTwf6bDPv4C "JavaScript (Node.js) – Try It Online")
[Answer]
# T-SQL, 192 bytes
Returns -1 for true, 0 for false
```
WITH x as(SELECT substring(@n,number,1)b,substring(@,number,1)a,number
n FROM spt_values)SELECT~(1/~count(*))FROM x,x y
WHERE x.b=y.a AND x.b>0and 1*stuff(@,x.n,1,'')*@n=@*1*stuff(@n,y.n,1,'')
```
**[Try it online](https://rextester.com/IRKIJ44587)**
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 58 bytes
```
{[(&)] .map:{m:g/./>>.&{(.prematch~.postmatch)/.orig~$_}}}
```
[Try it online!](https://tio.run/##RVPRThwxDHz3V@xDhUCVznGc2DES9EMorSgCisT1TgdShRD8@nWcRerT2ruTyczYu787PNlx@7qc3C8Xx7er05Oz62Wzvdmfv23PH3jDl5ebk7fTzf5wt715uf39sdnvnl9mecab3eHx4ePLz/f39@Pzzevy7X7Z3O62v075@9@vfHb1o14v97vD8vT45@75aMEWZblYgqNQBGvY7NRIo3GMjlYbj07ixtWzFxSdRsfbPNu5F@rBNfrs8A1Qt/xmbIVqV@4TWnViK/c6W66FPIxjHsWpwD2Q4VOGoDAag/tQtHgqaUnqqaqwJ1o5Zi/K1skq239uNVxokmgUAk/GI2aPQgh@2H3CUaQL@fTcZXo22LGW7CjazMBc1gwMfAjBx@RDIam1jTa1tkY1IHk6qSiMXJ1DRzpFMagFoouENxSNLL3McUB2rOqb1VV9q/Dqn@rEU11LszPmVjNn6Y1bn@pQyFSr3la1mnr8k7968stwtlFXPkv@zrFOuM9scb65ruebElSv5j29i2ACTab7WSLP5gOQRppxK/IpAQfAQukYuKFWTE@pa8ZnJIpVQO4KZb0EdcdCjqCBcyHAW2EdDmX5HLgzE8BGtRyHEQxHCHkLjLWSAyW4tTV27dQHnukTawdGqmlblKR4Liv6zoptVbCZNOolNxFTNsH7VFlm3wfooVpc4BIbi/8BbFgR10od/0GhpolBxkigBs5iBEMxY8eCQVIGU52wjJkh4BzQLwUSRKX@Aw "Perl 6 – Try It Online")
Same approach as in Jitse's Python answer.
### Alternative, 75 bytes
```
{?grep {[==] $_ Z*$^m[(3,4),(0,2)]>>.join},m:ex/^(.*)(.)(.*)\s(.*)$1(.*)$/}
```
[Try it online!](https://tio.run/##RVPLbhsxDLzzK/YQFHZrmKIokWIBp//RPIq2cIoUcRIkhzYI8u3uUA7Qy4rcHVIzQ@7j/unOjoeX5cPNsju@fvn1tH9cXi92u6vl7Nvy9ePZ9eFipZu23qzKpq6vzs@3vx9u7982h8/7v3y92n5cr7brPC6f83km88lvx@fvL8vNsv35cPix4ss/n3h9cV2vlpuHp@Xu9n7/fLRgi7LsluAoFMEaNjM10mgcoyPVxqOTuHH1zAVBp9HxNms790I9uEafGb4B6pbfjK1Q7cp9QqtObOVeZ8q1kIdxzFJUBe4BDZ80BIHRGNyHIsWppCVbT1aFPdHKMXNRtk5W2f73VsOFJolGINBkPGLmCISgh90nHEGqkHfNXaZmgxxr2R1Bmx6Yy8kDQz@Y4GP2QyDJtY02ubZGNUB5KqkIjFydQ0cqRTCoBayLhDcEjSy1zHGAdpzYN6sn9q1Cq7@zE092LcVOm1tNn6U3bn2yQyCTrXo7sdXk4@/9q2d/Gc426qmfZf/OcZpwn96ivrme6psSWJ/Ee2oXwQSaTPUzhJ/NByCNNO1W@FMCCoAF0zFwQ62YnlLXtM9IFKsA3xXMegnqjoUcQQN1IcBbYR0OZnkO3JkOYKNajsMIgiOEvAXGWsmBEtzaGrt26gNn6sTaoSPVlC1KUjyXFXlnxbYqupk06iU3EVM2wftkWWbeB9qDtbhAJTYW/wO6YUVcK3X8B4WaJgYew4EaqMUIhmLGjgUDpTSmOmEZ00PAOcBfCiiISv0H "Perl 6 – Try It Online")
Same regex-based approach as in Neil's Retina answer.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
DżḌ-Ƥ$€ŒpḢ€E$Ƈ÷/€F=÷/Ẹ
```
[Try it online!](https://tio.run/##NVI9bpRBDO05xRYpHfF5PB7bikIF3AGtKGlQClq6KM02VNTQRJT0LAjRrJJ77F5kefZ8W401tt@P7Y8f7u4@n8@vn/4e91@un39cnR5@Pn39dNw/Inhz9bw7/HqJ6O0t3uOf/fn4@9/N6f7b5vrV5nT//eawe3HYIf/ufN6OoBHLe9pGkMRAINEpXBGxDWqWkSu5ZpUGtcgfpGzkT1MhnblG2jKwGBRVxUC1QnUndUn4JTtnUigqGo1GdcoA2OBSMcgjIyggs0nOF2VDqY2@ahxWHRBpzpOreyZbgLXoTYxCHFEPxV9mR/LHhbaPVppspegpqhyydurKK5nYRLa1l91o@OxVCrsMrlu6NVvVMctCnVPfZtvN8Z04IjAsJX8JaKhSMPtEbA2zShwV2OR0woIx1zgEGnSJzBq26Bk5UIKrdywkbqUrIy8R6a621jHAnngwFzVn64GJZ6uhnktT72SSjtQRTb9NyIu1NaBxquPF1rNoTUmaVq9CcXrUJc@hljUY2elnWf/UQVse2Rh7qwPqVG6aMvhTkuIAM9Mlq2sDmGGLwmKUz90aLqWE54Bbmsc1rRvo2HY55gUiWTCl/w "Jelly – Try It Online")
A monadic link taking a list of `[num, den]` and returning `1` for phony and `0` for non-phony.
## Explanation
```
D | Convert to decimal digits
$€ | For each list of decimal digits:
ż | - Zip with:
Ḍ-Ƥ | - A list of lists of digits each one with 1 removed, that has then been converted back to a list of integers
Œp | Cartesian product
$Ƈ | Keep those where the following is true:
Ḣ€ | - The heads of each list (which will be the removed digits)
E | - Are equal
÷/€ | Reduce each by dividing
F | Flatten (to remove the nested lists)
=÷/ | Equal to the original argument reduced by division
Ẹ | Any
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~109 86 81~~ 78 bytes
```
->n,d{g=->n,d{w=1;n.digits.map{|s|[s,d*(n%w+w*(n/w*=10))]}};g[n,d]&g[d,n]!=[]}
```
[Try it online!](https://tio.run/##nVLRbhpBDHzPV7iREkFC4vV6vV4XXX@EoogUBfFQigoRqhK@nc4e6g/0Hs63e2PPeOzf769/Lm/D5enbbrb@2AzXeBpkvntebzfb4@H552r/8Xn4XBxm64fJ7u70eELg08MgaTpdns/zzQI5y/vNYj3bLb8Mi@X5cneaiGjiIk2oBtdIFMEalTQKRzMSr5zdqBk3S2TBOYxw6TVRNmXrt5ktJ/KoHPgrqIFvao2tKWnq6H6tHIg1cwVaK5KrgKlyCyGwsHunkCtzNc61jAqqAwcJDp2oWlqhHKgOElfn0EYlDOeCNsAS1/KlZrD6WK50WmgWK1xMxrLqvY6PeGnOtXW8cfi18eJK7p19@s9fWs1eh8Pz4cdqN@Hv60ce/0zuvx5/vWyn8z0tAJi99fdyeb7Zvx8PdPvUn9sb2I2Gx2YKRJZKxRuOhVThhaLHFBANcRDbupicYZ2SKTyQSqJwGh4pRFsKMsfQWlBDXgjwNbE2RxM9NhLpzWNQBV6CD70HrPYSsDyTAyVgLYVdjawhdiuyMipSzsgWJUk@Tj1nY80GvEFNIUt93pgQmtLcVabxbA3loVpcMCrsRQEblkXAksmwSQkGdAzshwM5kCsA9TE6lgCSujHZ/9P2y18 "Ruby – Try It Online")
Saved some bytes by using multiplication instead of division: if `a/b==a0/b0`, then `a*b0==a0*b`.
Then stole some ideas from Jitse's excellent Python answer (upvote him!) to trim a couple of bytes off the corners.
[Answer]
# Excel (Ver. 1911), 64 Bytes
Fraction entered as a row literal of 2 strings e.x. `={"16","64"}`
```
A1 'Input: row literal of 2 strings -> ={num,den}
C1:D9 {=SUBSTITUTE(A$1#,ROW(),,1)} 'Array formula (entered with <C-S-Enter>)
E1 =SUM((C1:C9/D1:D9=A1/B1)*(A1#<>C1#)) 'Output (truthy/falsy int)
```
### Test Sample
[![test sample](https://i.stack.imgur.com/VWkJp.png)](https://i.stack.imgur.com/VWkJp.png)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~128~~ ~~126~~ 124 bytes
* Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for saving ~~two~~ four bytes.
```
P,h,o,n,_=10;i(e,s){for(n=P=1;e/P;P*=_)for(h=1;s/h;h*=_)e/P%_&&e/P%_==s/h%_&&(o=s/h/_*h+s%h,n*=!o|(e/P/_*P+e%P)*s-e*o);e=n;}
```
[Try it online!](https://tio.run/##jZM/c9swDMX3fAolPceSg8QE/4GoTu2W2UOHDL3z9Wy59lC5F3dL06/uggJlD1065QUCH394hDeP3zeb83kFezjCAOsOTXuoezg1b7vjaz10qw7bfrlqV4tu3eTSXgqn5b7d54J8ma3v78c/XSfl/F99zGq5XuwfTrM9DIvu9vi7lh4prR762apZnB77xbFp@25o388ftv3uMPTVl3qAbfPz9TD82tV3s0012y5n2@rPJxFfhzuobg9jx@f50/zj/GUO1QDVFiqtNu3NZPT830YvYvT0r9GPb4ehbt5uBCkyRDZNlszgOI7SsQdOYdRIESypTgFS0O7AYFmr0kBRqzY4CFOHhWBVEkfg0o1yD5V7UoKQnF5pssvU4oCLjhZicXFRzCMWwgiJVQsdEE1YeCWPAWz0lykilbMyBiWcCHzSFstCU8DIEbBLo/YcpK49MZPxFcdHW4jpcq3PyCUPDB58wAuCo@kuuvhgIohp8gnAdA3ek6ZDdKFHdAY8Zv4bWQVPST5l1@faOQnIoWrDQqcahSiNN4i2VnJ2ow5OQsGodSfPNYYoZ4UuGNYekg1JqpN4MhafaMAlUs1ZJ9WYk1Af6@UBvPpLEMyKQ57l7dSG5CQWYu@BXNDuJJpNIXaQCo214o5Kj4bKCuZ6AGdD8QkylSYSTF48X4hReqbJzaUekuCURJBQ9sEUTChz24BCpsBBfgL63bt8Tj2svILl4o1y0GkanmQzy3j5oawGJltc3jPbAJeM0MgY6HLC7@e/ "C (gcc) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 69 bytes
```
L$w`(.)(.*)/(.*)\1
$($`$2)*$($3$1$')*_/$($`$1$2)*$($3$')*
\b(_+)/\1\b
```
[Try it online!](https://tio.run/##PZFNjlNBDIT3PsdDJEEat//tE7DhCJEmjMSCDQuExPFD9YvEJp041fVVl3//@PPz13d5frp8fTy/HX8fl7fr5e125f1xFzoux@PQ6w2nHXJ8vt7e@ZzJ/ylmdP@4vH@58l3uH89nDucsmmGbJBvn6SCpZK2gDu5YFMM6QRhWLtIwjj1VDl1Ukzz4V@CB79TN0Ua2tnqPjQdnKifUlricAlJyjxAoXLUR8iJnsKafCbKgQ4Rq2a7eTjpwB6SseKzJJ/DbKTdlXvaeCmqddr6xyCzh7CGnrdX2qVMvXZy99cFTr4d7GVWddBFb7AK@V2PiZIb8hlxrAIICgN4GqniuURhyS5IY2sG7DKBYQ1Eouoca90agz8XWBfA@G6QdGOU63u9JyDuop3xQk1JBJaC6c1lQNM4dX43hSKq4LUay6tyUarBpQB9I4xRr7witpmC@U67zdzTskVpKUC926aBhwQKKUmD7i9y2BpWhAR3cFYh29YXFIdIuRouw1LMyxyKQXxYiiIn@Aw "Retina – Try It Online") Link includes test suite. Outputs the number of phony pairs of digit cancellations. Explanation:
```
L$w`(.)(.*)/(.*)\1
```
List all matching pairs of digits in the numerator and denominator, including overlaps.
```
$($`$2)*$($3$1$')*_/$($`$1$2)*$($3$')*
```
Cross-multiply each value with the digit removed from the other value.
```
\b(_+)/\1\b
```
Count how many times this results in the same answer, indicating that this digit cancellation was a phony fraction.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
⊙θ⊙η∧⁼ιλ⁼×IΦη⁻ξμIθ×IΦθ⁻ξκIη
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMxr1KjUEcBRGWAqBQN18LSxJxijUwdhRxNHQUoLyQzN7VYwzmxuETDLTOnJLUIpNo3M6@0WKNCRyFXUxOoFCxbCGJhqi5EUp2NUJ2hCQHW//8bGhobcJkYWhj@1y3LSQQA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for phony, nothing otherwise. Explanation:
```
θ First input as a string
⊙ Any character satisfies
η Second input as a string
⊙ Any character satisfies
ι First character
⁼ Equals
λ Second character
∧ Logical And
η Second input
Φ Filtered by
ξ Inner index
⁻ Minus (i.e. not equal to)
μ Second index
I Cast to integer
× Multiplied by
θ First input
I Cast to integer
⁼ Equals
θ First input
Φ Filtered by
ξ Inner index
⁻ Minus (i.e. not equal to)
κ First index
I Cast to integer
× Multiplied by
η Second input
I Cast to integer
Implicitly print
```
] |
[Question]
[
Before anyone says anything, [similar](https://codegolf.stackexchange.com/questions/2958/check-if-number-is-a-sum-of-consecutive-numbers-or-not) and [similar](https://codegolf.stackexchange.com/questions/5703/in-how-many-ways-can-a-number-be-expressed-as-a-sum-of-consecutive-numbers). But this is not a dupe.
---
Some positive integers can be written as the sum of at least two consecutive positive integers. For example, `9=2+3+4=4+5`. Write a function that takes a positive integer as its input and prints as its output the **longest** sequence of increasing consecutive positive integers that sum to it (any format is acceptable, though -5 bytes if the output is the increasing sequence separated by `+` as shown above. If there exists no such sequence, then the number itself should be printed.
This is code golf. Standard rules apply. Shortest code in bytes wins.
---
**Samples** (note that formatting varies)
```
Input: 9
Output: 2,3,4
Input: 8
Output: 8
Input: 25
Output: [3,4,5,6,7]
```
[Answer]
## Python, 67 bytes
```
f=lambda n,R=[1]:n-sum(R)and f(n,[R+[R[-1]+1],R[1:]][sum(R)>n])or R
```
An oddly straightforward strategy: search for the interval R with the right sum.
* If the sum is too small, shift the right endpoint of the interval up
one by appending the next highest number.
* If the sum is too large, shift up the left endpoint by removing the smallest element
* If the sum is correct, output R.
Since the bottom end of the interval only increases, longer intervals are found before shorter ones.
[Answer]
# Pyth, ~~12~~ 10 bytes
```
j\+hfqsTQ}M^SQ2
```
The code is **15 bytes** long and qualifies for the **-5 bytes** bonus. Try it online in the [Pyth Compiler](https://pyth.herokuapp.com/?code=j%5C%2BhfqsTQ%7DM%5ESQ2&input=9).
*Thanks to @Jakube for golfing off 2 bytes!*
### How it works
```
j\+hfqsTQ}M^SQ2 (implicit) Store evaluated input in Q.
S Compute [1, ..., Q].
^ 2 Get all pairs of elements of [1, ..., Q].
}M Reduce each pair by inclusive range. Maps [a, b] to [a, ..., b].
f Filter; for each pair T:
sT Add the integers in T.
q Q Check if the sum equals Q.
Keep the pair if it does.
h Retrieve the first match.
Since the ranges [a, ..., b] are sorted by the value of a,
the first will be the longest, in ascending order.
j\+ Join, using '+' as separator.
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~40~~ 32 bytes
```
{^/!'1+i@'*>-/i:&x=s-\:s:+\!1+x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6qO01dUN9TOdFDXstPVz7RSq7At1o2xKrbSjlE01K6o5eJKU7dUsFAwMlUw5AIAI+oLTw==)
*-8 bytes thanks to @ngn*
[Answer]
# Haskell, ~~49~~ 48 bytes
```
f n=[[a..b]|a<-[1..n],b<-[a..n],sum[a..b]==n]!!0
```
[Answer]
# [Jelly (fork)](https://github.com/cairdcoinheringaahing/jellylanguage), 5 bytes
```
ẆSƘ¹Ṫ
```
[Try it online!](https://tio.run/##y0rNyan8///hrrbgYzMO7Xy4c9X///@NTAE "Jelly – Try It Online") (or rather, don't)
For an extra [3 bytes](https://tio.run/##ARwA4/9qZWxsef//4bqGU8aYwrnhuapq4oCdK////zI1) (again, doesn't work on TIO), we can get a score of 3
## How it works
```
ẆSƘ¹Ṫ - Main link. Takes N on the left
Ẇ - Cast N to range and get all contiguous, non-empty sublists
Ƙ¹ - Keep those for which the following is equal to N:
S - Sum
Ṫ - Take the last (and longest) one
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 - 5 = 6 bytes
```
ɾÞS≬∑?=c\+j
```
Just like most of the other answers in golfing languages.
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvsOeU+KJrOKIkT89Y1xcK2oiLCIiLCIyNSJd)
Explanation:
```
ɾ # Range from 1 to n
ÞS # All sublists
≬ # Three element lambda
∑ # Sum
= # Equals
? # The input
c # First truthy item under function application
j # Join by:
\+ # "+"
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
⟦₁s.+?!∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZY@aGov1tO0fdSz//9/yfwQA "Brachylog – Try It Online")
### Explanation
```
⟦₁s.+?!∧
⟦₁ Inclusive range from 1 to the input number
s A consecutive sublist (trying longest sublists first)
. is the output
+ Its sum
? is the input
! Don't try any further possibilities
∧ Break unification with the output
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~73~~ ~~68~~ ~~65~~ ~~56~~ ~~43~~ ~~42~~ 35 bytes
```
Range@#/.{___,x__,___}/;+x==#:>{x}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@z8oMS891UFZX686Pj5epwKIgXStvrV2ha2tspVddUWt2v@Aosy8kmhlBV07hbRo5dhYBTUFfQeFagsdBUsdBSPT2v8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 61 41 bytes
```
h:{i{x':y}\:i:1+!x}
f:{i@*|&x=+/'i:,/h@x}
```
[Try it online!](https://ngn.codeberg.page/k#eJzLsKrOrK5Qt6qsjbHKtDLUVqyo5UoDijlo1ahV2Grrq2da6ehnOABFudIcLIHYAoiNTAHi4g/Z)
*¯20 bytes thanks to @doug*
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~27~~ 26 bytes
```
{*|(x=+/')#{y+!'x}.1+!2#x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rWqtGosNXWV9dUrq7UVlSvqNUz1FY0Uq6o5eIyUjBWMKlLU7Dk0tCx0AQyLLiAAgqmCmYK5kCekSkA+roO4A==)
Uses [doug's insight](https://chat.stackexchange.com/transcript/message/62011611#62011611) that to get a run you just need a pair of numbers.
[Answer]
# MATLAB, ~~87~~ 79 bytes
I know there is already a MATLAB answer, but this one is significantly different in approach.
```
x=input('');m=1:x;n=.5-m/2+x./m;l=max(find(~mod(n(n>0),1)));disp(m(1:l)+n(l)-1)
```
This also works on **Octave**. You can [try online here](http://octave-online.net/?s=QHPazBNGkfyhbhbdFrYAnJeGZmDvKMKYapOgHyikJRbmUTQP). I've already added the code to `consecutiveSum.m` in the linked workspace, so just enter `consecutiveSum` at the command prompt, then enter the value (e.g. 25).
I am still working on reducing it down (perhaps adjusting the equation used a bit), but basically it finds the largest value `n` for which `m` is an integer, then displays the first `m` numbers starting with `n`.
So why does this work? Well basically there is a mathematical equation governing all those numbers. If you consider that they are all consecutive, and start from some point, you can basically say:
```
n+(n+1)+(n+2)+(n+3)+...+(n+p)=x
```
Now, from this it becomes apparent that the sequence is basically just the first `p` triangle numbers (including the 0'th), added to `p+1` lots of `n`. Now if we let `m=p+1`, we can say:
```
m*(n+(m-1)/2)==x
```
This is actually quite solvable. I am still looking for the shortest code way of doing it, I have some ideas to try and reduce the above code.
---
For an input of 25, the output would be:
```
3 4 5 6 7
```
[Answer]
# awk, 51 bytes
```
{while($0!=s+=s<$0?++j:-++i);while(++i-j)r=r i"+"}$0=r j
```
The code is 56 bytes, minus 5 bytes for the output format. I had to use 4 extra bytes to produce that format, so I actually saved 1 byte. Hooray! ;)
It's actually doing the hard work of summing up starting from 1 until the sum is bigger than the input. Then it begins substracting numbers starting from 1 until the number is smaller than the input. It keeps changing the start and end number this way until it found a result, which it then prints.
## Usage example
```
echo 303 | awk '{while($0!=s+=s<$0?++j:-++i);while(++i-j)r=r i"+"}$0=r j'
```
## Output of example
```
48+49+50+51+52+53
```
I've tried this for an input of `1e12` and it gave the correct result (`464562+...+1488562`) almost immediately. Though it took a while printing it of course...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ẆS⁼¥Ðf⁸Ṫ
```
[Try it online!](https://tio.run/nexus/jelly#ARgA5///4bqGU@KBvMKlw5Bm4oG44bmq////MjU "Jelly – TIO Nexus")
If I understand correctly, this could be an (11-5=6)-byte version:
```
ẆS⁼¥Ðf⁸Ṫj”+
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~64 62~~ 51 bytes
*-2 bytes thanks to Steffan*
*-11 bytes thanks to [Razetime's tip](https://codegolf.stackexchange.com/a/251862/76162)*
```
N+Z:-numlist(1,N,A),append([_,Z,_],A),sumlist(Z,N).
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/3087yko3rzQ3J7O4RMNQx0/HUVMnsaAgNS9FIzpeJ0onPhYkUgxVEKXjp6n3/7@ltqMeF5cFmDQDk0amQAoA "Prolog (SWI) – Try It Online")
[Answer]
## [Pyth](https://github.com/isaacg1/pyth), 12 - 5 = **7 bytes**
```
j\+efqQsT.:S
```
[Test suite](https://pythtemp.herokuapp.com/?code=j%5C%2BefqQsT.%3AS&test_suite=1&test_suite_input=9%0A8%0A25&debug=0)
The existing Pyth answer uses an older version of the language; new features have been added since.
##### Explanation:
```
j\+efqQsT.:S | Full code
j\+efqQsT.:SQ | with implicit variables
--------------+----------------------------------------------------
SQ | Get the range [1, ... input]
.: | Get all substrings, sorted by length
f | Filter for T such that
sT | the sum of T
qQ | equals the input
e | Get the last (longest) element of the filtered list
j\+ | Join by "+"
```
[Answer]
# Python 2, 94 bytes
```
n=input()
r=int((2*n)**.5)
while r:
if~r%2*r/2==n%r:print range(n/r-~-r/2,n/r-~r/2);r=1
r-=1
```
Input is taken from stdin. This solution is suitable for very large inputs.
This iterates over the possible solution lengths, *r*, having *r ≤ √(2n)*, and checks for a solution explicitly. In order for a solution to exist, if *r* is odd, *n mod r* must be zero, and if *r* is even, *n mod r* must be *r/2*.
---
**Sample Usage**
```
$ echo 8192 | python sum-con-int.py
[8192]
$ echo 1000002 | python sum-con-int.py
[83328, 83329, 83330, 83331, 83332, 83333, 83334, 83335, 83336, 83337, 83338, 83339]
$ echo 1000000006 | python sum-con-int.py
[250000000, 250000001, 250000002, 250000003]
```
I've deliberately choosen examples with relatively small outputs.
[Answer]
# Octave, 89 Bytes
This is the best I could do in Octave. The algorithm is the same as xnor's.
```
x=input('');k=i=1;while x;s=sum(k:i);if s<x;i++;elseif s>x;k++;else;x=0;end;end;disp(k:1)
```
In MATLAB this would be 95 bytes:
```
x=input('');k=1;i=1;while x;s=sum(k:i);if s<x;i=i+1;elseif s>x;k=k+1;else x=0;end;end;disp(k:i)
```
In MATLAB this runs in approx 0.1 seconds for input `2000000` and 1 second for input `1000002`.
[Answer]
# PHP, 70 bytes
```
while(fmod($q=sqrt(2*$argn+(++$p-.5)**2)-.5,1));print_r(range($p,$q));
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/69c2ba6fc0aa0f2edd8b21c20b22375464bbd59c).
increments `p` until it finds an integer solution for `argument==(p+q)*(q-p+1)/2`,
then prints the range from `p` to `q`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 - 5 = 7 bytes
```
J'+msḟo=¹ΣQḣ
```
[Try it online!](https://tio.run/##ARwA4/9odXNr//9KJyttc@G4n289wrnOo1HhuKP///84 "Husk – Try It Online")
Removing the first 5 bytes for joining, it still scores the same.
## Explanation
```
J'+msḟo=¹ΣQḣ
ḣ range from 1..n
Q all possible sublists
ḟ get the first value which satisfies:
=¹Σ sum = input.
ms convert each number to string
J'+ join on '+'
```
[Answer]
# Knight, 66 bytes
```
;=i+=a 0P W;=r""!>=a+1=b a=c iW!>0c;=c-c=b+1b;=r+r+"+"bI?0cQ Or 0
```
[Try it online!](https://tio.run/##rVltc9pIEv4Mv2IgZdCASCTZW7UHFpSTtVOudezETjYfbC4WQtiqE4KThL1ex/vXs909LxoBzl3u1h8Qmnm6p/uZnu4eHPZuwvDbizgNk9U02s@Labx4eTusmyNJPKkMhcXDMloDZXF6Uxkq4rnATKNZnEYsSViySG/oo65HP55@esfc8vXi4znzytffDs7ZXvl6dPqG/Vy@nn9ibgk@OrkwsKefTgzop9N3Bxe/WjlnFn602J/uT1zPHlzAsmIyvA0y1uGlgIkCW7WK4ZDtlXOnh59xMoVJ8ugrw@/7@2sYXIYw6CZgkoQjsIJ5fXZ2QiD8GJGTffTNMOT8rQCAvGHrXZCsIs4v0zGv18kP2JXLsX/ePDw7sr4N/LjrB8x5zz4P/KzZbAz9oOv6Exb4IYs/N4ZOOPDDXuhPuu4EEN2s2@w2J8cjJ/zAzjLmsG8cFDUHQncHlEfBnPm4yqBeB1OWQZZHFmeP9VqcFiwe1GswSmbZrDNbpSGMkHAI78V8aefL9NIb@4@O7TyBjloM6ggPTwcHXr1C9fGS3d/GRZQvgzCq1@B7ElkwDuKWMMNmzaviKr2aXWXs8elybPH@iyYnU2rxjFnaWp@1X7Q5EyrUaANGr1IY7nbFCNhZi5I8MgeehDnhbRT@i80WGUtX80mU5dIeZsX5NL6JC6UVVkd3XFt7JJ4d5jqsyzrS8m6Xsx5rO21YAi2NOcuiYpWlTAWSEKNYGqzbcBdkcTBJImUFGJEs7qPMCmE9ZQj7@pUp40J6C4mIL20u6Ym3uB77rg175OvhNevwaMoQBkg6XS0t3FImOe0xeNs0WCSKXGgTZly126VNzbbYNBAGD7RRDJRAYoHvYNkyyAtW3EagLMgKAMsN6ChGcUNDjp4oY43z9qyx8Oly2uhaSQaZj6FbxIsUzMaIdcZgWqgYyVfLJRLOVVSpEZN@M/6AdoNs1KFCeZlCHEOSw8iVlgtWPrZ1JhADRziACa@PiQ7NVEFGOVK4aqHdaGqQJIvQ2nNsl6ODOKydIAfTVZIE2YPpaLk/58b2vG9ry2hBKb9K16RpCReXkElhm6cHh6/fXH9onPxyZjhsqp3EW/V6m3obFcVvjy@e0VhEGakM0in79ypQr6j2zlxid3MJQcDbtubieAsXJLxXFa5inihVZqsUd2ggE3WnWOSWypV0ACC0izhkNDtZzS69vbG0Q2x0i9KDNiBfwrEqZhZAwf@dJJk2Vd6hQmWjknUFcCi0AlECxfoV3D5zd6t@ovMYiyPWLLJV1IQY1OMYkjA@CyCD4EQTI6tZkoB@ou@yVhEdX14vFgnMTKoMPOtr6db3HOr8uEemmZMNMxO0Mf1bbYSgLRZJYpmm2syxoUL8DyanGyZjFX538P7UxlosAg1ejy9dx3EgnMAVeFVvefxH9KVg@BgYMWp4iwzAm40fHn3u@q4q6ZjhsKrjgz498dgFwNHxyWGHzSA5Dmo6tOV6mIbDYGknUUodgMGVaqUEZ3DuniNjXRBrE5Y2LDhWTL0E1OJ94mIARSXGSZ03wvlybQeIpHhcphCkKR7jMvl9XIS3VgeY2ei8gCMm/0KsU@2Ddp/hKgLgI6HYu0EW5i1ySqqX3WMlZPmAqnCJoBa1yLB0UZd6OeaPZZhBA0W5XSx8DgtXdWeQ8Szecn6f4V@JfA9I0Co4uomKBBpMq0V72cIdwhI5jVM@iGeWRfuJDUF4m6EtNsQp52KbfWew1VZ4cGoDxHqHYj3ROWI2kIQMlL1IksydpZWvS38EXs@8KWdQ0qRYY64Bg9EA8ecvF8sotYyF7WbWpFYBrPLnolJCPPqes/czjcvmwhIdyQxMn6JT0MJByNrY3wEcegd6wzVgaRVeFgyyrk@tEJ5YQHJJN@ihtYhq1NDxmWf2LCWNpScfwJPod2jj8LRv@Nmo7DrdIxqYyTaAJxvhAaskVV4M@C/tvuwTtwSyznyyAjVPqS22sAZxVYSGwz1eNpYb6VCJXlBzaO3kKFg9DJvCQCe0Pua6kEl5s4SqCSwvUZBKtc@VMFmzzB2QuUWycFaygAdDXHyQNLGfFepYq0WXr14PoWPR5l5Ru11TZu287ORgjwVvnKmjlhnmr4pc7b6OCdHrCYO62iDKk5AvMSVjaBnbI7rpWnW3xU0W0dD3MxVLnthz7H/pMIgNIBQO4yn3lZce3x6qYVCoh@w63W5JE1ffUReHbtSmZyFzhPSrtxGdRrRjq161Vwh1yt3ZwsJ6ed7CQ2eDB7Gv21iYb3GtQxjfVEICUIMsypB@@woueQga9HqkTxJFJXN9owWjReX0v/ouMa@2E7PzXaGd7UL/JDYrDomrA415ppcDSbtg3Wc9V7NMWKDehXPWc@GMuSbY@0H0PqTHCtb3EUrr9tWIoygnor2hI7n2OLUrHZ/4r68fCJokV@COQAkWSwx8xyvDbZRF7ZylC@ih46SIU3YfPABvbLqAO2kR3UQZyCwXaZQWcYC3CDjJC3YfsdvgLgKgVITwgs2DdAXh8/ASR9G7CTIOVBAT@Sop8EcDWlwnPAXpmRi15BplppyGrKlHfc8jnecN0bD9Csqh@3mQYG18AK/TaRJN2XVp9rXW8ojfRGNmLFI6M0RlvZ565wSvSWjHMP1J58F9Cta1wodJr5IX/WpWHDHz8O@bxwBF@/I3uhYTgBGrNIo0aDMjG6IOR0iqkuuJOoDYhg/VxuiChnAoMbQW00WfzaN5uMQwS9nwevT/ujL8G1wZKlcaW3zxpS/SldHz7ItVt5iM0yNWAXga4akC2thmZ/mi3VOZx1SgzWuV6Q992VYbRqakTCVa/ut/Iy9zkKFGyw/afRNdaXPXsX6ZdavTP3yRUb1teZNBXK1ym9GpkDCocexXpI00iRKI6Ha1mDD5M7gnfvUyG82Kd8zsXaTYcbVrR6ghP/L6uwYtb8WVwTc6rK5ZgDbvSKm8eNj6LOxWGtoLQfSa0sF6yfO2lbxdrvsAT0vv0eB/aIjQMHziVoS6@dftkNkbeeAhrtp1sUmiBkHEv5ikByG68iTA6tNoFkCSBM9UhxmnMBlP6UekICygTLV3wjb2nDjC2TO3WFSmayB0g/KHhHkQp9issiC7CW1S2unA9zuOP1fR/RL/5WM5ZE31Gvf07R9/AQ "C (gcc) – Try It Online")
Annotated code:
```
;=i+ =a 0 PROMPT # set a to 0, i to input
WHILE ;=r "" !>(=a +1(=b a)) (=c i) # set r to "", b to a, a to a+1, c to i, check if a less than c
WHILE !< c 0 # while c >= 0:
;=c (-c (=b +1b)) # set b to b+1, c to c-b
;=r (+ r + " " b) # append b to r
IF (? c 0) (QUIT OUTPUT r) 0 # if c is 0, output r and break; else, do nothing
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 - 5 = 6 bytes
Taking that bonus of course :)
```
LŒʒOQ}é¤'+ý
```
[Try it online!](https://tio.run/nexus/05ab1e#@@9zdNKpSf6BtYdXHlqirn147///RqYA "05AB1E – TIO Nexus")
```
LŒʒOQ}é¤'+ý Argument: n
LŒ Sublists of range 1 to n
ʒOQ} Filter by total sum equals n
é¤ Get longest element
'+ý Join on '+'
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 72 bytes
```
L/X/H:-between(L,H,X).
N*Z:-1/A/N,A/X/N,findall(Y,A/Y/X,Z),sumlist(Z,N).
```
[Try it online!](https://tio.run/##DcqxCoAgFEDRva9w1Hj2KGhpCbeGcDa3IgvBNNLo883xHu79BBdOHj@b84wKp4FvJn3GeDrDBIo1laz1wFsUKEGUQ8Jh/b46R5fSCyrQDOJ7ORsT1SBZk0dOup7URAC5H@sTFQV/ "Prolog (SWI) – Try It Online")
-4 bytes thanks to DLosc.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 66 bytes
```
i,j;f(n){for(i=j=0;n;)n+=n>0?--j:++i;for(;i+j;)printf("%d ",++i);}
```
Inspired by xnor's sliding window solution, keeps track of the ends of the window.
[Try it online!](https://tio.run/##TU5LDoMgEF3DKQhNGwjS2G0p9iwGtA6xo/HTLoxnp@Cqs3mTeb9x@uVcjFAE0wqUWztMAmywpUEjUVmsyqfW4a4UmMwZUMHIcQJcWsHPnvEiUdLs8QTo@tU37DEvHoZrV1GaVPRdA4rPAF7SjZJ0YWgo@XbQN2J2NR4xvGAXlMxadpMsychfg65SCUOZXCT/mHFcl1lwnved7vFWHvMD "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), (10-5=) 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Åœ.Δ¥P}'+ý
```
[Try it online](https://tio.run/##yy9OTMpM/f//cOvRyXrnphxaGlCrrn147///RqYA) or [verify all test cases](https://tio.run/##AS4A0f9vc2FiaWX/dnk/IiDihpIgIj95/8OFxZMuzpTCpVB9JyvDvf8s/1s5LDgsMjVd).
**Explanation:**
```
Ŝ # Get all lists of positive integers that sum to the (implicit) input,
# which is sorted from longest (all 1s) to shortest (just the number)
.Δ # Find the first list which is truthy for:
¥ # Get the deltas/forward-differences of the list
P # Take the product (only 1 is truthy in 05AB1E)
}'+ý '# After we've found a list: join it with "+" delimiter
# (after which it is output implicitly as result)
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 10 - 5 = 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
RƑæS=;h'+j
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPVIlQzYlOTElQzMlQTZTJTNEJTNCaCclMkJqJmZvb3Rlcj0maW5wdXQ9OSZmbGFncz0=)
Port of tybocopperkettle's Vyxal answer.
#### Explanation
```
RƑæS=;h'+j '# Implicit input
RƑ # All sublists of [1..n]
æ ; # Filtered by:
S= # Sum equals input
h # First item
'+j '# Joined by "+"
# Implicit output
```
[Answer]
# [Japt](https://github.com/ETHproductions/Japt), 33 bytes
This uses [Dennis's Pyth technique](https://codegolf.stackexchange.com/a/66222/42545), although it's considerably longer...
```
1oU à2 £W=Xg o1+Xg1¹x ¥U©W} rª ªU
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=MW9VIOAyIKNXPVhnIG8xK1hnMbl4IKVVqVd9IHKqIKpV&input=MTg=) **Warning:** For larger inputs (<= 20), it takes a while to finish, and freezes your browser until it does.
### Ungolfed and explanation
```
1oU à2 £ W=Xg o1+Xg1¹ x ¥ U© W} rª ª U
1oU à2 mXYZ{W=Xg o1+Xg1) x ==U&&W} r|| ||U
// Implicit: U = input integer
1oU à2 // Generate a range from 1 to U, and take all combinations of length 2.
mXYZ{ // Map each item X in this range to:
W=Xg o // Set variable W to the range of integers starting at the first item in X,
1+Xg1) // and ending at 1 + the second item in X.
x ==U&&W // If the sum of this range equals U, return W; otherwise, return false.
r|| // Reduce the result with the || operator, returning the first non-false value.
||U // If this is still false, there are no consecutive ranges that sum to U,
// so resort to U itself.
// Implicit: output last expression
```
Bonus-earning version: (38 bytes - 5 = 33)
```
1oU à2 £W=Xg o1+Xg1¹x ¥U©W} rª ªU² q'+
```
[Answer]
# Julia, 92 bytes
```
x->(t=filter(i->all(j->j==1,diff(sort(i))),partitions(x));collect(t)[indmax(map(length,t))])
```
This is an anonymous function that accepts an integer and returns an array. To call it, give it a name, e.g. `f=x->...`.
Ungolfed:
```
function f(x::Integer)
# Get all arrays of integers that sum to x
p = partitions(x)
# Filter these down to only consecutive runs by checking whether
# all differences are 1
t = filter(i -> all(j -> j == 1, diff(sort(i))), p)
# Find the index of the longest element of t
i = indmax(map(length, t))
return collect(t)[i]
end
```
[Answer]
# Ruby, 94 bytes
```
->n{([*1..n].permutation(2).map{|i,j|[*i..j]if(i..j).reduce(:+)==n}-[p]).max_by{|k|k.size}||n}
```
**Ungolfed:**
```
-> n {
([*1..n].permutation(2).map { |i,j| # Finds all the possible sets of size 2
[*i..j] if(i..j).reduce(:+) == n # Adds a set to an array if sum of the set is n.
}-[p] # Removes nil from the array
).max_by { |k| # Finds the longest sequence
k.size
} || n # Returns n if no sequence found.
}
```
**Usage:**
```
->n{([*1..n].permutation(2).map{|i,j|[*i..j]if(i..j).reduce(:+)==n}-[p]).max_by{|k|k.size}||n}[25]
=> [3, 4, 5, 6, 7]
```
[Answer]
## Seriously, 53 - 5 = 48 bytes
```
,;;;╝`;u@n╟(D;)`n(XXk`iu@u@x;Σ╛=[])Ii`╗`ñ╜M`M;░p@X'+j
```
Hex Dump
```
2c3b3b3bbc603b75406ec728443b29606e2858586b60697540754
0783be4be3d5b5d29496960bb60a4bd4d604d3bb0704058272b6a
```
[Try It Online!](http://seriouslylang.herokuapp.com/link/code=2c3b3b3bbc603b75406ec728443b29606e2858586b606975407540783be4be3d5b5d29496960bb60a4bd4d604d3bb0704058272b6a&input=15)
It's the brute force approach, similar to Dennis's Pyth.
Everything up to the `k` just reads input `n` into register 1 and then creates the list `[[1],[2,2],[3,3,3],[4,4,4,4],...]` up to `n` `n`'s.
The next bit up to `╗` is a function stored in register 0 that takes a pair, increments both elements, converts them to a range, finds the sum of the range, and checks whether that sum is the value in register 1. If it is, it returns the corresponding range, and if it's not, it returns an empty list.
The part up to the last occurrence of `M` maps a function over the fancy list of lists described above, doing `enumerate` on each list, then mapping the stored function over it. When it is done, we have a list of lists each of which is empty or a range which sums to `n`.
`;░` removes the empty lists. `p@X` takes the first list which remains (`0@E` would also work). `'+j` puts `+` between each number as it converts the list to a string for the bonus.
[Answer]
## ES6, 72 bytes
```
n=>{for(l=u=1;n;)n>0?n-=u++:n+=l++;return[...Array(u).keys()].slice(l);}
```
Straight port of @Cabbie407's awk solution, but without the formatting bonus, since it's a penalty here.
] |
[Question]
[
Write the shortest program that solves Rubik's cube (3\*3\*3) within a reasonable amount of time and moves (say, max. 5 seconds on your machine and less than 1000 moves).
The input is in the format:
```
UF UR UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR
```
(this particular input represents the solved cube).
First 12 2-character strings are the edges in the UF, UR, ... BL positions (U=up, F=front, R=right, B=back, L=left, D=down), then the next 8 3-character strings are the corners in the UFR, URB, ... DBR positions.
The output should give a sequence of moves in this format:
```
D+ L2 U+ F+ D+ L+ D+ F+ U- F+
```
Where D1 or D+ represents turning the D (down) face clockwise 90 degrees, L2 is turning the L face 180 degrees, U3 or U- represents turning the U face counterclockwise 90 degrees.
Letters are case-insensitive and spaces are optional.
For example, the output above is correct for the following input:
```
RU LF UB DR DL BL UL FU BD RF BR FD LDF LBD FUL RFD UFR RDB UBL RBU
```
For more details, please refer to [Tomas Rokicki's cube contest](http://tomas.rokicki.com/cubecontest/), except scoring will be done directly by file size like a normal code golfing problem. An [online tester](http://tomas.rokicki.com/cgi-bin/cube-gen.pl) is included too.
For reference, the shortest solution already written is the last entry in the list of [cube contest winners](http://tomas.rokicki.com/cubecontest/winners.html)
---
For those struggling to visualise the layout format:
```
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-25-26 27-28-29 30-31-32 33-34-35 36-37-38 39-40-41 42-43-44 45-46-47
UF UR UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR
Front:
+-------+-------+-------+
/ / / /|
/ 30 / 4 / 27 / |
+-------+-------+-------+ |
/ / / /|28+
/ 6 / / 2 / | /|
+-------+-------+-------+ |/ |
/ / / /|3 + |
/ 33 / 0 / 24 / | /|21+
+-------+-------+-------+ |/ | /|
| | | |26+ |/ |
| 35 | 1 | 25 | /| + |
| | | |/ | /|47+
+-------+-------+-------+ |/ | /
| | | |17+ |/
| 18 | | 16 | /|11+
| | | |/ | /
+-------+-------+-------+ |/
| | | |37+
| 40 | 9 | 38 | /
| | | |/
+-------+-------+-------+
Hidden faces:
+-------+-------+-------+
/| | | |
/ | 31 | 5 | 29 |
+ | | | |
/|32+-------+-------+-------+
/ | /| | | |
+ |/ | 22 | | 20 |
/|7 + | | | |
/ | /|23+-------+-------+-------+
+ |/ | /| | | |
|34+ |/ | 44 | 13 | 46 |
| /| + | | | |
|/ | /|43+-------+-------+-------+
+ |/ | / / / /
|19+ |/ 42 / 12 / 45 /
| /|15+-------+-------+-------+
|/ | / / / /
+ |/ 14 / / 10 /
|41+-------+-------+-------+
| / / / /
|/ 39 / 8 / 36 /
+-------+-------+-------+
```
[Answer]
# C++ - 1123
Since nobody posted any answer so far, I decided to simplify and golf my 2004 solution. It's still far behind the shortest one I mentioned in the question.
```
#include<iostream>
#include<vector>
#define G(i,x,y)for(int i=x;i^y;i++)
#define h(x)s[a[x]/q*q+(a[x]+j)%q-42]
#define B(x)D=x;E=O.substr(j*3,3);G(i,0,3)E+=F[5-F.find(E[2-i])];G(i,0,D.length())D[i]=E[F.find(D[i++])];m.push_back(D);
#define P(a,b)G(i,0,6)G(k,49,52){e[0]=F[i];e[1]=k;m.push_back(e);}G(j,0,24){B(a)B(b)}
#define T C();z=m.size();for(b=c;b;){d=s;G(i,o=w=1,4){w*=z;if(o)G(j,0,w)if(o){s=d;u=j;G(k,0,i){f=m[u%z];G(x,0,f.length()){a=M[F.find(f[x++])];G(i,0,f[x]-48)G(l,0,2){q=3-l;p=4*l;G(j,0,q){t=h(p+3);G(k,-3,0)h(p-k)=h(p-1-k);h(p)=t;}}}u/=z;}C();if(c<b){u=j;G(k,0,i){std::cout<<m[u%z];u/=z;}b=c;o=0;}}}}
std::string s,a,D,E,d,f,e=" ",S="UFURUBULDFDRDBDLFRFLBRBLUFRURBUBLULFDRFDFLDLBDBR",F="ULFBRD",M[]={"KHEB*0.,","KRTI0<8@","KDNS*;2=","IVXG/@7>","BGWP,>4:","QNWT2468"},O=S.substr(24)+"FDRFRUFULFLDRDBRBURUFRFDBDLBLUBURBRDLDFLFULUBLBD";std::vector<std::string>m;int
w,X=8,Y=16,o,c,u,b,z,p,q,t;void C(){c=0;G(i,X,Y)c+=s[i]!=S[i];}main(int
g,char**v){G(i,1,g)s+=v[i];P("U2F1R1L3U2L1R3F1U2","L3R1F3L1R3D2L3R1F3L1R3");T;Y=24;T;X=0;T;m.clear();P("R3D3R1D3R3D2R1L1D1L3D1L1D2L3","R1F3L3F1R3F3L1F1");G(I,5,9){Y=I*6;T}}
```
It's not random, but it also doesn't proceed straightforwardly. It solves the edges first, then the corners. At each step, it tries various combinations of up to 4 algorithms and simple face turns (sequentially, not randomly), till it finds an improvement in the number of solved pieces, then repeats until solved. It uses 2 algorithms for edges and 2 for corners, translated to all cube positions.
Example output for `RU LF UB DR DL BL UL FU BD RF BR FD LDF LBD FUL RFD UFR RDB UBL RBU`:
L2F3B2F3B1U3F1B3R2F3B1U3F1B3D2F2L3D2L1U2B1L1R3U2R1L3B1U2R1U2L1F1B3U2B1F3L1U2L3R1D3L1R3B2L3R1D3L1R3L3R1D3L1R3B2L3R1D3L1R3B3F1D3B1F3R2B3F1D3B1F3U2F3L3R1B3L1R3U2L3R1B3L1R3F1D2F1L1R3D2R1L3F1D2F3L2U1B1F3L2F1B3U1L2R3L1F3R1L3U2R3L1F3R1L3U1F2U1L1R3F2R1L3U1F2U3L3U3L1U3L3U2L1R1U1R3U1R1U2R3F3U3F1U3F3U2F1B1U1B3U1B1U2B3L1B3R3B1L3B3R1B1B3D3B1D3B3D2B1F1D1F3D1F1D2F3R1F3L3F1R3F3L1F1R3B3R1B3R3B2R1L1B1L3B1L1B2L3R1D3L3D1R3D3L1D1B3D3B1D3B3D2B1F1D1F3D1F1D2F3U3R3U1R3U3R2U1D1R1D3R1D1R2D3
(234 moves, 0.3 sec here)
[Answer]
## Python 1166 bytes
*A considerable amount of whitespace has been left for the sake of readability. Size is measured after removing this whitespace, and changing various indentation levels to `Tab`, `Tab` `Space`, `Tab` `Tab`, etc. I've also avoided any golfing which affected the performance too drastically.*
```
T=[]
S=[0]*20,'QTRXadbhEIFJUVZYeijf',0
I='FBRLUD'
G=[(~i%8,i/8-4)for i in map(ord,'ouf|/[bPcU`Dkqbx-Y:(+=P4cyrh=I;-(:R6')]
R=range
def M(o,s,p):
z=~p/2%-3;k=1
for i,j in G[p::6]:i*=k;j*=k;o[i],o[j]=o[j]-z,o[i]+z;s[i],s[j]=s[j],s[i];k=-k
N=lambda p:sum([i<<i for i in R(4)for j in R(i)if p[j]<p[i]])
def H(i,t,s,n=0,d=()):
if i>4:n=N(s[2-i::2]+s[7+i::2])*84+N(s[i&1::2])*6+divmod(N(s[8:]),24)[i&1]
elif i>3:
for j in s:l='UZifVYje'.find(j);t[l]=i;d+=(l-4,)[l<4:];n-=~i<<i;i+=l<4
n+=N([t[j]^t[d[3]]for j in d])
elif i>1:
for j in s:n+=n+[j<'K',j in'QRab'][i&1]
for j in t[13*i:][:11]:n+=j%(2+i)-n*~i
return n
def P(i,m,t,s,l=''):
for j in~-i,i:
if T[j][H(j,t,s)]<m:return
if~m<0:print l;return t,s
for p in R(6):
u=t[:];v=s[:]
for n in 1,2,3:
M(u,v,p);r=p<n%2*i or P(i,m+1,u,v,l+I[p]+`n`)
if r>1:return r
s=raw_input().split()
o=[-(p[-1]in'UD')or p[0]in'RL'or p[1]in'UD'for p in s]
s=[chr(64+sum(1<<I.find(a)for a in x))for x in s]
for i in R(7):
m=0;C={};T+=C,;x=[S]
for j,k,d in x:
h=H(i,j,k)
for p in R(C.get(h,6)):
C[h]=d;u=j[:];v=list(k)
for n in i,0,i:M(u,v,p);x+=[(u[:],v[:],d-1)]*(p|1>n)
if~i&1:
while[]>d:d=P(i,m,o,s);m-=1
o,s=d
```
Sample usage:
```
$ more in.dat
RU LF UB DR DL BL UL FU BD RF BR FD LDF LBD FUL RFD UFR RDB UBL RBU
$ pypy rubiks.py < in.dat
F3R1U3D3B1
F2R1F2R3F2U1R1L1
R2U3F2U3F2U1R2U3R2U1
F2L2B2R2U2L2D2L2F2
```
This is an implementation of Thistlethwaite's Algorithm, using an IDA\* search to solve for each step. Because all of the heuristic tables need to be calculated on the fly, several compromises have been made, usually breaking a heuristic into two or more fairly equal size parts. This makes the computation of the heuristic tables many hundreds of times faster, while slowing down the search phase, usually only slightly, but it can be significant depending on the initial cube state.
### Variable Index
* `T` - the main heuristic table.
* `S` - a solved cube state. Each individual piece is stored as a bit mask, represented as a character. A solved orientation vector is defined as the zero vector.
* `I` - the various twists, in the order that they are eliminated from the search space.
* `G` - the groups for twist permutations, stored as pairs to be swapped. Each byte in the compressed string encodes for one pair. Each twist needs six swaps: three for the edge cycle, and three for the corner cycle. The compressed string contains only printable ascii (char 32 to 126).
* `M` - a function that performs a move, given by G.
* `N` - converts a permutation of four objects to a number, for encoding purposes.
* `H` - calculates the heuristic value for the given cube state, used to lookup move depth from T.
* `P` - perform a search at a single depth of a single phase of the algorithm.
* `s` - the input cube's permutation state.
* `o` - the input cube's orientation vector.
---
## Performance
Using [Tomas Rokicki's data set](http://tomas.rokicki.com/cubecontest/testdata.txt), this script averaged 16.02 twists per solve (maximum 35), with an average time of 472ms (i5-3330 CPU @ 3.0 Ghz, PyPy 1.9.0). Minimum solve time was 233ms with a maximum of 2.97s, standard deviation 0.488. Using the scoring guidelines from the contest (white space is not counted, keywords and identifiers count as one byte for a length of 870), the overall score would have been 13,549.
For the last 46 cases (the random states), it averaged 30.83 twists per solve, with an average time of 721ms.
---
## Notes on Thistlethwaite's Algorithm
For the benefit of anyone who might want to attempt an implementation of [Thistlethwaite's Algorithm](http://en.wikipedia.org/wiki/Morwen_Thistlethwaite#Thistlethwaite.27s_algorithm), here is a brief explanation.
The algorithm works on a very simple solution space reduction principle. That is, reduce the cube to a state in which a subset of twists are not necessary to solve it, reduce it to a smaller solution space, and then solve the remainder using only the few twists remaining.
Thistlethwaite originally suggested `<L,R,F,B,U,D>` → `<L,R,F,B,U2,D2>` → `<L,R,F2,B2,U2,D2>` → `<L2,R2,F2,B2,U2,D2>`. However, given the input format, I think it is easier to first reduce to `<L,R,F2,B2,U,D>` (no quarter turn `F` or `B`), and then `<L2,R2,F2,B2,U,D>` before finally reaching the half turn state. Instead of explaining exactly why this is, I think it will be evident after defining the criteria for each state.
### `<L,R,F,B,U,D>` ⇒ `<L,R,F2,B2,U,D>`
In order to eliminate `F` and `B` quarter turns, only the edges must be oriented correctly. Gilles Roux has a [very good explanation on his site](http://grrroux.free.fr/method/Step_4.html) of what 'correct' and 'incorrect' orientation is, so I'll leave the explaining to him. But basically, (and this is why this input format is so condusive to `F` and `B` elimination), an edge cubie is correctly oriented if it matches the following regex: `[^RL][^UD]`. A correct orientation is typically signified with a `0` and incorrect with `1`. Basically `U` and `D` stickers may not appear on the `R` or `L` faces, or on the edges of the any `U` or `D` edge cubies, or they cannot be moved into place without requiring an `F` or `B` quarter twist.
### `<L,R,F2,B2,U,D>` ⇒ `<L2,R2,F2,B2,U,D>`
Two criteria here. First, all corners must be oriented correctly, and second, each of the for middle layer cubies (`FR`, `FL`, `BR`, `BL`) must be somewhere in the middle layer. A corner orientation is very simply defined given the input format: the position of the first `U` or `D`. For example, `URB` has orientation `0` (correctly oriented), `LDF` has orientation `1`, and `LFU` has orientation `2`.
### `<L2,R2,F2,B2,U,D>` ⇒ `<L2,R2,F2,B2,U2,D2>`
The criteria here is as follows: each face may only contain stickers from its face, or from the face directly opposite it. For example, on the `U` face there may only be `U` and `D` stickers, on the `R` face there may only be `R` and `L` stickers, on the `F` face there may only be `F` and `B` stickers, etc. The easiest way to ensure this is to check if each edge piece is in its 'slice', and each corner piece in its 'orbit'. Additionally, one needs to pay attention to edge-corner parity. Although, if you check only for corner parity, edge parity is also guaranteed, and vice versa.
### How twists affect orientation
`U` and `D` twists affect neither the edge orientation, nor the corner orientation. The pieces may be swapped directly without updating the orientation vector.
`R` and `L` twists do not affect the edge orientation, but they do affect the corner orientation. Depending on how you define your cycle, the change in corner orientation will either be `+1, +2, +1, +2` or `+2, +1, +2, +1`, all modulo `3`. Note that `R2` and `L2` twists do not affect the corner orientation, as `+1+2` is zero modulo `3`, as is `+2+1`.
`F` and `B` affect both the edge orientations and corner orientations. Edge orientations become `+1, +1, +1, +1` (mod 2), and corner orientations are the same as for `R` and `L`. Note that `F2` and `B2` affect neither the edge orientations, nor corner orientations.
[Answer]
### Ruby, 742 characters
```
r=->y{y.split.map{|x|[*x.chars]}}
G=r['UF UR UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR']
o=r[gets]
x=[];[[%w{U UU UUU L LL LLL}+D=%w{D DD DDD},0],[%w{FDFFF RFDFFFRRR}+D,12],[%w{DDDRRRDRDFDDDFFF DLDDDLLLDDDFFFDF}+D,8],[%w{DFLDLLLDDDFFF RDUUUFDUUULDUUUBDUUU}+D,4],[%w{LDDDRRRDLLLDDDRD RRRDLDDDRDLLLDDD LFFFLLLFLFFFLLLF},16]].map{|q,y|x+=[*y..y+3]
3.times{q.map{|e|q|=[e.tr('LFRB','FRBL')]}}
w=->u{x.count{|t|u[t]!=G[t]}}
s=w[o]
(c=(0..rand(12)).map{q.sample}*''
z=o
c.chars{|m|z="=$'*:036\".?BOHKVGRWZ!$@*-0C69<4(E\\INQTMX!$'B-03<9*?6EHYLQPUZ!9'*-?360<$BSFKN[TWJ$'*!-0369<?BHKNEQTWZ!$'*6-039<?BEHKNTWZQ"[20*('FBLRUD'=~/#{m}/),20].bytes.map{|e|z[e/3-11].rotate e%3}}
t=w[z]
(c.chars{|e|$><<e<<'1 '};o=z;s=t)if s>t
)until s<1}
```
The above ruby code is not yet golfed fully. There are still possibilities to improve the code further (but its already enough as a starter).
It solves the cube layer by layer but uses no specific algorithm but instead performs random sequences of moves until the cube is solved.
Due to the probabilistic nature it may sometimes take longer than 5 seconds to solve the cube and in rare cases take more than 1000 moves.
Example output (for input 'RU LF UB DR DL BL UL FU BD RF BR FD LDF LBD FUL RFD UFR RDB UBL RBU') is 757 moves:
```
F1 R1 R1 F1 F1 F1 R1 R1 R1 L1 L1 L1 F1 D1 L1 L1 D1 D1 D1 D1 L1 B1 D1
B1 B1 B1 L1 L1 L1 F1 D1 F1 F1 F1 L1 D1 L1 L1 L1 B1 D1 B1 B1 B1 R1 D1
R1 R1 R1 L1 B1 D1 B1 B1 B1 L1 L1 L1 D1 D1 B1 D1 B1 B1 B1 B1 D1 B1 B1
B1 L1 D1 L1 L1 L1 D1 D1 D1 D1 D1 R1 D1 R1 R1 R1 R1 F1 D1 F1 F1 F1 R1
R1 R1 R1 D1 R1 R1 R1 F1 L1 D1 L1 L1 L1 F1 F1 F1 D1 D1 D1 D1 L1 D1 L1
L1 L1 F1 L1 D1 L1 L1 L1 F1 F1 F1 D1 D1 L1 D1 L1 L1 L1 D1 L1 D1 L1 L1
L1 L1 D1 L1 L1 L1 D1 R1 D1 D1 D1 R1 R1 R1 D1 D1 D1 B1 B1 B1 D1 B1 D1
L1 D1 D1 D1 L1 L1 L1 D1 D1 D1 F1 F1 F1 D1 F1 D1 D1 D1 B1 B1 B1 D1 B1
D1 R1 D1 D1 D1 R1 R1 R1 D1 D1 D1 B1 B1 B1 D1 B1 D1 R1 D1 D1 D1 R1 R1
R1 D1 B1 D1 D1 D1 B1 B1 B1 D1 D1 D1 L1 L1 L1 D1 L1 D1 B1 D1 D1 D1 B1
B1 B1 D1 D1 D1 L1 L1 L1 D1 L1 D1 D1 F1 D1 D1 D1 F1 F1 F1 D1 D1 D1 R1
R1 R1 D1 R1 D1 D1 D1 R1 R1 R1 D1 R1 D1 F1 D1 D1 D1 F1 F1 F1 D1 B1 D1
D1 D1 B1 B1 B1 D1 D1 D1 L1 L1 L1 D1 L1 D1 D1 D1 F1 F1 F1 D1 F1 D1 L1
D1 D1 D1 L1 L1 L1 D1 D1 D1 D1 D1 D1 F1 F1 F1 D1 F1 D1 L1 D1 D1 D1 L1
L1 L1 D1 D1 D1 F1 F1 F1 D1 F1 D1 L1 D1 D1 D1 L1 L1 L1 D1 F1 D1 D1 D1
F1 F1 F1 D1 D1 D1 R1 R1 R1 D1 R1 D1 D1 D1 F1 F1 F1 D1 F1 D1 L1 D1 D1
D1 L1 L1 L1 D1 D1 D1 F1 F1 F1 D1 F1 D1 L1 D1 D1 D1 L1 L1 L1 D1 D1 D1
D1 D1 F1 F1 F1 D1 F1 D1 L1 D1 D1 D1 L1 L1 L1 D1 D1 D1 D1 D1 D1 R1 F1
D1 F1 F1 F1 D1 D1 D1 R1 R1 R1 D1 F1 L1 D1 L1 L1 L1 D1 D1 D1 F1 F1 F1
D1 B1 R1 D1 R1 R1 R1 D1 D1 D1 B1 B1 B1 D1 B1 R1 D1 R1 R1 R1 D1 D1 D1
B1 B1 B1 D1 D1 D1 D1 B1 R1 D1 R1 R1 R1 D1 D1 D1 B1 B1 B1 D1 D1 D1 D1
D1 D1 B1 B1 B1 D1 F1 D1 D1 D1 B1 D1 F1 F1 F1 D1 D1 D1 R1 R1 R1 D1 L1
D1 D1 D1 R1 D1 L1 L1 L1 D1 D1 D1 B1 D1 D1 D1 F1 F1 F1 D1 B1 B1 B1 D1
D1 D1 F1 D1 B1 B1 B1 D1 F1 D1 D1 D1 B1 D1 F1 F1 F1 D1 D1 D1 L1 D1 D1
D1 R1 R1 R1 D1 L1 L1 L1 D1 D1 D1 R1 D1 F1 R1 R1 R1 F1 F1 F1 R1 F1 R1
R1 R1 F1 F1 F1 R1 R1 R1 R1 D1 L1 D1 D1 D1 R1 D1 L1 L1 L1 D1 D1 D1 B1
B1 B1 D1 F1 D1 D1 D1 B1 D1 F1 F1 F1 D1 D1 D1 F1 R1 R1 R1 F1 F1 F1 R1
F1 R1 R1 R1 F1 F1 F1 R1 F1 D1 D1 D1 B1 B1 B1 D1 F1 F1 F1 D1 D1 D1 B1
D1 F1 R1 R1 R1 F1 F1 F1 R1 F1 R1 R1 R1 F1 F1 F1 R1 F1 F1 F1 D1 B1 D1
D1 D1 F1 D1 B1 B1 B1 D1 D1 D1 R1 D1 D1 D1 L1 L1 L1 D1 R1 R1 R1 D1 D1
D1 L1 D1 R1 R1 R1 D1 L1 D1 D1 D1 R1 D1 L1 L1 L1 D1 D1 D1 R1 D1 D1 D1
L1 L1 L1 D1 R1 R1 R1 D1 D1 D1 L1 D1 F1 F1 F1 D1 B1 D1 D1 D1 F1 D1 B1
B1 B1 D1 D1 D1 L1 L1 L1 D1 R1 D1 D1 D1 L1 D1 R1 R1 R1 D1 D1 D1
```
It is possible to reduce the move-count considerably if same moves are grouped together. Therefore, one can replace the output like
```
(c.gsub(/(.)\1*/){j=$&.size%4;$><<$1<<j<<' 'if j>0};o=z;s=t)if s>t
```
] |
[Question]
[
Given any of the following characters (or a newline):
```
`1234567890-=~!@#$%^&*()_+qwertyuiop[]\QWERTYUIOP{}|asdfghjkl;'ASDFGHJKL:"zxcvbnm,./ZXCVBNM<>?
```
Your program must output the row that it is on the keyboard
---
Because my keyboard is (almost) out of battery, your code must be as short as possible
---
The keyboard your program should use (for the row lookup), should look like:
``Row 1:``~`` `!1``@2` `#3``$4` `%5``^6` `&7``\*8` `(9``)0` `\_-``+=`
`Row 2:` `Q` `W` `E` `R` `T` `Y` `U` `I` `O` `P` `{[` `}]` `|\`
`Row 3:` `A` `S` `D` `F` `G` `H` `J` `K` `L` `:;` `"'` `↵ return`
`Row 4:` `Z` `X` `C` `V` `B` `N` `M` `<,` `>.` `?/`
`Row 5:` `space``
Where `↵ return` is a newline. Empty keys don't mean anything.
## Examples
```
"$"
1
"R"
2
"a"
3
"?"
4
"\n"
3
" "
5
```
where `\n` is a newline character.
## Specifications
* Your program should be case insensitive
* Your program only needs to handle the characters on the keyboard shown
[Answer]
# JavaScript (ES6), ~~105~~ ~~102~~ 101 bytes
```
c=>/[~`0-9!@#-&^(-+_=-]/.test(c)+/[asdfghjkl;:'"\n]/i.test(c)*3+/[zxcvbnm,<.>/?]/i.test(c)*4||++c*7^2
```
## Explanation
In JavaScript `test` returns a boolean which acts the same as `1` or `0` so I multiply them by their row. Testing for row 2 took the most bytes so I used that one as the default if no others matched.
```
c=>
/[~`0-9!@#-&^(-+_=-]/.test(c) // row 1 regex
+/[asdfghjkl;:'"\n]/i.test(c)*3 // row 3 regex
+/[zxcvbnm,<.>/?]/i.test(c)*4 // row 4 regex
||++c // space ++ = 1, any character on row 2 ++ = NaN
*7^2 // 7 XOR 2 = 5, NaN XOR 2 = 2
```
## Test
```
var solution = c=>/[~`0-9!@#-&^(-+_=-]/.test(c)+/[asdfghjkl;:'"\n]/i.test(c)*3+/[zxcvbnm,<.>/?]/i.test(c)*4||++c*7^2
```
```
<textarea id="input">-</textarea><br />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# Pyth, ~~62~~ ~~66~~ 65 bytes
```
?zh@+,4Zmid2c.Bi."0fÀÓ¸[9Ѷ¤KïLäHÉðbÀ`]ü©¬vS"16 2-CzCd3
```
[Try it online.](http://pyth.herokuapp.com/?code=%3Fzh%40%2B%2C4Zmid2c.Bi.%220f%1E%C3%80%C3%93%C2%B8%5B%C2%809%C3%91%C2%B6%C2%A4K%0B%C3%AFL%C3%A4H%C3%89%C2%95%C3%B0b%C3%80%60%C2%8A%5D%C2%94%05%01%C3%BC%C2%87%C2%A9%1A%C2%ACvS%2216%202-CzCd3&test_suite=1&test_suite_input=%60%0Aq%0Aa%0Az%0A%20&debug=0)
Uses a packed string representing a number in hex which, when chopped into two-bit chunks, represents the row of every character except and `!` as a value from 0 to 3. We leave out and `!` so we don't have to store 4 or have a 0 at the start of this number, then add their row values using `+,4Z`. Once we've turned the string into row values, all we have to do is use the character code of the input to index into the array of values, and then add 1.
Newline is handled separately because it's interpreted by Pyth as an empty string and so has a character code of 0.
This would be shorter if I could figure out how to use base 256 in Pyth, but I can't quite make it work.
[Answer]
## [Glava 1.5](https://github.com/GamrCorps/Glava), 164 bytes
Glava is a dialect of Java that makes Java code shorter. This code is unfortunately non-competitive as the commit (2 hours late...) used was made after this challenge, which fixed some vital bugs that would not allow this program to work.
```
p(A[0].matches("[`0-9-=~!@#$%^&*()_+]")?1:A[0].replace("\\n","\n").matches("(?i)[asdfghjkl;':\"\n]")?3:A[0].matches("(?i)[zxcvbnm,.\\/<>?]")?4:A[0].matches(" ")?5:2
```
This is a full program that takes input via command-line arguments. Works by simply testing for which row regex it matches, then outputs the corresponding number.
[Answer]
# Python 3, 142
```
print(int(("~`!1@2#3$4%5^6&7*8(9)0_-+=""qwertyuiop{[}\|"+"]"*11+'asdfghjkl;:"\n'"'"*13+"zxcvbnm,<.>/""?"*14+" ").index(input().lower())/26)+1)
```
There is probably a shorter way that I am overlooking ¯\\_(ツ)\_/¯
[Answer]
# [Pyth](https://pyth.herokuapp.com/), 98
```
|+++l:"~`0123456789!@#$%^&*()_-=+"z1*l:"asdfghjkl;:'\"\n"rz0 1 3*l:"zxcvbnm,<.>/? "rz0 1 4 l:dz1 2
```
not sure how to get the 0-9 range working for some reason :|, inspired by user81655's answer
[Answer]
# Bash, 108
No Bash answer?
Bash answer. `grep -Fin` is definitely the right tool for this job.
This program is in two files.
## `k`, 73 bytes
```
`1234567890-=~!@#$%^&*()_+
qwertyuiop[]\{}|
asdfghjkl;':"
zxcvbnm,./<>?
```
There are 5 lines, the last one is a space. If you have trouble reproducing the file, the base64 is:
```
YDEyMzQ1Njc4OTAtPX4hQCMkJV4mKigpXysKcXdlcnR5dWlvcFtdXHt9fAphc2RmZ2hqa2w7JzoiCnp4Y3Zibm0sLi88Pj8KIA==
```
## `b`, 34 bytes
This is the program itself, it takes input as the only command line argument.
```
grep -Fin "$1" k|tail -n3|head -c1
```
Score: 34 + 73 + 1 (for `k`'s filename) = 108 bytes
## Ungolfed
```
grep --fixed-strings --ignore-case --line-number "$1" k|tail --lines=3|head --bytes=1
```
## Explanation
* `grep` - search a file for lines matching a string or regular expression, output only those lines
* `-F` aka `--fixed-strings` - disable regular expressions so `[` etc. are handled correctly
* `-i` aka `-y` aka `--ignore-case` - case-insensitive matching
* `-n` aka `--line-number` - show the line number and : before every line (e.g. `4:zxcvbnm,./<>?`)
* `"$1"` - search for the script's first command-line argument, the quotes are necessary to handle newline and space
* `k` - search in file `k`
* This `grep` command will match all five lines if the input is a newline, and only one line otherwise.
* `|` - pipe, send standard output of one command to standard input of the next
* `tail` - output the last N lines or characters of standard input
* `-n3` aka `--lines=3` - output the last 3 lines
* If the input wasn't a newline, there is only one line to process, which starts with the row number because of the `-n` flag on `grep`. Otherwise, this command takes only lines 3, 4 and 5 (the last 3 lines).
* `|` - pipe
* `head` - output the first N lines or characters of standard input
* `-c1` aka `--bytes=1` - output the first character
* If the input wasn't a newline, this takes the first character, which is the line number where the input is found. If the input is a newline, it takes the first character of lines 3, 4 and 5 combined, which is 3, which happens to be the correct row number for newline.
[Answer]
## Japt, ~~73~~ ~~70~~ 66 bytes
```
2+`qØÆyuiop\{}[]|\\1dfghjkl;:
'1zxcvbnm,.<>?/\"1 `q1 ®bUv)<0} b!1
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=MitgcdjGeXVpb3Bce31bXXxcXDFkZmdoamtsOzoKJzF6eGN2Ym5tLC48Pj8vXCIxIGBxMSCuYlV2KTwwfSBiITE=&input=Igoi) (in the example, the input is literally a newline)
[Answer]
# Java, 300 bytes
```
import java.util.Scanner;public class A{public static void main(String[] args){String g="~`!1@2#3$4%5^6&7*8(9)0_-+=qQwWeErRtTyYuUiIoOpP[{]}\\|aAsSdDfFgGhHjJkKlL;:\'\"\r";Scanner i=new Scanner(System.in);int f=g.indexOf((i.nextLine().charAt(0)));System.out.print(f<0?4:(f<26?1:(f<53?2:(f<76?3:5))));}}
```
I'm not an expert, and this is my first attempt at golfing, but I figured, what the hell, why not? Above is the full program version, the actual code that goes into it would most likely take a decent amount of characters off.
[Answer]
## Pyth, 105 bytes
```
J?<l-c".^$*+?{}[]\|()"1]z14+\\zrz0?qJd5?:"qwertyuiop[]\|"J)2?:"asdfghjkl;':\"\n"J)3?:"zxcvbnm,./<>?"J)4 1
```
Explanation:
```
J?<l-c".^$*+?{}[]\|()"1]z14+\\zrz0 # Escape input if regex metachar
?qJd5 # Check space
?:"qwertyuiop[]\|"J)2 # Check second row
?:"asdfghjkl;':\"\n"J)3 # Check third row
?:"zxcvbnm,./<>?"J)4 # Check fourth row
1 # If none of these, must be on first row.
```
I decided to choose the first row as the "must be if nothing else" row because it required the most bytes to represent even after golfing.
[Answer]
# Perl 6, 128 bytes
```
say 1+(/<[-\d=~!@#$%^&*()_+/`]>/,/<[qwertyuiop[\]\\{}|]>/,/<[asdfghjkl;':"\n]>/,/<[zxcvbnm,./<>?]>/,' ').first: @*ARGS.lc~~*,:k
```
I make a list of regexes containing character classes along with a string literal space. I then call the `first` method on the list (which is just the method version of the `first` higher order function), using smartmatch to compare the argument passed to the program against the current item in the list. Note that smartmatch does "the right thing" for both regexes and a string literal. The `:k` optional parameter to `first` causes the method to return the index of the matching item in the list, which I then add 1 to and output via `say`.
Note that when using this program you will have to properly escape certain characters like ` and space in your shell. For instance: perl6 keyboard.p6 \`
[Answer]
## Python 3, 89 bytes
```
print("qwertyuiop{}[]\\|asdfghjkl;:\"\n'''zxcvbnm,.<>/???? ".find(input().lower())//16+2)
```
As I can't comment yet, I'm posting the improvement for the [current Python 3 answer](https://codegolf.stackexchange.com/a/68746/76276) separately.
**Edit**: All code in `print` now and further tweaked.
[Answer]
## JavaScript ES6, 114 bytes
```
n=>[`qwertyuiop{}[]|\\`,`asdfghjkl;:
'`,`zxcvbnm,.<>?/"`,` `].map(x=>+(x.indexOf(n.toLowerCase())<0)).indexOf(0)+2
```
Another JavaScript solution. The principle is to return the index of the input char in the array of rows plus 2 (so as the 0-9 row returns -1, i.e. not exists, -1+2=1. `q` is in the first string of the array, so it returns 0+2=2nd row).
[Answer]
# Perl, ~~96~~ ~~77~~ 76 bytes
Run using `perl -p`. Make sure you're feeding it just single characters; for example, to run it from a file `key.pl` (to avoid mucking around with shell escape sequences) `echo -n q|perl -p key.pl`.
```
$_=/[\d~`!@#-&(-+_=-]/+/[adfghjkls"':;
]/i*3+/[bcnmvxz<>,.?\/]/i*4+/ /*5||2
```
Abusing the regex range functionality is fun.
[Answer]
# PHP, 173 bytes
The idea here was to use the regex capturing group number as the row index. Probably some more optimizations in the regex itself.
```
$i=$argv[1];preg_match("%([!#-&\(-+-0-9=@^-`~])|([EIO-RT-UWY[-]eio-rt-uwy{-}])|([\"':-;ADF-HJ-LSadf-hj-ls])|([,.-/<>-?B-CM-NVXZb-cm-nvxz])%",$i,$m);echo array_flip($m)[$i];
```
The `preg_match()` call will create an array `$m` of matches, and if we were to print that, it'd look something like this (assuming `z` was the input):
```
Array ( [0] => 'z', [1] => '', [2] => '', [3] => '', [4] => 'z' )
```
Flipping that array, by swapping keys and values, moves left to right and only keeps the last distinct key, so we end up with:
```
Array ( 'z' => 4, '' => 3 )
```
Then we use the input character as the index in the array to get our result.
[Try it out here](https://3v4l.org/jeris).
[Answer]
# C, ~~145 143 136 132 127 106~~ 104 bytes
```
#define c"\x7ea6a6f8\x5777595"
f(a){return a-32?L"\x200000\0\xf3008020\xf2a00000"c c[a>>4]>>a%16*2&3:4;}
```
[Try it online!](https://tio.run/##bcrRCoIwGIbhc69iLMwtEtamzhLWDXQHLehnbuJBo8RAEq99paf5Hb08fCZtjAlhU1vXeosM1oO0UEDhSj3kUsr8mOPIEaBjZ/t35xGkgp8vvx9n8zTTgxOMlYzPxWFRbJC5glLZTSmID8WOb8Upq6bwgNYTOkbPrvW9Iziutcd7R5J7Qmn1z691hnX@rDNaeApf "C (gcc) – Try It Online")
~~This uses `index()` from POSIX.1-2001 and is deprecated in POSIX.1-2008.~~
This assumes ASCII and 32 bit ints.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 82 bytes
```
->i{1+((0>r=i.ord-33)?r%5:"bc7xdutvz4ind3bwqf6mcu5vxiahnmlfs93c".to_i(36)>>2*r&3)}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6z2lBbQ8PArsg2Uy@/KEXX2FjTvkjV1EopKdm8IqW0pKzKJDMvxTipvDDNLDe51LSsIjMxIy83J63Y0jhZSa8kPz5Tw9hM087OSKtIzViz9n@BQlq0vUEsF5guhNKJEFpFH8qvgtBKCkqx/wE "Ruby – Try It Online")
[Answer]
# CJam, 125 bytes
```
q_" "={;5}{"`1234567890-=~!@#$%^&*()_+qwertyuiop[]\QWERTYUIOP{}|asdfghjkl;'ASDFGHJKL:\" zxcvbnm,./ZXCVBNM<>? "\#26/1+}?
```
---
### Explanation
```
q e# read input
_" "= e# decide if the input is a space
{;5} e# if it is, push 5
{"..."\#26/1+}? e# if it isn't, push the correct row
```
[Answer]
# SpecBAS - 178 bytes
```
1 a$="~`!1@2#3$4%5^6&7*8(9)0-_+=qQwWeErRtTyYuUiIoOpP{[}]|\aaaaAsSdDfFgGhHjJkKlL:;'"#34#13"zzzzzzzZxXcCvVbBnNmM<,>.?/"+" "*26
2 INPUT k$: IF k$="" THEN k$=#13
3 ?CEIL(POS(k$,a$)/26)
```
I used a long string where each row is 26 characters long (#34 is code for double quote and #13 is code for return).
Then print the result of rounding position/26.
[Answer]
# C#6, 201 bytes
Nothing special here. I found it cheaper to just write both cases rather than use ToUpper() due to the string's fixed width.
```
using C=System.Console;class P{static void Main(string[]a)=>C.Write("`1234567890-=~!@#$%^&*()_+qwertyuiop[]\\QWERTYUIOP{}|asdfghjkl;'\raASDFGHJKL:\"\nazxcvbnm,./zzzZXCVBNM<>?zzz ".IndexOf(a[0])/26+1);}
```
Indented:
```
using C=System.Console;
class P{
static void Main(string[]a)=>
C.Write("`1234567890-=~!@#$%^&*()_+qwertyuiop[]\\QWERTYUIOP{}|asdfghjkl;'\raASDFGHJKL:\"\nazxcvbnm,./zzzZXCVBNM<>?zzz ".IndexOf(a[0])/26+1);
}
```
[Answer]
# Python 2, 146 bytes
```
e="\n";lambda x:("`1234567890-=~!@#$%^&*()_+qwertyuiop[]\\QWERTYUIOP{}|asdfghjkl;'ASDFGHJKL:\""+e*4+"zxcvbnm,./ZXCVBNM<>?"+e*13+" ").index(x)/26+1
```
[Answer]
# Excel, 132 bytes
`=INT((FIND(A1,"`1234567890-=~!@#$%^&*()_+qwertyuiop[]\QWERTYUIOP{}|asdfghjkl;'ASDFGHJKL:""aaa
zxcvbnm,./ZXCVBNM<>?zzzzzz ")-1)/26)+1`
Attempts to use the case in-sensitive `SEARCH()` instead of `FIND()` revealed that Excel matches `~`, `*` and `?` to `(tick). The matching of`?`means we can't use`SEARCH()`, which would have shaved a massive 5 bytes...
] |
[Question]
[
Consider a square grid on the plane, with unit spacing. A line segment of integer length \$L\$ is dropped at an arbitrary position with arbitrary orientation. The segment is said to "touch" a square if it intersects the interior of the square (not just its border).
# The challenge
What is the maximum number of squares that the segment can touch, as a function of \$L\$?
# Examples
* **L=3** \$\ \, \$ The answer is \$7\$, as illustrated by the blue segment in the left-hand side image (click for a larger view). The red and yellow segments only touch \$6\$ and \$4\$ squares respectively. The purple segment touches \$0\$ squares (only the interiors count).
* **L=5** \$\ \, \$ The answer is \$9\$. The dark red segment in the right-hand side image touches \$6\$ squares (note that \$5^2 = 3^2+4^2\$), whereas the green one touches \$8\$. The light blue segment touches \$9\$ squares, which is the maximum for this \$L\$.
[![enter image description here](https://i.stack.imgur.com/pjZfr.png)](https://i.stack.imgur.com/pjZfr.png)
# Additional rules
* The input \$L\$ is a positive integer.
* The algorithm should theoretically work for arbitrarily large \$L\$. In practice it is acceptable if the program is limited by time, memory, or data-type size.
* Input and output are [flexible](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) as usual. [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Shortest code in bytes wins.
# Test cases
Here are the outputs for `L = 1, 2, ..., 50` (with `L` increasing left to right, then down):
```
3 5 7 8 9 11 12 14 15 17
18 19 21 22 24 25 27 28 29 31
32 34 35 36 38 39 41 42 43 45
46 48 49 51 52 53 55 56 58 59
60 62 63 65 66 68 69 70 72 73
```
[Answer]
# [Python 2](https://docs.python.org/2/), 27 bytes
```
lambda L:(2*L*L-2)**.5//1+3
```
[Try it online!](https://tio.run/##TZhBjl23EUXH0Sr@sFvuxKwiq1g0oB30DhwPFESyDSiyoWiS1St1LhUggyYg1AX0/@Hl@zzvz/98/e2Pz/7t47u/f/v0/l//@Of7x@tPT/729e3rX/357du/xY8/2g/z28c/vjxeH79/fnx5//nXD0/2Evb805u//Pnl989fH68vj49Pr89v3nx9/@XXD1///Xj3@Hm@POLlsV8e9fI4Lw@z/vP@W/3XA@uJ9ch65j3znnnPvGfeM@@Z92z2bPZs9mz2bGb/9Wz2bPVs9Wz1/7V6tnq2erZ6Fj2LngWfo2fRs@hZ9CxH//Use5Y9y55lz7Jnu2e7Z7tnmy/Qs92fZ/eselY9q55Vz6pnxTfs2enZ6dnp2enPenp2enb47mOwQGBMFhiMZIHCEB4igmREhMmICJRIOREXRyLQMicCLwOYTSIgs0kEaAY1m0TgZosI5AxstogAzxYR8FkQAaBB0EJbRiSIhCJ85iQCSEsioLQkAkyDpm0i8LRNZGvn@cybCFCtiIDVighgDbJWRGBrhwh0Dbx2iADYjhpEhUDsgxKB2Ac1ArEPijTUMiJ00EHstNBB7CB2FRHEriqC2FVGELsqSR8dxE4jHcQOYqeUDmKnlg5iB7GD2EHsdNNB7LTTQewgdgrqoeYTAbGD2Gmpg9jpqYPYaaqD2EHslNVB7NTVQexbB4gIiJ3OOoid1jqIHcReOmQ6ZURA7CB22usgdvrrRxFOIgWeIJ4UeIJ4UuAJ4jl0WImAeFLgCeIJ4kmBJ4in60ATocATxBPEkwJPHXmdeR16EE8de517HXwQTxDPpecCEQo8QTwp8ATxBPGkwBPEkwJPEE8QTwo8QTwp8ATxTD1fiIB4UuAJ4kmBJ4gniCcFniCeFHiCeFLgCeIJ4ll6TBGhwBPEE8STAk8QTwo8QTxBvCjwAvGiwAvEiwIvEC8QLwq8QLwo8ALxAvGiwAvEiwIv13ORCIgXiBcFXiBeFHiBeE09O4mAeFHgNRXh4aqnqx6vFHjpAUuBlx6xIF4UeIF4UeAF4gXiRYEXiBcFXiBeFHilHtNEKPAC8aLAC8QLxIsCLxAvCrxAvCjwAvEC8aLAq/S0JwLiBeJFgReIFwVeIF4gXhQ4QBwUOEAcFDhAHCCOoV8NIhQ4QBwgDgocIA4KHCAOChwgDhAHBQ4QBwUOEAeIgwIHiIMCB4gDxEGBA8RBgQPEQYEDxAHioMCh37H7I0ZEP2UUOPRjRoEDxEGBA8SR@rUjAuKgwAHiAHFQ4ABxUODYivCZQRwgDgocIA4KHCAOEAcFDhAHBQ4QB4jj6IdVv6zGwm8rBU4QJ4iTAieIkwIniBPESYETxEmBE8RJgRPECeKkwAnipMAJ4gRxTv2IE6HACeIEcVLgBHFS4ARxUuAEcYI4KXCCOClwhu4CfGYKnCBO3RV0WdBtQdcFEKcuDCBOCpwgThAnBU4QJwVOECeIk2dEgjgpcII4S9cOIqXLBxEQJwVOECeIkwIniDcF3iDeFHiDeIN4U@AN4k2BN4g3iDcF3iDeFHiDeLuuOERAvCnwBvGmwNsV4SZEgffUXYgIiDeINwXeIN4UeIN4U@AN4g3iTYE3iDcF3iDeoSsVERBvCrxBvCnwBvEG8U5du4hQ4K1bma5lupfpYqab2b2a8Zkp8AbxpsAbxJsCbxBvEG8KvEG8KfAG8QbxpsD76IanKx53PApcIC4QFwUuEBcFLhAXiIsCF4iLAheIiwKX66ZIhAIXiIsCF4gLxEWBC8RFgQvEBeKiwAXiosAF4qLABeICcVHgAnFR4AJxgbgocIG4KHCBuChwgbhAXBS4UrdXIqkIn5kCF4iLAheIa@uGS0T3XwpcugFT4NIdWJdgClwgLgpcIC4QFwUuEBcFrqObsrFwVwbxocAHxIcCHxAfEB8KfEB8KPAB8QHxAfFxXbiJgPhQ4APiA@JDgQ@Iz9SlnAiIDwU@ID4U@ID4UOCzdHEnQoEPiA8FPiA@ID4U@ID4UOAD4kOBD4gPiA8FPqn7PxEQHxAfCnxAfCjwAfEB8aHAB8SHAh8QHwp8QHxAfCjwAfGRZYD4yDUkGiA@VzVKriHZuLYB5V7lG3DuVcYxblJuIukYcrMh7RjysyH7GDKPYUrKPYYrKfsYrqQkZEhAhis5r@soKRMZspAxlZSHjKmkTGQsJdeVIyWXktKRsZSUlQwZyQgl5SQjlJSVDGnJSCUlJiOVlJqMVFKGMmQnYyspPxlbSWnK2FfOlJSkjFJSmjJKSdnKkKmMUlKuMo6SUpYhXRlHSQnLONf4rvLJ@bRTVwyvGV41vG5o2qn/2aGS1w@vIGqnviuidupK4rXEq4nXE007dU3xquJ1xSuLpp26unh98QrjNcarjNcZTTt1rfFq4/XGK46mnbrqeN3xyuO1R9NOXX@8AnkN8irkdcgrkaaduhp5PfKK5DVJ005dl7wyeW3y6uT1ySuUpp26Snmd8krltUrTTl2vvGJ5zfKq5XVLyaXJLk16afJLk2CaDLNX@bdOkyTTZJkmzexVnq7TJNM0qab51XmdJr9Cf43@Kv11ep0mKWev1/yV1E5JO03eaRJPk3ma1NPknib5NNmnST971bsEnSYZqElBTQ7aq76XRF8aavJQk4iaTNSkor0qqdMkGzXpqMlHe9X30mmSkpqc1CSlJis1aWmvSuo0yUxNampy0171vXSapKcmPzUJqslQTYpqclSTpJos1aSpJk/tNbXelyRK6jRJVnvV2xKdJvmqSVhNxmpSVpOz9qqkTpO01eZ98aKdmvf9i07TvG9g7tsX7ZT01eSvJoE1GaxJYU0Oa5LYXvW6RqdJHmsSWZPJ9npf6yipnZLNmnTW5LMmoe1VSZ0mOa1Jak1W26u@l06TxNZktia1NbmtSW57VVKnSX5rElyT4faq76XTJMk1Wa5Jc3vV99JOyXRNqmtyXZPsmmy3V72G0mmS8JqM16S8vertoU6TrLfX/cubN/cN5M8fnz49P3hJ@en/X1I@7PHD49OHz0/fX0w@P//yePfu8f1f3/4L "Python 2 – Try It Online")
A direct formula:
$$ f(L) = \lfloor \sqrt{2 L^2-2}\rfloor + 3 $$
**Derivation**
As noted [by @Kirill L.](https://codegolf.stackexchange.com/a/231179/20260) and others, the optimal layout uses a near-diagonal line segment whose horizontal and vertical span are at least \$(h,h)\$ or \$(h,h+1)\$. We need the length-\$L\$ to cover at least this much distance using the Pythagorean theorem, plus some extra to reach into squares and hit 3 more.
This gives a result of either:
* \$2h+3\$ where \$h\$ is the greatest positive integer where \$h^2+h^2 < L^2\$, or
* \$2h+4\$ where \$h\$ is the greatest positive integer where \$h^2+(h+1)^2 <L^2\$,
whichever of these is larger. We want to combine these two cases into one.
Let's start by making the two cases look more similar. Note that the second case can be rewritten as
>
> \$2(h+\frac{1}{2})+3\$, where \$2(h+\frac{1}{2})^2 + \frac{1}{2} < L^2\$
>
>
>
or as
>
> \$2h+3\$, where \$2h^2 + \frac{1}{2} < L^2\$
>
>
>
where \$h\$ is a positve integer-and-a-half.
The \$2h^2<L^2\$ in the first case can be also be written as \$2h^2 +\frac{1}{2} < L^2\$, which is equivalent because both sides were integers. So, the cases now merge into:
>
> \$2h+3\$ where \$h\$ is the greatest positive integer or half-integer
> where \$2h^2 +1/2 < L^2\$
>
>
>
Calling \$2h=H\$, this is:
>
> \$H+3\$ where \$H\$ is the greatest positive integer
> where \$2(H/2)^2 +1/2 < L^2\$.
>
>
>
This inequality is \$H^2 < 2L^2-1\$, and since these are integers, this is the same as \$H^2 \leq 2L^2-2\$. The greatest such positive integer \$H\$ is then \$\lfloor \sqrt{2 L^2-2}\rfloor\$, so the final result is \$ \lfloor \sqrt{2 L^2-2}\rfloor + 3 \$.
[Answer]
# [R](https://www.r-project.org/), ~~79~~ 77 bytes
```
L=scan();j=1:L;a=j*2^.5;b=Mod(j+j*1i+1i);3+2*sum(L>a)+max(a[L>a],b[L>b])%in%b
```
[Try it online!](https://tio.run/##K/qfpmCjq5BWmpdckpmfp5GpqVCtUJycmIciqpmpoBySWlyiUF6UWFCQWvTfxxakRkPTOsvW0MrHOtE2S8soTs/UOsnWNz9FI0s7S8swU9swU9PaWNtIq7g0V8PHLlFTOzexQiMxGsiM1UkCUkmxmqqZeapJ/2u5ioHG5lRqGFqZGuikaf4HAA "R – Try It Online")
*Note: as it turned out, this is completely destroyed by [xnor's formula](https://codegolf.stackexchange.com/a/231187/78274), which would be 23 bytes in R:*
```
(2*scan()^2-2)^.5%/%1+3
```
*However, I'm keeping the existing code as a reference to my original solution.*
### Original explanation
In general case, the most squares will be touched when the line is going close to the diagonal orientation. Specifically, the number of touched squares will be equal to \$2 \times x + 3\$, where \$x\$ is the number of unit square diagonals fully covered by the line. The lengths of square diagonals are stored in `a`.
However, in some cases a better coverage can be achieved by deviating from the diagonal orientation. To account for this, we also store a vector `b` containing the lengths of diagonals of "deviated" rectangles of size \$1 \times 2\$ up to \$L \times (L+1)\$ (instead of squares up to \$L \times L\$). It looks like we need to count one additional touch in those cases where the maximal value of `b` that is still smaller than \$L\$ exceeds the analogous value from `a`.
For example, the first few diagonals are of length:
```
1x1 2x2 3x3 4x4
1.414214 2.828427 4.242641 5.656854 ...
```
We can see that after going from \$L = 3\$ to \$L = 4\$ we have still covered only the 2nd term (\$2 \times 2\$ diagonal), it's not enough to reach the edge of the 3rd square, so we are not gaining any more touches. But if we switch to the "deviated" rectangles:
```
1x2 2x3 3x4 4x5
2.236068 3.605551 5.000000 6.403124 ...
```
Here \$L = 4\$ now encompasses a larger value of 3.60..., which corresponds to (\$2 \times 3\$) rectangle. In this orientation we gain an extra touched square compared to the diagonal.
[Answer]
# [J](http://jsoftware.com/), 28 bytes
*-1 thanks to Jonah!*
The optimal is always either the diagonal `L, L` with `3+2*L` tiles crossed as noted by @Kirill L. or `L, L+1`, in which case an extra tile is crossed.
```
((>]+&.*:>:)+3+2*])[<.@%%:@2
```
[Try it online!](https://tio.run/##Pc29SgNREEDh3qc4BGKyWXPZmbkz9wezBAQrK1tJJQkmjaDvz5rK4jRfc27LKm0uHDobnpjo9/aJl/e312W7nU/jY9r1uQ@jjbo7DR/P6bhe96Muw8P58@ubn/PvIXFZTcyda8Knf2ffMZxCpSGCKJIRRwpSkYYKqmhGHS1oRRsmmGIZcyywijWykJVsZCcHuZIbLrji94njgVe8EROhhBFOBFGJRpkoSrHlDw "J – Try It Online")
* `[<.@%%:@2` calculate `L` by dividing `n` by `sqrt(2)`, then flooring
* `3+2*]` `3+2*L`
* `]+&.*:>:` calculate length to `L, L+1`
* `> … +` if `n` is larger than this length, add 1
Because the lines have rational length `n`, and the diagonals irrational length `L`, we can always find an epsilon \$L - n > 0\$ to slide the line top-left to touch the 3 extra tiles, which justifies the `3+2*L`.
`L, L+2` will always be further away then the next diagonal `L+1, L+1`, as \$L^2 + (L+2)^2 = 2L^2 + 4L + 4 > 2L^2 + 4n + 2 = (L+1)^2 + (L+1)^2\$, so checking `L, L+1` is enough.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 7 bytes
```
*d⇩√3+⌊
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=*d%E2%87%A9%E2%88%9A3%2B%E2%8C%8A&inputs=1&header=&footer=)
Shameless port of xnor's answer
```
* # Square
d # Double
⇩ # Subtract 2
√ # Square root
3+ # Add 3
⌊ # Floor
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18 17~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-9 using [xnor's mathematical simplification](https://codegolf.stackexchange.com/a/231187/53748) of the same method as the 17, below.
```
²Ḥ_2ƽ+3
```
A monadic Link that accepts a positive integer, \$L\$ and yields the maximal squares touched.
**[Try it online!](https://tio.run/##y0rNyan8///Qpoc7lsQbHW47tFfb@P///6YGAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##AR4A4f9qZWxsef//wrLhuKRfMsOGwr0rM//Dh@KCrP//NTA "Jelly – Try It Online").
### How?
```
²Ḥ_2ƽ+3 - Link: positive integer, L
² - square -> L²
Ḥ - double -> 2L²
_2 - subtract 2 -> 2L²-2
ƽ - integer square-root -> ⌊√(2L²-2)⌋
+3 - add three
```
---
17:
```
²H½Ḟð‘Ḥ‘++²ḤƊ‘½<ʋ
```
**[Try it online!](https://tio.run/##y0rNyan8///QJo9Dex/umHd4w6OGGQ93LAGS2tqHNgFZx7qA7EN7bU51////39QAAA "Jelly – Try It Online")**
### How?
First finds the longest \$(a,a)\$ or \$(a,a+1)\$ diagonal that \$L\$ can cover with some to spare, then places the line along this diagonal, poking out at both ends, and shifts it in the \$x\$ direction to cover \$2a+3+X\$ squares where \$X=1\$ if the diagonal is \$(a,a+1)\$, otherwise \$X=0\$.
```
²H½Ḟð‘Ḥ‘++²ḤƊ‘½<ʋ - Link: positive integer, L
² - square -> L²
H - halve -> L²/2
½ - square-root -> side of square with diagonal L
Ḟ - floor -> a
ð - new dyadic chain, f(a,L)...
‘ - increment -> a+1
Ḥ - double -> 2a+2
‘ - increment -> 2a+3
ʋ - last four links as a dyad, f(a, L):
Ɗ - last three links as a monad, f(a):
² - square -> a²
+ - (a) add (that) -> a+a²
Ḥ - double -> 2(a+a²)
‘ - increment -> 2(a+a²)+1 = a²+(a+1)²
½ - square-root -> diagonal length of (a,a+1)
< - less than (L)? -> 1 or 0 -> X
+ - (2a+3) add (X)
```
[Answer]
# [Perl 5](https://www.perl.org/), 73 bytes
```
for$d(0,1){$w=0;1while$w**2+($d+$w++)**2<$_**2;$m+=2*$w-1+$d}$_=int$m/2+1
```
[Try it online!](https://tio.run/##DcdBCoAgEAXQy/xFOUkqtCrP0sYiwVJKmEV09aY2D15ZzjSIrPlEaExn2xvszWh5i2kBK@WoQSAwUftnwvw7YifvFFhbQngw@3hU7L0jKzKYN5ca83GJLukD "Perl 5 – Try It Online")
Took @Kirill L.'s explanation and ran with it. Does two passes, without and with "deviation" in `$d`. The `int$m/2+1` outputs the average (rounded up if .5) of those two passes, which will be the max of those two results. Reads the wanted length from stdin and prints max number of squares for that length. The following bash command outputs max number of squares touched for all lengths 1 to 50:
```
for l in {1..50}; do
echo $l | perl -pe \
'for$d(0,1){$w=0;1while$w**2+($d+$w++)**2<$_**2;$m+=2*$w-1+$d}$_=int$m/2+1';
echo -n " ";
done
3 5 7 8 9 11 12 14 15 17 18 19 21 22 24 25 27 28 29 31 32 34 35 36 38 39 41 42 43
45 46 48 49 51 52 53 55 56 58 59 60 62 63 65 66 68 69 70 72 73
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Ò2nU²Ñ ¬ÄÄ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=0jJuVbLRIKzExA&input=NTA)
```
Ò2nU²Ñ ¬ÄÄ :Implicit input of integer U
Ò :Negate the bitwise NOT of (i.e., floor and increment)
2n : Subtract 2 from
U² : U squared
Ñ : Times 2
¬ : Square root
ÄÄ :Add one twice
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 20 bytes
```
n=>(2*n*n-2)**.5+3|0
```
[Try it online!](https://tio.run/##VZjBcl5HEUbX0VMo3liyJ67p7umemYCSorJiBXtXFsLIQZSRUpYDC8hTsGDD0@VFzPkGlykWmqTSE/ne85//3jP@8@1fb5/evL//8cNXD49/vPv49ubjw803V/7i4cXDV3794sWrfBn/6B8/3D19@O726e7p5nVv0bLNttpuZs282WiWzWaz1Ww3t@befDTP5rP5ar5bWAtvMVpki2qxWuw2rA1vI9rINqqN1cZuaS29JX9ItqyWq@Vu1Vt5q2iVrarVarXb7G16m9Em11NtzjZ3W70tbyvayraqLS50t93b9raj7dF2tT3b5uJ754c76MEP99CLH@6i68aY6e6Mme7PmOkOdYvOzHXnzLhNc2bcqHGnFsy4Vwtm3K1xuxbMuGEbzLhl44ZtMOOubTDjvi2ZcefGrVuKJ7NklppxPcUMAlbMYGDFDAoGBpvMAGGT2dQHwfVMZtCwxQwetphBxEBiixlQbDMDi8HFNjPI2NZHyGcIG@98irDxzucIG@98kl2fLzM@doeN88E7bBw2rs8eNq5PHzauzx82LglQwGHjSOCwcdg4HjhsHBMcNg4bh43DxtHBYeMI4bBx2DhOeEorZrBx2DhiOGwcNRw2jhwOG4eN44fDxjHEYeNTPjKDjaOJw8YRxWHjsPElWWUrM9g4bBxhHDaOMr41Q2WcCdgEzgRsAmcCNtGlOTPYBM4EbAI2gTMBm3B9B5jhTMAmYBM4E/p66PuhLwhsQl8RfUf0JYFNwCaGvjzMcCZgEzgTsAnYBM4EbAJnAjYBm8CZgE3gTMAmSl87ZrAJnAnYBM4EbAI2gTMBm8CZgE3gTMAmYBNL31dmOBOwCdgEzgRsAmcCNgGbgTMDNgNnBmwGzgzYDNgMnBmwGTgzYDNgM3BmwGbgzHA9CpjBZsBm4MyAzcCZAZsRek4wg83AmRGa8QTRI0TPEJwZeorgzNBzBDYDZwZsBs4M2AzYDJwZsBk4M2AzcGaUnj7McGbAZuDMgM2AzcCZAZuBMwM2A2cGbAZsBs6MpccWM9gM2AycGbAZODNgM2AzcCZhkziTsEmcSdgkbLLrgccMZxI2CZvEmYRN4kzCJnEmYZOwSZxJ2CTOJGwSNokzCZvEmYRNwiZxJmGTOJOwSZxJ2CRsEmdST9nzjGWmBy3OpB61OJOwSZxJ2GTpIcwMNokzCZuETeJMwiZxJqdmXA9sEjaJMwmbxJmETcImcSZhkziTsEnY5NajXc9244enO84UbAo2hTMFm8KZgk3BpnCmYFM4U7ApnCnYFGwKZwo2hTMFm4JNhd4YzHCmYFOwKZwp2BTOFGwKZwo2BZvCmYJN4UylXjVcD84UbErvIL2E9BbSawg2pRcRbApnCjYFm8KZgk3hTMGmYFN8nwo2hTMFm1p6gTFbeosxg03hTMGmYFM4U7CZODNhM3FmwmbCZuLMhM3EmQmbCZuJMxM2E2cmbKbrvcgMNhNnJmwmzkzXjNcmzszQi5MZbCZsJs5M2EycmbCZODNhM2EzcWbCZuLMhM1MvXGZwWbizITNxJkJmwmbWXodM8OZqde03tN6UetNrVf1eVdzPTgzYTNxZsJm4syEzYTNxJkJm4kzEzYTNhNn5tZLXm95XvM4s2CzYLNwZsFm4cyCzYLNwpkFm4UzCzYLZ5YrD5jhzILNwpkFmwWbhTMLNgtnFmwWbBbOLNgsnFmwWTizYLNgs3BmwWbhzILNgs3CmQWbhTMLNgtnFmwWbBbOrFKVMCvNuB6cWbBZOLNgs6aShZlKBmeWWgZnlmpGOYMzCzYLZxZsFmwWzizYLJxZW7Fj/JA7sNk4s2GzcWbDZsNm48yGzcaZDZsNmw2b7aokZrDZOLNhs2GzcWbDZocSihlsNs5s2Gyc2bDZOLOH@ooZzmzYbJzZsNmw2TizYbNxZsNm48yGzYbNxpldCjNmsNmw2TizYbNxZsNmw2bjzIbNxpkNm40zGzYbNhtnNmy2Sg82W7mn2IPNPrlH19yp807wQYdFyQcfFkUfhFiUheq@rq7tKr@utu3qv67466Ytyr/u2qIA7K4tysCuBuyuLXHKUlvUgl0h2ENblII9tEUx2Ie2jJOg2jK0RUXYh7aoC7uisKe2KAt7aovCsKsMe2mL2rCXtqgOe2mLGrErEPvUFiVin9qiUOzz1K62qBP70haVYl/aol7sisW@tEW52Le2KBq7irFvbVEz9n2i@VSzslmIT1Sfqj5ZfbrahPhTWWvLaesT10L837wW4hPYp7BPYp/GNiE@lX0y@3T2CW0T4pPap7VPbJ/aPrl9etuE@BT3Se7T3Ce6TYhPdp/uPuF9ytuE@LT3ie9T3ye/T3@fADchPgl@GvxE@KlwE@LT4SfET4mfFD8tfmLchPjk@OnxE@SnyE2IT5OfKD9VfrL8dLnC3FTmpjQ3tbkpzk11zqIjiARWoJsK3ZToLDqjSGBVuinTzc8ZRgL7OcWcY8w5x5yDjARWrrOcc462CLGS3dTspmg3Vbsp203dbgp3U7mb0p1FZyUJrHo35bup31l0zTrdKOFNDW@KeFPFmzKeRVsksErelPKmlmfRNUtg5byp501Bbyp6U9KzaIsEVtWbst7U9Sy6ZgmstDe1vSnuTXVvyntT35sC31T4psQ3NT5LaTknPG2RwAp9Fp30JLBa3xT7pto35b6p91m0RQIr@S3OOVGI45wWJXCc8@I5LAqx0t/U/qb4N9W/Kf9N/W86ALDoVCmBdQYwHQJMpwCWc@zUFiHWScB0FDCdBUyHARZtkcA6D5gOBKYTAYuuWQLrUGA6FZiOBaZzgelgwKItElhnA9PhwHQ6YNE1S2AdEEwnBNMRgUXXLMQ6JZiOCaZzgumgYDopsOgoLIF1WDCdFkzHBRb99YIE1omBZX5/cXF785r17eP7q/ub/qv7X98k68uX13@/@OL21Y8/Pf3pin979ruf3l/@5uHpb3fvn319@fbq/rrxH797fP/@7s2H/w0@/8XG6/vvteG3T5ef9nz76X@7vLn5v12X314@/@Xf/3x@@bX@@a/nF1/8fH3x88Wbx4enx3d3rz7c/uHd3dXt9cXn//Lu8YerZ7@/fXq6f/jh8vbdu/PbLt/o1337rF1@@fmXv3p6/Mvd1dVtu7@@@UZ/9Jc3t9f8oo//AQ "JavaScript (Node.js) – Try It Online")
Shamelessly copies the idea from [xnor's answer](https://codegolf.stackexchange.com/a/231187/100752)
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 27 bytes
```
:*2*2-0v
:})?v1+>::*{
;n+2<
```
[Try it online!](https://tio.run/##S8sszvj/30rLSMtI16CMy6pW077MUNvOykqrmss6T9vI5v///7plCoYGAA "><> – Try It Online")
Xnor's formula, but in a language with neither square root nor rounding operations. Instead, it does the equivalent thing of finding the least square number larger than \$2L^2 - 2\$
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 20 bytes (14 characters)
```
⌊√(2#^2-2)⌋+3&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@/9RT9ejjlkaRspxRrpGmo96urWN1f4HFGXmlSg4KDgWFSVWRqfpKJgaxP4HAA "Wolfram Language (Mathematica) – Try It Online")
Shamelessly translating [xnor's Python answer](https://codegolf.stackexchange.com/a/231187/87058).
[Answer]
# [Java (JDK)](http://jdk.java.net/), 28 bytes
```
L->L+=Math.sqrt(2*L*L-2)+3-L
```
[Try it online!](https://tio.run/##JY5Ba8JAEIXv/opBCGyMWdqUXtQIHgsrPUhP0sM0yerEuNnuToRQ/O3piPDgPZjHN6/FG@ZtfZmqDmOEPZKDvxn44aejCiIji916quEqJ3XgQO50/AYMp5g@mtAKQQ9MnbaDq5h6pz8cfzkM46dvAnIfwEI5mXxrsnKPfNbxN7AqFmZh8iLN3nIzrQVkpajIMRCU8LoW25Tw/iIhy56v4DBGbq66H1h7GcJWzZOiXkFSJ26@BFqC1eh9N@6ibFCUpg/wfSa6T/8 "Java (JDK) – Try It Online")
Same as everyone, I guess, cheers to xnor!
#### Same length as:
```
L->(int)Math.sqrt(2*L*L-2)+3
```
[Try it online!](https://tio.run/##JY7BasJAEIbvPsUgBHaNWWqkl9oIHoVID9JT8TBNXDtp3Ky7EyGIz55OKAz8A/Pxzd/gHbOm/h2rFmOEA5KDxwx8/91SBZGRJe4d1XCVkzpyIHf5OgGGS9QTCY0YTM/UGtu7iqlzZu/402EYPvw5IHcBLBRjmW0VOdYH5B8Tb4FVvigXZZbrdD1uRGQFnAggKGC1kXgv4PVFljT9fwXHIfL5arqejZcibNU8yes3SOrEzZdAS7AGvW@HXZQOirSexM@ZzHP8Aw "Java (JDK) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~43~~ 29 bytes
```
.+
**2*
(^_|\1__)*__+
__$#1*
```
[Try it online!](https://tio.run/##K0otycxLNPyvp82lxeWjkhDPpaJnl8ClquGeABbTMtLi0oiLr4kxjI/X1IqP1@aKj1dRNtTi@v/f1AAA "Retina – Try It Online") Link is to test suite that generates the results from `1` to the input. Explanation: Now using @xnor's formula.
```
.+
**2*
```
Double the square of `L` and convert it to unary.
```
(^_|\1__)*__+
__$#1*
```
Subtract `2` and take the integer square root. This is based on @MartinEnder's comment to my Retina answer to [It's Hip to be Square](https://codegolf.stackexchange.com/questions/125237/) but without the leading `^` anchor as the subtraction of `2` guarantees a single match.
```
```
Add a final `1` and convert to decimal.
Previous 43-byte solution based on @KirillL.'s answer:
```
.+
**
((^(_)|\2__)*)\1(\2_(_))?.+
__$2$3$5
```
[Try it online!](https://tio.run/##K0otycxLNPyvp82lxeWjkhDPpaJnl8ClquGeABbT4tLQiNOI16yJMYqP19TSjDHUALKAApr2QOn4eBUjFWMVU67//00NAA "Retina – Try It Online") Link is to test suite that generates the results from `1` to the input. Explanation:
```
.+
**
```
Square `L` and convert it to unary.
```
((^(_)|\2__)*)\1(\2_(_))?.+
```
Find the largest `n` where `2n²<L²`, thereby dividing `L` by `√2`. Additionally, try to match a further `2n+1` (`\2` contains `2n-1`), because a rectangle of dimensions `n` by `n+1` has diagonal `√(2n²+2n+1)`. Match at least a further `1` so that the inequality is strict, but also because it guarantees a single match.
```
__$2$3$5
```
Calculate `2+2n`, plus add another `1` for the rectangular case. Note that `$2$3` is used because `\2` doesn't actually contain `2n-1` when `n=0`, but `$2$3` is always `2n`.
```
```
Add a final `1` and convert to decimal.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
é╟φQRl:
```
[Run and debug it](https://staxlang.xyz/#p=82c7ed51526c3a&i=1%0A2%0A3%0A4%0A5%0A6&m=2)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
n·Ít3+ï
```
Port of [*@xnor*'s Python answer](https://codegolf.stackexchange.com/a/231187/52210), so using the same formula:
$$f(L) = \lfloor\sqrt{L^2+2}+3\rfloor$$
[Try it online](https://tio.run/##yy9OTMpM/f8/79D2w70lxtqH1///b2oAAA) or [verify the first 50 test cases](https://tio.run/##yy9OTMpM/W9q4Opnr6Sga6egZO/3P@/Q9sO9Jcbah9f/1/kPAA).
**Explanation:**
```
n # Square the (implicit) input-integer
· # Double it
Í # Subtract it by 2
t # Take the square-root of that
3+ # Increase it by 3
ï # Truncate/floor it to an integer
# (after which the result is output implicitly)
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
²∞⌡√3+i
```
Port of [*@xnor*'s Python answer](https://codegolf.stackexchange.com/a/231187/52210), so using the same formula:
$$f(L) = \lfloor\sqrt{L^2+2}+3\rfloor$$
[Try it online.](https://tio.run/##y00syUjPz0n7///Qpkcd8x71LHzUMctYO/P/f0MuIy5jLhMuUy4zLnMuCy5LLkMDLiNTLlMDAA)
**Explanation:**
```
² # Square the (implicit) input-integer
∞ # Double it
⌡ # Subtract it by 2
√ # Take the square-root of that
3+ # Increment it by 3
i # Convert it to an integer
# (after which the entire stack is output implicitly as result)
```
] |
[Question]
[
Write a program or function that takes in a nonempty single-line string. You may assume it only contains [printable ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters) excluding space.
Print or return an ASCII art lozenge shape similar to a lemon or lime made from the prefixes of the string.
Suppose the input string is **n** letters long. Then, such a shape consists of **2n − 1** columns of ASCII art stitched together, each consisting of **2n − 1** lines. Counting from 1, the **k**-th column is **f(k) = min(k, 2n − k)** characters wide, and contains **f(k)** copies of the first **f(k)** characters of input, centered vertically, with single blank lines separating the copies.
For example, if the input is `Lemon`, the output should be:
```
Lemon
Lemo Lemo
Lem Lemon Lem
Le Lemo Lemo Le
L Lem Lemon Lem L
Le Lemo Lemo Le
Lem Lemon Lem
Lemo Lemo
Lemon
```
If the input is `lime` the output should be:
```
lime
lim lim
li lime li
l lim lim l
li lime li
lim lim
lime
```
And the same pattern is followed for other inputs:
```
a
a
Be
Be
B B
Be
/\
/\
/ /
/\
cat
cat
ca ca
c cat c
ca ca
cat
|||
|||
|| ||
| ||| |
|| ||
|||
.__.
.__.
.__ .__
._ .__. ._
. .__ .__ .
._ .__. ._
.__ .__
.__.
$tring
$tring
$trin $trin
$tri $tring $tri
$tr $trin $trin $tr
$t $tri $tring $tri $t
$ $tr $trin $trin $tr $
$t $tri $tring $tri $t
$tr $trin $trin $tr
$tri $tring $tri
$trin $trin
$tring
```
Lines in the output may have trailing spaces and there may be one optional trailing newline.
**The shortest code in bytes wins.**
[Answer]
# Matlab, ~~140 136 128~~ 124 bytes
Basically first starts with the middle section, and then prepends/appends the shortened/modified versions step by step.
```
a=input('');v=ones(nnz(a)*2-1,1)*a;v(2:2:end,:)=0;b=v;for k=a;v=v(2:end,1:end-1);v(end+1,:)=0;b=[v,b,v,''];end;b(~flip(b))=0
```
Thanks for 8 bytes @LuisMendo!
E.g. for `MATLAB` we get:
```
MATLAB
MATLA MATLA
MATL MATLAB MATL
MAT MATLA MATLA MAT
MA MATL MATLAB MATL MA
M MAT MATLA MATLA MAT M
MA MATL MATLAB MATL MA
MAT MATLA MATLA MAT
MATL MATLAB MATL
MATLA MATLA
MATLAB
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 44 bytes
*I took some inspiration from [@flawr's answer](https://codegolf.stackexchange.com/questions/89434/lemon-limify-a-string/89439#89439) (although the algorithm is not the same)*
```
GtnEq:!g*2Mo*XKG"K1YS3LZ)OX@:Y(PO5MY(XKwyhhc
```
Input is a string with single quotes.
[**Try it online!**](http://matl.tryitonline.net/#code=R3RuRXE6IWcqMk1vKlhLRyJLMVlTM0xaKU9YQDpZKFBPNU1ZKFhLd3loaGM&input=J0xlbW9uJw)
[Answer]
## Python 2, ~~121~~ 110 bytes
```
s=input()
n=len(s)
r=range(1,n)+range(n,0,-1)
for y in r:print''.join(s[:(x+y-n&(x+y>n))*x]or' '*x for x in r)
```
116 bytes if using `raw_input`. The program essentially does a mask based on L1-norm/Manhattan distance from the centre, as well as the parity of this distance compared to the parity of the input length.
*(Thanks to @Lynn for -9 bytes and paving the way for 2 more)*
[Answer]
# JavaScript (ES6), 132 bytes
```
s=>{x=' '.repeat(l=s.length);for(n=r='';n++<l;r=r?t+`
${r}
`+t:t)for(i=l,t='';i;t=t?w+t+w:w)w=(i<n|n+i&1?x:s).slice(0,i--);return r}
```
## Test
```
var solution =
s=>{
x=' '.repeat(l=s.length);
for(n=r='';n++<l;r=r?t+`\n${r}\n`+t:t)
for(i=l,t='';i;t=t?w+t+w:w)
w=(i<n|n+i&1?x:s).slice(0,i--);
return r
}
result.textContent = solution('Lemon');
```
```
<input type="text" id="input" value="Lemon" oninput="result.textContent=solution(this.value)" /><pre id="result"></pre>
```
[Answer]
# Pyth, 32 bytes
```
jsMCm.[tylztsmC*\ dd*;ld+J._zt_J
```
[Demonstration](https://pyth.herokuapp.com/?code=jsMCm.%5BtylztsmC%2a%5C+dd%2a%3Bld%2BJ._zt_J&input=Lemon&debug=0)
[Answer]
# Jelly, ~~32~~ 26 bytes
```
³L_+«0ị“~ ”«³ḣ
JµṖ;Ṛç@þ`j⁷
```
[Try it online!](http://jelly.tryitonline.net/#code=wrNMXyvCqzDhu4vigJx-IOKAncKrwrPhuKMKSsK14bmWO-G5msOnQMO-YGrigbc&input=&args=YXNkZg)
EDIT: Dennis saved 6 bytes. Thanks!
[Answer]
# JavaScript, ~~187~~ 178 bytes
A bitwise approach. Function `m` defines a mask by starting at `2 ** length`, e.g. `00100` in binary, and defining `m(n) = m(n-1) << 1 | m(n-1) >> 1` for the first half. Interestingly the second half can be defined as `m(n) = m(n-1) << 1 & m(n-1) >> 1`. (though the program instead opts to define `m(n) = m(2 * length - 1)` for the second half) From here these masks can be used to determine whether a word or space should appear by checking `2 ** column & m(row)`. Of course in JavaScript it's shorter to write `2 ** something` with `1 << something`...
*note: written while tired. ~~May~~ Almost surely does have mistakes.*
```
s=>{m=n=>n?n>l?m(2*l-n):(p=m(n-1))>>1|p<<1:1<<l
for(r=0;r/2<=(l=s.length-1);r++){for(i=1,o="";i/2-1<l;i++)o+=(1<<i-1&m(r)?s:" ".repeat(i)).slice(0,i>l?2*l+2-i:i)
console.log(o)}}
```
[Answer]
# Haskell, 109 bytes
```
f s|n<-length s,r<-[1..n]++[n-1,n-2..1]=unlines[do x<-r;min(" ~"!!mod((x+y+n)*min(n-x-y)0)2)<$>take x s|y<-r]
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 46 bytes
```
{a₀⟨{;Ṣ}j₎l⟩}ᶠL&l;Ṣj₍ẹa₁ᶠ;Lz{czzcᵐ}ᵐ⟨kc↔⟩zcᵐ~ṇ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoPRwV6f9o7YNj5qagKzah1sn/K9OfNTU8Gj@imrrhzsX1WY9aurLeTR/Ze3DbQt81HJAYkCh3oe7dgKVNQIFrX2qqpOrqpKBWkHagRqzkx@1TQFqAYvVPdzZ/v9/tJJPam5@npKOUk5mbiqQSgRiJxAjObEESNbU1ABJvfh4PSClUlKUmZcOZBSWZpak5uSD2QoKClpArBQLAA "Brachylog – Try It Online")
Terrible byte count and probably worse approach (not to mention Brachylog isn't exactly designed for ASCII art), but I wasted enough time on it to post it anyways.
```
L The variable L
{ }ᶠ is a list containing every possible
a₀ prefix of
the input
{;Ṣ} paired with a space
j and concatenated with itself
⟨ ₎l⟩ a number of times equal to its length.
```
```
ᶠ A list containing every possible
a₁ suffix of
Ṣ a space
j concatenated with itself
; ₍ a number of times equal to
l the length of
& the input
ẹ then split back up into its elements
is an important list which doesn't actually get a name.
```
```
That list
;Lz zipped with L
{ }ᵐ with each pair being
c concatenated,
z zipped with cycling,
z zipped back,
ᵐ and subjected to each of its elements being
c concatenated itself,
⟨kc↔⟩ then palindromized
z and zipped yet again
cᵐ with every line concatenated once more
~ṇ and finally joined on newlines
is the output.
```
Just about the only clever part of any of this is the use of `a₁` to generate the vertical spaces largest-first while `a₀` generates the word prefixes smallest-first, and `zz` to expand single spaces into blocks of space matching the widths of the prefixes.
[Answer]
# TSQL, 259 bytes
Golfed:
```
DECLARE @ VARCHAR(30)='TSQL'
,@o VARCHAR(max),@i INT=0,@j INT,@t VARCHAR(max)SET @j=LEN(@)z:WHILE @i<LEN(@)SELECT @o=x+ISNULL(@o+x,''),@i+=1FROM(SELECT LEFT(IIF((@j-@i)%2=1,@,SPACE(99)),LEN(@)-@i)x)z SELECT @j-=1,@t=@o+ISNULL(CHAR(10)+@t+CHAR(10)+@o,''),@o=null,@i=0IF @j>0GOTO z PRINT @t
```
Ungolfed:
```
DECLARE @ VARCHAR(30)='TSQL'
,@o VARCHAR(max),@i INT=0,@j INT,@t VARCHAR(max)SET @j=LEN(@)
z:
WHILE @i<LEN(@)
SELECT @o=x+ISNULL(@o+x,''),@i+=1
FROM(SELECT LEFT(IIF((@j-@i)%2=1,@,SPACE(99)),LEN(@)-@i)x)z
SELECT @j-=1,@t=@o+ISNULL(CHAR(10)+@t+CHAR(10)+@o,''),@o=null,@i=0
IF @j>0 GOTO z
PRINT @t
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/524628/lemon-limify-a-string)**
[Answer]
# [J](http://jsoftware.com/), 67 bytes
```
[:;"1@|:(#-h){.&.>"0 1]((<#)#&.>,:&''@]<@{"{~2|[)~[:+/~h=.|@i:@<:@#
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o62slQwdaqw0lHUzNKv11PTslAwUDGM1NGyUNZWBPB0rNXV1h1gbh2ql6jqjmmjNumgrbf26DFu9GodMKwcbKwfl/5pcXKnJGfkKaQrqPqm5@XnqEK66Oly4uKRI/T8A "J – Try It Online")
I may try to improve this further tomorrow.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 116 bytes
```
($r=0..($n=($a=$args).count-1)+$n..0|gu)|%{$y=$_;-join($r|%{($a[0..$_],(' '*($_+1)))[($_+$y+$n)%2-or($_+$y)-lt$n]})}
```
[Try it online!](https://tio.run/##PYtLCoMwEED3OUUWY5OpJmi3JSBd9wYiIhJtiybFD0XUs9tY285iePOG97Qv3XY3XdcrlGpaObQqlJKDURxyBXlbdSgLO5heROiDkTKcqwFnb4JRQXYWD3s3rnLCBYlrIUsDzig7csj8CBGTDWB0MXonYdv9RFH3YNIFl3UhJOaEumE5C3a4aEa/WOT9z17vjf6zbqxhBOlMPTp93AFKGmf7m22bLOsb "PowerShell – Try It Online")
Unrolled:
```
$a=$args
$n=$a.count-1
$range=0..$n+$n..0|Get-Unique
$range|%{
$y=$_
$line=-join(
$range|%{
$word=$a[0..$_]
$space=' '*($_+1)
$switch=($_+$y+$n)%2-or($_+$y)-lt$n
($word,$space)[$switch]
}
)
$line
}
```
[Answer]
# [J](http://jsoftware.com/), 49 bytes
```
3 :';"{((]<@{.y''''&[~2&|@+<:>)"+/e&-)|i:1-e=.#y'
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jRWs1K2VqjU0Ym0cqvUq1YFALbrOSK3GQdvGyk5TSVs/VU1XsybTylA31VZPuVL9vyZXanJGvkK6grpPam5@njqcW1xShOAkJiUlqv8HAA "J – Try It Online")
### How it works
```
3 :';"{((]<@{.y''''&[~2&|@+<:>)"+/e&-)|i:1-e=.#y'
3 :'...' Explicit function definition; right arg(y) = given string
|i:1-e=.#y e = length of y; create array of [e-1 .. 0 .. e-1]
((]<@{.y''&[~2&|@+<:>)"+/e&-) Create boxed lemon shape:
e&- Create array of [1 .. e .. 1]
( )"+/ Outer product with [e-1 .. 0 .. e-1]
(left item = a, right item = b)
2&|@+<:> (a+b)%2 <= (a>b)
y''&[~ If above is true, use '' (empty string)
otherwise use y
] {. Take first b chars from above
(fill with blanks if needed)
<@ Box it
;"{ Unbox and concatenate each row from the table (outer product)
Result is the matrix of chars, giving the lemon shape
```
[Answer]
# C, 167 bytes
This program expects the input text to be passed as the first parameter to the program (via command line or however else) and will write the output to stdout.
```
int i,j,k,l,v;main(h,s)char**s;{h=strlen(s[1]);l=h*2;for(;++i<l;puts(""))for(j=0;++j<l,v=j<h?j:l-j;)for(k=0;k++<v;putchar((i+j+h%2)%2&&v>h-(i<h?i:l-i)?s[1][k-1]:32));}
```
This is my first attempt at code golf here as it seemed like a reasonable challenge, so it can probably be golfed more than I was able to just due to how I did it.
### Explanation
```
/* Static variables
i - "Row" number
j - "Column" number
k - String character counter
l - Double length of the input string
v - Inverted column distance from center */
int i,j,k,l,v;
/* Main parameters
h - (argc) Input string length
s - argv */
main(h, s)
char**s;
{
/* Assign the input string length and double length */
h = strlen(s[1]);
l = h * 2;
/* Display content */
/* Loop over rows l - 1 times and put a newline after each */
for (; ++i < l; puts(""))
/* Loop over columns l - 1 times and set the inverted column
distance each time */
for (j = 0; ++j < l, v = ((j < h) ? j : l - j);)
/* Loop over characters up to the inverted column distance from the
center (this generates the pattern of output lengths needed) */
for (k = 0; k++ < v;)
putchar(
/* Check for if the current row + column (with an offset based on
the input parity) parity is even or odd, creating the needed
checkerboard pattern */
(i + j + h % 2) % 2 &&
/* If the inverted column distance from the center is more than the
row distance from the center, then the cell is inside the
circular shape */
v > (h - ((i < h) ? i : l - i)) ?
/* Display the requested character (minus one for 0 based) */
s[1][k-1] :
32 /* Otherwise display a space (ASCII 32) */
);
}
```
It is significant enough to note the usage of `(n < m) ? n : (m * 2) - n` in the program at least twice to get the inverted distance from a center position `m` on a range of `m * 2` with the input `n`. If there is a shorter way to do that then it could be golfed down some more easily as that algorithm is important for how this program works.
[Answer]
# C, 137 bytes
```
x,y,w;main(l,v)char**v;{for(y=l=strlen(v[1]);-l<--y;putchar(10))for(x=l;-l<--x;printf("%*.*s",w,w,x+y+l&1&&w>abs(y)?v[1]:""))w=l-abs(x);}
```
Breakdown:
This draws every element of the 2n-1 x 2n-1 grid, with a mask function deciding whether the current element should be blank space or the input word (the mask checks for a diamond shape and checkerboard pattern).
```
x,y,w;
main(l,v)char**v;{
for(y=l=strlen(v[1]);-l<--y;/*...*/) // row loop (count down to save bytes)
for(x=l;-l<--x;/*...*/) // column loop
w=l-abs(x); // calculate current word's width
printf("%*.*s", // print...
w,w, // ...with min & max width...
x+y+l&1&&w>abs(y) // Check mask:
?v[1] // ...word
:"") // ...or blank space
putchar(10) // Newline
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~27~~ 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ηεN>иygðש.ýIgN-<®и.ø}ûøJ»
```
[Try it online](https://tio.run/##AUAAv/9vc2FiaWX//863zrVOPtC4eWfDsMOXwqkuw71JZ04tPMKu0Lguw7h9w7vDuErCu///TGVtb27/LS1uby1sYXp5) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TpuSZV1BaYqWgZF95eEKYDpeSf2kJREDn/7nt57b62V3YUZl@eMPh6YdW6h3eG5nup2tzaN2FHXqHd9Qe3n14h9eh3f91Dm2z/@@Tmpufx5WTmZvKlcjllMqlH8OVnFjCVVNTw6UXH6/HpVJSlJmX/l9XNy9fNyexqhIA).
**Explanation:**
```
η # Get a list of prefixes of the (implicit) input-String
ε # Map each prefix `y` to:
N> # Get the (0-based) map-index, and increase it by 1 to make it 1-based
и # Repeat the current substring that many times as list
yg # Push prefix `y` again, and pop and push its length
ð× # Create a string of that many spaces
© # Store this spaces-string in variable `®` (without popping)
.ý # Intersperse the earlier list with this spaces-string
Ig # Push the input, and then pop and push its length
N- # Subtract the (0-based) map-index
< # And decrease it by 1 more
®и # Repeat spaces-string `®` that many times as list
.ø # Surround the earlier list with this list as both leading and trailing portion
}û # After the map: palindromize (abc → abcba) the entire list of lists
ø # Zip/transpose; swapping rows/columns
J # Join each inner list together to a single string
» # And join those strings by newlines
# (after which the result is output implicitly)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~120~~ ~~118~~ ~~109~~ 105 bytes
```
x=>(l=x.length,g=(F,i=1,w=F(i))=>i<l?w+g(F,i+1)+w:w)(y=>g(a=>a+y+l&a+y>l?x.slice(0,a):" ".repeat(a))+`
`)
```
[Try it online!](https://tio.run/##VYpBCoMwEADvvqLkUHZJGupVuvHmOww2pimrEZVGX5/qrb0MzDBv@7FLN4dpvY3x6XJPeSMDTJtmN/r1pTxBowKVKlEDAZFMeHCdpD@zLFGmKiHsZDxYMlbukq8HDdebXjh0Du7KYiUuQs9ucnYFiyjbosXcxXGJ7DRHDz0IdkMcBWLx24X49/MLgzu2/AU "JavaScript (Node.js) – Try It Online")
A bunch of bytes are shaved thanks to the similar structures of the nesting functions. I was confident that this golf could save some bytes but not that much.
```
x=>( // Main function:
l=x.length, // l = Length of x
g=( // Nesting function:
F, // Output-generating function
i=1, // Counter (initially 1)
w=F(i) // The output at that counter value
)=>
i<l // If not the center line/block:
?w+g(F,i+1)+w // Sandwich next iteration with output
:w // Otherwise: Return the output
)( // Call the nesting function with
y=> // Outer nest: Generating lines
g( // Call the nesting function with
a=> // Inner nest: Generating blocks
a+y+l&a+y>l // If the position should not be space:
?x.slice(0,a) // Output the first a characters of x
:" ".repeat(a) // Otherwise: Output a spaces
)+"\n" // Append the line with a newline
)
```
### Original 118-byte answers:
```
F=(x,i=1,t=x.length,w=(G=(j,A,B,c=i+j+t&1&i+j>t?A:B)=>j<t?c+G(j+1,A+x[j],B+' ')+c:c)(0,'','')+`
`)=>i<t?w+F(x,i+1)+w:w
```
[Try it online!](https://tio.run/##FY3RCoIwFEDf@4rwQTfuTdqrdBV90I@IQFmzNtYWOZp/vxYcOC8Hjlm@yyY/@h1Ozt9VWimNxHbUJDDQXlvlHuGJkdhEzGCPA0rSYCCUosxuQ9c3A6fWXEInYWIGBPawX80NB6iOFQfZSM7OWFUZDvNhzrXOdYTxPwLBITYxSe82b1Vt/YOtrLDq5V3BefoB "JavaScript (Node.js) – Try It Online")
```
F=(x,i=1,t=x.length,w=(G=(j,c=i+j+t&1&i+j>t?x.slice(0,j):" ".repeat(j))=>j<t?c+G(j+1)+c:c)(1)+`
`)=>i<t?w+F(x,i+1)+w:w
```
[Try it online!](https://tio.run/##Fc2xDoMgFEDRvV/RMJhHoKSupk83/Q0NRcsLBSOk@PcUpzuc4dLyW6I@7J4ePrxNWbGMCKe02MqEp3LGb@kjM8KEQFKjFSRS0za1fRpOFZ3VBp6SeMfuTB1mN0sC4hx7eqVBiwlItFzoTnOonW9zJVspi/EaXZi7XHTwMTijXNhgBebMN3jGefkD "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
**Intro**
This is based on an actual problem I recently faced while making a computer game and I thought it would make for a nice round of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
There are seven main [spectral classes](https://en.wikipedia.org/wiki/Stellar_classification) of star which put out varying amounts of heat. The geology of planets around a star are greatly influenced by the amount of heat received from the star, which is a factor of spectral class and distance from the star. Hence Mercury is practically molten, Neptune frozen.
The galaxy in my game is procedurally generated and randomly selecting planet types for given stars turned out to be a real 'if statement hell'!
**The challenge**
Your method should select one planet from a list of planet types appropriate for the class of star, based on a minimum heat threshold, a maximum heat threshold and a random number.
For simplicity this challenge will only use a class G star, just like our sun.
**Inputs**
An integer `heat` in the range 4 to 11 representing the amount of heat received by the planet from the star.
**Variables**
This table shows the possible planets based on `heat`. Your method should first narrow the available choices based on the heat min and heat max, `heat` should fall on or between the two. E.g. with a heat of 10 passed in the only choices would be Desert, Iron and Lava.
```
Planet type Heat min Heat max Random Chance
Gas Giant 4 9 15
Ice 4 6 10
Ice Giant 4 6 10
Gaia class 5 7 10
Dense Atmosphere 7 9 10
Desert 7 10 25
Iron 7 10 14
Lava 10 11 6
```
Next, the probability of a planet (in the remaining choices) being chosen is its random chances divided by the sum of the random chances of all the choices.
In the above example, the probability of Iron being chosen is `14/(25+14+6)`.
**Output**
Return the planet type as a string.
Do the best you can to avoid logic arrowheads. Shortest code wins, points all round for creativity. Happy golfing!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~78~~ 75 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“'ĖøÆḳƙ’ḃ7ṣ6Ä+3r/ċ€×“½½½½©ÐÇı‘
“ŀỊẋ8ƒ³ẈRɼƈñqẋẏȧɱḌ<ṄỴḳ⁾ÆʋeẒĊ'@ƬØƓƝ}ḟ¬»Ỵx'ÇX
```
A monadic link accepting an integer (in **[4,11]**) which returns a list of characters.
**[Try it online!](https://tio.run/##y0rNyan8//9Rwxz1I9MO7zjc9nDH5mMzHzXMfLij2fzhzsVm2jHaxkX6R7ofNa05PB2o7NBeKFx5eMLh9iMbHzXM4AIKH214uLvr4a5ui2OTDm1@uKsj6OSeYx2HNxYChR7u6j@x/OTGhzt6bB7ubHm4ewvQikeN@w63nepOfbhr0pEudYdjaw7PODb52NzahzvmH1pzaDdQUYX64faI////mwIA "Jelly – Try It Online")**
### How?
Creates the heat ranges of the planets as a list of lists and counts the occurrences of the input heat in those lists to get a list of zeros and ones representing which planet types are possible, then multiplies by the likelihood numbers of the eight planet types to get the distribution. The distribution is used to repeat the planet type names, and finally, a uniform random choice is made.
```
“'ĖøÆḳƙ’ḃ7ṣ6+\+3r/ċ€×“½½½½©ÐÇı‘ - Link 1, getDistribution: integer
“'ĖøÆḳƙ’ - base 250 integer = 39824688429662
ḃ7 - to bijective-base 7 = [1,1,2,4,7,1,4,4,6,2,2,2,2,1,5,3,3]
ṣ6 - split at sixes = [[1,1,2,4,7,1,4,4],[2,2,2,2,1,5,3,3]]
+\ - reduce by addition = [[1,1,2,4,7,1,4,4],[3,3,4,6,8,6,7,7]]
+3 - add three = [[4,4,5,7,10,4,7,7],[6,6,7,9,11,9,10,10]]
r/ - reduce by inclusive range = [[4,5,6],[4,5,6],[5,6,7],[7,8,9],[10,11],[4,5,6,7,8,9],[7,8,9,10],[7,8,9,10]]
ċ€ - count (input) in €ach e.g. for 5: [1, 1, 1, 0,0, 1, 0, 0]
“½½½½©ÐÇı‘ - list of code-page indices [10,10,10,10,6,15,14,25]
× - multiply [10,10,10, 0,0,15, 0, 0]
“ ... »Ỵx'ÇX - Main link: integer
“ ... » - compressed string = "Ice\nIce Giant\nGaia class\nDense Atmosphere\nLava\nGas Giant\nIron\nDesert"
Ỵ - split at new lines = ["Ice","Ice Giant","Gaia class","Dense Atmosphere","Lava","Gas Giant","Iron","Desert"]
Ç - call last link (1) as a monad e.g. for 5: [10,10,10,0,0,15,0,0]
' - spawn:
x - times e.g. for 5: ["Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant"]
X - a random choice from that list
```
[Answer]
# [R](https://www.r-project.org/), ~~225~~ ~~223~~ 183 bytes
Thanks to Giuseppe for clever refactoring to take it down to 188 bytes; the remaining five were shaved off by using less redundant number representations.
```
i=scan()-4
sample(c("Gas Giant","Ice","Ice Giant","Gaia class","Dense Atmosphere","Desert","Iron","Lava")[l<-c(0,0,0,1,3,3,3,6)<=i&c(5,2,2,3,5,6,6,7)>=i],1,,c(3,2,2,2,2,5,2.8,1.2)[l])
```
[Try it online!](https://tio.run/##PYzbCsIwDIZfZfRCWsjGDm4KboIgDME3kF2EErDQdaMZvn7tKsgHCfkP8SGYgTU6qfLjhXFeLUktxYicjQbdJkA8NP3mXxnRYKYtMsfjTo4pu23zwuubPCWJyaeqX1xcT/ygUC/b51qWsFNBk@hUP5iDli3UkQZa6CIndR3MFEOgZZOcnZgpzlAVdfw0qVCV4Qs "R – Try It Online")
[Answer]
# JavaScript 212
**Edit** 6 bytes save thx Jonathan Allan
```
h=>[963,640,640,649,667,1628,924,437].map((z,i)=>(z/8&7)+4>h|z%8+6<h?0:t=r.push(...Array(z>>6).fill(i)),r=[])&&"Gas Giant,Ice,Ice Giant,Gaia class,Dense Atmosphere,Desert,Iron,Lava".split`,`[r[t*Math.random()|0]]
```
*less golfed*
```
h=>(
r = [],
// heat min,max and chance encoded in base 8 with offsets
// min range 4 to 10, with offset 4, 0 to 6
// max range 6 to 11, with offset 6, 0 to 5
[(4-4)*8 + 9-6 + 15*64,
(4-4)*8 + 6-6 + 10*64,
(4-4)*8 + 6-6 + 10*64,
(5-4)*8 + 7-6 + 10*64,
(7-4)*8 + 9-6 + 10*64,
(7-4)*8 + 10-6+ 25*64,
(7-4)*8 + 10-6+ 14*64,
(10-4)*8+ 11-6+ 6*64]
.forEach( (z,i) => (
min = (z / 8 & 7) + 4,
max = z % 8 + 6,
chance = z >> 6,
min > h || max < h
? 0 // out of range
// add current position i repeated 'chance' times
// array size in t
: t = r.push(...Array(chance).fill(i))
),
pos = r[t * Math.random() | 0],
["Gas Giant", "Ice", "Ice Giant", "Gaia class", "Dense Atmosphere", "Desert", "Iron", "Lava"][pos]
)
```
*Test*
```
var F=
h=>[963,640,640,649,667,1628,924,437].map((z,i)=>(z/8&7)+4>h|z%8+6<h?0:t=r.push(...Array(z>>6).fill(i)),r=[])&&"Gas Giant,Ice,Ice Giant,Gaia class,Dense Atmosphere,Desert,Iron,Lava".split`,`[r[t*Math.random()|0]]
function test()
{
var heat=+H.value
var i,result,hashtable={},rep=1e5
for (i=0;i<rep;i++)
result = F(heat),
hashtable[result] = -~hashtable[result]
console.log('Input',heat)
for (i in hashtable)
{
console.log(i,(hashtable[i]/rep*100).toFixed(2),'%')
}
}
```
```
<input id=H type=number min=1 max =15 value=10>
<button onclick='test()'>Test</button>
```
[Answer]
# [Coconut](http://coconut-lang.org/), ~~214~~ 195 bytes
```
t->choice..sum([[n]*g(p)*(g(a)<t<g(b))for*n,a,b,p in'Gas Giant3AF_Ice37A_Ice Giant37A_Gaia class48A_Dense Atmosphere6AA_Desert6BP_Iron6BE_Lava9C6'.split('_')],[])
from random import*
g=int$(?,36)
```
[Try it online!](https://tio.run/##fVA7a8MwGNz9K74hIMkogtbBbSF2cfowgQ7ZXWMUVXZkYklIXzr1v7tOKXTrdA/uODjllLMXnPvifcZ1qU7OKC1EvEy0aWybDtSzlA5Usi1uB3pkrHchtVzyI/dgLKllhNpIi1n12u2Vzu6qK/x6i6ilkaDOMsbNfdU9axs1VDi56E866Ly6elEHzHeHbh@czXcv3Zv8lA9PORHRnw1S0hHW8qZlSR/cBEHajwXM5F3ANBkKY3FFH3mWs3mEAggRozM2WXKDphsON7cMvkqYpF9RhHUJFDmMQvQU2T@E/bV8WDZ@5HLXco6evwE "Coconut – Try It Online")
A Python port would be ~~203~~ 200 bytes long:
```
lambda t:choice(sum([[n]*int(p,36)*(int(a)<t<int(b,36))for*n,a,b,p in'Gas Giant3AF_Ice37A_Ice Giant37A_Gaia class48A_Dense Atmosphere6AA_Desert6BP_Iron6BE_Lava9C6'.split('_')],[]))
from random import*
```
[Try it online!](https://tio.run/##LY/LasMwEEX3@YrZ6YEItDZua5KF00cIdNG9a8zYkWsVayQktdCvdy3I6tw5qzP@L82OinU6fq4L2uGKkOpxdmbUPP5Y3rbUSUOJe1VUQvI8URzSIY8hOzG5IEmhGpQHQ@yMEc4GKRXNW38ZdfHQZNzcdpzRIIwLxlg@Nv2LpqihSdZFP@ugqya7qEOqTh/9JTiqTq/9O/7i03PF9tEvJnHWM9GpthNiNwVnISBdNxjrXUhy3YrAbC3Zf2leKri7F/UOwIecbRRIi57f/qWasf23M8QnTkIoaE0ny41R@yNTwMT6Dw "Python 3 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~115~~ 111 bytes
```
≔I⁻N³θF⁸«≔§⪪”↷&∧⬤.YLφκ¦(⁼;σ≕]✂↙ζC” ιη¿›θη¿‹θ§η¹FI✂η²⊞υ黧⪪”↓(″1↨▷]U,&ζ^iI″RSY≡´⍘'#﹪υVw5Vu>D<U5r6⁰Q▷Z◨⌕⁸ΣεCZ”¶‽υ
```
[Try it online!](https://tio.run/##XY/BasMwEETP8VcsPsnggpXESYpPoQVjSEtorr5sHaUW2GtHK4VC6be7kttcetCDHbEzs02Lphmwm6Y9s/4g8YRsxYsmx6Ki0dlX178rI5IUVonHNSmiy2BA7BL4ihZ/S3tb0Vl9itPYaSvibCtzyNYy@4XMPVbbgN0y95Br2Dxu4hRiiL2n9q/1vgt9AVEahdYHXoOWQJAOijnM95Q2BZn4v7nH3PfU6UYFfRn0o@NWuOBbRN/R0Wiy/xuWyFBqJFtT1agZ97lEjdB0yFzTsyJWPrcfeGyVUUFhZcKWGaimA97Q31BTOOMN6Tz0wvkKxTTJbHq4dT8 "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 4 bytes thanks to @ASCII-only. Explanation:
```
≔I⁻N³θ
```
Subtract 3 from the input so that it can be compared against single digits.
```
F⁸«≔§⪪”↷&∧⬤.YLφκ¦(⁼;σ≕]✂↙ζC” ιη
```
Split the string `0715 0410 0410 1510 3710 3825 3814 696` on spaces (spaces seem to compress better than commas but I didn't try any other characters) and loop over each portion.
```
¿›θη¿‹θ§η¹FI✂η²⊞υι»
```
Compare the input against the first and second digits and if it's between then push the loop index the given number of times to the predefined empty list, thus populating it.
```
§⪪”↓(″1↨▷]U,&ζ^iI″RSY≡´⍘'#﹪υVw5Vu>D<U5r6⁰Q▷Z◨⌕⁸ΣεCZ”¶‽υ
```
Split the list of planets on newlines (again, better than commas for some reason) and select the element corresponding to a index chosen randomly from the list.
[Answer]
# [R](https://www.r-project.org/), ~~196~~ ~~193~~ ~~190~~ ~~175~~ 171 bytes
```
sample(readLines(,8),1,,c(3,2,2,2,2,5,2.8,1.2)*((x=scan()-3)>c(0,0,0,1,3,3,3,6)&x<c(7,4,4,5,7,8,8,9)))
Gas Giant
Ice
Ice Giant
Gaia class
Dense Atmosphere
Desert
Iron
Lava
```
[Try it online!](https://tio.run/##LcvdCoJAEAXg@30Kr2ImJsmf0qCCIJDAlxi2gQRdZUfCt9/WkI9zcQ4cH4LyMPUCXvjddk4UqEbKiCwUlG9OlKc1ZWmOe4DlppYd4KHAu4UjrTIq/s64W64WKiqjE1VURxdENA1r0nTsZvOysmZrDXec2J5VzVOcSvKYh1Gnj3iJg4qPBz860/KXQxl@ "R – Try It Online")
Initially inspired by [this](https://codegolf.stackexchange.com/a/156683/78274) solution by @rturnbull, however as both submissions have significantly evolved, this is now essentially a mix of ideas of the original author, @Giuseppe who has been very helpful in comments, and mine. Here is a summary of key points that helped to bring the byte count down:
* ~~Encoding planet data as CSV~~ Collecting names with `readLines` to avoid the large number of quotation characters around strings.
* Tweaking the heat params so that we could use `<` and `>` signs
instead of `<=` and `>=`.
* ~~Changing the heat data format from `Heat min, Heat max` to `Heat min,
Heat Delta` to get rid of double digit numbers.~~
Replaced by shifting all numbers by -3
* Dividing all planet probabilities by 5 which also results in a few less digits.
* Multiplying the vector of planet probabilities with the vector of Booleans (indicating whether our input satisfies the heat requirements) to nullify the probabilities of unsuitable planets.
~~Probably, a few more bytes could be gained by applying some sort of data compression.~~
I think, not anymore.
[Answer]
# [Octave](https://www.gnu.org/software/octave/) with Statistics Package, ~~178~~ ~~176~~ ~~174~~ 158 bytes
```
@(h)randsample(strsplit('Gas Giant,Ice,Ice Giant,Gaia class,Dense Atmosphere,Desert,Iron,Lava',','),1,1,('UPPPP_TL'-70).*(h>'IIIJLLLO'-70&h<'PMMNPQQR'-70)){1}
```
The code defines an anonymous function that inputs a number and outputs a string.
[**Try it online!**](https://tio.run/##LYvBCsIwEETvfkVOJpFYzEEEsaIglErUKnqWpW5poSYlG72I316jOI85zDDjygBP7Ks0SZJ@JWrpwd4I7l2LgoKnrm2C4BkQyxqwQeUlfv1PGTTAyhaI1AYtIVuHu6OuRo@xIPTx4J1VBp7AVUQqHRH8UkRdz4aPZxOZjES95Hmeb40xh281rBe82O32xfF4@k3kS7/7ynlWuocNLGV6rqeDSuiJHKC99R8)
### Explanation
The code
```
@(h)
```
defines an anonymous function with input `h`.
The string
```
'Gas Giant,Ice,Ice Giant,Gaia class,Dense Atmosphere,Desert,Iron,Lava'
```
is split at commas using
```
strsplit(...,',')
```
The result is a cell array of strings, where each string is a planet class.
The code
```
'IIIJLLLO'-70
```
defines the shown string and subtracts `70` from the code points of its chars. This gives the array of minimum heat values *minus 1*, that is, `[3 3 3 4 6 6 6 9]`.
Similarly,
```
'PMMNPQQR'-70
```
produces the array of maximum heat values *plus 1*, that is, `[10 7 7 8 10 11 11 12]`.
The comparisons
```
h>...&h<...
```
give an array containing `true` or `false` indicating which planet classes are possible.
On the other hand,
```
'UPPPP_TL'-70
```
defines the array of random chance values, `[15 10 10 10 10 25 14 6]`.
The operation
```
(...).*(...)
```
is the element-wise multiplication of the latter two arrays (`true` and `false` behave like `0` and `1` respectively). This gives an array where each planet class has either its random chance, or `0` if that class is not possible based on the input. This array will be used as weights in the random sampling
The function call
```
randsample(...,1,1,...)
```
selects one of the cells from the cell array of strings (first input argument), using the computed array of weights (fourth input argument). Specifically, the function `randsample` automatically normalizes the weights to probabilities, and then does the random selection with those probabilities. The result is a cell array containing a string. The code
```
{1}
```
is used to extract that string, which constitutes the function output.
[Answer]
# [Python 3](https://docs.python.org/3/), 263 bytes
```
from random import*
P=lambda h:"Gas Giant|Ice|Ice Giant|Gaia class|Dense Atmosphere|Desert|Iron|Lava".split("|")[choices(*list(zip(*filter(lambda x:h in range(*x[2:]),zip(*[[int(x,32)for x in"0f4a1a472a473a584a7a5p7b6e7b76ac"][a::4]for a in(0,1,2,3)]))))[:2])[0]]
```
[Try it online!](https://tio.run/##TY5Pa8MwDMXv/RTGJzsLo/nTZhh2GAzKYIfejRlq6iyCxDa2GdmafvbMKYVN8BCS3uMn9x17a6pl6bwdiQdzTg1HZ33MNsfnAcbTGUgv6AECOSCYOL@1etV9OgACaQcIYX7VJmjyEkcbXK@9TougfQp4a@Z3@AL6GNyAkdGZctn2FlsdWDZgiOwHHcs6HKL27A6dRE/QrD99apZNshSK5zeflGgim/Kq5J31ZEo2uu1qKKBuyqQKdk81NLBzzWmvm1Ozh5YqCULUag1ACrBtXuRlXnHFU0lRKi63Si3rHf@4dV4UDwUXG0KcX6kdveCVCHKRR4Y3/Mc/N1dXypdf "Python 3 – Try It Online")
[Answer]
# Python 3, ~~199~~ 194 bytes
```
from random import*
lambda n:choices("Ice|Ice Giant|Gas Giant|Gaia class|Dense Atmosphere|Desert|Iron|Lava".split('|'),[(0x33b2a53d4a>>5*i&31)*(0xc07878380e3f0707>>8*i+n-4&1)for i in range(8)])
```
Splitting `h` into separate bit masks and random chance values (see explanation) saves a few bytes by eliminating an assignment to `h` and simplifying the `range()` in the list comprehension.
### Previous solution
```
from random import*
h=0xc033c39e3270a0e51fbc1d40ea
lambda n:choices("Ice|Ice Giant|Gas Giant|Gaia class|Dense Atmosphere|Desert|Iron|Lava".split('|'),[(h>>i&31)*(h>>i+n+1&1)for i in range(0,104,13)])
```
Defines an anonymous function that takes an int and returns the planet type.
For each planet type, a 13-bit value was calculated. The top 8 bits define a bit mask of valid heat values for that planet type. The bottom 5 bits are the random chance for that planet type. For example, "Gaia class" is a valid type for heat values 4 to 7, so it has a mask of `0b00001111`. It has a random chance of 10, or `0b01010`. Combining them results it the 13-bit value `0b0000111101010` for the "Gaia class" type. The 13-bit values for each planet type are concatenated to get the value for `h` (the lowest 13 bits are for the "Ice" planet type). (The newer answer doesn't combine these values).
The list comprehension iterates over the 13-bit values to create a list of weights, where the weight is the random chance if the planet type is a valid choice for the given heat value, and zero otherwise. For each planet type, `(h>>i&31)` extracts the random chance for that planet type. `(h>>i+n+1&1)` evaluates to 1 if the planet type is a valid choice for the heat value `n` and evaluates to 0 otherwise.
The library function `random.choices(choices, weights)` selects an item from the list of choices based on the list of weights.
[Answer]
# Python, ~~282 Bytes~~, 261 Bytes:
```
from random import*
i,p,l=input(),[('Gas Giant',3,11,15),("Ice",3,7,10),("Ice Giant",3,7,10),("Gaia Class",4,8,10),("Dense Atmosphere",6,10,10),("Desert",6,11,25),("Iron",6,11,14),("Lava",9,12,6)],[]
for x in p:exec"l+=x[0],;"*(x[1]<i<x[2])*x[3]
print choice(l)
```
Pretty simple - fairly sure it could be golfed more - Still looking for a better way to represent the planet range and probability data.
If i is in range of the planet type, appends it to the list according to the probability, then randomly prints one.
EDIT: With credit to Jonathan Frech - redid the for loop to knock a few bytes off. Better way of appending items to the list
[Answer]
# [Perl 5](https://www.perl.org/) (`-p`), 230 bytes
```
@a=(['Gas Giant',4,9,15],[Ice,4,6,10],['Ice Giant',4,6,10],['Gaia class',5,7,10],['Dense Atmosphere',7,9,10],[Desert,7,10,25],[Iron,7,10,14],[Lava,10,11,6]);//;map{push@b,($$_[0])x($$_[3]*($$_[1]<=$'&&$'<=$$_[2]))}@a;$_=$b[rand@b]
```
[Try it online!](https://tio.run/##Rc3RCsIwDAXQX9lDsU6ituoUmYMJwhD0C0YZmRYcaFfaKYL469ZSFZ9uTnIhWppz4lyOWb@kBdqoaFB1FGawBJ4IKLcH6TEHzjyo17/xWxbYYHQ4o7UUElh8txuprIzW3aW1@iSNpP6y/Nw20krThSZMwhPTqg/5zHOHNwzgMBdxOh6nF9QPfbWnvIY@IVXJRHwPw1QMQnKxygjt9Qj16T0RcfzMMSVVRurSoDrmtXCOs1eru6ZV1g33yYhx5ob6DQ "Perl 5 – Try It Online")
[Answer]
# [Nim](https://nim-lang.org/), ~~~~314~~ 298~~ 294 bytes
```
import random,sequtils
proc c(h:int)=
var a= @[""]
a.del 0
for n in[("Gas Giant",4,9,15),("Ice",4,6,10),("Ice Giant",4,6,10),("Gaia Class",5,7,10),("Dense Atmosphere",7,9,10),("Desert",7,10,25),("Iron",7,10,14),("Lava",10,11,6)]:(if h>=n[1]and h<=n[2]:a.add repeat(n[0],n[3]))
echo random a
```
For loop now in one line, no return, less bytes to implicit type
4 spaces removed (thanks [Kevin](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen))
[Try it online!](https://tio.run/##RZDBasMwEETv/opFJwlEsFMnoaYuLS2YQP7A@LBYGyywV66k5NCfd@3Yobedp9lZNGyHabLD6HwEj2zcoAP93KLtQzJ610Iru8JyVGUCd/SAJXzUQjQJ4M5QD2kCV@eBwXItRYUBKoschc71q84OSktxbmmRR52lm/z3PGGFFuGrxxCEPujTRr@JA8FnHFwYO/JzzGlJ3d4C@SgeXr1fD3nHG8jyBVzwjuIhM31UTSHtFbr3kuusmb8K3ds87psCd2gMeBoJo@Q6bTTXL41SCVDbua0WwGdNIfq1n54i8G2AEkb0gc4cpSc0F8skQzSW54h12f6SVEkrZ7ea8j8 "Nim – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~78~~ 76 bytes
```
”Œï²°™Ä²° Gaia classêη•™Äµ‰Ÿ± Lava”#8äðýā<•ŒEŽuS,•2ôו9èÁnÇ∞Λ•SÌ2ôεŸIå}ÏSΩè
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UcPco5MOrz@06dCGRy2LDreAGAruiZmJCsk5icXFh1cd7ju0/VHDIojk1kcNG47uOLRRwSexLBGoVdni8JLDGw7vPdJoA1RzdJLr0b2lwTpAptHhLYenA2nLwysON@Ydbn/UMe/cbCA/@HAPUOrc1qM7PA8vrT3cH3xu5eEV//@bAQA "05AB1E – Try It Online\"")
**Explanation**
`”Œï²°™Ä²° Gaia classêη•™Äµ‰Ÿ± Lava”`
pushes the string `Gas Giant Ice Giant Gaia class Dense Atmosphere Ice Desert Iron Lava`
```
# # split on spaces
8ä # divide into 8 parts
ðý # join each by spaces
ā< # push the range [0 ... 7]
•ŒEŽuS,• # push 151010101025146
2ô # split into pieces of 2
# results in [15, 10, 10, 10, 10, 25, 14, 6]
× # repeat each number in the range by these amounts
# results in ['000000000000000', '1111111111', '2222222222', '3333333333', '4444444444', '5555555555555555555555555', '66666666666666', '777777']
•9èÁnÇ∞Λ• # push 2724355724585889
S # split to list of digits
Ì # decrement each twice
# results in [4,9,4,6,5,7,7,9,4,6,7,10,7,10,10,11]
2ô # split into pieces of 2
# results in [[4, 9], [4, 6], [5, 7], [7, 9], [4, 6], [7, 10], [7, 10], [10, 11]]
εŸIå} # apply to each pair
Ÿ # range [a ... b]
Iå # check if input is contained in the range
# ex, for input 10: [0, 0, 0, 0, 0, 1, 1, 1]
Ï # keep only the indices which are true
# ex, for input 10: ['5555555555555555555555555', '66666666666666', '777777']
S # split to list of digits
Ω # pick one at random
è # index into the list of strings with this
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~214 193~~ 189 bytes
```
->h{'Gas Giant,Desert,Iron,Lava,Ice,Ice Giant,Gaia class,Dense Atmosphere'.split(?,).zip(31006330.digits,75449887.digits,[15,25,14,6]).flat_map{|n,m,x,r|m<h-3&&x>h-3?[n]*(r||10):[]}.sample}
```
[Try it online!](https://tio.run/##NYrrqoJAFEZfxV@lsRs0tcvhVASBBL2BiOxqzAFnHGbvoos9uxWc8@NjsVifuxzufbXsx6v6OcyQvEyhYdhKko5h51oDe7wi7I7yu7@coULv2CDR52lIehvWLdlaOjkUZBvF/hoC8VDWj6MwnMZxKE7qrJhglibJYj6f/XsepTBJIUpgWgSiapBLjfbZGdBwA9fp33ocDwa31Qfr3BQj33VdFAY/efEShNo28tVbpwx7VX6WTILbUhV9@gY "Ruby – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~377~~ ~~364~~ ~~358~~ ~~318~~ ~~312~~ ~~270~~ ~~265~~ ~~262~~ ~~256~~ 251 bytes
```
import System.Random
f h|x<-[n|(n,(a,b,c))<-zip(lines"Gas Giant\nIce\nIce Giant\nGaia class\nDense Atmosphere\n
Desert\nIron\nLava")$zip3[4,4,4,5,7,7,7,10][9,6,6,7,9,10,10,11][15,10,10,10,10,25,14,6],h<=
b,h>=a,_<-[1..c]]=(x!!)<$>randomRIO(0,length x-1)
```
(I've added linebreaks for nicer printout). The task says "return", not "print", so `f` is a function which returns the randomly selected planet name into the `IO` monad, `f :: Int -> IO String`.
The `main` is `main = do {f 10 >>= print}` ([Haskell golfing tips](https://codegolf.stackexchange.com/a/107238/5021) says it doesn't count). Prints
>
>
> ```
> "Iron" -- or "Desert", or "Lava"
>
> ```
>
>
(edits: removed `&`'s base case; moved `main` out; changed to quadruples and `unzip`, and switched to pattern guards and `>>=` following [suggestions](https://codegolf.stackexchange.com/questions/156666/create-a-solar-system/156788?noredirect=1#comment382046_156788) [from](https://codegolf.stackexchange.com/questions/156666/create-a-solar-system/156788#comment382062_156788) [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni), thanks!; implemented the approach from the [Jelly solution](https://codegolf.stackexchange.com/a/156674/5021) instead, repeating the names; explicit type is no longer needed; another advice by Laikoni saves 3 more bytes; made it an `IO` function; implemented [advice](https://chat.stackexchange.com/transcript/message/43111195#43111195) from the chat room).
[Try it online!](https://tio.run/##NY9va4MwEIff71OkpS8MnGK2/qGgwmAghcGge6lSrjZdwswpSRhu6z67U6E8Pw6egzvuFLpP2TTDoE3XWs/ev52XJjoiXVrzcGXq1idhQbeAIEA4Q815Ev7oLmg0SbfM0bFcI/mSDrWcy91z1MjqBp0r6UWSk@zZm9Z1Slo5dZy005RtqaRX/MIlX417n4o1TGxgNyPiqtjDdmQH@9HmiKoQm7vMeRx1DdsKVJKeQWUpwmm8W0RRXVVp0C8WPFlldv7qeHgLYmgkfXjF@lDwwaCm9NKy3ysTMcuylHVWk/8b/gE "Haskell – Try It Online")
[Answer]
# Java 8, ~~398~~ 384 bytes
```
n->{String r="",a[];for(String x:"456789~Gas Giant~15;456~Ice~10;456~Ice Giant~10;567~Gaia class~10;789~Dense Atmosphere~10;78910~Desert~25;78910~Iron~14;1011~Lava~6".split(";"))if(x.split("~")[0].contains(n))r+=x+";";long t=0,u=0;for(String x:(a=r.split(";")))t+=new Long(x.split("~")[2]);t*=Math.random();for(String x:a)if((u+=new Long((a=x.split("~"))[2]))>t)return a[1];return"";}
```
It can definitely be golfed some more, but the probability in combination with the Strings isn't very easy in Java.
**Explanation:**
[Try it online.](https://tio.run/##VVJNa@MwEL33Vww6WXVjrJL0S6vAQqEU2l72GHxQHWWrrCMZadzNUqK/no4Tm01AQjPzZp5m9LTWn3riW@PWyz/7utExwqu27usCwDo0YaVrA2@9C/ALg3W/oc4Gw3FJ8R1tWhE12hrewIGCvZvMv4asoBi70otKrnwYK7cPbDq7ub27T086wpPVDpOYSYql59okUY7miJWS0inZajg02Uf68kfjooGfuPGx/TDBDHFREhJNwHQ9G/zn4F0SUylKIdILTZ1uWBHbxmLGJOPcrrLt6CfGF2VV1N4hvUXMHOchV9ucEmXjqX9U5VWnyvORMq3CKSPHXDnzF16o4pz7uuISL9Wrxo8iaLf0m4yfc@m@n6w7ISD2U44DCZ8jDwa74EAvRCWPNmNyt5dHVdruvSFVBnE@vV3ChkYaLlpUoPlR2/52EhysmkqwP5QQdOQ5P4D/4bWaSVhPJvNSwojRx/gX0WwK32HREi82LrM5ewCWu6LuTer3@FV2@28)
```
n->{ // Method with String as both parameter and return-type
String r="", // Temp-String, starting empty
a[]; // Temp String-array
for(String x:"456789~Gas Giant~15;456~Ice~10;456~Ice Giant~10;567~Gaia class~10;789~Dense Atmosphere~10;78910~Desert~25;78910~Iron~14;1011~Lava~6".split(";"))
// Loop over the String-parts in the format "heats~type~probability"
if(x.split("~")[0].contains(n))
// If the heats contains the input
r+=x+";"; // Append this entire String-part to the temp-String `r`
long t=0,u=0; // Temp numbers, both starting empty
for(String x:(a=r.split(";")))
// Loop over the temp-String parts:
t+=new Long(x.split("~")[2]);
// Sum their probabilities
t*=Math.random(); // Get a random number in the range [0,sum_of_probabilities)
for(String x:a) // Loop over the temp-String parts again
if((u+=new Long((a=x.split("~"))[2]))>t)
// The moment the current probability-sum is > the random number
return a[1]; // Return the Type of planet
return"";} // Mandatory return we won't encounter (which returns nothing)
```
[Answer]
# [Min](https://min-lang.org), ~~280~~ 277 bytes
```
:a ' =b (("Gas Giant" 4 9 15) ("Ice" 4 6 10) ("Ice Giant" 4 6 10) ("Gaia Class" 5 7 10) ("Dense Atmosphere" 7 9 10) ("Desert" 7 10 25) ("Iron" 7 10 14) ("Lava" 10 11 6)) (=n (a n 1 get >= a n 2 get <= and) ((n 0 get b append #b) n 3 get times) when) foreach b b size random get
```
Starts with heat on the stack, leaves a string on the stack. Same general process as Python 2 answer.
### Explanation
Note that min is concatenative
```
:a ' =b ;Set the value on the stack (heat) to a, set empty quot to b
(("Gas Giant" 4 9 15) ("Ice" 4 6 10) ("Ice Giant" 4 6 10) ("Gaia Class" 5 7 10) ("Dense Atmosphere" 7 9 10) ("Desert" 7 10 25) ("Iron" 7 10 14) ("Lava" 10 11 6)) ;Data to be iterated over
(=n ; set n to current item
(a n 1 get >= a n 2 get <= and) ; check if n is between the min (2nd elment of n) and max (3rd element of n) heat
(
(n 0 get b append #b) n 3 get times ; insert the name(1st element of n) into the quot of names (b) a number of times corresponding to the 4th element of n
) when ; when the previous check is true
) foreach ; for every quot in previous data
b b size random get ;choose a random element from the list of names
```
[Answer]
# PowerShell, 56 + 135 (CSV file) + 1 (file name) = 192 bytes
```
param($z)ipcsv a|?{$z-in$_.m..$_.x}|%{,$_.p*$_.r}|Random
```
[Try it online!](https://tio.run/##PYxdC4IwFIbv9yuGGFScpIVa3hRBIEEX0R@Igw0U3BybmPjx29dU6ObleZ9zeFX15drkvCytVahRrP1uQ7wnCGhBkxQNTQuUNYSQAIvIPeMOY2D7Cf@3WaRYIM1KNAYiOE7mxqXh9FqLyqica@5ssnjDdT3/wMGN6kouhYXkgQ3OyCD2zkgKlZmG4nDp/W5XSP8diCBw2Y7DqgcHautCj8ML5acS1trTDw "PowerShell – Try It Online") (this is a slightly modified version that creates the temporary CSV file described below)
Imports a CSV file using `ipcsv` (short for `Import-CSV`) named `a` in the local directory that contains the following:
```
P,m,x,r
Gas Giant,4,9,15
Ice,4,6,10
Ice Giant,4,6,10
Gaia class,5,7,10
Dense Atmosphere,7,9,10
Desert,7,10,25
Iron,7,10,14
Lava,10,11,6
```
That automatically creates an iterable hashtable of things like the following:
```
@{P=Gas Giant; m=4; x=9; r=15}
@{P=Ice; m=4; x=6; r=10}
...
```
We then use `Where-Object` (`?`) to pull out those entries where our input integer `$z` is `-in` the range `$_.m` to `$_.x` (i.e., it's in the heat range). We then pump those into a `Foreach-Object` loop (`%`) that creates an array of strings of names based on the random chance of those names. For example, this will create an array of `15` `"Gas Giant"` strings if that heat matches. We then put those into `Get-Random` which will pull out the appropriate string with the appropriate weighting.
] |
[Question]
[
## Introduction
Consider two non-empty integer arrays, say **A = [0 3 2 2 8 4]** and **B = [7 8 7 2]**.
To perform *alignment addition* on them, we do the following:
1. Repeat each array enough times to have total length \$\text{lcm(length(A), length(B))}\$. Here \$\text{lcm}\$ stands for lowest common multiple.
```
A -> [0 3 2 2 8 4][0 3 2 2 8 4]
B -> [7 8 7 2][7 8 7 2][7 8 7 2]
```
2. Perform element-wise addition on the repeated arrays, and cut the result at every position where there's a cut in either of them.
```
A -> [0 3 2 2 8 4][0 3 2 2 8 4]
B -> [7 8 7 2][ 7 8 7 2][7 8 7 2]
-> [7 11 9 4][15 12][7 5][9 10 15 6]
```
3. This array of arrays is your result.
## The task
Your inputs are two non-empty arrays of integers, and your output shall be the result of their alignment addition, as defined above.
The inputs and output can be in any reasonable format.
You don't have to worry about integer overflow when performing the addition.
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins.
## Test cases
```
[1] [4] -> [[5]]
[1,2,-3,-4] [15] -> [[16],[17],[12],[11]]
[0,-4] [2,1,0,-3] -> [[2,-3],[0,-7]]
[0,3,2,2,8,4] [7,8,7,2] -> [[7,11,9,4],[15,12],[7,5],[9,10,15,6]]
[18,17,16] [-1,-2,-3,-4] -> [[17,15,13],[14],[16,14],[15,13],[15],[16,14,12]]
[18,17,16,15] [-1,-2,-3,-4] -> [[17,15,13,11]]
[1,1,1,1,1] [6,5,6,5,6,5,6,2,1] -> [[7,6,7,6,7],[6,7,3,2],[7],[6,7,6,7,6],[7,3,2],[7,6],[7,6,7,6,7],[3,2],[7,6,7],[6,7,6,7,3],[2],[7,6,7,6],[7,6,7,3,2]]
[1,1,1,1,1,1] [6,5,6,5,6,5,6,2,1] -> [[7,6,7,6,7,6],[7,3,2],[7,6,7],[6,7,6,7,3,2]]
[1,1,1,1,1,1,1] [6,5,6,5,6,5,6,2,1] -> [[7,6,7,6,7,6,7],[3,2],[7,6,7,6,7],[6,7,3,2],[7,6,7],[6,7,6,7,3,2],[7],[6,7,6,7,6,7,3],[2],[7,6,7,6,7,6],[7,3,2],[7,6,7,6],[7,6,7,3,2],[7,6],[7,6,7,6,7,3,2]]
```
[Answer]
## JavaScript (ES6), ~~101~~ 99 bytes
Takes input as 2 arrays. Returns a string.
```
f=(a,b,j=0,s='')=>a.map((v,i)=>(s+=i*j?' ':s&&'][',s+=b[j]+v,j=++j%b.length))|j?f(a,b,j,s):`[${s}]`
```
### How it works
We iterate on the first array `a` with a pointer `i` while updating another pointer `j` into the second array `b`. The sums `a[i] + b[j]` are appended to the output string `s`. A separator is inserted each time `i == 0` or `j == 0`. We repeat this process until `j` is back exactly at the beginning of `b` at the end of an iteration.
*Note:* When the `|` operator is applied, `a.map(...)` is coerced to either `NaN` (if `a` contains more than one element) or the current value of `j` (if `a` contains exactly one element). Therefore, `a.map(...)|j == j` in all cases and is safe to use here.
### Test cases
```
f=(a,b,j=0,s='')=>a.map((v,i)=>(s+=i*j?' ':s&&'][',s+=b[j]+v,j=++j%b.length))|j?f(a,b,j,s):`[${s}]`
console.log(f([1], [4]));
console.log(f([1,2,-3,-4], [15]));
console.log(f([0,-4], [2,1,0,-3]));
console.log(f([0,3,2,2,8,4], [7,8,7,2]));
console.log(f([18,17,16], [-1,-2,-3,-4]));
console.log(f([18,17,16,15], [-1,-2,-3,-4]));
console.log(f([1,1,1,1,1], [6,5,6,5,6,5,6,2,1]));
console.log(f([1,1,1,1,1,1], [6,5,6,5,6,5,6,2,1]));
console.log(f([1,1,1,1,1,1,1], [6,5,6,5,6,5,6,2,1]));
```
[Answer]
## Haskell, ~~84~~ 79 bytes
```
a#b=a%b where(c:d)%(e:f)|(x:y)<-d%f=(c+e:x):y;[]%[]=[[]];c%[]=[]:c%b;_%d=[]:a%d
```
My first version was the same in more readable layout:
```
a#b=a%b where
(c:d)%(e:f)|(x:y)<-d%f=(c+e:x):y
[]%[]=[[]]
c%[]=[]:c%b
_%d=[]:a%d
```
Using a local definition to avoid having to give `(%)` extra arguments for `a` and `b`. Amazingly, this is almost the same solution given at almost the same time as @nimi's, from whom I took the idea of using only one line for the local definition.
Usage:
```
*Main> [0,3,2,2,8,4] # [7,8,7,2]
[[7,11,9,4],[15,12],[7,5],[9,10,15,6]]
```
[Answer]
# PHP, ~~126~~ 120 bytes
```
function($a,$b){do{$c[$j][]=$a[$i%$x=count($a)]+$b[$i%$y=count($b)];++$i%$x&&$i%$y?:$j++;}while($i%$x|$i%$y);return$c;};
```
[Try it here!](http://sandbox.onlinephpfunctions.com/code/92e7acbcb821357be81ebc902dd7679e0e6a20d0)
Anonymous function that returns the resulting array of arrays.
Essentially, we loop through the contents of both of our arrays, modding our iterator by the length of the array to simulate 'copying' them. Taking each of the values from the arrays, we sum them and add them to an array in `$c`. If we reach the end of one of our input arrays (a split, in terms of the challenge), we start assigning into a new array in `$c`.
The reason for the `do while` loop is because our condition is based on `$i`, which starts at `0`. If we use a loop where the condition is checked at the beginning, the loop wouldn't run
We only end the summation once we reach the end of both of the arrays at the same time, which would imply the LCM.
[Answer]
## Haskell, ~~87~~ 84 bytes
```
a#b=a%b where[]%[]=[[]];(e:f)%(g:h)=f%h!(e+g);e%[]=[]:e%b;_%g=[]:a%g
(m:n)!l=(l:m):n
```
Usage example: `[0,3,2,2,8,4] # [7,8,7,2]` -> `[[7,11,9,4],[15,12],[7,5],[9,10,15,6]]`.
Simple recursion. Base case: both lists are empty. If only one of them is empty, restart with a full version and start a new cluster in the output. If none is empty, prepend the sum to the from element.
Have also a look at [@Christian Sievers' answer](https://codegolf.stackexchange.com/a/103356/34531), which is almost identical and was posted a few seconds earlier.
[Answer]
# Octave , 113 bytes
```
@(a,b)mat2cell(sum([repmat(a,1,(L=lcm(A=numel(a),B=numel(b)))/A);repmat(b,1,L/B)]),1,diff(unique([0:A:L,0:B:L])))
```
this function is directly callable to call it place it in parenthesis and call as (@(a,b)...)([1 2 3 4],[6 4 5])
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 30 bytes
```
{Sf*Laf+_s,f*:.+La/0=S2*a-Sa/}
```
[Try it online!](https://tio.run/nexus/cjam#jY1BC8IwDIXv@xXv4qWzbkm3dQz8B7v1GIr00rPgUfztXXQTFRQkhCTvfbyIUIR0MVYiBIZ1sJ0q1D@kdr0YBF3dpjkFGSPultfpwWvACPKgQWVLsM@0dwsa/MXFVuoN6PFq/fxJ/Mf8pKpYriGbOeX6dNlnMx3qOTXtMbBJNqTmVnbTuSw "CJam – TIO Nexus")
Takes input as a pair of lists.
### Explanation
The idea is to insert some markers into the input arrays (in the form of short strings) which indicate where the aligned array ends, and where we need to insert the breaks in the arrays. This way we can avoid having to compute the LCM.
```
Sf* e# Riffle each list with spaces. These are just place holders, so that having
e# an array-end marker between two elements doesn't misalign subsequent elements.
Laf+ e# Append an empty string to each list. This is the array-end marker.
_s, e# Convert the pair of lists to a string and get its length. This is always
e# greater than the number of elements in either input.
f* e# Repeat either array that many times. This is definitely more than necessary
e# to reach the LCM (since multiplying by the length of the other list always
e# gives a common multiple).
:.+ e# Pairwise addition of the list elements. There are four cases:
e# - Both elements are numbers, add them. This is the actual addition
e# we need for the problem.
e# - Both elements are spaces. This is just a regular position between
e# list elements.
e# - One is a space, one is empty: the result is a single space, and
e# this marks a position where one of the arrays ended, which means
e# we need to split here.
e# - Both elements are empty. This happens at the LCM of both list lengths
e# and indicates where we need to stop the output.
La/0= e# Split the input around empty strings and discard everything except
e# the first chunk.
S2*a- e# Remove the double-space strings, we no longer need them.
Sa/ e# Split the list around single spaces.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ ~~20~~ 18 bytes
```
ṁ€L€æl/$S
J€ỊÇœṗÇḊ
```
[Try it online!](https://tio.run/nexus/jelly#@/9wZ@OjpjU@QHx4WY6@SjCXF5D5cHfX4fajkx/unH64/eGOrv9hQGpnC9fD3VsOt4Okd85@1DDn//9ow1gdhWiTWK5oQx0jHV1jHV0TkIChKVDEAMox0jHUAbKNwULGQGVGOhY6YBlzIMNcxwik20LH0FzH0AwkqmuoowszCyGjAzQTU1IHCkFSZjqmOggMtBVZAVFKcCkCAA "Jelly – TIO Nexus")
### How it works
```
ṁ€L€æl/$S Helper link. Argument [X, Y] (arrays of integers).
$ Combine the two links to the left into a monadic chain.
L€ Length each; yield the lengths of X and Y.
æl/ Reduce by least common multiple.
ṁ€ Mold each; cyclically repeat the elements of X and Y to extend them
to length lcm(length(X), length(Y)).
S Compute the sum of the extended X and Y arrays.
J€ỊÇœṗÇḊ Main link. Argument [A, B] (arrays of integers).
J€ Indices each; replace A and B by the arrays of there 1-based indices.
Ị Insignificant; map 1 to itself, all other indices to 0.
Ç Apply the helper link to the result.
This yield a Boolean array with a 1 (or 2) at all indices where a new
repetition of A or B (or both) begins.
Ç Apply the helper link to [A, B].
œṗ Partition; break the result to the right at truthy elements (1 or 2) in
the result to the right.
Ḋ Dequeue; remove the first element of the partition (empty array).
```
[Answer]
# Python 3.5 - (~~146~~~~137~~~~134~~130+12) = 142 Bytes
```
import math
def s(a,b):
l,k,*r=map(len,[a,b])
for i in range(l*k//math.gcd(l,k)):
r+=a[i%l]+b[i%k],
if i%k==k-1or i%l==l-1:print(r);r=[]
```
I cannot figure out how to put the whole for loop in one line.
**Edits:**
* Thanks [zgarb](https://codegolf.stackexchange.com/users/32014/zgarb)
for saving 9 bytes!
* Thanks [vaultah](https://codegolf.stackexchange.com/users/44755/vaultah) for saving 3 bytes!
* Thanks [mathmandan](https://codegolf.stackexchange.com/users/36885/mathmandan) saving 5 bytes!
[Answer]
# Python 2, 119 bytes
```
a=input()
i,v,l=0,list(a),len
while 1:q=l(v[0])>l(v[1]);print map(sum,zip(*v)[i:]);i=l(v[q]);v[q]+=a[q];1/(i-l(v[q^1]))
```
Takes input from stdin as two tuples separated by comma, outputs resulting lists to stdout. Terminates by raising the `ZeroDivisionError` exception, since that [seems to be allowed](http://meta.codegolf.stackexchange.com/a/4781/44755).
For example, if the input is `(0, 3, 2, 2, 8, 4), (7, 8, 7, 2)`, the program will print
```
[7, 11, 9, 4]
[15, 12]
[7, 5]
[9, 10, 15, 6]
```
to stdout and the exception traceback to stderr.
[Answer]
# [J](http://jsoftware.com/), ~~34~~ 32 bytes
```
[:(<;.1~*)/[:+/*.&#$&>,:&(;2>#\)
```
[Try it online!](https://tio.run/##lY7NCsIwEITvfYrBStrUkjbpL4nti1TIoRjEi4ee9dXjiiLSWkGWYZeZj909ezeh08hB8oOO90bIW8KzQe@yRLBwy/pUs9ioPjxwz4ONQOQ6HSHFVcNNQXAcTxfExjHRZxwSBuXCU7AFbEmZrGZh/vQVUTQWi7SgSKHFA2qoN1Dz9S1kA1kTYCXs69YaJKvf3LsMalQfog9X2X/pr7y/Aw "J – Try It Online")
## Explanation
```
[:(<;.1~*)/[:+/*.&#$&>,:&(;2>#\) Input: array A (LHS), array B (RHS)
#\ Length of each prefix of A and B
2> Less than 2
; Link each with A and B
,:& Pair them
# Length of A and B
*.& LCM of the lengths
&> For each box
$ Reshape it to the LCM of the lengths
[:+/ Reduce by addition
[: / Reduce by
* Sign of RHS
<;.1~ Box each partition of LHS
```
[Answer]
# Haskell, 166 bytes
This is probably not the most elegant approach: Basically the function `?` creates one list of the needed length with thesums, and `%` is cutting this sum up again. `!` is the final function that merges those two.
```
l=length
a?b=take(lcm(l a)$l b)$zipWith(+)(cycle a)$cycle b
l%(i:ind)|l==[]=[]|1>0=take i l:(drop i l)%(map(+(-i))ind)
a!b=(a?b)%[k|k<-[1..],k`mod`l a<1||k`mod`l b<1]
```
[Answer]
# [PHP], ~~183~~ ~~152~~ 135 bytes
```
function O($A,$B){while($f<2){$O[$k][]=$A[+$i]+$B[+$j];$f=0;isset($A[++$i])?:$i=!++$k|!++$f;isset($B[++$j])?:$j=!++$k|!++$f;}return$O;}
```
Nice version:
```
function O($A,$B)
{
while($f<2) {
$O[$k][]=$A[+$i]+$B[+$j];
$f=0;
isset($A[++$i])?:$i=!++$k|!++$f;
isset($B[++$j])?:$j=!++$k|!++$f;
}
return$O;
}
```
Output:
```
array (size=4)
0 =>
array (size=4)
0 => int 7
1 => int 11
2 => int 9
3 => int 4
1 =>
array (size=2)
0 => int 15
1 => int 12
2 =>
array (size=2)
0 => int 7
1 => int 5
3 =>
array (size=4)
0 => int 9
1 => int 10
2 => int 15
3 => int 6
```
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), ~~147~~ 145 bytes
```
param($a,$b)$o=@{};do{$o[+$j]+=,($a[+$i%($x=$a.count)]+$b[$i++%($y=$b.count)]);if(!($i%$x-and$i%$y)){$j++}}until(($x,$y|?{!($i%$_)}).count-eq2)$o
```
[Try it online!](https://tio.run/nexus/powershell#NY5hCsIwDEbPIkRoSCZShQmjuHuMIZ1T6HCrisJK7dlrZEj@vHx5Ccl3@7SjAsvQIXhTx1T1PoJvCIaWDMtI0K0VzAbs5uzf0wtbgq4BRyRxMND9Y6zcVa2U6DAXdup/EBAjDEQpieJuSg4xhM8xLt4JEy7rxeWh5YWcc622vGMtdeA9SlsKlKzxCw "PowerShell – TIO Nexus")
(*Golfing suggestions welcome. I feel there's probably another 10 to 15 bytes that can be squeezed out of this.*)
Takes input as two explicit arrays (with the `@(...)` syntax) as command-line arguments. Returns a hashtable of the resulting arrays, because multidimensional arrays in PowerShell can get weird, and this is more consistent. Sets some initial variables, then enters a `do`/`until` loop again, with the conditional being until `$i` is the [lcm of the array counts](https://codegolf.stackexchange.com/a/95009/42963).
Each loop iteration, we add the corresponding `$a` and `$b` values together, treat it as an array `,(...)` before adding it into the hashtable `$o` at the appropriate spot `$j`. The array encapsulation is necessary to prevent arithmetical addition -- this forces the `+=` to overload to array concatenation instead. Then, a conditional on `$x` and `$y` (the counts) to determine if we're at an array edge - if so, we increment `$j`.
Finally, we leave `$o` on the pipeline and output is implicit.
(NB: Due to how PowerShell enumerates hashtables with the default `Write-Output`, this tends to be output "backward"; as in, the "0th" resultant array is on the "bottom" of the output. The hash itself is fine, and would be used just fine if you e.g., encapsulated this code in a return variable ... it just looks odd when it's printed.)
Saved 2 bytes by moving $x and $y into the array indexing rather than separate (saved two semicolons).
[Answer]
# Python 2, 113 bytes
```
a,b=input()
i=m=n=0;r=[]
while(not i)+m+n:r+=[[]]*(not m*n);r[-1]+=[a[m]+b[n]];i+=1;m=i%len(a);n=i%len(b)
print r
```
[Answer]
## Python 3.5, 210 176 173 169 158 Bytes
```
def f(a,b):
x=[];e=f=0
while 1:
if e==len(a):
print(x);x=[];e=0;
if f==len(b):break
if f==len(b):print(x);x=[];f=0
x+=a[e]+b[f],;e+=1;f+=1
```
**Takes two lists as input and prints all the lists.**
Its my first answer and I don't know how to golf yet. The basic idea I've used is to have two counters for each list which indicate a split and a current list where the added values are appended onto; as soon as a split is encountered, we print the current list and make a new empty one.
* **Saved 34 bytes**: Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) and [TimmyD](https://codegolf.stackexchange.com/users/42963/timmyd)
* **Saved 3 bytes**: was using c and d for len(a) and len(b), but turns out they weren't useful
* **Saved 4 bytes**: Thanks to [orlp](https://codegolf.stackexchange.com/users/4162/orlp), removed unwanted paranthesis
* **Saved 11 bytes**: rearranged some blocks and crunched them down
[Answer]
## Racket 373 bytes
```
(let*((lg length)(fl flatten)(ml make-list)(t rest)(r reverse)(m modulo)(o cons)(ln(lg l))(jn(lg j))(c(lcm ln jn))(l2(fl(ml(/ c ln)l)))
(j2(fl(ml(/ c jn)j)))(ll(for/list((a l2)(b j2))(+ a b))))(let p((ll ll)(ol '())(tl '())(n 0))(cond[(empty? ll)(t(r(o(r tl)ol)))]
[(or(= 0(m n ln))(= 0(m n jn)))(p(t ll)(o(r tl)ol)(take ll 1)(+ 1 n))][(p(t ll)ol(o(first ll)tl)(+ 1 n))])))
```
Ungolfed:
```
(define(f l j)
(let* ((ln (length l))
(jn (length j))
(c (lcm ln jn))
(l2 (flatten (make-list (/ c ln) l)))
(j2 (flatten (make-list (/ c jn) j)))
(ll (for/list ((a l2)(b j2))
(+ a b))))
; TO CUT LIST INTO PARTS:
(let loop ((ll ll)
(ol '())
(templ '())
(n 0))
(cond
[(empty? ll)
(rest (reverse (cons (reverse templ) ol)))]
[(or (= 0 (modulo n ln))
(= 0 (modulo n jn)))
(loop (rest ll)
(cons (reverse templ) ol)
(list (first ll))
(add1 n))]
[(loop (rest ll)
ol
(cons (first ll) templ)
(add1 n))]))))
```
Testing:
```
(f '[1] '[4])
(f '[1 2 -3 -4] '[15])
(f '[0 3 2 2 8 4] '[7 8 7 2])
```
Output:
```
'((5))
'((16) (17) (12) (11))
'((7 11 9 4) (15 12) (7 5) (9 10 15 6))
```
[Answer]
**Clojure, ~~280~~ 206 bytes**
```
(fn[a b](let[A(count a)B(count b)Q quot](map #(map last %)(partition-by first(take-while #((% 0)2)(map-indexed(fn[i s][[(Q i A)(Q i B)(or(= i 0)(>(mod i A)0)(>(mod i B)0))]s])(map +(cycle a)(cycle b))))))))
```
Well this makes a lot more sense. Generating the element-wise sum, adding positional metadata, taking while we haven't repeated yet and putting the sum value to each partition.
```
(def f (fn[a b]
(let[A(count a)B(count b)Q quot]
(->> (map +(cycle a)(cycle b))
(map-indexed (fn [i s][[(Q i A)(Q i B)(or(= i 0)(>(mod i A)0)(>(mod i B)0))]s]))
(take-while #((% 0)2))
(partition-by first)
(map #(map last %))))))
```
*Original:*
I'm hoping to improve this but this is the sortest one I have for now.
```
(fn[a b](let [C cycle o count c(take-while #(or(=(% 0)0)(>(% 1)0)(>(% 2)0))(map-indexed(fn[i[A B]][i(mod i(o a))(mod i(o b))(+ A B)])(map(fn[& v]v)(C a)(C b))))](map #(map last %)(partition-by first(map(fn[p c][p(last c)])(reductions + (map #(if(or(=(% 1)0)(=(% 2)0))1 0)c))c)))))
```
Ungolfed and verbose:
```
(def f (fn[a b]
(let [c(->> (map (fn[& v]v) (cycle a) (cycle b))
(map-indexed (fn[i[A B]][i (mod i(count a)) (mod i(count b)) (+ A B)]))
(take-while #(or(=(% 0)0)(>(% 1)0)(>(% 2)0))))]
(->> (map (fn[p c][p(last c)]) (reductions +(map #(if(or(=(% 1)0)(=(% 2)0))1 0)c)) c)
(partition-by first)
(map #(map last %))))))
```
Starts by "merging" an infinite cycle of collections `a` and `b`, adds metadata on each element's index within the collection, takes until both sequences start from index 0 again.
This collection `c` is then merged with partition data (a cumulative sum of ones and zeroes), partitioned and the last element (being sum of items) is selected.
I think for significant improvements a totally different approach is required.
[Answer]
# PHP, ~~150~~ ~~121~~ 119 bytes
```
function($a,$b){while($i<2|$x|$y)$r[$k+=!($x=$i%count($a))|!$y=$i++%count($b)][]=$a[$x]+$b[$y];array_pop($r);return$r;}
```
anonymous function takes input as arrays.
**breakdown**
```
while($i<2|$x|$y) // loop while either $a or $b has NO cut
$r[
// if either $a or $b has a cut, increment $k; post-increment $i
$k+=!($x=$i%count($a))|!$y=$i++%count($b)
// append current $a + current $b to $r[$k]
][]=$a[$x]+$b[$y];
array_pop($r); // $r has one element too much; remove it
return$r;
```
[Answer]
# C++14, 206 bytes
As unnamed generic lambda, requiring input containers `P`,`Q` and output container `R` to be like `vector<vector<int>>`.
```
[](auto P,auto Q,auto&R){R.clear();auto a=P.begin(),b=Q.begin(),x=P.end(),y=Q.end();auto A=a,B=b;do{R.emplace_back();while(a!=x&&b!=y)R.back().push_back(*a+++*b++);a=a==x?A:a;b=b==y?B:b;}while(a!=A||b!=B);}
```
Ungolfed and usage:
```
#include<vector>
#include<iostream>
using namespace std;
auto f=
[](auto P,auto Q,auto&R){
R.clear(); //just clear the output to be sure
//a and b are the iterators, x and y is the end
auto a=P.begin(),b=Q.begin(),x=P.end(),y=Q.end();
//just some abbreviations for .begin()
auto A=a,B=b;
do{
R.emplace_back(); //add new vector
while(a!=x&&b!=y) //while not at the end of one vector
R.back().push_back(*a+++*b++); //add the pointed elements and advance
a=a==x?A:a; //reset if at the end
b=b==y?B:b;
}while(a!=A||b!=B); //if both were resetted, then finish
}
;
int main(){
vector<int> A = {0, 3, 2, 2, 8, 4};
vector<int> B = {7, 8, 7, 2};
vector<vector<int>> R;
f(A,B,R);
for (auto c:R){
for (int x:c)
cout << x << ", ";
cout << endl;
}
cout << endl;
}
```
[Answer]
## Mathematica 112 Bytes
This could probably be improved upon. The idea is to create a 2D array with the second element used to track the lessor of the counter i mod the length of each input array.
```
Split[Table[{#[[1,(m=Mod[i,d=Length/@#,1])[[1]]]]+#[[2,m[[2]]]],Min@m},{i,LCM@@d}],#2[[2]]>#1[[2]]&][[;;,;;,1]]&
```
Usage
```
%@{{0,3,2,2,8,4},{7,8,7,2}}
```
[Answer]
## JavaScript (ES6), 131 bytes
```
(a,b,g=(r,[n,...d]=a,[m,...e]=b,s=[])=>1/n?1/m?g(r,d,e,[...s,n+m]):g([...r,s],[n,...d]):1/m?g([...r,s],a,[m,...e]):[...r,s])=>g([])
```
Slightly ungolfed:
```
(a,b,r=[],[n,...d]=a,[m,...e]=b,s=[])
=>1/n?1/m?f(a,b,r,d,e,[...s,n+m])
:f(a,b,[...r,s],[n,...d],b,[])
:1/m?f(a,b,[...r,s],a,[m,...e],[])
:[...r,s]
```
* If both arrays `d` and `e` contain numbers, the sum of the first number is appended to `s` and the remaining elements are processed recursively
* If one of the arrays contains numbers, the array of sums `s` is appended to the result `r` and the other array is reset to its initial array
* If both arrays are empty then simply return the result with the last sums appended.
Sadly this solution doesn't have the ruthless efficiency of @Arnauld's, but at least I think it's a beautiful solution.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
Ẉæl/
ẈḍⱮǧkṁ€ÇSƊṖ
```
[Try it online!](https://tio.run/##y0rNyan8///hro7Dy3L0uYD0wx29jzauO9x@aHn2w52Nj5rWHG4PPtb1cOe0/4fbj056uHPG///RBjrGOkZAaKFjEqujEG0OZJjrGMX@BwA "Jelly – Try It Online")
## How it works
```
Ẉæl/ - Helper link. Takes an array [A, B] on the left
Ẉ - Lengths; [len(A), len(B)]
/ - Reduce by:
æl - LCM
This yields R := lcm(length(A), length(B))
ẈḍⱮǧkṁ€ÇSƊṖ - Main link. Takes [A, B] on the left
Ẉ - [len(A), len(B)]
Ç - Call the helper link on [A, B]
Ɱ - Over each integer i = 1, 2, ..., R:
ḍ - Yield [x, y] where:
x = 1 if len(A) % i == 0 else 0
y = 1 if len(B) % i == 0 else 0
§ - For each pair, yield 0 if x = y = 0 else a non-zero element
Ɗ - To [A, B]:
Ç - Yield R
€ - Over each element A, B:
ṁ - Mold to length R
S - Columnwise sums
k - Partition this array on the right at the non-zero indexes on the left
Ṗ - Remove the trailing empty array
```
] |
[Question]
[
## Overview
Given a 3 line string, figure out if the structure falls to the left, balances, or falls to the right.
## Input structure
You can imagine the structure as metal rod with stuff on top, all being balanced on top of a vertical rod.
```
1 7 4 a
===============
|
```
The first line is the items. Each item's weight is calculated as the ascii value of the character minus 32. (Characters under 32 aren't considered and spaces weigh 0). Keep in mind that an item's force on the rod is its weight times the distance to the pivot point.
The second line is the rod. Each length of rod weighs 1 unit by itself. This line is exclusively equals signs (`=`).
The third line is the pivot point. This can be placed anywhere, and is represented by a number of spaces followed by a single pipe (`|`) character.
# Examples
Input:
```
=====
|
```
Output: Balance
Input:
```
=====
|
```
Output: Falls left
Input:
```
%
=====
|
```
Output: Balance (Because `%` weighs enough to counteract the weight of the left side of the rod)
Input:
```
a a
=======
|
```
Output: Falls right (because the `a` on the right is further away from the pivot point)
Input:
```
1 7 4 A
===============
|
```
Output: Falls left
Input:
```
1 7 4 a
===============
|
```
Output: Falls right (lower case letters are heavy!)
Input:
```
$ ~
===============
|
```
Output: Balance
# Notes
* Trailing whitespace is permitted, leading whitespace is not.
* Your program may output in whatever format you like, as long as there are 3 distinct outputs for left, balance, and right.
* Your program must accept the format shown as input.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins
[Answer]
# JavaScript (ES6), ~~116~~ ~~111~~ ~~108~~ 106 bytes
*-5 bytes by summing via `eval(array.join`+`)` instead of `array.reduce()`.*
*-3 bytes by defaulting to `1` instead of `32 - 31`, allowing parentheses to be removed.*
*-2 bytes since pivot point is the length of the last line - 1*
```
(s,[t,r,b]=s.split`
`)=>Math.sign(eval([...r].map((_,i)=>(t.charCodeAt(i)-31||1)*(i-b.length+1)).join`+`))
```
Outputs `-1`, `0`, or `1`, for left, balanced, or right, respectively. Ended up similar to [Chas Brown's python answer](https://codegolf.stackexchange.com/a/129695/69583), so credit goes there.
Can save 4 bytes if the first line is padded to match the length of the rod by using
`(31-t.charCodeAt(i))*(b.length+~i)`.
## Test Snippet
Includes additional output (`Left`/`Balanced`/`Right`) along with the number.
```
f=
(s,[t,r,b]=s.split`
`)=>Math.sign(eval([...r].map((_,i)=>(t.charCodeAt(i)-31||1)*(i-b.length+1)).join`+`))
```
```
<textarea id=I rows=3 cols=20></textarea><br><button onclick="O.value=I.value?`${x=f(I.value)} (${['Left','Balanced','Right'][x+1]})`:''">Run</button> <input id=O disabled>
```
### Another 106 byte method
```
(s,[t,r,b]=s.split`
`)=>Math.sign(eval(r.replace(/./g,(_,i)=>"+"+(t.charCodeAt(i)-31||1)*(i-b.length+1))))
```
Instead of `join`ing an array on `+`s, we create a string of numbers, each prefixed by `+`. The leading `+` gets ignored.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~112~~ 110 bytes
```
def f(s):w,b,p=s.split('\n');return cmp(sum((ord((w+' '*-~i)[i])-31)*(i-p.find('|'))for i in range(len(b))),0)
```
[Try it online!](https://tio.run/##jY/fTsIwFMav7VOcBM1psSMMUBLNLtTES18AuChbB022bmm7EBPCq891bGYoJp6r9vu@3/lTfrp9oWd1ncgUUmrZ04FveRnZiS0z5SiuNbJnI11lNMR5SW2VU1qYhNLDPQKOg5NiK7VhwTxkY6qCcpIqnVA8ImNpYUCB0mCE3kmaSU23jDE@ZfUInLQOYmGlJSOYQi6FtoBbkQkdS@QQhL32LrLMQiZT18g/VKN2e4eE@PV9R@o7flQ5h@YUclMapR3gWyM2bOf1su0f/m4OK3w9D7fIL7rz4QablU9vOpSQdmjIARFJ5IsAHJsP66wZHzoX1rylGhHurgcW54DwEXGO/A49tKEQYAkL6OqlD0cDqK0h@XiFFP8il9@b93ULpz/JAV5/AQ "Python 2 – Try It Online")
EDIT: Finally managed to eliminate the `enumerate` and `rjust` for a measly 2 bytes... meh!
Takes in a string; outputs -1,0, or 1 for falls left, balances, falls right, respectively.
First pass at 112 bytes was:
```
def f(s):w,b,p=s.split('\n');return cmp(sum((ord(c)-31)*(i-p.find('|'))for i,c in enumerate(w.rjust(len(b))),0)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes
```
ṪO_31
ỴµṪLạЀṪL$×Çṣ0S€IṠ
```
[Try it online!](https://tio.run/##y0rNyan8///hzlX@8caGXA93bzm0Fcjxebhr4eEJj5rWgNgqh6cfbn@4c7FBMFDA8@HOBf///1dAAioKdVy2qIALWV6hBgA "Jelly – Try It Online")
`-1` for falling left, `0` for balancing, `1` for falling right (full program).
`[-1]` for falling left, `[0]` for balancing, `[1]` for falling right (function).
First line must have trailing spaces, last line must not.
Explanation (we start with bottom line):
First of all, we're working with individual lines, so we need to somehow get them. That's a job for `Ỵ`. Then, we need to treat the `\n`-split version of the input as if it was the original input, so we use `µ` to make a monadic chain applied to the current value.
Now we begin real work, and our first job would be computing the factors of the weights. Essentially this is a range [distance from far left to pivot..0..distance from pivot to far right]. First of all, we have to find the 1-based index of the pivot, which is essentially the length of the last line without trailing spaces. So we pop the last line (pivot line) from our original list with `Ṫ`, since we won't need it anymore, and then we take its length with `L`. We then need to take the length of the rod, for which we do the same thing to the now-last line (rod line) with `ṪL$`. Finally, to get the range, we map **|*x* - *y*|** to [1..rod length], where ***x*** is the pivot index and ***y*** is each element of the list we map upon. We do this using `ạЀ`, where `ạ` calculates **|*x* - *y*|** and `Ѐ` makes a range from 1 up to and including the rod length. Now we'll have the range we want.
After that, we have to multiply each integer, representing a piece of the rod, with its corresponding weight. To calculate the weights, we use `Ç`, going to the top line of our code. We take the remaining line with `Ṫ`, its charcodes with `O`, and then we calculate ***x* - 31** using `_31`, ***x*** being each charcode. We then assign space to weight 1 (0 + rod piece = 1), `!` to weight 2 (1 + 1) etc. We're done with the top line, so now `Ç` would return the list of weights, which we multiply with the corresponding integers representing the rod pieces with `×`.
After that, we split with `ṣ0` on the pivot point, represented by a 0 (since any weight there won't affect the result), resulting in a list of the form [[1st weight, 2nd weight...weight just before pivot], [weight just after pivot, weight after the one before...last weight]]. Those lists represent the sides of the rod, left and right. We now sum each of the lists using `S€` to get the total weights on each side, and use `I` to take the delta, which will be negative if left side is heavier, zero if they're equal-weighted, and positive if right side is heavier. So, to return the final result using this properly to our advantage, we take the sign with `Ṡ`.
[Answer]
## Haskell, ~~212~~ 171 bytes (188 if take input as one string)
```
o!p=map(fst)(zip[p-0,p-1..]o)
x#p=sum(zipWith(\c w->(max(fromEnum c-32)0)*w)x(x!p))+sum(x!p)
x?c=length(takeWhile(==c)x)
```
**171 bytes variant**
```
r a b c=signum(take(b?'=')(a++repeat ' ')#(c?' '))
```
**188 bytes variant**
```
x%y=lines x!!y
r i=signum(take(i%1?'=')(i%0++repeat ' ')#(i%2?' '))
```
Explanation
```
o!p=map(fst)(zip[p-0,p-1..]o) Creates weights coefs list.
o - list, p - pivot position
for list "abcdf" and p=3 (pivot under 'd')
outputs [3,2,1,0,-1]
x#p Calculates total balance
x-list of "objects" on lever, p-pivot place
sum(zipWith sum of zipped lists
(\c w->(max(fromEnum c-32)0)*w) weight of ascii "object" times
distance from pivot
x(x!p)) x-ascii objects,
(x!p)-distances list(weight coefs)
+sum(x!p) balance of lever ("==") itself
x?c=length(takeWhile(==c)x) length of list before non c element met
used to find '|' position
and length of "===" lever
before right whitespaces met
r a b c= Sums it all up =)
a-ascii objects, b-lever, c-pivot line
signum( 1-tips left, 0-balance, -1-tips right
take(b?'=')(a++repeat ' ') takes all object on lever
plus whitespaces up to length of the lever
# calculate the balance
(c?' ') determine place of pivot
```
[Answer]
# [Python 2](https://docs.python.org/2/), 90 bytes
```
def f(s):L=len(s)/3;print cmp(sum((ord(s[i])-31)*(i-s[-L:].find('|'))for i in range(L)),0)
```
Expects input lines to be padded (with spaces) to the correct length. Outputs `-1` for *falls left*, `0` for *balanced*, and `1` for *falls right*.
**[Try it online!](https://tio.run/##dYvBCoJAFEX3fsXbzXuhlhkEhov2/oFJiM7URL4ZZpQI/PepqBYtOpt74HDtfTwbXofQSwUKPRVVeZX8lGW@s07zCN1g0U8DonE9@lo3lOQZLVAnvk6qokmV5h7FLIiUcaBBM7iWTxIronhFoWu9hBLEgUV6MZqxdu3tqNlOI1L8xxuKFL6eFDKALWzgwz4qf4m@ZX7PAw "Python 2 – Try It Online")**
---
## 94 bytes
For +4 bytes we can have a version which, using a `while` loop, requires *stripped* lines rather than *padded* lines:
```
def f(s):
i=r=0
while''<s[i]:r+=(ord(s[i])-31)*(i-s[-3::-1].find('='));i+=1
print cmp(r,0)
```
**[Try it online!](https://tio.run/##dYvLCsIwEEX3@QU3s8uMfdCqIESz8DtqkdI2dETTkFSK4L9HCrpw4Vndw@W45zSMdhNj1xswGEgJYO11IWAe@NbLlTyGimvlE42j73ARyrYlrZGzUGVbpbKyzg3bDqWWRAdOdCnAebYTtHeHPi0otk3oQYM8W5lfR7ZY@Wa@sHWPCSn9s2sSBpeSYgmwhx18OAn9i/g@rzc "Python 2 – Try It Online")**
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 bytes
```
O_31×J_¥A+\sṪ€µ÷ḢṪ_2Ṡ
ỴṪLç@ỴḢ$
```
[Test Suite](https://tio.run/##y0rNyan871pRkJpcomCgo2uoY6BjCKKAjP/@8caGh6d7xR9a6qgdU/xw56pHTWsObT28/eGORUBOvNHDnQu4Hu7eAmT7HF7uAGLtWKTyH0gXG0ceblcBqo78/18BBLhsQYBLQaGGC5UPFVBFEUgECSVChGCChgoK5gomClDgCJO0RVIEBugqE/GoVEACKgp1OFVClAMA "Jelly – Try It Online")
Outputs 0 for balanced, 1 for right, and -1 for left.
**How it Works**
```
O_31×J_¥A+\sṪ€µ÷ḢṪ_2Ṡ - helper function. Arguments position of pivot and first line
O - char codes of first line
_31 - subtract 31 to get weight
× - elementwise product with:
J_¥ - distances from the pivot
A - absolute value
+\ - cumulative sum
s - split to get [[...,left weight],...,[..., right + left weight]]
Ṫ€ - last element of each sublist: [left weight, ... right weight]
µ÷Ḣ - get ratio of each element over left weight: ratio n indicates
right + left = n × left ===> right = left if n = 2
_2 - subtract 2: positive is right>left and negative is right<left
Ṡ - return the sign of this
ỴṪLç@ỴḢ$ - main link. Argument: 3 line string.
ç@ - apply helper function with arguments:
Ỵ - split by linefeeds
Ṫ - last line
L - length (returns position of pivot)
$ - and
Ỵ - split by linefeeds
Ḣ - first line
```
[Answer]
## Ruby, 543 bytes
```
def willittip(s)
leftw=0;
rightw=0;
arr=[];
fields=s.split("\n")
pos=fields[2].index("|")
fields[0].split("").each do |i|
arr << i.ord-32
end
arr[pos+1..-1].each_with_index do |x,y|
rightw=rightw+1
if x>0
if pos>0
rightw=rightw+x*(pos-y).abs
else
rightw=rightw+x
end
end
end
arr[0..pos-1].each_with_index do |x,y|
leftw=leftw+1
if x>0
if pos>0
leftw=leftw+x*(pos-y).abs
else
leftw=leftw+x
end
end
end
if leftw==rightw
return "Equal"
elsif leftw<rightw
return "Right"
elsif leftw>rightw
return "Left"
end
end
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 43 bytes\*
```
{×(¯31+⎕UCS⊃⍵)+.×(⍳≢⊃⍵)-'|'⍳⍨⊃⌽⍵}⎕TC[2]∘≠⊆⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Tqw9M1Dq03NtR@1Dc11Dn4UVfzo96tmtp6QOFHvZsfdS6Ciuiq16iDBHpXgAR69gLFaoFaQpyjjWIfdcx41LngUVfbo65F///nAU2FGKZgaMClfmi9oVVaYk5OsUJOalqJtYKBVVJiTmJecmqKjgJMpigzPaNEnStNAagPqFvdFgTUdfJ01BUUanCIo0gAuQqqYAncShJBihIRirArM1RQMFcwUYACR2TltmjawAC33kSS9CogARWFOoJ6oQYAAA "APL (Dyalog Unicode) – Try It Online")
`⊆⊢` partition the argument into runs of characters that are
`⎕TC[2]∘≠` different from the **2**nd **T**erminal **C**ontrol character (Linefeed)\*\*
`{`…`}` apply the following anonymous function on the list of strings:
`⊃⌽⍵` in the first string of the reversed list (i.e. the last)
`'|'⍳⍨` find the **ɩ**ndex of the pivot point
`(`…`)-` subtract that from the following list:
`⊃⍵` the first string
`≢` its length
`⍳` all the **ɩ**ndices of that
`(`…`)+.×` weighted sum with those weights and the following values:
`⊃⍵` the first string
`⎕UCS` code points in the **U**niversal **C**haracter **S**et
`¯31+` add negative thirty-one (32 for the required offset minus one for the rod)
`×` signum of that
---
\* For 1 byte per char, use `{×(¯31+⎕UCS↑⍵)+.×(⍳≢↑⍵)-'|'⍳⍨↑⌽⍵}⎕TC[3]∘≠⊂⊢` with `⎕ML←3`. [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qr8@jtgnG/9OAZPXh6RqH1hsbagOFQ52DH7VNfNS7VVNbDyj8qHfzo85FUBFd9Rp1kEDvCpBAz16gWC1QS4hztHHso44ZjzoXPOpqetS16P//PKCpEMMUDA241A@tN7RKS8zJKVbISU0rsVYwsEpKzEnMS05N0VGAyRRlpmeUqHOlKQD1AXWr24KAuk6ejrqCQg0OcRQJIFdBFSyBW0kiSFEiQhF2ZYYKCuYKJgpQ4Iis3BZNGxjg1ptIkl4FJKCiUEdQL9QAAA "APL (Dyalog Unicode) – Try It Online")
\*\* `⎕TC` is deprecated and used here only for golfing purposes. In production code,
one should use `⎕UCS 10`.
[Answer]
# [Haskell](https://www.haskell.org/) (Lambdabot), 142 bytes
```
l=length
g[a,c,b]=splitAt(l b)$a++(' '<$[1..l c-l a])
k e=sum$zipWith((*).(-31+).ord)e[1..]
f=signum.uncurry(-).(k.drop 1.reverse***k).g.lines
```
[Try it online!](https://tio.run/##fZExT8MwEIV3/4oTCqqdJhYRSCx4qMrIztBmcFsnsXJxItsBgRB/PTiQQsLQN53uvc9nnyvpaoU46KZrrYdta7xtkW@sbV/J1HyUXvJtJe2i8aSdH1CgMqWvSLmTyTE55MJ1qP3GU4QDi@R6TVeweoh2GecIxxRB5ozUoITrm@hdd8/aV5TGjNP0Nlsz3toTU2M6J4VwujR9w3tz7K19o2lI1fxk2w4ybtWLsk7FcVwzXnLURrnhIBEEwA3Bwo9FRmw5FmlGiDZd7x0IArADerU3YtTeAHxcJQFkwUiWxuiEk85OaMD1P3sGghwDcgr8RcIVzpEM4B7uYNLmNyrmyLeWk5ecvMzN5sFMEXxe4M7w9J6ckEZqE1bXWW18gCUi0PNPCMF4oa3zUDD4WSwZvgA "Haskell – Try It Online")
### Ungolfed version:
```
-- for readability, allows reading top-down/left-right
(.>) = flip (.)
ungolfed =
lines -- separate out lines into..
.> (\[a,b,c] -> -- a,b,c (first,second,third)
-- ' ' pad the first line & split on pivot
splitAt (length c) (a ++ replicate (length b - length a) ' ')
)
.> (weight.drop 1.reverse *** weight) -- reverse left half, drop element above pivot & get weight for both
.> uncurry (-) -- subtract right from left
.> signum -- get sign
-- get ord of the character subtract 31 ('=' char from bar),
-- then multiply with scales ([1..]) and sum it all up
weight es = sum $ zipWith (ord .> subtract 31 .> (*)) es [1..]
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 106 ~~107~~ ~~121~~ ~~123~~ ~~124~~ ~~129~~ ~~131~~ bytes
```
c,b,l,i;f(char*a){l=strlen(a)/3;for(i=b=c=0;32/a[l*2+c];++c);for(;i<l-1;b+=(a[i]-31)*(i++-c));a=b>0?2:!b;}
```
Return 0 for falling left, 1 for balance and 2 for falling right.
Require all three lines to have same length and finish with `\n` to determine the length of string.
[Try it online!](https://tio.run/##pY5BTsMwEEX3OcUQUcnjxGriICFhGcQ5mi7GbgOWjEEmrNpy9eBEUZVVKeKvZkbvP40VL9YOgy1N6UunOmZfKXLCg9efffT7wAjXjereI7O6UowKzyVu7FbrRqqisKiMFsJz5kWNayks9xPtEk0btxV1lTCHptBs2huJnDmRiqTNY/UkH26MOg0u9PBGLjDMDhmkfMR06li@2rUhL9MwHqENekwbAI7jliOq6/DE/4av/oDTeKa5cK5cfqkGuIc7mPN8LuulZMoR5vevldH/ZLDILXxfkM3GhSzu@68YoFLZafgB "C (gcc) – Try It Online")
[Answer]
# Mathematica, 91 ~~92~~ bytes
```
Sign[(v=(g=ToCharacterCode)@#&@@(d=#~StringSplit~"
")-31).(Range@(l=Length)@v-l@g@Last@d)]&
```
The first line should have the same length with the rod. The third line should contain no trailing spaces.
Return -1, 0, 1 for falling left, balance and falling right.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~127~~ ~~95~~ 90 + 18 = 108 bytes
For this function the first line must be right padded with spaces to be the same length as the rod and the third line must not have trialing spaces. This conditions are allowed (see comments of the question).
```
s=>s.Split('\n')[0].Select((c,i)=>(c-31)*(i-s.Split('\n')[2].Length+1)).Sum().CompareTo(0)
```
[Try it online!](https://tio.run/##rY/BSsNAEIbv@xRDUbqjzdKo4KFuQAqeKggRPJgelnVbF5LZmt0IovXVY5LWUj0IDf7Hmf/7mNE@0q40deUtLSF988EUYmbpZcKYzpX3cMfeGTTxQQWr4dXZJ7hVljh2482yzRa@qUhf@VA2vhFYCgksQELtZeJFuspt4MOMhvg4novU5EYHzvXIoky4js5jPOE2@lk8m4uZoWV4Po0RRVoVHMXUFStVmnvHx1g3p/66YerIu9yIh9IG03xj@IIPukJGsk1GAB8DxEkv8kD0uCeq2obawgfjMcAlXHw3r3caua/r0tep/sUJezmCzz@cGzHszGu2rr8A "C# (.NET Core) – Try It Online")
Outputs:
-1 for tip left
0 for balance
1 for tip right
[Answer]
# Python 3, 217 bytes
### Also works in Python 2.7
```
def f(s):i,b,p=s.split('\n');c=p.find('|');l=sum((ord(e)-32)*(c-i.find(e))for e in i[:c])+sum(x for x in range(1,c+1));r=sum((ord(e)-32)*i[c:].find(e)for e in i[c:])+sum(x for x in range(len(b[c:])));return(l>r)-(r>l)
```
***Returns 1 for left-side, -1 for right-side, or zero if balanced.***
## Readable version:
```
def f(s):
i,b,p = s.split('\n')
c = p.find('|')
l = sum((ord(e)-32)*(c-i.find(e))for e in i[:c])+sum(x for x in range(1, c+1))
r = sum((ord(e)-32)*i[c:].find(e)for e in i[c:])+sum(x for x in range(len(b[c:])))
return(l>r)-(r>l)
```
[Answer]
# PHP, 105 bytes
```
for([$a,$b,$c]=explode("
",$argn);$b[$i];)$w+=(strpos($c,"|")-$i++)*8*(max(1,ord($a[$i])-31));echo$w<=>0;
```
prints `-1`/`0`/`1` for left/balance/right. Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/48a38d554247a0501168feec482beadb8c9fc21c).
**breakdown**
```
for([$a,$b,$c]=explode("\n",$argn); # import input
$b[$i];) # loop through bar
$f+= # add to force:
($i-strpos($c,"|")) # distance (<0 if left, >0 if right of pivot)
*8 # *8
*(max(1,ord($a[$i++])-31)); # *weight
echo$f<=>0; # print -1 if $f<0, 1 if $f>0, 0 if $f==0
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
A⁰ξFLθA⁺ξ×⁻ι⌕ζ|⁻℅§θι³¹ξI⁻›ξ⁰‹ξ⁰
```
[Try it online!](https://tio.run/##LY3BCsIwEETv/YqlIGwghYrH4qEIilCxB38gtLEuxJRmoxTpv8eE9l12dmeZ6V7KdaMyIdTMNFgsJcyiyp6jA2y0HfwLJyFgc1vzYZwlPOitGW9k40oSzmR7/EnIl1wICev97nqyymDtr7bXM04SKLmHvUgjtbSOrMeTYr9lXZxWXrtUUcafRjOvOlKFAJFddkxkUS6h@IaCzR8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs 0 for balance or -1 or 1 for falling left or right. Edit: Changes in Charcoal now mean that `≔ΣEθ×⁻κ⌕ζ|⁻℅ι³¹ξI⁻›ξ⁰‹ξ⁰` works for 24 bytes: [Try it online!](https://tio.run/##LYtNCsIwEEb3OcVQECYQQXFZXIhQNxYFvcDQBh1Mo2ZSKdK7x5T6Vo/vp7lTaJ7kUtqJ8M3jpe@wphe@DVy5s4I1@17wYaBi3@LXQDEWWhuY81No2ZNDzslmradi0KU6B/YR9yTx/z8ES9EGHAys8uZoRWbPlClBZqG2EyrrmJYf9wM "Charcoal – Try It Online") Link is to verbose version of code. Note: Both answers require padded input, but can be adapted to accept unpadded input at a cost of 3 bytes: `≔⁰ξFLη≔⁺ξ×⁻ι⌕ζ|⁻℅§◨θLηι³¹ξI⁻›ξ⁰‹ξ⁰` [Try it online!](https://tio.run/##RY1NCsIwEIX3PcVQECYQoeKyuCiCIigW8QKhic1ATDGJEqR3jw0t@BZv/njzdVq4bhAmpcZ76i1WHCKri8fgAM/K9kGjZgyWa2veHiOHOz2VxwvZaSQOB7ISvxzKsWSMw7y/OklWGGzCyUoVsRXyRr0O@OLw/8yBsm03LJeMbh3ZgHvhwwI4OiWCcplbsZz1fu4n1Smtil1WAWNaf8wP "Charcoal – Try It Online") `≔ΣE◨θLη×⁻κ⌕ζ|⁻℅ι³¹ξI⁻›ξ⁰‹ξ⁰` [Try it online!](https://tio.run/##LY3BCsIwEETv/YpQEDYQQfFYPIigF4tF/YGlDc3SNGo2lSL999hQ5zS8xzC1QV8/0cZ4YKbWwX3oocQXVNjcqDUB3kpctGuDASOlEg/qNUNJbmDolDiRa@CrRD7lyS786htyaIFmstvKJEZZZJUnF@CIHP77s9cYtIdRiY1MN8xLn1PEuMr2KZmY4vpjfw "Charcoal – Try It Online") Links are to verbose version of code.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
ỴµḢO_31×Ẉạ€/$ṣ0§IṠ
```
[Try it online!](https://tio.run/##y0rNyan8///h7i2Htj7cscg/3tjw8PSHuzoe7lr4qGmNvsrDnYsNDi33fLhzwf/D7UcnPdw5QzPy/38lJSUuWxDgUlCoAXJ0FJBFEEJAtoIqNvFEkEwiRAZNzlBBwVzBRAEKHGFqbJHUggEODYmENSggARWFOpwa4LoA "Jelly – Try It Online")
This started as a golf of [Erik's answer](https://codegolf.stackexchange.com/a/129798/66833) (so be sure to go upvote it), but it developed to be different enough, and Erik is no longer active on the site, that I thought posting a separate answer would be fine.
Outputs `[0]` for balanced, `[1]` for tipping right and `[-1]` for tipping left
## How it works
```
ỴµḢO_31×Ẉạ€/$ṣ0§IṠ - Main link. Takes a string S on the left
Ỵ - Split S into a list of lines [I, R, P]
µ - Use this list as the arguments
Ḣ - Pop and yield I
O - Convert to ordinals
_31 - Subtract 31, mapping space to 1, ! to 2 etc.
$ - Previous 2 links as a monad f([R, P]):
Ẉ - Get the length of each
/ - Reduce by:
€ - Convert len(R) to a range and over each element:
ạ - Take the absolute difference with len(P)
× - Multiply these lists together
ṣ0 - Split at 0, the pivot point
§ - Sum of each side
I - Difference between the sides
Ṡ - Sign
```
] |
[Question]
[
You are working as an intern for a mathematician who *really* hates TeX, LaTeX, etc. So much so that he has decided to abandon all typesetting whatsoever and make you do all the formatting in ASCII. You got tired of this after a while and decided to start automating parts of it, starting with square roots.
Here's how a square root is made:
```
### this is the input
###
###
_____ put a row of underscores stretching one character off either side on top
###
###
###
_____ put a diagonal of slashes in front going the height of the input
/ ###
/ ###
/ ###
_____ put a diagonal of backslashes in front of that, going up half of the input's height rounded up
/ ###
\ / ###
\/ ###
```
And that's it!
### Rules
You are to make a program or function that takes in a string, list of strings (i.e. lines), or array of characters, and outputs the input transformed according to the description above (not necessarily by the exact same order or process)
You may assume that the input is rectangular if preferred. Trailing whitespace is neither required nor disallowed.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
### Examples:
```
Input:
40
Output:
____
\/ 40
Input:
____
\/ 40
Output:
________
/ ____
\/ \/ 40
Input:
/|
|
|
_|_
Output:
_____
/ /|
/ |
\ / |
\/ _|_
Input:
# #
# #
#####
#
#
Output:
_______
/ # #
/ # #
\ / #####
\ / #
\/ #
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 27 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
1w⁄2+╔*00žl»╚;lH╚@Κ№↕h┼№↕;┼
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMTkyMXcldTIwNDQyKyV1MjU1NCowMCV1MDE3RWwlQkIldTI1NUElM0JsSCV1MjU1QUAldTAzOUEldTIxMTYldTIxOTVoJXUyNTNDJXUyMTE2JXUyMTk1JTNCJXUyNTND,inputs=JTVCJTIyLyU3QyUyMCUyMiUyQyUyMiUyMCU3QyUyMCUyMiUyQyUyMiUyMCU3QyUyMCUyMiUyQyUyMl8lN0NfJTIyJTVE) (`→` added for ease-of-use; the program expects the input on stack)
[Answer]
# [Python 2](https://docs.python.org/2/), 196 bytes
```
x=Q=input()
l=len(x)
k=(l+1)/2
q=l+k
x=[[' ']*(q+1)+list(y)for y in x]
for i in range(k):x[i+l/2][i]='\\'
for j in range(l):x[j][q-j-1]='/'
print'\n'.join([' '*q+'_'*(2+len(Q[0]))]+map(''.join,x))
```
[Try it online!](https://tio.run/##Rc5NDoMgEAXgPadgNzOitbpswiFcI2ls0x@UIlqb4Omp2EU3k5eXL3nj1@U5ujrGIBtpnP8sSMxKe3MYiA0SraiorNkkrRhYkEoBB53htNXCmveCK93Hma/cOB40S9mkPHfuccOBTkEZYctaK6MltC3spP8Tm0iv1VT0RbWREpifjVugdXDoR@MwTWaTgDNkWIv0WqOOmkiLV@cRfioPRDEq6DiHHPhlv/wK@gs "Python 2 – Try It Online")
-2 bytes thanks to Step Hen
-13 bytes thanks to Jonathan Allan
[Answer]
# [Python 3](https://docs.python.org/3/), 138 147 Bytes
```
def f(l):h=len(l);w=len(l[0]);c=int(h/2);print('\n'.join([(h*2-c)*' '+w*'_']+[(i*' '+'\\'+(h-i-1)*2*' '+'/'+i*' ')[c:]+s for(i,s)in enumerate(l)]))
```
Variable 'l' is a list of strings, each string a line. Readable Version:
```
def f(l):
height = len(l)
width = len(l[0])
half_height_floor = int(height / 2)
print((height * 2 - half_height_floor) * ' ' + width * '_')
for (index, line) in enumerate(l):
#build a V based on the location of the line
#surrounding V whitespace
outer_space = index * ' '
#inner V whitespace
inner_space = (height - index - 1) * 2 * ' ' #inner v space
#complete V
v = outer_space + '\\' + inner_space + '/' + outer_space
#left half_height_floor chars removed
v_chopped = v[half_height_floor:]
print(v_chopped + line)
```
Forms a square root symbol with a complete V then shaves off the left accordingly.
[Try it Online!](https://tio.run/##dY3BDoIwEETvfsXedrcFUbxB@JLSGMQ2rcFCAEP8@gp41cNk3swcZnjPrg@XGO/GgqWOC1d1JqxQLl9QJ81lW/kwk8tyLodxQ6wDHh@9D6TIiTxtWSCgXAReUUtFfo9Y1yjJpT49s8i/VYZyH1m1hZYT2H4kn0zsA5jwepqxmc16r5kPlhQ2AJgAwm3V5tCi5hh/D3/qDw)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes
```
WS⊞υιP⪫υ¶↖P×_⁺²⌈EυLι↙↙Lυ↑↖÷⁺¹Lυ²
```
[Try it online!](https://tio.run/##VY5BD4IwDIXv/IoGLl0yDnLUKxcMJCTqzcQQnNJkDAIb@O8nA0Xs4aV57fvasiq6simktWNFUgAmqjX6pDtST2QMctNXaDgQO3iZkZraaaLx2JBytn9VPnOjZhC4v7SpeOj/zTPVokf/5nPIpekx4pAVL6pNjVnROkYq1FNXSGyuLytuRvWh5TNoddaE2V7@7S1fcEiUjmmgu8D58G6b4xBNYWsDgMBbxJUHrp3FhoMNe/kG "Charcoal – Try It Online") Link is to verbose version of code. 29-byte version that assumes rectangular input:
```
WS⊞υιP⪫υ¶↖P×_⁺²Lθ↙↙Lυ↑↖÷⁺¹Lυ²
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~131~~ 130 bytes
```
x=input()
n=len(x)
s=" "
for v in[s*2*n+"_"*(2+len(x[0]))]+[s*i+"\\"+s*2*(n+~i)+"/"+s*-~i+r for i,r in enumerate(x)]:print v[n/2:]
```
A full program taking a list of lines as input with the rectangular-only allowance (actually that the first line is one of the longest).
**[Try it online!](https://tio.run/##TY1BC4JAFITv/orXO7muaQhdBA91l36ALlHwpIV6K@tqdvGv22qHHJjDxwwz7cc9DGfzPBaa296FIuDiSRyOIugKBAwaY2EAzVUXZRFLvGIUZnKtVAclhJI@0RLrGuVSCVlOWkhMF9xPWlpYJnTszUDcv8jeHPkDlbdWs4Oh4jTL1TxXmBgm@CnBGBNwb7NFcA9L9Ec/3dsNQqMH2iCUp/J82a3on@9k4ehT9QU "Python 2 – Try It Online")**
[Answer]
# Java 8, 244 bytes
A very long solution, but probably close to the shortest for Java. This lambda takes lines of input as a `String[]` and returns a `String`. All lines must have the same length.
Based on the example outputs, I assumed that there's no need to append a space to each line in the input, so the program doesn't.
Thanks to *Jonathan Allan* for [reminding me](https://codegolf.stackexchange.com/a/135795/44945) about the `~` operator.
```
l->{int h=l.length,w=l[0].length(),a=h/2,i=w+3,x=h+a+h%2;String s="",t=s;for(;--i>0;)t+="_";for(;i++<x;)s+=" ";t=s+t;for(i=0;i<h;)t+="\n"+s.substring(0,i<a?x+~i:i-a)+(i<a?"":"\\"+s.substring(0,(h+~i)*2))+"/"+s.substring(0,i+1)+l[i++];return t;}
```
[Try It Online](https://tio.run/##bZDNbsIwEITPyVNYlirFtWNSesMxvfXWE0dAyEBClhonih1@RNNXT01Ce2h7m92ZHa2@vTqquKwys9@@d1Wz1rBBG62sRW8KDLqGQVXDUbkMWaecN/f@gDcONM8bs3FQGv56F@nM1WB28yVDg5qiHMlOx9MrGIcKqbnOzM4V7CT1PFnep4gwJYvRmIE80Wd2lgVVtHgYi6EEWYkxc9KKvKwjEccwTQRxVOIVHlZAaXoWxPoVwsInqesNkImAtBjCC4Op5bZZ2741Shik6uVMP2ECsSI0uo0YT/Bi8TsYFT5FHseEUDz600KfCNVz/8NS1JlraoOcaDsRenIDzju4YwlbdPBQo29MSNU7S26Mg9nFuuzAy8Zxz9s4baKcq6rSl8hkJ/RzccsGePSBMOsV@ketPla9agkRYdCGbfcF)
## Ungolfed
```
l -> {
int
h = l.length,
w = l[0].length(),
a = h / 2,
i = w + 3,
x = h + a + h % 2
;
String
s = "",
t = s
;
for (; --i > 0; )
t += "_";
for (; i++ < x; )
s += " ";
t = s + t;
for (i = 0; i < h; )
t +=
"\n"
+ s.substring(0, i < a ? x + ~i : i - a)
+ (i < a ? "" : "\\" + s.substring(0, (h + ~i) * 2))
+ "/"
+ s.substring(0, i + 1)
+ l[i++]
;
return t;
}
```
## Acknowledgments
* -2 bytes thanks to *Kevin Cruijssen*
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `a`, 67 bytes
```
L3*½⌈ð*₴⁰hL⇧\_*,ƛ¥⁰L½⌊-:0≥[:ð*\\+₴⁰L½⌈ε‹|_⁰L½⌈]&›ð*₴⁰L¥εð*\/¥ð*++₴,
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=a&code=L3*%C2%BD%E2%8C%88%C3%B0*%E2%82%B4%E2%81%B0hL%E2%87%A7%5C_*%2C%C6%9B%C2%A5%E2%81%B0L%C2%BD%E2%8C%8A-%3A0%E2%89%A5%5B%3A%C3%B0*%5C%5C%2B%E2%82%B4%E2%81%B0L%C2%BD%E2%8C%88%CE%B5%E2%80%B9%7C_%E2%81%B0L%C2%BD%E2%8C%88%5D%26%E2%80%BA%C3%B0*%E2%82%B4%E2%81%B0L%C2%A5%CE%B5%C3%B0*%5C%2F%C2%A5%C3%B0*%2B%2B%E2%82%B4%2C&inputs=40&header=&footer=)
**Don't ask how it works**. It's a giant mess.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~40~~ 32 bytes
```
ẏṘ\\$꘍øm↵:IǏfL:£Nvȯ$Z¥?hL⇧\_*꘍p⁋
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuo/huZhcXFxcJOqYjcO4beKGtTpJx49mTDrCo052yK8kWsKlP2hM4oenXFxfKuqYjXDigYsiLCIiLCJbXCI0MFwiXSJd) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJQIiwixpsiLCLhuo/huZhcXFxcJOqYjcO4beKGtTpJx49mTDrCo052yK8kWsKlbmhM4oenXFxfKuqYjXDigYsiLCI7wqhaJOKBi2BJbnB1dDpcXG5gcCRgXFxuT3V0cHV0OlxcbmBwyK87YFxcblxcblxcbmBqIiwiW1tcIjQwXCJdLCBbXCIgIF9fX19cIixcIlxcXFwvIDQwIFwiXSwgW1wiL3wgXCIsXCIgfCBcIixcIiB8IFwiLFwiX3xfXCJdLCBbXCIjICAjIFwiLFwiIyAgIyBcIixcIiMjIyMjXCIsXCIgICAjIFwiLFwiICAgIyBcIl0sIFtcImFiXCIsXCJjZFwiLFwiZWZcIl1dIl0=).
*-8 bytes from porting 05AB1E*
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 46 bytes
```
l *2
£Vç hY'\ h~Y'/ +S+XÃuVç +'_p2+Ug l¹msV/4
```
Leading newline is part of the program. Input and output is an array of strings representing lines.
[Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=CmwgKjIKo1bnIGhZJ1wgaH5ZJy8gK1MrWMN1VucgKydfcDIrVWcgbLltc1YvNA==&inputs=WyI0MCJd,WyIgIF9fX18iLCAiXC8gNDAgIl0=,WyIvfCAiLCAiIHwgIiwgIiB8ICIsICJffF8iXQ==,WyIjICAjICIsICIjICAjICIsICIjIyMjIyIsICIgICAjICIsICIgICAjICJd&flags=LVI=) using the `-R` flag to join the resulting array with newlines.
[Answer]
## JavaScript (ES6), 140 bytes
Takes input as an array of strings / returns an array of strings.
```
a=>[a[0].replace(/./g,'_'),...a].map((r,y)=>[...a,...a].map((_,x)=>x-y+1|y-.5<l/2?l*2-x-y?' ':'/':'\\',c=y?' ':'_').join``+c+r+c,l=a.length)
```
### Test cases
```
let f =
a=>[a[0].replace(/./g,'_'),...a].map((r,y)=>[...a,...a].map((_,x)=>x-y+1|y-.5<l/2?l*2-x-y?' ':'/':'\\',c=y?' ':'_').join``+c+r+c,l=a.length)
console.log(
f([
'40'
]).join`\n`
)
console.log(
f([
' ____',
'\\/ 40 '
]).join`\n`
)
console.log(
f([
'/| ',
' | ',
' | ',
'_|_'
]).join`\n`
)
console.log(
f([
'# # ',
'# # ',
'#####',
' # ',
' # '
]).join`\n`
)
```
[Answer]
# [Perl 5](https://www.perl.org/), 177 185 160 bytes
```
$s=$f=int((@t=<>)*1.5+.5);print" "x$f;print"_"x length$t[0];print"_
";$b=-int(@t/2);for(0..$#t){--$s;print$_==$s?"/":$_==$b?"\\":" " for 0..$f;print$t[$_];++$b}
```
[Try it online!](https://tio.run/##bU1LCoMwFNx7ivB8C1NJtIVsTFO9R5WAoG1BrMS3EErPnkZrd53NDMN8ps4NynucDfbmMVKSVGTOF344SpVKxfXkggsMFux3bWFhQzfe6I50zZufG4HG1oh1o6LsxHX/dEkuJcbEX0Lg/A2iNQbnEjIoNtmWUNdQhAcWCmwt7EdhHW2j0xTbt/fxhugffQA "Perl 5 – Try It Online")
Changelog:
* needed more bytes to fix a bug (it assumed a *square* input first)
* fixed another bug and used some tips from comments (thanks Dada!)
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~169~~ 151 bytes
*-18 thanks to @[ceilingcat](https://codegolf.stackexchange.com/users/52904)*
```
#define P printf("%*c"
i;k;f(**l,c){P,i=c+c-c/2,32);for(k=strlen(*l)+3;--k;)P,1,95);for(;P,1,10),k<c;P"%s",k,32,*l++))P,i-k-P,k++<c/2?0:k-c/2,92),47);}
```
[Try it online!](https://tio.run/##VZBBboMwEEX3nGJkFMnGYwGGqkod1CuwbyqEHGgtU1oBO8LZqSEkLbOZ@X/eH1nWQjdl@zHP/qWqTVtBDj@daYeakkOgiWeUVTUNggY1G3M0meZa6FBiIpmqvztqs37omqqlQcN4ooSwiuUY4/HptleLiCOG9qRVTg49QevCGDScM0caYUWOlvOTu/oavdj1@lEyTJ@Zmuav0rSUjZ7@LLsAhqof4rd3yGAkaUQm9c@Xmw9QuCII5HwOIY1gjyUbFl5hYWDXimuxp9ON9gH8lfgbllqjd@c2uHhN13cixOwuJIJ8iAQhfYgUwX2VN82/ "C (clang) – Try It Online")
[Answer]
## C++, 291 bytes
The function assumes that all the strings in the vector passed as parameter have the same length
```
#include<vector>
#include<string>
#define S std::string
#define T size()
void f(std::vector<S>&c){c.insert(c.begin(),S(c[0].T+1,'_'));int i,j=0;for(i=1;i<c.T;++i){c[i]='/'+S(i,' ')+c[i];if(i>=c.T/2)c[i]='\\'+S((c.T-i-1)*2,' ')+c[i];}for(auto&a:c)j=j>a.T?j:a.T;for(auto&a:c)a=S(j-a.T,' ')+a;}
```
[Answer]
# Dyalog APL, 95 bytes
```
{((' '/⍨y+x),'_'/⍨2+⊃⌽⍴⍵)⍪⍉(x-y)↓⍉(⊖(x(-x)↑⌽y y⍴'\',' '\⍨y←⌈x÷2),x x⍴'/',' '\⍨x←⊃⍴⍵),' ',⍵,' '}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqDQ11BXX9R70rKrUrNHXU48FsI@1HXc2PevY@6t3yqHer5qPeVY96OzUqdCs1H7VNBjEfdU3TqNDQrQDyJwLVVSpUApWqx6jrAA2LARkGNPpRT0fF4e1GmjoVChUgWX24bAVIFmgBxHSQqA6QAaJrga5SMFEwAalXVudKUzBGYpugsI3BZtYoKIBRfE28OgA)
[Answer]
**C, 485 bytes**
This program takes up to 999 characters from standard input and reads them into an array. It prints them 1 at a time to standard output with the changes your challenge indicated. It assumes the input is rectangular.
```
#include<stdio.h>
#define p(a)putc(a,stdout);
#define P j+j/2+1
a[999],i,j,k,l,m,n,q;char c;pad(a){m=P;if(a&&!k){m-=1;}for(n=0;n!=m;n++){q=32;if((!a||k)&&n==c){c--;q=47;}else if((P-c+1)>j/2+1&&(P)/2-n==c-2){q=92;}p(q);}}int main(){k=i=j=0;x:if(read(0,&c,1)){if('\n'==(a[i++]=c)){if(!j){l=i;}j++;}goto x;}i--;if('\n'==a[i-1]){i--;}else{j++;}c=P-2;for(;k!=i;k++){if(!k||a[k]==10){if(a[k]==10){p(10);}pad(1);if(!k){l++;while(l-->0){p(95);}p(10);pad(0);}if(a[k]==10){continue;}}p(a[k]);}}
```
[Answer]
# [Perl 5](https://www.perl.org/), 159 bytes
```
@a=map{$m=(y///c)>$m?y///c:$m;$_}<>;$_=$"x($l=@a/2-.5).'\\/'.$"x@a;for$i(1..@a){$a[-$i]=$_.$a[-$i];s| \\|\\ |;s|/ | /|;$i>$l&&y/\\/ /}chop;say$_.'_'x++$m,$/,@a
```
[Try it online!](https://tio.run/##LYxBCsIwFET3niLIx7a0zTe23RhTcwFPYKQEUSw0JrQuLMarG4O4mXk8mHGXcWhCkFoY7V5gRDoj4jlrwex/tAXDoXvv2pgCls8UBiE1bkraZDRRChMardT8akfoU0ap1NkL9LGE/iSgo3/kkydKeaWIj4jEE/Qc@haG1WrG@EPwfb5Zxyc9x1XSJc88B1MAFlKHwDbVoqqbRV2x2Oxj3aO39ymUh4au2foL "Perl 5 – Try It Online")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 26 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
L├_×;∔r↔l╷\ ;∔+l½:/; *;∔+↔
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjJDJXUyNTFDXyVENyV1RkYxQiV1MjIxNCV1RkY1MiV1MjE5NCV1RkY0QyV1MjU3NyV1RkYzQyUyMCV1RkYxQiV1MjIxNCV1RkYwQiV1RkY0QyVCRCV1RkYxQSV1RkYwRiV1RkYxQiUyMCV1RkYwQSV1RkYxQiV1MjIxNCV1RkYwQiV1MjE5NA__,i=JTVCJTIyJTIzJTIwJTIwJTIzJTIwJTIyJTJDJTIyJTIzJTIwJTIwJTIzJTIwJTIyJTJDJTIyJTIzJTIzJTIzJTIzJTIzJTIyJTJDJTIyJTIwJTIwJTIwJTIzJTIwJTIyJTJDJTIyJTIwJTIwJTIwJTIzJTIwJTIyJTVE,v=8)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ā<R'\úíº.c.BD2äĆ˜g©δ.£søIнgÌ'_×®úš»
```
Input as a rectangular list of strings-lines (rectangular isn't completely necessary, as long the first line is the longest).
[Try it online](https://tio.run/##yy9OTMpM/f//SKNNkHrM4V2H1x7apZes5@RidHjJkbbTc9IPrTy3Re/Q4uLDOzwv7E0/3KMef3j6oXWHdx1deGj3///RSvo1Cko6SgpIZHxNvFIsAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VT@P9JoE6Qec3jX4bWHdukl6zm5GB1ecqTt9Jz0QyvPbdE7tLj48I7KC3vTD/eoxx@efmjd4V1HFx7a/V/n0Db7/9HRSiYGSrE6CtFKCgrxQKCkoxQTo69gYqAAEdWvAVqhpIBExtfEQ6SUFRSUQQJwGgRAyqB8CA1WmpgE5CenAInUNKXYWAA) or [see the step-by-step output](https://tio.run/##XVSxbhNBEO35ipEbG8kJISUQIYWACAgpCmUSOePz2LfovLvs7uUwSkOTip6GBkFDQSqEEIjmDBUS4o/M7M5dcqGxrPWbt2/ee2vjcaxotertaluGW9AbbtVf7l7r7ZU@B4RC@QBKQ8gJHOoZwcHNIR8wdq0gPQv5UZz5@UqmdihzhJ4gmO7IxhAEfD2C7wh2n07I/Q8dCG4IG4l3vyOmf9iHSoWc0RhgjnrBpDhRegbeYkY@DvQPl9@u0hNmOXi5Q3CAjm91qAqejUPLTzLyRDlnXJqIx3XDdI80owv1kuWpuS1UpkKxgGdGaQ/jBWiqmIl8Wm49k6Ft8wJUgIFnfACjL1BDQD0BnEwuJLSyqpxYmCb@7tEthG67MbaM92IgGRfWuFJm7ILziCZWBuh5icWaZ6kTsOiCh4GwRuhUOQ4zHoPyUKCbkYMpL2xYjPguO@xsLj/Itfd1VhhPtwGtJb5XMaOpNORsfMr9THAPCgyBdDz6/bbJzNgk1cbs4vVyAwyS/mBYlErVOkGncFwQHNfnxylhU7JMYy17k/TM6o/C@ZjIduK/MDDL0WEWOG@YOjNvMg@uyffP5/X6vTA8rdCKhbGogdgOdqXtFbXN5tbHQb/82ingpYctSjdx2O6u0SPZNVLs/v2xNROSXd08Dt6ba7OZqvdafnuIJ8TPTTSDmXa27I/6qdmj5ZtGDE7Eq7b@ODelDnHq8iHU5@1D2HPUZNc@tXa9X@8E8YibLJ4prbkT6dGzQmGTFXlO/gVE4pXic6ZTNp8LrJijIsjjNqbkZpWBnUoh1t@Hq9VB78Ypf@9B53N0Ouod/QM).
**Explanation:**
```
ā # Push a list in the range [1, (implicit) input-length]
< # Decrease each by 1 to the range [0, length)
R # Reverse it to the range (length, 0]
'\ '# Push string "\"
ú # Pad "\" with the integer amount of leading spaces
í # Reverse each, so the spaces are trailing
º # Mirror each line
.c # Centralize (implicitly joins by newlines)
.B # Box it (split on newlines, and add trailing spaces)
D # Duplicate it
2ä # Split it into two equal-sized parts (where the first is longer
# for odd-length lists)
Ć # Enclose: append its own head
˜ # Flatten
g # Pop and push the length
© # Store it in variable `®` (without popping)
δ # Map over each string:
.£ # Only leave the last `®` amount of characters
s # Swap so the input-list is at the top
ø # Create pairs of the two lists
Iн # Push the first line of the input-list
g # Pop and push its length
Ì # Increase it by 2
'_× '# Pop and push a string of that many "_"
®ú # Pad `®` amount of leading spaces
š # Prepend it to the list
» # Join each inner list by spaces, and then the strings by newlines
# (after which the result is output implicitly)
```
`2äĆ˜g` could alternatively be `gD;î+` for the same byte-count (length; duplicate; halve; ceil; sum together): [try it online](https://tio.run/##yy9OTMpM/f//SKNNkHrM4V2H1x7apZes5@SS7mJ9eJ32oZXntugdWlx8eIfnhb3ph3vU4w9PP7Tu8K6jCw/t/v8/Wkm/RkFJR0kBiYyviVeKBQA).
] |
[Question]
[
Here’s how to **backspace-and-retype** from one string to another:
1. Start from the first string.
2. Remove characters at the end until the result is a **prefix** of the second string. (This may take 0 steps.)
3. Add characters at the end until the result equals the second string. (This may take 0 steps, too.)
For example, the path from `fooabc` to `fooxyz` looks like:
```
fooabc
fooab
fooa
foo
foox
fooxy
fooxyz
```
## Task
Given a list of words, write a program that **backspace-and-retypes** its way from the empty string, to all of the words in the list in succession, back to the empty string. Output all intermediate strings.
For example, given the input list `["abc", "abd", "aefg", "h"]`, the output should be:
```
a
ab
abc
ab
abd
ab
a
ae
aef
aefg
aef
ae
a
h
```
## Rules
You may return or print a list of strings, or a single string with some delimiter of choice. You may **optionally** include the initial and final empty strings. The input is guaranteed to contain at least one word, and each word is guaranteed to contain only lowercase ASCII letters (`a`–`z`). *Edit:* consecutive strings in the input are guaranteed not to equal each other.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest code in bytes wins.
A reference implementation in Python 3: [Try it online!](https://tio.run/nexus/python3#hY3BDsIgDIbve4q6y5jiEnZc4pMQYtAxR4JAoEriy09YlsWbvfzt/39tF/30LiDIiFVyYYxwKX1nNKogzVW9pSHa@heStt0J3jQUjutEoWlENbkAiVFIPWgLH@3JFq7C2SDaoYJcadZGgXWY0S6iDBiTxpkktgGlfNAWi7U7ieWvifHhzMTPnWwfst//WT0VhhtlSyCWhdfydq8pZBlXUdOj6FyLLw "Python 3 – TIO Nexus\"")
[Answer]
## Perl, 43 bytes
42 bytes of code + `-n` flags.
```
chop$@,say$@while!s/^$@//;s/./say$@.=$&/ge
```
To run it:
```
perl -nE 'chop$@,say$@while!s/^$@//;s/./say$@.=$&/ge' <<< "abc
abd
aefg
h"
```
[Answer]
# Pyth, ~~25~~ 23 bytes
```
V+QkWxNk
=Pk)
M>._Nl~kN
```
[Try it online.](http://pyth.herokuapp.com/?code=V%2BQkWxNk%0A%3DPk%29%0AM%3E._Nl%7EkN&input=%5B%22abc%22%2C+%22abd%22%2C+%22aefg%22%2C+%22h%22%5D&debug=0)
[Answer]
# Java 8, 144 bytes
This one is similar to the reference implementation but combines the two `while` loops. It's a lambda expression accepting a `String[]` parameter.
```
a->{String c="";int l=0,i;for(String w:a)while((i=w.indexOf(c))!=0||!c.equals(w))System.out.println(c=i!=0?c.substring(0,--l):c+w.charAt(l++));}
```
## Ungolfed
```
a -> {
String c = "";
int l = 0, i;
for (String w : a)
while ((i = w.indexOf(c)) != 0 || !c.equals(w))
System.out.println(c = i != 0 ? c.substring(0, --l) : c + w.charAt(l++));
}
```
## Acknowledgments
* -38 bytes thanks to CAD97's lambda suggestion
[Answer]
# Mathematica, 149 bytes
```
Reap[Fold[n=NestWhile;s=StringMatchQ;r=StringReplace;n[k=#2;Sow@r[k,#~~a_~~___:>#<>a]&,n[Sow@r[#,a___~~_:>a]&,#,!s[k,#~~___]&],k!=#&]&,"",#]][[2,1]]&
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 39 bytes
Byte count assumes ISO 8859-1 encoding.
```
M!&r`.+
%)`\G.
¶$`$&
+`((.*).¶)\2¶\1
$1
```
[Try it online!](https://tio.run/nexus/retina#@@@rqFaUoKfNpaqZEOOux3Vom0qCihqXdoKGhp6Wpt6hbZoxRoe2xRhyqRj@/5@YlMyVmJTClZials6VAQA "Retina – TIO Nexus")
Input and output are linefeed-separated lists. Output does include the leading and trailing empty string.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~31~~ ~~29~~ 26 bytes
```
⁷œ|;\
ÇṚðfḢṭḟ;ḟ@ḊðÇ}
⁷;ç2\
```
[Try it online!](https://tio.run/nexus/jelly#@/@ocfvRyTXWMVyH2x/unHV4Q9rDHYse7lz7cMd8ayB2eLij6/CGw@21XEB11oeXG8X8//9fPTEpWV1HAUilgKnUtHQQnaEOAA "Jelly – TIO Nexus")
### How it works
```
⁷;ç2\ Main link. Argument: A (string array)
⁷; Prepend a linefeed to A.
This is cheaper than prepending an empty string.
ç2\ Reduce all overlapping pairs by the second helper link.
ÇṚðfḢṭḟ;ḟ@ḊðÇ} Second helper link. Arguments: s, t (strings)
Ç Call the first helper link with argument s.
Ṛ Reverse the results.
Ç} Call the first helper link with argument t.
ð ð Combine everything in between into a dyadic chain, and call it
with the results to both sides as arguments.
Let's call the arguments S and T.
f Filter; get the common strings of S and T.
Ḣ Head; select the first one.
ḟ Filterfalse; get the strings in S that do not appear in T.
ṭ Tack; append the left result to the right one.
ḟ@ Filterfalse swap; get the strings in T that do not appear in S.
; Concatenate the results to both sides.
Ḋ Dequeue; remove the first string.
⁷œ|;\ First helper link. Argument: s (string)
⁷œ| Linefeed multiset union; prepend a linefeed to s unless it already
has a linefeed in it (the first string does).
;\ Concatenate cumulative reduce; generate all prefixes of the result.
```
[Answer]
# GNU M4, 228 or 232 bytes¹
(¹ depending on whether to end the file with `dnl\n` or not—I'm still new to both golfing and M4)
```
define(E,`ifelse(index($2,$1),0,`T($1,$2)',`$1
E(substr($1,0,decr(len($1))),$2)')')define(T,`ifelse($1,$2,,`$1
T(substr($2,0,incr(len($1))),$2)')')define(K,`ifelse($2,,$1,`E($1,$2)K(shift($@))')')define(M,`K(substr($1,0,1),$@)')
```
Additionally, 3 bytes could be saved by replacing the second argument for `substr` from `0` to the empty string, but that would produce a lot of warnings on stderr.
Ungolfed:
```
define(erase_til_prefix, `dnl arguments: src dst; prints src and chops one char off of it until src == dst, at which point it calls type_til_complete instead
ifelse(dnl
index($2, $1), 0, `type_til_complete($1, $2)',dnl
`$1
erase_til_prefix(substr($1, 0, decr(len($1))), $2)dnl
')')dnl
define(type_til_complete, `dnl arguments: src dst; types src, does not type `dst' itself
ifelse(dnl
$1, $2, ,dnl
`$1
type_til_complete(substr($2, 0, incr(len($1))), $2)'dnl
)')dnl
define(main_, `dnl
ifelse(dnl
$2, , $1, dnl no arguments left
`erase_til_prefix($1, $2)main_(shift($@))'dnl
)')dnl
define(main, `main_(substr($1, 0, 1), $@)')dnl
```
Usage:
```
$ m4 <<<"include(\`backspace-golfed.m4')M(abc, abd, aefg, abcdefg, h)"
```
[Answer]
## [Haskell](https://www.haskell.org/), ~~102 93 91~~ 90 bytes
```
(?)=take.length
a!x@(b:c)|a==b=b!c|a/=a?b=a:init a!x|d<-'?':a=a:d?b!x
_!x=x
(""!).(++[""])
```
The last line is an anonymous function, which takes and returns a list of strings.
[Try it online!](https://tio.run/nexus/haskell#XYrLCsIwEADv/YrNIjShWu/BJf5HKbJ5EIM2iOSQQ/49FjwIXgZmmI1TBoLXO@UCB4iwIHuPR2TrvvThZ3997dIoKvwI8zPkWO4Di3qVVjvVmMiSFa7xmdhYYp1yKrAPzV9Ooxk1780bK@pwE5XqEEkiCjXLaVoQV9X7Bw "Haskell – TIO Nexus")
## Explanation
My solution is recursive.
First, `?` is a helper infix function: `a?b` gives the first `length a` characters of `b`, or the whole of `b` if `a` is longer.
Next I define an infix function `!`.
The idea is that `a!x`, where `a` is a string and `x` a list of strings, produces the path from `a` to the first string in `x` and recurses to the tail of `x`.
On the final line I define an anonymous function that appends the empty string, then applies `!` to the empty string and the input.
Explanation of `!`:
```
a!x@(b:c) -- a!x, where x has head b and tail c:
|a==b -- If a equals b,
=b!c -- recurse to x.
|a/=a?b -- If a is not a prefix of b,
=a: -- produce a and
init a!x -- continue with one shorter prefix of a.
| -- Otherwise a is a proper prefix of b.
d<-'?':a -- Let d be a with an extra dummy element,
=a: -- produce a and
d?b!x -- continue with one longer prefix of b.
_!x=x -- If x is empty, return x.
```
[Answer]
# Python 2, ~~118~~ ~~107~~ ~~103~~ ~~97~~ ~~93~~ 92 bytes
```
s=''
for i in input()+[s]:
while i.find(s):s=s[:-1];print s
while i>s:s+=i[len(s)];print s
```
Input is given as `['abc', 'abcdef', 'abcfed']`, or as [`"abc", "abcdef", "abcfed"]`.
Revision 1: -11 bytes. Credit goes to @xnor for his post on Python golfing tips, and to @Lynn for finding the tip for me, and to me for being smart. Two changes were made: Instead of `not s.startswith(i)`, I used `s.find(i)`, and instead of `i!=s` I used `i>s`.
Revision 2: -4 bytes. Credit goes to me realizing I made a really dumb mistake. Instead of using single-tab and double-tab indentation, I used single-space and single-tab indentation.
Revision 3: -6 bytes. Credit goes to @mbomb007 for suggesting to put the whiles on a single line. I also fixed a bug by changing `s.find(i)` to `i.find(s)`.
Revision 4: -4 bytes. Credit goes to @xnor for realizing that I didn't need to store the input in a variable.
Revision 5: -1 byte. Credit goes to me for realizing that `['']` is the same thing as `[s]` when adding it to the input.
[Answer]
# PHP, ~~116~~ ~~111~~ ~~101~~ 83 bytes
Note: uses Windows-1252 encoding.
```
for(;$w=$argv[++$i];)for(;$c!=$w;)echo$c=($c^$c^$w)==$c?$c.ÿ&$w:substr($c,0,-1),~õ;
```
Run like this:
```
php -r 'for(;$w=$argv[++$i];)for(;$c!=$w;)echo$c=($c^$c^$w)==$c?$c.ÿ&$w:substr($c,0,-1),~õ;' -- abc abd aefg h 2>/dev/null
> a
> ab
> abc
> ab
> abd
> ab
> a
> ae
> aef
> aefg
> aef
> ae
> a
>
> h
```
# Explanation
```
for( # Outer loop.
;
$w=$argv[++$i]; # Loops over the input words.
)
for( # Second inner loop.
;
$c!=$w; # Loop until the word was output.
)
echo $c=
($c^$c^$w)==$c? # Check if last output string is a substring
# match with the next word to output.
$c.ÿ&$w: # ... If yes, suffix the string with the next
# char of the word, and output the result.
substr($c,0,-1), # ... If not, remove a char and output.
~õ; # Output newline.
```
# Tweaks
* Saved 5 bytes by using `trim($c^$w,"\0")` to check for substring match instead of `$c&&strpos($w,$c)!==0`.
* Saved 2 bytes by using `~ÿ` to yield a string with a NUL byte instead of `"\0"`
* Saved 8 bytes by using `$c=$c.ÿ&$w` to suffix `$c` with the next char of `$w`
* Saved a massive 18 bytes by combining the logic of the 2 inner loops in a single loop
* Fixed a bug with a testcase from the comments, no change in byte count
[Answer]
## Batch, ~~296~~ 291 bytes
```
@echo off
set f=
set t=%1
:t
set f=%f%%t:~,1%
set t=%t:~1%
echo(%f%
if not "%t%"=="" goto t
shift
set t=%1
set s=%f%
set p=
:h
if %s:~,1%==%t:~,1% set p=%p%%t:~,1%&set s=%s:~1%&set t=%t:~1%&goto h
:b
set f=%f:~,-1%
echo(%f%
if not "%f%"=="%p%" goto b
if not "%1"=="" goto t
```
Computing the common prefix was cumbersome.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~33~~ 30 bytes
```
FsgAExTyQsYPyQs@<#y?y.s@#y;@<y
```
[Try it online!](https://tio.run/##K8gs@P/frTjd0bUipDKwODIASDjYKFfaV@oVOyhXWjvYVP7//z8xKRmIU/4npqal/88AAA "Pip – Try It Online")
### Explanation
```
g is list of cmdline args; x & y are "" (implicit)
Fs For each s in
gAEx g with an empty string appended:
TyQs Do this till y equals s:
s@< Get the prefix of s
#y having the same length as y
yQ and check if it equals y
? If so (y is a prefix of s), calculate:
y. y, concatenated with
s@ the character in s at index
#y len(y)
; If not, calculate:
@<y y without its last character
YP Print that quantity and yank it back into y
```
[Answer]
# PHP, 153 bytes
awfully long :(
```
for($s=$argv[$k=1];$t=$argv[++$k];){for(;$s>""&&strstr($t,$s)!=$t;$s=substr($s,0,-1))echo"$s
";for($i=strlen($s);$s<$t;$s.=$t[$i++])echo"$s
";echo"$s
";}
```
Run with `php -nr '<ode>' <text1> <text2> ...`.
[Answer]
# JavaScript (ES6), 135 bytes
Interesting challenge! Usage: `g(["abc", "abd", "aefg", "h"])`. I couldn't seem to save any bytes by writing this as one function, so it's two. Newlines not included in byte count.
```
f=a=>console.log(([,...z]=[x,y]=a)[0])||
y?f(a=(x==y.slice(0,-1))?z:([y.match(x)
?x+y[x.length]:x.slice(0,-1),...z])):1;
g=a=>f(['',...a])
```
I'm sure this can be reduced a lot more. Will add ungolfed version later.
[Answer]
# Javascript, 98 bytes
```
a=>{c="",l=0;for(w of a)while((i=w.indexOf(c))!=0||c!=w)alert(c=i!=0?c.substring(0,--l):c+w[l++])}
```
Port of Jakob's Java answer
] |
[Question]
[
## Background
The so-called "Urinal Protocol", describing the order in which individual urinals are picked in a men's bathroom, has been discussed in multiple places. One version is given in [this xkcd blog post](http://blog.xkcd.com/2009/09/02/urinal-protocol-vulnerability/). This question concerns a slight variation:
>
> **Arrangement**: n urinals in a line.
>
> **Protocol**: each new person selects one of the urinals most distant from those already in use.
>
>
>
Note that this places *no* restrictions on which urinal is picked by the first person.
**Update**: The sequence of the number of different ways in which n people can select n urinals starts with 1, 2, 4, 8, 20... Note that this *not* the same as [OEIS](http://oeis.org/) [A095236](http://oeis.org/A095236), which describes slightly stricter restrictions than in this question.
## Task
Given an integer n between 0 and 10, output (in any order) all the possible orderings in which n people can occupy n urinals. Each ordering should be printed as the final arrangement: a sequence of digits representing the people (1-9 for the first 9 people, 0 for the tenth), starting from the leftmost urinal, with *optional* non-alphanumeric separators between (but not before or after) the digits. For example, the following outputs are both valid:
```
>> 3
132
213
312
231
>> 4
1|3|4|2
1|4|3|2
3|1|4|2
4|1|3|2
2|3|1|4
2|4|1|3
2|3|4|1
2|4|3|1
```
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument. Results should be printed to STDOUT (or closest alternative).
## Scoring
Shortest code wins. Standard terms & conditions apply.
[Answer]
# Pyth, ~~53~~ 51
```
MhSm^-dG2HjbmjdmehxkbQusmm+dkfqgTdeSmgbdQUQGUtQm]dQ
```
This is an iterative approach. Given a possible partially filled in ordered sets of locations, we find all the optimal further locations, then generate the corresponding location list, and repeat.
Results are generated in the form `[<first person's location>, <second person's location> ...]`, then this is transformed into the desired format. `MhSm^-dG2H` defines a helper function which finds the minimum distances from a given stall to an occupied stall (squared). Amusingly, the separator is free.
[Example run.](https://pyth.herokuapp.com/?code=MhSm%5E-dG2HjbmjdmehxkbQusmm%2BdkfqgTdeSmgbdQUQGUtQm%5DdQ&input=4)
Explanation:
First, the helper function `g`, which finds the minimum squared distance between G and any value in H.
```
MhSm^-dG2H
M def g(G,H): return
hS min( )
m H map(lambda d: , H)
^-dG2 (d-G)**2
```
Next, we find the maximum over urinal locations of the minimum squared distance between that urinal and any occupied urinal:
(`Q` is the input.)
```
eSmgbdQ
eS max( )
m Q map(lambda b: , range(len(Q)))
gbd g(b,d)
```
`d` in this case is the list of occupied urinals, while `b` iterates over urinal locations.
Next, we find all urinal locations whose minimum squared distance from the nearest occupied urinal is equal to the maximum value found above.
```
fqgTdeSmgbdQUQ
f UQ filter(lambda T: , range(len(Q)))
qgTd g(T,d) ==
eSmgbdQ <value found above>
```
Next, we will generate the urinal location lists created by adding the urinal locations found above to `d`. We will do this for each previous list of urinal locations, thus extending the lists from length `N` to `N+1`. `G` is the list of legal lists of occupied urinal locations of a given length.
```
smm+dkfqgTdeSmgbdQUQG
sm G sum(map(lambda d: ,G)
m+dk map(lambda k:d+[k], )
fqgTdeSmgbdQUQ <above list>
```
Next, we will apply the above expression repeatedly, to generate the complete list of lists of occupied urinal locations. `u`, the reduce function, does exactly this, as many times as there are elements in its second argument.
```
usmm+dkfqgTdeSmgbdQUQGUtQm]dQ
usmm+dkfqgTdeSmgbdQUQG reduce(lambda G,H: <the above expression)
UtQ repeat Q-1 times
m]dQ starting with [[0], [1], ... [Q-1]].
```
Convert from the above representation, which goes `[<1st location>, <2nd location>, ... ]`, to the desired output form, `[<person in slot 1>, <person in slot 2>, ... ]`. Then, the output form is joined into the output string and printed. Printing is implicit.
```
jbmjdmehxkbQ
jbm '\n'.join(map(λ k: ,<above>)
jdm Q ' '.join(map(λ b: ,Q)
xkb b.index(k)
eh +1 %10
```
[Answer]
# Pyth, 75 71 67
```
DcGHFk_UQJf!s:GeS,0-TkhS,h+TklGUQIJRsmcX>G0dhHhHJ)R]Gjbmjdmebkcm0Q0
```
Recursive combinatorial solution.
It's a fairly direct translation from this Python solution:
```
N = int(input())
def gen(l, p):
for d in reversed(range(N)):
s = []
for i in range(N):
if not sum(l[max(0,i-d):min(i+d+1, len(l))]):
s.append(i)
if s:
r = []
for possib in s:
j = l[:]
j[possib] = p+1
r += gen(j, p+1)
return r
return [l]
print("\n".join(" ".join(str(x % 10) for x in sol) for sol in gen([0] * N, 0)))
```
[Answer]
# C, ~~929~~ 878 bytes
This one's a monster, guys. Sorry.
```
typedef unsigned long U;typedef unsigned char C;U f(int*u,n){C c[8],a[8];*(U*)(&c)=-1;int i,b=0,l=-9,s=-2,f=0,d;for (i=0; i<n; i++) {if (!u[i]&&s<0)s=i,l=0;if(!u[i])l++;if(u[i]&&s>=0){if(!s)l=2*l-1;d=(l-1)/2;if(b<d)*(U*)(a)=0,*(U*)(c)=-1,*c=s,*a=l,f=1,b=d;else if(b==d)c[f]=s,a[f++]=l;s=-1;}}if(s>=0&&l){l=2*l-1;d=(l-1)/2;if(b<d)*(U*)(c)=-1,*c=s,*a=l,f=1,b=d;else if(b==d)c[f]=s,a[f++]=l;}d=f;for(i=0;i<d;i++){if((c[i]+1)&&c[i]){if(c[i]+a[i]==n)c[i]=n-1;else{if(!(a[i]%2))c[f++]=b+c[i]+1;c[i]+=b;}}}return*(U*)c;}void P(int*u,n,i,c,m){for(i=0;i<n;i++){if(!u[i])c++;if(u[i]>m)m=u[i];}if(!c){for(i=0;i<n;i++)printf("%d",u[i]==10?0:u[i]);printf("\n");}else{int s[8][n];for(i=0;i<8;i++)for(c=0;c<n;c++)s[i][c]=u[c];U t=f(u,n);C*H=&t;for(i=0;i<8;i++)if((C)(H[i]+1))s[i][H[i]]=m+1,P(s[i],n,0,0,0);}}void L(n){int u[n],i,j;for(i=0;i<n;i++){for(j=0;j<n;j++)u[j]=j==i?1:0;P(u,n,0,0,0);}}
```
Defines 3 functions, `f(int*,int)`,`P(int*,int,int,int,int)`, and `L(int)`. Call `L(n)`, and it outputs to STDOUT.
Output for `n=5`:
```
14352
15342
31452
31542
41352
51342
41532
51432
24153
25143
34152
35142
23415
23514
24513
25413
24315
25314
24351
25341
```
**Update:** I removed separators and fixed up the code. The old code not only failed for n=7+, but failed to output anything at all for n=10 (oops!). I've more thoroughly tested this bunch. It now supports input of up to n=13 (though the `"%d"` should be changed to `"%x"`so it prints in hexadecimal). The size of input depends on `sizeof(long)` and it is assumed to be `8` in practice.
Here's some explanation of how it works, and why such an odd restriction exists:
These were used a lot, so we define them to save a couple bytes:
`typedef unsigned long U; typedef unsigned char C;`
Here is `f`:
```
U f(int*u,n){
C c[8],a[8];
*(U*)(&c)=-1;
int i,b=0,l=-9,s=-2,f=0,d;
for (i=0; i<n; i++) {
if (!u[i]&&s<0)
s=i,l=0;
if(!u[i])
l++;
if(u[i]&&s>=0){
if(!s)
l=2*l-1;
d=(l-1)/2;
if(b<d)
*(U*)(a)=0,
*(U*)(c)=-1,
*c=s,
*a=l,
f=1,
b=d;
else if(b==d)
c[f]=s,a[f++]=l;
s=-1;
}
}
if(s>=0&&l){
l=2*l-1;
d=(l-1)/2;
if(b<d)
*(U*)(c)=-1,
*c=s,
*a=l,
f=1,
b=d;
else if(b==d)
c[f]=s,a[f++]=l;
}
d=f;
for(i=0;i<d;i++){
if((c[i]+1)&&c[i]){
if(c[i]+a[i]==n)
c[i]=n-1;
else{
if(!(a[i]%2))
c[f++]=b+c[i]+1;
c[i]+=b;
}
}
}
return*(U*)c;
}
```
`f` takes an array of integers of size `n`, and `n` itself. The only clever bit here is that it returns an `unsigned long`, which is converted into a `char[8]` by the calling function. Each character in the array is thus set either to `0xFF` or to an index pointing to a valid urinal for the next person. For `n<10`, we never need more than 5 bytes to hold every valid urinal the next person can use.
Here is `P`:
```
void P(int*u,n,i,c,m){
for(i=0;i<n;i++){
if(!u[i])c++;
if(u[i]>m)m=u[i];
}
if(!c){
for(i=0;i<n;i++)
printf("%d",u[i]==10?0:u[i]);
printf("\n");
}
else{
int s[8][n];
for(i=0;i<8;i++)
for(c=0;c<n;c++)
s[i][c]=u[c];
U t=f(u,n);
C*H=&t;
for(i=0;i<8;i++)
if((C)(H[i]+1))
s[i][H[i]]=m+1,P(s[i],n,0,0,0);
}
}
```
`P` takes an array `u` of size `n` wherein exactly one element is set to `1`, and the rest are `0`. It then finds and prints every permutation possible recursively.
Here is `L`:
```
void L(n){
int u[n],i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++)
u[j]=j==i?1:0;
P(u,n,0,0,0);
}
}
```
`L` simply calls `P` `n` times with different starting positions each time.
For the interested, this (less golfed) `f` will generate the sequence in [A095236](http://oeis.org/A095236 "OEIS A095236").
```
U f(int*u,n) {
C c[8];
*(U*)(&c) = -1;
int i,b=0,l=-10,s=-2,f=0,d;
for (i=0; i<n; i++) {
if (!u[i]&&s<0) {
s=i,l=0;
}
if(!u[i]){
l++;
}
if (u[i]&&s>=0) {
if (!s) {
l=2*l-1;
}
if (b<l) {
*(U*)(&c)=-1;
c[0]=s;
f=1;
b=l;
}
else if (b==l)
c[f++]=s;
s=-1;
}
}
if (s>=0&&l) {
l=2*l-1;
if (b<l) {
*(U*)(&c)=-1;
c[0]=s;
f=1;
b=l;
}
else if (b==l)
c[f++]=s;
}
d=f;
for (i=0; i<d; i++) {
if ((c[i]+1)&&c[i]) {
if (c[i]+b==n) {
c[i]=n-1;
}
else{
if (!(b%2)) {
c[f++]=(b-1)/2+c[i]+1;
}
c[i]+=(b-1)/2;
}
}
}
return *(U*)c;
}
```
[Answer]
# Python 2, 208
```
n=input()
r=range(n)
l=[0]*n
def f(a,d=-1):
if a>n:print''.join(l);return
for i in r:
t=min([n]+[abs(i-j)for j in r if l[j]])
if t==d:p+=[i]
if t>d:p=[i];d=t
for i in p:l[i]=`a%10`;f(a+1);l[i]=0
f(1)
```
Recursive approach.
[Answer]
# JavaScript (ES6) 153 ~~160 169~~
**Edit** Using Math.min to find (of course) the max distance: streamlined code and 16 bytes saved.
Recursive search, can work with n > 10, just remove % 10 (and be prepared to wait while the console unrolls all its output).
I use a single array to store the slot in use (positive numbers) or the current distance from the nearest slot (negative numbers so `<` and `>` are swapped in code).
```
F=n=>{(R=(m,d,t,x=Math.min(...d=m?
d.map((v,i)=>(c=i<t?i-t:t-i)?v<c?c:v:m%10)
:Array(n).fill(-n)))=>
x<0?d.map((v,i)=>v>x||R(-~m,d,i)):console.log(d+[]))()}
```
**Ungolfed**
```
F=n=>{
var R=(m, // current 'man', undefined at first step
d, // slot array
t // current position to fill
) =>
{
if (m) // if not at first step
{
d[t] = m % 10; // mark slot in use, (10 stored as 0 )
d = d.map((v,i) => { // update distances in d[]
var c = i<t ? i-t : t-i; // distance from the current position (negated)
return v < c ? c : v; // change if less than current distance
});
}
else
{
d = Array(n).fill(-n) // fill distance array with max at first step
// negative means slot free, value is the distance from nearest used slot
// >= 0 means slot in use by man number 1..n
}
var x = Math.min(...d);
if ( x < 0 ) // if there is still any free slot
{
d.forEach((v,i) => { // check distance for each slot
if (v <= x) // if slot is at max distance, call recursive search
R(-~m, [...d], i) // ~- is like '+1', but works on undefined too
});
}
else
{
console.log(d+[]); // no free slot, output current solution
}
}
R() // first step call
}
```
**Test** In Firefox/FireBug console
```
F(5)
```
>
> 1,4,3,5,2
>
> 1,5,3,4,2
>
>
>
>
[Answer]
# Mathematica, ~~123~~ 104
```
f[n_,s_:{}]:=If[Length@s<n,f[n,s~Join~{#}]&/@MaximalBy[Range@n,Min@Abs[#-s]&];,Print@@Ordering@s~Mod~10]
```
[Answer]
## MATLAB, 164
```
function o=t(n),o=mod(r(zeros(1,n)),10);function o=r(s),o=[];d=bwdist(s);m=max(d);J=find(d==m);if~d,o=s;J=[];end,n=max(s)+1;for j=J,o=[o;r(s+n*(1:numel(s)==j))];end
```
[Answer]
# Perl, 174
Not very short, but fun. I'm not counting `use feature 'say';` towards the byte total.
```
$n=pop;@u="_"x$n." "x$n."_"x$n;for$p(1..$n){@u=map{my@r;for$x(reverse 0..$n){
s/(?<=\D{$x}) (?=\D{$x})/push@r,$_;substr $r[-1],pos,1,$p%10/eg and last;
}@r}@u}y/_//d&&say for@u
```
De-golfed:
```
$n = pop; # Get number of urinals from commandline
@state = ( "_" x $n . " " x $n . "_" x $n );
for my $person (1 .. $n) {
# Replace each state with its list of possible next states.
@state = map {
my @results;
for my $distance (reverse 0 .. $n) {
# If there are any spots with at least $distance empty on
# both sides, then add an entry to @results with the current
# $person number in that spot, for each spot. Note that this
# is only used for its side-effect on @results; the modified $_
# is never used.
s{
(?<=\D{$distance})
[ ]
(?=\D{$distance})
}{
push @results, $_;
substr $results[-1], pos(), 1, $person % 10;
}xeg
# If we found any spots, move on, otherwise try
# with $distance one lower.
and last;
}
# New state is the array we built up.
@results;
} @state;
}
# After adding all the people, remove underscores and print the results
for my $result (@state) {
$result =~ tr/_//d;
say $result;
}
```
[Answer]
# C, 248 bytes
This code uses a recursive algoritm to generate the desired outcome.
```
void q(char*f,int l,int d,char*o){char*c=f;while(f<c+l){if(!*f){sprintf(o+4*d,"%03i,",f-c);*f=1;q(c,l,d+1,o);*f=0;}f++;}if(d+1==l){o[4*d+3]=0;printf("%s\n",o);}}int main(int i,char**v){int k=atoi(v[1]);char*c=calloc(k,5),*o=c+k;q(c,k,0,o);free(c);}
```
---
*Expanded:*
```
void printperms(char* memory,int length,int offset,char*output)
{
char*temp_char=memory;
while(memory<temp_char+length)
{
if(!*memory)
{
sprintf(output+4*offset,"%03i,",memory-temp_char);
*memory=1;
printperms(temp_char,length,offset+1,output);
*memory=0;
}
memory++;
}
if(offset+1==length)
{
output[4*offset+3]=0;
printf("%s\n",output);
}
}
int main(int i,char**v)
{
int argument=atoi(v[1]);
char*t=calloc(argument,5),*output=t+argument;
printperms(t,argument,0,output);
free(t);
}
```
[Answer]
# Bash, 744 674 bytes
This is still way too long :). I use a string to represent the row of urinals and a flooding algorithm to find the most distant urinals in each phase of recursion. The ungolfed code is almost self-explanatory. The number of urinals is read from keyboard.
Code (golfed):
```
read l;u=----------;u=-${u::$l}-
s(){ u=${u:0:$1}$2${u:$((1+$1))};}
m(){ local u=$1;a=();while :;do [ 0 -ne `expr index - ${u:1:$l}` ]||break;t=$u;y=$u;for i in `seq $l`;do [ ${y:$i:1} = - ]||{ s $(($i-1)) X;s $(($i+1)) X;};done;done;while :;do k=`expr index $t -`;[ 0 != $k ]||break;t=${t:0:$(($k-1))}X${t:$k};if [ 1 -ne $k ]&&[ $(($l+2)) -ne $k ];then a+=($(($k-1)));fi;done;}
e(){ local u f b v;u=$1;f=$2;if [ 1 -eq $l ];then echo 1;return;fi;if [ 1 = $f ];then for i in `seq $l`;do v=$u;s $i 1;e $u 2;u=$v;done;else m $u;b=(${a[@]});if [ 0 -eq ${#b} ];then echo ${u:1:$l};else for i in ${b[@]};do v=$u;s $i $(($f%10));e $u $(($f+1));u=$v;a=(${b[@]});done;fi;fi;}
e $u 1
```
Use:
```
$ source ./script.sh
input number of urinals from keyboard
```
And ungolfed it goes:
```
read l # read number of urinals
u=----------
u=-${u:0:$l}- #row is two positions longer (it will be helpful when finding the most distant urinals)
# So, for the end, with 6 men, u might look like this:
# -143652-
# subu no fellow_no => set urinal [number] occupied by [fellow_no]
# this is just convenience for resetting a character inside a string
subu(){ u=${u:0:$1}$2${u:$((1+$1))};}
# this will be iterated in longest to find the remotest places:
# -1---3---2- => spreadstep => X1X-X3X-X2X => spreadstep => X1XXX3XXX2X
# see longest() to get more explanation.
spreadstep()
{
y=$u
for i in `seq 1 $l`
do
if [ "${y:$i:1}" != "-" ]
then
subu $(($i-1)) X
subu $(($i+1)) X
fi
done
}
# Find the urinals with the longest distance. It uses spreadstep() - see above.
# -1---3---2- => spreadstep => X1X-X3X-X2X => spreadstep => X1XXX3XXX2X
# ---> last state with free ones was X1X-X3X-X2X ,
# 123456789
# free urinals are no. 3 and no. 7 => save them to arr
longest()
{
local u=$1
arr=()
while true
do
if [ 0 -eq `expr index - ${u:1:$l}` ]
then
break
fi
save=$u
spreadstep
done
while true
do
index=`expr index $save -`
if [ 0 == $index ]
then
break
fi
save=${save:0:$(($index-1))}X${save:$index}
if [ 1 -ne $index ] && [ $(($l+2)) -ne $index ]
then
arr+=($(($index-1)))
fi
done
}
# main function, recursively called
# the first fellow may take any of the urinals.
# the next fellows - only those with the longest distance.
placements_with_start()
{
local u=$1
local fellow=$2
if [ 1 -eq $l ] # special case - there is no 2nd fellow, so below code would work incorrect
then
echo "1"
return
fi
if [ 1 == $fellow ] # may take any of urinals
then
for i in `seq 1 $l`
do
local _u=$u
subu $i 1 # take the urinal
placements_with_start $u 2 # let the 2nd fellow choose :)
u=$_u
done
else
longest $u # find the ones he can take
local _arr=(${arr[@]})
if [ 0 -eq ${#_arr} ]
then
echo ${u:1:$l} # no more free urinals - everyone took one - print the result
else
for i in ${_arr[@]}
do
local _u=$u
subu $i $(($fellow % 10)) # take urinal
placements_with_start $u $(($fellow+1)) # find locations for for next fellow
u=$_u
arr=(${_arr[@]})
done
fi
fi
}
placements_with_start $u 1
```
] |
[Question]
[
## Introduction
After a day of drinking and watching the world cup, you sit down to play friendly game of boggle. Tempers rise as you are accused of wasting everyone's time with nonsense words that aren't even on the board! You may be seeing double, but surely you're thinking straight enough to write a program that will verify that your words are on the board.
## Your Task
Write a program, script, or function that takes a boggle board and a word as input, and returns True if the word is on the board and False if the word isn't.
The input will be in the form of six `\n` delimited lines. The first five lines will comprise the 5x5 boggle board and will each contain five capital letters. The sixth line will contain the word-in-question, also in all capital letters.
Sample input:
```
AJNES
TNFTR
LSAIL
UDNEX
EQGMM
DAFTER
```
The output can be anything that unambiguously signifies True or False in your programming language of choice and adheres to standard conventions of zero, null, and empty signifying False.
Sample output for above input:
```
1
```
## I/O Guidelines
* The input may be read from stdin, and answer output to stdout.
Or
* The input may be a single string argument to a function, and answer be the return value of that function.
## Boggle Rules
* A word is 'on the board' if you can construct the word via a path of consecutive, adjacent, non-repeating tiles on the board.
* A tile is considered adjacent to the eight tiles that surround it (diagonal paths are allowed). Tiles on the edge of the board are adjacent to only five tiles. Tiles in the corner are adjacent to only three.
* Consecutive letters in the word must be adjacent, the `i`th letter in the word must be adjacent to the `i-1`th and `i+1`th.
* A letter may appear in a word more than once, but you cannot use the same square on the boggle board more than once per word.
* The online boggle site [wordsplay.net](http://www.wordsplay.net/) may be useful if you have never played boggle before, but want to get a feel for these rules.
Unlike regular boggle:
* You do NOT have to worry about the word being a valid English word.
* There will be NO `Qu` single tile.
* The word-in-question may be of any length > 0
## Example
On the board of
```
AJNES
TNFTR
LSAIL
UDNEX
EQGMM
```
These words should return True: FATE, DATING, STANDS, LIFTS.
These words should return False: SADDEN, SULTANS, EXIST, SUEDE, QUEST
This is a code-golf challenge, so shortest code wins!
[Answer]
# Javascript (E6) 137 ~~160 175 190~~
Less than 2\*Golfscript. Moral victory ...
```
F=a=>[...a].some((e,p,b)=>(Q=(p,n)=>p>29||b[p]!=b[n]||(b.r|=!b[++n])||(b[p]=b[n+~[1,5,6,7].map(q=>Q(p+q,n)|Q(p-q,n),b[p]=0)]))(p,30)&b.r)
```
**Edit** Golfed code reorganization. Again and again
**Ungolfed** Last version, a bit tricky to follow
```
F = a =>
[...a] // input string to array, 30 chars of board then the target word
.some ( // use some to scan the board, return true when found
(e,p,b)=> // params to callback: element, position, complete array
( // NB array b has no .r property, so use it for return value (it's undefined at start)
Q = (p,n) => // Scan function, p=position in board, n=nth char of target word
p > 29 || // Chaek if going outside the board to the target word
b[p] != b[n] || // if invalid char at current position, return
(b.r |= !b[++n]) || // if at end of target, set r to 1 and return (also increment n )
( // else... (NB next tree lines are coalesced in golfed code)
b[p] = 0, // remove current char (to avoid reusing)
[1,5,6,7].map( q => Q(p+q,n)|Q(p-q,n)), // recursive call for + - 1,5,6,7
b[p] = b[n-1] // put current char into array again
)
)(p,30) & b.r // initial position 0 in target word is 30 in the array
)
```
**Ungolfed** First version , should be clearer
```
F = a => (
b = a.split('\n'),
w = b.pop(),
r = 0,
Q = (p, n) =>
(r |= !w[n]) ||
(
b[p] = 0,
[1,5,6,7,-1,-5,-6,-7].map( q => b[q+=p]==w[n] && Q(q,n+1)),
b[p] = w[n-1]
),
b = [...b+''],
b.map((e, p) => e==w[0] && Q(p,1)),
r
)
```
**Usage**
```
F("AJNES\nTNFTR\nLSAIL\nUDNEX\nEQGMM\nLIFTS\nDAFTER")
```
**Test**
```
['DAFTER', 'STANDS', 'LIFTS', 'FATE', 'DATING' ,
'SADDEN','SULTANS', 'EXIST', 'SUEDE', 'QUEST']
.map(w => [w, F("AJNES\nTNFTR\nLSAIL\nUDNEX\nEQGMM\n" +w)])
```
Output:
```
[["DAFTER", true], ["STANDS", true], ["LIFTS", true], ["FATE", true], ["DATING", true],
["SADDEN", false], ["SULTANS", false], ["EXIST", false], ["SUEDE", false], ["QUEST", false]]
```
[Answer]
### GolfScript, 74 characters
```
:^n%5>)]){{^@==}+29,\,{{+}+1$/}%\;}/{:s$..&=[s{.@-\}*;]1567`{7&.~)}%-!&},,
```
The input must be given on STDIN. Prints the number of valid paths on the board, i.e. `0` for none and a positive number (true) else.
You can test the example [online](http://golfscript.apphb.com/?c=OyJBSk5FUwpUTkZUUgpMU0FJTApVRE5FWApFUUdNTQpEQUZURVIiCgo6Xm4lNT4pXSl7e15APT19KzI5LFwse3srfSsxJC99JVw7fS97OnMkLi4mPVtzey5ALVx9KjtdMTU2N2B7NyYufil9JS0hJn0sLAo%3D&run=true).
*Code with some comments:*
```
:^ # assign the input to variable ^
n% # split at newlines
5> # truncate array such that [WORD] remains
)]) # prepares [[]] and WORD on the stack
# the following loop generates all possible paths (valid and invalid ones)
# by looking up all index combinations which yield the correct word
{ # loop over all characters
{^@==}+29,\, # get all indices of current character in the board
{{+}+1$/}%\; # append any index to all lists in the result set
}/ # end loop
# filter the results list for valid paths
{ # {...}, -> apply filter
:s # save path to variable s
$..&= # check if all numbers in path are unique
[s{.@-\}*;] # calculate differences along the path
1567`{7&.~)}% # generate the array [1 -1 5 -5 6 -6 7 -7] of valid
# differences
-! # check if all differences were valid
& # are both conditions fulfilled?
}, # end of filter block
, # count the number of remaining paths
```
[Answer]
# J - 75 char
Eugh, this one looks nasty. And not even tying with Golfscript! This is a function taking a string as its sole argument. You can use any one-character delimiter as long as it's found at the end of each line, including the last.
```
+/@([:*/"1^:2(2(=*)@-/\>@~.)S:1)@{@(((<@#:i.)5 5)<@#~&,"2{:=/&:>}:)@(<;._2)
```
An explanation follows. Note that the function can be cleaved into 5 distinct top-level parts, each separated by `@`, so we will treat each of those parts separately, from right to left.
* `(<;._2)` - This splits the lines up on the newlines/separator characters. It uses the character at the end of the string as the character on which to split. We put everything into boxes (`<`) because if we don't we get some padding issues when J gives us the result back.
* `(((<@#:i.)5 5)<@#~&,"2{:=/&:>}:)` - For each letter in the word to check, create a list of indices in the Boggle board where one can find that letter.
+ `{:` is the last split piece (the word to check) and `}:` is everything but the last (the Boggle board).
+ `&:>` opens up the boxes we made previously, with the useful byproduct of turning `}:` into a 2D array of characters. `=/` then makes a copy of this Boggle board for each letter in the word, and turns the positions into booleans depending on whether the letter in the board matched that letter in the word.
+ `((<@#:i.)5 5)` is a short way of expressing a 5x5 array of indices. `x#:y` is converts `y` into an array of the base `x` representation. (Well, almost. [The truth](http://www.jsoftware.com/help/dictionary/d402.htm) is more complex, but this works for our purposes.)
+ `<@#~&,"2` - For each letter's resulting boolean matrix, collect all the correspondingly true indices together. `"2` makes everything work on on the right results, `#~&,` does the selecting, and `<@` collects each result into a box to prepare for the next step.
* `{` - This verb, used monadically, is called Catalogue, and it takes a list of boxes as argument. It combines the insides of each box in every possible way. So e.g. a catalogue on some boxes containing the strings "AB" and "abc" would give the results "Aa", "Ab", "Ac", "Ba", "Bb", "Bc".
Running this on our boxed list of lists of indices makes every possible combination of indices. This can be a big set if there the word is long and there are many repeated letters, but also empty if any letter is not on the board. We also note that we reuse tiles in some of these paths: we will account for this later.
* `([:*/"1^:2(2(=*)@-/\>@~.)S:1)` - Here we check each path to see if it's valid.
+ `(...)S:1` applies the `(...)` to each path and collects the results into a flat list. This is crucial because the result of `{` is a multi-dimensional array, and we don't care about the structure of that array, just its contents at each box.
+ `2(=*)@-/\>` gives a 1 if each coordinate of each index is at most one away from the one following it, and 0 otherwise. The `2` and the `/\` are responsible for doing this pairwise.
+ `*/"1^:2` logical-ANDs these all together at the end. The `[:` part is a structural thing in J, don't worry about it.
+ Adding `@~.` to the `>` is actually a clever way to exclude paths with repeated entries. `~.` takes the unique items of a list, so the list is shortened if it self-intersects, and shorter lists get automatically padded with 0s when they're put together, like the way that the results are combined as they come out of `S:`. This is ultimately shorter than explicitly excluding self-intersecting paths.
* `+/` - Finally, we simply add everything together at the end. The result is the number of valid paths that make the word on the board, with 0 meaning no paths, i.e. this word is not on the board. For the cost of one character, we can write `+./` (logical-ORing everything together) instead, which will explicitly give a boolean 1 or 0.
Here are some example runs. You can get the J interpreter at [jsoftware.com](http://www.jsoftware.com/stable.html) or try it online at [tryj.tk](https://googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%2B%2F%40%28%5B%3A%2a%2F%221%5E%3A2%282%28%3D%2a%29%40-%2F%5C%3E%40~.%29S%3A1%29%40%7B%40%28%28%28%3C%40%23%3Ai.%295%205%29%3C%40%23~%26%2C%222%7B%3A%3D%2F%26%3A%3E%7D%3A%29%40%28%3C%3B._2%29%20%20%27AJNES%20TNFTR%20LSAIL%20UDNEX%20EQGMM%20DAFTER%20%27).
```
NB. the 0 : 0 ... ) thing is how you do multiline strings in J
+/@([:*/"1^:2(2(=*)@-/\>@~.)S:1)@{@(((<@#:i.)5 5)<@#~&,"2{:=/&:>}:)@(<;._2) 0 : 0
AJNES
TNFTR
LSAIL
UDNEX
EQGMM
DAFTER
)
1
b =: +/@([:*/"1^:2(2(=*)@-/\>@~.)S:1)@{@(((<@#:i.)5 5)<@#~&,"2{:=/&:>}:)@(<;._2)
b 'AJNES TNFTR LSAIL UDNEX EQGMM FATE ' NB. any separator will do
1
b 'AJNES TNFTR LSAIL UDNEX EQGMM SADDEN ' NB. not on the board
0
b 'AJNES TNFTR LSAIL UDNEX EQGMM SANDS ' NB. self-intersecting path
0
b 'AJNES TNFTR LSAIL UDNEX EQGMM MEND ' NB. multiple paths
2
```
[Answer]
# Python, 207 204 203
```
g=raw_input
r=range
b=''.join(g()for _ in r(5))
w=g()
s=lambda b,w,i:0<=i<25and(not w or(b[i]==w[0])*any(s(b[:i]+'_'+b[i+1:],w[1:],i+j+k*5-6)for j in r(3)for k in r(3)))
print any(s(b,w,i)for i in r(25))
```
Replacing `... (b[i]==w[0])*any ...` with `... b[i]==w[0]and any ...` gives much better performance at the cost of 2 characters.
[Answer]
# Prolog - 315
```
r(L):-get_char(C),(C='\n',!,L=[];r(T),L=[C|T]).
b(0,[]):-!.
b(N,[R|T]):-M is N-1,r(R),b(M,T).
d(-1). d(0). d(1).
d([A,B],[C,D]):-d(X),C is A+X,d(Y),D is B+Y.
f([L|W],B,P,U):-P=[X,Y],nth(Y,B,R),nth(X,R,L),\+member(P,U),(W=[];d(P,Q),f(W,B,Q,[P|U])).
m:-b(5,B),r(W),f(W,B,_,[]),write(t);write(f).
:-initialization(m).
```
I thought Prolog might be a good language for this one, with the built-in backtracking support, but I guess it's more handicapped by needing a variable for almost every computed value.
Tested with GNU Prolog; should be compliant with ISO Prolog.
Ungolfed:
```
get_line(Line) :-
get_char(C),
( C='\n', !, Line=[]
; get_line(Tail), Line=[C|Tail]
).
% The cut prevents recursion to help_get_board(-1, MoreRows)
% (and golfs one character shorter than putting N>0 in the second rule).
help_get_board(0, []) :- !.
help_get_board(N, [Row|Tail]) :-
M is N-1, get_line(Row), help_get_board(M, Tail).
% The golfed version doesn't define an equivalent to get_board/1.
% help_get_board(5,Board) is used directly instead.
get_board(Board) :- help_get_board(5,Board).
small(-1). small(0). small(1).
step([X1,Y1],[X2,Y2]) :-
small(DX), X2 is X1+DX,
small(DY), Y2 is Y1+DY.
% The golfed version doesn't define an equivalent to letter_at/3.
% See find_word/4.
letter_at([X,Y], Letter, Board) :-
nth(Y, Board, Row),
nth(X, Row, Letter).
find_word([Letter|Word], Board, Pos1, Used) :-
% letter_at(Pos1, Letter, Board), % "inlined" to next three lines:
( Pos1 = [X,Y],
nth(Y, Board, Row),
nth(X, Row, Letter) ),
\+member(Pos1, Used),
( Word=[]
;
step(Pos1, Pos2),
find_word(Word, Board, Pos2, [Pos1|Used])
).
main :-
get_board(Board),
get_line(Word),
% Begin at any position. Initially no positions are "Used".
find_word(Word, Board, _, []).
```
] |
[Question]
[
This is the audio version of the [Twitter image encoding challenge](https://stackoverflow.com/questions/891643/twitter-image-encoding-challenge).
Design an audio compression format that can represent **at least one minute of music** in 140 bytes or less of printable UTF-8-encoded text.
Implement it by writing a command-line program that takes the following 3 arguments (after the name of the program itself):
1. The string `encode` or `decode`.
2. The input filename.
3. The output filename.
(If your preferred programming language lacks the ability to use command-line arguments, you may use an alternative approach, but must explain it in your answer.)
The `encode` operation will convert from your chosen audio format to your compressed “tweet” format, and the `decode` operation will convert from your “tweet” format to the original audio format. (Of course, you're expected to implement lossy compression, so the output file need not be identical to the input, just in the same format.)
Include in your answer:
* The source code of your program, in full. (If it's too long for this page, you may host it elsewhere and post a link to it.)
* An explanation of how it works.
* At least one example, with a link to the original audio file(s), the “tweet” text it compresses down to, and the audio file obtained by decoding the tweet. (Answerer is responsible for copyright “fair use” assertions.)
# Rules
* I reserve the right to close any loopholes in the contest rules at any time.
* **[Edited April 24]** For the input of your `encode` function (and output of your `decode` function), you may use any reasonable, common audio format, whether it be:
+ Uncompressed waveform, like WAV.
+ Compressed waveform, like MP3.
+ “Sheet music” style, like MIDI.
* Your compressed “tweet” format must actually encode the sounds in the input file. So, the following types of output do **not** count:
+ A URI or file path giving the location where the actual output is stored.
+ A key to a database table where the actual output is stored as a blob.
+ Anything similar.
* Your program must be designed to compress *generic* music files, so don't do stuff that's too obviously tied to your specific example song. For example, if you're demonstrating “Twinkle, Twinkle, Little Star", your compression routine shouldn't hard-code a specific symbol for the sequence do-do-so-so-la-la-so.
* Your program's output should actually be able to go through Twitter and come out unscathed. I don't have a list of the exact characters that are supported, but try to stick to letters, digits, symbols, and punctuation; and avoid control characters, combining characters, BIDI markers, or other weird stuff like that.
* You may submit more than one entry.
# Judging criteria
This is a popularity contest (i.e., most net upvotes wins), but voters are urged to consider the following:
## Accuracy
* Can you still recognize the song after it's been compressed?
* Does it sound good?
* Can you still recognize which instruments are being played?
* Can you still recognize the lyrics? (This is probably impossible, but it would be impressive if anyone accomplished it.)
## Complexity
The choice of the example song matters here.
* **[Added April 24]** This challenge will be easiest with MIDI or similar formats. However, if you take the extra effort to make it work with waveform-type formats, that deserves extra credit.
* What's the structure? Sure, you can meet the one-minute requirement by simply repeating the same 4 measures an arbitrary number of times. But more complex song structures deserve more points.
* Can the format handle a lot of notes being played at one time?
## The code
* Keep it as short and simple as possible. However, this is not a code golf, so readability matters more than character count.
* Clever, complicated algorithms are OK too, as long as they're justified by improved quality of results.
[Answer]
# Scala
Sure, it'd be easier to encode MIDI files, but who's got a bunch of MIDI files lying around? It's not 1997!
First things first: I've decided to interpret a "Unicode byte" as a "Unicode char" and use CJK characters, because:
* It matches the image challenge
* Twitter is cool with it
* I **really** need those bits
There are a few tricks I use to squeeze every last drop of entropy from the sources:
Firstly, music is made with notes. Moreover, we generally regard the same note in a different octave as the same note (which is why a 12-string guitar sounds right), so we only have 12 possibilities to encode. (when I output B, for example, I actually output a chord, consisting solely of B in all the octaves, a bit like a 12-string guitar).
Next, I remember from high-school music class that most note transitions are small (up or down one note). Jumps are less common. This tells us that there's probably less entropy in the jump sizes than in the notes themselves.
So, our approach is to break our source into a number of blocks - I found 14 blocks per second worked well (side note, I'd always wondered why audio was encoded at 44100 Hz. It turns out that 44100 has lots of factors, so I could have chosen 1, 2, 3, 4, 5, 6, 7, 9, 10, 12, 14, 15, 18, 20, 21, 25, 28 or 30 blocks per second, and it would have divided cleanly). We then FFT these blocks (well, technically not fast, as the library I used isn't fast for non-power-of-2 blocks. And technically I used a [Hartley transform](http://en.wikipedia.org/wiki/Discrete_Hartley_transform), not Fourier).
We then find the note that sounds loudest (I used [A-weighting](http://en.wikipedia.org/wiki/A-weighting), with high and low cut-offs, mostly because it's easiest to implement), and either encode this note, or encode silence (silence detection is based on SNR - low SNR is silence).
We then translate our encoded notes into jumps, and feed them to an adaptive arithmetic coder. The process for translation to text is similar to the image compression question (but involves some abusive use of BigInteger).
So far, so good, but what if the sample has too much entropy? We use a crude psychoacoustic model to remove some. The lowest entropy jump is "no change", so we look at our FFT data to try to find blocks where the listener probably won't notice if we keep playing the previous note, by looking for blocks where the note from the previous block is almost as loud as the loudest note (where "almost" is controlled by the quality parameter).
So, we've got a target of 140 characters. We start by encoding at quality 1.0 (max quality), and see how many characters that is. If it's too many, we drop to 0.95 and repeat, until we get to 140 characters (or we give up after quality 0.05). This makes the encoder an n-pass encoder, for n <= 20 (although it's massively inefficient in other areas too, so m'eh).
The encoder/decoder expects audio in s16be mono format. This can be achieved using avconv as:
```
#decoding ogg to s16be, and keeping only the first 60s
avconv -i input.ogg -ac 1 -ar 44100 -f s16be -t 60s input.raw
#encoding s16be to mp3
avconv -f s16be -ac 1 -ar 44100 -i output.raw output.mp3
```
To run the encoder:
```
sbt "run-main com.stackexchange.codegolf.twelvestring.TwelveString encode input.raw encoded.txt"
sbt "run-main com.stackexchange.codegolf.twelvestring.TwelveString decode encoded.txt output.raw"
```
Full code at <https://github.com/jamespic/twelvestring>.
Pitfall to note: You'll need nayuki's Arithmetic Coding library, which doesn't currently have Maven artifacts available. Instead, you'll need to locally build and install [developster's fork of it](https://github.com/developster/Arithmetic-Coding).
And here are some samples. They sound awful, but just about recognisable:
* Beethoven's 5th: [original](http://commons.wikimedia.org/wiki/File:Ludwig_van_Beethoven_-_Symphonie_5_c-moll_-_1._Allegro_con_brio.ogg), [encoded](https://github.com/jamespic/twelvestring/raw/master/b5-processed.mp3) - 刲檁囉罓佖镱賑皌蝩蔲恁峕逊躹呯兲搆摼蝺筶槛庬一掛獴趤笲銗娵纜喫覤粠僭嫭裵獄鱨蠰儏咍箪浝姑椻趕挍呪白鸞盙宠埘謭擆闯脲誜忘椐笸囃庣稨俖咛脔湙弻籚砌鍖裏橈镙訁鹻塿骱踠筟七趇杅峇敖窈裞瘫峦咰呹櫬茏蛏姆臸胝婁遼憀麁黦掏毈喙眝綄鴀耢椚筤菮蟞斗俼湛营筬禴籙嬧窻丄
* Fur Elise: [original](http://commons.wikimedia.org/wiki/File:FurElise.ogg), [encoded](https://github.com/jamespic/twelvestring/raw/master/furelise-processed.mp3) - 訖忢擫鏝拪纒铇鯪薯鉰孝暱埛痏絘僌莻暆鴈屖鳮絒婘譮蠣託騶腀饚緂柤碠瞢碩脅歙棆敗辦冏鄔酾萖苯劺誺軩忇穤锳婁伉巠桭晘酉筟緵俅怚尵鎽蜓崁飿嘔但鈐謽酝屮呤誥俊覊鶮龔癸埙煂臙牎繬肜摲炚雗頨款驦燈菩凧咁楾媡夥俰欓焵韀冊嗥燠鱧駟髉
* Twinkle Twinkle Little Star: [original](http://en.wikipedia.org/wiki/File:Twinkle_Twinkle_Little_Star_plain.ogg), [encoded](https://github.com/jamespic/twelvestring/raw/master/twinkle-processed.mp3) - 欠悺矜莳錥鷗谴裴皽鳺憝漿箔皇殤鸧蜻猻丱
* A fun chiptune: [original](http://opengameart.org/content/jump-and-run-8-bit), [encoded](https://github.com/jamespic/twelvestring/raw/master/chip-processed.mp3) - 简詐諥尘牿扫鲑龮箫颫齰蠏騁煟靸阒萎囦鮇雝愯訖芉馄鈿鬦嶏觲沠丆贀蛑蛀漥荤侲咔麑桬鲠僵擕灼攲陇亄鹘琾業纟鵼牤棌匩碆踬葫鶙懲欃铳樯柇鋡疡衻澯伅墇搢囻荸香貱夹咽蟽籐屈锂蛉袒貊屨鈦夜镤沄鍡唦魮骬乔蚖醶矕咻喸碋利褼裊匎嶮窢幘六沧鼝瞮坡葍帷锆邵旻符琨鱴郤栱烇仾椃騋荄嘵統篏珆罽
## Update
I tweaked the silence threshold in the code, and re-encoded. The encodings have been updated accordingly. Also, I added another song (technically not open source, but I doubt the original copyright holder will feel their IP is under threat), just for fun:
* Imperial March: [original](http://starwars.wikia.com/wiki/File:Imperial_March.ogg), [encoded](https://github.com/jamespic/twelvestring/raw/master/march-processed.mp3) - 岼讶湠衢嫵焅喋藭霔憣嗗颟橳蕖匵腾嗅鈪芔区顕樭眀冂常僠寝萉乹俚戂闤灈蟑拷邢音褈霈媬盒萳璥唂焰銯艉鶱縩巻痭虊窻熲紆耺哅淙苉嘏庸锺禒旇蘄籷遪刨繱蕖嬯摺祑仰軈牰杊瘷棏郖弘卄浕眮騜阖鏴鶺艂税寛柭菸採偋隆兎豅蚦紛襈洋折踜跅軩树爺奘庄玫亳攩獼匑仡葾昐炡瞱咏斎煟价藭恐鷖璌榍脅樐嬨勀茌愋
## More Updates
I've tweaked the encoder a little, and it's had a surprising impact on quality (I'd forgotten that in DHT, out-of-phase signals are effectively negative, so I was ignoring out-of-phase signals).
An earlier version of the code just took the larger of these out-of-phase signals, but we now take the RMS. Also, I added a fairly conservative window function to the encoder (Tukey, alpha 0.3), to try to combat artifacting.
Everything's updated accordingly.
[Answer]
# Python
I don't do any special mangling with regards to UTF-8, so my submission passes the 140 bytes requirement. I make no claims about the usefulness, accuracy, or efficiency of my solution.
I used a sample rate of 44100 Hz for the input and output. SAMPLES\_PER\_BYTE controls the quality of the conversion. The lower the number, the better quality the sound. The values I used are given in the results section.
## Usage
### Encode
Input file should be a wav. It only encodes the first channel.
```
twusic.py -e [input file] > output.b64
```
### Decode
```
twusic.py -d [input file] > output.raw
```
### Playing the Decoded Music
```
aplay -f U8 --rate=[rate of input file] output.raw
```
## The Code
```
#!/usr/bin/env python
SAMPLES_PER_BYTE = 25450
from math import sin, pi, log
from decimal import Decimal
PI_2 = Decimal(2) * Decimal(pi)
FIXED_NOTE = Decimal('220') # A
A = Decimal('2') ** (Decimal('1') / Decimal('12'))
A_LN = A.ln()
def freq(note):
return FIXED_NOTE * (A ** Decimal(note))
def note(freq):
return (Decimal(freq) / FIXED_NOTE).ln() / A_LN
VOLUME_MAX = Decimal('8')
def volume(level):
return Decimal('127') * (Decimal(level+1).ln() / VOLUME_MAX.ln())
def antivolume(level):
x = Decimal(level) / Decimal('127')
y = VOLUME_MAX ** x
return y - 1
NOTES = [freq(step) for step in xrange(-16, 16)]
VOLUMES = [volume(level) for level in xrange(0, VOLUME_MAX)]
def play(stream, data):
t = 0
for x in data:
x = ord(x)
w = PI_2 * NOTES[(x&0xf8) >> 3] / Decimal(16000)
a = float(VOLUMES[x&0x07])
for _ in xrange(0, SAMPLES_PER_BYTE):
stream.write(chr(int(128+(a*sin(w*t)))))
t += 1
NOTE_MAP = {'A': 0b00000000,
'g': 0b00001000,
'G': 0b00010000,
'f': 0b00011000,
'F': 0b00100000,
'E': 0b00101000,
'd': 0b00110000,
'D': 0b00111000,
'c': 0b01000000,
'C': 0b01001000,
'B': 0b01010000,
'a': 0b01011000}
def convert(notes, volume):
result = []
for n in notes:
if n == ' ':
result += '\00'
else:
result += chr(NOTE_MAP[n] | (volume & 0x07)) * 2
return ''.join(result)
TWINKLE = convert('C C G G A A GG' +
'F F E E D D CC' +
'G G F F E E DD' +
'G G F F E E DD' +
'C C G G A A GG' +
'F F E E D D CC', 0x7)
if __name__ == '__main__':
from base64 import b64encode, b64decode
import numpy as np
from numpy.fft import fft, fftfreq
import wave
import sys
if len(sys.argv) != 3:
print 'must specify -e or -d plus a filename'
sys.exit(1)
if sys.argv[1] == '-e':
w = wave.open(sys.argv[2], 'rb')
try:
output = []
(n_channels, sampwidth, framerate, n_frames, comptype, compname) = w.getparams()
dtype = '<i' + str(sampwidth)
# Find max amplitude
frames = np.abs(np.frombuffer(w.readframes(n_frames), dtype=dtype)[::n_channels])
max_amp = np.percentile(frames, 85)
w.rewind()
read = 0
while read < n_frames:
to_read = min(n_frames-read, SAMPLES_PER_BYTE)
raw_frames = w.readframes(to_read)
read += to_read
frames = np.frombuffer(raw_frames, dtype=dtype)[::n_channels]
absolute = np.abs(frames)
amp = np.mean(absolute)
amp = int(round(antivolume(min((amp / max_amp) * 127, 127))))
result = fft(frames)
freqs = fftfreq(len(frames))
while True:
idx = np.argmax(np.abs(result)**2)
freq = freqs[idx]
hz = abs(freq * framerate)
if hz > 0:
break
result = np.delete(result, idx)
if len(result) <= 0:
hz = 220
amp = 0
break
n = int(round(note(hz)))
n &= 0x1F
n <<= 3
n |= amp & 0x07
output.append(chr(n))
finally:
w.close()
print b64encode(''.join(output)).rstrip('=')
else:
with open(sys.argv[2], 'rb') as f:
data = f.read()
data = data + '=' * (4-len(data)%4)
play(sys.stdout, b64decode(data))
```
## The Inputs
My official submission is [*Impromptu for Pianoforte and Beatbox* by Kevin MacLeod](http://freepd.com/Piano/Impromptu%20for%20Pianoforte%20and%20Beatbox). For this file I used a SAMPLES\_PER\_BYTE of 25450.
I also took the liberty of encoding [Twinkle, Twinkle, Little Star](http://en.wikipedia.org/wiki/File%3aTwinkle_Twinkle_Little_Star_plain.ogg) with a SAMPLES\_PER\_BYTE of 10200. It sounds much better.
## The Output
### Impromptu for Pianoforte and Beatbox
```
aWnxQDg4mWqZWVl6W+LyOThfHOPyQThAe4x5XCqJK1EJ8Rh6jXt5XEMpk1Epe5JqTJJDSisrkkNCSqnSkkJDkiorCZHhCxsq8nlakfEp8vNb8iqLysp6MpJ7s4x7XlxdW4qKMinJKho
```
[Link](https://drive.google.com/file/d/0B-IX3gZIz5ludDZlQ2E1UzF2QkE/edit?usp=sharing)
### Twinkle, Twinkle Little Star
```
HBobGlJSUlJSY2FlYVNRUVFCQkJCQjs5PDksKisqGxoZGVFTUVNRREFDQjs6OjoqKykpKVRRVFJDQkJCOjs6OzksKikpGxobG1JSUlNRZWFlYVNSUVFCQkJDQTw5PDorKisqGhsZGRk
```
[Link](https://drive.google.com/file/d/0B-IX3gZIz5ludlBiNU1pUFlBcEE/edit?usp=sharing)
] |
[Question]
[
**Please note:** By its nature, the spec for this challenge is difficult to understand. It probably requires at least a freshman course in computability theory, or equivalent background reading. In addition, the challenge itself is rather hard. Answering it will require writing an entire interpreter for some subset of your language of choice, and not only that but the interpreter will have to be in the form of a something like a quine. If your answer isn't doing all of this, it is almost certain not to meet the spec.
You don't need to solve the halting problem (even partially) in order to solve this challenge. However, you almost certainly *do* need to write an interpreter (of the language you are using, written in the same language it interprets), though it need not be feature complete. It's this that makes this an interesting challenge.
I promised to award a 500 point bounty to the first answer that meets the spec, and this will be awarded to [Jo King's BF answer](https://codegolf.stackexchange.com/a/152406/21034).
**The challenge**
A rough, simplified version of Alan Turing's proof of the unsolvability of the halting problem goes something like this:
Suppose I've written a program `F` that's meant to solve the halting program. That is, `F` takes the source code of another program as input, and `F(G)` is supposed to return `1` if `G` halts, and `0` otherwise.
But if I give you my program `F` then you can construct another program, `H`, that runs my program with `H` as its input. If `F(H)` returns `0` then `H` returns `0`, but otherwise it deliberately goes into an infinite loop. This leads to a paradox, and we have to conclude that `F` can't solve the halting problem after all.
Your task is to write the program `H`, but with a twist: I'm not going to give you my program. Instead, your program will receive my program's source code as an input. That is:
* **Your program** will receive **my program** as an input, in source code form. (E.g. as a file or as command line input, the details are up to you.)
* **My program** will be written in the same language as your program, and also takes input in the form of a source code string.
* If **my program** returns `0` when given **your program** as input, **your program** should halt (and return `0`) when given **my program** as input. (The exact meaning of "returing `0`" is up to you.)
* if **my program** doesn't halt, or if it returns anything other than `0` when given your program as input, **your program** should keep running indefinitely.
The twist is that, just to make it really quite a lot harder, you have to obey the following rules:
1. You can't use any kind of built-in `exec` or `eval`-type function.
2. You can't use any "cheating" methods to get at your own program's source code. (E.g. you can't say "save this in a file called 'program'" and then have `open(program)` in your program.)
This means that your program has to be some kind of crazy super-quine that can not only reproduce its own source code in the form of a string, but is also capable of correctly parsing and interpreting the language it's written in.
To make it slightly less insanely hard, you're allowed to use just a (Turing-complete) subset of your chosen language. So if your program is written in Python and will only work if my program only contains `if`s and `while` loops and basic string operations, then that's OK as long as your program only uses those things too. (This means that you don't have to worry about implementing your chosen language's entire standard library!) However, your program does have to actually run - you can't just make up your own language.
This is [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so the answer with the most votes wins. However, as mentioned above, it's a serious challenge just to meet the spec at all, so I will award a 500 point bounty to the first answer that does so according to my judgement.
**please note:** no doubt there are many ways you can "cheat" at this challenge, given the exact wording I've used. However, I'm really hoping for answers that enter into the spirit of the question. The challenge as intended is very difficult but possible, and I'm really hoping to see genuine solutions to it. I won't award the bounty to an answer that feels cheaty in my judgement.
---
Note: this challenge was originally posted as [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), but it was closed in 2016 due to not having an "objective winning criterion", and I changed it to [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") in order to get it reopened. However, I've found that, as of January 2018, [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'")s are not in fact banned on PPCG (with [this](https://codegolf.meta.stackexchange.com/questions/13461/should-we-blacklist-popularity-contests) being the most recent meta discussion) so closing it in the first place was against site policy. I understand that popcons are not popular these days, but this is an old challenge, and its nature makes it really unsuitable for the [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") scoring system. If anyone still feels strongly that it shouldn't be allowed then let's have a meta discussion before close votes start getting thrown around. Finally, on the off-chance that someone's spent the last year attempting to golf their solution, rest assured that it will be just as competitive in this challenge, and just as worthy of the bounty, as it would have been in the [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") version.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~6013~~ ~~4877~~ 4376 bytes
Edit: -1136 bytes. Switched to a better way of generating the data for the quine
Edit2: -501 bytes. Revisited my self-interpreter and cut it down a couple of hundred bytes
```
->++>++++>+>++>+++>>++++>>++++>>+++>>++++>>+++>>++>++>++>++>++>++>++>++>++>++>++++>+++++>+>++>++>++>++>++>++>>+++>+>++>++>++++>+>+++>+>++++>+>+++>+>++>>>+++++>++++>++++>>+++>>++++>>+++>>++>++>++>++>++>++>++>++++>+++++>+>++>++>++>++>++>++>>+++>+>++>++++>+>+++>+>++++>+>+++>+>++>>>+++++>+++>>+++>+>+++++>+++++>++++>>++>+>++>++>++>++>++>++>+++>>++>++>>++++>>+++>++>++>++>++>++>++++>+++++>>++>++>++>+>+++>>++++>>++>++>++>>++>++>++>>++>++>++>>++>++>++>++>++>++>>++>++>++>++>++>++>>++>++>++>>++>++>++>++>>++>++>++>++>++++>+>+++>>+++++>+++>>++>>+++++>>>++>>++>++>++>>+++++>+++++>>>++>++>++++>+>+++>+>+>++++>+>+++>+>+>++++>+>+++>>++++>++++>++++>>+++>>>++++>>+++>>>++++>>+++>+>++++>+++++>>>++>+>+>+++>+>++++>+>+++>+>+>++++>+>+++>+>+>++++>+>+++>>+++++>+++>>++++>>+++>>>++++>>+++>>>++++>>+++>>>++++>+++++>+>+>++>++++>+>+++>+>++>>>++++>>+++>>+++>+>+>++++>++++>+++++>>++>+>+++>+>+++>>>++++>>+++>>++++>++++>+++++>+>++>>+++>>+++>+>+>++++>+>+++>+>+>++++>+>+++>+>+>++++>+>+++>>+++>>>>++++>>+++>>>++++>>+++>+>++++>++++>+++++>+++>+>+++>>>>++++++>++++>>++>++>++>++>++>++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>>+++++>+++>++>+>+++++>++++>>+++>>++++>+>++>+>++>>>>>+++>+>+>+>+++++>++++>>+++>>++++>+>++>+>++>>>>>+++>+>+>+>+++++>++++>>+++>>++++>+>++>+>++>>>>>+++>+>+>+>+++++>++++>>+++>>++++>+>+++++>+>++>++>++>>>>>+++>+>+>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++>>+++>>++++>+>++>++>+>++>>>>>+++>+>+>+>+++++>+++++>++++>>+++>>++++>+>+++++>+>++>++>++>++>++>++>++>>>>>+++>+>+>++>++>++>++>++++>+++++>+>+++++>+++++>+++++>+++++>+++++>+++++>>+++>++>+>++>++++>>+++>>++++>+>++>++>+>++>>>>>+++>+>+>+>+++++>+++++>++++>>+++>>++++>+>+++++>+>++>>>>>+++>+>+>+++++>+>++++>++>+++>+>++++>>+++>>++++++>+++>>>>++>+>+>+>+>+++++>++++>+>+++>>++++>+++++>++++>+>+>+++>>++++>+>++>++++>>+++>>>++++>+>+++>+>+>++++>>>++>++++>+>+>++++>+>+++>+>+>+++++>++++>>>+++>+>++++>>>>>++++>>+++>>++>+>+>++++>+>+++>+>+++>+>+++++>++++>>>+++>+>++++>>>>>++++>>+++>>+++++>+>+>++++>+>+++>+>+++>+>++>++>++++>+++++>>>++>+>+>+++>>>++++>>+++>>+++>+>+++>+>++++>+>+++>>+++++>+>+++>>+++++>++++>+>+>+++>>++++>+>++>++>++++>>+++>>>++++>+>+>+++>>++++>+>+>++>++++>+>+>++++>+>+++>>++++>+++++>+>+>++>>>+++>>+++++>+++++>++++>+>+>+++>>++++>++++>>+++>>++>+>+>++++>+>+++>+>+++>>++>++++>+>+>+++>>++++>++++>>+++>>+++++>+>+>++++>+>+++>+>+++>>++>++++>>+++>>+++>+++>+>+>++++>+>+++>>+++++>+++++>+>+++>>+++++>++++>+>+>+++>>++++>++++>>+++>>>+++++++>+>+>+>++++>+>+++>+>+++>>+++++>++++>+>+>+++>>++++>++++>>+++>>>+++++>+>+>+>++++>+>+++>+>+++>>+++++>++++>+>+>+++>>++++>++++>>+++>>>++++++>+>+>+>++++>+>+++>+>+>+>++++>+>+++>+>++++>+>+++>>++++>++++>>+++>>++++>>+++>>>>++++>>+++>>>++>+>+>+>++++>+>+++>+>+>+>++++>+>+++>+>++++>+>+++>>+++++>+++>>++++>>+++>>++++>>+++>>>++++>+>+++>+>+++>>+++++>++++>+>+>+++>>++++>++++>>+++>>>++>+>+>+>++++>+>+++>+>+++>>+++++>++++>+>+>+++>>++++>++++>>+++>>>>++++>>>+++>>++++>+>+>+>++++>+>+>+++>+>++>>>>++++>>>+++>>+++++>+++>>++++>+++++>+++>+>+>++>++++>+>++++>+++++>>>++>+>+>+++>+>+++>+>++++>+++++>>>++>+>+>+++>+>++++>+>+++>+>+++>>+++++>++++>+>+>+++>>++++>++++>>+++>>++>++>++++>+++++>+++++>>++++>+++++>+>+>++>>>+++>>+++>++>+>+>+++++>++++>++>++>+>+>+++>+>++++>+++++>>>>++++>>>+++>>++>+>+>+>++++>+>+>+++>+>+++>+>++++>+>+++>+>+++>+>++>++>++>++>++>++>++>++>>>++++>++>+>+>+++++>>>+++>>+++>>>++++>++++[<+]>[>[>]>[>]>++++++++++[-<++++++>]<++[<]<[<]<+>>-[[>]>[>]>+++++++[-<++++++>]<+[<]<[<]<+>>-]>]<--[>+<++++++]>++>[>]+++++[->+++<]>[>+++>+++>+++>++++++>++++++>+++>++++>++++[<]>-]>+>->>+>+++>-->>++[<]<<[<]<<[<]>[[[>]>>[>]>>[>]<[->>+<<]<[<]<<[<]<<[<]>-]>[>]>>[>]>>[>]>>[-<<+[<]<+>>[>]>]<<[[->+<]<]>>[>]>[[-<+>]>]<<[<]<<[<]<<[<]>]>>>[>]>>[>]<[[-]<]>>>,[>+++++++[<------>-]+<-[>]>[<+<+>>>>]<<<-[>]>[<+<+>>>>]<<<-[>]>[<+<+>>>>]<<<-[>]>[<-<+++>>>>]<<<--------------[>]>[<++<+>>>>]<<<--[>]>[<-<+++++++>>>>]<<++++[-<------>]+<+[>]>[<++<+>>>>]<<<--[>]>[<-<+>>>>]<<-<[+]<[>]>,]>>>+<<<<-[<]>[-[<<]>[<+[>]>>[<]<<[>>+[<<[<]<<-[>>]<[>>>>[>]>+<<[<]<]<-[>>]<[>>>>[>]>-<<[<]<]<++[->>+<<]>>[>]>]<]<[<]>-<]>-[<<]>[<++[>]>>[<<]>[<<+[<<[<]>[-<<+>>]>--[<<]>[[>]>+<<[<]<]>+[<<]>[[>]>-<<[<]<]>+[>]>]]<<[<]>--<]>-[<<]>[[>]>>.<<<[<]<]>-[<<]>[[>]>>-<<<[<]<]>-[<<]>[[>]>>,<<<[<]<<<[<]<[<]>[[>]>[>]>>>[>]>>+<<<[<]<<<[<]<[<]>-]>[>]>[>]>>[<]<]>-[<<]>[[>]>>+<<<[<]<]>-[<<]>[[>]>>>[>>]>[<<<[<<]<+>>>[>>]>-]>[-]<<+[<[->>+<<]<]<[->>+<<]<[<]<]>-[<<]>[[>]>++[-->[-<<+>>]>]+<<-[++<<]<[->>>[>>]>+<<<[<<]<]<[<]<]<++++++++>>[+<<->>]>]>>[]
```
**[Try it online!](https://tio.run/##rVdbbuQgEDwQQ06A6iKIj@xKkaJI@Yi055/QPLuhwczOOB5iQ1NUP8F/ft4/vz/@/f263y1MvBD/6DbIr70dHvd3aRqcuCEHyktp@QtQUVpzyuSYwNnqYCK8zevrDMBWW7JtaKxT6thRNk9nXTtJqbrRDFBfMaEyNVTA2W5siHdAdffiWdoPfSmo6@uvg48vlsQQWprtxpyBYMrdDUZjCu8xhjW8Q/1wYkJmCE5JBPoi0Sb3ai3Hn6YJxVn0AUOcrMXHqH9g9nMr7QFe2y7oXK6/VkNO3ZXRMy9jzIydAZ/grQMocdzKseEBuHZlThd0SqsK1bvHrK05x22npKmsnRdAL0BhDsKYmCPVAUpOxrRbXFfjFzCfS68siiyAsMScVVkqzQJvItbD6EB1vkuudr5H48HskKButGPq4LToLJk85ValukgNhrwGLk96rBosNkteSmCk6Ia1DJ0LL0jHK7dSqy7rPi9oAE68wGrwdrbIjMHeunvBi8X6SDtaWS8Ey5Kv@O6/0oTvB4t0WX4I7D49cF6kr1Yw2H5sPabxU3uOwf6oww/BbMvGfNikxjsT4ONfSD/TLm9dYRociQVHvzjZ@kFYSHLBEDus9TBlnGb0iT59zzqCYsdOfqRlPYUrUcnIBhbFNJae0iCtRv@IAXziido4T2Ku0GsNYQm52FiX9TC5gwSJbOwpIp5ULiMCLI6zBb1NM26@WSoSpCsuap1NSC45BQTVe2qyy@6FHOsXVxNi431i6awOrMRIzjB4dW7vJg29CbfQwgY5vJyrXogeSc5ItoGtA2R5MWJWIx60sE1uIQFHzk@dkUGKuObZsABIHkVymHG2gBBkQjENlxTM8xAELoWbq5E1UW8xR4FCbc04nx3RZI0y39syNYdTqxCVc40ysn0UIpJltrOQBEiquIFeaxhQKKIEZmVATub9UdWyeigUyRQ1PLIZqn1zKBRWZraGDc2VufVN154g3OFdqiRjwh9g3@b4sMH1uIOPgDY5mdYI9/vNv93CLw "brainfuck – Try It Online")** The input here is a simple cat program (`,[.,]`) which will print the program itself.
"Return 0" is defined by ending the program on a cell with value 0.
A unholy combination of two programs I've written in the past, a quine and a self-interpreter. First section is the quine part, which takes the data and populates the tape with the the data generation followed by the source code. Next is the self-interpreter, which takes **your program** and runs it. This is pretty much a unchanged copy of a normal self interpreter, except that instead of taking input directly, it gets input from the beginning of the data section, setting the cell to 0 if there is no more input. Finally, end on the current cell of **your program** and run `[]`. If the returned value was 0, **my program** will end on zero. If it is anything else, it will run an infinite loop. If **your program** runs forever, **my program** will run forever.
## How It Works:
### Part 1: Data Generation
```
->++>++++> ....... >+++++>>>+++>>+++>>>++++>+++
```
This part makes up the data section of the quine, and is by far the majority of the code at 3270 bytes. The beginning `-` is a marker for the beginning of the data. Each `>+++` represents a character of the code after this section.
```
Number of Pluses
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
> | < | + | ] | [ | - | , | . |
```
### Part 2: Generate the data section using the data
```
+[<+]>
[
Add a right arrow
>[>]>[>]>(10++++++++++)[-<(6++++++)>]<++[<]<[<]
<+>>-
Add the right amount of pluses
[
[>]>[>]>(7+++++++)[-<(6++++++)>]<+[<]<[<]<+>>-
]
>
]
Add the beginning minus
<--[>+<++++++]>++
```
This uses the data from part one to add the characters that are used to generate the data to the code section. It adds a `>` to the end of the code section and that cell's value many pluses.
### Part 3: Generate the rest of the code using the data
```
Initialises the 8 characters of brainfuck
>[>]+++++[->+++<]>[>+++>+++>+++>++++++>++++++>+++>++++>++++[<]>-]
>+>->>+>+++>-->>++[<]<<[<]<<[<]>
Tape looks like:
data 0 0 code 0 0 characters
Runs through the data destructively and adds the represented symbol to the code section
[
[
For each plus in this cell
Shift the gap in the characters over one
[>]>>[>]>>[>]<[->>+<<]
<[<]<<[<]<<[<]>-
]
Navigate to character
>[>]>>[>]>>[>]>>
Copy the character to the end of the code section
[-<<+[<]<+>>[>]>]
Shift the symbol section over one
<<[[->+<]<]
>>[>]>[[-<+>]>]
Navigate to next byte of data
<<[<]<<[<]<<[<]>
]
Remove characters
>>[>]>>[>]<[[-]<]
```
Destroys the data section and adds the rest of the source code to the code section
### Part 4: Get inputted program
```
>>>,
[
>(7+++++++)[<(6------)>-]+<-
[>]>
[plus <+<+>>>>]<<<
-[>]>
[comma <+<+>>>>]<<<
-[>]>
[minus <+<+>>>>]<<<
-[>]>
[dot <-<+++>>>>]<<<
(14--------------)[>]>
[left <++<+>>>>]<<<
--[>]>
[right <-<+++++++>>>>]<<
(29++++[-<------>]+<+)
[>]>
[start loop <++<+>>>>]<<<
--[>]>
[end loop <-<+>>>>]<<
-<[+]<[>]>,
]
```
Gets the inputted program. Removes non-brainfuck characters and represents each character with a number:
```
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
] | [ | . | - | , | + | > | < |
```
Represents the end of the program with `255`.
### Part 5: Interpreting the input
```
Initialise simulated tape
>>>+<<<<-
[<]>
[
-[<<]>
[end loop
co 0 0 0 e: _1 0 0 0 1 ?
Check if current cell is one
<+[>]>>[<]<<
co 0 0 1 e _1: 0 0 !0 1
or
co 0 0 1 e _1 0: 0 0 1
[ If current cell is one navigate to corresponding start loop
Create counter
>>+
[
co 0 0 de _1 0 c: !0 1
checks if next instruction is an end loop
<<[<]<<-
[>>]<
c !0 0: 0 de _1 0 c !0 1
or
c: 0 0 0 de _1 0 c !0 1
[>>>>[>]>+<<[<]<] Add one to counter if it is
checks if start loop
<-[>>]<
c !0 0: 0 de _1 0 c !0 1
or
c: 0 0 0 de _1 0 c !0 1
[>>>>[>]>-<<[<]<] Subtract one from counter if it is
c ? 0: 0 de _1 0 c !0 1
Adds two to counteract checks and move to the next instruction
<++[->>+<<]
>>[>]>
c 0 0 ode _1 0 c: !0 1
End on the counter
If the counter is 0 then we have reached the corresponding bracket
]
c 0 0 2 de _1 0 0: !0 1 0
<
]
c 0 0 1?2 de _1 0: 0 0 1 0
Subtract one from current instruction
This executes the start loop code next but that does nothing
<[<]>-<
]
>-[<<]>
[start loop
c 0 0 0 de: _1 0 0 ? 1
<++[>]>>[<<]>
c 0 0 2 de _1 0 0 0 1:
or
c 0 0 2 de _1 0 0: !0 1
[ If current cell is 0 navigate to corresponding end loop
Initialise counter
<<+
c 0 0 ode _1 0 c: 0 1
[ While counter is not 0
Transfer current instruction over (first instruction is guaranteed to be start loop)
<<[<]>[-<<+>>]>
co 0 0 de _1 0 c: 0 1
Check if start loop
--[<<]>
co 0 0: !0 e _1 0 c 0 1
or
co 0 0 0 e _1 0 c 0 1
[[>]>+<<[<]<] Add one to counter if so
checks if end loop
>+[<<]>
co 0 0: !0 e _1 0 c 0 1
or
co 0 0 0 e: _1 0 c 0 1
[[>]>-<<[<]<] Subtract one from counter if so
Add one to counteract checks and navigate to counter
>+[>]>
co 0 0 de _1 0 c: 0 1
End on counter
If counter is 0 then we have reached the corresponding end loop
]
co 0 1 e _1 0 0: 0 1
]
co 0 0 2?1 e _1 0 0: ? 1
Subtract two from the current instruction to bring it back up to the right value
<<[<]>--<
]
3 of these are pretty self explanatory
Navigate to the current cell and execute the instruction on it
>-[<<]>
[output
[>]>>.<<<[<]<
]
>-[<<]>
[minus
[>]>>-<<<[<]<
]
>-[<<]>
[input
Reset current cell
[>]>>, (no more input so this is set to 0)
co 0 0 0 e: _1 0 0 0: 1 b 1 a 0 d 1 e 1 f
Navigate to start of code section
<<<[<]<<<[<]<[<]>
d: ata 0 co 0 0 0 e _1 0 0 0 1 b
or
0: co 0 0 0 e _1
Transfer next instruction to current cell
[[>]>[>]>>>[>]>>+<<<[<]<<<[<]<[<]>-]
0: ata 0 co 0 0 0 e _1 0 0 d 1 b
or
0: co 0 0 0 e _1
Navigate back to the normal spot
>[>]>[>]>>[<]<
]
>-[<<]>
[plus
[>]>>+<<<[<]<
]
>-[<<]>
[right
Simulated tape looks like:
a b c: d e f
co 0 0 0 e: _1 0 0 c 1 b 1 a 0 d 1 e 1 f
Navigate to value of cell to the right
[>]>>>[>>]>
co 0 0 0 e _1 0 0 c 1 b 1 a 0 d: 1 e 1 f
Transfer it to temporary cell
[<<<[<<]<+>>>[>>]>-]
co 0 0 0 e _1 d 0 c 1 b 1 a 0 0: 1 e 1 f
Pop extra marker if it exists from the right cells and add one to the left
>[-]<<+
co 0 0 0 e _1 d 0 c 1 b 1 a 1: 0 0 e 1 f
Transfer all left cells over 2 cells
[<[->>+<<]<]<[->>+<<]
co 0 0 0 e _1 0: 0 d 1 c 1 b 1: a 0 e 1 f
Navigate back to normal spot
<[<]<
]
>-[<<]>
[left
Simulated tape looks like:
a b c: d e f
co 0 0 0: e _1 0 0 c 1 b 1 a 0 d 1 e 1 f
Add temporary marker
[>]>++
co 0 0 0 e _1 0 2: c 1 b 1 a 0 d 1 e 1 f
Remove temporary marker and transfer all left cells over two
[-->[-<<+>>]>]
co 0 0 0 e _1 c 0 b _1 a _1 0 0: d 1 e 1 f
Add marker to right cells remove marker from left cells and reset left cell's markers
+<<-[++<<]<
co 0 0 0 e _1 c: 0 b 1 a 0 0 1 d 1 e 1 f
Transfer current cell to to right cells
[->>>[>>]>+<<<[<<]<]
co 0 0 0 e _1 0: 0 b 1 a 0 c 1 d 1 e 1 f
Navigate back to normal spot
<[<]<
]
Add 8 to reverse checks
<(8++++++++)>>
Execute next instruction
[+<<->>]>
]
```
Interprets the program. The only difference from a normal one is that the input is taken from the beginning of the code section instead of the input.
### Part 6: Halt if return is not 0
```
>>[]
```
Navigate to the ending cell of **your program** and run an infinite loop if the return is not 0. If it is 0, exit the loop and end on that same 0.
## Test Inputs:
[Always returns 0 (halts and returns 0)](https://tio.run/##xVZbrtwgDF2Qh64AeSOIj7ZSpapSP67U9U9tMME2jzC3IzUzsYjjx@HYEL59fP35@8ef77@ez4AA9GchI6yPXbrh/i/iCmf@aF/Ig0j9gNiiXOIUyTGAs@yoTLSs@ecIUGVrAZYwldJOsQfZjM5UO0ubuONv8IZICvq0kptHnNZ0MbYsYY@Gr2aEoXf246t/Jo2CfmGgQaqLigrG0MO@UWfxDueHJxQqIkA7mXZe9OnQ/DOpE1gfM23sPKrp/idrt02s3N4rR8g3qI@ww2oe683xrKZodsw3Y7dITcvqBlZLWTUvTgrs95muHpH7VW/XF6Jz9hbKTjkNn6jx8/JSANjF8J8SvUnO9ilY7I5uq1zwNaXMmq04m@yr6JPOU9@TiQeecOuseNp9RU7YcizZZeGznwZ5Q4h5DFyfhXanL//J@VRswM1J8/Nz/Teu9KrECW36KDDYTvef8SixPta8cOw5ndG4@cPtmsRxozNKD9MRsaLsZicbP2QwYEGcHddShIyJfrnccF0pRGn@HNksR77JNyRnbCy1YSZFCAlB3rMHO4oX@0eO1I8/oI9WSiNQM8cEDCgEBB6VlLEJTAUeNhET20RB1c1CRmNHIsQKH6qCDRkkacQk8UzljQlG71XCFIoHPtLFENHAF2WFGEqoCLGUnyK8oilUXzpziYv20U7QHaVogokgwdZXVCEmoNmR9sGzI04ZFTNOMhb/ykFhhQySMESRmBYUkqCqs9eHpi@9UWrWCpFryfhuqVqu8hQlV60hcjAx1AkLItGFruMMrSlUihL/S2x2Whum2odoq0xNn3p3wGAhXXjxZiPCNA8ybTzpyMpSnqLhWCEXLq6ed@1vAjHNoTNGbUAVgWobWlBoafJVnNZKiR2KJ43z8/kX)
```
(empty program)
```
[Always returns 1 (runs forever)](https://tio.run/##xVZbrtwgDF2Qh64AeSOIj7ZSpapSP67U9U9tMME2jzC3IzUzsYjjx@HYEL59fP35@8ef77@ez4AA9GchI6yPXbrh/i/iCmf@aF/Ig0j9gNiiXOIUyTGAs@yoTLSs@ecIUGVrAZYwldJOsQfZjM5UO0ubuONv8IZICvq0kptHnNZ0MbYsYY@Gr2aEoXf246t/Jo2CfmGgQaqLigrG0MO@UWfxDueHJxQqIkA7mXZe9OnQ/DOpE1gfM23sPKrp/idrt02s3N4rR8g3qI@ww2oe683xrKZodsw3Y7dITcvqBlZLWTUvTgrs95muHpH7VW/XF6Jz9hbKTjkNn6jx8/JSANjF8J8SvUnO9ilY7I5uq1zwNaXMmq04m@yr6JPOU9@TiQeecOuseNp9RU7YcizZZeGznwZ5Q4h5DFyfhXanL//J@VRswM1J8/Nz/Teu9KrECW36KDDYTvef8SixPta8cOw5ndG4@cPtmsRxozNKD9MRsaLsZicbP2QwYEGcHddShIyJfrnccF0pRGn@HNksR77JNyRnbCy1YSZFCAlB3rMHO4oX@0eO1I8/oI9WSiNQM8cEDCgEBB6VlLEJTAUeNhET20RB1c1CRmNHIsQKH6qCDRkkacQk8UzljQlG71XCFIoHPtLFENHAF2WFGEqoCLGUnyK8oilUXzpziYv20U7QHaVogokgwdZXVCEmoNmR9sGzI04ZFTNOMhb/ykFhhQySMESRmBYUkqCqs9eHpi@9UWrWCpFryfhuqVqu8hQlV60hcjAx1AkLItGFruMMrSlUihL/S2x2Whum2odoq0xNn3p3wGAhXXjxZiPCNA8ybTzpyMpSnqLhWCEXLq6ed@1vAjHNoTNGbUAVgWobWlBoafJVnNZKiR2KJ43z8wl/AQ)
```
+
```
[Returns all input added together, mod 256 (returns 211, so it runs forever)](https://tio.run/##xVZbrtwgDF2Qh64AeSOIj7ZSpapSP67U9U9tMME2jzC3IzUzsYjjx@HYEL59fP35@8ef77@ez4AA9GchI6yPXbrh/i/iCmf@aF/Ig0j9gNiiXOIUyTGAs@yoTLSs@ecIUGVrAZYwldJOsQfZjM5UO0ubuONv8IZICvq0kptHnNZ0MbYsYY@Gr2aEoXf246t/Jo2CfmGgQaqLigrG0MO@UWfxDueHJxQqIkA7mXZe9OnQ/DOpE1gfM23sPKrp/idrt02s3N4rR8g3qI@ww2oe683xrKZodsw3Y7dITcvqBlZLWTUvTgrs95muHpH7VW/XF6Jz9hbKTjkNn6jx8/JSANjF8J8SvUnO9ilY7I5uq1zwNaXMmq04m@yr6JPOU9@TiQeecOuseNp9RU7YcizZZeGznwZ5Q4h5DFyfhXanL//J@VRswM1J8/Nz/Teu9KrECW36KDDYTvef8SixPta8cOw5ndG4@cPtmsRxozNKD9MRsaLsZicbP2QwYEGcHddShIyJfrnccF0pRGn@HNksR77JNyRnbCy1YSZFCAlB3rMHO4oX@0eO1I8/oI9WSiNQM8cEDCgEBB6VlLEJTAUeNhET20RB1c1CRmNHIsQKH6qCDRkkacQk8UzljQlG71XCFIoHPtLFENHAF2WFGEqoCLGUnyK8oilUXzpziYv20U7QHaVogokgwdZXVCEmoNmR9sGzI04ZFTNOMhb/ykFhhQySMESRmBYUkqCqs9eHpi@9UWrWCpFryfhuqVqu8hQlV60hcjAx1AkLItGFruMMrSlUihL/S2x2Whum2odoq0xNn3p3wGAhXXjxZiPCNA8ybTzpyMpSnqLhWCEXLq6ed@1vAjHNoTNGbUAVgWobWlBoafJVnNZKiR2KJ43z8/mQ1ULd8Rc)
```
,[[->+<],]>
```
[Returns 0 if the last two characters of a code are an infinite loop (`[]`) (**your program** returns 0 when given **my program**, therefore **my program** halts)](https://tio.run/##xVbdqhwhDH6Vc3kOWUt7WZC8iHjRFgql0ItCn3@baNTEv3FPFzq7I04mP59fYsavv7/8@PX9z7ef97tDAPrzIDPMj23spvu/DNWd@aN9IQ8y6gfE4qUOp0iOAZxFR6Wixxx/jgBVtOJgCVMJ7RKbk83sTLTTtIEb/gJv8KSgTzO5ecRpThdzyxI2b/hoRBhqZz@v9TMpFOw3BhqkOqmoYAw13BfqzN/h@vCEQkUEaCNTzos6HYp/NuoA1sYsGxuParn/SbtrEyuz544j5AvUR9hhtY51czzLKZqO@WTsFqkpWV3Aaiur4sVJgvs@08Qj8n7X2/2F2Bn3GkpPGQ2fqPHz8pAD2PnoPyW6Sc76FCy6Y9cqF3xNKbNqK84mfRX7oPPQ12TigSVcGiuedl@RE7Y6luy26KOfOnmCi7kPXJ@Fdqev/pPzLt@Am5Pm@9f6b1zpXYkT2vRRYNCd9p/xKLE@1jxw7Dld0dj84XJP4tjojLCH2RGxouyik40fMhiwIM6Oa8FDxEC/mG6oV3Beij96Voueb7J1oVM2mloxksC5gCDv2YINxYrtPXtqxx/QRyslEaiRfQI6FAIcz1JIXwYMCR6WwQfW8YKqqbmIRo8G5zN8yAJWZJAkEZXAK5U3xhm9VwGDSxZ4C5UhooEvigreJVcefEo/eXhEkqiuMnOJibbRRtAMJWmCiSDB1lZEzgeg1ZH0xqsjThkVM06jT/aZg8QKKQRhiDwxLSgkQRbHXu6KPNVGyllJRMwp47uEKrHSk5dYOYfIzkRRB0yIROaajCOUolAhkv8PvuhpqZtKbyLNYyjy0KoDBg2pwsqb9QjTOMi08aI9C1N6koR9uZi4qDXflb9xxDS7xhiVAWUEsq4rTqGEiTU5pZQCGyRLmsf7ncqdCuP1c@0gb@T79dPH1lLe0nakQmIz4PrjvZJQczXwPC@BNzkrkv7Ly18)
```
,[>,]>(9+++++++++)[-<(10++++++++++)>]<[-<-<->>]+<---[[-]>[-]<]<-[[-]>>[-]<<]>+>[-<->]<
```
### Fun Fact for those who are still reading
If the input for this program is the source code of this program, then it will start recursing, repeatedly creating self-interpreters that run this program and then give it the same program again. This gives me some interesting ideas on creating actual recursive programs in brainfuck. Instead of checking the return value and starting an infinite loop as in this question, the return value can be saved and acted upon. A simple example would be a factorial program that goes
```
If cell1 == 0:
Get input into cell1
If cell1 == 1 or cell1 == 0:
Return 1
Else:
Initialise self-interpreter-quine function
Pass cell1-1 into cell1 of the function
Run function
Multiply cell1 by the return value
Return cell1
```
Of course, this is a completely insane way of coding brainfuck, given that running recursing self-interpreters will increase the runtime exponentially.
[Answer]
# Lazy K, 5891 bytes
```
````ssk``s``si``s``si`ks``s``si`kk``s``si``s``si`ks``s``si``s``si`ks``s``si`kk`k
s``s``si``s``si`ks``s``si``s``si`ks``s``si`kk`ks``s``si``s``si`ks``s``si`kk``s``
si`ks``s``si``s``si`ks``s``si``s``si`ks`ki``s``si`kk``s``si``s``si``s``si`ks`ki`
`s``si`ks``s``si`kk``s``si``s``si`ks``s``si``s``si`ks``s``si`kk`ks``s``si``s``si
`ks``s``si`kk``s``si`ks``s``si``s``si`ks``s``si``s``si`ks`ki``s``si`kk``s``si``s
``si`ks`ki`kk``s``si`kk`ki``s``si``s``si`ks``s``si`kk`kk``s``si``s``si`ks``s``si
`kk`kk``s``si``s``si`ks``s``si``s``si`ks``s``si`kk`ks``s``si``s``si`ks``s``si`kk
``s``si`ks`ki`kk``s``si``s``si`ks``s``si`kk`kk``s``si``s``si`ks``s``si``s``si`ks
``s``si`kk`ks``s``si``s``si`ks``s``si`kk`kk``s``si``s``si`ks``s``si`kk`ks``s``si
``s``si`ks``s``si`kk``s``si`ks`ki`kk``s``si`kk``s``si``s``si`ks``s``si`kk`kk``s`
`si`ks``s``si`kk``s``si``s``si`ks``s``si``s``si`ks``s``si`kk`ks``s``si``s``si`ks
``s``si`kk`kk``s``si``s``si`ks``s``si`kk`ks``s``si``s``si`ks``s``si`kk``s``si`ks
`ki`kk``s``si`kk`kk``s``si`kk``s``si``s``si`ks``s``si``s``si`ks``s``si`kk`ks``s`
`si``s``si`ks``s``si`kk`kk``s``si``s``si`ks``s``si`kk`ks``s``si``s``si`ks``s``si
`kk``s``si`ks`ki``s``si``s``si``s``si`ks`ks``s``si`ks``s``si``s``si`ks``s``si``s
``si`ks``s``si``s``si`ks``s``si``s``si`ks`ki``s``si`kk``s``si``s``si`ks``s``si``
s``si`ks`ki`ki`kk``s``si`kk`ki``s``si`kk``s``si`kk``s``si`kk`ki``s``si`kk``s``si
`kk`ks``s``si`kk`kk``s``si`kk`kk``s``si``s``si`ks`ki`ki``s``si`kk`kk``s``si``s``
si`ks``s``si`kk`kk``s``si``s``si`ks``s``si``s``si`ks``s``si``s``si`ks``s``si``s`
`si`ks``s``si``s``si`ks``s``si``s``si`ks``s``si``s``si`ks`ki``s``si`kk``s``si``s
``si`ks``s``si`kk``s``si`ks``s``si`kk``s``si``s``si`ks``s``si`kk`kk``s``si``s``s
i`ks``s``si`kk`kk``s``si``s``si`ks``s``si`kk`kk``s``si``s``si`ks``s``si`kk`kk`kk
``s``si``s``si`ks``s``si`kk``s``si`ks``s``si`kk``s``si`ks``s``si`kk``s``si``s``s
i`ks``s``si`kk``s``si`ks``s``si``s``si`ks`ki``s``si`kk``s``si``s``si``s``si`ks``
s``si``s``si``s``si`ks``s``si``s``si`ks`ki`ki``s``si``s``si`ks`ks`ks``s``si``s``
si`ks``s``si`kk`ks`kk``s``si``s``si`ks`ki``s``si``s``si`ks`ki`ki``s``si``s``si`k
s``s``si``s``si`ks``s``si`kk`ks`kk`ki`kk``s``si``s``si`ks``s``si``s``si`ks``s``s
i`kk`ks``s``si``s``si`ks``s``si``s``si`ks``s``si`kk`ks``s``si``s``si`ks``s``si`k
k`kk``s``si``s``si`ks``s``si`kk`ks``s``si``s``si`ks``s``si`kk``s``si`ks``s``si`k
k``s``si``s``si`ks``s``si`kk`ks`kk``s``si``s``si`ks``s``si`kk``s``si`ks`ki`kk``s
``si`kk``s``si``s``si`ks``s``si`kk``s``si`ks`ki`kk``s``si`kk``s``si`kk``s``si``s
``si`ks``s``si``s``si`ks``s``si``s``si`ks``s``si``s``si`ks``s``si``s``si`ks`ki``
s``si`kk``s``si`kk`ki``s``si`kk``s``si`kk``s``si`kk``s``si``s``si`ks`ki``s``si`k
k``s``si``s``si``s``si``s``si`ks``s``si``s``si`ks``s``si`kk`ks`kk`ki``s``si``s``
si`ks``s``si`kk``s``si`ks`ks``s``si`ks``s``si``s``si`ks`ki``s``si``s``si`ks`ks``
s``si`kk`ki``s``si``s``si`ks`ks``s``si``s``si``s``si`ks`ks`ki``s``si``s``si`ks`k
s``s``si``s``si`ks`ks``s``si`kk`ki``s``si`kk``s``si`kk``s``si``s``si`ks`ki``s``s
i`kk``s``si``s``si`ks``s``si``s``si`ks`ki``s``si``s``si`ks`ks``s``si``s``si``s``
si`ks`ks`ki``s``si``s``si`ks`ks``s``si`kk`ki``s``si``s``si`ks`ks``s``si``s``si`k
s``s``si``s``si`ks`ks`ks``s``si``s``si``s``si`ks`ks`ki``s``si``s``si`ks`ks``s``s
i`kk`ki``s``si`kk``s``si``s``si`ks`ki``s``si`kk``s``si``s``si`ks``s``si``s``si`k
s``s``si``s``si``s``si`ks`ks`ki``s``si``s``si`ks`ks``s``si``s``si`ks`ks``s``si`k
k`ki`ks``s``si``s``si`ks``s``si``s``si`ks`ki``s``si``s``si`ks`ks``s``si``s``si``
s``si`ks`ks`ki``s``si``s``si`ks`ks``s``si`kk`ki``s``si``s``si``s``si`ks`ks``s``s
i``s``si`ks`ks`ki``s``si``s``si`ks`ks``s``si`kk`ki``s``si`kk``s``si``s``si`ks``s
``si``s``si`ks``s``si`kk`ks``s``si``s``si`ks``s``si`kk`kk``s``si``s``si`ks``s``s
i`kk`ks``s``si``s``si`ks``s``si`kk``s``si`ks`ki``s``si``s``si`ks``s``si`kk`kk``s
``si``s``si`ks`ki``s``si`kk``s``si``s``si`ks``s``si`kk`ks`kk``s``si`kk`kk``s``si
`kk`ki``s``si`kk`ki``s``si`kk`ki``s``si`kk`ki``s``si`kk`ki``s``si`kk``s``si``s``
si``s``si`ks`ki``s``si`ks``s``si`kk``s``si``s``si`ks``s``si`kk``s``si`ks``s``si`
`s``si`ks`ki``s``si`kk``s``si``s``si``s``si`ks``s``si``s``si`ks`ki`ki``s``si``s`
`si`ks`ki`ki``s``si``s``si`ks``s``si``s``si`ks``s``si`kk`ks`kk`ki`kk``s``si``s``
si`ks`ki`ki``s``si`kk``s``si`kk``s``si``s``si``s``si`ks`ki`ki``s``si``s``si`ks`k
i`ki``s``si`kk``s``si`kk``s``si`kk`ki``s``si``s``si`ks``s``si``s``si`ks``s``si`k
k`ks``s``si``s``si`ks``s``si`kk``s``si`ks`ki``s``si``s``si`ks``s``si`kk``s``si`k
s``s``si``s``si`ks`ki``s``si``s``si`ks``s``si``s``si`ks`ki``s``si``s``si`ks``s``
si``s``si`ks`ki``s``si`kk`ks``s``si`kk`ks``s``si`kk`kk``s``si``s``si`ks``s``si``
s``si`ks``s``si``s``si`ks``s``si``s``si`ks``s``si``s``si`ks``s``si``s``si`ks`ki`
`s``si`kk``s``si``s``si`ks``s``si``s``si`ks``s``si`kk`ks``s``si``s``si`ks``s``si
``s``si`ks``s``si`kk`ks``s``si``s``si`ks``s``si`kk`kk``s``si``s``si`ks``s``si`kk
`ks``s``si``s``si`ks``s``si`kk``s``si`ks``s``si`kk``s``si``s``si`ks``s``si`kk``s
``si`ks``s``si`kk`kk``s``si``s``si`ks``s``si`kk``s``si`ks``s``si`kk`kk``s``si``s
``si`ks``s``si`kk``s``si`ks``s``si`kk`kk``s``si``s``si`ks``s``si`kk``s``si`ks``s
``si`kk`kk``s``si``s``si`ks``s``si`kk``s``si`ks``s``si`kk`kk``s``si``s``si`ks``s
``si`kk`ks``s``si``s``si`ks``s``si`kk``s``si`ks`ki``s``si``s``si`ks``s``si`kk``s
``si`ks``s``si``s``si`ks`ki``s``si`kk`ks``s``si`ks``s``si``s``si`ks`ki``s``si``s
``si`ks``s``si``s``si`ks`ki``s``si`kk`ks``s``si`kk`ki``s``si``s``si`ks``s``si`kk
``s``si`ks`ki`kk``s``si`kk``s``si``s``si`ks``s``si`kk``s``si`ks`ki`kk``s``si`kk`
`s``si`kk``s``si``s``si`ks``s``si``s``si`ks``s``si``s``si`ks``s``si``s``si`ks``s
``si``s``si`ks`ki``s``si`kk``s``si`kk`ki``s``si`kk``s``si`kk``s``si`kk``s``si``s
``si`ks`ki``s``si`kk`ks``s``si`kk``s``si`kk``s``si``s``si`ks`ki``s``si`kk`ki``s`
`si`kk``s``si``s``si`ks`ki``s``si`kk`kk``s``si`kk``s``si``s``si`ks``s``si`kk``s`
`si`ks``s``si``s``si`ks`ki``s``si`kk`kk`kk``s``si`kk`ki``s``si`kk`ki``s``si`kk`k
i``s``si`kk`ki``s``si`kk`ki``s``si`kk``s``si`kk`kii
```
Line breaks added for clarity.
This program is written in, and is capable of parsing, only the Unlambda-syntax subset of Lazy K; that is:
```
program ::= "s" | "k" | "i" | "`" program program.
```
It expects input to be encoded in the standard format for Lazy K: an input stream is a pair whose first element is a Church numeral, representing the first byte of the stream, and whose second element is the remaining input stream. However, the *output* is expected to be only a single Church numeral rather than a full output stream.
## The parsing part
If we look at the character codes for the relevant bits of Lazy K syntax, we notice something interesting:
* `s` is 115, or 1 mod 6;
* `k` is 107, or 5 mod 6;
* `i` is 105, or 3 mod 6;
* ``` is 96, or 0 mod 6.
If we assume the input program is part of the relevant subset, we can distinguish application using only a parity test, and then distinguish the combinators from each other using remainder mod 3.
Doing these tests effectively in combinatory logic requires a little cleverness, though.
* **mod 2**: the idea is to find terms `a`, `b`, and `f` such that `f a = b` and `f b = a`, and then call `N f a` and examine the result. Traditionally the Church booleans are used for `a` and `b` and `f` is `not`, but `not` is annoyingly difficult to encode in SKI. Instead, I did an automated search for terms that would work, and it came up with this:
+ `S I K I = I (K I) = K I`;
+ `S I K (K I) = K I (K (K I)) = I`.
* **mod 3**: similarly, we find distinct terms `a`, `b`, `c`, `f` with `f a = b`, `f b = c`, `f c = a`. A search yielded:
+ `S (S I I) K I = I I (K I) = K I`;
+ `S (S I I) K (K I) = K I (K I) (K (K I)) = K (K I)`;
+ `S (S I I) K (K (K I)) = K (K I) (K (K I)) (K ...) = I`.
Given these, we can write a fairly conventional recursive-descent parser:
```
parse : stream -> (term, stream)
parse (c, rest) =
match (c mod 2)
0 -> let (f, rest') = parse rest
let (x, rest'') = parse rest'
(f x, rest'')
1 -> ((match (c mod 3)
0 -> I
1 -> S
2 -> K), rest)
```
## The quining part
This is the fun part. One of the most important parts of any quine is figuring out a data format to represent the encoded form of the program. This ends up being the largest source of overhead since it essentially multiplies the program's length.
The representation I went with involves a lambda that substitutes its argument for every application in the encoded term, but leaves combinators unchanged. For example, the SKI-term `(S S) (K I)` would be encoded as:
```
λf. f (f S S) (f K I)
```
In terms of SKI, the encoding looks like this:
```
encode(S) = (K S)
encode(K) = (K K)
encode(I) = (I I)
encode(f x) = S (S I (encode(f))) (encode(x))
```
This encoding introduces 3x overhead for combinators and 7x overhead for applications. There are about half many applications as combinators in any Lazy K term, so this encoding has ~5x overhead. There are other encodings which are more efficient than this. For example, @msullivan's [quine](https://github.com/msullivan/LazyK/blob/master/eg/quine.lazy) uses a representation which exploits the fact that top-level terms are applied together to have just 1.5x overhead. However, this approach has several disadvantages. It supports only the S and K combinators, making the body of the quine more verbose. It relies on going outside of the Unlambda subset of the syntax, so I would need to make the parser more complex. Finally, it lacks a very useful feature of my representation: it can be trivially "interpreted" into the term it represents by passing `I` as the argument, avoiding the need to store both the encoded and decoded form of the quine payload. Nevertheless, the savings from using a more efficient representation like this are so large that it would probably be worth doing.
Finally there is the task of stringifying the encoded quine to obtain the source code and passing it to the parsed input term. For this we need to construct the Church numerals 96, 105, 107, and 115. For golfing purposes I was able to find terms which are much more efficient than the constructions given in the [standard library](https://github.com/msullivan/LazyK/blob/master/prelude-numbers.scm): `96` is reduced from 63 bytes to 45, `105` is reduced from 81 bytes to 49, `107` is reduced from 91 bytes to 65, and `115` is reduced from 89 bytes to 55. I obtained these using alternative representation of numbers which can be easily converted to and from Church numerals. This representation admits much more compact definitions of `succ` and `+`, and only slightly less compact definitions of `*` and `^`.
Also, there is the problem of traversing the encoded form of the program to build up the stringified form. For this, we effectively need `f x y` to be able to distinguish the cases when its arguments are combinators and when its arguments are further applications of `f`. We accomplish this using a helper function:
```
helper(x) = x (K I) (K (K (λt. t foo))) (K (λt. t baz)) (λt. t bar) t
```
This evaluates to `t foo`, `t bar`, and `t baz` when passed `S`, `K`, and `I` as arguments respectively, but you can also pass `(λ a b c d e. something else)` to distinguish applications. This kind of function is unfortunately relatively cumbersome when encoded in SKI, but I haven't found anything better. We use a [difference list](https://en.wikipedia.org/wiki/Difference_list) to accumulate the stringified representations, since it makes it very cheap to append (just function composition) and doesn't require modification to work with infinite streams.
## Further golfing
How to improve this:
* Use a better data representation, even though this comes at the cost of easy interpretation.
* Find a more efficient way to distinguish the `S`, `K`, and `I` combinators. If a better way exists, it's too large for my search program to find it as-is, so I would need to make it more efficient somehow or make assumptions to reduce the search space.
* Find more efficient representations of each of the numbers. 96 in particular feels like it could be improved a lot, although it's probably also too large for the search program.
* Better optimize `parse`, since it has some room for improvement.
The Lazier code used to generate this program can be found [here](https://github.com/Reconcyl/eso/blob/main/lazyk/main.scm).
] |
[Question]
[
[Lisp](http://en.wikipedia.org/wiki/Lisp_(programming_language)) programmers boast that Lisp is a powerful language which [can be built up from a very small set of primitive operations](https://en.wikipedia.org/wiki/Scheme_(programming_language)#Minimalism). Let's put that idea into practice by golfing an interpreter for a dialect called `tinylisp`.
## Language specification
In this specification, any condition whose result is described as "undefined" may do anything in your interpreter: crash, fail silently, produce random gobbldegook, or work as expected. A reference implementation in Python 3 is available [here](https://gist.github.com/dloscutoff/254267bce8cb09f009ad).
### Syntax
Tokens in tinylisp are `(`, `)`, or any string of one or more printable ASCII characters except parentheses or space. (I.e. the following regex: `[()]|[^() ]+`.) Any token that consists *entirely* of digits is an integer literal. (Leading zeros are okay.) Any token that contains non-digits is a symbol, even numeric-looking examples like `123abc`, `3.14`, and `-10`. All whitespace (including, at a minimum, ASCII characters 32 and 10) is ignored, except insofar as it separates tokens.
A tinylisp program consists of a series of expressions. Each expression is either an integer, a symbol, or an s-expression (list). Lists consist of zero or more expressions wrapped in parentheses. No separator is used between items. Here are examples of expressions:
```
4
tinylisp!!
()
(c b a)
(q ((1 2)(3 4)))
```
Expressions that are not well-formed (in particular, that have unmatched parentheses) give undefined behavior. (The reference implementation auto-closes open parens and stops parsing on unmatched close parens.)
### Data types
The data types of tinylisp are integers, symbols, and lists. Built-in functions and macros can also be considered a type, though their output format is undefined. A list can contain any number of values of any type and can be nested arbitrarily deeply. Integers must be supported at least from -2^31 to 2^31-1.
The empty list `()`--also referred to as nil--and the integer `0` are the only values that are considered logically false; all other integers, nonempty lists, builtins, and all symbols are logically true.
### Evaluation
Expressions in a program are evaluated in order and the results of each sent to stdout (more on output formatting later).
* An integer literal evaluates to itself.
* The empty list `()` evaluates to itself.
* A list of one or more items evaluates its first item and treats it as a function or macro, calling it with the remaining items as arguments. If the item is not a function/macro, the behavior is undefined.
* A symbol evaluates as a name, giving the value bound to that name in the current function. If the name is not defined in the current function, it evaluates to the value bound to it at global scope. If the name is not defined at current or global scope, the result is undefined (reference implementation gives an error message and returns nil).
### Built-in functions and macros
There are seven built-in functions in tinylisp. A function evaluates each of its arguments before applying some operation to them and returning the result.
* `c` - cons[truct list]. Takes two arguments, a value and a list, and returns a new list obtained by adding the value at the front of the list.
* `h` - head ([car](https://en.wikipedia.org/wiki/CAR_and_CDR), in Lisp terminology). Takes a list and returns the first item in it, or nil if given nil.
* `t` - tail ([cdr](https://en.wikipedia.org/wiki/CAR_and_CDR), in Lisp terminology). Takes a list and returns a new list containing all but the first item, or nil if given nil.
* `s` - subtract. Takes two integers and returns the first minus the second.
* `l` - less than. Takes two integers; returns 1 if the first is less than the second, 0 otherwise.
* `e` - equal. Takes two values of the same type (both integers, both lists, or both symbols); returns 1 if the two are equal (or identical in every element), 0 otherwise. Testing builtins for equality is undefined (reference implementation works as expected).
* `v` - eval. Takes one list, integer, or symbol, representing an expression, and evaluates it. E.g. doing `(v (q (c a b)))` is the same as doing `(c a b)`; `(v 1)` gives `1`.
"Value" here includes any list, integer, symbol, or builtin, unless otherwise specified. If a function is listed as taking specific types, passing it different types is undefined behavior, as is passing the wrong number of arguments (reference implementation generally crashes).
There are three built-in macros in tinylisp. A macro, unlike a function, does not evaluate its arguments before applying operations to them.
* `q` - quote. Takes one expression and returns it unevaluated. E.g., evaluating `(1 2 3)` gives an error because it tries to call `1` as a function or macro, but `(q (1 2 3))` returns the list `(1 2 3)`. Evaluating `a` gives the value bound to the name `a`, but `(q a)` gives the name itself.
* `i` - if. Takes three expressions: a condition, an iftrue expression, and an iffalse expression. Evaluates the condition first. If the result is falsy (`0` or nil), evaluates and returns the iffalse expression. Otherwise, evaluates and returns the iftrue expression. Note that the expression that is not returned is never evaluated.
* `d` - def. Takes a symbol and an expression. Evaluates the expression and binds it to the given symbol treated as a name *at global scope*, then returns the symbol. Trying to redefine a name should fail (silently, with a message, or by crashing; the reference implementation displays an error message). Note: it is not necessary to quote the name before passing it to `d`, though it is necessary to quote the expression if it's a list or symbol you don't want evaluated: e.g., `(d x (q (1 2 3)))`.
Passing the wrong number of arguments to a macro is undefined behavior (reference implementation crashes). Passing something that's not a symbol as the first argument of `d` is undefined behavior (reference implementation doesn't give an error, but the value cannot be referenced subsequently).
### User-defined functions and macros
Starting from these ten built-ins, the language can be extended by constructing new functions and macros. These have no dedicated data type; they are simply lists with a certain structure:
* A function is a list of two items. The first is either a list of one or more parameter names, or a single name which will receive a list of any arguments passed to the function (thus allowing for variable-arity functions). The second is an expression which is the function body.
* A macro is the same as a function, except that it contains nil before the parameter name(s), thus making it a three-item list. (Trying to call three-item lists that do not start with nil is undefined behavior; the reference implementation ignores the first argument and treats them as macros as well.)
For example, the following expression is a function that adds two integers:
```
(q List must be quoted to prevent evaluation
(
(x y) Parameter names
(s x (s 0 y)) Expression (in infix, x - (0 - y))
)
)
```
And a macro that takes any number of arguments and evaluates and returns the first one:
```
(q
(
()
args
(v (h args))
)
)
```
Functions and macros can be called directly, bound to names using `d`, and passed to other functions or macros.
Since function bodies are not executed at definition time, recursive functions are easily definable:
```
(d len
(q (
(list)
(i list If list is nonempty
(s 1 (s 0 (len (t list)))) 1 - (0 - len(tail(list)))
0 else 0
)
))
)
```
Note, though, that the above is not a good way to define a length function because it doesn't use...
### Tail-call recursion
[Tail-call recursion](https://en.wikipedia.org/wiki/Tail_call) is an important concept in Lisp. It implements certain kinds of recursion as loops, thus keeping the call stack small. Your tinylisp interpreter **must** implement proper tail-call recursion!
* If the return expression of a user-defined function or macro is a call to another user-defined function or macro, your interpreter must not use recursion to evaluate that call. Instead, it must replace the current function and arguments with the new function and arguments and loop until the chain of calls is resolved.
* If the return expression of a user-defined function or macro is a call to `i`, do not immediately evaluate the branch that is selected. Instead, check whether it is a call to another user-defined function or macro. If so, swap out the function and arguments as above. This applies to arbitrarily deeply nested occurrences of `i`.
Tail recursion must work both for direct recursion (a function calls itself) and indirect recursion (function `a` calls function `b` which calls [etc] which calls function `a`).
A tail-recursive length function (with a helper function `len*`):
```
(d len*
(q (
(list accum)
(i list
(len*
(t list)
(s 1 (s 0 accum))
)
accum
)
))
)
(d len
(q (
(list)
(len* list 0)
))
)
```
This implementation works for arbitrarily large lists, limited only by the max integer size.
### Scope
Function parameters are local variables (actually constants, since they can't be modified). They are in scope while the body of that call of that function is being executed, and out of scope during any deeper calls and after the function returns. They can "shadow" globally defined names, thereby making the global name temporarily unavailable. For example, the following code returns 5, not 41:
```
(d x 42)
(d f
(q (
(x)
(s x 1)
))
)
(f 6)
```
However, the following code returns 41, because `x` at call level 1 is not accessible from call level 2:
```
(d x 42)
(d f
(q (
(x)
(g 15)
))
)
(d g
(q (
(y)
(s x 1)
))
)
(f 6)
```
The only names in scope at any given time are 1) the local names of the currently executing function, if any, and 2) global names.
## Submission requirements
### Input and output
*Updated June 2022 to be more flexible*
Your interpreter should input a tinylisp program in one of two ways:
* directly, as a multiline string, or
* indirectly, as the name of a file containing the tinylisp program.
It should evaluate each expression in the program one by one, outputting each result with a trailing newline.
* Integers should be output in your implementation language's most natural representation. Negative integers can be output, with leading minus signs.
* Symbols should be output as strings, with **no** surrounding quotes or escapes.
* Lists should be output with all items space-separated and wrapped in parentheses. A space inside the parentheses is optional: `(1 2 3)` and `( 1 2 3 )` are both acceptable formats.
* Outputting built-in functions and macros is undefined behavior. (The reference interpretation displays them as `<built-in function>`.)
All [default input and output methods](https://codegolf.meta.stackexchange.com/q/2447/16766) are acceptable. Your submission may be a full program or a function.
### Other
The reference interpreter includes a REPL environment and the ability to load tinylisp modules from other files; these are provided for convenience and are not required for this challenge.
### [Test cases](https://gist.github.com/dloscutoff/25873038e3e8eb057d61)
The test cases are separated into several groups so that you can test simpler ones before working up to more-complex ones. However, they will also work just fine if you dump them all in one file together. Just don't forget to remove the headings and the expected output before running it.
If you have properly implemented tail-call recursion, the final (multi-part) test case will return without causing a stack overflow. The reference implementation computes it in about six seconds on my laptop.
[Answer]
# Python 2, ~~685~~ ~~675~~ ~~660~~ ~~657~~ ~~646~~ ~~642~~ 640 bytes
```
import sys,re
E=[]
G=zip("chtsle",[eval("lambda x,y=0:"+f)for f
in"[x]+y (x+[E])[0] x[1:] x-y +(x<y) +(x==y)".split()])
def V(e,L=E):
while 1:
try:return e and int("0%s"%e)
except:A=e[1:]
if""<e:return dict(G+L).get(e,e)
f=V(e[0],L)
if""<f:
if f in"iv":t=V(A[0],L);e=(e[~bool(t)],t)[f>"u"];continue
if"e">f:G[:]+=(A[0],V(A[1],L)),
return A[0]
if[]>f or f[0]:A=[V(a,L)for a in A]
if[]>f:return f(*A)
P,e=f[-2:];L=([(P,A)],zip(P,A))[P<""]
F=lambda x:V<x<""and"(%s)"%" ".join(map(F,x))or"%s"%x
for t in re.sub("([()])"," \\1 ",sys.stdin.read()).split():
if")"==t:t=E.pop()
if"("==t:E+=[],
elif E:E[-1]+=t,
else:print F(V(t))
```
Reads input from STDIN and writes output to STDOUT.
Although not strictly required, the interpreter supports nullary functions and macros, and optimizes tail calls executed through `v`.
## Explanation
**Parsing**
To parse the input, we first surround each occurence of `(` and `)` with spaces, and split the resulting string into words; this gives us the list of tokens.
We maintain an expression stack `E`, which is initially empty.
We scan the tokens, in order:
* if we encounter a `(`, we push an empty list at the top of the expression stack;
* if we encounter a `)`, we pop the value at the top of the expression stack, and append it to the list that was previously below it on the stack;
* otherwise, we append the current token, as a string, to the list at the top of the expression stack (we keep integers as strings at this stage, and parse them during evaluation.)
If, when processsing an ordinary token, or after popping an expression from the stack due to `)`, the expression stack is empty, we're at a top-level expression, and we evaluate the value we'd otherwise have appended, using `V()`, and print its result, formatted appropriately using `F()`.
**Evaluation**
We maintain the global scope, `G`, as a list of key/value pairs.
Initially, it contains only the builtin functions (but not the macros, and not `v`, which we treat as a macro), which are implemented as lambdas.
Evaluation happens inside `V()`, which takes the expression to evaluate, `e`, and the local scope, `L`, which is, too, a list of key/value pairs (when evaluating a top-level expression, the local scope is empty.)
The guts of `V()` live inside an infinite loop, which is how we perform tail-call optimization (TCO), as explained later.
We process `e` according to its type:
* if it's the empty list, or a string convertible to an int, we return it immediately (possibly after conversion to int); otherwise,
* if it's a string, we look it up in a dictionary constructed from the concatenation of the global and local scopes.
If we find an associated value, we return it; otherwise, `e` must be the name of a builtin macro (i.e. `q`, `i`, `d` or `v`), and we return it unchanged.
Otherwise, if `e` is not a string,
* `e` is a (nonempty) list, i.e., a function call.
We evaluate the first element of the list, i.e., the function expression, by calling `V()` recursively (using the current local scope); we call the result `f`.
The rest of the list, `A`, is the list of arguments.
`f` can only be a string, in which case it's a builtin macro (or the function `v`), a lambda, in which case it's a builtin function, or a list, in which case it's a user-defined function or macro.
If `f` is a a string, i.e., a builtin macro, we handle it in-place.
If it's the macro `i` or `v`, we evaluate its first operand, and either select the second or third operand accordingly, in the case of `i`, or use the result of the first operand, in the case of `v`;
instead of evaluating the selected expression recursively, which would defeat TCO, we simply replace `e` with the said expression, and jump to the beginning of the loop.
If `f` is the macro `d`, we append a pair, whose first element is the first operand, and whose second element is the result of evaluating the second operand, to the global scope, `G`, and return the first operand.
Otherwise, `f` is the macro `q`, in which case we simply return its operand directly.
Othrtwise, if `f` is a lambda, or a list whose first element is not `()`, then it's a non-nullary function, not a macro, in which case we evaluate its arguments, i.e., the elements of `A`, and replace `A` with the result.
If `f` is a lambda, we call it, passing it the unpacked arguments in `A`, and return the result.
Otherwise, `f` is a list, i.e., a user-defined function or macro; its parameter list is the second-to-last element, and its body is the last element.
Like in the case of the macros `i` and `v`, in order to perform TCO, we don't evaluate the body recursively, but rather replace `e` with the body and continue to the next iteration.
Unlike `i` and `v`, however, we also replace the local scope, `L`, with the new local scope of the function.
If the parameter list, `P`, is, in fact, a list, the new local scope is constructed by zipping the parameter list, `P`, with the argument list, `A`;
otherwise, we're dealing with a variadic function, in which case the new local scope has only one element, the pair `(P, A)`.
## REPL
If you want to play with it, here's a REPL version of the interpreter.
It supports redefining symbols, and importing files through either the command line arguments, or the `(import <filename>)` macro.
To exit the interpreter, terminate the input (usually, Ctrl+D or Ctrl+Z).
```
try:import sys,re,readline
except:0
E=[];G=zip("chtsle",[eval("lambda x,y=0:"+f)for f
in"[x]+y (x+[E])[0] x[1:] x-y +(x<y) +(x==y)".split()])
def V(e,L=E):
while 1:
try:return e and int("0%s"%e)
except:A=e[1:]
if""<e:return dict(G+L).get(e,e)
f=V(e[0],L)
if""<f:
if f in"iv":t=V(A[0],L);e=(e[~bool(t)],t)[f>"u"];continue
if"e">f:G[:]+=(A[0],V(A[1],L)),
elif"j">f:X(open(str(A[0])).read())
return A[0]
if[]>f or f[0]:A=[V(a,L)for a in A]
if[]>f:return f(*A)
P,e=f[-2:];L=([(P,A)],zip(P,A))[P<""]
F=lambda x:V<x<""and"(%s)"%" ".join(map(F,x))or"%s"%x
def X(s,v=0):
for t in re.sub("([()])"," \\1 ",s).split():
if")"==t:t=E.pop()
if"("==t:E[:]+=[],
elif E:E[-1]+=t,
else:
x=V(t)
if v:print F(x)
for f in sys.argv[1:]:X("(g %s)"%f)
while 1:
try:X(raw_input(">."[[]<E]*3+" "),1)
except EOFError:break
except KeyboardInterrupt:E=[];print
except Exception as e:print"Error: "+e.message
```
And here's an example session, implementing merge sort:
```
>>> (d let d) (d if i) (d head h) (d tail t) (d prepend c) (d less l)
let
if
head
tail
prepend
less
>>>
>>> (let list (q (x... x...)))
list
>>> (let lambda (q (() (params body) (list params body))))
lambda
>>> (let def (q (() (name params body) (
... v (list (q let) name (list (q lambda) params body))
... ))))
def
>>>
>>> (def else(body) body)
else
>>> (def or(x y) ( if x x y ))
or
>>> (def and(x y) ( if x y x ))
and
>>>
>>> (def front-half(L) ( front-half/impl L L ))
front-half
>>> (def front-half/impl(L M) (
... if M (
... prepend (head L)
... (front-half/impl (tail L) (tail (tail M)))
... ) (else
... ()
... )
... ))
front-half/impl
>>>
>>> (def back-half(L) ( back-half/impl L L ))
back-half
>>> (def back-half/impl(L M) (
... if M (
... back-half/impl (tail L) (tail (tail M))
... ) (else
... L
... )
... ))
back-half/impl
>>>
>>> (def merge(L M comp) (
... if (and L M) (
... if (comp (head M) (head L)) (
... prepend (head M) (merge L (tail M) comp)
... ) (else (
... prepend (head L) (merge (tail L) M comp)
... ))
... ) (else (
... or L M
... ))
... ))
merge
>>>
>>> (def sort(L comp) (
... if (and L (tail L)) (
... merge (sort (front-half L) comp)
... (sort (back-half L) comp)
... comp
... ) (else
... L
... )
... ))
sort
>>>
>>>
>>> (let my-list (list 4 7 2 5 9 1 6 10 8 3))
my-list
>>> my-list
(4 7 2 5 9 1 6 10 8 3)
>>> (sort my-list less)
(1 2 3 4 5 6 7 8 9 10)
>>> (sort my-list (lambda(x y) ( less y x )))
(10 9 8 7 6 5 4 3 2 1)
```
[Answer]
# C (GNU), 1095 bytes
Much of the action takes place in the giant `v` function. Instead of implementing tail recursion explicitly, `v` is structured so that many of the calls from `v` to `v` will be handled by gcc's tail recursion optimization. There is no garbage collection.
This makes heavy use of GCC extensions, so it could only be compiled with gcc (use the command `gcc -w -Os tl.c`). It also uses some `scanf` extensions which were not available on Windows, which I usually use. The prospect of writing the parser with standard `scanf` was so awful that I used a Linux VM to test the program instead. Parsing without `scanf` character classes probably would have added 100+ bytes.
```
#define O(...)({o*_=malloc(32);*_=(o){__VA_ARGS__};_;})
#define P printf
#define F(I,B)({for(I;x->c;x=x->l)B;})
#define Z return
typedef struct o{struct o*n,*l,*c;int i,t;}o;E(o a,o b){Z
a.n?!strcmp(a.n,b.n):a.c?b.c&&E(*a.c,*b.c)&E(*a.l,*b.l):!b.c&a.i==b.i;}p(o*x){x->t?P("%d ",x->i):x->n?P("%s ",x->n):F(P("("),p(x->c);P(")"));}o*x,G,N;*C(o*h,o*t){Z
O(c:h,l:t);}o*v(o*x,o*e){o*W(o*l,o*e){Z
l->c?C(v(l->c,e),W(l->l,e)):&N;}o*y,*a,*f;int t;Z
x->c?y=v(x->c,e),x=x->l,t=y->i,t?9/t?a=v(x->c,e),t>7?(t>8?a->c:a->l)?:a:t>6?v(a,e):t<6?x=v(x->l->c,e),t>4?C(a,x):O(t:1,i:t>3?E(*a,*x):t>2?a->i<x->i:a->i-x->i):v((a-&N&&!a->t|a->i?x:x->l)->l->c,e):(t&1&&d(x->c->n,v(x->l->c,e)),x->c):(y->l->l->l?y=y->l:(x=W(x,e)),a=y->c,v(y->l->c,a->n?O(n:a->n,c:x,l:&G):F(f=&G,(f=O(n:a->c->n,c:x->c,l:f),a=a->l);f))):x->n?e->n?strcmp(x->n,e->n)?v(x,e->l):e->c:e:x;}d(o*n,o*x){*v(O(n:""),&G)=(o){n:n,c:x,l:O()};}*R(h){char*z,*q;Z
scanf(" %m[^ \n()]",&q)>0?h=strtoul(q,&z,10),C(*z?O(n:q):O(t:1,i:h),R()):~getchar()&1?q=R(),C(q,R()):&N;}main(i){for(;++i<12;)d(strndup("slecivthqd"+i-2,1),O(i:i));F(x=R(),p(v(x->c,&G)));}
```
**Semi-ungolfed**
```
typedef struct o o;
struct o {
char* n;
o* l, //next in this list
* c;
int i,
t;
} ;
#define O(...)({o*_=malloc(32);*_=(o){__VA_ARGS__};_;})
E(o a, o b) { //tests equality
return
a.n ? !strcmp(a.n,b.n) :
a.t ? a.i==b.i :
a.c ? b.c && E(*a.c,*b.c)&E(*a.l,*b.l) :
!b.c
;
}
#define P printf
p(o*x){
x->t?P("%d ",x->i):x->n?P("%s ",x->n):({for(P("(");x->c;x=x->l)p(x->c);P(")");});
}
o*_,G,N; //N = nil
o*C(o*h,o*t){return O(c:h,l:t);}
/*
2 3 4 5 6 7 8 9 10 11
s l e c i v t h d q
*/
o* v(o* x, o* e) { //takes list, int, or name
o*W(o* l, o* e) { //eval each item in list
return l->c ? C(v(l->c ,e), W(l->l, e)) : &N;
}
o*y,*a,*f;int t;
return x->c ? //nonempty list = function/macro call
y = v(x->c,e), //evals to function/macro
x = x->l, //list position of first arg (if it exists)
(t=y->t)? //builtin no., if any
t>9 ?
t&1 ? x->c // 11 = q
: //10 = d
(d(x->c,v(x->l->c,e)),x->c)
: (a = v(x->c,e), //eval'd first arg
t)>7 ? // t/h
(t > 8 ? a->c : a->l) ?: a
: t>6 ? //v
v(a,e)
: (x = x->l, //position of 2nd arg in list
t)>5 ? //i
v( (a->n||a->l||a->i|a->t>1 ? x : x->l)->c, e)
: (x = v(x->c,e), //evaluated 2nd arg
t)>4 ? // c
C(a,x)
: O(t:1,i:
t>3 ? E(*a,*x) : //e
t>2 ? a->i<x->i : //l
a->i-x->i //s
)
:
(
y->l->l->l ? //whether this is macro
y = y->l :
(x = W(x,e)), //eval args
a = y->c, //a = arg list
//a = a->n ? x=C(x, &N), C(a, &N) : a, //transform variadic style to normal
v(y->l->c,
a->n ? //variadic
O(n:a->n,c:x,l:&G)
: ({
for(f=&G; a->c; a=a->l,x=x->l)
f=O(n:a->c->n, c: x->c, l:f);
f;
})
)
)
:
x->n ? // name
e->n ?
strcmp(x->n,e->n) ?
v(x,e->l)
: e->c
: e
: x; //int or nil
}
d(o*n,o*x){
* v(O(n:""),&G) =
(o){n:n->n,c:x,l:O()};
}
;
o*R(){
char*z,*q;int h;
return scanf(" %m[^ \n()]",&q)>0?
h=strtoul(q,&z,10),
C(*z ? O(n:q) : O(t:1,i:h), R())
: getchar()&1?&N:(q=R(),C(q,R()));
}
main(i) {
for(;++i<12;) d(O(n:strndup("slecivthdq"+i-2,1)),O(t:i));
o *q;
for(q=R(); q->c; q=q->l) p(v(q->c,&G));
}
```
[Answer]
# Ceylon, 2422 bytes
(I think this is my longest golfed program yet.)
```
import ceylon.language{sh=shared,va=variable,fo=formal,O=Object}import ceylon.language.meta.model{F=Function}interface X{sh fo V v(S t);sh fo G g;}class G(va Map<S,V>m)satisfies X{v(S t)=>m[t]else nV;g=>this;sh S d(S s,V v){assert(!s in m);m=map{s->v,*m};return s;}}V nV=>nothing;class LC(G c,Map<S,V>m)satisfies X{g=>c;v(S t)=>m[t]else g.v(t);}alias C=>V|Co;interface Co{sh fo C st();}interface V{sh fo C l(X c,V[]a);sh default Boolean b=>0<1;sh fo C vO(X c);sh default V vF(X c){va C v=vO(c);while(is Co n=v){v=n.st();}assert(is V r=v);return r;}}class L(sh V*i)satisfies V{vO(X c)=>if(nonempty i)then i[0].vF(c).l(c,i.rest)else this;equals(O o)=>if(is L o)then i==o.i else 1<0;b=>!i.empty;string=>"(``" ".join(i)``)";hash=>i.hash;sh actual C l(X c,V[]p){value[h,ns,x]=i.size<3then[f,i[0],i[1]]else[m,i[1],i[2]];value n=if(is L ns)then[*ns.i.narrow<S>()]else ns;assert(is S|S[]n,is V x);V[]a=h(c,p);LC lC=if(is S n)then LC(c.g,map{n->L(*a)})else LC(c.g,map(zipEntries(n,a)));return object satisfies Co{st()=>x.vO(lC);};}}class S(String n)satisfies V{vO(X c)=>c.v(this);l(X c,V[]a)=>nV;equals(O o)=>if(is S o)then n==o.n else 1<0;hash=>n.hash;string=>n;}class I(sh Integer i)satisfies V{vO(X c)=>this;l(X c,V[]a)=>nV;equals(O o)=>if(is I o)then i==o.i else 1<0;hash=>i;b=>!i.zero;string=>i.string;}V[]f(X c,V[]a)=>[for(v in a)v.vF(c)];V[]m(X c,V[]a)=>a;L c(X c,V h,L t)=>L(h,*t.i);V h(X c,L l)=>l.i[0]else L();V t(X c,L l)=>L(*l.i.rest);I s(X c,I f,I s)=>I(f.i-s.i);I l(X c,I f,I s)=>I(f.i<s.i then 1else 0);I e(X c,V v1,V v2)=>I(v1==v2then 1else 0);C v(X c,V v)=>v.vO(c);V q(X c,V a)=>a;C i(X c,V d,V t,V f)=>d.vF(c).b then t.vO(c)else f.vO(c);S d(X c,S s,V x)=>c.g.d(s,x.vF(c));class B<A>(F<C,A>nat,V[](X,V[])h=f)satisfies V given A satisfies[X,V+]{vO(X c)=>nV;string=>nat.declaration.name;l(X c,V[]a)=>nat.apply(c,*h(c,a));}{<S->V>*}b=>{S("c")->B(`c`),S("h")->B(`h`),S("t")->B(`t`),S("s")->B(`s`),S("l")->B(`l`),S("e")->B(`e`),S("v")->B(`v`),S("q")->B(`q`,m),S("i")->B(`i`,m),S("d")->B(`d`,m)};[V*]p(String inp){value ts=inp.split(" \n()".contains,1<0,1<0);va[[V*]*]s=[];va[V*]l=[];for(t in ts){if(t in" \n"){}else if(t=="("){s=[l,*s];l=[];}else if(t==")"){l=[L(*l.reversed),*(s[0]else[])];s=s.rest;}else if(exists i=parseInteger(t),i>=0){l=[I(i),*l];}else{l=[S(t),*l];}}return l.reversed;}sh void run(){va value u="";while(exists l=process.readLine()){u=u+l+"\n";}V[]e=p(u);X c=G(map(b));for(v in e){print(v.vF(c));}}
```
I could have golfed some bytes more, as I used some two-letter identifiers in some places, but I've run out of somewhat meaningful single letters for those. Although even this way it doesn't look like Ceylon very much ...
This is an **object-oriented** implementation.
We have a value interface `V` with implementing classes `L` (list – just a wrapper around a Ceylon sequential of `V`), `S` (symbol – wrapper around a string), `I` (integer – wrapper around a Ceylon integer) and `B` (builtin function or macro, a wrapper around a Ceylon function).
I use the standard Ceylon equality notation by implementing the `equals` method (and also the `hash` attribute, which is really only needed for symbols), and also the standard `string` attribute for output.
We have a Boolean attribute `b` (which is true by default, overridden in `I` and `L` to return false for empty lists), and two methods `l` (call, i.e. use this object as a function) and `vO` (evaluate one step). Both return either a value or a Continuation object which allows then evaluation for one more step, and `vF` (evaluate fully) loops until the result is not a continuation anymore.
A context interface allows access to variables. There are two implementations, `G` for the global context (which allows adding variables using the `d` builtin) and `LC` for a local context, which is active when evaluating the expression of a user function (it falls back to the global context).
Symbols evaluation accesses the context, lists (if non empty) evaluate by first evaluating their first element and then calling its call method. Call is implemented just by lists and builtins – it first evaluates the argument (if a function, not if a macro) and then does the actual interesting stuff – for builtins just what is hardcoded, for lists it creates a new local context and returns a continuation with that.
For the builtins I used a trick similar to what I used in my [Shift Interpreter](https://codegolf.stackexchange.com/a/61340/2338), which allows me to define them with the argument types they need, but call them with a generic sequence using reflection (the types will be checked at call time). This avoids type conversion/assertion hassle inside the functions/macros, but needs top-level functions so I can get their meta-model `Function` objects.
The `p` (parse) function splits the string at spaces, newlines and parentheses, then loops over the tokens and builds lists using a stack and a running list.
The interpreter (in the `run` method, which is the entry point) then takes this list of expressions (which are just values), evaluates each of them, and prints the result.
---
Below is a version with comments and run through a formatter.
An earlier version before I started golfing (and still with some misunderstandings about list evaluation) is found at [my Github repository](https://github.com/ePaul/ceylon-codegolf/blob/master/source/codegolf/tinylisp62886/expressions.ceylon), I'll put this one there soon (so make sure to look at [the first version](https://github.com/ePaul/ceylon-codegolf/blob/4de5667509a34f402b88ea8cd616f2b333408897/source/codegolf/tinylisp62886/expressions.ceylon) if you want the original).
```
// Tiny Lisp, tiny interpreter
//
// An interpreter for a tiny subset of Lisp, from which most of the
// rest of the language can be bootstrapped.
//
// Question: https://codegolf.stackexchange.com/q/62886/2338
// My answer: https://codegolf.stackexchange.com/a/63352/2338
//
import ceylon.language {
sh=shared,
va=variable,
fo=formal,
O=Object
}
import ceylon.language.meta.model {
F=Function
}
// context
interface X {
sh fo V v(S t);
sh fo G g;
}
// global (mutable) context, with the buildins
class G(va Map<S,V> m) satisfies X {
// get entry throws error on undefined variables.
v(S t) => m[t] else nV;
g => this;
sh S d(S s, V v) {
// error when already defined
assert (!s in m);
// building a new map is cheaper (code-golf wise) than having a mutable one.
m = map { s->v, *m };
return s;
}
}
// This is simply a shorter way of writing "this is not an allowed operation".
// It will throw an exception when trying to access it.
// nV stands for "no value".
V nV => nothing;
// local context
class LC(G c, Map<S,V> m) satisfies X {
g => c;
v(S t) => m[t] else g.v(t);
// sh actual String string => "[local: ``m``, global: ``g``]";
}
// continuation or value
alias C => V|Co;
// continuation
interface Co {
sh fo C st();
}
// value
interface V {
// use this as a function and call with arguments.
// will not work for all types of stuff.
sh fo C l(X c, V[] a);
// check the truthiness. Defaults to true, as
// only lists and integers can be falsy.
sh default Boolean b => 0 < 1;
// evaluate once (return either a value or a continuation).
// will not work for all kinds of expression.
sh fo C vO(X c);
/// evaluate fully
sh default V vF(X c) {
va C v = vO(c);
while (is Co n = v) {
v = n.st();
}
assert (is V r = v);
return r;
}
}
class L(sh V* i) satisfies V {
vO(X c) => if (nonempty i) then i[0].vF(c).l(c, i.rest) else this;
equals(O o) => if (is L o) then i == o.i else 1 < 0;
b => !i.empty;
string => "(``" ".join(i)``)";
hash => i.hash;
sh actual C l(X c, V[] p) {
value [h, ns, x] =
i.size < 3
then [f, i[0], i[1]]
else [m, i[1], i[2]];
// parameter names – either a single symbol, or a list of symbols.
// If it is a list, we filter it to throw out any non-symbols.
// Should throw an error if there are any, but this is harder.
value n = if (is L ns) then [*ns.i.narrow<S>()] else ns;
assert (is S|S[] n, is V x);
V[] a = h(c, p);
// local context
LC lC = if (is S n) then
LC(c.g, map { n -> L(*a) })
else
LC(c.g, map(zipEntries(n, a)));
// return a continuation instead of actually
// calling it here, to allow stack unwinding.
return object satisfies Co {
st() => x.vO(lC);
};
}
}
// symbol
class S(String n) satisfies V {
// evaluate: resolve
vO(X c) => c.v(this);
// call is not allowed
l(X c, V[] a) => nV;
// equal if name is equal
equals(O o) => if (is S o) then n == o.n else 1 < 0;
hash => n.hash;
string => n;
}
// integer
class I(sh Integer i) satisfies V {
vO(X c) => this;
l(X c, V[] a) => nV;
equals(O o) => if (is I o) then i == o.i else 1 < 0;
hash => i;
b => !i.zero;
string => i.string;
}
// argument handlers for functions or macros
V[] f(X c, V[] a) => [for (v in a) v.vF(c)];
V[] m(X c, V[] a) => a;
// build-in functions
// construct
L c(X c, V h, L t) => L(h, *t.i);
// head
V h(X c, L l) => l.i[0] else L();
// tail
V t(X c, L l) => L(*l.i.rest);
// subtract
I s(X c, I f, I s) => I(f.i - s.i);
// lessThan
I l(X c, I f, I s) => I(f.i < s.i then 1 else 0);
// equal
I e(X c, V v1, V v2) => I(v1 == v2 then 1 else 0);
// eval (returns potentially a continuation)
C v(X c, V v) => v.vO(c);
// build-in macros
// quote
V q(X c, V a) => a;
// if (also returns potentially a continuation)
C i(X c, V d, V t, V f) => d.vF(c).b then t.vO(c) else f.vO(c);
// define symbol in global context
S d(X c, S s, V x) => c.g.d(s, x.vF(c));
// buildin function or macro, made from a native function and an argument handler
class B<A>(F<C,A> nat, V[](X, V[]) h = f)
satisfies V
given A satisfies [X, V+] {
vO(X c) => nV;
string => nat.declaration.name;
// this "apply" is a hack which breaks type safety ...
// but it will be checked at runtime.
l(X c, V[] a) => nat.apply(c, *h(c, a));
}
// define buildins
{<S->V>*} b => {
S("c") -> B(`c`),
S("h") -> B(`h`),
S("t") -> B(`t`),
S("s") -> B(`s`),
S("l") -> B(`l`),
S("e") -> B(`e`),
S("v") -> B(`v`),
S("q") -> B(`q`, m),
S("i") -> B(`i`, m),
S("d") -> B(`d`, m)
};
// parses a string into a list of expressions.
[V*] p(String inp) {
// split string into tokens (retain separators, don't group them –
// whitespace and empty strings will be sorted out later in the loop)
value ts = inp.split(" \n()".contains, 1 < 0, 1 < 0);
// stack of not yet finished nested lists, outer most at bottom
va [[V*]*] s = [];
// current list, in reverse order (because appending at the start is shorter)
va [V*] l = [];
for (t in ts) {
if (t in " \n") {
// do nothing for empty tokens
} else if (t == "(") {
// push the current list onto the stack, open a new list.
s = [l, *s];
l = [];
} else if (t == ")") {
// build a lisp list from the current list,
// pop the latest list from the stack, append the created lisp list.
l = [L(*l.reversed), *(s[0] else [])];
s = s.rest;
} else if (exists i = parseInteger(t), i >= 0) {
// append an integer to the current list.
l = [I(i), *l];
} else {
// append a symbol to the current list.
l = [S(t), *l];
}
}
return l.reversed;
}
// Runs the interpreter.
// This handles input and output, calls the parser and evaluates the expressions.
sh void run() {
va value u = "";
while (exists l = process.readLine()) {
u = u + l + "\n";
}
V[] e = p(u);
// create global context
X c = G(map(b));
// iterate over the expressions, ...
for (v in e) {
// print(" '``v``' → ...");
// ... evaluate each (fully) and print the result.
print(v.vF(c));
}
}
```
] |
[Question]
[
## TAS Golf
![SMB1 1-1 ending](https://i.stack.imgur.com/kD8Oc.png)
In the style of a [tool-assisted speedrun](https://en.wikipedia.org/wiki/Tool-assisted_speedrun) with a code-golf twist, the goal of this challenge is to complete [World 1-1](https://www.youtube.com/watch?v=PsC0zIhWNww) of the original *Super Mario Bros* game for the NES in your chosen programming language in as few bytes as possible, using only the in-game controller inputs in the format I'll describe below. Your program must output to `stdout` a list of lines in this format, created specifically for this challenge:
```
up down left right start select A B
```
Starting with the first frame, each newline represents the inputs for Controller 1 for a particular frame. The order of buttons per frame does not matter, and they can be separated by any amount of non-newline whitespace. All or none or some of the button names can be included per line. For example, a simple Python program that presses the D-pad right for 3 frames and then presses A might look like this:
```
for _ in range(3): print('right')
print('A')
```
And its output (which I would feed into my emulator to verify) would be:
```
right
right
right
A
```
Here, we define 'success' as reaching the flag at the end of World 1-1 pictured above. The score for this example Python submission, if it succeeded (which it doesn't), would be **44 bytes**, or the original length of the Python program.
For an example working input file I created based on the [current fastest TAS](http://tasvideos.org/2964S.html), see this Github Gist: <https://gist.github.com/anonymous/6f1a73cbff3cd46c9e1cf8d5c2ff58e1> Note that this file completes the entire game.
There is no way to enter [subframe inputs](https://arstechnica.com/gaming/2016/07/how-to-beat-super-mario-bros-3-in-less-than-a-second/). There is also no way to enter inputs in Player 2's controller, but that also shouldn't be necessary (or useful) for completing the level or game.
The version of SMB used will be the original USA / Japan iNES ROM (md5sum 811b027eaf99c2def7b933c5208636de -- the USA version is the exact same as the Japanese version so either will work, the ROM is commonly labeled `Super Mario Bros (JU) (PRG 0)` or similar).
To test the submissions, I will run the programs, pipe their `stdout` into an input.txt file, and load them into FCEUX using this Lua script `mario.lua` I wrote for this challenge:
```
for line in io.lines('input.txt') do
local t = {}
for w in line:gmatch("%S+") do
t[w] = true;
end;
joypad.set(1, t);
emu.frameadvance();
end;
while (true) do
emu.frameadvance();
end;
```
The specific command I'll be using is `fceux mario.nes --loadlua mario.lua`. There is no time limit to the programs, though they must eventually terminate.
This is a little Bash one-liner I made to convert a FCEUX movie (.fm2) file to an input.txt for my script, if it helps:
```
cat movie.fm2 | cut -d'|' -f 3 | sed 's/\.//g' | sed 's/R/right /g' | sed 's/L/left /g' | sed 's/D/down /g' | sed 's/U/up /g' | sed 's/T/start /g' | sed 's/S/select /g' | sed 's/B/B /g' | sed 's/A/A /g' | tail -n +13 > input.txt
```
For reference, here is a full-resolution map of World 1-1 (open the image in a new tab for full resolution): [![World 1-1](https://i.stack.imgur.com/0CkEk.png)](https://i.stack.imgur.com/0CkEk.png)
(source: [mariouniverse.com](http://www.mariouniverse.com/images/maps/nes/smb/1-1.png))
Note: At first glance, this may seem like a Kolmogorov complexity challenge on my given input.txt file. However, in reality the challenge is more complex than that because (a) the input.txt I provided is definitely not the shortest possible and (b) there has never been an attempt to create the shortest possible set of keypresses for SMB in this format. The 'fewest buttons possible' known TAS is different because it allows for holding of buttons for a long time, which would add length to the desired output in this challenge.
[Answer]
# Python 2, 69 48 46 44 bytes
```
print"start\n\n"*19+(27*"A right\n"+"\n")*99
```
[See it in action on youtube!](https://www.youtube.com/watch?v=2-I1EEOlQYA)
Automatically found with (a modified version of) this hacky script:
```
start = 18
oncycle = 21
offcycle = 4
while true do
emu.poweron()
-- emu.speedmode("maximum")
starting = 0
i = 0
frames = 0
last_mario_x = -1
emu.message(start .. " " .. oncycle .. " ".. offcycle)
state = 0
while state ~= 6 and state ~= 11 and frames < 4000 do
if frames > 500 and frames % 100 == 0 then
mario_x = memory.readbyte(0x6D) * 0x100 + memory.readbyte(0x86)
if mario_x == last_mario_x then emu.message("stuck " .. mario_x .. " " .. last_mario_x); break end
last_mario_x = mario_x
end
if starting < start then
joypad.set(1, {start=1})
emu.frameadvance(); frames = frames + 1;
joypad.set(1, {})
emu.frameadvance(); frames = frames + 1;
starting = starting + 1
else
if i < oncycle then
joypad.set(1, {A=1, B=1, right=1})
i = i + 1
else
joypad.set(1, {})
i = i + 1
if i == oncycle + offcycle then
i = 0
end
end
emu.frameadvance()
frames = frames + 1
end
state = memory.readbyte(0x000E)
if state == 4 then
emu.message("success!")
os.exit()
break
end
end
if start < 30 then
start = start + 1
elseif offcycle < 10 then
start = 18
offcycle = offcycle + 1
else
offcycle = 1
oncycle = oncycle + 1
end
end
```
[Answer]
# Python 2, 107 bytes
```
i=0
print'\n'*33+'start'
for c in'~~22 + 2 2? @ F . \r0'+'@'*10:print'A B right\n'[i:]*ord(c);i^=2
```
[Answer]
# JavaScript (ES6), 59 characters
```
_=>`start
`[a="repeat"](19)+(`A right
`[a](27)+`
`)[a](99)
```
This outputs the same text as [orlp's answer](https://codegolf.stackexchange.com/a/109083/63774). I tried coming up with a better method myself, but the movies I converted to an `input.txt` file did not always play properly. Whenever I tried running the emulator from cmd, I got an error stating `"an unknown error occurred"`.
] |
[Question]
[
A challenge with simple rules but non-trivial algorithms. :-)
### Task
Take input in the form of space-separated integers:
```
N A B S
```
Where N is the side length of a 2D square matrix filled with *unique* numbers (integers) between A and B inclusive. For each row and column in this matrix, the sum is always the same: S. (In other words, the matrix is a semi-magic square).
Note:
All numbers are positive. Exception is A, which can be 0.
### Examples
For
```
3 1 10000 2015
```
a valid solution would be
[![enter image description here](https://i.stack.imgur.com/61bzW.png)](https://i.stack.imgur.com/61bzW.png)
For
```
8 1 300 500
```
a valid solution would be
[![enter image description here](https://i.stack.imgur.com/nXdkv.png)](https://i.stack.imgur.com/nXdkv.png)
### Output
You output should be an ASCII table. Example for the first example above:
```
384 159 1472
1174 499 342
457 1357 201
```
Right-aligned integers padded by spaces. The width of each column is the width of the largest integer in that column.
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. Standard loopholes apply (especially about built-ins to solve this problem). You don't have to care about wrong or otherwise impossible inputs (including negative numbers). Please provide a sample output in your answer (mandatory) for the second example above.
[Answer]
# CJam, ~~119~~ 91 bytes
```
q~:M;),>:R;(:L{{R{ML)d/-Y#)mr}$L/L<2{{M1$:+-+}%z}*:U:+__O|=R*-}gU{:s_:,:e>f{Se[}}%zSf*N*}M?
```
This is a provably correct, non-deterministic approach.
On my desktop, the second test case generally finishes in less than 10 minutes.
The first case finishes instantly. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%3AM%3B)%2C%3E%3AR%3B(%3AL%7B%7BR%7BML)d%2F-Y%23)mr%7D%24L%2FL%3C2%7B%7BM1%24%3A%2B-%2B%7D%25z%7D*%3AU%3A%2B__O%7C%3DR*-%7DgU%7B%3As_%3A%2C%3Ae%3Ef%7BSe%5B%7D%7D%25zSf*N*%7DM%3F&input=3%201%2010000%202015).
### Sample run
```
$ cjam grid.cjam <<< '8 1 300 500'
77 66 37 47 56 46 86 85
63 102 70 72 49 54 81 9
62 69 58 57 71 17 48 118
64 65 67 87 53 44 80 40
73 60 55 89 51 76 84 12
68 59 28 78 74 38 50 105
61 75 52 43 125 83 42 19
32 4 133 27 21 142 29 112
```
### Idea
Without time limits, we could just randomly generate squares until finding a valid square. This approach builds on that idea, adding two optimizations:
* Instead of pseudo-randomly generating square of side length **N**, we generate squares of side length **N-1**, add one column to form a **N × (N-1)** rectangle whose rows have sum **S**, then one row to form a square of side length **N** whose columns have sum **S**.
Since the sum of the elements of all columns will be **NS** and the sum of the elements of the first **N-1** rows is **(N-1)S**, the last row will also have sum **S**.
However, this process may generate an invalid matrix, since there's no guarantee that all elements of the last row and column will be unique or fall in the range **[A ... B]**.
* Picking a square of unique integers in **[A ... B]** and side length **N-1** uniformly at random would take way too long. We somehow have to prioritize squares that have a higher chance of resulting in a valid square of side length **N** after applying the process detailed in the previous bullet point.
Given that each row and column has to have a sum of **S**, its elements have an average of **S/N**. Thus, picking more elements close to that average should increase our chances.
For each **I** in **[A ... B]**, we pseudo-randomly pick a float between **0** and **(I - S/N)2 + 1** and sort the elements of **[A ... B]** by the picked floats. We keep the first **N2** numbers and place them in reading order in a square.
Assuming a perfectly uniform distribution of all real numbers between **0** and **(I - S/N)2 + 1** in each step, all squares have a non-zero probability of being picked, meaning that the process will finish eventually.
### Code
```
q~ e# Read all input from STDIN and evaluate it.
:M; e# Save "S" in M and discard it from the stack.
),>:R; e# Transform "A B" into [A ... B], save in R and discard.
(:L e# Save "N - 1" in L and keep it on the stack.
{ e# If L is non-zero:
{ e# Do:
R{ e# For each I in R:
ML)d/ e# Compute M/Double(L+1).
-Y# e# Subtract the result from I and square the difference.
)mr e# Add 1 and pick a non-negative Double below the result.
}$ e# Sort the values of I according to the picks.
L/ e# Split the shuffled R into chunks of length L.
L< e# Keep only the first L chunks.
2{ e# Do twice:
{ e# For each row of the L x L array.
M1$ e# Push M and a copy of the row.
:+- e# Add the integers of the row and subtract their sum from M.
+ e# Append the difference to the row.
}% e#
z e# Transpose rows and columns.
}* e#
:U:+ e# Save the result in U and concatenate its rows.
__O| e# Push two copies. Deduplicate the second copy.
=R* e# Push R if all elements are unique, an empty array otherwise.
- e# Remove the result's elements from U's elements.
}g e# If the resulting array is non-empty, repeat the loop.
U{ e# For each row in U:
:s e# Convert its integers into strings.
_:, e# Copy and replace each string with its length.
:e> e# Compute the maximum length.
f{ e# For each integer, push the maximum length; then
Se[ e# Left-pad the integer with spaces to that length.
} e#
}% e#
z e# Transpose rows with columns.
Sf*N* e# Join columns by spaces, rows by linefeeds.
}M? e# Else, push M.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 18 bytes
```
S;§f⁵
r/œ!²}s€ÇÞṪG
```
[Try it online!](https://tio.run/##ATAAz/9qZWxsef//UzvCp2bigbUKci/FkyHCsn1z4oKsw4fDnuG5qkf///8xLCA5/zP/MTU "Jelly – Try It Online")
Takes input via the command-line in the form `A, B` `N` `S`. Outputs the lexicographic ally first grid that fits
-1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!
On the one hand, it's short. On the other hand, it's incredibly inefficient. This generates
$$\frac {(B-A+1)!} {(B-A-N^2+1)!}$$
\$N\times N\$ squares to check. For example, if \$A = 1, B = 9, N = 3\$ (the example in TIO), this generates \$362880\$ \$3\times3\$ matrices to check are semi-magic. For the second test case, it generates 243427020732724848691170301000009788596908895057539171134817782742659530443034291592046861179091424965386457564096330026488754281163364761600000000000000000 \$8\times8\$ matrices.
Given enough time and memory, this would work on any input. However, on my computer, it runs out of memory for the second test case after 5 minutes
## How it works
```
S;§f⁵ - Helper link. Takes a matrix M and outputs if it's semi-magic to S
S - Column sums of M
§ - Row sums of M
; - Concatenate
f⁵ - Keep only S
r/œ!²}s€ÇÞṪG - Main link. Takes [A, B] on the left and N on the right
r/ - Reduce [A, B] by range, yielding [A, A+1, ..., B-1, B]
} - To N:
² - Square
œ! - Generate all permutations of range(A, B) of length N²
€ - Over each:
s - Slice into NxN matrices
ÇÞ - Sort the matrices by the helper link
ṪG - Take the last and format as a grid
```
] |
[Question]
[
Given a string you must move each letter (starting from the first letter) by its position in the alphabet. If you reach the end of the string you must wrap around. Non-letters don't need to be moved.
Example:
`Dog`
`D` is the fourth letter in the alphabet so we move it four spots to the right. After wrapping around, that changes the string to `oDg`. `o` is the 15th letter, (15 mod 3) = 0, so it does not move. `g` is the 7th letter - (7 mod 3) = 1, so the string becomes `goD`.
`hi*bye`
* `h` is the 8th letter, move it 8 spots - `hi*bye` => `i*hbye`
* `i` is the 9th letter, move it 9 spots - `i*hbye` => `*hbiye`
* `b` is the 2nd letter, move it 2 spots - `*hbiye` => `*hiybe`
* `y` is the 25th letter, move it 25 spots - `*hiybe` => `*hibye`
* `e` is the 5th letter, move it 5 spots - `*hibye` => `*hibey`
Non-letters don't need to be moved, but they still take up space.
* `cat` => `tca`
* `F.U.N` => `.F.NU`
* `mississippi` => `msiisppssii`
[Answer]
## CJam, ~~44~~ ~~42~~ 40 bytes
```
qN+ee_{Xa/~\+XW=eu__el=!\'@-*m<Xa+}fXWf=
```
Output contains a trailing linefeed.
[Test it here.](http://cjam.aditsu.net/#code=qN%2Bee_%7BXa%2F~%5C%2BXW%3Deu__el%3D!%5C'%40-*m%3CXa%2B%7DfXWf%3D&input=Hello%2C%0AWorld!)
### Explanation
Instead of moving the letters through the string, I repeatedly remove a letter, rotate the string accordingly, and then reinsert the letter. There's one catch for doing this: we need to be able to distinguish the beginning of the string from the end of the string (which we can't after a simple rotation). That's why we insert a linefeed at the end as a guard (letter before the linefeed is the end of the string, letter after it is the beginning). The bonus is that this automatically returns the final string to the correct rotation where the linefeed actually *is* at the end of the string.
```
lN+ e# Read input and append a linefeed.
ee e# Enumerate the array, so input "bob" would become [[0 'b] [1 'o] [2 'b] [3 N]]
e# This is so that we can distinguish repeated occurrences of one letter.
_{ e# Duplicate. Then for each element X in the copy...
Xa/ e# Split the enumerated string around X.
~ e# Dump the two halves onto the stack.
\+ e# Concatenate them in reverse order. This is equivalent to rotating the current
e# character to the front and then removing it.
XW= e# Get the character from X.
eu e# Convert to upper case.
_ e# Duplicate.
_el=! e# Check that convert to lower case changes the character (to ensure we have a
e# letter).
\'@- e# Swap with the other upper-case copy and subtract '@, turning letters into 1 to
e# 26 (and everything else into junk).
* e# Multiply with whether it's a letter or not to turn said junk into 0 (that means
e# everything which is not a letter will be moved by 0 places).
m< e# Rotate the string to the left that many times.
Xa+ e# Append X to the rotated string.
}fX
Wf= e# Extract the character from each pair in the enumerated array.
```
To see why this ends up in the right position, consider the last iteration of the `hi*bye` example. After we've processed the `e`, the enumerated string is in this position:
```
[[4 'y] [6 N] [2 '*] [0 'h] [1 'i] [3 'b] [5 'e]]
```
First, we split around the linefeed and concatenate the parts in reverse order:
```
[[2 '*] [0 'h] [1 'i] [3 'b] [5 'e] [4 'y]]
```
The linefeed would now be either at the beginning or the end of this string. But since the linefeed is just a guard that *marks* the end of the string, this means that the characters are actually in the right order. Now the linefeed is not a letter, so that the array is not rotated at all. Thus, when we append the linefeed, it goes where it belongs, and everything is in the order we're looking for:
```
[[2 '*] [0 'h] [1 'i] [3 'b] [5 'e] [4 'y] [6 N]]
```
Some additional results if someone wants to compare longer test cases:
```
Hello, World!
,W oeHlo!lrld
Programming Puzzles & Code Golf
ago fgliPomomnrr elP& uC dezzsG
The quick brown fox jumps over the lazy dog
t eg chbi ko qfTounyzrj omw epx ueoahs rlvd
abcdefghijklmnopqrstuvwxyz
aqbrcdsetfguhivjwklxmnyozp
zyxwvutsrqponmlkjihgfedcba
abcdefghijklmnopqrstuvwxyz
```
I like that last one. :)
[Answer]
# Ruby 125 ~~130 132 139~~ bytes
```
->q{a=q.chars.map{|c|[c,c=~/[a-z]/i&&c.ord%32]}
while i=a.index{|c,s|s}
c,s=a.delete_at i
a.insert (i+s)%q.size,[c]
end
a*''}
```
Online demo with tests: <http://ideone.com/GYJm2u>
The initial (ungolfed version): <http://ideone.com/gTNvWY>
*Edit:* Big thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) for his suggestions!
*Edit 2*: fixed character count (I was initially counting CRLF line endings.)
[Answer]
# Python 3, ~~278~~ ~~275~~ ~~273~~ ~~270~~ ~~260~~ ~~258~~ ~~249~~ ~~248~~ ~~243~~ 238 bytes
I should really golf this down better, but here is my solution, with thanks to [katenkyo](https://codegolf.stackexchange.com/users/41019/katenkyo) for his help with the logic, and to [Cyoce](https://codegolf.stackexchange.com/users/41042/cyoce) and [Mego](https://codegolf.stackexchange.com/users/45941/mego) for their help with the golfing.
**Edit:** At last, I got it down to one comparison statement. WOO! (And yes, I could move that `z=-z` into `a,m=m,a` bit, but that doesn't save bytes and it muddled the code more than I thought was necessary)
**Edit:** Byte count was off.
```
def m(s):
l=len(s);r=range(l);p=[[i,s[i]]for i in r]
for i in r:
if s[i].isalpha():
a=p[i][0];p[i][0]=m=(a+ord(s[i])%32)%l;z=1
if a>m:a,m=m,a;z=-z
for j in r:p[j][0]-=z*(j!=i)*(a<=p[j][0]<=m)
return''.join(dict(p).values())
```
**Ungolfed:**
```
def move(string):
length = len(string)
places = [[i,string[i]]for i in range(length)]
for index in range(length):
char = string[index]
if char.isalpha():
a = places[index][0]
mov = (a + ord(char)%32) % length
places[index][0] = mov
for j in range(length):
k = places[j][0]
if a <= k <= mov and j!=index:
places[j][0]-=1
elif mov <= k <= a and j != index:
places[j][0]+=1
return''.join(dict(places).values())
```
[Answer]
# [J](https://www.jsoftware.com), 92 84 bytes
```
{~(g=.i.@#@[)([/:g(]+]-*@-)#@[|g+(={.)*1{])~&;/@([|.@;;/@,.)[:(26&|+52&>)Alpha_j_&i.
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrcTOkuk4j3VYvU89B2SFaUyNa3ypdI1Y7VlfLQVcTKFKTrq1hW62nqWVYHatZp2at76ARXaPnYA1k6OhpRltpGJmp1WibGqnZaTrmFGQkxmfFq2XqQc1O1ORKTc7IV0hTUHfTC9XzU4dzkxNLEJzczOJiECooyEQIViCYVZUV5WWlJcVFhQX5ebk52VmZGelpqSnJSYnqEIsWLIDQAA)
*-8 thanks to rdm!*
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~46~~ 45 bytes
-1 byte from @Traws' improvement
```
{x{?[x^z;(#x)!y+x?z;z]}/[;a*27>a:96!_x].&=#x}
```
[Try it online!](https://ngn.codeberg.page/k/#eJxNjr1ugzAURnc/BSFVlVDFliqFqlhJlihjtkyINo5rjBXAFLuVAdFnr3+WXN3lnG85ZTaZ6ZCbjxGvlma9GF7MYcRjMaMck+T1bU+y93TxaQr4vFuaGQCdTU/58NdnZWTwVd7x6loSUWODB9yvixnoPD5KHuOYy2NcOKxEchuYNUklbmwIkhJtjaYk4Ale4NkKeILnS1CNUMp91wk7NEoI1XWWhZ0BApXWncoQovKLcVmXUGlC78zQirScQSob9P3DlBayVShNt9sU1Uxr1qsNZ3rTyF/RcgAie7Y32u0jG+wx9DoTgr20vc7YYI++1wkf7NVDrxseggH4B+Rzbnw=)
A bit complicated to unpack. Takes input as `x`.
* `&=#x` generate two copies of `0..count[input]` (e.g., `(0 1 2 3 4;0 1 2 3 4)`)
* `{...}/[;...].` set up a seeded-reduce, fixing the second (`y`) arg, and passing the pair of ranges as the first (`x`) and third (`z`) args. `x` represents the to-be-shuffled indices of the input, `y` the number of positions to shift each character in the input, and `z` the *initial* position of each character
+ `a*27>a:96!_x` determine the number of positions to shift each character in the input; non-letters are shifted `0` places, leaving them in the same position
+ `{?[x^z;(#x)!y+x?z;z]}/` set up a `?[x;indices;values]` splice. each iteration is run on the original input (`x`), a single number of positions to move (`y`), and a single initial position (`z`)
- `x^z` remove the current item being shifted
- `(#x)!y+x?z` determine where it should be after being moved (offset by where it is *now* (`x?z`), and with wrap-around `(#x)!`)
- `z` re-insert the value/index at the correct position
* `{x{...}...}` index back into the original input, and (implicitly) return
] |
[Question]
[
Recently I've been playing a game called Alcazar. It is a board puzzle game where your goal is to enter from one door, pass through all squares, and exit through another door. The only rules are:
* Enter once, leave once;
* Pass through all squares;
* Do not pass through a square more than once
The image below shows an example of an Alcazar board and, at its right, the solved puzzle (of course this is an easy one):
[![Sample Alcazar Puzzle](https://i.stack.imgur.com/3UUqp.jpg)](https://i.stack.imgur.com/3UUqp.jpg)
You can find more puzzles at <http://www.theincrediblecompany.com/try-alcazar> and download the game at PlayStore (P.S.: Not an advertisement).
My problem is that I almost finished the game, except for one level. I simply cannot find a way to solve it. So the challenge I propose is: create an algorithm that solves any normal1 solvable2 Alcazar level.
Of course, I'm not asking for anyone to build an image interpreter to read the image and solve the puzzle (or am I?). So I redrew the above puzzle using box drawing characters. The puzzle and its solution would be like this:
```
╔═══════╗ ╔═══════╗
║▒ ▒ ▒ ▒║ ║┌─┐ ┌─┐║
║ ║ ║ ║│ │ │║│║
╣▒ ▒ ▒║▒╠ ╣│ └─┘║└╠
║ ══╦═╩═╣ ║│══╦═╩═╣
║▒ ▒║▒ ▒║ ║└─┐║┌─┐║
║ ║ ║ ==> ║ │║│ │║
╣▒ ▒║▒ ▒║ ╣┐ │║│ │║
║ ║ ║ ║ ║│║│║│ │║
╣▒║▒ ▒ ▒║ ╣│║└─┘ │║
║ ║ ║ ║│║ │║
║▒ ▒ ▒ ▒║ ║└─────┘║
╚═══════╝ ╚═══════╝
```
In the board above, `▒` are the cells to be filled.
One can observe that there is a vertical and horizontal gab between the cells. This is because I had to insert a space between cells to add the walls. This means that the only important cells are the ones above, below, to the left, and to the right of each cell. The diagonals could be removed without information loss. For example, in the board below, both represent the same puzzle:
```
╔════╩╗ ═ ═ ╩
║▒ ▒ ▒║ ║▒ ▒ ▒║
║ ═══ ║ ═
║▒ ▒ ▒║ == ║▒ ▒ ▒║
║ ║
║▒ ▒ ▒║ ║▒ ▒ ▒║
╚╦════╝ ╦═ ══
```
This is also valid for the solutions. That is, it is not required to connect the cells:
```
╔════╩╗ ╔════╩╗ ╔════╩╗
║▒ ▒ ▒║ ║┌───┘║ ║┌ ─ ┘║
║ ═══ ║ ║│═══ ║ ║ ═══ ║
║▒ ▒ ▒║ == ║└───┐║ => ║└ ─ ┐║
║ ║ ║ │║ ║ ║
║▒ ▒ ▒║ ║┌───┘║ ║┌ ─ ┘║
╚╦════╝ ╚╦════╝ ╚╦════╝
```
In the example above, both solutions mean the same.
Yes, the test cases. Here they are:
### Puzzle 1
```
╔════╩╗ ╔════╩╗
║▒ ▒ ▒║ ║┌ ─ ┘║
║ ═══ ║ ║ ═══ ║
║▒ ▒ ▒║ => ║└ ─ ┐║
║ ║ ║ ║
║▒ ▒ ▒║ ║┌ ─ ┘║
╚╦════╝ ╚╦════╝
```
### Puzzle 2
```
╔═════╗ ╔═════╗
║▒ ▒ ▒║ ║┌ ─ ┐║
║ ║ ║ ║ ║ ║
╣▒ ▒║▒║ ╣└ ┐║│║
║ ║ ║ ║ => ║ ║ ║ ║
╣▒║▒ ▒╠ ╣┐║│ │╠
║ ║ ║ ║ ║ ║
║▒ ▒ ▒║ ║└ ┘ │║
╚════╦╝ ╚════╦╝
```
### Puzzle 3
```
╔════╩══╗ ╔════╩══╗
║▒ ▒ ▒ ▒║ ║┌ ┐ └ ┐║
║ ║ ║ ║ ║ ║ ║ ║
╣▒║▒ ▒║▒╠ ╣┘║└ ┐║│╠
║ ╚══ ║ ║ ║ ╚══ ║ ║
║▒ ▒ ▒ ▒╠ => ║┌ ─ ┘ │╠
║ ═══ ║ ║ ═══ ║
║▒ ▒ ▒ ▒║ ║│ ┌ ┐ │║
║ ║ ║ ║ ║ ║
║▒ ▒║▒ ▒║ ║└ ┘║└ ┘║
╚═══╩═══╝ ╚═══╩═══╝
```
### puzzle 4
```
╔═══════╗ ╔═══════╗
║▒ ▒ ▒ ▒║ ║┌ ┐ ┌ ┐║
║ ║ ║ ║ ║ ║
╣▒ ▒ ▒║▒╠ ╣│ └ ┘║└╠
║ ══╦═╩═╣ ║ ══╦═╩═╣
║▒ ▒║▒ ▒║ ║└ ┐║┌ ┐║
║ ║ ║ => ║ ║ ║
╣▒ ▒║▒ ▒║ ╣┐ │║│ │║
║ ║ ║ ║ ║ ║ ║ ║
╣▒║▒ ▒ ▒║ ╣│║└ ┘ │║
║ ║ ║ ║ ║ ║
║▒ ▒ ▒ ▒║ ║└ ─ ─ ┘║
╚═══════╝ ╚═══════╝
```
### Puzzle 5
```
╔══╩══════╗ ╔══╩══════╗
║▒ ▒ ▒ ▒ ▒║ ║┌ ─ ┐ ┌ ┐║
║ ║ ║ ║ ║ ║
║▒ ▒║▒ ▒ ▒╠ ║└ ┐║└ ┘ │╠
║ ╠════ ║ ║ ╠════ ║
║▒ ▒║▒ ▒ ▒║ => ║┌ ┘║┌ ─ ┘║
║ ║ ║ ║ ║ ║
║▒ ▒║▒ ▒ ▒╠ ║└ ┐║└ ─ ─╠
║ ╠═════╣ ║ ╠═════╣
║▒ ▒║▒ ▒ ▒║ ║┌ ┘║┌ ─ ┐║
║ ║ ║ ║ ║ ║
║▒ ▒ ▒ ▒ ▒║ ║└ ─ ┘ ┌ ┘║
╚══╦═══╦══╝ ╚══╦═══╦══╝
```
### Puzzle 6
```
╔═══════════╗ ╔═══════════╗
║▒ ▒ ▒ ▒ ▒ ▒║ ║┌ ┐ ┌ ┐ ┌ ┐║
║ ║ ║ ║
║▒ ▒ ▒ ▒ ▒ ▒║ ║│ └ ┘ └ ┘ │║
║ ═══ ║ ║ ═══ ║
║▒ ▒ ▒ ▒ ▒ ▒║ ║└ ┐ ┌ ─ ─ ┘║
║ ═══ ║ ║ ═══ ║
╣▒ ▒ ▒ ▒ ▒ ▒╠ => ╣┐ │ │ ┌ ┐ ┌╠
║ ║ ║ ║
║▒ ▒ ▒ ▒ ▒ ▒║ ║│ │ │ │ │ │║
║ ║ ║ ║ ║ ║ ║ ║
║▒ ▒║▒ ▒║▒ ▒║ ║│ │║│ │║│ │║
║ ║ ║ ║ ║ ║ ║ ║
║▒ ▒ ▒ ▒ ▒ ▒║ ║└ ┘ └ ┘ └ ┘║
╚═══════════╝ ╚═══════════╝
```
### Puzzle 7
```
╔════╩════════╦╩╗ ╔════╩════════╦╩╗
║▒ ▒ ▒ ▒ ▒ ▒ ▒║▒║ ║┌ ─ ─ ─ ─ ─ ┐║│║
║ ║ ║ ║ ║ ║ ║ ║ ║ ║
║▒║▒ ▒ ▒ ▒║▒ ▒ ▒║ ║│║┌ ─ ─ ┐║┌ ┘ │║
║ ║ ║ ═══ ║ ║ ║ ║ ║ ═══ ║ ║
║▒ ▒║▒ ▒ ▒ ▒ ▒ ▒╠ ║│ │║┌ ─ ┘ └ ┐ │╠
║ ║ ║ ║ ║ ║
║▒ ▒ ▒ ▒ ▒ ▒ ▒ ▒║ ║│ │ └ ┐ ┌ ┐ └ ┘║
║ ║ ║ ══╣ ║ ║ ║ ══╣
║▒ ▒ ▒║▒║▒ ▒ ▒ ▒║ ║│ └ ┐║│║│ └ ─ ┐║
║ ║ ║ ║ ║ ║ ║ ║
║▒ ▒ ▒ ▒ ▒ ▒ ▒ ▒║ ║│ ┌ ┘ │ └ ┐ ┌ ┘║
║ ║ ══╣ => ║ ║ ══╣
║▒ ▒ ▒ ▒ ▒ ▒║▒ ▒║ ║└ ┘ ┌ ┘ ┌ ┘║└ ┐║
╠══ ║ ╚══ ║ ╠══ ║ ╚══ ║
║▒ ▒ ▒ ▒ ▒║▒ ▒ ▒║ ║┌ ┐ └ ┐ │║┌ ─ ┘║
║ ║ ║ ║ ║ ║ ║ ║ ║ ║
║▒ ▒ ▒║▒║▒ ▒ ▒ ▒║ ║│ └ ┐║│║│ └ ─ ┐║
║ ║ ║ ║ ╔══ ║ ║ ║ ║ ║ ╔══ ║
║▒║▒ ▒ ▒ ▒║▒ ▒ ▒║ ║│║┌ ┘ │ │║┌ ┐ │║
║ ║ ║ ║ ║ ║ ║ ║ ║ ║
║▒ ▒ ▒ ▒║▒ ▒ ▒ ▒║ ║│ └ ─ ┘║└ ┘ │ │║
║ ╚══ ║ ║ ╚══ ║
║▒ ▒ ▒ ▒ ▒ ▒ ▒ ▒║ ║└ ─ ─ ─ ─ ─ ┘ │║
╚════╦═╦═╦═════╦╝ ╚════╦═╦═╦═════╦╝
```
### Puzzle 8 (Sorry, I really don't have the solution to this one)
```
╔══╩╦══╩═══╩═╩═╩═══╩╗
║▒ ▒║▒ ▒ ▒ ▒ ▒ ▒ ▒ ▒║
║ ║ ║
╣▒ ▒║▒ ▒ ▒ ▒ ▒ ▒ ▒ ▒║
║ ╚══ ╔══ ╔═══╣
╣▒ ▒ ▒ ▒║▒ ▒ ▒ ▒║▒ ▒╠
║ ║ ╔══ ║ ║
╣▒ ▒ ▒ ▒ ▒ ▒║▒ ▒ ▒ ▒╠
║ ║ ║
║▒ ▒ ▒ ▒ ▒ ▒ ▒ ▒ ▒ ▒╠
║ ║ ║
╣▒ ▒ ▒ ▒ ▒ ▒║▒ ▒ ▒ ▒╠
║ ╔═══╗ ╚══ ║
╣▒ ▒║▒ ▒║▒ ▒ ▒ ▒ ▒ ▒║
║ ║ ║ ║
╣▒ ▒║▒ ▒║▒ ▒ ▒ ▒ ▒ ▒╠
║ ══╝ ║ ╔══ ║
║▒ ▒ ▒ ▒║▒ ▒ ▒ ▒║▒ ▒║
║ ══╗ ╚══ ╔══ ║ ║
╣▒ ▒ ▒║▒ ▒ ▒║▒ ▒ ▒ ▒╠
║ ║ ║ ║ ║
╣▒ ▒ ▒ ▒ ▒ ▒ ▒ ▒║▒ ▒║
║ ═══ ══╗ ║ ║
╣▒ ▒ ▒ ▒ ▒ ▒║▒ ▒ ▒ ▒╠
╠══ ║ ║ ╔══ ║
║▒ ▒║▒ ▒ ▒ ▒ ▒ ▒║▒ ▒╠
║ ╚══ ║ ║ ║ ║
╣▒ ▒ ▒ ▒║▒ ▒║▒ ▒ ▒ ▒╠
║ ║ ║ ║
║▒ ▒ ▒ ▒ ▒ ▒ ▒ ▒ ▒ ▒║
╚══╦═══╦═══╦═╦═╦═╦═╦╝
```
### Input
The input of your code can have any representation as long as it follow these rules:
1. It must be a graphical input. So it is not possible to read a coordinate list, for example.
2. Horizontal walls, vertical walls, and doors must be distinct, and they must be made of a visible character (no blank characters).
3. The `▒` can be replaced by blanks. I just used a different character to highlight them.
### Output
The output can also have any representation as long as it follows these rules:
1. It must be a graphical output. That is, one can see the path by looking at it.
2. Rule number one implies that the path characters be different. That is, there are going to be at least 6 path characters; horizontal, vertical, and corners.
3. For the answer to be valid, the output must be the same board as the input (obviously) with all the cells (in my representation, the `▒`) filled. Filling the gaps between the cells is optional.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
1 There are some Alcazar levels that have optional cells and tunnels. These will not be considered.
2 There are some Alcazar boards that are impossible.
[Answer]
# [Python 3](https://docs.python.org/3/), 809 728 723 714 693 688 684 663 657 641 639 627 610 571 569 bytes
**Edit:** Saved 55 bytes thanks to [@Felipe Nardi Batista](https://codegolf.stackexchange.com/users/66418/felipe-nardi-batista)
Does not run the last test case in 60 seconds on TIO, but should work correctly nonetheless. Returns a list of coordinates for the path. Some
400 of the bytes are used to get the data lists from the I/O.
```
A=enumerate
I,J="═║"
B=range
L=len
K=-1
Z=1,0
X=0,1
C=K,0
V=0,K
E=lambda a,b,p:(((a,b)in d)*L(p)==H*h)*p or max([E(q+a,w+b,p+[(q+a,w+b)])for q,w in y[a][b]if~-((q+a,w+b)in p)*-h>w+b>K<q+a<H]+[[]])
x=input().split("\n")
h=L(x[0])//2
H=L(x)//2
y=[[{C,Z,V,X}for i in B(h)]for j in B(H)]
d=[]
exec('d+=[(%s,i)for i,a in A(x[%s][1::2])if I<a]\nfor i,u in A(x[%s:%s:2]):\n d+=[(i,0)]*(J<u[0])+[(i,h-1)]*(J<u[K])\n for j,w in A(u[%s:%s:2]):\n if"%s"==w:y[i][j]-={%s};y[i+%s][j+%s]-={%s}\n'*2%(0,*X,"",2,K,J,X,*X,V,H-1,K,2,K,1,"",I,Z,*Z,C))
print(max(E(*D,[D])for D in d))
```
[Try it online!](https://tio.run/##pVZfS@NAEH/ufoolUNxNt2fTe8u5gv@gWh/6JOK6SGpTG6lpbFptEe8zeIc9QRAEQfBr9Yt4s0mTNm2iPa@km53ZHzO/nZnNjjfstTru9/fTTsPGHHc1TUPoxOs6bg/E4I0adjOckQE1Ue6s3albbVxDuRpABgB3XK@v4MEbRVLbuqg3LBNfvW9w2@1f2F2rZ6Ndtse18ehuPPqloU3etdwzG@3ztu2iKi8a6IgbrIQOeYkZaItXYX4A8yra4aE9bLE680xCCEyo4@IG1feJRzmv6C2qe7jTxRfWgIgdclmw2HUB0AURzamkTQBcsmsgi4fCkqIunebPIokRoPeoXmytg7BeXQP1WkUWhJCSogEPNkfoN99rOz2iHbsaRS2@TwaiJOnqahlVlBDMhlyImy12xA7Y4a3y6iifm6RFpZLOQ6lCJWpwIZE9sE/JSqPABcn7zAl4OsxSqA0wn/elMEyzLKnTxLtrljx2Q0R/ijDhAYB5DFFRdhxWolIne2t9xa6gFK2iEamqkgIwoBKGY4P0k0aw09Tyvsb5tTkUjhTnsshv8v7tD5AKitC5GkPdsbuil/OkxPRDpmmszKpsjx0q6YBVigaISmWotV2IiX7EtihFYVmpfO0QfZuJ7TA/2zhILH2PCjGsyLi0wopDQbH2bL93cmr5tg8LQunGo/ugwOLnbTx6QFBw4z@/8eQPktLgGIUnmhSM@mWtPo5Hr0lnT8CApdKIn3kyKc4mDl@SiGB8ThB/jXYI48uM3cRsYjkeZywv4qL/LDIreFnBSQQoNQZpYXqbCeZbMn9zY2peFyngzCBH1Ke/rLAsY@sxrqHJXiYWZwvgZS6d6V5md/OMpiwjT/fTal3gjJewPmsTJ@KQnsTs3X9m6SuskhF7SMQWf1y6S2Z8gfM/20sev6e5nd9nfk0@z/eUabT/tMrKyvzCEf0gY8n3MrW0DN@7BHf8XzX6nNhtxglAS1ZASp09zkfzE74feUo/qV89V4mP5uzdsjhPHdWHVSKkrtErdY1O70dhFg0JDVzQaaiGj6JceAHXYNaGdqUErYG6jD1hBD2KpwzUaMGgcf8SNGwBqEYBD0sS5cJOpKXW404P1sFXri1aAJMwGlKqHjHyqbcZ9m2Phz3UREnf/wI)
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 319 bytes
```
i←N⍴j←⍳1+n←×/N←⌊2÷⍨⍴a←⎕⋄e←↑⊃,/{(,~'#='∊⍨a[(⍵⌽⍳2)∘+¨2×⍳N+⍵=⍳2])/,2,/[⍵]⊃,[⍵]/n i n}¨⍳2
r←{e g c←⍵⋄d←+/j∘.=∊g⋄e⌿⍨←(≠/c[e])∧2>⌈/d[e]⋄n≡≢g:g⍪j/⍨d=1⋄0≡≢e:0⋄2>⌊/d+D←+/j∘.=,e:0⋄u←,¯1↑e←e[⍒⌊/D[e];]⋄e↓⍨←¯1⋄0≢r←∇e(g⍪u)(c-(-/c[u])×c=c[⊃u]):r⋄∇e g c}e(0↑e)j
a[1+2×⍳N]←' ??┌?─┐┬?└│├┘┴┤┼'[2⊥(↑(⊂i),¨¨{⊖∘⍉⍣⍵⊢n⍪¯1↓⌽∘⍉⍣⍵⊢i}¨⍳4)∊↓r⍪⌽r]
a
```
[Try it online!](https://tio.run/##jVRRa9pQFH7Pr7hwH0wwGpVBwRn7UnwY0qe@SYQQgyjFDqXCKB2jG04zU9o1XfswxuY2JqOwh7XsZWOg/@T8EXdOEs1NtGWKeM893/3O951zE/PpfqbxzNw/aGasfbPXa1kLOL1sHcDgLCfB8HVl0cLlLri3bfwH92c@3cHF/ErbpXjsFOa/wJ1i3qT49BLevLJpNTgH56WqHcnq8xTXUzB0EGbWZHDvYPwHiQoKDK/Ts2lhfoXRbhoTOm0biqYWVK2GsUEU/kLrsBbrHM@mhJC6WODIZk1m@ZrusGYDV2mtjZRZHWs1fRnjvyRtcCbD6KNm1WwDS34rlGE81BoYIaYDo08wmjSLTXC/tzWEN/Q87ueCfbuYw4BOOFojvSPUUIPUIW6psx95tEuubRT7lsA7SP/YCHpxEYgglE88IfnYWlumooeKbGXkDMo7NJT5laVbNXSN62IX4QQjn8e2nKMaSlsya/l02DMDiVJsexu8Mf5egHcG3g2uPPBOwHsP3jV4t@B9Ae93qlYA56uMHDI4Jy1FnU1n0yNw3qEbcEfgfqY@OpMOSvL9XNCU4rlW0P9HCg1zcNFFKIK6hmQuUCfdFnK2JzF/PihxNOn5A/pQxBxyqFi6R67wmqDyFC3xnrh3x@De0PlFRdqTKjp@6lsSzzL8cokzjBkXYvpEcbVPB55I0uqwvhUDcwSXKPJjHsaEKPtxjIyO90WyekTHQgImUHCfpEoKVzQBMYvpjsQsy/FVwXpSf7IkE1wsS6JMPFgSqCL6krDHV3s8ZoHFpFXDupGMelKIWEL0sHRb1iO//H/xgoFNeEEeTbm/1qekxKhfbI1GzMVHI@Yow1a9Fsf5EOeG0d6TY2s9T17f@nKzX49bi65wKCS8Fjy7GqQw4vC5Weu@aOl@W4mrF7amtHxQsvwezEM8S9URT6SaS2W/8QGimhgPX6uVeAtkNzyhrBKOcnN/RNXCo7CmuRrq2uQreF343/DF8Q8 "APL (Dyalog Classic) – Try It Online")
Input uses `=#F7LJ<>^v.` instead of `═║╔╗╚╝╣╠╩╦▒` in order to fit in the [classic charset](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/).
All test cases except for the last one pass in a few seconds.
The last test takes 47 min on my computer and yields no solution.
When the resulting path uses a door near a corner it may be rendered incorrectly (it's as if the trail forks and passes through an extra imaginary door), but it's still discernable and unambiguous.
[Answer]
# JavaScript (ES6), 274 bytes
Input as a multiline string, each line terminated with a newline character. The doors are marked with character '2'
Output as a multiline string with the path marked by character '1', very easily discernable.
This is a *Depth First Search*, trying all paths and backtraking when stuck. It's not efficient at all, but can solve puzzles 1 .. 6 in a less than 1 minute.
```
z=>(w=z.search`
`+1,t=(w-2)*(z.length/w-1)/4,z=[...z],R=(p,l,q)=>[1,-1,w,-w].some(d=>l<t?z[q=p+d]<1&z[q+d]<1&&(R(q+d,++z[q]+l)||--z[q]):z[p+d]>1&&--z[p+d],++z[p])||--z[p],z.some((c,i)=>-c&&(x=i%w,R(i<w?i+w:x?x>w-3?i-1:i-w:i+1,--z[i])||++z[i]*0))&&z.join``.replace(/0/g,' '))
```
*Less golfed*
```
z => (
w = z.search`\n`+1, // board width and offset to next row
t = (w-2)*(z.length/w-1)/4, // total size of board, number of cells that must be filled
z = [...z], // convert string to array
d = [1, -1, w, -w], // delta to next position in all directions
// recursive search
// given a current position, try to move in all directions
// if the board is not full, look for an emoty cell
// if the board is full, look for a door
R = (p, // current position
l, // fill level
q // parameter used as a local variable
) => (
++z[p], // mark current position
// .some will terminate early if the called function returns true
// in case of return true the recursive function returns all way up leaving the path marked
// in case of return false we need to unmark path and backtrack
d.some( d => // for each direction, offset in d
l < t // check if board is full
? z[q=p+d] < 1 & z[q+d] < 1 // not full, try to advance
&& (++z[q], // mark intermediate cell
R(q+d, 1+l) // recursive call incrementing fill level
|| --z[q] // if R return false, backtrack: unmark intermediate cell
)
: z[p+d] > 1 && --z[p+d]
) // full, ok only if I find a door nearby
|| --z[p], // if some returns false, unmark and backtrak
// look for doors and for each door call R
// when R returns true, stop and return the marked board
// if R returns false for each door, no solution, return false
z.some((c,i) =>
-c && // if numeric and != 0
(x = i%w,
z[i]=1, // marking starting position (door)
R(i<w ? i+w : x ? x > w-3 ? i-1 : i-w : i+1, 1)
|| (z[i] = 2, false) // if R returned false, unmark a return false
)
) && z.join``.replace(/0/g,' ')
)
```
Inside the test snippet there is a solution using a DFS with some constraint that solves puzzle 7 in less than a minute (on my PC). Puzzle 8 has no solution.
Constraints:
* All empty cells must be reachable from the current cell - the empty space must not be split in two parts
* There must be a reachable door
* A configuration of cells cannot be explored more than one time
* Cannot skip a cell that has only one empty adjacent cell
**Test**
Beware, puzzle 7 is well beyond the timeout for javascript execution in any browser (using the Short and Slow solver)
```
var Short=
z=>(w=z.search`
`+1,t=(w-2)*(z.length/w-1)/4,z=[...z],R=(p,l,q)=>[1,-1,w,-w].some(d=>l<t?z[q=p+d]<1&z[q+d]<1&&(R(q+d,++z[q]+l)||--z[q]):z[p+d]>1&&--z[p+d],++z[p])||--z[p],z.some((c,i)=>-c&&(x=i%w,R(i<w?i+w:x?x>w-3?i-1:i-w:i+1,--z[i])||++z[i]*0))&&z.join``.replace(/0/g,' '))
var Fast=
b=>{
N=0
console.clear()
F=(b,p,n) => D.reduce((n,d) => b[p+d] < 1 && b[p+d+d] < 1? F(b, p+d+d, n) : n, n+1, b[p]=1)
A=(s, f, o, q, k)=>{
D.map(d => b[s[1] + d] == 2 && (++o, q = s[1] + d));
++b[s[0]];
if (++f < t)
{
if (o < m && !K[k=b.reduce((k,c,i)=>c>3?k+' '+i:k,s[1])] && F(b.slice(), s[K[k] = 1], f) >= t
&& R(D.reduce((n,d) =>(b[s[1] + d] == 0 && b[s[1] + d + d ] == 0 && n.push([s[1] + d, s[1] + d + d ]),n),[]),f,o,b[s[1]]=4))
return 1;
}
else
{
b[s[1]] = 4;
if (q) return b[q]++;
}
--b[s[0]]
b[s[1]]=0
}
R=(s, f, o)=>{
if (!s[1]) return A(s[0], f, o);
var e, n, z=[];
if (s.some(s =>(
n = D.reduce( (n,d) => b[s[1]+d]>1 || (b[s[1]+d]<1 && b[s[1]+d+d]<1) ? n+1 : n, 0),
n>2 ? !z.push(s)
: n>1 ? !z.unshift(s)
: n>0 && (e||(e=s,0))
))) return 0
if (e) return A(e, f, o);
return z.some(s => A(s, f, o))
}
w = b.search`\n` + 1;
h = b.length / w;
t = (w - 2) * (h - 1) / 4;
D = [ 1, -1, w, -w ];
b = [...b];
K = {};
s = [];
b.forEach( (c,i) => -c ?
m = s.push( [i,i < w ? i + w : (x = i % w) > w - 3 ? i - 1 : x ? i - w : i + 1]):0
)
R(s, 0, 0);
return b.join``.replace(/\d/g, c => ' oXOo'[c])
}
Out=(e,s)=>e.textContent = s
function Test(num)
{
var puzzle = document.getElementById('Z'+num).textContent;
var solver = MF.checked ? Fast : Short
Out(S,'...wait...')
Out(T,'');
var t0=performance.now()
setTimeout(_=>(
Out(S,solver(puzzle)),Out(T,((performance.now()-t0)/1000).toFixed(3)+' sec')
),10)
}
```
```
td { border: 1px solid #000; font-family: helvetica; font-size:12px; vertical-align: top; }
pre { line-height: 13px; }
```
```
Short and slow <input type='radio' value='S' name='M' id='MS'>
Long and faster <input type='radio' checked value='F'name ='M' id='MF'>
<table >
<tr>
<td id=T>Solution</td>
<td>Puzzle 1<input type='radio' name='T' onclick="Test(1)"></td>
<td>Puzzle 2<input type='radio' name='T' onclick="Test(2)"></td>
<td>Puzzle 3<input type='radio' name='T' onclick="Test(3)"></td>
<td>Puzzle 4<input type='radio' name='T' onclick="Test(4)"></td>
<td>Puzzle 5<input type='radio' name='T' onclick="Test(5)"></td>
<td>Puzzle 6<input type='radio' name='T' onclick="Test(6)"></td>
<td>Puzzle 7<input type='radio' name='T' onclick="Test(7)"></td>
</tr>
<tr>
<td><pre id=S></pre></td>
<td><pre id='Z1'>╔════2╗
║ ║
║ ═══ ║
║ ║
║ ║
║ ║
╚2════╝
</pre></td>
<td><pre id='Z2'>╔═════╗
║ ║
║ ║ ║
2 ║ ║
║ ║ ║ ║
2 ║ 2
║ ║ ║
║ ║
╚════2╝
</pre></td>
<td><pre id='Z3'>╔════2══╗
║ ║
║ ║ ║ ║
2 ║ ║ 2
║ ╚══ ║ ║
║ 2
║ ═══ ║
║ ║
║ ║ ║
║ ║ ║
╚═══╩═══╝
</pre></td>
<td><pre id='Z4'>╔═══════╗
║ ║
║ ║ ║
2 ║ 2
║ ══╦═╩═╣
║ ║ ║
║ ║ ║
2 ║ ║
║ ║ ║ ║
2 ║ ║
║ ║ ║
║ ║
╚═══════╝
</pre></td>
<td><pre id='Z5'>╔══2══════╗
║ ║
║ ║ ║
║ ║ 2
║ ╠════ ║
║ ║ ║
║ ║ ║
║ ║ 2
║ ╠═════╣
║ ║ ║
║ ║ ║
║ ║
╚══2═══2══╝
</pre></td>
<td><pre id='Z6'>╔═══════════╗
║ ║
║ ║
║ ║
║ ═══ ║
║ ║
║ ═══ ║
2 2
║ ║
║ ║
║ ║ ║ ║
║ ║ ║ ║
║ ║ ║ ║
║ ║
╚═══════════╝
</pre></td>
<td><pre id='Z7'>╔════2════════╦2╗
║ ║ ║
║ ║ ║ ║ ║
║ ║ ║ ║
║ ║ ║ ═══ ║ ║
║ ║ 2
║ ║ ║
║ ║
║ ║ ║ ══╣
║ ║ ║ ║
║ ║ ║ ║
║ ║
║ ║ ══╣
║ ║ ║
╠══ ║ ╚══ ║
║ ║ ║
║ ║ ║ ║ ║
║ ║ ║ ║
║ ║ ║ ║ ╔══ ║
║ ║ ║ ║
║ ║ ║ ║ ║
║ ║ ║
║ ╚══ ║
║ ║
╚════2═2═2═════2╝
</pre></td>
</tr>
</table>
```
] |
[Question]
[
*Disclaimer: This does not do any justice on the rich topic of elliptic curves. It is simplified a lot. As elliptic curves recently got a lot of media attention in the context of encryption, I wanted to provide some small insight how "calculating" on an elliptic curve actually works.*
### Introduction
Elliptic curves are sets of points \$(x,y)\$ in the plane of the form \$y^2 = x^3+Ax+B\$. (Additionally, \$4A^3+27B^2 ≠ 0\$ to avoid nasty singularities.) You can consider these curves in any field. If you use the field of real numbers, the curves can be visualized and they look like this:
[![two examples of elliptic curves](https://i.stack.imgur.com/vf8mP.png)](https://i.stack.imgur.com/vf8mP.png)
[Source](https://commons.wikimedia.org/wiki/File:ECClines-3.svg)
The special thing about these curves is that they have a *built in* arithmetic operation that is the analogue of addition. You can add and subtract points, and this operation is both associative and commutative (an abelian group).
### How does addition work?
Note: addition of points on elliptic curves is not intuitive. This kind of addition is defined the way it is because it has certain nice properties. It's weird, but it works.
As elliptic curves form a group, there is an *additive identity* that is the equivalent of 0. That is, adding \$0\$ to any point will not change the result. This additive identity is the "point" at infinity. All lines on the plane include this point at infinity, so adding it makes no difference.
Let's say that any given line intersects the curve at three points, which may be \$0\$, and that the sum of these three points is \$0\$. Keeping that in mind, take a look at this image.
[![elliptic curve addition special cases](https://i.stack.imgur.com/bspCG.png)](https://i.stack.imgur.com/bspCG.png)
[Source](https://en.wikipedia.org/wiki/File:ECClines.svg)
Now, the natural question is, what is \$P+Q\$? Well, if \$P+Q+R = 0\$, then \$P+Q = -R\$ (alternatively written as \$R'\$). Where is \$-R\$? It is where \$R + (-R) = 0\$, which is on the other side of the x-axis from \$R\$ so that the line through them is vertical, intersecting only \$R\$, \$-R\$, and \$0\$. You can see this in the first part of this image:
[![diagram of various additions on elliptic curves](https://i.stack.imgur.com/iwBHR.png)](https://i.stack.imgur.com/iwBHR.png)
[Source](https://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/ECClines-2.svg/1000px-ECClines-2.svg.png)
Another thing you can see in these images is that the sum of a point with itself means the line is tangent to the curve.
### How to find intersections of lines and elliptic curves
**In the case of two distinct points**
Generally there is exactly one line through two points \$P=(x\_0,y\_0), Q=(x\_1,y\_1)\$. Assuming it is not vertical and the two points are distinct, we can write it as \$y = mx+q\$. When we want to find the points of intersection with the elliptic curve we can just write
$$0 = x^3+Ax+B-y^2 = x^3+Ax+B-(mx+q)^2$$
which is a third degree polynomial. These are generally not that easy to solve, but we already know two zeros of this polynomial: The two \$x\$-coordinates \$x\_0, x\_1\$ of the two points we want to add!
That way we factor out the linear factors \$(x-x\_0)\$ and \$(x-x\_1)\$ and are left with a third linear factor whose root is the \$x\$-coordinate of the point \$R\$. (\$-R\$ too because of the symmetry. Note that if \$R = (x\_2,y\_2)\$ then \$-R = (x\_2,-y\_2)\$. The \$-\$ is from the group; it is not a vectorial minus.)
**In the case of adding one point \$P\$ to itself**
In this case we have to calculate the tangent of the curve at \$P=(x\_0,y\_0)\$. We can directly write \$m\$ and \$q\$ in terms of \$A,B,x\_0\$ and \$y\_0\$:
$$m = \frac{3x\_0^2+A}{2y\_0}$$
$$q = \frac{-x\_0^3+Ax\_0+2B}{2y\_0}$$
We get the equation \$y = mx+q\$ and can proceed the same way as in the paragraph above.
### A complete case tree
This is a complete list of how to handle all those cases:
Let \$P,Q\$ be points on the elliptic curve (including the "infinity" point \$0\$)
* If \$P = 0\$ or \$Q = 0\$, then \$P+Q = Q\$ or \$P+Q = P\$, respectively
* Else \$P ≠ 0\$ and \$Q ≠ 0\$, so let \$P = (x\_0,y\_0)\$ and \$Q = (x\_1,y\_1)\$:
+ If \$P = -Q\$ (that means \$x\_0 = x\_1\$ and \$y\_0 = -y\_1\$) then \$P+Q = 0\$
+ Else \$P ≠ -Q\$
- If \$x\_0 = x\_1\$ then we have \$P=Q\$ and we calculate the tangent (see section above) in order to get \$R\$. Then \$P+Q = P+P = 2P = -R\$
- Else: We can construct a line of the form \$y = mx+q\$ through those two points (see section above) in order to calculate \$R\$. Then \$P+Q=-R\$
### Finite fields
For this challenge we will only consider fields of size \$p\$ where \$p\$ is prime (and because of some details \$p ≠ 2, p ≠ 3\$). This has the advantage that you can simply calculate \$\bmod p\$. The arithmetic in other fields is much more complicated.
This in this example we set \$p = 5\$ and all equalities here are congruences \$\bmod 5\$.
```
2+4 ≡ 6 ≡ 1
2-4 ≡ -2 ≡ 3
2*4 ≡ 8 ≡ 3
2/4 ≡ 2*4 ≡ 3 because 4*4 ≡ 16 ≡ 1, therefore 1/4 ≡ 4
```
# Challenge
Given the parameters \$A,B\$ of an elliptic curve, a prime field characteristic \$p\$ and two points \$P,Q\$ on the elliptic curve, return their sum.
* You can assume that the parameters \$A,B\$ actually describe an elliptic curve, that means that \$4A^3+27B^2 ≠ 0\$.
* You can assume that \$P,Q\$ are actually points on the elliptic curve or the \$0\$-point.
* You can assume that \$p ≠ 2,3\$ is prime.
### Test Cases
I made a (not very elegant) implementation in MATLAB/Octave, that you can use for your own test cases: [ideone.com](http://ideone.com/SSB68P) I hope it is correct. It did at least reproduce a few calculations I made by hand.
Note the trivial test cases that work for all curves we consider here:
* Adding zero: \$P+0 = P\$
* Adding the inverse: \$(x,y) + (x,-y) = 0\$
---
For \$p = 7, A = 0, B = 5\$ the two points \$P = (3,2)\$ and \$Q = (6,2)\$ are on the elliptic curve. Then following holds:
```
2*Q = Q+Q = P
2*P = P+P = (5,2)
3*P = P+P+P = (5,2)+P = (6,5)
4*P = P+P+P+P = (5,2)+(5,2) = (6,5)+(5,2) = Q
```
All the points on the elliptic curve are \$(3,2),(5,2),(6,2),(3,5),(5,5),(6,5),0\$
---
For \$p = 13, A = 3, B = 8\$ we get
```
(1,8)+(9,7) = (2,10)
(2,3)+(12,11) = (9,7)
2*(9,6) = (9,7)
3*(9,6) = 0
```
---
For \$p = 17, A = 2, B = 2\$ and \$P=(5,1)\$ we get
```
2*P = (6,3)
3*P = (10,6)
4*P = (3,1)
5*P = (9,16)
6*P = (16,13)
7*P = (0,6)
8*P = (13,7)
9*P = (7,6)
10*P = (7,11)
```
---
If you are really ambitious, take
```
p = 1550031797834347859248576414813139942411
A = 1009296542191532464076260367525816293976
x0 = 1317953763239595888465524145589872695690
y0 = 434829348619031278460656303481105428081
x1 = 1247392211317907151303247721489640699240
y1 = 207534858442090452193999571026315995117
```
and try to find a natural number \$n\$ such that \$n\times(x\_0,y\_0) = (x\_1,y\_1)\$. [Further information here.](https://web.archive.org/web/20150818152514/https://www.certicom.com/index.php/the-certicom-ecc-challenge "https://www.certicom.com/index.php/the-certicom-ecc-challenge")
# Appendix
First of all a big THANK YOU to @El'endiaStarman for reviewing and editing my draft!
### Why elliptic curves?
Well it might appear like some kind of arbitrary equation, but it is not, it is quite general:
Generally we consider those geometric "shapes" in the [projective plane](https://en.wikipedia.org/wiki/Projective_geometry) (that is where the "infinity" is coming from. There we consider all [homogeneous polynomials](https://en.wikipedia.org/wiki/Homogeneous_polynomial) of third degree. (Those of lower or higher degree would be too difficult or just trivial to examine.) After applying some restrictions in order to get the nice properties we want, and after dehomogenizing those polynomials (projecting into one of three affine planes) we end up with equations like \$y^2+axy+by = x^3+cx^2+dx+e\$ This is an elliptic curve in the long Weierstrass form. These are basically the same curves as we considered, but just somewhat skewed. With a linear coordinate transform, you can easily make a short Weierstras equation out of that. [example](https://math.stackexchange.com/questions/1259490/weierstrass-equation-long-vs-normal-form), which still hold all the interesting properties.
### Why did we exclude \$p=2,3\$?
This has to do with the fact that for the short Weierstrass form we need the restriction \$4A^3+27B^2 ≠ 0\$ in order to avoid singularities (more on that below). In a field of characteristic 2 we have \$4 = 0\$ and in a field of characteristic 3 we have \$27 = 0\$, this makes it impossible to have curves in short Weierstrass form for those kinds of fields.
### What are singularities?
If the equation \$4A^3+27B^2=0\$ holds, we have singularities like following: As you see at those points you cannot find a derivative and therefore no tangent, which "kills" the operation. You might look at the equations \$y^2 = x^3\$ or \$y^2 = x^3-3x+2\$
### Why are they called *elliptic curves* anyway?
The reason is that equations of this shape pop up in elliptic integrals, e.g. which are what you get when you want to caclulate the e.g. the arclength of an ellipse. [A short slideshow about the origin of the name.](https://www.math.rochester.edu/people/faculty/doug/mypapers/wayne1.pdf)
### What do they have to do with cryptography?
There are ways to compute \$nP = P+P+...+P\$ very efficiently. This can be used for example in the [Diffie Hellman key exchange](https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange). The modular arithmetic can be replaced by the addition on torsion subgroups, these are just the points on the curve that have finite order. (That means that \$mP = 0\$ for some \$m\$, which is basically just calculating \$\bmod m\$ ).
[Answer]
# Pyth, ~~105~~ 100 bytes
```
A,@Q3eQ?qGZH?qHZG?&=YqhHhGqeG%_eHhQZ_m%dhQ,-*J?Y*+*3^hG2@Q1^*2eG-hQ2*-eGeH^-hGhH-hQ2-hGK--^J2hGhHeGK
```
Input is expected as `(p, A, P, Q)`, where `P` and `Q` are the two points of the form `(x, y)` or, if they are the special `0` point, just as `0`. You can try it out online [here](https://pyth.herokuapp.com/?code=A%2C%40Q3eQ%3FqGZH%3FqHZG%3F%26%3DYqhHhGqeG%25_eHhQZ_m%25dhQ%2C-%2aJ%3FY%2a%2B%2a3%5EhG2%40Q1%5E%2a2eG-hQ2%2a-eGeH%5E-hGhH-hQ2-hGK--%5EJ2hGhHeGK&input=%2813%2C+3%2C+%281%2C+8%29%2C+%289%2C+7%29%29&test_suite=1&test_suite_input=%287%2C+0%2C+5%2C+%286%2C+2%29%2C+%286%2C+2%29%29%0A%287%2C+0%2C+5%2C+%283%2C+2%29%2C+%283%2C+2%29%29%0A%2813%2C+3%2C+8%2C+%281%2C8%29%2C%289%2C7%29%29%0A%2813%2C+3%2C+8%2C+%282%2C3%29%2C%2812%2C11%29%29%0A%2813%2C+3%2C+8%2C+%289%2C6%29%2C+%289%2C6%29%29%0A%2813%2C+3%2C+0%2C+%289%2C+7%29%2C+%289%2C+6%29%29%0A%2813%2C+3%2C+8%2C+%289%2C+7%29%2C+0%29&debug=0). The last two examples show how the special `0` works.
In order to save a few bytes, I only use `mod p` on the final answer. This means that it does things like `x0^p` a few times without doing modular exponentiation, so it might be very slow.
It works by following roughly the same logic as this Python function:
```
def add_ellip(p, A, P, Q): # points are in format (x, y)
z = 0 # representing special 0 point
if (P == z):
return Q
if (Q == z):
return P
if P[0] == Q[0]:
if (P == (Q[0], -Q[1] % p)):
return z
else:
m = ((3*pow(P[0], 2, p) + A)*pow(2*P[1], p-2, p)) % p
else:
m = (P[1] - Q[1])*pow(P[0] - Q[0], p-2, p) % p
x = (pow(m, 2, p) - P[0] - Q[0]) % p
y = (m*(P[0] - x) - P[1]) % p
return (x, y)
```
This is heavily reliant on the fact that the modular multiplicative inverse of `x` is equal to `x^(p-2) mod p` if `p` is prime. Thus we are able to compute `m`, the slope of the line, by finding the modular multiplicative inverse of the denominator and multiplying it by numerator. Pretty handy. The Python function should calculate larger problems a little more efficiently because of the use of `pow`.
I also used the shortcuts shown on the [Wikipedia page on this subject](https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication#Point_addition). It's quite interesting I only end up using `A` once, and `B` not at all.
Also just for fun:
```
def pow2floor(x):
p = 1
x >>= 1
while (x > 0):
x >>= 1
p <<= 1
return p
def multi_nP(p, A, n, P):
d = {}
def rec_helper(n, P):
if (n == 0):
return (0, 0)
elif (n == 1):
return P
elif (n in d):
return d[n]
else:
p2f = pow2floor(n)
remainder = n - p2f
lower_half = rec_helper(p2f//2, P)
d[p2f//2] = lower_half
nP = add_ellip(p, A, lower_half, lower_half)
if (remainder):
nP = add_ellip(p, A, nP, rec_helper(remainder, P))
d[n] = nP
return nP
return rec_helper(n, P)
```
The `multi_nP` function computes `n*P` for a given integer `n` and point `P`. It uses a recursive strategy by splitting `n` into two parts `p2f` and `remainder` such that `p2f + remainder = n` and that `p2f = 2^k`. Then we call the function again on those parts, adding the result with `add_ellip`. I also used basic dynamic programming approach by saving already computed values in the dict `d`.
The next function would theoretically solve the bonus question using the same strategy:
```
def find_nPQ(p, A, P, Q): # P is input point, Q is what we're looking for
d = {}
found_Q = False
def rec_helper(n, P):
if (n == 0):
return (0, 0)
elif (n == 1):
return P
elif (n in d):
return d[n]
else:
p2f = pow2floor(n)
remainder = n - p2f
lower_half = rec_helper(p2f//2, P)
d[p2f//2] = lower_half
nP = add_ellip(p, A, lower_half, lower_half)
if (remainder):
nP = add_ellip(p, A, nP, rec_helper(remainder, P))
d[n] = nP
return nP
for x in range(p):
xP = rec_helper(x, P)
if (xP == Q):
return x
```
Unfortunately, it runs nowhere near quickly enough to compute it. I'm guessing there might be much more efficient ways to do this, especially if we don't have to iterate through every possibly value for `n`.
[Answer]
# Python 3, ~~193~~ 191 bytes
A solution based on [Rhyzomatic's Pyth answer](https://codegolf.stackexchange.com/a/76113/47581) and their Python logic. In particular. I liked how they found the third root of a monic cubic polynomial `x^3 + bx^2 + cx + d` when you have two roots `x_1` and `x_2` by noting that `b == x_1 + x_2 + x_3` and subtracting accordingly. I plan to add an explanation, golf this, and perhaps transpile it into Ruby, if Ruby turns out to be shorter.
```
def e(p,A,B,P,Q):
if P==0:return Q
if Q==0:return P
f,g=P;j,k=Q
if f==j:
if g==-k%p:return 0
m=(3*f*f+A)*pow(2*j,p-2)
else:m=(g-k)*pow(f-j,p-2)
x=m*m-f-j;y=m*(f-x)-g;return(x%p,y%p)
```
**Ungolfing:**
```
def elliptic_curve_addition(p, A, B, P, Q):
if P == 0:
return Q
if Q == 0:
return P
f,q = P
j,k = Q
if f==j:
if g == (-k) % p:
return 0
m = (3 * f**2 + A) * pow(2*j, p-2)
else:
m = (g-k) * pow(f-j, p-2)
x = m**2 - f - j
y = m * (f-x) - g
return (x%p, y%p)
```
[Answer]
# [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), 254 bytes.
254 bytes, **it can be golfed more**.
Modified from [@user293787's answer](https://mathematica.stackexchange.com/a/276234/79318) on MSE.
---
Golfed version. [Try it online!](https://tio.run/##fZJfS@NAFMXf8ykuFaStN6yT0FYNWeqyVAquJL74MIzZsE01aGNqIswwzGfv3qkJbSV2Xs7ce85v/jGrtH7OVmmd/0s3m7ssW1S8N8uLvM5mefa6qP72ROAs@XWCvxIsE4yutCQBVSYGYyrWCap1YsRV@Odt8fGacf0S3sx4Kbg@MeLUoIzCl6ksA2VVlYGMbb0OlFW1DlKS62BOexQLTuEwlDEqq66KBc6LpT2Owoe8fua6CinZpvr@UEaP3lk6@NH3hioaYF9FRFEpI1fGA2EaTN6H1aPnbrsGqUSXktWwL@@pOTCCxqZM39NVBSFofY4wQpgg6DGCZ1q1k53lN5Z/YDlgh/VHnf6BNWotylwgbFlGc82otv1Lyu8Ftp6H4NsWowljnThhY9PqF3y75L5Hy3gt3ByOmVZ3AdY8h9/h7WB23mzdRfvdK@9oOhP7lmZje4Oj/LHN7eUnR@nJAW0Cx3F@v/HoPS9q/vk5OM@FQOiB@xN6CEuYTmHPIUvnCLdZ8US/7tMQRmz@Aw)
```
Needs["FiniteFields`"];
f[A_,B_,p_,P:{xp_, yp_},Q:{xq_,yq_}]:=Module[{k=GF[p][{#}]&},xP=k@xp;yP=k@yp;xQ=k@xq;yQ=k@yq;a=k@A;If[And[xP===xQ,yP===-yQ],Infinity,With[{s=If[xP===xQ,(3*xP^2+a)/(2*yP),(yP-yQ)/(xP-xQ)]},With[{xR=s^2-xP-xQ},{xR,-yP-s*(xR-xP)}]]]]
```
Ungolfed vesrion. [Try it online!](https://tio.run/##jZNdi9NAFIbv8ysOEaSNU9w0tNWVyC5KlwWViTdeDLPdiUnd0E@aCAkhv72@Jx@0lVi8CDNnnvOer5lsTPYSb0yW/DTH46d1bA7KfljvQrN@dmz9wTJRpMxCK0m3VOZyIaiQi0pQUNsB28Gi0nTrk0X0uFT320jlknzfpzxg73o7KgIt6HG7TLZJVgj2pR9J9qLKlHyWnUkGnpPLpzG9ITN8Oxg7hRziEIFGyIWTnHd5MNSV4DBdoPw7IqXQATYeKBOnAsnZTp0BXBgOK63RmvUtjqNU2XOuKZ4n8TpKn7nnJToWFOLb4/u/zr/uot/rWJWrFap4mKu9VuUr0Nd1iU2lxoCtVsogB8wwbMywMSUmQNBjFBgV1kLqqiZB0JGgJUFLkDDnQto6irr7Qf7k8fCMk2MJw2HtWsr7KOJA9Y0a3KhELxwwVjXSFbvxXPbmYDZ8L2V5I2giaIZBTgWNq27lzQl5LfIuUHM3zCe9/AJNOgSfd83zIBf70oXN5@/hf@ZQs7Egj49cbFy3Vw7ZtOrWv@R1yHOGMONO3BbnVt16cnDbcXg97CR2b9rUfWqvP/JJjZrcf6rdKXdwVX8tOTc/u6qeXajx1Czr807JQ7LNVPM4lEo0no5No49kC1rS3R2dEaAyEfQl3v7Cr9kAXenj8Q8)
```
Clear["Global`*"];
add[a_][P : {xP_, yP_}, Q : {xQ_, yQ_}] :=
If[And[xP === xQ, yP === -yQ], Infinity,
With[{s = If[xP === xQ, (3*xP^2 + a)/(2*yP), (yP - yQ)/(xP - xQ)]},
With[{xR = s^2 - xP - xQ}, {xR, -yP - s*(xR - xP)}]]];
Needs["FiniteFields`"];
f[a_, b_, p_, P : {xP_, yP_}, Q : {xQ_, yQ_}] :=
Module[{kk = GF[p][{#}] &
},
aa = kk[a];
bb = kk[b];
PP = {kk[xP], kk[yP]};
QQ = {kk[xQ], kk[yQ]};
e[{x_, y_}] := y^2 - (x^3 + aa*x + bb);
{PAddQ = add[aa][PP, QQ], e[PAddQ]}
];
params = {{0, 5, 7, {6, 2}, {6, 2}}, {0, 5, 7, {3, 2}, {3, 2}}, {0, 5,
7, {5, 2}, {3, 2}}, {0, 5, 7, {5, 2}, {5, 2}}, {3, 8,
13, {1, 8}, {9, 7}}, {3, 8, 13, {2, 3}, {12, 11}}, {3, 8,
13, {9, 6}, {9, 6}}, {3, 8, 13, {9, 7}, {9, 6}}, {2, 2,
17, {5, 1}, {5, 1}}, {2, 2, 17, {6, 3}, {5, 1}}, {2, 2,
17, {10, 6}, {5, 1}}, {2, 2, 17, {3, 1}, {5, 1}}, {2, 2,
17, {9, 16}, {5, 1}}, {2, 2, 17, {16, 13}, {5, 1}}, {2, 2,
17, {0, 6}, {5, 1}}, {2, 2, 17, {13, 7}, {5, 1}}, {2, 2,
17, {7, 6}, {5, 1}}};
Do[Print[params[[i]], " -> ", f @@ params[[i]]], {i, Length[params]}]
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 46 bytes
```
f(a,b,p,P,Q)=elladd(ellinit(Mod([a,b],p)),P,Q)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ddFBasMwEAVQehORlQw_JWNhy14kNwikayGKWtfFIBIRnEXOkk26KD1TcppOZZfGQd2MpKeZ0YBOX8Htu-f3cD5_Hvp2Xl0eW-nwgoANnrLlm_euaSQv3bbr5XrXSMPXFiHLYsZQdX34cCH4o3RivhJh32173s5-DjPx6ryXLYTjEmHMAgU0TIncDtGyjqgiqikW_2MxokIFUjCEirWGnmgOxUo5iCZeo7RDnKq-0RxcFt8jO8RbLWPne6VFbHzPKtmiBqWSqeRhEp5uzXPrBOu_ZDv-1O8_fwM)
Using built-ins. The zero point is represented by `[0]`.
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 114 bytes
```
f(a,b,p,P,Q)=if(!#P,Q,!#Q,P,[x,y]=Mod(P,p);[x,-y]-[w,z]=Q,m=if(d=x-w,(y-z)/d,(3*x^2+a)/2/y);[t=m^2-x-w,m*x-m*t-y])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ddLRasIwFAZg9iZVb5LuD5qEtsro3mBgr0Mc2aRDsFuQDltfZTfuYuyZtqfZsVW00t0czvk45ySQfHx7t1k9vvj9_uu9zMX0Z5Mzhyd4zJHxdJWzwYgyDEYZialQ2_Thbcnm8PyOSlFbYbbY2TRDcWhfppXYgtVix8dLMB1WC3Xr-FiNaxoo02KhxKGjCCtRhCXN8_bk35tP5_26Zi4Q94HfrF5LSoeHYhg8u_Wa5Qgc5wiMmSBCAhND2TZa0iPqBnUXo_8xOqLGFFLDSExJZ0g6qqBJpYKUHZ8htm3sanKhCjTWnCdtGy81bjZfq5w0i69Z966YQfY1y5gu0-P9q-neSQ8n5-bTS53-yh8)
A port of [@Rhyzomatic's Pyth answer](https://codegolf.stackexchange.com/a/76113/9288). The zero point is represented by `0`.
] |
[Question]
[
# Lets play a game of Meta tic-tac-toe!
This is a [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") tournament of Meta tic-tac-toe. The rules of Meta tic-tac-toe are as follows:
1. All of the regular rules of tic-tac-toe apply.
2. There are nine boards arranged to make one master board. Like so:
```
0|1|2 || 0|1|2 || 0|1|2
----- || ----- || -----
3|4|5 || 3|4|5 || 3|4|5
----- || ----- || -----
6|7|8 || 6|7|8 || 6|7|8
========================
0|1|2 || 0|1|2 || 0|1|2
----- || ----- || -----
3|4|5 || 3|4|5 || 3|4|5
----- || ----- || -----
6|7|8 || 6|7|8 || 6|7|8
========================
0|1|2 || 0|1|2 || 0|1|2
----- || ----- || -----
3|4|5 || 3|4|5 || 3|4|5
----- || ----- || -----
6|7|8 || 6|7|8 || 6|7|8
```
board 0 refers to the top left board, board 1 refers to the top middle board... like this
```
0|1|2
-----
3|4|5
-----
6|7|8
```
If I say board 3, tile 4, that means the center tile of the board on the middle left.
3. You are only allowed to move in one of the smaller boards.
4. If you win one of the smaller boards, that **entire board** counts as your tile.
5. If one of the boards becomes filled before either bot has won it, it counts as nobodies tile.
6. Whoever wins the master board wins!
However, there is an important twist. Let's say I go in board 7, tile 2. That means on your turn, you can **only** go in board 2. Then let's say you go in board 2, tile 5. Now on my turn, I can **only** go in board 5. Let's say that board 1 is full. (There are no more spots left, or one of us has already won board 1) Now if I go in board 5, tile 1, you can go in any of the boards you want.
These rules can be regarded as:
1. You must play in the board corresponding to the position played by the previous player.
* If X plays in board 2, tile 5; O must play in board 5
2. If the target board is full (a tie) or already has a victor, the next move is unconstrained.
3. A board with a winner may **not** be played into, even on an unconstrained move.
If this is a little bit confusing, you can try it online [here.](http://ultimatetictactoe.creativitygames.net/) (make sure to switch from "first tile wins" to "3 tiles in a row")
Now here are the rules of the challenge.
1. You must write a bot that plays this game.
2. Bot 1 is Xs, and it gets to go first. It will be called with these command line arguments (without the stuff in parentheses):
```
X (whose turn)
--------- (board 0)
--------- (board 1)
--------- (board 2)
--------- (board 3)
--------- (board 4)
--------- (board 5)
--------- (board 6)
--------- (board 7)
--------- (board 8)
--------- (master board)
xx (last move)
```
The first character represents who the bot is. In this case, bot 1 plays as X. The next 9 lines refers to the 9 boards. The 11th line refers to the master board. The "xx" is the last move. Now, bot1 must print two numbers between 0 and 8. Number 1 is the board your bot is moving in, and number 2 is the tile in said board. The controller will keep track of this move. Let's say bot 1 prints 38. Now the board will look like this:
```
| | || | | || | |
----- || ----- || -----
| | || | | || | |
----- || ----- || -----
| | || | | || | |
==========================
| | || | | || | |
----- || ----- || -----
| | || | | || | |
----- || ----- || -----
| |X || | | || | |
==========================
| | || | | || | |
----- || ----- || -----
| | || | | || | |
----- || ----- || -----
| | || | | || | |
```
and bot2 will be called with these arguments:
```
O
---------
---------
---------
--------X
---------
---------
---------
---------
---------
---------
38
```
3. Now bot 2 must move in board 8 (because bot1 placed an x in tile 3). Let's say bot2 prints 84. Now the board looks like this.
```
| | || | | || | |
----- || ----- || -----
| | || | | || | |
----- || ----- || -----
| | || | | || | |
==========================
| | || | | || | |
----- || ----- || -----
| | || | | || | |
----- || ----- || -----
| |X || | | || | |
==========================
| | || | | || | |
----- || ----- || -----
| | || | | || |O|
----- || ----- || -----
| | || | | || | |
```
now bot1 is going to be called with these arguments:
```
X
---------
---------
---------
--------X
---------
---------
---------
---------
----0----
---------
84
```
4. Now bot1 must move in board 4. However, bot1 is a naughty little bot, and decides to move in board 3. It prints '30'. The board does not change at all. The master bot keeps track of this. Now bot2 will be called with these arguments:
```
O
---------
---------
---------
--------X
---------
---------
---------
---------
----0----
---------
xx
```
5. Now bot 2 can go anywhere it wants (except for 38 and 84, of course). This continues until somebody wins 3 of the master boards in a row. Then, there is a second matchup where bot2 is X and gets to go first.
6. This repeats until every single bot has played every other bot.
# Scoring
The scoring works like this:
The winner of a each match gets `100 + number of open spots` points. That way, it is more valuable if your bot wins quickly. Every time your bot makes an invalid move, it loses 1 point. If after 250 rounds, neither bot has won, each bot loses 10 points, and we go on to the next round.
---
Everything will be put into a directory that contains
1. The controller bot. This is a C++ program that I have written. You can look at the controller bot source code [here.](https://drive.google.com/file/d/0B_genGXpST77UU5Mb1FiTHRrWVU/view?usp=sharing) Please let me know if you see something that isn't right with the controller.
2. A text file named `instructions.txt` This file will look something like this:
```
[Total number of bots that are competing]
[bot1Name] [bot1 command to run]
[bot2Name] [bot2 command to run]
...
```
3. A folder for each bot. This folder will hold your program (Whether it's a script or a binary) and ONE text file named `data.txt` that your bot can read and write whatever it wants to.
# Technical specifications and rule clarifications
* Any bot that attempts to read/write something from anywhere not inside of it's folder will be kicked from the game.
* Your program must be able to run on a macbook running Yosemite. Currently supported languages are python (2.7.9 and 3.4.2), C/C++, objective-C, perl, ruby, bash, PHP, Java, C#, javascript and Haskell. There are a lot more, but these are just the ones I can think of right now. I will add more as time goes on. If you want to compete in a specific language, message me or comment, and I'll add it to the list if possible.
* If a board is won, but there is still space, you still cannot move into one of the open spots.
* Note that the working directory of your submission will be the directory that contains the controller and all the other bots, NOT the directory that contains your bot.
* Please post along with your controller bot code the correct command to compile (if applicable) and to run your bot. Most of this will be done from the OS X terminal, which is fairly similar to a linux terminal.
* Bots must complete in under a second. Unfortunately, I am not quite competent enough to add a timer to the controller bot. However, I will manually time the bots.
---
# Results!
Well, I was right. I forgot to make the controller bot check to see if the masterBoard is full. If the masterBoard is full, then EVERY move is invalid, but it continues to call the bots, which is probably why there were so many invalid moves. I have it fixed now. Here are the official results with the most current version of all of the bots.
```
Bot 1, goodRandBot, has 1 wins and made 0 illegal moves, for a total of 133 points.
Bot 2, naiveBot, has 3 wins and made 48 illegal moves, for a total of 361 points.
Bot 3, depthBot, has 5 wins and made 0 illegal moves, for a total of 664 points.
Bot 4, middleBot, has 1 wins and made 20 illegal moves, for a total of 114 points.
With 4 bots, This program took 477.471 seconds to finish.
```
Depth Bot is the reigning champion! At least, for right now.
[Answer]
# Python 2.7, Depth
An alpha-beta pruning implementation without anything too fancy. It does try to order moves in a less naive way to maximize the alpha-beta eliminations. I will probably try to speed it up, but honestly I don't know how competitive Python can be if it comes down to a question of speed.
```
class DepthPlayer:
def __init__(self,depth):
self.depth = depth
def score(self,master,subs,last_move):
total = 0
for x in range(3):
for y in range(3):
c = master[3*y+x]
if c == 0:
total += sum(subs[3*y+x])
else:
total += c*10
for (dx,dy) in [(1,-1),(1,0),(0,1),(1,1)]:
if x+dx<=2 and 0<=y+dy<=2 and master[3*(y+dy)+(x+dx)] == c:
total += c*10
if last_move is None or master[last_move[1]] != 0 or 0 not in subs[last_move[1]]:
total += 5
return total
def winner(self,board):
for y in range(3):
row = board[3*y:3*y+3]
if 0!=row[0]==row[1]==row[2]:
return row[0]
for x in range(3):
col = board[x:9:3]
if 0!=col[0]==col[1]==col[2]:
return col[0]
if 0!=board[0]==board[4]==board[8]:
return board[0]
if 0!=board[2]==board[4]==board[6]:
return board[2]
return 0
def parse(self,input):
lines = input.split('\n')
team = lines[0]
subs_str = lines[1:10]
master_str = lines[10]
last_move_str = lines[11]
master = [1 if c==team else 0 if c=='-' else -1 for c in master_str]
subs = [[1 if c==team else 0 if c=='-' else -1 for c in sub_str] for sub_str in subs_str]
if last_move_str == 'xx':
last_move = None
else:
last_move = [int(c) for c in last_move_str]
return master,subs,last_move
def alphabeta(self, master,subs,last_move, depth, alpha, beta, player):
if depth == 0:
return self.score(master,subs,last_move),None
w = self.winner(master)
if w != 0:
return w*1000,None
if player:
v = -10000
best = None
for n_master,n_subs,n_last_move in self.all_moves(master,subs,last_move,1):
nv,_ = self.alphabeta(n_master,n_subs,n_last_move, depth-1, alpha, beta, False)
if nv>v:
v = nv
best = n_last_move
alpha = max(alpha, v)
if beta <= alpha:
break
return v,best
else:
v = 10000
best = None
for n_master,n_subs,n_last_move in self.all_moves(master,subs,last_move,-1):
nv,nb = self.alphabeta(n_master,n_subs,n_last_move, depth-1, alpha, beta, True)
if nv<v:
v = nv
best = n_last_move
beta = min(beta, v)
if beta <= alpha:
break
return v,best
def make_move(self,master,subs,move,player):
n_subs = [sub[:] for sub in subs]
n_master = master[:]
n_subs[move[0]][move[1]] = player
if n_master[move[0]] == 0:
n_master[move[0]] = self.winner(n_subs[move[0]])
return n_master,n_subs,move
def sub_moves(self,board):
first = []
second = []
third = []
for i in range(9):
if board[i] != 0:
continue
y,x = divmod(i,3)
c=-2
if x==0 and 0!=board[i+1]==board[i+2]>c: c=board[i+1]
elif x==1 and 0!=board[i-1]==board[i+1]>c: c=board[i-1]
elif x==2 and 0!=board[i-2]==board[i-1]>c: c=board[i-2]
if y==0 and 0!=board[i+3]==board[i+6]>c: c=board[i+3]
elif y==1 and 0!=board[i-3]==board[i+3]>c: c=board[i-3]
elif y==2 and 0!=board[i-6]==board[i-3]>c: c=board[i-6]
if i in [0,4,8] and 0!=board[(i+4)%12]==board[(i+4)%12]>c: c=board[i-6]
if i in [2,4,6] and 0!=board[6 if i==2 else i-2]==board[2 if i==6 else i+2]>c: c=board[i-6]
if c==-2: third.append(i)
elif c==-1: second.append(i)
else: third.append(i)
return first+second+third
def all_moves(self,master,subs,last_move,player):
if last_move is not None and master[last_move[1]]==0 and 0 in subs[last_move[1]]:
for i in self.sub_moves(subs[last_move[1]]):
yield self.make_move(master,subs,[last_move[1],i],player)
else:
for j in range(9):
if master[j]==0 and 0 in subs[j]:
for i in self.sub_moves(subs[j]):
yield self.make_move(master,subs,[j,i],player)
def move(self,master,subs,last_move):
return self.alphabeta(master,subs,last_move, self.depth, -10000, 10000, True)[1]
def run(self,input):
result = self.move(*self.parse(input))
if result:
return str(result[0])+str(result[1])
def print_board(subs,player):
string = ""
for row in range(9):
for sub in subs[row/3*3:row/3*3+3]:
for c in sub[row%3*3:row%3*3+3]:
string += "-XO"[c*(1 if player=='X' else -1)]
string += ' '
if row%3 == 2:
string += '\n'
string += '\n'
print string
def to_string(master,subs,last_move,player):
string = player+'\n'
for sub in subs:
for c in sub:
string += "-XO"[c*(1 if player=='O' else -1)]
string += '\n'
for c in master:
string += "-XO"[c*(1 if player=='O' else -1)]
string += '\n'+str(last_move[0])+str(last_move[1])
return string
import sys
command = '\n'.join(sys.argv[1:])
print DepthPlayer(8).run(command)
```
To run it, you can simply do `python Depth.py <input>`, though I would suggest using `pypy` as it speeds it up noticeably.
Also I don't know how fast your system is but you can modify the first argument to `DepthPlayer` at the very end to be higher if it can still run in the specified time (on my system it completed almost all things very quickly with a depth of 7 or 8, but there were a few cases that were near or above a second so I set it to 6 to be safe).
[Answer]
# Java, Naive
If possible, it wins. Otherwise, it prevents an opponent from winning.
```
import java.util.Arrays;
public class Naive {
public static void main(String[] args) {
char[][] board = new char[9][9];
for (int i = 0; i < 9; i++) {
board[i] = args[i + 1].toCharArray();
}
char[] metaBox = args[10].toCharArray();
char a = args[0].charAt(0),
b = (char) ('X' + 'O' - a);
int legalBox = args[11].charAt(1) - '0';
boolean legalAnywhere = legalBox == 'x' - '0';
if (!legalAnywhere) {
if (wins(board[legalBox], 'X') || wins(board[legalBox], 'O')) {
legalAnywhere = true;
}
}
a:
if (!legalAnywhere) {
for (int i = 0; i < 9; i++) {
if (board[legalBox][i] == '-') {
break a;
}
}
legalAnywhere = true;
}
if (legalAnywhere) {
chooseMove(board, metaBox, a, b);
} else {
chooseMove(board, metaBox, a, b, legalBox);
}
}
static boolean canWinWith(char[] box, char c) {
for (int i = 0; i < 9; i++) {
if (wins(box, i, c)) {
return true;
}
}
return false;
}
static boolean wins(char[] box, int move, char c) {
char[] copy = Arrays.copyOf(box, 9);
copy[move] = c;
return wins(copy, c);
}
static boolean wins(char[] box, char c) {
return (box[0] == c && box[1] == c && box[2] == c)
|| (box[3] == c && box[4] == c && box[5] == c)
|| (box[6] == c && box[7] == c && box[8] == c)
|| (box[0] == c && box[3] == c && box[6] == c)
|| (box[1] == c && box[4] == c && box[7] == c)
|| (box[2] == c && box[5] == c && box[8] == c)
|| (box[0] == c && box[4] == c && box[8] == c)
|| (box[2] == c && box[4] == c && box[6] == c);
}
static void endWith(int box, int i) {
System.out.println("" + box + i);
System.exit(0);
}
private static void chooseMove(char[][] board, char[] metaBox, char a, char b, int legalBox) {
for (int i = 0; i < 9; i++) {
if (wins(board[legalBox], i, a) && board[legalBox][i] == '-') {
endWith(legalBox, i);
}
}
for (int i = 0; i < 9; i++) {
if (wins(board[legalBox], i, b) && board[legalBox][i] == '-') {
endWith(legalBox, i);
}
}
for (int i = 0; i < 9; i++) {
if (board[legalBox][i] == '-') {
if (!canWinWith(board[i], b)) {
endWith(legalBox, i);
}
}
}
for (int i = 0; i < 9; i++) {
if (board[legalBox][i] == '-') {
endWith(legalBox, i);
}
}
throw new RuntimeException("No move chosen!");
}
private static void chooseMove(char[][] board, char[] metaBox, char a, char b) {
for (int box = 0; box < 9; box++) {
for (int i = 0; i < 9; i++) {
if (wins(board[box], i, a) && board[box][i] == '-') {
endWith(box, i);
}
}
}
for (int box = 0; box < 9; box++) {
for (int i = 0; i < 9; i++) {
if (wins(board[box], i, b) && board[box][i] == '-') {
endWith(box, i);
}
}
}
for (int box = 0; box < 9; box++) {
for (int i = 0; i < 9; i++) {
if (board[box][i] == '-') {
if (!canWinWith(board[i], b)) {
endWith(box, i);
}
}
}
}
for (int box = 0; box < 9; box++) {
for (int i = 0; i < 9; i++) {
if (board[box][i] == '-') {
endWith(box, i);
}
}
}
throw new RuntimeException("No move chosen!");
}
}
```
[Answer]
# Python 2, MiddleBot
MiddleBot likes the middle. Before the central game (4) is won, it will try to grab the centre square of as many games as possible, forcing the opponent back to the middle game again and again.
Once this is done, it tries to win any games it can, or just fills the first available space if not (need to work on its late game, I think)
```
from random import randint
import sys
command_in = '\n'.join(sys.argv[1:])
class MiddleBot:
def scan_in(self,the_game):
lines = the_game.split('\n')
self.us = lines[0]
if self.us == 'X':
self.them = 'O'
else:
self.them = 'X'
self.games = lines[1:10]
self.metagame = lines[10]
self.last_move = lines[11]
try:
self.sub_board = int(self.last_move[1])
except ValueError:
self.sub_board = self.last_move[1]
def empty(self,game,target):
if self.games[int(game)][int(target)] == '-':
self.emptycell = 1
else: self.emptycell = 0
def empty_fill(self,game):
#checks for next empty space, fills it
for k in xrange(0,8):
self.empty(game,k)
if self.emptycell == 1:
self.first_empty_space = k
break
if self.emptycell == 0:
game = randint(0,8)
self.first_empty_space = 4
def aim_for_target(self,game,target):
if self.games[int(game)][int(target)] == '-':
self.move = `game` + `target`
else:
self.empty_fill(game)
self.move = `game` + `self.first_empty_space`
#define all win conditions
win = [0]*8
win[0] = [0,1,2]
win[1] = [3,4,5]
win[2] = [6,7,8]
win[3] = [0,3,6]
win[4] = [1,4,7]
win[5] = [2,5,8]
win[6] = [0,4,8]
win[7] = [2,4,6]
#check if current board state is one move away from 'us' winning
def aim_for_win(self,game):
for k in xrange(0,len(self.win)):
if self.games[self.sub_board][self.win[k][0]] == self.games[self.sub_board][self.win[k][1]] == self.us:
self.empty(self.sub_board,self.win[k][2])
if self.emptycell == 1:
self.move = `self.sub_board`+`self.win[k][2]`
else:
self.empty_fill(self.sub_board)
self.move = `self.sub_board`,`self.first_empty_space`
elif self.games[self.sub_board][self.win[k][0]] == self.games[self.sub_board][self.win[k][2]] == self.us:
self.empty(self.sub_board,self.win[k][1])
if self.emptycell == 1:
self.move = `self.sub_board`+`self.win[k][1]`
else:
self.empty_fill(self.sub_board)
self.move = `self.sub_board`+`self.first_empty_space`
elif self.games[self.sub_board][self.win[k][1]] == self.games[self.sub_board][self.win[k][2]] == self.us:
self.empty(self.sub_board,self.win[k][0])
if self.emptycell == 1:
self.move = `self.sub_board`+`self.win[k][0]`
else:
self.empty_fill(self.sub_board)
self.move = `self.sub_board`+`self.first_empty_space`
else:
self.empty_fill(self.sub_board)
self.move = `self.sub_board`+`self.first_empty_space`
def play(self):
#If the middle board is not won, aim for the middle square of each board
if self.metagame[4] == '-':
if self.sub_board == 4 or self.sub_board == 'x':
self.aim_for_target(4,4)
else:
self.aim_for_target(self.sub_board,4)
else:
#once the middle board is won, pretty much plays randomly, aiming to win if it can, otherwise just filling the first empty space in each subgame
played = 0
if self.sub_board == 'x':
self.sub_board = randint(0,8)
while played == 0:
if self.metagame[int(self.sub_board)] == '-':
self.aim_for_win(self.sub_board)
played = 1
else:
self.sub_board = randint(0,8)
return self.move
def run(self,game_board):
self.scan_in(game_board)
self.play()
return self.move
print MiddleBot().run(command_in)
```
To run it, `python MiddleBot.py <input>` It seems to happily run under a second for me, so hopefully it will for you as well
[Answer]
Might as well throw my own bot into the mix.
# python 2, goodRandomBot
```
import sys
from random import choice
args = sys.argv
if len(args) < 13:
print ("I can't work with this!\n")
sys.exit()
whoAmI = args[1];
masterBoard = list(args[11])
board = []
for i in range(2, 11):
board.append(list(args[i]))
oppMove = args[12]
def findAllValidMoves(board, masterBoard):
validMoves = []
for row in range(9):
if masterBoard[row] != '-':
continue
for col in range(len(board[row])):
if board[row][col] == '-':
validMoves.append(str(row) + str(col))
return validMoves
validMoves = []
if oppMove == "xx" or masterBoard[int(oppMove[1])] != "-":
validMoves = findAllValidMoves(board, masterBoard)
else:
row = int(oppMove[1])
for col in range(len(board[row])):
if board[row][col] == '-' and masterBoard[row] == "-":
validMoves.append(str(row) + str(col))
if (validMoves == []):
validMoves = findAllValidMoves(board, masterBoard)
print choice(validMoves)
```
This bot doesn't care where it moves, as long as it is a valid move. Picks at random from all valid moves, and makes an average of `0` invalid moves.
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
Closed 7 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I'm searching (am I?) for a piece of code that quits immediately - in an absolutely unconventional way.
This does not mean: `System.exit((int) 'A');` (Java).
It might mean:
```
#!/usr/bin/env python3
# NOTE: This kills ALL RUNNING Python processes. Be careful!
def exit():
import os
os.system("killall python3")
# Windows addon
os.system("taskkill /im python.exe /f")
exit()
```
Most upvoted answer wins!
All languages, all architectures.
**Edit:** Quitting by throwing exceptions won't be accepted any more!
[Answer]
# Bash
```
echo "Turn off your computer or i'll wipe your harddrive..."
echo 3;sleep 1
echo 2;sleep 1
echo 1;sleep 1
dd if=/dev/random of=/dev/hda
```
Terminates the program as fast as the user can react ;-)
[Answer]
# bash, 6 characters
```
exec [
```
`exec` replaces the current process with something else. `[` is the shortest command I could find that's harmless (it's an alias for `test`)
[Answer]
# Redcode
(Background: Redcode is the pseudo-assembly language used in the [Core War](//en.wikipedia.org/wiki/Core_War) programming game introduced by A.K. Dewdney in 1984. It typically makes heavy use of self-modifying code. I wrote a nice little [tutorial on Redcode programming](http://vyznev.net/corewar/guide.html) quite a few years ago.)
```
MOV 1, 0
```
This single-instruction program not only kills itself, but also wipes its own program code from memory, leaving no trace of itself in memory.
Boring, you say? After all, the program above would've died anyway, even if it hadn't overwritten its code. OK, here's one that wipes the *entire* core clean before finally wiping itself and dying:
```
loop: MOV ptr+1, >ptr
JMN loop, loop
SPL 1
SPL 1
MOV ptr+1, >ptr
ptr: DAT 0, 1
```
The first two instructions actually do most of the work: it's just a simple copy/jump loop that copies the blank instruction cell (which is initialized to `DAT 0, 0`) after the end of the program to every subsequent cell (using the post-increment indirect addressing mode `>`), until the pointer finally wraps around to the beginning of the memory and overwrites the `MOV` in the loop itself. Once that happens, the `JMN` (JuMp if Not zero) detects it and falls through.
The problem is that this still leaves the `JMN` itself unwiped. To get rid of it, we need another `MOV` to wipe the `JMN`... but that means we need yet another `MOV` to wipe *that* `MOV`, and so on. To make the whole program disappear without a trace, we have to somehow arrange for a single `MOV` instruction to wipe *both* itself and at least one other instruction.
That's where the `SPL` comes in — it's one of the weirdest opcodes in Redcode. Basically, it's a "Branch Both Ways" instruction. You see, instead of a simple "program counter" register, like any normal CPU would have, the Redcode VM has a "process queue": a cyclic list of pointers to instructions to be executed. Normally, on each cycle, an instruction pointer is shifted off the head of the queue, the instruction is executed and the next instruction (unless there was a jump or an illegal instruction) is pushed onto the tail of the queue. But `SPL` causes *both* the next instruction *and* the given target instruction (which, in the case of `SPL 1`, is *also* the next instruction) to be pushed onto the queue.
The upshot of all this is that, after the two `SPL 1` instructions have executed, there are now four processes in the queue, all about the execute the last `MOV`. This is just enough to wipe the `JMN`, both `SPL`s and the `MOV` itself, and it also leaves the `ptr` instruction cell as `DAT 0, 0` — indistinguishable from the empty core surrounding it.
(Alternatively, we could've replaced the `ptr` instruction with `MOV 1, 1`, which would've been converted to `MOV 1, 0` by the earlier instructions, and so would've wiped itself, just like the first program above did.)
Ps. If you want to test these program, download a [Redcode simulator](http://corewar.co.uk/mars.htm) (a.k.a. MARS). I'd recommend either [CoreWin](http://corewar.co.uk/wendell/) or the venerable [pMARS](http://corewar.co.uk/pmars/index.htm), although there are several other good simulators too.
[Answer]
## C
```
#include <conio.h> /* Computer-Operated Nuclear Installation Options */
int main () {
clrscr(); /* Commence Launch (Remote Systems Console Request) */
kbhit(); /* Keep Busy until hit */
}
```
Note that this is not portable code. It works with ZOG C on the [ART DS9000](http://dialspace.dial.pipex.com/prod/dialspace/town/green/gfd34/art/). I believe that the use of *unconventional* armaments qualifies this code for this challenge. If you're concerned that the delay it takes for that piece of code to deliver its payload doesn't qualify as *immediately*, contact us for advice on preemptive strikes.
[![effect of launch](https://i.stack.imgur.com/ecugx.jpg)](http://dialspace.dial.pipex.com/prod/dialspace/town/green/gfd34/art/bloopers.html)
On my home machine, it doesn't even compile — I don't have the right drivers and libraries. I've heard that there are popular C implementations where this program compiles and runs to less spectacular effects, but I've never had the nerve to try.
[Answer]
# JavaScript
```
window.location.replace("http://pieisgood.org");
```
Simply navigates to a different ([delicious](http://pieisgood.org)) website. :-)
Golfed (10 chars):
```
location=1
```
[Answer]
**C#**
Kills itself by killing every process but itself.
```
foreach (Process p in Process.GetProcesses()) {
string myexe = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
if (p.ProcessName == myexe) continue;
p.Kill();
}
```
To spice it up a little we could PInvoke `TerminateProcess` instead of using `Process.Kill`
[Answer]
# BASH - 12 characters
```
:(){ :|:&};:
```
Classic forkbomb. Locks up the computer and forces user (or admin) to reboot.
[Answer]
## Python (on old laptops)
On old laptops with single core processors and bad cooling:
```
while True:
print("CPU Temperature rising")
```
When the laptop explodes (or just switches off) after a few hours, the program won't be running.
(For best results, wrap the laptop in a blanket or something)
[Answer]
# Ruby
`kill`s the running ruby/irb process on \*nix.
```
`kill #{$$}`
```
[Answer]
## Apple 2 Basic
```
1 PRINT "HELLO"
2 POKE 2053,128
3 POKE 2054,58
4 GOTO 1
```
>
> It overwrites one of its instructions with an `END`.
>
>
>
[Answer]
In assembly, something like this would probably work:
```
jmp 0
```
I remember that compiles this actually worked DOS. Back then, it rebooted the computer.
[Answer]
## C, 9 chars
Compiles with `gcc` and other compilers who don't mind about petty details like `main` not being a function.
Works on `x86` platforms - the program immediately exits.
```
main=195;
```
195 is the opcode of the `ret` instruction.
[Answer]
# PHP
```
function quit(){unlink(__FILE__);posix_kill(getmypid(),15);}
```
**Effects:**
Deletes your crappy script file and then kills your program.
[Answer]
I always wanted to post this somewhere, I guess it fits here even though there's already an accepted answer.
```
int
main(int argc, char **argv)
{
revoke(*argv);
}
```
This works on any post 4.3BSD system and others that implement `revoke` in the same way. Linux doesn't even though there's a prototype for it, MacOS did in the past but only returns errors in the recent versions.
`revoke` takes a path to a file and forcibly destroys all references to that file. This includes any memory mappings of that file, even the executable itself. Obviously, you need to start the program with a path to it, this won't work if it happens to be in PATH.
A variation of this that should work on most unix-like systems is:
```
#include <sys/mman.h>
#include <inttypes.h>
#include <unistd.h>
int
main(int argc, char **argv)
{
intptr_t ps = getpagesize();
munmap((void *)(((intptr_t)main)&~(ps - 1)), ps);
}
```
We just unmap the page that maps `main` so that when the call to `munmap` returns, it doesn't have anywhere to return to. There's a slight chance that the the function call to `munmap` is just on a page boundary and the return will succeed, so to be perfectly sure this works, we probably have to attempt to unmap two pages first.
And of course, a variation on the same theme:
```
#include <sys/mman.h>
#include <inttypes.h>
#include <unistd.h>
int
main(int argc, char **argv)
{
intptr_t ps = getpagesize();
munmap((void *)(((intptr_t)&ps)&~(ps - 1)), ps);
}
```
Just unmap the stack so that we don't have anywhere to return to. Same caveat as unmapping `main` - we might need to unmap two pages, except that we have to remember that the stack probably grows down (unless you're on PA-RISC or some other strange architecture like that).
Another way to pull the rug from under your own feet:
```
#include <sys/resource.h>
int
main(int argc, char **argv)
{
setrlimit(RLIMIT_CPU, &((struct rlimit){ 0 }));
while(1);
}
```
It is operating system dependent with how the system handles a 0 second cpu limit and how often accounting for cpu time is done. MacOS kills the process immediately, Linux requires the while loop, another system I tried didn't do anything even with a one second limit and a while loop, I didn't debug further.
[Answer]
# sh
```
sudo kill -SEGV 1
```
Instant kernal panic on Linux. Destorys all processes, including itself
# Cmd
```
pskill csrss.exe
```
Instant blue screen on Windows. Terminates the `Client/Server Runtime SubSystem`. Pskill must be installed.
[Answer]
Taking things literally in a silly way with Haskell:
```
import System.Exit
absolutely doThis = if True then doThis else undefined
unconventional doThat = do
putStrLn "I could just do that"
putStrLn "But I'm gonna print factorial of 100 first"
putStrLn "There you go:"
print $ fac 100
doThat
where fac n = foldl (*) 1 [1..n]
main = absolutely unconventional exitFailure
```
[Answer]
**In C (Compatible Windows / Linux / (probably Unix / Freed BSD too)):**
```
main;
```
**Usage example:**
Under Windows compile with:
```
echo main; > main.c && cl /Fe:main.exe main.c
```
And Linux:
```
echo "main;" > main.c && gcc -w -o main main.c
```
Assuming the compiler is installed and in the currenth PATH variable.
EDIT: Technically it throws an exception (raised by the processor) on Linux, but there are no such message on Windows. So this entry probably is not valid; however I think it's cool :P
**EDIT: In x86 assembler (using NAsm/YAsm)**
```
global s
s:
ret
```
Compile with:
(Windows)
```
nasm -f win32 -o test.obj test.asm
LINK /OUT:test.exe /SUBSYSTEM:CONSOLE /ENTRY:s test.obj
```
(Linux)
```
nasm -f elf32 -o test.obj test.asm
ld -o test -e s test.obj
```
Unfortunately this way also produces a core dump on linux, so I believe it's functionally equivalent to the C method; except more efficient.
[Answer]
# Python
---
Using [the `multiprocessing` module](http://docs.python.org/2/library/multiprocessing.html), we can spawn another thread whose job is to communicate with the original process through a queue, telling it when to quit:
```
import multiprocessing
import time
queue = multiprocessing.Queue()
def second_thread():
while True:
queue.put('quit')
time.sleep(0.1)
second_ps = multiprocessing.Process(target = second_thread)
second_ps.start()
while True:
msg = queue.get()
if msg == 'quit':
break
time.sleep(0.1)
second_ps.join()
```
[Answer]
Okay. If simply calling `System.exit` isn't permitted in Java, how about calling it via reflection from another thread?
```
import java.lang.reflect.*;
public class Quit {
public static void main(String[] args) throws Exception {
final Method exit = System.class.getMethod("exit", new Class<?>[]{ int.class });
new Thread(new Runnable() {
@Override public void run() {
try {
System.out.println("calling... " + exit);
exit.invoke(null, new Object[] { 0 });
} catch (Exception e) { e.printStackTrace(); }
}
}).start();
for (int i = 1; ; ++i) {
System.out.println("counting... " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) { break; }
}
}
}
```
Looks up the exit method, spawns a new thread, and counts ~~down~~ until that thread kills the process by calling exit via reflection.
[Answer]
**x86 machine language, 1 character**
You can usually make a workable executable out of one RET instruction
```
\xC3
```
[Answer]
# C (Linux)
## Suicide version
Sends a SIGKILL to itself.
```
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
int main()
{
kill(getpid(),SIGKILL);
printf("Not killed");
}
```
## "Tu quoque mi fili" version
Forks, then the son kills the father.
```
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
int main()
{
if (!fork())
kill(getppid(), SIGKILL);
printf("Not killed");
}
```
[Answer]
# Perl
```
...
```
That is all.
---
Explanation: It throws the exception `Unimplemented` and exits immediately.
[Answer]
## ANSI C
With no code optimisation the following program quits so fast - it can actually not be launched even though it compiles into a valid program
```
#include<stdlib.h>
#include<stdio.h>
char tooLong[0x7CFFFFFF];
void main()
{
printf("never executed.");
}
```
---
this may be system dependent - comment if you can launch it.
[Answer]
# Batch & Debug
An oldie but goodie, works on DOS machines for an instant system reboot. Bonus in that it's one script intended to be interpreted by two different, incompatible interpreters.
## reset.bat
```
goto start
rcs
ffff
rip
0000
g
:start
debug < reset.bat
```
The batch file interpretation skips over the instructions intended for debug, and feeds itself to debug for interpretation. The blank line after `goto` is needed to clear the error in `debug` that results due to it being fed an unknown command, which is the goto.
[Answer]
Java
The below code is not tested and will only work on some platforms.
```
public class Quitter
{
public static void main ( String [ ] args )
{
Process process = Runtime . getRuntime ( ) . exec ( "reboot" ) ;
}
}
```
[Answer]
# Powershell
```
get-process | stop-process -force
```
Save this as 'lastresort.ps1' and it should do the trick.
If you run into problems with the script not executing due to some dumb policy, type this before executing the script:
```
Set-ExecutionPolicy Unrestricted
```
[Answer]
## TI-Basic 84
```
:;;::;banana\\sEnd\;:;1:If X=X-1 :eat banana juice and lol;;;::::;:thought you could EAT THINGS XD /// CRAZIEST ANSWER YET!!!
```
[Answer]
# Python (a one line alternative to the OP)
I figured there wasn't really a better Python answer than what the OP suggested, but I didn't like how it was so many lines, so here's how you do exactly as the OP did but in one line:
```
exec(''.join([ chr(x) for x in [35, 33, 47, 117, 115, 114, 47, 98, 105, 110, 47, 101, 110, 118, 32, 112, 121, 116, 104, 111, 110, 10, 35, 32, 117, 110, 105, 120, 32, 111, 110, 108, 121, 44, 32, 109, 105, 103, 104, 116, 32, 119, 111, 114, 107, 32, 111, 110, 32, 119, 105, 110, 100, 111, 119, 115, 10, 35, 32, 110, 111, 116, 101, 58, 32, 107, 105, 108, 108, 115, 32, 65, 76, 76, 32, 82, 85, 78, 78, 73, 78, 71, 32, 112, 121, 116, 104, 111, 110, 32, 112, 114, 111, 99, 101, 115, 115, 101, 115, 46, 32, 66, 101, 32, 99, 97, 114, 101, 102, 117, 108, 32, 47, 33, 92, 10, 100, 101, 102, 32, 101, 120, 105, 116, 40, 41, 58, 10, 32, 32, 32, 32, 105, 109, 112, 111, 114, 116, 32, 111, 115, 10, 32, 32, 32, 32, 111, 115, 46, 115, 121, 115, 116, 101, 109, 40, 34, 107, 105, 108, 108, 97, 108, 108, 32, 112, 121, 116, 104, 111, 110, 51, 34, 41, 10, 32, 32, 32, 32, 35, 32, 87, 105, 110, 100, 111, 119, 115, 32, 97, 100, 100, 111, 110, 10, 32, 32, 32, 32, 111, 115, 46, 115, 121, 115, 116, 101, 109, 40, 34, 116, 97, 115, 107, 107, 105, 108, 108, 32, 47, 105, 109, 32, 112, 121, 116, 104, 111, 110, 46, 101, 120, 101, 32, 47, 102, 34, 41, 32, 35, 32, 111, 114, 32, 119, 104, 97, 116, 101, 118, 101, 114, 32, 102, 105, 108, 101, 110, 97, 109, 101, 32, 112, 121, 116, 104, 111, 110, 64, 119, 105, 110, 100, 111, 119, 115, 32, 104, 97, 115, 10, 101, 120, 105, 116, 40, 41, 10] ]))
```
You can make this a function and it will do the job for you.
[Answer]
My own idea, not participating
## TIGCC (for Texas Instrumens TI-89, TI-89 Titanium, TI-92+, TI-V200)
```
void main(void) {
unlink("quit");
asm("trap #2");
}
```
## TI-Basic for the same calculators
```
quit()
:© lines starting with © are comments
:Prgm
:©DelVar quit
:Exec "4E424E750000"
:EndPrgm
```
What the program does:
First it deletes itself out of the RAM. (Don't put it to the ROM or it won't work...) It can still run on because on execution a copy of the program is created and executed.
`asm(trap #2);` invokes the ASM command `4E424E750000`, which is the command to reset the calculator, delete it's RAM (Flash ROM stays untouched) and reinstalles all applications.
EDIT: Just tested the Basic version. It can't delete itself...
[Answer]
# MS-DOS .com format
It writes invalid instructions (FFFF) into the memory and then executes them, making NTVDM crash.
## Hexadecimal
```
B8 FF FF A3 06 01
```
## Debug.exe assembly language
```
MOV AX, FFFF
MOV [0106],AX
```
] |
[Question]
[
**Challenge**
Print the numbers:
```
1
22
333
4444
55555
666666
7777777
88888888
999999999
```
In that order.
**I/O**
Takes no input. The numbers can have any delimiters desired (or none). That includes lists, cell arrays, .jpeg, etc.... Example outputs:
```
122333444455555666666777777788888888999999999
[1,22,333,4444,55555,666666,7777777,88888888,999999999]
etc....
```
**Code Example**
This is an un-golfed example that may perhaps act as algorithm guide (or maybe not):
# [Turing Machine Code](http://morphett.info/turing/turing.html), 535 bytes
```
0 * 1 r L
L * _ r 2
2 * 2 r a
a * 2 r M
M * _ r 3
3 * 3 r b
b * 3 r c
c * 3 r N
N * _ r 4
4 * 4 r d
d * 4 r e
e * 4 r f
f * 4 r O
O * _ r 5
5 * 5 r g
g * 5 r h
h * 5 r i
i * 5 r j
j * 5 r P
P * _ r 6
6 * 6 r k
k * 6 r l
l * 6 r m
m * 6 r n
n * 6 r o
o * 6 r Q
Q * _ r 7
7 * 7 r p
p * 7 r q
q * 7 r r
r * 7 r s
s * 7 r t
t * 7 r u
u * 7 r R
R * _ r 8
8 * 8 r v
v * 8 r w
w * 8 r x
x * 8 r y
y * 8 r z
z * 8 r A
A * 8 r B
B * 8 r S
S * _ r 9
9 * 9 r C
C * 9 r D
D * 9 r E
E * 9 r F
F * 9 r G
G * 9 r H
H * 9 r I
I * 9 r J
J * 9 r halt
```
[Try it online!](http://morphett.info/turing/turing.html?af86c0ef679234d7861085b48ba90983)
This prints out the numbers with a space delimiter:
```
1 22 333 4444 55555 666666 7777777 88888888 999999999
```
**Challenge Type**
[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes (by language) wins.
*Based on a [submission in the sandbox](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/18658#18658).*
[Answer]
# Google Sheets, 35 bytes
```
=ArrayFormula(Rept(Row(1:9),Row(1:9
```
Sheets will automatically add three trailing parentheses when you exit the cell. Output is one line per row.
[![results](https://i.stack.imgur.com/b4IMO.png)](https://i.stack.imgur.com/b4IMO.png)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
9L×
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f0ufw9P//AQ "05AB1E – Try It Online")
```
9L Build a list from 1 to 9 {1, 2, 3, 4, 5, 6, 7, 8, 9}
× copy each number that many times
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Core utilities, ~~27~~, 25 bytes
```
seq -f8d%f*7-v1+2/n 45|dc
```
[Try it online!](https://tio.run/##S0oszvj/vzi1UEE3zSJFNU3LXLfMUNtIP0/BxLQmJfn/fwA "Bash – Try It Online")
---
*Changed seq formatting from %0.f to %f for a 2-byte savings.*
*Modified to print on one line, with no delimiters, instead of having a newline after each number, just because I like that better. Same number of bytes.*
---
This uses the formula $$\left\lfloor\frac{\big\lfloor\sqrt{8n-7}\big\rfloor+1}2\right\rfloor$$
for the \$n^{th}\$ digit, where \$n\$ goes from 1 to 45.
[Answer]
# [Python 2](https://docs.python.org/2/), 28 bytes
```
i=1;exec"print`i`*i;i+=1;"*9
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9PW0Dq1IjVZqaAoM68kITNBK9M6UxsoqKRl@f8/AA "Python 2 – Try It Online")
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 6 bytes
Full program, requiring `⎕IO←0`.
```
⍋⍛⌿⍨⎕D
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfz/qG@qp/@jtgkGXEAWkNb4/6i3@1Hv7Ec9@x/1rgCKufzX/A8A "APL (dzaima/APL) – Try It Online")
`⎕D` on the string "0123456789",
`⍛⌿⍨` replicate the characters by
`⍋` their grade (0, 1, 2, …, 9)
[Answer]
# [Kotlin](https://kotlinlang.org), 30 bytes
```
{(1..9).map{"$it".repeat(it)}}
```
[Try it online!](https://tio.run/##DcsxDoAgDADArzTEoR0kcdSIL3DzBQxiGgGJVhfC25Hb77zEc6yf9eAmQIJ@gZUfmTe5OR4LmJpx0HokHWzKqmNR@t7TbgVZqJTq3gjBcmzXQGpJ0CFR/QE "Kotlin – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 18 bytes
```
a=1:9;(10^a-1)/9*a
```
[Try it online!](https://tio.run/##K/r/P9HW0MrSWsPQIC5R11BT31Ir8f9/AA "R – Try It Online")
Use the formula \$\frac{10^n-1}{9}\times n\$ for the \$n\$th number.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 4 bytes
```
\⍨⍳9
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBDGPelc86t1sCQA "APL (Dyalog Unicode) – Try It Online")
### How it works
```
⍳9 ⍝ Integers 1..9
⍨ ⍝ Duplicate argument on each side
\ ⍝ Replicate each element *n* times
```
### Examples
```
Index Generator: ⍳5 = 1 2 3 4 5
Expand: 2 3 \ 1 4 = 1 1 4 4 4
Commute: +⍨4 = 4 + 4 = 8
```
[Answer]
# [Perl 5](https://www.perl.org/), 18 bytes
```
map{say$_ x$_}1..9
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saC6OLFSJV6hQiW@1lBPz/L//3/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 56 bytes
```
+++++++[>+++++++<-]+++++++++[<+[>>.<<-<+>]<[>+<-]>>>+<-]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwKi7aAMG91YbRiItgGK2@nZ2OjaaNvF2gDVAGXt7MDU//8A "brainfuck – Try It Online")
```
+++++++[>+++++++<-] 49 (ASCII "1")
+++++++++[ do 9 times
<+ add 1 to output counter
[ do that many times
>>.<< print character
-<+> move value of output counter to temp
]
<[>+<-] move value of temp back to output counter
>>>+ increment character
<- decrement loop counter
]
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 12 bytes
```
9*
$.`*$.`
```
[Try it online!](https://tio.run/##K0otycxLNPz/n8tSi4tLRS9BC4j//wcA "Retina – Try It Online") Outputs a leading `_` to each number, which appears to be acceptable (would cost 2 bytes to fix if not). Explanation:
```
9*
```
Insert 9 `_`s.
```
$.`*$.`
```
Around each `_`, insert its position repeated appropriately.
[Answer]
# [Haskell](https://www.haskell.org/), ~~30~~ 29 bytes
```
(<$)<*>g<$>g '9'
g c=['1'..c]
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX8NGRdNGyy7dRsUuXUHdUp0rXSHZNlrdUF1PLzn2f25iZp6CrUJBUWZeiUKawv9/yWk5ienF/3WTCwoA "Haskell – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 bytesSBCS
```
⎕D/⍨⍳10
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGIJaL/qPeFY96Nxsa/E8Dij3q7YNIdzUfWm/8qG0ikBcc5AwkQzw8g/@nAQA "APL (Dyalog Unicode) – Try It Online")
Uses `⎕IO←0`.
### How it works
```
⎕D/⍨⍳10
⎕D ⍝ The string '0123456789'
/⍨ ⍝ Replicate each of them the following times...
⍳10 ⍝ 0..9
```
[Answer]
# [Brain-Flak](https://github.com/Flakheads/BrainHack), ~~90~~ 82 bytes
```
([(()()())({}){}]){((({})()<([{}]((((()()()){}){}){}){})>)<{({}()<(({}))>)}{}>)}{}
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fI1pDQxMENTWqazWra2M1qzU0QEwNTRuNaCBfAwQgKsAKoMhO06YaqAykCqQayK@trgUT////13UEAA "Brain-Flak (BrainHack) – Try It Online")
## Explanation:
---
Compare this with the output of [JoKing's autogolfer](https://codegolf.stackexchange.com/a/157666/56656)
# [Brain-Flak](https://github.com/Flakheads/BrainHack), 142 bytes
```
(((((((((((((((((((((((((((((((((((((((((((((((((()()()){}){}){}){}())()))())))()))))())))))()))))))())))))))()))))))))()))))))))){({}<>)<>}<>
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fg2SgCYKa1bVwBOQBERhDCCgJo@A0goHE0qzWqK61sdO0sQOS////13UEAA "Brain-Flak (BrainHack) – Try It Online")
---
# Strange delimiters, 78 bytes
```
([(()()())({}){}]){((({})()<([{}]((((()()()){}){}){}){})>)<{({}()<(({}))>)}>)}
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fI1pDQxMENTWqazWra2M1qzU0QEwNTRuNaCBfAwQgKsAKoMhO06YaqAykCqQayK8Fov///@s6AgA "Brain-Flak (BrainHack) – Try It Online")
If we decide to play around with our delimiters a bit, we can shave off 4 bytes. This version outputs the correct stuff but with two leading null bytes and null bytes between the chunks:
This is a tiny bit cheaty but it meets the specs of the challenge.
---
And for posterity [here](https://tio.run/##SypKzMzLSEzO/v9fAwI0QVCzuhaOgLxoDQ0IL1azGsTU0LQBi0RrAEXsNG2qkcSA/Fo7IF37//9/XUcA "Brain-Flak (BrainHack) – Try It Online") is the old super cheaty version that has been made obsolete by my golfs.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
d´Ṙḣ9
```
[Try it online!](https://tio.run/##yygtzv7/P@XQloc7Zzzcsdjy/38A "Husk – Try It Online")
Output: `122333444455555666666777777788888888999999999`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
9ẋ`€Ḍ
```
[Try it online!](https://tio.run/##y0rNyan8/9/y4a7uhEdNax7u6Pn/HwA "Jelly – Try It Online")
A niladic link returning a list of integers. If a program printing the numbers is preferred, subsitute `Y` for `Ḍ`.
## Explanation
```
9 | Literal 9
ẋ`€ | Repeat each that many times
Ḍ | Convert from decimal digits to integer
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 13 bytes
```
{1..9 Zx^9+1}
```
[Try it online!](https://tio.run/##K0gtyjH7X5xYqaDxv9pQT89SIaoizlLbsPa/pobmfwA "Perl 6 – Try It Online")
Anonymous code block that returns a list of strings by zip string multiplying the range 1 to 9 with itself.
[Answer]
# [R](https://www.r-project.org/), 15 bytes
```
strrep(1:9,1:9)
```
[Try it online!](https://tio.run/##K/r/v7ikqCi1QMPQylIHiDX//wcA "R – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 18 bytes
```
echo u:(#48+])i.10
```
[Try it online!](https://tio.run/##y/r/PzU5I1@h1EpD2cRCO1YzU8/Q4P9/AA "J – Try It Online")
# [K (oK)](https://github.com/JohnEarnest/ok), ~~11~~ 10 bytes
-1 byte thanks to ngn!
```
,/${x}#!10
```
[Try it online!](https://tio.run/##y9bNz/7/X0dfpbqiVlnR0OD/fwA "K (oK) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 46 bytes
```
s;main(n){n>9||main(puts(memset(&s,n+48,n)));}
```
[Try it online!](https://tio.run/##S9ZNT07@/7/YOjcxM08jT7M6z86ypgbMKSgtKdbITc0tTi3RUCvWydM2sdDJ09TUtK79/x8A "C (gcc) – Try It Online")
[Answer]
# x86-16 machine code, IBM PC DOS, ~~18~~ 16 bytes
**Binary**:
```
00000000: b839 0ab2 09b1 2dcd 1048 2aca 4a75 f8c3 .9....-..H*.Ju..
```
**Listing**:
```
B8 0A39 MOV AX, 0A39H ; AH = 0AH, AL = '9'
B2 0A MOV DL, 10 ; DL as counter value
B1 2D MOV CL, 1+2+3+4+5+6+7+8+9 ; start digit repeat 45 times
NLOOP:
CD 10 INT 10H ; call BIOS - write digit * CX times
48 DEC AX ; decrement ASCII digit
4A DEC DX ; decrement counter value
2A CA SUB CL, DL ; reduce digit repeat value by counter
75 F8 JNZ NLOOP ; loop until 0
C3 RET ; return to DOS
```
[Try it online!](http://twt86.co?c=uDkKsgqxLc0QSEoo0XX4ww%3D%3D)
**Explanation**:
This uses the PC BIOS API's `INT 10H` / `0AH` function to write the ASCII char in `AL` to the screen `CX` number of times. However, this function does not update the cursor position to the end of the output -- it just stays where it started. In other words, the next call simply overstrikes existing characters writing over them. Making a BIOS call to advance the cursor is expensive byte-wise.
Since going forward isn't going to work, we go backwards starting from `'9'`. It writes `'9'` 45 times, then `'8'` 36 times, `'7'` 28 times, etc -- each time starting from the first column overwriting like so:
```
999999999999999999999999999999999999999999999
888888888888888888888888888888888888999999999
777777777777777777777777777788888888999999999
666666666666666666666777777788888888999999999
555555555555555666666777777788888888999999999
444444444455555666666777777788888888999999999
333333444455555666666777777788888888999999999
222333444455555666666777777788888888999999999
122333444455555666666777777788888888999999999
```
**Output**:
[![enter image description here](https://i.stack.imgur.com/uUtKa.png)](https://i.stack.imgur.com/uUtKa.png)
[Answer]
# [Java 11 (JDK)](http://jdk.java.net/), ~~60~~ 59 bytes
Not sure if thats the shortest approach but couldn`t make it shorter even without System.out.print.
Output is without delimiters.
*-1 byte thanks to Kevin Cruijssen*
```
v->{for(int i=0;i++<9;System.out.print((i+"").repeat(i)));}
```
[Try it online!](https://tio.run/##LY7BDoIwEETvfMXG0zaExqup@AdyIfFiPNRSSLEU0pYaQ/j2WtDLTnY3M/N6HnjRN68oNHcOrlyZJQNQxkvbciGh2laAMKoGBN42CYSl25qlUYGBMobisrSjxeQCVR6ZyvPzidUf5@VAx9nTyaYXosoPB0KtnCT3qAghbI1b1DQ/tRLgPPdJ9qohgWDtk6@7P4DbzpEfiJHvnRIJNVSgmbX@46zxCw "Java (JDK) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 21 bytes
```
[c<$[1..c]|c<-[1..9]]
```
[Try it online!](https://tio.run/##y0gszk7NyfmfbhvzPzrZRiXaUE8vObYm2UYXxLKMjf2fm5iZp2CrUFCUmVeikP7/X3JaTmJ68X/d5IICAA "Haskell – Try It Online")
A list of lists of numbers.
**23 bytes**
```
replicate<*>id=<<[1..9]
```
[Try it online!](https://tio.run/##y0gszk7Nyfmfbhvzvyi1ICczObEk1UbLLjPF1sYm2lBPzzL2f25iZp6CrUJBUWZeiUL6/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online")
A flat list of numbers.
[Answer]
# [Julia](https://julialang.org), 22 bytes
```
1:9 .|>i->show("$i"^i)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FtsMrSwV9GrsMnXtijPyyzWUVDKV4jI1IZJQNTC1AA)
prints
```
"1""22""333""4444""55555""666666""7777777""88888888""999999999"
```
Relying on the repl for printing output we can get to 17 bytes
```
~i="$i"^i;.~(1:9)
```
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$6\log\_{256}(96)\approx\$ 4.939 bytes
```
Mcd'*_
```
[Try it online!](http://fig.fly.dev/#WyJNY2QnKl8iLCIiXQ==)
Lyxal [tried](https://codegolf.stackexchange.com/a/251799/107299) to outgolf me in my own language again.
```
Mcd'*_ # Full program
cd # Digits
M ' # Map each digit string
* # Repeat the digit
_ # By the number form of it
```
[Answer]
# [Deadfish~](https://github.com/TryItOnline/deadfish-), 194 bytes
```
{{i}ddddd}dc{d}{d}iiic{i}{i}ddcc{d}{d}iic{i}{i}dccc{d}{d}ic{i}{i}cccc{d}{d}c{i}{i}iccccc{d}{d}dc{i}{i}iicccccc{d}{d}ddc{i}{i}iiiccccccc{d}{d}dddc{i}{i}iiiicccccccc{d}{d}ddddc{i}{i}iiiiiccccccccc
```
[Try it online!](https://tio.run/##Tck5DoAwEEPRE3EoZINwTTnK2YcAs8Ry9T6Pnafua3M30@C7QRjHvCRM/BxlSSgKQUmA0MS0H1ObwyssJVO3NVaF@wM "Deadfish~ – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 15 bytes
```
1..9|%{"$_"*$_}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31BPz7JGtVpJJV5JSyW@9v9/AA "PowerShell – Try It Online")
[Answer]
# [Icon](https://github.com/gtownsend/icon), 27 bytes
```
write(1(i:=1to 9,1to i))&\z
```
[Try it online!](https://tio.run/##y0zOz/tfUJSfnJpSWpSqkJuYmaeh@b@8KLMkVcNQI9PK1rAkX8FSB0RmamqqxVT9T81L@Q8A "Icon – Try It Online")
[Answer]
# T-SQL, 69 bytes
```
SELECT top 9replicate(1+number,1+number)FROM spt_values WHERE'p'=type
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1211381/numbers-by-position)**
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 5 bytes
```
⭆χ⭆ιι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaBga6CggeJk6CpmamprW////1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Outputs without separators. The first `StringMap` could be changed into a `for` statement for the same byte count. Explanation:
```
χ Predefined variable 10
⭆ Map over implicit range and join
ι Current index
⭆ Map over implicit range and join
ι Outer index
Implicitly print
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Write a script that works fine when a blank line is present in the flow of program logic, but breaks or causes unexpected behaviour when that line is removed.
Avoid [standard loopholes](http://meta.codegolf.stackexchange.com/q/1061) and stupid answers. Your program should do something "useful," even if all it does is add a few integers.
Removing an empty line from a multiline string doesn't count, unless the expected output from that multiline string shouldn't technically change (ie: if you're removing all blank lines matching `^$`).
Whitespace foolery isn't allowed either; don't do weird things with carriage returns, tabs, spaces, etc.
[Answer]
# Javascript
Opens an alert popup with "Hello, World!" if the blank line exists, otherwise alerts "0".
```
(function(){
alert(~(arguments.callee+[]).indexOf('\n\n') && "Hello, World!");
})();
```
**[Demo](http://jsfiddle.net/fs7C9/)**
**Explanation:**
`arguments.callee` is a reference to the self-executing anonymous function.
Appending a blank array (`[]`) casts the function to a string, which gives you its source code.
`indexOf` returns `-1` if the string is not found.
Performing a bitwise not operation (`~`) results in `-1` being turned into `0`, which is a falsey value.
[Answer]
# C
This magic 8-ball program will still work without the blank line, but it will be a bit more decisive — none of the neutral answers will ever appear in the output.
```
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
int x, t;
char *quotes[] = {
// Positive :-)
"It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it",
"As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes",
// Indifferent :-\
"Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again",
// Negative :-(
"Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful" };
srandom(time(NULL)); // Initialize random number generator
x = random() % (sizeof(quotes) / sizeof(char*)); // Choose a random outcome
printf("The Magic Eight Ball says...\n%s\n",quotes[x]);
return 0;
}
```
### Explanation
>
> When the C parser sees a backslash followed by a newline character, it ignores both and treats the second line as a continuation of the first. Without the empty line, the "indifferent" answers will all be treated as part of the previous comment.
>
>
>
[Answer]
# Befunge-93
```
v
&
&
+
#
.
@
```
My first befunge program :)
It reads two numbers from the input and prints their sum. If you delete the empty line, it doesn't print anything.
**Explanation:**
`v` sets a downward direction for executing the code
`&` reads an integer
`+` adds the numbers together
`#` skips the next command
`.` prints an integer from the stack
`@` ends the program
As written, `#` skips over the empty line and contines with `.`. Buy when you delete the empty line, `.` is skipped.
There seems to be a nice interpreter at <http://befunge.aurlien.net/>
[Answer]
# Ruby/Shell
```
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#! The Amazing Integer Adder !
#! Adds 1 and 1, and displays the result !
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
p 1+1
```
Works fine if a newline is at the top, otherwise the first comment line is interpreted by the shell as a malformed shebang.
[Answer]
# Scala
```
case class IntWrapper(i: Int)
{
val answer = (IntWrapper(0) /: (1 to 100)){(x, y) => IntWrapper(x.i + y)} // Add up ints
println(s"Sum of wrapped integers is $answer")
}
```
If you remove the blank line, no output will be printed. Which is for the best, as your stack would overflow if you actually called `IntWrapper`.
>
> This is a corner case of Scala's semicolon inference. Normally newlines get a semicolon whenever the resulting code would be valid. However, the Scala devs didn't want to force people to use [Egyptian brackets](http://blog.codinghorror.com/new-programming-jargon/), so it's valid to put the brackets for a class definition on the line immediately after - no semicolon is added, even though one could be. However, a blank line divorces the brackets from the class definition. With the blank line removed, the code changes from being a class definition and a block, to a class definition with a constructor - and a recursive constructor at that!
>
>
>
[Answer]
# GolfScript
```
~{.@\%:
}do;
```
Calculates the GCD of two non-zero integers. Removing the blank line breaks the program.
[Try it online.](http://golfscript.apphb.com/?c=IjE1IDI0IiAjIFNpbXVsYXRlIGlucHV0IGZyb20gU1RESU4uCgp%2Bey5AXCU6Cgp9ZG87)
### How it works
This is a GolfScript implementation of the Euclidean algorithm:
```
# STACK: "15 24"
~ # Interpret the input string.
{ # STACK: 15 24
.@ # Duplicate the topmost integer and rotate the other on top of both copies.
# STACK: 24 24 15
\ # Swap the topmost integers.
# STACK: 24 15 24
% # Calculate the modulus.
# STACK: 24 15
}do # If the modulus is non-zero, repeat the loop.
; # Discard the last modulus.
```
There's just one tiny problem:
>
> `{}do` pops the modulus from the stack to check if it's truthy, so it has to get duplicated at the end of the loop. This is normally accomplished by `.`, but `:\n\n` has the same effect: It stores the topmost stack item in the variable LF (`:\n`), then pushes the contents of that variable.
>
>
>
[Answer]
## MediaWiki Template Syntax
Define Template:Foo as
```
{{{a
b|Uh-oh!}}}
```
In another page,
```
{{Foo|a
b=Works!}} <!-- outputs "Works!" -->
{{Foo|a
b=Works!}} <!-- outputs "Uh-oh!" -->
{{Foo|a
b=Works!}} <!-- outputs "Uh-oh!" -->
```
>
> In MediaWiki, parameter names can contain newlines.
>
>
>
[Answer]
# LaTeX (backref)
The following LaTeX code uses a citation and the citation contains a list of pages, where the entry is citated. Here it is the first page. Package `hyperref` also adds PDF links, the page back reference is red, the citation link is green.
```
\documentclass{article}
\usepackage[colorlinks,pagebackref]{hyperref}
\begin{document}
Donald E. Knuth is the inventor of \TeX~\cite{knuth}.
\begin{thebibliography}{9}
\bibitem{knuth}
Donald E. Knuth: \textit{The \TeX book}; Addison Wesley, 1984.
\end{thebibliography}
\end{document}
```
>
> ![Result](https://i.stack.imgur.com/DAE0n.png)
>
>
>
But LaTeX does not require the empty line, the empty line looks superfluous and the example will still work without `hyperref` and the empty line:
```
\documentclass{article}
\begin{document}
Donald E. Knuth is the inventor of \TeX~\cite{knuth}.
\begin{thebibliography}{9}
\bibitem{knuth}
Donald E. Knuth: \textit{The \TeX book}; Addison Wesley, 1984.
\end{thebibliography}
\end{document}
```
>
> ![Result without hyperref](https://i.stack.imgur.com/BqE8G.png)
>
>
>
But the links and back reference are gone, thus we reinsert them:
```
\documentclass{article}
\usepackage[colorlinks,pagebackref]{hyperref}
\begin{document}
Donald E. Knuth is the inventor of \TeX~\cite{knuth}.
\begin{thebibliography}{9}
\bibitem{knuth}
Donald E. Knuth: \textit{The \TeX book}; Addison Wesley, 1984.
\end{thebibliography}
\end{document}
```
But now the example is **broken** and will **not compile** anymore:
```
Runaway argument?
Donald E. Knuth: \textit {The \TeX book}; Addison Wesley, 1984. \end \ETC.
! File ended while scanning use of \BR@@bibitem.
<inserted text>
\par
<*> knuth
?
```
What happened? Package `hyperref` (or more precise package `backref`, which is loaded by `hyperref`) wants to get at the end of the bibliography entry to add the back reference list. But the syntax in LaTeX only provides the beginning of the entry by `\bibitem`, the end can be anywhere. In this emergency package `backref` has added a restriction that `\bibitem` has to end the entry with an empty line. Then the package can redefine `\bibitem` to put the back references at the end of the entry.
Since the empty line is missing, TeX keeps looking for it, but found the end of file instead and issues the error message.
[Answer]
# C (semi-obfuscated)
This little program takes a number on the command line and computes its factorial. However, it also contains cutting-edge AI functionality for runtime verification that the company's coding standards, including the correct use of whitespace and blank lines, are being followed. Removing a blank line will trigger the algorithm to reject the insufficiently maintainable program.
No line continuations or trigraphs anywhere. I believe it is valid ANSI C99.
Due to the advanced mathematics involved, if you compile with `gcc`, remember to use `-lm`.
```
#include <setjmp.h>
#include <stdio.h>
#define max(x,y) ((x<y?y:x))
#define swap(x,y) ((x^=y,y^=x,x^=y))
#include <stdlib.h>
#include <math.h>
#define vfry(x,p,z,y,i) (!!y&((z##z##L##I##p##x##z##z)))
#define NDEBUG
/*
* Proper use of whitespace is essential!
* Please do not remove any blank lines.
*/
const double E = 2.71828182845904523536;
int vrfy(double epsilon, int magic, const char *key, long int L) {
/* You are not expected to understand this */
double x=284.2891,u=2.34e56;
while (rand()+magic*pow(epsilon,sin(x-E))!=log(u*L))
x*=vrfy(1.0/epsilon,(int)u,&key[swap(L,magic)],L++);
return u/lgamma(x);
}
int main(int argc, char *argv[]) {
int N_=831293812; /* do not change, see Knuth 1987 */
if (!vfry(E, N,_, "M=&;VT=I!9", 0xfe86ddcaL)) {
fprintf(stderr, "Code standards violation detected!\n");
abort();
}
if (argc < 2) {
fprintf(stderr, "Usage: %s n\nComputes n!\n", argv[0]);
exit(1);
}
int m=1, n=atoi(argv[1]), i;
for (i=1; i <= n; i++)
m *= i;
printf("%d! = %d\n", n, m);
return 0;
}
```
# Spoiler
>
> The complicated `vrfy` function is never called, but rather the funny-looking `vfry` macro. The use of the preprocessor's [string concatenation feature](http://gcc.gnu.org/onlinedocs/cpp/Concatenation.html) disguises the fact that we are really just checking the parity of `__LINE__`.
>
>
>
[Answer]
# C
This program works as expected (as described in the comments) unless the blank line before `foo = 5;` is removed.
Sadly, I encountered an error almost exactly like this in production code once.
```
#include <stdio.h>
int main()
{
int foo = 0;
#define FROB(x) do { \
x++; \
printf("%d\n", x); \
} while (0); \
foo = 5;
FROB(foo); /* prints 6 */
FROB(foo); /* prints 7 */
FROB(foo); /* prints 8 */
return 0;
}
```
This example uses the `do { ... } while (0)` idiom for creating a multiline statement in a macro (see <https://stackoverflow.com/questions/257418/do-while-0-what-is-it-good-for>). It also uses the backslash character to spread a `#define` over multiple lines, conveniently lined up well out of sight. However, it also does two things kind of wrong:
* There is a semicolon after `while (0)`, while the idiom usually omits this
* There is a backslash after the final line of the `#define`
With this in place, removing the blank line before `foo = 5;` causes that assignment to be executed *after* the `printf`, but also after *every* invocation of the `FROB` macro. As a result, the output after removing the blank line is:
```
1
6
6
```
[Answer]
# C/C++
```
int main(){
return __LINE__ - 3;
}
```
Returns success and can be used as an implementation for [true](http://ss64.com/bash/true.html). If the empty line is removed you can use it as an implementation for [false](http://ss64.com/bash/false.html) instead.
[Answer]
## PowerShell
This function will add two numbers.
```
function add ($a, $b) {
$numbers = @($a `
$b)
$numbers| measure -sum| select -expand sum
}
```
Removing the blank line will cause the function to fail with: `Unexpected token '$b' in expression or statement.`
**Explanation**
>
> Array elements can be separated by newlines and/or commas. Placing the line continuation character (```) after `$a` requires an extra newline to separate `$a` and `$b`. Otherwise, the interpreter views the code as `$numbers = @($a $b)` (no element separator).
>
>
>
[Answer]
## TeX
```
\noindent\everypar{$\bullet$ hello }
world
\bye
```
Without the empty line, "hello" is not printed.
**Explanation**
TeX treats the empty line as a paragraph break, and `\everypar` is executed at the start of a new paragraph.
[Answer]
# Java
```
import java.util.Scanner;
public class BlankLine
{
public static void main( String[] args )
{
//This calculates 2^ given number
//if you remove blank line after the next line it will always print 1
int x = new Throwable().getStackTrace()[0].getLineNumber();
int y = new Throwable().getStackTrace()[0].getLineNumber() - x;
System.out.println("Number:");
Scanner scanner = new Scanner(System.in);
int r = 1;
int n = scanner.nextInt();
for(int i = 0; i < n; i++){
r *= y;
}
System.out.println("2^number: "+r);
}
}
```
>
> x is current line number, y is current line number - x. If there is blank line between them the result is 2. So the code calculates 2 ^ number.
>
>
>
[Answer]
# Perl 5
```
print(<<""
Hello, World!
);
```
This code prints `Hello, World!`. Removing the blank line gives a syntax error instead.
Explanation:
>
> Perl's [here-doc syntax](http://perldoc.perl.org/perlop.html#%3C%3CEOF) for multi-line strings allows an empty terminator string. It's even explicitly documented. Removing the blank line causes the closing parenthesis (and everything else up to the next blank line, if there is one) to be interpreted as part of the string, causing a syntax error.
>
> The error messages you get are actually pretty decent, for such an oddball syntax feature. If there are no blank lines at all in the program after the `print(<<""` line, Perl simply says:
>
>
> ```
> Can't find string terminator "" anywhere before EOF at foo.pl line 1.
> ```
>
> If there *is* an empty line at the end of the program, you get something like this instead:
>
>
> ```
> syntax error at foo.pl line 4, at EOF
> (Might be a runaway multi-line << string starting on line 1)
> Execution of foo.pl aborted due to compilation errors.
> ```
>
>
>
>
>
>
>
>
[Answer]
## Batch
```
@echo off
setLocal enableDelayedExpansion
set NL=^
echo Hello!NL!World
```
This code will output `Hello` and on the next line `World`. When either or both of the blank lines are removed, it outputs nothing at all.
[There is an explanation here](https://stackoverflow.com/questions/6379619/explain-how-dos-batch-newline-variable-hack-works/6379861#6379861).
[Answer]
# Ruby
Deletion of the first line will cause error:
`line = IO.readlines($0).first.chomp
if line.empty?
puts 34+4
else
raise "Please add a newline at the beginning of the program."
end`
[Answer]
# Python
Don't know if this falls under the standard loopholes, I looked at the list and didn't see this.
```
src = open(__file__, 'r')
code = src.readlines()
src.close()
if code[3] == '\n':
print 'Hello World!'
```
Running this regularly returns
```
Hello World!
```
Running it without the blank line on line 4, ie like below:
```
src = open(
__file__, 'r')
code = src.readlines()
src.close()
if code[3] == '\n':
print 'Hello World!'
```
returns nothing.
[Answer]
# Python 2.x
This program outputs the fifth character of the inputted string.
```
import inspect
text = raw_input()
print 'Fifth character of the string:', text[inspect.getlineno(inspect.currentframe())]
```
This isn't in any way hidden. If you remove the empty line, it gives the fourth character and the sixth if you add one.
[Answer]
## Tcl
A function that adds two numbers (and checks if the newline have been deleted):
```
proc add {a b} {
if {[llength [split [info body add] \n]] < 5} {error "function has been modified"}
return [expr $a+$b]
}
```
There's nothing to hide here, it does what it says, so I'm not spoilerizing the explanation. The function `info` is a swiss army knife of introspection (what other languages call reflection). `info body` returns the source code of a function (if not written in C or assembly).
I have to admit that this had me stumped until I saw the javascript solution.
[Answer]
# C
```
#include <stdio.h>
int main() {
const char* a = "You love blank lines.";
#define print_out(a) \
printf("%s\n", a);
a = "You don't seem to love blank lines";
print_out(a);
return 0;
}
```
With the blank line, `a` is the local variable a and without it's the macro parameter...
[Answer]
Technically not a "code" issue, but a server one. If this is sent to Apache from a CGI script (which can be generated with any language you please), it will send an HTTP response to the client:
```
HTTP/1.x 200 OK
Content-Type: text/html; charset=UTF-8
Hello world!
```
On the other hand, this will fail as it is missing the blank space after the header.
```
HTTP/1.x 200 OK
Content-Type: text/html; charset=UTF-8
Hello world!
```
[Answer]
**JavaScript**
The function `whereami` responds with the position of the calling line, relative to its own position in the source code.
```
console.log (whereami ()) //3 line(s) before me
function whereami () {
var a=function a(e){try{to}catch(c){for(var d=c.stack.split("\n"),b=0;b<d.length&&!~d[b].indexOf("a");b++);return c.stack.split("\n")[b+~~e].match(/:(\d+)/)[1]-~~window.hasOwnProperty("__commandLineAPI")}},a1=a(1),i
i= a(2)>a(1)+4?a(1):a(1)>a1+2?a1-1:a/a1
return ((i=(a(2)<i?i-1:a(1)>i+3?a(2)-a(1)-1:a/1)) + " line(s) " ) + (i<a(2)?" after":(i>=a(2)?" before":"confusing")) + " me";
}
console.log (whereami ()) //3 line(s) after me
```
If any blank line in the `whereami` function is removed. The output is `NaN line(s) confusing me`. *(Adding lines doesn't break it)*
>
> It actually only counts how many lines are between `i` and the first and last line respectively. If they fall under a given value. The reference line is set to `NaN` which neither satisfies `NaN<callingLine` nor `NaN>=callingLine`. I tried to hide it a bit in unreadable ternary expressions.
>
>
>
[Answer]
# Perl
```
#!/usr/bin/perl
use strict;
use warnings;
open IN, "<".$0 or die "Did not find input files!";
while (<IN>) {
m/blabla/ && ((<IN> =~ /\}/ && print "tra-la-la...\n") || print "ti-ri-li\n");
}
close IN;
```
>
> This perl script will read the script file and check if after the line containing "blabla" there is a closing bracket.
>
>
>
[Answer]
## Escript
Due to bug in `escript` implementation valid escript has to be at least three lines long and first line hast to be shebang line or empty line. So following script hast to have two empty lines where first one has to be first one:
```
main(_) -> io:format("Hello world!~n", []), halt().
```
Or it hast to be broken in two lines but still has to have first empty line.
```
main(_) ->
io:format("Hello world!~n", []), halt().
```
Otherwise you will get
```
escript: Premature end of file reached
```
[Answer]
# Ruby
```
print %q
2+2=
p(2+2)
```
Prints `2+2=4`, but gives a syntax error without the blank third line. `%q` allows any non-word character to serve as a string delimiter, even the newline character. So the first three lines of code are actually equivalent to `print %q"2+2="`, or just `print "2+2="`. Since the newline after `2+2=` is being used as a quote delimiter, it's not also parsed as a *line* delimiter, so you need another one immediately after.
[Answer]
# Insomnia (both versions)!
```
Þyoo
â
```
This code prints a ~ (don't ask why, insomnia is weird). If you remove the blank line, it prints a ÿ instead.
By the way that first letter is a [thorn](https://en.wikipedia.org/wiki/Thorn_(letter)).
[Answer]
## C++
This is a classic and rather dumb trick. You will know what it is when you see it, this is just here for completion's sake. As such, I'm marking this as a community wiki answer.
```
int main() {
//This program won't work without the next line, why??/
return 1;
}
```
[Why this works](http://en.wikipedia.org/wiki/Digraphs_and_trigraphs#C)
[Answer]
Paste this into a html file, and open it in your browser. It's pretty simple, but a little tricky because it takes the number of blank lines in the document and indexes an array to call a function which shows an alert.
```
<body>
<script>
[null, function(){alert("GIVE ME MY LINE BACK")}, function(){alert("2 + 2 = " + (2+2))}][document.body.innerHTML.split("\n\n").length]()
</script>
</body>
```
This one is borderline rule breaking. Technically JavaScript doesn't have multiline strings, which is the only reason this works.
Because you can have a syntax error in one script tag without interfering with the other script tags this shows a positive result only if there's an error on the page. The error prevents the second alert from firing because it's in the same script tag.
```
<body>
<script>
window.onerror=function(){
alert("2 + 2 = " + (2+2));
}
</script>
<script>
var a = "\
";
alert("GIVE ME MY LINE BACK!");
</script>
</body>
```
[Answer]
Ruby
```
puts (% #{ARGV[0].to_i + ARGV[1].to_i}
)
```
The secret is that the newline, is really a tab, then a new line. I don't know if this counts but I thought it was cleaver. The character after the `%` is also a tab, but for some reason it doesn't show up like one. I'm using Ruby's percent notation to make a string, that adds the first 2 arguments passed to the script. There's more on that here:
<http://teohm.com/blog/2012/10/15/start-using-ruby-percent-notation/>
] |
[Question]
[
# Introduction
It may sound strange, but we haven't got ONE challenge for counting from `1` to `n`, inclusive.
*[This is not the same thing.](/questions/11955) That one is a (closed) not well-explained challenge.*
*[This is not the same thing.](/questions/63834) That one is about counting up indefinitely.*
# Challenge
Write a program or function that prints every integer from `1` to `n` inclusive.
# Rules
* You can get `n` any way.
* You can assume that `n` will always be a positive integer.
* You can get `n` in any base, but you should always output in decimal.
* Output must be separated by any character (or pattern) not in `0123456789`. Non-decimal leading or trailing characters are allowed (for example when using arrays such as `[1, 2, 3, 4, 5, 6]`).
* Standard loopholes are denied.
* We want to find the shortest approach in each language, not the shortest language, so I will not accept any answer.
* You must update your answer(s) after this edit, answers posted before the last edit must comply with the change rule about standard loopholes (I didn't want to deny them, but I didn't want to make the community roar, so I denied them).
* You can use any post-dating language version (or language). You cannot use any language or language version made just for this challenge.
# Bonuses
## 20%
* Your program must be able to count at least up to `18446744073709551615` (`2^64-1`). For example, if a new datatype is the only way to support big integers, you must construct it. If your language does not have any way to support huge integers up to 2^64-1, the upper limit of that particular language must be supported instead.
**EDIT**: I've changed the limit from `2^64` to `2^64-1` to allow more answers.
**EDIT**: I made the 2^64-1 rule a bonus, since there has not been much interest in this challenge. If your answer supports 2^64-1, you can now edit it to include the bonus. Also, you can post an answer not supporting it, if it is shorter.
[Answer]
# [MarioLANG](//esolangs.org/wiki/MarioLANG), 29 bytes
```
;
) <
+===="
>:(-[!
=====#
```
[Try it online!](https://tio.run/##y00syszPScxL///fmktTAQhsuLRtgUCJy85KQzdakQvEsVX@/98UAA)
I know my code is sadly super-sad or angry:
```
>:(
```
# Happy MarioLANG, 46 bytes
```
;
) <
+======="
> >((-[!
=:)^====#
===
```
[Try it online!](https://tio.run/##y00syszPScxL///fmktTAQJsuLRtIUCJy05BwU5DQzdakcvWSjMOJKbMpQAk//83BQA)
A happier approach:
```
:)
```
# Non-emotional MarioLANG, 41 bytes
```
;
) <
+====="
> >(-[!
= "===#
:!
=#
```
[Try it online!](https://tio.run/##y00syszPScxL///fmktTAQRsuLRtQUCJy07BTkM3WpHLVkEJyFfmUrBS5FKwVf7/3xQA)
[Answer]
# Pyth, 1 byte
```
S
```
Body must be at least 30 characters; you entered 14.
[Answer]
# Cjam, 5 bytes
```
{,:)}
```
[Try it online!](http://cjam.tryitonline.net/#code=MTAKCnssOil9Cgp-cA&input=MTA)
This is an unnamed block which expects `n` on the stack and leaves a list with the range `[1...n]` on it.
Works by just building the range with `,` and then incrementing every range element with `:)` to make the range one-based.
[Answer]
# Hexagony, 19
```
$@?!{M8.</(=/>').$;
```
Or in the expanded hexagon format:
```
$ @ ?
! { M 8
. < / ( =
/ > ' )
. $ ;
```
Huge thanks to Martin for [basically coming up with](http://chat.stackexchange.com/transcript/message/29240853#29240853) this program, I just golfed it to fit in a side length 3 hexagon.
[Try it online!](http://hexagony.tryitonline.net/#code=JEA_IXtNOC48Lyg9Lz4nKS4kOw&input=NQ)
I don't have Timwi's fantastic Hexagony related programs, so this explanation won't be very colourful. Instead, you get to read a huge blob of text. Isn't that nice?
In any case, the IP starts at the top left corner, on the `$`, moving Eastward if you imagine this program were placed with North facing upward on a map. The `$` causes us to skip the next instruction, which would be `@`, which would end the program. Instead, we execute `?` which sets the current memory edge to be the input number. Now we reach the end of the row, which takes us to the middle row of the hexagon, still moving Eastward.
Most of the rest of the program is a loop. We start with `.` which is a no-op. Next we encounter a fork in the... uh... hexagon... the `<` instruction causes the IP to rotate 60 degrees to the right if the current memory edge is positive, otherwise we rotate 60 degrees left. Since we are moving Eastward, we either end up with our heading being South or North East. Since the input is greater than zero (and hence positive) we always start by going South East.
Next we hit a `>` which redirects us Eastward; these operators only fork if you hit the fork part. Then we hit `'` which changes what memory edge we are looking at. Then we hit `)` which increments the value of the current memory edge. Since all memory edges start at 0, the first time we do this we get a value of 1. Next we jump up to the second to top line and execute `!` which prints out our number. Then we move to another edge with `{` and store the ASCII value of M multiplied by 10 plus 8 (778). Then we jump back to the second to last line of the hexagon, and hit the `/`. This results in us moving North West. We go past the `.` on the middle row, and come out on the `;` at the bottom right. This prints out the current memory edge mod 256 as ASCII. This happens to be a newline. We hit `'` which takes us back to the first edge that has the value we read in. The we hit `/` which sets us to move Eastward again. Then we hit `(` which decrements the value. `=` causes us to face the right direction again for the future memory edge jumping.
Now, since the value is positive (unless it is zero) we go back to the bottom of the hexagon. Here we hit `.` then we jump over the `;` so nothing happens, and we go back to the start of the loop. When the value is zero we go back to the beginning of the program, where the same stuff happens again but `?` fails to find another number, and we take the other branching path. That path is relatively simple: we hit `{` which changes the memory edge, but we don't care anymore, then we hit `@` which ends the program.
[Answer]
# Mathematica, 5 bytes
```
Range
```
Simple enough.
[Answer]
# MATL, 1 byte
```
:
```
Example output:
```
15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
```
[Try it online here](http://matl.tryitonline.net/#code=Og&input=MTU)
[Answer]
# GNU Coreutils, 6 bytes
```
seq $1
```
split answer to pure bash, see below...
[Answer]
# R, 13 bytes
```
cat(1:scan())
```
Body must be at least 30 characters.
[Answer]
# Javascript ~~182~~ ~~177~~ ~~160~~ ~~154~~ ~~139~~ ~~138~~ 132 bytes (valid)
1 byte saved thanks to @ShaunH
```
n=>{c=[e=0];for(;c.join``!=n;){a=c.length-1;c[a]++;for(;a+1;a--){c[a]+=e;e=0;if(c[a]>9)c[a]=0,e++;}e&&c.unshift(1);alert(c.join``)}}
```
Arbitary precision to the rescue!
Because javascript can only count up to 2^53-1 (Thanks goes to @MartinBüttner for pointing it out), I needed to create arbitary precision to do this. It stores data in an array, and each "tick" it adds 1 to the last element, then goes trough the array, and if something exceedes 9, it sets that element to 0, and adds 1 to the one on the left hand.
[Try it here!](https://jsfiddle.net/f86ursas/1/) *Note: press F12, to actually see the result, as I didn't want to make you wait for textboxes.*
BTW.: I was the only one, who didn't know, ternary operators are so useful in codegolf?
```
if(statement)executeSomething();
```
is longer than
```
statement?executeSomething():0;
```
by 1 byte.
# Javascript, 28 bytes (invalid - can't count to 264)
```
n=>{for(i=0;i++<n;)alert(i)}
```
[Answer]
## Java 8, 43/69/94 bytes
~~Crossed out 44 is still a regular 44 -- wait, I didn't cross it out I just replaced it :(~~
If I can return a [`LongStream`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/LongStream.html): (`43 bytes`)
```
n->java.util.stream.LongStream.range(1,n+1)
```
This is a lambda for a `Function<Long,LongStream>`. Technically, I should use [`rangeClosed`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/LongStream.html#rangeClosed-long-long-) instead of [`range`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/LongStream.html#range-long-long-), as I'm cutting off one from my maximum input in this way, but `rangeClosed` is longer than `range`.
If I have to print in the function: (`69 bytes`)
```
n->java.util.stream.LongStream.range(1,n+1).peek(System.out::println)
```
This is a lambda for a `Consumer<Long>`. Technically I'm abusing [`peek`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/LongStream.html#peek-java.util.function.LongConsumer-), as it is an [intermediate operation](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps), meaning this lambda is technically returning a `LongStream` like the first example; I should be using [`forEach`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/LongStream.html#forEach-java.util.function.LongConsumer-) instead. Again, golf is not nice code.
Unfortunately, since `long`'s range is a *signed* 64-bit integer, it does not reach the requested `2^64-1`, but merely `2^63-1`.
*However*, Java SE 8 provides functionality to treat `long`s *as if* they were unsigned, by calling specific methods on the `Long` class explicitly. Unfortunately, as Java is still Java, this is rather long-winded, though shorter than the BigInteger version that it replaces. (`94 bytes`)
```
n->{for(long i=0;Long.compareUnsigned(i,n)<0;)System.out.println(Long.toUnsignedString(++i));}
```
This is a `Consumer<Long>`, as the previous.
And just too long to avoid scroll.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 1 byte
Code:
```
L
```
[Try it online!](http://05ab1e.tryitonline.net/#code=TA&input=MTU).
A more interesting approach:
```
FN>,
```
Explanation:
```
F # For N in range(0, input):
N> # Push N + 1
, # Pop and print with a newline
```
[Try it online!](http://05ab1e.tryitonline.net/#code=Rk4-LA&input=MTU).
[Answer]
## [MarioLANG](http://esolangs.org/wiki/MarioLANG), 19 bytes
```
;
)<
+"
:[
(-
>!
=#
```
[Try it online!](http://mariolang.tryitonline.net/#code=OwopPAorIgo6WwooLQo-IQo9Iw&input=NTY)
Vertical programs are usually more golfable for simple loops in MarioLANG. I'm not sure *what* the interpreter does when encountering `[` inside an elevator, but it seems to terminate the program when the current cell is 0. That's probably a useful trick in general.
### Explanation
MarioLANG is a Brainfuck-like language (with an infinite memory tape of arbitrary-precision integers) where the instruction pointer resembles Mario walking and jumping around.
Mario starts in the top left corner and falls downward. `;` reads an integer from STDIN and places it in the current memory cell. Now note that `=` is a ground cell for Mario to walk on, the `"` and `#` form an elevator (with `#` being the start) and `!` makes mario stop on the elevator so that he doesn't walk off right away. The `>` and `<` set his movement direction. We can see that this gives a simple loop, containing the following code:
```
) Move memory pointer one cell right.
+ Increment (initially zero).
: Print as integer, followed by a space.
( Move memory pointer one cell left.
- Decrement.
[ Conditional, see below.
```
Now normally `[` would conditionally make Mario skip the next depending on whether the current cell is zero or not. That is, as long as the counter is non-zero this does nothing. However, it seems that when Mario encounters a `[` while riding an elevator *and* the current cell is `0`, the program simply terminates immediately with an error, which means we don't even need to find a way to redirect him correctly.
[Answer]
# MATLAB, 7 bytes
An unnamed anonymous function:
```
@(n)1:n
```
Run as:
```
ans(10)
ans =
1 2 3 4 5 6 7 8 9 10
```
[Test it here!](https://ideone.com/jGGYgQ)
---
If a full program is required, 17 bytes:
```
disp(1:input(''))
10
1 2 3 4 5 6 7 8 9 10
```
[Test it here!](https://ideone.com/0ggsdY)
[Answer]
## ArnoldC, 415 bytes
```
IT'S SHOWTIME
HEY CHRISTMAS TREE n
YOU SET US UP 0
GET YOUR ASS TO MARS n
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
HEY CHRISTMAS TREE x
YOU SET US UP n
STICK AROUND x
GET TO THE CHOPPER x
HERE IS MY INVITATION n
GET DOWN x
GET UP 1
ENOUGH TALK
TALK TO THE HAND x
GET TO THE CHOPPER x
HERE IS MY INVITATION n
GET DOWN x
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED
```
The only thing of interest is to use n-x (where n is the goal and x the incremented variable) to test the end of the while loop instead of having a dedicated variable, so I end up having n-x and n-(n-x) = x in each loop run
**Note**: I can only count to 2^31-1. Well I guess the Terminators are not a real danger after all.
[Answer]
## Haskell, 10 bytes
```
f n=[1..n]
```
Usage example: `f 4`-> `[1,2,3,4]`.
[Answer]
# [Joe](//github.com/JaniM/Joe) - 2 or 6
While you can use the inclusive variant of the range function..
```
1R
```
..that's boring! Let's instead take the cumulative sum (`\/+`) of a table of ones of shape n (`1~T`).
```
\/+1~T
```
[Answer]
# Pyth - ~~3~~ 2 bytes
*1 bytes saved thanks to @DenkerAffe.*
Without using the builtin.
```
hM
```
[Try it online](http://pyth.herokuapp.com/?code=hM&input=5&debug=0).
[Answer]
## Pyke, 1 byte
```
S
```
[Try it here!](http://pyke.catbus.co.uk/?code=S&input=10)
Or 2 bytes without the builtin
```
mh
```
[Try it here!](http://pyke.catbus.co.uk/?code=mh&input=10)
```
#h
```
[Try it here!](http://pyke.catbus.co.uk/?code=%23h&input=10)
```
Lh
```
[Try it here!](http://pyke.catbus.co.uk/code)
[Answer]
# dc, 15
```
?[d1-d1<m]dsmxf
```
Input read from stdin. This counts down from `n`, pushing a copy of each numbers to the stack. The stack is then output as one with the `f` command, so the numbers get printed in the correct ascending order.
Because all the numbers are pushed to the stack, this is highly likely to run out of memory before getting anywhere near 2^64. If this is a problem, then we can do this instead:
---
# dc, 18
```
?sn0[1+pdln>m]dsmx
```
[Answer]
# Piet, 64 Codels [codelsize 1](https://i.stack.imgur.com/iZZJC.png)
With codelsize 20:
[![codelsize 20](https://i.stack.imgur.com/wiRvD.png)](https://i.stack.imgur.com/wiRvD.png)
### Npiet trace images
First loop:
[![tracestart](https://i.stack.imgur.com/asQ0j.png)](https://i.stack.imgur.com/asQ0j.png)
Remaining trace for `n=2`:
[![traceend](https://i.stack.imgur.com/wCwhi.png)](https://i.stack.imgur.com/wCwhi.png)
### Notes
* No Piet answer yet? Let me fix that with my first ever Piet program! This could probably be shorter with better rolls and less pointer manipulation though...
* The upper supported limit depends on the implementation of the interpreter. It would theoretically be possible to support arbitraryly large numbers with the right interpreter.
* The delimeter is `ETX` (Ascii `3`), however this cannot be properly displayed in this answer so I'll just leave them out. It works in the console:
[![enter image description here](https://i.stack.imgur.com/zrPkE.png)](https://i.stack.imgur.com/zrPkE.png)
### Output
```
Input: 1
Output: 1
Input: 20
Output: 1234567891011121314151617181920
Input: 100
Output: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
Undefined behaviour:
Input: -1
Output: 1
Input: 0
Output: 1
```
### Npiet trace for `n=2`
```
trace: step 0 (0,0/r,l nR -> 1,0/r,l lB):
action: in(number)
? 2
trace: stack (1 values): 2
trace: step 1 (1,0/r,l lB -> 2,0/r,l nB):
action: push, value 1
trace: stack (2 values): 1 2
trace: step 2 (2,0/r,l nB -> 3,0/r,l nG):
action: duplicate
trace: stack (3 values): 1 1 2
trace: step 3 (3,0/r,l nG -> 4,0/r,l dY):
action: out(number)
1
trace: stack (2 values): 1 2
trace: step 4 (4,0/r,l dY -> 5,0/r,l lY):
action: push, value 1
trace: stack (3 values): 1 1 2
trace: step 5 (5,0/r,l lY -> 6,0/r,l lG):
action: add
trace: stack (2 values): 2 2
trace: step 6 (6,0/r,l lG -> 7,0/r,l lR):
action: duplicate
trace: stack (3 values): 2 2 2
trace: step 7 (7,0/r,l lR -> 10,0/r,l nR):
action: push, value 3
trace: stack (4 values): 3 2 2 2
trace: step 8 (10,0/r,l nR -> 12,0/r,l dR):
action: push, value 2
trace: stack (5 values): 2 3 2 2 2
trace: step 9 (12,0/r,l dR -> 13,0/r,l lB):
action: roll
trace: stack (3 values): 2 2 2
trace: step 10 (13,0/r,l lB -> 14,0/r,l lG):
action: duplicate
trace: stack (4 values): 2 2 2 2
trace: step 11 (14,0/r,l lG -> 15,2/d,r nG):
action: push, value 3
trace: stack (5 values): 3 2 2 2 2
trace: step 12 (15,2/d,r nG -> 15,3/d,r dG):
action: push, value 1
trace: stack (6 values): 1 3 2 2 2 2
trace: step 13 (15,3/d,r dG -> 14,3/l,l lR):
action: roll
trace: stack (4 values): 2 2 2 2
trace: step 14 (14,3/l,l lR -> 13,1/l,r lC):
action: greater
trace: stack (3 values): 0 2 2
trace: step 15 (13,1/l,r lC -> 11,1/l,r nC):
action: push, value 3
trace: stack (4 values): 3 0 2 2
trace: step 16 (11,1/l,r nC -> 10,1/l,r lB):
action: multiply
trace: stack (3 values): 0 2 2
trace: step 17 (10,1/l,r lB -> 9,1/l,r nY):
action: pointer
trace: stack (2 values): 2 2
trace: step 18 (9,1/l,r nY -> 7,1/l,r dY):
action: push, value 2
trace: stack (3 values): 2 2 2
trace: step 19 (7,1/l,r dY -> 6,1/l,r lY):
action: push, value 1
trace: stack (4 values): 1 2 2 2
trace: step 20 (6,1/l,r lY -> 5,1/l,r nM):
action: roll
trace: stack (2 values): 2 2
trace: step 21 (5,1/l,r nM -> 4,1/l,r dM):
action: push, value 3
trace: stack (3 values): 3 2 2
trace: step 22 (4,1/l,r dM -> 3,1/l,r lG):
action: pointer
trace: stack (2 values): 2 2
trace: step 23 (3,1/d,r lG -> 2,3/l,l nG):
action: push, value 3
trace: stack (3 values): 3 2 2
trace: step 24 (2,3/l,l nG -> 2,2/u,r lY):
action: out(char)
trace: stack (2 values): 2 2
trace: white cell(s) crossed - continuing with no command at 2,0...
trace: step 25 (2,2/u,r lY -> 2,0/u,r nB):
trace: step 26 (2,0/u,r nB -> 3,0/r,l nG):
action: duplicate
trace: stack (3 values): 2 2 2
trace: step 27 (3,0/r,l nG -> 4,0/r,l dY):
action: out(number)
2
trace: stack (2 values): 2 2
trace: step 28 (4,0/r,l dY -> 5,0/r,l lY):
action: push, value 1
trace: stack (3 values): 1 2 2
trace: step 29 (5,0/r,l lY -> 6,0/r,l lG):
action: add
trace: stack (2 values): 3 2
trace: step 30 (6,0/r,l lG -> 7,0/r,l lR):
action: duplicate
trace: stack (3 values): 3 3 2
trace: step 31 (7,0/r,l lR -> 10,0/r,l nR):
action: push, value 3
trace: stack (4 values): 3 3 3 2
trace: step 32 (10,0/r,l nR -> 12,0/r,l dR):
action: push, value 2
trace: stack (5 values): 2 3 3 3 2
trace: step 33 (12,0/r,l dR -> 13,0/r,l lB):
action: roll
trace: stack (3 values): 2 3 3
trace: step 34 (13,0/r,l lB -> 14,0/r,l lG):
action: duplicate
trace: stack (4 values): 2 2 3 3
trace: step 35 (14,0/r,l lG -> 15,2/d,r nG):
action: push, value 3
trace: stack (5 values): 3 2 2 3 3
trace: step 36 (15,2/d,r nG -> 15,3/d,r dG):
action: push, value 1
trace: stack (6 values): 1 3 2 2 3 3
trace: step 37 (15,3/d,r dG -> 14,3/l,l lR):
action: roll
trace: stack (4 values): 2 3 2 3
trace: step 38 (14,3/l,l lR -> 13,1/l,r lC):
action: greater
trace: stack (3 values): 1 2 3
trace: step 39 (13,1/l,r lC -> 11,1/l,r nC):
action: push, value 3
trace: stack (4 values): 3 1 2 3
trace: step 40 (11,1/l,r nC -> 10,1/l,r lB):
action: multiply
trace: stack (3 values): 3 2 3
trace: step 41 (10,1/l,r lB -> 9,1/l,r nY):
action: pointer
trace: stack (2 values): 2 3
trace: white cell(s) crossed - continuing with no command at 9,3...
trace: step 42 (9,1/d,r nY -> 9,3/d,l nR):
```
[Answer]
## JavaScript (ES6), ~~77~~ ~~76~~ ~~63~~ ~~59~~ 58 Bytes
```
n=>{for(s=a=b=0;s!=n;console.log(s=[a]+b))a+=!(b=++b%1e9)}
```
Takes input `n` as a string, should support up to 9007199254740991999999999
Explained:
```
n=>{ //create function, takes n as input
for( //setup for loop
s=a=b=0; //init s, a, and b to 0
s!=n; //before each cycle check if s!=n
console.log(s=[a]+b) //after each cycle concat a and b into to s and print
)
a+=!(b=++b%1e9) //During each cycle set b to (b+1)mod 1e9, if b == 0 and increment a
} //Wrap it all up
```
[Answer]
# Oration, 31 bytes
```
literally, print range(input())
```
[Answer]
# GNU bc, 23
```
n=read()
for(;i++<n;)i
```
Input read from stdin. `bc` handles arbitrary precision numbers by default, so the 2^64 max is no problem.
[Answer]
## Actually, 1 byte
```
R
```
Boring builtin is boring. Requires a 64-bit version of Python 3 to get all the way up to `2**64`.
[Try it online!](http://actually.tryitonline.net/#code=Ug&input=MjU1) (due to memory and output length restrictions, the online interpreter can't go very high).
Here's a 5-byte version that doesn't require 64-bit Python 3 and is a little nicer on memory usage:
```
W;DWX
```
[Try it online!](http://actually.tryitonline.net/#code=VztEV1g&input=MjU1&args=) (see above caveats)
[Answer]
# Fuzzy-Octo-Guacamole, 7 bytes
```
^!_[+X]
```
Explanation:
```
^ get input to ToS
! set for loop to ToS
_ pop
[ start for loop
+ increment ToS (which aparently happens to be 0)
X print ToS
] end for loop
```
[Answer]
## QBASIC, 43 bytes
```
1 INPUT a
2 FOR b=1 TO a
3 PRINT b
4 NEXT b
```
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 17 bytes
```
..U;I0-!@;)wONow!
```
[Try it here](https://ethproductions.github.io/cubix)
Cubix is a 2D language created by @ETHProductions where the commands are wrapped onto a cube. This program wraps onto a cube with an edge length of 2 as follows.
```
. .
U ;
I 0 - ! @ ; ) w
O N o w ! . . .
. .
. .
```
* `I` gets the integer input
* `0` push 0 to the stack
* `-` subtract top items of stack
* `!` if truthy jump the next command `@` terminate
* `;` pop the subtraction result from the stack
* `)` increment top of stack
* `w` move ip to the right and carry on. This causes it to drop to the next line
* `O` output the top of stack as a number
* `N` push linefeed (10) to the stack
* `o` output a linefeed
* `w` move ip to the right and carry on. This causes it to drop to the next face
* `!` because TOS truthy, jump the `@` terminate
* `;` pop the linefeed from the stack
* `U` uturn to the left onto the `-` subtraction and resume from there
[Answer]
# [Sesos](https://github.com/DennisMitchell/sesos), 3 bytes
```
Hexdump of generated binary file:
0000000: 16f8ce ...
Size : 3 byte(s)
```
[Try it online!](http://sesos.tryitonline.net/#code=c2V0IG51bWluCnNldCBudW1vdXQKam1wCnN1YiAxCmZ3ZCAxCmFkZCAxCnB1dApyd2QgMQ&input=MjA&debug=on)
Assembler:
```
set numin
set numout
get
jmp
sub 1
fwd 1
add 1
put
rwd 1
;implicit jnz
```
Brainfuck pseudocode: `,[->+.<]`
[Answer]
# Python 2, ~~37~~ ~~33~~ ~~32~~ 33 bytes
```
for i in xrange(input()):print-~i
```
Presumably works up to `2**64` and beyond.
*Shot down four bytes thanks to @dieter*, *and another thanks to @orlp*. *But apparently, as @Sp3000 found out, `range()` might have issues with higher values, so the function was changed to `xrange()`*. *Note: even `xrange()` might have issues, at least in 2.7.10*.
[Answer]
# Zsh, 12 bytes
```
echo {1..$1}
```
This works because variables are expanded before the braces.
] |
[Question]
[
The flag of Bangladesh is very simple. It looks like below:
[![enter image description here](https://i.stack.imgur.com/JaXP4.png)](https://i.stack.imgur.com/JaXP4.png)
The flag will be in bottle green (#006a4e) and rectangular in size in the proportion of length to width of 10:6, with a red circle in near middle. The red circle (#f42a41) will have a radius of one-fifth of the length of the flag. This image will help you to understand the proportions properly:
[![enter image description here](https://i.stack.imgur.com/U4J11.png)](https://i.stack.imgur.com/U4J11.png)
In this Graphical output challenge, you need to draw the flag of Bangladesh like first image. Standard loopholes apply, Shortest code wins.
Resolution cannot be 0px, or `echo` style answers not supported.
Minimum resolution is `286*176`
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes
¯\\_\_(ツ)\_/¯ of course there is a built in for this...
```
"BD"~CountryData~"Flag"
```
but you can also get the same result with...
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 78 bytes
```
Graphics@{(c=RGBColor)@"#006a4e",{0,0}~Cuboid~{5,3},c@"#f42a41",Disk[{9,6}/4]}
```
[![enter image description here](https://i.stack.imgur.com/mvuhS.png)](https://i.stack.imgur.com/mvuhS.png)
-8 bytes {first code) thanks to @Makonede for "Bangladesh" to "BD"
-4 bytes (second code) thanks to @att
[Answer]
# SVG, 67 bytes
By tweaking the viewBox, we can take advantage of the fact that the stroke of a shape has a default width. That avoids creating any element for the background.
```
<svg viewBox=-.9,-.6,2,1.2><circle r=.9 fill=#f42a41 stroke=#006a4e
```
[Answer]
# SVG in HTML, 74 bytes
```
<svg viewBox=-9,-6,20,12 style=background:#006a4e><circle r=4 fill=#f42a41
```
-8 bytes by [Joey](https://codegolf.stackexchange.com/users/15/joey)
[Answer]
# Python3 + [Turtle](https://docs.python.org/3/library/turtle.html), ~~112~~ 84 bytes
```
from turtle import*
setup(286,176)
bgcolor("#006a4e")
ht()
bk(14)
dot(114,"#f42a41")
```
-28B thanks to Digital Trauma
Can't try it online but here is how it looks:
![Turtle Screenshot](https://i.stack.imgur.com/FXqFN.png)
[Answer]
# HTML, 110 bytes
```
<div style=padding:10%35%10%25%;background:#006a4e><nav style=padding:50%;background:#f42a41;border-radius:50%
```
-1 bytes by Ad√°m
Fun fact: percentage values on `padding-top` / `padding-bottom` follow the container’s width (not height).
[Answer]
# Bash + ImageMagick, ~~80~~ 79 characters
```
convert -size 500x300 xc:#006a4e -draw 'fill #f42a41 circle 225,150,225,250' x:
```
Thanks to
* [Chris Down](https://codegolf.stackexchange.com/users/6534/chris-down) for pointing out word I missed in man bash: “a word *beginning* with `#` causes that word and all remaining characters on that line to be ignored”
Sample output:
![flag of Bangladesh](https://i.stack.imgur.com/vDRHy.png)
[Answer]
## CSS, ~~128~~ ~~107~~ ~~104~~ 89 bytes
```
*{background:radial-gradient(200px at 45%,#f42a41 50%,#006a4e 0)0 0/500px 300px no-repeat
```
For best results run the code snippet and then click Full Page. Edit: Worked out that setting the background position and size works better than setting the body size. Saved 3 bytes thanks to @sech1p. Saved 15 bytes by copying @dingledooper's radial gradient.
[Answer]
# [PostScript](https://en.wikipedia.org/wiki/PostScript), ~~114~~ 95 bytes
Code:
```
0 .42 .31 setrgbcolor
0 0 300 180 rectfill
.96 .16 .25 setrgbcolor
135 90 60 0 360 arc fill
```
Result:
[![result](https://i.stack.imgur.com/VBGew.png)](https://i.stack.imgur.com/VBGew.png)
[Answer]
# [Red](http://www.red-lang.org), 101 bytes
```
Red[Needs:'view]view[base 500x300 0.106.78
draw[pen 244.42.65 fill-pen 244.42.65 circle 225x150 100]]
```
[![Flag of Bangladesh, drawn in Red](https://i.stack.imgur.com/krn2V.png)](https://i.stack.imgur.com/krn2V.png)
[Answer]
# Perl 5, 89 bytes
Using [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) for Linux-like command terminals. [WSL](https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux) in Windows should also work:
```
print"\33[0;3",($_%286-129)**2+($_/286-88)**2<3442?"1m#":"2m#",$_%286?"":"\n"for 1..50336
```
Run it in a terminal like this to get a big or small flag respectively in ansi colors or via a [.ppm image file](https://en.wikipedia.org/wiki/Netpbm#PPM_example) that can show the flag using most image viewers or web browsers:
```
perl -e'print"\33[0;3",($_%286-129)**2+($_/286-88)**2<3442?"1m#":"2m#",$_%286?"":"\n"for 1..50336'
perl -e'print"\33[0;3",($_%72-32)**2+($_/72-22)**2<215?"1m##":"2m##",$_%72?"":"\n"for 1..3168'
perl -E'say"P3 286 176 255 ",map 3442>($_%286-129)**2+($_/286-88)**2?"244 42 65 ":"0 106 78 ",1..50336' > flag.ppm
```
[Answer]
# [R](https://www.r-project.org/), ~~143~~ ~~111~~ ~~108~~ 92 bytes
```
plot(0:9,,"n",as=1)
rect(0,0,10,6,,,"#006a4e",NA)
symbols(4.5,3,2,f=NA,bg="#f42a41",i=F,a=T)
```
[Try it on rrdr.io](https://rdrr.io/snippets/embed/?code=plot(0%3A9%2C%2C%22n%22%2Cas%3D1)%0Arect(0%2C0%2C10%2C6%2C%2C%2C%22%23006a4e%22%2CNA)%0Asymbols(4.5%2C3%2C2%2Cf%3DNA%2Cbg%3D%22%23f42a41%22%2Ci%3DF%2Ca%3DT))
*-32 bytes after looking at [@Dominic's answer to related challenge](https://codegolf.stackexchange.com/a/211475/55372)
-3 bytes thanks to [@Frédéric](https://codegolf.stackexchange.com/users/56131/fr%c3%a9d%c3%a9ric)*
Slighlty ungolfed to show full argument names (R allows partial matching):
```
plot(x=0:9,y=NULL,type="n",asp=1)
rect(0,0,10,6,col="#006a4e",border=NA)
symbols(4.5,3,circles=2,fg=NA,bg="#f42a41",inches=F,add=T)
```
[![result image](https://i.stack.imgur.com/Ua5fJ.png)](https://i.stack.imgur.com/Ua5fJ.png)
[Answer]
# C + stb\_image\_write, ~~296~~ ~~288~~ ~~278~~ 270 bytes
```
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include"stb_image_write.h"#include<math.h>
main(i){char p[151008];for(i=0;i<151008;i+=3){p[i]=0;p[i+1]=106;p[i+2]=78;if(pow(i/3%286-129,2)+pow(i/3/286-88,2)<3481)p[i]=244,p[i+1]=42,p[i+2]=65;}stbi_write_bmp("b.bmp",286,176,3,p);}
```
Outputs a BMP image called b.bmp:
[![enter image description here](https://i.stack.imgur.com/wiDJ5.png)](https://i.stack.imgur.com/wiDJ5.png)
Thanks to MerseyViking for the suggestion about removing `sqrt`
[Answer]
# [HTML](https://en.wikipedia.org/wiki/HTML), 95 bytes
```
<p style="width:500;height:300;background:radial-gradient(200px at 45%,#f42a41 50%,#006a4e 0)">
```
[Try it online!](https://www.w3schools.com/code/tryit.asp?filename=GPQTJHFVBSWQ)
[Answer]
# Basic (Tandy CoCo3 specifically), 109 Bytes
Firstly, hopefully there isn't a 'hard fast' rule on the exact color when the target computer only has a palette of 64 total... :-) I got as close as I could. I used the darkest green available and the 2nd darkest red.
Also, putting a CoCo3 in graphic mode doesn't "stay" unless you put some kind of pause at the end - but at 0.89 MHz it draws slowly enough you can see the result before it disappears back to text mode.
```
HSCREEN1:PALETTE1,2:PALETTE2,32:HCOLOR1,3:HLINE(0,0)-(299,179),PSET,BF:HCIRCLE(134,89),60,2:HPAINT(99,89),2,2
```
That said, if you did want to "press Enter to erase" and make it re-runnable without retyping in the line, it'll cost 9 bytes:
```
0 HSCREEN1:PALETTE1,2:PALETTE2,32:HCOLOR1,3:HLINE(0,0)-(299,179),PSET,BF:HCIRCLE(134,89),60,2:HPAINT(99,89),2,2:INPUTK
```
then type 'RUN'. Here's a screenshot of the result (emulated via VCC 2.1.0c on Server 2016):
[![enter image description here](https://i.stack.imgur.com/Gguyl.png)](https://i.stack.imgur.com/Gguyl.png)
The resolution of the flag is 300x180; the resolution of the video mode is 320x192, hence the (default) brighter green border on the edges.
Lastly, the program technically takes less bytes than I specified as it's tokenized, but I don't feel like doing that math.
[Answer]
# Gnuplot, ~~147~~ ~~140~~ ~~137~~ ~~120~~ 112 bytes
```
se si rat-2
se xr[0:20]
se yr[0:6]
uns ti
uns ke
uns bor
p'-'w cir fs s fc rgb var
9 3 99 27214
9 3 4 16001601
e
```
Written out neatly:
```
# set length unit ratio on 2:1
set size ratio -2
# set axis ranges
set xrange[0:20]
set yrange[0:6]
# make it look less like a chart
unset tics
unset key
unset border
# plot inline data series (everything on the next lines, up to an 'e')
# data cx cy radius color (rgb, decimal)
p '-' with cirles fillstyle solid fillcolor rgb variable
9 3 99 27214
9 3 4 16001601
e
```
Result in the 'qt' terminal:
[![Bangladesh flag, rendered using Gnuplot](https://i.stack.imgur.com/zvnIh.png)](https://i.stack.imgur.com/zvnIh.png)
[Answer]
# [PHP](https://php.net/), 129 bytes
```
($f=imagecolorallocate)($i=imagecreate(500,300),0,106,78);imagefilledellipse($i,225,150,200,200,$f($i,244,32,65));imagepng($i,a);
```
You cannot try it online as online testers logically disable image creation functions.
Here is the result (original file is called "a", I added the extension for the import)
[![enter image description here](https://i.stack.imgur.com/cc9T0.png)](https://i.stack.imgur.com/cc9T0.png)
[Answer]
# [p5.js](https://editor.p5js.org/), 97 bytes
```
setup=x=>createCanvas(300,180)+background(0,106,78)+fill(244,42,65)+noStroke()+circle(135,90,120)
```
[Answer]
# Ruby with Shoes, 87 characters
```
Shoes.app(width:500,height:300){background'006a4e'
stroke fill'f42a41'
oval 125,50,200}
```
Sample output:
![flag of Bangladesh](https://i.stack.imgur.com/MMxQS.png)
[Answer]
# Python + Pygame, 124 bytes
```
from pygame import*
s=display.set_mode((286,176))
s.fill((0,106,78))
draw.circle(s,(244,42,65),(128,86),57)
display.update()
```
I haven't used Pygame in a long time, so I'm probably missing something obvious here (like setting the background of the window directly) but it's not the shortest answer overall either.
*-7 bytes thanks to @tsh's suggestion*
*-31 bytes thanks to @ChrisH and @Sadap*, wow I really need to learn Pygame again
[Answer]
# Python 3
I tried different solutions, here are my two best attempts...
## Python + turtle, 113 bytes
*Thanks to @Sadap to give me some hints on an "alternative" use of the turtle :)*
```
from turtle import*
s=Screen()
s.screensize(300,180,'#006a4e')
s.setup(305,183)
ht()
setx(-15)
dot(120,'#f42a41')
```
[![python + turtle](https://i.stack.imgur.com/ojVh9.png)](https://i.stack.imgur.com/ojVh9.png)
Commented code:
```
from turtle import*
# initialize a new window
s=Screen()
# define the turtle drawing area, with thee green background
s.screensize(300,180,'#006a4e')
# setup the size of the window
# slightly bigger than the drawing area, to avoid the scroll bars
s.setup(305,183)
# hide turtle default image
ht()
# from the center of the image, move to the left
# center of the circle
setx(-15)
# draw the red circle
dot(120,'#f42a41')
```
---
## Python + tkinter, 132 bytes
```
from tkinter import*
c=Canvas(Tk(),bg='#006a4e',width=300,height=180)
c.create_oval(75,30,195,150,fill='#f42a41',width=0)
c.pack()
```
[![python + tkinter](https://i.stack.imgur.com/SGsgp.png)](https://i.stack.imgur.com/SGsgp.png)
Commented code:
```
from tkinter import*
# initialize a new window, setting the background color and the size
c=Canvas(Tk(),bg='#006a4e',width=300,height=180)
# draw the red circle
c.create_oval(75,30,195,150,fill='#f42a41',width=0)
# add the circle to the canvas
c.pack()
```
[Answer]
# [Lua](https://www.lua.org/) + [LÖVE/Love2D](https://love2d.org/), ~~176~~ 160 bytes
```
l=love;g=l.graphics;c=255;l.window.setMode(500,300)function l.draw()g.setBackgroundColor(0,106/c,78/c)g.setColor(244/c,42/c,65/c)g.circle('fill',225,150,100)end
```
-16 bytes thanks to [@manatwork](https://codegolf.stackexchange.com/users/4198/manatwork)
[![Screenshot](https://i.stack.imgur.com/RBujW.png)](https://i.stack.imgur.com/RBujW.png)
[Answer]
# stacked, 93 bytes
```
400 setwidth 240 setheight'#006a4e'setbg'#f42a41'allstyle'370px Arial'font 69 226 to'‚óè'text
```
[Online interpreter.](https://conorobrien-foxx.github.io/stacked/stacked.html) Here's the output generated (Firefox, latest version):
[![picture of bangladesh flag generated by stacked program](https://i.stack.imgur.com/KaDEk.png)](https://i.stack.imgur.com/KaDEk.png)
Or, a screenshot of the webpage:
[![screenshot of the program and bangladesh flag it generates](https://i.stack.imgur.com/hJ920.png)](https://i.stack.imgur.com/hJ920.png)
## Explanation
Simply initializes the canvas with appropriate dimensions, sets the appropriate background color, and then draws a bullet character of the correct font height and location. We have to do this because stacked has no native way of drawing circles arbitrarily. The correctness of these arbitrary values can be verified with the following program, which draws a square on the lower-right quadrant of where the circle ought to be:
```
400 setwidth 240 setheight'#006a4e'setbg'#f42a41'allstyle'370px Arial'font 69 226 to'‚óè'text
'white' allstyle
180 120 to
[80 go 90 turn] 4*
```
[![bangladesh flag with white measuring square on lower right quadrant](https://i.stack.imgur.com/5UL0y.png)](https://i.stack.imgur.com/5UL0y.png)
[Answer]
# HTML / Pug + Tailwind, 96 bytes
```
.w-80.py-8.pl-20(style='background:#006a4e')
.rounded-full.w-32.h-32(style='background:#f42a41')
```
[Test](https://jsitor.com/26bCEpc2c)
# HTML / Pug + Tailwind, slightly changed colors, 64 bytes
```
.w-80.py-8.pl-20.bg-green-800
.rounded-full.w-32.h-32.bg-red-600
```
[Test](https://jsitor.com/yyuCSEocV)
[Answer]
# HTML/CSS, 168 bytes
```
<div><div style=left:125;top:50;width:200;height:200;background:#f42a41;border-radius:50%><style>div{position:fixed;left:0;top:0;width:500;height:300;background:#006a4e
```
You can try it out [here](https://www.w3schools.com/code/tryit.asp?filename=GPU3SVQLA5X1) (doesn't seem to work as a snippet, for whatever reason...)
-1 byte thanks to Ad√°m by removing the `}` at the end of the style block
-2 bytes thanks to Manish Kandu
-12 bytes thanks to pxeger
-13 bytes thanks to Neil
[Answer]
# [Scratch](https://scratch.mit.edu/), ~~230~~ 201 bytes
[Try it online!](https://scratch.mit.edu/projects/518572657)
-26 thanks to @att, who used pen size to skip the lengthy circle formula!
Scratchblocks can't understand that hex values are literally what the value should be, and incorrectly displays a color. Visually, changing `set[C v]to[#123abc` to `set pen color to(#123abc` would work in Scratchblocks (and save bytes in the process), but due to Scratch's HSL system, such a color cannot be reached without hacks. Using the built-in eyedrop tool, we can get close (almost indistinguishable to the human eye) but it is only an approximation. Alternatively, ~~23~~ 15 blocks.
```
when gf clicked
go to x:(240)y:(
erase all
set pen size to(288
set[C v]to(27214
set pen color to(C
pen down
set x to(-240
set[C v]to[#f42a41
set x to(-24
set pen size to(192
set pen color to(C
pen down
```
[Answer]
# [Racket](https://racket-lang.org/), 110 bytes
```
#lang slideshow
(pin-over(colorize(filled-rectangle 300 180)'(0 106 78))75 30(colorize(disk 120)'(244 42 65)))
```
[Can't try it online!](https://tio.run/##RYu7CoQwEAB7v2LB4rKFEGN8/I4kqy4uRhK5A38@5iqrgWEmzm6nK@da5mOFJOwpbeFXqZOPJnwpKhckRL5JLSxCvonkrtIKQac1tJPGjyrUA4wT4tgX/T6e0w6t@TfGWrAGhh4Rc34A "Racket – Try It Online"), but here's a screenshot:
[![enter image description here](https://i.stack.imgur.com/OZ9Ea.png)](https://i.stack.imgur.com/OZ9Ea.png)
[Answer]
# FLTK, 135 characters
```
Function{}{}{Fl_Window{}{xywh{0 0 500 300}box BORDER_BOX color 0x6a4eff}{Fl_Box{}{xywh{125 50 200 200}box OFLAT_BOX color 0xf42a41ff}}}
```
Ungolfed:
```
Function {} {} {
Fl_Window {} {
xywh {0 0 500 300}
box BORDER_BOX
color 0x6a4eff
} {
Fl_Box {} {
xywh {125 50 200 200}
box OFLAT_BOX
color 0xf42a41ff
}
}
}
```
Sample output:
![flag of Bangladesh](https://i.stack.imgur.com/oV2k1.png)
[Answer]
# p5.js, ~~105~~ ~~98~~ 96 bytes
```
draw=x=>createCanvas(300,180)+background(0,106,78)+noStroke()+fill(244,42,65)+circle(135,90,120)
```
Try it in the editor [here](https://editor.p5js.org/).
[Answer]
# [Desmos](https://www.desmos.com), ~~64~~ 61 bytes
```
r=rgb(244,42,65)
g=rgb(0,106,78)
-9<=x<=11\{yy<36\}
xx+yy<=16
```
[Try it on Desmos!](https://www.desmos.com/calculator/tj1ipkdqvw)
*-3 bytes thanks to Aiden Chow*
[Answer]
# Javascript + HTML, ~~167~~ 153
## Javascript: ~~154~~ 140, HTML: 13
```
C.width=w=300
C.height=h=180 // 300 * 0.6
with(C.getContext`2d`)fillStyle="#006a4e",fillRect(0,0,w,h),fillStyle="#f42a41",arc(.45*w,.3*w,.2*w,0,7),fill()
```
```
<canvas id=C>
```
-14 characters from @Ismael Miguel
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 7 years ago.
[Improve this question](/posts/5760/edit)
**Puzzle:**
Write a short, three-line program which:
* has 5/7/5 syllables per line when read aloud
* outputs a haiku when run.
An example of a program having the correct structure, but non-haiku output, is (Python):
```
>>> for x in range(3):
... print "EXTERMINATE HUMANS"
... # I am a Dalek.
...
EXTERMINATE HUMANS
EXTERMINATE HUMANS
EXTERMINATE HUMANS
```
(The comment is a bit of a cop-out.)
This reads aloud as:
>
> for x in range three
>
>
> print EXTERMINATE HUMANS!
>
>
> I am a Dalek.
>
>
>
Any language is acceptable. For the purposes of reading aloud, symbols like `!@#$%^&*()_+` can be ignored if you want, or pronounced aloud, admitting something like [Waka Waka Bang Splat](http://babek.info/libertybasicfiles/lbnews/nl123/fun.htm). (I'm sure there will be a Perl entry like `!***(!:, )(*@@@#, )_(*)!.`)
Extra points if either the code or the output is especially funny, or especially zen.
---
Edit: If your language requires boilerplate before it can do anything interesting (`#include <iostream>`?) then I'm happy to ignore the boilerplate.
---
I've accepted Paul Richter's Common Lisp haiku on the grounds that it made me laugh for a good five minutes.
Honorable mention for Timwi's creative rule-bending (*compiler* output?!) and for the extremely memorable line `"Static void. I long for you."`
>
> Now this question ends;
>
>
> Many more haikus await.
>
>
> **Continue posting!**
>
>
>
[Answer]
# C#
Program:
```
#warning Lonesome
class _{
static void Eye(long forYou='
){ /* My program ends here. */ ;}}
```
Read:
```
Warning: Lonesome class.
Static void. I long for you.
My program ends here.
```
*Compiler* output:
```
#warning: 'Lonesome' (read: hash warning lonesome)
Empty character literal (read: empty character lit’ral)
Newline in constant
```
[Answer]
## Piet, 867 executing color blocks
Grand Prize, you say? This has codel size of 2.
![a haiku that prints itself](https://i.stack.imgur.com/22e5A.png)
Output:
```
SPRING EVER RETURNS
NEVER EXACTLY THE SAME
THIS IS NOT A QUINE
```
This challenge was fun! I've written a [Piet instruction encoder](http://meta.codegolf.stackexchange.com/a/374/2180) that takes instructions and translates them into a Piet script. It's short work from there to generate code to print a given string. I put a small (but effective) amount of effort into golfing the Piet code while only using single-codel instructions.
I then made a pixel font. For every pixel in a character, I blow it up into 4 codels: 2 black, and 2 executed. The first codel encountered is non-executing, so if a segment of a character has *n* pixels, for example, that corresponds to 2\*n\*-1 instructions.
The lines down the sides reverse the direction pointer and move it down by 2 pixels, taking it to the next row. Thus, instructions are reversed on every other line.
Once I had code to produce "text embedded in text", it gets fun. I probably wrote 20 haiku along the way, but I eventually settled. By tweaking the font; adding / removing serifs, rounding corners, changing height / width, etc., I was able to alter the total number of nonwhite pixels in the image such that the Piet code fit exactly into the image text.
Bonus! You can make your own quinelike haiku! <http://pastebin.com/zxc9V3UX>
[Answer]
## Common Lisp
Parentheses are silent!
Program:
```
((lambda (&rest foo)
(list foo (cons 'truly foo) foo))
'this 'is 'lisp 'haiku)
```
Read as:
```
lambda and rest foo
list foo cons truly foo foo
this is lisp haiku
```
Output:
```
((THIS IS LISP HAIKU) (TRULY THIS IS LISP HAIKU) (THIS IS LISP HAIKU))
```
[Answer]
## Perl
```
$_
= "Repeating myself"
;print"$_\nis like $_.\n$_.\n";
```
How to read it out loud:
```
dollar underscore
equals repeating myself
print nis like line noise.
```
Output:
```
Repeating myself
is like Repeating myself.
Repeating myself.
```
[Answer]
## INTERCAL
INTERCAL has limited output capabilities, but "limited capabilities" has never stopped me from writing an INTERCAL program!
```
DO READ OUT #18
+#3301
+#214
PLEASE GIVE UP
```
Please read [out] this as:
```
Do read out eighteen,
Three thousand three hundred one,
Two hundred fourteen.
```
(Note that my boilerplate is at the end of the program instead of at the beginning.)
The program produces the output:
```
XVIII
MMMCCCI
CCXIV
```
Which, when spoken aloud, goes:
```
Ex vee eye eye eye,
Em em em cee cee cee eye,
Cee cee ex eye vee.
```
[Answer]
## CoffeeScript
With tongue firmly in cheek, I present CoffeeScript:
```
here = "my haiku"
were_doomed() unless 1 is 1
alert Date.now()
```
Pronounced:
```
Here is my haiku
We're doomed unless one is one
alert date dot now
```
If your timing is right (!), your output might be e.g. 1337181872717, pronounced:
```
one three three seven
one eight one eight seven two
seven one seven
```
Considering my first run at this was one microsecond out from a valid haiku response, I think that's zen enough to qualify!
NB: I'd be happy to hear sufficiently zen alternatives for my first two (admittedly weak) lines.
[Answer]
# J
Program:
```
p:i.4
*:*:*:i.3
!8
```
Read (substituting verb names):
```
Prime Integers Four
Square Square Square Integers 3
Factorial Eight
```
Output (read numbers out loud):
```
2 3 5 7
0 1 256 (Read: Zero One Two-Fifty-Six)
40320 (Read: Forty Three-Twenty)
```
[Answer]
## Python
Code:
```
for _ in range(1,3):
print 'Hi ' * 5, 'there ' * 2 * (-1+_)
print 'I now', 'go ' * 3
```
How to read:
```
for in range one three
print hi five there two one plus
print i now go three
```
Output:
```
Hi Hi Hi Hi Hi
Hi Hi Hi Hi Hi there there
I now go go go
```
Working sample: <http://ideone.com/hDniW>
[Answer]
## logo
Here's a Haiku procedure that's also a quine procedure (easy because of logo's introspection capability)
```
to better_yourself
printout "better_yourself
end ; as you began
```
Read as
>
> To better yourself
>
> Print out quote better yourself
>
> End as you began
>
>
>
[Answer]
# JavaScript (doesn't work in Firefox)
```
(function haiku() { with (
console) log ((('' + haiku). // output
replace) (/[ !-@{-~[-^]+/gim, ' ')); void haiku })()
```
works except for mozilla
javascript engine and shows
spelling after ran
[Answer]
## Ruby
```
"A ruby haiku.
Why, yes, it is."; print open(
__FILE__).read #this now, please.
```
Read as:
```
A ruby haiku.
Why, yes, it is. Print open
file. Read this now, please.
```
It doesn't flow very well, unfortunately. In my defense, it *is* 12:50am...
[Answer]
# Python
(Only read the first level of parentheses (not the second)).
Code and how to read:
```
for e in range(3): # for e in range three
if True is False: what = then # if true is false, what is then?
print "oh " * (5 + 2 * (e & 1)) # print oh times _seven_
```
Output, probably most basic haiku in the world:
```
oh oh oh oh oh
oh oh oh oh oh oh oh
oh oh oh oh oh
```
[Answer]
# Python (2 entries)
## Entry 1: A haiku in time
You need to save this in a file and run it from the same directory. This haiku very slowly prints itself out to screen, a poem in words and time.
```
from time import sleep
for line in open(__file__):
print line; sleep(len(line))
```
## Entry 2: A haiku without symbolism
This is similar to the above, but was an attempt to write a Python haiku that used just keywords and minimal brackets or substitutions of symbols (eg. `=` pronounced as "is").
```
if __file__ is not None:
for line in open(__file__):
print not False and line
```
[Answer]
# Tcl
Here's a self-documenting, self-outputting, example:
```
catch {me as I make}
proc unknown args {puts [read $args]}
[open [info script]]
```
[Answer]
# Vim
```
ia0 <esc><c-x>
YpA-<esc>
px5<c-x><c-x>
```
read as
```
i a zero x
Y p A hyphen escape
p x five x x
```
Writes:
```
a-1
a-1-
-7
```
read as:
```
a negative one
a minus one negative
negative seven
```
[Answer]
# Python 3
```
print(print.__doc__[:15])
print(print.__doc__[13:][:13])
print(print.__doc__[32])
```
Read as:
```
print print doc one five
print print doc one three one three
print print doc three two
```
Prints:
```
print(value, ..
..., sep=' ',
\
```
Read as:
```
print value dot dot
ellipses, sep equals blank
reverse solidus
```
] |
[Question]
[
In this challenge, we will together create a word-search containing many programs in different languages.
I have started us off with a grid of 60-by-25 blanks (`·`), some of which are replaced by the characters of a Ruby program.
To answer, choose a language that was not yet used. Using your chosen language, write a program that **reads a character, token, line, *or* all input from the console, and prints it**. Then, insert your program into the word-search.
For example, suppose you choose Python 3 for your answer, and write the program `print(input())`. Now you have to insert that program into the grid.
If the grid before your answer looks like this:
```
···a·24··········
··z····t·········
```
Then you can just put your program in the second line, overlapping with the existing `t`:
```
···a·24··········
··zprint(input())
```
Note that you can place your program in any direction: forward, backward, upward, downward, or diagonally, as long as it's in a straight line.
But what if the existing grid looks like this:
```
···a·24··········
··z····q·········
```
There's no way to fit the `print(input())` here without changing existing characters, which is forbidden. Instead, you can change the program:
```
print(
input())
```
This two-line program fits neatly:
```
···a·24·print(···
··z····q input())
```
Here you replace a blank (`·`) with a space (). However, a space is just like any other character, and can not be overwritten in future programs.
Just like a one-liner, a multi-line program can be placed in any direction. For example, in a larger grid, you could do the following, by rotating the program 135° clockwise.
```
··········
········ ·
·······i·p
······n·r·
·····p·i··
····u·n···
···t·t····
··(·(·····
·)········
)·········
```
## Scoring
Your score for each answer is thirty divided by the number of characters added. Do not count characters that already existed in the grid, even if you use them yourself.
Your total score is the sum of the scores for all of your answers, multiplied by the number of answers. Highest score wins.
# Rules
* Every answer must be written in a different language. Languages that differ only in version number (e.g., Python 2 and Python 3) are considered the same.
* Every answer must build off of the most recent valid answer. That is, take the grid of the most recent such answer, and insert your program into it.
* To insert your program, replace at least one of the blanks (`·`) with characters of your choice. You may use existing characters from the grid in your answer, but you may not change or move any of them.
* You may not insert more than 500 characters in total, across all your answers.
* All characters you insert must be part of your program.
* Your program may consist only of printable ASCII and newlines, but there may not be two or more consecutive newlines back-to-back.
* Newlines do not count towards your score.
* A full program, not just a function or snippet, is required.
* The same user may not write two consecutive answers.
* If someone's answer violates a rule, leave a comment. If the mistake is not fixed in 30 minutes, it should be deleted.
# Used language snippet
This is a Stack Snippet, made by ETHproductions, FryAmTheEggman, and Mauris, that keeps track of users' scores and the used languages. It was originally copied from [Martin Büttner's amazing template](http://meta.codegolf.stackexchange.com/questions/5139/leaderboard-snippet).
Original leaderboard:
```
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,r){return"http://api.stackexchange.com/2.2/answers/"+r.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 r=+e.share_link.match(/\d+/);answer_ids.push(r),answers_hash[r]=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=[],r={},x={};answers.forEach(function(s){var a=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(a="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var n=a.match(SCORE_REG);if(n){var t=getAuthorName(s);e.push({user:getAuthorName(s),size:+n[2],language:n[1],link:s.share_link}),r[t]=r[t]||0,r[t]+=30/+n[2],x[t]=x[t]||0,x[t]++}});Object.keys(r).forEach(function(e){r[e]*=x[e]});var s=Object.keys(r).sort(function(e,s){return r[s]-r[e]});e.sort(function(e,r){var s=e.size,a=r.size;return s-a});var a={},t=null;e.forEach(function(e){t=e.size;var r=e.language;/<a/.test(r)&&(r=jQuery(r).text()),a[r]=a[r]||{lang:e.language,user:e.user,size:e.size,link:e.link}});for(var c=0,o=1;c<s.length;c++){var i=jQuery("#author-template").html();r[s[c]]!==r[s[c-1]]&&(o=c+1);i=i.replace("{{PLACE}}",o+'.').replace("{{NAME}}",s[c]).replace("{{SCORE}}",r[s[c]].toFixed(2)),jQuery("#authors").append(jQuery(i))}var u=[];for(var m in a)a.hasOwnProperty(m)&&u.push(a[m]);u.sort(function(e,r){var s=e.lang.replace(/<.*?>/g,"").toLowerCase(),a=r.lang.replace(/<.*?>/g,"").toLowerCase();return s>a?1:a>s?-1:0});for(var l=0;l<u.length;++l){var h=jQuery("#language-template").html(),m=u[l];h=h.replace("{{LANGUAGE}}",m.lang).replace("{{NAME}}",m.user).replace("{{SIZE}}",m.size).replace("{{LINK}}",m.link),h=jQuery(h),jQuery("#languages").append(h)}}var QUESTION_ID=57327,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",OVERRIDE_USER=16294,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}#author-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="author-list"> <h2>Leaderboard</h2> <table class="author-list"> <thead> <tr><td></td><td>Author</td><td>Score</td></tr></thead> <tbody id="authors"> </tbody> </table> </div><div id="language-list"> <h2>Languages</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="author-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{SCORE}}</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>
```
New (experimental) version, using a modified formula:
```
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,r){return"http://api.stackexchange.com/2.2/answers/"+r.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 r=+e.share_link.match(/\d+/);answer_ids.push(r),answers_hash[r]=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=[],r={},x={};answers.forEach(function(s){var a=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(a="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var n=a.match(SCORE_REG);if(n){var t=getAuthorName(s);e.push({user:getAuthorName(s),size:+n[2],language:n[1],link:s.share_link}),r[t]=r[t]||0,r[t]+=30/+n[2]+20,x[t]=x[t]||0,x[t]++}});var s=Object.keys(r).sort(function(e,s){return r[s]-r[e]});e.sort(function(e,r){var s=e.size,a=r.size;return s-a});var a={},t=null;e.forEach(function(e){t=e.size;var r=e.language;/<a/.test(r)&&(r=jQuery(r).text()),a[r]=a[r]||{lang:e.language,user:e.user,size:e.size,link:e.link}});for(var c=0,o=1;c<s.length;c++){var i=jQuery("#author-template").html();r[s[c]]!==r[s[c-1]]&&(o=c+1);i=i.replace("{{PLACE}}",o+'.').replace("{{NAME}}",s[c]).replace("{{SCORE}}",r[s[c]].toFixed(2)),jQuery("#authors").append(jQuery(i))}var u=[];for(var m in a)a.hasOwnProperty(m)&&u.push(a[m]);u.sort(function(e,r){var s=e.lang.replace(/<.*?>/g,"").toLowerCase(),a=r.lang.replace(/<.*?>/g,"").toLowerCase();return s>a?1:a>s?-1:0});for(var l=0;l<u.length;++l){var h=jQuery("#language-template").html(),m=u[l];h=h.replace("{{LANGUAGE}}",m.lang).replace("{{NAME}}",m.user).replace("{{SIZE}}",m.size).replace("{{LINK}}",m.link),h=jQuery(h),jQuery("#languages").append(h)}}var QUESTION_ID=57327,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",OVERRIDE_USER=16294,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}#author-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="author-list"> <h2>Leaderboard</h2> <table class="author-list"> <thead> <tr><td></td><td>Author</td><td>Score</td></tr></thead> <tbody id="authors"> </tbody> </table> </div><div id="language-list"> <h2>Languages</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="author-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{SCORE}}</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>
```
To ensure your submission is recognized by the snippet, please use the following header template:
```
# Language, X characters added
```
[Answer]
# Java, 124 characters added
While there is still room!
```
class C{public static void main(String[]a) throws Throwable{
System.out.println(new java.util.Scanner(System.in).next());
}}
```
The grid is now
```
····························································
···········i········a·······································
··········?pio;·····l·······································
··········,u········e·······································
··········.t········r·······································
··········@s········t·······································
··········· ··printf(·······································
···········g·· input('','s'))····························
···········e·····n··r·······································
········write(read-host)····································
·········E·s········m·······································
········C·E·········p·······································
·······H·T··········t·····················r·················
······O· ···········(·······································
····· ·/············)·······································
····%·P·············)·······································
···A· ······················································
··%·A·······················································
···=························································
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
··························································}}
····························································
····························································
····························································
```
Made a ninja edit and reversed the code in the grid, since OP states the code can be backwards. Then retrofitted it into the next answer
[Answer]
# Mumps, 23 characters added
Sorry again for missing the one requirement in the question.
here's my new submission:
```
s t=" " r t#50:20 w !,t,!
```
This sets the t variable to a space, then reads at most 50 characters from standard input with a 20 second timeout writes a newline, the variable, then another newline. (Many mumps terminals get kinda messy if you don't do that...)
The grid is now:
```
····························································
···········i········a·······································
··········?pio;·····l·······································
··········,u········e·······c·······························
··········.t········r·······a·······························
··········@s······s t=" " r t#50:20 w !,t,!·················
··········· ··printf(·······(·······························
···········g·· input('','s'))····························
···········e·····n··r·······c·······························
········write(read-host)····a·······························
·········E·s········m·······n·······························
········C·E·········p·······(·······························
·······H·T··········t·······,·············r·················
······O· ···········(·······'·······························
····· ·/············)·······'·······························
····%·P·············)·······)·······························
···A· ······················)·······························
··%·A·······················································
···=························································
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
··························································}}
····························································
····························································
····························································
```
that gosh darned R submission made this a bit tougher to write... :-)
[Answer]
# [Beatnik](https://esolangs.org/wiki/Beatnik), 29 characters added
```
Get a chr!
Outputs it
and 'BZam.
```
Explanation coming:)
>
> **Get a** # ignored with scrabble values under 5
>
> **chr!** # score 8, input a character and push its value
>
> **Outputs** # score 9, pop a number and output it's character
>
> **it and** # ignored with scores under 5
>
> **'BZam.** # score 17 terminates the program
>
>
>
The new grid
```
·········v---H\·············································
·········>qir@uH····a·······································
Get a chr!?pio;·····l·······································
Outputs it,u········e·······c·······························
and 'BZam..t········r·······a·······························
··········@s······s t=" " r t#50:20 w !,t,!·················
··········· ··printf(·······(·······························
···········g·· input('','s'))····························
···········e·····n··r·······c·······························
········write(read-host)····a·······························
·········E·s········m·······n·······························
········C·E·········p·······(·······························
·······H·T··········t·······,·············r·················
······O· ···········(·······'·······························
····· ·/············)·······'·······························
····%·P·············)·······)·········1·····················
···A· ······················)········n······················
··%·A·······························-·······················
···=······························· ···$·d··················
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
································e···a·····················}}
·······························h···=························
··································<·························
·································>··························
```
[Answer]
# C, 27 characters added
Somebody mentioned C, and I saw that it was still possible.
```
main( ){printf("%c", (getchar()));}
```
New grid:
```
·········v---H\·············································
······,··>qir@uH···IaP.·····································
Get a chr!?pio;·····l·······································
Outputs it,u········e·······c··········print(readline())····
and 'BZam..t········r·······a·······························
········~,@s······s t=" " r t#50:20 w !,t,!·················
······main( ){printf("%c", (getchar()));}··················
···········g·> input('','s'))····························
···········e·····n··r·······c·········g·····················
·······(write(read-host)····a)········r······ ··············
·······))E·s········m·······n)········e·····················
········C·E·········p·······((·······{print;exit}····K······
·······H·T··········t·······,t········ ···r·················
······O· ···········(·······'u········-·····················
····· ·/············)·······'p········m·····················
····%·P·············)·······)n········1·····················
···A· ······················)io······n ·····················
··%·A························(······-·.·····················
···=·························t\···· ···$·d··················
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
·····························r··e···a b c d e f g h i·····}}
·····························p·h···=b c d e f g h i·········
··································<·························
·································>··························
```
[Answer]
# [???](https://esolangs.org/wiki/%3F%3F%3F), 1 character added
```
?!
```
The grid is now:
```
·········v---H\·············································
·········>qir@uH····a·······································
·········!?pio;·····l·······································
··········,u········e·······c·······························
··········.t········r·······a·······························
··········@s······s t=" " r t#50:20 w !,t,!·················
··········· ··printf(·······(·······························
···········g·· input('','s'))····························
···········e·····n··r·······c·······························
········write(read-host)····a·······························
·········E·s········m·······n·······························
········C·E·········p·······(·······························
·······H·T··········t·······,·············r·················
······O· ···········(·······'·······························
····· ·/············)·······'·······························
····%·P·············)·······)·········1·····················
···A· ······················)········n······················
··%·A·······························-·······················
···=······························· ···$·d··················
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
································e···a·····················}}
·······························h···=························
··································<·························
·································>··························
```
[Answer]
# [Urn](http://esolangs.org/wiki/Urn), 3 characters added
```
(:::)
```
The new grid:
```
·········v---H\··v+C+<D_··············S·P··············;····
G`····,··>qir@uH· IaP.C·············A·USE: io·········>····
Get a chr!?pio;····Ol···············Y·Lreadln(write(···;····
Outputs it,u········e·······c······ ·L·print(readline())····
and 'BZam..t········r·······a·····ai ··string))··<v;i:j;p:j·
G·······~,@s······s t=" " r t#50:20 w !,t,!······?a?·:·E····
G·····main( ){printf("%c", (getchar()));}·······pr>·:·;····
O·········)g·> input('','s'))·················h_··)·P····
a··········e·····n··r·····^·c·········g··········pd····;····
·······(write(read-host)····a)········r·input n$!?u····(····
·······))E·s········m·······n)···KVGH·e·print n$!·m····;····
········C·E·········p·······((···TIIA{print;exit}·pYEK·*····
$'main'H·T··········t·······,t···HSMI· ···r·······(·········
\/\··O· ···········(·······'u···XIM ·-···········$·········
\/· ·/(println····)·······'p···BBE1·m···········a·········
\%·PQ (read-line))······)n···YLH.·1···········r·········
A\ /-io-\············)io··EE 4n ·····`·····g·········
% A\-e-< |·············(···· V-·.··di _r(a)·v·········
$ = \----#·············t\···V ···$;di $a····)·········
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
·····························r··e···a b c d e f g h i·····}}
···········>maertsoi<edulcni#p·h···=b c d e f g h i·········
····;s gnirts::dts{)(niam tni····v< o<····················
···};s<<tuoc::dts;s>>nic::dts····>i:1+?/;···················
```
[Answer]
# Ruby, 9 characters added
```
puts gets
```
The grid is now:
```
····························································
····························································
···········p················································
···········u················································
···········t················································
···········s················································
··········· ················································
···········g················································
···········e················································
···········t················································
···········s················································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
```
[Answer]
# Pyth, 1 character added
```
w
```
The grid is now:
```
····························································
····························································
··········?pio··············································
··········,u················································
··········.t················································
···········s················································
··········· ················································
···········g················································
···········e················································
········w··t················································
···········s················································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
```
[Answer]
# LISP, 3 characters added
```
(write(read
))
```
The new grid:
```
·········v---H\·············································
·········>qir@uH····a·······································
Get a chr!?pio;·····l·······································
Outputs it,u········e·······c·······························
and 'BZam..t········r·······a·······························
··········@s······s t=" " r t#50:20 w !,t,!·················
··········· ··printf(·······(·······························
···········g·· input('','s'))····························
···········e·····n··r·······c·······························
·······(write(read-host)····a)······························
·······))E·s········m·······n)······························
········C·E·········p·······((······························
·······H·T··········t·······,t············r·················
······O· ···········(·······'u······························
····· ·/············)·······'p······························
····%·P·············)·······)n········1·····················
···A· ······················)i·······n······················
··%·A························(······-·······················
···=·························t····· ···$·d··················
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
·····························r··e···a·····················}}
·····························p·h···=························
··································<·························
·································>··························
```
[Answer]
# Perl, 6 characters added
```
die
$ a=<>
```
The grid is now:
```
·········v---H\·············································
·········>qir@uH····a·······································
··········?pio;·····l·······································
··········,u········e·······c·······························
··········.t········r·······a·······························
··········@s······s t=" " r t#50:20 w !,t,!·················
··········· ··printf(·······(·······························
···········g·· input('','s'))····························
···········e·····n··r·······c·······························
········write(read-host)····a·······························
·········E·s········m·······n·······························
········C·E·········p·······(·······························
·······H·T··········t·······,·············r·················
······O· ···········(·······'·······························
····· ·/············)·······'·······························
····%·P·············)·······)·······························
···A· ······················)·······························
··%·A·······················································
···=···································$·d··················
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
····································a·····················}}
···································=························
··································<·························
·································>··························
```
[Answer]
# [Quipu](https://esolangs.org/wiki/Quipu), 3 characters added
The cat program in Quipu is four characters:
```
\/
/\
```
I rotated this 90° and re-used one of the slashes from the [Rail](https://codegolf.stackexchange.com/a/57455/668) program.
The new grid:
```
·········v---H\··v+C+<D_··············S·P··············;····
G`····,··>qir@uH· IaP.C·············A·USE: io·········>····
Get a chr!?pio;····Ol···············Y·Lreadln(write(···;····
Outputs it,u········e·······c······ ·L·print(readline())····
and 'BZam..t········r·······a·····ai ··string))··<v;···;····
G·······~,@s······s t=" " r t#50:20 w !,t,!······?a?···E····
G·····main( ){printf("%c", (getchar()));}·······pr>···;····
O··········g·> input('','s'))·················h_····P····
a··········e·····n··r·····^·c·········g··········pd····;····
·······(write(read-host)····a)········r·input n$!?u····(····
·······))E·s········m·······n)···KVGH·e·print n$··m····;····
········C·E·········p·······((···TIIA{print;exit}·pYEK·*····
$'main'H·T··········t·······,t···HSMI· ···r·······(·········
\/\··O· ···········(·······'u···XIM ·-···········$·········
\/· ·/(println····)·······'p···BBE1·m···········a·········
\%·P· (read-line))······)n···YLH.·1···········r·········
A\ /-io-\············)io··EE 4n ·····`·····g·········
% A\-e-< |·············(···· V-·.··di _r(a)·v·········
$ = \----#·············t\···V ···$;di $a····)·········
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
·····························r··e···a b c d e f g h i·····}}
···········>maertsoi<edulcni#p·h···=b c d e f g h i·········
····;s gnirts::dts{)(niam tni·····<·························
···};s<<tuoc::dts;s>>nic::dts····>··························
```
[Answer]
# [Marbelous](https://github.com/marbelous-lang/marbelous.py/blob/master/doc/marbelous.md), 7 characters added
```
00
\\/\]]
```
(If I understood correctly how Marbelous works...)
```
·········v---H\OIv+C+<D_··············S·P··············;····
G`····,··>qir@uH· IaP.C········LAMBDA·USE: io·········>····
Get a chr!?pio;····Ol···········ZEROY·Lreadln(write(···;····
Outputs it,u········e·······c······ ·L·print(readline())····
and 'BZam..t········r·······a·····ai ··string))·o<v;i:j;p:j·
G·······~,@s······s t=" " r t#50:20 w !,t,!······?a?·:·E····
G·····main( ){printf("%c", (getchar()));}·······pr>·:·;····
O·········)g·> input('','s'))·················h_··)·P····
a··········e·····n··r·····^·c·········g··········pd····;····
·······(write(read-host)····a)········r·input n$!?u····(····
·······))E·s········m·······n)···KVGH·e·print n$!·m····;····
········C·E·········p·······((···TIIA{print;exit}·pYEK·*····
$'main'H·TUPTUO·····t·00····,t···HSMI· ···r·······(·········
\/\··O· ·TUPNI···S (I\\/\]]'u···XIM ·-···········$·········
\/· ·/(println··FO) /·····'p···BBE1·m···········a·········
\%·PQ (read-line))······)n···YLH.·1··print(io.read())···
A\ /-io-\············)io··EE 4n ····,`·····g·········
% A\-e-< |··········)#_(···· V-·.··di _r(a)·v·········
$ = \----#·············t\·c&V ···$;di $a····)·········
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
··`[x.````?10xx][x.````?10xx]r··e···a b c d e f g h i·····}}
···········>maertsoi<edulcni#p·h···=b c d e f g h i·········
····;s gnirts::dts{)(niam tni····v< o<····················
···};s<<tuoc::dts;s>>nic::dts···o>i:1+?/;][gnirtStupnI@tnirP
```
[Answer]
# PowerShell, 14 characters added
```
write(read-host)
```
I'll be nice and give people lots more room to breathe. :)
The grid is now
```
····························································
···········i················································
··········?pio;·············································
··········,u················································
··········.t················································
···········s················································
··········· ················································
···········g················································
···········e················································
········write(read-host)····································
···········s················································
····························································
··········································r·················
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
····························································
```
[Answer]
# ALGOL 68, 7 characters added
```
print(read
string)
```
The new grid:
```
·········v---H\········································;····
······,··>qir@uH···IaP.················USE: io·········>····
Get a chr!?pio;·····l··················readln··········;····
Outputs it,u········e·······c··········print(readline())····
and 'BZam..t········r·······a··········string)·········;····
········~,@s······s t=" " r t#50:20 w !,t,!············E····
······main( ){printf("%c", (getchar()));}·············;····
···········g·> input('','s'))·······················P····
···········e·····n··r·······c·········g················;····
·······(write(read-host)····a)········r·input n········(····
·······))E·s········m·······n)········e·print n········;····
········C·E·········p·······((·······{print;exit}····K·*····
·······H·T··········t·······,t········ ···r·················
······O· ···········(·······'u········-·····················
····· ·/············)·······'p········m·····················
····%·P·············)·······)n········1·····················
···A· ······················)io······n ·····················
··%·A························(······-·.·····················
···=·························t\···· ···$·d··················
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
·····························r··e···a b c d e f g h i·····}}
·····························p·h···=b c d e f g h i·········
··································<·························
·································>··························
```
[Answer]
# [LOLCODE](http://esolangs.org/wiki/LOLCODE), 31 Characters Added
```
HAI 1.4
GIMMEH V
VISIBLE V
KTHXBYE
```
Just to the right of the middle, rotated 90o. Butted up nicely against the `-`, , and `d` there. Between this, Batch files, and PowerShell, I'm pretty sure I'm not going to be winning based on points, though. :-)
The grid is now:
```
·········v---H\··v+C+<D_··············S·P··············;····
G`····,··>qir@uH· IaP.C·············A·USE: io·········>····
Get a chr!?pio;····Ol···············Y·Lreadln(write(···;····
Outputs it,u········e·······c······ ·L·print(readline())····
and 'BZam..t········r·······a·····ai ··string))··<v;···;····
G·······~,@s······s t=" " r t#50:20 w !,t,!······?a?···E····
G·····main( ){printf("%c", (getchar()));}·······pr>···;····
O··········g·> input('','s'))·················h_····P····
a··········e·····n··r·····^·c·········g··········pd····;····
·······(write(read-host)····a)········r·input n$!?u····(····
·······))E·s········m·······n)···KVGH·e·print n$··m····;····
········C·E·········p·······((···TIIA{print;exit}·pYEK·*····
·······H·T··········t·······,t···HSMI· ···r·······(·········
······O· ···········(·······'u···XIM ·-···········$·········
····· ·/(println····)·······'p···BBE1·m···········a·········
····%·P· (read-line))······)n···YLH.·1···········r·········
···A· ······················)io··EE 4n ·····`·····g·········
··%·A························(···· V-·.··di _r(a)·v·········
·$·=·························t\···V ···$;di $a····)·········
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
·····························r··e···a b c d e f g h i·····}}
·····························p·h···=b c d e f g h i·········
··································<·························
·································>··························
```
(I also corrected the fourth-from-the-bottom row)
[Answer]
# Prolog (SWI), 14 characters added
```
:-get(C),
put(C).
```
Reads a single character and outputs it. On Ideone, [this works](http://ideone.com/9evRc1) but with output to stderr. With `swipl` on Ubuntu, it does the following:
```
dlosc@dlosc:~/tests$ swipl -qs getput.prolog
|: X
X?-
```
where `X` is the character entered and `?-` is a prompt. You can exit out of the prompt with Ctrl-D.
New grid (code reads top-to-bottom, right-to-left near upper right corner):
```
·········v---H\OIv+C+<D_··············S·Psgv···········;····
G`····,··>qir@uH· IaP.C········LAMBDA·USE: io·········>····
Get a chr!?pio;p···Ol···········ZEROY·Lreadln(write(···;····
Outputs it,u··a$ ohce·······c······ ·L·print(readline())····
and 'BZam..t···a daer·······a·····ai ··string))·o<v;i:j;p:j·
G·······~,@s······s t=" " r t#50:20 w !,t,!······?a?·:·Eu-··
G·····main( ){printf("%c", (getchar()));}·······pr>·:·;tg··
O·········)g·> input('','s'))·················h_··)·P(e··
a··········e·····n··r·····^·c·········g··········pd····;Ct··
·······(write(read-host)····a)········r·input n$!?u····()(··
·······))E·s········m·······n)···KVGH·e·print n$!·m····;.C··
········C·E·········p·······((···TIIA{print;exit}·pYEK·*·)··
$'main'H·TUPTUO·····t·00····,t···HSMI· ···r·······(······,··
\/\I^O= ·TUPNI···S (I\\/\]]'u···XIM ·-···········$·········
\/· ·/(println··FO) /·····'p···BBE1·m···········a·········
\%·PQ (read-line))······)n···YLH.·1··print(io.read())···
A\ /-io-\············)io··EE 4n ··@.,`·····g·········
% A\-e-< |··········)#_(···· V-·.··di _r(a)^v·········
$ = \----#·············t\·c&V ···$;di $a····)·········
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
··`[x.````?10xx][x.````?10xx]r··e···a b c d e f g h i·····}}
···········>maertsoi<edulcni#p·h···=b c d e f g h i·········
····;s gnirts::dts{)(niam tni····v< o<····················
···};s<<tuoc::dts;s>>nic::dts···o>i:1+?/;][gnirtStupnI@tnirP
```
[Answer]
# [oOo CODE](http://esolangs.org/wiki/OOo_CODE), 1 character added
```
ROYALr
```
New grid:
```
·········v---H\OIv+C+<D_··············S·Psgv···········;····
G`····,··>qir@uH· IaP.C········LAMBDA·USE: io·········>····
Get a chr!?pio;p···Ol···········ZEROYALreadln(write(···;····
Outputs it,u··a$ ohce·······c······ ·L·print(readline())····
and 'BZam..t···a daer·······a·····ai ··string))·o<v;i:j;p:j·
G·······~,@s······s t=" " r t#50:20 w !,t,!······?a?·:·Eu-··
G·····main( ){printf("%c", (getchar()));}·······pr>·:·;tg··
O·········)g·> input('','s'))·················h_··)·P(e··
a··········e·····n··r·····^·c·········g··········pd····;Ct··
·······(write(read-host)····a)········r·input n$!?u····()(··
·······))E·s········m·······n)···KVGH·e·print n$!·m····;.C··
········C·E·········p·······((···TIIA{print;exit}·pYEK·*·)··
$'main'H·TUPTUO·····t·00····,t···HSMI· ···r·······(······,··
\/\I^O= ·TUPNI···S (I\\/\]]'u···XIM ·-···········$·········
\/· ·/(println··FO) /·····'p···BBE1·m···········a·········
\%·PQ (read-line))······)n···YLH.·1··print(io.read())···
A\ /-io-\············)io··EE 4n ··@.,`·····g·········
% A\-e-< |··········)#_(···· V-·.··di _r(a)^v·········
$ = \----#·············t\·c&V ···$;di $a····)·········
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
··`[x.````?10xx][x.````?10xx]r··e···a b c d e f g h i·····}}
···········>maertsoi<edulcni#p·h···=b c d e f g h i·········
····;s gnirts::dts{)(niam tni····v< o<····················
···};s<<tuoc::dts;s>>nic::dts···o>i:1+?/;][gnirtStupnI@tnirP
```
[Answer]
# [Labyrinth](https://github.com/mbuettner/labyrinth), 1 character added
```
,.@
```
Reads and writes a character.
The grid is now
```
····························································
···········i········a·······································
··········?pio;·····l·······································
··········,u········e·······································
··········.t········r·······································
··········@s········t·······································
··········· ··printf(·······································
···········g·· input('','s'))····························
···········e·····n··r·······································
········write(read-host)····································
·········E·s········m·······································
········C·E·········p·······································
·······H·T··········t·····················r·················
······O· ···········(·······································
····· ·/············)·······································
····%·P·············)·······································
···A· ······················································
··%·A·······················································
···=························································
····························································
····························································
····························································
····························································
····························································
····························································
```
[Answer]
# Beam, 11 characters added
An extra H added to stop it behaving like a cat program. The `q` and `i` are ignored. I probably could have gone larger with this, but that seemed a bit like cheating.
```
v---H\
>qir@uH
```
The grid is now
```
·········v---H\·············································
·········>qir@uH····a·······································
··········?pio;·····l·······································
··········,u········e·······c·······························
··········.t········r·······a·······························
··········@s······s t=" " r t#50:20 w !,t,!·················
··········· ··printf(·······(·······························
···········g·· input('','s'))····························
···········e·····n··r·······c·······························
········write(read-host)····a·······························
·········E·s········m·······n·······························
········C·E·········p·······(·······························
·······H·T··········t·······,·············r·················
······O· ···········(·······'·······························
····· ·/············)·······'·······························
····%·P·············)·······)·······························
···A· ······················)·······························
··%·A·······················································
···=························································
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
··························································}}
····························································
····························································
····························································
```
[Answer]
# [ferNANDo](http://esolangs.org/wiki/FerNANDo), 31 characters added
```
a b c d e f g h i
b c d e f g h i
```
The new grid:
```
·········v---H\·············································
·········>qir@uH···IaP.·····································
Get a chr!?pio;·····l·······································
Outputs it,u········e·······c·······························
and 'BZam..t········r·······a·······························
········~,@s······s t=" " r t#50:20 w !,t,!·················
··········· ··printf(·······(·······························
···········g·· input('','s'))····························
···········e·····n··r·······c·········g·····················
·······(write(read-host)····a)········r······ ··············
·······))E·s········m·······n)········e·····················
········C·E·········p·······((·······{print;exit}····K······
·······H·T··········t·······,t········ ···r·················
······O· ···········(·······'u········-·····················
····· ·/············)·······'p········m·····················
····%·P·············)·······)n········1·····················
···A· ······················)i·······n ·····················
··%·A························(······-·.·····················
···=·························t····· ···$·d··················
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
·····························r··e···a b c d e f g h i·····}}
·····························p·h···=b c d e f g h i·········
··································<·························
·································>··························
```
[Answer]
# Scheme, 8 characters added
```
(write(
read
))
```
The new grid:
```
·········v---H\·······················S·P··············;····
······,··>qir@uH···IaP.··············A·USE: io·········>····
Get a chr!?pio;·····l···············Y·Lreadln(write(···;····
Outputs it,u········e·······c······ ·L·print(readline())····
and 'BZam..t········r·······a·····ai ··string))········;····
········~,@s······s t=" " r t#50:20 w !,t,!············E····
······main( ){printf("%c", (getchar()));}·············;····
···········g·> input('','s'))·······················P····
···········e·····n··r·····^·c·········g················;····
·······(write(read-host)····a)········r·input n$!?·····(····
·······))E·s········m·······n)········e·print n$·······;····
········C·E·········p·······((·······{print;exit}····K·*····
·······H·T··········t·······,t········ ···r·················
······O· ···········(·······'u········-·····················
····· ·/············)·······'p········m·····················
····%·P·············)·······)n········1·····················
···A· ······················)io······n ·····`···············
··%·A························(······-·.··di _r(a)···········
·$·=·························t\···· ···$;di $a··············
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
·····························r··e···a b c d e f g h i·····}}
·····························p·h···=b c d e f g h i·········
··································<·························
·································>··························
```
[Answer]
# Bash, 6 characters added
```
head -n1
```
The grid is now:
```
·········v---H\·············································
·········>qir@uH····a·······································
··········?pio;·····l·······································
··········,u········e·······c·······························
··········.t········r·······a·······························
··········@s······s t=" " r t#50:20 w !,t,!·················
··········· ··printf(·······(·······························
···········g·· input('','s'))····························
···········e·····n··r·······c·······························
········write(read-host)····a·······························
·········E·s········m·······n·······························
········C·E·········p·······(·······························
·······H·T··········t·······,·············r·················
······O· ···········(·······'·······························
····· ·/············)·······'·······························
····%·P·············)·······)·········1·····················
···A· ······················)········n······················
··%·A·······························-·······················
···=······························· ···$·d··················
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
································e···a·····················}}
·······························h···=························
··································<·························
·································>··························
```
[Answer]
# [itflabtijtslwi](https://esolangs.org/wiki/Itflabtijtslwi), 5 characters added
```
GGOaGGOa
```
This is the /// language but with user input when surrounded by `GG`. It is "named" whatever comes between them. Therefore this just echoes the first character of STDIN. (Since this only reads 1 character, the 2 character name means it will always halt after replacing Oa with what you type in)
Added to top left vertically from (across, down) = (0,1) to (0,9)
The new grid:
```
·········v---H\··v+C+<D_··············S·P··············;····
G`····,··>qir@uH· IaP.C·············A·USE: io·········>····
Get a chr!?pio;····Ol···············Y·Lreadln(write(···;····
Outputs it,u········e·······c······ ·L·print(readline())····
and 'BZam..t········r·······a·····ai ··string))··<v;···;····
G·······~,@s······s t=" " r t#50:20 w !,t,!······?a?···E····
G·····main( ){printf("%c", (getchar()));}·······pr>···;····
O··········g·> input('','s'))·················h_····P····
a··········e·····n··r·····^·c·········g··········pd····;····
·······(write(read-host)····a)········r·input n$!?u····(····
·······))E·s········m·······n)········e·print n$··m····;····
········C·E·········p·······((·······{print;exit}·pYEK·*····
·······H·T··········t·······,t········ ···r·······(·········
······O· ···········(·······'u········-···········$·········
····· ·/(println····)·······'p········m···········a·········
····%·P· (read-line))······)n········1···········r·········
···A· ······················)io······n ·····`·····g·········
··%·A························(······-·.··di _r(a)·v·········
·$·=·························t\···· ···$;di $a····)·········
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
·····························r··e···a b c d e f g h i·····}}
·····························p·h···=b c d e f g h i·········
··································<·························
·································>··························
```
[Answer]
# PHP, 24 characters added
```
<?php
var_dump($argv)
;?>
```
The grid is now:
```
·········v---H\··v+C+<D_··············S·P··············;····
·`····,··>qir@uH· IaP.C·············A·USE: io·········>····
Get a chr!?pio;····Ol···············Y·Lreadln(write(···;····
Outputs it,u········e·······c······ ·L·print(readline())····
and 'BZam..t········r·······a·····ai ··string))··<v;···;····
········~,@s······s t=" " r t#50:20 w !,t,!······?a?···E····
······main( ){printf("%c", (getchar()));}·······pr>···;····
···········g·> input('','s'))·················h_····P····
···········e·····n··r·····^·c·········g··········pd····;····
·······(write(read-host)····a)········r·input n$!?u····(····
·······))E·s········m·······n)········e·print n$··m····;····
········C·E·········p·······((·······{print;exit}·p··K·*····
·······H·T··········t·······,t········ ···r·······(·········
······O· ···········(·······'u········-···········$·········
····· ·/(println····)·······'p········m···········a·········
····%·P· (read-line))······)n········1···········r·········
···A· ······················)io······n ·····`·····g·········
··%·A························(······-·.··di _r(a)·v·········
·$·=·························t\···· ···$;di $a····)·········
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
·····························r··e···a b c d e f g h i·····}}
·····························p·h···=b c d e f g h i·········
··································<·························
·································>··························
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 1 character added
```
G`
```
This is essentially `cat`. `G` activates grep mode, i.e. the program prints each line of the program which matches the given regex. But the regex is empty, so every line is a match and the entire input is printed back to STDOUT.
```
·········v---H\··v+C+<D_··············S·P··············;····
·`····,··>qir@uH· IaP.C·············A·USE: io·········>····
Get a chr!?pio;····Ol···············Y·Lreadln(write(···;····
Outputs it,u········e·······c······ ·L·print(readline())····
and 'BZam..t········r·······a·····ai ··string))········;····
········~,@s······s t=" " r t#50:20 w !,t,!············E····
······main( ){printf("%c", (getchar()));}·············;····
···········g·> input('','s'))·······················P····
···········e·····n··r·····^·c·········g················;····
·······(write(read-host)····a)········r·input n$!?·····(····
·······))E·s········m·······n)········e·print n$·······;····
········C·E·········p·······((·······{print;exit}····K·*····
·······H·T··········t·······,t········ ···r·················
······O· ···········(·······'u········-·····················
····· ·/············)·······'p········m·····················
····%·P·············)·······)n········1·····················
···A· ······················)io······n ·····`···············
··%·A························(······-·.··di _r(a)···········
·$·=·························t\···· ···$;di $a··············
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
·····························r··e···a b c d e f g h i·····}}
·····························p·h···=b c d e f g h i·········
··································<·························
·································>··························
```
[Answer]
# [RunR](http://esolangs.org/wiki/RunR), 8 characters added
One last one for the moment
```
S (I\
FO) /
```
Added close to the middle, down and left a bit.
The new grid is
```
·········v---H\·Iv+C+<D_··············S·P··············;····
G`····,··>qir@uH· IaP.C········LAMBDA·USE: io·········>····
Get a chr!?pio;····Ol···········ZEROY·Lreadln(write(···;····
Outputs it,u········e·······c······ ·L·print(readline())····
and 'BZam..t········r·······a·····ai ··string))··<v;i:j;p:j·
G·······~,@s······s t=" " r t#50:20 w !,t,!······?a?·:·E····
G·····main( ){printf("%c", (getchar()));}·······pr>·:·;····
O·········)g·> input('','s'))·················h_··)·P····
a··········e·····n··r·····^·c·········g··········pd····;····
·······(write(read-host)····a)········r·input n$!?u····(····
·······))E·s········m·······n)···KVGH·e·print n$!·m····;····
········C·E·········p·······((···TIIA{print;exit}·pYEK·*····
$'main'H·T··········t·······,t···HSMI· ···r·······(·········
\/\··O· ·········S (I\·····'u···XIM ·-···········$·········
\/· ·/(println··FO) /·····'p···BBE1·m···········a·········
\%·PQ (read-line))······)n···YLH.·1···········r·········
A\ /-io-\············)io··EE 4n ·····`·····g·········
% A\-e-< |·············(···· V-·.··di _r(a)·v·········
$ = \----#·············t\···V ···$;di $a····)·········
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
··`[x.````?10xx][x.````?10xx]r··e···a b c d e f g h i·····}}
···········>maertsoi<edulcni#p·h···=b c d e f g h i·········
····;s gnirts::dts{)(niam tni····v< o<····················
···};s<<tuoc::dts;s>>nic::dts···o>i:1+?/;···················
```
[Answer]
# Mathematica, 19 characters added
```
Print@InputString[];
```
New grid:
```
·········v---H\OIv+C+<D_··············S·P··············;····
G`····,··>qir@uH· IaP.C········LAMBDA·USE: io·········>····
Get a chr!?pio;····Ol···········ZEROY·Lreadln(write(···;····
Outputs it,u········e·······c······ ·L·print(readline())····
and 'BZam..t········r·······a·····ai ··string))··<v;i:j;p:j·
G·······~,@s······s t=" " r t#50:20 w !,t,!······?a?·:·E····
G·····main( ){printf("%c", (getchar()));}·······pr>·:·;····
O·········)g·> input('','s'))·················h_··)·P····
a··········e·····n··r·····^·c·········g··········pd····;····
·······(write(read-host)····a)········r·input n$!?u····(····
·······))E·s········m·······n)···KVGH·e·print n$!·m····;····
········C·E·········p·······((···TIIA{print;exit}·pYEK·*····
$'main'H·TUPTUO·····t·······,t···HSMI· ···r·······(·········
\/\··O· ·TUPNI···S (I\·····'u···XIM ·-···········$·········
\/· ·/(println··FO) /·····'p···BBE1·m···········a·········
\%·PQ (read-line))······)n···YLH.·1··print(io.read())···
A\ /-io-\············)io··EE 4n ····,`·····g·········
% A\-e-< |·············(···· V-·.··di _r(a)·v·········
$ = \----#·············t\·c·V ···$;di $a····)·········
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
··`[x.````?10xx][x.````?10xx]r··e···a b c d e f g h i·····}}
···········>maertsoi<edulcni#p·h···=b c d e f g h i·········
····;s gnirts::dts{)(niam tni····v< o<····················
···};s<<tuoc::dts;s>>nic::dts···o>i:1+?/;][gnirtStupnI@tnirP
```
[Answer]
# Haskell, 16 characters added
```
main = interact id
```
Copies stdin to stdout. The code starts at line 15, char 39.
```
·········v---H\OIv+C+<D_Include C by GS·Psgv···········;····
G`····,··>qir@uH· IaP.C.·······LAMBDA·USE: io·········>····
Get a chr!?pio;p···Ol···Z: say TZEROYALreadln(write(···;····
Outputs it,u··a$ ohce·······c······ ·L·print(readline())····
and 'BZam..t···a daer·······a·····ai ··string))·o<v;i:j;p:j·
G·······~,@s······s t=" " r t#50:20 w !,t,!······?a?·:·Eu-··
G·····main( ){printf("%c", (getchar()));}·······pr>·:·;tg··
O·········)g·> input('','s'))(enildr ,tnirp···h_··)·P(e··
a··········e·····n··r·····^·c·········g··········pd····;Ct··
·······(write(read-host)····a)········r·input n$!?u····()(··
·······))E·s········m·······n)···KVGH·e·print n$!·m····;.C··
········C·E·········p·······((···TIIA{print;exit}·pYEK·*·)··
$'main'H·TUPTUO·····t·00····,t···HSMI· ···r·······(······,··
\/\I^O= ·TUPNI···S (I\\/\]]'u···XIM ·-···········$·········
\/· ·/(println··FO) /·····'p···BBE1·main = interact id····
\%·PQ (read-line))······)n···YLH.·1··print(io.read())···
A\ /-io-\············)io··EE 4n ··@.,`·····g·········
% A\-e-< |··········)#_(···· V-·.··di _r(a)^v·········
$ = \----#·············t\·c&V ···$;di $a····)·········
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
··`[x.````?10xx][x.````?10xx]r··e···a b c d e f g h i·····}}
···········>maertsoi<edulcni#p·h···=b c d e f g h i·········
····;s gnirts::dts{)(niam tni····v< o<····················
···};s<<tuoc::dts;s>>nic::dts···o>i:1+?/;][gnirtStupnI@tnirP
```
[Answer]
# [Ook!](https://esolangs.org/wiki/Ook), 19 characters added
```
Ook. Ook! Ook! Ook.
```
Placed on the 24th line.
```
·········v---H\OIv+C+<D_Include C by GS·Psgv···········;····
G`····,.·>qir@uH· IaP.C.%······LAMBDA·USE: io·········>····
Get a chr!?pio;p···Ol···Z: say TZEROYALreadln(write(···;····
Outputs it,u··a$ ohce····.··c······ ·L·print(readline())····
and 'BZam..t···a daer····x··a·····ai ··string))·o<v;i:j;p:j·
G·······~,@s······s t=" " r t#50:20 w !,t,!······?a?·:,Eu-··
G·····main( ){printf("%c", (getchar()));}·······pr>·:·;tg··
O·········)g·> input('','s'))(enildr ,tnirp···h_··)·P(e··
a··········e·····n··r·····^·c·········g··········pd····;Ct··
·······(write(read-host)····a)········r·input n$!?u····()(··
·······))E·s········m·······n)···KVGH·e·print n$!·m····;.C··
········C·E·········p·······((···TIIA{print;exit}·pYEK·*·)··
$'main'H·TUPTUO·····t·00····,t···HSMI· ···r·······(······,··
\/\I^O= ·TUPNI···S (I\\/\]]'u···XIM ·-···········$·········
\/· ·/(println··FO) /·····'p···BBE1·main = interact id····
\%·PQ (read-line))······)n···YLH.·1··print(io.read())···
A\ /-io-\············)io··EE 4n ··@.,`·····g·········
% A\-e-< |··········)#_(o··· V-·.··di _r(a)^v·········
$ = \----#·············t\·c&V ···$;di $a····)·········
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
··`[x.````?10xx][x.````?10xx]r··e···a b c d e f g h i·····}}
··········;>maertsoi<edulcni#p·h···=b c d e f g h i·········
····;s gnirts::dts{)(niam tni····v< o<Ook. Ook! Ook! Ook.·
···};s<<tuoc::dts;s>>nic::dts···o>i:1+?/;][gnirtStupnI@tnirP
```
[Answer]
# Tcl, 16 characters added
```
puts [gets stdin]
```
New grid:
```
·········v---H\OIv+C+<D_Include C by GS Psgv···········;····
G`····,.·>qir@uH· IaP.C.%······LAMBDA·USE: io·········>····
Get a chr!?pio;p···Ol···Z: say TZEROYALreadln(write(···;····
Outputs it,u··a$ ohce····.··c······ ·L·print(readline())····
and 'BZam..t···a daer····x··a·····ai ··string))·o<v;i:j;p:j·
G·······~,@s······s t=" " r t#50:20 w !,t,!······?a?·:,Eu-··
G·····main( ){printf("%c", (getchar()));}·······pr>>:·;tg··
O·········)g·> input('','s'))(enildr ,tnirp···h_··)·P(e··
a··········e·····n··r·····^·c···puts [gets stdin]pd····;Ct··
·······(write(read-host)····a)········r·input n$!?u····()(··
·······))E·s········m·······n)···KVGH·e·print n$!·m····;.C··
········C·E·········p·······((···TIIA{print;exit}·pYEK·*·)··
$'main'H·TUPTUO·····t·00····,t···HSMI· ···r·······(······,··
\/\I^O= ·TUPNI···S (I\\/\]]'u···XIM ·-···········$·········
\/· ·/(println··FO) /·····'p···BBE1·main = interact id····
\%·PQ (read-line))······)n···YLH.·1··print(io.read())···
A\ /-io-\············)io··EE 4n ··@.,`·····g·········
% A\-e-< |··········)#_(o··· V-·.··di _r(a)^v·········
$ = \----#·············t\·c&V ···$;di $a····)·········
{elbaworhT sworht )a][gnirtS(niam diov citats cilbup{C ssalc
;))(txen.)ni.metsyS(rennacS.litu.avaj wen(nltnirp.tuo.metsyS
··`[x.````?10xx][x.````?10xx]r··e···a b c d e f g h i·····}}
··········;>maertsoi<edulcni#p·h···=b c d e f g h i·········
····;s gnirts::dts{)(niam tni····v< o<Ook. Ook! Ook! Ook.·
···};s<<tuoc::dts;s>>nic::dts···o>i:1+?/;][gnirtStupnI@tnirP
```
] |
[Question]
[
### Background:
The current [Perfect Numbers challenge](https://codegolf.stackexchange.com/q/58026/76162) is rather flawed and complicated, since it asks you to output in a complex format involving the factors of the number. This is a purely [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") repost of the challenge.
## Challenge
Given a positive integer through any [standard input format](https://codegolf.meta.stackexchange.com/q/2447/76162), distinguish between whether it is perfect or not.
A perfect number is a number that is equal to the sum of all its proper divisors (its positive divisors less than itself). For example, \$6\$ is a perfect number, since its divisors are \$1,2,3\$, which sum up to \$6\$, while \$12\$ is not a perfect number since its divisors ( \$1,2,3,4,6\$ ) sum up to \$16\$, not \$12\$.
### Test Cases:
```
Imperfect:
1,12,13,18,20,1000,33550335
Perfect:
6,28,496,8128,33550336,8589869056
```
### Rules
* Your program doesn't have to complete the larger test cases, if there's memory or time constraints, but it should be theoretically able to if it were given more memory/time.
* Output can be two distinct and consistent values through any [allowed output format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). If it isn't immediately obvious what represents Perfect/Imperfect, please make sure to specify in your answer.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes
```
fk+?
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/UUNAJSi9JSk0s0lWpAgmmJOcUgUc/cAph47cNdnbUPt074n5atbf//f7ShjpmOoZGOkYWOobGOiSWQY6FjYQjkGhnoGBubmhoYGwPFDAwMYgE "Brachylog – Try It Online")
The predicate succeeds for perfect inputs and fails for imperfect inputs, printing `true.` or `false.` if run as a complete program (except [on the last test case](https://tio.run/##SypKTM6ozMlPN/r/Py1b2/7/fwtTC0sLM0sDUzMA) which takes more than a minute on TIO).
```
The input's
f factors
k without the last element
+ sum to
? the input.
```
[Answer]
# [Neim](https://github.com/okx-code/Neim), 3 bytes
```
ùêïùê¨ùîº
```
[Try it online!](https://tio.run/##y0vNzP3//8PcCVOBeM2HuVP2/P9vYWphaWFmaWBqBgA "Neim – Try It Online")
(I don't actually know how to run all of the test cases at once, since I started learning Neim about fifteen minutes ago, but I did check them individually.)
Prints 0 for imperfect, 1 for perfect.
```
ùêï Pop an int from the stack and push its proper divisors,
implicitly reading the int from a line of input as the otherwise absent top of the stack.
ùê¨ Pop a list from the stack and push the sum of the values it contains.
ùîº Pop two ints from the stack and push 1 if they are equal, 0 if they are not;
implicitly reading the same line of input that was already read as the second int, I guess?
Implicitly print the contents of the stack, or something like that.
```
[Answer]
# [R](https://www.r-project.org/), ~~33~~ 29 bytes
```
!2*(n=scan())-(x=1:n)%*%!n%%x
```
[Try it online!](https://tio.run/##K/r/X9FISyPPtjg5MU9DU1NXo8LW0CpPU1VLVTFPVbXiv6HRfwA "R – Try It Online")
Returns `TRUE` for perfect numbers and `FALSE` for imperfect ones.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-!`, 4 bytes
```
¥â¬x
-----------------
Implicit Input U
¥ Equal to
x Sum of
√¢ Factors of U
¬ Without itself
```
*For some reason `¦` doesnt work on tio so I need to use the `-!` flag and `¥` instead*
[Try it online!](https://tio.run/##y0osKPn//9DSw4sOran4/9/Y2NTUwNjYTEFXEQA "Japt – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
Æṣ=
```
[Try it online!](https://tio.run/##y0rNyan8//9w28Odi23/H25/1LTG/f//aEMdQyMdQ2MdQwsdIwMdQwMDAx1jY1NTAyChY6ZjZKFjYmmmY2EIZECFgTxTC0sLM0sDU7NYAA "Jelly – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 46 bytes
```
lambda x:sum(i for i in range(1,x)if x%i<1)==x
```
[Try it online!](https://tio.run/##Xc69DoIwEMDx2T7FBWPSJje0YJtC5AHc3NUBleoR@Qhigk9fISpRlxsu/1/umkd3qavIu3Tnr1l5OGXQJ7d7yQlc3QIBVdBm1TnnCntBDvoFrZRI095T2eSty48dpLBVqEJUESqLoUQlpdzDHCGKtJbDYOyrNRhaXMYGrQrtmL2rYaFtbE0stRlAS1XHg/XnShIINr003U7Y7BUSguMkxAQ3v6wY2T8qRlQMyD8B "Python 3 – Try It Online")
Brute force, sums the factors and checks for equality.
[Answer]
# [Python](https://docs.python.org/2/), 45 bytes
```
lambda n:sum(d*(n%d<1)for d in range(1,n))==n
```
`True` for perfect; `False` for others (switch this with `==` -> `!=`)
**[Try it online!](https://tio.run/##NZPLbttADEXXzVcMUBSxCwYYcmY0mqDpN3TfduFAsmMglgJZSZuvdw8ddOXnvTw@pF/e16d5ssv@4dfleXd6HHZhuj@/njbD1830Zfim2/28hCEcp7DspsO4UZm224eH6fI5LONpfhuH8Hg8hHU8r@ewzmH3Nh@HsB5P4/zKO5vdNIQTX1zew7gsdNH04zo0WLgL69MYDuM0LruVz97G5Xzkk3n/MU3C3@tj@DO/Pg//u5/G87i9cS6f6oVQqYkm0V4sisYYpRPrJbdOerV@e3/z6WU5Tus1IuH27vuthP3GX20vP4lnlURFNekSHUlaFkuZ3iLaiZZOcqW/SmUGczQ2sdxIRkkUVJXOSJo0ChIsRppwKZIp6DuplSQlkYZMQ2qSoK3AKkmVRoFTGGkPZ8kU9EUqv8YpIg2OkWhgdNekiySjNAqcwj40lCSZgj5LLSQpiTQ4RqruRbteCgWtSaPAKezDYTHJ7jFJRYBTRBocI9HA6K5KoaD10iPAKdw44aKSKehNKgKcItLgGIkGRnedFApalR58p1DShEsU9Guvgn5zCvybY7CAq/8i@FdfJvhOwQJcfRPsax8F@@YQ6DenSF5AMAv6tRVBvzkE/hmMfeRrbYJ8cwbsm0MkXwHBJNhXjgD75gzoZy7yca/cAO4tOj8FDoF9l88NIF@5AeSbM2CfubhHvXICnd8o@OSdITkAORXUKxeAenME3DMW84hXDgDxxv4Rb45g7Xrq7B/xyv4Rb06AeabiHe3K@tFubB/t5gTunbFsH@3K9nsHpwLvfnZJ/OpZPtKN3SPdnMCtEy3@p@JZE6zbdfXkyZEmzupxbmwe5@YELp0om/eTZ/NINyfAupX4@x8 "Python 2 – Try It Online")**
**~~44 42~~ 41 bytes** (-2 thanks to ovs) if we may output using "truthy vs falsey":
```
f=lambda n,i=1:i/n or-~f(n,i+1)-(n%i<1)*i
```
(falsey (`0`)) for perfect; truthy (a non-zero integer) otherwise
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 25 bytes
```
@(n)~mod(n,t=1:n)*t'==2*n
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI0@zLjc/RSNPp8TW0CpPU6tE3dbWSCvvf2JRUWJlWmmeRpqOQrShjqGRjqGxjqGFjpGBjqGBgYGOsbGpqQGQiNXkQlFqpmNkoWNiaaZjYQhkQFWZxWr@BwA "Octave – Try It Online")
### Explanation
```
@(n)~mod(n,t=1:n)*t'==2*n
@(n) % Define anonymous function with input n
1:n % Row vector [1,2,...,n]
t= % Store in variable t
mod(n, ) % n modulo [1,2,...,n], element-wise. Gives 0 for divisors
~ % Logical negate. Gives 1 for divisors
t' % t transposed. Gives column vector [1;2;...;n]
* % Matrix multiply
2*n % Input times 2
== % Equal? This is the output value
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 46 bytes
```
n=>Enumerable.Range(1,n).Sum(x=>n%x<1?x:0)^n*2
```
Returns 0 if perfect, otherwise returns a positive number. I don't know if outputting different types of integers are allowed in place of two distinct truthy and falsy values, and couldn't find any discussion on meta about it. If this is invalid, I will remove it.
[Try it online!](https://tio.run/##DcuxCsIwEADQvV8RCkJiY0nEqcnFSScnHdyEGlI5sCekDQRKvz12eOPz08FPWK6JvEWa5cYNUAjchdIYYv/@hvbe0ydwLUm0jzTyDI522epz7pR40f5YTDX8It8uQ9AGLWilDDaNqJ4R53BDCrxelDytDBxb9FpLlANHYbUw5Q8 "C# (Visual C# Interactive Compiler) – Try It Online")
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~49~~ 47 bytes
```
n=>Enumerable.Range(1,n).Sum(x=>n%x<1?x:0)==n*2
```
[Try it online!](https://tio.run/##DcwxCsIwFADQvacIBSGxsSTiZPLjpJOTDs5tSOVD@wNpC4HSs0ffAZ6fT37G8ljJW6RF9jGOboBC4O60TiF1/RjaV0ffwLUk0b7XiWdwdMhW3/JVCQA6nouphpj4f2AI2qAFrZTBphHVJ@ESnkiB15uSl52BY5vea4ly4CiEKT8 "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Labyrinth](https://github.com/m-ender/labyrinth), 80 bytes
```
?::`}:("(!@
perfect:
{:{:;%"}
+puts; "
}zero: "
}else{(:
"negI" _~
""""""{{{"!@
```
The Latin characters `perfect puts zero else neg I` are actually just comments\*.
i.e. if the input is perfect a `0` is printed, otherwise `-1` is.
**[Try it online!](https://tio.run/##y0lMqizKzCvJ@P/f3soqodZKQ0lD0YGrILUoLTW5xIqr2qraylpVqZZLu6C0pNhaQYmrtiq1KN8KxEjNKU6t1rDiUspLTfdUUlCIr@NSAoPq6molRYf//y0MjSwA "Labyrinth – Try It Online")**
---
\* so [this](https://tio.run/##y0lMqizKzCvJ@P/f3soqodZKQ0lD0YFLAQKsuKqtqq2sVZVqubRBfGsFJa5asASMUa1hxaUEYgCJ@DouJTCorq5WUnT4/9/C0MgCAA "Labyrinth – Try It Online") or [this](https://tio.run/##y0lMqizKzCvJ@P/f3soqodZKQ0lD0YHLyTXcMchVwYqr2qraylpVqZZL28fRM8haQYmrVsHfTcEKxPD19POv1rDiUgpxDA1SUlCIr@NSAoPq6molRYf//y0MjSwA) work too...
```
?::`}:("(!@ ?::`}:("(!@
: BEWARE :
{:{:;%"} {:{:;%"}
+ ; " +LAIR; "
} : " } OF : "
} {(: }MINO{(:
" " _~ "TAUR" _~
""""""{{{"!@ """"""{{{"!@
```
### How?
Takes as an input a positive integer `n` and places an accumulator variable of `-n` onto the auxiliary stack, then performs a divisibility test for each integer from `n-1` down to, and including, `1`, adding any which do divide `n` to the accumulator. Once this is complete if the accumulator variable is non-zero a `-1` is output, otherwise a `0` is.
The `?::`}:(` is only executed once, at the beginning of execution:
```
?::`}:( Main,Aux
? - take an integer from STDIN and place it onto Main [[n],[]]
: - duplicate top of Main [[n,n],[]]
: - duplicate top of Main [[n,n,n],[]]
` - negate top of Main [[n,n,-n],[]]
} - place top of Main onto Aux [[n,n],[-n]]
: - duplicate top of Main [[n,n,n],[-n]]
( - decrement top of Main [[n,n,n-1],[-n]]
```
The next instruction, `"`, is a no-op, but we have three neighbouring instructions so we branch according to the value at the top of Main, zero takes us forward, while non-zero takes us right.
If the input was `1` we go forward because the top of Main is zero:
```
(!@ Main,Aux
( - decrement top of Main [[1,1,-1],[-1]]
! - print top of Main, a -1
@ - exit the labyrinth
```
But if the input was greater than `1` we turn right because the top of Main is non-zero:
```
:} Main,Aux
: - duplicate top of Main [[n,n,n-1,n-1],[-n]]
} - place top of Main onto Aux [[n,n,n-1],[-n,n-1]]
```
At this point we have a three-neighbour branch, but we know `n-1` is non-zero, so we turn right...
```
"% Main,Aux
" - no-op [[n,n,n-1],[-n,n-1]]
% - place modulo result onto Main [[n,n%(n-1)],[-n,n-1]]
- ...i.e we've got our first divisibility indicator n%(n-1), an
- accumulator, a=-n, and our potential divisor p=n-1:
- [[n,n%(n-1)],[a,p]]
```
We are now at another three-neighbour branch at `%`.
If the result of `%` was non-zero we go left to decrement our potential divisor, `p=p-1`, and leave the accumulator, `a`, as it is:
```
;:{(:""}" Main,Aux
; - drop top of Main [[n],[a,p]]
: - duplicate top of Main [[n,n],[a,p]]
{ - place top of Aux onto Main [[n,n,p],[a]]
- three-neighbour branch but n-1 is non-zero so we turn left
( - decrement top of Main [[n,n,p-1],[a]]
: - duplicate top of Main [[n,n,p-1,p-1],[a]]
"" - no-ops [[n,n,p-1,p-1],[a]]
} - place top of Main onto Aux [[n,n,p-1],[a,p-1]]
" - no-op [[n,n,p-1],[a,p-1]]
% - place modulo result onto Main [[n,n%(p-1)],[a,p-1]]
- ...and we branch again according to the divisibility
- of n by our new potential divisor, p-1
```
...but if the result of `%` was zero (for the first pass only when `n=2`) we go straight on to BOTH add the divisor to our accumulator, `a=a+p`, AND decrement our potential divisor, `p=p-1`:
```
;:{:{+}}""""""""{(:""} Main,Aux
; - drop top of Main [[n],[a,p]]
: - duplicate top of Main [[n,n],[a,p]]
{ - place top of Aux onto Main [[n,n,p],[a]]
: - duplicate top of Main [[n,n,p,p],[a]]
{ - place top of Aux onto Main [[n,n,p,p,a],[]]
+ - perform addition [[n,n,p,a+p],[]]
} - place top of Main onto Aux [[n,n,p],[a+p]]
} - place top of Main onto Aux [[n,n],[a+p,p]]
""""""" - no-ops [[n,n],[a+p,p]]
- a branch, but n is non-zero so we turn left
" - no-op [[n,n],[a+p,p]]
{ - place top of Aux onto Main [[n,n,p],[a+p]]
- we branch, but p is non-zero so we turn right
( - decrement top of Main [[n,n,p-1],[a+p]]
: - duplicate top of Main [[n,n,p-1,p-1],[a+p]]
"" - no-ops [[n,n,p-1,p-1],[a+p]]
} - place top of Main onto Aux [[n,n,p-1],[a+p,p-1]]
```
At this point if `p-1` is still non-zero we turn left:
```
"% Main,Aux
" - no-op [[n,n,p-1],[a+p,p-1]]
% - modulo [[n,n%(p-1)],[a+p,p-1]]
- ...and we branch again according to the divisibility
- of n by our new potential divisor, p-1
```
...but if `p-1` hit zero we go straight up to the `:` on the second line of the labyrinth (you've seen all the instructions before, so I'm leaving their descriptions out and just giving their effect):
```
:":}"":({):""}"%;:{:{+}}"""""""{{{ Main,Aux
: - [[n,n,0,0],[a,0]]
" - [[n,n,0,0],[a,0]]
- top of Main is zero so we go straight
- ...but we hit the wall and so turn around
: - [[n,n,0,0,0],[a,0]]
} - [[n,n,0,0],[a,0,0]]
- top of Main is zero so we go straight
"" - [[n,n,0,0],[a,0,0]]
: - [[n,n,0,0,0],[a,0,0]]
( - [[n,n,0,0,-1],[a,0,0]]
{ - [[n,n,0,0,-1,0],[a,0]]
- top of Main is zero so we go straight
- ...but we hit the wall and so turn around
( - [[n,n,0,0,-1,-1],[a,0]]
: - [[n,n,0,0,-1,-1,-1],[a,0]]
"" - [[n,n,0,0,-1,-1,-1],[a,0]]
} - [[n,n,0,0,-1,-1],[a,0,-1]]
- top of Main is non-zero so we turn left
" - [[n,n,0,0,-1,-1],[a,0,-1]]
% - (-1)%(-1)=0 [[n,n,0,0,0],[a,0,-1]]
; - [[n,n,0,0],[a,0,-1]]
: - [[n,n,0,0,0],[a,0,-1]]
{ - [[n,n,0,0,0,-1],[a,0]]
: - [[n,n,0,0,0,-1,-1],[a,0]]
{ - [[n,n,0,0,0,-1,-1,0],[a]]
+ - [[n,n,0,0,0,-1,-1],[a]]
} - [[n,n,0,0,0,-1],[a,-1]]
} - [[n,n,0,0,0],[a,-1,-1]]
""""""" - [[n,n,0,0,0],[a,-1,-1]]
- top of Main is zero so we go straight
{ - [[n,n,0,0,0,-1],[a,-1]]
{ - [[n,n,0,0,0,-1,-1],[a]]
{ - [[n,n,0,0,0,-1,-1,a],[]]
```
Now this `{` has three neighbouring instructions, so...
...if `a` is zero, which it will be for perfect `n`, then we go straight:
```
"!@ Main,Aux
" - [[n,n,0,0,0,-1,-1,a],[]]
- top of Main is a, which is zero, so we go straight
! - print top of Main, which is a, which is a 0
@ - exit the labyrinth
```
...if `a` is non-zero, which it will be for non-perfect `n`, then we turn left:
```
_~"!@ Main,Aux
_ - place a zero onto Main [[n,n,0,0,0,-1,-1,a,0],[]]
~ - bitwise NOT top of Main (=-1-x) [[n,n,0,0,0,-1,-1,a,-1],[]]
" - [[n,n,0,0,0,-1,-1,a,-1],[]]
- top of Main is NEGATIVE so we turn left
! - print top of Main, which is -1
@ - exit the labyrinth
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 33 bytes
```
->n{(1...n).sum{|i|n%i<1?i:0}==n}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNQT08vT1OvuDS3uiazJk8108bQPtPKoNbWNq/2f0FpSbFCtKGOoZGOobGOoYWOkYGOoYGBQaxeYl6lfXVNSU1adElsrYKyZ25BalFaanIJF0SLmY6RhY6JpZmOhaGRBVB1Tg6y6gCI2v8A "Ruby – Try It Online")
[Answer]
# JavaScript, 38 bytes
```
n=>eval("for(i=s=n;i--;)n%i||!(s-=i)")
```
[Try it online!](https://tio.run/##LYy9CsIwGAB3n0ILQgJfSn5sqJSvm08hDiGmGgmJNCFT3z12cDmOG@5jqsl29d/CYnq6tmCLOLtqAumWtBKPGePkGZtoPPttO5HM0NOOtoJ3AUKCUCBGkBwE5xyUGga@AzTIES5XDaPY5Z/141D6fXsz9k0qzjbFnILrQ3qRCseFVErp1H4 "JavaScript (Node.js) – Try It Online")
(Last testcase timeout on TIO.)
[Answer]
# TI-BASIC (TI-84), ~~30~~ 23 bytes
```
:2Ans=sum(seq(Ans/Xnot(remainder(Ans,X)),X,1,Ans,1
```
~~Horribly inefficient, but it works.~~
Reducing the bytecount sped up the program by a lot.
Input is in `Ans`.
Output is in `Ans` and is automatically printed out when the program completes.
**Explanation:**
(TI-BASIC doesn't have comments, so just assume that `;` makes a comment)
```
:2Ans=sum(seq(Ans/Xnot(remainder(Ans,X)),X,1,Ans ;Full program
2Ans ;double the input
seq( ;generate a list
X, ;using the variable X,
1, ;starting at 1,
Ans ;and ending at the input
;with an implied increment of 1
Ans/X ;from the input divided by X
not( ), ;multiplied by the negated result of
remainder(Ans,X) ;the input modulo X
;(result: 0 or 1)
sum( ;sum up the elements in the list
= ;equal?
```
**Example:**
```
6
6
prgmCDGF2
1
7
7
prgmCDGF2
0
```
---
**Note:** The byte count of a program is evaluated using the value in **[MEM]**>**[2]**>**[7]** (36 bytes) then subtracting the length of the program's name, `CDGF2`, (5 bytes) and an extra 8 bytes used for storing the program:
36 - 5 - 8 = 23 bytes
[Answer]
# [Java (JDK)](http://jdk.java.net/), 54 bytes
```
n->{int s=0,d=0;for(;++d<n;)s+=n%d<1?d:0;return s==n;}
```
[Try it online!](https://tio.run/##PY/BboMwDIbvfQqrEhKsLg3tQLQp23mHSZN6nHZISajStQElptJU8ewsQLeD7Vj@83/2WdzE8iy/e31taktw9n3ckr7EVWtK0rWJn/isvAjn4F1oA/cZQNMeL7oER4J8udVawtXPwgNZbU6fXyDsyUWjFODN0IdVUpeCFDTKVqokKKA3y5e7NgSuYCgLxqvahnyxkHvDI7coTCD3yavcMW4VtdZ4XWF41/PR1H/0GFKOnPeaQAAJJmtMNpjkuGaYMMZws0lT5hM@JBmuc3zeZpgn/vGYZrha5Wm@zbMtS7NJ2k2gYathywG1m4DRP@/w40hd47qluPGXUxXOA7mD4BiYOY5i/Ls4HrpwSFE0OXezIbr@Fw "Java (JDK) – Try It Online")
Though for a strict number by number matching, the following will return the same values, but is only 40 bytes.
```
n->n==6|n==28|n==496|n==8128|n==33550336
```
[Try it online!](https://tio.run/##PY9Pa4NAEMXvfoohIGiZGP/UZU2w9x4KhRxLDxtdw1pdxR0DpfWz21WTHvYtj3nze0wtbmJfl1@zavtuIKitD0ZSTVCNuiDV6eDp5BSNMAbehNLw4wD046VRBRgSZL9bp0po7cw706D09eMTxHA1/hoFeNX0PshSFYIk9HKoZEGQw6z3LzrP2a@VmC/6nK2GR5tNkjQNk4TNpxWjNFkwSUPGbm9ogAijGKMEI45xiFEYhnjfS/EeYRhztGxcwI8pw8OBpzzjLAtTtkWnrajqBs@WrVXHrdD/7zt/G5Jt0I0U9PZWqrydWx7Bvbh6h2sYHzcGi/MW8f2NPDnLm@Y/ "Java (JDK) – Try It Online")
[Answer]
# x86 Assembly, 45 43 Bytes.
```
6A 00 31 C9 31 D2 41 39 C1 7D 0B 50 F7 F9 58 85
D2 75 F1 51 EB EE 31 D2 59 01 CA 85 C9 75 F9 39
D0 75 05 31 C0 40 EB 02 31 C0 C3
```
**Explaination** (Intel Syntax):
```
PUSH $0 ; Terminator for later
XOR ECX, ECX ; Clear ECX
.factor:
XOR EDX, EDX ; Clear EDX
INC ECX
CMP ECX, EAX ; divisor >= input number?
JGE .factordone ; if so, exit loop.
PUSH EAX ; backup EAX
IDIV ECX ; divide EDX:EAX by ECX, store result in EAX and remainder in EDX
POP EAX ; restore EAX
TEST EDX, EDX ; remainder == 0?
JNZ .factor ; if not, jump back to loop start
PUSH ECX ; push factor
JMP .factor ; jump back to loop start
.factordone:
XOR EDX, EDX ; clear EDX
.sum:
POP ECX ; pop divisor
ADD EDX, ECX ; sum into EDX
TEST ECX, ECX ; divisor == 0?
JNZ .sum ; if not, loop.
CMP EAX, EDX ; input number == sum?
JNE .noteq ; if not, skip to .noteq
XOR EAX, EAX ; clear EAX
INC EAX ; increment EAX (sets to 1)
JMP .return ; skip to .return
.noteq:
XOR EAX, EAX ; clear EAX
.return:
RETN
```
Input should be provided in `EAX`.
Function sets `EAX` to `1` for perfect and to `0` for imperfect.
**EDIT**: Reduced Byte-Count by two by replacing `MOV EAX, $1` with `XOR EAX, EAX` and `INC EAX`
[Answer]
# Regex (Perl/PCRE+`(?^=)`[RME](https://github.com/Davidebyzero/RegexMathEngine)), ~~44~~ 41 bytes
```
((\2x+?|^x\B)(?^=\2+$))++$(?^!(\2x+)\3+$)
```
[Try it on replit.com](https://replit.com/@Davidebyzero/regex-Perfect-numbers-with-lookinto)
This was a port of my 48 byte .NET regex below, using lookinto instead of variable-length lookbehind. This makes it far faster, and able to scan all numbers from 0 to 9000 in about 7 seconds on my PC. It also enables somes golfs that aren't possible in the .NET version.
```
# No anchor needed, because \2 cannot be initially captured if
# matching is started anywhere besides the beginning.
# Sum as many divisors of N as we can (using the current position as the sum),
# without skipping any of them:
(
(
\2x+? # \2 = the smallest number larger than the previous value of \2
# for which the following is true; add \2 to the running total
# sum of divisors.
|
^x # This must always be the first step. Add 1 to the sum of
# divisors, thus setting \2 = 1 so the next iteration can keep
# going.
\B # Exclude 1 as a divisor if N == 1. We don't have to do this for
# N > 1, because this loop will never be able to add N to the
# already summed divisors (as 1 will always be one of them).
)
(?^=\2+$) # Assert that \2 is a divisor of N
)++ # Iterate the above at least once, with a possessive quantifier
# to lock in the match (i.e. prevent any iteration from being
# backtracked into).
$ # Require that the sum equal N exactly. If this fails, the loop
# won't be able to find a match by backtracking, because
# everything inside the loop is done atomically.
# Assert that there are no more proper divisors of N that haven't already been summed:
(?^! # Lookinto – Assert that the following cannot match:
(\2x+) # \3 = any number greater than \2
\3+$ # Assert \3 is a proper divisor of N
)
```
## Regex (Perl/PCRE+`(?^=)`[RME](https://github.com/Davidebyzero/RegexMathEngine)), 45 bytes
```
^(?=(x(?=(x*))(?^=(?(?=\2+$)(\3?+\2))))+$)\3$
```
[Try it on replit.com](https://replit.com/@Davidebyzero/regex-Perfect-numbers-with-lookinto-45-bytes)
This is a port of the largest-to-smallest 47 byte .NET regex below, using lookinto instead of variable-length lookbehind.
## Regex (Perl/PCRE+`(?^=)`[RME](https://github.com/Davidebyzero/RegexMathEngine)), 47 bytes
```
^(?=((?^0=(x*))(?^=(?(?=\2+$)(\3?+\2)))x)+$)\3$
```
[Try it on replit.com](https://replit.com/@Davidebyzero/regex-Perfect-numbers-with-lookinto-47-bytes)
This is a port of the smallest-to-largest 47 byte .NET regex below, using lookinto instead of variable-length lookbehind. This one is less conducive to being ported, and I had to use `(?^0=)`, lookinto accessing the in-progress current match. I've not decided how to finalize the current behavior of this, so it's likely this version will not work with a future version of lookinto.
# Regex (.NET), 47 bytes
```
^(?=((?<=(?=(?(\3+$)((?>\2?)\3)))(^x*))x)+$)\2$
```
[Try it online!](https://tio.run/##ZVBNT@MwEL3zK0yFVA9NIifsAWHcrhTtAQm0K4q0BwqSNx2KJdeJbKdrGvjtxU1aLvhijd8bv4/KpVVtcWfkGl0jKyTzN@dx3bVOmRUpRVkbV2vkw/yAwWf3uGq1tL9CY9E5FQm80tI5su6cl15VZFOrJbmTyhAK3UZa4sTP0e6ZzgSls2uxv2d0cTE5gzhPF8UMFhcAQJ/DOUCA@L4oznYjvl@1wuB/EjUxUJfN23/O22iF5onLbtGs/GtaQNLjvxu/d5OV9bpRGpfABy7R/KW2VBlPjGCcalHGEHJ5qwxSgFNhWq25ETl06oWaKYMy@2uVx4HQ22iEzuaNVp6O0zHw/V8qQX4SF5qDj2nx/n4agezBvv2R1iFtHtlTUreRCt@h41qaDxyEoywd3ZiN1LFDK80Kr0jHPkaJBo7aYd9n6EuZD02MwzhR8BVxGyOqa4FcTSZJmIgIQ3Rpsxt3J331SgP0Obffcm5Fzr8s9Jrh4BH4R392LM0ZYyeXecHSy/wH@wQ "C# (.NET Core) – Try It Online")
```
^(?=(x(?=(x*$)(?<=(?(^\2+)(\2(?>\3?))))))+$)\3$
```
[Try it online!](https://tio.run/##ZZBfa9swFMXf@ynUEIju/AfZ3UOZqnhg9lBo2VgKe1hW0JzbVKDIRpIzN24/e6bIbV@qB4E45@r@zmlc1rQWj0bu0HWyQbJ6ch53Y@@U2ZJa1K1xrUY@ve9w8PlP3PZa2m9DZ9E5FQy80dI5shudl141ZN@qDbmVyhAK415a4sTX2fGeVoIO8fo0B1pdCVrR@3WZAF2XtFquLyqIJ5nD@mJ@nPHTqBUG/5GwEwfq8lX/13kbUGiRuvwGzdY/ZiWkUf/e@RNNXre7TmncAJ@8RPOH1lJlPDGCcapFHULIzY0ySAHOhem15kYUMKoHapYM6vyXVR4nQ8TohM5XnVaeLrIF8NNfKkV@Fga6V45l@fx8HoT8zj79kNYh7X6zP2nbByt8lN7GsmLyILytpbNrs5c6dGil2eIXMrKXWaqBo3YY@xxiKaupicWwSBW8RzyEiOpKIFdJkg6JCDIESptfu1vpm0c6QMx5@JDzIAr@jhB3Dq@MwF/iObKsYIydXRYlyy6Lz@w/ "C# (.NET Core) – Try It Online")
This is based on [my 44 byte abundant numbers regex](https://codegolf.stackexchange.com/questions/110708/an-abundance-of-integers/219934#219934), with is in turn based on [Martin Ender's 45 byte abundant numbers regex](https://codegolf.stackexchange.com/questions/110708/an-abundance-of-integers/110732#110732). It was trivial to adapt to matching perfect numbers; just two small changes were needed, with a third change made for aesthetic purposes.
```
# For the purpose of these comments, the input number will be referred to as N.
^(?= # Attempt to add up all the divisors of N.
(x # Cycle through all positive values of tail that are less than N,
# testing each one to see if it is a divisor of N. Start at N-1.
(?= # Do the below operations in a lookahead, so that upon popping back
# out of it our position will remaing the same as it is here.
(x*$) # \2 = tail, a potential divisor; go to end to that the following
# lookbehind can operate on N as a whole.
(?<= # Switch to right-to-left evaluation so that we can operate both
# on N and the potential divisor \2. This requires variable-length
# lookbehind, a .NET feature. Please read these comments in the
# order indicated, from [Step 1] to [Step 4].
(?(^\2+) # [Step 1] If \2 is a divisor of N, then...
( # [Step 2] Add it to \3, the running total sum of divisors:
# \3 = \3 + \2
\2 # [Step 4] Iff we run out of space here, i.e. iff the sum would
# exceed N at this point, the match will fail, and the
# summing of divisors will be halted. It can't backtrack,
# because everything in the loop is done atomically.
(?>\3?) # [Step 3] Since \3 is a nested backref, it will fail to match on
# the first iteration. The "?" accounts for this, making
# it add zero to itself on the first iteration. This must
# be done before adding \2, to ensure there is enough room
# for the "?" not to cause the match to become zero-length
# even if \3 has a value.
)
)
)
)
)+ # Using "+" instead of "*" here is an aesthetic choice, to make it
# clear we don't want to match zero. It doesn't actually make a
# difference (besides making the regex ever so slightly more
# efficient) because \3 would be unset anyway for N=0.
$ # We can only reach this point if all proper divisors of N, all the
# way down to \2 = 1, been successfully summed into \3.
)
\3$ # Require the sum of divisors to be exactly equal to N.
```
# Regex (.NET), 48 bytes
```
((?=.*(\1x+$)(?<=^\2+))\2|^x\B)+$(?<!^\3+(x+\2))
```
[Try it online!](https://tio.run/##ZZDNbtswEITveQraCGBu9QNK7SEow6So0EOABC3qAD1UNcDKG4cATQkk5TKW8@wuLSW5hDdyZrnfTOOyprV4NHKLrpMNkuWT87gdeqfMhlSiao1rNfLpfo/B5z9x02tpv4XOonMqGnijpXNkOzgvvWrIrlVrcieVIRSGnbTEiS/zI6XXIv9A6yIk50CvL8WqLhOAujysQv0VkvP4NlvVHxMakroEOM75adYKg/9IXIqBunzZ/3XeRhZapC6/RbPxj1kJ6ah/7/wJJ6/abac0roFPXqL5Q2upMp4YwTjVooop5PpWGaQAM2F6rbkRBQzqgZorBlX@yyqPk2HE6ITOl51Wni6yBfDTXypFfhYHuheOq/JwmEUhv7dPP6R1SLvf7E/a9tEK76XXsayYPAiva@n8xuykjiVaaTb4mQzseZ5q4KgdjoWGsZTl1MQiLFIFbxH3MaK6FMhVkqQhEVGGSGnzG3cnffNIA4w59@9y7kXB3xDGneGFEfjzeI4sKxhjZxdFybKL4hP7Dw "C# (.NET Core) – Try It Online")
This is based on [my 43 byte abundant numbers regex](https://codegolf.stackexchange.com/questions/110708/an-abundance-of-integers/219934#219934). It was interesting and somewhat tricky to adapt into a fully golfed perfect numbers regex.
```
# No anchor needed, because \1 cannot be initially captured if
# matching is started anywhere besides the beginning.
# Sum as many divisors of N as we can (using the current position as the sum),
# without skipping any of them:
(
(?= # Atomic lookahead:
.*(\1x+$) # \2 = the smallest number larger than the previous value of \1
# (which is identical to the previous value of \2) for which the
# following is true. We can avoid using "x+?" because the ".*"
# before this implicitly forces values to be tested in increasing
# order from the smallest.
(?<=^\2+) # Assert that \2 is a divisor of N
)
\2 # Add \2 to the running total sum of divisors
|
^x # This must always be the first step. Add 1 to the sum of divisors,
# thus setting \1 = 1 so the next iteration can keep going
\B # Exclude 1 as a divisor if N == 1. We don't have to do this for
# N > 1, because this loop will never be able to add N to the
# already summed divisors (as 1 will always be one of them).
)+$ # Require that the sum equal N exactly. If this fails, the loop
# won't be able to find a match by backtracking, because everything
# inside the loop is done atomically.
# Assert that there are no more proper divisors of N that haven't already been summed:
(?<! # Assert that the following, evaluated right-to-left, cannot match:
^\3+ # [Step 2] is a proper divisor of N
(x+\2) # [Step 1] Any value of \3 > \2
)
```
# Regex (Perl / PCRE2 v10.35+), ~~64~~ ~~60~~ 57 bytes
This is a port of the 41 byte regex, emulating variable-length lookbehind using a recursive subroutine call.
```
(?=((\2x+?|^x\B)((?<=(?=^\2+$|(?3)).)))++$)(?!(\2x+)\4+$)
```
[Try it online!](https://tio.run/##RY5RS8MwFIXf/RVxhPVe0rqkrjBMs3QyX33yzW5lygqBuNWkQqWrf73GMvDlcr9zDvfc5uhsNn58E@ok6e35/WAJXciAKt9uXjbrgdRnB9QrLvO1xJ4UVvnGmhaiJIr915tvg13FiYgFHj9n5Wmm/1UedHygFUpiavDh@sEVNk@xL@yr2Kkw@U5eO8wVqcnVZIeNMexNTQCiLiIdCSFEon7IgroF9tTP540zp/avVoYnhZyQUCOHYaiqp@dtVY2gFUCZdkxf9l35iAA6V0HclymjF9D3iHeIyBhF0LdTEstloHHkSZbxm5VIebISS/4L "Perl 5 – Try It Online") - Perl
[Attempt This Online!](https://ato.pxeger.com/run?1=fVHNbtQwEBbXfYrBspQZkuwmSyst8kaRECBVQhyAW9NaaXC6hqwTOV5ppbZPwqUS6rlPwUPA0zDZ7QUOHDyen--bbzz-_mPYDPe_n_1cl-yA9FCAWAiYw-DNtfZm6OrGYLSYvyi13tRd0E2_HWxnfIUVqerjYowSiPi0nNTXZgK4YFwYUet3Z-_fak0J5MQtubGaWWf1aAKKofFmflU334Jnozu7tUEkINJckIK_Yd40Oz_a3v0f9vVYyrgya3uP0haZkl3R8lgjfvr85uwDKboB26LszsfgO-PYozS_KApROUEMHndXXOF0kiVpThPf7Ieu_2JQpCJhuGJ-0-9cmLjrJZPOuQHb7ELNAA7K7imWbl0c6uzFMbE04GG12zo0G5Q-YbFpz6YOGO2jRDoigptpREum2fTTXAr4KbmCKQbp1B3L3P3zH0jqYRfadPXrFZYFYrXcx-Xt5b56TYjluuDkZbWM5S2WL4nmrBLHkrB8fkBSdcLRscH90_WYpaen2WyVL7N0lZ9kx_Qf "PHP - Attempt This Online") - PCRE2 v10.40+
```
# No anchor needed, because \2 cannot be initially captured if
# matching is started anywhere besides the beginning.
(?=
# Sum as many divisors of N as we can (using the current position as the sum),
# without skipping any of them:
(
(
\2x+? # \2 = the smallest number larger than the previous value of \2
# for which the following is true; add \2 to the running total
# sum of divisors.
|
^x # This must always be the first step. Add 1 to the sum of
# divisors, thus setting \2 = 1 so the next iteration can keep
# going.
\B # Exclude 1 as a divisor if N == 1. We don't have to do this for
# N > 1, because this loop will never be able to add N to the
# already summed divisors (as 1 will always be one of them).
)
((?<= # Define subroutine (?3); lookbehind
(?= # Circumvent the constant-width limitation of lookbehinds
# in PCRE by using a lookahead inside the lookbehind
^\2+$ # This is the payload of the emulated variable-length
# lookbehind: Assert that \2 is a divisor of N
|
(?3) # Recursive call - this is the only alternative that can
# match until we reach the beginning of the string
)
. # Go back one character at a time, trying the above
# lookahead for a match each time
))
)++ # Iterate the above at least once, with a possessive quantifier
# to lock in the match (i.e. prevent any iteration from being
# backtracked into).
$ # Require that the sum equal N exactly. If this fails, the loop
# won't be able to find a match by backtracking, because
# everything inside the loop is done atomically.
)
# Assert that there are no more proper divisors of N that haven't already been summed:
(?! # Assert that the following cannot match:
(\2x+) # \4 = any number greater than \2
\4+$ # Assert \4 is a proper divisor of N
)
```
It isn't practical to directly port the 47 byte regex to PCRE, because it changes the value of a capture group inside the lookbehind, and upon the return of any subroutine in PCRE, all capture groups are reset to the values they had upon entering the subroutine. It is possible, however, and I did this for the corresponding [Abundant numbers regex](https://codegolf.stackexchange.com/a/219934/17216) by changing the main loop from iteration into recursion.
# Regex (ECMAScript), 53 bytes – Even perfect numbers
If it is ever proved that there are no odd perfect numbers, the following would be a robust answer, but for now it is noncompeting, as it only matches even perfect numbers. It was written by [Grimmy](https://codegolf.stackexchange.com/users/6484/grimmy) on [2019-03-15](https://chat.stackexchange.com/transcript/message/49504867#49504867).
```
^(?=(x(x*?))(\1\1)+$)((x*)(?=\5$))+(?!(xx+)\6+$)\1\2$
```
[Try it online!](https://tio.run/##Tc@9bsIwFAXgvU8BEaL3kiY4qEUI12TqwMLQjk0rWWAct8axbAMpP8@emqFSlytdfUc6Ol/8wP3aKRsyb9VGuF1jvsVP55gRx96rkC@tBTixxXjUfULJoIV2VCJCVVQFpgOE@GOE6mmAmELZh7ZNsZpGipHJoBuNT5iH5i04ZSRg7rVaC5g@ZI@I1DNCj7XSAkAzJ/hGKyMAsc/MXms8S6Zzb7UKcJ/dI1VbAMNkroWRocbF5HJRfsVXoJjlzoulCSDfyQfiH4j/YBZFWcxvjKF2zTFZmgPXatNz3Egx7yWpptvGAVXPTFCVphgLkzbJnbCCB1CY73hY1@AQz344tHFSgNuKgtp98MHFCL1eO5IVhJC7WTzZbELILw "JavaScript (SpiderMonkey) – Try It Online")
This uses the fact that every [even perfect number](https://en.m.wikipedia.org/wiki/Perfect_number#Even_perfect_numbers) is of the form \$2^{n-1} (2^n-1)\$ where \$2^n-1\$ is prime. For \$2^n-1\$ to be prime, it is necessary that \$n\$ itself be prime, so the regex does not need to do a \$log\_2\$ test on \$2^n\$ to verify \$n\$ is prime. (I have used \$n\$ here instead of \$p\$ to make that clear.)
```
^ # N = tail = input
(?=(x(x*?))(\1\1)+$) # Assert that the largest odd divisor of N is >= 3 (due to
# having a "+" here instead of "*"; this is not necessary, but
# speeds up the regex's non-match when N is a a power of 2);
# \1 = N / {largest odd divisor of N}
# == {largest power of 2 divisor of N}; \2 = \1 - 1
((x*)(?=\5$))+ # tail = N / {largest power of 2 divisor of N}
# == {largest odd divisor of N}
(?!(xx+)\6+$) # Assert tail is prime
\1\2$ # Assert tail == \1*2 - 1; if this fails to match, it will
# backtrack into the "((x*)(?=\5$))+" loop (effectively
# multiplying by 2 repeatedly), but this will always fail
# to match because every subsequent match attempt will be
# an even number, and "\1\2$" can only be odd.
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 41 bytes
```
f(n,i,s){for(i=s=n;--i;s-=n%i?0:i);n=!s;}
```
[Try it online!](https://tio.run/##VYzNboMwEAbv@xTbRES2BJUNxTJxaR@k7YHwE1YiprKNcoh4dmqqXnpZ7Yw@TZtd23bbBmZTSj1/DLNjVPvamiwj47PaJvQuzsSNrZ@8Wbcj2XZauh5ffehofh7f4J@a6LI7IBvw1pBl/AG4g11uBrAdG4eXZfiQ6ivifaSpZ9c@eBYlx9MJWRxijU2Yp1/H9wB@u9gY2CHpzph0n/aQ7sEUh33OeUytgK4Pi7MoDKybBJmDLEBqyAVIIQQURVmKeEBBruGlUqBlfP50pFJXWlWiVD8 "C (gcc) – Try It Online")
```
1: 0
12: 0
13: 0
18: 0
20: 0
1000: 0
33550335: 0
6: 1
28: 1
496: 1
8128: 1
33550336: 1
-65536: 0 <---- Unable to represent final test case with four bytes, fails
```
Let me know if that failure for the final case is an issue.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 [bytes](https://github.com/barbuz/Husk/wiki/Codepage)
```
=¹ΣhḊ
```
Yields `1` for a perfect argument and `0` otherwise.
**[Try it online!](https://tio.run/##yygtzv7/3/bQznOLMx7u6Pr//78ZAA "Husk – Try It Online")**
### How?
```
=¹ΣhḊ - Function: integer, n e.g. 24
Ḋ - divisors [1,2,3,4,6,8,12,24]
h - initial items [1,2,3,4,6,8,12]
Σ - sum 36
¬π - first argument 24
= - equal? 0
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 5 bytes
```
;÷Σ½=
```
Full program taking input from STDIN which prints `1` for perfect numbers and `0` otherwise.
**[Try it online!](https://tio.run/##S0wuKU3Myan8/9/68PZziw/ttf3/38gCAA "Actually – Try It Online")**
### How?
```
;÷Σ½= - full program, implicitly place input, n, onto the stack
; - duplicate top of stack
√∑ - divisors (including n)
Σ - sum
¬Ω - halve
= - equal?
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 45 bytes
```
: f 0 over 1 ?do over i mod 0= i * - loop = ;
```
[Try it online!](https://tio.run/##LYzLCsIwEEX38xWHLoWUPKxUS/VjGquCkhCqvx8z6ObeM5fDrKlsd3NbtWo9sWJJn2vBcYnphw9eKWLnBjsMz5QyM1OzM/GdGekL0HdgznTth9dlKUyIHJolfiTL/thYRqcHEsIw2BB0Woq4Vs5rBA3VvVWyVusvD@T6BQ "Forth (gforth) – Try It Online")
### Explanation
Loops over every number from 1 to n-1, summing all values that divide n perfectly. Returns true if sum equals n
### Code Explanation
```
: f \ start word definition
0 over 1 \ create a value to hold the sum and setup the bounds of the loop
?do \ start a counted loop from 1 to n. (?do skips if start = end)
over \ copy n to the top of the stack
i mod 0= \ check if i divides n perfectly
i * - \ if so, use the fact that -1 = true in forth to add i to the sum
loop \ end the counted loop
= \ check if the sum and n are equal
; \ end the word definition
```
[Answer]
# [Kotlin](https://kotlinlang.org), 38 bytes
```
{i->(1..i-1).filter{i%it==0}.sum()==i}
```
Expanded:
```
{ i -> (1..i - 1).filter { i % it == 0 }.sum() == i }
```
Explanation:
```
{i-> start lambda with parameter i
(2..i-1) create a range from 2 until i - 1 (potential divisors)
.filter{i%it==0} it's a divisor if remainder = 0; filter divisors
.sum() add all divisors
==i compare to the original number
} end lambda
```
[Try it online!](https://tio.run/##HY2xCsIwEED3fsV1EO6GBLs4COngJvgTQVM4TC/SXl1Cvj0mvvnx3jtpZKlfH2E55HkFvIsSmBluKcXgBRzUzGbGyVo2E9mFo4Yt84nVuXOx@7EiOceltgCsngUJ8gCNXtWwa2tswb8eLAFpHK2mNkH6O5@NRaNgv2OXiYZSLz8)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), ~~5~~ 4 bytes
```
─╡Σ=
```
[Try it online!](https://tio.run/##y00syUjPz0n7///RlIZHUxeeW2z7/78hlxGXMZcJlymXGZeROZeRxX8A "MathGolf – Try It Online")
## Explanation
```
─ get divisors (includes the number itself)
‚ï° discard from right of list (removes the number itself)
Σ sum(list)
= pop(a, b), push(a==b)
```
Since MathGolf returns divisors rather than proper divisors, the solution is 1 byte longer than it would have been in that case.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 ~~13~~ bytes
```
qsf!%QTSt
```
[Try it online!](https://tio.run/##K6gsyfj/v7A4TVE1MCS45P9/QyMA "Pyth – Try It Online")
Thank you to the commentors for the golf help
Finds all the factors of the input, sums them, and compares that to the original input.
[Answer]
# [VDM-SL](https://raw.githubusercontent.com/overturetool/documentation/master/documentation/VDM10LangMan/VDM10_lang_man.pdf), 101 bytes
```
f(i)==s([x|x in set {1,...,i-1}&i mod x=0])=i;s:seq of nat+>nat
s(x)==if x=[]then 0 else hd x+s(tl x)
```
Summing in VDM is not built in, so I need to define a function to do this across the sequences, this ends up taking up the majority of bytes
A full program to run might look like this:
```
functions
f:nat+>bool
f(i)==s([x|x in set {1,...,i-1}&i mod x=0])=i;s:seq of nat+>nat
s(x)==if x=[]then 0 else hd x+s(tl x)
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 4 bytes
```
dΣ⁻=
```
[Try it online!](https://tio.run/##S0/MTPz/P@Xc4keNu23//zeyAAA "Gaia – Try It Online")
1 for perfect, 0 for imperfect.
```
d | implicit input, n, push divisors
Σ | take the sum
⁻ | subtract n
= | equal to n?
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~3+1~~ 3 bytes
```
∆K=
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%88%86K%3D&inputs=1&header=&footer=)
*-1 byte thanks to @Deadcode for telling me to not be an idiot and remember that I added a sum of proper divisors built-in. I actually forgot that I did*
This is: does the sum of the proper divisors of the input (`∆K`) equal the input itself (`=`).
[Answer]
# Qbasic, ~~53~~ 47 bytes
Thank you @Deadcode, -6 bytes
```
INPUT n
FOR i=1TO n-1
s=s-i*(n\i=n/i)
NEXT
?n=s
```
Literally quite Basic... Prints `-1` for perfect numbers, `0` otherwise.
[REPL](https://repl.it/@pimsteenbergh/FlickeringJadedSymbol)
[Answer]
# Machine Language (x86 32-bit), ~~24~~ 23 bytes
This is a macro that takes an unsigned integer in EAX as input (N), and outputs the result in the Zero Flag (set=perfect, clear=imperfect). It also outputs a result in the Carry Flag (set=abundant, clear=non-abundant). As such, it's actually an answer for both this question and [An abundance of integers!](https://codegolf.stackexchange.com/questions/110708/an-abundance-of-integers), requiring no modification.
It's based on [640KB's abundant numbers answer](https://codegolf.stackexchange.com/questions/110708/an-abundance-of-integers/179016#179016), with the two additional optimizations from [l4m2's answer](https://codegolf.stackexchange.com/questions/110708/an-abundance-of-integers/179303#179303), where the divisors are subtracted from N instead of added to it (thus simultaneously setting the flags for the return value). An input of 1 is correctly handled, costing ~~3~~ 2 bytes.
```
89 C1 89 C3 9E EB 0E 31 D2 50 F7 F1 58 85 D2 75 04 29 CB 72 02 E2 F0
```
[Try it online!](https://tio.run/##jVZNb@M4DD1Hv4KYSxpMOusk7e42RQ/ZbAvsYjGXuRQzKAzZomMNbMmw5DSdP9@lbPlrEkziQxtJ5CP5SJHixmAeZW/XCTf5e6LLnFt4/O8J8IBxZXmUIawYC43lpV2zSYYcAI2cwzdpwgLLBGP70u4Lt49KhKOzXO8BojeL8E1VeYTlx@XLHKYwZSkeQlHlRZhpXTh0LUzkFXg6B56xiUlLWmRzuGETrkRzEByeaCXc6kBQQTBlkzgvGsHpHa2@RwhAXhkbGrkLlYwolNDkPMtaTSe6mV5fkfzHxYydFl63wOkQONe/wE3HuCdl1z7KV12KlhYihR/8PgqKa@Vt13wTuc44kAEhQlPwGE9g1NQGh02wYROp4hqIdQqtVYwJvVFodyLaWbQLR@qNA7BAYH8Gp/0YZa/PpdCKDA2hFqyvh/U7@K/3hIT83j3EungDqYrKegdpYTU8bp/ZWDG6UPGvXtHwNIGfvnsSg5gb/EnXwGJO9WPh69NDAK7wtvSjg/ru@Ii1snXwLRQe4qwSCLqUO6l41qJxAxyE3EujS5bw2PqCb9EOuvQppz99RFSRJTz@/QxXqdylTZ7pitZIgq7ZrAMoKpMO2PAAhu8HvrRanRJt1AkYKzVizuz6cfMMv42oL1ysR3ZKNFaXeGzB0sFxXDIhjZxLJYiaBwjmIK3XNYB7VNlbz7P6cYJnQlDazusDqSqEugK7NFdRWx9xb/VLFdmSqG/zAEmpc1ce92BTSreReZVZrlBXZuDAqY9Sk3K1I29tilBWSkm1A6utaymuVAza5izJ@M64nJ3Bq3HQVqWCPc8q/NQTELtM0ZUayf@TuHKkCnWKpspBJ21cxsVfR4qiixFSbs64QLWLKEhHV@XoLswhR15HSGkionhUKcGVnZ8BdES8IihCJW4In9Sdu3UilX51mz5ml4AzaFRjlB53WTteP7GuMPqrVKN3V4zVzegXoD3l6zMOXP37dQZUrtQPFvTPt7OzSp9J66FpIg8g80vVtrWtbWOrZfy8se2s0XLGlFbXF2tuWntNr/P@CkxkLPESy5tZ66/rZZ4k50KH8T5@GLgRUd/unpRJ28bY6EGh8DWTCq8XL8PxRcPKWDEaXwETGEsar@17YtRX2aRpeBH9OsTprplN9UH/HnAPCWpm7hXSjM/4WLrparyZPz6IoeFu8ko2nOY11GDouTl6yewlWnzXZR1VjrzGiPOgGc5OcRnQ598oPdVDidXq9jZYLZ0QJ6GCGgOGy6HxTsKfrY/Vb0/YaNmmYGqKh@N/GI0fiSAi@HCzvLu5@/2P5d3tB@az7Pbp/fL@Pw "Assembly (fasm, x64, Linux) – Try It Online")
```
89 C1 mov ecx, eax ; copy input number into ECX
89 C3 mov ebx, eax ; copy input number into EBX
9E sahf ; in case input number is 1, let ZF=0 and CF=0
EB 0E jmp cont_loop ; exclude original number as a divisor
fact_loop:
31 D2 xor edx, edx ; clear EDX (high word for dividend)
50 push eax ; save original dividend
F7 F1 div ecx ; divide EDX:EAX / ECX
58 pop eax ; restore dividend
85 D2 test edx, edx ; if remainder = 0, it divides evenly
75 04 jnz cont_loop ; if not, continue loop
29 CB sub ebx, ecx ; Subtract divisor from EBX; this simultaneously
; changes the running total, and sets the flags for
; the return value.
72 02 jc done ; If CF=1, the sum of divisors subtracted from EBX has
; exceeded our input number, meaning it is abundant,
; and we need to exit the loop now to return this
; result in the flags.
cont_loop:
E2 F0 loop fact_loop
done: ; return value:
; (JZ) = ZF=1 = perfect
; (JNZ) = ZF=0 = imperfect
; (JC) = CF=1 = abundant
; (JNC) = CF=0 = non-abundant
; (JA) = CF=0 and ZF=0 = deficient
; (JNA) = CF=1 or ZF=1 = non-deficient
```
[Answer]
# [Machine Language (x86 32-bit)](https://flatassembler.net/), 21 bytes
```
is_perfect:
mov ecx, esi ; copy input number into ECX
inc esi
mov ebx, esi ; copy input number + 1 into EBX
fact_loop:
xor edx, edx ; clear EDX (high word for dividend)
mov eax, esi
div ecx ; divide (n+1) / ECX
dec edx ; if remainder = 1, n/ECX is zero and ECX is not 1
; In case EAX = 2^32-1, this doesn't work as intended
; (get edx=0 for all ECXs)
; According to test 2^(2^n)-1 up to 2^128-1 are all
; deficient so it happens to be correct
jnz cont_loop ; if not, continue loop
sub ebx, eax ; Subtract divisor from EBX; this simultaneously
; changes the running total, and sets the flags for
; the return value.
jc done ; If CF=1, the sum of divisors subtracted from EBX has
; exceeded our input number, meaning it is abundant,
; and we need to exit the loop now to return this
; result in the flags.
cont_loop:
loop fact_loop
dec ebx ; Subtract the 1 added into esi for ZF
done: ; return value:
; (JZ) = ZF=1 = perfect
; (JNZ) = ZF=0 = imperfect
end_is_perfect:
```
[Try it online!](https://tio.run/##hVZNb@M2ED1bv2KwFzuIvSs5abtxkIO7TYAtil56CRIkBiWOLG4lUhCpRN4/nw4p6itwYx1sk@I8znvzZaY1FnF@WKVMF2@pqgpm4PavO8AGk9qwOEe4CIKdNqwym2CWIwNALZbwKPSuxCrFxDx1@9zuo@S7ybtCvQDEB4PwKOsixup8/bSEOcyDDJsdr4tylytVWnTFdewNWLYElgcznVW0yJdwGcyY5O2LsLmjFberhqDCcB7MkqJsD86vaPUjRgDySpudFvudFDFR2emC5XlnaY9u56sFnT@PzoLjhzcdcDYGLtQHuNkU9@jZjWf5qireyUKisMbvIydeF/5upzeJay8HuoDznS5ZgkcwnLRhsw23wUzIxAEFvUF3KyaE3hp0OzHtRN3CinppAQwQ2NfwuB@T6A2x5ErSRR2UNYnehnzYBOCfwRM65PeuIVHlAYQsa@MdpIVRcPvtviOkxTuI@CTEOUQe5vf7IGWJ8QnX4TSq8pLTx4BDGVHB7R/3sMjEPmt1phIBLl4EpzQ/e@cIax3pd@mcYwij59pbw0JScsAXx6w3wDZiUwORQoUFE5ITlRuIKHRfyAqEhp9YKbBV4ddSGRtFOPJcw3cJCdMIt9t7glk/X6xXhGUysuMKtZwbS/FfYNqKRfyQ/x/UYo/GOnoTOkEooa0HehDkuNk2SUhDIfdAsTCoDXmxWD/Ls1UEdWk318/R@iutWIXgSuo4EMdUJAIpP7UCYSBjZYlSWwQqT7qkolTrnfkhfwJtyjbsI1lJrqV7IWSN4NK4s9F13KUWG1Linzo2FeWPC6Im5mmlCptV162OWhR1bphEVev8cEKNJGNyj@R0hlDVUra6GNuXbEg1mvZdmrO9tjqfwHM4aOpKwgvLa/w8CJDY5KK6nOZDCt/ublwKIPEtQKUdL235O6bIe46ksj7hAjYJIuUNqLqalOASCmSOIUWLhGJxLTmTZnkC0ArxiiAJ1QYXGzK37rpASvVqNz1nG4ATaBVqCg85Nuj6OegTY@gHDr3vE8Gsrcv4XV32yWDBItuWyUnXZmw3snXxcBe4bviBQ0O4NiecX/z5cAZUuA8UM/ry/fSk0d9k5YxC@hJFZzad0pu38WSnz1X0RNZpLRMjlCRWSUXjkfhZavHBNhlXVQPgjEa14f34IhyJr7mQOB4qtjuq2vhxP2m7k0FEE6dtnnHjpyq309qOed8jhT//SD9p5HFqFa6htNfYOer885eNp6p365wotEXeOiDGs3G0/HgwEu1egs1oQo0GZhTS4/83DIoHGctNrwFd4qgOt0STWwI/yIDH8OlyfXV59etv66tfPgWejN2Pwrf/AA "Assembly (fasm, x64, Linux) – Try It Online")
# [Machine Language (x86 32-bit)](https://flatassembler.net/), 22 bytes edited from [here](https://codegolf.stackexchange.com/a/220380/) with also abundant? output
```
is_perfect:
mov ecx, esi ; copy input number into ECX
mov ebx, esi ; copy input number into EBX
fact_loop:
xor edx, edx ; clear EDX (high word for dividend)
lea eax, [esi+1]
div ecx ; divide (n+1) / ECX
dec edx ; if remainder = 1, n/ECX is zero and ECX is not 1
; In case EAX = 2^32-1, this doesn't work as intended
; (get edx=0 for all ECXs)
; According to test 2^(2^n)-1 up to 2^128-1 are all
; deficient so it happens to be correct
jnz cont_loop ; if not, continue loop
sub ebx, eax ; Subtract divisor from EBX; this simultaneously
; changes the running total, and sets the flags for
; the return value.
jc done ; If CF=1, the sum of divisors subtracted from EBX has
; exceeded our input number, meaning it is abundant,
; and we need to exit the loop now to return this
; result in the flags.
cont_loop:
loop fact_loop
test ebx, ebx ; Not SUBed in last cycle
done: ; return value:
; (JZ) = ZF=1 = perfect
; (JNZ) = ZF=0 = imperfect
; (JC) = CF=1 = abundant
; (JNC) = CF=0 = non-abundant
; (JA) = CF=0 and ZF=0 = deficient
; (JNA) = CF=1 or ZF=1 = non-deficient
end_is_perfect:
```
[Try it online!](https://tio.run/##jVZNb@M2ED1bv2KwF9uIvSs5abtxkIM3TYAWxV4WBYINEoMSRxa3EimIVCLvn0@HFCVZhRtHhzj8mDczbx6HZFpjEef7Zcp08ZqqqmAGbv@6A2wwqQ2Lc4TzINhqwyqzDiY5MgDUYgEPQm9LrFJMzGM3z@08Sr4drRXqGSDeG4QHWRcxVmerxwVMYRpk2Gx5XZTbXKnSoiuuY2/AsgWwPJjorKJBvoCLYMIkbxfC5o5G3I4aggrDaTBJirLdOL2k0Y8YASgqbbZa7LZSxJTKVhcszztLu3UzXc5o/1k0D45vXnfA2SFwod7Azca4R/eufZYvquIdLUQKa/w8csrr3Pt2fBO51jmQA863umQJHsFw1IbNJtwEEyETBxT0Bp1XTAi9NehmYpqJuoEl9cICGCCwz@HxOEbVG2rJlSRHHZQ1iV4HPawD8N8QCW3yc1eQqHIPQpa18QHSwCi4vbn/j2H8TsMv90HKEuMl1mE0qvIk058BgzRQwe3v9zDLxC5rmaVDAVw8C07CnvcAreAtUQ8UxVn02K/QXpcXHHxXHgFmkiQBn0b5cGzrNDYQKVRYMCE5pXINERXsE1mB0PATKwX2LPixVMbWDo58V/CHhIRphNvNPcGsns5XS8IyGdlxhVpOjU3zH2DaEkY5Iv8/qNkOjQ30OnSkkIxtBHog5bjZJkmIRyF3QPUwqA1FMVs9yfkygrq0k6unaPWZRqxCcAfpOBDHVCQCSZVagTCQsbJEqS0CHUpyUpHA@mB@yJ9Ak7It/QGtRNfCLQhZIzjxdja6jjtpsUEW3@rYVKQhV0RNmaeVKqyyrloetSjq3DCJqtb5/gQbScbkDinoDKGqpWx5MbYb2ZJqNO1amrOdtjyfwHM4aOpKwjPLa/w4EJBYcdFpHOshhZu7aycBpHwLUGmXl7b5u0yR9zkSy/pECNgkiKQbUHU1OoILKJC5DKlaRBSLa8mZNIsTgJaIFwRJqLa42JC5DdcVUqoXO@lztgU4gVahpvJQYAOvH4NeGENPcOh9rwgmTqqtGOJBDF/psH37@wtFRoA5XRmQ7KlvBK7tvRHDUKH1iXhnf36fA53V71Qm@vGN86TRV7JyRiH9iOK9ZjfO103rqyvQaWc389bKOpNKLt9tuen8ha7MPt7@aJ/2vJl38doe7kmyIQwY4yfI@nXiesHAyYSeFYb3Vy1dURJfciHx8AKkth6o2vinyejCGF2adDu2LT9u/AuA25eFfZL4zi78/gf6l65nnnfaYm2jCdr4vLPDF4AP64y6e9ua2gDE4T1@MHz7Eqe0ewrW3fOAkjy43KOQPv/GGQgMMpabngNy4lIdvEQjL4G/foHH8OFidXlx@etvq8tfPgQ@GTsfha//Ag "Assembly (fasm, x64, Linux) – Try It Online")
Bad luck in last round `sub` is not runned and a `test` is needed
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~70~~ ~~67~~ 63 bytes
*-3 bytes thanks to [@Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)*
*-4 bytes thanks to [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan)*
```
$N:-bagof(M,(between(1,N,M),N mod M<1),L),sumlist(L,S),S=:=2*N.
```
[Try it online!](https://tio.run/##LYlBC0RAHEe/ioMys/1o/mPJ2qXccXFRcqBFCiNsbr661baX1@u9eVGD6sx1789TT32zrjrVsgSsbra9aSZGSJFwpNqo3lryIo6YY/2MQ79uLEbGkQV@IG@pdfrmWM2/XkRlGDKmR8gDeuaB4GjVMlYbM45ZM0PtmI/JQHH9knMUBJIgG@RBCpAQArbtOOICXEgP94cLjy75Z7fk1vkF "Prolog (SWI) – Try It Online")
] |
[Question]
[
## Challenge
A [repdigit](https://oeis.org/wiki/Repdigit_numbers) is a non-negative integer whose digits are all equal.
Create a function or complete program that takes a single integer as input and outputs a truthy value if the input number is a repdigit in base 10 and falsy value otherwise.
The input is guaranteed to be a *positive* integer.
You may take and use input as a string representation in base 10 with impunity.
## Test cases
These are all repdigits below 1000.
```
1
2
3
4
5
6
7
8
9
11
22
33
44
55
66
77
88
99
111
222
333
444
555
666
777
888
999
```
A larger list can be found [on OEIS](https://oeis.org/A010785).
## Winning
The shortest code in bytes wins. That is not to say that clever answers in verbose languages will not be welcome.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 1 byte
```
=
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/3/b/f0NDQwA "Brachylog – Try It Online")
This acts on integers.
From [`src/predicates.pl#L1151`](https://github.com/JCumin/Brachylog/blob/master/src/predicates.pl#L1151):
```
brachylog_equal('integer':0, 'integer':0, 'integer':0).
brachylog_equal('integer':0, 'integer':I, 'integer':I) :-
H #\= 0,
integer_value('integer':_:[H|T], I),
brachylog_equal('integer':0, [H|T], [H|T]).
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~33~~ ~~30~~ 29 bytes
```
f(n){n=n%100%11?9/n:f(n/10);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOs82T9XQwEDV0NDeUj/PCiimb2igaV37PzcxM09Dk6uaizMtv0gjM69EIU/BVsHQGkjZKAB1GABZ2tqaXJycIHMU1NQUCoqAqtI0lFRLY/KUdBTyNK25av8DAA "C (gcc) – Try It Online")
[Answer]
# [COBOL](https://en.wikipedia.org/wiki/COBOL), 139 BYTES
I feel like COBOL doesn't get any love in code golfing (probably because there is no way it could win) but here goes:
```
IF A = ALL '1' OR ALL '2' OR ALL '3' OR ALL '4' OR ALL '5' OR
ALL '6' OR ALL '7' OR ALL '8' OR ALL '9' DISPLAY "TRUE" ELSE
DISPLAY "FALSE".
```
A is defined as a PIC 9(4).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte
```
Ë
```
Checks if all digits are equal
[Try it online!](https://tio.run/##MzBNTDJM/f//cPf//yYmJgA "05AB1E – Try It Online")
[Answer]
# Python 3, 25, 24 19 bytes.
```
len({*input()})>1>t
```
A stdin => error code variant.
Returns error code 0 if it's a repdigit - or an error on failure.
Thanks to Dennis for helping me in the comments.
[Answer]
# [Haskell](https://www.haskell.org/), 15 bytes
```
all=<<(==).head
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P802MSfH1sZGw9ZWUy8jNTHlf25iZp6CrUJBUWZeiYKKQm5igUKaQrSSoZKOgpIhmDQ2NgZzjCBiRmAxICf2PwA "Haskell – Try It Online") Takes string input.
Equivalent to `\s->all(==head s)s`. Narrowly beats out alternatives:
```
f s=all(==s!!0)s
f s=s==(s!!0<$s)
f(h:t)=all(==h)t
f(h:t)=(h<$t)==t
f s=(s<*s)==(s*>s)
f(h:t)=h:t==t++[h]
```
[Answer]
## Mathematica, 27 bytes
```
AtomQ@Log10[9#/#~Mod~10+1]&
```
It doesn't beat `Equal@@IntegerDigits@#&`, but it beats the other arithmetic-based Mathematica solution.
Repdigits are of the form **n = d (10m-1) / 9** where **m** is the number of digits and **d** is the repeated digit. We can recover **d** from **n** by taking it modulo 10 (because if it's a rep digit, it's last digit will be **d**). So we can just rearrange this as **m = log10(9 n / (n % 10) + 1)** and check whether **m** is an integer.
[Answer]
# [Slashalash](https://esolangs.org/wiki/Slashalash), 110 bytes
```
/11/1//22/2//33/3//44/4//55/5//66/6//77/7//88/8//99/9//1/.//2/.//3/.//4/.//5/.//6/.//7/.//8/.//9/.//T..///.//T
```
[Try it online!](https://tio.run/##HcuxDYAwDAXRjTglThxnDxagQKKgy/4y@TRP19x6r/XcK5NSKFArFcwwaI0GvdPBHYcxGBBBwJxM9nLsSZhoogsXQ4SY4jw2f2R@ "/// – Try It Online")
The /// language doesn't have any concept of truthy and falsey, so this outputs "T" if the input is a repdigit, and does not output any characters if the input is not a repdigit.
[Answer]
## C (gcc), 41 bytes
```
f(char*s){s=!s[strspn(s,s+strlen(s)-1)];}
```
This is a function that takes input as a string and returns `1` if it is a repdigit and `0` otherwise.
It does this by making use of the `strspn` function, which takes two strings and returns the length of the longest prefix of the first string consisting of only characters from the second string. Here, the first string is the input, and the second string is the last digit of the input, obtained by passing a pointer to the last character of the input string.
Iff the input is a repdigit, then the result of the call to `strspn` will be `strlen(s)`. Then, indexing into `s` will return a null byte if this is the case (`str[strlen(str)]` is always `\0`) or the first digit that doesn't match the last digit otherwise. Negating this with `!` results in whether `s` represents a repdigit.
[Try it online!](https://tio.run/##TYzBDoIwEETvfMVKYrILJSkHT8iXqIdarTaBQrp4Inx7XQgmzmUmmTdjq5e1KTm0bxMLppnbA194ijwGZMWlxO4pkaqabs2SeuMDEswZiNYRFPePgxZ603WDxRM1W@WGCOjDBF463YidodZaUln6334Vj1Ewh/KiID8@cgV@/1jlHeBWEsFOCnQNf9gC2ZK@ "C (gcc) – Try It Online")
Thanks to @Dennis for indirectly reminding me of the assign-instead-of-return trick via his [insanely impressive answer](https://codegolf.stackexchange.com/a/125150/3808), saving 4 bytes!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~2~~ 1 byte
```
E
```
[Try it online!](https://tio.run/##AVsApP9qZWxsef//Rf/It@G5vuKCrCDDh8OQZiBZIOG4t@KAnCBHZW5lcmF0ZSBbIjEiLCAuLi4sICIxMDAwIl0sIGZpbHRlciBieSB0aGUgY29kZSwgZGlzcGxheS7/ "Jelly – Try It Online")
[Answer]
## PHP, ~~25~~ ~~28~~ 25
```
<?=!chop($argn,$argn[0]);
```
remove all chars from the right that are equal to the first and print `1` if all chars were removed.
[Answer]
## R, 31 bytes
```
function(x)grepl("^(.)\\1*$",x)
```
This functions works with string inputs and uses a regular expression to determine whether the input is a repdigit.
### Example
```
> f <- function(x)grepl("^(.)\\1*$",x)
> x <- c("1", "2", "11", "12", "100", "121", "333")
> f(x)
[1] TRUE TRUE TRUE FALSE FALSE FALSE TRUE
```
[Answer]
## Regex (ECMAScript), 31 bytes
```
^(x{0,9})((x+)\3{8}(?=\3$)\1)*$
```
[Try it online!](https://tio.run/##Tc3NTsJAFEDhV8GGhHspHVowRqkDKxdsWOhSNJmUy/TqMNPMjFD5efaKCxO351ucD7VXofLcxCw0vCG/c/aTvjsvLR16z6Sf2gbgKOfjYfcO7SkfPVwQoE1xPT3dX2Ah19M@rgsc9rvh@Igiupfo2WpAEQxXBHej7BaxPNRsCMBIT2pj2BIg3kj7ZQyetDQiNIYjDLIBlrwFsFILQ1bHGueT85nDSq2AZaN8oKWNoF/zN8Q/oP9g58WimP0yxtq7Q7K0e2V40/PKapr1ktSUW@eh5EdJJacpXodJmwhPDakIjGKnYlWDR6ycDc6QME5fe3np8mwyzfMf)
Takes input in unary, as usual for math regexes (note that the problem is trivial with decimal input: just `^(.)\1*$`).
Explanation:
```
^(x{0,9}) # \1 = candidate digit, N -= \1
( # Loop the following:
(x+)\3{8}(?=\3$) # N /= 10 (fails and backtracks if N isn’t a multiple of 10)
\1 # N -= \1
)* $ # End loop, assert N = 0
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 11 bytes
```
@(s)s==s(1)
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo1iz2Na2WMNQ83@ahrqhuiYXkDIBAgjLFCpiaGQMROqa/wE "Octave – Try It Online")
Takes the input as a string.
It checks all characters for equality with the first characters. If all are equal, the result will be a vector with only `1` (true in Octave), otherwise there will be at least one `0` (false in Octave).
Here's a [proof](https://tio.run/##y08uSSxL/f8/M00h2lABCGN1UjKLCzTUoTyFzGKFkqLSkoxKdU2d1JziVAW4tAFUOi0xpxgsm5fCBTHGAMUYA5KN@f8fAA).
[Answer]
# grep, 17 bytes
```
grep -xP '(.)\1*'
```
Matches any string that's a repetition of its first character.
[Answer]
# APL, 5 bytes
*2 bytes saved thanks to @KritixiLithos*
```
⍕≡1⌽⍕
```
[Try it online!](http://tryapl.org/?a=f%25u2190%25u2355%25u22611%25u233D%25u2355%20%25u22C4%20f%20445%20%25u22C4%20f%20444%20%25u22C4%20f%20%27445%27%20%25u22C4%20f%20%27444%27&run)
[Answer]
# C#, 42 33 28 bytes
```
i=>i.Replace(i[0]+"","")==""
```
`i` has to be a string.
Shaved down a lot thanks to @LethalCoder
[Answer]
# [Braingolf](https://github.com/gunnerwolf/braingolf), 6 bytes
```
iul1-n
```
[Try it online!](https://tio.run/##SypKzMxLz89J@/8/szTHUDfv/38TExNTAA "Braingolf – Try It Online")
Unfortunately, Braingolf's implicit input from commandline args can't accept an all-digits input as a string, it will always cast it to a number, so instead the solution is to pass it via STDIN, which adds 1 byte for reading STDIN (`i`)
## Explanation:
```
iul1-n
i Read from STDIN as string, push each codepoint to stack
u Remove duplicates from stack
l Push length of stack
1- Subtract 1
n Boolean negate, replace each item on stack with 1 if it is a python falsey value
replace each item on stack with 0 if it is a python truthy value
Implicit output of last item on stack
```
After `u`, the length of the stack equals the number of unique characters in the input, subtracting 1 means it will be `0` if and only if there is exactly 1 unique character in the input, `0` is the only falsey number in Python, so `n` will replace `0` with `1`, and everything else with `0`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 bytes
```
¥çUg
```
[Try it online!](https://tio.run/##y0osKPn//9DSw8tD0///VzIxMVH6DwA "Japt – Try It Online")
[Answer]
## JavaScript (ES6), ~~23~~ 21 bytes
*Saved 2 bytes thanks to Neil*
Takes input as either an integer or a string. Returns a boolean.
```
n=>/^(.)\1*$/.test(n)
```
### Demo
```
let f =
n=>/^(.)\1*$/.test(n)
console.log(f(444))
console.log(f(12))
```
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), 4 bytes
```
Ul2<
```
[Try it online!](https://tio.run/##y8/I/f8/NMfI5v9/ExNjAA "Ohm – Try It Online")
### Explanation
```
Ul2<
U # Push uniquified input
l # Length
2< # Is it smaller than 2?
```
[Answer]
# Java, ~~38~~ ~~33~~ 23 bytes
```
n->n.matches("(.)\\1*")
```
`n` is a `String`, naturally.
Note that there is no need for `^...$` in the regex since it's automatically used for exact matching (such as the `match` method), compared to finding in the string.
[Try it!](http://ideone.com/KxyRJ9)
## Saves
* -5 bytes: used `String` since "You may take and use input as a string with impunity."
* -10 bytes: regex is apparently a good fit.
[Answer]
# Java, 21 bytes:
```
l->l.toSet().size()<2
```
`l` is a `MutableList<Character>` from eclipse collections.
[Answer]
# [Kotlin](https://kotlinlang.org), ~~28~~ 19 bytes
```
{it.toSet().size<2}
```
[Try it online!](https://tio.run/##JYyxDoIwFEV3vuKGqW@QWMcGMDi78QVNbEljeTWlmCjh22vVs95zzz0k7zg/tYdVEGOKjifCocclBG80o8ubS00Ko0mCmsW9TXvas10Zs3YsdJwWhSFG/Wr/756wVSh8o7zO6BCNvl0dG0E4K9TH@rc/ip2EFcUhqvYspfwA "Kotlin – Try It Online")
Takes input as a `String` because
>
> You may take and use input as a string representation in base 10 with impunity.
>
>
>
## Explanation
```
{
it.toSet() // create a Set (collection with only unique entries)
// out of the characters of this string
.size < 2 // not a repdigit if the set only has one entry
}
```
If you don't like the fact it takes a `String`, you can have one that takes an `Int` for **24 bytes**.
```
{(""+it).toSet().size<2}
```
[Answer]
# PHP, 30 bytes
```
<?=($a=$argn).$a[0]==$a[0].$a;
```
[Answer]
# [Neim](https://github.com/okx-code/Neim), 1 byte
```
ùêê
```
Simply checks that all elements are equal.
Without builtin, 2 bytes:
```
ùêÆùê•
```
Explanation:
```
ùêÆ Calculate unique digits
ùê• Get the length
```
This works because only `1` is considered truthy in Neim, and everything else is falsy.
Alternatively, for 4 bytes:
```
ùêÆù꣌ºùïÉ
```
Explanation:
```
ùêÆ Calculate unique digits
ùê£ Join list into an integer
ùïÉ Check that is is less than
μ Ten.
```
[Try it!](http://178.62.56.56:80/neim?code=%F0%9D%90%90&input=12)
[Answer]
# C, 38 bytes
```
f(char*s){return*s^s[1]?!s[1]:f(s+1);}
```
Recursively walks a string. If the first two characters differ (`*s^s[1]`) then we succeed only if we're at the end of the string (`!s[1]`) otherwise we repeat the test at the next position (`f(s+1)`).
## Test program
```
#include <stdio.h>
int main(int argc, char **argv)
{
while (*++argv)
printf("%s: %s\n", *argv, f(*argv)?"yes":"no");
}
```
[Answer]
# R, 25 bytes
```
grepl("^(.)\\1*$",scan())
```
[Try it online](https://tio.run/##K/r/P70otSBHQylOQ08zJsZQS0VJpzg5MU9DU/O/paUllwmXhSGXpYW5mfF/AA)
Best non-regex solution I could come up with was 36 bytes:
```
is.na(unique(el(strsplit(x,"")))[2])
```
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 15 bytes
```
uOn@ii?-?;.$@<_
```
[Try it online!](https://tio.run/##Sy5Nyqz4/7/UP88hM9Ne195aT8XBJv7/f1MQAAA "Cubix – Try It Online")
```
u O
n @
i i ? - ? ; . $
@ < _ . . . . .
. .
. .
```
[Watch It Run](https://ethproductions.github.io/cubix/?code=ICAgIHUgTwogICAgbiBACmkgaSA/IC0gPyA7IC4gJApAIDwgXyAuIC4gLiAuIC4KICAgIC4gLgogICAgLiAuCg==&input=MjIzMjI=&speed=20)
Outputs 1 for truthy and nothing for falsey
Very simply read reads in the input one character at a time. It takes the current character away from the previous. If a non zero result then it halts immediately. Otherwise it continues inputting and comparing until the EOI. On EOI (-1), negate and exit
[Answer]
# QBasic 4.5, 55 bytes
```
INPUT a
FOR x=1TO LEN(STR$(a))
c=c*10+1
NEXT
?a MOD c=0
```
I've mathed it! The FOR-loop checks the number of digits in the input, then creates `c`, which is a series of 1's of length equal to the input. A number then is repdigit if it modulo the one-string == 0.
[Try it online!](https://repl.it/IcSt/0) Note that the online interpreter is a bit quirky and I had to write out a couple of statements that the DOS-based QBasic IDE would expand automatically.
] |
[Question]
[
Your task is simple: output the letter `x` a random number of times. Every possible length of `x`s must have a non-zero probability of being output.
Of course, there must be some lengths whose probabilities tend to \$ 0 \$, in order for the total probabilities to sum to \$ 1 \$, but all must still be theoretically possible.
* You may choose whether to include the empty string as a possible output
* You may have any consistent separator between the `x`s, and you may output the separator more than once. The separator may not contain the unary character
* You may use any other consistent single character instead of `x`
* Per standard rules, [your program must always halt](https://codegolf.meta.stackexchange.com/a/4785) in finite time. (Terminating "with probability 1" [is allowed](https://codegolf.meta.stackexchange.com/q/17122), though)
* You can assume your language's random number generator is perfectly random. If it is supposedly continuous, you may assume it has infinite precision.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 3 bytes
```
x7n
```
Terminates on an error once x sends the IP left.
[Try it online!](https://tio.run/##S8sszvj/v8I87/9/AA "><> – Try It Online")
~~4 bytes:
```
x7
n
```
[Try it online!](https://tio.run/##S8sszvj/v8KcK@//fwA "><> – Try It Online")
This will terminate with an error when `n` has been executed more times than `7`, which has probability 1 of eventually occurring, thought there is no upper limit on how many times `7` will be executed first.~~
[Answer]
# MATLAB, ~~28~~ 25 bytes
```
while rand<.5 disp(1),end
```
Outputs "1" a random number of times, with newline in between. Each length l of has half the probability of length l-1.
Thanks @Luis Mendo for the 3 bytes!
[Answer]
# [Vyxal 2.4.1](https://github.com/Vyxal/Vyxal), 6 bytes
```
{×₴₀℅|
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%7B%C3%97%E2%82%B4%E2%82%80%E2%84%85%7C&inputs=&header=&footer=)
We use v2.4.1 because it seems in 2.6 and later there's no way to get a random bit in two bytes.
```
{ # Forever...
×₴ # Print an asterisk
| # While...
₀℅ # A random bit is nonzero
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 43 bytes
```
setrand(getwalltime)
while(random,print(1))
```
(Don't) [Try it online!](https://tio.run/##K0gsytRNL/j/vzi1pCgxL0UjPbWkPDEnpyQzN1WTqzwjMydVAySen6tTUJSZV6JhqKn5/z8A "Pari/GP – Try It Online") This version is very likely to time out on TIO; here's a slightly longer version that produces nicer results: [Try it online!](https://tio.run/##K0gsytRNL/j/vzi1pCgxL0UjPbWkPDEnpyQzN1WTqzwjMydVAySen6tqqVNQlJlXomGoqfn/PwA "Pari/GP – Try It Online")
### Explanation
```
setrand(getwalltime)
```
Seed the random number generator with `getwalltime`, which is "time in ms since UNIX Epoch."
```
while(random,print(1))
```
While a random integer in the range \$[0,2^{31})\$ is not equal to zero, print `1` with a trailing newline.
[Answer]
# [R](https://www.r-project.org/), 20 bytes
```
while(rexp(1))cat(1)
```
[Try it online!](https://tio.run/##K/r/vzwjMydVoyi1okDDUFMzObEESP3/DwA "R – Try It Online")
3 bytes longer than [Giuseppe's R answer](https://codegolf.stackexchange.com/a/243531/95126), but can output unary values greater than 2147483647.
In fact, it will nearly *always* output unary values that are significantly greater than 2147483647, since the chance of stopping after any outputted `1` character is about `1e-324` (the lower limit of [R](https://www.r-project.org/)'s double-precision numeric type, below which values are truncated to zero).
This will also nearly always exceed the output limit on TIO, so [here](https://tio.run/##ZY/BTsQwDETv/YqR9rCNVCoCnCr1W1BIXGopJFXibhd@viSrpRJwsuOM53nSfoKjiQPBxw1LIsuZY8CF0q3GCedE1@WMaQ1Wyqg5oWVHQdgaD4nIYoIzyf0VdnhbBRvLjBj8J3QhWf4oS4s3lqr1weuKa464GL9ShqecIbMJeOw1TCKkuAZHruK@KMUOHLKQcdXk35Kmh@enFzU0Tcn0ejDGn8Pa0nSO31nyqNUxvXZ936sbqSru77tQNTXc@MuwLcklD0P9Ufs2s6e29q1WyhopZd@/AQ) is a link using a modified version of the `rexp` function with only 1 decimal place of precision.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~4~~ 3 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
⌂v▲
```
Pushes `*` with a probability of \$\frac{4\text{,}294\text{,}967\text{,}294}{4\text{,}294\text{,}967\text{,}295}\$ (99.999999999767%) each iteration, and won't include the empty output (so will always output at least one `*`).
*Don't try it online.*
**Previous 4 [byter](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py):**
```
⌂v¶▼
```
Pushes `*` with a probability of \$\frac{837\text{,}973\text{,}946}{858\text{,}993\text{,}459}\$ (~97.55%) each iteration, and won't include the empty output (so will always output at least one `*`).
[Try it online.](https://tio.run/##y00syUjPz0n7//9RT1PZoW2Ppu35/x8A)
**Explanation:**
```
▲ # Do while falsey with pop:
⌂ # Push character '*'
v # Push a random integer in the range [-2³¹, 2³¹)
# (only 0 is a falsey integer in MathGolf)
# (after which the entire joined stack is output implicitly as result)
```
```
▼ # Do while truthy with pop:
⌂ # Push character '*'
v # Push a random integer in the range [-2³¹, 2³¹)
¶ # Pop and check if this integer is a (positive) prime number
# (after which the entire joined stack is output implicitly as result)
```
The mentioned probability is basically the amount of non-prime numbers within the range \$[-2^{31},2^{31})\$ (which is \$4\text{,}189\text{,}869\text{,}730\$ [according to WolframAlpha](https://www.wolframalpha.com/input?i=2%5E31+%2B+2%5E31-1+-+%28count+primes+less+than+2%5E31%29)) as numerator and total amount of integers within the range \$[-2^{31},2^{31})\$ (basically \$2^{32}-1=4\text{,}294\text{,}967\text{,}295\$) as denominator (and then simplified by dividing both by their greatest common divisor \$5\$).
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 4 bytes
```
1X/r
```
Outputs one or more `1`s (usually not very many of them). [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZLDCP0iyBMqAhMBgA)
### Explanation
```
r Random number in [0, 1)
/ Invert
1X Repeat 1 that many times
```
Theoretically, I think it's possible for this to output nothing if `r` returns exactly `0`, but that's within the rules anyway.
[Answer]
# [Haskell](https://www.haskell.org/), 56 bytes
```
import System.Random
main=print 1>>randomIO>>=([main]!!)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRCG4srgkNVcvKDEvJT@XKzcxM8@2oCgzr0TB0M6uCCzo6W9nZ6sRDZKKVVTU/P8fAA "Haskell – Try It Online")
Random improvements applied to [AZTECCO's answer](https://codegolf.stackexchange.com/a/243550/78410). Halts by non-recoverable error, so it needs to be a full program. Prints at least once, but has \$\frac{1}{2^{64}}\$ chance of continuing to print. (The return type of `randomIO` is inferred to be `Int`, which is a signed 64-bit integer in TIO's environment.)
# [Haskell](https://www.haskell.org/), 59 bytes
```
import System.Random
f=do print 1;n<-randomIO;mapM_ id[f|n]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRCG4srgkNVcvKDEvJT@XK802JV@hoCgzr0TB0DrPRrcILOzpb52bWOAbr5CZEp1Wkxf7PzcxM8827T8A "Haskell – Try It Online")
A function that terminates gracefully and has 1/2 chance of continuing. `[f|n]` becomes `[f]` or `[]` with 1/2 chance each, and `mapM_ id` (one byte shorter than `sequence_`) runs all monads in the list sequentially. Deleting `_` results in a type inference error.
[Answer]
# [Thue](https://esolangs.org/wiki/Thue), 20 bytes
```
x::=xx
x::=~x
::=
x
```
[Try it online!](https://tio.run/##K8koTf3/v8LKyraiggtE1VVwAUmuCq7//wE "Thue – Try It Online") (I'm not sure why the final blank line is necessary, but the program doesn't output anything if I delete it.)
### Explanation
Thue starts with an initial string and executes rewriting rules nondeterministically until it cannot execute any more, at which point it halts. This program consists of two rules:
```
x::=xx
```
Replace an `x` in the string with `xx`.
```
x::=~x
```
Delete an `x` from the string and output `x`.
The program's starting string is:
```
x
```
Thus, at each stage of execution, the string consists of one or more `x`s; it can either get longer by one `x`, or get shorter by one `x` and output an `x`. Once all the `x`s have been output, the program halts. This occurs with probability 1, although in practice sometimes the interpreter segfaults.
[Answer]
# [Random Brainfuck](https://github.com/TryItOnline/brainfuck), ~~7~~ 6 bytes
*-1 byte thanks to [je je](https://codegolf.stackexchange.com/users/103412/je-je)'s observation that Null bytes are accebtale as output.*
```
+[>.?]
```
[Try it online!](https://tio.run/##K0rMS8nP1U0qSszMSytNzv7/XzvaTs8@9v9/AA "Random Brainfuck – Try It Online")
Outputs at least 1 `0x01` character, and terminates each iteration with a 1/256 chance. `?` sets the current cell to a random byte, and this will only terminate when that byte is 0.
## Detailed Explanation
```
+ set first cell to 1
[ while the current cell is non-zero:
> move right one cell
. output it (0x00)
? set current cell to a random byte from 0 to 255
] end while
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 29 bytes by noodle man
```
_=>''.padEnd(1/Math.random())
```
[Try it online!](https://tio.run/##BcExDoAgDADA3Y/Yxog4I26OvsE0AorB1iDx@3h30UfvnuNTehbna7B1s3Pbqofcwg7GYaVyqkzs5AbEapogGaLVJk6j1qbrIu7CrySvkhwQAFXyfJQT6w8 "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 30 bytes
```
f=_=>Math.random()>.5?'':1+f()
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbe1s43sSRDrygxLyU/V0PTTs/UXl3dylA7TUPzvzVXWn6RRqatgXWmjaGBgbW2dqZmcn5ecX5Oql5OfroGUI3mfwA "JavaScript (Node.js) – Try It Online")
Simple
[Answer]
# [R](https://www.r-project.org/), ~~19~~ 17 bytes
```
strrep(1,rexp(1))
```
[Try it online!](https://tio.run/##K/r/v7ikqCi1QMNQpyi1Akhpav7/DwA "R – Try It Online")
Samples from an \$Exp(1)\$ distribution to determine the length. This allows any positive real number to be generated, which `strrep` truncates, though most of them will be rather small.
[Answer]
# [Factor](https://factorcode.org/) + `random.c`, ~~26~~ ~~25~~ 21 bytes
```
[ 1 . rand 9 > ] loop
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqVQUJRaUlJZUJSZV6JQlJiXkp@rl6yQm1iSoZCdWpSXmqNg/T9awVBBDyypYKlgpxCrkJOfX/D/PwA "Factor – Try It Online")
This uses similar logic as flipping a coin until it lands on tails. Only you're using a severely weighted coin, so you usually get heads, leading to fairly long runs. `rand` is C's `rand()` function, returning an integer between 0 and 2147483647 (probably, though it doesn't matter). Each iteration of the loop, print `1` followed by a newline. If the output of `rand` is greater than 9, perform another iteration; otherwise, end the program.
[Answer]
# Pure [Bash](https://www.gnu.org/software/bash/) (no external utilities), 30 26
```
for((;RANDOM;));{ echo x;}
```
[Try it online!](https://tio.run/##S0oszvhf/T8tv0hDwzrI0c/F39daU9O6WiE1OSNfocK69n9tTXnyfwA "Bash – Try It Online")
[Answer]
# Python 3, ~~62~~ ~~60~~ ~~59~~ ~~45~~ ~~43~~ 41 bytes
```
import os
while os.urandom(1)[0]:print(1)
```
[Try online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3NTNzC_KLShTyi7nKMzJzUoEMvdKixLyU_FwNQ81og1irgqLMvBIgG6IBqg-mHwA)
Thanks to @pxeger, @mvirts, @MarcMush and @loopywalt.
[Answer]
# [Python 3](https://docs.python.org/3/), 50 bytes
```
lambda:'x'*int(1/(1-random()))
from random import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3jXISc5NSEq3UK9S1MvNKNAz1NQx1ixLzUvJzNTQ1NbnSivJzFSB8hczcgvyiEi2oToW0_CKFTIXMPJB0eqqGoammFZeCQkERyJg0oGaIugULIDQA)
*Thanks to users `pxeger` and `DominicVanEssen` for their clarifications.*
Outputs the character `x` a random number of times. Random sequences of `x`s are separated by the newline character.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
2ȮX$’¿
```
A niladic Link that prints `2`s as a side-effect (it also yields `1`). Only prints strictly positive numbers (as allowed in the specification).
**[Try it online!](https://tio.run/##y0rNyan8/9/oxLoIlUcNMw/t/39oUdr//wA "Jelly – Try It Online")** (The footer suppresses the printing of `1` that a full program would otherwise do implicitly.)
Or [see forty at once](https://tio.run/##ASAA3/9qZWxsef//MsiuWCTigJnCv//CouG4nzHhuYQp//80MA) (plus a single trailing newline).
### How?
```
2ȮX$Ḋ¿ - Link: no arguments
2 - two - let's call this V
¿ - while...
’ - ...condition: decrement V (V=2 -> 1 (truthy); V=1 -> 0 (falsey))
$ - ...do: last two links as a monad - f(V):
Ȯ - print V, yield V
X - random integer in [1,V] -> next V = 1 or 2 (probability = 0.5)
```
---
Previous @ 7 bytes:
```
2XȮß$Ị¡
```
A niladic Link that prints `1`s as a side-effect (it also yields `2`). This one includes the empty output (i.e. zero).
[Try it online!](https://tio.run/##ARkA5v9qZWxsef//MljIrsOfJOG7isKh/8KiZv// "Jelly – Try It Online") (The footer suppresses the printing of `2` that a full program would otherwise do implicitly.)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
`1rEk
```
Outputs `1` separated by newlines `n` times, where `n` is a (shifted) geometric random variable with parameter `1/2`. This means `n` is `1,2,3...` with probability `1/2`,`1/4`, `1/8` ... The program halts with probability `1`.
[**Try it online!**](https://tio.run/##y00syfn/P8GwyDX7/38A "MATL – Try It Online")
```
` % Do...while
1 % Push 1
r % Push uniform random number in the interval (0,1)
E % Multiply by 2
k % Round down. This gives 0 or 1 with probability 1/2
% End (implicit). The top of the stack is used as loop condition
% If 1 a new iteration is executed, otherwise the loop is exited
% Display stack (implicit)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[?₄Ω#
```
Outputs `0`s with a probability of \$\frac{3}{4}\$ each time. Could be a probability of \$\frac{2}{3}\$ or \$\frac{1}{2}\$ for the same byte-count by replacing the `₄` with `т` or `T` respectively.
[Try it online.](https://tio.run/##yy9OTMpM/f8/2v5RU8u5lcr//wMA)
**Explanation:**
```
[ # Loop indefinitely:
? # Print an empty string without newline in the first iteration,
# or the 0 that was previously on the stack in other iterations
₄ # Push 1000 (or 100 for `т` or 10 for `T`)
Ω # Pop and push a random digit from this integer
# # If it's 1: stop the infinite loop
```
[Answer]
# [Cascade](https://github.com/GuyJoKing/Cascade), 6 bytes
```
$/
.x/
```
[Try it online!](https://tio.run/##S04sTk5MSf3/X0WfS69C//9/AA "Cascade – Try It Online")
# [Cascade](https://github.com/GuyJoKing/Cascade), 6 bytes
```
\$
.|x
```
[Try it online!](https://tio.run/##S04sTk5MSf3/P0aFS6@m4v9/AA "Cascade – Try It Online")
*Likely* optimal, considering one row has to have width at least 3 for `$` to produce distinct random outcomes.
Both programs consist of two random branches from `$`, one of which returns the codepoint of `x`, and the other of which prints (the character value of) and returns the return value of (a fresh evaluation of) the `$`.
[Answer]
# TI-Basic (TI-84), ~~11~~ 10 [bytes](https://codegolf.meta.stackexchange.com/a/4764/98541)
```
Repeat checkTmr(startTmr
Disp 1
End
```
the program can only end when the check `checkTmr(startTmr` happens between two seconds (`checkTmr(startTmr) = 1` instead of `0`). This way, any number of ones is possible (the shortest I got was 3 ones, the longest printed during approx 10 seconds)
`Repeat` always executes the loop the first time, so the empty string is not included (`repeat until` or `do while not`)
For calculators without time (TI-83), replace `checkTmr(startTmr` with `rand>.9` but it's not true randomness (same output on each reset of the calculator)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 4 bytes
```
W‽φx
```
[Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUEjKDEvJT9Xw9DAwEBTUyGgKDOvREOpQknT@v///7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Prints an average of 999 `x`s. (Other average counts from `1` to `9` are also possible by substituting an appropriate character for `φ`.)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 29 bytes
```
f(){putchar(63)&rand()&&f();}
```
[Try it online!](https://tio.run/##FYyxDoQgEER7vmJjQXZjTIgmNtz9iQ1B0S1Eg1x14dtxKefNm/HD7n2tAel//7I/XMJ5Ip1cXJG0Fm5L5ZjhdBxBLPW0DjDzuaEhsipcCbAp/DWWP6Oxfc8iQhsrkNsHuyV2Eooq9QU "C (gcc) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~10~~ 9 bytes
```
1#~>.@%?0
```
-1 byte by using Reflex `~` instead of Bond `&1`
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZXr7PQcVO0N/mtycaUmZ@QrpP0HAA "J – Try It Online")
[Answer]
## Batch, 28 bytes
```
@if %random% gtr 9 echo x&%0
```
Outputs an average of about 3276 `x`s, assuming `CMD.EXE` doesn't stack overflow first.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
9w9ṙ9|↰
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/37Lc8uHOmZY1j9o2/P//HwA "Brachylog – Try It Online")
### Explanation
```
9w Write 9
9ṙ Pick a random integer in 0..9
9 If it is 9, terminate
|↰ Else, recurse
```
[Answer]
# [Alchemist](https://github.com/bforte/Alchemist), 14 bytes
```
_->Out__+_
_->
```
[Try it online!](https://tio.run/##S8xJzkjNzSwu@f8/XtfOv7QkPl47ngvI/P8fAA "Alchemist – Try It Online")
Breaks the loop with probability \$\frac12\$ at each iteration.
### Explanation
The program starts with a single `_` atom. Since both instructions consume only a `_` atom, they are both satisfied and one is chosen randomly. The first outputs the number of `_` atoms remaining (0) and produces another `_` atom to continue the loop. The second just consumes the atom, ending the loop.
[Answer]
# [Julia 1.0](http://julialang.org/), 22 bytes
```
!_=.1<rand()&&!show(1)
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/XzHeVs/QpigxL0VDU01NsTgjv1zDUPN/Wn6RQqZCZp6CoZWhgQGXYl5@SUZmXjpXQVFmXklOnoYmV2peyn8A "Julia 1.0 – Try It Online")
[Answer]
# [Java](https://en.wikipedia.org/wiki/Java_(programming_language)), ~~58~~ ~~45~~ 44 bytes
```
String f(){return.5<Math.random()?"":1+f();}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kK7EsccHN2ILSpJzMZIXknMTiYgXfxMy8aqhIcUliCZAqy89MUcgFimsElxRl5qVHxyZqVnMFVxaXpObq5ZeW6BUARUty8jTSNDQ1rWu5UHQvLS1J07W4qQPRqgBUUl2UWlJalKdnauObWJKhV5SYl5Kfq6Fpr6RkZagNlLeuhehZCKUXLIDQAA)
-1 thanks to @Kevin Cruijssen
Same strategy as the [NodeJS](https://codegolf.stackexchange.com/a/243526/107299) answer. Previous answer did not fit challenge spec, this version turned out to be shorter as well.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~28~~ 24 bytes
```
Dot@@Table[x,1/Random[]]
```
Thanks to att for –4!
[Try it online!](https://tio.run/##y00syUjNTSzJTE78X6RgZfvfJb/EwSEkMSknNbpCx1A/KDEvJT83OjYWKBEdUJSZVxJdFKujYGgQ@x8A "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
Your program should take an array as input.
The array:
1. Will always be 1 dimensional
2. Will only contain integers
3. Can be empty
The program should reverse the array, and then add up the elements to the original for example:
**Input:** `[1, 2, 3]`
**Original:** `[1, 2, 3]`
**Reversed:** `[3, 2, 1]`
```
[1, 2, 3]
+ + +
[3, 2, 1]
[1+3, 2+2, 3+1]
```
**Output:** `[4, 4, 4]`
---
**Test Cases:**
```
#In #Out
[8, 92], [100, 100]
[1, 2, 3], [4, 4, 4]
[5, 24, 85, 6], [11, 109, 109, 11]
[], []
[999], [1998]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code (in bytes) wins!
[Answer]
# [Haskell](https://www.haskell.org/), 20 bytes
*5 bytes save by changing to a point free as suggested by nimi*
```
zipWith(+)=<<reverse
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0RFoyqzIDyzJENDW9PWxqYotSy1qDhVM9pQx0jHWMcw9v9/AA "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
+U
```
[Try it online!](https://tio.run/##y0rNyan8/1879P///9GGOkY6JrEA "Jelly – Try It Online")
or
```
+Ṛ
```
[Try it online!](https://tio.run/##y0rNyan8/1/74c5Z////NzTWMdExBAA)
(thanks @Mr. Xcoder for the second program)
### explanation, though it's pretty self-explanatory
```
+U Main link
+ Add, vectorizing,
U the input, reversed
```
```
+Ṛ Main link
+ Add, vectorizing,
Ṛ the input, reversed, without vectorizing (same thing for depth-1 lists)
```
For empty array `[]`, this outputs nothing. That is correct. Jelly's representation of an empty list is just simply nothing. Note that Jelly's representation of a list with a single element is just the element itself. Append `ŒṘ` to the code to see the Python internal representation of the output.
[Answer]
## JavaScript (ES6), 27 bytes
```
a=>[...a].map(e=>e+a.pop())
```
```
f=
a=>[...a].map(e=>e+a.pop())
console.log(f([8, 92])) // [100, 100]
console.log(f([1, 2, 3])) // [4, 4, 4]
console.log(f([5, 24, 85, 6])) // [11, 109, 109, 11]
console.log(f([])) // []
console.log(f([999])) //[1998]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
Â+
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cJP2///RhjoKRjoKxrEA "05AB1E – Try It Online")
[Answer]
# Python 2, 32 bytes
```
lambda l:map(sum,zip(l,l[::-1]))
```
Alternative solution without `zip` (35 bytes):
```
lambda l:map(int.__add__,l,l[::-1])
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIccqN7FAo7g0V6cqs0AjRycn2spK1zBWU/N/QVFmXolCmka0hY6lUawmF5xvqGOkY4wsYKpjZKJjYapjhiyIzLa0tIzV/A8A "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 40 bytes
```
lambda l:[i+j for i,j in zip(l,l[::-1])]
```
[Try it online!](https://tio.run/##NY09DsMgFIN3TuExUV@H0B8FpJyEMqRqUV9EE5SwpJenlAov1mdLdtjja5llcsMt@fF9f4zw2vBhgltWME3gGR8OjSdvtD52trUpPre4YYARyDI9QUlLf@gIknCqeMl4JvTZrzWrrpSywgpRnn4/ZVeXMqw8R7iG2/QF "Python 2 – Try It Online")
The other, shorter Python answer replaces a list comprehension with `map`. Wish I'd thought to do that faster. ;-;
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 bytes
```
mÈ+Ug~Y
```
[Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=bcgrVWd+WQ==&inputs=WzgsIDkyXQ==,WzEsIDIsIDNd,WzUsIDI0LCA4NSwgNl0=,W10=,Wzk5OV0=,WzEsMCwyXQ==&flags=LVE=) with the `-Q` flag to format the output array.
## Explanation
Implicit: `U` = input array
```
mÈ
```
Map the input by the following function...
```
+Ug
```
The value, plus the value in the input array at index...
```
~Y
```
`-(index+1)`, which gets elements from the end of the array.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 25 bytes
```
->a{[*a].map{|i|i+a.pop}}
```
[Try it online!](https://tio.run/##DcdJCgIxEIXhfU5RS4cyaNqhs9CLxCClpO1A1MIJJMnZY8GD7/3Pz/nXhv2xLQ6U3Yy8vhHnEkuck@YH19qu4f2a8FQHuoynFO8hl1QUw@DClxIkr2pzK@zQ4A6XXsk32Ik9gjXiBsGsEXpxKymz1vo/ "Ruby – Try It Online")
[Answer]
# Mathematica, 12 bytes
```
Reverse@#+#&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvs/KLUstag41UFZW1ntf0BRZl6JgkOagkO1hY6lUS0XkoChjpGOMYqIqY6RiY6FqY4ZAXUoHEtLy9r/AA "Mathics – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~33~~ 32 bytes
-1 byte thanks to @xnor
```
lambda l:[i+l.pop()for i in l*1]
```
[Try it online!](https://tio.run/##PYzLCsMgFET3fsUsk/YSiH0QA/kS6yKllV6wKombfL2RFDubw5mBiVv6BC@znR7Zzd/na4YbNZ9dF0NsWhsWMNjDnXqT03tNKyZogRI9EJQ09JOeIAmXqreiV8JQeK9dpVLKCCPE//z4HY8xLuwTbMNt3gE "Python 2 – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes
```
↔;?z+ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HbFGv7Ku2HWyf8/x9tqGOkYxz7PwoA "Brachylog – Try It Online")
[Answer]
# J, 3 bytes
```
+|.
```
Reverse, sum.
[Try it online!](https://tio.run/##y/r/P81WT0G7Ro8rNTkjXyFNwVDBSMEYxrFQsDSCsdXV//8HAA "J – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~61~~ 60 bytes
*-1 byte thanks to [TheLethalCoder](https://codegolf.stackexchange.com/users/38550/thelethalcoder)*
```
a=>a.Reverse().Zip(a,(x,y)=>x+y).ToArray()
```
[Try it online!](https://tio.run/##dZBBS8NAEIXP5lc8etpgkoKoCGkKRfCiXqogWDws20m70O7G3U1sKPntcZMUtVXfZWZ5b79hRthYaEOt4luyBReEp9o62gb7AF6llWqFB6ne0/4tNtxazPp@SHSyjjspUGm5xCOXioVf1neo012pxEQqt3iL0JcpcmQtRzYFT@ZUkbHEwuRVFoxHYLsIddiZO5z7LnnWM2N4zcL2rMOlR/CKGw8tSocMij6GAdjjKsLFZYQbX6/RpBiPMYnjQ3SlyWJNhoJfLF26AZazPhsej8v92bhYs36spx3y4cnKnW61snpDyYuRjpj0u4wwOsE1wb8//Pn9UdI/A3Piy3uqf9oDqQma9hM "C# (.NET Core) – Try It Online")
Byte count also includes:
```
using System.Linq;
```
For explanation - Zip function in LINQ takes two collections and executes given function for all corresponding elements, ie. both first elements together, both second elements etc.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes
```
Ḃ+
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuIIrIiwiIiwiWzEsIDIsIDNdIl0=)
```
Ḃ+
Ḃ # bifurcate, i.e. duplicate and reverse
+ # vectorized addition of two lists
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 7 bytes
```
{_W%.+}
```
[Try it online!](https://tio.run/##S85KzP1fWPe/Oj5cVU@79n9dwv9oQwUjBeNYAA "CJam – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 3 bytes
```
⌽+⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/FR24RHPXu1H3UtAnIUTBWMTBQsTBXMAA "APL (Dyalog Unicode) – Try It Online")
### Explanation
```
⌽ The argument reversed
+ Plus
⊢ The argument
```
[Answer]
# [R](https://www.r-project.org/), ~~17~~ 16 bytes
*-1 byte thanks to djhurio*
```
rev(l<-scan())+l
```
Reads from stdin; returns the vector; `numeric(0)` is the zero-length numeric vector for the empty list.
[Try it online!](https://tio.run/##K/r/vyi1TCPHRrc4OTFPQ1NTO@f/fwA)
[Answer]
# Clojure, ~~20~~ 17 bytes
3 bytes saved thanks to @MattPutnam
```
#(map +(rseq %)%)
```
Seems to be quite competitive with non-golfing languages.
[See it online](https://tio.run/##S87JzyotSv3/X6OgKDOvREEjN7GgjEtBGUQraGsUFacWKqhqqmpyKURHWyhYGsUqRBsqGCkYA2lTBSMTBQtTBTMgG4gsLS1jY7kUNDX//wcA)
[Answer]
# Pyth, 3 bytes
```
+V_
```
[Try it here.](http://pyth.herokuapp.com/?code=%2BV_&input=%5B1%2C+2%2C+3%5D&debug=0)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 26 bytes
```
($a=$args)|%{+$a[--$i]+$_}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0Ml0VYlsSi9WLNGtVpbJTFaV1clM1ZbJb72////pv@NTP5bmP43AwA "PowerShell – Try It Online")
Takes input as command-line arguments.
[Answer]
# C, 49 bytes
```
f(a,n,b)int*a,*b;{for(b=a+n;a<b--;a++)*a=*b+=*a;}
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~40~~ 32 bytes
```
($n=$args)|%{$n[-++$i]+$n[$i-1]}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0Mlz1YlsSi9WLNGtVolL1pXW1slM1YbyFLJ1DWMrf3//7/pfyOT/xam/80A "PowerShell – Try It Online")
Takes input as individual command-line arguments, which is allowed as one of the native list format for PowerShell. Then loops through each element (i.e., a shorter way of looping through the indices), adding the element counting from the back (`-1` indexed) to the current element (`0` indexed, hence the decrement `-1`). Those are left on the pipeline and output is implicit.
Saved 8 bytes thanks to @briantist
[Answer]
# Java 8, ~~61~~ ~~57~~ ~~56~~ 53 bytes
```
a->{for(int l=0,r=a.length;l<r;a[l]=a[--r]+=a[l++]);}
```
-1 byte and bug-fixed thanks to *@Nevay*.
-3 bytes thanks to *@OliverGrégoire*.
(It was a port of (and golfed by ~~4~~ 8 bytes) of [*@jkelm*'s C# answer](https://codegolf.stackexchange.com/a/135447/52210), but now it's a different shorter solution thanks to *@OliverGrégoire*.)
**Explanation:**
[Try it here.](https://tio.run/##tZDBboMwEETv@Yo9grCtloYE5FKpH9BcckQcXOKkpsZGxqSKEN9ODebWa5FsWTsavRlvze4M65ar@vI9iabVxkLtNNJbIcm7MezR0V0lWdfBBxNq2AEIZbm5sorDaR4B7lpcoAqcXpTAQurE0V13OsusqOAECnKYGH4brtrMRpD5EzI5I5Krm/2i8tVQVsgyZwXGpozcK6OoDOk4UY9q@0/pUCtxiWxcoeBsjVC3Jdi3WWvM1V2o4j9eGVKUxSNdLIpUwWII/Xx@dJY3RPeWtI5mpQr814nVnr/aV/9f@DOK0ctm9ATFe5Qm6LBZwmbgLMs2XDp2W0d4jxKED@iIcPovWeNunH4B)
The method modifies the input-array to save bytes, so no need for a return-type.
```
a->{ // Method with integer-array parameter and no return-type
for(int l=0, // Left-integer (starting at 0)
r=a.length; // Right-integer (starting at the length of the input-array)
l<r; // Loop as long as left is smaller than right
a[l]= // Change the number at the current left index to:
a[--r]+=a[l++] // The number at the right index + itself
// (The += adds the number at the left index also to the right index)
// (And the --/++ increases/decreases the indexes by 1,
// until we've reached the middle of the array)
); // End of loop
} // End of method
```
[Answer]
# [K4](https://kx.com/download/) / [K (oK)](https://github.com/JohnEarnest/ok), 5 bytes
**Solution:**
```
x+|x:
```
[Try it online!](https://tio.run/##y9bNz/7/v0K7psLKUMFIwfj/fwA "K (oK) – Try It Online")
**Example:**
```
x+|x:,()
,()
x+|x:8 92
100 100
x+|x:,999
,1998
```
**Explanation:**
Not quite as elegant as the `J` solution, but same kinda thing:
```
x+|x: / the solution
x: / store input as x
| / reverse it
+ / add to
x / x
```
[Answer]
# [Factor](https://factorcode.org/), 18 bytes
```
[ dup reverse v+ ]
```
[Try it online!](https://tio.run/##HYuxCsIwGAb3PsW3CwWrlUYfQFxcxEkcQv3UYprGP2mgSp892g4Hd8PddR06SefT4bjf4kWxNPB897Q1PR60FG2ajw5NZz1aHZ555PR4OGEIg5PGBuyy7IsKqsD4lyUKrGYrUaxRldjMNaGUwpguuPUOwkjxRFzgmkpY7ZwZkHvUhlrSDw "Factor – Try It Online")
## Explanation
```
! { 1 2 3 }
dup ! { 1 2 3 } { 1 2 3 }
reverse ! { 1 2 3 } { 3 2 1 }
v+ ! { 4 4 4 }
```
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 44 39 bytes
```
(load library
(q((p)(map* a p(reverse p
```
-5 bytes thanks to @DLosc
[Try it online!](https://tio.run/##JYm7DYAgFEV7prjl004UAwu4BwYKEtQnGBOmxyDd@TzhLDFkrpXiZR1i2JNNRZDDRjcRD3RYHmHBlPzrU/bgSu1pGCl@miAxd1SQC7TC2rQnY0z9AA "tinylisp – Try It Online")
## Explanation
An anonymous function that maps the `a` function (addition) over pairwise elements in the input and the reverse of the input, forming a new list.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 6 bytes
```
{x+|x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6qu0K6pqOXiSlMwVDBSMFbQV9C1UzABQaCQhYKlEUTE0MAAhIFipgpGJgoWpgpmUAlDoLglBBsCpTU0IeIamkCOpaUlVJWlpQUAsgUUwQ==)
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), 3 bytes
```
DR+
```
[Try it online!](https://tio.run/##y8/I/f/fJUj7//9oQx0FIx0F41gA "Ohm – Try It Online")
[Answer]
# [Actually](https://github.com/Mego/Seriously), 4 bytes
```
;R♀+
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/9866NHMBu3//6MNdRSMdBSMYwE "Actually – Try It Online")
[Answer]
# [anyfix](https://github.com/alexander-liao/anyfix), 3 bytes
```
"U+
```
The version on TryItOnline! is an outdated version of anyfix, which contains a few fatal errors such as not being able to add lists because of typos in the source code. Use the code on GitHub instead.
```
"U+ Program
" Duplicate top of stack
U Reverse top of stack if it is a list (which it should be...)
+ Add, vectorizing for lists
```
] |
[Question]
[
# Background
Some holidays have fixed, easy-to-remember dates, like Oct 31, Dec 25, etc. Some, however, want to be troublesome. They're specified as things like "the first Monday in September" or "the fourth Thursday in November". How am I supposed to know when that is?
All I know is that Thanksgiving is fast approaching, so I need a program to help me figure out when it is. Some people even say that it's *tomorrow*, so your program needs to be as short as possible to make sure I can re-type it in time.
# The Challenge
Create a program or function that, given an up-to-four-digit year (e.g. 2015 or 1984), outputs or returns the date of the United States' Thanksgiving in that year. Thanksgiving is defined as the fourth Thursday of November according to [the Wikipedia page](https://en.wikipedia.org/wiki/Thanksgiving). *(Hint: that page also includes some interesting information on the date pattern.)*
**Input**: a decimal number with a maximum of four digits representing a year in the Common Era (C.E.). Examples: 987, 1984, 2101
**Output**: the date, including month and day, on which Thanksgiving falls, or would fall if it existed, in that year. This may be in any reasonable format; use your best judgment. Use the Gregorian Calendar in all cases, even if it was not in use at the time.
*(Note: Make sure to handle leap years correctly!)*
**Test cases**
Input 1:
```
2015
```
Output 1:
```
Nov 26
```
Input 2:
```
1917
```
Output 2:
```
Nov 22
```
# Scoring
Submissions will be scored in **bytes**. I recommend [this website](http://bytesizematters.com) to keep track of your byte count, though you can use any counter you like.
### Bonuses
**-25%** to your score if you handle B.C.E. dates as negative numbers (e.g. -480 would be the year of the battle of Thermopylae).
Negative test case input:
```
-480
```
Corresponding output:
```
Nov 25
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest score wins!
Edit: I am marking Thomas Kwa's TI-BASIC submission as accepted. Don't let this discourage you from submitting new entries!
## 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=64785,OVERRIDE_USER=45162;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]
# TI-BASIC, 15 bytes \* 0.75 = 11.25
*Tested on my TI-84+ calculator*
```
1129-dayOfWk(Ans+ᴇ4,9,1
```
Thankgiving is November 29, minus the day of the week of September 1st, where 1 is Sunday and 7 is Saturday. This outputs in the format `MMDD`.
Test cases: `2015` -> `1126`, `1917` -> `1122`, `-480` -> `1125` have been verified. TI-BASIC seems to use the Gregorian calendar for all dates.
TI-BASIC doesn't support negative years, but this gets the bonus because we add 10000 to the input. Because the Gregorian calendar has a period of 400 years, this doesn't change the day of the week.
[Answer]
## PHP, ~~65~~ ~~48~~ ~~42~~ ~~41~~ 36 (+2 for `-F`) = 38 bytes
```
<?date(Md,strtotime("4thuXI$argn"));
```
Takes input as the first command line argument. Runs with warnings, which are acceptable by our rules. Prints `NovDD`, where `DD` is the day of Thanksgiving.
No online link because ideone doesn't support command line args and I don't know of an online interpreter that does.
Thanks to Alexander O'Mara for teaching me a new trick, and primo for a significant reduction
[Answer]
## Mathematica, ~~59~~ 38 bytes
```
DayRange[{#,11},{#,12},Thursday][[4]]&
```
[Answer]
# JavaScript (ES6), ~~42~~ ~~40~~ 31 bytes - 25% = 23.25
```
a=>28.11-new Date(a,8).getDay()
```
Since the date "may be in any reasonable format", this function uses `DD.MM`. I wrote a [TeaScript answer](https://codegolf.stackexchange.com/a/64805/45393) with a different technique, but this formula was shorter.
## Explanation
As the months are zero based, `new Date(a,10)` returns a `Date` object representing November 1 of the specified year.
Since `getDay()` returns a number representing the day of week from `0..6` we want to map from
```
Su Mo Tu We Th Fr Sa
0 1 2 3 4 5 6
to to to to to to to
4 3 2 1 0 6 5
```
then add 22. It turns out that `(11 - new Date(a,10).getDay()) % 7` will do the trick. As [@Thomas Kwa](https://codegolf.stackexchange.com/users/39328/thomas-kwa) pointed out, this is the same as `28-new Date(a,8).getDay()` which is 28 minus the day of the week of September 1.
[Answer]
# [Japt](https://github.com/ETHproductions/Japt), ~~43~~ ~~37~~ ~~36~~ ~~35~~ 29 bytes - 25% = 21.75
**Japt** is a shortened version of **Ja**vaScri**pt**.
```
`{28.11-?w D?e(U,8).getDay()}
```
Hahaha, I found a *really* cheaty trick: the interpreter ignores any brackets inside strings (used to insert code) while decompressing them, so we can compress the entire source code to save a byte >:D
The two `?`s should be the Unicode unprintables U+0098 and U+0085, respectively. [Try it online!](http://ethproductions.github.io/japt?v=9b914b60365b0031f09d30c79d98d504131f1328&code=YHsyOC4xMS2adyBEhWUoVSw4KS5nZXREYXkoKX0=&input=MjAxNQ==)
After decompression, the code evaluates to this:
```
"{28.11-new Date(U,8).getDay()}"
```
Which evaluates to:
```
""+(28.11-new Date(U,8).getDay())+""
```
Which gives the proper output.
Uses [intrepidcoder's technique](https://codegolf.stackexchange.com/a/64797/42545), outputting in format `dd.mm`. Properly supports negative years.
Suggestions welcome!
**Edit:** As of Dec 2, you can now use this **11-byte** code (scoring **8.25 points**):
```
28.11-ÐU8 e
```
(I so wish I had implemented this sooner!)
[Answer]
# [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), 44 bytes
I'm calculating with *pure mathemagics*!
Golfed:
```
Ve2*V2-V41m+Vaa*Dv1m-Vv4*1m+7M-baa*/+N
/D1M-
```
Ungolfed (moved the method call to the first line to make it readable):
```
Ve2*V2-V4/D1M-+Vaa*Dv/D1M--Vv4*/D1M-+7M-baa*/+N
V Save the input as a final variable.
e2* Push 28 to the stack.
V Push the input to the stack.
2- Subtract two.
V4/D1M- Get floor(input/4).
+ Add it to the total.
Vaa*Dv/D1M- Get floor(input/100), and save 100 as a temp
variable in the process.
- Subtract it from the total.
Vv4*/D1M- Get floor(input/400).
+ Add it to the total.
7M Modulo by seven.
- Subtract the result from 28.
baa*/+ Add .11
N Output as number.
```
There's probably a better algorithm for this (and this is likely horridly golfed), but for those wondering, my algorithm comes from [here](https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week).
[Try it online!](http://vitsy.tryitonline.net/#code=VmUyKlYyLVY0MW0rVmFhKkR2MW0tVnY0KjFtKzdNLWJhYSovK04KL0QxTS0&input=&args=MjAxNg&debug=on)
~~Do I get bonus points for calculating it and having exactly 42 bytes?~~ Dreams ruined.
Thanks to @Hosch250 for pointing out I was doing it wrong. :D Fixed.
[Answer]
# Python, 38 \* 0.75 = 28.5 bytes
```
lambda x:28.11-(x-2+x/4-x/100+x/400)%7
```
This works with negative years in the manner specified in the question, although it's come to my attention that there is no year 0 in the Gregorian calendar so this behavior is a bit suspect.
[Answer]
# JavaScript (ES6), 43.5
Actual byte count is 58. The bonus of -25% applies => 58 \* 0.75 = **43.5**
```
s=>new Date(s,10,(a=new Date(s,10).getDay())<5?26-a:a+21)
```
Pretty straight ~~and silly~~ way as it could be, without any tricky workarounds or calculations.
De-golf (ES5) + demo:
```
function t(s) {
a = new Date(s, 10).getDay();
alert(new Date(s,10,a<=4?26-a:a+21))
}
t(prompt())
```
Note, that entering year 0-100 produces 1900-2000 year. Though, it looks like 0-100 years give the same date as do 1900-2000, judging from the other answers.
---
Replacing `a+18` with `22`, because it's called only in "else", and "else" occurs only if a is neither greater nor less than 4, i.e. exactly 4.
---
Replacing `a<4?26-a:a>4?a+21:22` with `a<=4?26-a:a+21`
[Answer]
# TeaScript, ~~35~~ ~~33~~ 24 bytes - 25% = 18
```
28.11-new D(x,8).getDay¡
```
This is the same method as [my JavaScript answer](https://codegolf.stackexchange.com/a/64797/45393), which uses [Thomas Kwa's](https://codegolf.stackexchange.com/a/64890/45393) clever formula.
### Alternate Version with Explanation
```
r(22,28)F(#/h/t(new D(x,10,l)))+'-11'
r(22,28) // Range from 22 to 28
F( // filter, keeps elements for which the function returns true.
# // Expands to function(l,i,a,b)
/h/ // RegExp literal, Thursday is the only day with an 'h'.
t( // test, true if date string contains an 'h'.
new D(x,10,l) // Create date object
))+'-11' // Append '-11' for the month.
```
[Answer]
# Jython, 141 155 Bytes
Uses the Java Calendar and Scanner classes with Python syntax.
```
import java.util.Scanner as s;import java.util.Calendar as c
d=c.getInstance();k=s(System.in);d.set(c.YEAR,k.nextInt());d.set(c.DAY_OF_WEEK,c.THURSDAY)
```
**Edit:** Minor syntax issues, added 14 bytes.
Also see my [Brainfuck](https://codegolf.stackexchange.com/a/64806/47629) version.
[Answer]
## Python, ~~83~~ ~~81~~ 78 bytes
```
from datetime import*
lambda a:'Nov '+`((10-datetime(a,11,1).weekday())%7)+22`
```
* **-2 bytes:** added a name to import (thanks @Κριτικσι Λίθος)
* **-1 bytes:** changed to \*import\*\* (thanks @FryAmTheEggman)
* **-2 bytes:** changed to repr to convert the day (thanks @willem)
[Answer]
## Excel, ~~367~~ ~~154~~ 53 - 25% = 39.75 bytes
Assumes the year is held in cell A1, in Date format. Returns the integer number of the day in November on which Thanksgiving is held.
This only accounts for normal leap years. It does not account for the fact that the years, 2100, 2200, 2300 are not leap years.
This is only designed to work for 1621 onwards - i.e. since Thanksgiving began being held. (Although it will certainly work all the way back to 0 A.D.).
```
=IF(MOD(YEAR(A1),4)=0,IF(WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))<6,1127-WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy")))),1134-WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))),IF(WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))<6,1127-WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy")))),1134-WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))))
```
Pretty-printed:
```
=IF(MOD(YEAR(A1),4)=0,
IF(WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))<6,
1127-WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy")))),
1134-WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))),
IF(WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))<6,
1127-WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy")))),
1134-WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))))
```
Gah! Instead of calculating based on the 1st of Jan, then doing lots of leap year calculations to cope with the 29th of Feb, I should have based the calculations on the 1st of Nov. n.b. This now deals correctly with the years 2100, 2200 and 2300, but makes the implementation dependent on your Excel installation's default date format. This version is designed for dd/mm/yyyy:
```
=IF(WEEKDAY(DATEVALUE(("01/11/"&TEXT(C1,"yyyy"))))<6,
1127-WEEKDAY(DATEVALUE(("01/11/"&TEXT(C1,"yyyy")))),
1134-WEEKDAY(DATEVALUE(("01/11/"&TEXT(C1,"yyyy")))))
```
And now that I've done the pfaffing about to get a terse calculation in Smalltalk, backporting it to Excel results in:
```
=DATE(A1,11,MOD(12-WEEKDAY(DATE(9600+A1,11,1)),7)+22)
```
(with the year still in A1, but as an integer). This works even for years 2100, 2200 and 2300, for all dates from 7700BC/E onwards, using Thomas Kwa's date repetition trick.
[Answer]
## PowerShell, ~~67~~ ~~64~~ ~~84~~ ~~72~~ ~~58~~ 45 Bytes
```
param($a)'Nov';28-(date "00$a/9/1").DayOfWeek
```
We take our input integer as `$a`, and immediately output `Nov` and a newline. Then we take `$a` and prepend it with zeroes and September 1st with `00$a/9/1` before generating a new `date` and determining what `DayOfWeek` that is. If September 1st is on a Sunday (`.DayOfWeek` equal to `0`), Thanksgiving is on the 28th. If September 1st is on a Monday (`.DayOfWeek` equal to `1`), Thanksgiving is on the 27th. And so on. Thus, we subtract that day of the week from `28` to output our answer.
Prepending with double-zeroes accounts for single- and double-digit years without interrupting parsing for three- or four-digit years. Doesn't work for negative numbers, as .NET `datetime` doesn't support years less than `0`.
Thanks to [TessellatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler) and [Toby Speight](https://codegolf.stackexchange.com/users/39490/toby-speight) for assistance on this.
[Answer]
# Golfscript, 25 \* 0.75 = 18.75 bytes
```
~.4/.25/.4/2---+7%28\--11
```
This uses Sakamoto's formula for the day of the week. Since there are people doing this, the output is in the form of `dd-mm`. My previous submission can be found below:
```
~.4/.25/.4/2---+7%"Nov "28@-
```
[Answer]
# TSQL, ~~478~~ 296 bytes
Just for funsies. Typically, you'd have a date dimensional table to make this a simple `select * from dimDate where [Year] = @Year and [Holiday] = 'Thanksgiving'` but in the absence of that...
```
create function a(@y varchar(4))returns date as begin declare @d date,@i int=0 set @d=convert(date,@y+'-11-01')declare @t table(d date,c int identity)while @i<28 begin if datepart(weekday,@d)=5 insert @t(d) select @d select @d=dateadd(d,1,@d),@i+=1 end select @d=d from @t where c=4 return @d end
```
Ungolfed:
```
if exists(select * from sys.objects where name='a' and [type]='FN') drop function a
go
create function a(@y varchar(4))returns date
-- select dbo.a('2015')
as
begin
declare @d date,@i int=0;
set @d=convert(date,@y+'-11-01'); -- cannot golf out dashes for dates <year 1000
declare @t table(d date,c int identity)
while @i<28
begin -- populate "November" array
if datepart(weekday,@d)=5 insert @t(d) select @d -- assumes @@datefirst = 7
select @d=dateadd(d,1,@d),@i+=1
end;
select @d=d from @t where c=4
return @d
end
```
[Answer]
# Pyth, ~~30~~ 28 \* 75% = 21 bytes
I'm 100% positive that this could be made shorter, but hey, it's my first Pyth program! \o/
```
-28.11%+-+-Q2/Q4/Q100/Q400 7
```
[Test suite](https://pyth.herokuapp.com/?code=-28.11%25%2B-%2B-Q2%2FQ4%2FQ100%2FQ400+7&input=2015&test_suite=1&test_suite_input=2014%0A2015%0A2016%0A2017%0A1917%0A-480%0A0&debug=0)
Outputs the date in `dd.mm` format.
*Please* suggest ways to golf this if you can! I'd like to learn more about Pyth.
[Answer]
# Excel, ~~64~~ 48
Year in A1
~~=DATE(A1,11,CHOOSE(WEEKDAY(DATE(A1,11,1)),26,25,24,23,22,28,27))~~
```
=DATE(A1,11,MOD(12-WEEKDAY(DATE(A1,11,1)),7)+22)
```
[Answer]
## Befunge, 41 Bytes
```
47*&:::4"d"*/\"d"/-\4/++5+7%-" voN",,,,.@
```
Run on [this interpreter](http://www.quirkster.com/iano/js/befunge.html).
**Explanation:**
A common year is *365 = 1 mod 7* days, so the year plus every 4th year, minus every 100th (`d` in ascii) year, plus every 400th years accounts for any leap days (including the present year). The result of `:::4"d"*/\"d"/-\4/++` can then be thought of as March 5th, the first day after February to fall on the same day as the first day of the year in common years. After that we calibrate to the pattern with `5+7%-` subtracting a number of days of the week from the 28th(the `47*`stored earlier) of November. Then print.
A version correcting for B.C. years is currently longer than the bonus provides for, at 59 -25% = 44.25 bytes:
```
47*&v
!`0:<+*"(F"_v#
" voN",,,,.@>:::4"d"*/\"d"/-\4/++5+7%-
```
[Answer]
## Matlab, 78 bytes
```
x=find(all(bsxfun(@eq,datestr(datenum(input(''),11,1:30),'ddd'),'Thu')'));x(4)
```
[Answer]
# Ruby, ~~60~~ ~~58~~ ~~42.75~~ 39 \* 0.75 = 29.25 bytes
```
->y{puts"Nov #{28-Time.new(y,9).wday}"}
```
**42.75 bytes**
```
->y{puts"Nov #{[5,4,3,2,1,7,6][Time.new(y,11).wday]+21}"}
```
**58 bytes**
```
->y{puts "Nov #{[5,4,3,2,1,7,6][Time.new(y,11).wday]+21}"}
```
**60 bytes**
```
->y{puts "Nov #{[5,4,3,2,1,7,6][Time.new(y,11,1).wday]+21}"}
```
Ungolfed:
```
-> y {
puts "Nov #{[5,4,3,2,1,7,6][Time.new(y,11).wday]+21}"
}
```
Tests:
```
->y{puts"Nov #{28-Time.new(y,9).wday}"}.(2015)
Nov 26
->y{puts"Nov #{28-Time.new(y,9).wday}"}.(1917)
Nov 22
->y{puts"Nov #{28-Time.new(y,9).wday}"}.(-480)
Nov 25
```
[Answer]
# PHP 5.3+, 59 bytes
This uses PHP builtin function [`strtotime`](http://php.net/manual/en/function.strtotime.php) to parse the date.
```
<?=gmdate('M d',strtotime("Next Thursday $_GET[Y]-11-19"));
```
This expects the value to be passed over GET parameter `Y` **OR** over `php-cli Y=<year>`.
It tries to find the next thursday after 19th November.
So far, with the tests I've made, it works fine.
Be aware that 2-digit years may be interpreted differently.
I use `gmdate` to avoid timezone issues, but it works equally well using `date` (at least, where I live).
[Answer]
# GNU coreutils, 35 bytes
```
seq -f$1-11-2%g 2 8|date -f-|grep h
```
Simply searches the week 22-28 November for a Thursday. Run it in a C or POSIX locale, as I depend on Thursday being the only day abbreviation to contain a 'h'.
---
Here's a cleverer answer, albeit a byte longer:
```
echo Nov $((28-`date -d$1-5-5 +%w`))
```
We retrieve the day-of-week number of a date in a fairly arbitrary week between March and September (so day and month are one digit each, and we're not affected by a possible leap day). We pick the day so that it's a Sunday (`%w==0`) when Thanksgiving is on the 28th. We can then subtract that value from 28 to obtain the appropriate Thursday.
[Answer]
# VBA, 124 bytes \* 75% = 93 bytes
```
Function e(y)
For i = 1 To 7
x = DateSerial(y, 11, 21) + i
If Weekday(x) = 5 Then e = Format(x, "mmm dd")
Next
End Function
```
I'm not sure if spaces count, it's somewhere between 102 and 124, feel free to edit.
If integers are a valid output I'm more than happy to remove the `Format` part.
[Answer]
# T-SQL ~~215 bytes~~ 248 \* 0.75 = 186 bytes
```
create function t(@y int)returns table return select x=convert(char(6),x,107)from(select x=cast(dateadd(dd,d,dateadd(yy,@y-2015+7600,'20151101'))as date)from(select d=21+n from(values(0),(1),(2),(3),(4),(5),(6))b(n))c)t where datepart(weekday,x)=5
```
Ungolfed
```
set nocount on;
if object_id('dbo.t') is not null drop function dbo.t
go
create function t(@y int)returns table return
select x=convert(char(6),x,107)
from (
select
x=cast(dateadd(dd,d,dateadd(yy,@y-2015+7600,'20151101'))as date)
from (
select d=21+n
from (values (0),(1),(2),(3),(4),(5),(6))b(n)
)c
)t
where datepart(weekday,x)=5
go
```
which with this test scaffold
```
select
[ 2015 = Nov. 26]=(select x from dbo.t( 2015))
,[ 1917 = Nov. 22]=(select x from dbo.t( 1917))
,[ 1752 = Nov. 23]=(select x from dbo.t( 1752))
,[ 1582 = Nov. 25]=(select x from dbo.t( 1582))
,[ 1400 = Nov. 27]=(select x from dbo.t( 1400))
,[ -480 = Nov. 25]=(select x from dbo.t( -480))
,[-5480 = Nov. 28]=(select x from dbo.t(-5480))
;
go
```
yields as desired
```
2015 = Nov. 26 1917 = Nov. 22 1752 = Nov. 23 1582 = Nov. 25 1400 = Nov. 27 -480 = Nov. 25 -5480 = Nov. 28
--------------- --------------- --------------- --------------- --------------- --------------- ---------------
Nov 26 Nov 22 Nov 23 Nov 25 Nov 27 Nov 25 Nov 28
```
[Answer]
# [Pike](http://pike.lysator.liu.se), ~~87 91 107 77~~ 76 bytes - 25% = 57
```
string t(int y){return"Nov "+((11-Calendar.Day(y,11,1)->week_day())%7+22);}
```
leaving the old one in for comparison because i find it more clever in terms of taking advantage of the Calendar module, but the above is way shorter.
```
string t(int y){object n=Calendar.Month(y,11);return"Nov "+(n->weeks()->day(4)&n->days())[3]->month_day();}
```
[Answer]
## [Smalltalk - Squeak and Pharo](http://beginningtosmalltalk.blogspot.com), ~~69~~ ~~57~~ ~~54~~ ~~49~~ ~~35~~ ~~34~~ ~~33~~ 32 - 25% = 24 bytes
**"Nov nn": ~~69B~~ 49B (-25% = 36.75B)**
**11nn (anInt): ~~57~~ ~~54~~ 32B (-25% = 24B)**
```
"Year supplied as an integer value, y
Result provided as an integer value, 11nn
Methods Date>>y:m:d: and >>w created as duplicates
of year:month:day and weekdayIndex"
(12-(Date y:y m:11d:1)w)\\7+1122
```
Previous versions
**11nn output**
```
"Year supplied as an integer value, y
Result provided as an integer value, 11nn"
(12-(Date year:y month:11 day:1) weekdayIndex)\\7+1122
"Year supplied as an integer value, y
Result provided as an integer value, d, prefixed by 11"
d:=(12-(Date year:y month:11 day:1) weekdayIndex)\\7+1122
```
**Nov nn output**
```
"Year supplied as an integer value, y Result provided as a string, 'Nov nn'"
'Nov ', (12-(Date year:y month:11 day:1) weekdayIndex\\7+22) asString
```
**nn output**
```
"Year supplied as an integer value, y Result provided as an integer value, d"
d:=(12-(Date year:y month:11 day:1) weekdayIndex)\\7+22
```
n.b. This is provided as a program - specifically a Workspace expression - rather than as a method.
It assumes the input is a given (as per the phrasing "given an up-to-four-digit year".
Including the declaring and giving of the input would add another 11 characters:
`|y|y:=2015.(12-(Date y:y m:11 d:1)w)\\7+1122`
Thanks to eMBee, for showing how to remove yet one more char - the whitespace immediately before the 'w'.
Actually, that inspired me to try removing the whitespace before 'd:' :
`|y|y:=2015.(12-(Date y:y m:11d:1)w)\\7+1122`
Which worked!
[Answer]
# TSQL, ~~53~~ 52 bytes
```
DECLARE @ CHAR(4)=2000
PRINT DATEADD(d,59,DATEDIFF(d,1,DATEADD(m,9,@))/7*7)
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/508977/when-is-thanksgiving)**
Calculating monday before or on september 2nd and adding 59 days
(better than calculating monday before or on october 4th and adding 31 days because october is the 10th month thus saving 1 byte)
[Answer]
## Perl, 92 bytes
```
use Time::Local;(localtime(timelocal 0,0,0,$_,10,$ARGV[0]))[6]==4?print "Nov $_":0for 22..28
```
EDIT : Fixed output format, fixed bug e.g. 2012 result, used shorter "for" format. Thanks to msh210.
] |
[Question]
[
**This question already has answers here**:
[Find a multiple of a given number whose decimal representation looks like binary](/questions/60942/find-a-multiple-of-a-given-number-whose-decimal-representation-looks-like-binary)
(44 answers)
Closed 6 months ago.
A *binary multiple* of a positive integer `k` is a positive integer `n` such that `n` is written only with `0`s and `1`s in base 10 and `n` is a multiple of `k`. For example, `111111` is a *binary multiple* of 3.
It is easy to show that a positive integer has infinitely many *binary multiples*. See [here](https://mathspp.com/blog/binary-multiples) for a construction proof of one *binary multiple* for each `k`. Multiplying by powers of `10` you get infinitely many more.
# Your task
Given a positive integer `k`, return the smallest binary multiple of `k`.
# Input
A positive integer `k`.
# Output
A positive integer `n`, the smallest binary multiple of `k`.
# Test cases
```
2 -> 10
3 -> 111
4 -> 100
5 -> 10
6 -> 1110
7 -> 1001
8 -> 1000
9 -> 111111111
10 -> 10
11 -> 11
12 -> 11100
13 -> 1001
14 -> 10010
15 -> 1110
16 -> 10000
17 -> 11101
18 -> 1111111110
19 -> 11001
20 -> 100
100 -> 100
```
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!
---
This is the first challenge of the [RGS Golfing Showdown](https://codegolf.meta.stackexchange.com/q/18545/75323). If you want to participate in the competition, you have 96 hours to submit your eligible answers. Remember there is 450 reputation in prizes! (See **6** of [the rules](https://codegolf.meta.stackexchange.com/q/18545/75323))
Otherwise, this is still a regular [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so enjoy!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
∞b.ΔIÖ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Uce8JL1zUzwPT/v/39ACAA "05AB1E – Try It Online") or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeWilvZLCo7ZJCkr2/x91zEvSOzfl0LrD0/7X6vyPNtQx0jHWMdEx1THTMdex0LHUMTTQMTTUMTTSMTTWMTTRMTTVMTTTMTTXMbTQMbTUMQLKGhjEAgA) *(courtesy of @KevinCruijssen)*
---
## Explanation
```
∞b - Infinite binary list
.Δ - Find the first value such that..
IÖ - It's divisible by the input
```
[Answer]
# [Python 2](https://docs.python.org/2/), 42 bytes
```
f=lambda k,n=0:n*(max(`n`)<'2')or f(k,n+k)
```
[Try it online!](https://tio.run/##JYxBCoMwEADvfcXezDZ7SHJqpL6kCEY0dkldJXior48BbzMMzH4e301cKbH7hXWcAiSSzrTyVGv4q0EGfDeuwS1DVDXphCVWYWCBHGSZlSOP@kZryL5Qf6wnV9GYvn0A7JnlAKZ6YCwX "Python 2 – Try It Online")
---
Full program, same length:
```
a=b=input()
while'1'<max(`b`):b+=a
print b
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9E2yTYzr6C0REOTqzwjMydV3VDdJjexQiMhKUHTKknbNpGroCgzr0Qh6f9/YwA "Python 2 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
`@YBUG\}HM
```
[Try it online!](https://tio.run/##y00syfn/P8Eh0inUPabWw/f/f0MLAA) Or [verify all test cases](https://tio.run/##LY1BC4JAFITv/YohEG9hHj1ZQcZS3YqigtZ1Q0F9y/MZeei3m5Vznfm@qbSU/SWMwgDzILgBHhbMugM9ILYRFLVrpZlM45N64R8PWyIHeloe6xlW5DqYltnWIwMhmLJwKWnOoPp7fF4e1PW92X0NexKLBEUDtq7UxmZIu2Gljn4EP83z38@auNICamUQ9h8).
### Explanation
```
` % Do...while
@ % Push iteration index (1-based)
YB % Convert to binary string (1 gvies '1', 2 gives '10, etc).
U % Convert string to number ('10' gives 10). This is the current
% solution candidate
G % Push input
\ % Modulo. Gives 0 if the current candidate is a multiple of the
% input, which will cause the loop to exit
} % Finally: execute on loop exit
H % Push 2
M % Push input to the second-last normal function (`U`); that is,
% the candidate that caused the loop to exit, in string form
% End (implicit). If top of the stack is 0: the loop exits.
% Otherwise: a new iteration is run
% Display (implicit)
```
[Answer]
# JavaScript (ES6), 37 bytes
Looks for the smallest \$n\$ such that the decimal representation of \$p=n\times k\$ is made exclusively of \$0\$'s and \$1\$'s.
```
f=(k,p=k)=>/[2-9]/.test(p)?f(k,p+k):p
```
[Try it online!](https://tio.run/##Fcm7DoIwFAbg3afoZk/8LRzAG6Y4@QSOhqEB6gXTNtD4@hWnb/je5mvmbnqFuHW@H1KyWo4IeiTdZPdie2ozFYc5ykAX@5/NSHVI53uBEhV22OOAIzgHM7gAl@AKvAPvwQfwCcVSed6ulPXT1XRP6YRuROfd7D@D@viHdCr6W5xe7iFJBdPfopmiLElsxLoW6wUrHRGlHw "JavaScript (Node.js) – Try It Online") (some test cases removed because of recursion overflow)
---
# JavaScript (ES6), 41 bytes
Looks for the smallest \$n\$ such that \$k\$ divides the binary representation of \$n\$ parsed in base \$10\$.
```
k=>(g=n=>(s=n.toString(2))%k?g(n+1):s)(1)
```
[Try it online!](https://tio.run/##RY27DoJAFAV7v2Ibw95wJFyQp1ms/AJKY7HhJUJ2CWz8faSzOVNMMuejv3pr1nFxF2Pbbu/VPqlKDsocuykTOFu7dTSDjIjO032QxmcqN5JM@@0ZIcYVCVJkyFGAQzCDI3AMvoITcArOwDm4QHTYMHydgt6uD928pRGqEo01m527YLZH/P9HwaLb2unVyZiEL7xSeAd6aYho/wE "JavaScript (Node.js) – Try It Online") (all test cases)
[Answer]
# [PHP](https://php.net/), 38 bytes
```
while(($n=decbin(++$x))%$argn);echo$n;
```
[Try it online!](https://tio.run/##VVBbT8IwFH7fr/iyzGwLI1CQi85BSJRIQpQE38SYOStbgt1cOyQx/vbZrR1gX3rO@S7nksVZeTPN4swwLEG54AjwbAA9BBOQrifDfh0SUsWXqlzXByfKUFPqZKQ5tWCskxq50jT1qgrpnkwIUXAd9xpHBfXPPUkzhdYNzruTYdNRpaMGVNLxvxEURY@l3Xvdsx3ld8xefMPodFBdCVHIKUfBE7aFFeZbBod@Fck@3FEmIFKsn24XD5ogr4v23DU@0pyGUexAXzrkWis7WDnlxU7AxY9sS6M4VZgHE@0JTL/8jpMddRyLBe80ekuY02pZB9e9qGmuX0ks5pdabGIjNsL0YEn74Gg/hb2ardc2rmHPZ4ul7WF1v3q9e1z6sq3cTvKoAGX7JE/Zp1xGlgsma3LqA1wfgPFb/gE "PHP – Try It Online")
Counts up `n` in binary and divides it's decimal representation by `k` until there is no remainder; indicating the first, smallest multiple.
[Answer]
# [R](https://www.r-project.org/), ~~50~~ 38 bytes
-4 bytes thanks to Giuseppe.
```
grep("^[01]+$",(k=scan())*1:10^k)[1]*k
```
[Try it online!](https://tio.run/##K/r/P70otUBDKS7awDBWW0VJRyPbtjg5MU9DU1PL0MrQIC5bM9owViv7v9l/AA "R – Try It Online")
It follows from [this blog post](https://mathspp.com/blog/binary-multiples) (linked in the question) that the smallest binary multiple of \$k\$ is smaller than \$2\cdot10^{k-1}\$; this answer uses the larger bound \$k\cdot10^k\$ instead.
Creates a vector of all multiples of \$k\$ between \$k\$ and \$k\cdot10^k\$. The regexp gives the indices of those made only of 0s and 1s; select the first index and multiply by \$k\$ to get the answer.
Will time out on TIO for input greater than 8, but with infinite memory it would work for any input.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
≔1ηW﹪IηIθ≔⍘⊕⍘粦²ηη
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU9DyVBJRyFD05qrPCMzJ1VBwzc/pTQnX8M5sbhEI0NTRwHMKNTU1FSAanBKLE4NLinKzEvX8MxLLkrNTc0rSU1BFs7QUTDS1AQREJMDgKIgw6z//ze0/K9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔1η
```
Start at `1`.
```
W﹪IηIθ
```
Repeat until a multiple of `n` is found, treating the values as base 10.
```
≔⍘⊕⍘粦²η
```
Convert from base 2, increment, then convert back to base 2.
```
η
```
Output the result.
[Answer]
# [Haskell](https://www.haskell.org/), ~~44 38~~ 36 bytes
Saved two bytes by using `filter` as suggested by @ovs.
```
f k=filter(all(<'2').show)[0,k..]!!1
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00h2zYtM6cktUgjMSdHw0bdSF1Trzgjv1wz2kAnW08vVlHR8H9uYmaebUFRZl6JgopCmoKh5X8A "Haskell – Try It Online")
This checks all multiples of `k` and is slow for input 9 and 18.
I much prefer this version which defines the list of all "binary" numbers and searches for the first multiple of `k` among them. It quickly handles all test cases, but needs 52 bytes:
```
b=1:[10*x+d|x<-b,d<-[0,1]]
f k=[m|m<-b,mod m k<1]!!0
```
[Try it online!](https://tio.run/##PYyxCsIwGIT3PsVVHNQ05Y@jJD6BTo4hSEqUSpqm2Iod@u4xOnjDx/EdXGtHf@u6lBolDlrQbmZumSVvKie5pkoYU9zhlQ5L@NoQHQK8FKYsKcW8DK/pMj1PPdYY2/iGB2NYgR8zcvu5Tb7YFsE@eii4iGCH8xURWtT1nkyBfyIEUfoA "Haskell – Try It Online")
[Answer]
# T-SQL, 57 bytes
This script is really slow when using 18 as input
```
DECLARE @z INT = 18
DECLARE @ int=1WHILE
@z*@ like'%[^10]%'SET @+=1PRINT @z*@
```
# T-SQL, 124 bytes
T-SQL doesn't have binary conversion
This will execute fast:
```
DECLARE @ int=1,@x char(64)=0,@a int=2WHILE
@x%@z>0or @x=0SELECT
@x=left(concat(@%2,@x),@),@a-=1/~@,@=@/2-1/~@*-~@a
PRINT @x
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1203060/rgs-1-5-binary-multiples)**
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 52 bytes
```
for((n=1;n%$1;));do n=`dc<<<2dio1d$n+p`;done
echo $n
```
[Try it online!](https://tio.run/##S0oszvj/Py2/SEMjz9bQOk9VxdBaU9M6JV8hzzYhJdnGxsYoJTPfMEUlT7sgASicl8qVmpyRr6CS9///f0NzAA "Bash – Try It Online")
This counts in binary, views the resulting numbers in base 10, and stops when a multiple of the input is reached.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/),, ~~75~~\$\cdots\$ ~~50~~ 52 bytes
Saved 2 bytes thanks to [Mukundan](https://codegolf.stackexchange.com/users/91267/mukundan)!!!
Added 2 bytes to fix error kindly pointed out by [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).
```
f=lambda k,n=1:(i:=int(f"{n:b}"))%k and f(k,n+1)or i
```
[Try it online!](https://tio.run/##TZDbaoQwEIbvfYrBpZCwKRjdgxXSyz5B70ovsuvIhl2jxAgW8dltDvaQq2/m@ycT0n/ZW6eLsjfr2oiHbC@1hDvTgldEVUJpS5p01tVlSSl9uoPUNTTEBfacdgbUasT8bkasUjmkDN7kY3CsOwuuXpLGZSxDUBpIQnLGM8oSUjDOuYeDa4TOcTMnbwKdGTgXUmXA0H1x@HN8zTPvAnGvAuUhFAd48XcPP0SO4hhTgU9xQyzOUfiRHeHlv43O73C6ItYDtHJS7diCwetoBtVpqLG3Nzcf3ritzMP74r3ZL9Mqgd5sf2sXeH6FuSGWLjCbDw9C4OcCOPV4tVindP0G "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
‘¡DṀḊƊ¿
```
**[Try it online!](https://tio.run/##ARsA5P9qZWxsef//4oCYwqFE4bmA4biKxorCv////zY "Jelly – Try It Online")**
### How?
Note that in Jelly empty lists are falsey, while other lists are truthy. Also dequeue, `Ḋ`, is a monadic atom which removes the first item from a list, but when presented with only an integer Jelly will first convert that integer to a list by forming the range `[1..n]` thus `Ḋ` yields `[2..n]`.
```
‘¡DṀḊƊ¿ - Link: integer, k
¿ - while...
Ɗ - ...condition: last three links as a monad:
D - decimal digits e.g. 1410 -> [1,4,1,0] or 1010 -> [1,0,1,0]
Ṁ - maximum 4 1
Ḋ - dequeue (implicit range of) [2,3,4] []
- (truthy) (falsey)
¡ - ...do: repeat (k times):
‘ - increment
```
For some reason, when the body of a while loop, `¿`, is a dyad each iteration sets the left argument to the result **and** then sets the right argument to the value of the left argument, so the 6 byte `+DṀḊƊ¿` does not work. (For example given `3` that would: test `3`; perform `3+3`; test `6`; perform `6+3`; test `9`; perform `9+6`; test `15`; perform `15+9`; etc...)
---
**[Previous 8](https://tio.run/##ARoA5f9qZWxsef//ROG4gsaRyKfhu43DsDEj////Ng):**
```
DḂƑȧọð1#
```
(`DḂƑ` could be `DỊẠ` too.)
**[An alternative](https://tio.run/##y0rNyan8/9/l4c4GbdWHu7sObzBU/v//vxkA "Jelly – Try It Online") 8**:
```
DṀ+%Ịð1#
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~11~~ ~~9~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
È*nvU}a¤
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yCpudlV9YaQ&input=MTg)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 68 bytes
```
.+
$*1:1,1;
{`^(1+):\1+,(.+);
$2
T`d`10`.1*;
,0
,10
1+,(.+)
$1$*1,$1
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRcvQylDH0JqrOiFOw1Bb0yrGUFtHQ09b05pLxYgrJCElwdAgQc9Qy5pLx4BLx9CACyrNpWII1KqjYvj/v6ElAA "Retina 0.8.2 – Try It Online") Somewhat slow so no test suite. Explanation:
```
.+
$*1:1,1;
```
Initialise the work area with `n` in unary, `k` in unary, and `k` in decimal.
```
{`^(1+):\1+,(.+);
$2
```
If `n` divides `k` then delete everything except the result. This causes the remaining matches to fail and eventually the loop exits because it fails to achieve anything further.
```
T`d`10`.1*;
,0
,10
```
Treat `k` as a binary number and increment it.
```
1+,(.+)
$1$*1,$1
```
Regenerate the unary conversion of `k`.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Core utilities, 40 bytes
```
seq $1 $1 $[10**$1]|grep ^[01]*$|head -1
```
[Try it online!](https://tio.run/##S0oszvj/vzi1UEHFEIyiDQ20tFQMY2vSi1ILFOKiDQxjtVRqMlITUxR0Df///28OAA "Bash – Try It Online")
[Answer]
# [W](https://github.com/A-ee/w), ~~7~~ 6 [bytes](https://github.com/A-ee/w/wiki/Code-Page)
-1 because I realized that W has operator overloading over `t`.
```
•B⌡≡kü
```
Uncompressed:
```
*Tt!iX*
```
[repl.it](https://repl.it/@wgolf/w) is quite slow and you need to type in the program in code.w.
## Explanation
```
% For every number in the range
i % from 1 to infinity:
X % Find the first number that satisfies
* % Multiply the current item by the input
T % The constant for 10
t % Remove all digits of 1 and 0 in the current item
% Both operands are converted to a string, just like in 05AB1E.
! % Negate - checks whether it contains only 1 and 0.
* % Multiply that result with the input (because it's the counter value).
```
```
[Answer]
# Java 10, ~~62~~ ~~59~~ 58 bytes
```
n->{var r=n;for(;!(r+"").matches("[01]+");)r+=n;return r;}
```
[Try it online.](https://tio.run/##bU/LbsIwELzzFVOfbFlESY@46R@UC0fEwTUGTJMNWjuRKpRvT50Ublx29jE7mrnawa6vx5/JNTZGfNlA9xUQKHk@WeexnUeg6egMJxcgZfJuXOUSk03BYQtCjYnWn/fBMrgmc@pYmjfJWghVtDa5i49S7MvqoIUyinXmsE89E9iMk5nVbv13k9UeokMXjmizIblLHOi8P8Cqfzez@GIl1JVB@Kjfywxaq@UK7H5j8m3R9am45dfUkAxabCA0FU4GtQR4SRNVWT55uVWPqOP0Bw)
**Explanation:**
```
n->{ // Method with long as both parameter and return-type
var r=n; // Result-long, starting at the input
for(;!(r+"").matches("[01]+");)
// Loop as long as `r` does NOT consists of only 0s and 1s
r+=n; // Increase `r` by the input
return r;} // After the loop is done, return `r` as result
```
This method above only works for binary outputs \$\leq1111111111111111111\$. For arbitrary large outputs - given enough time and resources - the following can be used instead (**~~99~~ ~~70~~ 64 bytes**):
```
n->{var r=n;for(;!(r+"").matches("[01]+");)r=r.add(n);return r;}
```
[Try it online.](https://tio.run/##jY89b4MwEIZ3fsXVky0rFnSsS4ZuHZoOGaMMVzDEFEx0GKQq4rfTI83I0OVO9/Xc@zY44a4pv5eixWGAD/ThlgD4EB1VWDg4rCVAw3umw3gxb75@52ntCAq52Q7K8s2ccBgiRl/AAQLksITd/jYhAeXBVj1J@yRJC6FWQnFxgxSnNDtroayinAyWpWQWuThSALLzYlfmdfxqmflAT70voWPZ8hjJh/p0BlR/mtcXbAR8nlnwr/lzyklrdR8CHH@G6DrTj9Fc@TK2QXotXkDoYLadmQnb0X1W0it197gJEVma/ovCew/OnMzLLw)
[Answer]
# [Perl 5](https://www.perl.org/), 21 +2 (-ap) = 23 bytes
```
$_+=$F[0]while/[^01]/
```
Run with `-a` and `-p`, input to stdin. Just keeps repeatedly adding the input for as long as the result contains anything other than digits 0 and 1.
[Try it online!](https://tio.run/##K0gtyjH9/18lXttWxS3aILY8IzMnVT86zsAwVv//f7N/@QUlmfl5xf91EwsA "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~42~~ ~~40~~ 36 bytes
```
->k{z=k;z+=k until z.digits.max<2;z}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y67uso227pK2zZboTSvJDNHoUovJTM9s6RYLzexwsbIuqr2v4aRnp6RgaZeamJyRnVNZk1BaUmxgpJqsYKunYJqsZJqdKZOWnRmbGztfwA "Ruby – Try It Online")
Very slow for 18, but ultimately gets the job done.
4 bytes golfed down by G B.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 80 bytes
```
r,m,n;b(h){for(r=0,m=1;h;h/=2)r+=h%2*m,m*=10;h=r;}f(k){for(n=1;b(++n)%k;);b(n);}
```
This can probably be improved some but I have yet to find a way.
Converts the integer into binary and checks if it's a multiple.
Brute-force.
[Try it online!](https://tio.run/##XY/bbsIwDIbv8xQWU6WEmhF3RxTCi7BejJQuEWuK2rKLoT5759INbbNk@fTZ@u0Wb84NQ4MVRrOTXp3LupGN1VhZMt74pc1Uk1qfZPMKq7klbbxtTF/Kw8RG5nYyTaNKDkZxGpXph5sQ3fup2MO67YpQ3/qNECF2UL2GKD/qUChxFsA2NkM8nrp2m4O9tKbBaBnCHcI9wgPCI8ITwjPCCq9z0ghE7AwSk8QoMUsME9PEOK0QMv1757vojbjE8YlRhQML2nBYQxs@93UpJ11q@afc6lwxlabqn9hjw1dKOUsKWGwgKV7iDH9ecznC9YDLlTKTBNEPXw "C (gcc) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~50~~ 48 bytes
```
f=lambda k,n=0:n*({*str(n)}<={*"01"})or f(k,n+k)
```
[Try it online!](https://tio.run/##JY1BCsIwEADvfcUaL0kbIdGLFvMS8RCbrQ2t25JEUErfHgPeZmBglm8aZjrl3JvJvh7OwijJqJZqvtYxBU5iu5q1ZkqzTcwBel6CZhS5L@LBE0w@Jh4sPZFredRCNDet1L2twPel2Bm4gCX3R31uYZ8GjAidjRgBPx2ig4DdO0Q/Ezhc0gAVwBI8Je4lOzBZtl6I/AM "Python 3 – Try It Online")
## Explanation
* `n` represents the current multiple of `k`.
* `{*str(n)}<={*"01"}` checks if `n` only contains digits `0` or `1`. This is done by creating a set of characters of `n`, then checks if that set is a subset of \$\{0,1\}\$.
* `n*({*str(n)}<={*"01"}) or f(k,n+k)` is arranged such that the recursive call `f(k,n+k)` is only evaluated when `n` is 0 or `n` is not a binary multiple of `k`. Here multiplication acts as a logical `and`.
[Answer]
# [J](http://jsoftware.com/), 24 23 22 bytes
```
+^:(0<10#@-.~&":])^:_~
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/teOsNAxsDA2UHXT16tSUrGI146zi6/5rcqUmZ@QrGBoo2CqkKRhBeYaGYK4xTBIia4Ki1hSuFsI3gyuGaDaH8yHyFnD1EAAWtEQx0tAApgbCNURYAVVghGaJIcKJMDNM0NxlaIpwCFTEDKEEagzMsQiDLVH9bmSAygfSXH5OegqofoLKWXD9BwA "J – Try It Online")
Add the number to itself `+` while `^:...^:_` the following is true:
`(0<10#@-.~&":])` - Something other than the digits 0 and 1 appear in the stringified number.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 13 bytes
```
rimo{>]2.<}fe
```
[Try it online!](https://tio.run/##DclLCoAgFAXQrdwVhPf5K4g2Ek0igyCJDGkgrt0607PmdIbnzqG9W2npiFeZFunGuodW49wEGgYWDh49qECCAmrQgBZ0oAcHyF9KfQ "Burlesque – Try It Online")
9 & 18 do work, but take a while because they're such large multiples. So I've taken them out of tests.
```
ri # Read to int
mo # Generate infinite list of multiples
{
>] # Largest digit
2.< # Less than 2
}fe # Find the first element s.t.
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 49 bytes
```
(x=#;While[Or@@(#>1&)/@IntegerDigits@x,x=x+#];x)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X6PCVtk6PCMzJzXav8jBQUPZzlBNU9/BM68kNT21yCUzPbOk2KFCp8K2Qls51rpCU@1/QFFmXomCQ3q0cez//wA "Wolfram Language (Mathematica) – Try It Online")
[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ô+_▒╙2<▼
```
[Try it online.](https://tio.run/##DckxDkAwAIbR/buKpX@rLYm7iAUDsTiJRBP3MNrcpBcpb33rsM/TtoylmPeu@pyOfF62y@kpRVgcNZ5ApEEGCVnkUI08CiiiFvuXMR8) (Test cases `n=9` and `n=18` are excluded, since they time out.)
**Explanation:**
```
0 # Start with 0
▼ # Do-while false with pop,
ô # using the following 6 commands:
+ # Add the (implicit) input-integer to the current value
_ # Duplicate it
▒ # Convert it to a list of digits
╙ # Pop and push the maximum digit of this list
2< # And check if this max digit is smaller than 2 (thus 0 or 1)
# (after the do-while, the entire stack joined together is output implicitly)
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax/blob/master/docs/instructions.md), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü◘ø⌠Δ>0↔å
```
Port of [my MathGolf answer](https://codegolf.stackexchange.com/a/200033/52210). This is only my second Stax answer, so there might be a shorter alternative.
[Try it online](https://staxlang.xyz/#p=810800f4ff3e301d86&i=14) or [try it online unpacked (10 bytes)](https://staxlang.xyz/#c=0wx%2BcE%7CM1%3E&i=14).
**Explanation (of the unpacked version):**
```
0 # Start at 0
w # While true without popping, by using everything else as block:
x+ # Add the input-integer
c # Duplicate the top of the stack
E # Convert it to a list of digits
|M # Get the maximum of this list
1> # And check that it's larger than 1
# (after the while, the top of the stack is output implicitly as result)
```
[Answer]
# [Red](http://www.red-lang.org), 52 bytes
```
func[n][i: 0 until[""= trim/with to""i: i + n"01"]i]
```
[Try it online!](https://tio.run/##DcnLCsIwEEDRvV9xma2ImT61oB/hNmQhfdCATiWk@PnRsz1pnspjnnw4LANl2W30FnwccOyW48uL3Mgpvs/fmFfyJvLPyBETpxJiKMuW5ue4YviKmoaWjp4L6lBFK7RGG7RFO7RHr1T/ci74T4qW8Yac7sKChVB@ "Red – Try It Online")
# [Red](http://www.red-lang.org), 54 bytes
```
func[n][i: 0 until[parse to""i: i + n[any["0"|"1"]]]i]
```
[Try it online!](https://tio.run/##Dck9CsMwDAbQvaf40FoKlvPXZughugoNJrGpoSjBSYZC7@5mfa/Eub7iLHpJI2o6bBJTySMcDtvzR9ZQtoh9ITox4wqTYF8hRz9iUtWsNS0lhukNg3g0aNGhx4A72IEZ7MENuAV34B48gB/wZzmnspZsO8RAtychwVTrHw "Red – Try It Online")
[Answer]
# [Icon](https://github.com/gtownsend/icon), 50 bytes
```
procedure f(n)
i:=seq(n,n)&0=*(i--10)
return i
end
```
[Try it online!](https://tio.run/##TY09DsIwDIX3nMLqgGKUSA4jUrkLaozkAQdMCuL0xVWH8ran7/3I1HRZHtYmrrMx3KJikPP44mfUpHig8Rgl50IYjPtsChJY61/lfhWNGMDFb7YveL1Ab3AiqA0@Jp2jJBjyZUh@ILiFN1CIduTG4Tr/Aw "Icon – Try It Online")
`seq(n,n)` generates an "infinite" (seq operator doesn’t work with large integers) sequence starting at `n` with step `n`
`&`is conjunction - Icon evaluates the next expression and if it fails, than backtracks to the expression to its left - so generates the next integer.
`i--10` finds the difference of the string representation of `i` with the string `10` - Icon automatically casts number to strings when an operation on strings is used.
`*(1--10)` finds the length of the difference of `i` and `10` (which is a string)
`0=*(1--10)` - if the length is `0`, the number is composed only of 1's and 0's.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~53~~ 49 bytes
turns out Max can cast chars to codes implicitly
I tried a recursive version, but it was longer. Can't think of a way to replace the loop with LINQ...
```
a=>{int r=a;while($"{r}".Max()>49)r+=a;return r;}
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXogPEdgpuCrYK/xNt7aqBPIUi20Tr8ozMnFQNFaXqololPd/ECg1NOxNLzSJtoFRRaklpUZ5CkXXtf2uugCKgDg03DSNNTQTHGJljgswxReaYIXPMkTkWyBxDsNR/AA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~9~~ 7 bytes
```
ḟoΛεd∫∞
```
[Try it online!](https://tio.run/##ARkA5v9odXNr///huJ9vzpvOtWTiiKviiJ7///8y "Husk – Try It Online")
-2 bytes from Leo.
] |
[Question]
[
Writing out numbers is among the Hello worlds of programming, often the numbers 1-10.
I want to write out many numbers! Many, Many numbers. But how many numbers do I have to write?
# Task
Given an integer input, give a number as output that would give me the number of digits that would be in a string containing all integer numbers in the range from 0 to the input, inclusive. The negation identifier ("-") counts as a single character.
# Example I/Os
Input: 8
Written out: 0,1,2,3,4,5,6,7,8
Output: 9
Input: 101
written out: 0,1,2,3....,99,100,101
Output: 196
Input: 102
written out: 0,1,2,3....,100,101,102
output: 199
Input -10
Written out: 0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10
output: 22
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The lowest number of bytes wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
Code:
```
√ùJg
```
Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@394rlf6//@GBoYA "05AB1E – TIO Nexus")
Explanation:
```
√ù # Range [0 .. input]
J # Join into one string
g # Get the length of the string
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~55~~ 46 bytes
```
lambda n:len(`range(abs(n)+1)`)+2*~n+3*n*(n<0)
```
**[Try it online!](https://tio.run/nexus/python2#HcsxDsIwDEDRGU5hdbKTgOJ2QRHchKGuSFCl1qA0WwVXDy3Lf9NPt3udZB4eAhqmqNhn0WdEGRZUskw92dZ81XZGDerVU02vDCUuBUYFvDhgz3taByf2FI6Hdx61QLP60H0CrLzRnLdrloL76CD9Jar1Bw)**
Getting better.
[Answer]
# [Röda](https://github.com/fergusq/roda), 23 bytes
```
f x{[#([seq(0,x)]&"")]}
```
[Try it online!](https://tio.run/nexus/roda#@5@mUFEdrawRXZxaqGGgU6EZq6akpBlb@z83MTNPoZqLM9pCR8HQwBBEGOko6BoaxCrUKKQpxAPJgqLMvBKFeK7a/wA "Röda – TIO Nexus")
Explained:
```
f x{[#([seq(0,x)]&"")]}
f x{ } /* Defines function f with parameter x. */
seq(0,x) /* Creates a stream of numbers from 0 to x. */
[ ] /* Creates an array. */
&"" /* Joins with "". */
#( ) /* Calculates the length of the resulting string. */
[ ] /* Returns the value. */
```
[Answer]
# [Python 2](https://docs.python.org/2/), 41 bytes
```
f=lambda n:len(`n`)+(n and f(n+cmp(0,n)))
```
[Try it online!](https://tio.run/nexus/python2#FYxNCoAgGAXXdYq3kT7JQGsTQZ1Fy4SgXiHdv5/NzGrmSeMejjkGcNhXiqfXtRCBEUlYL8cl1lBr/aQzg9iI3sBZ96M1aJwdyuLKG29UqotoJnyqoCA0/@NLXw "Python 2 – TIO Nexus")
[Answer]
# Bash + OS X (BSD) utilities, ~~24~~ 22 bytes
*Thanks to @seshoumara for saving 2 bytes.*
```
seq 0 $1|fold -1|wc -l
```
Test runs on Mac OS X:
```
$ for n in 8 101 102 -10 -1 0 1; do printf %6d $n; ./digitcount $n; done
8 9
101 196
102 199
-10 22
-1 3
0 1
1 2
```
---
Here's a GNU version:
# Bash + coreutils, ~~40~~ 38 bytes
*Again, 2 bytes saved thanks to @seshoumara.*
```
(seq $1 0;seq 0 $1)|uniq|fold -1|wc -l
```
[Try it online!](https://tio.run/nexus/bash#@69RnFqooGKoYGANYhgAmZo1pXmZhTVp@TkpCrqGNeXJCro5////NzQwAgA "Bash – TIO Nexus")
[Answer]
# Python 2, ~~83~~ ,~~78~~ 64 bytes
shortest version:
```
lambda x:sum(map(len,map(str,(range(0,x+cmp(x,.5),cmp(x,.5))))))
```
this version saved 5 bytes, thanks to @numbermaniac :
```
x=input()
print len(''.join(map(str,(range(x+1)if x>0 else range(0,x-1,-1)))))
```
[Try it online!](https://tio.run/nexus/python2#S7ON@V9hm5lXUFqioclVUJSZV6KQk5qnoa6ul5WfmaeRm1igUVxSpKNRlJiXnqpRoW2omZmmUGFnoJCaU5yqABE10KnQNdTRNdQEgf//dQ0NAA "Python 2 – TIO Nexus")
this one I came up with on my own after that (same amount of bytes):
```
x=input()
print sum(map(len,map(str,(range(x+1)if x>0 else range(0,x-1,-1)))))
```
[Try it online!](https://tio.run/nexus/python2#S7ON@V9hm5lXUFqioclVUJSZV6JQXJqrkZtYoJGTmqcDootLinQ0ihLz0lM1KrQNNTPTFCrsDBRSc4pTFSCiBjoVuoY6uoaaIPD/v66hAQA "Python 2 – TIO Nexus")
[Answer]
# Java 7, 74 bytes *(recursive - including second default parameter)*
```
int c(int r,int n){r+=(n+"").length();return n>0?c(r,n-1):n<0?c(r,n+1):r;}
```
**Explanation (1):**
```
int c(int r, int n){ // Recursive method with two integer parameters and integer return-type
// Parameter `r` is the previous result of this recursive method (starting at 0)
r += (n+"").length(); // Append the result with the current number's width
return n > 0 ? // If the input is positive
c(r, n-1) // Continue recursive method with n-1
: n < 0 ? // Else if the input is negative
c(r, n+1) // Continue recursive method with n+1
? // Else (input is zero)
r; // Return the result
} // End of method
```
---
# Java 7, ~~81~~ 79 bytes *(loop - single parameter)*
If having a default second parameter as `0` for this recursive approach isn't allowed for some reason, a for-loop like this could be used instead:
```
int d(int n){String r="x";for(int i=n;i!=0;i+=n<0?1:-1)r+=i;return r.length();}
```
**Explanation (2)**
```
int d(int n){ // Method with integer parameter and integer return-type
String r = "x"; // Initial String (with length 1 so we won't have to +1 in the end)
for(int i=n; i != 0; // Loop as long as the current number isn't 0
i += n < 0 ? 1 : 1) // After every iteration of the loop: go to next number
r += i; // Append String with current number
// End of loop (implicit / single-line body)
return r.length(); // Return the length of the String
} // End of method
```
---
[Answer]
# Mathematica, ~~48~~ ~~47~~ 46 bytes
-1 byte thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender)!
```
StringLength[""<>ToString/@Range[0,#,Sign@#]]&
```
Anonymous function, taking the number as an argument.
### Shorter solution by [Greg Martin](https://codegolf.stackexchange.com/users/56178/greg-martin), 39 bytes
```
1-#~Min~0+Tr@IntegerLength@Range@Abs@#&
```
[Answer]
# [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 5 bytes
```
n0R.L
```
## Explination
```
n0R # A Stack of all numbers between 0 and the input converted to a number.
.L # The length of the stringification of this.
```
Simple solution, works like a charm.
[Try it online!](https://tio.run/nexus/rprogn-2#@59nEKTn8///f11DAwA "RProgN 2 – TIO Nexus")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
⟦ṡᵐcl
```
[Try it online!](https://tio.run/nexus/brachylog2#@/9o/rKHOxc@3DohOef//3hDg/9RAA "Brachylog – TIO Nexus")
Builds the range [0,input], converts each number to string, concatenates into a single string and returns the length of the result
[Answer]
### PHP, ~~59~~ 60 bytes
**Outgolfed by Roberto06 - <https://codegolf.stackexchange.com/a/112536/38505>**
Thanks to [roberto06](https://codegolf.stackexchange.com/users/64847/roberto06) for noticing the previous version didn't work for negative numbers.
Simply builds an array of the numbers, puts it to a string, then counts the digits (and minus sign)
```
<?=preg_match_all("/\-|\d/",implode(",",range(0,$argv[1])));
```
Run example: `php -f 112504.php 8`
* [8 test case](https://eval.in/752102)
* [101 test case](https://eval.in/752103)
* [102 test case](https://eval.in/752104)
* [-10 test case](https://eval.in/752100)
[Answer]
# [Haskell](https://www.haskell.org/), ~~39~~ 38 bytes
```
f 0=1
f n=length$show=<<[0..n]++[n..0]
```
[Try it online!](https://tio.run/nexus/haskell#@5@mYGBryJWmkGebk5qXXpKhUpyRX25rYxNtoKeXF6utHZ2np2cQ@z83MTNPwVahoCgzr0RBRSFNQ9fQQPM/AA "Haskell – TIO Nexus") Edit: saved 1 byte thanks to @xnor!
**Explanation:**
In Haskell for numbers `a` and `b` `[a..b]` is the range from `a` to `b` in 1-increments or 1-decrements, depending on whether `b` is larger `a`. So for a positive `n` the first list in `[0..n]++[n..0]` is `[0,1,2,...,n]` and the second one is empty. For negative `n` the second range yields `[0,-1,-2,...,n]` and the first one is empty. However if `n=0` both ranges yield the list `[0]`, so the concatenation `[0,0]` would lead to a false result of `2`. That's why `0` is handled as a special case.
The `=<<`-operator on a list is the same as `concatMap`, so each number is converted into a string by `show` and all those strings are concatenated in one long string of which the `length` is finally returned.
---
Before xnor's tip I used `[0,signum n..n]` instead of `[0..n]++[n..0]`.
`signum n` is `-1` for negative numbers, `0` for zero and `1` for positive numbers and a range of the form `[a,b..c]` builds the list of numbers from `a` to `c` with increment `b`. Thereby `[0,signum n..n]` builds the range `[0,1,2,...,n]` for positive `n` and `[0,-1,-2,...,n]` for negative `n`. For `n=0` it would build the infinite list `[0,0,0,...]` so we need to handle `0` as a special case, too.
[Answer]
# PHP, ~~41~~ 35 bytes
*Saved 6 bytes thanks to user59178*
Since [∞·µà's answer](https://codegolf.stackexchange.com/questions/112504/how-much-do-i-have-to-write/112526#112526) was wrong for a negative input, I took it upon myself to build a new solution :
```
<?=strlen(join(range(0,$argv[1])));
```
This function :
* Builds an array from `0` to `$argv[1]` (aka the input)
* Implodes it with an empty character (i.e. transforms it to a string)
* Echoes the length of the string
[Try it here!](https://eval.in/752325)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~20 26~~ 29 bytes
```
->x{[*x..-1,0,*1..x]*''=~/$/}
```
[Try it online!](https://tio.run/nexus/ruby#@59mq2tXUR2tVaGnp2uoY6CjZainVxGrpa5uW6evol/LxVWgkBZtaGAUC2boGhpAGAax//8DAA "Ruby – TIO Nexus")
[Answer]
# R, ~~26~~ 20 bytes
`sum(nchar(0:scan()))`
Very basic approach:
* Make a vector 0:x
* Count the characters in each value (will be coerced to a string automatically)
* Sum
~~Not sure if there are any tricks to cut down the function definition?~~
6 bytes saved thanks to Giuseppe, by taking input from stdin instead.
[Answer]
## Batch, 110 bytes
```
@set/a"n=%1,t=n>>31,n*=t|1,t=1-t*n,i=0
@for /l %%i in (0,1,9)do @set/a"t+=(i-n)*(i-n>>31),i=i*10+9
@echo %t%
```
Computes `sum(min(0,abs(n)+1-10^k),k=0..9)+(n<0?1-n:1)`. (I only have to go up to `9` because of the limitations of Batch's integer arithmetic.)
[Answer]
# [Python 2](https://docs.python.org/2/), 68 bytes
```
def f(i,j=1):
if i==0:print j
else:j+=len(`i`);f((i-1,i+1)[i<0],j)
```
[Try it online!](https://tio.run/nexus/python2#JcXBCoAgDADQu1@x44YKrlNYfkkEHnIwEYnq/43oXd44ioCgupqYogEV0JRCPC/tD1QDpd0lVpta6Zg10yKI6tmpZdp0DburNARnMoIc@G/68hzIjBc "Python 2 – TIO Nexus")
Longer than but different from other Python solutions. Defines a recursive function called as e.g. `f(10)`
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
```
0hSZ}&:VXzn
```
[Try it online!](https://tio.run/nexus/matl#@2@QERxVq2YVFlGV9/@/oYEhAA "MATL – TIO Nexus")
```
0h % Implicitly input n. Append a 0: gives array [n 0]
S % Sort
Z} % Split array: pushes 0, n or n, 0 according to the previous sorting
&: % Binary range: from 0 to n or from n to 0
V % Convert to string. Inserts spaces between numbers
Xz % Remove spaces
n % Length of string. Implicit display
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 23 bytes
```
-join(0.."$args")|% Le*
```
[Try it online!](https://tio.run/nexus/powershell#@6@blZ@Zp2Ggp6ekkliUXqykWaOq4JOq9f//f0MDIwA "PowerShell – TIO Nexus") (will barf on TIO for very large (absolute) inputs)
Uses the `..` range operator to construct a range from `0` to the input `$args` (cast as a string to convert from the input array). That's `-join`ed together into a string (e.g., `01234`) and then the `Le`ngth is taken thereof. That is left on the pipeline and output is implicit.
[Answer]
# [Perl 6](https://perl6.org), 18 bytes
```
{chars [~] 0...$_}
```
[Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLzk9JVbD9X52ckVhUrBBdF6tgoKenpxJf@z8tv0hBRcvTT688vyilWC83sUBDW0tToZpLQaE4sVIBrFElnqv2v4WCoYEhEBsp6BoaAAA "Perl 6 – TIO Nexus")
## Expanded:
```
{ # bare block lambda with implicit parameter ÔΩ¢$_ÔΩ£
chars # how many characters (digits + '-')
[~] # reduce using string concatenation operator &infix:<~>
0 ... $_ # deductive sequence from 0 to the input
}
```
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 25 bytes
```
:[0,a,sgn(a)|A=A+!b$]?_lA
```
Explanation:
```
:[0,a Read 'a' from the cmd line, start a FOR loop from 0 to 'a'
,sgn(a)| with incrementer set to -1 for negative ranges and 1 for positive ones
A=A+!b$ Add a string cast of each iteration (var 'b') to A$
] NEXT
?_lA Print the length of A$
```
[Answer]
## JavaScript, 50 bytes
*Collaborated with @ETHproductions*
```
n=>{for(t="";n;n<0?n++:n--)t+=n;alert(++t.length)}
```
[Answer]
# Bash + GNU coreutils, 28
```
eval printf %s {0..$1}|wc -c
```
[Try it online](https://tio.run/nexus/bash#DcNNCoAgEAbQfaf4FrYcmWkVdJrwB4QYQ6UW1dnNBy/mAkVSrBCWcQEJj2DIBp8nDDU0EMFoD9d@4CxJW8Rc8bC1Rr73diDXfdbQfw).
[Answer]
# [Retina](https://github.com/m-ender/retina), 28 bytes
```
\d+
$*
1
$`1¶
1+
$.&
^-?
0
.
```
[Try it online!](https://tio.run/nexus/retina#U9VwT/gfk6LNpaLFZcilkmB4aBuXIZCnp8YVp2vPZcCl9/@/BZehgSEQG3HpGhoAAA "Retina – TIO Nexus")
### Explanation
```
\d+
$*
```
Convert the number to unary, keeping the sign untouched.
```
1
$`1¶
```
Each 1 is replaced by everything up to itself plus a newline. With this we get a range from 1 to n if n was positive, from -1 to n with an additional `-` at the start if it was negative. All numbers are in unary and separed by newlines.
```
1+
$.&
```
Convert each sequence of ones to the corresponding decimal number.
```
^-?
0
```
Put a `0` at the start, replacing the extra `-` if it's there.
```
.
```
Count the number of (non-newline) characters.
[Answer]
# Emacs, 20 bytes
```
C-x ( C-x C-k TAB C-x ) M-{input} C-x e C-x h M-=
```
The command itself is 20 keystrokes, but I need clarification on how this should be counted as bytes. I reasoned that counting each keystroke as 1 byte would be the most fair. The command above is written conventionally for easier reading.
## Explanation
```
C-x (
```
Begin defining a keyboard macro.
```
C-x C-k TAB
```
Create a new macro counter. Writes `0` to the buffer; the counter's value is now 1.
```
C-x )
```
End keyboard macro definition.
```
M-{input} C-x e
```
After hitting META, type in your input number. The `C-x e` then executes the macro that many times.
```
C-x h
```
Set mark to beginning of buffer (which selects all of the text thus generated).
```
M-=
```
Run character count on the selected region. The number of characters will be printed in the minibuffer.
## Example
Apologies for the terrible highlighting color. This is an example of using this command with the input 100. The output is in the minibuffer at the bottom of the screen.
[![Example execution with input of 100](https://i.stack.imgur.com/F28O6.png)](https://i.stack.imgur.com/F28O6.png)
[Answer]
# Lua, 52 bytes
```
t=0;for i=0,io.read()do t=t+#tostring(i)end;print(t)
```
Iterates through a for loop from 0 - input, converts the integer `i` to a string and adds the length of the string to `t` before printing `t`
[Answer]
# [Perl 5](https://www.perl.org/), 32 bytes
31 bytes of code + `-p` flag.
```
$\+=y///c for$_>0?0..$_:$_..0}{
```
[Try it online!](https://tio.run/nexus/perl5#U1bULy0u0k/KzNMvSC3KUdAt@K8So21bqa@vn6yQll@kEm9nYG@gp6cSb6USr6dnUFv9/7@hgREA "Perl 5 – TIO Nexus")
[Answer]
# C#, ~~77~~ 73 bytes
*-4 bytes thanks to @Kevin Cruijssen*
Lambda function:
```
(r)=>{var l="";for(int i=0,s=r<0?-1:1;i!=r+s;i+=s)l+=i;return l.Length;};
```
Ungolfed and with test cases:
```
class P
{
delegate int numbers(int e);
static void Main()
{
numbers n = (r) =>
{
var l = "";
for (int i = 0, s = r < 0 ? -1 : 1; i != r + s; i += s)
l += i;
return l.Length;
};
System.Console.WriteLine(n(8));
System.Console.WriteLine(n(101));
System.Console.WriteLine(n(102));
System.Console.WriteLine(n(-10));
System.Console.ReadKey();
}
}
```
[Answer]
## JavaScript, 44 bytes
```
f=(n,i=1)=>n<0?f(-n)-n:n<i?1:n+1-i+f(n,i*10)
```
```
<input type=number oninput=o.textContent=f(+this.value)><pre id=o>
```
[Answer]
## REXX, 56 bytes
```
arg n
l=0
do i=0 to n by sign(n)
l=l+length(i)
end
say l
```
] |