text
stringlengths 180
608k
|
---|
[Question]
[
## The Machine
A billiard-ball type machine is composed of only the symbols `\` `_` `/` along with upper- and lower-case letters, spaces, and the number `1`.
`\` and `/` are ramps. A ball coming from above will be deflected to either the right or left side, respectively. For both ramps, if a ball comes from either side, it will be deflected downward.
`_` is a logic element. The logic performed by it is the most un-billiard-like part of the computer. First, a ball coming from the left or right continues in the same direction. A ball coming from above will be stopped. Then, after the end of its execution (see Running the Machine below), if the number of balls crossing/landing on it is positive even number, then a single ball is released from the bottom of the element.
A space does nothing. Any balls coming from any direction fall straight down due to gravity.
Lowercase letters are inputs. All inputs will either be a single 1 or 0.
Uppercase letters are outputs. The number outputted will be the number of billiard balls that hit its location.
The number `1` releases a extra billiard-ball at that location. It represents a logical 1.
All characters besides `\_/` cause any ball coming from any direction to fall straight down due to gravity.
Balls never combine, split, or collide. They are only created when released from an input, a `_`, or a `1`. They are only destroyed when they fall straight down onto a `_`.
Example machine-
```
1 a
\_/ b
\_/
\/
/\ /
_ _
A B
```
There will never be any blank lines in a machine, but the `_`'s may make it appear that there is a blank line.
## Running the Machine
A machine is run in layers, or rows. All billiard-ball movement on the top layer is performed before anything happens on the second layer.
The machine
```
ab
\_A
C
```
is run as follows:
First, it prompts for the input `a` in the form `a:`. The user will then input a 1 or 0 (followed by enter). It repeats this for the input `b`. This is the end of the first layer. I am going to assume that the user entered a 1 for both inputs.
It then traces out the path of the first ball (from `a`), which goes along the `\`, across the `_`, into the `A`, and falls down to the spot under the `A`. It then traces out the path for the second ball (from `b`), which goes straight down onto the `_` and terminates. This is the end of the second layer.
Now, before the third layer, since the `_` has had two balls cross over it, it releases one ball. The output `A` has had one ball cross over it, so it outputs `A:1`.
For the third layer, it traces the path of the first ball (from the `_`), which goes though the `C` and falls straight down. The second ball (which fell through the `A`) also falls straight down.
Now, before the fourth layer, since the output `C` had one ball travel over it, it outputs `C:1`.
Since the fourth layer is blank, the program terminates.
The total result should look like
```
a:1 (the user entered the one)
b:1 (same here)
A:1
C:1
```
## The Goal
Your goal is to take a machine from STDIN and simulate it by taking inputs and printing output as needed to STDOUT. The first part of the input to your program will consist of the machine to be run, followed by a blank line. Any input letters encountered should cause your program to prompt for input in the form of the input name followed by a colon. Any output should be shown in the form of the output name, followed by a colon, followed by the number of balls passing over that spot.
This is golf.
## Examples
A wire crossing
```
ab
\/
AB
```
An XOR gate
```
ab1
\_/
C
```
A full adder
```
1 a
\_/ b
\_/
\/
/\
_ __/
\_/
\/c
\\_/
_S1
\ \/
__/
/
_
\__
C
```
[Answer]
## JavaScript (392 423)
Assumes machine is set in a variable called `m`, then alerts the final output.
```
l=m.split(q='\n');o='';for(r=Array(z=l[i=0].length);i<l.length;i++){L=l[i];n=Array(z);for(c=0;c<z;n[c]=N,r[c++]=R){C=L[c];N=~~n[c];R=~~r[c];if(C>'`'){N+=x=~~prompt(C);R+=x;o+=C+': '+x+q}else if(C=='\\'||C=='/'){for(d=c+(g=C=='/'?-1:1);L[d]=='_';r[d]+=R,d+=g);if(L[d]>'@'&L[d]<'[')r[d]+=r[c];n[d]=~~n[d]+R}else if(C<'2')N+=R+=~~C;else if(C!='_')o+=C+': '+R+q}for(c=0;c<z;c++)if(L[c]=='_')n[c]+=(r[c]%2)?0:r[c]>0;r=n}alert(o)
```
Sample source (runs adder machine, see history for less golfed sources): <http://jsfiddle.net/96yLj/12/>
**Spoilers:**
>
> - `r` tracks the # of balls across current row, `n` tracks # of balls across next row.
>
> - Algorithm: process each row character by character, but process `_`'s last.
>
> - Algorithm: `\` -> follow `_` and increase `r` until non-`_`. Same for `/` but in reverse direction. At the end increase `n` for gravity pulling balls down. `g` holds direction.
>
> - `if(L[d]>'@'&L[d]<'[')r[d]+=r[c];` is for the bug mentioned in **Edit 1**. The reason we can't just say `r[d]+=r[c];` is because `\_/` will double-count balls when processing `/`
>
> - `else if(C<'2')` handles both cases `'1'` and `' '`, which `~~C` turns into 1 and 0, respectively.
>
>
>
---
**Edit 1:** Fix bug with ball running over `_` not included in `A` for sample code.
] |
[Question]
[
## Mathemania Specs:
Every piece of Mathemania code starts off with the number `2`. From the `2`, you can do the following operations:
* `e`: Exponentiation. This command's default is squaring the number.
* `f`: Factorial. This command's default is using the single factorial on the number (`using f on 2 = 2! = 2`).
* `r`: Root. This command's default is square-rooting the number.
* `c`: Ceiling function.
* `l`: Floor function.
To generate a number in Mathemania, you must string together these commands, which are performed left-to-right on the number `2`.
## Examples:
```
ef = (2^2)! = 4! = 24
rl = floor(sqrt(2)) = floor(1.4...) = 1
er = sqrt(2^2) = sqrt(4) = 2
efrrc = ceil(sqrt(sqrt((2^2)!)))
= ceil(sqrt(sqrt(24)))
= ceil(sqrt(4.89...))
= ceil(2.21...)
= 3
```
The `e`, `f` and `r` commands can be altered by extra Mathemania commands (which also start off with `2` as its "base" number) to generate different exponentiations, factorials and roots by placing brackets after the altered function and placing the Mathemania commands inside it.
For example, to cube a number instead of squaring it, you can put the command for `3` after `e` like so:
```
e(efrrc) -> cube a number, "efrrc" = 3
```
*NOTE: for our purpose, the factorial command (`f`) start off with `2` as a single factorial. So if you do `f(efrrc)`, that will get evaluated to a double factorial, not a triple factorial.*
*For `n`-factorials (e.g. double factorials = 2-factorial, triple factorial = 3-factorial etc.), the base number is multiplied by the number that is `n` less than it, and `n` less than that, and so on until the final number cannot be subtracted by `n` without becoming `0` or negative.*
*For example:*
```
7!! = 7 * 5 * 3 * 1 = 105 (repeatedly subtract 2, 1 is the last term as
1 - 2 = -1, which is negative)
9!!! = 9 * 6 * 3 = 162 (repeatedly subtract 3, 3 is the last term as
3 - 3 = 0, which is 0)
```
*For more information, see [here](https://en.wikipedia.org/wiki/Factorial#Multifactorials).*
You can insert it anywhere, and it will get treated by Mathemania as a single function:
```
e(efrrc)rc = ceil(sqrt(2^3))
= ceil(2.82...)
= 3
```
You're also allowed to nest these inside one another:
```
e(e(e)) = e(4th power)
= (2^4)th power
= 16th power
```
For an interpreter of Mathemania code, click [here](https://goo.gl/Kl2wdi) (cheers, @BradGilbertb2gills!)
## Task:
Your task is to create a program that, when given a positive integer `n` as input, generates a Mathemania program that when executed, returns `n`.
However, the Mathemania programs that you generate must be as small (golfed) as possible, and your final score is determined by the sum of the number of bytes in the generated Mathemania programs of the sample, which are the integers `10,000` to `10,100`. The lowest score wins.
## Rules and specs:
* Your program must output a valid Mathemania program for any positive integer, but only the numbers between `10,000` and `10,100` will be tested.
* You are not allowed to output Mathemania programs that do not result in an integer. If you do so, your program is disqualified.
* For the commands `e`, `f` and `r`, the Mathemania code inside those functions (e.g. `e(efrrc)`, where the `efrrc` is the code inside the function) must evaluate to a positive integer above `2`. If your program doesn't follow this rule, it is disqualified as well.
* Your program must return a Mathemania program for any one of the 101 test integers in at most 30 minutes on a modern laptop.
* Your program must return the same solution for any integer every time it is run. For example, when a program is given an input `5` and it outputs `efrc`, it must output that every time the input `5` is given.
* You may not hard-code any solutions for any positive integer.
* In order to fully maximise golfing potential in your output, your program should be able to handle arbitrarily large integers. It is not a requirement, though good luck if your language doesn't support this.
This is [metagolf](/questions/tagged/metagolf "show questions tagged 'metagolf'"), so lowest score wins!
[Answer]
# Python 3.5, Score of ??
As of now I don't have the output for all 101 inputs, but once I run the program for all the test cases I will update with my score.
```
from math import *
memoized = {}
same = {}
def _(mathmania, n):
memoized[n] = mathmania
return mathmania
def is_prime(n):
if n == 2:
return True
if n % 2 == 0 or n <= 1:
return False
for divisor in range(3, int(sqrt(n)) + 1, 2):
if n % divisor == 0:
return False
return True
def pair_key(pair):
low, high = pair
diff = high - low
if diff == 0:
return 100
low_done, high_done, diff_done = low in memoized, high in memoized, diff in memoized
if high_done and memoized[high] == None or low_done and memoized[low] == None:
return -1
return (high_done + diff_done + (diff + 1 == low)) * 33 + low / high
def major_pairs(n):
for i in range(n, int(sqrt(n)), -1):
d = n / i
if i - d < d - 1:
break
if d == int(d):
yield (int(d), i)
def fact_key(pair):
i, f = pair
if i in memoized:
if memoized[i] == None:
return -1
return 1
return i / f
def near_fact(n, level):
s = 4
if n in same:
s = same[n]
for i in range(s, n ** 2 ** level):
f = factorial(i)
if f > (n - 1) ** 2 ** level:
if f < (n + 1) ** 2 ** level:
same[n] = i
yield (i, f)
else:
return
def generate_mathmania(n):
if n in memoized and memoized[n] != None:
return memoized[n]
memoized[n] = None
binx = log(n, 2)
if binx == int(binx):
if binx == 2:
return _("e", n)
if binx == 1:
return _("er", n)
if binx == 0:
return _("rl", n)
return _("e(" + generate_mathmania(int(binx)) + ")", n)
sq = sqrt(n)
if sq == int(sq):
return _(generate_mathmania(int(sq)) + "e", n)
low, high = max(major_pairs(n), key=pair_key)
if pair_key((low, high)) == -1:
level = 1
while True:
try:
i, f = max(near_fact(n, level), key=fact_key)
except:
level += 1
continue
if fact_key((i, f)) == -1:
return _(generate_mathmania((n - 1) ** 2 + 1) + "rc", n)
if f == n ** 2 ** level:
return _(generate_mathmania(i) + "f" + "r" * level, n)
if f < n ** 2 ** level:
return _(generate_mathmania(i) + "f" + "r" * level + "c", n)
return _(generate_mathmania(i) + "f" + "r" * level + "l", n)
if low != 1:
if low == high:
return _(generate_mathmania(low) + "e", n)
if high - low == 1:
return _(generate_mathmania(high) + "f", n)
return _(generate_mathmania(high) + "f(" + generate_mathmania(high - low + 1) + ")", n)
good = None
for i in range(n ** 2 - 1, (n - 1) ** 2, -1):
if i in memoized:
return _(generate_mathmania(i) + "rc", n)
if not is_prime(i):
good = i
if good:
return _(generate_mathmania(good) + "rc", n)
for i in range((n + 1) ** 2 - 1, n ** 2, -1):
if i in memoized:
return _(generate_mathmania(i) + "rl", n)
if not is_prime(i):
good = i
if good:
return _(generate_mathmania(good) + "rl", n)
return _(generate_mathmania((n - 1) ** 2 + 1), n)
```
Additionally, I was unable to verify the outputs of some of the test cases I tried due to sheer number size, and at that point @BradGilbertb2gills's online interpreter times out. Hopefully all the outputs work.
] |
[Question]
[
The nutty maths professor wants to encode all of their research using a system sure to fox even the wiliest of their competitors!
To this end the professor has decided to change the base of not just the number that they're writing but every single digit in that number, according to which place the digit finds itself in (counting from the right, starting with 1). For example:
The number 0 has one digit, so it is represented in base 1: 0
The number 1 would have one digit in base ten, but in our professor's system that isn't valid. The first place is reserved for base 1 digits only! This means it must be bumped to the second place where base 2 is allowed: 10
The number 2 requires at least base 3 to be written: 100
But now the number 3 can be written by changing the digit in the second place: 110
and 4 as so: 200
Here are some more examples to help you get the idea:
>
> 5:210
>
>
> 6:1000
>
>
> 7:1010
>
>
> 8:1100
>
>
> 9:1110
>
>
> 10:1200
>
>
> 11:1210
>
>
> 12:2000
>
>
> 13:2010
>
>
> 14:2100
>
>
> 15:2110
>
>
> 16:2200
>
>
> 17:2210
>
>
> 18:3000
>
>
>
Using this system the professor's notes will make no sense to anyone but them, and they can finally ~~take over the world!!!!~~ sleep well at night.
Of course the encoding method must be as obscure as possible.
---
Your task is to write 10 code snippets, each representing one of the base 10 digits
>
> 0 1 2 3 4 5 6 7 8 9
>
>
>
which when combined in the order of the number to be converted will produce a number written in the professor's diabolical numbering system (the output method may be of your choice but must be a human readable number using only the digits 0-9)
For example if my snippets are:
0=MONKEY 1=EXAMPLE, 2=CODE, 3=GOLF and 9=TEST
then
19 = EXAMPLETEST -> 3010
20 = CODEMONKEY -> 3100
21 = CODEEXAMPLE -> 3110
22 = CODECODE -> 3200
23 = CODEGOLF -> 3210
No input numbers with more than 10 digits or negative numbers need to be considered, though if you want to write the code for additional digits you will get extra kudos. This is code golf, so shortest answer (using the combined byte totals of all snippets) wins and the standard loopholes aren't allowed.
ADDENDUM: Before anyone gets started on whether 0 is the correct representation of 0 in base 1 I would like to remind you that this professor is nutty. Live with it.
[Answer]
# Mathematica (REPL environment), 858 total bytes
Here is the 86-byte code snippet for the digit 9:
```
1;ValueQ@a||(a=0;b=3);a=10a+9;b++;FromDigits[a~IntegerDigits~MixedRadix@Range[b,1,-1]]
```
The code snippets for the digits 1 through 8 are identical, except that the 9 is replaced by the appropriate digit. The code snippet for the digit 0 is identical, except that `+9` is simply deleted.
`a~IntegerDigits~MixedRadix@Range[b,1,-1]` computes the list of the factorial-number-system digits of `a`, as long as `b` is at least as large as the number of digits; `FromDigits` converts that list of digits to a regular base-10 integer for the purposes of output. (If any of the list elements exceeds 9, something funny happens.)
In Mathematica's REPL environment, computations can be terminated with semicolons to suppress the output; so only the last output in a semicolon-separated chain will be displayed. We recursively define the integer `a` designated by the snippets, and also a bound `b` on the number of factorial-system digits needed. The command `ValueQ@a||(a=0;b=3)` initializes these variables if they're uninitialized (i.e., in the first snippet) and leaves them alone otherwise; then `a=10a+9;b++` carries out the recursion. Finally, the initial `1;` is for gluing the snippets together: it multiplies intermediate computations by 1 (which we never see anyway).
[Answer]
# Goruby, 790 ~~810~~ ~~980~~
Here's a second attempt, relying on the fact that, in basically any shell, printing a carriage return ("\r") without a newline ("\n") will overwrite the previously printed line, ultimately ensuring that only the last bit printed (that is, the final result) is shown.
This must be run in a shell, e.g. `ruby name_of_file.rb`.
It works for positive numbers of unrestricted length.
The code is ten copies of the snippet below, with `X` (at the top) replaced with the digits from 0-9, one per snippet.
```
->*t{n,d,o="X#{t}".toi,0,''
dw{n,r=n.dm d+=1;o.pr r.ts;n>0}
$>.fu
pr"\r",o
o}
```
That is, the snippet representing (for example) 8 would look like:
```
->*t{n,d,o="8#{t}".toi,0,''
dw{n,r=n.dm d+=1;o.pr r.ts;n>0}
$>.fu
pr"\r",o
o}
```
The challenge states that the snippets need to be "combined" to create represent a multiple-digit number, so, to append a digit to a number, simply place it in the square brackets at the number's end. Thus, the number 103 (in decimal) would be:
```
->*t{n,d,o="1#{t}".toi,0,''
dw{n,r=n.dm d+=1;o.pr r.ts;n>0}
$>.fu
pr"\r",o
o}[->*t{n,d,o="0#{t}".toi,0,''
dw{n,r=n.dm d+=1;o.pr r.ts;n>0}
$>.fu
pr"\r",o
o}[->*t{n,d,o="8#{t}".toi,0,''
dw{n,r=n.dm d+=1;o.pr r.ts;n>0}
$>.fu
pr"\r",o
o}[]]]
```
] |
[Question]
[
I was walking through a pumpkin patch the other day for a birthday party, and noticed the pumpkin vines making a nifty pattern, with whirls, loops, and offshoots. We're going to simulate that here with some ASCII art.
```
(())
\
p--q p-----q
/ \ / \
(()) b--d (())
```
### Vine Construction Rules
* There is only one main vine, composed solely of `\ / - p q b d` characters.
* The vine only travels from left to right across the screen. In other words, suppose you were an ant starting at the left-most vine character. As you progress to the next adjacent character on the main vine, you *must* move one column to the right - never to the left.
* When the vine changes direction, one of the `p q b d` characters are required to simulate a loop. The `p` joins vines traveling northeast to east, the `q` for east to southeast, the `b` from southeast to east, and the `d` from east to northeast. Note that the "loop" of the letter connects to the horizontal vine, and the "stem" of the letter connects to the diagonal.
* The beginning of the vine must be one of `p` or `b` (your choice, doesn't have to be random), and starts horizontally. The end of the vine must be one of `q` or `d` (your choice, doesn't have to be random), and must end horizontally.
* Note that loops can be placed immediately adjacent to other loops (e.g., `pd` is a valid substring of the vine), but that may make it more difficult to place the pumpkins later. You may want to always have one of `- / \` immediately after a loop (as I did in my examples), but it's not required.
### Pumpkin Rules
* The pumpkins are composed solely of `(())` (this exact string).
* From the main vine, the pumpkins are attached by offshoots. These offshoots can only be attached to the `p q b d` loops, are precisely one `\` or `/` in length, and attach to the pumpkin so the "end" of the offshoot is in the middle.
* They can connect above or below the main vine.
* The offshoots can connect going to the "left."
* Only one pumpkin can attach per offshoot, and only one offshoot per loop.
### Randomness
* When traveling horizontally, the vine has a 50% chance of continuing horizontally, a 25% chance of turning northeast, and a 25% chance of turning southeast.
* When traveling diagonally, the vine has a 90% chance of turning horizontal and a 10% chance of continuing diagonally.
* There must be sufficient turns to support the input number of pumpkins, though more turns are allowed.
* Once the vine is constructed, pumpkins can be randomly placed at any corner not already occupied by a pumpkin.
* Pumpkins cannot overlap the vine or other pumpkins.
### The Challenge
Given an input number, output a randomized pumpkin patch following the above rules. Executing the code multiple times with the same input should yield different results. All possible pumpkin patches for a given input number should have some (not necessarily equal) non-zero chance of occurring.
### Input
A single integer `n` representing the number of pumpkins in the patch, in [any convenient format](https://codegolf.meta.stackexchange.com/q/2447/42963). For brevity of code, you can assume the input is `0 < n < 256`.
### Output
The resulting pumpkin patch, either printed/displayed to the screen or returned as a string/string-array/etc.
### Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all the usual rules for golfing apply, and the shortest code (in bytes) wins.
* Use our [standard definition](https://codegolf.meta.stackexchange.com/a/1325/42963) of "Random."
* Either a full program or function are acceptable.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/42963) are forbidden.
* Leading and trailing whitespace / newlines are all completely optional.
### Examples
For input `n = 3`, here are some VALID examples of a pumpkin patch following the above rules (separated by blank newlines).
```
(())
\
p--q p-----q
/ \ / \
(()) b--d (())
(()) (())
\ /
b-q (())
\ /
b-q
p-----------------------q (())
/ \ /
(()) b-q
/
(())
```
Here are some INVALID examples for input `n = 3`, with explanations `#`.
```
(()) (())
/ /
p---q----q
\
(())
# The vine continued horizontally after a loop was placed.
(()(())
\ /
p---q
\
(())
# The pumpkins are both overlapping and sprouting from the same loop.
p----------------q
\ \ \
(()) (()) (())
# The pumpkin is attached to the middle of the vine, not at a loop.
```
[Answer]
## Python 2, 819 bytes
Takes `n` as input
Always places pumkpins on the 'outside' of corners (randomly left/right)
While the vine is constructed, pumpkins are added, and when enough pumpkins are there, the vine stops.
```
r=lambda:__import__('random').random()
s=1
v=[s]*4
U=[-9]
D=[-9]
i=input()
while len(U)+len(D)<i+2:s=[[0,1][r()<.9],[[0,2][r()<.5],1][r()<.5],[2,1][r()<.9]][s];exec['',[['','U+=[len(v)]'][U[-1]<len(v)-7],'',['','D+=[len(v)]'][D[-1]<len(v)-7]][v[-1]-s+1]][r()<.8];v+=[s]*[1,2][v[-1]!=s]
v+=[1]*5
m=M=s=0
for i in v:s+=i-1;m=[m,s][m>s];M=[M,s][M<s]
R=[[' ']*(M-m+5)for x in v]
m=-m+2
R[2][m]='p'
for x in range(3,len(v)-3):X=v[x-1];R[x][m]='/d p-b q\\'[v[x]*3+X];m+=v[x]-1
R[-3][m]='q'
M=[len(a)-len(a.lstrip())for a in map(''.join,R)]
R=map(list,zip(*R))
B,L,a='-/U'
K="\\"*4
W="""exec("for p in "+a+"[1:]:x=M[p];b=r()<.5;exec('R[x"+B+"1][p'+['+1]=\\""+L+"\\"','-1]=\\""+K+"\\"'][b]);i=p-[0,3][b];l='(';exec('R[x"+B+"2][i]=l;i+=1;'*2+'l=\\")\\";')*2")"""
exec W+";B,a='+D';L,K=K,L;"+W
for x in R:print''.join(map(str,x))
```
### Examples:
`n=4`
```
(())
/
p---q
(()) /
\ p--d
p-q / \
\ / (())
b-d
\
(())
```
`n=20`
```
(())
\
p--q
/ \
/ b--q
(()) p----d / \
(()) \ / (()) b-q (())
\ p---d \ \
p--q / \ b--q
\ / (()) / \ (()) (())
b---d (()) b-q \ /
\ \ (()) p-q p---q
(()) \ \ / \ /
b-----------q p-d b-q (())p--d
\ / / \ / / \
b-d (()) b-q (()) (()) p-q p-d (())
/ \ / \ / \ /
(()) b-q p-d b-d
\ \ / \
(())b----d (())
/
(())
```
] |
[Question]
[
If we have a list, say the list `[9, 2, 4, 4, 5, 5, 7]`, we can do a moving average across it.
Taking a window of say, 3 elements, each element is replaced by a window like such: `[[9], [9, 2], [9, 2, 4], [2, 4, 4], [4, 4, 5], [4, 5, 5], [5, 5, 7]]`, and then taking averages, we get `[9.0, 5.5, 5.0, 3.3333333333333335, 4.333333333333333, 4.666666666666667, 5.666666666666667]`.
Pretty simple so far. But one thing you can notice about this is that taking a moving average "smooths out" the list. So this begs the question: how many times does one have to take a moving average to make the list "smooth enough"?
# Your task
Given a list of floats, an integer window size, and a float, output how many times one has to take the moving average to get the standard deviation less than that float. For those that don't know, standard deviation measures how un-smooth a set of data is and can be calculated by the following formula:
[](https://i.stack.imgur.com/LGVuB.png)
For example, using our earlier list and a max stddev of `.5`, we get `8` iterations that look like this:
```
[9.0, 5.5, 5.0, 3.3333333333333335, 4.333333333333333, 4.666666666666667, 5.666666666666667]
[9.0, 7.25, 6.5, 4.6111111111111116, 4.2222222222222223, 4.1111111111111107, 4.8888888888888893]
[9.0, 8.125, 7.583333333333333, 6.1203703703703702, 5.1111111111111107, 4.3148148148148149, 4.4074074074074074]
[9.0, 8.5625, 8.2361111111111107, 7.2762345679012341, 6.2716049382716044, 5.1820987654320989, 4.6111111111111107]
[9.0, 8.78125, 8.5995370370370363, 8.024948559670781, 7.2613168724279831, 6.2433127572016458, 5.3549382716049374]
[9.0, 8.890625, 8.7935956790123466, 8.4685785322359397, 7.9619341563786001, 7.1765260631001366, 6.2865226337448554]
[9.0, 8.9453125, 8.8947402263374489, 8.7175997370827627, 8.4080361225422955, 7.8690129172382264, 7.141660951074531]
[9.0, 8.97265625, 8.9466842421124824, 8.8525508211400705, 8.6734586953208357, 8.3315495922877609, 7.8062366636183507]
```
and end with a stdev of `0.40872556490459366`. You just output `8`.
# But there's a catch:
**The answer does not have to be nonnegative!** If the initial list already satisfies the maximum stddev, you have to see how many iterations you can "go backwards" and undo the moving average and still have the list satisfy the max stddev. Since we are truncating the windows for the initial `n` data points and not dropping those, there is enough data to reverse a moving average.
For example, if we start with the list `[9.0, 8.99658203125, 8.9932148677634256, 8.9802599114806494, 8.9515728374598496, 8.8857883675880771, 8.7558358356689627]` (taken from our earlier example with 3 more moving averages done to it) and the same window size and max stddev, you will output `-3` because you can reverse the moving average at most `3` times.
Any reasonable I/O format is fine.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in **bytes** wins!
# Test Cases
```
[9, 2, 4, 4, 5, 5, 7], 3, .5 -> 8
[9, 2, 4, 4, 5, 5, 7], 3, .25 -> 9
[9.0, 8.99658203125, 8.9932148677634256, 8.9802599114806494, 8.9515728374598496, 8.8857883675880771, 8.7558358356689627], 3, .5 -> -3
[1000, 2, 4, 4, 5, 5, 7], 7, .25 -> 13
[1000.0, 999.98477172851563, 999.96956668760447, 999.95438464397, 999.90890377378616, 999.83353739825293, 999.69923168916694], 4, 7 -> -6
```
[Answer]
# Wolfram - 236
Pretty clunky right now, but at least it works.
```
f[x_,w_,c_]:=Module[{l=Length,d=Sqrt@CentralMoment[#,2]&,n,a,b,t,r},n=Length@x;a=Normalize/@LowerTriangularize@Array[Boole[Abs[#1-#2]<w]&,{n,n}]^2;{b,t,r}=If[d@x>c,{a,d@#>c&,l@#-1&},{Inverse@a,d@#<c&,-l@#+2&}];r@NestWhileList[b.#&,x,t]]
```
] |
[Question]
[
Jason has a big JSON but it's unreadable, so he needs to prettify it.
## Formatting Spec
The JSON has 4 different types:
* Numbers; Just `0-9`
* Strings; Double quoted `"` strings escaped with `\`
* Arrays; Delimited by `[]`, with items separated by `,`, items can be any of these types
* Objects; Delimited by `{}`, format is `key: value` where key is a string and value is any of these types
Spacing
* Arrays should have exactly one space after the commas between items
* Objects should have have just one space between the key and the value, after the `:`
Indentation
* Each nesting level is indented 2 more than the previous
* Each object key/value pair is always on its own line. Objects are indented
* An array is indented across multiple lines if it contains another array or object. Otherwise the array remains on one line
## Rules
* Built-ins which trivialize this task are **not** allowed.
* As always standard loopholes are disallowed
## Examples
```
[1,2,3]
[1, 2, 3]
```
```
{"a":1,"b":4}
{
"a": 1,
"b": 4
}
```
```
"foo"
"foo"
```
```
56
56
```
```
{"a":[{"b":1,"c":"foo"},{"d":[2,3,4,1], "a":["abc","def",{"d":{"f":[3,4]}}]}]}
{
"a": [
{
"b": 1,
"c": "foo"
},
{
"d": [2, 3, 4, 1],
"a": [
"abc",
"def",
{
"d": {
"f": [3, 4]
}
}
]
}
]
}
```
```
[2,["foo123 ' bar \" baz\\", [1,2,3]]]
[
2,
[
"foo123 ' bar \" baz\\",
[1, 2, 3]
]
]
```
```
[1,2,3,"4[4,5]"]
[1, 2, 3, "4[4,5]"]
```
```
[1,2,3,{"b":["{\"c\":[2,5,6]}",4,5]}]
[
1,
2,
3,
{
"b": ["{\"c\":[2,5,6]}", 4, 5]
}
]
```
[Answer]
## JavaScript (ES6), 368 bytes
```
f=(s,r=[],i='',j=i+' ',a=[])=>s<'['?([,,r[0]]=s.match(s<'0'?/("(?:\\.|[^"])*")(.*)/:/(\d+)(.*)/))[1]:s<'{'?(_=>{for(;s<']';s=r[0])a.push(f(s.slice(1),r,j));r[0]=s.slice(1)})()||/\n/.test(a)?`[
${j+a.join(`,
`+j)}
${i}]`:`[${a.join`, `}]`:(_=>{for(a=[];s<'}';s=r[0])a.push(f(s.slice(1),r,j)+': '+f(r[0].slice(1),r,j));r[0]=s.slice(1)})()||`{
${j+a.join(`,
`+j)}
${i}}`
```
Less golfed:
```
function j(s, r=[], i='') { // default to no indentation
if (s < '0') { // string
let a = s.match(/("(?:\\.|[^"])*")(.*)/);
r[0] = a[2]; // pass the part after the string back to the caller
return a[1];
} else if (s < '[') { // number
let a = s.match(/(\d+)(.*)/);
r[0] = a[2]; // pass the part after the string back to the caller
return a[1];
} else if (s < '{') { // array
let a = [];
while (s < ']') { // until we see the end of the array
s = s.slice(1);
a.push(j(s, r, i + ' ')); // recurse with increased indentation
s = r[0]; // retrieve the rest of the string
}
r[0] = s.slice(1); // pass the part after the string back to the caller
if (/\n/.test(a.join())) { // array contained object
return '[\n ' + i + a.join(',\n ' + i) + '\n' + i + ']';
} else {
return '[' + a.join(', ') + ']';
}
} else { // object
let a = [];
while (s < '}') { // until we see the end of the object
s = s.slice(1);
let n = j(s, r, i + ' ');
s = r[0].slice(1);
let v = j(s, r, i + ' ');
a.push(n + ': ' + v);
s = r[0]; // retrieve the rest of the string
}
r[0] = s.slice(1); // pass the part after the string back to the caller
return '{\n ' + i + a.join(',\n ' + i) + '\n' + i + '}';
}
}
```
] |
[Question]
[
The [SAS programming language](https://en.wikipedia.org/wiki/SAS_language) is a clunky, archaic language dating back to 1966 that's still in use today. The original compiler was written in [PL/I](https://en.wikipedia.org/wiki/PL/I), and indeed much of the syntax derives from PL/I. SAS also has a preprocessor macro language which derives from [that of PL/I](https://en.wikipedia.org/wiki/PL/I_preprocessor) as well. In this challenge, you'll be interpreting some simple elements of the SAS macro language.
In the SAS macro language, macro variables are defined using the `%let` keyword and printing to the log is done with `%put`. Statements end with semicolons. Here are some examples:
```
%let x = 5;
%let cool_beans =Cool beans;
%let what123=46.lel"{)-++;
```
Macro variable names are case insensitive and always match the regular expression `/[a-z_][a-z0-9_]*/i`. For the purposes of this challenge, we'll say the following:
* Macro variables can only hold values consisting entirely of printable ASCII characters *except* `;`, `&`, and `%`
* There will be no leading or trailing spaces in the values
* The values will never be more than 255 characters long
* Values may be empty
* Brackets and quotes in the values may be unmatched
* There can be any amount of space before and after the `=` in the `%let` statement and this space should be ignored
* There can be any amount of space before the terminal `;` in the `%let` statement and this space should similarly be ignored
When a macro variable is called, we say it "resolves" to its value. Macro variables are resolved by prepending `&`. There is an *optional* trailing `.` that denotes the end of the identifier. For example,
```
%put The value of x is &X..;
```
writes `The value of x is 5.` to the log. Note that two periods are required because a single period will be consumed by `&X.` and resolve to `5`. Also note that even though we defined `x` in lowercase, `&X` is the same as `&x` because macro variable names are case insensitive.
Here's where it gets tricky. Multiple `&`s can be strung together to resolve variables, and `&`s at the same level of nesting resolve at the same time. For example,
```
%let i = 1;
%let coolbeans1 = broseph;
%let broseph = 5;
%put &&coolbeans&i; /* Prints broseph */
%put &&&coolbeans&i; /* Prints 5 */
```
The innermost `&`s resolve first, and resolution continues outward. Variable name matching is done greedily. In the second `%put` statement, the processor makes the following steps:
1. `&i` resolves to `1`, and the innermost leading `&` is consumed, giving us `&&coolbeans1`
2. `&coolbeans1` resolves to `broseph`, giving us `&broseph`
3. `&broseph` resolves to `5`.
If there are trailing `.`s, only a single `.` is consumed in resolution, even if there are multiple `&`s.
### Task
Given between 1 and 10 `%let` statements separated by newlines and a single `%put` statement, print or return the result of the `%put` statement. Input can be accepted in any standard way.
You can assume that the input will always be valid and that the `%let` statements will preceed the `%put` statement. Variables that are defined will not be redefined in later `%let` statements.
If actually run in SAS, there would be no issues with variables resolving to variables that don't exist and everything will be syntactically correct as described above.
### Examples
1. Input:
```
%let dude=stuff;
%let stuff=bEaNs;
%put &&dude..;
```
Output:
```
bEaNs.
```
2. Input:
```
%let __6 = 6__;
%put __6&__6;
```
Output:
```
__66__
```
3. Input:
```
%let i=1;
%let hOt1Dog = BUNS;
%put &&HoT&i.Dog are FUNS&i!");
```
Output:
```
BUNS are FUNS1!")
```
4. Input:
```
%let x = {*':TT7d;
%put SAS is weird.;
```
Output:
```
SAS is weird.
```
5. Input:
```
%let var1 = Hm?;
%let var11 = var1;
%let UNUSED = ;
%put &&var11.....;
```
Output:
```
Hm?....
```
Note that `&&var11` matches `var11` since name matching is greedy. If there had been a `.`, i.e. `&&var1.1`, then `var1` would be matched and the extra 1 wouldn't be part of any name.
This is code golf, so the shortest solution in bytes wins!
[Answer]
# [Python 3](https://docs.python.org/3/), ~~354~~ ~~341~~ 336 bytes
```
import re
S=re.sub
def f(x):
r=x.splitlines();C=r[-1].strip('%put ');D=0
while D!=C:
D=C
for a in sorted([l.strip('%let ').replace(" ","").split(';')[0].split('=')for l in r[:-1]],key=lambda y:-len(y[0])):
s=1
while s:C,s=re.subn('&'+a[0]+'(\.?)',a[1]+'üòç\\1',S('üòç+\.([^\.])','\\1',C),0,re.I)
return S('üòç+\.?','',C)
```
[Try it online!](https://tio.run/##dVLLjpswFF3DV3gsFdsNsYIqTSWQFbUw1XSTLkhWkEakmMYqAWRDJ1G/ofvu@ov9g/SaYdJOpVry4557zrnXhu7cH9rm1eWijl2re6SlmwotuRn2bikrVNETC11HixM3Xa36WjXSUBbFQmfzYMtNr1VHyYtu6BFhUSIWrvNwULVEyY2IQekkIoa1ajUqkGqQgSqypFl9ldbSSrmWXV18khQj7GPMHstREhGWLbZPkSDMOtXWSWchdLD1v8izqIvjvizQOZzXsqFnUDDbtuMYEdjtsSUTxr6ZbtdQ4pFZAcwZoTlfMuIXWQDBr58/vud5QPyUjudZzmn2MedbYJAxETN/4YPLewYPI/tBN@gPdwksS7kYgwTKMMbjBcuhlML0Q1VF7giMZ7G/K1YGEPt8npcAifMINL77JNztbsHndrebWBB7MJ@TlAgm28OHPkjazyB5u1mlV@f7du0pbhOFlugdpDx1g9lzlxOovr0k4Xr9upyU6ZsUKYMepNLlP419LXSAEEjQ/XE5VbdYAJDdJ2iz2qR3CWDXXkYSt8Mabl37Qc34a5jQBUfUadX0tKKGsb9iPP/vwMzSLr8B "Python 3 – Try It Online")
edit: some easy shortening
edit: reverse sort by -len(...) instead of [::-1] (5 bytes), thanks to Jonathan Frech!
## Ungolfed
```
import re
S=re.sub # new name for the function re.sub()
def f(x):
r=x.splitlines() # input string to list of rows
C=r[-1].strip('%put ') # get the string to put (from the last row)
D=0
while(D!=C): # iterate until the result does not change
D=C
for a in : # iterate over the list of variables
sorted( ,key=lambda y:len(y[0]),reverse=1) # sort list for greediness by decreasing var.name lengths
[l.strip('%let ') # cut the 'let' keyword
.replace(" ","") # erase spaces
.split(';')[0] # cut parts after ';'
.split('=') # create [variable_name,value] list
for l in r[:-1]] # for each row but last
s=1
while(s): # iterate until the result does not change
C,s=re.subn( # substitute
'&'+a[0]+'(\.?)', # &varname. or &varname
a[1]+'üòç\\1', # to valueüòç. or valueüòç
S('üòç+\.([^\.])','\\1',C), # in the string we can get from C erasing (üòç's)(.) sequences if the next char is not .
0,re.I) # substituting is case insensitive
return S('üòç+\.?','',C) # erase smileys and one .
```
] |
[Question]
[
Easy As ABC, also known as "End View", is a puzzle where you are given an empty grid with letters around it; you must partially fill in the grid so that exactly one of each letter is in every row and column; in addition, letters at the end of a row (or column) must be the first letter visible in that row (or column) from that direction. Your goal in this code golf will be to solve an Easy As ABC puzzle.
For example, here is an Easy As ABC puzzle [from this year's MIT Mystery Hunt](http://huntception.com/puzzle/paint_it_black/) using the letters MIC:
[](https://i.stack.imgur.com/B7h5i.png)
The solution is:
[](https://i.stack.imgur.com/2EXwT.png)
(Sorry about the artifacts on the Cs; I tried to edit out the irrelevant information from the rest of the puzzle.)
# I/O
Input will be an array of strings or a string possibly with delimiters. It will start in the top left corner and go clockwise. For instance, the above puzzle could be input like this:
```
".CMM.M|....IM|.....I|C.ICI."
```
Output should be the solved grid, with or without the border. It can be as an array of chars, array of strings, or any other convenient format. The same "blank" character must be accepted as input and displayed as output, but that blank character may be anything. If they are single strings, both input and output must have the same separator (between sides for input and rows for output) or no separator at all.
For unsolvable puzzles, you must output something that is not mistakable for a solution. You may assume that no puzzle has more than one solution.
You must allow any number of letters and any size grid; *all* used letters will appear in the border of the grid.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): as usual, shortest code wins!
# Test Cases
```
"T.AA..|.T.TSS|..TST.|A...SS"
"R.RU..|B.B..B|.UR.UB|UR..B."
"N...NK|E.NK.K|..KK..|....EK"
"CA..DBD|.B..CC.|.D.DEB.|DB.A..A"
"...DDEBE|DC..EBBD|BA..ABF.|E..FECDE"
```
[Answer]
# PHP, 1111 Bytes
minus the Bytes removing newlines
The [Online version](http://sandbox.onlinephpfunctions.com/code/3a4a6897506590bd31bea9f9aecd69ffa7f8dd59) works only with the Testcases with a length of 6
## short workaround
make all permutations
fill 2 arrays with the permutations $x $y
change between two functions so long till only 1 solution in the x array foreach line exists
function i:find intersections in the grid and drop permutations
function c:check the colums in each array of unique charcters and remove permutations in the other lines for array $x and $y
```
$p=[];p(array_pad(($s="str_split")(substr(count_chars($a=$argn,3),1,-1)),$l=(strlen($a)-3)/4," "));
$e=explode("|",$a);$e[3]=strrev($e[3]);$e[2]=strrev($e[2]);
$x=$y=array_fill(0,$l,$p);$g="preg_grep";$c="array_column";$o="join";
foreach($q=range(0,$l-1)as$i){
$e[0][$i]=="."?:$y[$i]=$g("#^\s*{$e[0][$i]}#",$y[$i]);
$e[2][$i]=="."?:$y[$i]=$g("#{$e[2][$i]}\s*$#",$y[$i]);
$e[3][$i]=="."?:$x[$i]=$g("#^\s*{$e[3][$i]}#",$x[$i]);
$e[1][$i]=="."?:$x[$i]=$g("#{$e[1][$i]}\s*$#",$x[$i]);}
for(;array_sum(($m="array_map")("count",$x))>$l;){
foreach($q as$i)foreach($q as$j){
$k=array_intersect($c($m($s,$x[$i]),$j),$c($m($s,$y[$j]),$i));
$y[$j]=$g("#^.{{$i}}(".$o("|",$k).")#",$y[$j]);
$x[$i]=$g("#^.{{$j}}(".$o("|",$k).")#",$x[$i]);
foreach(["x","y"]as$z){
$u=array_unique($c($m($s,${"$z"}[$i]),$j));
if(count($u)==1&&end($u)!=" "){$w=end($u);
foreach($q as$h){
if($i!=$h)${"$z"}[$h]=$g("#^.{{$j}}{$w}#",${"$z"}[$h],1);}}
}}}
echo$o("\n",$m($o,$x));
function p($c,$b=[]){global$p;
if(($c)){$n=[];while($c){
$e=array_pop($c);
p(($m="array_merge")($c,$n),$m($b,[$e]));
$n[]=$e;
}}else in_array($b=join($b),$p)?:$p[]=$b;}
```
] |
[Question]
[
# üê∏üê∏
You must make the shortest program to always find the optimal solution to a simplified Frogger game on a 9x9 grid.
**Course Elements:**
* `L` - Log (Length: 3-4). When you hop on a log, it carries you with it.
* `V` - Vehicle (Length: 1-2)
* Speed (1-2): On the left hand side of the row will be the speed that elements in the row move.
* Spaces: There will **always** be at least two spaces between elements.
* Direction: In both the Vehicle and the Log sections, the direction of movement in each lane alternates between left and right.
**Course Structure:**
* If it's capital, it goes right; if it's lowercase, it goes left. All elements in a row go the same direction. As soon as part of an element goes off the screen, it will appear on the opposite side of the screen.
* The first row is a safe zone. The frog starts at `F`, which is always the same spot.
* The next 3 rows are roads with Vehicles.
* The next row is a safe zone.
* The next 3 rows are water (touching water == death) with Logs.
* Once you reach the `W` lane you win.
* If the frog dies it goes back to `F`
**Player Controls:**
* `L` - Left
* `R` - Right
* `U` - Up
* `D` - Down
* `W` - Wait
After you move, another frame passes. (Note that the frame passes after your move, not at the same time as your move.) Your program must give the optimal solution as a sequence of characters such as `URWUUL`. If a course has no solution, your program should output `N`.
**Examples:** (Since I did these by hand I don't know if they are optimal solutions.)
```
0WWWWWWWWW
1  lll    
2  LLLL   
2  llll   
0         
1  vv  vv 
1  V  V   
1   vv    
0    F    
```
Solution: `WUWUUURWUULWUU`
```
0WWWWWWWWW
2   lll   
1   LLLL  
1   lll   
0         
2   vv    
1  VV     
2   vv    
0    F    
```
Solution: `WUWUWUUWUUWWUU`
```
0WWWWWWWWW
2   llll  
2   LLL   
1   llll  
0         
2  v   vv 
1  VV  VV 
1  v  v   
0    F    
```
Solution: `WWUUUURURRWWUUU`
```
0WWWWWWWWW
2 llll
2 LLL
1 lll
0
1 vv v
2 V V V
2 v v v
0 F
```
Solution: `N` (No way to get past first row.)
Test these in the snippet by pasting the course into the textbox and pushing "Load Course". Then paste the solution into "Input" and push submit.
**Snippet:** It's hard to make test cases, so I made this snippet which lets you see if your program can solve randomly-generated courses. For testing purposes, all you need to do is input your program's solution (e.g. `LRUWL...`) into the "Input" section and push submit. To reset the course back to it's original state push "Reset". Let me know if you find any bugs.
```
var timer;
var f_x, f_y;
var replaced;
var copy;
document.body.onkeyup = function(e) {
var a = document.activeElement;
if (a !== controls && a !== data) hop(e.keyCode);
};
function setup() {
stop();
var rows = game.children;
rows[0].innerHTML = "0WWWWWWWWW";
load(logs, "L");
rows[2].innerHTML = "0 ";
load(cars, "V");
rows[4].innerHTML = "0 F ";
copy = game.innerHTML;
save();
f_x = 5;
f_y = 9;
replaced = " ";
}
function save() {
data.value = "";
for (var i = 1; i <= 9; i++) {
data.value += getRow(i).textContent;
if (i < 9) data.value += "\n";
}
}
function extLoad() {
stop();
var rows = data.value.split("\n");
replaced = " ";
for (var i = 0; i < rows.length; i++) {
var r = getRow(i + 1);
r.innerHTML = rows[i].replace(/ /g, " ");
if (rows[i].indexOf("V") !== -1 || rows[i].indexOf("L") !== -1) r.className = "right";
else if (rows[i].indexOf("v") !== -1 || rows[i].indexOf("l") !== -1) r.className = "left";
var f = rows[i].indexOf("F");
if (f !== -1) {
f_y = i + 1;
f_x = f;
}
}
copy = game.innerHTML;
}
function reset() {
stop();
game.innerHTML = copy;
f_x = 5;
f_y = 9;
replaced = " ";
}
function play() {
if (!timer) {
timer = setInterval(next, 1500);
}
}
function stop() {
if (timer) {
clearInterval(timer);
timer = null;
}
}
function input(i) {
var s = controls.value;
if (i === 0) {
stop();
sub.disabled = true;
}
if (s[i] === "L") hop(65);
else if (s[i] === "U") hop(87);
else if (s[i] === "R") hop(68);
else if (s[i] === "D") hop(83);
next();
if (i < s.length - 1) setTimeout(function() {
input(i + 1);
}, 750);
else sub.disabled = false;
}
function load(part, code) {
for (var r = 0; r < 3; r++) {
var row = part.children[r];
var s = "";
var dir = r % 2;
row.className = dir === 1 ? "right" : "left";
s += Math.floor(Math.random() * 2) + 1;
var end = 0;
for (var c = 0; c < 9-end;) {
var spaces = Math.min(9 - end - c , Math.floor(Math.random() * 2) + 2);
if(c === 0 && end===0) {
spaces = Math.floor(Math.random()*4);
end = Math.max(0,2-spaces);
}
s += " ".repeat(spaces);
c += spaces;
var type = "";
var len = 0;
var rand = Math.floor(Math.random() * 2);
if (code === "L") {
type = dir === 1 ? "L" : "l";
len = rand + 3;
} else {
type = dir === 1 ? "V" : "v";
len = rand + 1;
}
if (c + len > 9-end) continue;
s += type.repeat(len);
c += len;
}
row.innerHTML = s + " ".repeat(end);
}
}
function next() {
move(logs);
move(cars);
}
function move(part) {
var rows = part.children;
for (var i = 0; i < rows.length; i++) {
var s = rows[i].textContent;
var f = s.indexOf("F") !== -1;
if (f) {
replace(f_y, f_x, false);
s = rows[i].textContent;
}
var speed = s[0];
var stuff = s.substring(1);
var v = vel(speed, rows[i].className);
rows[i].textContent = s[0] + shift(stuff, speed, rows[i].className);
if (f) {
if (part === logs) {
f_x += v;
if (f_x < 1 || f_x > 9) {
go(5 - f_x, f_y - 9);
return;
}
}
replace(f_y, f_x, true);
s = rows[i].textContent.substring(1);
var c = f_x + v;
var t = "";
if (c > 9) t = s.substring(f_x) + s.substring(0, c - 9);
else if (c < 0) t = s.substring(0, f_x) + s.substring(9 + c);
else t = v > 0 ? s.substring(f_x, c) : s.substring(c, f_x);
if (t.indexOf("V") !== -1 || t.indexOf("v") !== -1) {
go(5 - f_x, f_y - 9);
}
}
}
}
function vel(mag, dir) {
var d = dir === "right" ? 1 : -1;
var m = parseInt(mag);
return d * m;
}
function shift(s, n, d) {
n = parseInt(n);
for (var i = 0; i < n; i++) {
if (d === "left") {
s = s.substring(1) + s.substring(0, 1);
} else {
s = s.substring(s.length - 1) + s.substring(0, s.length - 1);
}
}
return s;
}
function hop(k) {
if (k === 65) go(-1, 0);
else if (k === 87) go(0, 1);
else if (k === 68) go(1, 0);
else if (k === 83) go(0, -1);
}
function go(x, y) {
replace(f_y, f_x, false);
f_y -= y;
f_x += x;
replace(f_y, f_x, true);
if (f_x < 1 || f_x > 9 || f_y > 9) {
go(5 - f_x, f_y - 9);
return;
}
if (f_y == 1) {
alert("win!");
go(5 - f_x, f_y - 9);
}
}
function replace(y, x, f) {
var row = getRow(y);
if (!row) return false;
var s = row.textContent;
if (x < 1 || x >= s.length) return false;
if (f) {
replaced = s[x];
if (replaced === "V" || replaced === "v" || (replaced.charCodeAt(0) === 160 && y < 5)) {
go(5 - f_x, f_y - 9);
} else {
row.textContent = s.substring(0, x) + "F" + s.substring(x + 1);
}
} else {
row.textContent = s.substring(0, x) + replaced + s.substring(x + 1);
}
}
function getRow(y) {
if (y < 1 || y > 9) return false;
if (y === 1) return game.firstChild;
if (y === 9) return game.lastChild;
if (y > 5) return cars.children[y - 6];
if (y < 5) return logs.children[y - 2];
return game.children[2];
}
```
```
<body onload="setup()"><code id="game"><div></div><div id="logs"><div></div><div></div><div></div></div><div></div><div id="cars"><div></div><div></div><div></div></div><div></div></code>
<input type="button" value="Step" onclick="next()" />
<input type="button" value="Pause" onclick="stop()" />
<input type="button" value="Play" onclick="play()" />
<input type="button" value="Reset" onclick="reset()" />
<input type="button" value="New Course" onclick="setup()" />
<div>Controls: WASD</div>
<div>Input:
<input type="text" id="controls" />
<input type="submit" onclick="input(0)" id="sub" />
</div>
<div>
<textarea id="data" rows=9 cols=12></textarea>
<input type="button" onclick="extLoad()" value="Load Course" />
<input type="button" onclick="save()" value="Save Course" />
</div>
</body>
```
**Where to Start:**
* [A\*](https://en.wikipedia.org/wiki/A*_search_algorithm)
* [Dijkstra's Algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm)
**Related:**
* [Frogger Champion](https://codegolf.stackexchange.com/questions/37975/frogger-champion)
* [Frogger-ish game](https://codegolf.stackexchange.com/questions/26824/frogger-ish-game)
**See also:**
* [Play Frogger](http://www.froggerclassic.appspot.com)
[Answer]
## Javascript, 854 bytes
```
function f(w){h=[];z=[];for(y=0;y<9;y++){l=w.split('\n')[y];r={s:parseInt(l[0]),d:1,e:[]};for(x=0;x<9;x++){c=l[1+x];if(c=='v'||c=='l')r.d=-1;r.e.push(c);}z.push(r);}h.push(z);h.push(z);for(g=2;g<40;g++){z=JSON.parse(JSON.stringify(z));for(y=0;y<9;y++){r=z[y];if(r.s>0&&(g%2==0||r.s==2)){i=0;t=0;if(r.d==-1){t=r.e[0];for(i=0;i<8;i++)r.e[i]=r.e[i+1];r.e[i]=t;}else{t=r.e[8];for(i=8;i>0;i--)r.e[i]=r.e[i-1];r.e[i]=t;}}}h.push(z);}j=15;k="";m(0,4,8,"","");return k==""?"N":k;function m(s,a,b,u,v){if(s<j){q={'U':[0,-1],'D':[0,1],'L':[-1,0],'R':[1,0]}[u];if(q)a+=q[0],b+=q[1];v+=u;if(!b){j=s;k=v;return;}if(s>0){for(i=0;i<3;i++){z=h[s*2+i-2];r=z[b];if(i&&(i==1||r.s==2)&&r.e[a].toUpperCase()=='L')a+=r.d;if(a<0||a>8||b>8)return;z=h[s*2+i-1];e=z[b].e;if(e[a].toUpperCase()=='V'||(b<4&&e[a].toUpperCase()!='L'))return;}}t="UWRLD";for(x in t)m(s+1,a,b,t[x],v);}}}
```
Ungolfed
```
function solve(input) {
var grids = [];
var maxgrid = 40;
// load input
var grid = [];
var lines = input.split('\n');
for (var y = 0; y < 9; y++) {
var line = lines[y];
var row = {
speed: parseInt(line[0]),
direction: 1,
cells: []
}
for (var x = 0; x < 9; x++) {
var c = line[1 + x];
if (c == 'v' || c == 'l')
row.direction = -1;
row.cells.push(c);
}
grid.push(row);
}
grids.push(grid);
grids.push(grid);
// animate grids
for (var g = 2; g < maxgrid; g++) {
grid = JSON.parse(JSON.stringify(grid));
for (var y = 0; y < 9; y++) {
var row = grid[y];
if (row.speed > 0 && (g % 2 == 0 || row.speed == 2)) {
if (row.direction == -1) {
var i, temp = row.cells[0];
for (i = 0; i < 8; i++)
row.cells[i] = row.cells[i + 1];
row.cells[i] = temp;
}
else {
var i, temp = row.cells[8];
for (i = 8; i > 0; i--)
row.cells[i] = row.cells[i - 1];
row.cells[i] = temp;
}
}
}
grids.push(grid);
}
var best = 15;
var best_moves = "";
var forceExit = false;
move(0, 4, 8, "", "");
return best_moves == "" ? "N" : best_moves;
function move(step, fx, fy, dir, moves) {
if (step >= best)
return "die";
switch (dir) {
case 'U':
fy--;
break;
case 'D':
fy++;
break;
case 'L':
fx--;
break;
case 'R':
fx++;
break;
}
if (dir != '')
moves += dir;
if (fy == 0) {
best = step;
best_moves = moves;
return "win";
}
if (step > 0) {
for (var i = 0; i < 3; i++) {
var grid = grids[step * 2 + i - 2];
if (i > 0 && (i == 1 || row.speed == 2)) {
var row = grid[fy];
if (row.cells[fx].toUpperCase() == 'L')
fx += row.direction;
}
if (fx < 0 || fx > 8 || fy > 8)
return "die";
var grid = grids[step * 2 + i - 1];
var cells = grid[fy].cells;
if (cells[fx].toUpperCase() == 'V')
return "die";
if (fy < 4 && cells[fx].toUpperCase() != 'L')
return "die";
}
}
move(step+1, fx, fy, 'U', moves);
move(step+1, fx, fy, 'W', moves);
move(step+1, fx, fy, 'R', moves)
move(step+1, fx, fy, 'L', moves);
move(step+1, fx, fy, 'D', moves)
}
}
```
I'm only testing for Up, Wait and Right in the example to speed things up:
[JSFiddle](https://jsfiddle.net/k5z32a7v/)
] |
[Question]
[
[Mahjong](https://en.wikipedia.org/wiki/Mahjong) is a tile game that is immensely popular in Asia. It is typically played with four players, and the goal of the game is to be the first person to complete a valid hand using the tiles. In mahjong there are three tile suits plus honour tiles — for this challenge we will only consider hands formed using tiles from a single suit.
Tiles are numbered from `1` to `9`, and there are exactly four copies of each tile. A valid hand consists of four sets of three and a pair, for a total of fourteen tiles.
A set of three can be either:
* A triplet, three of the same tile (e.g. `444`), or
* A sequence of three consecutive tiles (e.g. `123` or `678` but not `357`). Sequences do not wrap (so `912` is invalid).
A pair is simply two identical tiles (e.g. `55`).
# The challenge
Given a valid hand of fourteen tiles, determine its score based on the following criteria:
```
Condition Description Point/s
-------------------------------------------------------------------------------
Straight Contains the sequences 123 456 789 1
Identical sequences Contains two identical sequences 1
All simples Only 2-8, no 1s or 9s 1
All sequences All sets of three are sequences 1
All triplets All sets of three are triplets 2
Flush Single-suit hand (always applies) 5
```
*(Scoring here is based off Japanese mahjong rules, but heavily simplified to make the spec less messy.)*
The score of a hand is the sum of points for the conditions it satisfies. If a hand can be decomposed in more than one way, take the highest scoring decomposition.
The input hand is guaranteed to be valid, i.e. fourteen tiles from 1 to 9 and each tile appearing at most four times, and may be assumed to be already sorted. Input is a list of digits (as a string or a single flat list of integers) via STDIN, function argument or command line. Output may be to STDOUT or return value.
# Test cases
```
22233355777888 -> 8 # 222 333 55 777 888, flush + all simp. + all trip.
11112345678999 -> 6 # 111 123 456 789 99, flush + straight
11123456788999 -> 5 # 111 234 567 88 999, flush only (no straight)
23344455566788 -> 7 # 234 345 456 567 88, flush + all simp. + all seq.
33334444555566 -> 8 # 33 345 345 456 456, flush + all simp. + all seq. + identical seq.
11122233377799 -> 7 # 111 222 333 777 99, flush + all trip. (no identical seq.)
12344556678889 -> 8 # 123 456 456 789 88, flush + all seq. + straight + identical seq.
11344556678999 -> 5 # 11 345 456 678 999, flush only (no identical seq.)
22233344455566 -> 8 # 222 333 444 555 66, flush + all simp. + all trip.
11112233344555 -> 5 # 111 123 234 345 55, flush only
```
For the fifth example, despite having two pairs of identical sequences, only one needs to be present to attain the point. The decomposition `345 345 345 345 66` would score the same, while `333 345 444 555 66` scores worse.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the solution in the fewest bytes wins. [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny/) apply.
---
*Related challenge: [What are you waiting for? (A mahjong solver)](https://codegolf.stackexchange.com/questions/39896/what-are-you-waiting-for-a-mahjong-solver)*
[Answer]
# J (241 byes)
You need the latest version of [J](http://jsoftware.com/) installed.
```
i=:>:@i.9
q=:,/^:4>@:{(i.9);(i.;i.;i.;i.)16
s=:3 :'(>./((5+([:(*./)(3*i.3)&e.)+(-.@:(-:~.))+((*./)@:(6&>:))+2*((*./)@:(6&<)))"1(}."1(y(-:/:~"1)"1((([:{&(i,.i){.),[:,/[:{&(((>:@i.7)+"0 1(i.3)),|:3 9$i)}.)"1 q))#q)))+([:(*./)[:-.((1 9)&e.))y'
```
---
Call the function `s` with a list of integers. For example, the following example script verifies the test cases above:
```
#!/usr/bin/jconsole
i=:>:@i.9
q=:,/^:4>@:{(i.9);(i.;i.;i.;i.)16
s=:3 :'(>./((5+([:(*./)(3*i.3)&e.)+(-.@:(-:~.))+((*./)@:(6&>:))+2*((*./)@:(6&<)))"1(}."1(y(-:/:~"1)"1((([:{&(i,.i){.),[:,/[:{&(((>:@i.7)+"0 1(i.3)),|:3 9$i)}.)"1 q))#q)))+([:(*./)[:-.((1 9)&e.))y'
echo (s 2 2 2 3 3 3 5 5 7 7 7 8 8 8)=8
echo (s 1 1 1 1 2 3 4 5 6 7 8 9 9 9)=6
echo (s 1 1 1 2 3 4 5 6 7 8 8 9 9 9)=5
echo (s 2 3 3 4 4 4 5 5 5 6 6 7 8 8)=7
echo (s 3 3 3 3 4 4 4 4 5 5 5 5 6 6)=8
echo (s 1 1 1 2 2 2 3 3 3 7 7 7 9 9)=7
echo (s 1 2 3 4 4 5 5 6 6 7 8 8 8 9)=8
echo (s 1 1 3 4 4 5 5 6 6 7 8 9 9 9)=5
echo (s 2 2 2 3 3 3 4 4 4 5 5 5 6 6)=8
echo (s 1 1 1 1 2 2 3 3 3 4 4 5 5 5)=5
exit''
```
] |
[Question]
[
# Background and Rules
There is a variant of chess called atomic chess, which follows essentially the same rules as normal chess, except that pieces explodes other pieces around them when captured. In addition to checkmate, you can also win the game by blowing up the king.
When a piece captures another piece, all adjacent pieces (even diagonally adjacent) are destroyed, along with the pieces that were originally part of the capturing.
An exception to this rule are pawns. Pawns can be destroyed by directly capturing them, but they cannot be destroyed by the explosion of a nearby capture. Capturing with a pawn or capturing a pawn with another piece (even a pawn) will still result in an explosion.
A special case is the en passant capture, which allows a pawn that is pushed 3 ranks from its original position to capture an adjacent pawn immediately after that pawn has moved two squares in one move from its original position. In this case, the explosion is centered around where the capture would have been if the captured pawn had only moved one square instead of two.
For example, consider the following position (`N` represents a knight, capital letters represent white pieces, lowercase represent black pieces, `~` represents an empty space):
```
White to move
rnbqkb~r
pppppppp
~~~~~~~~
~~~N~~~~
~~~~n~~~
~~~~~~~~
PPPPPPPP
R~BQKBNR
```
Picture of the board (white to move):

If white then goes to take the pawn on c7 (the black pawn, 3rd from the left) with their knight on d5, both the white knight and the black pawn are destroyed, along with the b8 knight, the c8 bishop, and the queen. Notice how the b7 pawn and the d7 pawn are still alive, even though they were right next to the capture. Recall that they cannot be destroyed by the explosion of a nearby capture.
The resulting position after the capture is as follows:
```
Black to move
r~~~kb~r
pp~ppppp
~~~~~~~~
~~~~~~~~
~~~~n~~~
~~~~~~~~
PPPPPPPP
R~BQKBNR
```
Picture of the board (black to move):

With those rules out of the way, we can now talk about legal and illegal moves.
# Legal and Illegal Moves
Just like how a piece covering a check (pinned piece) cannot move (you cannot make a move that results in your king being in check), similar things also exist in the atomic chess variant.
Because atomic chess follows all normal chess rules (but with a few differences, more details below), many illegal moves in normal chess also carry over into atomic chess. For example, moving a piece out of a pin is also illegal in atomic chess.
An illegal move unique to atomic chess is that you cannot capture around any piece that is pinned, because that results in your king being in check. Here's an example:
```
White to move
rnb~k~nr
pppppppp
~~~~~~~~
q~~~B~~~
~~~b~~~~
~~N~PN~~
PPP~~PPP
R~~QKB~R
```
Picture of the board (white to move):

Even though a pawn, a bishop, a knight, and a queen are all attacking the black bishop on d4, it cannot be taken because the resulting the explosion would also destroy the white knight on c3, which would expose the white king to a check by the black queen.
A legal move in atomic chess that is illegal in regular chess is moving the king next the opponent's king. The reasoning behind allowing this is that taking the opponent's king with your king would blow up both kings, so *technically* the opponent's king would not be threatening your king at all, which means it is safe to move your king next to the opponent's king.
That also leads to another illegal move: taking any piece with a king. This is because when a piece captures another piece, the capturing piece is also destroyed. Just like it's illegal to make a move such that the king is in check, it's also illegal to make the king suicide by blowing up itself. This also means that a king cannot capture an opponent king.
Another illegal move is taking a piece that is adjacent to both kings. Overall, any move that results in both kings being blown up in the same move is illegal. Taking a piece adjacent to both kings will result in exactly that. For example, take a look at the following position:
```
White to move
~~~~~~~~
~~kb~~~~
~~K~~~~~
~~~~~~~~
~~~~~~~~
~~~~~~~~
~~~~~~~~
~~~R~~~~
```
Picture of the board (white to move):

In this position, the white rook cannot take the black bishop because the resulting explosion would destroy both kings.
This also has the side effect that a king can move directly into check if it is adjacent to the opponent king. This is because the piece giving the check can't "take" the king or else it would blow up both kings, which is not allowed.
Looking back at the position above, even though the white king seems to be in check by the black bishop, that is actually not the case, because the white king is adjacent to the black king.
A legal move that is unique to atomic chess is that you can blow up the opponent's king even if your king is in check (or seemingly a checkmate!). For example, consider the following position:
```
Black to move
~~~~~R~k
~~~~~~pp
~~~~~~~~
~~~~~~~~
~~~~~~~~
~~~~~~~~
~~~~r~PP
~~~~~~~K
```
Picture of the board (Black to move):

Even though white seems to have checkmated black, it is actually legal for black to take the white pawn and blow up the white king.
# Task
Your task is, given a board state (always \$8\times8\$) and a *valid* move, determine whether or not the move is legal in atomic chess. For the sake of this challenge, you can assume that a move is *valid* when the piece that is moving can make that move if there were only that piece on the board. So rooks won't be moving like knights, for example. You also won't have to deal with castling (short or long) as an input. You can also assume that it is **white to move** and that the board state is **reachable in a real game** (this prevents a board state like the black king already being in check, which is impossible if it's white's turn).
# Test Cases
One of these test cases is from a real game while all the other test cases were created specifically for this challenge; can you figure out which one?
```
FEN, move (algebraic notation)
---------------------------------
Illegal:
rnb1k1nr/pp1p1ppp/2p5/q3B3/3b4/2N1PN2/PPP2PPP/R2QKB1R w KQkq - 3 7, Bxd4
rnb1k1nr/pp1p1ppp/2p5/q3B3/3b4/2N1PN2/PPP2PPP/R2QKB1R w KQkq - 3 7, Nd5
8/2kb4/2K5/8/8/8/8/3R4 w - - 20 30, Rd7
8/2kb4/2K5/8/8/8/8/3R4 w - - 20 30, Rd8
8/2kb4/2K5/8/8/8/8/3R4 w - - 20 30, Kb5
7k/4R1pp/8/8/8/8/6PP/5r1K w - - 14 24, Kg1
rnb1kbnr/1p2p3/pqp2ppp/2NpP3/8/5P2/PPPP1KPP/R1BQ1BNR w kq - 0 8, exd6 e.p.
5k1r/ppp3pp/5p2/2b5/4P3/4BP2/PP1r2PP/RN1Q1RK1 w - - 5 14, Qxd2
Legal:
8/2kb4/2K5/8/8/8/8/3R4 w - - 20 30, Rd6
7k/4R1pp/8/8/8/8/6PP/5r1K w - - 14 24, Rxg7
rnbqkb1r/pppppppp/8/3N4/4n3/8/PPPPPPPP/R1BQKBNR w KQkq - 4 3, Nxc7
8/8/4k3/4q3/5K2/8/8/8 w - - 11 26, Kf5
2rqk3/2q3K1/2qqq3/8/8/8/8/r7 w - - 26 53, Kf7
```
If you want to see the board states on an actual chessboard, you can use the analysis tool on [lichess.org](https://lichess.org/analysis/atomic) and paste in the FEN for each board.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
]
|
[Question]
[
[Sandbox](https://codegolf.meta.stackexchange.com/a/18563/82007)
Finding radicals of arbitrary ideals in rings is hard! However, it's a doable task in polynomial rings, since they are Noetherian (all ideals are finitely generated)
**Background**
[A quick introduction to radical ideals](http://mathworld.wolfram.com/IdealRadical.html)
A ring is a set, paired with two binary operations + and \* such that 0 is a additive identity, 1 is a multiplicative identity, addition is commutative, every element has an additive inverse, and multiplication distributes over addition. For a more proper introduction, see Wikipedia. In this challenge, we'll be dealing with rings of polynomials over the complex numbers (for example, C[x,y,z]), so multiplication will also be commutative.
An ideal is a non-empty set closed under addition that contains additive inverses for all elements, and such that for any r in the ring and i in the ideal, r\*i is in the ideal.
Given some polynomials p1,...,pn, the ideal generated by the polynomials is the set of all polynomials p such that there exists polynomials q1,...,qn such that p = p1q1+p2q2+...+pnqn.
In other words, the ideal generated by a set of polynomials is the smallest ideal containing the set.
Given ideal I of R, the radical ideal of I, or root I, √I, is the ideal of elements r in R such that there is some natural n, r^n is in I.
[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") **challenge**:
Given an ideal generated by polynomials in any number of variables in the complex numbers, you need to return a set of polynomials that generate the radical ideal.
Important Notes:
* While the polynomials all will belong to the space of complex coefficients, I'll only give you inputs of polynomials with integer coefficients.
* Variables will always be single letters.
* The output must be algebraically independent (there is no non-zero linear combination of the polynomials that sums to 0). The input will be algebraically independent.
* Obviously, the output is non-unique.
**Hints**
A less algebraic way of thinking about radical ideals is: given that the input polynomials all evaluate to 0, what is the set of all polynomials we know that evaluate to 0. That set is the radical ideal.
Another nice characterization of the radical ideal is the intersection of all prime ideals containing the original generators.
There are no good known ways to find radicals in infinite fields, like the complex numbers. However, there are several algorithms that have reasonable average case times (many of which are listed [here](http://cms.dm.uba.ar/Members/slaplagn/archivos/linz_2006-02.pdf))
[Singular](https://www.singular.uni-kl.de/) has all of these algorithms implemented, if you want to experiment before building your own.
Of course, this is code golf, so inefficient solutions are permitted.
**Input/Output**
I/O should be pretty flexible. Possible forms of input/output:
```
Ideal: (x^2y-z^3, 2xy^2-2w^3, xy-zw)
I/O 0: "x^2y-z^3, 2xy^2-2w^3, xy-zw"
I/O 1: "x2y-z3,2xy2-2w3,xy-zw"
I/O 2: ["x2y-z3","2xy2-2w3","xy-zw"]
I/O 3: [[[1,2,1,0,0],[-1,0,0,3,0]],[[2,1,2,0,0],[-2,0,0,0,3]],[[1,1,1,0,0],[-1,0,0,1,1]]]
```
If there's some other more convenient I/O, let me know.
**Test Cases**
As I said earlier, these are not the only valid outputs for these inputs.
>
> x^3 → x
>
>
>
>
> 2x^4y^2z^3 → xyz
>
>
>
>
> xy-z^2, x-y, y-z+1 → x-y, x+z
>
>
>
>
> x^2, xz^2-x, y-z → x, y-z
>
>
>
>
> y^2+z, yz → y, z
>
>
>
>
> x^2+y^2-1, w^2+z^2-1, xw+yz, xz-yw-1 → y+w, x-z, y^2+z^2-1
>
>
>
>
> xy, (x-y)z → xy, yz, xz
>
>
>
>
> xy, x-yz → x, yz
>
>
>
>
> x^2y-z^3, 2xy^2-2w^3, xy-zw → z^2-xw, yz-w^2, xy-zw
>
>
>
**Explained Examples**
Upon request in the comments, I'll work a few examples out:
>
> Example 1: 2x^4y^2z^3 → xyz
>
>
>
>
> Note that (xyz)^4 = x^4y^4z^4, while 0.5*y^2z*(2x^4y^2z^3)=x^4y^4z^4, so this tells us that xyz is in the radical of 2x^4y^2z^3. Now, consider some polynomial p with a term that doesn't have x as a factor. Then, p^n will also have such a term, so it can't be in the ideal generated by 2x^4y^2z^3. So, every polynomial in the radical ideal has x as a divisor, and by symmetry, has y and z as divisors, so has xyz as a divisor.
>
>
>
>
> Example 2: x^2, xz^2-x, y-z → x, y-z
>
>
>
>
> Note that x^2 is in the ideal, so x is in the radical ideal. So, x\*(z^2-1)=xz^2-x will be in the radical ideal since it is a multiple of x. Clearly, x and y-z are independent, and since they are terms of degree 1, they generate the radical ideal.
>
>
>
]
|
[Question]
[
[Alpha Decay](https://en.wikipedia.org/wiki/Alpha_decay) is a kind of radiation decay where every time the atom "decays", it loses a helium nucleus (an alpha particle). This means that an atom loses 2 protons and 2 neutrons each time. Your task is to simulate this, including the problems that occur during alpha decay.
Given two integers as input, \$m\$ and \$p\$, where \$1 < p < m\$, count down in steps of 4 and 2 respectively until either \$m\$ or \$p\$ is equal to or less than 1. At this point, you should output the number which has not yet reached 1.
In order to mimic radioactive decay, however, your program should work when up to any 2 characters are removed from your program. These characters are chosen with uniform probability, and (obviously) chosen without replacement. "Up to" means that the number of characters removed can either be 0, 1 or 2, and your program should work when any number of characters between 0, 1 and 2 are removed.
By "work" it means that, your program, modified or not, should perform the task as specified. Programs may error, so long as the correct output is produced.
Input and output formats are liberal, so long as it's covered by the [defaults](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), it's allowed.
The shortest code in bytes (without characters removed) wins!
## Test Cases
```
m, p => output
100, 20 => 60
101, 100 => 50
45, 2 => 41
2000, 80 => 1840
57, 23 => 13
80, 40 => 0
81, 40 => 1
81, 41 => 1
43, 42 => 20
```
]
|
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/123907/edit).
Closed 6 years ago.
[Improve this question](/posts/123907/edit)
Writing quines is hard. Why not have your computer write them for you!
Your program will take as input an interpreter (in a Turing complete language of your choosing) for a language X, and you will output a quine in language X.
Notes:
* Language X is guaranteed to be Turing complete (you do not need to check this (it would be impossible to do so anyways)).
* Due to some issues that jimmy23013 raised in the comments, I'll also guarantee that the language has a quine.
* A quine for the purposes of this challenge is a program that outputs its own source code when given no input.
* The interpreter might throw errors if the program it is running has errors, so be prepared! (A quine shouldn't throw errors.)
Here is an example algorithm you can use. I am only putting it here so people don't claim this challenge is impossible:
>
> Go through every possible program, running them all in parallel or via [Dovetailing](https://en.wikipedia.org/wiki/Dovetailing_(computer_science)). Throw out programs that cause errors. Whenever a program outputs its own source code, you are done. Since every [Turing complete language has at least one quine](https://en.wikipedia.org/wiki/Quine_(computing)), this is guaranteed to eventually return a result.
>
>
>
This is code golf, so the shortest answer wins!
]
|
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/28148/edit).
Closed 6 years ago.
[Improve this question](/posts/28148/edit)
Your mission is not so simple. You have to write a program that decodes QR-codes.
There are some things that are not permitted:
* Making web requests (except <https://i.stack.imgur.com/sCUJT.png> or <https://i.stack.imgur.com/mXUcd.jpg>)
* Using any QR code processing library (Or using any external library to do this)
* Image processing libraries should not be be used to do anything other than loading image, determining its size and reading single pixels from it
* Using built-in functions to read QR codes
* Brute forcing
If you use any external files (except QR code file and language libraries), the byte count of those files will be added to your code.
Other rules:
* Program must be able to read any valid QR code (No error correction is required). You can assume that the maximum size of QR-Code is 10000 pixels.
* QR code colors are black and white. ((0, 0, 0) and (255, 255, 255) in RGB. Alpha channel is not used, so your program can ignore it.
* Image file must be saved as PNG or loaded from <https://i.stack.imgur.com/mXUcd.jpg> or <https://i.stack.imgur.com/sCUJT.png> runtime. (And tricks like using raw txt file with .png file extension are prohibited)
* QR code decoded content must be outputted to stdout. If your language does not allow this, you can save it to file named `qrcode.txt`.
* QR-code format is normal qr-code (not any modification like micro QR code)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins
An example file is here: <http://api.qrserver.com/v1/create-qr-code/?color=000000&bgcolor=FFFFFF&data=http%3A%2F%2Fcodegolf.stackexchange.com&qzone=1&margin=0&size=400x400&ecc=L>

]
|
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/8986/edit).
Closed 3 years ago.
[Improve this question](/posts/8986/edit)
**Challenge**
Your challenge is simply to write a program in the language of your choosing that when run, determines the highest possible score for a board of *Scrabble* - For the sake of this challenge, a few rules have been modified.
Notably, bonus squares are counted for every single word on the board, rather than only the "first" time used, The 50 Point Bonus for 7-letter plays is removed, and scoring is calculated at the end of the entire board, for every word on the board. Do not score any words double such as text/texts being 2 separate words.
You may use any dictionary file you like, there are multiple online scrabble dictionaries you may use. The accepted answer must include only scrabble-valid words.
**Rules**
A Scrabble game board is made of up cells in a square grid. The Scrabble board is 15 cells wide by 15 cells high. The Scrabble tiles fit within these cells one to a cell.
Scrabble is played with exactly 100 tiles. 98 of these tiles contain letters on them, while there are 2 blank tiles. These blank tiles add a wildcard aspect to Scrabble. The blanks substitute for any letter in the alphabet. Once played, a blank tile remains for the remainder of the game the letter for which it was substituted when first played.
Various letters have different point values, depending on the rarity of the letter and the difficulty in playing it. Blank tiles have no point value.
English-language editions of Scrabble contain 100 letter tiles, in the following distribution:
```
2 blank tiles (scoring 0 points)
1 point: E ×12, A ×9, I ×9, O ×8, N ×6, R ×6, T ×6, L ×4, S ×4, U ×4
2 points: D ×4, G ×3
3 points: B ×2, C ×2, M ×2, P ×2
4 points: F ×2, H ×2, V ×2, W ×2, Y ×2
5 points: K ×1
8 points: J ×1, X ×1
10 points: Q ×1, Z ×1
```
Some squares on the Scrabble board represent multipliers. If a tile is placed on this square, then the tile's value is multiplied by a factor or either 2x or 3x. Certain tiles multiply the point value of an entire word and not simply the tile on that space.
>
> Double Letter Scores - Light blue cells are found isolated on the board. When a tile is placed on this space, that tile's point value is multiplied by two.
>
>
> Triple Letter Score - This is a dark blue cell on the Scrabble. The tile placed on this square has its points multiplied by three.
>
>
> Double Word Score - Light red cells are found running diagonally towards the four corners of the board. When a player plays a word on one of these squares, the point value of the entire word is multiplied by two.
>
>
> Triple Word Score - This is a dark red square on the Scrabble board. These are found on the four sides of the board equidistant from the four corners of the board. When a word is played using this square, then the points for the word are multiplied by three.
>
>
>
**For the sake of this challenge, the rule that a colored square be counted only once will be omitted. Count the bonus for every word on the board!**
The board to be used is: <http://upload.wikimedia.org/wikipedia/commons/thumb/c/c2/Blank_Scrabble_board_with_coordinates.svg/300px-Blank_Scrabble_board_with_coordinates.svg.png>
**WINNING**
The winner will be the highest valid-scoring scrabble board as of December 1st. Please be sure to include your total score, and output. If the top scoring board is mis-scored, or is invalid, the next place will be considered. No input is required, output may be in any format that is properly readable. This is not Code-Golf, highest score wins.
]
|
[Question]
[
I'm work on a problem which I set myself for fun, which is to create a python script which prints the even numbers from 0 to 100. The challenge is to make the script as small as possible. This is what I have so far:
```
for x in range(0, 101):
if (x % 2 == 0):
print x
```
Currently it is 60 bytes. Can anyone think of a way to make it smaller?
---
Edit: `print(*range(2,101,2),sep='\n')` which is 30 bytes. Any smaller?
[Answer]
# Python 2 - 12 characters
```
print 8**999
```
The decimal representation of all even numbers from 0 to 100 can be found in the output:
```
153778990270139647116444851659594064330089236967104214470764753645007350076834118596920008479824182447803706156756475613564110522612279602948135310258168541404369918794480627176627915013920083365328091029969610052054309789461709376676636344651086297099162082351332867728061686056465813162964114500668343488577962834185114919242101638217077550294093097112980059735456387540301162747936045475366317560310988720435512281742591085641505551107966844283901574058972330493685836063965131445246304097593431852972101058022587137885482726523043570690342524474585327775688980689010069001288756281975198668705741000141718184277589376710426738442847382969979234512669279398030637083755270090078676447687796406001053805898105262326290072552249025832780916090265261064205460488458795026145331708830141367124625271312584437671840499845750728447412590406684361326531266896486146862384988911439049971734022314877278748672
```
As a bonus, so can the odd numbers.
[Answer]
# Python 3, 22 (Possibly not allowed)
If the challenge is "to create a python script which prints the even numbers from 0 to 100" and not "to create a python script which prints the even numbers from 0 to 100, *newline separated*", then the shortest solution is:
```
print(*range(0,101,2))
```
Remember, it's very important in code golf not to put any limitations on yourself you don't have to - do what the problem asks, and no more.
[Answer]
# Python2 26
```
i=0;exec"print i;i+=2;"*51
```
independent discovery of @bitpwner's solution
[Answer]
# Python 2 - 26
```
i=0;exec"print i;i+=2;"*51
```
Based on the tip on exec with string multiplication found at [Tips for golfing in Python](https://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python/1020#1020).
[Answer]
# Python 2, 26 (possibly not allowed)
```
i=102
while i:i-=2;print i
```
It wasn’t strictly specified, in which order the numbers were to be printed.
[Answer]
# Python 2 - 20 (Possibly not allowed)
This is python 2 specific and probably cheating since it prints the list, but since all numbers end up on the screen:
```
print range(0,101,2)
```
[Answer]
# Python 2, 28
```
for i in range(51):print 2*i
```
[Answer]
# Python 2 in \*NIX, 24
```
os.system('seq 0 2 100')
```
If you need to add
```
import os
```
Then the total is 33 characters.
[Answer]
# Python 3, 29
```
*a,=map(print,range(0,101,2))
```
If you're in Python 2 and happen to have already imported the print function, you don't have to make the iterator object into a list and it becomes 25 characters:
```
map(print,range(0,101,2))
```
I don't know that that's entirely fair though.
Here's another fun idea that works in python 2 or 3. It's a tad longer.
```
def p(i):
if i+2:p(i-2);print i
p(100)
```
[Answer]
## Python 2 - 24
```
0;exec"_+=2;print _;"*50
```
(based on bitpwner and Sparr solution)
In the shell, "\_" contains the value of the previously evaluated expression
[Answer]
# Python 2 - 20 (questionable)
If isaacg's [space-separated solution](https://codegolf.stackexchange.com/a/36087) is OK, then presumably the normal list formatting is as well:
```
print range(0,101,2)
```
For further rule-twisting, apply SirBraneDamuj's suggestion from the comments:
```
print range(101)
```
and you are at 16. So what if there's some extra garbage separating them?
[Answer]
# Python List Comprehension - 39
This uses a list comprehension, one trick to make it shorter is to multiply the index by 2 rather than going from 0 to 100 and a trailing `if x % 2` check for even.
```
print'\n'.join(`2*x`for x in range(51))
```
Using a map and @isaacg's suggestion it ends up being the same 39 characters:
```
print'\n'.join(map(str,range(0,101,2)))
```
Edit: After separating values by newline it is by far not the shortest.
[Answer]
In my case, I use list comprehension (in Python 3.9). < Sorry, I came late but I hope it makes sense.>
```
even_numbers = [x for x in range(100) if x % 2 == 0]
print(even_numbers)
```
] |
[Question]
[
**Challenge:** Print the **entire** printable ASCII charset (not just a range!) in order.
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
**Rules:** *read closely*
* No other characters allowed in the output.
* Program/function does not accept input.
* Try not to hardcode/embed the output.
* This is code golf, shortest answer wins.
[Answer]
# Brainfuck, ~~30~~ 27 bytes
```
+[[>++<<+>-]>]<<<++[<.+>++]
```
[Try it online!](http://brainfuck.tryitonline.net/#code=K1tbPisrPDwrPi1dPl08PDwrK1s8Lis-Kytd&input=)
### How it works
`+` changes the initial cell to **1**. After this step, we enter the following, nested loop.
```
[ While the current cell is non-zero:
[ While the current cell (C) is non-zero:
>++ Increment the cell to C's right twice.
<<+ Increment the cell to C's left.
>- Decrement C.
]
> Advance to the cell to C's right.
]
```
This computes consecutive powers of **2** until the the value **256 = 0 (mod 256)** is reached. When the outer loop finishes, the tape is in the following state.
```
v
001 002 004 008 016 032 064 128 000 000 000
```
`<<<++` retrocedes three cells and increments twice, leaving the tape as follows.
```
v
001 002 004 008 016 032 066 128 000 000 000
```
Now we're ready to print the actual output. As a stop condition, we increment the cell above twice each time we print and increment the cell to its left. Since **66 + 95 × 2 = 256 = 0 (mod 256)**, we stop after printing all **95** printable ASCII characters. We achieve this as follows.
```
[ While the current cell (C) is non-zero:
< Retrocede to the cell to C's left.
.+ Print its content and increment.
>++ Increment C twice.
]
```
[Answer]
# MATL, 3 bytes
```
6Y2
```
[**Try it Online**](http://matl.tryitonline.net/#code=Nlky&input=)
And for the sake of a non-built-in (7 bytes)
```
32:127c
```
[Answer]
# Brainfuck, ~~40~~ 39 bytes
```
++++[->++++[->++>++++++<<]<]>>>-[-<.+>]
```
[Try it online.](http://brainfuck.tryitonline.net/#code=KysrK1stPisrKytbLT4rKz4rKysrKys8PF08XT4-Pi1bLTwuKz5d&input=)
## Explanation
```
++++[->++++[->++>++++++<<]<]
```
The nested loops basically mean you multiply the number of plusses together, so 4 × 4 × 2 = 32 in one cell and 4 × 4 × 6 = 96. Here is the tape after running this:
```
00 00 32 96
^
```
---
`>>>-` moves the pointer to the fourth cell and decrements it. Now we're done with the setup. 32 is the code for space, the first printable ASCII character. 95 is the number of characters we have to print. Here is the tape now:
```
00 00 32 95
^
```
---
`[-<.+>]` runs until the current cell (the fourth one) is zero. It decrements the counter and prints the character and increments it for the next time.
[Answer]
# Cheddar, 29 bytes
```
->(32:126).map((i)->@"i).fuse
```
Range from 32-126, loop over it and get the string at the given char code `@"` and the fuse together (join)
## Cheddar, 7 bytes
```
32@"126
```
Unfortunately this is broken as of the current release but I'm sure you can go back some versions where this works
[Answer]
## [Retina](https://github.com/m-ender/retina), 18 bytes
```
~
{2`
$`
T01`p`_p
```
The leading linefeed is significant.
[Try it online!](http://retina.tryitonline.net/#code=Cn4KezJgCiRgClQwMWBwYF9w&input=)
### Explanation
**Stage 1: Substitution**
```
~
```
We start by replacing the empty (non-existent) input with a single `~`.
**Stage 2: Substitution**
```
{2`
$`
```
The regex of this substitution is still empty, since the ``` separates configuration from regex and `{2` is therefore just the configuration. The `{` indicates that the remaining two stages should be run in a loop until they stop changing the output. The `2` indicates that this specific stage has a limit of `2`, meaning that only the first two matches of the regex will be replaced. Since the regex is empty, that means we get an empty match in front of the string and an empty match after the first character.
This match is replaced with the prefix `$`` which refers to everything in front of the match. For the first match, there is nothing in front of it, so this doesn't insert anything, but for the second match, there is the leading character in front of it, which therefore gets duplicated.
**Stage 3: Transliteration**
```
T01`p`_p
```
Here, `T` activates transliteration mode, and `0` and `1` are limits (where `0` just means "don't set this limit"). Together, they mean "transliterate only the first character in the string". The actual transliteration maps from `p` to `_p`. Here, `p` expands to the printable ASCII characters and `_` means "remove" this character, so the expanded lists look like this:
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
_ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
That means spaces get removed and all other characters get decremented by one.
To see how the last two stages act together here is the string after each of the first few and last stages:
```
~
~~
}~
}}~
|}~
||}~
{|}~
...
"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
!!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
Since the state of the string is only checked after every other stage to determine whether to end the loop, and the two stages cancel each other once we reach the leading space (since Stage 2 adds a space and Stage 3 removes it), this terminates the loop and therefore the program.
[Answer]
# Python 2.7, 36 bytes:
```
print''.join(map(chr,range(32,127)))
```
Simple enough. A full program that prints out the entire ASCII sequence in order.
[Answer]
# Octave, 13 bytes
```
disp(' ':'~')
```
Try it on [ideone](http://ideone.com/XcdBES).
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 54 bytes
```
man ascii|fold -w1|LC_ALL=C sort -u|tr -cd '[:print:]'
```
[Try it online!](https://tio.run/##S0oszvj/PzcxTyGxODkzsyYtPydFQbfcsMbHOd7Rx8fWWaE4v6hEQbe0pqRIQTc5RUE92qqgKDOvxCpW/f9/AA "Bash – Try It Online")
I like that this uses the ASCII man page (which contains an ASCII table) to extract the characters.
[Answer]
# [Python 2](https://docs.python.org/2/), 30 bytes
```
print bytearray(range(32,127))
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EIamyJDWxqCixUqMoMS89VcPYSMfQyFxT8/9/AA "Python 2 – Try It Online")
[Answer]
## Pyth, 5 bytes
```
srd\
```
[Try it here](https://pyth.herokuapp.com/?code=srd%5C%7F&debug=0).
```
r range from
d space
\<del> to the delete character, 0x7F (included literally in the program)
s sum (concatenate all)
```
[Answer]
# JavaScript, 54 bytes
```
for(i=32;i<128;i++)console.log(String.fromCharCode(i))
```
Wasted quite a few bytes printing it... Also prints each char on a new line.
[Answer]
# Java 8, 48 bytes
```
v->{for(char i=31;++i<127;)System.out.print(i);}
```
[Try it online.](https://tio.run/##LY7BDoIwEETvfMUe2xBI0IOHin8gFxIvxsNaQFdLIW1pYgjfXoty2clOJm/mhR6zV/MOUqG1cEbScwJA2rWmQ9lCtb4AfqAGJLus4rmI3pLEYx06klCBhhKCz05zNxgmn2iAyn0h0pSOxe4geP2xru3zYXL5aCKdERdLECtjnO4qMjbUr6iPM1jtYvBxvQHy/wadS6Ynpbb6JXwB)
**Explanation:**
```
v->{ // Method with empty unused parameter and no return-type
for(char i=31;++i<127;) // Loop characters from ' ' to '~'
System.out.print(i);} // And print it
```
[Answer]
# CJam, 6 bytes
```
',32>
```
The second byte is a DEL character. [Try it online!](http://cjam.tryitonline.net/#code=J38sMzI-&input=)
[Answer]
# [Perl 6](http://perl6.org), 17 bytes
```
print |(' '..'~')
```
```
print chrs ^95+32
```
[Answer]
## C, 40 bytes
```
f(){for(char i=32;i<128;i++)putchar(i);}
```
[Answer]
# Bash + general Linux utilities, 18
```
jot -s '' -c 95 32
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
@Pw
```
`@P` is the string that contains the printable ASCII characters so… yeah, not very interesting.
It's not clear whether OP accepts built-ins or not, and since others have posted answers that use built-ins, I'll use the 3 bytes version until OP clarifies this point.
### With no built-in, 14 bytes
```
32:126e Get a number between 32 and 126
:"~c"w Format that number to STDOUT as a char code
\ Backtrack
```
[Answer]
# Ruby, 17 bytes
```
$><<[*' '..?~]*''
```
or
```
print *[*' '..?~]
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 1 [byte](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
C
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjIz,v=2)
---
*Without builtin:*
## ~~15~~ 14 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
9⁵×4-{⁷⁷++╷c]∑
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjE5JXUyMDc1JUQ3JXVGRjE0JXVGRjBEJXVGRjVCJXUyMDc3JXUyMDc3JXVGRjBCJXVGRjBCJXUyNTc3JXVGRjQzJXVGRjNEJXUyMjEx,v=2)
[Answer]
# TSQL, 53 bytes - Vertical solution
```
DECLARE @ int=32x:PRINT char(@)SET @+=1IF @<127GOTO x
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/510173/print-the-ascii-printable-character-set)**
# TSQL, ~~75~~ ~~71~~ 68 bytes - Horizontal solution
```
DECLARE @ char(95)=''WHILE 95>LEN(@)SET @=char(126-LEN(@))+@ PRINT @
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/510780/print-the-ascii-printable-character-set)**
[Answer]
# [Elixir](https://elixir-lang.org/), 24 bytes
```
IO.puts Enum.uniq 32..?~
```
[Try it online!](https://tio.run/##S83JrMgs@v/f01@voLSkWME1rzRXrzQvs1DB2EhPz77u/38A "Elixir – Try It Online")
Prints a trailing newline. If that's not acceptable, it's +1 byte for `write` instead of `puts`.
`uniq` is the cheapest operation I managed to find for converting range to list. As a bonus, here are 4 different programs that all accomplish the task in 27 bytes:
```
IO.puts Enum.to_list 32..?~
IO.puts Enum.into 32..?~,[]
IO.puts Enum.take 32..?~,95
IO.puts for n<-32..?~,do: n
```
[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"))
Full program.
```
' '…'~'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94L@6gvqjhmXqdeog7n8FMCgAAA "APL (Dyalog Extended) – Try It Online")
Do I need to explain?
[Answer]
### x86\_16 machine code - 21 15 bytes
-6 bytes, thanks [@anna328p](https://codegolf.stackexchange.com/users/53551/anna328p)
```
B8 20 0E MOV AX, 0E20H
.LOOP:
CD 10 INT 10H
40 INC AX
3C 7E CMP AL, 7EH
75 F6 JNE .LOOP
B8 4C00 MOV AX, 4C00H
CD 21 INT 21H
```
Running on DOSBox :
[](https://i.stack.imgur.com/23GCP.png)
[Answer]
# [Perl 5](https://www.perl.org/) using only keywords with lowercase alphabets only separating each of them only a space, ~~227~~ 129 bytes
```
eval q y print chr length xor s qq q while uc le q q q x length q q truncate tie q x length q q foreach q y for q q q x ord q q q
```
[Try it online!](https://tio.run/##XY1LDoAgEEOv0kt4IDKOQkL4jIPi6RExujDdtHltmlj81BrvxiPjRBIXFGQFnsOqFjUKNuTc6WGdZxTqCHmovq07qJRARhnq@M@WKGzIjovuv3mU@fGtXQ "Perl 5 – Try It Online")
## How it works
```
eval q y
print chr length
xor s qq q
while
# default variable has spaces only; equibalent to $_
uc
# instead of <=126
le q q q
# 126==14*9
x length q q truncate tie q
x length q q foreach q
# just noticed i could golf the word
y for q q q x ord q q q
```
## Previous: 227 bytes.
```
eval q y print chr length xor s qq q while chr length lt chr length q q length length length length length length length length length length length length length length length length length length q y foreach q q q x ord q q q
```
[Try it online!](https://tio.run/##xY9RCoAgEESvMpfoQGJbCou6m5SdfkskqBP0NQPvfcwUUp7MaHcMwYmiMVX4oGBKaw1oWbFB5KZHiExvxh@zKw/4J/qBJSs5P9YIGrLOo5td "Perl 5 – Try It Online")
### How it works
Using length of default variable to be accumulator.
```
eval q y
# print chr($accumulator)
print chr length xor
# increment it
s qq q
while
# instead of <
chr length lt
# 127 is unfortunately a prime; any efficient ideas within the restrictions?
chr length q q length length length length length length length length length length length length length length length length length length q
# $accumulator=32
y foreach q q q x ord q q q
```
[Answer]
# [Python 3](https://docs.python.org), 20 bytes
```
lambda:range(32,127)
```
[Try it online!](https://tio.run/##K6gsycjPM/5fUJSZV6Khrq6XlZ@Zp5GbWKCRnFGko/E/JzE3KSXRqigxLz1Vw9hIx9DIXPO/poYmEPwHAA "Python 3 – Try It Online") Returns a `range` of codepoints.
```
lambda:range(32,127) # full program
lambda: # return function taking no arguments that returns...
range( , ) # range object of all integers between...
32 # literal...
range( , ) # minus 1 and...
127 # literal
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 5 bytes
```
kPs5ȯ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=kPs5%C8%AF&inputs=&header=&footer=)
-2 byte thanks to @AaronMiller
[Answer]
# SQL, ~~76~~ 75 bytes
(Microsoft SQL Server 2012+)
```
declare @ int=32;while(@<127)begin;print char(@);set @+=1;end
```
[Demo](http://data.stackexchange.com/codegolf/query/510047)
[Answer]
## Haskell, 16 bytes
```
putStr[' '..'~']
```
[Answer]
## Pyke, 5 bytes
```
~KS4>
```
[Try it here!](http://pyke.catbus.co.uk/?code=%7EKS4%3E)
Pyke's printable variable isn't sorted and it contains tabs and newlines etc... :(
[Answer]
## C - 35 bytes
```
f(i){for(i=31;++i<128;putchar(i));}
```
Call:
```
int main() {
f();
}
```
Uses the horrible `int`-as-a-string trick I learnt from [Lynn](https://codegolf.stackexchange.com/a/83141/30000). (Will again if OP confirms that a vertical output is OK).
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/35182/edit).
Closed 5 years ago.
[Improve this question](/posts/35182/edit)
**Problem:**
In your choice of language, write the shortest function that returns the floor of the square root of an unsigned 64-bit integer.
**Test cases:**
Your function must work correctly for all inputs, but here are a few which help illustrate the idea:
```
INPUT ⟶ OUTPUT
0 ⟶ 0
1 ⟶ 1
2 ⟶ 1
3 ⟶ 1
4 ⟶ 2
8 ⟶ 2
9 ⟶ 3
15 ⟶ 3
16 ⟶ 4
65535 ⟶ 255
65536 ⟶ 256
18446744073709551615 ⟶ 4294967295
```
**Rules:**
1. You can name your function anything you like. (Unnamed, anonymous, or lambda functions are fine, as long as they are somehow callable.)
2. Character count is what matters most in this challenge, but runtime is also important. I'm sure you could scan upwards iteratively for the answer in O(√n) time with a very small character count, but O(log(n)) time would really be better (that is, assuming an input value of n, not a bit-length of n).
3. You will probably want to implement the function using purely integer and/or boolean artithmetic. However, if you really want to use floating-point calculations, then that is fine so long as you call no library functions. So, simply saying `return (n>0)?(uint32_t)sqrtl(n):-1;` in C is off limits even though it would produce the correct result. If you're using floating-point arithmetic, you may use `*`, `/`, `+`, `-`, and exponentiation (e.g., `**` or `^` if it's a built-in operator in your language of choice, but *only exponentiation of powers not less than 1*). This restriction is to prevent "cheating" by calling `sqrt()` or a variant or raising a value to the ½ power.
4. If you're using floating-point operations (see #3), you aren't required that the return type be integer; only that that the return value is an integer, e.g., floor(sqrt(n)), and be able to hold any unsigned 32-bit value.
5. If you're using C/C++, you may assume the existence of unsigned 64-bit and 32-bit integer types, e.g., `uint64_t` and `uint32_t` as defined in `stdint.h`. Otherwise, just make sure your integer type is capable of holding any 64-bit unsigned integer.
6. If your langauge does not support 64-bit integers (for example, Brainfuck apparently only has 8-bit integer support), then do your best with that and state the limitation in your answer title. That said, if you can figure out how to encode a 64-bit integer and correctly obtain the square root of it using 8-bit primitive arithmetic, then more power to you!
7. Have fun and get creative!
[Answer]
# CJam, 17 (or 10) bytes
```
{_1.5#\/i}
```
[Try it online](http://cjam.aditsu.net/) by verifying the test cases:
```
[0 1 2 3 4 8 9 15 16 65535 65536 18446744073709551615]{_1.5#\/i}%N*
```
It won't pass the last test case because of rounding issues, but since `18446744073709551615` isn't an *Integer* in CJam (it's a *Big Integer*), we're still good, right?
If not, the following (and slightly longer) code will correct those errors:
```
{__1.5#\/i_2#@>-}
```
Not the shortest solution anymore, but *faaast*.
### How it works
```
__ " Duplicate the integer twice. ";
1.5# " Raise to power 1.5. Note that, since 1.5 > 1, this doesn't break the rules. ";
\ " Swap the result with the original integer. ";
/ " Divide. ";
i " Cast to integer. ";
_2# " Push square of a copy. ";
@ " Rotate the orginal integer on top of the stack. ";
>- " If the square root has been rounded up, subtract 1. ";
```
[Answer]
# Haskell, 28 26
I believe that this is the shortest entry from any language that wasn't designed for golfing.
```
s a=[x-1|x<-[0..],x*x>a]!!0
```
It names a function `s` with parameter `a` and returns one minus the first number whose square is greater than `a`. Runs incredibly slowly (O(sqrt n), maybe?).
[Answer]
### Golfscript, 17 characters
```
{).,{.*1$<},,\;(}
```
I could name my function any way I liked, but I decided not to name it at all. Add two characters to name it, add three to name it and not leave it on the stack, subtract one character if providing a full program is OK.
This abomination runs not in logaritmic time in the value of the input, not in O(sqrt n) time, it takes a whooping linear amount of time to produce the result. It also takes that much space. Absolutely horrendous. But... this is code-golf.
The algorithm is:
```
n => [0..n].filter(x => x*x < n+1).length - 1
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 characters
```
DsbR;fgb*TTL'b
```
Provides a named function, s, which calculates the square root by filtering the list from 0 to n for the square being larger than the input, then prints the last such number. Uses no exponentiation or floats.
```
Dsb def s(b):
R; return last element of
f filter(lambda T:
gb*TT b>=T*T,
L'b range(b+1))
```
Example usage:
```
python3 pyth.py <<< "DsbR;fgb*TTL'b \msd[0 1 2 3 4 8 9 15 16 65535 65536"
[0, 1, 1, 1, 2, 2, 3, 3, 4, 255, 256]
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language) (non-competing - Language is newer than the challenge), 43
While working on [this answer](https://codegolf.stackexchange.com/questions/82565/return-the-integers-with-square-digit-sums/82632#82632), it occurred to me that a similar method can be used to calculate integer square roots using retina:
```
.+
$*
^
1:
+`(1+):(11\1)
1 $2:
1+:$|:1+
1+
```
This relies on the fact that perfect squares may be expressed as `1+3+5+7+...`, and by corollary that the number of terms in this expression is the square root.
[Try it online. (First line added to allow multiple testcases to be run.)](http://retina.tryitonline.net/#code=JShHYAouKwokKgpeCjE6CitgKDErKTooMTFcMSkKMSAkMjoKMSs6JHw6MSsKCjEr&input=MAoxCjIKMwo0CjgKOQoxNQoxNgoxMDIzCjEwMjQ)
Obviously due to the decimal to unary conversion, this will only work for relatively small inputs.
[Answer]
## Perl, 133 characters
Not the shortest by far, but uses a digit-by-digit algorithm to handle any size input, and runs in O(log n) time. Converts freely between numbers-as-strings and numbers-as-numbers. Since the largest possible product is the root-so-far with the square of a single digit, it should be able to take the square root of up to 120-bit or so numbers on a 64-bit system.
```
sub{($_)=@_;$_="0$_"if(length)%2;$a=$r="";while(/(..)/g){
$a.=$1;$y=$d=0;$a<($z=$_*(20*$r+$_))or$y=$z,$d=$_ for 1..9;$r.=$d;$a-=$y}$r}
```
Decompressed, that is:
```
sub {
my ($n) = @_;
$n = "0$n" if length($n) % 2; # Make an even number of digits
my ($carry, $root);
while ($n =~ /(..)/g) { # Take digits of $n two at a time
$carry .= $1; # Add them to the carry
my ($product, $digit) = (0, 0);
# Find the largest next digit that won't overflow, using the formula
# (10x+y)^2 = 100x^2 + 20xy + y^2 or
# (10x+y)^2 = 100x^2 + y(20x + y)
for my $trial_digit (1..9) {
my $trial_product = $trial_digit * (20 * $root + $trial_digit);
if ($trial_product <= $carry) {
($product, $digit) = ($trial_product, $trial_digit);
}
}
$root .= $digit;
$carry -= $product;
}
return $root;
}
```
[Answer]
# Matlab (56) / Octave (55)
It works out the square root by using a fixed point method. It converges in maximal 36 steps (for 2^64-1 as argument) and then checks if it is the lower one of the 'possible' integer roots. As it always uses 36 iterations it has a runtime of O(1) =P
The argument is assumed to be uint64.
Matlab:
```
function x=q(s)
x=1
for i = 1:36
x = (x+s/x)/2
end
if x*x>s
x=x-1
end
```
Octave:
```
function x=q(s)
x=1
for i = 1:36
x = (x+s/x)/2
end
if x*x>s
x-=1
end
```
[Answer]
### Ruby — 36 characters
```
s=->n{g=n;g=(g+n/g)/2 while g*g>n;g}
```
[Answer]
# Python (39)
```
f=lambda n,k=0:k*k>n and k-1or f(n,k+1)
```
The natural recursive approach. Counts up potential square roots until their square is too high, then goes down by 1. Use [Stackless Python](http://www.stackless.com/) if you're worried about exceeding the stack depth.
The `and/or` idiom is equivalent to the ternary operator as
```
f=lambda n,k=0:k-1 if k*k>n else f(n,k+1)
```
**Edit:** I can instead get **25 chars** by exploiting the rule "you may use `*`, `/`, `+`, `-`, and exponentiation (e.g., `**` or `^` if it's a built-in operator in your language of choice, but only exponentiation of powers not less than 1)." (Edit: Apparently [Dennis](https://codegolf.stackexchange.com/a/35199/20260) already found and exploited this trick.)
```
lambda n:n**1.5//max(n,1)
```
I use the integer division operator `//` of Python 3 to round down. Unfortunately, I spend a lot of characters for the case `n=0` not to give a division by 0 error. If not for it, I could do 18 chars
```
lambda n:n**1.5//n
```
The rules also didn't say the function had to be named (depending how you interpret "You can name your function anything you like."), but if it does, that's two more characters.
[Answer]
## C99 (58 characters)
This is an example of an answer I would not consider to be a good one, although it's interesting to me from a code golf point of view because it's so perverse, and I just thought it would be fun to throw into the mix:
**Original: 64 characters**
```
uint64_t r(uint64_t n){uint64_t r=1;for(;n/r/r;r++);return r-1;}
```
The reason this one is terrible is that it runs in O(√n) time rather than O(log(n)) time. (Where n is the input value.)
**Edit: 63 characters**
Changing the `r-1` to `--r` and abutting it to `return`:
```
uint64_t r(uint64_t n){uint64_t r=1;for(;n/r/r;r++);return--r;}
```
**Edit: 62 characters**
Moving the loop increment to inside the conditional portion of the loop (note: this has unguaranteed behavior because the order of operations with respect to the preincrement operator is compiler-specific):
```
uint64_t r(uint64_t n){uint64_t r=0;for(;n/++r/r;);return--r;}
```
**Edit: 60 characters**
Adding a `typedef` to hide `uint64_t` (credit to user *technosaurus* for this suggestion).
```
typedef uint64_t Z;Z r(Z n){Z r=0;for(;n/++r/r;);return--r;}
```
**Edit: 58 characters**
Now requiring second parameter being passed as 0 in invocation of the function, e.g., `r(n,0)` instead of just `r(n)`. Ok, for the life of me, at this point I can't see how to compress this any further...anyone?
```
typedef uint64_t Z;Z r(Z n,Z r){for(;n/++r/r;);return--r;}
```
[Answer]
## Golfscript - 14 character
```
{.,\{\.*<}+?(}
```
Find the smallest number `i` less than the input `n` for which `n < i*i`. Return `i - 1`.
I.e. `[0..n-1].first(i => n < i*i) - 1`
Explanation for those who don't know Golfscript as well, for sample call with input `5`:
```
. //Duplicate input. Stack: 5 5
, //Get array less than top of stack. Stack: 5 [0 1 2 3 4]
\ //Switch top two elements of stack. Stack: [0 1 2 3 4] 5
{\.*<}+ //Create a block (to be explained), and prepend the top of the stack.
//Stack: [0 1 2 3 4]{5\.*<}
? //Find the first element of the array for which the block is true.
//So, find the first element of [0 1 2 3 4] for which {5\.*<} evaluates to true.
//The inner block squares a number and returns true if it is greater than the input.
( //Decrement by 1
```
[Answer]
# Haskell, 147 138 134 128 bytes
Not the shortest code in the world, but it does run in O(log n), and on arbitrary-sized numbers:
```
h x=div(x+1)2
n%(g,s)|g*g<n=(g+s,h s)|g*g>n=(g-s,h s)|0<1=(g,0)
f(x:r@(y:z:w))|x==z=min x y|0<1=f r
s n=fst$f$iterate(n%)(n,h n)
```
This does a binary search of the range [0..n] to find the best lower approximation to sqrt(n). Here is an ungolfed version:
```
-- Perform integer division by 2, rounding up
half x = x `div` 2 + x `rem` 2
-- Given a guess and step size, refine the guess by adding
-- or subtracting the step as needed. Return the new guess
-- and step size; if we found the square root exactly, set
-- the new step size to 0.
refineGuess n (guess, step)
| square < n = (guess + step, half step)
| square > n = (guess - step, half step)
| otherwise = (guess, 0)
where square = guess * guess
-- Begin with the guess sqrt(n) = n and step size (half n),
-- then generate the infinite sequence of refined guesses.
--
-- NOTE: The sequence of guesses will do one of two things:
-- - If n has an integral square root m, the guess
-- sequence will eventually be m,m,m,...
-- - If n does not have an exact integral square root,
-- the guess sequence will eventually alternate
-- L,U,L,U,.. between the integral lower and upper
-- bounds of the true square root.
-- In either case, the sequence will reach periodic
-- behavior in O(log n) iterations.
guesses n = map fst $ iterate (refineGuess n) (n, half n)
-- Find the limiting behavior of the guess sequence and pick out
-- the lower bound (either L or m in the comments above)
isqrt n = min2Cycle (guesses n)
where min2Cycle (x0:rest@(x1:x2:xs))
| x0 == x2 = min x0 x1
| otherwise = min2Cycle rest
```
*Edit:* Saved two bytes by replacing the "otherwise" clauses with "0<1" as a shorter version of "True", and a few more by inlining g\*g.
Also, if you are happy with O(sqrt(n)) you could simply do
```
s n=(head$filter((>n).(^2))[0..])-1
```
for 35 characters, but what fun is that?
*Edit 2:* I just realized that since pairs are sorted by dictionary order, instead of doing min2Cycle . map fst, I can just do fst . min2Cycle. In the golfed code, that translates to replacing f$map fst with fst$f, saving 4 more bytes.
*Edit 3:* Saved six more bytes thanks to proudhaskeller!
[Answer]
**JavaScript ~~91~~ ~~88~~ 86:** Optimized for speed
```
function s(n){var a=1,b=n;while(Math.abs(a-b)>1){b=n/a;a=(a+b)/2}return Math.floor(a)}
```
**JavaScript 46:** Non optimized for speed
```
function s(n){a=1;while(a*a<=n)a++;return a-1}
```
Here is a JSFiddle: <http://jsfiddle.net/rmadhuram/1Lnjuo4k/>
[Answer]
# C 95 ~~97~~
**Edit** Typedef, suggested by @Michaelangelo
This should be more or less a straightforward implementation of Heron algorithm. The only quirk is in computing the average avoiding integer overflow: a=(m+n)/2 does not work for biiiig numbers.
```
typedef uint64_t Z;
Z q(Z x)
{
Z n=1,a=x,m=0;
for(;a-m&&a-n;) n=a,m=x/n,a=m/2+n/2+(m&n&1);
return a;
}
```
[Answer]
# C# ~~64~~ ~~62~~ 55
Since this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") (and I'm terrible with maths), and runtime is merely a suggestion, I've done the naive approach that runs in linear time:
```
decimal f(ulong a){var i=0m;while(++i*i<=a);return--i;}
```
([test on dotnetfiddle](https://dotnetfiddle.net/vAa4CX))
Of course, it's terribly slow for larger inputs.
[Answer]
## Clojure - 51 or 55 bytes
Checks all numbers from n to 0, giving the first one where `x^2 <= n`. Runtime is `O(n - sqrt n)`
Unnamed:
```
(fn[x](first(filter #(<=(* % %)x)(range x -1 -1))))
```
Named:
```
(defn f[x](first(filter #(<=(* % %)x)(range x -1 -1))))
```
Example:
```
(map (fn[x](first(filter #(<=(* % %)x)(range x -1 -1)))) (range 50))
=> (0 1 1 1 2 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 7)
```
[Answer]
# Befunge 93 - 48 Bytes or 38 Characters
```
101p&02p>02g01g:*`#v_01g1-.@
^ p10+1g10<
```
Try it over [here.](http://www.bedroomlan.org/tools/befunge-93-playground)
[Answer]
# Cobra - 62
```
do(n as uint64)as uint64
o=n-n
while o*o<n,o+=1
return o
```
# Batch - 74
```
set a=0
:1
set /ab=%a%*%a%
if %b% LSS %1 set /aa=%a%+1&goto 1
echo %a%
```
[Answer]
**Haskell, 53 50 49 characters, O(log n)**
```
s n=until((<=n).(^2))(\g->g-1-div(g^2-n-1)(2*g))n
```
this solution implements the newton-raphson method, although it searches integers instead of floats.
wiki: <http://en.wikipedia.org/wiki/Newton%27s_method>
the complexity seems to be about O(log n), but is there a proof of it? please answer in the comments.
[Answer]
# J (10)
Very, very, very inspired by the [answer of @Dennis](https://codegolf.stackexchange.com/a/35199/18638):
```
<.@%~^&1.5
```
And a slightly longer, but with better performance (I suspect):
```
<.@(-:&.^.)
```
`floor(halve under log)`
To execute, indented parts are input:
```
f=:<.@%~^&1.5
f 0 8 12 16
0 2 3 4
g=:<.@(-:&.^.)
g 0 8 12 16
0 2 3 4
```
[Answer]
# APL - 12 chars, 19 bytes
```
{⌊(⍵*1.5)÷⍵}
```
example use:
```
{⌊(⍵*1.5)÷⍵}17
```
returns 4
## Test vector
```
{⌊(⍵*1.5)÷⍵}¨0 1 2 3 4 8 9 15 16 65535 65536 18446744073709551615
```
returns
1 1 1 1 2 2 3 3 4 255 256 4294967296
[Try Online](http://tryapl.org/?a=%7B%u230A%28%u2375*1.5%29%F7%u2375%7D%A80%201%202%203%204%208%209%2015%2016%2065535%2065536%2018446744073709551615&run)
**Big thanks to**: user "ssdecontrol" for algorithm
[Answer]
## C99 (108 characters)
Here is my own solution in C99, which is adapted from an algorithm in [an article on Wikipedia](http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_.28base_2.29). I'm sure it must be possible to do much better than this in other languages.
Golfed:
```
uint64_t s(uint64_t n){uint64_t b=1,r=0;while(n/b/4)b*=4;for(;b;b/=4,r/=2)n>=r+b?r+=b,n-=r,r+=b:0;return r;}
```
Partially golfed:
```
uint64 uint64_sqrt(uint64 n)
{
uint64 b = 1, r = 0;
while (b <= n / 4)
b *= 4;
for (; b; b /= 4, r /= 2)
if (n >= r + b)
{ r += b; n -= r; r+= b; }
return r;
}
```
Ungolfed:
```
uint64_t uint64_sqrt(uint64_t const n)
{
uint64_t a, b, r;
for (b = 1; ((b << 2) != 0) && ((b << 2) <= n); b <<= 2)
;
a = n;
r = 0;
for (; b != 0; b >>= 2)
{
if (a >= r + b)
{
a -= r + b;
r = (r >> 1) + b;
}
else
{
r >>= 1;
}
}
// Validate that r² <= n < (r+1)², being careful to avoid integer overflow,
// which would occur in the case where n==2⁶⁴-1, r==2³²-1, and could also
// occur in the event that r is incorrect.
assert(n>0? r<=n/r : r==0); // Safe way of saying r*r <= n
assert(n/(r+1) < (r+1)); // Safe way of saying n < (r+1)*(r+1)
return r;
}
```
[Answer]
# JavaScript 73 81 (to comply with 64-bit numbers requirement)
`n=prompt();g=n/3;do{G=g,g=(n/g+g)/2}while(1E-9<Math.abs(G-g))alert(Math.floor(g))`
Implementing *Heron of Alexandria's* algorithm...
[Answer]
## Powershell (52) Limited to Int32 (-2,147,483,648 to 2,147,483,647)
```
function f($n){($n/2)..0|%{if($_*$_-le$n){$_;exit}}}
```
I'm screaming at Powershell right now trying to make the last test case work but no matter what I do Powershell winds up using the pipeline variable $\_ as an Int32, and I can't find a way around it right now.
So I'll just limit my answer for now. If I can find a better way to handle uint64s I will edit. (The last test case is too big for Powershell's normal Int64 type, by the way!)
Here are a few test cases (with a bit of extra output I used to track the time)
```
f 17
4
Elapsed Time: 0.0060006 seconds
f 65
8
Elapsed Time: 0.0050005 seconds
f 65540
256
Elapsed Time: 1.7931793 seconds
f 256554
506
Elapsed Time: 14.7395391 seconds
```
I don't know my O()s, but this seems like a pretty dramatic jump.
[Answer]
Caveat: as of 2011, R had no built-in support for 64 bit integers as I had assumed it did. These answers might be invalid on that technicality, but then again R has changed a lot in the last 3 years.
---
## R, 85
Using Newton's method:
```
function(n){s=F
x=n
y=(1/2)*(x+n/x)
while(abs(x-y)>=1){x=y
y=(1/2)*(x+n/x)}
trunc(y)}
```
which converges quadratically. +2 characters to assign the function to a variable for benchmarking:
```
microbenchmark(q(113424534523616))
# Unit: microseconds
# expr min lq median uq max neval
# q(113424534523616) 24.489 25.9935 28.162 29.5755 46.192 100
```
---
## R, 37
Brute force:
```
function(n){t=0
while(t^2<n) t=t+1
t}
```
And the same check:
```
microbenchmark::microbenchmark(q(113424534523616),times=1)
# Unit: seconds
# expr min lq median uq max neval
# q(113424534523616) 4.578494 4.578494 4.578494 4.578494 4.578494 1
```
---
## R, 30
The [cheap/brilliant exponentiation trick](https://codegolf.stackexchange.com/a/35199/26904):
```
function(n) trunc(n^(1.5)/n)
```
which also happens to be very fast (although not as fast as the built-in):
```
microbenchmark(q(113424534523616),sqrt(113424534523616))
# Unit: nanoseconds
# expr min lq median uq max neval
# z(113424534523616) 468 622.5 676.5 714.5 4067 100
# sqrt(113424534523616) 93 101.0 119.0 160.5 2863 100
```
[Answer]
# C, 38
```
f(n){int m;while(++m*m<=n);return--m;}
```
Translation of my Forth submission. Slow but correct. O(√n). Tested on OS X (64 bit).
[Answer]
# dc, 50 bytes
```
dc -e"?dsist[lt2/dstd*li<B]dsBx[lt1+dstd*li!<A]dsAxlt1-f"
```
Spaced out and explained:
```
# The idea here is to start with the input and reduce it quickly until it is
# less than what we want, then increment it until it's just right
? # Take input from stdin
d si st # Duplicate input, store in `i' and in `t'
[ # Begin macro definition (when I write in dc, "macro"=="function")
lt # Load t, our test term
2/ # Divide t by two
d st # Store a copy of this new term in `t'
d* # Duplicate and multiply (square)
li<B # Load i; if i<(t^2), execute B
] d sB x # Duplicate, store function as `B', and execute
# Loop ends when t^2 is less than i
[ # Begin macro definition
lt # Load t, our test term
1+ # Increment
d st # Store a copy of this new term in `t'
d* # Duplicate and multiply (square)
li!<A # Load i; if i>=(t^2), execute A
] d sA x # Duplicate, store function as `A', and execute
# Loop ends when t^2 == i+1
lt 1- f # Load t, decrement, and dump stack
```
[Answer]
# C, ~~139~~ ~~137~~ 136 bytes
My first try at code golf. It looks like it's the shortest in C that fits the "efficient" requirement, as it runs in `O(log n)` time, using only addition and bit shifts. Though I'm sure it could be shorter yet...
It should work just fine for larger integer values too as long as the `a=32` part is changed to `a=NUMBITS/2`.
```
typedef uint64_t x;x f(x o){x a=32,t=0,r=0,y=0,z;for(;a--+1;){z=(x)3<<2*a;y*=2;t++<r?y++,r-=t++:t--;t*=2;r*=4;r+=(o&z)>>2*a;}return y;}
```
[Answer]
**C - 50 (61 without global)**
```
typedef uint64_t T;T n,i;f(){while(++i*i<=n);--i;}
```
It use global variables as parameter and return value to save space.
No global version :
```
typedef uint64_t T;T f(T n){T i=0;while(++i*i<=n);return--i;}
```
[Answer]
## C++ 125
```
int main()
{
uint64_t y;cin>>y;
double x=y/2,d,z;
while((d=(x*x-y))>0.5)
{
d<0?x+=0.5:x-=0.5;
}
cout<<(uint64_t)x;
}
```
] |
[Question]
[
Write a program or function that takes in a string and outputs a count of each modern English alphabet letter in the string, case-insensitive.
Input: A string consisting of printable ASCII characters (code points 32-126).
Output: A list of pairs, where each pair consists of a letter and its count in the string. The list should be sorted in alphabetical order by letter. The list shall omit letters occurring zero times.
## Test Cases
```
Input: "hello world"
Output: [('d', 1), ('e', 1), ('h', 1), ('l', 3), ('o', 2), ('r', 1), ('w', 1)]
Input: "The quick brown fox jumps over the lazy dog"
Output: [('a', 1), ('b', 1), ('c', 1), ('d', 1), ('e', 3), ('f', 1), ('g', 1), ('h', 2), ('i', 1), ('j', 1), ('k', 1), ('l', 1), ('m', 1), ('n', 1), ('o', 4), ('p', 1), ('q', 1), ('r', 2), ('s', 1), ('t', 2), ('u', 2), ('v', 1), ('w', 1), ('x', 1), ('y', 1), ('z', 1)]
```
Code Golf Specifics:
Your goal is to write the shortest possible code in bytes that correctly solves the problem. Your code must be able to handle any valid input within the given constraints. Note that your code should treat uppercase and lowercase letters as equivalent.
Good luck!
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
ǍɽĊs
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLHjcm9xIpzIiwiIiwiXCJUaGUgcXVpY2sgYnJvd24gZm94IGp1bXBzIG92ZXIgdGhlIGxhenkgZG9nXCIiXQ==)
**How it works**:
```
ǍɽĊs
Ǎɽ Remove non-alphabetical chars and lowercase
Ċ Count of each element
s Sorted
```
[Answer]
# [Python](https://www.python.org), 60 bytes
```
lambda s:{c:s.lower().count(c)for c in s.lower()if'`'<c<'{'}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3bXISc5NSEhWKraqTrYr1cvLLU4s0NPWS80vzSjSSNdPyixSSFTLzFOBSmWnqCeo2yTbq1eq1EDN2FhRlAhWnaSh5pObk5OsolOcX5aQoKmlqQuQXLIDQAA)
Returns a dictionary. Suggested by *@JonathanAllan*.
## [Python](https://www.python.org), 70 bytes
```
lambda s:sorted((c,s.lower().count(c))for c in{*s.lower()}if'`'<c<'{')
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY33XISc5NSEhWKrYrzi0pSUzQ0knWK9XLyy1OLNDT1kvNL80o0kjU10_KLFJIVMvOqteCStZlp6gnqNsk26tXqmhDTdhYUZQLVp2koeaTm5OTrKJTnF-WkKCppQuUXLIDQAA)
Returns a sorted list of tuples.
## [Python](https://www.python.org), 75 bytes
```
lambda s:sorted({*zip(x:=[*filter(str.isalpha,s.lower())],map(x.count,x))})
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3vXMSc5NSEhWKrYrzi0pSUzSqtaoyCzQqrGyjtdIyc0pSizSKS4r0MosTcwoyEnWK9XLyy4FimpqxOrmJQHV6yfmleSU6FZqatZoQI3cWFGXmlWikaSh5pObk5OsolOcX5aQoKmlC5RcsgNAA)
Returns a sorted list of tuples.
#### Commented
```
lambda s: sorted( # Define an anonymous function which takes a string, s,
# and returns a sorted version of the following:
(c, s.lower().count(c)) # a tuple of the character, c, and its count
# in the lowercase version of s
for c in {*s.lower()} # for each character, c, in the lowercase version of s uniquified
if '`' < c < '{' ) # but only keep it if it is between the characters
# '`' (right before 'a') and '{' (right after 'z')
# i.e., it's alphabetic
```
```
lambda s: sorted( # Define an anonymous function which takes a string, s,
# and returns a sorted version of the following:
{*zip( # a uniquified version of two iterables zipped together:
x := [*filter( # filter by
str.isalpha, # is the character in the alphabet
s.lower() # apply to a lowercase version of s
)], # and store in x
map(x.count, x) )}) # the counts of each character in x
```
[Answer]
# [jq](https://stedolan.github.io/jq/), 66 bytes
```
ascii_downcase|reduce match("[a-z]";"g").string as $c({};.[$c]+=1)
```
[Try it online!](https://tio.run/##pc7ZQoJAGEDhe5/ij6ggg7K9yMr2fTFbiWycGWFQGJgZXFB79Mh36Nx@NydMiwJJzFiT8H6MkaRjQUmGKURI4cDQXGTlnuZovmbaUgkW@4Ak6NgYTRzb1bFXrlbMooAZbVafm18wzMXykmUvr1RW19Y3Nre2d3adver@wWHt6Pjk9Oz84vLq@ub27v7hsf7UeH55fXv/cD@9r@Y3amFC237Awk43inmSCqmyXn8wzEfjyU@pEVBIM4Y70BLTUWjzAYRZlFACvEcFqKl3UT4Ewn27VPtnvzxRjMeysOp/ "jq – Try It Online")
`reduce` is just too good.
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~151~~ ~~142~~ 135 bytes
```
s->{var m=new java.util.TreeMap();for(var c:s.replaceAll("[^a-zA-Z]","").toCharArray())m.merge(c|=32,1,(a,b)->(int)a+(int)b);return m;}
```
[Try it online!](https://tio.run/##fU/BTsMwDD3Tr7B6SqCNBNzoVmlC4sRO24lpSG6XdunSJLhpRzf27aUbOyAh4Ytlv@fn9yrsMK42u0HVzpKHapxF65UWRWtyr6wRt0nwB5yjSwLXZlrlkGtsGpijMnAMYKzGox/3L1eBycKTMmU0UtzkeYuEuZcUwas1ZZpCMR2aOD12SFBPjdz/@rIkKccjxpPCEjsz8qdGkHQacznTmoWrd4wPs/htHUZhyIW3Z/0ZEfaM81rUkkrJ8q/p40N0HzGMMh6nTBnP8e7SMp6Q9C0ZqJPTkFzsX2NdU3RWbaAew7GfGKs1IJUNPwY3i77xsha29cKNkNeGFQKd0z0Lt1JrC3tLehNynvxPXm4lfLQq30FGdm@gsJ9QtbVrwHaSwI@wxkMPG1texM4uT8Fp@AY)
Saved 15 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210).
[Answer]
# [Perl 5](https://www.perl.org/) -n, 37 bytes
```
for$l(a..z){/$l/i&&say"$l ".s/$l//gi}
```
[Try it online!](https://tio.run/##K0gtyjH9/z8tv0glRyNRT69Ks1pfJUc/U02tOLFSSSVHQUmvGCSgn55Z@/@/R2pOTr6OQnl@UU6K4r/8gpLM/Lzi/7p5vmWmeoYGAA "Perl 5 – Try It Online")
[Answer]
# Excel, ~~85~~ 82 bytes
Saved 3 bytes thanks to [JvdV](https://codegolf.stackexchange.com/questions/258761/counting-letters-in-a-string/258876?noredirect=1#comment571179_258876)
```
=LET(c,CHAR(ROW(65:90)),q,LEN(A1)-LEN(SUBSTITUTE(UPPER(A1),c,)),FILTER(c&"="&q,q))
```
The `LET()` function allows you to assign variables to values and reference them by name later. Every term is a pair except the last which is the output.
* `c,CHAR(ROW(65:90))` creates an array of the strings `A` through `Z`.
* `q,LEN(a)-LEN(SUBSTITUTE(UPPER(a),c,))` creates an array of how many times each letter appears by measuring the length of the input vs. the length if we replace that letter with nothing. `SUBSTITUTE()` is case-sensitive so we transform the input to uppercase.
* `FILTER(c&"="&q,q)` combines the array of letters with the count of each character and then filter for just those where the count (`q`) was truthy (anything not zero).
[](https://i.stack.imgur.com/08DN1.png)
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 62 bytes
```
$args-match'[a-z]'|%{"$_"|% *l*r}|group|%{,($_.Name,$_.Count)}
```
[Try it online!](https://tio.run/##lYy9DoIwFEZ3nuKmqVYN5Q1MTNgcnNyMIRULiKUXb4v4A7464uKs05d8J@fU2GpyhTZGpkh64NnyOXBFuZOV8mkhdko@9qKbPBlPWDeBhVlQ3@WETT2e4Ywn0UZVOhw3xsb6eT/0QcCdJ1gC@4QRWiRzZMGUZ7D6gA5itFdNfoty7dCCjLGqSTsXMPZ1t4WGS3NKz3AgbC1keIOyqWoHOLrgR2zU4w5HzP9tCxBRJF5ClniyQvxkD28 "PowerShell Core – Try It Online")
```
$args-match'[a-z]' # For each character argument, exclude non letters characters
|%{"$_"|% *l*r} # Converts to lowercase
|group # Groups them
|%{,($_.Name,$_.Count)} # build pairs of letters and counts
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~97~~ ~~94~~ 87 bytes
* -3 thanks to Unrelated String
* -7 thanks to c--
Uses uppercase as the challenge only states case-insensitive.
```
f(char*s){for(int a[96]={},i=64;i<90;)*s?a[*s++&95]++:a[++i]&&printf("%c:%d ",i,a[i]);}
```
[Try it online!](https://tio.run/##PU9BTsMwELznFYOlRo5tpB6gUmoCVx7ALcrBOEnrksbBdlsgytuD0yIuq52dndlZfb/Tep5bqvfKMZ@NrXXU9AGqzDdVMU7CFJsHaZ7ytcyYf1El85yn@WPF@VaVnJsqTQcXFS0lK71d1SDCCFWaKpPTvDgdlenp2Zo6w5gAyyEwX0bziADy2nSdFbhY19V3RNyGb/sGnyejP/Du7KVHa79wOB2HpoY9Nw4h8p36@UZtd/5PtI51EmAsyCS2yyeh8BIRYzgFTwnJbhmA/8gexXOMHJcyeWVaygLnVzAl0/wL "C (gcc) – Try It Online")
Ungolfed:
```
f(char*s){
for(int a[96]={},i=64;
i<90;) // for all characters in string, then from 'A' to 'Z':
*s? // done processing string?
a[*s++&95]++: // no, uppercase letter and increment count
a[++i]&&printf("%c:%d ",i,a[i]); // yes, print counts
}
```
[Answer]
# JavaScript, 68 bytes
```
s=>s.toLowerCase(m={}).match(/[a-z]/g).sort().map(l=>m[l]=-~m[l])&&m
```
Try it:
```
f=s=>s.toLowerCase(m={}).match(/[a-z]/g).sort().map(l=>m[l]=-~m[l])&&m
;[
'hello world',
'The tuick brown fox jumps over the lazy dog'
].forEach(s=>console.log(f(s)))
```
## UPD 73 -> 68
Thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) for the tips ([one](https://codegolf.stackexchange.com/questions/258761/counting-letters-in-a-string/258779?noredirect=1#comment571012_258779), [two](https://codegolf.stackexchange.com/questions/258761/counting-letters-in-a-string/258779?noredirect=1#comment571013_258779)) to reduce bytes count
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
álТøê
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8MKcwxMOLTq84/Cq//@jlTyUdJRSgTgHivOBGAQVgLgcyi@CyqUAsaJSLAA "05AB1E – Try It Online")
Input as a list of characters.
**Alternative 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer with input as a string:** (suggested by *@KevinCruijssen*)
```
ál{Åγø
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8MKc6sOt5zYf3vH/v0dqTk6@jkJ5flFOiiIA "05AB1E – Try It Online")
*-3 thanks to @KevinCruijssen*
#### Explanation
```
á # Filter for alphabetic characters only
lÐ # Convert to lowercase and triplicate
¢ # Count the occurences of each character
øê # Zip, sort, and uniquify
```
```
á # Filter for alphabetic characters only
l{ # Convert to lowercase and sort
Åγ # Run-length encode the string
ø # Zip
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~38~~ 29 bytes
```
T`Llp`ll_
O`.
(.)\1*
$1, $.&¶
```
[Try it online!](https://tio.run/##K0otycxL/P8/JMEnpyAhJyeeyz9Bj0tDTzPGUItLxVBHQUVP7dC2//89UnNy8nUUyvOLclIUAQ "Retina 0.8.2 – Try It Online") Output includes trailing newlines. Saved 9 bytes thank to @FryAmTheEggman. Explanation:
```
T`Llp`ll_
```
Convert letters to lower case and delete all other printable ASCII.
```
O`.
```
Sort the characters.
```
(.)\1*
$1, $.&¶
```
Output the count of each letter.
Previous 38-byte version worked with any input, not just printable ASCII:
```
T`L`l
O`.
M!`([a-z])\1*
(.)\1*
$1, $.&
```
[Try it online!](https://tio.run/##K0otycxL/P8/JMEnIYfLP0GPy1cxQSM6UbcqVjPGUItLQw9MqRjqKKjoqf3/75Gak5Ovo1CeX5SToggA "Retina 0.8.2 – Try It Online") Explanation:
```
T`L`l
```
Lowercase the input string.
```
O`.
```
Sort the characters.
```
M!`([a-z])\1*
```
Extract the runs of identical letters.
```
(.)\1*
$1, $.&
```
Output the count of each letter.
~~31~~ 30 bytes in [Retina](https://github.com/m-ender/retina/wiki/The-Language) 1:
```
.
$L
O`.
L$`([a-z])\1*
$1, $.&
```
[Try it online!](https://tio.run/##K0otycxLNPz/X49LxYfLP0GPy0clQSM6UbcqVjPGUItLxVBHQUVP7f9/j9ScnHwdhfL8opwURQA "Retina – Try It Online") Explanation:
```
.
$L
```
Lowercase the input.
```
O`.
```
Sort the characters.
```
L$`([a-z])\1*
```
For each run of identical letters...
```
$1, $.&
```
... output the count of each letter.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~21~~ 23 bytes
```
YSSLCaFiUQy@XL;Pi.(iNy)
```
How?
```
YSSLCaFiUQy@XL;Pi.(iNy) : One arg; str
a : First input
LC : To lowercase
SS : Sort
Y : Yank
Fi : For i in
UQy : Unique values of y
@XL : Only lowercase alphabet characters
P : Print
i : Letter
. : Concatenated with
iN : Letter in
y : Input
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJZU1NMQ2FGaVVReUBYTDtQaS4oaU55KSIsIiIsIiIsIlwiVGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZ1wiIl0=)
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), ~~185~~ ... 134 bytes
```
var c,d:char;s:string;i:word;begin;read(s);for c:=^to^do begin;i:=0;for d in upcase(s)do i+=ord(c=d);if i>0then writeln(c,i)end;end.
```
[Try it online!](https://tio.run/##JY1BDsIgEEXjNVzNssRqumaCR2mCM9MyCYEG0B4fiS7@6r28f/hKPt63g3r/@AI0s6XgC1ZbW9G0o9ozF8aX7JqwiOepGtzyUK1bLy2vV87wp2rd8kMMmuB9kK8y7MH15kZkIscGdQN9Li1IgrNok5gmmtVIYhx79B4kxgzjNfIX) (134b, courtesy of @michael-tkach)
~~[150b](https://tio.run/##JY7BDsIgEER/ZY80QdOLJkLwX3B3abch0ADaz0esh7m8eZPM7iv6eAk79v7xBVCTrqa2Immxojdz5EL2xYskW9iTqpMNucBm3P3WMjxmyvCv0Thci9omK8bNp0UgCd47@spjOEwJgI6grZxGhUqGHECe80mOIo1jUqgH50S/XHtfOcYM40ikLw)~~
~~[155b](https://tio.run/##JY7BDsIgEER/ZY80qaYXTYTgv@AulG0INAvaz0esh7m8eZPM7iq6dAk79v5xAlXXJpxXgzNpjE4Mz5s@ipB5@ZWzEe9I1cmEIrBpe7@1Ao@FCvxr1BajqG0yrO1yWgSc4b2jq34Mh8kB0BK06POoUPGQA/BzOckh3HzKCufBfaZfrr1Hn1KBcSTRFw)~~
~~[160b](https://tio.run/##JY7BDsIgEETvfsUe21hN9dBECP4L7kLZhoBZiP18xHqYy5s3ybxtQRsv/o2tfaxAUaUKp1XjRAqDFc3TpvYspF9u5aTFWRrKqH0W2JS51Qz3hfLp36IyGGTYzo9l1KzMfHgEnCDm3Qna4vq6@@wBDUENLvUWB@6@B37OB9mFq4tpwKlzl@iXa2vBxZihv4n0BQ)~~
~~[161b](https://tio.run/##HY6xDoMwDER3vsJbQaIV7dAhVvovqW3AKEpQEpXPTwPDLe/dSbe7TM7f551q/bkE2eSSNCxIIxtaXUIdN3PExPiVRUNHxt7cDZM47vOAc0ywGfssEV5vjnCVUI2dLsWgAXw8JJHL0gYcO52BLENZJTRLvQ7YkH6mixxJi/jQ03jypmlACXzmUesq3kdodzz/AQ)~~
~~[162b](https://tio.run/##JY7BDoIwEETvfsXegAQNZxr8l7K7hdXaYlup@vO1wcNc3uRNZtMRtT2bDUvZdYDYY09jTEHcomTMPpCaeRGnAmtqY6eMD4AgrtEzEptlldvdPpzfniGm157fn29D/vSXZJyGw6BqgPWZA@rIdYc8iAGcCNLKrrbYSqcqkutwkBwksXUt9tKxI1VzKWVlaz3UW5Z@)~~
~~[185b](https://tio.run/##JczBDoIwDMbxV@kNSNBwMB624LuUrkB1bthNUF8eQQ89fP9f0gkToT/0E63rjApYJ5OyShgs1c7QiGrFSMjnk@14kGCV0ZWpssm0Pi6shIn3jaYtsCPH/TDK9ebvIU4PTfk5L6/3p7B9VCCQAAguwv@XmLb5gdsh7SA9uJYgjxy2RqVUdktyaf5pUcnsQ0n1Bhzcfsd1Hdn7CEtU774)~~
Iterates over the alphabet and the input string `s`, comparing chars `d` and `c`. The `for <char> in <string>` syntax was handy. Implemented some of the [Pascal golfing tips](https://codegolf.stackexchange.com/questions/240117/tips-for-golfing-in-pascal).
[Answer]
## Mathematica (Wolfram Language), 34 bytes
```
KeySort@*LetterCounts@*ToLowerCase
```
TIO.run is in the comments below. Edited to save 4 bytes thanks to a suggestion from ZaMoC.
[Answer]
# [Arturo](https://arturo-lang.io), 34 bytes
```
$=>[match lower&{/\pL}|tally|sort]
```
[Try it](http://arturo-lang.io/playground?CKEWco)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
⭆¹ΦEβ⟦λ№↧θλ⟧§λ¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaBjqKLhl5pSkFmmAeEk6CtE5OgrO@aVART755alFyYnFqRqFmjoKOZqxQNKxxDMvJbVCA6jIUBMIrP//90jNycnXUSjPL8pJUeT6r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
β Predefined variable lowercase alphabet
E Map over letters
λ Current letter
⟦ ⟧ Make into tuple with
№ Count of
λ Current letter in
θ Input string
↧ Lowercased
Φ Filtered where
§λ¹ Count was nonzero
⭆¹ Pretty-print
```
[Answer]
# [J9.4](https://www.jsoftware.com), 35 bytes
```
'\pL'(~.,:<@#/.~)@/:~@rxall tolower
```
# [J903](https://www.jsoftware.com), 37 bytes
```
'[a-z]'(~.,:<@#/.~)@/:~@rxall tolower
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmtxU1U9OlG3KlZdo05Px8rGQVlfr07TQd-qzqGoIjEnR6EkPye_PLUIqthNkys1OSPfIU3NTkE9IzUnJ1-hPL8oJ0XdWj0kI1WhsDQzOVshqSi_PE8hLb9CIas0t6BYIb8stUihBCidk1hVqZCSn64OMW3BAggNAA)
Explanation is the same, but the PCRE engine was updated which makes the regex 2 bytes shorter.
```
'\pL'(~.,:<@#/.~)@/:~@rxall tolower
tolower NB. lowercase the input
'\pL' rxall NB. match every letter
/:~@ NB. then sort
( )@ NB. then invoke a monadic fork
#/.~ NB. count the occurrences of each letter
<@ NB. then box each result
~. NB. uniquify the matches
,: NB. stack matches on top of counts
```
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$18\log\_{256}(96)\approx\$ 14.82 bytes
```
UgAzsAqkztcsZZZUz:
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhabQtMdq4odC7OrSpKLo6KiQqusIBJQ-QVrPVJzcvJ1FMrzi3JSFCGCAA)
#### Explanation
```
U # Lowercase
gAzsAqk # Alphabetic characters only
zt # Triplicate
cs # Counts of each
ZZ # Zip
ZU # Uniquify
z: # Sort
```
[Answer]
# JavaScript (ES6), 82 bytes
Probably takes *a list of pairs* a bit too literally... ¯\\_(ツ)\_/¯
```
s=>[...s.toLowerCase()].sort().join``.match(/([a-z])\1*/g).map(s=>[s[0],s.length])
```
[Try it online!](https://tio.run/##XcsxEoIwEEDR3lNkqBJHFj0ANraWdpgZIgQChixmAyiXj9ja/je/V7OiyndjSB3WOjZ5pPxcAABBwCsu2l8UaS4kEPrABfTYubKEQYXK8IwXKl2luJ/2WSu2OPLfTsVRHgisdm0wUsQKHaHVYLHlDU@MthbZgt7WiRC7P70ZzV5TVz3Zw@PiWINv1k/DSAxn7VnY2Kr1w2pstzt@AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [J](https://www.jsoftware.com), 32 bytes
```
(u:97+i.26)(e.#[;"+1#.=/)tolower
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmtxU0Gj1MrSXDtTz8hMUyNVTznaWknbUFnPVl-zJD8nvzy1CKrOTZMrNTkj3yFNzU5BPSM1JydfoTy_KCdF3Vo9JCNVobA0MzlbIakovzxPIS2_QiGrNLegWCG_LLVIoQQonZNYVamQkp-uDjFtwQIIDQA)
`u:97+i.26` A character vector of all lowercase letters.
`tolower` Input converted to lowercase.
`(u:97+i.26)(...)tolower` Apply inner function with lowercase alphabet as left argument and lowercased string as right argument.
`=/` Equality table.
`1#.` Sum each row. This gives a vector of length 26 with the count of each letter in the input.
`[;"+` Pair up each letter with its count.
`e.#` Only keep the pairs where the letter is an element of the input.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ŒlḟŒuṢŒr
```
[Try it online!](https://tio.run/##y0rNyan8///opJyHO@YfnVT6cOeio5OK/h9uPzrp4c4ZmpH//ytlAJXkK5TnF@WkKOkoKIVkpCoUlmYmZyskFeWX5ymk5VcoZJXmFhQr5JelFimUAKVzEqsqFVLy05UA "Jelly – Try It Online")
At least slightly less boring than if I'd used `Øa`. Feels ever so vaguely beatable, still...
```
Œl The lowercased input,
ḟŒu with elements of the uppercased input filtered out.
ṢŒr Sort and run-length encode.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 48 bytes
```
->s{[*s.upcase.chars.tally.slice(*?A..?Z).sort]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY3DXTtiqujtYr1SguSE4tT9ZIzEouK9UoSc3Iq9YpzMpNTNbTsHfX07KM09Yrzi0pia6H6XAsU0qLVM1JzcvIVyvOLclLUY7nAQiEZqQqFpZnJ2QpJRfnleQpp-RUKWaW5BcUK-WWpRQolQOmcxKpKhZT8dPVYiGELFkBoAA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, ~~15~~ 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
v r\L ü ËÎ+DÊ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=diByXEwg/CDLzitEyg&input=IlRoZSBxdWljayBicm93biBmb3gganVtcHMgb3ZlciB0aGUgbGF6eSBkb2ciCi1S)
-2 by Shaggy
Outputs a list of “ab” strings where a is the character and b is the number of occurrences
## [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ü ËÎ+DÊ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=/CDLzitEyg&input=ImFiY2FhYSIgLVE)
Doesn’t remove non-letters
Made on My iPhone
```
ü ËÎ+DÊ # input string
ü # list of same characters grouped together
Ë # map each string of same char to:
Î # the character
+DÊ # append length of group
```
[Answer]
## Common Lisp, 110 bytes
```
(lambda(s)(reduce(lambda(s c &aux(e(assoc c s)))(if e(prog1 s(incf(cdr e)))(acons c 1 s)))s :initial-value()))
```
The ungolfed version is:
```
(defun frequencies (string)
(reduce (lambda (map char)
(let ((entry (assoc char map)))
(if entry
(prog1 map
(incf (cdr entry)))
(acons char 1 map))))
string
:initial-value nil))
```
For example:
```
> (frequencies "abcbad")
((#\d . 1) (#\c . 1) (#\b . 2) (#\a . 2))
```
[Answer]
## Pascal, ~~590~~ 358 bytes
This full `program` requires a processor supporting features of ISO standard 10206 “Extended Pascal”.
Furthermore,
* the *implementation-dependent* behavior of the selection order in a `for … in` set member iteration statement must be *ascending*,
* the *implementation-defined* default `TotalWidth` for `integer`-type `write` arguments must be sufficiently large in order to leave some space between a character and the number, and
* the *implementation-defined* set of available characters contains both upper and lowercase characters.
The GPC ([GNU Pascal Compiler](https://www.GNU-Pascal.de/)) fulfills these conditions on an x86‑64 Linux system if compiling with the `‑‑extended-pascal` option.
```
program p(input,output);var c:char;f:array[char]of integer value[otherwise 0];begin while not EOF do begin read(c);c:=(c+'ABCDEFGHIJKLMNOPQRSTUVWXYZ')[index('abcdefghijklmnopqrstuvwxyz',c)+1];f[c]:=f[c]+1 end;for c in['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']do if 0<f[c]then writeLn(c,f[c])end.
```
Ungolfed:
```
program letterFrequency(input, output);
var
c: char;
letterFrequency: array[char] of integer value [otherwise 0];
begin
while not EOF(input) do
begin
{ `read(input, c)` is equivalent to `c := input^; get(input)`. }
read(input, c);
{ There is no built-in “change case” function as Pascal does not
guarantee the coexistence of lower and uppercase letters. The EP
function `index(source, pattern)` returns the index of the first
occurence of `pattern` in `source`. If `pattern` is not found,
zero is returned. Remember, `string` indices are 1-based, thus
add `1` to select the prepended value of `c`. }
c := (c + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
[index('abcdefghijklmnopqrstuvwxyz', c) + 1];
letterFrequency[c] := letterFrequency[c] + 1;
end;
for c in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] do
begin
if letterFrequency[c] > 0 then
begin
writeLn(c, letterFrequency[c]);
end;
end;
end.
```
See also [FreePascal implementation](/a/258872/94076).
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 19 bytes
```
el_'{,97>--$e`{W%}%
```
[Try it online!](https://tio.run/##S85KzP1f/T81J169WsfS3E5XVyU1oTpctVb1f62Vm3W0UkZqTk6@Qnl@UU6KkoJSSEaqQmFpZnK2QlJRfnmeQlp@hUJWaW5BsUJ@WWqRQglQOiexqlIhJT9dKbY63k1JQddOQSlGW7tW1U/rPwA "CJam – Try It Online")
Returns strings in the form of `{char}{count}`
# Explanation
```
el_'{,97>--$e`{W%}% # a function taking an input string
el_ -- # remove all elements of the input which do not occur in
'{,97> # the character range lowercase a-z
$ # sort
e` # run-length encode (1h1e2l as an example)
{W%}% # to meet the output specification of {char}{count} and not {count}{char}
# we reverse each of the arrays in this sorted array
```
[Answer]
# [Haskell](https://www.haskell.org), ~~75~~ 71 bytes
*-4 bytes thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn)*
```
f s=[(l,n)|(u,l)<-zip['A'..'Z']['a'..],n<-[sum[1|c<-s,l==c||u==c]],n>0]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN93TFIptozVydPI0azRKdXI0bXSrMgui1R3V9fTUo9Rjo9UTgaxYnTwb3eji0txow5pkG91inRxb2-SamlIgGQuUszOIhRqXkJuYmadgq5CSz6WgUFCUmVeioKKQpqDkAbQzX0chPL8oJ0VRCVUuJCNVobA0MzlbIakovzxPIS2_QiGrNLegWCG_LLVIoQQonZNYVQk0M11PCWIPzPkA)
### Explanation
List comprehensions seem to be shorter than `map` and `filter`.
```
f s=
```
Define our function, `f`, which takes a string `s`.
```
zip['A'..'Z']['a'..]
```
Create a list of (uppercase letter, lowercase letter) tuples.
```
(u,l)<-___
```
For each uppercase letter `u` and lowercase letter `l` in that list...
```
,n<-sum[1|c<-s,l==c||u==c]
```
Let `n` be the number of characters `c` in `s` for which `c` equals one of `l` and `u`...
```
[(l,n)|____,n>0]
```
Return a list of tuples of `l` and the corresponding `n` where `n` is greater than `0`.
---
A solution using `toLower` from `Data.Char` comes in at **76 bytes**:
```
import Data.Char
f s=[(l,n)|l<-['a'..'z'],n<-[sum[1|c<-s,l==toLower c]],n>0]
```
[Answer]
# [Julia 1.0](http://julialang.org/), 51 bytes
```
~s=(x='A':'Z';[[email protected]](/cdn-cgi/l/email-protection)(in(x=>x+32),s);(x.=>y)[y.>0])
```
[Try it online!](https://tio.run/##Rcm7DsIgFADQ3a@46QJEQ3xsNhD9ByeNQ7VoqZRboVhw6K9jN9dz2mB0tYk5T17QKMiR7MmZlEkcuA8d1XZGGZe7LVt5VtLIhUzskrhcX1nunbaDsXQqGmUMwojO1AVb/P3UKHgHfX/BzeFo4YER2tD1HvCjHAxzm@qboMZnwfIP "Julia 1.0 – Try It Online")
* Thanks to MarcMush for the following:
1. replace `sum(==(x),uppercase(s))` with `sum(in(x=>x+32),s)`
2. replace Tuples with Pairs (e.g., `(a,b)` vs. `a=>b`).
## 54 byte solution
```
~s=(y='A':'Z'.|>x->x=>sum(in(x=>x+32),s))[@.last(y)>0]
```
[Try it online!](https://tio.run/##Rcm7DsIgFIDh3ac46QJEbbxsJhB9ByeNQ7VoqadQuVgwpq@O3dz@fH8bUFXrmPPoOE2cHMiOnEj5FXEpIhcudFRpOlWcbzds4Rg770usnKeJidUl91Zpj5qORSMRDQzGYl2w2d@PjYRXULcnXK0ZNNxNhDZ0vQPzlhb8tLH6JKjNo2D5Bw "Julia 1.0 – Try It Online")
## 55 byte solution
```
~s=[x=>y for x='A':'Z' for y=sum(in(x=>x+32),s) if y>0]
```
[Try it online!](https://tio.run/##RYy7DsIgFEB3v@KmCxAdfGwmNOk/OGkcqqWWesutUCw49NeRuDiec5LTe9T1LqS0OHkJsozQkoUgWcWO7Mx@FKXzA9eG5x7Wh73YOAG6hVhur2m02kxo@FJ0CpFgJotNIVZ/f@oUvLy@P@FmaTZ5GaD3w@iA3srClDPWnwgNPQqRvg "Julia 1.0 – Try It Online")
* Thanks to Kirill L. for suggesting [comprehensions](https://docs.julialang.org/en/v1/manual/arrays/#man-comprehensions) and [generator expressions](https://docs.julialang.org/en/v1/manual/arrays/#Generator-Expressions)!
[Answer]
# Excel (ms365), 87 bytes
[](https://i.stack.imgur.com/FCqlV.png)
Formula in `B1`:
```
=LET(x,CHAR(ROW(97:122)),y,LEN(A1)-LEN(SUBSTITUTE(LOWER(A1),x,)),FILTER(HSTACK(x,y),y))
```
And 83 bytes if you don't want tupples, but a concatenation would do:
```
=LET(x,CHAR(ROW(97:122)),y,LEN(A1)-LEN(SUBSTITUTE(LOWER(A1),x,)),FILTER(x&"-"&y,y))
```
[Answer]
# [Java 16+ (JDK)](http://jdk.java.net/), 166 bytes
Tried to use only inline stream as a different approach, but couldn't beat the best Java answer.
```
s->s.toLowerCase().chars().distinct().filter(e->e>96&e<123).sorted().mapToObj(e->new String[]{(char)e+"",s.toLowerCase().chars().filter(o->o==e).count()+""}).toList()
```
[JDoodle (because TIO currently only supports Java up to v12)](https://www.jdoodle.com/ia/FjF "Java (JDK) – JDoodle")
] |
[Question]
[
**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.
The challenge:
>
> Input text from one file and output it to another. Solution should be a complete, working function.
>
>
>
Note: This is a [code-trolling](/questions/tagged/code-trolling "show questions tagged 'code-trolling'") question. Please do not take the question and/or answers seriously. More information [here](https://codegolf.stackexchange.com/tags/code-trolling/info "Rules").
[Answer]
# C
The whole point of having multiple programming languages, is that you need to use the right tool for the job.
In this case, we want to copy bytes from one file to another.
While we could use something fancy like bash or ruby, or fall to the power of ASM, we need something quick, good with bits and fast.
The obvious choice is C.
The SIMPLEST way of doing it would be like so:
```
#include <stdio.h>
#define THEORY FILE
#define AND *
#define PRACTICE myfile1
#define SOLUTIONS myfile2
#define ARE fopen
#define IMPORTANT "r"
#define BAD "w"
#define LOL fclose
#define PLEASE fgetc
#define HELP fputc
#define ME return
#define NEVER for
#define SURRENDER !=
#define VERY filename1
#define NOT filename2
#define _ 1
int copyFile(char* filename1, char* filename2)
{
THEORY AND PRACTICE = ARE (VERY, IMPORTANT);
THEORY AND SOLUTIONS = ARE (NOT, BAD);
NEVER (;_;)
{
HELP(PLEASE(PRACTICE),SOLUTIONS);
}
ME _SURRENDER_;
}
```
This is evil because it will read garbage on things like cygwin, is completely chinese for a beginner, will scare him when he realizes it's a call for help and, obviously, because C.
[Answer]
## sh
I like the simplicity of this one.
```
echo File1.txt > File2.txt
```
Really only works properly if `File1.txt` contains "File1.text"...
[Answer]
# AutoHotKey
```
WinActivate, file1.txt
SendInput ^a^c
WinActivate, file2.txt
SendInput ^a^v^s
```
You must first open the files in notepad or some other text editor that makes the window names start with the file names. Then it copies the contents of file1 to the clipboard (literally, using `ctrl`+`c`), and pastes it into file2, overwriting anything currently in it, and saves.
Solves the problem, but in a very inconvenient and pretty useless fashion. It would probably by easier to just copy and paste manually.
[Answer]
As everyone knows, perl is very good for manipulating files. This code will copy the contents of one file to another, and will do so with extra redundancy for good measure.
```
#Good perl programs always start thusly
use strict;
use warnings;
my $input_file = 'File1.txt';
my $output_file = 'File2.txt';
open(my $in, '<', $input_file) or die "Couldn't open $input_file $!";
my $full_line = "";
while (my $line = <$in>) {
#Get each letter one at a time for safety,
foreach my $letter (split //, $line) {
#You could and should add validity checks here
$full_line .= $letter;
#Get rid of output file if it exists! You are replacing it with
# new content so it's just wasting space.
unlink $output_file if (-e $output_file);
#Write data to new file
open(my $out, '>', $output_file) or die "Couldn't open $output_file $!";
print {$out} $full_line;
close($out);
}
}
```
To be safe, test this out on a small file at first. Once you are convinced of its correctness you can put it into production for use on very large files without worry.
[Answer]
**C#**
In order to achieve this, you must make sure to do several things:
1. Read string from file
2. Download Microsoft File IO and String Extension for Visual Studio
3. Remove viruses from string ("sanitize")
4. Write file to path
5. Delete and reload cache
Here's the code:
```
static void CopyTextFile(string path1, string path2)
{
try
{
FileStream fs = new FileStream(path1, FileMode.OpenOrCreate); //open the FTP connection to file
byte[] file = new byte[fs.Length];
fs.Read(file, 0, file.Length);
string makeFileSafe = Encoding.UTF32.GetString(file);
using (var cli = new WebClient())
{
cli.DownloadData(new Uri("Microsoft .NET File IO and String Extension Package")); //get MS package
}
fs.Dispose();
File.Create(path2);
StreamReader read = new StreamReader(path2);
read.Dispose(); //create and read file for good luck
var sb = new StringBuilder();
foreach (char c in path1.ToCharArray())
{
sb.Append(c);
}
string virusFreeString = sb.ToString(); //remove viruses from string
File.WriteAllText(path2, virusFreeString);
File.Delete(path1);
File.WriteAllText(path1, virusFreeString); //refresh cache
}
catch
{
//Don't worry, exceptions can be safely ignored
}
}
```
[Answer]
In four simple steps:
1. Print the file. You can use the `lpr` command for this.
2. Mail the printouts to a scanning service. (You will need postage for this).
3. The scanning service will scan the printouts and do OCR for you.
4. Download to the appropriate file location.
[Answer]
# Java
A lot of people find it useful to attempt to use regular expressions or to evaluate strings in order to copy them from one file to another, however that method of programming is sloppy. First we use Java because the OOP allows more transparency in our code, and secondly we use an interactive interface to receive the data from the first file and write it to the second.
```
import java.util.*;
import java.io.*;
public class WritingFiles{
public static void main(String []args){
File tJIAgeOhbWbVYdo = new File("File1.txt");
Scanner jLLPsdluuuXYKWO = new Scanner(tJIAgeOhbWbVYdo);
while(jLLPsdluuuXYKWO.hasNext())
{
MyCSHomework.fzPouRoBCHjsMrR();
jLLPsdluuuXYKWO.next();
}
}
}
class MyCSHomework{
Scanner jsvLfexmmYeqdUB = new Scanner(System.in);
Writer kJPlXlLZvJdjAOs = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("File2.txt"), "utf-8"));
String quhJAyWHGEFQLGW = "plea";
String LHpkhqOtkEAxrlN = "f the file";
String SLGXUfzgLtaJcZe = "e nex";
String HKSaPJlOlUCKLun = "se";
String VWUNvlwAWvghVpR = " ";
String cBFJgwxycJiIrby = "input th";
String ukRIWQrTPfqAbYd = "t word o";
String CMGlDwZOdgWZNTN = quhJAyWHGEFQLGW+HKSaPJlOlUCKLun+VWUNvlwAWvghVpR+cBFJgwxycJiIrby+SLGXUfzgLtaJcZe+ukRIWQrTPfqAbYd+LHpkhqOtkEAxrlN;
public static void fzPouRoBCHjsMrR(){
System.out.println(CMGlDwZOdgWZNTN);
kJPlXlLZvJdjAOs.write(jsvLfexmmYeqdUB.next());
}
}
```
---
In theory (I haven't tested it) this makes the user manually input the content of the first file (word by word) and then writes it to the second file. This response is a play on the ambiguity of the question as to what it means by "input text from one file," and the crazy variable names (generated randomly) were just for some extra fun.
[Answer]
## sh
Like @Shingetsu pointed out, one has to use the right tool for the right job. Copying the content from one file to another is an old problem, and the best tool for such file-management tasks is using the shell.
One shell command that every programmer has to familiarise themself with is the common `tac` command, used to **tac**k the content of files together, one after another. As a special case of this, when only one file is passed in it is simply spit out as-is again. We then simply redirect the output to the appropriate file:
```
tac inputfile.txt >outputfile.txt
```
Simple and to-the-point, no tricks!
[Answer]
# Perl
Antivirus included.
```
#!/usr/bin/perl -w
use strict;
use warnings;
print "Copy the text of the file here: (warning: I can't copy files with newlines):\n";
my $content = <STDIN>;
print "\n\nPlease wait, removing viruses...";
my @array = split(//,"$content");
my @tarray;
foreach my $item (@array)
{
if ($item ne "V" && $item ne "I" && $item ne "R" && $item ne "U" && $item ne "S")
{
push(@tarray, $item);
}
}
print "\n\nNow copy this into the target file:\n";
foreach my $item (@tarray){ print "$item"};
```
[Answer]
# Windows Batch
(because you gotta have this supposedly "dead" language ;-)
```
@echo off
setlocal enabledelayedexpansion
for %%I in ('type %1') do set this=!this!%%I
echo !this!>%2 2>nul
```
You simply call this as `copy.bat file1.txt file2.txt` (or whatever files you want)
If only it would keep line breaks...
[Answer]
# Linq
Efficiency is not important, correctness is. Writing in a functional style results in more clear and less error-prone code. If performance does turn out to be a problem, the last ToArray() line can be omitted. It's better to be lazy anyway.
```
public void CopyFile(string input, string output)
{
Enumerable
.Range(0, File.ReadAllBytes(input).Length)
.Select(i => new { i = i, b = File.ReadAllBytes(input)[i] })
.Select(ib => {
using (var f = File.Open(output, ib.i == 0 ? FileMode.Create : FileMode.Append))
f.Write(new byte[] { ib.b }, 0, 1);
return ib; })
.ToArray();
}
```
[Answer]
**Smalltalk**
There is a library yet ported to several Smalltalk dialects (Visualworks, Gemstone Squeak/Pharo, ...) named [Xtreams](https://code.google.com/p/xtreams/) that makes this task more than easy.
FileStream would be as simple as `'foo' asFilename reading` and `'bar' asFilename writing` for example in Visualworks, but are dialect specific.
For this reason I demonstrate the algorithm with dialect neutral internal Streams instead.
A good idea could be to process each byte code in increasing order:
```
| input |
input := 'Hello world' asByteArray reading.
^((ByteArray new writing)
write: ((0 to: 255) inject: ByteArray new reading into: [:outputSoFar :code |
| nextOutput |
nextOutput := ByteArray new writing.
((input += 0; selecting: [:c | c <= code]) ending: code inclusive: true) slicing do: [:subStream |
| positionable |
positionable := subStream positioning.
nextOutput write: (outputSoFar limiting: (positionable ending: code) rest size).
nextOutput write: (positionable += 0; selecting: [:c | c = code])].
nextOutput conclusion reading]);
conclusion) asString
```
Of course, it is also possible to process in random order, but i'm afraid that it makes the code a bit too compact:
```
| input output |
input := 'Hello world' asByteArray reading.
output := ByteArray new writing.
(0 to: 255) asArray shuffled do: [:code |
output += 0.
(input += 0; ending: code inclusive: true) slicing do: [:subStream |
| positionable |
positionable := subStream positioning.
output ++ (positionable += 0; rejecting: [:c | c = code]) rest size.
output write: (positionable += 0; selecting: [:c | c = code])]].
^output conclusion asString
```
**EDIT**
Ah stupid me, I didn't saw the log2 solution:
```
| input output |
input := 'Hello world' asByteArray reading.
(output := ByteArray new writing) write: (input collecting: [:e | 0]).
output := (0 to: 7) asArray shuffled inject: output into: [:outputSoFar :bit |
(ByteArray new writing)
write:
(((input += 0; collecting: [:e | e >> bit bitAnd: 1]) interleaving: outputSoFar conclusion reading)
transforming: [ :in :out | out put: in get << bit + in get]);
yourself].
^output conclusion asString
```
[Answer]
## **BASH**
*on terminal #1 with the IP, 192.168.1.2*
```
nc -l 8080 | gpg -d > mydocument.docx
```
*on terminal #2 with the IP, 192.168.1.3*
```
gpg -c mydocument.docx | nc 192.168.1.2 8080
```
This will encrypt and send `mydocument.docx`, using `nc` and `gpg`, over to terminal #1
You will have to type the password on terminal #2, then on terminal #1
[Answer]
# C++
This is somewhat based on [Shingetsu's answer](https://codegolf.stackexchange.com/questions/16359/file-output-help/16365#16365), but I couldn't resist. It is fully functioning, but no student would submit it to their teacher (I hope). If they are willing to analyze the code, they will be able to solve their problem:
```
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define SOLVE ifs
#define IT >>
#define YOURSELF ofs
ifstream& operator IT(ifstream& ifs, ofstream& ofs) {
string s;
SOLVE IT s;
YOURSELF << s;
return ifs;
}
void output(ofstream& ofs, ifstream& ifs) {
while (ifs) {
SOLVE IT YOURSELF;
ofs << ' ';
}
}
int main() try {
ofstream ofs("out.txt");
ifstream ifs("in.txt");
output(ofs, ifs);
return 0;
}
catch (exception& e) {
cerr << "Error: " << e.what() << endl;
return 1;
}
catch (...) {
cerr << "Unknown error.\n";
return 2;
}
```
[Answer]
## Python
Inputs text from file1.txt and outputs it to file2.txt
It's complete and "working". No one said anything about writing the input as it is. All input characters appear in the output. "getchar" is the trolling part.
```
from random import choice as getchar
f1 = open("file1.txt")
s1 = []
for line in f1:
for char in line:
s1.append(str(char))
s2 = ''
while len(s1) > 0:
x = getchar(s1)
s2 += x
s1.remove(x)
f2 = open("file2.txt" , 'w')
f2.write(s2)
```
[Answer]
# Mathematica, 44 characters
Implementation
```
f = (BinaryWrite[#2, BinaryReadList@#]; Close@#2) &
```
Execution
```
f["one file", "another"]
```
Check
```
check = Import[StringJoin["!diff \"", #, "\" \"", #2, "\" 2>&1"], "Text"] &;
check["one file", "another"]
```
>
>
>
[Answer]
**DELPHI / PASCAL** ( copy from f1.txt to f2.txt )
```
program t;
{$APPTYPE CONSOLE}
uses
classes;
var a : TStringlist;
begin
a:=TStringlist.Create;
a.LoadFromFile('e:\f1.txt');
a.SaveToFile('e:\f2.txt');
a.Free;
end.
```
[Answer]
# MASM
I'm certainly not an assembly expert, but below is my little snippet:
```
include \masm32\include\masm32rt.inc
.code
start:
call main
inkey
exit
main proc
LOCAL hFile :DWORD
LOCAL bwrt :DWORD
LOCAL cloc :DWORD
LOCAL flen :DWORD
LOCAL hMem :DWORD
.if rv(exist,"out.txt") != 0
test fdelete("out.txt"), eax
.endif
mov hFile, fopen("source.txt")
mov flen, fsize(hFile)
mov hMem, alloc(flen)
mov bwrt, fread(hFile,hMem,flen)
fclose hFile
invoke StripLF,hMem
mov hFile, fcreate("out.txt")
mov bwrt, fwrite(hFile,hMem,flen)
fclose hFile
free hMem
ret
main endp
end start
```
[Answer]
# C++
Did you notice the "complete, working function" bit?
Anyway, here is my answer:
```
#include <stdlib.h>
int main(void)
{
system("echo < input > dest");
}
```
[Answer]
## Lua
```
io.read()
```
Run with an input file containing `text from one file and output it to another. Solution should be a complete, working function.`.
[Answer]
**PHP**
```
function copyFile($input, $output)
{
return file_put_contents($output, file_get_contents($input));
}
```
[Answer]
# #!/bin/sh
```
contents=`< $1` ; echo "$contents" > $2
```
Looks reasonable, but rather inefficient if the file is large.
Works fine on ASCII files except when the input file contains `-n`, `-e` or `-E`. (Because these are interpreted as arguments by `echo`.)
Does not produce the correct output for all (most) binary files.
(Using `printf "%s" "$contents" > output` under `/bin/bash` works a little better, but that still drops NULL bytes.)
Oh and of course it doesn't work for filenames\_containing\_spaces. But such files are illegal under UNIX%20policy anyway.
] |
[Question]
[
Given a string consisting of only upper and lower case letters, output `an` if it begins with a vowel, and `a` if not. For the purposes of this challenge, we'll ignore normal grammar rules, and use a very basic rule instead: if the input begins with a vowel (any of `AEIOUaeiou`), then output `an`. Otherwise, output `a`.
Your program should be case insensitive (`computer` and `CoMpUtER` are the same). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
## Test cases
```
airplane: an
water: a
snake: a
hybrid: a
igloo: an
WATER: a
IglOO: an
HoUr: a
unIverSe: an
youTH: a
```
Note that for the last 3, they contradict typical grammar rules, in favour of our simplified rule, and that `y` is not counted as a vowel
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 44 bytes
```
f(int*s){printf("a%.*s",2130466>>*s&1,"n");}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NIzOvRKtYs7qgCMhI01BKVNXTKlbSMTI0NjAxM7Oz0ypWM9RRylPStK79X5afmaKQm5iZp6GpUM2lAAQgDZlFBTmJealAFQowQ2JA6hX09RUS82DKyhNLUotAokCAqQymqjgvMTuVoKqMyqSizBSIMtyqMtNz8vNxmgV3WLhjiGsQQSs903P8/Qkb5pEfCvMkHsNK8zzLUouCCQVZZX5piAdul9X@/5eclpOYXvxftxwA "C (gcc) – Try It Online")
### Commented
```
f(int *s) { // *s = input string
printf( // print ...
"a%.*s", // the letter 'a' followed by a string with
// a dynamic length
2130466 // using the bitmask of vowels:
// 1000001000001000100010
// ^ ^ ^ ^ ^
// utsrqponmlkjihgfedcba_
>> *s & 1, // output 1 character if the first character
// is a vowel, or zero otherwise
// (assumes that the shift is modulo 32,
// which is guaranteed on Intel and may be
// true on ARM as well)
"n" // where the string to be printed is "n"
); //
} //
```
---
# [C (clang)](http://clang.llvm.org/), 39 bytes
This version was suggested by [Johan du Toit](https://codegolf.stackexchange.com/users/41374/johan-du-toit).
```
f(*s){write(1,"an",(2130466>>*s&1)+1);}
```
[Try it online!](https://tio.run/##S9ZNzknMS///P01Dq1izurwosyRVw1BHKTFPSUfDyNDYwMTMzM5Oq1jNUFPbUNO69n9uYmaehiZXNZcCEKRpKCVmFhUATUhV0rRWKCjKzCsBisXkgXj6@gqJeTBl5YklqUUgUSDAVAZTVZyXmJ1KUFVGZVJRZgpEGW5Vmek5@fk4zYI7LNwxxDWIoJWe6Tn@/oQN88gPhXkSj2GleZ5lqUXBhIKsMr80xAO3y2r//0tOy0lML/6vWw4A "C (clang) – Try It Online")
---
# [C (clang)](http://clang.llvm.org/), 36 bytes
This one was suggested by [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper).
```
f(*s){puts(2130466>>*s&1?"an":"a");}
```
[Try it online!](https://tio.run/##S9ZNzknMS///P01Dq1izuqC0pFjDyNDYwMTMzM5Oq1jN0F4pMU/JSilRSdO69n9uYmaehiZXNZcCEKRpKCVmFhUAtacCJRX09RUS82AS5YklqUUgUSAAScDEi/MSs1OxiGdUJhVlpkAkkMUz03Py85HUwy0IdwxxDcJikGd6jr8/Ng0e@aEwB6FoKM3zLEstCsb0QmV@aYgHsg21//8lp@Ukphf/1y0HAA "C (clang) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `english`, 15 bytes
```
[ >lower a/an ]
```
Almost a builtin. For whatever reason, `a/an` doesn't handle capital letters properly so we need to make it lowercase first. Luckily it's simplistic enough that it doesn't return the correct article for 'universe.'
Doesn't work on TIO because the `english` vocabulary postdates build 1525 (the one TIO uses), so have a picture:
[](https://i.stack.imgur.com/41Lh5.png)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-mg`](https://codegolf.meta.stackexchange.com/a/14339/), ~~9~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as an array of characters.
```
è\v îÍia
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LW1n&code=6Fx2IO7NaWE&input=WyJhIiwiYiIsImMiXQ)
```
è\v çÍia :Implicit map of each element in input array
è :Count the occurrences of
\v : RegEx /[aeiou]/gi
ç :Repeat that many times
Í : "n"
ia :Prepend "a"
:Implicit output of first element
```
The `Í` is Japt's shortcut for `n2<space>` (Mainly intended for converting binary strings to decimal) The space close the `ç` method and the `n` and the `2` are passed to it as individual arguments but as `ç` only expects one argument the `2` is ignored.
[Answer]
# [Python 3](https://docs.python.org/3/), 37 bytes
```
lambda x:'a'+'n'*(x[0]in'aeiouAEIOU')
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCSj1RXVs9T11LoyLaIDYzTz0xNTO/1NHV0z9UXfN/QVFmXolGmoZSZXpOfr6SpuZ/AA "Python 3 – Try It Online")
-1 thanks to @xnor
[Answer]
# JavaScript, ~~32~~ 31 bytes
*-1 thanks to @Arnauld*
```
s=>/^[aeiou]/i.test(s)?"an":"a"
```
[Try it online!](https://tio.run/##XclBDkAwEAXQvVPIrNoF9hIcREgmDKk0M@KX65e1t30HP4zlCmeq1FbJW9lldH0zjyzB7qkJdRIkBz8QK7XElBdTWJQ62u42RxyuM7IKeV/8CrfukQHBl/kF "JavaScript (Node.js) – Try It Online")
[Answer]
# [jq](https://stedolan.github.io/jq/), 36 bytes
```
1?*(test("^[aeiou]";"i")//"a")//"an"
```
[Try it online!](https://tio.run/##JcSxCsJADADQPZ@RqQpSnB3EQWinQm1xEIWIocYelzZ3p/TnPQff8F5zztv9uogcYoG3C7FouuIOBVdlifTfY84kNjnyDB@KbBA8jQzP5W7yABmcKpwP3bGFenBNA5X2BsnXb7YTw6Kpq746RVEf8sbaHw "jq – Try It Online")
Some longer alternatives:
```
"an"[:match("^[aeiou]?";"i").length+1]
```
[Try it online!](https://tio.run/##BcGxCsJADADQPZ@RSREFVx3EQWinQq04lApRw/X0TGp6p/TnPd97vHNGEmw3L4q3foaXlthr6na4RY/zVWBxsV@su5zJ2xBIGL4U2WAUejL009X8HbwLqnDeN4caSheqCgo9GSQpP2xHhklTU/x0iF5lzEur/w "jq – Try It Online")
```
.[:1]|1?*(inside("aeiouAEIOU")//"a")//"an"
```
[Try it online!](https://tio.run/##JcSxCsIwEADQ/T4jUxW0dHWRDoV2CtQWB3E46VHPhly9NErBbzcOvuE9nintL4fi@imO24x94IEyg8QSy6qxvdnkucH/3qSErLNDT/DGhRSCx4ngvt6UB@DRicC57KoWmtFZC7X0CtE3L9ITwSqxq78yLyw@pJ22Pw "jq – Try It Online")
```
"a"+sub("^([^aeiou](?<x>))?.*";.x//"n";"i")
```
[Try it online!](https://tio.run/##BcHBCoJAEADQ@3zGnNwi/QAj6RDoSTCjQySstOjUsmOzbunPt733fMeIGrc@9Al2ya3Thjjck2K/HJQq0g3m6ZJl6DBHQhWjJpmsdga@ejYC3umXgXHthR5Ag2WG67E9NVANtq6h5ItAcNXHyNnAyqEtfzzNxM7HnTR/ "jq – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 11 9 bytes
```
hk∨c›‛anẎ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=r&code=hk%E2%88%A8c%E2%80%BA%E2%80%9Ban%E1%BA%8E&inputs=test&header=&footer=)
```
hk∨c›‛anẎ
h - First character of input
k‚à® - All vowels ("aeiouAEIOU")
c - A in B? ("h" in "k‚à®"?)
› - Increment
`an - Two-byte string literal "an"
Ẏ - Slice until B (A[0:B])
```
9 bytes thanks to @Aaron Miller
[Answer]
# Dyalog APL, 21 chars
```
'an'↑⍨1+'aeiou'∊⍨⊃∘⎕c
```
Same logic as [this](https://codegolf.stackexchange.com/a/235346) Jelly answer. This answer feels too long...
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 33 bytes
```
"a"+"n"*("$args"-match"^[AEIOU]")
```
[Try it online!](https://tio.run/##XY7RboJAEEWf2a8gk20DLXxBY4IxJvJEI5g@GNusOAJ2ZenuUmss305Xg23Xxzlz7p1pxAGlKpHzMBcSe7odnXpg8Ag1PHhAmSwUhHum8xJel@NpnCxW4PcdIZFHnMgDVsmGsxohcIHV4AcXemAa5QVdiarZO1qkPK5ltbFQVXAh7KaXcTadW1Jc8CSxpZlY2NfaOv5Emd58dRRtNhs84n/fnYhDNSo9YQoDl@JXg7nGjTty6duT2UlULddmvKdb99c0m@VzOmmVFvtkvTORVWSanLTNc1TqnB6CIX78tZqYkw0VZ@dfnTO/HhqShnWk638A "PowerShell Core – Try It Online")
Or 36 bytes without regex
```
"a"+"n"*($args[0]-in("AEIOU"|% t*y))
```
[Try it online!](https://tio.run/##XY7RasIwFIavm6cIIY7WtbD7IVREsFcdtrILEYn1WLtlSZekc0V99i5Ky5Zdnu98/39OLU@g9BE4jwqpoKOHybkjjDwSQcY@ZarU66dNVAmfTOdJuiKXETbjNgi6K0Kxj7zYJ6xSNWcCSIgJEyQI7/TEDKg7GogW7B0ccmx3qto7qCq5lG7T6zSfLx0pKXmautJCrtxrjUi@QGX/vmplky96DwWX0Rl51IA2M6YhxBS@aygM7PEE0@2z3SnQDTd2fKAHHA@m3axfslmjjfxId282soltk5c1RQFa39J9MILP31Yb8/K@4ub8qfOWw6E@adkVXbsf "PowerShell Core – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~36~~ 34 bytes
```
fn($s)=>stripos(_aeiou,$s[0])?an:a
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSZvs/LU9DpVjT1q64pCizIL9YIz4xNTO/VEelONogVtM@Mc8q8b81F1dqcka@gkqahlJiZlFBTmJeqpKmgp6CUkyekrWCvr5CYh5CRXliSWoRkjQQgFQgFBTnJWan4lOQUZlUlJmCogJVQWZ6Tn4@pglIjgh3DHENwmeHZ3qOvz9eIzzyQ9G8gWZEaZ5nWWpRMJ6gqMwvDfHAtOQ/AA "PHP – Try It Online")
Straightforward PHP code. Ignoring accented vowels of course, the `_` is ignored, it is only there so that the index in the string is truthy
EDIT: saved 2 bytes thanks to YetiCGN's suggestions
[Answer]
# JavaScript, ~~91~~ 73 bytes
-18 from @emanresuA
```
a=(s)=>{return 'a'+('AEIOU'.includes(s.charAt(0).toUpperCase())?"n":"");}
```
## Explanation
```
a= declares variable
(s)=>{ ES6 Arrow Function
return 'a'+ return statement
('AEIOU'.includes( check if in string 'AEIOU'
s.charAt(0) first letter of string
.toUpperCase()) case insensitivity
? ternary operator
"n" if true, add 'n' (an)
:""); else, add nothing (a)
} finish function
```
[Try it Online!](https://tio.run/##XcmxCsIwEADQ3a8IWXKHmDqKpUpQB6eCUJyPNGglJCFJ6yB@e8RFoW99D5oo6TiEvJo2pVADCZvdK5o8RscEiSUIdTq3nZCD03bsTYIk9Z2iyrBGmX0XgokHSgYQ99zxLedYv4v2LnlrpPU3IBDX9nIUiDVjVcVoMVv16@@6edPTx/7f5QM)
[Old TIO link](https://tio.run/##XcmxCsIwEADQ3a8IWS6HmjqKUqWog1NBKA7icKRBKyEpSVoH8dtjXRQ6vOk9qKegfNPGeb9MyejIKBcB883L69h5y4BgKi5QwAwOg@OgHFRwlY1Vpqt1EEGqO/kiigXK6Kq21X5HQQvELbd8xTmu30k5G5zR0ribIAHn8rQHxDVjWcZoMtri19@146an8/W/0wc)
first time here so let me know if I missed something
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ḢeØc‘⁾anḣ
```
[Try it online!](https://tio.run/##y0rNyan8///hjkWph2ckP2qY8ahxX2Lewx2L/z/cveXQ1oc7Fz9qmGsFlD7crhn5/39iZlFBTmJeqpVCYh5XeWJJahGQxVWcl5gNEuLKqEwqykwBsTLTc/LzwarCHUNcg0BCnuk5/v5gIY/8ULC@0jzPstSiYIhplfmlIR5AFgA "Jelly – Try It Online")
The footer simply extracts the test case from the `:` separated string
## How it works
```
ḢeØc‘⁾anḣ - Main link. Takes a string S on the left
·∏¢ - Extract the first character of S
√òc - Yield vowels; "AEIOUaeiou"
e - Is the first character in that string? Yield 1 if so, else 0
‘ - Increment, yielding 2 for vowel-starting strings, 1 otherwise
‚Åæan·∏£ - Take that many characters of the string ‚Åæan
```
[Answer]
# TI-Basic, 43 bytes
```
Input Str1
"a
If inString("AEIOUaeiou",sub(Str1,1,1
"an
```
Ouput is stored in `Ans`.
[Answer]
# [R](https://www.r-project.org/), 47 bytes
```
function(s)"if"(grepl("^[aeiou]",s,T),"an","a")
```
[Try it online!](https://tio.run/##Tc2xCsIwEAbg3aeQc0kgTyA4OAjtVNCIgyicmsTQcClJo/TpY6VDshx89/Pfhax3WSd6jtYTixysBmaCGhyD@xWV9ekGIgrJBSDBPIBnzQBtGBySAr7ZrpFW8@qLowqL/4yEvSp8T49gX8XWOO@r9mUvD8cSt8Z1XRU3/lzdTtR@VDjV3yefZLM4/wA "R – Try It Online")
Other solutions:
```
function(s)c("a","an")[1+grepl("^[aeiou]",s,T)] # 47 bytes
function(s)paste0("a","n"[grepl("^[aeiou]",s,T)]) # 49 bytes
```
[Answer]
# [Nim](https://nim-lang.org), 61 bytes
```
proc a(i:string):string=
if i[0]in "aeiouAEIOU":"an"else:"a"
```
[Try it online!](https://tio.run/##Lc7BCoMwDAbge58iZCATdthZGMyDoDAQNmUH8dC5qGGulVY3fHpX6sghX0J@iOL3uo5GNyD3HNnJsOrCfz8J4Ba4OtasACWxnuMky0uMUCqkwZIDrjsoyE6i1QYsuMtzJdw1m3GQivDghq@cyHhZJV/brl8ehp@e3A1ae93jIrl6Zd0lz71SXW7ZWWUfMrctvui5SFFAHQmgptfufRtCAOgqALv@AA)
Simple explanation + ungolfed code:
```
# Define function
proc a(i: string): string =
# If the first character of 'i' is in "aeiouAEIOU",
# Then it is a "an"
if i[0] in "aeiouAEIOU":
return "an"
# Else, return "a"
else:
return "a"
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 39 bytes
```
s->s.matches("(?i)^[aeiou].*")?"an":"a"
```
[Try it online!](https://tio.run/##VY5Ba8JAEIXv/ophQUhEl/aqreKhRQ9FqJYexMIY17i62Q27symh@NunMebiYXjMzDfvzRkrHJ0PF9ZF6TzBuellJG3kMdqMtLNyMOllBkOAD9QW/noAZdwbnUEgpEYqpw9QNLtkTV7bfLsD9HlIWxTgvfN5uW@Hd5kCrvzcwiu0EIfRNMgCKTupkIhkptOfLSrt4k4ORDoTaMVYoOBJix@dh6RCD6QCjR/iAG5zr0I01Li3KRLL0tTJDU4nHbWuA6lCukiybB6iYyL6z09hDP3Qt2LYOg87n@7o2rvVlRm1Lw1axb9IynOweFF8qvdeH1jnxjn@nm/ePnmZm9WKF@7Lc7TLSvm14trFzeIf "Java (JDK) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
„anžMIнlå>∍
```
[Try it online](https://tio.run/##yy9OTMpM/f//UcO8xLyj@3w9L@zNObzU7lFH7///pXmeZalFwakA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/f9HDfMS847u8628sDfn8FK7Rx29/3X@RyslZhYV5CTmpSrpKJUnlqQWAenivMRsED@jMqkoMwXIyEzPyc8H0uGOIa5BQNozPcffH0h75IeC1JfmeZalFgWDtFTml4Z4KMUCAA).
**Explanation:**
```
„an # Push "an"
žM # Push builtin constant "aeiou"
I # Push the input-string
–Ω # Pop and leave just its first character
l # Convert it to lowercase
å # Check if this lowercase first letter is in the vowels-string
> # Increase it by 1
‚àç # Shorten the "an" to this length
# (after which the result is output implicitly)
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~28~~ 20 bytes
*27 bytes for the actual code; +1 byte for -E to get **say***
*-8 bytes by golfing further*
```
$_=/^[aeiou]/i?an:a
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lY/LjoxNTO/NFY/0z4xzyrx/3/P9Bz//H/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~80~~ ~~76~~ ~~74~~ ~~64~~ ~~40~~ 35 bytes
*-24 thanks to @Franky*
*-5 thanks to @ovs*
```
a(x:_)='a':['n'|elem x"aeiouAEIOU"]
```
[Try it online!](https://tio.run/##bY/BasMwEETv@YplibENoR9gcCCHQEwLLo1DD6UUtd3YIvJKSHIjQ//dddyeivY0zPCYnU64Cyk1yd5o66Gh4O8erWR/nkQWire8TEVavKScfpOiHgIKknrY7av6hK@TgQAjlGAGf/T2gWENZqEBE1cABUMfXnILiduAJTcoP0vIEpfjgmYCQg6ZPP@pspxN3xED1vcIpBwBXq3mFvNVLyTfygCFtEYJJpwlI2y3K/i9ObsKT/YW/PMdiwtF/G58t/IzEshWaR1reN41@6cIULWqrmPAQZ9iHw1cfZE9RleMemgOCzP9AA "Haskell – Try It Online")
[Answer]
# F#, 61 bytes
```
let a(i:string)=if"aeiouAEIOU".Contains(i.[0])then"an"else"a"
```
[Try it online!](https://tio.run/##bc6xCsIwEIDh3acIB0Iz2DoLDkWEdipoi4M4nHhtD@OlJKnSp4/uZv744e/95mXFxmgoKMx454NjGfSee0BiO5fHuukgP1gJyOIzzq/bmw4jCaAAGU@AEItCteTDavrFoRcFaw8qQwXIbjIoBPrfPhjIpcALPpPFuNwdP1LCg7E2BZeyPZ5SUA@maVJQ2S55NUv9JndOji12bivQ8Qs)
Alternative 66 bytes solution:
```
let a(i:string)=if"aeiouAEIOU".Contains(i.Chars(0))then"an"else"a"
```
[Try it online!](https://tio.run/##bc4xC8IwEIbh3V8RDoRmsHUWHEoptFNBW5xPvLaH8VKSVOmvj@5mfvg@3tEfXlZsjIaCwoxPPjiWSZ95BCS2a1m33QB5ZSUgi884r2Z0PjtqHWYSQAEyngAhFoXqyYfd8nsIoyjYe1AZKkB2i0Eh0P/2wUAuBV7wmVzM293xIyU8GWtTcCv7@pKCdjJdl4LGDsmqVdo3uWsybLNr34COXw)
Check if the input's first character is in `aeiouAEIOU` or not (`if"aeiouAEIOU".Contains(i.Chars(0))`), if true, return "an" (`then"an"`), else, return "a" (`else"a"`)
Ungolfed version:
```
let anOrA (inpt : string) =
if "aeiouAEIOU".Contains(inpt.Chars(0)) then "an" else "a"
```
[Answer]
# [Vim](https://www.vim.org), 20 bytes
```
lD:s/[aeiou]\c/an
ra
```
[Try it online!](https://tio.run/##K/v/P8fFqlg/OjE1M780NiZZPzGPqyjx//@S1OISAA)
Explanation:
```
lD # Keep only the first character
:s/[aeiou]\c/an # Replace any of AEIOUaeiou with 'an'
ra # Replace the first character with 'a'
```
[Answer]
# [C (clang)](http://clang.llvm.org/), 34 bytes
```
f(*s){puts("a\00an"+('A\04D'>>*s&2));}
```
[Try it online!](https://tio.run/##S9ZNzknMS///P01Dq1izuqC0pFhDKZEhMU9JW0PdkcVF3c5Oq1jNSFPTuvZ/bmJmnoYmVzWXAhCkAZVlFhUANacqaVor6OsrJObBJMoTS1KLQKJAAJKAiRfnJWanYhHPqEwqykyBSCCLZ6bn5OcjqYdbEO4Y4hqExSDP9Bx/f2waPPJDYQ5C0VCa51mWWhSM6YXK/NIQD2Qbav//S07LSUwv/q9bDgA "C (clang) – Try It Online")
Partial based on [dingledooper's answer](https://codegolf.stackexchange.com/a/235350).
`\00` and `\04` should be replaced by raw bytes instead of using escaped character sequences.
[Answer]
# JavaScript (ES6), 37 bytes
```
s=>'a'+(/[aeiou]/i.test(s[0])?"n":"")
```
[Answer]
## Python, ~~42~~ 37 bytes
```
lambda s:'a'+'n'*(2130466>>s[0]%32&1)
```
Uses the same logic as [this](https://codegolf.stackexchange.com/a/235350/103498) C answer, but I have to take `%32` because python bit shifts aren't modulo 32.
Note that I take advantage of order of operations by using `%32` and `&1` (which is `%2`) to avoid needing parentheses.
(-5): Removed the `ord()` by taking a bytestring (`bytes`) instead of a `str`.
[Answer]
# [jq](https://stedolan.github.io/jq/), 33 bytes
```
(match("^[aeiou]";"i")|"an")//"a"
```
[Try it online!](https://tio.run/##yyr8/18jN7EkOUNDKS46MTUzvzRWyVopU0mzRikxT0lTX18pUen/f6XEzKKCnMS8VCUupfLEktQiIF2cl5gN4mdUJhVlpgAZmek5@flAOtwxxDUISHum5/j7A2mP/FCQ@tI8z7LUomCQlsr80hAPJQA "jq – Try It Online")
[Answer]
# [CLC-INTERCAL](https://esolangs.org/wiki/CLC-INTERCAL), 144 bytes.
In ISO-8859-1:
```
DO,1<-#99DOWRITEIN,1DO;1<-#2DO;1SUB#1<-#52DO;1SUB#2<-#360(1)DO.1<-',1SUB#3'~#31(3)DO¬x(6)DO¬x(7)DO¬x(24)DO¬xDO;1SUB#2<-#0DOCOMEFROM.1DOREADOUT;1
```
## Usage
* Stdin and stdout, both of each as a line.
+ No trailing LF for output.
## [Copy and paste the following Bash script to test online on shinh's server!](http://golf.shinh.org/check.rb)
```
printf %s "$(cat<<'x'
DO,1<-#99DOWRITEIN,1DO;1<-#2DO;1SUB#1<-#52DO;1SUB#2<-#360(1)DO.1<-',1SUB#3'~#31(3)DO¬x(6)DO¬x(7)DO¬x(24)DO¬xDO;1SUB#2<-#0DOCOMEFROM.1DOREADOUT;1
x
)" | iconv -f UTF-8 -t LATIN1 >x.i
wc -c x.i
sick x.i
while IFS=: read x _; do
echo $x
./x.io <<<$x
echo
done<<'x'
airplane: an
water: a
snake: a
hybrid: a
igloo: an
WATER: a
IglOO: an
HoUr: a
unIverSe: an
youTH: a
x
```
## How it works
The idea was just to make "an" on the variable `;1` and then erase "n" unless vowel. I used Baudot character set for input.
[Answer]
# [Zsh](https://www.zsh.org/) `--continue-on-error`, 25 bytes
```
>$1:l
s=n<[aeiou]*
<<<a$s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwRobG3U9dTu9ZD0gb2lpSZquxU47FUOrHK5i2zyb6MTUzPzSWC0uGxubRJViiPzNCD2utPwiBUMFjcTUovyCnMS8VIXQvMyy1KLizJJKhcj80pIMhYrKnPyCjPy8VE0FoMkKurrJ-XklmXmlqbr5ebqpRUVAAyCWKqgYKqipKRTlKmhBzF-wAEIDAA)
When `[aeiou]*` fails to match (i.e., the word begins with a consonant), Zsh would normally exit with a "fatal" error. The aptly named option `CONTINUE_ON_ERROR` overrides this, and simply skips the assignment line `s=n` instead.
[Answer]
# [International Phonetic Esoteric Language](https://github.com/bigyihsuan/International-Phonetic-Esoteric-Language), 40 bytes
```
0h"aeiouAEIOU"d îdp å…î|a|"an"…î|e||a|"a"|e|
```
Expects a string, leaves the string and a `"a"` or `"an"`.
### Ungolfed:
```
(s -- a/an)
0h (first char)
"aeiouAEIOU"d î (is c a vowel?)
dp (discard vowels)
å…î|a| (if c is not a vowel, go to |a|)
|an|"an"…î|end| (when c is a vowel)
|a|"a" (when c is not a vowel)
|end|
```
[Answer]
# [GAIA](https://github.com/Glan9/Gaia), 32 bytes
```
{(⟨₵v&!!⟩⟨₵V&!!⟩v}⟨“a”p⟩⟨“an”p⟩?
```
[Try it online!](https://tio.run/#gaia)
Probably could be shortened, especially on the second section.
Explanation:
```
( -takes first letter of the input
₵v& - is member (&) of string aeiou (₵v) -> returns the contained letter if member, empty if not.
₵V& - is member (&) of string AEIOU (₵V) -> returns the contained letter if member, empty if not.
!! - if the passed value is empty returns 0, otherwise 1
v - is logical or
{(⟨₵v&!!⟩⟨₵V&!!⟩v} - so this checks if the first letter is member of either lower or upper case vowels
⟨“a”p⟩⟨“an”p⟩? - this checks for the value passed by the first section, if true executes the first member, if false the second.
p -prints a string
```
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 21 bytes
**Solution:**
```
{$`an`a@^"aeiou"?*_x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlolITEvIdEhTikxNTO/VMleK76i9n@auoZSYmZRQU5iXqqStVJ5YklqEZAuzkvMBvEzKpOKMlOAjMz0nPx8IB3uGOIaBKQ903P8/YG0R34oSH1pnmdZalEwSEtlfmmIh5LmfwA "K (ngn/k) – Try It Online")
**Explanation:**
```
{ } / function taking implicit x argument
_x / convert x to lowercase
* / take first
"aeiou"? / find right in left
^ / null?
`an`a@ / index into 2-item list (`a;`an)
$ / convert to string
```
] |
[Question]
[
This challenge is [related](https://codegolf.stackexchange.com/questions/124362/how-high-can-you-count)
# Challenge
Your task is to write as many programs/snippets as you can, where each one outputs/prints/ returns an alphabet. The first program must output the letter `A` or `a`, the second one `B` or `b` and so on.
**You can not reuse any characters between the programs (Except Whitespace, it can be reused through snippets). So, if the first program is: `0==0`, then you may not use the characters `0` and `=` again in any of the other programs.** Note: It's allowed to use the same character many times in one program.
### Scoring:
The winner will be the submission that can print alphabets up to the highest, if anyone can print upto `Z` or `z`, it will receive an extra `+50` bounty from me. In case there's a tie, the winner will be the submission that used the fewest number of bytes in total.
### Rules:
* You can only use a single language for all alphabets, polygots not supported
* **Snippets are allowed! But quine snippets like `A` which prints `A` are not allowed.**
* leading and trailing spaces are not allowed. But newlines are allowed
* You may disregard STDERR, as long as the correct output is returned to STDOUT
* You cannot choose to output the letters to STDERR.
* Letters are case sensitive `a != A`.
* **The programs/snippets must be independent**
* **Whitespace can be reused**
* Output is case-insensitive, you may choose to either output `a` or `A` but not both!
* You can't use a function, that does not print anything, such as `f(){print a}` will print `a` when it is called, but if you don't call the function, then that snippet/program is invalid.
* Minimum submission length should be `1` byte, but again quines are not allowed
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 390 bytes, A-Z
Exploiting the rules a little:
>
> * **Whitespace can be reused**
>
>
>
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgVMBBDi5OLkUFP7/BwA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgVMBTHBxciko/P8PAA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgVMBRHBycXIpKPz/DwA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgROCuTi5FBT@/wcA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgROMObk4uRQU/v8HAA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgROEORW4OLkUFP7/BwA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgROEOTm5OLkUFP7/BwA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgROMFLg4uRQU/v8HAA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgROCuDi5FBT@/wcA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgROEOBW4OLkUFP7/BwA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgROEODm5OLkUFP7/BwA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgROIgJiLk0tB4f9/AA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgROIOBU4uTi5FBT@/wcA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgROIODkVuDi5FBT@/wcA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgROIgICLk0tB4f9/AA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgRMIgYCLk0tB4f9/AA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgRMIgSQXJ5eCwv//AA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgRMIgYiLk0tB4f9/AA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgRMIFTg5uTi5FBT@/wcA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgRMMFbg4uRQU/v8HAA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgRMCuTi5FBT@/wcA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgRMEORW4OLkUFP7/BwA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgRMEOTm5OLkUFP7/BwA "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgVOBkxNIcXFyKSj8/w8A "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgVOBkxNIcnFyKSj8/w8A "Whitespace – Try It Online")
```
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgVOBE4gUuDi5FBT@/wcA "Whitespace – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), A-N 109 bytes
Previously: A-F, 41 bytes || A-G, 53 bytes || A-K, 85 bytes || A-M, 101 bytes
```
eCho a
'b'
"c"
{d}
writE E
‛F‛
(mAn)[7][3]
“H“
”I”
’J’
‘K‘
„L„
‚M‚
sv N;gv N|% N*
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/P9U5I18hkUs9SZ1LKVmJqzqllqu8KLPEVcGV61HDbDcg5tLIdczTjDaPjTaOBYrN8QBiID3XE4iB9EwvIAbSM7yBGEjP8wFiID3LF4i5issU/KzTgUSNqoKf1v//AA "PowerShell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 39 bytes, letters a-n
A: [`Th`](https://tio.run/##yy9OTMpM/f8/JOP/fwA): 10 converted to hexadecimal.
b: [`žNн`](https://tio.run/##yy9OTMpM/f//6D6/C3v//wcA): The first consonant.
C: [`т.X`](https://tio.run/##yy9OTMpM/f//YpNexP//AA): 100 as a Roman numeral.
D: [`₂;₂B`](https://tio.run/##yy9OTMpM/f//UVOTNRA7/f8PAA): Convert 13 to base 26.
e: [`A4è`](https://tio.run/##yy9OTMpM/f/f0eTwiv//AQ): The character at index 4 in the alphabet.
f: [`Ƶ1ç`](https://tio.run/##yy9OTMpM/f//2FbDw8v//wcA): `chr(102)`
g: [`'g`](https://tio.run/##yy9OTMpM/f9fPf3/fwA): single character string.
H: [`"H`](https://tio.run/##yy9OTMpM/f9fyeP/fwA): string without closing quote.
i: [`‘i`](https://tio.run/##yy9OTMpM/f//UcOMzP//AQ): uppercase compressed string.
j: [`’j`](https://tio.run/##yy9OTMpM/f//UcOMrP//AQ): compressed string without spaces.
k: [`“k`](https://tio.run/##yy9OTMpM/f//UcOc7P//AQ): lowercase compressed string.
l: [`”l`](https://tio.run/##yy9OTMpM/f//UcPcnP//AQ): titlecased compressed string.
m: [`„mmθ`](https://tio.run/##yy9OTMpM/f//UcO83NxzO/7/BwA): last character of `"mm"`.
n: [`…nnn¤`](https://tio.run/##yy9OTMpM/f//UcOyvLy8Q0v@/wcA): last character of `"nnn"`.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 34 bytes, letters a-g
```
"a
```
[Try it online!](https://tio.run/##K6gsyfj/Xynx/38A "Pyth – Try It Online")
```
\b
```
[Try it online!](https://tio.run/##K6gsyfj/Pybp/38A "Pyth – Try It Online")
```
C99
```
[Try it online!](https://tio.run/##K6gsyfj/39nS8v9/AA "Pyth – Try It Online")
```
.H+/TT+T2
```
[Try it online!](https://tio.run/##K6gsyfj/X89DWz8kRDvE6P9/AA "Pyth – Try It Online")
```
>-!4k4
```
[Try it online!](https://tio.run/##K6gsyfj/305X0STb5P9/AA "Pyth – Try It Online")
```
@G5
```
[Try it online!](https://tio.run/##K6gsyfj/38Hd9P9/AA "Pyth – Try It Online")
```
$chr(103)
```
[Try it online!](https://tio.run/##K6gsyfj/XyU5o0jD0MBY8/9/AA "Pyth – Try It Online")
# Explanation
```
" # Can be used to start a string literal.
\b # Corresponds to the one-character string 'b'
C99 # Character with code 99.
T # Variable initialized to 10 by default.
+/TT+T2 # Prefix notation. Evaluates to 13.
.H # Convert into hexadecimal.
!4 # Logical negation -> False
k # Variable initialized to empty string by default.
- # Casts the first argument (bool) into the type of second argument (str).
>4 # Prints all characters starting from index 4.
G # Variable initialized to "abcdefghijklmnopqrstuvwxyz" by default.
@ G 5 # Get character at index 5 of G.
$ # begin and end python literal.
chr # Returns the character represented by the integer.
```
*thanks to FryAmTheEggman*
[Answer]
## Whitespace, 390 bytes (15 bytes per letter), A-Z
S = Space; T = Tab
### A
```
SSSTSSSSST
T
SS
```
### B
```
SSSTSSSSTS
T
SS
```
### C
```
SSSTSSSSTT
T
SS
```
### D
```
SSSTSSSTSS
T
SS
```
### E
```
SSSTSSSTST
T
SS
```
### F
```
SSSTSSSTTS
T
SS
```
### G
```
SSSTSSSTTT
T
SS
```
### H
```
SSSTSSTSSS
T
SS
```
### I
```
SSSTSSTSST
T
SS
```
### J
```
SSSTSSTSTS
T
SS
```
### K
```
SSSTSSTSTT
T
SS
```
### L
```
SSSTSSTTSS
T
SS
```
### M
```
SSSTSSTTST
T
SS
```
### N
```
SSSTSSTTTS
T
SS
```
### O
```
SSSTSSTTTT
T
SS
```
### P
```
SSSTSTSSSS
T
SS
```
### Q
```
SSSTSTSSST
T
SS
```
### R
```
SSSTSTSSTS
T
SS
```
### S
```
SSSTSTSSTT
T
SS
```
### T
```
SSSTSTSTSS
T
SS
```
### U
```
SSSTSTSTST
T
SS
```
### V
```
SSSTSTSTTT
T
SS
```
### W
```
SSSTSTTSSS
T
SS
```
### X
```
SSSTSTTSST
T
SS
```
### Y
```
SSSTSTTSTS
T
SS
```
### Z
```
SSSTSTTSTT
T
SS
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes, `ABCdefG`
```
ØAḢ
```
[Try it online!](https://tio.run/##y0rNyan8///wDMeHOxb9/w8A "Jelly – Try It Online")
```
”B
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw1yn//8B "Jelly – Try It Online")
```
⁾C
```
[Try it online!](https://tio.run/##y0rNyan8//9R4z5nrv//AQ "Jelly – Try It Online")
Note the trailing newline
```
³Ọ
```
[Try it online!](https://tio.run/##y0rNyan8///Q5oe7e/7/BwA "Jelly – Try It Online")
```
.ȷ22ŒṘ2ị
```
[Try it online!](https://tio.run/##y0rNyan8/1/vxHYjo6OTHu6cYfRwd/f//wA "Jelly – Try It Online")
```
1÷0ṾṪ
```
[Try it online!](https://tio.run/##y0rNyan8/9/w8HaDhzv3Pdy56v9/AA "Jelly – Try It Online")
```
“G
```
[Try it online!](https://tio.run/##y0rNyan8//9Rwxz3//8B "Jelly – Try It Online")
+2 more from Unrelated String
How you can make a string in Jelly:
* Character literals, beginning with `”`
* String literals, using `“”` as delimiters (or `“«`, but that's undefined behaviour that happens to work in our favor). Trailing `”` can be omitted at the end of the program
* Compressed strings, using `“»` as delimiters
* Two character literals, beginning with `⁾`
* Converting from a number to a character with `Ọ`
* Using the builtin string constants, almost all of which begin with `Ø`
* Python/Jelly representations
## How they work
* `A`:
```
ØAḢ - Main link. No arguments
ØA - Yield the uppercase alphabet
Ḣ - Head; Take the first element, "A"
```
* `B` uses a character literal `”B`
* `C` uses a two character literal, with a trailing newline, to output `C` and a newline
* `d`:
```
³Ọ - Main link. No arguments
³ - Yield 100
Ọ - Convert to character "d"
```
* `e`:
```
.ȷ22ŒṘ2ị - Main link. No arguments
.ȷ22 - Literal: 5e+21
ŒṘ - Python representation
2ị - Second character
```
* `f`:
```
1÷0ṾṪ - Main link. No arguments
1÷0 - 1÷0 = inf
ṾṪ - Last character; "f"
```
* `G` uses a character literal `“G`
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 1 byte for each, 26 bytes for `a`-`z`
```
B
```
```
C
```
```
D
```
... some programs omitted ...
```
Y
```
```
Z
```
```
[
```
[Try them online!](https://tio.run/##ncs7DoJAGADh3lP8FzAcwMRCAUVFHr6lcjcbKIQ1wp5/aTS2Zrop5lOPvvHe6MbKtJOFzKW37q3NTAL7GgLllHqa2rW/@gyTr1kCEwITARMDswJmDUwCzAaYLTA7YFJg9sBkwOTAFMCUwByAOQJzAuYMzAWYKzA3YO7AVP8b70c)
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), 26 bytes (Sbcs) (A through Z)
```
Ȧ
Ɓ
Ƈ
Ɖ
Ɛ
Ƒ
Ɠ
Ƕ
Ȋ
ȷ
Ǩ
Ƚ
Ɯ
Ɲ
Ǫ
Ƿ
Ɋ
Ʀ
Ș
Ț
Ȕ
Ʋ
Ʌ
ƛ
Ƴ
Ƶ
```
[Try it online!](https://tio.run/##ATsAxP9rZWf//8imxoHGh8aJxpDGkcaTx7bIisi3x6jIvcacxp3Hqse3yYrGpsiYyJrIlMayyYXGm8azxrX//w "Keg – Try It Online")
Each byte is a program - I simply put them together for convenience. This kids is the power of bad language design - a built-in for each letter of the alphabet, something specifically designed for challenges like this.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes, ABCDEF
```
⌊α
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9RT9e5jf//AwA "Charcoal – Try It Online") Explanation: Outputs the minimum of the uppercase letters, i.e. `A`.
```
℅⁶⁶
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9RS@ujxm1A9P8/AA "Charcoal – Try It Online") Explanation: Outputs the ASCII character 66, i.e. `B`.
```
↥§β²
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R29JDy89tOrTp/38A "Charcoal – Try It Online") Explanation: Outputs the lowercase letter at position 2 (0-indexed), converted to upper case, i.e. `C`.
```
⊟…ψE
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R1/xHDcvOd7j@/w8A "Charcoal – Try It Online") Forms the range of characters up to (but not including) `E`, and takes the last, i.e. `D`.
```
⍘⁴⁰φ
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R74xHjVseNW443/b/PwA "Charcoal – Try It Online") Explanation: Converts 40 to base 62, which is `E`.
```
Φγ⁼κ³⁸
```
[Try it online!](https://tio.run/##S85ILErOT8z5///csnObHzXuObfrEJDa8f8/AA "Charcoal – Try It Online") Explanation: Outputs the 38th printable ASCII character, counting space as 0, i.e. `F`.
[Answer]
# [Zsh](https://www.zsh.org/), 76 bytes, `abcd`
```
echo a
print b
w=101;x=99;y=104;z=111;${(#)w}${(#)x}${(#)y}${(#)z} ${(#)x}
<<<d
```
[Try it online!](https://tio.run/##qyrO@P8/NTkjXyGRq6AoM69EIYmr3NbQwNC6wtbS0roSyDSxrrI1NDS0VqnWUNYsrwVTFRCqEkJV1SpARblsbGxS/v8HAA "Zsh – Try It Online")
+1 score thanks to @Makonede
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `K`, 864 bytes, A-Z
The `K` flag treats numbers as ordinal values when printing them, so for everything except the string and character literals, we just need to get the right number, and it gets converted to a character automatically.
**Note: Space is shown used twice, but that is only for readability. The link for `X` has the spaces replaced with newlines.**
```
₄₄₄₄±₄±↲/Ṡ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%E2%82%84%E2%82%84%E2%82%84%E2%82%84%C2%B1%E2%82%84%C2%B1%E2%86%B2%2F%E1%B9%A0&inputs=&header=&footer=)
```
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!&inputs=&header=&footer=)
```
⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐ꜝ⌐
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90%EA%9C%9D%E2%8C%90&inputs=&header=&footer=)
```
44H
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=44H&inputs=&header=&footer=)
```
111111111111111111111111111111111111111111111111111111111111111111111„1βȧ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=111111111111111111111111111111111111111111111111111111111111111111111%E2%80%9E1%CE%B2%C8%A7&inputs=&header=&footer=)
```
99999999999999999999999999999999b∑
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=99999999999999999999999999999999b%E2%88%91&inputs=&header=&footer=)
```
₆›››››››
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%E2%82%86%E2%80%BA%E2%80%BA%E2%80%BA%E2%80%BA%E2%80%BA%E2%80%BA%E2%80%BA&inputs=&header=&footer=)
```
88¦¦¦¦¦¦¦¦G
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=88%C2%A6%C2%A6%C2%A6%C2%A6%C2%A6%C2%A6%C2%A6%C2%A6G&inputs=&header=&footer=)
```
u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-&inputs=&header=&footer=)
```
⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧⇧
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7%E2%87%A7&inputs=&header=&footer=)
```
555555555555555555555555555555555555555555555555555555555555555555555555555L
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=555555555555555555555555555555555555555555555555555555555555555555555555555L&inputs=&header=&footer=)
```
76
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=76&inputs=&header=&footer=)
```
≤mmmmm
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%E2%89%A4mmmmm&inputs=&header=&footer=)
```
₈⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%E2%82%88%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9%E2%87%A9&inputs=&header=&footer=)
```
\O
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%5CO&inputs=&header=&footer=)
```
«≬λλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλλ«żt
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%C2%AB%E2%89%AC%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%CE%BB%C2%AB%C5%BCt&inputs=&header=&footer=)
```
3²²
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=3%C2%B2%C2%B2&inputs=&header=&footer=)
```
`R
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%60R&inputs=&header=&footer=)
```
‛S Ǎ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%E2%80%9BS%20%C7%8D&inputs=&header=&footer=)
```
×Cd
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%C3%97Cd&inputs=&header=&footer=)
```
₇‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%E2%82%87%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9%E2%80%B9&inputs=&header=&footer=)
```
=:+:+:+:+:+:+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+::=+
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%3D%3A%2B%3A%2B%3A%2B%3A%2B%3A%2B%3A%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B%3A%3A%3D%2B&inputs=&header=&footer=)
```
₀ɽ÷_p
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%E2%82%80%C9%BD%C3%B7_p&inputs=&header=&footer=)
```
2 2*2*2 2*2*J
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=2%0A2*2*2%0A2*2*J&inputs=&header=&footer=)
```
kZḢh
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=kZ%E1%B8%A2h&inputs=&header=&footer=)
```
»[
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=K&code=%C2%BB%5B&inputs=&header=&footer=)
[Answer]
# [\/\/>](https://github.com/torcado194/worm), 36 bytes, `abc`
a: `'a'u;`
b: `e7*Uf4*1-00s` program terminator ";" is used up, so `f4*1-00s` places a ";" at 0,0
c: `"␀␁9"2+"c␀␀S"2+mS}S` now both "u" and "U" are used, so I do the same trick to place "U;" at the start. (␀ and ␁ are the actual ascii 0 and 1 characters)
This is the logical limit to the alphabet size since I can only use the "s" instruction twice, can probably still be golfed though.
Alphabet is even smaller for ><> due to not supporting uppercase instructions.
What a neat challenge!
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 15 bytes, a-f
```
kzt
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=kzt&inputs=&header=&footer=)
```
\b
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%5Cb%0A&inputs=&header=&footer=)
```
‛cch
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%80%9Bcch&inputs=&header=&footer=)
```
₁C
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%82%81C&inputs=&header=&footer=)
```
«ƛ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%AB%C6%9B&inputs=&header=&footer=)
```
`f
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60f&inputs=&header=&footer=)
So, there are only a few ways to get strings in Vyxal:
String literals:
```
\. , ‛.. , `...\`
```
chr(x) - `...C`
compressed string literals - `«...«`
And deriving from a constant (`k...`).
That's all we can really do :P
[Answer]
# [Factor](https://factorcode.org), ~~8~~ 14 bytes, ~~`a`~~`ab`
```
"a"print
11 .h
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjUFCUWlJSWVCUmVeikJmvYP1fKVEJzOMyNFTQy/j/HwA "Factor – Try It Online")
In Factor you can `print`, `printf` or `write` to stdout, but they share characters. I don't know of any other suitable output method.
But as @Bubbler writes, a-f can be output as hex numerals.
[Answer]
# V ~~a-r 46 bytes~~ ~~a-x 77 bytes~~ ~~a-y 84 bytes~~ a-z 86 bytes
Probably not going to be a contender, but maybe someone can help me improve it. Had fun trying anyways.
EDIT: Got a lot farther than I thought I would! A few of my older answers were invalid, according to the rules, so they've been removed. I don't have any ideas for the last two letters, so I think this is it for this one.
EDIT2: Had another idea. Any ideas for getting `z` are welcome.
EDIT3: Got the last one! I could have sworn I had already used `C` somewhere, but turns out I hadn't. Still not a contender, but it was a fun exercise.
```
aa
```
[Try it online!](https://tio.run/##K/v/PzHx/38A "V (vim) – Try It Online")
```
Ab
```
[Try it online!](https://tio.run/##K/v/3zHp/38A "V (vim) – Try It Online")
```
ccc
```
[Try it online!](https://tio.run/##K/v/Pzk5@f9/AA "V (vim) – Try It Online")
```
³dd2Fd
```
[Try it online!](https://tio.run/##K/v//9DmlBQjt5T//wE "V (vim) – Try It Online")
```
Re
```
[Try it online!](https://tio.run/##K/v/Pyj1/38A "V (vim) – Try It Online")
```
Sf
```
[Try it online!](https://tio.run/##K/v/Pzjt/38A "V (vim) – Try It Online")
```
Ég
```
[Try it online!](https://tio.run/##K/v//3Bn@v//AA "V (vim) – Try It Online")
```
éh
```
[Try it online!](https://tio.run/##K/v///DKjP//AQ "V (vim) – Try It Online")
```
ii
```
[Try it online!](https://tio.run/##K/v/PzPz/38A "V (vim) – Try It Online")
```
Ij
```
[Try it online!](https://tio.run/##K/v/3zPr/38A "V (vim) – Try It Online")
```
¬kk
```
[Try it online!](https://tio.run/##K/v//9Ca7Oz//wE "V (vim) – Try It Online")
```
ál
```
[Try it online!](https://tio.run/##K/v///DCnP//AQ "V (vim) – Try It Online")
```
Ám
```
[Try it online!](https://tio.run/##K/v//3Bj7v//AA "V (vim) – Try It Online")
```
On
```
[Try it online!](https://tio.run/##K/v/3z/v/38A "V (vim) – Try It Online")
```
oo
```
[Try it online!](https://tio.run/##K/v/Pz///38A "V (vim) – Try It Online")
```
í^/p
```
[Try it online!](https://tio.run/##K/v///DaOP2C//8B "V (vim) – Try It Online")
```
±q9X
```
[Try it online!](https://tio.run/##K/v//9DGQsuI//8B "V (vim) – Try It Online")
```
²r#r
```
[Try it online!](https://tio.run/##K/v//9CmIuUirv//AQ "V (vim) – Try It Online")
```
ss
```
[Try it online!](https://tio.run/##K/v/v7j4/38A "V (vim) – Try It Online")
```
µtótttt
```
[Try it online!](https://tio.run/##K/v//9DWksObS4Dg/38A "V (vim) – Try It Online")
```
·uÓuu
```
[Try it online!](https://tio.run/##K/v//9D20sOTS0v//wcA "V (vim) – Try It Online")
```
²vD
```
[Try it online!](https://tio.run/##K/v//9CmMpf//wE "V (vim) – Try It Online")
```
¹wÍww
```
[Try it online!](https://tio.run/##K/v//9DO8sO95eX//wMA "V (vim) – Try It Online")
```
¶x5Fx5x
```
[Try it online!](https://tio.run/##K/v//9C2ClO3CtOK//8B "V (vim) – Try It Online")
```
´yyEVP
```
[Try it online!](https://tio.run/##K/v//9CWykrXsID//wE "V (vim) – Try It Online")
```
Cz
```
[Try it online!](https://tio.run/##K/v/37nq/38A "V (vim) – Try It Online")
] |
[Question]
[
**Closed**. This question is [opinion-based](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it can be answered with facts and citations by [editing this post](/posts/20994/edit).
Closed 2 years ago.
[Improve this question](/posts/20994/edit)
Write some code in any language that inputs a string such as "Today is a great day" (Note that there is no punctuation) and converts it to the "Secret Language". Here are the rules for the "Secret Language".
* a=c, b=d, c=e and so on (y=a and z=b)
* separate each word by a space
* make sure there is proper capitalization
Example:
```
Input: "Today is a great day"
Output: "Vqfca ku c itgcv fca"
```
It is a popularity-contest. Other users should give points by looking for most "to the point" yet "unique" code.
CHALLENGE:
I was looking up uncommon programming languages and I found a language called [Piet](http://en.wikipedia.org/wiki/Esoteric_programming_language#Piet) ([esolang](http://esolangs.org/wiki/Piet)). I challenge anyone to write it in this language.
[Answer]
# Smalltalk (Smalltalk/X), 29 27 chars
I am lucky - it is already in the String class:
```
'Today is a great day' rot:2
-> 'Vqfca ku c itgcv fca'
```
adding I/O, this makes it:
```
(Stdin nextLine rot:2)print
```
in the spirit of doorknob's obfuscated example below, how about:
```
Parser evaluate:('(Uvfkp pgzvNkpg tqv:2)rtkpvPN' rot:-2)
```
[Answer]
## Postscript
The HQ requires, that from now on all agents shall receive communication in printed form only (as electronic channels proved too unreliable) using special top secret font. It is your responsibility to include this top secret procedure into prologue of our printing software:
```
/define_Secret_font {
/Secret_font
/Coronet findfont dup
/Encoding get
aload pop 256 array astore
/secret_proc {
2 copy
26 getinterval aload pop
26 -2 roll 26 array astore
putinterval
} def
dup 65 secret_proc
dup 97 secret_proc
exch dup length dict dup
3 -1 roll {put dup} forall
exch /Encoding 4 -1 roll put
definefont pop
} def
```
And only that font is allowed, e.g.:
```
define_Secret_font
/Secret_font 36 selectfont
0 841 translate
20 -60 moveto
(Today is a great day) show
20 -120 moveto
(Programming Puzzles & Code Golf) show
showpage
```
And that's what it prints:

[Answer]
# Ruby, obfuscated edition (with commentary included!)
I suggest reading the entire thing; I find it quite amusing ;)
```
$s='';class Module;def const_missing c
# MAGIC:
$s+="#{c}".split("#{$;}").map{|x|x.ord-8**2}.reduce(:"#{43.chr}").chr;end;end
# My commentary ;)
ZZZY # ?
YAYYY # Oookay; you seem excited
Yaz # Typo?
Yay # Better
JEEEEEEF # You misspelled Jeff's name
LAZZZY # Yes, you are very lazy
Yax # Another typo...
LLAMA # Definitely not completely random at all...
EEEEEEEEEEEEE # Ouch my ears
IIIII # Ouch stop
ASDFASDFASDF # I SAID STOP BANGING ON THE KEYBOARD
YUMMY # ... you eat keyboards?
IIIII # Stop!
YUMMYY # Why are you eating your keyboard
LLAMA # That doesn't make sense :(
VV # :(
LLAMA # Could you stop saying that?!
CODEGOLF # Yay, one of my favorite SE sites! :D
VW # I don't drive
ASDFASDFASDF # Why do you keep banging on your keyboard?!?!
EEEEEEEEEEEEE # No
VVV # Stop
HELLOo # ...it's a little late for a greeting, isn't it?
DOGS # ...
OOOOOo # No, you're not a ghost.
HELLOOOO # Just a *bit* late.
NNNNNNN # Huh?
LLAMA # I said to stop.
print eval$s
```
Hints on how it works (spoilers, hover to show):
>
> This code builds a string and then evaluates it.
>
>
>
>
> It uses `const_missing` in order to build the string character by character.
>
>
>
>
> The string it ends up building is `gets.tr'A-Za-z','C-ZABc-zab'`.
>
>
>
[Answer]
# bash
Classic.
```
tr A-Za-z C-ZABc-zab
```
Example:
```
$ tr A-Za-z C-ZABc-zab <<< "Today is a great day"
Vqfca ku c itgcv fca
```
[Answer]
DFSORT (IBM Mainframe sorting program)
```
OPTION COPY
INREC BUILD=(1,80,TRAN=ALTSEQ)
```
No SORT control statement can start in column one.
For the above to work on its own, you'd have to change the default installation alternate translation table, to offset all values for upper- and lower-case letters, wrapping around the final two letters.
Without changing the default table, it would require an ALTSEQ statement listing all the required pairs of hex values (from-hex-code immediately followed by to-hex-code, each pair of hex values separated by a comma):
```
OPTION COPY
INREC BUILD=(1,80,TRAN=ALTSEQ)
ALTSEQ CODE=(xxyy,...)
```
So to get upper-case EBCDIC A to C and B to D:
ALTSEQ CODE=(C1C3,C2C4)
For the whole thing, that would be a lot of error-prone typing, of course, so you'd use another SORT step to generate the control cards for this step, and let SORT read them from the dataset created by that new step.
Of course, for any language which supports a "translation table", it is as easy as changing the translation table. Nice COBOL program, with a specific Codepage, and it could be done in one line of COBOL procedure code (plus the obligatory lines of COBOL that go with everything... not so many in this particular case).
Oh, the 1,80 is the "card image" which will contain the text. Probably all in upper-case on the first run...
[Answer]
# C, 75 bytes
```
main(c){while((c=getchar())>0)putchar(isalpha(c)?(c&224)+((c&31)+2)%26:c);}
```
Example:
```
$echo "Today is a great day" |./a.out
Vqfca ku c itgcv fca
```
[Answer]
## PHP
Not the shortest one though!
Live example: <https://eval.in/102173>
```
<?php
$str = 'Today is a great day';
$out = implode('', array_map(function ($val) {
if ($val == ' ') return ' ';
$c = ord($val)+2;
if (ctype_lower($val)) {
if ($c > ord('z')) {
return chr(ord('`') + ($c - ord('z')));
}
return chr($c);
}
else {
if ($c > ord('Z')) {
return chr(ord('A') + ($c - ord('Z')));
}
return chr($c);
}
}, str_split($str)));
var_dump($out);
```
Note:
```
ord('`') = ord('a') - 1
```
[Answer]
TI-Basic (the language that runs on TI-83 graphing calculators)
```
:ClrHome
:" abcdefghijklmnopqrstuvwxyz" //all symbols that can be interpreted
:Ans+Ans+Ans->Str1
:Menu("crippter","encript",1,"decript",2
:Lbl 2
:1->C
:Lbl 1
:if not(C)
:Imput ">",Str2
:if C
:Imput "<",Str2
:length(Str2)->D
:lenght(Str1)/3->E
:if not(C)
:Then
:randInt(1,E)->B
:sub(Str1,B,1)->Str3
:Else
:inString(Str1,sub(Str2,1,1),1)->B
":"->Str3
:For(X,1+C,D
:inString(Str1,sub(Str2,X,1)->A
:if not(C
:A+E-B-X->A
:if C
:A+B+X-1->A
:Str3+sub(Str1,A,1)->Str3
:End
:if C
:sub(Str3,2,D-1)->Str3
:Pause Str3
:Goto A
```
This is some nice encryption software (for a TI-83). By ti-83 I mean any calculator in the ti-83 or ti-84 family. "->" means "STORE" accessed by "STO>"
[Answer]
**Ruby ~~40~~ 32**
```
p gets.tr("A-XY-Za-xy-z","C-ZA-Bc-za-b")
```
update (as seen from danieros bash solution):
```
p gets.tr("A-Za-z","C-ZABc-zab")
```
[Answer]
I think I'll ROT2 it!
## Javascript
```
function r(a,b){return++b?String.fromCharCode((a<"["?91:123)>(a=a.charCodeAt()+2)?a:a-26):a.replace(/[A-z]/g,r)}
console.log(r('Qccipcr'));
```
[Answer]
# Java, it's actually understandable.
I know that anything with whitespace and parentheses has a hard time on CG, but here's a shot.
```
class SecretLanguage {
public static void main(String[] args) {
for (String S : args) {
for (char s : S.toCharArray()) {
System.out.print((char) (s + ((s < 'y') ? 2 : -24)));
}
System.out.print(" ");
}
}
}
```
There are separate contests for obfuscating code, but I can make mine ridiculous too.
```
class S{public static void main(String[]args){for(String str:args){for(char i:(str).toCharArray())System.out.print((char)(i+((i<'y')?2:-24)));System.out.print(" ");}}
```
[Answer]
# Python
```
a = list('abcdefghijklmnopqrstuvwxyz')
b = list('yzabcdefghijklmnopqrstuvwx')
c = {}
#generate conversion dictionary
for i in range(len(a)):
c[a[i]] = b[i]
instring = "the weather is very nice today"
outstring = ""
for i in list(instring):
try:
outstring += c[i]
except:
outstring += i
print outstring
```
Output:
rfc ucyrfcp gq tcpw lgac rmbyw
[Answer]
# JavaScript
```
// setup alphabet and secret rotated alphabet
//
var alpha=' abcdefghijklmnopqrstuvwxyz'
var rotor=' cdefghijklmnopqrstuvwxyzab'
alpha+=alpha.toUpperCase()
rotor+=rotor.toUpperCase()
function encrypt(str) {
return crypt(str, alpha, rotor)
}
function decrypt(str) {
return crypt(str, rotor, alpha)
}
// swap position of char from one dictionary to the other
function crypt(msg, d1, d2) {
var out=''
var len=str.length
for(var i=0; i < len; i++) {
var c = msg.charAt(i)
var j = d1.indexOf(c)
out += d2.charAt(j)
}
return out
}
```
[Answer]
## Javascript
```
var str = '';
var textInput = 'myString';
for (var i = 0; i < textInput.length; i++) {
str += textInput.charAt(i).replace(/([a-zA-Z])[^a-zA-Z]*$/, function (a) {
var c = a.charCodeAt(0);
switch (c) {
case 89:
return 'A'; //Letter Y!
case 90:
return 'B'; //Letter Z!
case 121:
return 'a'; //Letter y!
case 122: //Letter z!
return 'b';
default:
return String.fromCharCode(c + 2); //If not y, Y, z, or Z, then just two more from the usual char code
}
})
}
console.log(str);
```
What with all the comments, my hamster can understand this.
[Answer]
### Powershell
```
$chars = [int]('a')[0]..[int]('z')[0] | %{ [char]$_, [char]::ToUpper([char]$_) }
$y = $args[0].ToCharArray() | %{
$idx = $chars.indexOf($_);
if ($idx -ge 0) {
$chars[($idx + 4) % 52]
} else {
$_
}
}
-join [char[]]$y
```
Output:
```
PS C:\Temp> .\z.ps1 "Today is a great day"
Vqfca ku c itgcv fca
PS C:\Temp>
```
[Answer]
# Haskell
Here's a lens based implementation. I'm using `Iso` to represent the isomorphism between regular text and text converted into the secret language. Unless you provide the `--from` option, the input is converted into the secret language. If the `--from` option is provided, the opposite conversion is performed.
```
module Main where
import Control.Lens
import System.Environment (getArgs)
import Data.Char (ord, chr, isUpper, isSpace)
import Data.Word (Word8)
ord8 :: Char -> Word8
ord8 = fromIntegral . ord
chr8 :: Word8 -> Char
chr8 = chr . fromIntegral
ordIso :: Iso' Char Word8
ordIso = iso ord8 chr8
firstLetterOrd :: Word8 -> Word8
firstLetterOrd n
| n ^. from ordIso . to isUpper = ord8 'A'
| otherwise = ord8 'a'
secretChar :: Iso' Char Char
secretChar =
iso toSecret
fromSecret
where
toSecret, fromSecret :: Char -> Char
toSecret = secretConversion 2
fromSecret = secretConversion (-2)
secretConversion :: Int -> Char -> Char
secretConversion n c
| isSpace c = c
| otherwise = c & over ordIso (secretShift n)
secretShift :: Int -> Word8 -> Word8
secretShift shiftAmount =
preserveLetters $ (`mod` 26) . (+ shiftAmount)
preserveLetters :: (Int -> Int) -> Word8 -> Word8
preserveLetters fn n =
firstLetter + overWord8 fn (n - firstLetter)
where
firstLetter = firstLetterOrd n
overWord8 :: (Int -> Int) -> Word8 -> Word8
overWord8 fn = fromIntegral . fn . fromIntegral
help :: IO ()
help =
putStr
$ unlines
["SecretLang [--from]"
,"If the --from option is provided, the program"
,"converts from the secret language. Otherwise,"
,"it converts to the secret language."
]
convertContents :: (String -> String) -> IO ()
convertContents fn = do
input <- getContents
putStrLn . ("Output: " ++) $ fn input
main :: IO ()
main = do
args <- getArgs
case args of
("--from":_) ->
convertContents (^. mapping (from secretChar))
("--help":_) -> help
("-h" :_) -> help
_ ->
convertContents (^. mapping secretChar)
```
Examples:
```
$ ./SecretLang
Today is a great day
Output: Vqfca ku c itgcv fca
$ ./SecretLang --from
Vqfca ku c itgcv fca
Output: Today is a great day
```
[Answer]
# Python 2.x
An attempt at a feature rich Python solution.
Features:
* the use of a dict
* handling the list in a circular way, so that `shift=2` can be varied
* you can also use it to decipher when you know `shift` (just use minus), it'll also allows you to test your output.
* ability to add "shifting scopes" -- scopes in which you cycle
* option to either be `strict` for undefined characters, or just return the undefined input character.
* a secret language leaves no trace ;)
Here goes:
```
# Shifting scopes
lower_case = map(chr, range(97, 123))
upper_case = map(chr, range(65, 91))
space = [" "] # space will always be transformed to space
def secret(instring, shift, scopes, strict=False):
def buildTranslationDict(scores):
translation_dict = {}
for scope in scopes:
for index in range(len(scope)):
translation_dict[scope[index]] = scope[(index+shift) % len(scope)]
return translation_dict
translation_dict = buildTranslationDict(scopes)
# Use the translation dictionary to transform input
output = ""
for char in instring:
if strict:
output += translation_dict[char] # will crash if unexpected char
else:
try:
output += translation_dict[char]
except:
output += char
return output
```
Proof:
```
secret(instring="Today is a great day", shift=2, scopes=[lower_case, upper_case, space])
'Vqfca ku c itgcv fca'
```
Can you decipher `'Wrpruurz lv qrw edg hlwkhu!'` :) ?
[Answer]
# C
```
#include<stdio.h>
int main()
{ char p[256];
int i;
fgets ( p, 256, stdin );
for(i=0; i<256 ; i++)
{
if ( p[i] == '\n' )
{
p[i] = '\0';
break;
}
else
{
if((p[i] >= 'a' && p[i] <= 'x') || (p[i] >= 'A' && p[i] <= 'X') )
{
p[i] +=2;
}
else
{
switch(p[i])
{
case 'y': p[i] = 'a';
break;
case 'Y': p[i] = 'A';
break;
case 'z': p[i] = 'b';
break;
case 'Z': p[i] = 'B';
break;
case ' ': p[i] = ' ';
break;
}
}
}}
printf("%s", p);
return 0;
}
```
[Answer]
# EcmaScript 6:
```
alert(prompt(_='').split(_).map(x=>String.fromCharCode(x.charCodeAt()+(x>' '?x>'x'|x>'X'&x<'['?-24:2:0))).join(_))
```
[Answer]
**JAVA**
`32` is `space` so we print it out as is
`88` is `X` so anything less than `89` moves up 2 characters
`90` is `Z` so anything less than `91` moves down 24 characters (with anything less than `89` already handled so only `89` and `90` effectively)
Repeat same process for lowercase letters, ranging from `97` as `a` to `122` as `z`.
```
void secret(String s) {
for (char c : s.toCharArray()) {
System.out.print((char)(c == 32 ? c : c < 89 ? c + 2 : c < 91 ? c - 24 : c < 121 ? c + 2 : c - 24));
}
}
```
[Answer]
# PHP
This solution is rather boring:
```
echo strtr('Today is a great day','ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz','CDEFGHIJKLMNOPQRSTUVWXYZABcdefghijklmnopqrstuvwxyzab');
```
[Answer]
## Python 3
I think i didn't quite understand the question, but anyway:
```
alphabet = "abcdefghijklmnopqrstuvwxyz"
rot = alphabet[2:] + alphabet[:2]
rot = rot + rot.upper()
alphabet = alphabet + alphabet.upper()
def encode_letter(letter):
return rot[alphabet.index(letter)]
def encode_word(word):
return "".join(encode_letter(letter) for letter in word)
def encode_string(string):
return " ".join(encode_word(word) for word in string.split())
print("Output: " + encode_string(input("Input: ")))
```
[Answer]
# JavaScript (V8)
```
t=>t.replace(/./g,d=>/[a-z]/i.test(d)?((parseInt(d,36)-8)%26+10).toString(36)[/[A-Z]/.test(d)?"toUpperCase":"valueOf"]():d)
```
This is code golf, short *is* popular.
[Answer]
# Python 3
```
# To understand recursion, go to the bottom of the program
from string import ascii_letters
translate_table = {
c: chr(ord(c) + 2) for c in ascii_letters
}
def translate_helper(string):
if len(string) == 1:
if string not in {"y", "z"}:
return translate_table[string]
else:
return "a" if string == "y" else "b"
else:
return translate_helper(string[:-1]) + translate_helper(string[-1])
def translate(string):
return " ".join(map(translate_helper, string.split(" ")))
print(translate("Today is a great day"))
# To understand recursion, go to the top of the program
```
[Answer]
## Javascript, 255 bytes
```
const sl = text =>
text
.split(" ")
.map(word =>
word
.split("")
.map(c => String.fromCharCode(c.charCodeAt(0) + (c < "y" ? 2 : -24)))
.join("")
)
.join(" ");
console.log(sl("Today is a great day"));
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal)
```
@rotate:letter|
kL ←letter c [
←letter \Y = [
\A | ←letter \y = [
\a | ←letter \Z = [
\B | ←letter \z = [
\b | ←letter C 2 + C
]
]
]
] | ←letter
]
;
`Today is a great day`f °rotate; M ¤j
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%40rotate%3Aletter%7C%0A%20kL%20%E2%86%90letter%20c%20%5B%0A%20%20%20%E2%86%90letter%20%5CY%20%3D%20%5B%0A%20%20%20%20%20%5CA%20%7C%20%E2%86%90letter%20%5Cy%20%3D%20%5B%0A%20%20%20%20%20%20%20%5Ca%20%7C%20%E2%86%90letter%20%5CZ%20%3D%20%5B%0A%20%20%20%20%20%20%20%20%20%5CB%20%7C%20%E2%86%90letter%20%5Cz%20%3D%20%5B%0A%20%20%20%20%20%20%20%20%20%20%20%5Cb%20%7C%20%E2%86%90letter%20C%202%20%2B%20C%20%0A%20%20%20%20%20%20%20%20%20%5D%0A%20%20%20%20%20%20%20%5D%0A%20%20%20%20%20%5D%0A%20%20%20%5D%20%7C%20%E2%86%90letter%0A%20%5D%0A%3B%0A%0A%60Today%20is%20a%20great%20day%60f%20%C2%B0rotate%3B%20M%20%C2%A4j&inputs=&header=&footer=)
Finally, a chance to use the more obscure features of Vyxal! Behold the beauty of named functions, variables, if-else chains and function references. I also got to make good use of the codemirror functionality built into the online interpreter for once.
Also, I know caird said not to, but I answered anyway, because I never get the chance to properly show off the cooler stuff of my esolang.
[Answer]
# [Extended BrainFuck](http://sylwester.no/ebf/)
Since this is a popularity contest I've written this with the intention
of it being as easy to follow as EBF can be. It's heavily commented and
I've intentionally used macros to make the program flow more literal.
Probably the most difficult thing here is the main switch since EBF doesn't have any special means of doing it so it's in reality no simpler than how one would do it in BrainFuck except for the variables and balancing parentheses.
```
;;;; rot2.ebf : Perform rot2 on ascii text
;;;; Usage: bf ebf.bf < rot2.ebf > rot2.bf
;;;; echo "Today is a great day" | bf rot2.bf
;;;; # => Vqfca ku c itgcv fca
;;;;
;;;; BF interpreter/Compiler requirement:
;;;; Wrapping cells at any size (allmost all of them do)
;;;;
;;; Memory map
:tmp ; a temporary cell used for the read routine
:input ; a copy of the input for output purposes
:switch ; a copy of the input for the switch statements
:flag ; flag to indicate the predicate has been processed or not
;;; Macros
;; Ultracompatible read
;; supports EOF 0, -1 and no change
{read_tmp
$input+
$tmp(-),
[+[-$input-]] ; blanks for all EOFs
$switch [
@input &clear
$switch
]
}
;; for the switch we need
;; to do destructive testing
;; and we need to preserve the
;; original as well.
{copy_input
$tmp(-$input+$switch+)
}
;; clears the cell
{clear (-)}
;; prints current cell
{print .}
;;; Main proram
;;; flow starts here
&read_tmp
while $tmp not eof
(
©_input
$flag+
$switch 10-(22-(
;; not linefeed/space
$switch 57-(-(31-(-(
;; default: not wrapping
&clear
$flag-
$input 2+))))
$flag (-
;; wrapping
$input 24-)))
$flag &clear
$input &print &clear
&read_tmp
)
;;; End
```
[Answer]
**Javascript**
```
var STR = "Today is a great day";
//so i can replace chars at a index in the string
String.prototype.replaceAt=function(i, char) {
var a = this.split("");
a[i] = char;
return a.join("");
}
function secretIt( str ){
for( var i = 0; i < str.length; i++ ) {
var c = str.charCodeAt( i );
/**
* check for spaces first
* check if get outside of the letter range for both lower and upper
* if we dont go then were good
* if so go back 26 chars
*/
str = str.replaceAt( i, String.fromCharCode( ( c == 32 ) ? c : ( ( c = c + 2 ) > 91 && c < 97 || c < 123 ) ? c : c - 26 ) ) ;
}
return str;
}
console.log( secretIt( "Qsncp qcapcr ambc" ), ' ' , secretIt( STR ));
```
[Answer]
# Q
```
{x^(raze a!'rotate[2] each a:.Q`a`A)x}
```
[Answer]
## Java
```
void sl(String s){
for (char c: s.toCharArray()){
char l = Character.toLowerCase(c);
System.out.print((char)(c + (l < 'y'? l < 'a'? 0: 2: -24)));
}
}
```
] |
[Question]
[
Consider the [triangular numbers](https://en.wikipedia.org/wiki/Triangular_number) and their forward differences:
$$
T = 1, 3, 6, 10, 15, 21, ... \\
\Delta T = 2,3,4,5,6, ...
$$
If we alter \$\Delta T\$ so that it begins with a different integer, we get a different, yet similar sequence (assuming that it begins with \$T'\_1 = 1\$):
$$
\Delta T' = 3,4,5,6,7,8,... \\
T' = 1, 4, 8, 13, 19, 26, 34,...
$$
This can be extended to begin with negative numbers:
$$
\Delta T' = -2,-1,0,1,2,3,... \\
T' = 1,-1,-2,-2,-1,1,4,...
$$
More generally, for a given integer \$n\$, we can define a "triangle-style" sequence \$T'\$ as a sequence whose forward differences form the sequence \$n, n+1, n+2, n+3, ...\$, and that has \$1\$ as its first term
---
You should take an integer \$n\$ and do one of:
* Take a positive integer \$m\$ and output the first \$m\$ integers of the "triangle-style" sequence for \$n\$
* Take an integer \$m\$ and output the \$m\$th integer in the "triangle-style" sequence for \$n\$. You may use either 0 or 1 indexing
* Output all integers in the "triangle-style" sequence for \$n\$
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
---
## Test cases
These are the first 10 outputs for each provided \$n\$:
```
n -> out
-4 -> 1, -3, -6, -8, -9, -9, -8, -6, -3, 1
-3 -> 1, -2, -4, -5, -5, -4, -2, 1, 5, 10
-2 -> 1, -1, -2, -2, -1, 1, 4, 8, 13, 19
-1 -> 1, 0, 0, 1, 3, 6, 10, 15, 21, 28
0 -> 1, 1, 2, 4, 7, 11, 16, 22, 29, 37
1 -> 1, 2, 4, 7, 11, 16, 22, 29, 37, 46
2 -> 1, 3, 6, 10, 15, 21, 28, 36, 45, 55
3 -> 1, 4, 8, 13, 19, 26, 34, 43, 53, 64
4 -> 1, 5, 10, 16, 23, 31, 40, 50, 61, 73
39 -> 1, 40, 80, 121, 163, 206, 250, 295, 341, 388
68 -> 1, 69, 138, 208, 279, 351, 424, 498, 573, 649
48 -> 1, 49, 98, 148, 199, 251, 304, 358, 413, 469
```
[Answer]
# [Haskell](https://www.haskell.org/), 18 bytes
```
f n=scanl(+)1[n..]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz7Y4OTEvR0Nb0zA6T08v9n9uYmaegpWVgqe/goYmF5hnq5CSz6WgUFCUmVeioKJQkpidqmAKZKQpaOiaaGKTAUoZ4BA3wSVu8R8A "Haskell – Try It Online")
Outputs an infinite list.
```
f n = scanl (+) 1 [n..]
[n..] -- Make an infinite list n, n+1, ...
scanl (+) 1 -- Cumulative sum, starting at 1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
Ḷ+S‘
```
[Try it online!](https://tio.run/##y0rNyan8///hjm3awY8aZvw3NAAyDy8/vE/XpMjk0BL3/wA "Jelly – Try It Online")
Takes 0-based \$m\$ and \$n\$, and returns the \$m\$-th term.
### How it works
```
Ḷ+S‘ Left arg: m, Right arg: n
Ḷ [0..m-1]
+ [n..n+m-1]
S Sum
‘ Increment
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 4 bytes
```
ʁ+∑›
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%CA%81%2B%E2%88%91%E2%80%BA&inputs=9%0A-4&header=&footer=)
An exact port of Bubbler's jelly answer. Takes `m` as the 0-based index to retrieve and `n` as the variant
## Explained
```
ʁ+∑›
ʁ # [0 ... m-1]
+ # ↑ + n (vectorises)
∑ # sum(↑)
› # ↑ + 1 (implicitly output)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 24 bytes
Takes an integer \$n\$ and outputs the \$m\$th integer in the "triangle-style" sequence for \$n\$. Uses 0-indexing.
```
lambda n,m:~-m*m/2+n*m+1
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFPJ9eqTjdXK1ffSDtPK1fb8H9afpFCpkJmnkJRYl56qoahgaYVl0JBUWZeiUKahq6JjkKm5n8A "Python 2 – Try It Online")
### [Python 2](https://docs.python.org/2/), 26 bytes
```
lambda n,m:m*(m+n+n-1)/2+1
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFPJ9cqV0sjVztPO0/XUFPfSNvwf1p@kUKmQmaeQlFiXnqqhqGBphWXQkFRZl6JQpqGromOQqbmfwA "Python 2 – Try It Online")
[Answer]
# [convey](http://xn--wxa.land/convey/), 14 bytes
```
1"}
+<
",{
>+1
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiMVwifVxuKzxcblwiLHtcbj4rMSIsInYiOjEsImkiOiItMSJ9)
[](https://i.stack.imgur.com/hJq3J.gif)
The lower loop is the increment, that starts with the input `{` and gets increased by one `+1` each iteration. It's get copied `"` into `+`, where the accumulator loops. Every iteration it gets copied into the output `}`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
r+ṖS‘
```
[Try it online!](https://tio.run/##y0rNyan8/79I@@HOacGPGmb8//9f1@S/CQA "Jelly – Try It Online")
Given left argument \$n\$ and right argument \$m\$, output the \$m\$th element of the \$n\$-variant triangular sequence (0-indexed).
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~40~~ 38 bytes
```
param($a,$b)($i=1)
2..$b|%{($i+=$a++)}
```
[Try it online!](https://tio.run/##fVLtSsNAEPzdPMUhpzY0keRylw8kUPEBFOs/EUnrqZV@maQoaJ@9zrZ3uaIiZJPb3ZnZ2SSr5buumxc9m4WTZa23/Kn83K6qupr3eRXwsd/n0zL2PXF2xsdfx59IByWvBgN/s9143rDv9YJhP5RBHOEZByxMECkiRxQmclNDL/b9PSVxFIGQCGVC7mtoIYsjyxCOYVlif8YFDqbENKGwhLgjRLsLB/RT0kRAW6AicgOPOjRVd4oZzpSDIlAR2CXJDNyJ/4NFJzV45/4vD6iiJpErZQjuBR3uBjCACUoSuSItaQjuIygjT16ASEgDuUKkOGeJHVG4GejlxBG7JcASEdGJIwpFI8l6bt9WmnfUtCBzOTHoltHmiiQFuSxQU9nOp/0w0nElwISIJd0KWo@oSSRJBDVJa8uUqD7@P693N12097zVTXtZNTpgfI7QHys9afUjKxl/8Hq81s161iI74U@sAwPb9S6aUVtPF8/EMOjwdTldsNOAnQJlFQ9x3ZRD5N316HLdtMv51fgV3fshPPZG68lEN40T72RC/cZ@iZ@DcmtNluzIOQ7h@YjaN3ajH4LobbzN9hs "PowerShell Core – Try It Online")
Saved two bytes by removing superfluous parentheses
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
L<+O>
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fx0bb3@7/fxMuXTMA "05AB1E – Try It Online")
05AB1E looks like brainfuck :P
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 9 bytes
```
{1+/x+!y}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqtpQW79CW7Gy9n@agp66uq6Jgq6xgq6Rgq6hgoGCoYKRgrGCiY6@VYyVoqHBfwA "K (ngn/k) – Try It Online")
Takes `n` as `x`, and `m` as `y`; outputs the m-th integer in the "triangle-style" sequence for n (0-indexed). Feels like there is a more clever way, but...
* `x+!y` generate `n..n+m-1`
* `1+/` take the sum (seeded with 1)
[Answer]
# [kalker](https://kalker.strct.net/), 26 bytes
Nothing fancy, just bringing attention to [kalker](https://kalker.strct.net/), a lovely command-line calculator that I recently stumbled upon.
```
f(a,b)=Σ(1,b,n)+(b-1)(a-2)
```
An online interpreter can be found [here](https://kalker.strct.net/kalk).
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 44 bytes
```
f=lambda n,m,a=1:m and[a]+f(n+1,m-1,n+a)or[]
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P802JzE3KSVRIU8nVyfR1tAqVyExLyU6MVY7TSNP21AnV9dQJ087UTO/KDr2f0FRZl6JRpqGromOmaYmF4xrgMJDlTOxAHH/AwA "Python 3.8 (pre-release) – Try It Online")
```
f=lambda n,m,a=1:m and[a]+f(n+1,m-1,n+a)or[]
a=1 #Set accumulator to 1 initially
m and #If m>0
[a]+f(n+1,m-1,n+a) #Prepend accumulator to the rest of
#Every time, the accumulator increases by
#the current n
#the sequence
or[] #Otherwise, return an empty list
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
∫:1¡→
```
[Try it online!](https://tio.run/##yygtzv7//1HHaivDQwsftU36//@/iQUA "Husk – Try It Online")
an infinite list.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 30 bytes
```
param($m,$n)$m*($m+2*$n-1)/2+1
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVXRyVPUyVXC8jSNtJSydM11NQ30jb8//@/yX9dMwA "PowerShell – Try It Online")
-1 byte thanks to @Julian
[Answer]
# [R](https://www.r-project.org/), 28 bytes
```
function(n,m)m*(m-1)/2+m*n+1
```
[Try it online!](https://tio.run/##PcxLDkAwEADQvVNYzjCNXyMIV7C0l6ZNmpgSKimXr513gHdGM0VzO@Xt7sARI2fAosKizjlzeRXDKBQIOUhqemo7kh0ml/bzyvqCbT2O7YFA6X9YXLTy@2lfDQbBUjn0iJQGjB8 "R – Try It Online")
Outputs `m`th (0-indexed) term.
Using straightforward formula.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 19 bytes
```
n=>m=>m--*(m/2+n)+1
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i4XiHR1tTRy9Y208zS1Df8n5@cV5@ek6uXkp2ukaeiaaGqYaWr@BwA)
-5 bytes thanks to Bubbler, tsh and ophact
[Answer]
# MATLAB/Octave, 22 bytes
```
@(n,m)sum([1,n:m+n-2])
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNPJ1ezuDRXI9pQJ88qVztP1yhW83@abWJesTVXmoauiY6hgSaIYQxjGMEYhlCGggGMAReBqVGA6VKAmWNsCWWYWUAZJmDGfwA "Octave – Try It Online")
Anonymous function. Outputs `m`th integer of sequence for `n`.
Alternatively, if we want to output all elements from 1st to `m`th we can achieve so with **25 bytes**:
```
@(n,m)cumsum([1,n:m+n-2])
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNPJ1czuTS3uDRXI9pQJ88qVztP1yhW83@abWJesTVXmoauiY6hgSaIYQxjGMEYhlCGggGMAReBqVGA6VKAmWNsCWWYWUAZJmDGfwA "Octave – Try It Online")
---
The part `m:m+n-2` of the functions is actually sequence ΔT - vector starting from `n` to `m+n-2`.
We subtract 2 to get the correct number - one value is added as the `1` which starts the triangle sequence and second is added by the fact we include both ends of the vector.
We could subtract 1 and get 0-based indexing but since MATLAB is 1-base indexed I decided to stay consistent and subtract 2 as it doesn't change the length of the code.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 19 bytes
```
f:{1+y*(y+x+x-1)%2}
```
[Try it online!](https://tio.run/##y9bNz/7/P82q2lC7UkujUrtCu0LXUFPVqPZ/WrSuibVZ7H8A "K (oK) – Try It Online")
-2 thanks to tip of @Razetime
[Answer]
# [Commentator](https://github.com/cairdcoinheringaahing/Commentator), 44 bytes
```
{- {-//-}-}
?{-*///{- {-# /*-}-}-}
```
[Try it online!](https://tio.run/##S87PzU3NK0ksyS/6/1@hWheI9PV1a3VrueyrdbX09fXBQsoKcKCvBZLVrf3//7@uCQA "Commentator – Try It Online")
outputs all entries in the triangle style sequence for n.
[Answer]
# [J](http://jsoftware.com/), 13 bytes
```
1+*+2%~]-~]*]
```
[Try it online!](https://tio.run/##Tc7NCsIwDAfw@54iCDK3bnX9WNcWB0PBk@zg2eJBHOrFN9ir10bE5ZBDfiT55xVXPJ@g95BDBQ34VDWHw/l0jIKVTK7nUM@hDLHIxj0HwbaXodqwJx92vsiy@@3xBgE9XDVM4H59g6AIOAS5gLQIYgHVJUjZf9AGgUy0LQK5YTQCSekUAvlDWYxRju7gJ8bSHBT9lfgB "J – Try It Online")
Based on same formula used by [pajonk](https://codegolf.stackexchange.com/a/226566/15469) and others.
Returns `m`th element, with 0 indexing.
* `]-~]*]` `m` subtracted from `m*m`...
* `2%~` divided by 2...
* `1+*+` plus `m*n` plus 1
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 21 bytes
```
f←{(⍺×(⍺+⍵+⍵-1)÷2)+1}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/P@1R24RqjUe9uw5PB5Haj3q3grCuoebh7Uaa2oa1//8DAA "APL (Dyalog Extended) – Try It Online")
Port of my JS answer.
Dyadic function taking \$m\$ on the left and \$n\$ on the right.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 44 bytes
```
(n,m)->Vec(1/(1-x)^3-(2-n)*x/(1-x)^2+O(x^m))
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmD7XyNPJ1dT1y4sNVnDUF/DULdCM85YV8NIN09TqwLKN9L216iIy9XU/J@WX6SRp2CroGuiowBEBUWZeSVAASUFXTsFJR2FNKBhCoYGmkCVAA "Pari/GP – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 44 bytes
```
n=>g=(m,j=1,i=n)=>m--?[j,...g(m,j+i++,i)]:[]
```
[Try it online!](https://tio.run/##FchLCoAgFADA6/jwQ0KLCJ4dRFyIqSh@IqPrG81ysn3tcHe6Ht766WfA2VBFJJVllCxhA1SV80NnJoSI/9NEKUtgdm2m62304kXpkQSybkDkAjA/ "JavaScript (Node.js) – Try It Online")
>
> Take a positive integer m and output the first m integers of the "triangle-style" sequence for n.
>
>
>
Simple recursive function.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
I⁺⊘×Iη⊕η×⊖η⁻θ²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyCntFjDIzGnLDVFIyQzN7UYIpyhqaPgmZdclJqbmlcClMrQ1ASKQBS4pCKL6yj4ZuYBzSjUUTDSBAHr//91TbhM/uuW5QAA "Charcoal – Try It Online") Explanation: \$ T'(n, m) = T(m) + (m - 1)(n - 2) \$.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 84 bytes
```
\d+
$*
^,
-,
^-
-11
^1,
-1,
^11
(?=(1*,1)?(1*))1
$2
-(1*)(1*,)\1
-$2
-?,
^$|1+
$.&
```
[Try it online!](https://tio.run/##HZC7TsNAEEX7@Q6D7LCLdh5xvAVyyU9EFkhQ0FAgSv7dzNkiN44z5@rq/Hz@fn2/nw/z69t5/3iS6SJHkVrkqFJV5dD8lZ8jn2XeX2a9FF32/FoWlcmk8sjb5a5SebEXkWP60yx7fjzPGiX/iGKEE0FciZW4ERvRCW1SHcRBHMRBHMRBHMRBHMQHYiAGYiAGYiAGYiAGYiA2EAVREAVREAVREAVREAVRkJZES6Dlfcvzltctj1vetjxtedk4pJpmiumlllZK6aRyNDKb1YxmM5NZzGD2MnesRQlGEIIPdGADGbhAxTCBbmwjG9eoxjSi8YzmYdk7lZ3OTmmntVPb6e0Ud5o71R1k3RLJMMKJIK7EStyIjejjOOeABEiABEiABEiABEiAcNz@AQ "Retina 0.8.2 – Try It Online") Link includes test cases. Takes `n,m` as input. Explanation:
```
\d+
$*
```
Convert to unary.
```
^,
-,
^-
-11
^1,
-1,
^11
```
Subtract 2 from \$ n \$.
```
(?=(1*,1)?(1*))1
$2
```
Calculate \$ (n - 2)(m - 1) \$ and \$ T(m) \$.
```
-(1*)(1*,)\1
-$2
-?,
```
Take the sum.
```
^$|1+
$.&
```
Convert to decimal.
[Answer]
# [Raku](https://raku.org/), 19 bytes
```
{[\+] [1,|[$_..*]]}
```
```
[$_..*] -- generate infinite list from topic variable $_ (implicity set when calling fn with 1 param) to infinity
|[$_..*] -- flatten once
[1,|[$_..*] -- put the flattened version into a list with 1 at the front
[\+] [1,|[$_..*]] -- triangular reduce on addition
{[\+] [1,|[$_..*]]} -- put in a block
```
[Try it online!](https://tio.run/##fVDRSuRAEHyfr2gHkY0mMTOZSTIse/p6cH@QjRI0C4E1rpt4ILv76Juf4P3c/chaHTMgxyGkQ3d1VXUlm2a7zo4PL3S2ogUdd@XyoqJShfvy9DaOz6vqwMvroemH6K7um6jebkFct13Txw/1Zhb9oCVPtBM0wnG/WbfD7FISVnK/lyHJy6BMQlJsGN83zYaF5/HPbgjEIZgLsXrc/nsD4tmy7UK6fnwegtGdg9Rdj/OrWdsF5Y1Kqjnwvn4hyZuyosViFKDbMRL/avuBmqffI0pXVyT/vr9KOjlB8@dNHuRcHI6R4XMqpChFZagC5aYqJgw7JaLUUzXKoOxU5hPDCpNKRKQ907P1Z48HXLgqdnQiUhMxGR80wDP2QMFLA9GFoGSi8Tha5Oh5BlcD0Qib5oK83TckbDJBPuD/zgEFZjBbK8h/9NfcYIGRAjKYLZsYQf5P2smQz2KVshizRWXo81SkzpsCK5irx5xg64RlzNXO8g0OWRQiKyZJ5jhFwUx@5fxRlq00x3HAbD4GcsJ4jQGJN8rwy3F@lqSJYTEww99lMvcB)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 4 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
r+Σ)
```
Similar as the Jelly, Vyxal, and 05AB1E answers.
Inputs are a 0-based \$m\$ and \$n\$, and it outputs the \$m\$'th triangle-style number.
[Try it online.](https://tio.run/##y00syUjPz0n7/79I@9xizf//DRR0TbgMQYQRiDAGESYgwlJB1xhEGIEIQyBhAMQgGiQAkgEpMbYEEmYWIJ4FAA)
**Explanation:**
```
r # Push a list in the range [0, (implicit) first input-integer)
+ # Add the second (implicit) input-integer to each value in this list
Σ # Sum this list
) # Increase it by 1
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~80~~ 71 bytes
```
[S S S N
_Push_0][S N
S _Duplicate_0][T N
T T _Read_STDIN_as_integer][T T T _Retrieve_input_m][S N
S _Duplicate_m][S S S T N
_Push_1][T S S T _Subtract][S S S T S N
_Push_2][T S T S _Integer-divide][S S S N
_Push_0][S N
S _Duplicate_0][T N
T T _Read_STDIN_as_integer][T T T _Retrieve_input_n][T S S S _Add][T S S N
_Multiply][S S S T N
_Push_1][T S S S _Add][T N
S T _Print_as_integer_to_STDOUT]
```
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/##K8/ILEktLkhMTv3/X0FBgQsIObk4QQDIAgIgB0iAGApAFoiBrAYiAVYJVggkFTj//7fkMrYEAA) (with raw spaces, tabs and new-lines only).
**Formula used:**
Given a 0-based \$m\$ and \$n\$, it outputs the \$m\$'th triangular-style number with the following formula:
$$T(n,m) = m\left(\left\lfloor\frac{m-1}{2}\right\rfloor + n\right) + 1$$
[Answer]
# T-SQL, 88 bytes
```
SELECT-sum(~number+~(1/~number)*~-~-@)over(order by number)FROM spt_values
WHERE'P'=type
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1507982/triangle-style-sequences)**
[Answer]
# [Rust](https://www.rust-lang.org/), 20 bytes
```
|n,m|(m+2*n-1)*m/2+1
```
[Try it online!](https://tio.run/##fVJdb5tAEHy/X7HxQwQJUDg@DHbjh/6EPvQlqiLLPiRUOFM40qgxv92dhaO21CoSC3ezs7Oza3dDby5Dr6g3x82mOm02X4byq9oft6LU1Owr7bj0TrUyVD5dztprzk7zKB@0H7kPzSf5GF2ItoKoPHVUV1pRpa9aOLBAUJ8OP/iDfM964NOk6WiP1FurDkYdXXqidt/16qXS7WCce6YHg/7V7VvHdbdiqmq7Sps7Z/U@kr@jlUfa3U4JNtBw9zAIotD2mLt0qh9qA/kS/ZpFiagqUbEjkP/KerRytzRawrUZErOK7Ua073vVmRf1886ZM9dJnhtkaeir3@q75Y9X87WG4mrCRzEK3vPt2Dz1hu5707k8oVPF0vumDp/x3d2urhkMVTzUtKa@rSvjrKad2JaONYo5TaDVm8EvsGwzMF3V4DM1vsG9j2psD15R0AA5v55f/1Fwg8OprrEGx520XDFe/IR9RR75MSJD5IjCRm4x5CLhxwtVIhJEaiOZMaRwi0Lhy4W5sOV8xgMuVCNWLIQfWWI4PTgAz1gDAS0JROYCf4OZxtdJYo0z38GVQCTMxmtBi9wHJGQyQYvB/7UDCizBPU0FLUPf@gYLjBhQgnvKIomgZZOpFeS2SMVcjHuKyHBexyIuFlFgOXPl5BNsGXIZc2WRcg82meciy21JVrCLnJn8WvNQKUtJtlMAS9eToUIkS00CEmeihF8F@@eSOEy4GFjCcyVZ8Qc "Rust – Try It Online")
Takes \$n\$ and \$m\$ and returns the \$m\$-th integer (0-based indexing).
Uses the straightforward formula.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
M.u++NGYUtH1
```
Takes \$n\$ and \$m\$, and returns the first \$m\$ integers of the sequence for \$n\$.
[Try it online!](https://tio.run/##K6gsyfj/31evVFvbzz0ytMTD8H96vImCocH/f/kFJZn5ecX/dVMA "Pyth – Try It Online")
] |
[Question]
[
The title says it all; Given a number in the binary (base-2) number system, output the same number expressed in unary (base-1).
You should take the binary number as a string (optionally with a separator), list, or equivalent structure of digits, using any number or digit you like for the digits. The unary output can use any aforementioned format, and it should use a single-digit throughout the number but does not have to be consistent for different input values. You may choose to assume that the binary number will have no more than 8 bits, and/or that it will always be left-padded with zero bits to a certain length.
One method you may use to achieve this task is documented at [this esolangs.org article](https://esolangs.org/wiki/Binary_to_unary_conversion):
1. Replace all `1`s with `0*` (Using `*` as the unary digit; you may use any character.)
2. Replace all `*0`s with `0**`.
3. Remove all `0`s.
Here are some examples, using `0` and `1` for the binary digits and `*` for the unary digit:
* `1001` → `*********`
* `1010` → `**********`
* `00111111` → `***************************************************************`
* `00000` → (empty output)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins.
[Answer]
# [TypeScript](https://www.typescriptlang.org)'s Type System, ~~130~~ 128 bytes
```
//@ts-ignore
type R<S,F,X>=S extends`${infer A}${F}${infer B}`?R<`${A}${X}${B}`,F,X>:S;type B<S>=R<R<R<S,1,"02">,20,"022">,0,"">
```
[Try it at the TypeScript Playground!](https://www.typescriptlang.org/play?#code/PTAEGEHsDsDcFMBOAXUAjAltAhognqMpKAK476gC0oAjAEwAc6ey8AzqABRoHSSQATADbwAttmgBKAFDSQAAWRtKGAOZ9E8acjwAHeKABKAHgDKAGgBi5gBoA+ALynQ8AB6toAtgAMAJAG8sADMkUABBAF8AyyjA6BDEUAAhCO8AfhM-f0iAm1iU7ytbOwAuUwBuHX1ks0cTerNzGnMAIgAGOha7czo21o7O7r6WrtkqgwAVdmQ20Acakbs5MFBQAD007T1J6Zo5hZpRkFX1zfHQKbZkOn2k4xaaNsejldOt6svkAGZb+8enl4nDbvHZXAAsv3aTxoMJhgNWwKAA)
Uses 2 as the unary digit. Defines a utility type to recursively remove all occurrences of a given string with a different string, and then defines the main type which is a series of nested calls to the utility type.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes
```
BI
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJCSSIsIiIsIlwiMTAxMFwiIl0=) or [see it with asterisks instead](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJCSSIsIsOwXFwqViIsIlwiMTAxMFwiIl0=)
Same as my Thunno 2 answer.
#### Explanation
```
BI # Implicit input
B # From binary
I # That many spaces
# Implicit output
```
[Answer]
# Excel, 20 bytes
```
=REPT(9,BIN2DEC(A1))
```
Input in cell `A1`.
[Answer]
# [Haskell](https://www.haskell.org/), 26 bytes
```
f l=10^foldl((+).(2*))0l-1
```
[Try it online!](https://tio.run/##PcZBCoAgEEDRq7jUUtH2HqEThMFQWdJYkp2/KVzE48PfoOwLIlFg6KwZw4kzct4KzbtGCIPKUoJ4MMcS5J7nKx63DoINg5XmY72s91Xv5z09U0BYC6kp5xc "Haskell – Try It Online")
Input is a list of `0/1`, output is a number like `9999999999` made of the digit `9`.
Haskell is interesting for this challenge because it lacks base-conversion built-ins without imports, so we have to do it ourselves. This answer folds the operation `\n b->n*2+b` over the list of bits to get a number `k`, then computes `10^k-1` to get a number made of `k` 9-digits. The 9's trick is shorter than more natural methods like `replicate k 1` or `1<$[1..k]` or `take k[0,0..]`.
It's slightly longer to do the power-of-10 within the fold and decrement after:
**27 bytes**
```
pred.foldl(\n b->n^2*10^b)1
```
[Try it online!](https://tio.run/##PcZBDkAwEEDRq8wSQVr7uoET0Calihg1Kec3hERefvJne6wjInvVMcXRlX5Hh0kXoC/qYKpMCtOnkje7BFCwWWogobiEs/QptK3MxUPqHN59@vanNV@DRzsdXAxENw "Haskell – Try It Online")
though if we bend the rules and represent bits as `1` or decimal `10`, we can do
**21 bytes**
```
pred.foldl((*).(^2))1
```
[Try it online!](https://tio.run/##VYdBDkAwEAC/ssdWqlF3T/CCqqQpRaza4P0WCQeZySQz@n3uETlWDdPWdzqu2KEQmdSiLaU0vPgpQQWLpxoEbVM6dJRgrSmUeSicgnfufPPTOT5DRD/snAeiCw "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/), 26 bytes
```
foldl(\s b->s++s++[1|b])[]
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPy0/JyVHI6ZYIUnXrlhbG4iiDWuSYjWjY//nJmbmKdgq5CYW@GoUFGXmleilaSpER4cUlabquCXmFMNIkECsjgKyBIIJl8BFxMb@/5eclpOYXvxfN7mgAAA "Haskell – Try It Online")
Input is list of Booleans, output is a list of 1's. This iterates over the list of Booleans, each time doubling the current string then appending an additional `1` if the bit is `True`.
[Answer]
# [Python 3](https://docs.python.org/3/), 21 bytes
```
lambda s:"*"*int(s,2)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYSklLSSszr0SjWMdI839BEYiZpqFkaGBooKSp@R8A "Python 3 – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 3 bytes
Anonymous tacit prefix function. Takes list of binary digits and returns list of `1`s
```
⊥⍴≡
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HX0ke9Wx51Lvyf9qhtwqPevkddzY961wDFDq03ftQ28VHf1OAgZyAZ4uEZ/D9NwVDBAAgNuSAsIAaywCIICAA "APL (Dyalog Extended) – Try It Online")
`⊥` the base-2 evaluation
`⍴` **r**eshapes
`≡` the depth (nesting level, which is always 1 for a list)
[Answer]
# [TypeScript](https://www.typescriptlang.org) Type System, 79 bytes
```
type B<S>=S extends`${infer Q}${infer V}`?`${B<V>}${B<V>}${Q extends"1"?Q:""}`:S
```
[Try it on the Typescript Playground!](https://www.typescriptlang.org/play?#code/C4TwDgpgBAQgPAZQHwF4FQgD2BAdgEwGcADAEgG8BLXAMwgCcoBFAXwursYDUXiB+MuXhckbIXBFimGbHiIAiAIzy+TAFzz5vNQgBQu0JCgAVCIWAAGKClhxNSXQHpHUVwD0+B8NFPnF12yV5B2dXKA8vI19gACYA+HkLRSTgpxd3T0MfM2AAZni7ZJSQ9PDM7xMcgBYCpUV6+osLVNCMoA)
Note: This works with little-endian binary, not big-endian.
While the algorithm in the post allows simply performing replacements, we can take advantage of Typescript's ability to anchor string matches for a much simpler algorithm.
Essentially, `S extends`${infer Q}${infer V}`` matches the first character `Q` and the rest of the string `V`. We recurse on `V` twice, and append a 1 if `Q` is a 1.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
```
B1ḋ
```
[Try it online!](https://tio.run/##yygtzv7/38nw4Y7u////RxvoGOgYImAsAA "Husk – Try It Online")
```
ḋ # interpret input as binary digits
B # and convert this to base
1 # 1
```
[Answer]
# x86+MMX machine code, 10 bytes
Despite the question only saying the input has to be "binary", comments seem to imply they're thinking of a text string of base-2 digits, not 1-bit digits packed into an integer which a computer can already use directly as an unsigned integer. If that's allowed, see my 7-byte answer on [Output / Convert to unary number](https://codegolf.stackexchange.com/questions/262975/output-convert-to-unary-number/263103#263103).
This is that answer plus conversion from 8 bytes to an 8-bit integer, by extracting the high bit of each input. Input is in `mm0`, an MMX vector register, with the lowest element being the *least* significant. (If stored to memory, this would be opposite of standard printing order where the most significant goes first, at the lowest address of a string.)
```
; machine code | NASM source
; RDI or ES:EDI = output buffer of size n+1
binary_to_unary:
; pslld mm0, 7 ; 4 bytes. For input digits '0' / '1', shift the low bit to high
0FD7C8 pmovmskb ecx, mm0 ; pack the binary digits into an integer in ECX
; memset(dst, '1', n)
B031 mov al, '1'
F3AA rep stosb
880F mov byte [rdi], cl ; terminate the C-style string
C3 ret
```
For ASCII `'0'` / `'1'` input, we'd start with `pslld mm0, 7` to shift the low bit to the high position of each byte. Also, if the digit-string was loaded from a string in memory in printing order (most significant at lowest address), we'd need to byte-reverse. In that case scalar code to read input would be smaller than `movbe` or load+`bswap` in an integer register + `movq mm0, rax`, or `psufb` with an 8-byte vector constant.
In this current version, our input string in an MMX register is effectively big-endian, most significant digit in the highest element number (on the left when writing it in [the notation](https://stackoverflow.com/questions/41351087/convention-for-displaying-vector-registers) Intel manuals use to document vector instructions).
# x86 scalar machine code, 14 bytes, input from a C string in printing order
* RDI or ES:EDI points to an input buffer of base-2 ASCII digits, terminated by a `0` byte (or any byte below ASCII `'0'`), padded to at least 32 digits.
* RSI or ES:ESI points to an output buffer of size n+1, will be filled with `'0'` digits and terminated with a `0`.
Callable from C with the x86-64 System V calling convention as `void binary_string_to_unary(const char *binary_src, char *unary_dst);`. Use the x32 ABI for 32-bit pointers, or change the `mov edi, esi` to `push rsi`/`pop rdi` to copy a 64-bit register with the same code size. (Or use the same binary machine code in 32-bit mode.)
```
binary_string_to_unary:
B030 mov al, '0' ; input digit to compare against, also the output digit
.loop:
11C9 adc ecx, ecx ; ECX = 2*ECX + CF
AE scasb ; set FLAGS like cmp al, [rdi] then increment RDI. CF=1 for digit='1', CF=0 for digit='0'.
76FB jbe .loop ; while('0' <= digit); i.e. while digit >= '0', false for digit = 0 terminator
89F7 mov edi, esi ; x32 ABI, or for 32-bit mode. For full 64-bit pointers, push rsi / pop rdi
F3AA rep stosb ; memset(rdi, al='0', rcx)
880F mov [rdi], cl ; terminate the C-style string
C3 ret
```
Note that we don't `xor ecx,ecx` before the loop. Instead we rely on the input string being '0'-padded to at least 32 digits, so the previous contents get shifted out.
There might be a way (with same code size) to take the input pointer in RSI like you'd expect from the traditional meanings of those registers, perhaps with `lodsb` / `cmp al, '0'` (3 bytes instead of 1 for scasb, but avoiding the 2-byte `mov edi, esi` after the loop). Change the branch conditions accordingly for comparing in the other direction. Except that would get CF=0 for digit='1'. So maybe `add al, 255-'0'` so '1' produces a carry-out but '0' doesn't? And the terminator is a value that results in some FLAGS condition that the other two don't, perhaps a signed overflow and/or the sign flag.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 53 bytes
Takes a string of `0` and `1` characters, outputs a string of `1`s.
```
>,[>-[<->-----]<+++<[->++<]>>,]>-[<+>-----]<--<[->.<]
```
**Explaination**
```
>,[ read a character
>-[<->-----]<+++ subtract 48 to turn it into 0/1
<[->++<] double the existing sum and add it to the new digit
>>,] read another character and repeat if not EOF
>-[<+>-----]<-- make 49
<[->.<] print 49 the necessary number of times
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v/fTifaTjfaRtdOFwRibbS1tW2ide2AZKydnU4sSE4bJqerC5LSs4n9/9/QwMAQAA "brainfuck – Try It Online")
[Answer]
# Mathematica, 14 bytes
As a list of '1's:
```
Table[1,2^^#] &
```
Anonymous function. Would probably be 10 bytes in the hypothetical mthmca golfing language.
[Answer]
# TI-Basic, 15 bytes
```
1 or rand(.5sum(Ans2^cumSum(1 or Ans
```
Input is taken as a list of `0`s and `1`s in little-endian binary in `Ans`. Output is a list of `1`s.
[Answer]
# [R](https://www.r-project.org), 22 bytes
```
\(x)rep(1,strtoi(x,2))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMG6pMy8xKLKkvxSEGW7tLQkTddiW4xGhWZRaoGGoU5xSVFJfqZGhY6RpiZEcjeKDo0KWyUDA0MwUIKqWLAAQgMA)
Convert from binary and repeat `1` that many times.
Unfortunately shorter than the more-interesting (I think):
# [R](https://www.r-project.org), ~~36~~ 34 bytes
*Edit: -2 bytes thanks to pajonk*
```
\(x)Reduce(\(a,b)c(a,a,b[b]),x,{})
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMG6pMy8xKLKkvxSEGW7tLQkTdfiplKMRoVmUGpKaXKqRoxGok6SZjKQBNLRSbGaOhU61bWaUJXKKPo1KmyTNQx0DHQMEVATqnTBAggNAA)
Input is a vector of binary digits; fold over (`Reduce`) this from the left, starting with an empty vector (`NULL`), at each step duplicating whatever we've got so far, and appending the new digit if it's a `1`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 20 bytes
```
->(b){?**b.to_i(2)}
```
[Try it online!](https://tio.run/##KypNqvyfpmCrEPNf104jSbPaXksrSa8kPz5Tw0izVuF/QWlJsUKaXnJiTo6GkqGBgaGS5v//AA "Ruby – Try It Online")
It goes from binary to a decimal integer, and becomes a factor by which an asterisk char is multiplied.
(Idea to switch to char from string was suggested by [Travis](https://codegolf.stackexchange.com/users/75203/travis). Thanks!)
---
# [Ruby](https://www.ruby-lang.org/), 21 bytes | (old)
```
->(b){"*"*b.to_i(2)}
```
[Try it online!](https://tio.run/##KypNqvyfpmCrEPNf104jSbNaSUtJK0mvJD8@U8NIs1bhf0FpSbFCml5yYk6OhpKhgYGhkub//wA "Ruby – Try It Online")
Same as the upper one, but the upper one has been improved.
[Answer]
# [C (clang)](https://clang.llvm.org), ~~60~~ 58 bytes
```
i;f(char*s){for(i=0;*++s;i+=i+*s-48);i&&printf("%0*d",i);}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700OScxL33BgqWlJWm6FjetMq3TNJIzEou0ijWr0_KLNDJtDay1tLWLrTO1bTO1tYp1TSw0rTPV1AqKMvNK0jSUVA20UpR0MjWtayEm3GJsA0oo5CZm5mloKlRzKQABTG1MXpBrcKhPiIKClZKmNVgKKGpgYAgGMCGEateIAFfnEFcXKy3KQEweyGxinGIIhES5g3gj8RhHgrvwOQrJmKLUktKiPAUDay5odMAiFgA)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 21 bytes
```
x=>'x'.repeat('0b'+x)
```
[Try it online!](https://tio.run/##BcFRCoAgDADQ42wSiX6H3cVsSiFOVGK3X@@98YszjaevvfFNmoNKOEHADuoUF4K7YBOjR@I2uZKtXDAjeOcdGKM/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [J](https://www.jsoftware.com), 4 or 5 bytes
```
#.##
```
Uses the length of the input digit list for the unary digit.
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxRFlPWRnCvGmiyZWanJGvoKOnkKamZ6dgCFRsACStwSwQBrIMFJT1MvPKFAwMDMEAonfBAggNAA)
Like 05AB1E, uniformity is one extra byte, with alternatives.
* Infinity [`#.#_:`](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxVFlPOd4Kwr5posmVmpyRr6Cjp5CmpmenYAhUbQAkrcEsEAayDBSU9TLzyhQMDAzBAKJ3wQIIDQA) or [`_#~#.`](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxNF65TlkPwr5posmVmpyRr6Cjp5CmpmenYAhUbQAkrcEsEAayDBSU9TLzyhQMDAzBAKJ3wQIIDQA)
* Any digit [`#.#1:`](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxVFlP2dAKwr5posmVmpyRr6Cjp5CmpmenYAhUbQAkrcEsEAayDBSU9TLzyhQMDAzBAKJ3wQIIDQA) or [`1#~#.`](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmux1FC5TlkPwr5posmVmpyRr6Cjp5CmpmenYAhUbQAkrcEsEAayDBSU9TLzyhQMDAzBAKJ3wQIIDQA)
* Level (direct port of [Adam's APL](https://codegolf.stackexchange.com/a/264024/110888)) [`#.#L.`](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxVFlP2UcPwr5posmVmpyRr6Cjp5CmpmenYAhUbQAkrcEsEAayDBSU9TLzyhQMDAzBAKJ3wQIIDQA)
[Answer]
# [Perl 5](https://www.perl.org/), 15 bytes
```
$_=9x oct"0b$_"
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3tayQiE/uUTJIEklXun/f0MDA0MuQwNDAy4gAwz@5ReUZObnFf/XLcgBAA "Perl 5 – Try It Online")
Outputs 9 (my chosen char) the number of times given in the input binary number.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 28 bytes
```
"*"*[Convert]::ToInt32($_,2)
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkliUXlyjWv1fSUtJK9o5P68stagk1soqJN8zr8TYSEMlXsdI83/t//@GBgaGCoYGhgYKQAYYABlAAAA "PowerShell – Try It Online")
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 2 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
Ḃṣ
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVFMSVCOCU4MiVFMSVCOSVBMyZmb290ZXI9JmlucHV0PTEwMTAmZmxhZ3M9) or [see it with asterisks instead](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVFMSVCOCU4MiVFMSVCOSVBMyZmb290ZXI9JUMzJUIwJyp2JmlucHV0PTEwMTAmZmxhZ3M9)
Uses spaces.
#### Explanation
```
Ḃṣ # Implicit input
Ḃ # From binary
ṣ # That many spaces
# Implicit output
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 3 bytes
```
⍘S²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMpsTg1uATITNfwzCsoLYGyNXUUjDQ1rf//NzQwNPivW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a string of `-`s. Explanation:
```
S Input string
⍘ Convert from base
² Literal integer `2`
Print as row of `-`s
```
Unfortunately `BaseString(2, InputString())` performs a different operation, which means I can't use implicit input to save a byte.
[Answer]
# [Arturo](https://arturo-lang.io), 23 bytes
```
$=>[@.of:from.binary&1]
```
[Try it!](http://arturo-lang.io/playground?lpQeWe)
Returns a list of digits.
```
$=>[ ; a function where input is assigned to &
from.binary& ; convert input from binary string to decimal integer
@.of: _ 1 ; create list of that many 1s
] ; end function
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 16 bytes
```
1
01
+`10
011
0
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7w35DLwJBLO8HQAEgD2Vz//xsaAEUMDUAiQCEQAAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: A direct interpretation of the method given in the question, except using `1` instead of `*` for obvious reasons. Note that the method in Retina's own tutorial is slightly different preferring to use `^0+` presumably for a slight performance improvement.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 3 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
Some different alternatives are available:
* Output as `*`s: [`å⌂*`](https://tio.run/##y00syUjPz0n7///w0kc9TVr//ysZGhgYKnEBKUMDIAXkgIESAA); [`åÄ⌂`](https://tio.run/##y00syUjPz0n7///w0sMtj3qa/v9XMjQwMFTiAlKGBkAKyAEDJQA); [`å{⌂`](https://tio.run/##y00syUjPz0n7///w0upHPU3//ysZGhgYKnEBKUMDIAXkgIESAA).
* Output as spaces: [`å *`](https://tio.run/##y00syUjPz0n7///wUgWt/@pK8YfW/FcyNDAwVOICUoYGQArIAQMlAA); [`åÄ`](https://tio.run/##y00syUjPz0n7///w0sMtCv/VleIPrfmvZGhgYKjEBaQMDYAUkAMGSgA) ; [`å{`](https://tio.run/##y00syUjPz0n7///w0mqF/7XqSvGH1vxXMjQwMFTiAlKGBkAKyAEDJQA) .
* All six above should have been also possible with a binary-list instead of binary-string as input, replacing the `å` with `ä`, but unfortunately there seems to be a bug with leading `0`s apparently.. - [Try `ä⌂*` online](https://tio.run/##y00syUjPz0n7///wkkc9TVr//0cb6hgAoWEsF5gFxEAWWAQBYwE).
**Explanation:**
```
å # Convert the (implicit) input binary-string to a base-10 integer
⌂* # Repeat that many "*" as string
* # Or alternatively, repeat that many spaces as string
# (after which the entire stack is output implicitly as result)
å # Convert the (implicit) input binary-string to a base-10 integer
Ä # Pop and loop that many times, using the following character as inner code-block:
{ # Or alternatively, use everything after it as code-block:
⌂ # Push an "*" to the stack every iteration
# Or alternatively, push a space character to the stack every iteration
# (after which the entire stack is joined together and output implicitly as result)
```
[Answer]
# [PHP](https://www.php.net/), 32 bytes
```
echo str_repeat('*',bindec($i));
```
Where `$i` is the input string.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Since outputting the unary as a single character is required, there are a couple of 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternatives:
* Output as spaces: `Cð×` - [Try it online](https://tio.run/##yy9OTMpM/f/f@fCGw9P//zc0MDAEAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/58MbDk///6hhmdLh/Uo6/6OVDA0MDJV0gJShAZACcsBAKRYA);
* Output as 1s: `$C×` - [Try it online](https://tio.run/##yy9OTMpM/f9fxfnw9P//DQ0MDAE) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKS/f8YFefD0//rcIFEucozMnNSFYpSE1MUMvO4UvK5FBT08wtK9CGaoRSaeTYKKmC1ean/DQ0MDLkMDQwNuIAMMOACAA);
* Output as 0s: `ÎC×` - [Try it online](https://tio.run/##yy9OTMpM/f//cJ/z4en//xsaGBgCAA) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKS/f/Dfc6Hp//X4QKJcpVnZOakKhSlJqYoZOZxpeRzKSjo5xeU6EM0Qyk082wUVMBq81L/GxoYGHIZGhgacAEZYMAFAA);
* Output as any digit (as a list of characters): `CÅ9` (where the `9` could be any other digit) - [Try it online](https://tio.run/##yy9OTMpM/f/f@XCr5f//hgYGhgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/58Otlv91/kcrGRoYGCrpAClDAyAF5ICBUiwA).
If a mixture of multiple characters for the unary output would have been allowed, since only the length matters in unary, it could have been 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) with:
```
C∍
```
Outputs a mixture of `1`s and `0`s (depending on the input) for its unary output.
[Try it online](https://tio.run/##yy9OTMpM/f/f@VFH7///hgYGhgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf@dHHb3/df5HKxkaGBgq6QApQwMgBeSAgVIsAA).
**Explanation:**
```
C # Convert the (implicit) input binary-string to a base-10 integer
ð× # Pop and push a string with that many spaces
# (after which the result is output implicitly)
$ # Push 1 and the input binary-stringC×
Î # Or alternatively, push 0 and the input binary-string
C # Convert the binary-string to a base-10 integer
× # Repeat the 1 or 0 that many times as string
# (after which the result is output implicitly)
C # Convert the (implicit) input binary-string to a base-10 integer
Å9 # Pop and push a list with that many 9s (or any other digit)
# (after which the result is output implicitly)
```
```
C # Convert the (implicit) input binary-string to a base-10 integer
∍ # Extend/shorten the (implicit) input binary-string to that length
# (after which the result is output implicitly)
```
[Answer]
# [///](https://esolangs.org/wiki////), 18 bytes
```
/1/0*//*0/0**//0//
```
[Try it online!](https://tio.run/##K85JLM5ILf7/X99Q30BLX1/LAEgBaQN9fUMDIPz/HwA "/// – Try It Online")
I didn't write this, I borrowed it from [the esolangs wiki](https://esolangs.org/wiki////). Here's how it works:
Let's start with the string `10101`, which represents 21.
`/1/0*/` replaces `1`s with `0*`. The string becomes `0*00*00*`. In this, each `*` represents a sort of place value - for example, the first `*` has 4 `0`s after it, so it represents 24 = 16.
`/*0/0**/` replaces each `*` before a zero with two copies of it after the zero, each with half the place value. The first replacement this would do would be replacing `0**\*0**0*00*` with `0**0\*\***0*00*`, replacing a `*` representing 16 with 2 `*`s each representing 8.
In `///`, replacements are repeated until nothing is left to replace, so this will eventually result in a string with some amount of 0s at the start, followed by 21 `*`s each representing 1.
Finally, `/0//` removes the leading zeros, leaving just 21 `*`s, which is the output in unary.
[Answer]
# [sed 4.2.2](https://www.gnu.org/software/sed/), 28
```
:
s/1/0u/
s/u0/0uu/
t
s/0//g
```
Implementation algorithm as per the question.
[Try it online!](https://tio.run/##HYnBEcAwCMP@LGPzzTztdYA08xMBD1sW@32qVmylfEQfA9APW/qqMtKRnZTpmbNbtDEKmAP6cQE "sed 4.2.2 – Try It Online")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 17
```
[q]sz2iA?^9/d0=zn
```
[Try it online!](https://tio.run/##S0oszvhfnpGZk6pQlJqYYq2Qks@VmpyRr6AS5BrgE1mTkqygm6oQ8z@6MLa4yijT0T7OUj/FwLYq7z9IFVdKfl7qf0MuQwMuQxAJpAyANJgL5oMEQCIGQCEgAwyADJAEAA "Bash – Try It Online")
### Explanation
```
[ ] # define a macro to...
q # quit (i.e. print the empty string)
sz # save the macro to register z
2i # set input radix to 2 (binary)
A # pop 10
? # read input
^ # exponentiate 10 to the power of the input
9/ # divide by 9. This gives a number consisting of n 1s, or 0
d # duplicate top of stack
0=z # if equal to 0, call macro stored in z register to print the empty string
n # otherwise print the unary number
```
[Answer]
# [Julia 1.0](http://julialang.org/), 24 bytes
```
~x="*"^parse(Int,"0b"*x)
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/v67CVklLKa4gsag4VcMzr0RHySBJSatC879DcUZ@uUKdkqGBgaESF5dDYnFxalEJTEDB1lZBSQsGlFCkDQ3QpFHkgbrBAF0NWQDVYCCAmKr0HwA "Julia 1.0 – Try It Online")
Generally, any base other than 10 needs to be specified: `parse(Int,x,base=2)`. Two bytes are saved by appending a `0b` [integer prefix](https://docs.julialang.org/en/v1/manual/integers-and-floating-point-numbers/#Integers) instead.
] |
[Question]
[
Write a program to calculate the first 500 digits of the mathematical constant e, meeting the rules below:
* It cannot include "e", "math.e" or similar e constants, nor may it call a library function to calculate e.
* It must execute in a reasonable time (under 1 minute) on a modern computer.
* The digits are to include the 2 at the start. You do not need to output the `.` if you choose not to.
The shortest program wins.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 58 bytes
```
x=10**499
print(x+sum((x:=x//i)for i in range(1,253))+128)
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/v8LW0EBLy8TSkqugKDOvRKNCu7g0V0Ojwsq2Ql8/UzMtv0ghUyEzT6EoMS89VcNQx8jUWFNT29DIQvP/fwA "Python 3.8 (pre-release) – Try It Online")
---
Original version, before it was clearly specified that the decimal point could be omitted:
# [Python 3.8](https://docs.python.org/3.8/), 63 bytes
```
x=10**499
print(f'2.{sum((x:=x//i)for i in range(2,253))+128}')
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/v8LW0EBLy8TSkqugKDOvRCNN3Uivurg0V0Ojwsq2Ql8/UzMtv0ghUyEzT6EoMS89VcNIx8jUWFNT29DIolZd8/9/AA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 11 bytes
```
1∆ȯ1∆ṡ+500Ḟ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCIx4oiGyK8x4oiG4bmhKzUwMOG4niIsIiIsIiJd)
Calculates cosh(1)+sinh(1) to 500 decimal places.
```
1∆ȯ # cosh(1)
+ # +
1∆ṡ # sinh(1)
500Ḟ # to 500 decimal places
```
[Answer]
# [Python 3](https://docs.python.org/3/), 54 bytes
```
n=x=z=499
while~-n:x=(x+10**z)//n;n-=1
print(f'2.{x}')
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P8@2wrbK1sTSkqs8IzMntU43z6rCVqNC29BAS6tKU18/zzpP19aQq6AoM69EI03dSK@6olZd8/9/AA "Python 3 – Try It Online")
# [Python 3](https://docs.python.org/3/), 44 bytes
Outputs *e* without the `.`, courtesy of [@xnor](https://codegolf.stackexchange.com/users/20260/xnor).
```
n=x=z=499
while n:x=x//n+10**z;n-=1
print(x)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P8@2wrbK1sTSkqs8IzMnVSHPqsK2Ql8/T9vQQEuryjpP19aQq6AoM69Eo0Lz/38A "Python 3 – Try It Online")
[Answer]
# R, ~~104~~ 90 bytes
Since R doesn't have arbitrary precision arithmetic, and other answers already have used the limit definition and Taylor series of *e*, I use a decimal spigot algorithm to spice things up. I don't usually write loop-based code in R, so there is plenty of room for improvement. (`divmod` would be useful).
-7 bytes thanks to pajonk's better looping, and another -7 because I remembered R's colon operator can go backwards.
```
C=rep(1,254)
d=2
for(i in 1:500){cat(d)
d=0
for(j in 254:2)C[j]=(t=10*C[j]+d)-(d=t%/%j)*j}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWN6OcbYtSCzQMdYxMTTS5UmyNuNLyizQyFTLzFAytTA0MNKuTE0s0UkBSBmCpLJAUULGVkaZzdFasrUaJraGBFoipnaKpq5FiW6Kqr5qlqZVVC7EBahHMQgA)
Based on [*The Calculation of e to Many Significant Digits* by AHJ Sale (1968)](https://academic.oup.com/comjnl/article/11/2/229/378761?login=true). The basic idea is to use an \$m\$th order Taylor polynomial, extract an integer part and fractional part, multiply the fractional part by 10, and repeat on the fractional part. Here's an example extracting the first decimal digit using 4 terms: (the 0 coefficients are coincidence)
\begin{alignat}{4}
\newcommand\pp{\phantom{0}}
e
&\approx 2 + {} && \biggl[ &\frac 1 2 \biggl(\pp1 + {}
&&\frac 1 3 \biggl(\pp1 + {} &\frac 1 4 (\pp1) \biggr) \biggr) \biggr]\\
&= 2 + \frac{1}{10} && \biggl[ &\frac 1 2 \biggl( 10 + {}
&&\frac 1 3 \biggl( 10 + {} &\frac 1 4 (10) \biggr) \biggr) \biggr]\\
&= 2 + \frac{1}{10} && \biggl[ &\frac 1 2 \biggl( 10 + {}
&&\frac 1 3 \biggl( 12 + {} &\frac 1 4 (\pp2) \biggr) \biggr) \biggr]\\
&= 2 + \frac{1}{10} && \biggl[ &\frac 1 2 \biggl( 14 + {}
&&\frac 1 3 \biggl(\pp0 + {} &\frac 1 4 (\pp2) \biggr) \biggr) \biggr]\\
&= 2 + \frac{1}{10} && \biggl[7 + {} &\frac 1 2 \biggl(\pp0 + {}
&&\frac 1 3 \biggl(\pp0 + {} &\frac 1 4 (\pp2) \biggr) \biggr) \biggr]
\end{alignat}
Thanks to Steven B. Segletes for helping with MathJax formatting.
I believe the integers involved never exceed \$10m\$. The fractional part is always less than 1, so the computed digit can't affect the previous digit. \$e\$ is special because the coefficients of the Maclaurin series of \$e^x\$ are all 1. Trig functions for \$\pi\$ would have larger coefficients or produce negative digits, which would require amending previous digits. For example, here's Newton's arctan formula for \$\pi\$:
\begin{align}
\frac \pi 2
&\approx 1 + \frac 1 3 \biggl( 1 + \frac 2 5 \biggl( 1 + \frac 3 7 (1) \biggr) \biggr) \\
&= 1 + \frac 1 3 \biggl( 1! + \frac 1 5 \biggl( 2! + \frac 1 7 (3!) \biggr) \biggr)
\end{align}
There is no clean way to transform \$\frac 3 7 (10)\$ into an integer part while the fractional part is a multiple of \$\frac 3 7\$ and less than 1. The solution is modifying the spigot to maintain held *predigits* that are released once we are sure the digits are correct. See [*A Spigot Algorithm for the Digits of π* by Rabinowitz and Wagon (1995)](https://maa.org/sites/default/files/pdf/pubs/amm_supplements/Monthly_Reference_12.pdf).
\$m\$ can be calculated beforehand from the error of the finite sum using Stirling's approximation. For \$n+1\$ correct digits, find least \$m\$ satisfying \$m! > 10^{n+1}\$, equivalently
$$\frac 1 2 \ln(2\pi m) + m(\ln m - 1) > (n+1) \ln 10$$
Ungolfed algorithm:
```
n = 500
m = 254
C = rep(1,m)
cat(2)
for(i in 2:n){
d = 0
for(j in m:2){
t = 10*C[j] + d
d = t %/% j
C[j] = t - d*j
}
cat(d)
}
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes
```
Sum[1/k!,{k,0,∞}]~N~500
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P7g0N9pQP1tRpzpbx0DnUce82tg6vzpTA4P/AUWZeSUKDun//wMA "Wolfram Language (Mathematica) – Try It Online")
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 29 bytes
```
Limit[(1+1/n)^n,n->∞]~N~500
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773yczN7MkWsNQ21A/TzMuTydP1@5Rx7zYOr86UwOD/wFFmXklCg7p//8DAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 51 bytes (-2 thanks @xnor)
```
m=p=~2**3333
exec"m=m*m/~p;"*3333
print-m*10**499/p
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWN41zbQts64y0tIyBgCu1IjVZKdc2VytXv67AWgkiWFCUmVeim6tlaKClZWJpqV8A0Qo1AWYSAA)
### former [Python 2](https://docs.python.org/2/), 53 bytes
```
p=4000
m=2**p+1
exec"m=m*m>>p;"*p
print`m*5**p`[:500]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWN00LbE0MDAy4cm2NtLQKtA25UitSk5VybXO1cu3sCqyVtAq4Cooy80oScrVMgQoSoq1MDQxiIZqhZsDMAgA)
Outputs the digits as a single string, no decimal point.
## How?
Approximately computes \$(1+1/n)^n\$ for \$n=2^{4000}\$ using repeated squaring.
[Answer]
# [Python](https://www.python.org), 100 bytes
```
from decimal import*
getcontext().prec=500
e=d=Decimal(1)
for x in range(2,254):e+=1/d;d*=x
print(e)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Nc1LCsIwEADQfU6RZVJ_bbFQlOy8SMlMasBkwjBCPIubbvRO3sZFdf_gPd_lIVfKy_K6S9iNHwhMSQP6mKabjqkQS6NmFE9ZsIqx-8Lo3dC2Ch24yypNZ1Ug1lXHrHnKM5p-2w9He8KN6w5whsZVVThmMWjX61f-6y8)
-2 bytes thanks to [RubenVerg](https://codegolf.stackexchange.com/users/118045/rubenverg)
254 is the lowest number which gives the correct result, but this doesn't get slow until you start looping for thousands of iterations.
This uses the definition:
\$ \displaystyle e = \sum\_{n=1} ^{\infty} \frac{1}{n!} = \frac{1}{1} + \frac{1}{1 \cdot 2} + \frac{1}{1 \cdot 2 \cdot 3} + \cdots \$
The only optimization used is to instead of calculating the factorial of each n from 1 to 254, we store the factorial of \$ n-1 \$ in the variable `d`, and each iteration multiply d by the loop number `x`.
This uses the Python's decimal library with `getcontext()` in order to calculate the number to 500 digits of precision.
[Answer]
# C, ~~126~~ ~~116~~ 109 bytes
Port of [my R answer](https://codegolf.stackexchange.com/a/269079/17360).
-10 bytes by rearranging loop logic printing leading 2, inspired by pajonk, and some small optimizations.
-7 bytes by using `C` with zeros instead of ones, credit
chux - Reinstate Monica. Previously, the initialization of array `C` to 1s is a GNU extension.
```
i=500,d=2,j,t,C[255];main(){while(i--){putchar(d+48);d=0;j=254;while(j-->2)t=10*C[j]+d+10,d=t/j,C[j]=t%j-1;}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBgqWlJWm6FjdzM21NDQx0UmyNdLJ0SnSco41MTWOtcxMz8zQ0q8szMnNSNTJ1dTWrC0pLkjMSizRStE0sNK1TbA2ss2yNTE2sIUqydHXtjDRLbA0NtJyjs2K1U7QNQWaW6GfpgPi2JapZuobWtbUQS6F2w9wAAA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
≔⁰θF⊖φ≔÷⁺Xχ⁴⁹⁹θ⁻φιθ2.Iθ
```
[Try it online!](https://tio.run/##PYxBCsIwEEX3nmLoagaiRHFTuhK7cVHIFUI66kBMaBLb48cWxeXnv/fc0yYXra/1krM8AmoFE3W7e0yAPbvELw6FRzxqrYngR91C6WWWkdH4d0YTF04rouDctrQVFAwS1mfTFAjRN2uShILN6dD8x9XmghNRV2vdz/4D "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁰θ
```
Start with a running total of `0`.
```
F⊖φ≔÷⁺Xχ⁴⁹⁹θ⁻φιθ
```
For each integer from `1000` down to `2`, add `10**499` to the running total, then divide by that integer. This is equivalent to summing the reciprocals of the factorials from `2` to `1000` but without any loss of precision.
```
2.Iθ
```
Output `e` to `500` digits.
20 bytes to output without the decimal point:
```
≔⁰θFφ≔⁺Xχ⁴⁹⁹÷θ⁻φιθIθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DQEehUNOaKy2/SEHD0MDAQFMBKhGQU1qsEZBfnloEFNdRMLG01NRR8Mwrccksy0xJ1SjUUfDNzAMqAWnSUcjU1NSEmBRQlJlXouGcWFyiUaipaf3//3/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: As above but counts down to `1` and also adds the `10**499` after dividing so that the result includes the `0!` and `1!` terms.
[Answer]
# APL (NARS2000), 20 chars = 40 bytes
```
499⍕+/5 6x○≢⎕FPC←1E4
```
`⎕FPC←1E4` set Floating Point Control to use ten thousand bit floats
`≢` count that (gives 1)
`5 6x○` compute sinh and cosh of that (while indicating with `x` that we want extended precision)
`+/` sum
`499⍕` output with 499 decimals, i.e. 500 digits in total
[Answer]
# JavaScript (ES11), 45 bytes
*-5 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)*
A port of [Neil's method](https://codegolf.stackexchange.com/a/269035/58563), as suggested by Neil himself.
```
f=(q=i=999n)=>i?f((q+10n**499n)/-~i--):"2."+q
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVaj0DbT1tLSMk/T1i7TPk1Do1Db0CBPS8sEJKSvW5epq6tppWSkp6Rd@D85P684PydVLyc/XSNNQ1PzPwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 29 bytes
```
2 4000:a?:b){.*b/}a*5a?*+500<
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/30jBxMDAwCrR3ipJs1pPK0m/NlHLNNFeS9vUwMDm/38A "GolfScript – Try It Online")
Ports [Albert.Lang's wonderful Python 2 solution](https://codegolf.stackexchange.com/a/269058/108687) to GolfScript. Check that answer for a better understanding of the math.
Code explanation:
```
2 4000:a?:b)
2 4000 # Push 2, 4000 to the stack.
:a # Store 4000 in variable a.
? # Power; 2 ^ 4000
:b # Store 2 ^ 4000 in variable b.
) # Add one.
{.*b/}a*5a?*
{ # Open a block:
.* # * Duplicate and multiply (squaring
# the top of the stack.)
b/ # * Integer divide by b.
}a* # Run this block a times.
5a? # Push 5 ^ a.
* # Multiply.
+500<
+ # Append this result to the implicit input,
# which is the empty string, therefore
# coercing the number to a string.
500< # Leave just the first 500 characters of
# this string.
```
## [GolfScript](http://www.golfscript.com/golfscript/), 30 bytes
```
"2."128 10 499?{2+/.@+\}251,/;
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/X8lIT8nQyELB0EDBxNLSvtpIW1/PQTum1sjUUEff@v9/AA "GolfScript – Try It Online")
Based on m90's Python solution, since GolfScript has big integers but no floats.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ȷ⁵*;R:\SDḣH
```
[Try it online!](https://tio.run/##y0rNyan8///E9keNW7Wsg6xigl0e7ljs8f8/AA "Jelly – Try It Online")
A Jelly version of [m90’s Python answer](https://codegolf.stackexchange.com/a/269032/42248). This is a niladic link which returns the first 500 digits of e as a list of decimal digits.
## Explanation
```
ȷ | 1000
⁵* | 10 ** this
;R | Concatenate to 1..1000
:\ | Reduce using integer division, collecting intermediate results
S | Sum
D | Decimal digits
ḣH | First 500 (since half of 1000 is 500)
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 110 bytes
```
252*
L$`_
$>`,_
^
2.¶
749{`$
;
(_*);(_*)
10*$1$2;
¶(_+),(\1)*(_*);
;$#2*_¶$1,$3
)`^(.*)(¶.*);(_*)
$1$.3$2
1G`
```
[Try it online!](https://tio.run/##NYuxDUIxDAX7twYubBNF2GmQIv2WhhHQdygoaCgQHXtlgCwWPkg019zd8/a6P642J@xwVJypBWhpKbDC8@hwK@9GqOBQqV9spZKRV4zOsZfEFxP9aVTaucboZIkKpK2cVXj0/H@3MRdy2KnN@QE "Retina – Try It Online") Too slow to produce 500 digits on TIO so link just produces 108. Explanation: Port of @qwr's R answer.
```
252*
L$`_
$>`,_
```
Generate the working array. (Note: This is an estimate of its size, but increasing it just requires additionally increasing the iteration count of the loop below to compensate.)
```
^
2.¶
```
Start with `2.`.
```
749{`
)`
```
Loop 749 times, which produces 499 digits for some reason.
```
$
;
```
Start another parallel iteration.
```
(_*);(_*)
10*$1$2;
```
Multiply each value by 10 and add the carry from the next element's previous iteration.
```
¶(_+),(\1)*(_*);
;$#2*_¶$1,$3
```
Divmod each value by its index and propagate the carry to the previous element for its next iteration.
```
^(.*)(¶.*);(_*)
$1$.3$2
```
Generate the next digit from the first element.
```
1G`
```
Remove all of the elements leaving just the final decimal expansion.
[Answer]
# [WolframAlpha](https://www.wolframalpha.com/), 26 bytes
```
N[Sum[1/k!,{k,0,∞}],500]
```
[Try it on WolframAlpha](https://www.wolframalpha.com/input?i=N%5BSum%5B1%2Fk%21%2C%7Bk%2C0%2C%E2%88%9E%7D%5D%2C500%5D)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 17 bytes
```
Cosh@1+Sinh@1`500
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zm/OMPBUDs4Mw9IJZgaGPwPKMrMK1FwSP//HwA "Wolfram Language (Mathematica) – Try It Online") A direct port of [emanresu A's nice answer](https://codegolf.stackexchange.com/a/269030/56178).
[Answer]
# APL(NARS), 76 chars
```
Q;r;d;k;v;⎕FPC
r←d←1⋄k←÷10x*501⋄v←0x
r+←d×←÷v+←1⋄→2×⍳k<∣d
⎕FPC←4×501⋄⎕←499⍕r
```
14+21+20+18+3=76
Calculus in rationals, and print with 499 digits after the point (499+1=500) the last digit rounded
(but not changed because the 500th digit after the point should be 2<6)
```
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663919320
0305992181741359662904357290033429526059563073813232862794349076323382988075319525101901157383418793070215408
9149934884167509244761460668082264800168477411853742345442437107539077744992069551702761838606261331384583000
7520449338265602976067371132007093287091274437470472306969772093101416928368190255151086574637721112523897844
250569536967707854499699679468644549059879316368892300987931
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₅L₄°šÅ»÷}O₄;£
```
Port of [*@NickKennedy*'s Jelly answer](https://codegolf.stackexchange.com/a/269056/52210), which in turn is based on [*@m90*'s Python answer](https://codegolf.stackexchange.com/a/269032/52210), so make sure to upvote those answers as well.
Outputs the first 500 digits as a single concatted integer.
[Try it online.](https://tio.run/##yy9OTMpM/f//UVOrz6OmlkMbji483Hpo9@Httf5ArvWhxf//AwA)
**Explanation:**"
```
₅L # Push a list in the range [1,255]
₄°š # Prepend 10**1000
Å» } # Cumulative left-reduce, keeping intermediate results
÷ # by doing integer-division
O # Sum all those results together
₄; # Push 500 (1000 halved)
£ # Keep only the first 500 digits
# (after which this integer is output implicitly as result)
```
[Answer]
# [Scala 3](https://www.scala-lang.org/), 89 bytes
A port of [@m90's Python answer](https://codegolf.stackexchange.com/a/269032/110802) in Scala.
---
Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=m72sODkxJ9F4R7SSbk5iXnppYnqqVUF-cUlaZoV_QbFS7M78pKzU5BIF38TMPIXUipLUvJRiBceCAoXqpaUlaboWNyPLEosUKmydMtM980o0DA00FQryyxVMLC25Cooy80py8jSKlYz0VKo1oCoMNPWtNIwUSvIVjEyNNDU1NIp1MjUVbO2Ktasr9G0zrStqNbUNjSxqlTQhFiyshdALFkBoAA)
```
var x=BigInt(10) pow 499
println(s"2.${(BigInt(0)/:(2 to 252))((s,i) =>s+{x/=i;x})+128}")
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=NU-9DgFBGOw9xUQUuxGHRYJQ0ClUohLFur-srD3Z3fMTuSfRaHgnvQex51b3zXzzfTNzf5mQS957PJ65TVrD9yfb7ePQYsmFwq0GRHGCgwOE69SMMdOaXzcrq4VKt3SMtRIW058SOHGNi0NzkS6UJd0ODY7ZmfRHI-r3Ejo2uSxPSJJpEIFJCww2AxswiquIZeS_VfpInJz4gjaEZ0sHx3r0nwoamPyAJrps-COOLqKVipg6CxqVa72MUdSKqquv_K_-BQ)
```
object Main {
def main(args: Array[String]): Unit = {
var x = BigInt(10).pow(499)
val result = (for (i <- 2 to 252) yield {
val div = x / i
x = div
div
}).sum + 128
println(s"2.$result")
}
}
```
[Answer]
# SageMath, ~~20~~ 18 Byte
Sehr unkreativ:
```
n(i^(2/i/pi),1664)
```
Alte Antwort:
```
n((-1)^(-i/pi),1664)
```
[Onlinetest](https://sagecell.sagemath.org/?z=eJzL09DQNdSM09DN1C_I1NQxNDMz0QQAMugEuQ==&lang=sage&interacts=eJyLjgUAARUAuQ==)
`i^(2/i/pi)` =e :
`e^(πi) = -1` => `e^(πi/2) = i` => `e = i^(2/πi)`
`n(....)` : Kontentiere zu Dezimal
`1664` : Mit einer Genauigkeit von 1664 bit
] |
[Question]
[
# Robbers' Challenge
Read the [cops' challenge](https://codegolf.stackexchange.com/q/245701/110951) first.
In this [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge, you (the robbers) must find the correct string of characters, which, when added into the cop's code, will make it produce the correct (case-sensitive) output (except that there may also be an extra trailing newline at the end).
The number of characters you add in must be less than or equal to the number of characters removed from the original code, and your answer is still valid even if it was not intended.
The characters can be added anywhere in the code, but they must all be consecutive in the same place (i.e. not random characters dotted around the code).
Make sure to link the cop's post that you have cracked in your answer, and once you have posted your answer here, comment under the cop's post linking your answer if you have enough reputation.
## Example
Say a cop posted the following submission:
>
> # Python, score of 14
>
>
> Code: `print(5*"a")`
>
> Number of characters removed: 1
>
> Target output: `5 a` (currently outputs `aaaaa`)
>
>
>
This is the answer a robber would post to crack it:
>
> # Cracks ...'s Python answer (link)
>
>
> Character to add: `,` before the `*`
>
> Resulting code: `print(5,*"a")`
>
> Resulting output: `5 a`
>
>
>
## Scoring
The following scoring criterion will be used in order (if #1 is a tie, then #2 is used to tiebreak, etc.):
1. The robber who has cracked the most cops' answers (that were uncracked at the time of posting) after 1 week wins!
2. Out of the tied robbers, the one whose most-upvoted answer has the most upvotes wins
3. Out of the tied robbers, the one whose most-upvoted answer was posted first wins
Good luck!
[Answer]
# Python 3, cracks [Sisyphus' answer](https://codegolf.stackexchange.com/a/245729/20260)
```
print(d‚Ö≥mod(99,15))
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/v6AoM69EI@VR6@bc/BQNS0sdQ1NNzf//AQ "Python 3.8 (pre-release) – Try It Online")
Inserts `d‚Ö≥mod` where the `‚Ö≥` is U+2173 (Small Roman Numeral Four), a one-character multibyte ligature that normalizes to `iv`, letting us squeeze the built-in into 5 characters. I learned of this ligature trick for Python 3 in doing [this crack](https://codegolf.stackexchange.com/a/231637/20260).
[Answer]
# [JavaScript (Node.js)](https://%5BJavaScript%20(Node.js)%5D:%20https://nodejs.org), cracks [l4m2's answer](https://codegolf.stackexchange.com/a/245715/58563)
```
console.log((99n**77n).toString(34))
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/OT@vOD8nVS8nP11Dw9IyT0vL3DxPU68kP7ikKDMvXcPYRFPz/38A "JavaScript (Node.js) – Try It Online")
### Cracking script
```
let s = "39iw027a2hnuqi2c1os255jmjsidafs3nx6496n8vl8dak0qc3r15xwheq4vxpb136up7rsmbm8v5slowjwf7mvj0s751b03gxif5";
// there's no 'y' and no 'z', so this could be an integer in base 36, 35 or 34
[36, 35, 34].forEach(base => {
let n = [...s].reduce((p, c) => p * BigInt(base) + BigInt(parseInt(c, base)), 0n);
console.log(`Base ${base} -> ${n}`);
// look for divisors of reasonable size
for(let d = 2n; d < 1000n; d++) {
let k = 0, N = n;
while(!(N % d)) { N /= d; k++; }
k && console.log(`${d}**${k}\t${N == 1n ? "success!" : "failed"}`);
}
console.log();
});
```
[Try it online!](https://tio.run/##VY/fbqJAFMbvfYqvxK2gFEFE7bJ2kyZ70Zu@QLdJB2bQEZxBDqJbw7O7A6bJ7sXk/PvNOd@3Yw2jtJJl/aA0F9drIWoQ1rDCR3nyZ0s226rjQc7SQNMsinb7HUnOMgrVeTF/XKhVU6w4y/1DGlZBdD5txWHenMskCBfHclnRPtmvmogKfdqdsuW@2fm0jILEDzdnmUVWPBhMp6i3ohIjgtIY/RmBKd6nnyMXpM1UElJ9LDgSYYaQqhYbUZmIhJFAuHARRtAVwvng7VaZN3/3Ml39YunW7rH1Ey4DoHOojMM3z/Po3asEP6bCtksXqdMxJcZ4lpsXVfffHEy@ypJVJLokdfvDjuPCV47xAKNPkS6EV@iN/fHcnRteOqbFw5NJVftx44zbQuscRhm4bCTpiqAzVIKRViwpBEh@CkMawu60cqN1pmITfyDwfb9LJxOn93JzkxvCd/Fqgor77mkrC2Hf2a/4Bu4Y1gyna/AY@WQSo@2hHPf3/@seXng7Hg8vefu7Hl7MvjUChZ@w6JimgujOwndYGTPLudU7Qr/r3yWm2Trx9foX "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), cracks [pajonk's answer](https://codegolf.stackexchange.com/a/245717/95126)
```
el(names(swiss),6)
```
[Try it online!](https://tio.run/##K/r/PzVHIy8xN7VYo7g8s7hYU8dM8/9/AA "R – Try It Online")
Characters to add = `names(swiss),`
[Answer]
# Java, cracks [*David Conrad*'s answer](https://codegolf.stackexchange.com/a/245724/52210)
`Character.` is added before the `getName(x)` within the `toString()` method.
[Try it online.](https://tio.run/##bVFNSwMxEL3vrxgEIaFtcKnVQtFLL3pRod5KD@k2brNmkyWZrSvS375Ot@kXOoHJkLx5815SyI0cuErZYvXZtrqsnEcIKFFnUNCdqFEbEdArWYqpM0Zl6HwQhdNW23ySxJY/2GeLs66aJElmZAjw5l3uZQk/CVBU9dLQjDhq4/QKSqktoybinS9A@jzwCN7F7DugKoWrUVQEQWOZVV8HVsb5pINuk27b00Cu8EWWihEemnM2r7D2FhrowRWtHpBelSsv0D2pZt/NmkvOKDlSo4uof2iP5oX7YOnwpg/pbR/Gd@mQ8v2Y6nS0OxylXJSyenevy4I1MHg8ozq5oMcI8ADTtfQyQ9J4cNVwESqjkZGFKPUQO8OWmoj1GtIhpzy6RESpYW7pLgijbI7rxQmz5SLb/zeLn92NOT7Jtm1/AQ)
This took longer than expected..
**Explanation:**
The [`Character#getName(int)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Character.html#getName(int)) method returns the Unicode name for the given character codepoint.
The characters names of the given codepoints `130, 14, 8613, 8784, 150, 151` are in order:
```
BREAK PERMITTED HERE
SHIFT OUT
UPWARDS ARROW FROM BAR
APPROACHES THE LIMIT
START OF GUARDED AREA
END OF GUARDED AREA
```
Which then gets split by spaces and the correct word is extracted based on the modulo operators used.
[Answer]
# [R](https://www.r-project.org/), cracks [Robin Ryder's answer](https://codegolf.stackexchange.com/a/245750/95126)
```
print("R",,F)
```
[Try it online!](https://tio.run/##K/r/v6AoM69EQylISUfHTfO/skJJRmaxAhAVZ@QXlWQk5qUopOUXWXEpKyAUFpbml6Taujn6BLtq/gcA "R – Try It Online")
The original answer indicated that 8 characters had been removed; this crack uses only 3 characters:
`,,F`, so presumably it isn't the intended solution...
[Answer]
# Cracks [emanresu A's](https://codegolf.stackexchange.com/users/100664/emanresu-a) [Vyxal "kay"](https://github.com/Vyxal/Vyxal) submission
```
ka√∏By
```
**[Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrYcO4QnkiLCIiLCIiXQ==)**
All we need to do is wrap the alphabetic characters we get from `ka` in square brackets before we uninterleave with `y`, and that's a two-byte built-in, `√∏B`.
---
The "bonus" output is achieved with a reversal (`«ì`) instead: `ka«ìy` [Try it](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrYceTeSIsIiIsIiJd).
[Answer]
# [PHP](https://php.net/), cracks [Michel's answer](https://codegolf.stackexchange.com/a/245773/88546)
```
<?php for($i=7;$i-->2;)print$i<<print$i;
```
[Try it online!](https://tio.run/##K8go@P/fxr4go0AhLb9IQyXT1txaJVNX187IWrOgKDOvRCXTxgbKsP7/HwA "PHP – Try It Online")
The main observation is that the expected output (`612510483624`) can be split in such a way that an obvious pattern emerges: `6 12 5 10 4 8 3 6 2 4`. It follows a consistent pattern of `$i*2 $i ...`.
The tricky bit is figuring out how to print it, but it turns out to be as simple as inserting a `print` before the second `$i`. The rightmost `print` is evaluated first, printing `$i`, and then `$i<<1` is printed, since the other `print` returns a `1`.
[Answer]
# [Python](https://www.python.org), cracks [pxeger's answer](https://codegolf.stackexchange.com/a/245921/88546)
```
"print("")"
print(__doc__)
""
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhZ7lQqKMvNKNJSUNJW4IMz4-JT85Ph4TS4lJYgaqFKYFgA)
TIL you can store a string inside `__doc__` by adding it on the first line.
[Answer]
# Python 3, Cracks [des54321's answer](https://codegolf.stackexchange.com/a/245761/46076)
```
print(str(quit)[14:18])
```
OR
```
print(str(exit)[14:18])
```
I brute-forced this by running:
```
import gc
for x in gc.get_objects():
if str(x)[14:18] == "Ctrl":
print(x)
```
[Answer]
# Python 3, cracks [thegreatemu's answer](https://codegolf.stackexchange.com/a/245769/20260)
```
import random as r
r.seed(258117)
print(r.random())
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEoMS8lP1chsVihiKtIrzg1NUXDyNTC0NBck6ugKDOvRKNID6JEQ1Pz/38A "Python 3 – Try It Online")
I just brute-forced six-digit seeds, which took 8 seconds to run on TIO.
[Answer]
# [MATL](https://github.com/lmendo/MATL), cracks [Luis Mendo's answer](https://codegolf.stackexchange.com/a/245747/32352)
```
'Hey My'YbtvZc
```
[Try it online!](https://tio.run/##y00syfn/X90jtVLBt1I9MqmkLCr5/38A "MATL – Try It Online")
Adds the string `YbtvZc` to the end.
[Answer]
# Cracks des54321's [Python answer](https://codegolf.stackexchange.com/a/245707/111322)
Adding `^63` after `chr(i` results in:
```
print("".join(chr(i^63)for i in b'wZSSP\x1fhPMS[\x1e'))
```
...which outputs `Hello World!`
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ0lJLys/M08jOaNIIzPOzFgzLb9IIVMhM08hSb08Kjg4IKbCMC0jwDc4GshIVdfU/P8fAA "Python 3 – Try It Online")
[Answer]
### Crack for [bigyihsuan's](https://codegolf.stackexchange.com/users/77309/bigyihsuan) [Lexurgy SC answer](https://codegolf.stackexchange.com/a/245706/53748)
```
a:
*=>w
b:
w=>zwq
```
Obviously not the intended solution, but seems to work fine.
[Answer]
# Python 3, cracks [EphraimRuttenberg's answer](https://codegolf.stackexchange.com/a/245725/111305):
```
print(str(...)[1:3]*50)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69Eo7ikSENPT08z2tDKOFbL1EDz/38A)
Added code: `...` inside the `str()`.
[Answer]
# [R](https://www.r-project.org/), cracks [Robin Ryder's second answer](https://codegolf.stackexchange.com/a/245822/95126)
```
`?`=noquote#print
?"R"
```
[Try it online!](https://tio.run/##K/r/P8E@wTYvv7A0vyRVuaAoM6@Ey14pSOn/fwA "R – Try It Online")
The 8 characters to add are `noquote#`.
This exchanges the asssignment of `?` to the `print` function into an assignment to the `noquote` function, and comments-out the now-useless `print`.
[Answer]
# [R](https://www.r-project.org/), cracks [Robin Ryder's third answer](https://codegolf.stackexchange.com/a/245833/95126)
```
{assign("?",print.noquote)}
?"R"
```
[Try it online!](https://tio.run/##K/r/vzqxuDgzPU9DyV5Jp6AoM69ELy@/sDS/JFWzlsteKUjp/38A "R – Try It Online")
The 8 characters to add are `.noquote`, changing the `print` function into the rather-obscure `print.noquote` function.
This series of challenges was an uphill battle for poor [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder); I think neither of us was fully aware of the variety of `noquote`-like options and functions that lurk in base-[R](https://www.r-project.org/), and Robin patiently added more-and-more convoluted re-assignments and curly-braces to counteract each new `noquote` variant as it popped up in unintended cracks...
[Answer]
# [Behavior](https://github.com/FabricioLince/BehaviourEsolang), cracks [Lince Assassino's answer](https://codegolf.stackexchange.com/a/245866)
```
@(type:type)-0-3
```
[Try it online!](https://replit.com/@fabriciorodrigues/bhv) (you will have to input the program yourself)
Adds `-3` to the end. Removing the `-0` originally gives a result of `cfunc`, so I assumed `-0` meant "remove the character at index `0`." Using the same logic, we add `-3` to remove the character at index `3` in `func` to get `fun`.
[Answer]
# [Python](https://www.python.org), 124 bytes, cracks [jezza\_99's answer](https://codegolf.stackexchange.com/a/245728/46076)
```
import sys
S=sys.stdout
sys.stdout=type('',(),{'write':lambda x,y:'','flush':lambda z:1})()
import this
S.write(this.s[:98])
```
All of the re-added characters are at the end of the program.
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3azJzC_KLShSKK4u5gm2BpF5xSUp-aQkXgmlbUlmQqqGurqOhqVOtXl6UWZKqbpWTmJuUkqhQoVNpBZRRT8spLc6Ai1ZZGdZqamhyQc0uycgEGq4H1qkB4ugVR1tZWsRqQtwAdQrMSQA)
[Answer]
# [PHP](https://php.net/), cracks [Michel's answer](https://codegolf.stackexchange.com/a/245882/88546)
```
<?php echo hexdec(M_E),'';
```
[Try it online!](https://tio.run/##K8go@P/fxr4go0AhNTkjXyEjtSIlNVnDN95VU0dd3fr/fwA "PHP – Try It Online")
My first thought was, "maybe the number is large enough that printing it as a hex literal is shorter somehow...". When converting it to hex, I immediately notice that the hex digits are the first few digits of \$ e \$ (`0x2718281828459`). The rest is trivial.
] |
[Question]
[
Behold! The Crystal Maze‚Ñ¢ Time Matrix!
```
0 1 2 3 4 5 6 7 8 9 10
1 0 5 10 15 20 25 30 35 40 45 50
2 0 10 20 30 40 50 60 70 80 90 100
3 0 15 30 45 60 75 90 105 120 135 150
4 0 20 40 60 80 100 120 140 160 180 200
5 0 25 50 75 100 125 150 175 200 225 250
```
Obviously, this is self explanatory to anyone who knows The Crystal Maze™️, but here's a quick run-down for anyone else:
* In The Crystal Maze‚Ñ¢, team members attempt a series of games where they can win Crystals.
* Crystals represent time in the final game, 5 seconds for every crystal.
* They can also fail these games in a way which gets a team member locked in, so they are not able to participate in the final game.
* Before the final game, they have the option to buy the team members back with crystals, giving them less time but more people.
The Matrix shows you the number of crystals along the top, and the number of team members on the left. The body of the matrix is filled with "people seconds". Its purpose is to decide if selling a crystal will increase your "people seconds" or not.
# The game
* Generate the precise textual output of The Crystal Maze‚Ñ¢ Matrix.
+ The crystals, along the top, will range from 0 to 10.
+ Team members will range from 1 to 5.
+ All columns will be exactly 3 characters wide and right-justified.
+ Columns are separated with a space.
+ A single value will show (crystals √ó team members √ó 5).
* Use any language capable of producing this textual output.
* It's code golf, so attempt to do so in the fewest bytes.
* Please include a link to an online interpreter such as TIO.
[Answer]
# [R](https://www.r-project.org/), 60 bytes
```
write(format(rbind(c("",1:5),0:10%o%c(1,1:5*5)),j="r"),1,12)
```
[Try it online!](https://tio.run/##K/r/v7wosyRVIy2/KDexRKMoKTMvRSNZQ0lJx9DKVFPHwMrQQDVfNVnDEMTXMtXU1MmyVSpS0tQBChhp/v8PAA "R – Try It Online")
[Answer]
# Excel (ms365), ~~145~~, 122 bytes
* -23 bytes thanks to @[JosWoolley](https://codegolf.stackexchange.com/users/116680/jos-woolley)
[](https://i.stack.imgur.com/bHzSj.png)
Formula in `A1`:
```
=LET(x,ROW(1:6)-1,y,COLUMN(A:K)-1,TEXTJOIN(HSTACK(IF(y+1," "),CHAR(10)),,RIGHT(" "&HSTACK(IF(x,x," "),IF(x,y*5*x,y)),3)))
```
This can be 117 bytes if we would swap `CHAR(10)` out for a literal `Alt`+`Enter`:
```
=LET(x,ROW(1:6)-1,y,COLUMN(A:K)-1,TEXTJOIN(HSTACK(IF(y+1," "),"
"),,RIGHT(" "&HSTACK(IF(x,x," "),IF(x,y*5*x,y)),3)))
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~26~~ 25 bytes
```
E⁶⪫E¹²◧⎇λI×⊖λ∨×⁵ι¹⎇ιIιω³
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDDTEfBKz8zD8w2NNJRCEhM8UlNK9EISS3KSyyq1MjRUXBOLAbyM3NTizVcUpOLUnNT80pSU0Ay/kVQcVMdhUxNHQVDTU0gCdOaCdUKkikHSRiDCCUFJaAq6////@uW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⁶ Literal integer `6`
E Map over implicit range
¹² Literal integer `12`
E Map over implicit range
⎇λ If not the first column
λ Current column
‚äñ Decremented
√ó Multiplied by
ι Current row
√ó Multiplied by
⁵ Literal integer `5`
‚à® Logical Or
¬π Literal integer `1`
I Cast to string
⎇ι If not the first row
Iι Current row as a string
ω Else empty string
◧ ³ Left-pad to length 3
‚™´ Join with spaces
Implicitly print
```
~~23~~ 22 bytes using the newer version of Charcoal on ATO:
```
E⁶⪫E¹²◧⎇λ×⊖λ∨×⁵ι¹∨ιω³
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjfzAooy80o0fBMLNMx0FLzyM_PAbEMjHYWAxBSf1LQSjZDUorzEokqNHB2FkMzc1GINl9TkotTc1LyS1BSQoH-RBkTcVEchU1NHwVBTEyyYqaNQDmIagwglBSVNTU3rJcVJycVQu5dHK-mW5SjFQrkA "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation: `PadLeft` stringifies its argument, allowing the removal of two instances of `Cast` and the subsequent simplification of `Ternary` to `Or`.
[Answer]
# Pure [Bash](https://www.gnu.org/software/bash/) - no external utilities, 66
Thanks to @Nahuel Fouilleul for saving 10 bytes!
```
printf "`echo %3s{,,}{,,,}`\n" '' {0..10} $[{1..5}*{1,{0..50..5}}]
```
[Try it online!](https://tio.run/##S0oszvj/v6AoM68kTUEpITU5I19B1bi4WkenFoh1ahNi8pQU1NUVqg309AwNahVUoqsN9fRMa7WqDXVAYqYgXFsb@/8/AA "Bash – Try It Online")
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `N`, 21 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
5ıTĖ×5×nƤð4ṙ;TĖðƤð4ṙƤ
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPTUlQzQlQjFUJUM0JTk2JUMzJTk3NSVDMyU5N24lQzYlQTQlQzMlQjA0JUUxJUI5JTk5JTNCVCVDNCU5NiVDMyVCMCVDNiVBNCVDMyVCMDQlRTElQjklOTklQzYlQTQmZm9vdGVyPSZpbnB1dD0mZmxhZ3M9Tg==)
#### Explanation
```
5ı # Map over [1..5]:
TĖ× # Multiply by [0..10]
5√ó # And multiply by 5
n∆§ # Prepend the current number
√∞4·πô # Right-justify to length 4
; # End map
TĖ # Push [0..10]
√∞∆§ # Prepend a space
√∞4·πô # Right-justify to length 4
∆§ # Prepend this list
# Implicit output, joined on newlines
```
[Answer]
# [Perl 5](https://www.perl.org/), 76 bytes
```
printf$"x3 .($b="%4d"x11),0..10;//,printf"
$_$b",map$_*=5*$',0..10for 1..5
```
[Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvJE1FqcJYQU9DJclWSdUkRanC0FBTx0BPz9DAWl9fB6JEiUtBQSVeJUlJJzexQCVey9ZUS0Udoigtv0jBUE8PaNq//IKSzPy84v@6vqZ6BoYGAA "Perl 5 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3.8/), 69 bytes
```
for k in b"\n":print(('%4s'*12%(k//5or'',*range(0,11*k,k)))[1:])
```
[Try it online!](https://tio.run/##LY67CgIxEEWxsLGxsbELguyDBTOTzLr6K2qh4IuF7BJt/Pr15hE4XGZyuMn4@74GZ7rRT9Nj8KpXb6dum9n87Jar9eY4@rf7lmWxtZ@iJt6W/W4ngy@KpvZX97yXuiGq@6avqupEx0s1TSoeDQgwMMACAS3Ygw4coOhF8nS6JyQhGclIgzRIi7RICT4nP7jBC064F9CCPejAQUMJvsl@7gs90ZPsiCL0EN6h2G@Tz7m3TX3oSh52hB1hx7Ffsi/pD@hNbuxThBmeYsws@g8 "Python 3.8 (pre-release) – Try It Online")
Thanks to dingledooper for -3 bytes from the bytestring hardcode. If trailing spaces are allowed:
**64 bytes**
```
for k in b"\n":print('%3s '*12%(k//5or'',*range(0,11*k,k)))
```
[Try it online!](https://tio.run/##LY7LCsIwEEVx4caNGzfuQkH6oGBm0qnVb3Gj4KMU0hLd@PXx5hE4XGZyuMny@75na4bFef@cnZrUaNW9WK2vdrvbF5fFjfZblQfzUWVDfKim41FmV5Zt42729ah0S9RM7VTXtfcqHg0IMDCgAwJ6cAIDOEPRm@TpdE9IQjKSkQZpkB2yQ0rwOfnBDV5wwr2AHpzAAM4aSvBN9nNf6ImeZEcUoYfwDsX@Lvmce/vUh67kYUfYEXYc@yX7kv6A3uTGPkWY4SnGzKL/ "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Python 3](https://www.python.org/), 76 bytes
```
print(*(' '.join(f'{i*j*5:3}'for i in range(11))for j in range(6)),sep='\n')
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ0tDXUFdLys/M08jTb06UytLy9TKuFY9Lb9IIVMhM0@hKDEvPVXD0FBTEySUhRAy09TUKU4tsFWPyVPX/P8fAA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 115 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 14.375 bytes
```
5∆õ‚ÇÄ Ä*5*J;‚ÇÄ Ä√∞pp√ûƒ†
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyI9IiwiIiwiNcab4oKAyoAqNSpKO+KCgMqAw7BwcMOexKAiLCIiLCIiXQ==)
## Explained
```
5∆õ‚ÇÄ Ä*5*J;‚ÇÄ Ä√∞pp√ûƒ†¬≠‚Ű‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Ű‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Ű‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Ű‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å£‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å£‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚ŧ‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚ŧ‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Ű‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Ű‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Å¢‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Å¢‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Å£‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚ŧ‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå¬≠
5ƛ ; # ‎⁡To each number in the range [1, 5]:
‚ÇÄ Ä* # ‚Äé‚Å¢ Multiply it by the range [0, 10]
5* # ‎⁣ Multiply that by 5
J # ‎⁤ And prepend the number to the start of the list
‚ÇÄ Ä√∞p # ‚Äé‚Å¢‚ŰThe list [0, 10] with " " prepended
p # ‎⁢⁢Put that list at the start of the list of lists from before
ÞĠ # ‎⁢⁣Gridify, right-aligning and joining columns on spaces.
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
**SQL, Will never win 267**
```
with C AS(SELECT 10 C UNION ALL SELECT C-1FROM C WHERE C-1>=0),M AS(SELECT 5 M UNION ALL SELECT M-1FROM M WHERE M-1>0),PS as(select C,M,C*M*5 PS from C cross join M)SELECT*FROM(SELECT*FROM PS)tbl PIVOT(max(PS)FOR C IN ([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10]))P
```
Try it here [db<>fiddle](https://dbfiddle.uk/L106onYm)
**Explained...**
```
--List Crystals 0-10
with Crystal AS (
SELECT 10 Crystal
UNION ALL
SELECT Crystal-1
FROM Crystal
WHERE Crystal-1>=0
)
--List Members 1-5
,Member AS (
SELECT 5 Member
UNION ALL
SELECT Member-1
FROM Member
WHERE Member-1>0
)
--Join Crystal and Member, Calc People Seconds
,PS as
(
select Crystal,Member,Crystal*Member*5 PS
from Crystal
cross join Member
)
--Pivot Maze
SELECT * FROM
(
SELECT *
FROM PS
) tbl
PIVOT(
max(PS)
FOR Crystal IN ([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10])
) pvt
```
[Answer]
# JavaScript (ES6), 74 bytes
*+4 bytes for a quick and dirty fix to comply with the updated output*
```
f=(y=5,x=11)=>x--?f(y,x)+` ${x*y*5||x}`.slice(-4):y?f(y-1)+`
`+y:' '
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVaj0tZUp8LW0FDT1q5CV9c@TaNSp0JTO0FBQUGlukKrUsu0pqaiNkGvOCczOVVD10TTqhKkRtcQqIZLQSFBu9JKHahW/X9yfl5xfk6qXk5@ukaahqbmfwA "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
y = 5, // y = team members
x = 11 // x = crystals
) => //
x-- ? // if x is not 0 (decrement it afterwards):
f(y, x) + // do a recursive call with (x, y)
` ${x * y * 5 || x}` // and append x * y * 5 or x if this is 0
.slice(-4) // right-justified to 4 characters
// with leading spaces
: // else:
y ? // if y is not 0:
f(y - 1) + // do a recursive call with just y-1 (which
// means that x is implicitly reset to 11)
`\n ` + // followed by a line feed a 2 spaces
y // followed by y
: // else:
' ' // insert the 3 top-left spaces and stop
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 138 bytes
```
(echo;seq 0 10;paste -d' ' <(seq 5) <(printf %s\\n {1..5}\*{0..10}\*5|bc|xargs -n11)|tr \ \\n)|sed 's/^/printf %3s\\\\n /e'|pr -ats\ -12
```
[Try it online!](https://tio.run/##NYxLDsIgGAav8m0MxYSXhlV7FGJCW7RuEPlZmBTPjnThbjKZzOxpa20Iy/YaKbyhYfSYPJUAsTIwTMOhLe@Q8jOWO07kXMRupLRfd961lEZ3sHVe6sfnB0FEY3gtGQ7oLa8UVjBSN/VfXPvjuKjAasoQvlBvhbm09gM "Bash – Try It Online")
### With comments
This solution works by generating all the desired numbers, one per line, and then formatting the table with `printf(1)` and `pr(1)`:
```
(
# Generate the top line
echo
seq 0 10
# Intersperse 1 through 5 in-between the calculated rows using paste(1).
# The calculation is done with a cross-product of {1..5}*{0..10}*5 piped
# to bc(1).
paste -d' ' \
<(seq 5) \
<(\
printf '%s\n' {1..5}\*{0..10}\*5 |
bc |
xargs -n11 \
) |
tr ' ' '\n' \
) |
# All columns should be 3 characters wide.
sed 's/^/printf "%3s\\n" /e' |
# Use pr(1) to output data across (-a), no header (-t) and with a space
# separator (-s ' ') between the 12 columns (-12).
pr -ats' ' -12
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 67 bytes
```
11*#5*$(¶_11*@
_
$>:&
#
$:&
%`@(?<=(.).*)
$.($1*$:&*5*
P^`\d+
```
[Try it online!](https://tio.run/##K0otycxLNPz/n0tBQcHQUEvZVEtF49C2eCDTgSueS8XOSo1LmUtBBUipJjho2NvYauhp6mlpAoX0NFQMtYASWqZaXAFxCTEp2v//AwA "Retina – Try It Online") Explanation:
```
11*#5*$(¶_11*@
```
Insert a template for the output: 11 column headers, and 5 rows, each with a header.
```
_
$>:&
```
Populate the row headers. `$>:&` translates as `1`-indexed match index.
```
#
$:&
```
Populate the column headers. `$:&` is the `0`-indexed match index.
```
%`@(?<=(.).*)
$.($1*$:&*5*
```
Populate the table body. Each row is processed independently, and each `@`'s match index is multiplied by the row number and by `5`.
```
P^`\d+
```
Left-pad all of the numbers to the same width.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
-r⁵×þ`ḣ7ẸƇ»×¥5AG⁶3¦
```
**[Try it online!](https://tio.run/##ASsA1P9qZWxsef//LXLigbXDl8O@YOG4ozfhurjGh8K7w5fCpTVBR@KBtjPCpv// "Jelly – Try It Online")**
### How?
```
-r⁵×þ`ḣ7ẸƇ»×¥5AG⁶3¦ - Main Link: no arguments
-r⁵ - -1 inclusive range 10 -> [-1,0,1,2,3,4,5,6,7,8,9,10]
` - use as both arguments of:
þ - table with:
√ó - multiplication
·∏£7 - head to index seven
Ƈ - keep those for which:
·∫∏ - any?
¥5 - last two links as a dyad - f(M=that, 5):
√ó - {M} multiply {5}
» - {M} maximum {that}
(multiplies M's positive values by 5)
A - absolute values
G - format as a grid
¦ - sparse application...
3 - ...to indices: [3]
⁶ - ...action: a space character
(replaces the top left 5 (from -1√ó-1√ó5) with a space)
```
[Answer]
# [C (clang)](http://clang.llvm.org/), 99 bytes
```
p(r,i){r?printf("\n%d",r):0;for(i=-1;i++<10;printf("\t%d",r>0?i*5*r:i));}f(i){for(i=0;i<6;p(i++));}
```
[Try it online!](https://tio.run/##PYxLCsIwEED3OUWpCDP9SLrQRSe2F3FTEqMDNQ0xrkrPHqOC6/fRrZ4nd0vJQ2gY1zD6wC5aKC9ub8omYC/JLgH43HbEda06SX8lfpVBjlwdq9AzIm0W8uZXSGJ1Ig85@5C0Y6fnl7kW6hkNL4f7IPKoeEzsAFdhAUls6Q0 "C (clang) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
5LTÝδ*5*TÝšεNš}§3j»ð2ǝ
```
Should have been 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) without the `§`, but unfortunately [there is a bug in 05AB1E](https://github.com/Adriandmen/05AB1E/issues/173).
[Try it online.](https://tio.run/##yy9OTMpM/f/f1Cfk8NxzW7RMtYD00YXntvodXVh7aLlx1qHdhzcYHZ/7/z8A)
**Explanation:**
```
5LTÝδ* # Push a 0..10 by 1..5 multiplication table:
5L # Push a list in the range [1,5]
T√ù # Push a list in the range [0,10]
δ # Pop both lists, and apply double-vectorized:
* # Multiply the values together
5* # Multiply each value by 5
TÝš # Prepend list [0,10] to this matrix
ε } # Map over each row:
Nš # Prepend the 0-based map-index to the list
§ # (workaround: cast every integer to a string)
3j # Prepend leading spaces where necessary so each string is of length 3
» # Join each inner list of strings with space delimiter,
# and then each string with newline delimiter
«ù # Replace the character
2 # at (0-based) index 2 (which is the first '0')
√∞ # with a space
# (after which the result is output implicitly)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 77 bytes
Improvements thanks to Dingus
```
q=*r=1..10;s=" "
1.upto(6){|i|puts" #{s} "+("%4d"*10)%q
q=r.map{|j|j*5*s=i}}
```
[Try it online!](https://tio.run/##BcFLCoAgEADQvaeQCcEMxIFqE3OYoo1C5HcR6tntvViub4xAKhJqjeZIBBwY6uLzK/e5Ntt8yQk4n2rqHBYJYr1BoZlFYIGifk5fm2tObSqR7X2MHw "Ruby – Try It Online")
# [Ruby](https://www.ruby-lang.org/), 82 bytes
```
q=r=[*1..10];s=" "
1.upto(6){|i|puts (" #{s} "+"%4d"*10)%q
s=i;q=r.map{|j|j*i*5}}
```
[Try it online!](https://tio.run/##KypNqvz/v9C2yDZay1BPz9Ag1rrYVklBictQr7SgJF/DTLO6JrOmoLSkWEFDSUFBubq4VkFJW0nVJEVJy9BAU7WQq9g20xqoXy83saC6JqsmSytTy7S29v9/AA "Ruby – Try It Online")
[Answer]
# [Python](https://www.python.org), 97 bytes
```
[print(("%4s"*12%x)[1:])for x in[(" ",*range(11))]+[(c,*range(0,c*50+1,5*c))for c in range(1,6)]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3E6MLijLzSjQ0lFRNipW0DI1UKzSjDa1iNdPyixQqFDLzojWUFJR0tIoS89JTNQwNNTVjtaM1kmECBjrJWqYG2oY6plrJmmA9yUA9ClDVOmaasbEQi6D2wewFAA)
[Answer]
# [Kotlin](https://kotlinlang.org/), ~~118 bytes~~ 97 bytes
```
fun main() = println((0..5).joinToString("\n") { j -> (0..10).joinToString(" ") { i -> "${i * j * 5}".padStart(3) } })
```
[Try it online!](https://tio.run/##Xco9CoNAEAbQq3wsKWYEFyVYxkuYMs2CKGPMrMhYyZ59/SnTPt432iya87ApfkGUGC8sq6jNSlR537Cfoug7dnbqSO6jjrFjQtniCnX1P3AHuYJ77ILizAWa5PwS@s7CavRkJCTO@QA)
I've removed about 21 bytes thanks to [The Thonnu](https://codegolf.stackexchange.com/users/114446/the-thonnu) because I forgot to remove spaces, also I've used `"%3d".format()` to pad the numbers to a width of 3 characters.
```
fun main()=println((0..5).joinToString("\n"){j->(0..10).joinToString(" "){"%3d".format(it*j*5)}})
```
[Try it online!](https://tio.run/##y84vycnM@/8/rTRPITcxM09D07agKDOvJCdPQ8NAT89UUy8rPzMvJD@4BCiarqEUk6ekWZ2laweSNDRAl1UASiqpGqco6aXlF@UmlmhklmhlaZlq1tZq/v8PAA)
[Answer]
# [BQN (CBQN)](https://mlochbaum.github.io/BQN/), 128 bytes
This is definitely sub-optimal. I don't really know what I'm doing with this language.
```
•Out ¯1↓⥊(1↓˘∾˘⍉(/⟜" "∘(4-≠)∾⊢)¨•Fmt¨[↕6]∾⍉[↕11]∾5××´¨1↓↕6‿11)∾˘6‿1⥊@+10
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m704qTBvwYKlpSVpuhY3Gx41LPIvLVE4tN7wUdvkR0u7NED06RmPOvYBid5ODf1H8-coKSg96pihYaL7qHOBJlDmUdcizUMrgDrdcksOrYh-1DbVLBYk3NsJYhsagjimh6cfnn5oy6EVYHOBKh417Dc01ASbC2YD7XLQNjSAuAPqHJizAA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
⁵Żð⁶;W;Gµ5×1;×þ5
```
[Try it online!](https://tio.run/##ASMA3P9qZWxsef//4oG1xbvDsOKBtjtXO0fCtTXDlzE7w5fDvjX//w "Jelly – Try It Online")
```
ð⁶;W;Gµ [[" "] + a] + f(a), as a grid
where
⁵Ż a = [0…10]
5×1;×þ5 f(r) = table of [1]+(5×r) times [1…5]
```
[Answer]
# Java, 112 bytes
```
v->{var r="";for(int i=-1,j;i++<5;r+="\n")for(j=-2;j++<10;)r+=r.format("%4s",i<1?j<0?r:j:j<0?i:i*j*5);return r;}
```
[Try it online.](https://tio.run/##LY9BasMwEEX3OcUgKEhxbOLSbCyrOUGyKXTTdqEqThnVlsNIFoTgs7sS9WaGeR@G962OurSX38X02ns4aXSPDQC60NFVmw7O@QR4C4TuBwx/H/ECUchE500aPuiABs7gQC2xfH1ETUCKMXkdiac/gKqsd1ZiUbQHSYVin46JHFpVPkubcL2XIgVUJTrowNnTi2c7bOujbfdHamyTNza4tduDkNSFiRyQnBeZFW7Td58UVpOYBYfUg/87f3xpsXa4@9AN1TiF6paSwF1luJv6Xqx15uUP)
**Explanation:**
```
v->{ // Method with empty unused parameter and String return-type
var r=""; // Result-String, starting empty
for(int i=-1,j;i++<5 // Loop `i` in the range (-1,5]:
; // After every iteration:
r+="\n") // Append a newline to the result-String
for(j=-2;j++<10;) // Inner loop `j` in the range (-2,10]:
r+=r.format("%4s", // Append the following with up to 4 leading spaces to the
// result-String:
i<1?i<j? // If it's the first row and column:
r // Append the result-String itself, which is still "" at
// this point
: // Else-if it's the first row, but NOT the first column:
j // Append `j`
:j<0? // Else-if it's the first column, but NOT the first row:
i // Append `i`
: // Else (it's neither the first row nor column):
i*j*5); // Append `i` multiplied by `j` multiplied by 5
return r;} // After the nested loops, return the result-String
```
] |
[Question]
[
Yeah... it's confusing. Let me explain it a little better:
1. With a string, get the unicode code points of each letter
* Let's use `"Hello World!"`.
* The code points would be `[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]`
2. Of each digit of the code points, get their binary format
* Get the binary of `7`, then `2`, then `1`, then `0`, and so on...
* `['111', '10', '1', '0', '1', '1', '0', '1000', ...]`
3. The binary integers are treated as decimal and summed, and that's the result.
* Take the integer of the binary (e.g. `'111'` is the integer `111` in decimal; one hundred and one) then sum all of these integers.
* The result of `"Hello World!"` would be `4389`.
## Test Cases
```
"Hello World!" -> 4389
"Foo Bar!" -> 1594
"Code Golf" -> 1375
"Stack Exchange" -> 8723
"Winter Bash" -> 2988
```
Shortest code in bytes wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
ÇSbO
```
[Try it online!](https://tio.run/##yy9OTMpM/V9zbuv/w@3BSf7//3uk5uTkK4TnF@WkKHK55ecrOCUWKXI556ekKrjn56RxBZckJmcruFYkZyTmpadyhWfmlaQWARUVZwAA "05AB1E – Try It Online")
Get the codepoints, split into digits, convert to binary, sum.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 6 bytes
```
ODFBḌS
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJPREZC4biMUyIsIsOH4oKsIiwiIixbIlwiSGVsbG8gV29ybGQhXCIsIFwiRm9vIEJhciFcIiwgXCJDb2RlIEdvbGZcIiwgXCJTdGFjayBFeGNoYW5nZVwiLCBcIldpbnRlciBCYXNoXCIiXV0=)
Literally just ord ‚Üí to digits ‚Üí flatten ‚Üí to binary ‚Üí from decimal ‚Üí sum
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 8 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
▒$m▒─àiΣ
```
[Try it online.](https://tio.run/##y00syUjPz0n7///RtEkquUDi0ZSGwwsyzy3@/1/JIzUnJ18hPL8oJ0VRiUvJLT9fwSmxCMR0zk9JVXAH6gOyg0sSk7MVXCuSMxLz0lOBAuGZeSWpRUClxRlKAA)
7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) by removing the leading `‚ñí` and taking the input as a list of characters: [try it online](https://tio.run/##y00syUjPz0n7/18l99G0SY@mNBxekHlu8f//0eoe6jrqqUCcA8X5QKwAxOFQdhFUPAWIFdVjuaLV3aAyMJVOQJwIVQlR4QyVTYGaDVLlDhUDmZUGVhUMZJVA9SYDcTZUpSsQV0DFMqDyeUCcDjYNpBPktkyoaAnUjiI01xSDdccCAA).
**Explanation:**
```
‚ñí # Convert the (implicit) input-string to a list of characters
$ # Convert each character to its codepoint integer
m # Map over each integer:
‚ñí # Convert it to a list of digits
─ # Flatten the list of lists
à # Convert each digit to a binary string
i # Convert each string to an integer
Σ # Sum them together
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 62 bytes
```
Tr[FromDigits/@Join@@i@ToCharacterCode@#~i~2]&
i=IntegerDigits
```
[Try it online!](https://tio.run/##JYzLCsIwEEX3fkWM4EoouC8Eq/WxEix0IS6GdEwG0wxMsxDE/npscXe43HN6SB57SGQhuzI3cq@F@z05SkNhLkzRGDINVx4EbEKpuEOzGmncPtYLKs8xoUP5C/kqFFNhXGGU@ugThsCqZQndUm90zax2IDPOEXXk8Jz4lsC@1OFtPUSH09BODZTpOnj9VTn/AA "Wolfram Language (Mathematica) – Try It Online")
-6 bytes from @att
[Answer]
# [Python 2](https://docs.python.org/2/), 61 bytes
```
lambda s:sum(int(bin(int(y))[2:])for x in s for y in`ord(x)`)
```
[Try it online!](https://tio.run/##HYuxCoAgFAB/5eXkWx2D9v6goYISkwT1iRrk15s23Q13oeSbvKh62qo9nVQnpDE9jhufuTT@Z0FcxbijpggvGA8JupamB0XFXzywhthT3YbwZI6Ilc2XtQQLRasG9gE "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~87~~ 83 bytes
*Edit: -4 bytes magnanimously thanks to pajonk*
```
function(s,e=7:0,`/`=Vectorize(function(x,b)x%/%b^e%%b))sum(utf8ToInt(s)/10/2*10^e)
```
[Try it online!](https://tio.run/##TcyxCsIwEADQX9FC4E4CSV0UIbvupW6lJF6hEHMll0Dx5@Mmzg9ebsI@cQ0bi2tLTaGsnEA0ucvN6tnMbqRQOK8fgh/v2uOujPITKeURpb6hluU68CMVEDS9NedTbyfCvx@6O8XIhyfn@Dp22L4 "R – Try It Online")
Works for ASCII characters (codepoint ‚â§8 bits). Add 1 byte to handle up to 100-bit codepoints, by changing `7:0` to `99:0`.
**Ungolfed**
```
g=Vectorize( # g is a vectorized helper function
function(x,b)x%/%b^(7:0)%%b # that converts x to base b digits
function(s){ # get the string s
c=utf8ToInt(s) # get the codepoints c
d=g(c,10) # apply g with arg 10 => get decimal digits
b=g(d,2) # apply g with arg 2 => get binary digits
e=b*10^(7:0) # multiply binary digits by powers of 10
sum(e) # return the sum
```
[Answer]
# [R](https://www.r-project.org/), ~~100~~ ~~97~~ ~~85~~ 79 bytes
Or **[R](https://www.r-project.org/)>=4.1, 72 bytes** by replacing the word `function` with a `\`.
*Edit: - 5 bytes by @Dominic van Essen with huge thanks and a fair play award.*
```
function(s)sum(10^(0:31)*!intToBits(unlist(strsplit(c("",utf8ToInt(s)),'')))<1)
```
[Try it online!](https://tio.run/?fbclid=IwAR0IWJL7VHWOtmZj8oqD2wuj7Ec178yjFRJyRrqLYmiC2jqJeL8_nPngSrY##Nc5dC4IwGIbh837FtAP3hoFf0YzqwOjrOMGzQJar0dob24T@vSno6XXDw2M6setEq7mTqKkF235oHN1ptEljWHhSuxIL6SxttZLWUeuM/SrpKKe@H7ZOsBKvuneAMAgAYBtDJ6h/aZRCUqFRD8@HOVnuSZayfNanEyIpajNxvMqzgQ/4aMgZlZg8Xa8Gv7mav8nxx1@1fjZjZOskHWLVH2xMP2dfY0lyxro/ "R – Try It Online")
Strings, digit split, converting to binary? These are things [R](https://www.r-project.org/) isn't great in. Thank goodness there aren't primes involved in this challenge...
[Answer]
# [Vyxal 2.4.1](https://github.com/Vyxal/Vyxal) `s`, 6 bytes
```
C·πÖfbv·πÖ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=C%E1%B9%85fbv%E1%B9%85&inputs=Hello%20World!&header=&footer=)
```
C # Charcodes
·πÖf # to digitlist
b # Each to binary
v·πÖ # Each to integer
# (s flag) Sum
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
IΣIE⭆S℅ι⍘Iι²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0F8LwTSzQCC4BSqSDWJ55BaUlEK6Gpo6Cf1FKZl5ijkamJpDjlFicCpUC68wEihlpgoH1//8eqTk5@Qrh@UU5KYpc/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
⭆ Map over characters and join
ι Current character
‚ÑÖ Ordinal
E Map over digits
ι Current digit
I Cast to integer
⍘ ² Convert to base `2`
I Cast to integer
Σ Take the sum
I Cast to string
Implicitly print
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 74 bytes
```
s=>eval([...s.replace(/./gu,c=>c.codePointAt()),0].join`..toString(2)*1+`)
```
[Try it online!](https://tio.run/##DcqxCsIwEADQX9Gpd1qv6p5CN0fBwUGEhvQaUo5cSWJ/P3Z88Ba72exSWMsl6sR1NjWbnjcr8CGiTIlXsY6ho87/Wmd6R26PTw2xDAUQ2@uXll0jUdFXSSF6uOPpdh6xOo1ZhUnUwwzNg0X08NYk07FBrH8 "JavaScript (Node.js) – Try It Online")
Eval abuse ftw!!! -2 bytes thanks to Neil. -1 byte thanks to tsh.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 11 bytes
```
+//10/2\10\
```
[Try it online!](https://ngn.codeberg.page/k#eJxdj8tqwzAQRffzFarpoqUoiu2Y2BZ00dLHvossEkMUR7ZFbCmVZLAp7bdXEoU23QzDucwdTlPeERIvSbKLlzsAW35cb+cvXTYIoYnu1Yne7BsmejrRmerb6hPsNnrlfa/QRun+eBXRVZoXlcfPSqEHph2Ks2IV0KM6cvSi+saxdJ0F9mZZfUJPU90x2fKI5uskDcFGSMu1qzBdRJMizysAAp21Z1MSUruq1jUtjL/nP+eLWg3kfeTGCiUNSdKiSDPScottx7EZB6yasB6EZHrGchwOXBtPRyl8Jw7jrNzzgBk2VgvZAlx6InyPvCr8enrkVeGPZ2BOFf57+sCrwoWnp171G20pdyI=)
* `10\` convert input string to a matrix of the digits of its byte representation
* `2\` convert those digits to binary
* `10/` treat those binary numbers as if they were in base 10 (e.g. treat `111` in binary as `111` in base-10)
* `+//` take the sum
[Answer]
# [Python](https://www.python.org/), 62 Bytes
*Thanks to @U12-F̉͋̅̾̇orward*
```
lambda p:sum(int(f'{int(d):b}')for i in p for d in'%s'%ord(i))
```
[Attempt it online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweIc25ilpSVpuhY37XISc5NSEhUKrIpLczUy80o00tSrQVSKplVSrbpmWn6RQqZCZp5CgQKImQJkqqsWq6vmF6VoZGpqQk0pKygC6cnRUPJIzcnJVwjPL8pJUVTS1OSCS7jl5ys4JRahCjrnp6QquOfnpKGIBpckJmcruFYkZyTmpaeiSIUD6dQioEHFGUow2xcsgNAA)
## [Python](https://www.python.org/), 63 Bytes
*Thanks to @att*
```
lambda p:sum(int(f'{int(d):b}')for i in p for d in str(ord(i)))
```
[Attempt it online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweIc25ilpSVpuhY37XMSc5NSEhUKrIpLczUy80o00tSrQVSKplVSrbpmWn6RQqZCZp5CgQKImQJiFpcUaeQXpWhkampqQo0pKygCacrRUPJIzcnJVwjPL8pJUVTS1OSCS7jl5ys4JRahCjrnp6QquOfnpKGIBpckJmcruFYkZyTmpaeiSIUD6dQioEHFGUow2xcsgNAA)
## [Python](https://www.python.org/), 70 Bytes
*Thanks to @Unrelated String*
```
lambda p:sum(int(f'{int(i):b}')for i in"".join(str(ord(i))for i in p))
```
[Attempt it online!](https://ato.pxeger.com/run?1=VY2xCsIwFEV3v-KZpcmgsxRcFKu7QxeXtElsNM0LaSqK-CUuBdF_8m9sUQudDtzDvff-cpdQoG0eZr571kFNZu_E8DITHFxc1SXVNlAVXTtoFme3iCn0oEFbQqYH1JZWwVP0otW9AsfYb-3kfNc1lGykMQgpeiPGhLFRLxJEWHA_DJcoJKzRqEG6DTw_wuqcF9zu5UClLaVvh6qC_N-b5ssP)
## [Python](https://www.python.org/), 77 Bytes
Just a bunch of comprehension
```
l=lambda p:sum(int(format(int(i),"b"))for i in"".join(str(ord(i))for i in p))
```
[Attempt it online!](https://ato.pxeger.com/run?1=VY89DsIwDEZ3TmEyJRIwIyQWED8LE0PntElpwImjNEVwFpYucCduQ0C0Uidb35Of9T1e_h4rcm37bGI5nb8PuERpcyXBL-rGcuMiLylYGX-rEROWMyFSBAaMY2x2JuN4HQOnoBLvEXgh_tKrD99j5GyvEQkyCqjGSTPqwZYIVjIMwzUpDTvCcpAeoywusLkVlXQnPUBZmjokUV2x7ntX7QM)
[Answer]
# JavaScript (ES6), 82 bytes
```
s=>-[...s].flatMap(c=>[...c.codePointAt()+""]).reduce((n,x)=>n-(+x).toString(2),0)
```
[Answer]
# [Lua](https://www.lua.org/), 141 bytes
```
s=...t={}u=0 for i=1,#s do v=s:sub(i,i):byte()while v>=1 do n=v%10 v=v//10 b="0"while n>0 do b=(n&1)..b n=n>>1 end u=u+b//10 end end print(u)
```
[Try it online!](https://tio.run/##JctdCsIwEATgqywVJcGSJq@FzZsn8ARNG22wbKX5URHPHhN9GIaBb5Y45OxRCBHw/Yko4bJu4FC1Ow/TCgl976NhrnW8N69gGX/MbrGQNKoKCNNeyeJS15U22MjmL0jLCgwyOiguhCmWtFZgaYKI8Wh@j7pq7pujwCLPOZ/DMN7g9Bznga72Cw "Lua – Try It Online")
**Important** The current version of Lua in TIO is 5.3, this causes the output to be shown with .0 as a floating point number, in Lua 5.4 the output is shown as an integer as expected.
[Answer]
# [Factor](https://factorcode.org/) + `math.text.utils math.unicode`, 52 bytes
```
[ [ 1 digit-groups ] map-flat [ >bin dec> ] map Σ ]
```
[Try it online!](https://tio.run/##TZBBbsIwEEX3PsXHe5AgIJJWyoKqpd10gyoWiIXrTBILY7v2RIJep/fpldIURNXlvDej@TO10uxj/7Z5eV3f4ai4nTCdeNKxsQnaH4OxFC@lYUPp2hJUTBSR6KMjp2@0c0b7ihAiMZ9DNI5xoOjIoiFHUVnzqdh4l3AvhHwmaz22PtpqJAGMMC4xz/JCyCfvsVLxgnFT00UxF/Lhd8Pa21r@V9lyIeSGlT7g8aRb5RqSV5UvZ5mQ2yHLEHilUiv/pmZFnvc77DBFZRrD4yb6LiTsh3PCuLaKB1e@G4eKdHnF@P7Cvl/AqRDsGZPhR5ZU7H8A "Factor – Try It Online")
```
! "hi"
[ 1 digit-groups ] map-flat ! { 4 0 1 5 0 1 }
[ >bin dec> ] map ! { 100 0 1 101 0 1 }
Σ ! 203
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 55 bytes
```
->s{s.chars.sum{|c|c.ord.digits.sum{|d|("%b"%d).to_i}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664ulgvOSOxqFivuDS3uia5JlkvvyhFLyUzPbMEKpZSo6GkmqSkmqKpV5Ifn1lbW/u/QCEtWskjNScnXyE8vygnRVEp9j8A "Ruby – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
```
oV!UYBUs
```
The online interpreter only works with ASCII, because of Octave limitations. For non-ASCII the offline interpreter on MATLAB gives the correct result.
[Try it online!](https://tio.run/##y00syfn/Pz9MMTTSKbT4/391j9ScnHyF8PyinBRFdQA) Or [verify all test cases](https://tio.run/##y00syfmf8D8/TDE00im0@L9LyH91j9ScnHyF8PyinBRFdS51t/x8BafEIhDTOT8lVcE9PycNyA4uSUzOVnCtSM5IzEtPBQqEZ@aVpBYBlRZnqAMA).
### Explanation
```
o % Implicit input. Convert to double, element-wise. This gives codepoints
V % Convert to string representation. Gives a row vector of chars
! % Transposse into a column vector of chars
U % Interpret each row (that is, each char) as a number
YB % Convert to binary chars. Gives 3- or 4-column matrix with chars '0', '1', ' '
U % Interpret each row as a number. Gives a column vector
s % Sum. Implicit display
```
[Answer]
# [Python3.7.4](https://www.python.org/downloads/release/python-374/), ~~81~~ 79 bytes
```
f=lambda x:sum([int(bin(int(i))[2:])for i in"".join([str(ord(j)) for j in x])])
```
I was able to remove 2 bytes thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing)'s suggestion.
You can [try it online](https://tio.run/##PcsxDsIwDIXhnVOYTPbCQLdKLAyIGzBEGVKFCEdpXLlBKqcPzdLpSf@nt/zqR8rQWrxlP0/Bwzau3xktl4oTF@zLRPY6OoqiwMDFmEuS3exaFUUDJiLomHaEzZGjtmh/RjTPd84CL9EczobodMBDBO5ee2x/)!
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 39 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
{+¬¥{0:0;(2|ùï©)+10√óùïä‚åäùï©√∑2}¬®'0'-Àú‚àæ‚Ä¢Fmt¬®ùï©-@}
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeyvCtHswOjA7KDJ88J2VqSkrMTDDl/CdlYrijIrwnZWpw7cyfcKoJzAnLcuc4oi+4oCiRm10wqjwnZWpLUB9Cgo+4ouI4p+cRsKo4p+oCiJIZWxsbyBXb3JsZCEiICMtPiA0Mzg5CiJGb28gQmFyISIgIy0+IDE1OTQKIkNvZGUgR29sZiIgIy0+IDEzNzUKIlN0YWNrIEV4Y2hhbmdlIiAjLT4gODcyMwoiV2ludGVyIEJhc2giICMtPiAyOTg4CuKfqQ==)
From what I could muster, recursion was the shortest method to convert the things to proper decimal. Character arithmetic saves a lot as usual.
## Explanation
```
{+¬¥{0:0;(2|ùï©)+10√óùïä‚åäùï©√∑2}¬®'0'-Àú‚àæ‚Ä¢Fmt¬®ùï©-@}
ùï©-@ subtract null character from string
∾•Fmt¨ join all codepoints into a string
'0'-Àú subtract zero character to get the digits
{ }¨ for each digit:
0:0; if input is 0, return 0
(2|ùï©)+10√óùïä‚åäùï©√∑2 otherwise,
ùïä‚åäùï©√∑2 recursive call with x // 2
10√ó multiply with 10
(2|ùï©)+ add x % 2
+´ sum the result
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-mx`](https://codegolf.meta.stackexchange.com/a/14339/), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as an array of characters.
```
c ì x¤
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW14&code=YyDsIHik&input=WyJIIiwiZSIsImwiLCJsIiwibyIsIiAiLCJXIiwibyIsInIiLCJsIiwiZCIsIiEiXQ)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `d`, 7 bytes
```
C∆õfbv·πÖ‚åä
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJkIiwiIiwiQ8abZmJ24bmF4oyKIiwiIiwiSGVsbG8gV29ybGQhIl0=)
Fun for the whole family.
## Explained
```
C∆õfbv·πÖ‚åä
C # Character code of each letter
∆õ # to each letter code n:
fb # get the binary representation of each digit
v·πÖ‚åä # and convert to int
# the d flag deep sums the list.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
ṁodḋṁodc
```
[Try it online!](https://tio.run/##yygtzv7//@HOxvyUhzu6wXTy////PVJzcvIVwvOLclIUAQ "Husk – Try It Online")
(or `ṁȯṁodḋdc` [TIO](https://tio.run/##yygtzv7//@HOxhPrgUR@ysMd3SnJ////90jNyclXCM8vyklRBAA) or `ṁöṁdmḋdc` [TIO](https://tio.run/##yygtzv7//@HOxsPbgERK7sMd3SnJ////90jNyclXCM8vyklRBAA), all 8 bytes)
`ṁ`ap & flatten c`o`mbination of `d`ecimal digits & `c`haracter code functions; then `ṁ`ap & sum c`o`mbination of `d`ecimal values from binary `ḋ`igits.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
mc ¨nA2
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=bWMgrK5uQTI&input=IkhlbGxvIFdvcmxkISI)
```
mc - codepints
¨nA2 - digits to binary string
-x flag to sum
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~100~~ 89 bytes
```
m;b;r;d;f(char*s){for(r=0;d=*s++;)for(;d;d/=10)for(m=1,b=d%10;b;b/=2,m*=10)r+=b%2*m;d=r;}
```
[Try it online!](https://tio.run/##XVBNb8IwDL3zK7xIlfqFKAVEqyw7DLHtvgOHwaEkKVS0DUoqrRrir69zS6m2RUqU9@znZ5uPD5w3TUH3VFNBU5sfE@0a55IqbWsWUMFc43nUaTEmiAmbBh0o2NTfM2FNA9TuJyz0C7eNaY/trdAtUKnptcnKCookK20HLiPA0xlAJU1lPnbA4ELeZJ4r2CidiwcCPpAXpeA50TewUkLCq8rTDr1XCT/BusYq5UF21AYtpEaBORK40s6kdZX1WfJKipvLfBbFPkwX8Rzf2XLhQ7QMZz6EcRT1Iq5KU/X98aPkJ6n7Drf1OtzW8QrvgqDlLzwjvRp3Anbrm5VC1igLaP99BJN9SZXa946cSU@4A0PB87rs@5p@rQpr3dbVJezoEG/dDEZTu3L@shLZYf7/srPGlNQmW2KZLYHxE1gC8FviaJUPxh@mN4zJXV/6Oro23zzNk4Npxp8/ "C (gcc) – Try It Online")
Inputs a string and returns the sum of the binary numbers.
[Answer]
# APL+WIN, 38 bytes
This assumes we are allowed an answer based on the the common ASCII/Unicode code points.
Index origin = 0. Prompts for string:
```
+/⍎¨(⍕¨⊂[1]⍉(4⍴2)⊤⍎¨(⍕⎕av⍳⎕)~' ')~¨' '
‚éïav‚ç≥ uses the APL atomic vector to retrieve the ASCII code points.
```
I can only use TIO via Dyalog Classic APL and Dyalog's atomic vector is not identical to that of APL+WIN so that will not work for this solution. However for those who would like to try the integer/binary manipulation via TIO the code below prompts for the integer code points for all the examples given in the question and yields the appropriate sums.
```
+/⍎¨(⍕¨⊂[1]⍉(4⍴2)⊤⍎¨(⍕⎕)~' ')~¨' '
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##RY49CsJAEIX7PcV2Jkhwf5JscgRB8QBiESIRIaCQyiaFhT@BBJvcwCIH8AQ5ylwkzv6gxbCPN@97s9m5DPaXrDwdgrzMquqYT9D16xXcXpKgWm5QMQKPezHNF9B24@BB248DNNct30H79EJoP8KH5v3bIufXMzrz63HAZ0KaTAVRgnLGcRI7nFMpaKKM4jx0G0alJJhmzjepOKapMiGzjB2EYV2JAcWdoysERhKJhqHSFC1lWlAJZo3QFuoCqUs0ggaLrImo@ay@@D8fafAL "APL (Dyalog Classic) – Try It Online")
[Answer]
# APOL, 32 bytes
`⊕(⭳(ƒ(i ƒ(Ŀ(t(↶(∋))) I(b(∋))))))`
## Explanation
```
‚äï( Sum (totals all items in a list)
‚≠≥( List flatten (Turns 2d lists into 1d lists)
ƒ( List-builder for (returns a list of every return value of the passed instruction during the loop
i Input (being iterated through
ƒ( List-builder for
ƒø( Cast to int list (Splits a string and returns a list of each character as an integer
t( Cast to string
↶( Unicode codepoint
‚àã For loop item
)
)
)
I( Cast to integer
b( Binary representation of
‚àã For loop item
)
)
)
)
)
)
```
[Answer]
# [Zsh](https://www.zsh.org/), 61 bytes
```
for c (${(s'')1})for d (${(s'')$((#c))})T+=+$[[##2]d]
<<<$[T]
```
[Try it online!](https://tio.run/##qyrO@J@moanxPy2/SCFZQUOlWqNYXV3TsFYTJJACF1DR0FBO1tSs1QzRttVWiY5WVjaKTYm1trGxUYkOif2vyZWmoOSRmpOTrxCeX5SToqik8B8A "Zsh – Try It Online")
Nothing terribly interesting here, except that it saves **1 byte** to do string appending and defer the final `$[sum]` until the last step.
```
for char (${(s'')1}) # split into characters
for digit (${(s'')$((#char))}) # split decimal codepoint into characters
sum_string+=+$[[##2]digit] # append "+" and the binary representation to a string
<<<$[sum_string] # evaluate that string arithmetically, output
```
[Answer]
# [Haskell](https://www.haskell.org/), 76 bytes
```
e=fromEnum
f s=sum$map(\x->read$(mapM id$"01"<$[0..3])!!(e x-48))$s>>=show.e
```
[Try it online!](https://tio.run/##Rc67boMwFAbgPU9xsDzY4qIkEMVIMUOqtB3aKUMGiiormIACOLJBZei7U7tCyni@/9xqYe6ybedZ8kqr7tSP3aoCw83Y4U48yNcUZlqKEhNbfUJTYrTeoAPO11EUF9TziIQpTBil2GQZN7X6ieTciaYHDm7kGx7jcB70Rw@58X0EYQbI94nrxPYSdfYUzbnDX2ICTQ9hvgIg6N1@qOCidFt6KIAkZikN/pNXpeAotNPNLk0WfVGlhDfVVo7j/W7h8yCudzhN11r0N2kztt/GS3Zp@kFqu8vUNtimjNGimP8A "Haskell – Try It Online")
```
..s>>=show.e - all digits of ascii values
mapM id$"01"<$[0..3] - combinations of bits
!!(e x-48) - take at (enum-48) and
map(\x->read$(...) - read it for every digit
sum - sum
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 69[:(] 68 65 bytes
```
$args|% t*y|%{+$_-split''|%{$s+=+[Convert]::ToString("$_",2)}};$s
```
[Try it online!](https://tio.run/##Xc9NT8JAEAbgc/sr1mYREDCxQCg0TYgNqCeMNeFACKll@NDarTtTxZT97XWDaazcZjLPzJtJxRdI3EEcF3zj5QUP5RaPNUZX38da3uKrDqbxnup13XFsea2FL5JPkLQcjZ5FQHKfbBsWX1ltu6mUy7FQJidA8kMEZB4zxg3TMIxx/pCkGXnWvY4SbC5kvL6w3MkhhYhg7fW6zlC1/8mpEOw2lFV10x/2zpQv1sDuRLypsu6gf8YCCqM3NjlEuzDZQsU6A7t7Zuf7hEDqbNxVoD10HKVds/rfkdVy0@BPgFlM@ttLvmF8dX06ZBqLx8DPkMT77OVVH1mWCaVwZxmd@t/9vywNytoNsigCxBKxDnywylyZyix@AA "PowerShell – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 10 bytes
```
$+TB*J A*a
```
[Try it online!](https://tio.run/##K8gs@P9fRTvESctLwVEr8f///x6pOTn5CuH5RTkpigA "Pip – Try It Online")
### Explanation
```
a First command-line argument (the input string)
A Get ASCII code
* of each character
J Join into a single string
TB Convert to binary
* each character (i.e. digit)
$+ Sum
```
] |
[Question]
[
## Preamble
We've already proven we're good at [adding two numbers](https://codegolf.stackexchange.com/questions/84260/add-two-numbers), but many solutions only operate on tiny numbers like 2³²-1, honestly we can do a lot better.
## The Challenge
Given two unsigned, non-negative integers, add them together and return the output.
Input may be taken in any convenient format (String, Array of bytes/characters, BigInteger, etc.), and output may be in any convenient format as well. Inputs may optionally be padded with any character of choice to any length of choice.
Output must support at minimum all numbers in the range of [0,10²⁵⁶), Inputs will always be in this range as well.
## Test Cases
```
1168 + 0112 = 1280
23101333 + 01858948 = 24960281
242942454044 + 167399412843 = 410341866887
9398246489431885 + 9300974969097437 = 18699221458529322
83508256200399982092 + 74143141689424507179 = 157651397889824489271
173163993911325730809741 + 291008926332631922055629 = 464172920243957652865370
```
## Rules
* [Standard IO Applies](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* [Standard Loopholes Apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* You may **not** output as Scientific Notation. All digits must be included in the output.
* Solutions do **not** need to finish in any reasonable time, they only must provably work.
* Use of built-in BigInteger implementations is allowed, though I encourage you to include a non-built-in solution.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes wins!
* I/O may not be taken as Unary.
* Have Fun!
[Answer]
# Trivial Built-in Answers
For languages where bignum addition is already supported.
## [05AB1E](https://github.com/Adriandmen/05AB1E), [Brachylog](https://github.com/JCumin/Brachylog), [Factor](https://factorcode.org), [J](https://www.jsoftware.com), [Jelly](https://github.com/DennisMitchell/jelly), [Julia](http://julialang.org/), [Nekomata](https://github.com/AlephAlpha/Nekomata), [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte
```
+
```
[Try it online! (05AB1E)](https://tio.run/##yy9OTMpM/f9f@/9/IxMjSxMjE1MTAxMTLkMzc2NLSxNDIwsTYwA "05AB1E – Try It Online")
[Try it online! (Brachylog)](https://tio.run/##DcMxDkBAEAXQq@gp5s@3s/uvQhQoKCQSndMPL3nbs@7ne92HZ/aZMyoRlCiAXiqtmeqIoXPBrMmD/EPuVkq4lpw@)
[Try it online! (Factor)](https://tio.run/##DcM5CoAwEADA3lekF2QPc6w@QGxsxAcEUbRQQ9jG10cHZo@rPrks8zgNnbmiHiblTfVN@bzV9FWFntGxCAsik/UMAcS3aEgQIAg55j8KEVjrSEpdmvIB "Factor – Try It Online")
[Attempt This Online! (J)](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxUBtC37TS5EpNzshXMDTCBSsU0hSMTTBhBcSEBQsgNAA)
[Try it online! (Jelly)](https://tio.run/##DcPBDYAwDAPAgfjENknqgfigLsD0KSfd@@z9zVwzgxZKtgyI2YoV7htDI2KZJf1hMjKLPg "Jelly – Try It Online")
[Try it online! (Julia)](https://tio.run/##yyrNyUw0rPifpmCr8F/7v0NxRn65QpqGobmxoZmxpaWxpaGhsZGpubGBhYGluYmhjpGloYGBhaWRmbExEBtaGhkZmJqaGVlqchHSSrKRuDRo/gcA "Julia 1.0 – Try It Online")
[Attempt This Online! (Nekomata)](https://ato.pxeger.com/run?1=LY4xTgNADAT7e8UpLYrk9fruvG9BFAFBgwJFwmtoEgkQPa_hNzhAYVkrjcf7-vl0__i83x13H9eb7X5zc3p_OT5s83z1dri9O_yn0_cXMLMb4M0JA8lKOVKRzcMVHiMsomMuSgHPYBOVHjMKIzJHF820QlOXxdWSw9LHdLM6K9rkfQWKj3r567WFpYZFzGIogD4WLS8OdBfMUj7JGsjdRgn11_0H)
[Try it online! (RProgN 2)](https://tio.run/##DcNRCoAwDAPQA4nQJLZbTuSfjt0fqg/eXvu9n5PdR3djCCVbBsQcihkeF5pGxDRL@sNkZBb9AQ "RProgN 2 – Try It Online")
[Try it Online! (Vyxal)](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCIrIiwiIiwiODM1MDgyNTYyMDAzOTk5ODIwOTJcbjc0MTQzMTQxNjg5NDI0NTA3MTc5Il0=)
---
## [Haskell](https://www.haskell.org), [Python](https://www.python.org), [Raku](https://raku.org), 3 bytes
```
sum
```
[Attempt This Online! (Haskell)](https://ato.pxeger.com/run?1=Nc09CsJAEEDhq0xhoaAwPzszO8WeRCwiGAwmQUxymjRpgmfyNgrB4sHrvvl9r4bHrW2XZZ3G-pTXugxTt_3n2lVNDwWer6YfYQf7Gs7kQiYREkTC6oIZwxMdOQgxB5vILwpmVDWOywFKgWSJnIORk4S6KWdTcdykv_4F)
[Attempt This Online! (Python)](https://ato.pxeger.com/run?1=JYw5DsIwEAC_k0gg7eHd9RZ-BwXQWlDkEDgFb0ljKYI_5TdBcjGaqWb9zZ_ymMa65XT7LiWf4_Zehlb7ZX49x9Ll7orGqOzOjsgkxhDBLeCJHAGikzL_QScCESW_9ykFDWjkBBTYxVQoqrBB3_a1Nh8)
[Attempt This Online! (Raku)](https://ato.pxeger.com/run?1=m72kKDG7dMGCpaUlaboWUOqmVXFipUJxaa6GobmxoZmxpaWxpaGhsZGpubGBhYGluYmhjpGloYGBhaWRmbExEBtaGhkZmJqaGVlqQg2CmgQA)
Takes input as a list.
---
## [Charcoal](https://github.com/somebody1234/Charcoal), 2 bytes
```
I⁺
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9npWPGnf9/x9taG5saGZsaWlsaWhobGRqbmxgYWBpbmKoo2BkaWhgYGFpZGZsDMSGlkZGBqamZkaWsQA "Charcoal – Try It Online") Requires input in JSON format. 4 bytes for string input:
```
I⁺NN
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9npWPGne937MOiP7/NzQ3NjQztrQ0tjQ0NDYyNTc2sDCwNDcxVDCyNDQwsLA0MjM2BmJDSyMjA1NTMyNLAA "Charcoal – Try It Online")
---
## Java, 14 bytes
```
a->b->a.add(b)
```
I/O as `java.math.BigInteger`s.
[Try it online.](https://tio.run/##nZFBa@MwEIXv@RWDTzZJhEYj29K2CbQLC3vYU49tDnLiZJ06jrGULKXkt2fHqbMsJbCwAiEx873nN/LWHd10u3o9L2vnPfxwVfM@AvDBhWoJW@6KQ6hqsT40y1DtG/FtuNxfejsXforHavO9CeWm7Cb/q/hUnc9hDbOzm86L6dwJt1rFRXK@G3Gy9lDUnGwIeNxXK9hx6PgpdFWzeV64buOTfgSA9b6Lj66DUPrw1fnyS1P@giv3HiFmBsYgEVU0iRShRCK6VExqrDZ9VSurlU611Jo7mOVkrUZlNHHXkjVKZ5phQmNSJixJaXNtM9sflDNlKJVGpZmSksWskFYxmWtkleYQly/IHHPLNOaEGXNkEUmlOUnTOyErlEUpjVUZEW@0SsmUbW10GgYGeHrzodyJ/SGIlucM8XX2cQQziJK7geufxYfuoetmV0L4tq5CHMHLy/gv8tbvATfrn/JWK/5wfZaLZDI43FzFPx1w8SfD56nqJl4L17b1W@yS4VIkA34a9ft0/g0)
---
## JavaScript (ES11), 9 bytes
With BigInts as I/O.
```
a=>b=>a+b
```
[Try it online!](https://tio.run/##DcPtDkAgFADQ16kZux8q90feJZQxK8O8fpzt7OEN93xt59PmssSafA1@nPwYmqnOJd/liN1RVpUUOkbLIiyITMYxDCCux6wVCQIMQpb5j0IExliSrHX9AA "JavaScript (Node.js) – Try It Online")
---
## [PARI/GP](https://pari.math.u-bordeaux.fr), 9 bytes
```
a->b->a+b
```
[Attempt This Online!](https://ato.pxeger.com/run?1=JVBLasUwDLyKySqhDuhnW1o0Fwmh5C1SHpQSHq-QnqWbQCmlR-plSuVkIaQZzYxAH9_rfLs-Pa_75xIev97uS68_cz9c-mF-uJz4929e15f3dgv9ENbb9fXebiNOoYmhCdtIPtVNE5aD79rKdV0M44iYNQIiTY6IEZCZndCkJnqQQiYkSUAkYi5sJkgqXJfGpiRZXMyomqIxgBWxbLVxqSLlBEopE4Cb3QBGsQi6Rfz8kQ4Fi1UxFsbsMjZEplQYtCZhJEMANcrMXmhEkDzTpqk7v7DvZ_8H)
---
## [Ruby](https://www.ruby-lang.org/), 8 bytes
```
proc &:+
```
[Attempt This Online!](https://ato.pxeger.com/run?1=JY9RbsIwDIbfc4qsSAjEVsV20sRInGSbUKFBq8Sgoq20CXjbLfbCw5B2i52D28yhD5b1x9__x_7-OfSrz8u1rCq9uPbd5in8Nof9Wo_ns0Hevg6xrLb1LrZ5LNdvutrrU5InpXXqeRW3sYvLtt9s6o-HSfayy6YyKx_1Si8GpG22dTfJ9Exn0_y9bCbjebdf1glr-q7V2eiYuLPwo6Ps8pzMr7kw7TlTcVcNu1xufwBFkBgDgAoJDBDRXQcX2AaFFtmiddZYK-9QeGK2gMGSYuKAtrACEoTgZM5kDHvLBadGXgVyJqAr0BgxCm8YhfMWxGPl83u68eBZgScohCIGIHSeTEgpIDwyGBMYCyIpYETjJJSHO_4B)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 9 bytes
```
Dv+T‰Áø`À
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fpUw75FHDhsONh3ckHG74/z/aWEcBggx1FAzAJJBtFMsVbaGjYKKjYKmjAGSYgkmQilgA "05AB1E – Try It Online")
No bigints. Takes both inputs as a reversed list of digits, padded to at least the length of the output, and outputs in the same way.
Uses `a + b = (list(a)+list(b))%10 + right_rotate((list(a)+list(b))//10)`. Once we do that length(output) times the second addend will become zero.
## Explanation
```
# implicit input a, b
D # duplicate b, stack is a,b,b
v # for x in b (x isn't used)
+ # add a+b digit-wise
T # push 10
‰ # divmod, so we now have a list of ((a[i]+b[i])//10, (a[i]+b[i])%10)
Á # rotate right
√∏ # transpose
` # dump, the stack has right_rotate((a[i]+b[i])//10), right_rotate((a[i]+b[i])%10)
À # left rotate
# stack is right_rotate((a[i]+b[i])//10), (a[i]+b[i])%10
# implicit output
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 13 bytes
```
10!(_0.1/,)\+
```
[Try it online!](https://ngn.codeberg.page/k#eJxtjTEKwkAQRfs9RUyjosT5MzszO/EoKpIUKW3SimfXiLAWefDhFw/e1IM2uzt1OB3310NKQ980z27bwgUmERKAsLpQofCMNo0/gwNEJdhEPkMwk6pxtGl4zP1iZMtwDibOEuqmXEzF6Wu8pstwHm+1SLFOLdICWLKal6ivFrFulP/iG9/XNfc=)
Takes two lists of digits in reverse order padded to an equal length that is at least as long as the result.
```
10!(_0.1/,)\+
+ Add two numbers digit-by-digit
( )\ Handle carry using scan:
left = 10 * carry + digit value, right = next digit value
_0.1/, add carry to the next digit
10! Remove carry information
```
[Answer]
# [TypeScript](https://www.typescriptlang.org/)'s Type System, ~~211~~ 193 bytes
```
//@ts-ignore
type F<A,C=[]>=A extends[[...infer G,infer X],[...infer H,infer Y]]?[...X,...Y,...C]extends[1,1,1,1,1,1,1,1,1,1,...infer R]?[...F<[G,H],[1]>,R]:[...F<[G,H],[]>,[...X,...Y,...C]]:[]
```
[Try it at the TypeScript Playground!](https://www.typescriptlang.org/play?#code/PTAEEEBNNAXB3A9qATgUwIYBssE9QBGAlgOagB2ArgLYFooDOoAtKAIwCcAzIbrGgwBQgkAAFYDZqXKJ0g2LgAOaUADEAPOAA0AYQC8AbQC6APj3hQaAB79ykBgYMA6F0XIAzeqADiWt55RQAA0jLWdXDy8ACT9IwIBNIyMAfnCnIK0XJ3jMlx0ja1t7AzYtUvKyyoqKrP8vACUUtI0DXyjQktMtRoAuZvVWrXawrrSMrJys-KM+o2EQUHdERH4UYQVlUABVcgwUXHUAOUsbNDsmKlp6LVAAFROipjZjUD1QYxNXu4MAIiwzkiwAAWPyMDzO9lAh0EoFAyTuMNAPW2u32RxuaVuNzYpgA3PIlCoAMqwFC3RA7Pa4AAipCIEnURPB51ADFJbhInzeTMKEKYAAMACQAbzqgVpJHpzPsiMudBQAF8RWLQPUBLAFfzEfCDJS0RL6SYblkSWSKaiaXSGWq2SY5rDkcZ8RsVABZDCKPW4cnUtAAYyI1GwR2lT2MHy+x15LIMKtUREYsFD7GMxoiAVV6uTzyMxntcPe8cTv3+5EBINCoCy7s9Fp9-sDwZtsDtiMdRmdhNABok5NNHM0ybl9Ajbws0chBkRKupQ5o8q0iNqcVVc6uKFTgnz8KFwupSr3VoYffZZfU9RMmrboB+P07m1u6sHE6YbJQHJuACFk2+OVzu0eJ7vmeiI1l69YBkGWDqC0prkl6PYMJoRqgHB5pUoh6ifnaJgmIIJj4gSD7qmwXyPmy6g-GwbAAGwABw-DcPwAAzUQATD8BEiGAsIAHrJERKjkbAbFkU+PxsVwbCsVwsmMTerF0QArHRHAACwMVxCx8QJLp3OqPBvMJlFsWpbHqaZSlqcxalqfJVE0QA7FwHDqWwbF0WpXCcdxsKgPxgn6WyaliRRLHcBwdGmTRGnqVJdHKfZzHcMxyWOWpHA0RwaVeY5Pnaf5uldsJSmhbAlHMXRXBKZVbFKTRbGpS5rlRclHFMcx6VsF53W0apZlqTVjlsI5HD5TxhWBcJNFlZRI1STRzUudRXB1c5lU5Ww9nmdJlUcGxi2rYtnBsY1Sn1eZ41+QFQA)
This is a generic type `F` taking type `A` which is a tuple of two lists of unary numbers (using unary not for the numbers themselves but for the individual digits, as allowed by OP) padded with leading zeroes (`[]`s) to the length of the output.
For example: `F<[[[1],[1],[1,1,1,1,1,1],[1,1,1,1,1,1,1,1]],[[],[1],[1],[1,1]]]>` (1168 + 0112) `= [[1],[1,1],[1,1,1,1,1,1,1,1],[]]` (1280)
## Explanation
```
//@ts-ignore Ignore any compilation errors in
type F< // Recursive main type F
A, // A is tuple of two lists of unary digits
C=[] // C is the digit to carry, default 0
>=
// Match A to get the last and other digits of each number
// X and Y are the current digits of each, G and H are the rest
A extends[[...infer G,infer X],[...infer H,infer Y]]
?[...X,...Y,...C]extends // If it matched: Merge X,Y,C and match against
[/* ... */,...infer R] // ten 1s, storing what's left in R
?[...F<[G,H],[1]>, // If it matched, recurse with [G,H], C=[1]
R] // And append R
:[...F<[G,H],[]>, // Otherwise, recurse with [G,H], C=[]
[...X,...Y,...C]] // And append X,Y,C merged
:[] // If the match failed, return the empty tuple
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 62 bytes
```
f(a,b)char*a,*b;{*a=*a?48+(*b+=f(a+1,b+1)+*a-96)%10:0;b=*b>9;}
```
[Try it online!](https://tio.run/##TZDLbttADEX3/oqBCsOSLAN8zIOM4GTVL2h2bReSYicGEjewg8SF4V@vSk0LxIsBZ8DLc3lnWD0Owzhuy67pq@GpO9RdU/ftue7WdXfnZVnW/XJt7SU2/RKrZd2tNFZzhBto@3Xd32p7Gb88bLa7/cbdf/12byTXN26o3MMvd3YT052@/3RrZ43f@dK3blue7FW17vWw279ty2I@uPnxx75o3PHtMLy8Tn1j3LnFaeFu3OJ90biT6S/u42n3vHElVLPZS7fbl9V5ln0LxCg2XwAiTRVJoKja/11iBGTmfwoJoj6ryWsEErxSelJPPnjwPnNiYlVvOJ@nPQJ7lBhF0ucUKKuQj97AjCIhGykDaDILnQqnzJOoSoQ@SCBloiuIcAChEAnAPA0ImrNA8mhYbxHzbpAwaYaFFAOyJpHJ3twpXWXBxBiNxIrIFBKDTItgTq4IYPrIbAdtJQjmnLGWAxMpAXnWyYIkBk75Py/jn2H73D0ex9XHXw "C (gcc) – Try It Online")
Input two `char*` strings. They must be padded with leading `0`s so they have same length and enough to contain the output. Modify the first array in-place for output.
[Answer]
# [Lua](https://www.lua.org/), ~~121~~ 119 bytes
```
load"A,B=...m=math.floor o=''c=0 for i=1,#A do L=#A-i+1O=A:sub(L,L)+c+B:sub(L,L)c=O/10 o=m(O%10)..o end return m(c)..o"
```
[Try it online!](https://tio.run/##PY7RaoQwEEV/ZchSVlHTmYlJnEIe3GfBb7BmlwpqitXvt/alDxfuuXDgzsdwDjFCgHNOQ1Rt@Qha6yUsw/6lX3NKG6Rwv48B4XX1KVB5ayEm6MKtraaC@tB@/ByfWVd2eTEWj38YQ/9OeNlL1r8R5loneK4Rtud@bCss2fg3qfN7m9Y9u05kirwhZ0SMEBm23mCD4mtSpWIhxEbYGXOFhBmtdSwqz6GqoHY1eRZGro1Y7yw3zhqP5y8 "Lua – Try It Online")
## Ungolfed
```
function add(A,B)
floor=math.floor
output=""
carry=0
for i=1,#A do
L=#A-i+1
sumResult=A:sub(L,L)+carry+B:sub(L,L)
carry=sumResult/10
output=floor(sumResult%10)..output
end
return floor(carry)..output
end
```
Inputs must be 0 padded to equal length.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 35 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.375 bytes
```
02(?(›
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiMDIoPyjigLoiLCIiLCIzMFxuNDUiXQ==)
Doesn't use `+`, but does use addition of some sort (incrementing the top of the stack). Takes inputs as two numbers.
## [Vyxal](https://github.com/Vyxal/Vyxal), 47 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 5.875 bytes
```
2(?(1}!
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiMig/KDF9ISIsIiIsIjMwXG40NSJd)
No addition used, but still requires bignums to be inputted.
## [Vyxal](https://github.com/Vyxal/Vyxal), 133 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 16.625 bytes
```
ZEṠṘ0$(n+₀ḋ÷⅛)¾ṘJṅ⌊
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiWkXhuaDhuZgwJChuK+KCgOG4i8O34oWbKcK+4bmYSuG5heKMiiIsIiIsIlwiMTczMTYzOTkzOTExMzI1NzMwODA5NzQxXCJcblwiMjkxMDA4OTI2MzMyNjMxOTIyMDU1NjI5XCIiXQ==)
A version that takes both numbers as strings, and never has any values that could be a bignum on the stack (except at the end to remove a leading 0 from a string and to implicitly print - this could be done with string methods but it's shorter to use number conversion).
## Explained
```
02(?(›­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁡​‎‏​⁢⁠⁡‌­
0 # ‎⁡Push a 0 to the stack to act as a register
2( # ‎⁢Twice:
?( # ‎⁣ For each number in the range(1, input() + 1):
› # ‎⁤ Increment that 0
# ‎⁢⁡The "register" value is then implicitly printed
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
```
2(?(1}!­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌­
2( # ‎⁡Twice:
?( # ‎⁢ Number of input times:
1 # ‎⁣ push a 1 to the stack
}! # ‎⁤Close all loops and push the length of the stack
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
```
ZEṠṘ0$(n+₀ḋ÷⅛)¾ṘJṅ⌊­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌­
ZEṠ # ‎⁡Zip the input strings together, evaluate the digits in each pair, and vectorise sums
Ṙ0$ # ‎⁢Reverse it, and push a 0 underneath it. This will act as the carry.
( ) # ‎⁣For each digit in that list,
n+ # ‎⁤ Add the carry to that digit, consuming the carry
₀ḋ # ‎⁢⁡ Divmod by 10
÷⅛ # ‎⁢⁢ And add the mod value to the global array, leaving the div value on the stack as the new carry.
¾ṘJ # ‎⁢⁣Push the global array, reverse it, and prepend the carry
ṅ⌊ # ‎⁢⁤Convert to a single string and cast to int, removing any leading 0s.
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Factor](https://factorcode.org/), ~~39 31~~ 43 bytes
```
[ 0 -rot [ + + 10 /mod ] 2map swap suffix ]
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQm1iSoZCdWpSXmqNQnFpYmpqXnFqsUFCUWlJSWVCUmVeiYM3FVa1gCYS1MPp/tIKBgm5RfolCtII2EBoaKOjn5qcoxCoY5SYWKBSXg4jStLTMCoXY/8mJOTkKev8B "Factor – Try It Online")
Non-builtin counterpart to the `+` answer. Takes two reversed, padded lists of digits as input and outputs the reversed answer as a list of digits.
[Answer]
# ISO C23 (clang 16), 42 bytes
`_BitInt(constant)` is a [new C23 feature](https://en.cppreference.com/w/c/23) for [fixed-width integers](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2709.pdf), wide or small. Implementations can have limits (`BITINT_MAXWIDTH`) on how wide they support, but clang 16 is wide enough for the problem's stated range of [0, 10256). log2(10^256) rounds up to 851 bits required. 960 is the largest 3-digit number that's a multiple of 64 (not required, I just chose for efficiency); you can use `unsigned _BitInt(999)` if you want.
```
typedef _BitInt(960)T;T f(T*a,T b){*a+=b;}
```
**Updates the caller's `a` by reference.** Using the return value would be undefined behaviour (and in practice isn't useful even in a debug build.)
Works in practice with clang 16 ([**Godbolt**](https://godbolt.org/#z:OYLghAFBqd5TKALEBjA9gEwKYFFMCWALugE4A0BIEAZgQDbYB2AhgLbYgDkAjF%2BTXRMiAZVQtGIHgBYBQogFUAztgAKAD24AGfgCsp5eiyagA%2BudTkVjVEQJDqzTAGF09AK5smBpwBkCTNgAcp4ARtikILIADuhKxPZMrh5eBrHxdkL%2BgSFs4ZGy1ti2iSJELKREyZ7ePFbYNplMZRVE2cFhEVFW5ZXVqXVKvW0BHXld0gCUVujupKicXEQAntHYODQA1KYAQsQAksIQAJwAbFqTACoApADMO5ebNBCXAFQs5I%2Bhk9cA7Dvva4AJh2dwAIqE7qDfmDrloAIIAekRTwk9ACwE26BoWxYmyYQgAtAA3dAETBPdxMEpCTYEJSbBQ7OlMTbOYGgkHkTahdxEFlsulEMBcBnoADWdK2RCQ2E24nojFIm0w6GwSiYIv57hUmxlctI2CIxIkcPhZotCOBtwCqA8OE2d2cQ0I6AAdEg7rgzQF%2BWwWAEID9/mbNptHupHbcwZstOpblpbscoWHkZseEDbtIAKyh8ObZZRmNxnGlsvlnHuXy%2BFObNOEnh557A07qbnLH73PNU%2BLAQIU%2BhCTGCdBFzaRr1ezanaRQvPRUi%2B5tAoGDgDumyB8qQVPFYulss2Sk8IEdQNzmZ4p3o6mu2ecRGBF9uV5vd%2BcTGBQO5EB7BD76ybIOJiTG2TzoOgnaglaMJcNM9DcNm/DeFwOjkOg3DOEeszzHK1p8OQRDaHB0ziiA2ZaIY3DSPwbDkZRKFoRhXD8EoICUURqFweQcCwCgGBsNEDARJQ1ACUJSpoMAGosNEShIOgRDkDgxIEAsABqBDYGuADyawoQRdD0EQERsRAoTEeQoQBBUyzcAR1msKQyw6aEujFJxBECRwwg6Uw9B2VxynYLywDOGibG8PwOD%2BiYkhBYQholMS6qWdg6jFHyiwEb6DSWeioSkLZrg4JZRCLnRUXTDQRjSZp2l6cw9n8IIwhiBInAyHIwjKGomhBfotyGMYZgWIYBChGxkDTOg0RNJFhIuuCfbuECkaEgA6mimybel5V4oSOm3Pw6ApaQi44FNQb1I0iSOEwLhuDUPgPe0uT5GkcQJEI/S1OQ6TfUwb2dJEgwNB5pTDL9BhFDSzTDMD4ygz0rTQ4MCOjO9XQ8NMSg4QsUjwYhyGWcx44ABynISM6bMAqCoJsEDlbukyM/gxBkGeL6TPwnE6JM0yyiwOCRNdCFcDR5B0ee5CMSd3CsexhHEdMvHICAsxENEfKiRA4nCaQQTsIs6iU9T0i0/TjPM0w4o8%2BQ6wcxdBitaICqdbIru9RolmDeQa5FdEzVE1wSGy6T3A6Xy2v8tiFNUzTdMM0zpAs4zriCQbXO3PbfMkeQQsi9QIeS9L2bh0FzGKxxKukfRVFcMdFdMQrytcariBqxA/HoJnSq6/rkn00YJhXlolEqWp2D1bp%2BnNQIDAmaQZkWUFjm2fP6/Oa57m2PP3nMEQfkBZZOCheFiqRQRMUjfFaGJRDKWRWh6WZSZlm5eLaEFUVzklYsaFyoEEqnwaqtUlAz0agZFq8h2qSC6l7FQPsBoGBHqNUwlgCpXRmnNRIC0lrRhWmtHaW1FQkL2kVHaR0TpnQuqlaaN0IYOAgE4NGDtXqYxBp9DIiQ2EAyaIjD6YNbpCBaH0J6AxGFwzESMHIXD0aowkX9IYrRBHY1xvjTqIcw5y3QtweO5t5RoPTKcN0WgzFs0ICQZU%2BFc61wLtgYWXRrpkR4OPBupdyLkzdOTIE49jhZmzL8Y40gkxAlOM3eWLErBKzzh3eA3cNbRx1lQPWvcJIRCNhwbgpsE4WyTumW4bogT8EdtY8kLtYHuykJ7eQ3t%2BpoX0HUAOslg4Nx0RHLgUctZ8ixFsXJhi7QjRMWYixEAM4ZJsZeOx7cS60SiDwN0PBgnHC0KcbM0g/HZnOL8WQuiq4xJrrM8gZEKINybvs1ucSQ4lMiXo6J1zyBnXiA4aQQA%3D%3D) shows it compiles to a sequence of `add`/`adc` instructions for x86-64, with some wasted loads/stores). But not GCC 13.2 or 14-trunk: *error: '\_BitInt' argument '960' is larger than 'BITINT\_MAXWIDTH' '575'*. (The Godbolt link also includes a simple test caller in `main`, but AFAIK there isn't convenient support for `printf` of big `_BitInt` values, and I didn't bother writing a hexdump.)
C23 doesn't allow implicit-`int` return values, and `T` is a shorter type-name than explicit `void` or `int`. But in C (unlike C++) it's *not* UB for execution to fall off the end of a non-`void` function, so we can declare it with a short type-name as the return type and still not actually `return` anything, if implicit-`int` isn't an option. `void f(...)` would cost 3 extra bytes. Or actually returning by value like `T f(T a,T b){return a+b;}` costs an extra 5.
`typedef _BitInt(960)T;` is one byte shorter than `#define T _BitInt(960)`+newline. The more readable version is 43 bytes:
```
#define T _BitInt(960)
T f(T*a,T b){*a+=b;}
```
Related: <https://stackoverflow.com/questions/61411865/how-do-you-use-clangs-new-custom-size-int-feature>
---
**[Clang provides `_BitInt`](https://clang.llvm.org/docs/LanguageExtensions.html#extended-integer-types) as an extension in older C modes, and in C++ mode.**
# C89 (clang 16), 40 bytes
```
typedef _BitInt(960)T;f(T*a,T b){*a+=b;}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZDBToNAEIbvfYo_NJrdSi0tlRQRDt5MeuSmxlBgYSOdbWQ3QhqfxEsvvfss3nwbtw0XnctM8s38f_75POZNRtXXI5xpq4u4IrMKHTwfjkaL6eqH6X5XFqXAy73UD6RZGHg8jQRLJ5mbYsP3k-wq3kQfw_73WFLemKLEnZWT6rpORpI0tpkkxvcjIEWHGF7ne34YAbMZ5gt_eXMm_ZmIf2XW68hiwS47Fz0_zYZaWVFZoFFUQShlDzskCYLlCe_erKdgTqPesUBeG3ptoQR0XaI121tcjOdB0z3poZPjgv3R5NbKylqzIdlh-Mgv)
With default options (I think `-std=gnu11`), clang 16 requires `-Wno-implicit-int`, otherwise we get an error: *source.c:2:1: error: type specifier missing, defaults to 'int'; ISO C99 and later do not support implicit int [-Wimplicit-int]*. (And yes, in clang it's an error, not a warning, even without `-Werror`.)
But `-std=gnu89` or `c89` is allowed "for free" without having to count those compiler command-line options as part of the size of the answer. (I think? I can't find the relevant meta Q&A.) This feels like bending the rules because I'm using a very recent clang extension, but is arguably not breaking them. It compiles to the same asm on [Godbolt](https://godbolt.org/#z:OYLghAFBqd5TKALEBjA9gEwKYFFMCWALugE4A0BIEAZgQDbYB2AhgLbYgDkAjF%2BTXRMiAZVQtGIHgBYBQogFUAztgAKAD24AGfgCsp5eiyagA%2BudTkVjVEQJDqzTAGF09AK5smIWU4AyBEzYAHKeAEbYpCAATOQADuhKxPZMrh5ePvGJyUIBQaFsEVGx1ti2KSJELKREaZ7esqXlQpXVRHkh4ZExVlU1dRmNfe2BnYXd0QCUVujupKicXEQAnnHYODQA1KYAQsQAksIQAJwAbFqTACoApADMOzQQlwBULOSXm2GT1wDsO6/XaI7O4AETCd2BPxB1y0AEEAPTwzY0CT0QLATboGhbFibJhCAC0ADd0ARMMj3ExmkxNgQlJsFDtaTTnIDgUDyJ93ERmZtnLSiGAuPT0ABrWlbIhIbCbcT0RikTaYdDYJRMIU89wqTZSmWkbBEIkSLjTejcACs/G8XB05HQ3H5Slm8xlgNufHIRG0JumopA5q0hm40n4bBAt1uADoIzHY3HTuRrbb7Vx%2BEoQIGvTaTeQ4LAUBg2HEGJFKNRC8WFWhUEYTDxzoGcESCAsAGoEbAAdwA8mtrR66PQiJF0xAwt7yGFAtVltwPVPWKRlt2wroylmPYWOMJu0x6LPs%2BQcGF3MBnKj07x%2BDg2MZgJJD4R9eUiaqJ9h1GVuYsPYFh2bDzRMJSBnVwcAnIhSAIMMr2mGgjGAJR2y7XtmDnfhBGEMQJE4GQ5GEZQ1E0Q99FiWszAsQwCDCdNIGmdA4jsIRLwJAB1VFNjYj9INxAluyUfh0FfUgoJwWiIGmJomO8CAnAGbweHIfxRgKIoDASJJpPk9TsmkjpVO6RSpIqYZtKM7AbGk1oan0rooiM0y3HqAwlGGWzxnsyTnQWKRTQtK0JxTTZ1AADlOAlTmkWVyM2etIy0eLNggfBiDITY3R4SZ%2BCzHRJmmaUWBwKIJKDLgQ3IMMI2jOMaojBMk0E7g0wzT1vWmPNkBAWYiDibkywgCsS1IYJ2EWULwsi6K71i054vi/h1lS0SDEw0Q5Vw2RVsIjQJ1I8hOxAuJ0L8rhLUTQLuG7blep5LFgrCiKopraa4oSrQktcIshvS6JbimbK2pO8rKqjWravOw8U2azNAfIP0A1K24AshprWuzdrEA6iAC3QL6FX6waq1QZ66wbI9sGbNsOx7Pt0IEBhh1IUdx0PBcZzptmlxXNdbDprdmCIXd9wnY9T3PeVLw9G87wfW0n3XAhX0vW0Py/Yc6b/CyJyAkClzAxZbUg6DjoEBCkOp1D%2Bww%2BRsMkPCtpUHaSIMciQHMUxLCA8T6MYlIWNczBQWAJh3BC45OPY%2BUI%2B4kDOP4wThNEt86KsCyFYcWSmBcJyMkU5T8jsnTNJSMysmL3IVML8zLJMtpS%2BMlo3MrjyXMc9IFN6Np3LUzKZjmHze4As6Grtbh7omp6YtexLksIEhFQyrK0dy/LsEK7oSr9HgtEDADgf9Y5I1Oc0fj%2BrQQp%2BaJoh%2BaQ8JHqGrBanKcyxlBupugnccrSIRo4bhxsepsYAxNYpRmiAtOeZAyQrRtutKQm15DbWIrafQikDosCOrBUqw8LpcCuj1bkmItgAMmiTDE093oQE%2Bt/Bev1MoA3RkDUMPgEq3GkNEU4Pxjg8Gvpfc0YUIbJlRumGGjC4b%2Bl3twJGgjGqpmXj6Uq4CZGjzkc/PK5BhJJAcNIIAA%3D%3D%3D).
# C++ (clang 16), 43 bytes
```
using T=_BitInt(960);void g(T&a,T&b){a+=b;}
```
C++ `using` is shorter than C `typedef` or `#define`, but falling off the end of a non-void function is UB in C++, not just if the caller uses the result. (`void` didn't exist in the early days of C, but existed from the start for C++.)
With `T` as the return type but no `return` statement, clang `-Os` emits zero instructions (not even `ret`) for the function. With optimization disabled, clang emits a `ud2` (illegal instruction) at the end instead of `ret`. ([Godbolt](https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAMzwBtMA7AQwFtMQByARg9KtQYEAysib0QXACx8BBAKoBnTAAUAHpwAMvAFYTStJg1DIApACYAQuYukl9ZATwDKjdAGFUtAK4sGErgDMpK4AMngMmAByPgBGmMQgAKykAA6oCoRODB7evv5BaRmOAmER0SxxCcl2mA5ZQgRMxAQ5Pn5cgbaY9sUMDU0EpVGx8Um2jc2teR1BChOD4cMVo4kAlLaoXsTI7BxeGUYA1AAqJgEAIgD6FoQAkoIQAJwAbBqrZxYAbqh46IfAEFOZmeTFIx0OMXeAHYLExrGdzjEPiYoecTBoAILojH7cLAE4I653B4vN4fcFUQHmEFg6mQlEWYiYAhbBiHOGWJEBKyo7HY3FHU4XIkEe4EJ6vd7c8EIKnA0FA570mEcqwXLk886HQ4Aeh1hy8DCwNAifziCCYnycW1I7KNh3QqEwCgYYA4BEOAHcSABrQ7hQ4pYhMOo7Q6YT6MdkegC0AHkNIcQAb0GYOOtaJxErw/BwtKRUJw3PDLIcFJttphDuYAjxSARNOn1j6khp9JxJLwWBING3c/nCxxeAoQG2G3n06Q4LAYIgUKgWCk6PFyJQ0IvlwlkAYjFxXm2sFadgA1PCYT1xlKMTh1mi0AjxEcQGKN0gxcJNACeN947%2BYxE/OMYm0Wpxzrdc2EEOMGFob8J1ILAYi8YA3DEWgR24XgsBYQxgHEeD8CZOpIww/NMFUWovAfH9yEEbpX1oPAYmDACPCwV8CGIPBu0w9YqAMYAFFPc9L2vTCZEEEQxHYKQJPkJQ1FfXQuH0XCUBLGxGJiEdIHWVAUl6DCYzmdAEWABgvA0swYkOeMzFsgB1NDHPIzimF4VBI2ILisB0iB1hqOpnAgVwpnaYIjSGcpKj0QpMgEMLYvSeKGCikYEhUwLen6SZPDaPQsvqeY0uWDLxgGRLMuKxZotGLgAorHYJAzLMc1fQdDlUAAOZ4Y2eSRDm3XDDj3AA6DRxsOCBcEIEhqzMWtVl4cctFWdYEEwJgsASfzSBbLhe3bDhO1IbsAkeUaoShLhEkkKEzEkLquC6swoWeUh%2Bw8zhh1HetG3Wac502AgUio1cIHXJd6GISJWF2brev6/5kGQEaAlGtNgnwIgfL0fhJNEcRZPx%2BSVHUeDlNIT1gxSH8Wo4bMPvazg4yo0GPVQKhOp6vqBqGo4xomxMIA8Ddofmxblv%2B%2BmTu7Z7RseLr7qhSRHgCRJax6xJ3s%2BgtvtsX6VsnQGICQSHN3B83oZQHdgD3Q7DzwE8zwvK9c1vOgH2IJ8X3gv8vxo/2AKAkCHBoiDGAIaDYNfRDkNQ2h0Jo7DcPw/NCNAvASNfcjKOo8TwgfTN4K0ljPzY3Z8047i6b4AShJd0T3d4EmpKJ6QScUMmlJAMxVKMdTLGsfQmL8vSDKyIyTLMiyrJs%2BNExjJzE5c1Q3I8ryfOdeAAu6TPgtCvLpgi9ASpilS4t6SrUmS3oz7qroeiKiqj/CwqBByhYynSgr5mvuYBj3wyg1LYTV6pHUZrrDqCNeaDVtiNZ441JrTWxnNGs9UpYTjWkdWWIBJBcAxvgrgV0nr9UVokLqTN4KDh%2BmOaWe1WxHQCG1ah%2BsjbYOLpjKBbD6FeQyM4SQQA%3D))
`using T=_BitInt(960);T g(T&a,T&b){return a+b;}` is 46 bytes.
Taking both args by reference is probably better for efficiency in the caller. In the callee, clang still saves enough call-preserved registers to load a whole arg into registers, instead of working on a couple chunks at a time. And that's just addition; things get really hairy with division or multiplication. (But unlike Clang 14, division is supported for big `_BitInt` types, both by small constants and by other variables. Clang 15 dropped the max bit width to 128; Clang 16 widened it again.)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~49~~ 44 bytes
```
O#$`.
$.%`
¶
M!`..
.
$*
+`¶1{10}
1¶
%M`1
¶
```
[Try it online!](https://tio.run/##HY2xrQJBDERzV3FfcNIXSCuP7d21i0AENLAEBCQE6GdftHUF0NjhI7Asz7wZP29/98d1nX8vYyrTet7tR6F9mQe9F6LTzyiFUjjQcbwX/INfhHTm08BGrCvQfDpODAiJgqGq39urhzmJSZhYNTZLHa1rhEHclELDxZolqHCv6YcyR7dosS3t5FrZpTZhzmDyHJJcN2TG8vm3nTt6ELqiJaUBqNSu7FsLkpcAs4c01RyECNcsjQ8 "Retina 0.8.2 – Try It Online") Takes input on separate lines but link is to test suite that splits on `.` for convenience. Requires both inputs to be 0-padded to the same length. Explanation:
```
O#$`.
$.%`
¶
M!`..
```
Transpose the inputs.
```
.
$*
```
Convert to unary, summing each pair of digits.
```
+`¶1{10}
1¶
```
Perform any necessary carries.
```
%M`1
```
Convert to decimal.
```
¶
```
Join all of the digits together.
[Retina](https://github.com/m-ender/retina/wiki/The-Language) 1.0 has some support for bignums which does include addition so here's how it would be done:
```
L$`¶
$.($`*_$'*
```
[Try it online!](https://tio.run/##HY2xbQNBDATzq@KDNyTIgMDl8u64PShTAXoHDpw4EFSbC3BjL0oBQZCcHd6/Hz@/X9g/jtdtOS/7Zd3@/9p6Pq7b6bYeTvsOjFw@FwO8OWEg@Z6zpyKbhys8elhE7TEmpYBnsIlKjxEFEpm97qKZZmjo1Thbslt6H25WweJNXtwMVCbq@dtuE1MNkxhFUQC9T1q@LCjeBbOUD7IKcrdeUj0B "Retina – Try It Online") Takes input on separate lines but link is to test suite that splits on `.` for convenience. Explanation: `¶` matches the newline between the numbers, but the numbers themselves can be retrieved via `$`` and `$'`. The `*` operator notionally converts them to unary and the `$.(` then converts the sum to decimal, although the underlying code simply sums the two bignums directly.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~78 67 59~~ 49 bytes
```
->a,b{c=0;a.zip(b).map{s=_1+_2+c;c=s>9?1:0;s%10}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY_BTsMwDIbvfYpQBNq0rbLjtI03dTwIoKprMyga7dR0CNj2JFw4wJkLb8BT8DYkG0IcEsfO__22X966zeLp9WPVNjd5UVV1X7eNyN43_XKiv3EyL8aLbZnBrIie6_VgMYzui_XWZjmOcjkqZ2Vm53yBU5jZM4T9_hf87ExRrerG2MgU5a2oWrHz6S4QwseoMivTm9xulsv68WQQXjXh0P0VY7EQ2VFi16u6H4RiJMJDV7Hd2b7bCXdF5W3RWV8cnE_7Nq-HUWceTGfN3pmsN70V4enWu-ydm3v93-7SN7mO7tq6-aPCwDTVcfbX7y_ERLu2gCgDSQhIRIdcx5qVDqSSrKSKFSjl6pikxKxQakUBMLGWKlFOSah17EEmAE4VJ-wDpQFoikHLOJEAjnUEsPTKVKHDlBvg0AFSTDnAlDBxMmJEknFKoL0POkAyAmiWCZE7yFJC7Fz5uMsP)
My first Ruby submission! This is probably a little golfable but I'm pretty happy with it considering I have almost zero Ruby experience. Suggestions are welcome!
Implements long addition on two lists of digits in reverse order padded to the length of the output with zeroes, and outputs a list of digits in reverse order. Explanation:
* `->a,b{...}` Proc (anonymous function) taking parameters `a` and `b`
+ `c=0;` Set the `c` (the carried digit) to 0
+ `a.zip(b)` Zip `a` with `b` to get a list of pairs of digits
+ `.map{...}` Map each pair of digits to
- `s=_1+_2+c;` Set `s` to the sum of the two digits and the carry
- `c=s>9?1:0;` Set `c` to 1 if `s` is greater than 9, or 0 otherwise
- `s%10` Return the ones place of `s` by taking it modulo 10
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 63 bytes
```
f=(a,b,c=0)=>(c-=~a.pop()+~b.pop()+2)||a+b?f(a,b,c/10|0)+c%10:a
```
[Try it online!](https://tio.run/##LZDrasJAEIX/71PkT2GXxDiXvU1L2gepUtcYpUVM0FIUxFdPN2kXljk78505sF/pJ13a8@fwvTj1u24c941O1bZqGzDNq24XzSPVQz9oUz62/4LM/Z7K7dv@j1wi3MGU7RPCcxpfNog@FmUBiKSIEZCZ53d0UWxUZEksWWfB2txHH1jEIkXLSlgiWW8zyBijy3NhAAlWvEyFg4rsIJLzBJCNmQehzAWL2WNz@LwdAgZRCNOZUmahMDD67GJBZHKBIU5bMRMkmYlCnjlfFCJwOUQ29bkbjqnttFrq1a40xaosZrE8VIX@qK7VLX9V258u/bGrj/1B7/V7XdfXdTWV29oYM/4C "JavaScript (Node.js) – Try It Online")
no bigint
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~73~~ ~~69~~ 58 bytes
```
c;f(*a,*b,n){for(;n--;c/=10)a[n]=(c+=a[n]+b[n]-96)%10+48;}
```
[Try it online!](https://tio.run/##bVLLbtswELznKwgBBiRbQrh8E6p7KXrLH8RGQTFUalSRDctF3Br@9bpLPVwnqQCRy@XM7HBJX/jGtc@Xiy/rdO7yeZW32ane7tOyLYrS3y@BZu6xXS9Tv1jGYFHhUFiVzYAuhCnPl017IC9u06YZOd0R/DAxJ4fQHb65xzVZYub0kAAok@TkIWEcKHDOh4VgVjAhBRWiT1DLrWFCCWMFB2PkkDVcUsOkYpRyaxFBLet3QHNQmOIWgDOpOTXUagHJuXznpfrnhQIMbApGYqHBGCiNQgKYEXzyQqOYVTZOXA9ZVEdrAs/TW6catB0OY4FSY5niHH@wjFGJlu0bL@G4C/4Qnno3sS/M0LEVVlFmoF8IoFyAUcqYoSrGFgVBSCOZ5Ww8vdRKArfamNg1bBrTo4ASoJlllAluI4oZJbmmkxe/bbsD8d/dfo5j8D/CfnCUrI5f2epov@Afm3@75hMbHwhJ471v2qdwRBotx/AT6Ta/w7ZOp3Nm92Nifs2UZLHo0VkvNjyaa4Mcyo2Ppwety9t90oQWAa@@wyB1WfmWXP2sa9z2rmm2Po3YBYGciBscUv3uVxqROfkoMFWvPlSvR06VRxPviQGJ17v9n/Gd67rBuX/ZjVIhI8vYvCtwt0donSazpkPncSw@99OsW7V4G64vP5Cna4vC6xs79T6EXn/Mne/Olz@@btxzdyle/wI "C (clang) – Try It Online")
*Saved 4 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)*
*Saved 11 bytes thanks to [Peter Cordes](https://codegolf.stackexchange.com/users/30206/peter-cordes)*
Inputs two wide-charater strings, padded to the length of the expected output.
Returns the sum in the first input string.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
PS¶S¶Wⅈ«←P←⮌IΣEKD³↑Σκ
```
[Try it online!](https://tio.run/##fY1LC4JAFIXX@SsGV1cwmEc@Rpe1CRIkCVq0EbnloKnoaIvot09m0LIDF@4534FTlHlftHltTDLWWnW9ajTsm27UmZ7/GzhObKVLal8a@2f@Vh6lqpHAeSbkaa2SdkKIDnjVM1stO9/6krnkiBP2A8I2HzRk4x2SvIMUsdqpHgut2gaES6JT57jkgytnUWy9jGGBYL6QUkjGBPcCQUMqgw2zuGSUhpL7QszHJOfU83wuzXqq3w "Charcoal – Try It Online") Link is to verbose version of code. Takes input as two strings of equal length but spaces can be used for padding and outputs the input strings and their sum. Explanation:
```
PS
```
Write the first string to the canvas without moving the cursor.
```
¶
```
Move down a line.
```
S
```
Write the second string to the canvas.
```
¶
```
Move down another line.
```
Wⅈ«
```
Repeat until the cursor reaches the left column.
```
‚Üê
```
Move left.
```
P←⮌IΣEKD³↑Σκ
```
Overwrite the current character with the sum of the column, overflowing any carry to the left.
[Answer]
# [Perl 5](https://www.perl.org/), 84 bytes
```
sub f{($x,$y,$c,$s)=@_;$x|$y?f((map{s/.?$/$c+=$&;''/er}$x,$y),$c>9,$c%10 .$s):$c.$s}
```
[Try it online!](https://tio.run/##VZNRb9owEMff@RSnzBtxyYjPdmKbNKWatIdp2ip1e2urKtDAskKggWpEjM/Ozon6sIfknLv//3dn6bItm1VyPu9eZ7A4huwQsTZi84jteH79mLHDX9ZOF2G4LrbHXTyespjNRzn7kA2HcdmcOj0nw5Wj13sUMCbnhM0pnM7vdk1RP4XIs8G6BVY2TS6ywWLThAOAEDwT1u11kdMJqnof9vIy5TzC8RhFxoqcFXfiIWOz/PemqoMgui7uqOYespAVEZvxPGSziBUcqgWMk0uPyAJWAJtBMA5n1bIiIR/1hxnnJ3JLATyiGXbbVbWP7@s4urwMAn6kFABiamEEAlFCDiit6NJSoUClVFeyiXXaUllqlwppsZdo6bTUiRZakwxTo5zTRNCKpBqF0mjT1FrTyZ1yVupUE0qhtQlZnBLCGWI6H5TxA9jUOSlRJzaRTknZea1KhJVJKoWgHsQRTpLfaCSWpht0gwiDxnlGYtIElTPW@pbUUZp@ZDQKUyIoh6hkYpSwvjMSSzoUgpSpUvQgzSASauh5NDQa6aSQWjnPljZNlBEDYq7bty0qD1tO4vj@aRQvs64EbLnZU27Ra/hbdvNMSW@A8qXXTGG4eR7CBIbfb37Czdehl24b2hIIvBwOOTvQBdqctRTIWs735VPeQQAIkXvOfR14o9@90civiPfWZQfPBqdBT/Rl6hhcXFx8vr29uf0x6VJkpgGCYrWCzXNH8r@J3yQ4QlO@vFZNCd@K/a/J5FO1/FLvs/@@Pl7V5Z@QPdL@cjid/wE "Perl 5 – Try It Online")
[Answer]
# [R](https://www.r-project.org), 30 bytes
```
\(x,y)c(0,z<-x+y)%%10+c(z>9,0)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bc9BSsQwFAbgfU4RkMKLbTGpg4zFeADPIJbQtDWQSWfaZEjnKm7qwlMI3mNu46t14YDZvBDe__Hn7X2Yz5_G-cr3lW5qs1O20qYzfpRatsHV3vQOYmal7TvBIbJUsKE5QkxuEsFfQJQ2FyzBOyOXwEKi_EdhY9hBvF5itnGdf8WnUmCcEXJFjdsHT9VIm0NQNl836LGpfT-MtG_pL09XviRKa_kRfJtvv56x4sRq4NnpIY_p9FMoreH0eJ9xti6dn6IUxe2GTLLY3G0FJ6AcfvO_0oA2aEQLzjIN0zLxEKSlxNQqzvM6vwE)
Input as vectors of decimal digits, padded to the same length with leading zeros (or [27 bytes](https://ato.pxeger.com/run?1=bdBdToQwEADg955iEkPSyhIpbsxKUg_gFfwhDS3YpNsqlLVwFV_wwVN4kvU0DuLDmtiXmbQzX2b69t7Nxy_jQhV8pXRt9tJWyrQm9EKJZnB1MN7RuLHC-pbnNLKUs04faEwuEp4_Ul7ajLMEc0b-AguJ8onC-mFP4_nSZrVrwxNelRzbGSFnYNzzEED2oF8GabO1Ag66Dr7rwTfwy8PKw6vBZxnAatkH8E4vmTKuhUl3viRSKfExhCbbfd7jBiOjk4jp-DNrSqeba3aX8Ye14ngbBS8ut2QUxfZqx3NCpcMv-G8hijBVKBY52yg6LhEPQVsI7FrFeV7jNw) if the padding always contains at least one leading zero).
Automatic vectorization of (most) functions in R makes this pretty easy.
---
# [R](https://www.r-project.org), 41 bytes
```
\(x,y)c(0,z<-c(y&0,x)+c(x&0,y))%%10+(z>9)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZBRToQwEIbfOUUTg5kKRLpuzEqsTx7DSJAC26S0hJa15Sq-4IOH2jN4CQd3H9zEp047833NPx-f43L8ltqVzpSiqWVfqVLITjrLBW8nXTtpNPhUcWU6loOnCaNjcwAf38YsfwVWqIzRGGsaXQpWJZr_WKidevA3K6Ya3bk9PhUMcRpFV0TqYXKksuTQ1M6MlpiWnI3kZCTv0u0NDg2VEFJ3KVJ4XbG1Q2Aw1so3FUhf6UDRKJ1Eem5GY4sIIf41uTbbHekLZgq0hjydH7MawnWeYrQaPBaB_uZJYH56oGfg2XO2udtGgW-29zuWR1BpXNF_gQH_AYHRUgGownA-CZzj_Mm1LKfzBw)
Input as vectors of decimal digits, no padding required. Output can contain (possibly many) leading zeros.
---
# [R](https://www.r-project.org), ~~90~~ 58 bytes
```
\(x,y,a=c(0,z<-c(y&0,x)+c(x&0,y))%%10+(z>9))a[cumsum(a)>0]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZBNasMwEIX3OoWgOEi1TaU0lNRUuUPX_TFCsh2BLQVbSuVcpRt30bP0DLlNx00WCXQ1j-G9jzfz-dVPxx9jfeldqStlOtmW2jTGD0KLOljljbMkZq1oXcMZiTTltK_2JCZ3CWfvhBdtzmkCmqJrwIwE8gWFDqEj8XaOtZVt_BZWBYc4RegGG7sLHi-wC34WcsD7SnnXD9jV-IzGJzT-MH4LPryTWhvbFAim-A6-ztfH4hX6jpkUirDs8JQrMi5YBsUViSBG-tc2JYfNI6XyRYVuriXphr2dCc9R8OX9Co1iuXpYczbTiYaymSYQR9LCd_67lVwbKYrpKATYT-BpOs1f)
Input as vectors of decimal digits, no padding required. Output has no leading zeros.
[Answer]
# x86-64 machine code, ~~10~~ 8 bytes
A function that adds two little-endian binary Bigintegers of the same (non-zero) length, updating the destination in-place, using add-with-carry as a building block as it was designed for this.
It takes 2 pointer args and a count of how many 32-bit chunks, like `add_bignum(uint32_t *rdi_dst, uint32_t *rsi_src, size_t count_rcx)`. (That matches the x86-64 SysV calling convention if you use a dummy 3rd arg to fill the EDX slot.) The same machine code works in 32-bit mode, since `lodsd` and `stosd` work with whatever the native pointer size is.
It returns CF = carry-out from the top element. (If you want that to be part of the output, zero-extend the inputs with an extra 0 element at the top, and include that in the count.)
```
; NASM listing: machine code | source
add_bignum:
F8 clc ; CF=0, no carry-in to the bottom.
; Peeling a first iteration using ADD would cost more bytes
.loop: ;do {
AD lodsd ; eax = [rsi]; rsi+=4 without affecting FLAGS
13 07 adc eax, [rdi]
AB stosd ; [rdi] = eax; rdi+=4 without affecting FLAGS
E2 FA loop .loop ; }while(--rcx);
C3 ret
```
---
Add-with-carry ([`adc`](https://www.felixcloutier.com/x86/adc)) chains the carry-out from the top of one chunk into the carry-in for the next chunk. As the loop iterates, it's like one wide [ripple-carry adder](https://en.wikipedia.org/wiki/Adder_(electronics)#Ripple-carry_adder) over the full width of the arrays. (With carry-lookahead or whatever optimizations exist inside the CPU's ALUs happening within each chunk to run it with single-cycle latency. But as far as the result is concerned, it's like one long chain of full-adders, with the same hardware reused by software feeding the carry-out of the last instruction to the carry-in of the next. Carry only propagates from low to high in both addition and subtraction. It doesn't matter what element-size you use for it, as long as you get all the bytes of your bigints and chain the carry correctly.)
Bigint performance notes: the `loop` instruction is [slow except on recent AMD CPUs](https://stackoverflow.com/questions/35742570/why-is-the-loop-instruction-slow-couldnt-intel-have-implemented-it-efficiently), where it's actually really handy for loops that want to preserve FLAGS. It's too bad Intel didn't make it fast. Normal bigint loops on Sandybridge and later use `dec ecx / jnz` which leaves only CF unmodified, because Sandybridge has cheap partial-flag merging instead of stalling. And Broadwell and later don't merge at all; uops that want both parts of FLAGS just read it as 2 separate inputs, which is why `cmovbe` and `cmova` are still 2 uops while others are down to 1 uop. So the bigint looping problem has been solved that way, [unlike on older P6-family CPUs](https://stackoverflow.com/questions/32084204/problems-with-adc-sbb-and-inc-dec-in-tight-loops-on-some-cpus) where partial-flag stalls are a real problem.
Also, for performance, memory *source* `adc` is better on Intel CPUs, with a separate `mov` store. (Fun fact: memory destination `adc` has an extra uop beyond what you'd expect because of arcane microarchitectural reasons involving lack of TLB coherency across the uops of one instruction, [according to Andy Glew](https://stackoverflow.com/a/32258855/224132).)
Also obviously using 64-bit operand-size would go twice as fast as 32-bit, or 8x as fast as bytes, for the same number of bytes. (Instruction fetch/decode isn't the bottleneck on modern CPUs with a uop cache, so the code-size differences aren't very significant for a hot loop). That costs an extra REX prefix on most instructions so I didn't use it in the initial version with 32-bit elements.
**TL:DR: un-golfing this code to something that performs well is more than just the obvious changes.** (Especially before the last update.) Look at the hand-written asm in GMP for production-quality example. (e.g. <https://github.com/sethtroisi/libgmp/blob/master/mpn/x86_64/coreisbr/aors_n.asm> is the add-or-sub template for `adc` or `sbb` loops for Sandybridge-family. It uses some `jrcxz` instead of just `dec/jnz` at the bottoms of loops, but I think the main unrolled loop uses `dec/jnz`.)
---
A previous version of this answer used memory-destination `adc [edi], al`, having to use byte operand-size instead of dword so we could use 1-byte `inc` in 32-bit mode. Thanks @m90 for reminding me of the standard lods / stuff / stos pattern which has the added bonus of allowing memory-source `adc`! My comments below are about why that 1-byte version was so inefficient:
Normally you can use `scasd` to increment RDI by 4, as long as it's a valid pointer, but that does a compare as well as load which overwrite FLAGS, breaking the chain of carry propagation through CF. Some shenanigans like pointing ESP at this array and using 1-byte `pop eax` then `adc [esi], eax` and a dummy `lodsd` to increment ESI might work, but would probably cost more bytes than `lea edi, [edi+4]` (and a signal handler could clobber the array). Maybe we could expect our caller to pass one of the bigints by value on the stack. And we'd still have to push the return address back again.
So ~~definitely the smallest~~ (and lowest performing) is to use 1-byte "limbs", making the pointer increment a single-byte (in 32-bit mode) `inc`, which sets the other FLAGS (all of SPAZO), but not CF. Other code can process the same bigint in larger chunks; **the limb size is only relevant to the count the caller passes, not anything else about the layout.**
[Answer]
# C, 54 bytes
Binary bigint using 8 bits per `int`, in little-endian limb order. Carry-out still fits within an `int` where we can get it with a shift. `void f(int *dst, int *src, int n)`. Updates the destination in place
```
x;f(*a,*b,n){for(x=0;n--;*a++&=255)x=*a+=x/256+*b++;}
```
[Try it online!](https://tio.run/##VZDhaoMwFIV/16cIHR2Jua5qazuauhfpZMQYu4CNRVOQia8@l7jKuvw43HP5uPfkikBUXJ/HsWMl9jn4OWjSl3WDuzRkOgiYzyl9TuMkIV1q67Rbx8mO@jmlbBiflBbVrZDo2JpC1S@fb57SBl240pig3ls4Z2RrPvgpQylCqI/AauxkehvYQgI72A/sgc4faLv6TrsqhAj2EM207K5SGFlMfB8DjqmLurIZwc52k6MNvM64tlSrvmRd4t9UZP3PnsKMWHS2cE8DSE/tukHYjVH2NuqomaKU2E8uro3tlnjJhbnx6jCHOqBVgZy86yXMZ1AZ/KVW07rBG8ZvUVb83I4/ "C (clang) – Try It Online")
Iterates over the arrays, `a[i] += b[i] + carry_in`, truncating dst elements to 8 bits. `x` = un-truncated addition result, so the carry-out is in its 9th bit. It's non-negative since `int` is at least 16-bit, so we can do `x/256` = `x>>8` to get it as a 0 / 1 integer that has the right place-value for the next limb.
9 bits per limb would still cost the same code size (`&=511` and `x/512`), but more bits would need longer constants. I picked 8 because it's a round number, and easy to pack down to bytes to avoid the wasted space. (Making it a plausible format for larger code-golfed programs that want to use this.)
On a 64-bit machine with 32-bit `int`, this supports numbers up to `8*(2^31-1)` bits wide. That's vastly larger than the required 10^256 which only requires 851 bits. I could have used just 4, 2 or even 1 bit per limb to make the constants even smaller. Or 3 bits per limb (`&=7` and `x/8`); it doesn't have to be a power-of-2 number of bits. Using up 4x the amount of space seemed more reasonable than wasting 31x the amount, and more plausible for code converting to this format.
---
Real-life code uses this technique, but with 30 bits per `uint32_t` for example in CPython, since they avoid using hand-written asm for more efficient bigint on machines that have a carry flag. (See my [codereview answer](https://codereview.stackexchange.com/questions/237690/bigint-class-in-c/237764#237764) discussing BigInt implementation techniques, that using base 10 is highly inefficient, although base 10^9 in 32-bit chunks is good for efficient conversion to/from decimal strings, as in [Extreme Fibonacci](https://codegolf.stackexchange.com/questions/133618/extreme-fibonacci/135618#135618) code golf.) Multiply uses stuff like `a * (uint64_t)b` as a widening multiply.
Partial-word bigint formats (not using all the bits per chunk) also allow deferring carry for SIMD implementations ([as Mysticial explains](https://stackoverflow.com/questions/8866973/can-long-integer-routines-benefit-from-sse)), but that requires writing code that's aware of it.
C sucks at exposing add-with-carry or sub-with-borrow, especially carry-*in* to the same element where you want a carry-out. No portable functions for this, so it's up to compilers to recognize some idioms, such as `carry = (a+b)<a` for unsigned types. Or there are non-portable intrinsics such as for x86, but [those often compile to poor asm](https://stackoverflow.com/questions/33690791/producing-good-add-with-carry-code-from-clang) for more than 2 limbs, or in a loop. But things have improved some recently, with a combination of some compilers getting better at keeping carry-out in the carry flag (instead of materializing a 0/1 integer in a register), and [a way of writing portable ISO C source](https://stackoverflow.com/questions/4153852/assembly-adc-add-with-carry-to-c/75759422#75759422) that actually gets clang to compile to a chain of `adc` instructions on ISAs that have a carry flag.
This version is of course optimizing for source size, not performance or storage density.
[Answer]
# [dc](https://en.wikipedia.org/wiki/Dc_(computer_program)), ~~4~~ 3 bytes
```
?+p
```
[Try it online!](https://tio.run/##DcOxEYAwDAPAVehpLAnbUcUwMED2bwx/9@8zc597Bi2UbBkQsxUr3BcOGhHLLOkPk5FZ9Ac)
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 12
```
{print$1+$2}
```
[Try it online!](https://tio.run/##HY0xCkJBDET7PcUWdjaZTHY3cxxLEUREsBDPvuZbhGHgzcvlfdv783he768Tzif/7g3M7AZ4c8JAslqOVGTzcIXHCIvomItSwDPYRKXHjMKIzNFFM63Q1BFcLTksfUw3q1nRJu8rUHzUy7/XFpYaFjGLoQD6WLQ8HOgumKV8knWQu40S6gc "AWK – Try It Online")
] |
[Question]
[
Let us define the *"multiplicative deltas"* of values \$[\; a\_0, \cdots a\_N, \;]\$ as:
$$
[\; a\_1 / a\_0, \cdots, a\_{i+1} / a\_i, \cdots, a\_N / a\_{N-1} \;]
$$
The reverse operation - namely *"multiplicative undelta"* - returns values such that the above operation results in the given values.
### Example
Given values \$[\; 1, 5, 3, 2 \;]\$ a general solution to the "*multiplicative undelta*" operation is:
$$
[\;
a\_0,
\quad \underset{a\_1}{\underbrace{a\_0 \cdot 1}},
\quad \underset{a\_2}{\underbrace{a\_1 \cdot 5}},
\quad \underset{a\_3}{\underbrace{a\_2 \cdot 3}},
\quad \underset{a\_4}{\underbrace{a\_3 \cdot 2}}
\;]
$$
A particular solution can be obtained by setting \$a\_0\$ to any value other than zero, for example by setting \$a\_0 := 1 \$ we would get:
$$
[\; 1, 1, 5, 15, 30 \;]
$$
## Challenge
Your task for this challenge is to implement the operation "*multiplicative undelta*" as defined above.
## Rules
Inputs are:
* a non-zero value \$a\_0\$
* a non-empty list/array/vector/... of non-zero "*multiplicative deltas*"
Output is a list/array/vector/... of values such that the first element is \$a\_0\$ and for which the "*multiplicative deltas*" are the input.
**Note:** If your language has no support of negative integers you may replace *non-zero* by *positive*.
## Test cases
```
2 [21] -> [2,42]
1 [1,5,3,2] -> [1,1,5,15,30]
-1 [1,5,3,2] -> [-1,-1,-5,-15,-30]
7 [1,-5,3,2] -> [7,7,-35,-105,-210]
2 [-12,3,-17,1311] -> [2,-24,-72,1224,1604664]
-12 [7,-1,-12,4] -> [-12,-84,84,-1008,-4032]
1 [2,2,2,2,2,2,2,2] -> [1,2,4,8,16,32,64,128,256]
```
[Answer]
## Haskell, 8 bytes
```
scanl(*)
```
[Try it online!](https://tio.run/##dY4xDsIwDEV3TuGBoUX2YBeUqScpHaJAoCKEqOH8ddMxKsjbe19Pftr8uoegvr9qdjaG5tTq204Rerh9DgBpnuIXjuBBYBAeK8QwMF6wQ6l5Q9z@UWbj9EOUPLEUTmyQO@ZdUkrTFI3b7rz7RLC6URfng31kJZfSCg "Haskell – Try It Online")
[Answer]
# APL(Dyalog), 3 bytes
```
×\∊
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//8PSYRx1dMFrBSEHDyFCTC8ozVNAwVDBVMFYwggsBFRxab2gEFANS5gqGxoaGmgA)
If I have to take the number on the left and the array on the right:
*-2 thanks to @H.PWiz*
**~~7~~ ~~5~~ 3 bytes**
`×\,`
[Answer]
# [R](https://www.r-project.org/), 15 bytes
```
cumprod(scan())
```
[Try it online!](https://tio.run/##K/r/P7k0t6AoP0WjODkxT0NT8785l6GCrqmCsYLRfwA "R – Try It Online")
Full program. Function is longer (unless we were allowed to "glue" the inputs together, so that built-in `cumprod` would suffice as a complete answer):
# [R](https://www.r-project.org/), 28 bytes
```
function(i,x)cumprod(c(i,x))
```
[Try it online!](https://tio.run/##Zc7BCoAgDADQe1/h0cF22Cy89DeG0CENSejvTSuKiMHY3hhbKn6k4nNw2xyDnnEHl5c1xUm7s4PitaAShs5rRuVqGtCgQAP6ib2AXpEmxFKB2CIb5nv3nNiq2OoenhOCn6hPHA "R – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
hYp
```
[Try it online!](https://tio.run/##y00syfn/PyOy4P9/Q65oQwUjBWMF01gA "MATL – Try It Online")
```
#implicit input, x_0 and A
h #horizontally concatenate
Yp #cumulative product
#implicit output
```
The `hYp`e about MATL is real.
[Answer]
# Python 3, 39 bytes
```
def f(a,b):
for x in[1]+b:a*=x;yield a
```
Alternative approach. [Returns a generator.](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753)
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI1EnSdOKizMtv0ihQiEzL9owVjvJKlHLtsK6MjM1J0Uh8X9BUWZeiUZOZnGJRpqGkU60kWGspqYmF4qwoU60oY6pjrGOEaacrqGRgk60uY6uIRAZ6ZiAVPwHAA)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 14 bytes
```
FoldList@Times
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d8tPyfFJ7O4xCEkMze1@L@Cg4NCtbFOtZEOFNbWxv4HAA "Wolfram Language (Mathematica) – Try It Online")
`FoldList[Times, a0, {x1, x2, ..., xn}]` produces the desired output. `FoldList[Times]` is the curried form that produces a pure function still waiting for its `a0` and `{x1, x2, ..., xn}`.
[Answer]
# JavaScript (ES6), 27 bytes
Takes input as `(m)(a)`.
```
m=>a=>[m,...a.map(x=>m*=x)]
```
[Try it online!](https://tio.run/##fZDRbsIwDEXf@Yo8ttNNiN006Uv6I1UeIgYIRCmCaeLvOxdNaO3YEtuKZJ2bax/zZ75trofLhz4P79txF8c@tjm2XQ9jTDZ9vhT32PZv8V6mcTOcb8Npa07DvtgVSnFZdExJ/TxlqdZr1TEcp9USIAEINSpwWgCEqUHSs784/Q@nCVPUUiVfwCo8YD2jv@GAIMzEWilML@hpRk0ssKYAqkjmfc6o2UEHBrE8yFvnvVtKCCwS4eFSdFyauxeRxkFCPNgG2tnqj8UxZjc9FyeiaOR7VAwvPrgB1z6NXw "JavaScript (Node.js) – Try It Online")
[Answer]
# Japt, 3 bytes
```
å*V
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=5SpW&input=WzEsLTUsMywyXQo3)
---
## Explanation
```
:Implicit input of array U and integer V
å :Cumulatively reduce U
* :By multiplication
V :With an initial value of V
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
;×\
```
[Try it online!](https://tio.run/##y0rNyan8/9/68PSY////6xoa/Y8219E1BCIjHZNYAA "Jelly – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 9 bytes
```
{[\*] @_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OjpGK1bBIb72vzVXcWKlQpqGrqGRjkK0uY6CriEIAzkmsZrW/wE "Perl 6 – Try It Online")
[Answer]
# [Standard ML](http://sml-family.org/), 32 bytes
```
fun f(x::r)a=a::f r(a*x)|f&a=[a]
```
[Try it online!](https://tio.run/##dZDLasNADEXXyVcIL4od5GDJ4wcOzr67QhdduA4MAbeBeBySaUmh@NddTfMgwS3zRLrnjkaHdhu2W9uZYWg@DDT@sSj2gS51UTSw9/XsGHw3D7qsdD186i20X0/7jbFQwu737MBvDBygXIJXebCS6wq8@tV4geSerYje5uvOrLV92dh38NCTeKt38Gjs3HYnxWI6vRj7DVRMNXCwmEwm/gzCpQRQcQ2z4E5FmGCMEicnPSsJXZgkE/0P9LdESOhmIrusP7H@zGU3WIaZqB0VycY05npiwXrKkGK6/Oj6oZAVhhkjsVwojVSaqpFFJjg6H@WK5ruqxSJXKFMqiHIMVRSPe8R4N069urZKfDGXxzFmTKUKzpGT1JkMPw "Standard ML (MLton) – Try It Online")
**Ungolfed:**
```
fun f (x::xr) a = a :: f xr (a*x)
| f _ a = [a]
```
[Answer]
# [J](http://jsoftware.com/), 6 5 bytes
-1 byte thanks to Bubbler
```
*/\@,
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F9LP8ZB578ml5KegnqarZ66go5CrZVCWjEXV2pyRr6CkUKagpEhhG0IZBsqmCoYKxhBBOIxRMzBAvFIIiAD4g2NgALxhuYKhsaGhjC9IBlzkBkgpgnCCiNU@B8A "J – Try It Online")
## Explanation:
A diadic verb, the left argument is `a0`, the rigth one - the vector
```
@, - append the vector to a0 and
*/\ - find the running product
```
[Answer]
# [Factor](https://factorcode.org/), 22 bytes
```
[ prefix cum-product ]
```
[Try it online!](https://tio.run/##bY/BCsIwEETv@Yr5gRQSlYKCV/HiRTyJhxBTDNo2JltQSr@9JhalFncuy9thdrdQmmrfH/bb3WYJFUKtA67GV@aGYO6NqbQJKBVdskCKbCAbDc4boqfztiKsGGsZYrVRUqCDRPcFAgvMEondP8p/Mf/wfIS5kJFykUPMxHRBniKSY/5OG4/kRMMNHeuP6YHCPqCbkjtfnxtNOPXF8P@6VA5Z/wI "Factor – Try It Online")
[Answer]
## Batch, 69 bytes
```
@set/pa=
@echo %a%
@for %%d in (%*) do @set/aa*=%%d&call echo %%a%%
```
Takes input of \$a\_0\$ on STDIN and the deltas as command-line arguments.
[Answer]
# Common Lisp, 67 bytes
```
(lambda(a l &aux(y 1))(mapcar(lambda(x)(setf y(* y x)))(cons a l)))
```
[Try it online!](https://tio.run/##NYtBCoAgFESvMqsagxYW0Xl@ViBYiRbo6c0W7Yb33hhnoy/0wZ6GhU6OZRUKHBp5EjO0UjzEGwm/TIpxu3dkdshIqgbmOiPqqe6CGS01@gkjhg@8)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 2 bytes
```
G*
```
[Try it online!](https://tio.run/##yygtzv7/313r////hv@jDXVMdYx1jGIB "Husk – Try It Online")
This is equivalent to [nimi's answer](https://codegolf.stackexchange.com/a/173538/62393) in Haskell: `scanl(*)`, which means reduce from the left using multiplication, and return all partial results.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~5~~ 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
šηP
```
-2 bytes thanks to *@BMO*.
[Try it online](https://tio.run/##yy9OTMpM/f//6MJz2wP@/9c1NOKKNtfRNQQiIx2TWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/u5ulir6SQmJeioGQPZj5qmwRkFv8/uvDc9oD/Ov@NuKKNDGO5DLmiDXVMdYx1jGK5dJE55iC2LpQDVKxraARk6xqa6xgaGxqCFAMFzYECOiAZE7BJRjooMBYA).
**Explanation:**
```
š # Prepend the (implicit) input-integer at the start of the (implicit) input-list
# i.e. -12 and [7,-1,-12,4] → ["-12",7,-1,-12,4]
η # Prefixes of this new list
# i.e. ["-12",7,-1,-12,4]
# → [["-12"],["-12",7],["-12",7,-1],["-12",7,-1,-12],["-12",7,-1,-12,4]]
P # Take the product of each inner list (and output implicitly)
# i.e. [["-12"],["-12",7],["-12",7,-1],["-12",7,-1,-12],["-12",7,-1,-12,4]]
# → [-12,-84,84,-1008,-4032]
```
[Answer]
# Pyth, 6 bytes
```
*FR._s
```
[Test that one here!](http://pyth.herokuapp.com/?code=%2aFR._s&input=2%2C+%5B-12%2C3%2C-17%2C1311%5D%0A&debug=0)
Alternatively, 7 bytes:
```
.u*NYEQ
```
[Test it here!](http://pyth.herokuapp.com/?code=.u%2aNYEQ&input=2%0A%5B-12%2C3%2C-17%2C1311%5D%0A&debug=0)
The first takes input as a tuple, the second takes input as two separate lines.
Thanks to @Sok for helping me with getting good at mapping and saving 1 byte.
[Answer]
# [Python 2](https://docs.python.org/2/), 40 bytes
```
f=lambda a,b:[a]+(b and f(a*b[0],b[1:]))
```
[Try it online!](https://tio.run/##ZYrBCsIwEAXvfkWOG30Fd1WEgl@y5LBLCRZqLDYXvz5tjyLMaWbmb32@i7SWH5O9fLBg8F4tnciDlSFksqPrOcGV@xRjmz9jqTSNS6VMAhXebDz8aIYybrhA/lvHEqB3dLwhuO5HWwE "Python 2 – Try It Online")
Surprisingly, the move to Python 3 and use of generators there only saves 1 byte over the recursive solution.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 29 bytes
```
param($a,$b)$a;$b|%{($a*=$_)}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRRyVJUyXRWiWpRrUayNWyVYnXrP3//7@hgoahjqmOsY6RJgA "PowerShell – Try It Online")
This assumes just outputting the values is fine.
```
> .\scratch.ps1 1 (1,5,3,2)
1
1
5
15
30
```
If that's not fine, this actually builds the list and then pushes it to toString which prints the same way.
```
param($a,$b)$c=,$a;$b|%{$c+=$_*$c[-1]};$c #41 bytes
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), ~~6~~ 5 bytes
```
\{\o*
```
[Try it online!](https://tio.run/##y00syUjPz0n7/z@mOiZf6/9/Q4VoQx1THWMdo1gA "MathGolf – Try It Online")
~~I think this could be 5 bytes (`\{\o*`) but `\` instruction seems a little off when dealing with input.~~ This is now fixed in the latest version.
### Explanation:
```
\ Swap arguments, pushing both to stack
{ Foreach loop over second argument
\o Output counter with newline
* Multiply counter by current element
Implicitly output the last element
```
[Answer]
# [Desmos](https://desmos.com/calculator), 47 bytes
```
f(k,l)=∏_{n=1}^{[1...l.length+1]}join(k,l)[n]
```
[Try It On Desmos!](https://www.desmos.com/calculator/oymvkmcaku)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/fph597nbql)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 8 bytes
```
{x,x*\y}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxlj8uKwkAQRff5iloPt7Cr+hUMuPUjNIswJJpNRkwWivjvVnygMvTtouk69bjd8nLC6Wd7vhbFgtbt0B6bqR92NLXjRL/N2I7U/R1p2vcjmQ5NPxTdRiuo1LQgXtFGEbS2T6mEInnSV0IgiJAI7+Y8/wNYMCtatPugskH8RWVkS86Qs6Byx7RiUaNYMomXj2VYAzgrRO0hyYWUwmO8Vtl4mgvDewWrKANM1t+V4OD8047S13nbMscorTe8ItkQLaEx1Tc0jkqX)
Another easier-than-I-thought problem. `\` is the scan operator.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 3 bytes
```
pɖ*
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCJwyZYqIiwiIiwiLTFcblsxLDUsMywyXSJd)
```
p # Prepend
ɖ* # Cumulative product
```
[Answer]
# [Perl 5](https://www.perl.org/) `-n`, 16 bytes
```
$b||=1;say$b*=$_
```
[Try it online!](https://tio.run/##K0gtyjH9/18lqabG1tC6OLFSJUnLViX@/39DLkMuUy5jLqN/@QUlmfl5xf91fU31DAwN/uvmAQA "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 47 bytes
```
lambda n,A:reduce(lambda a,c:a+[a[-1]*c],A,[n])
```
[Try it online!](https://tio.run/##bY5NCsJADIXXeors2mpmkVQRBhR6jjGLsT9YqNNS6sLTj9NpEReFhPA@Xl4yfKZn79g317vv7OtRWXBY6LGu3mWdrsRiqe3RWKNIDqVggcZJ5pt@nM3QOjCGEQyTSBi09BkhR@CI1Aa7LEj9M45ejkRRcFBOtCbwsjNHRXH6HQtio0RE73fD2LoJ0vBnhgmoGyTYROW/ "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
IE⁺⟦N⟧AΠ⊞Oυι
```
[Try it online!](https://tio.run/##HcexDsIgEIDhV7nxSI7h7ODg6OSgshMGxCZtgoUcnK@Prf/wJX9aoqQS8xhO1q3jNbaO91jRZW3ob1vV/tDPaxY0geD/aAyBk/LW1NFpW551ltiLoBKs5ugyhj8ReMu7E4HlMwFPzCEM@80/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
N Input a₀
⟦ ⟧ Wrap in a list
A Input deltas as a list
⁺ Concatenate lists
E Map over elements
ι Current element
υ Predefined empty list variable
⊞O Push and return updated list
Π Product
I Cast to string
Implicitly print each value on its own line
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 9 bytes
```
{(*\)x,y}
```
[Try it online!](https://tio.run/##y9bNz/7/v1pDK0azQqey9v9/AA "K (oK) – Try It Online")
Joins the first number to the second input as a list, and then returns successive results of multiplication
**Test Cases**
Enter your input after the function like below and then run, as I'm unsure how to use input properly for this language in TiO
```
{(*\)x,y}[1;1 5 3 2]
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 13 bytes
```
p[*pz1<A]dsAx
```
[Try it online!](https://tio.run/##XZBLCsMwDET3PYWhuzICS3bsLEoh5wghi@YAhW5KL5@O0ph@kH@x9TQTLdf1GEyDBW5hNJ2CXLgj23TwqxS6oIwj56jokGDvHIV/Km/id@rsufKfLAofHVfODzE7UklUB@SLqKhMdCByMSWiSb1@dU6teRY1UqIV/t78i2VINajxoCXmUrKL5g2dXdQPbtVcbDPI3252WaHP4KB@7CE5pr0jv7F3xvATrUMsiJ7ySIZCH9bDujKtt/F0e@p5mJb78FjXFw "dc – Try It Online")
```
p[*pz1<A]dsAx
p # Print the first element
*p # Multiply top elements on the stack
[ z1<A]dsAx # until only one element is left
```
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), 3 bytes
```
\×⊂
```
[Try it!](https://uiua.org/pad?src=0_8_0__ZiDihpAgXMOX4oqCCgpmIDIgWzIxXQpmIDEgWzEgNSAzIDJdCmYgNyBbMSDCrzUgMyAyXQo=)
] |
[Question]
[
*This is the robbers' thread. The cops' thread is [here](https://codegolf.stackexchange.com/q/137742/61563).*
Your challenge is to take an uncracked submission from the cops' thread and find, for what input or inputs, the program will print `Hello, World!` and a newline. Capitalization, spacing, and punctuation must be exact.
Please comment on the cop's submission when you've cracked their code.
[Answer]
# [Bash by Sisyphus](https://codegolf.stackexchange.com/a/137809)
Original code:
```
[[ ! "${1////x}" =~ [[:alnum:]] ]]&&[[ $# = 1 ]]&&bash -c "$1"
```
Input:
```
__=; (( __++, __-- ));
(( ___ = __, ___++));
(( ____ = ___, ____++));
(( _____ = ____, _____++));
(( ______ = _____, ______++));
(( _______ = ______, _______++));
(( ________ = _______, ________++));
(( _________ = ________, _________++));
${!__##-} <<<\$\'\\$___$______$_______\\$___$______$_____\\$___$_______$__\\$___$_______$_________\'\ \$\'\\$___$___$__\\$___$______$_______\\$___$_______$______\\$___$_______$______\\$___$_______$_________,\ \\$___$____$_________\\$___$_______$_________\\$___$________$____\\$___$_______$______\\$___$______$______\\$__$______$___\'
```
Explanation:
This encodes "echo Hello, World!" as octal escape sequences (\xxx).
Except you also can't use numbers, so the first part builds up variables for the numbers 0-7. You can use those to build a string with octal sequences that will evaluate to give you the actual command.
But `eval` is also alphanumeric. So instead this pipes that string as input to another instance of `bash`. `$0` contains the name of the command used to invoke Bash, which is usually just `bash` (or `-bash` for a login shell) if you're running it normally (through TIO or by pasting it in a terminal). (This incidentally means that if you try to run this by pasting it into a script, things will go horribly wrong as it tries to fork itself a bunch of times.)
But anyway, you can't say `$0` directly. Instead, `$__` contains the *name* of `$0` ("0"), and you can use indirect expansion to access it (`${!__}` refers to the contents of `$0`).
And that, finally, gives you all the pieces you need.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), [Adnan](https://codegolf.stackexchange.com/a/137767/53748)
```
•GG∍Mñ¡÷dÖéZ•2ô¹βƵ6B
```
>
> **-107**
>
>
>
**[Try it online!](https://tio.run/##ATEAzv8wNWFiMWX//@KAokdH4oiNTcOxwqHDt2TDlsOpWuKAojLDtMK5zrLGtTZC//8tMTA3 "05AB1E – Try It Online")**
### How?
```
•GG∍Mñ¡÷dÖéZ• - big number
2ô - split into twos (base-10-digit-wise)
¹β - to base of input
B - convert to base (using 012...ABC...abc...):
Ƶ6 - 107 (ToBase10(FromBase255(6))+101 = 6+101 = 107)
```
[Answer]
# [totallyhuman](https://codegolf.stackexchange.com/a/137744/56656), Python 2
A solution is
```
'Uryyb, Jbeyq!'
```
[Answer]
# [Pyth](http://pyth.readthedocs.io): [Mr. Xcoder](https://codegolf.stackexchange.com/a/137754)
```
"abcdefghijklmnopqrstuvwxyz"
```
`G` is the built-in for the lowercase alphabet. The code checks for equality against that.
[Answer]
# [Jelly: EriktheOutgolfer](https://codegolf.stackexchange.com/a/137758/68942)
```
〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ
```
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
sLƽ$Xṙ5O½Ọ
```
[Try it online!](https://tio.run/##y0rNyan8/7/Y53Dbob0qEQ93zjT1P7T34e6e////P25Y@Li75dG2CY/mTLjY@HBiw6P5M0G8bROAMvcmXGh4uG3iqJqhpQYA "Jelly – Try It Online")
# Explanation
The original code can be explained as such:
```
sLƽ$Xṙ5O½Ọ Main link; argument is z
s Split z into n slices, where n is:
$
ƽ The integer square root of
L the length of z
X Random of a list. Returns a random row of the input put into a square
ṙ5 Rotate the list left 5 times
O Get codepoints
½ Floating-point square root
Ọ From codepoints
```
So, just take "Hello, World!" and get codepoints, square them, cast back to codepoints, rotate right 5 times, and then square and flatten the result.
[Answer]
# [Octave by Stewie Griffin](https://codegolf.stackexchange.com/a/137764/48198)
Not sure if this is the correct solution (on TIO it prints the `\00` character), but in my `octave-cli` shell it looks like this:
[](https://i.stack.imgur.com/tWdfN.png)
Also in the original challenge it says *print nothing (or the null-character)*, so if nothing is the same as `\00` then this should be fine.
```
[72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33, 0]
```
[Try it online!](https://tio.run/##y08uSSxL/f8/0zYzr6C0RENdXdO6oCgzryRNQ101WV0nU6suMSdHI7M4tbA0EUjrqHuk5uTk6yiE5xflpCiqa2pq/v8fbW6ko2BoYAgiLGCEIZBrYqKjYAyUszCHChgamsAVGQDljHUUDGIB "Octave – Try It Online")
[Answer]
# [Python 3 by rexroni](https://codegolf.stackexchange.com/a/137806/48931)
```
print("Hello, World!") or __import__('sys').exit(0)
```
Prevent any errors by exiting early.
[Try it online!](https://tio.run/##VY/NDoIwEITvfYrVS7tIiD9n7r6Bh4Y0pFStgS4pVeDpawUT4233y8xkpp/DndwpxqunDoZ5ANv15ANkbCHu2fXzj5nSJGJ8HQzTJT@btiW4kG@bDWdjaV51K2p/e8lDhWwqJflGONwdMwtX8mBzB9aBERor1nvrguC8eJB1Qmr5eYdnl85M0yBcZnE16dU0YoW7Yn/A6i9rShhjjGvedumUf0ttEZJUqXWAUoKniRwLM9kg9vgG "Python 3 – Try It Online")
[Answer]
# [JavaScript (ES6) By Ephellon Dantzler](https://codegolf.stackexchange.com/a/137912/34509)
`{length:1, charCodeAt:()=>(e='Hello, World!', String.fromCharCode=()=>'')}`
[Try it online!](https://tio.run/##bc5BC4JAEAXge79i8@IsbtISHUo3iC7dO3QTREez1h0ZtyCi325GQZduD96D753zW94X3HR@1ndNidySu@B9GG45C1JogkA5M1dN21kq0QBLs3lUxJBwbNHV/rRxCRmOi1POu3Gy9RBFTiqMzMFz4@q4Ymp33xYAFhlleiXTVGd6menFO0mZMPorO4HPZDIpyPVkMbZUw1eGx0dbayV@1BrGO4Am3KO1pMSR2JbTUIk/tHlvw1A@R2wYXg)
That was pretty easy.
I noticed that any string inputs wouldn't be possible to output `Hello, World!` because the whole thing inside `String.fromCharCode` will only return multiples of 4, and `!` has a char code of 33. So clearly we just have to hack the whole program. Hacking built-ins in JavaScript is trivial if one doesn't try to stop them (and even if one does so, there are usually lots of workarounds...).
[Answer]
# [JavaScript (ES6), Voile](https://codegolf.stackexchange.com/a/137939/72685)
Simple proxy that only returns the wanted character every 3rd time it's called.
```
var i = 0;
var string = "Hello, World!";
var proxy = new Proxy([], {
get: function(target, property) {
if (!(++i%3)) {
return string[property];
}
return [1];
}
});
```
[Try it online!](https://tio.run/##VY4xb8IwEIX3/IoLUhVbSVEQG66Z2dqtQ5QhDefUyLKjs4FSyG9PE1Okdnv3vnd379CcGt@S7sOzdXscRyW93F4NBiCZZYWWpTh/aoNMv6zWnHKZ@krXVVnfbrOQMtuhMa6Ad0dmn2aTF0me14IwHMkCDeL144BtWCpC/Eam@HhqCDRIKEUySx9I226aF/@uLe60J/d1maDFM7zNmlV1AdcEoMOwAXW0bdDOstDQZBRzvkcKFx4zAFoBS1me66c1f3gAv@3ur6vHTi0iHpI/kWoV3SEZuEhaZ70zuDSuY4rFapyL8Qc)
[Answer]
# [Ruby, by Histocrat](https://codegolf.stackexchange.com/a/137950/3527)
The magic input is: `1767707618171221 30191World!`
[Try it online.](https://tio.run/##KypNqvz/vyi1sDSzKFW9oCgzN1WdK882PbWkWK8kPz6TK08PLGivpqZiZ2OTBxIs1jA204w20DGN1UtOLMgsSczJrErlAkkr6Sgoq6grZabpGxsYWhrq//9vaG5mbm5gbmZoYWhuaGRkqACWCM8vyklRBAA)
### Explanation:
* the number `1767707618171221` is a prime, and, written in base 36 it is `"hello"`. When capitalized, this produces `"Hello"`, which is printed using `$><<`
* the line `$><<", #$'"if/30191/` looks for the number `30191` in the input and writes to stdout a string composed of a comma, a space, and whatever is in the input after the `30191` (using the `$POSTMATCH`, which is referred here by its short variant, `$'`).
[Answer]
# [Lua 5.1 by tehtmi](https://codegolf.stackexchange.com/a/137798/72546)
Pass this as the first argument:
```
C=("").char;_G[C(112,114,105,110,116)](C(72,101,108,108,111,44,32,87,111,114,108,100,33))
```
Assuming the original code is in a file `tehtmi.lua`, run (in bash or a similar shell):
```
lua tehtmi.lua 'C=("").char;_G[C(112,114,105,110,116)](C(72,101,108,108,111,44,32,87,111,114,108,100,33))'
```
It also works on Lua 5.3, which is what TIO uses, so why don't you [try it online](https://tio.run/##JYvBCsIwEER/RVKEXVxCtom2KPWSgx8hIlGhCsFC1n7/Gu3hMbwZJs9JVQZrbZ7SQz7l9R6hkWPYNLIfZb6BWWdDxuBUVoKAqhoHqG7vz1QO19M5AnNLzIHYbWu6yg4vEKGrteNKv8BMIZBvqe/@snx@oyPvEb8 "Try It Online")? I haven't tested on a implementation that uses the "PUC-Rio's Lua 5.1" core (because I can't really find any information), but my solution probably also works there.
## How?
It runs the first argument as code, but only if it contains less than 5 lowercase characters.
The trick is to run `print("Hello, World!")`. Another way this can be run is using `_G["print"]("Hello, World!")`, which only uses strings.
But we can't use the string directly due to the lowercase-count restriction, however, you can run `("").char` to get the function `string.char`, that can convert from a series of bytes to a string. I assigned it to an uppercase variable (so we don't hit the limit) so we can use it to construct both the `print` and the `Hello, World!` strings that can be used like above.
[Answer]
# [JavaScript (ES6) by Voile](https://codegolf.stackexchange.com/a/137922)
Input must be a string containing this:
```
e(
`\
_\
=\
>\
"\
H\
e\
l\
l\
o\
,\
\
W\
o\
r\
l\
d\
!\
"\
+\
\`
\`
`)
```
Try it using this:
```
const e=eval,p=''.split,c=''.slice,v=[].every,f=s=>(t=c.call(s),typeof s=='string'&&t.length<81&&v.call(p.call(t,`\n`),l=>l.length<3)&&e(t)(t))
input='e(\n`\\\n_\\\n=\\\n>\\\n\"\\\nH\\\ne\\\nl\\\nl\\\no\\\n,\\\n \\\nW\\\no\\\nr\\\nl\\\nd\\\n!\\\n\"\\\n+\\\n\\`\n\\`\n`)'
console.log(f(input))
```
If you don't care about the trailing newline requirement for the output, you can replace the last 6 lines with this instead:
```
!"
`)
```
### How I did it
The restrictions on the input are that it's a string, each line is two bytes long or less, and that the total length is 80 bytes or less. My first attempt after understanding that correctly was this:
```
_
=>
`\
H\
e\
l\
l\
o\
,\
\
W\
o\
r\
l\
d\
!
`
```
Note: the `\`s are to ignore the newlines in the string in the input. This is incredibly crucial to the answer, and I can't believe that I stumbled upon it on accident. (I was familiar with it before but forgot about it)
But this didn't work, since the `=>` has to be on the same line as the arguments. Thankfully, I had the idea of wrapping something similar in a string and putting an eval in my input to reduce it to one line, resulting in my final answer. After the eval in the input occurs, the following is generated as a string (which is then eval'd to a function and then run):
```
_=>"Hello, World!"+`
`
```
This was really tough to crack, but I succeeded in the end.
Also, first crack ever!
[Answer]
# [Cubically](https://codegolf.stackexchange.com/a/137766/63446) by MD XF
I imagine this is always dangerous, but I think I have a crack, pending that I am correct in that there is a bug in the interpreter (which I just now compiled).
My input
>
> 0 1 0 1 0 1 0 1 1 0 1 0 0
>
>
>
Output is `Hello, World!\n\n\n\n\n\n\n\n\n\n.....` with unending newlines.
But I noticed the last section of code:
```
:1/1+1$(@6)7
```
sets the notepad to `0x0A` (newline) in a scary way, reads input to face 7 (the input face), and then prints the 6 face (notepad face) repeatedly until the 7 face is zero. If you set face 7 to zero, you should only get one newline. However, I got infinite newlines and my 13th input WAS a zero, and I can verify that the 7 face is always zero by inserting a "print number from 7 face" in the loop:
```
:1/1+1$(@6%7)7
```
then it prints unending `\n0` pairs.
I am looking at the specs on the [cubically github page](https://github.com/aaronryank/cubically) and this behavior looks an awful lot like a bug. Changing the last character of the original program from a `7` to a `0` results in the expected behavior. The TIO interpreter exhibits the same incorrect behavior.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), [Erik the Outgolfer](https://codegolf.stackexchange.com/a/137771/53748)
```
q5/:i:c
```
>
> **00072001010010800108001110004400032000870011100114001080010000033**
>
>
>
**[Try it online!](https://tio.run/##S85KzP3/v9BU3yrTKvn/fwMDA3MjAwNDIAQiCxhhCOQamJgACWOgrIGFOVTM0NAErg4EjI3/AwA "CJam – Try It Online")**
### How?
```
q - Take input (string)
5/ - split into chunks of five
:i - cast to integers
:c - cast to characters
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), [Grzegorz Puławski](https://codegolf.stackexchange.com/a/137772/71434)
The solution I found makes very substantial use of unprintable characters, so attempting to paste it here didn't work well. The byte values for the input are:
```
109, 89, 4, 121, 3, 11, 8, 29, 37, 38, 27, 25, 72, 4, 4, 4, 3, 3, 3, 4, 4, 37, 3, 27, 4, 3
```
Or the string version is available in the input field of the TIO link.
[Try it online!](https://tio.run/##VVBNSwMxED0kB1l/gRQhl5VE2qCWnuouFKV40EsriJQehnSqobvZmqR1l7K/fc1a2@I7DDPvzcdjlOupwmKzcdp8sGnlPObyWZuvYRQZyNGtQeEfH@0iFqAycI6NfvM908J58FqxbaEX7AW04eIonZpajDdG3Ttvw70uU59gZ/OULVnSQJKCfNTOa6M8F3KKGYaEl91KtNIEt2gdtspKr3kl5FhbFzqvy/huMBDyFVbI4cD2@n0hHwqjwHOD30wbP5vvbm/q4@YySXlrQJRhthhZCxUXzfCf27DAFRnKN6s98iU/1BOERXhTcCPEaaKO9rFu8ndakfOzy/iqc/FEKSWEUBqTDiU/ "C# (.NET Core) – Try It Online")
The original program would take the distinct characters in the input, then reverse the input and multiply the elements of the two lists. Thus I created a string 26 characters long where the first 13 characters were distinct, the last 13 characters all also appeared in the first 13, and each pair of indexes `[i, 26-i]` multiplied to the byte value of the i-th character in `Hello, World!`.
[Answer]
# [Ly](https://github.com/LyricLy/Ly), [LyricLy](https://codegolf.stackexchange.com/a/137792/53748)
```
n[>n]<[8+o<]
```
>
> 2 25 92 100 106 103 79 24 36 103 100 100 93 64
>
>
>
**[Try it here](https://lylang.herokuapp.com/?program=n[%3En]%3C[8%2Bo%3C]&input=2%2025%2092%20100%20106%20103%2079%2024%2036%20103%20100%20100%2093%2064)** (although the page does not render the newline).
`n` takes input, trys to split on spaces and cast to ints, these get put on the stack. `o` prints ordinal points, and `8+` does what one would think. So input needs to be 8 less than the codepoints in reverse order split by spaces.
[Answer]
# [C (gcc), by Felix Palmen](https://codegolf.stackexchange.com/a/137948/73229)
Original code:
```
#define O(c)(((char**)v)+c)
#define W(c)*(O(c)-**O(2)+x)
main(x,v){puts(W(42));}
```
Arguments:
```
"Hello, World!" ","
```
[Try it online!](https://tio.run/##NcqxDoIwEAbgnafAuNx/tEth8wXcGDs3R0GSAgaQkBhenVMH5@8T24moXpvY9mPMaxIQkTzCzIwNhSD7m/8a029Y5pocih3ZEPqRdrPh/XytC3mqHHA7VPUeU5pM7qc5NRc1p7QpdIvaoXQf)
Explanation:
`W(c)` is calculating the address of a string from the argument list to print out. It starts with the address of the cth argument (`O(c)`), which is the 42nd argument in this case, and then subtracts the first character of the second argument (`**O(2)`) as an integer offset, and then adds `x`, which is the number of arguments.
`W(c)` uses the second argument, so you know there need to be at least 3 of them (0, 1, 2). Then "Hello, World!" can go in the first argument, and then to address that argument you need a character whose ASCII value fits in the equation "42-x+3=1". That happens to be ",".
[Answer]
# [JavaScript: ThePirateBay](https://codegolf.stackexchange.com/a/137757/31343)
I override the `valueOf()` and `toString()` methods of the parsed objects so that coercion fails with a `TypeError`.
```
{"valueOf": 7, "toString": 7}
```
[Answer]
# [6502 Assembly (C64) - Felix Palmen](https://codegolf.stackexchange.com/a/137935/73219)
>
> The correct answer is ,52768,23
>
>
>
The explanation is slightly involved.
```
00 c0 ;load address
20 fd ae jsr $aefd ; checks for comma
20 eb b7 jsr $b7eb ; reads arguments
```
The code first checks for a comma (syntax necessity) and then reads in two arguments, the first of which is a WORD, stored little-endian in memory location 0014 and 0015, the latter of which is stored in the X register.
```
8a TXA ;Store second argument into A (default register)
0a ASL ; bitshifts the second argument left (doubles it)
45 14 EOR $14 ; XOR that with the low byte of first argument
8d 21 c0 STA $c021 ; Drop that later in the program
```
That's pretty clever, using our input to rewrite the program. It eventually rewrites the counter for the output loop at the end of the program.
```
45 15 EOR $15 ; XOR that with the high byte of the first argument
85 15 STA $15 ; Put the result in $15
49 e5 EOR #$e5 ; XOR that with the number $e5
85 14 STA $14 ; Put that in $14
```
Here comes the devious part:
```
8e 18 d0 STX $d018 ; stores the original second argument in d018
```
on the C64, d018 is a very important byte. It stores the reference points for things involving the screen's output. See [here](http://codebase64.org/doku.php?id=base:vicii_memory_organizing) for more info. If this gets a wrong value, it will crash your C64. In order to print the requisite mixed upper and lowercase letters, this needs to be $17.
Now we begin our output loop:
```
a0 00 ldy #$00 ; zeroes out the Y register
b1 14 lda ($14),y ; puts the memory referenced by the byte
; starting at $14 (remember that byte?)
; into the default register
20 d2 ff jsr $ffd2 ; calls the kernal routine to print the char stored in A
c8 iny ; increment Y
c0 0e cpy #$0e ; test for equality with the constant $0e
```
That constant is what got written over before. It clearly determines how long the loop runs. It happens to be the right value already, but we need to stick 0e there again.
```
d0 f6 bne *-8 ; jump back 8 bytes if y and that constant weren't equal
60 rts ; ends the program
```
The rest is just the information which we need to print out, starting at memory address c025.
So it's just following the math from there.
[Answer]
# [6502 Machine Code (C64)](https://codegolf.stackexchange.com/a/138533/73219) - Felix Palmen
The correct answer is
>
> 8bitsareenough
>
>
>
The code is rather complicated, involving a lot of self modifying. So instead of fully reverse engineering it, you can just use it to crack itself.
Here's a slightly more helpful disassembly of the code, to help understand what happened. The syntax is for KickAssembler.
```
*=$c000 // LOAD ADDRESS
jsr $aefd //checks for a comma
jsr $ad9e /*Reads in an argument. Stores length of it into
$61, with the address of the stored arg in $62-3*/
jsr $b6a3 /*Evaluates the string, leaving the pointer on $22-3
and the length on A*/ //I think
ldy #$00
loop: lda thedata,y
cpy #$01
beq shuffle
cpy #$07
beq shuffle
cpy #$0b
beq shuffle
tricks: jsr output
iny
bne loop
output: eor ($22),y //XOR's A with the y-eth letter of our input
jmp $ffd2 //good old CHROUT, returns to tricks above
thedata: .byte $f0,$48,$fa,$a2, $1c,$6d,$72,$30
.byte $06,$a9,$03,$48,$7c,$a3
shuffle: sta $c048 //drops A in mystery+4, over the constant
lda $c026,y
sta $c045 //overwrites the low byte of mystery
lda $c027,y
sta $c046 //overwrites the high byte of mystery
ldx #$00
mystery: lda $aefd,x
eor #$23
jsr output
iny
inx
cpx #$03
bne mystery
cpy #$0e
bne loop
eor #$1a
sta $d018
rts
```
Labelling it up like this was enough for me to see that the code XORs a bunch of constants that are hidden around in order to print out what we need. Since XOR is reversible, if you input the desired output, it'll tell you what the key is.
So I switched the last line
```
/*from sta $d018
to*/ jsr $ffd2
```
so it would print the last required input instead of crashing on a wrong input.
And that's that!
If there's any interest, I'll crack the code more.
[Answer]
# [Explode](https://github.com/stestoltz/Explode), [Step Hen](https://codegolf.stackexchange.com/a/137787/53748)
```
@_?&4_-j>5&f^~c>&6\|4>7
```
>
> **Rh/qi?,Wcr+du**
>
>
>
**[Try it online!](https://tio.run/##S60oyMlPSf3/3yHeXs0kXjfLzlQtLa4u2U7NLKbGxM78//@gDP3CTHud8OQi7ZTS/wA "Explode – Try It Online")**
* Trying to work out what all the "explorers" are actually doing hurts one's head too much, so I just reverse engineered it (literally :p - starting from the rightmost character I offset each in turn along [and around] the printable character range).
[Answer]
# [C (tcc) by Joshua](https://codegolf.stackexchange.com/a/137785/12012)
```
int puts(const char *s)
{
printf("Hello, World!%s", s);
}
```
[Try it online!](https://tio.run/##RY3BCsIwEETv@xXbFLHVNvkAS8/@gRcvcVNJIE1KkoogfntsK@jCsIeZeXOTUWeSCXvUg7Ueuw73fJ/LQvgpCWoTkViEbZgdlMaRndWAXUzKeK57AOMSjtK4qoYX4HLTnGLFro7VJ3j/K0yo4SHWnmOZA5AevcLj87sLXGw/r7iNQN7FhKRlwEP8scPi3yt2XrMNXnywqthF1mBc1z4 "Bash – Try It Online")
[Answer]
# [MATL by Luis Mendo](https://codegolf.stackexchange.com/a/137799/12012)
```
tsZp?x
```
[Try it online!](https://tio.run/##y00syfn/v6Q4qsC@4v//aHWP1JycfB2F8PyinBRFdR0FQ@NYAA "MATL – Try It Online")
[Answer]
# [Jelly by Jonathan Allan](https://codegolf.stackexchange.com/a/137783/49958)
Original code:
```
œ?“¥ĊɲṢŻ;^»œ?@€⁸ḊFmṪ⁷
```
[Try it online!](https://tio.run/##y0rNyan8///oZPtHDXMOLT3SdXLTw52Lju62jju0Gyjo8KhpzaPGHQ93dLnlPty56lHj9v///xvqGJlamBlbAmlLE0sjc2MdY2NDI0NTEzhtaGhsYmBgqGNsZmRhAVRmZGRsamCqY25mZgDkwmQNTSzNzUCqYLoszAzMwOIGAA "Jelly – Try It Online")
Input:
>
> 1,2586391,2949273,3312154,3312154,1134001,362881,2223505,766081,1134001,1497601,3312154,1860601,140
>
>
>
Explanation:
>
> Mainly, it is necessary to understand what the code does. The first thing it does is it takes the string `"!,Word Hel"` (with all the needed characters except newline) and creates a bunch of permutations of them. The inputs specify permutation numbers, and each pair of permutations from the input is applied to the string exluding pairs where the first permutation is applied first. Basically, P2(P1(S)), P2(P2(S), P2(P3(S)), ..., P2(PN(S)), P3(P1(S)), ..., P3(PN(S)), ... ..., PN(P1(S)), ..., PN(PN(S)). These are all concatenated together. Then the last input is reused to take every PNth character from this big string. So, I take PN = len(S)\*N = 10\*N. This means we'll take the first character of P2(P1(S)), the first character of P3(P1(S)), all the way up to the first character of PN(P1(S)). To simplify further, I let P1 = 1 which is the identity permutation. Then it suffices to choose any P2 that permutes "H" into the first position, a P3 that permutes "e" into the first position and so on. Luckily, small permutation numbers like the one already chosen for PN don't affect the earlier characters in the string, so PN leaves "!" at the beginning of the string. (If this wasn't true, it would still be possible to solve by choosing a different P1.)
>
>
>
[Answer]
# [C (GCC on TIO) by MD XF](https://codegolf.stackexchange.com/a/137865/72546)
```
4195875
```
[Try it online!](https://tio.run/##S9ZNT07@/185My85pzQl1aa4JCUzXy/Djis3MTNPo0Kzujg5MS9NQ0k1RUlHrULTuqAoM68ExDdSKVbSUfJIzcnJ11EIzy/KSVGMyVPS0SjLz0zR0gSqrP3/38TQ0tTC3BQA "C (gcc) – Try It Online")
# How?
It tries to print the second argument as a string, which is a pointer we can determine on the input. It just so happens that at location memory `4195875` starts the `"Hello, World!\n"` string.
The number was determined by adding `print("%p", "Hello, World!");` before the `printf`, converting the hexadecimal number to decimal and tried it out on the original TIO. However, it showed me the `printf` format string. By trying out some numbers, I found out that the string is located before the format string.
So in memory, it would look like this (as a C string):
```
Hello, World!\n\0%2$s\0
```
This also means that any update to the compiler might break the solution.
[Answer]
# [JavaScript (Node.js) By Voile](https://codegolf.stackexchange.com/a/137925)
`['Hello, World!','','','','','','','','','','','','']`
[Try it online!](https://tio.run/##hYyxCsIwFAD3fkWcktBYFMf4Ors5OpQOtX3RlEcjL1FB67fHzi7CTXdwY/foYs/@ltZTGDBnBxHqN2ESDFIaDxv7vHpC5ffbneYSYuNbAHlAomDEKTANK7m4eV5KWbaWMd15Evyxx/OIfaocI75QOV0UfZhiIKwoXJRTzc/FyP@0Wuf8BQ)
[Answer]
# [Röda by fergusq](https://codegolf.stackexchange.com/a/137932/41805)
```
[1, "HH", 1, "eellloo", 1, ",,", 1, " WWoo", 1, "rr", 1, "ll", 1, "dd", 1, "!!"]
```
[Try it online!](https://tio.run/##PcyxCsMgFAXQufmKl0xabMC10C5d8gcZ5CFSDQm8arFxivl2m4J0O/deuDFYU6ayKTU7Y5nm2Pcq@XciYpIvk9LyLhExK814fs4mfnLyIVoXnX2E5NdjOTN9kRxxLy@zeNia03I8rHC9gZICumHoBPzgHBGFUJMQFQDj@G9jrCCqsLaibTus34xDhonxZi9f "Röda – Try It Online")
Explanation coming in a bit...
[Answer]
# [JavaScript (ES6), Voile](https://codegolf.stackexchange.com/questions/137742/hello-world-cops-thread/137934#137934)
```
var i = 0;
var string = `"${t}"`;
var answer = "i++?0:q=string";
console.log( f(answer) );
```
[Try it online!](https://tio.run/##NY/NjoMwDITvPIWLqhKr6Yq9LnL32jfolYgGlFWUkMSlB8SzU366vtjzzczBf2pQqYmm54vzDz3PjXeJgam4aWu9hLuP9nEoZAbbdBToqgdlRS3ap2vYeCd6GY5jmHCMmp/Rweb3KLcdcMIa//stJbp2oihQJFkiEZ9Oi6TvDzisgOdBRTBAUFbZeiaOxnWLrvPjyFNe71i59NJxwbk5n3/Ln0B7MK@y9Q1v9Zf1nYBW7EkErOY3)
[Answer]
# [PHP by LP154](https://codegolf.stackexchange.com/a/137943/40634)
```
PDO,FETCH_CLASSTYPE
```
[Try it online!](https://3v4l.org/Gf7XM)
(TIO doesn't have the PDO class defined, so the above demo uses a codepad that does)
Another solution:
```
ReflectionFunction,IS_DEPRECATED
```
[Try it online!](https://tio.run/##K8go@P/fxt42OT@vuCQxr0QjtaIgJz8lVUNdR11HJbEovSzaMFYz2iBWT8nKSkkPuywQ29oamRkZmpjYK3mk5uTk6yiU5xflpHApWSVa////Pyg1LSc1uSQzP8@tNA9M63gGx7u4BgS5OjuGuLoAAA "PHP – Try It Online")
[Answer]
# [JavaScript (ES6), Voile](https://codegolf.stackexchange.com/a/137922/72685)
Given the 81 character limit, this probably isn't the intended solution
```
global.g = ()=>"Hello, World!";
var str = "g";
```
[Try it online!](https://tio.run/##TY/BasMwDIbvfQovh8QG1zB2GXTKeW/QQzeo6ypehrCNLQx9@tRrl3VCIP7vF7/Qt622uDwn3oZ4xmVxMRQWCFgt6Y24VYJhMCXRzCtxN0Kzw5VUOHwarJgvK5mgwCh/hRAMzjhLJIvSD3hJGCdRAIbCeQ5@@LP6ng1h8Pz19vr8j9Z7SroP1sePcFSaYKR1/UX1PUpWrdXiKZ4sGS9ASAVj945EUYt9zHR@6nabarNop5vd@SZ/3o@EhqKXk2yGUrvlCg)
] |
[Question]
[
Today, my girlfriend and I started with [this year's Advent of Code](https://adventofcode.com/2020) to improve our Python. So far we only did Day 1 and the first part of Day 2. The latter, I found to be very fun, so, to spice it up a little, and with a tip o' the head to Eric Wastl, here's my attempt at turning it into a Code Golf challenge.
## Task
Your task, should you accept it, would be to determine the number of lines where the number of occurrences of `char` in each `string` is at least `min` and at most `max`. With the above data, a valid entry will output `23`¬π.
Valid entries shall not only work with the below two example data sets, but with any data set produced by the [Advent of Code website's Day 2 Part 1](https://adventofcode/com/2020/day/2) puzzle (so head on over there already - but just going with the examples is fine, too). **Other formats of input are not allowed. Specifically, the entry has to handle the newlines itself.**
I've posted an answer with my Ruby version along with this Question in the hopes that it will help.
## Input
* A multiline string where each line/element contains a number `min`, a number `max`, a character `char`, and a string `password`² (i.e., `min-max char: password`).
* `min` and `max` are positive integers, and `max` is guaranteed to be greater than or equal to `min`.
* As far as I can tell, the `password`s are all ASCII-alphabetical, as is the `char`.
## Output
* A number representing how many lines had at least `min` and at most `max` occurrences of `char` in `password`.
## Scoring
* The winner shall be the shortest entry by characters¬≥, *not* bytes (to make sure that variable names such as `üéÖ`, `ü¶å` and `üéÑ` don't put contestants in the mood of the season at a disadvantage).
## (Shorter) Test Case
```
Output: 3
Input:
1-5 c: abcdefg
5-12 j: abcdefg
1-5 z: zzzzzzzz
3-3 h: hahaha
4-20 e: egejeqwee
```
## (Longer) Example
```
Output: 23
Input:
3-8 j: ksjjtvnjbjppjjjl
6-10 s: sszlkrsssss
1-4 z: znzfpz
7-11 m: dfkcbxmxmnmmtvmtdn
6-9 h: hlhhkhhhq
8-9 p: ppppppppvp
6-9 c: cccgccccmcch
5-8 g: bgkggjgtvggn
3-4 x: xxhk
10-12 h: hhhhhhhhhlhhhhdnh
5-6 j: zjjsjn
9-14 s: ksclwttsmpjtds
6-7 l: gtdcblql
1-4 d: dkndjkcd
1-6 k: kkkkkckmc
10-12 x: xxxxxxxxxrxl
2-5 v: fxdjtv
3-5 q: pjmkqdmqnzqppr
5-8 t: xtgtgtcht
6-11 j: nftjzjmfljqjrc
6-9 g: rskgggmgmwjggggvgb
11-12 v: vkvdmvdvvvdv
15-16 z: zzzzzzzzzzzzzzgxz
13-17 v: vvvvvvvvvvvvvvvvnv
9-14 j: clrfkrwhjtvzvqqj
1-12 l: lljljznslllffhblz
4-7 c: cccgcxclc
6-11 z: tbxqrzzbwbr
18-19 m: jmbmmqmshmczlphfgmf
1-5 s: ssvsq
4-5 k: kkkkw
4-7 f: fcqffxff
3-8 f: fffzthzf
9-12 v: vvvvvvvvvvvmvv
14-17 f: ftflcfffjtjrvfkffmvf
4-7 n: pnmnxnqqjp
6-7 r: rrrkrmr
4-13 k: drckdzxrsmzrkqckn
5-14 t: dttttttttttttt
13-14 v: vvvvfvvvvvvvvvv
7-12 j: jrljwnctjqjjxj
6-7 v: wchfzvm
1-8 d: dddddddzd
10-12 g: gvvzrglgrgggggggggg
```
---
¬π: But, say `puts 23` (that is, without doing the actual work) is no valid entry.
²: On Advent of Code, the background to the puzzle is that you're helping a toboggan rental company with their computer trouble. For some reason, their password database has been jumbled up and you're trying to fix it, which requires you to figure out which passwords adhere to the password policy, which solely consists of a specific character (`char`) to be present at least and at most a certain number of times.
³: As determined via `wc -m`.
[Answer]
# Ruby, 56 characters
```
eval'㵰␼⹣潵湴筼汼氽縯層⬠⠮⤯㬨①⹴潟椮⸤☮瑯彩⤽㴽␧⹣潵湴⠤ㄩ紻'.encode('utf-16').b
```
[Try it online!](https://tio.run/##XVJLbtswEN3zFNylXSgI/Uui21RkSIG/ShRDq1z3AMmuuxqogTZAmg/gAA0aX0ZGnGO4Q9lO2zxDNmTMzPvMuPPi02ZzFj7og9XDXXfx1D1@Wy8f1o@Ll59P6/un9d3y5dft8/28u551s5tufru6/tFdzrrHxXr5dT2/6X7Nuy83L5e3z8urbr5cLZbdxffXId1svvp89bL4fXB4ZulHdvbu4NzzjEwO3h8Wm80wO8Eyx6qR0gcrC1lVUkqNJhk5wk2OmyZq5ZoERLIRjjmONvIqouOMEGxyzLiiRWtaY43xwXhmofkUlzkudVmqsixrdAJ/VDmudghVX0JzTCkV8FBDaYnGoEXkuBBKCCl8EMKiIXC2OW7bUiFylJFBP3gPnb6YTa2TZCNK2UiLTjMySuJVQ/XU@8ZU0rMGOI@xzrHwjBa61r0fBgaUZVJRBu8TrKArgSpDd4Q9/Q6u1WiQjXHIMW8ZRAYCx7gGa9KompnaxrqqXG/FQ58X8KGlT3mSpNByL6M0XMtaOtrHAJZdA5aFEWYq4VcEUSBCEjfwBBWYCSwEeBAZw@b6JfwH0UZEhhk57hvewIZtIMBOtePKTUsQHkNdS9STQCZaSy2jbbTWnJeFjmgEYe0X1FJNtw6A2Rdt7WIspoVD5CQjp@kIpCmMqU1TGhp1VXJhOMweby8oNDWMG@@znfazOSRIa85bzlE6wvTOefRl5Enu4I0TE8D8KDlMhZ5rCtXSSxe44twE3g@1sAhrbGvBW9Xv20G4zilnHBSQYdLAHFUstq4x0amaKgvbgnhgXcz/iz7R0V4H/6slnf4gxSmdllNLPexStrLng@opLXkMBvyf9Oe1RWS7c4J1ixCiE1o48Yo/ "Ruby – Try It Online")
Decompresses to:
```
p$<.count{|l|l=~/\d+ (.)/;($`.to_i..$&.to_i)===$'.count($1)}
```
Character scoring allows these sort of shenanigans!
This is also a great showcase of Ruby's regex global variables. Given a line:
```
3-8 j: ksjjtvnjbjppjjjl
```
Our regex matches here:
```
3-8 j: ksjjtvnjbjppjjjl
\-/
Regex matches here
```
Then `$'` is the part after the regex, `$&` is the part that matches the regex, `$`` is the part before the regex, and `$1` matches the character to count, so we have:
```
$` = '3-'
$& = '8 j'
$1 = 'j'
$' = ': ksjjtvnjbjppjjjl'
```
Since Ruby's `to_i` just ignores garbage after a numeric string, we can just cast it to int.
### Ruby `-n`, 60 characters
```
~/\d+ (.)/;($`.to_i..$&.to_i)===$'.count($1)||$.-=1
END{p$.}
```
[Try it online!](https://tio.run/##XVLJbtswEL3zK3gw2gSFlNBbHBW@tdd@QYEWIkEyw8USxdAqm/bT6w5pu0ueQG2YmTfvzYTn/tvp9PPus3hHb9rbu/c3i69tPHx5atvFm/pyu9/vF29bfnj28WbBbl9eFm2zZ@Tjpw/fh0X743RaNTsKHTUTQEweehgGALBk27B7OnV0mrI1YSogrFnT3NHssxwyeWgYo66jQhrez2523rmYXBQekx@p7qi2Whut9Uh2@GPo6HBBGmoI7yjnXOHhjnNNNtiL6mivjFKgYlLKkxVyzh2dZ20Iu2/Ysha@wpab8CV1W2RkgAk8eWzYujRvJm6PMU5ugCgm5HygtqMqCt7b0VY9AgUYL8Bwgd9bajCrgBvHL4SV/oIwW7JsNjR1VM4CLcMGN3REaeDMKNzo8zgMoUqJmBcVXlzH4icrHXoZIYOTFkYIvNqAksOEkpVT7gj4VEn1hLHCjTzJJOGSSAkPYZuGbesQ/oOaM2Grhj3UhFfw6WwIsnMbpAlHjY3nNI5AKgl6Yi1YyH6y1kqpe5vJGs26Dmjmlp8VIHPs5zHk3B/7QNiuYY9lCcD1zo1u0o5nO2ipnMTam/MGpWnEcpurt8daW6KDfJRylpKUJSzfUuaosyztLl8pcQnFr4vCEhil5RgNEUKSRkqXZC3qcRDe@dmjtqHOO6C5IZjgAgawVelBBG5EnsPkcjAjNx6nhfbguET8F9XR9bUP@beXsvrLYicEC0fPI84SZqh8GH3kWubkUP@urtcZWVzWCcetUspBWRXUH/w6DPHp4KdT438D "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 71 characters
```
exec(bytes("浩潰瑲爠੥㵦慬扭慤砠攺慶⡬敲献扵✨尨⭤⸩尨⭤⸩⸨⠩⬮尩㽮Ⱗ❲⠫ㅜ㴼尢∴挮畯瑮∨㍜⤢㴼㉜✩砬⤩",'U16')[2:])
```
[Try it online!](https://tio.run/##XVLLbtw2FN3rK4hsMgNUhTkv2/qPrIouInJIla9IFMFRuDdgA8kiQLKbAJPAbT2oMx0YcREUzb8UGljzGc6lbKdNjqD3vffcc@4tn7vimRnf3s6bORnkz928Hjzqrtfd5@3@1dX@dPXv@tfd9W/dyWV39qE7Od@vVt3rv7uTv9p3l92bq/2LTXd23S4vbrYX7Yfz9tP660P76aJdrdvLzc12vfu8abe/t2@v2tUfu5Pl7uM/N9v37enH7sVm/@bP/atNe3qxe7lsz9/Dr93Zsl2u96vL9nz96IfHT/Ds8fCnUfbz8La0vxg3YINn5dwMDoY/2vlTOhgOh7fj9AiJDMlaCOeNyEVZCiFUMkvxAaozVNdBSVtHJDidoJChYAIrQ3KYYox0hiiTJG90o43WzmtHDSQfoyJDhSoKWRRFlRzBhzJD5T182YeQDBFCOJxEE1IkU@iFZyjnknPBnefcJGPgbDLUNIVM8EGKR33hB6h4oSamzqKMIEQtTHKc4klsXtZELZyrdSkcrYHzEKkMcUdJrirV66EgQBoqJKHwPkMSsiKI1OSesKe/h21UMkqnyGeINRQsgwanqAJpQsuK6sqEqixtL8VBnuNwkMJFP3Hs0DAngtBMiUpY0tsAkm0NkrnmeiHgzj3PE4wjN/B46an21Hs4EzxN8awfwjfgTUjwOMWHfcJ3MP7OEGAnyjJpFwU0HnxViaQnAU@UEkoEUyulGCtyFZIJmPUwoIYocqcAmF3eVDaEfJHbBB@l@DgugdC51pWuC02CKgvGNYPa07sN8nUF5aYP3i762gwcJBVjDWNJXML4zlhwRWCx3dF3SrQH8ZOoMAY6pghECyesZ5Ix7Vlf1MAgjDaNAW1lP28L5lorrbYQgMexB2qJpKGxtQ5WVkQamBbYA@Oi7v/oHZ089MH@6yWu/ijaKawSC0MczFI0oueD6AUpWPAa9B/163WHQO/XCcbNvQ@WK275V3wB)
Decompresses to:
```
import re
f=lambda x:eval(re.sub('(\d+).(\d+).(.)(.+)\n?',r'+(\1<="\4".count("\3")<=\2)',x))
```
Note we need to name the function even though it's not recursive since we are wrapping in `exec`.
This is probably not optimal, since we shouldn't have to use regexes here, but parsing the format is so painful using only Python stdlib.
[Answer]
# GAWK, 87 bytes
```
split($1,b,"-")sub(":",a,$2){n=b[1];x=b[2];c=split($3,y,$2);t+=n<c&&--c<=x}END{print t}
```
[Try it online!](https://tio.run/##RYrfCoIwHIXvfYofQ0RpgzbzZnN3ddsLhBfbWv4pxHKhKT77ShA65@Lw8R013L3vu0ft4pBijRFBSf/WMeIIKxyyZG6lvtBCjL9hhTByO6f4s2rhdrLNTRQRYnI5Lqfzce5edevALd5TkoHhoLS52lsZZIQyaP686onDtCVISQoVh0qtDQ6E7cFysKVt7HOw9gs)
It's pretty brute force, but there are a few GAWK'isms that shorten things a bit.
First, doing the "split" and "sub" calls in the test condition section means not having to use `;` characters.
Then taking advantage of the fact that uninitialized variables are treating like empty strings (when strings are called for), means it’s possible to use `a` instead of `""` and save one character.
The code also relies on the fact that when a uninitialized variable is treated like an integer, its value is 0
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
```
| í#ƒá'-¬°≈∏sR`–Ω¬¢√•}g
```
[Try it online!](https://tio.run/##yy9OTMpM/f@/5tQk5SPt6rqHFh7dURyUcGHvoUWHl9am//9vrGuhkGWlkF2clVVSlpeVlFVQkJWVlcNlpmtooFBspVBcXJWTXVQMAlyGuiYKVVYKVXlVaQVVXOa6hoYKuVYKKWnZyUkVuRW5ebm5JWW5JSl5AA "05AB1E – Try It Online")
This is technically a character counter with a twist!
*-2 bytes thanks to ovs!*
At the time of writing, this answer is winning!
# How?
```
| # Convert the input into a list
í# # For each element in each line
ć'-¡Ÿ # Parse the range
sR` # Unpack the string and character
–Ω # Parse the character
¢å # Is the number of occurences in the range?
}g # How many lines have this condition?
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ 19 bytes=chars
```
ḲµḢ⁾-ryViḢċ@¥/
ỴÇƇL
```
[Try it online!](https://tio.run/##bXxJjiS7st28VlEbKOhm9XVHWoDGWgBJkRQ7sAPJz5lGf6BdCNAGBAn4gAANvgTt42kjT9aQEZF1H1HhmVkR7k43mh071jDcfwjhn/7@97/9y3/71//xt3/5L//vP/2vT/Wf/v1/hF//z3/@t//6X//Nh7/9z//@v//5//7zv/v73//@@dP3j/PPj9PPOfWcecwPb18/vX37OP78aIcdwY4x5hpqNKnyMB8@f/ryUfz5UXgvPnz59BU/N80Ye1g5Qh1ujDg@vL19evv8Uf75Ud5R8OClhPO/fdx/ftx@5x02jg8/Pr19@bj@/LjeD/z/Pz5q@KzWS0yti14aftUf3r5/evvx0dIMX0ftND3/50dfnfcf3v749PZGfz6G@fD249PnPz6qPz@qqLNSWwWl@lBKTdU9PNK3j/HPj13NCMN9@ArygcdNUgmRzarmw0@cLZwulFbKBA9nmjKVlrvRwzU4u7XtrdF3Nlv4/uHbp1/4eykzquK3D8pmVwLdIcPlstO2ZnUmXf/8WGtd8KrT4vHDdzg/wUzSSjOlJPhMfLhosvdOwd@0bGMoM2htQEIOxAK3fvuK55rU4MwwxJbNuVkcrfUPlHEB6WoUsU5hSq33WUP358cobS3BVWcd/BvRTfHhDa5@5frh7Qtev@Cz8Vh4CKXAx@j5ZfRV5R78Ct7Csv5CEcfHgInDQqNSVbGKECKwasG0dFFa0x8okFLzJkn8wKeRPiWVksnwTB8@8zplL3DAGb9wIUKj4drcrcFsvuON/cud8TlIqDjoPrAUOeeSUfu@4zVaSy202Kxuo/XVcgUTAUmDwqajqJ8/8ePLUmyhZaDly3WTRsBbngVDU4cpJGNylPjgv85K84AZfEeR7@Ly9j63DHOnSaKyW9vgjJ8fA5hcKMaHFuiCaCJLT5k1rvSPjwZkY4Yu0cAoeNhmwkxAb1HuucWXgfr8mYSvSPIwlhdRoJ28/SRT/W24DXcFFYUpKVhPacvqNpF0QSaBRNKWWsqupR0JlZY7xzv7JLONtgcVax8tVNEP6Eh8z7hupRrGySnhXl/ZpgRIojXRSaIgIpDMcFsYezUVH@FlsGie/0l/PqAgtw@/UOkQ@uaUdclJQ1@VrajYX3nxVFmyoPwI7QBy@jBzKDtiGbFlsnKcudhVj0GGTsvlR6zLNk2gMlDCwQxZdB9jgdh/HV2jMcmaYSWV9lpp0L6fJLWUYgTEiNtpQQ/6g@Zs5stwAo@klAUhV0xrStsmla5pWRDs/FqAVKggf1xgroTIMAhzCIJBELR@Fn56Vu3vj2nqTBIB6UTvko8d5OjRTthUaXjAaW1BE39eKdCYE48PQz66/vVjB/uaucfQM8M9aEeIIZgQZsAlhGkVtIdUfclFKp3KUCnUUi64SgliBmQh6XyjC7wbOfBbPxkbBzgrGD2OCj9aYWdFM1HNFqGHUL0XuWgJEsraAjYg5MYBGPH1aFVeUmgtG8IRz7umkGaIo4fjY0BLHSgpjUbHHh1o9De4MNhoHFL7qqUByToEbLApkKOsW@cVAS0n3FRXRZrBcwd1Gwo@@YOW9IzjMZ6QCg4B7JpWGgzHGbAbfJVmP7x9RkHAzbUwppfhjFkIEw4dI10GbpS0DNuKlC0pAFwGIauXqDy4IkcigEvAqT0qY6KxRiKMvOH/VsSbBRKEHwT1INjebXM59647WPo3BNbzPC/DkmXDFZqRpsL0CdjQ5TtUrEzz@/aES0VHB4qE/ueppVkci8oRjiiGN0IxEZfuiF@REYOUB1jCQjwYfvKP61xguXtKmx8LFtLg8iXnlSvZdUeQz5TFOYZWnJhJNeRZBXjugbPbE@7/MjWCue94/SzBkZdkAtwEfBjC5@eHFS2yM1riPAAKSdXhJK9JAb@TsxFWyBltto9bJCHlyoQ/L@KN4062ujYQ9r6/kq3IP9K6wOqUE6SsqNifefm6gVfooifgWMazqb4uIVwYtQIMfsdgbQ5EFoq2hAOsmiu26Nnr/nEX5Y4@j1N5RwPtZYK0XKRyRpvXsY/jQMlVB04eACJtHUBfWgHng3f6@USnd4MAiBx8NIfD8MM@humkDgwpTSKQ0PrBUnchUjXKgxY2VVN1SRw/BFoVyMcUPMhAv9ASwAraxEv4jXSspdwN4G@qXbI/epVJ3dcLAFcwnUx7xRGJCR45aXgVujh7MnJrTI2FBUZuq5WdSDJZMpHhopPXNgjtmwUIkMlfbnpJsqAjzPx6rmzA25Iwn3RpM2lKPiEE/sTzc/YWKLZ3voBh2e3FuHqdtbzrzutozIQXoNCD6mndHPDPRzjg18xtrVn86gvhkZl9WLX1BG@M6IkvwZOrWcElku8@NJTUERY3q6YigF@Ex/9FJtU3EvcoRVfKKSVpNQiqLSo9elFccOVguX88gBVccLiM6Rf@L8VAIRK3gEhCEJd7z0GOwIiFG2lBNuQLi2WTBTkEWwAvdQJFqqrbHcZiebzoAblg@Dvkjo6B2CBOCfiQhNnImKW75GY1H4oviFrf33PsF8Z75AjkafcUU/HAAoxnYD6OJUoMa5QH@h2VYqeHtrF7H6Kv0BvyMEaH1L3aCaB9JRdIYR5WxDhBf2rTg7YAwF53Wid4IgEz2JdkwTID6WYzbPh4PCQehlzIgkHqLwa6eiO9O5bQ6MD8DQnwAo5N7u7rCRTBHtINFC9XOqz8K3v6lGzyYHfCzC5GyjU5RkW4a6mh96o0rdzlNYEvBXJg60MCCbEgqPaCYFpMpgYvLC9LcgKfH7qch481gD1mgunjejLEK4B@6kZ4OYFRlWrZoR772UDtkyFt/Myr5pkPQFBLyohaDHNcshWIvFYTjsGf2J8C7gf8T1p4ZSkb@0k4xTVbg6xwRsl0f/z4lAN5YgeqiCLHuzURIXAORdKHKuJvrbaJhyOr1mpntEYSg1f/8jtDZxv5dqDdpSUc2BFQFwELd57TGwPLYfg/3scih0i8i@5pNLIgvFnvkSD0@Zl@NOx4hHZ9gSM/RVyfxtSlCA7lyIz0OFEqzMFCBJSrLmCOO2BSBIzqF/K99ymMfX7KA3u4HBv8iIKXhZdEYvrrUlYN/yOIrxZ8mzD@5k82uPUBRnq4NujactLOMrw2wJ4BJb0kJGSPvLogM6Rn9G2URTP4TCxu7e5TnCaCopJZo8IBkdhiWHNjYIW4aZWZh1x@oSn2CJQ8rBC6DAUmnzEP8/mP353mHYRJIC6j4dOwXgRdRD008MYelgHOjsQGiVMDGvf5sLieW7exQCzq1Fi6QdyIi/btXT6JB60ar6UHpmjQq79xHKU3LivbK5Nlqap6CoYpwLFmQOeQPcRqaNCHbNU0FqHJSRWRJpHtbeDLE1STU0GYicA8hE8jp8G5CAJwEPWmixFcAO8kdboP4bcqcpLnnZQVgjHaJPOhuxAtNyRF@BuMYBm4J3AVQ@uGWYIK3H5wjgo@MoBKGPBnb8dpyRSFC9GGsjjIvw5B4MHERu6A6BMqwczpdeRE75HxdAqZ6R@MZb27eTII6mOK6kAa/Ed58TUrRoILMEWJtu7B3G9cS6NHwryGTkRAeD@bbVclRK8QBbCNW3y4pcxyw24lrLPWnbfIcTNfzYVDLZL/CRMINwhTe7NzN32JGD2hk/LmfGzdufEaM91LQZRIp8P6N/UItnB6SBrRMU0IqshBwAV2HpMs4u0dUOlKPxpGHcfpm46wBlpUaSHBIIQMS/TyJJBPMFMeMYK8nFiwkuOBLxD2UtRFSqlMBmacjIsF3ELJ6cDV4VWk7JOt4ytnGSQ4/90NCPLppDuEaL53B8Z70odDo58b5HcapolhlcJSrXFO8eVBMz6o3hugZJPZIBhlCLLlGMpTPEqIJqQg/Y/ge6qh5O8JfIoeaMZ1dwfTg7nePF@NCmLvSGpZiHmy0@M5t8ITrxiinAxwIn@SQSDdRNJ@dsML1jjvcYKxryeLBzSVLR0MEQI4RzZIGTF7/OKhCuImOMtTjYAVbtvB@pEBsq4ulJlkpmEgGMK83fcne9kFAilCSHYMcHEHl6yl5NJSefVQllIqB6sYxJ@BP8QeFP2T6cFtC9xLjW5XYVrCPjCNRskvvhGEnBrnP4qGVymYkiETb75xAOxvypvcMwcbsJQaLoyB3rYnw/VgPMS8v6Daw@oOgFFnuxzCd3hLxnSTSxXxCoeZcAC8r3JglM/hMFA8WFkgQ84K45b98IAlBFYkZo@Ba080XxcwCOA2xSxfBjhkIw4o/CVpaRXxaLAVzBy66udUommI4aTz@WYQ358WaY1Brj4DPfh2wqppp9ogi5dBqQrCG1lGag4fbFZdM71BcqrzZOjYk6KDf/t8IkkBAF1W28CTWq9aXxeVl6qackWgo1Y6@Mg62TmyTtbJIG802TRIiU4msYG5YBrhxFs@JhO8W8DlydwZHkGfYT1ErTGT2yT9TBJ1c4sugeQznjHfzUZ2oNAKglVhh7MPdggEMijMIpIUERzFgFAcwDyNgMZHUmhyAleh0Qf94OTAC2vyR5nJ/3WxMIe0l8zNktODi4P0cgWOlILZDdZ/TMHU7WkWEEwRGQIRVrKeoo@wDZaSBsSyMdqea5aAPx6X5fPRKLSMfkoYi8MCvG7eCkNGeOaWd06E@JiNccBUEVFPQiXw6mQ4FcJyCFPXTRaCOVRY5ia2vAAMlp1hrU/SF@aZdNQHECgnQSM23diUcXYwD5yaPHMkZ4WfVdZFNWaHQOldHkNS2uaGSyxAzNDYFQRp7pb2JURROfe8PCCjopgTo@cWIGar5pGa6@BlwOddgi2W4AwXfLY4CLQteESXfcMaINUPWKoROGcFNc@@dAwZuIB3qZB6HPH1gNaRhqJnfM11fsXHg/@ISpZgZHWqDq0IpQ4d0UAsRuQ8yF@zjDAepBNzmQxOKEVXUeJKd5L8URmAC@F2QloxHfAPV1jdMFvMcpX8Q1NI@SwlvcHKo1S7yg14W5@IMxj7wafAGCqZQkHle/j8Vb2v4FCM95vsmFalUMT4iVTf@Rp7TTos6zgLAXqXQVfXiKtgnuyW86buJQCnjzYF7cTQtILH1BwnU0Be2wFLA4csYMVSX8Y2pDyUKU8sLDeGeS53EIRhGZUxxzks0EgvW1Yx0IceiVOScUZ3moEDPGuasj4HAVdG55d9PKE6cR@HqSfr6yMTxfNF5CzaQQC1dEgDolQF5DawP0BdWk1KUTyGtHJJJzOpJr4zJLx1swsv6kTDKVoVhXVKoVZaSWXJDIipoKfrHJeoBP0FEvJyF9Knr1eF2m4gSQMaJMAWQvtwgcWXVSDaNtpOWdgQT9QUWH2C5/wf0VnnJB4Ms9m3Syvsb@MfpFGJep11TquRGeOZEwObjf8ALJY9wsaPtQef7J4cC8dTwMQGgJg@8QHJAaI/nUAcFfxzWM9wCLN4rl8CNSdFNTAxznvMchPyJ/398x9b5SCxnkx7yc6R60OFKn0Bpu@kJ9y5r0dIJeFx/A22RqdnJ6CMpaRSyIRurhFTCOiN8das2TRfvEyQzQFB@4mODheR7D@X2Z6DPquxMKLTa5rs93ET7WbZcAz7gQjEY9w8CXxmT@R8/sDLkaxmRojIA2yrbbHyqUzxAttG9BqcDILDG3UwQNipVJyqpay8SMTSH8HtBEz6dRMPNimuhkGAICmRDYgC9ugexnj7OmCkl4qzteQGQTDgNhugDwsD/vZHNF8eduuZQ1KM6Ll@ShLvCsJURBI0l8RctGKqxedkagRaGPq76xh/D4ADpMQXuUIAjWX2/6JFjdbz82tEkuk4trwVgstXx62a5kkmTqlQj@UfuBHFptb2OJeJnJrCC8LFJgVzc4Me7jg3e26cFWbgDfkfWMMWnZrALLbl8hvpzCJXTzUsfR4TZJtvZbRXiGf1kTRTnCRq6wXUw8ggBdwRMJx0C@FhUEkxuguxwDc4lGFdp7Tn2@lRMaiVBZtcgMIoZmydCtHdR3ReU1KKjCuPYs0Vwd9rEV@IWMZMPcQx0sARXBn8TZHZEWjmzM3ng5Vx1YTV2wFw0WUgTcKrVPOoMoSFVYIA2K5KOFpSkZYbCCGBj@aVpF@7AoY/E3CYq/hxXHoTfYhsRCpCt6msYJeOE@pz3ZpFwAq9YLqLdr2xD6RBhHRK/@SddW46u5wgJIRw0SJEkXm/y50veBVsVgCx/PwtvufqFR78o2QZqJdmIFgcLWmrFh9uXOk3RGSfXxJ84LYc1le@XygYWeeXMTNnbtEkEck7hFioOpasg3tndJxaSDUHEeKnK4FRua5BqQYA0O2mWlE60odT@sDPUF2Z4GMQHz1qtLHNQ1r8RA1cj/j5QlERA05XgNCgmwZ7m6YgZP6GE9veywTLGuTS/rDCiFX@98NwYxDm/4CIepmTzz7fqJe8pSlAUgTE@sxHIz60t@/LSmrBC3NlXL3EhzOTpLDQbopyhjt7/kFjy6ZqBPd7tdppkUg@EDi5XgOFFYiRti9gYEB@qdMIbgNOJ@UEKl00qG9xW2mXHg5HAEKZQSsOKxif/vvt5A9f8242kSOk/5XABm8mJoPftpROO4aX4GUCBt/HcRaHD8qY/44uGFogjEPspS@nS8KF1@An3OyGKY9isAczZlyC25poIHTTE5tlBNkcZfyG4toFqAAYdgTvCTyVtAlzh8EHC/BKZokKb81Gpo/z/PUPuv6woLleAwyxr/sFkNS3Mo7xWKY3SH8T0/JXWdI18IZO9r@0SMCwZI44AUElZnIfDpmEdwoEaU0mEnaXowYFa5zCSsJFAyxRDuJAGKqnKnM0Wm9qVahLE9YlYgzqpK3iKUZf0xmt@YW/1CbIkf61WfG0ILGQgqHQ/7RDwcnU1HGs73huz/yc/1rcptfxkXq3Dg7gvX@cljMndbW1xOP@T1jqNWbe9OV9xHIA/ojddHgN0kDULliMYUchvPx1u9@ew5bi2iNNJtNMz6qMSJf6tyQVQK/P9tEbgQFqEbYmi82nwKTsJENCe3VbUtGFc5sRFRICvghPUWR8CUBo@X@wt@kKHGmwYcKtNnsDeCobMZ4H9rQT8zYqBzbgnZz2oYTuhIkBFNOFEV3W6afj3Cd8ZCBdy1XpLXzqFJ0Stg1wFinA1JoS@5msCZHj9i@3B2QD0YDYHeLLIn1MC9bh560tDyuaSMKKKCCAK4I7YqhQekz067MaX3XDXkiJ7WJqMiaB6vsOljbyNl4XKpawK4xyDtNUg@ieIO22TI1bQNcg0HJU4HecnPvZUrMj0FRYFeRbB0gOODU7id@GeTJf31D1X1sd7wj1VnG1NEWBMU7Q9BvcvCv5aMn5QnIGrbtKaarugMx0z3iPNXWgK0qrjYvljjt/jTgcdxuZcSN2yfpyknURprtgxr9uWXfMm7cS8GukRNlLW@FhXqAWoppTCKTyxQBFHTvWbZeXwHl0ZWjGjlofIzijoAqX8ymyDQYi2qKRm385gpfYBEL5y4d/@nHa6rYB9z@tZVL0CHPCS2/Mow7i9K5Pp5JSSyImcuNgH0MVqwGP/dH8je3Lm5OalCw13QHJI9V@iaaM4ZoSNoEmb2QJEKBArOe3NSrfvtp8kZitTlHGOlSAS4sZNW5Zhkt0uxXmsxhyph8Q7EGgagb40XrkgTifqZUuYIgIMSfzmpcwqyc69MTtVM9szI9HWm1iOy8MMBgyTMTWuDZTwoH0eozFXYKdZIAaGEH3sLJ2YAJYBJrHj1PznVX5nbJbcrpVelp5rJsbjVi8PalRwmVZhbCLVEfTj3VyrCfq1rqY0/AGv6pXr@C4q0h6ClW@szW11DNO7O0HYzDmCPWjTjFpyuguB7YFCF8ovXPq3LpsenDyEd5nsRsuN/BZ6tGgEMvc0OrLY5vATB1zuNP3yLb95YbOZ6BX84caEuY8nZrAyPDW2sFjKCdCwkJEY2h81AqotS9Tf18d9dHqXoBfjKunIHZx49YphDzk8vZbmCeBXqcTkBt41QgAAxt@5iEZLFENsJu7u0V9r@BoT87HFGDr43QQ32exi5q7gNjKBXHqu9wN5W@ac9SDAYKdm9KvpluhhTh9MziNDaIFhjtynXEsLOUqyr90rLV3iZm@vqazNhab4OluM5LKseSoho9hnpgBhL9J3qDePVPLOzbQUHGHqCC1v1im2NRkjV1nS3KABaKMBC7fP71ACeMHPkCJvWwf0u30qFVWXc0jUWvA9dx@ZuzzhIBYpstKJwerX/jSpflctSXZgMzVIXyjQHCg3F7c/MVJ495LWVGD39wlo3L8fO0eMxiYnu4x9q7r2f8FDqEWTgG/NJ2Yl7aT74/Oe1Eh6JSMzS8OqnGLMlUWAizN7hkB69cpFC3GYwMvifEfpyjRiIFCKXBLCi3YOCZTn6hu1xnxCBhmM9pKWSc8933fqp7EAptIEewnPuYYao2L2l1Jyk@fGCXnKDjyxVrGdHOpCe5dTAp0frKz9MW03tlx4xxxWtgsoYJ@6XDEppRwuwmOMzn4@t5zr9dGbvIMuPKY5lMVDjFDBPzYieONhYiwrrlYxsiPcHONyivIHSc3IzhCKo/a7Wpb3iY2lAMd0oJE3BTeTy4oPSY0qkcB1dofTCvVs9PCId5OFxyYtXOeXDc2W1yP3kmeT3LgxyPT2zupyW3/7U6Q7wElvVm2SgX1BI4ckPAU17@@61AmehOIXX8@bW1NQwjdWgkSuCG4IH7jtxAQu83JQvjhJWCm4e4BurQi5SSloUR8oPzPbezijiE9s5UCFeTz6bVrp52UgolguWEOQqOzfQVvtU/EAVh2aGV6VDOIT@a9teA0BrLlzL1zpC7ZpGFmx/rQCdl/b7q9wRL2vIPc2vv9Gf2G9M9Oxe8oTAwwl8Xey4WdJjGCetWe6B5cObb@BFgyJMftN5dtrGdm9pUmyGeHCwtn7cDJ49t4eMs34qSuveFawmG3ojytJB@o5ETJ7Uv78bod6o5OHo7IzPFRm14asz2PDoEVuuXKkhSlV3COrb8Ubec1wWf2f1B6ssH6ISRRR97l2tiG3uphs@ig7GYPJdxrlnfzJjECQIgIc/cVANS101xPDFW921TBdJty3WsJ48uYxlLKnoiAbhKYyQOurJHGSPmyN@qBZqwmmCAFGso75qiY2uXCPQlkUVhdvORC4ctR2Ev5BaBDslCJiGQeKvgKkW5XThk652v3SFtmpLLbvKdj2z9uwwCXrp67I15YtKPjacuV6OL7jNKEv/Z25pvZ17w7Rwo/bzsxt/bdLS@pdgEBzJpIs66yYjPyGUUJVFkuUCxJG2dIH2eyq@Z86OQBrvW@jMKM4Fpff7XAt1Ml9VG4mEWlnMxNwTCJOee5UclBaP3ciqBUo3l9f092oqO@K8YNXIHbJ2MIHTgRTdsrf6@WnF5hozq2P7Uk2eTRY2nhpO0K@1lAKyAE6bwz47UUTGQPGwvAr/u5jFpjBuu07AzbGH8ITWjaD4q9fXtlaWcwA8RMpRDwhDCXMkS@uyr2yq7nqy7eKNu4OT5qk8BMIsvt0F@Lqu/ywp7lR1u@DZbrvCfrKF7Txm0zR4Zl6LgZY2ADAe7LiBAnOQLNR@tMbeQWeN2BleLxBQeYk6zIW2qPbY8lq6XO817F7MaehaY3tac@pTxbttYpayUtyqMVghafVCKiJj3rsGFG6mTVEHw/SkfF816405P3KPTUNIEXAJPPC@GLaUDBynVoBbSn7N7KAJpLEkMFBWrDrYOckno06T7AaL1gEYQEgYPRa43Y4OWxn4E3Df1i4Sbe1hZXVUs7f/bgXfUXS3LQc/caVsIQKjQKK8NzTzOYgQ@YoZLcrcDFZ8l/XiendQCB9RM6vaQxHLyMpGRwpTwzkN8OTp3QGDeW1Csh7J3dMWDEWNvYzP/ROGzHDHSup/fg@qINMYYWj44J7aMt1TWAk8tMqH/J2hVrsc62YZodQ3JFlXjiwqtmBXMwiSfx0tybqWXtbJFNOdNqcdg67h2uNM3N5R6cTJRyS6Hm5Nnt4nbkPpJV6LSf6cb4ihA9qNOHgepdjtFINc@@CCLcEdt83bNPGewmjBAXaQbIhjfixSGWcnYNMLKaAN9Co@4zYhgb@GXeDbB@gOVGl2lX7NfLTsBuhHDwy6Z8z8knhREJcNPseBzDXux9tMaJ7p67NIk3Yi3IWVcFKFx5Vib9/Mt4n087Yy08hvlKlriN96Q7VDL0O56WIYQMwHPTrgobj7781rF5KqQMP89tkyv4QJbxEtFnJhDUbHST141bdXkj4HhpWM@k4@wPsH8mTldsjxrik4Ddcc8NP5N3@5BVlQlRZZdF7qLWoy13jLsWGBpQUXjTxqo9HTfG/pZ3eJbsP6NscXbNmErBTDL4G/zS774hDATkw7serse5gke2LInE/gTb5yHkjkpi57I4@03/2v3@sqGJs4pPkitO1ugp7fSyTdXcFHZNop1qwSnkYLU44vYVTItzqZixycZsb@ikk6Ii/BD@FumPML78450Sm2uy9Ah7AuSFM3uccYjClGwzdqSSDYJ1buVkUlk5I7CfHknKtxNkBwUWAsA6lQlKg9/l8Bufxq4Gsp9pKK0muOJe3yljvrrYjlFTnETVWlhRjtoS7vFKhkMScoK0OgY35QOTZx3GDp61VIpZefuywRqEm2vCZX1uSi7J4A6VU4j78tLSURODjzgdHbzjAjhx2bKpAcSkz6b9FKRECwt6VLK6KSrvOwVtD3iUQG09si8iLP9gt4TrN6Ta0ujyaN1l0AH4eXSOw@iYmeKSY5nAdXP0WGuhR6OTKMuxxCO7Sc7tNon63nx6bjUMW5mI8n8ECMIxnTPcSM8pdVmAsS4LUWiNS4tM6UecQDK@U5oR5w8XTFid0ap4TvmCxbhYZ7QQ5C91avhUPpcQqijn6hbP7weIhtP7xzj0u13caA6fibXUtTxEL8PlsYuztBuABAQXWT7GwmWM8@gnUERbV8D7LbYnRamx@fTHa0mw36jzM9eadK1b7k3Ja2Z@wvtqQAS0M9sHJ8vT58hg5nACtL8G/uIBXGYlMZIjYVFpNNnsOWFzwKY/Q4efp/qI@xhcweryIaffPt1atSdTeUD/zBo8WZMmw3rPfmOLnmNnNoSJK1LiocirYgtIeDQm3rzonS1xiRweBM5W9/wKEJlE3YDrxjrWtFe3dD52Iw4OG6R@qcdxDxGWCnaPdZzmeDK7n79v2D/LfoGgb0zY3y9JoUnbXAMDK6qmCxChNTOCNyUYtg1Daadl7PB1T2OGZm8EswaHvNP0sTpef7iozMJmcJZmd53Fs5cGgla9b2dJApUpPsx67QoYjj2pe4lEzS5T9pBB1Ki9DKGdIO2ZBnEU5jbq6g8PclkUkH7OzuJmgbP/KGBjWphMuJnvg6sewE/C1mFUDr/py0xwF2iKCnjN4RO4mMH2oqRWSSoINW@Dhsb82fLAw7uX3W0LDoNZOtJHRJekDEqTtu4zbQPWlrqHCMrd3NgKnEL98dKrvLFXmR0Npcg5PY4G4z2gX7UeJ/eZAuYikZkrAGSXs5FoBeXu2pi4ndjNXqRvmN6@s3Bpd5GAycy/5Npdvh3zFrwOEPuoM/zQg1SEttr7XEVN61EQE6XyLql3SZpdPjw2ZvqIdRaIYOHZY729V8PtR8XpcSqWvXUulfNOlNS2pa8u/ALPBOy9m8wkGOl3sFtZKS3vu6EUX0uAysVH6ePWEFlsP27iWWEEvLOazHWouSgbrBM13s9jmj9Nv0@/sl6oyI8TL82UF@8tHNYLCxzvr/2JFncM/DzZXo1fOoSxiJzm8QUDDRvE3zmWQ7P@srOz6OdX@OhGtcJndzTu5KGuCMPZxa@Xg2jbdZ/9GXUOyj8wy3PECB4jtRHb/TapTnH0r1MKTTMX3lvu8NsCoglW3VZgL6XCDUiPDLbhcItzHAUFjjsIaCPBVtz5IulbDbIMUa1WeAssVsmnB1KgSznJoYZl2ZQa8NdHhQv7IApyWu7WJxf52wZWhrX4cAUB@5/YHzy7eLhp6BCW27eoZ5JW@dbN6SKlzSoStA68k5VFSKCC5ea4@7ZyiL5HD/EwuoDZWBeiUwBYPk@Ij20KnIXBRr2gwXxT4zZsQRVI5uuwkj2BEzb4tSghDSy0ExSCRI3o69FXghthwrMh4XwPmNTPHZwvXQbjGZYk8L1362ahb@miDAx764rdOx13vmPk8@3k7IKxlb9XABd/pVhAc3@9bJlyVdFudvVMM@GI11gKWcyv40CA4XI3pcQc7929JuVoVpWO@6F3eFSN1xhdr3pScX0I1q8nSgGJPltNsz/Z1gejM9xTAB9Wx@effaJrgBv1et8v4VHggX0zq@cb41XcWKQmnYB5RVOBTWpEAF87lXo7bW6FBxO3/kNbjoaJbdcM4dAENGY1dxibOhc5Q5wd1@NRTC0kyjWA2zA90lLTTio33aSyyNbYYDfcqXpKxFiYrdTGzppoIjf6AED1Ehni202cAE8a8D/ykrhn@p88dihTAtPd3krMX419uC0ahwGiBFgacmynWZq@lgGia@UrhOttitvprCC8PO0Zf/mKoAflIPjQkVoIzXrXf02xMtx7b0um/OBQav1/ "Jelly – Try It Online")
```
ḲµḢ⁾-ryViḢċ@¥/ Monadic helper link:
µ Consider
·∏≤ the argument split on spaces.
·∏¢ Pop the first element,
‚Åæ-ry replace the hyphen with "r" (inclusive range dyad),
V and eval.
i Find the index (or 0 if not found) in that range of
ċ the number of occurrences of
·∏¢ @ the first element of
¥/ the first remaining element of the split input in the second.
ỴÇƇL Main link:
Ỵ split on newlines,
Ƈ filter by
Ç helper link (is the password valid?),
L length.
```
[Answer]
# Ruby, 80 74 characters, thanks to pppery
```
p $<.count{|l|a,b,c,s=l.split /[- ]/;a.to_i>=x=s.count(c[0])and x<=b.to_i}
```
[Try it online](https://tio.run/##RYrLDoIwFAX3/Yq7cKFJy1M2hfojhJi2XHmkAZQSEfHba1ATz6wmc26Tejg3wC7zdD919rmaVVJFNR2F8cbBNBb8nEHhp9Kz/bk5iVmM3@9e50FxkF0JcybUp76cC1kCmoNUusRLRRIWRtD@fcsLh@U3ErMYag613CBHFgWAHLDCFq93xDc)
or if you dislike "magic" numbers:
```
p $<.count{|l|a,b,c,s,s=l.split /[- :]/;a.to_i>=x=s.count(c)and x<=b.to_i}
```
[Try it online](https://tio.run/##RYrLDoIwFAX3/Yq7cKFJWwRkU6k/Yoxpy5VHGkBbIiJ@ew1q4pnVZM5t0I8Qeljl3HRD65@znRXV1FBHnbTc9bb2EB0ZiFO0V9x35/ogR@m@97XZqLaAMZf6k14hxCwDI0BpU@ClJBmLE2j@vuRJwPQbSVkKlYBKLZAdS7aAArDEBq93xDc)
[Answer]
# [Python 3](https://docs.python.org/3/), 121 characters
```
def f(x,z=0):
for l in x.splitlines():n,p=l.split(":");m,o=n.split("-");z+=int(m)<=p.count(o[-1])<=int(o[:-1])
return z
```
[Try it online!](https://tio.run/##XVPbciIhEH3nKyiftDaTCt5iJuuXbO3LQAC5yQBBlp93G9S95FijQ1c3p8/p1v9K8uw21yv74Jgvy1M9vqxGhPk5YINPDpfn6M0pmZP7iMvV6J780dxCy8W4WL3bp/PRPQIDBOq348mlpV19P/pnev6E9/OPgfyE86m/j@2AcPhIn8HhevWhxflysVhshgNWI9ZRqZSdmpT3SimD9gN5wXHEMVajQ2xAZNjiOuLqKvcVvQ6EYDtixjWdii3WWZuyTcxB8RuWI5ZGSi2lnNEBAn7E/o7sewodMaVUwEMtpRLtoBcx4kloIZRIWQiHNsBZRlyK1Ii8DGTdL37AtC/mWum@yahKReXQ20C2rXkdqbmkFK1XiUXgfMVmxCIxOpnZdD0MBGjHlKYMznusoaqBakvvhJ3@jlAMWg87nEfMCwPLoMEdnkGasnpmdnZ19j50KQnqkoAPlan5SVqHjidVleVGzSrQbgNIDhEkCyvsRcGvyGJChDRu4Mk6M5tZzvAgshvIvg/hP4hSEdkM5LUXfIHLN0OAnZrAdbhIaLzmeVaok4AnxiijqovGGM7lZCraglmPARVq6E0BMKepzKHW6TIFRA4DeWtLoOxk7WyjtLQaL7mwHO7e3TYoxxmu2z28vfS7OThIZ84L56gtYTtzXpOsvLW7/qLEZhC/bQpbYuKGQrZKKmSuObeZ90sdDMJZVxxo833eAcwNQQcbIIFsWg8sUM1qCdHWoGeqHUwL7IFxsfQvuqPbRx/8by9t9dfNThWMujiaYJaqqM4H2Rcqec0W9B/6et1Q2X2dYNwi5xqEEUH8AYL/4mp1/Q0 "Python 3 – Try It Online")
[Answer]
# Oracle SQL, 231/186/117 bytes
```
with p as (select regexp_substr(s,'\d+') l,
regexp_substr(s,'\d+',1,2) u,
regexp_substr(s,'\w+',1,3) j,
regexp_substr(s,'\w+',1,4) p from test)
select count(*) from p where length(regexp_replace(p,'[^'||j||']','')) between l and u;
```
[Try it online!](http://sqlfiddle.com/#!4/40e8e7/1/0)
The [obvious shortening](http://sqlfiddle.com/#!4/40e8e7/4/0) takes it down to 186 bytes with a marked decrease in legibility.
```
select count(*) from test where length(regexp_replace(regexp_substr(s,'\w+',1,4),'[^'||regexp_substr(s,'\w+',1,3)||']','')) between regexp_substr(s,'\d+') and regexp_substr(s,'\d+',1,2);
```
Using `regexp_replace` to construct a regular expression to match the full input takes us down to [117 bytes](http://sqlfiddle.com/#!4/40e8e7/38/0).
```
select count(*) from test where regexp_like(s,regexp_replace(s,'(\w+)-(\w+) (\w): \w+',':[^\3]+(\3[^\3]*){\1,\2}$'));
```
The regular expression is:
```
: start at the colon
[^\3]+ read in the space and any other characters not the key
(\3[^\3]*) the key character followed by any number of non-key characters
{\1,\2} exactly lowerbound-upperbound times
$ end of string
```
[Answer]
# Scala, 84 characters
```
_ split "\n"count{case s"$m-$n $c:$s"=>val o=s.count(c(0)==_);m.toInt<=o&o<=n.toInt}
```
[Try it online](https://scastie.scala-lang.org/5nPJH8YhRxCvQYsqlwJcjA)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~138~~ 130 characters, thanks to pppery
```
n=0;$<.readlines.each{|s|i,a,c,p=s.match(/(\d+)-(\d+) (.): (.*)/).to_a.drop(1);m=p.count(c);n+=1 if (m>=i.to_i&&m<=a.to_i)};puts n
```
[Try it online](https://tio.run/##RYrLDoIwFET3fMVdGNIKrVZkU6hfYmJquUKJFOQR4@vbqxgTZ5KTmcz00/HmvVPrbJHzHnVxtg4HjtpUj@fwtLGOTdypgTd6NBVZkX0RUfYlEE7lB0u6onxsD5oXfdsRQbNGddy0kxuJoZmLlAB7AtLslJ1/NgybXOlvpK@sm8YBnPeCpWAk6KMp8FQGKRMbqP99nu8S7j8FCUugklDp2cGWbdaAErDEGi9XxDc)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 43 bytes
```
%~`(.+)-(.+) (.): .+
[^$3]¶¶^$3$3{$1,$2}$
1
```
[Try it online!](https://tio.run/##XVJbbtwwDPzXKfSxBRKkDqJ9ZeOrFC1aS5VU6gHrAdlQ0R4rB8jFUkq726YZQzZkkBzOkPF7/uG/sdfXD7@/3tzf3Q7tRW/ub0d6f0c@fdnsPr88vzzjd7P7uWEfN9tfG4Lhu@FEYaQmAeTiYYJ5BgBLjgN7oGmkKVVrYmogbNjTOtLqq5wreRwYo26kQho@rW513rlcXBYek5@oHqm2WhutdSAn/DGPdL6gzD2Ej5RzrvBwx7kmB@xFjXRSRilQuSjlyQ4515GuqzaEPQxs2wtfYdtL@JZ6bDIqQAJPnga2b82bxO2Sc3IzZJGQ85Hakaos@GSD7XoECjBegOEC70dqMKuBG8cvhJ3@grhash0OtIxUrgItwwYPNKA0cCYIF3wN8xy7lIx5WeHDdW5@stahlxkqOGkhQOTdBpQcE0pWTrkF8KuKmghjjRt5iinCFVEKHsIOAzv2IfwHtVbCdgN77Anv4MvZEGTnNkoTF42N1xICkE6CnlgLFqpP1lop9WQr2aNZ1wGt3PKzAmTO0xpirdMyRcJOA3tqSwBuci64pB2vdtZSOYm1D@cNKilgucPV26XXluggD1KuUpK2hO0uZc26ytbu9p0SV1D8vilsgVlajtGQIRZppHRF9qIeB@GdXz1qm/u8I5obo4kuYgDbtR5E5EbUNSZXownceJwW2oPjEvktuqP7ax/yXy9t9bfNTogWFs8zzhJW6HwYvXAta3Go/9TX64wqLuuE41al1Kisiuov/gA "Retina – Try It Online") Explanation:
```
%`
```
Loop over each line of the input.
```
(.+)-(.+) (.): .+
[^$3]¶¶^$3$3{$1,$2}$
```
Write a script that deletes everything other than the desired character, then matches the required range of characters, plus one (for the character itself).
```
~`
```
Evaluate that script on the line of input.
```
1
```
Sum the number of successful matches.
As an example, the script for the line `6-10 s: sszlkrsssss` is
```
[^s]
^ss{6,10}$
```
The first stage deletes everything except `s`, leaving `ssssssss` (1 for the `s` itself and 7 occurrences in the string). The second stage then checks that there are between 7 and 11 occurrences.
[Answer]
# JavaScript (ES6), ~~ 89 ... 84 ~~ 83 bytes / chars
```
s=>s[S='split']`
`.map(s=>t+=([m,M,c]=s[S](/\W/),k=s[S](c).length-2)>=m&k<=M,t=0)|t
```
[Try it online!](https://tio.run/##XVPbbuMgEH3nK3jaJtq4jXOvtekf9Gkf9qFbKTEYKLfYgIiF9t@zA0kv6rFsC3uGM@fMII/x6Il760NlT7S7sP3F75/8y@/9ne/1W7h7PaDDvTn2E/gcfu4nL2b2PCOvewh5nTz8/fMwnanrgkzvdWd5ENVi@rQ3P9Sv/fMs7OfTf@FCTtafdHevT3zCJuhQV2tMGnxsCe0YR@uqXmD5uc6/U4PTDWhZLbFosDjmC62qxRx3De54J7vh3HUHNJ0i9J1jWe3ynspLGaKVrex7KaVGm6qeY99g75NWzmcA4aoQ2sT6hLZVXWPTYMoUaUczGmtMiCZQC8mPpRIthBJCDGgHH/oG9zfEvoSANkIIh5sYQgQI3GHe4JYrziUPkXMLolZ4bPA4CoXqeXYgb/wOnR/U5tRNlpGk9NKix6pe5eKVJ/ocgje9DNQD5xbrBvNASasHXfRQEKAslYpQWG@wgqwMogy5ERb6G9yo0QJ8jw1mIwXLoMA1HkCaNGqgZrBp6HtXpATICxwuIkL2s84VWhZkkoZpOUhHig0g2XmQzA03ZwlvHnmL6jpzA09UkZpIY4Qb1TAEm69dv4KPCdXLqt6WhG@w8WoIsBPtmHJnAYWnOAwSFRLwRGupZbJea82YaHWC@dl@NGgkmlwVAHNox8Gl1J5bh@pdVT/mIZCmNWYwXhiSdC8YN6zMZ5mg6AfYbv3u7bnszcBBMjA2MobyEOY1YymIxHK5i29KTATxq6wwBwamCUTLIF1kijETWdnUQiOssaMFbX3ptwNznVPOOAiol7kG6oiiaXTeJKcGomw@WavcLhq@oji6eq@DfdaSR7@cROm0PFsSoJdylIUPos9EsBQN6N@V8boi0ds4Qbt5jMlxzR3/QD6dl/8 "JavaScript (Node.js) – Try It Online")
### Commented
```
s => // s = input string
s[S = 'split']`\n` // split it on line-feeds
.map(s => // for each line s:
t += // update t:
( [m, M, c] = // [m, M, c] = [min, max, char] obtained by ...
s[S](/\W/), // ... splitting s on non-alphanumerical characters
k = s[S](c) // k = number of occurrences of c in s, minus 1
.length - 2 // (so we have to subtract 2 from the length of the array)
) >= m & // increment t if k is greater than or equal to m
k <= M, // and less than or equal to M
t = 0 // starting with t = 0
) | t // end of map(); return t
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 90 characters
```
Count[FromDigits/@(#‚â§{#5~StringCount~#3}‚â§#2)&@@@S[#~S~"
","-"|" "|":"],1>0]&
S=StringSplit
```
[Try it online!](https://tio.run/##XVPLbtswELzzKwgZCFogQk0/EkdACgMtei7gY5CDRZqk@YpEsbTAtr73P/pl/RF3STsPZATalry7szO7stsgd3Yb9nR74venL08/XHj45p/s173Yh@HT@sPk35@/PyfL4yb4vRMl4DiZ/4ank9nHq/V6vXmYHDfHClXXVV39qjCcpnq8Jp@nj1doc3/O23RmH07f4WdY83VF6iWmDd62lO24QMuazLB6vc9/pwanC9C8nmPZYLnNF1rUsyneNXgndmrXH3a7CqGXyvN6lSvpQakQnWpV1ymlDLqpyRQPDR6GZLQfMoBmUWhc4l1CtzUh2DaYcU3b0Y7WWRuiDcxB8l3hN1JqKWWPVvCga3B3QexKCCiilAo41FIqQdYKiwa3QguhRIhCOJCywGODx1FqRKZZdy78DJM/mMupN1lGUmpQDt3VZJGb1wM1hxAG26nABuC8xabBIjDamt4UPQwEaMeUpgzub7CGrAyqLb0QFvoL/GjQDNyODeYjA8ugwSXuQZqyume2d6nvOl@kBMgLAi4qQ/aT5A4dDyopy43qlafFBpDsB5AsrLAHBd8iihYRkrmBJ@rIbGQxwkEERn/zdtZniDEhMq/JbUl4BxfPhgA7NZ5rf5DQeIp9r1AhAU@MUUYlNxhjOJetSbA1ty8DGqmhZwXAHNqx9ym1h9YjsqrJXV4CZVtreztIS5PpJBeWl60sGxSHHsotn709lNocHKQ95yPnKC9hvuc8BZl4bnf2TomNIH6RFebAwA2FaBWUj1xzbiMvRR0Mwlk3OtDWlXl7MNd77a2HADLPPTBPNUujH2zyuqfa5fdpkcfFwlsURxfPffDXXvLql/dPeaMOjgaYpRpV4YPoA5U8RQv6V2W9zkjssk4wbhFj8sIIL15Qnf4D "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-r`, 21 characters
```
$+Y{a<=cNd<=b}MUg@+XW
```
[Try it online!](https://tio.run/##XVLJbtswEL3zK3joLRAQeosjJEB/oL0VbY8VCZIZLhAXUASLfrs7pO0ueYZsyJiZt8ysb@vl8uHh@88fL6/8s3h5XX59@qI@Pnz7ernspzOFmZoEkIuHBdYVACw5TeyRppmm1KyJqYOw6UDbTJtvcm3kaWKMupkKafhSXXXeuVxcFh6bn6meqbZaG611IGf8Y53pekNZRwmfKedc4cMd55ocUYua6aKMUqByUcqTPXLWmdaqDWGPE9uNwXfY/iV8bz11Gw0ggSfPEzt08SZxu@Wc3ApZJOR8onamKgu@2GCHH4EGjBdguMD3EzXY1cGN4zfCQX9DrJbspiMtM5VVYGQo8EgDWgNngnDBt7CucVjJ2JcVfrjOPU/WFXqZoYGTFgJEPmJAyzGhZeWU2wB/VVELYaxzI08xRbgiSsGHsOPETmMJ/0HVRth@Yk@j4R18uQaC7NxGaeKmUXgrIQAZJJiJtWCh@WStlVIvtpEDhnVfUOWWXx0gc15qiK0t2xIJO0/suR8BuMW54JJ2vNlVS@Ukzj5eL6ikgOOO92y3MVtigjxIWaUk/Qj7u5Qt6ya73N07J66g@UN32AuztByrIUMs0kjpihxDPS7CO189elvHviOGG6OJLmIB23cNInIjWo3JtWgCNx63hfHgukT@FyPRw12H/Kuln/6uxwnRwuZ5xl1ChcGH1RvXshWH/s/jvK5o4nZOuG5VSovKqqj@4DLF3w "Pip – Try It Online")
### Explanation
```
$+Y{a<=cNd<=b}MUg@+XW
g is lines of stdin (due to -r flag); XW is builtin for regex \w
+XW Construct the regex \w+
g@ Get all matches in each element of list g: this converts each line
into a list containing the two numbers, the char, and the password
{ }MU Map this function, calling it on the four elements of each sublist:
a The first number
<= is less than or equal to
cNd the number of occurrences of the char in the password
<= which is less than or equal to
b the second number
The results are 1 if the condition is true, 0 otherwise
$+Y Fold the list of 1s and 0s on addition (the Y is just there to make
this operation lower precedence than MU)
```
---
As a bonus, here's a **29-character** port of Sisyphus' [elegant Ruby solution](https://codegolf.stackexchange.com/a/216034/16766) using regex match variables:
```
{a~XI.s.CXX$`<=$1N$'<=-$0}MSg
```
[Try it online!](https://tio.run/##XVK5bhsxEO35FSwEpNrA1GV5YVepUiRNGpfJkiCZ4YHlAYpgkPy6MqSkHH7CSlhhZt4xs35fL5cf3369fnyf3n94fd18fX7ZsM@bd88v0@bh56cv6nLZTScKMzUJIBcPC6wrAFhynNgDTTNNqVkTUwdh0562mTbf5NrI48QYdTMV0vCluuq8c7m4LDw2P1E9U221NlrrQE74xzrT9YayjhI@U865woc7zjU5oBY100UZpUDlopQnO@SsM61VG8IeJrYdg@@w/Uv43nrsNhpAAk@eJrbv4k3i9pxzcitkkZDzkdqZqiz4YoMdfgQaMF6A4QLfj9RgVwc3jt8IB/0NsVqynQ60zFRWgZGhwAMNaA2cCcIF38K6xmElY19W@OE69zxZV@hlhgZOWggQ@YgBLceElpVT7gz4q4paCGOdG3mKKcIVUQo@hB0mdhxL@A@qNsJ2E3scDW/gyzUQZOc2ShPPGoW3EgKQQYKZWAsWmk/WWin1YhvZY1j3BVVu@dUBMuelhtjacl4iYaeJPfUjALc4F1zSjje7aqmcxNmH6wWVFHDc4Z7tecyWmCAPUlYpST/C/i5ly7rJLnf7xokraH7fHfbCLC3HasgQizRSuiLHUI@L8M5Xj97Wse@I4cZoootYwHZdg4jciFZjci2awI3HbWE8uC6R/8VIdH/XIf9q6ae/7XFCtHD2POMuocLgw@oz17IVh/5P47yuaOJ2TrhuVUqLyqqo/uAyxd8 "Pip – Try It Online")
Explanation:
```
{ }MSg Map this function to each line and sum the results:
XI.s.CXX Construct this regex: -?\d+ (.)
a~ Find the first match in the line (everything from the
hyphen through the char)
$` The part left of the match (the first number)
<= is less than or equal to
N the number of occurrences of
$1 capture group 1 (the char) in
$' the part right of the match (the password, with an extra
colon and space that don't matter)
<= which is less than or equal to
-$0 the whole match, treated as a number, negated (the
second number)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
WΦ⪪S κ«≔I⪪§ι⁰-θ⊞υ№…·⌊θ⌈θ№⊟ι§⊟ι⁰»IΣυ
```
[Try it online!](https://tio.run/##XVLZauMwFH2uvkL0yYEaomxN3adSGOhDocx8QSxFkrXVlhTZaJhvz1w5ySw9xovMXc4591J58PTzYM7nUXbmiKtvnYlHX/3oTRerN9ef4o/oOyeqxQO@x/fw1IsF/onuXkLohKteDyFeo1/im2PHqeoe8LJE1/cLeA2LZ3T3cQqyOj3g18@TK2WpOYUuHb8fnDhW753r7MlWA0S/H6br9@IW/fHZVx2cbuVv5@UC8Ix@oQ/gF69EIPVUfp/P63qPVYN1UComp1rV90opg3Y1WeLQ4BCy0T4UIFJvcG5wdpn3GT3WhGDbYMY1bSc7WWdtTDYyB8lPWDZYGim1lHJAe/jRN7i/IvVzCG0wpVTATS2lEm2Bi2hwK7QQSsQkhENr6Dk1eJqkRmRZk9Vc@AZTHsyV1F2RkZUKyqGnmmwKeR2oGWMMtleRBej5iE2DRWS0NYOZ9TAQoB1TmjI477CGrAKqLb02nNtf4SeDVvUWpwbziYFlQHCLB5CmrB6YHVwe@t7PUiLkRQEXlbH4SQpDx6PKynKjBuXpbANI9gEkCyvsqOAtkmgRIaU39Ek6MZtYSnAjsq3Jbh7CfxBTRmRdk8c54QtcuhgC3anxXPtRAvGchkGhuQl4YowyKrtgjOFctiajDZh1G9BEDb0ogM6xnQafczu2HpF9TZ7KEijbWjvYIC3NppdcWA61t5cNSmGActubt@Ncm4ODdOB84hyVJSxnznOUmRe6qy9KbALxm6KwBEZuKESrqHzimnOb@FzUwSCcdZMDbf08bw/meq@99RBA1oUD81SzPPlgs9cD1Q6mBfbAuFj8F7OjmxsP/pdLWf1VsVN5o0ZHI8xSTWruB9EjlTwnC/r383pdkNl1nWDcIqXshRFe/AE618n8Bg "Charcoal – Try It Online") Link is to verbose version of code. Explantion:
```
WΦ⪪S κ«
```
Loop over the input, splitting each line on spaces.
```
≔I⪪§ι⁰-θ
```
Extract the numbers from the first part of the string.
```
⊞υ№…·⌊θ⌈θ№⊟ι§⊟ι⁰
```
Create a range across those numbers and check whether the count of characters in the string occurs within the range.
```
»IΣυ
```
Output the total number of matches.
[Answer]
# Perl 5, 56 characters
Run with `perl -nE`. Takes input in the usual Perl ways: as standard input or as filenames passed as command line args.
```
/-(.+) (.):/;{$x=()=/$2/g};$i++if$x>$`&&$x-2<$1}{say$i+0
```
Gotta love those arcane regex semantics.
Explanation:
```
/-(.+) (.):/
```
First, we get the minimum, maximum, and character to match into the `$``, `$1`, and `$2` variables, respectively (`$`` is the "everything before the match" string, which is our first number).
```
{$x=()=/$2/g}
```
Then we see how many `$2` there are in the string and store that number in `$x`. Note that we'll overcount by one, since we're also counting the instance before the colon. The `=()=` is creatively called the "Saturn" operator and is one of the Perl "secret" operators. We wrap this in a block so that the regex variables (which are block-local for some reason) don't overwrite our `$1` and `$2` from the first match.
```
$i++if$x>$`&&$x-2<$1
```
Increment the variable `$i` if the number of matches (correcting for our earlier overcount) is between the min and the max. It's times like these that make me really wish Perl had Python's transitive comparison operators.
```
}{say$i+0
```
Another secret operator to take us to the end of the script, then we print the number of correct lines. We throw `+0` at the end because `$i` starts out undefined, and we need to print zero if there were no matches at all.
You can learn about the secret operators I used here, and several others, on the [relevant CPAN page](https://metacpan.org/pod/distribution/perlsecret/lib/perlsecret.pod).
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~281~~ ~~271~~ ~~249~~ 244 bytes
```
int c,n,i,j;for(String[]x=s[i=n=c=0].split("\n"),a,r;i<x.length;n+=Integer.parseInt(r[0])>c|Integer.parseInt(r[1])<c?0:1)for(r=(a=x[i++].split(" "))[j=c=0].split("-");j<a[2].length();)if(a[1].charAt(0)==a[2].charAt(j++))c++;System.out.print(n);
```
[Try it online!](https://tio.run/##bY8xT8MwEIX3/IpTJpskVtLSJa5BjAxMHUMG13UTm9QJtltKS397cFFUhMTdcPrune7paX7gmd68jWo39NaDDkz2XnXkjkbRsF93SoDouHPwwpWBcwQwbZ3nPoxDrzawCxpaeatMU9XgMJxHZTyI1KQq1XTb25t6ZK5SzDDB8pq4oVMexa8mxilPLVXLI@mkaXxLTcKejZeNtGTg1skAyFZ5jR/E1z9CUeOleMzLAl/NLEOcHSuVJDcPiDGu9B/bLMZUL3k1qydThClWW8TDNyJabp88yjFjPxcT6yTBWCQJXX06L3ek33syhGQeGUxHgEt0GcciW4Aoga/FRm6baJEVM9C/fJVPJZymiubZHNoSWn7t6D6b5SBLCAm1fP@Q8hs "Java (JDK) – Try It Online")
Edit: Thanks @ceilingcat for -11 bytes.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~130~~ ~~128~~ 127 bytes
-1 byte thanks to [ceilingat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
```
m,M,l,d,t;f(S,n,c)char**S,c;{for(t=n;n--;t-=d<m|d>M,S++)for(d=!sscanf(*S,"%d-%d %c: %n",&m,&M,&c,&l);l[*S];)d+=l++[*S]==c;n=t;}
```
[Try it online!](https://tio.run/##dVTbbuM4DH1uv0JToEXS2ECdOG1qb/YP@tTH2XmIqUga3caWBMXQbL@9Kzl2HHQxNHIBKZGHh8eEnAJ8fqrsLZMZzlxNFu@ZzmAJ7GAeH98zqH@TX2bh9rrWeV67fI//Uv/iv9@y99VqmUJ4/81aOGiyiMfv7nF@j9E9VOhe32UPKnt4yx4ge5DLWn5/fP9RL/FqL1er9H@/h1rvXf3x@VM7pA4/9WJ5@/v2Bn5p61BCgB7d0bri@w@0RzFwc1fkWxRzHxrAR0LvsuTb5sUa8S/OdDBUKIx2dm7yDWIVYof0nF1lvn5Cxwod6ZEfu9PxmNwf9e3N/2GsZxibfJcqCsu585o3vG055/Kc8jkvnpCtkLVBCmOTTZjKAZMOpB0RveRFgVSFMBHQ9KpXWinnlcN6yvU6IJaMCcZYd/buoretUDuab@fDkRwAiEMFUABsYmiHaIUaKijl1HlK9URIifoK9T0TI8SnRGaqOJlMX1hfMj2nxgPnlo85XvOiTO0KC/LknFUtd9hOiF6QrBB1GBrZyZkGHFsWGnMBeHI@IxGTJAOh4BrOgHA0049Z1nHAvkKkx3EEUzdb1EVauBIdVp0OXduamQEX0zgaH2DuMqkitaOJ44ErInnHDcxkRs6MjZxRRdWJx1/qaTMiKxKyCMALj5XH3sfPGIqCfL4W39loP8682OTFy3D1i2l/xWiEBdIQYU4sNhh81/GJqVg4kiollzxoK6UkhDUyTIJ@uYigBwlXnUZIruk7E0JzakZiil1evCYFctUo1SnLFATZMkIVmd@kQc3edlOJ7TSr01yUxGFAR0hPyDSO3eAkJDgWyKW39ZfelZ@IKxMx6YojEuI97rjxRBCiPJkL6ThirXSvIyXtrDMTh2WMMMpMR4tNgokNCBx6Y1UwogOhL1ujTJLA7trmCZUTSjIjvbyzw77hRvKTBhdFw3s@A4n3TsBI8GoicDfo/WwBX0s7Kox6HwyV1NCLzTuoNXE1kkVcq/9E3Igshn2Yoe1yWf8hus5QWabwx@d/ "C (gcc) – Try It Online")
[Answer]
# Javascript, 106 chars
```
s=>eval(s.replace(/(.+)-(.+)(.): (.+)/g,(m,l,r,c,p)=>"+"+eval(`p.replace(/${c}/g,x=>--l*--r),l>=0&r>=0`)))
```
Test:
```
f=s=>eval(s.replace(/(.+)-(.+)(.): (.+)/g,(m,l,r,c,p)=>"+"+eval(`p.replace(/${c}/g,x=>--l*--r),l>=0&r>=0`)))
console.log(f(`1-5 c: abcdefg
5-12 j: abcdefg
1-5 z: zzzzzzzz
3-3 h: hahaha
4-20 e: egejeqwee`))
console.log(f(`3-8 j: ksjjtvnjbjppjjjl
6-10 s: sszlkrsssss
1-4 z: znzfpz
7-11 m: dfkcbxmxmnmmtvmtdn
6-9 h: hlhhkhhhq
8-9 p: ppppppppvp
6-9 c: cccgccccmcch
5-8 g: bgkggjgtvggn
3-4 x: xxhk
10-12 h: hhhhhhhhhlhhhhdnh
5-6 j: zjjsjn
9-14 s: ksclwttsmpjtds
6-7 l: gtdcblql
1-4 d: dkndjkcd
1-6 k: kkkkkckmc
10-12 x: xxxxxxxxxrxl
2-5 v: fxdjtv
3-5 q: pjmkqdmqnzqppr
5-8 t: xtgtgtcht
6-11 j: nftjzjmfljqjrc
6-9 g: rskgggmgmwjggggvgb
11-12 v: vkvdmvdvvvdv
15-16 z: zzzzzzzzzzzzzzgxz
13-17 v: vvvvvvvvvvvvvvvvnv
9-14 j: clrfkrwhjtvzvqqj
1-12 l: lljljznslllffhblz
4-7 c: cccgcxclc
6-11 z: tbxqrzzbwbr
18-19 m: jmbmmqmshmczlphfgmf
1-5 s: ssvsq
4-5 k: kkkkw
4-7 f: fcqffxff
3-8 f: fffzthzf
9-12 v: vvvvvvvvvvvmvv
14-17 f: ftflcfffjtjrvfkffmvf
4-7 n: pnmnxnqqjp
6-7 r: rrrkrmr
4-13 k: drckdzxrsmzrkqckn
5-14 t: dttttttttttttt
13-14 v: vvvvfvvvvvvvvvv
7-12 j: jrljwnctjqjjxj
6-7 v: wchfzvm
1-8 d: dddddddzd
10-12 g: gvvzrglgrgggggggggg`))
```
[Answer]
# SmileBASIC 4, 198 characters
```
@0:S=INSTR(I$[0]," ")C=I$[0][S+1]N=S+3
REPEAT N=INSTR(N+1,I$[0],C)INC M,N>0UNTIL N<0
H=INSTR(I$[0],"-")
U=VAL(LEFT$(I$[0],H))
V=VAL(MID$(I$[0],H+1,S-H-1))
INC O,M>=U&&M<=V:IF LEN(I$)GOTO@0'newline char here
?O
```
---
Receives input through I$[]. Simply parses the min-max char information and searches through each string of the string array, doing a tally and summing up the number of true hits.
---
Single-line (ish) version (same number of characters):
```
@0:S=INSTR(I$[0]," ")C=I$[0][S+1]N=S+3REPEAT N=INSTR(N+1,I$[0],C)INC M,N>0UNTIL N<0H=INSTR(I$[0],"-")U=VAL(LEFT$(I$[0],H))V=VAL(MID$(I$[0],H+1,S-H-1))INC O,M>=U&&M<=V:IF LEN(I$)GOTO@0
?O
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as an array of lines.
```
m¸£OvXÎr-'õ)øXÌèXÅÎÎ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&header=tw&code=bbijT3ZYznItJ/Up%2bFjM6FjFzs4&input=IjMtOCBqOiBrc2pqdHZuamJqcHBqampsCjYtMTAgczogc3N6bGtyc3Nzc3MKMS00IHo6IHpuemZwego3LTExIG06IGRma2NieG14bW5tbXR2bXRkbgo2LTkgaDogaGxoaGtoaGhxCjgtOSBwOiBwcHBwcHBwcHZwCjYtOSBjOiBjY2NnY2NjY21jY2gKNS04IGc6IGJna2dnamd0dmdnbgozLTQgeDogeHhoawoxMC0xMiBoOiBoaGhoaGhoaGhsaGhoaGRuaAo1LTYgajogempqc2puCjktMTQgczoga3NjbHd0dHNtcGp0ZHMKNi03IGw6IGd0ZGNibHFsCjEtNCBkOiBka25kamtjZAoxLTYgazoga2tra2tja21jCjEwLTEyIHg6IHh4eHh4eHh4eHJ4bAoyLTUgdjogZnhkanR2CjMtNSBxOiBwam1rcWRtcW56cXBwcgo1LTggdDogeHRndGd0Y2h0CjYtMTEgajogbmZ0anpqbWZsanFqcmMKNi05IGc6IHJza2dnZ21nbXdqZ2dnZ3ZnYgoxMS0xMiB2OiB2a3ZkbXZkdnZ2ZHYKMTUtMTYgejogenp6enp6enp6enp6enpneHoKMTMtMTcgdjogdnZ2dnZ2dnZ2dnZ2dnZ2dm52CjktMTQgajogY2xyZmtyd2hqdHZ6dnFxagoxLTEyIGw6IGxsamxqem5zbGxsZmZoYmx6CjQtNyBjOiBjY2NnY3hjbGMKNi0xMSB6OiB0Ynhxcnp6YndicgoxOC0xOSBtOiBqbWJtbXFtc2htY3pscGhmZ21mCjEtNSBzOiBzc3ZzcQo0LTUgazoga2tra3cKNC03IGY6IGZjcWZmeGZmCjMtOCBmOiBmZmZ6dGh6Zgo5LTEyIHY6IHZ2dnZ2dnZ2dnZ2bXZ2CjE0LTE3IGY6IGZ0ZmxjZmZmanRqcnZma2ZmbXZmCjQtNyBuOiBwbm1ueG5xcWpwCjYtNyByOiBycnJrcm1yCjQtMTMgazogZHJja2R6eHJzbXpya3Fja24KNS0xNCB0OiBkdHR0dHR0dHR0dHR0dAoxMy0xNCB2OiB2dnZ2ZnZ2dnZ2dnZ2dnYKNy0xMiBqOiBqcmxqd25jdGpxamp4ago2LTcgdjogd2NoZnp2bQoxLTggZDogZGRkZGRkZHpkCjEwLTEyIGc6IGd2dnpyZ2xncmdnZ2dnZ2dnZ2ci)
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/231794/edit).
Closed 2 years ago.
[Improve this question](/posts/231794/edit)
Given a long multi-sentence string, the goal is the count the occurrences of the following words: `park`, `lake`, `Santa Fe`.
The words can appear as substrings of other words, i.e, `parked` counts as an instance of `park`.
`Santa Fe` counts as one word (so the space matters). Both `Santa` and `Fe` appearing alone or out of order does **not** count as an instance of `Santa Fe`.
The output should be counts of the number of times the words `park`, `lake`, and `Santa Fe` appear in the input string, in any consistent and readable format and order.
For example, for an input of
```
I'm just parked out by the lake; the lake 80 miles from Santa Fe. That's where i'm parked, out by the lake.
```
the output would resemble
```
2 3 1
```
as there are \$2\$ occurrences of `park`, \$3\$ of `lake` and \$1\$ of `Santa Fe`.
Good luck! If you want a fun song to test this on you can use the lyrics to [Parked by the lake - Dean Summerwind](https://www.youtube.com/watch?v=D_zS_uiPWxs) (below) and use it as the input; The output ought to be `20 24 14`.
Winning submission is the least number of bytes.
---
[Lyrics to Parked by the Lake](https://tio.run/##5ZTNboMwEITvfoq9cclLNGorceqhkaoeHbGAi38q22nE01OvMWBCEqXnnvgR83lmvMZJ7lp0w1AWCpwXUsI3tx1WYE4ejj34FkHyDtmLaFrfgxISHdTWKHjn2nN4RfakK4h64b3QBbRoEb5Ozt9isbKG3pyK8NnZ6Aotqc5RViYNIyDpEiKXl75w81O44fSMt/3NBv8e7epSCZMMBy73GyYt6VvhRmG4Ll@ngI8UerkhkRGXSeR7FPZsqGWwqFAd0Ub7YGQ1Kg/BqtERN0sOY8BVsmVnm8VDynDZ7OLvsakRm3rXjvOZ@LfbSBhnFFa8j6eiMVpzUOYH2T7ALElBm3PuijTUZEfvY68xwBiPTezdVEXewS7nfHARj3RtLPHYFfCdHfncTF/mYtvTGCzM2mrG3ibo1NXmxX5ZkvZwaS7/KV2ObpnlBk@ngmK1VCPUKP2KKvRMHYZf)
[Answer]
# [J](http://jsoftware.com/), 36 30 bytes
```
1#.('Santa Fe';park`lake)E.&><
```
[Try it online!](https://tio.run/##5ZRfS8MwFMXf8ykuCsZBLfNNNhWcblAQBB2Ib2Y2XbO1ibSZo59@5qb/snUb89mHQSk5v3vOye0WmzOfRnA3AAoe9GFgflc@PL4@TzbX5/4lfWNSM5hwOvxm2fIzYUveG/sX97ebHuFfsYIIaEBpCotVrgHP8BDUSsOsAB1zQMGweYKbPqQi4TlEmUqhhvswjZmmNId1zDMOAoEly9uF@bSea9z2SWBO5lokyYHZZCzmsS72TSUPMgSrF1oLScHOPpKDkCCCQq2oObZWMuQZqkrLQaWxhlBXIVx5oE3CpgqNkXPgh/01Bv8ebe@oClMZNlymO0wcqWORl0KRO6ergKcUunshlmHHVORjFPKksGXIeMrTGc@sfVBJWCqnxqqSFtdIpmXArWTtzc5bD1WG3WZbf6dtjejUu@3Y3Yl/e42IyVXKQ1bYr2KupGSQqh9ORgaWoRSkWruuUINNLvG97dUGKOORmu3VVbgdeC7nnQn7SUcqQx7ZAz5yIx@d7XNcdHsqg5ld29qxlxpad9V5MWpH4h22zbl/SrurGzi5QeNXgbFirBEinugtqpAttbf5BQ "J – Try It Online")
*-5 thanks to Bubbler!*
Returns count in order "Santa Fe", "park", "lake".
* `E.` Does all the matching work, returning three rows of ones and zeros, where ones represent the start of each match.
* `1#.` Sums row-wise.
[Answer]
# [Python 2](https://docs.python.org/2/), 48 bytes
```
lambda k:map(k.count,["park","lake","Santa Fe"])
```
[Try it online!](https://tio.run/##5ZQ/T8MwEMV3f4pTlrRSxMCIxEAFSJkYqIQQMLjEaUxiO3Icqnz64HP@OQ2tysyUxPL7@d27c8rGZEpet@nte1tQsUso5DeClqv86lPV0kRvQUl1HkRBQXNmH89UGgqPLPhYt6Xm0qzSVRAEcSigMrwoALezBFRtYNeAyRigkjzwfWYaELxgFaRaCRhI5E4m4PTcGC5DyJhm8FVX5hSLxCk0qg7ttoOSCdOoOjhZ3GsIAlHXI3x5bMJq/LIvFL/ZaX@jwb@X9utRPaY3bLnULJh4pMl41Qntc9rdF3hJoMcNcQx3TE8@RyH3ClMGzQQTO6adfVBF0im31qqSDjdKtl2Bs8qmzu4nD30Nx8lO/i6bGr6Id@7Yn4l/20bEVEqwhDbuVuyVlBSE@mZkY2EapSDVwXeFGkwyx3WXqyugK48M7GiIws8g8jkvlLsrnSqNPPIL@ExHXhfT57lY5tQVZmdtNmNPA3TIarGwmY7EHk7J@T@l49GNvbrB4K3AsjKMEVJWmBmVy5Fq/5XrdfsD "Python 2 – Try It Online")
-7 bytes thanks to tsh
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
„†¹Š°#„š´º´™ª¢
```
[Try it online!](https://tio.run/##5ZSxbsIwFEX3fMUTHbLwE0VtpUwdilR1NMoLcUnsyjFF2Rj6HRVl7NSBpR0j8SP8SOrnJMQhgOjcCRzlHt97/RyZsQnHstwt33fLVfG9XRVfV2ax/Sg2xU@x2b2ti89iXZaDwSDwU8g0TxJ4YWqGIci5hkkOOkZI2Ay9Wz6NdQ4pTzCDSMkUHpjQDO7QuxYhWD3XmgsfYlQIz/NMn2J5QQS5nPvmtYUUISpSLawsqDUeAUlXI1x5oP1svzJ/GK3xtL@9wb9HO7pVjakNGy7TPSZtqWOeVULz275dB7yk0MMDsQy7TU0@R/FuJLUMClNMJ6isfZBJWCnHxqoUFreXjKuAnWTtyU5bD3WGw2Zbf5dNDe/V23XszsS/PUbCZDLFkOX2VkylEAxS@YreyMAUSUHIheuKNNTkjJ7bXm2AKp7XsIdNFW4HQ5fzyLi90pFUxPOOgM@cyFNv@hwX/Z6qYGbWOjN230CbrnoPRu2WdIZtc@5H6XB0Ayc3aLoVFCumGiHCRHeoXOyp5lv5Cw "05AB1E – Try It Online")
```
„†¹Š° -- compressed string => "park lake"
# -- split on spaces => ["park", "lake"]
„š´º´ -- compressed string => "santa fe"
™ -- title cased => "Santa Fe"
ª -- append to the list => ["park", "lake", "Santa Fe"]
¢ -- for each word, count the number of occurences in the input
```
[Answer]
# [Factor](https://factorcode.org/), 58 bytes
```
[ { "park" "lake" "Santa Fe" } [ count-subseq ] with map ]
```
`count-subseq`:
* Doesn't exist in build 1525 (the one TIO uses).
* Has stack effect `( subseq seq -- n )` in every build that permits the omission of whitespace after strings.
* Has stack effect `( seq subseq -- n )` in the current build, which means we don't need an extra `swap`.
Therefore, the code retains the whitespace after strings but it's still shorter than the alternatives. Also, have a picture.
[](https://i.stack.imgur.com/1WfqF.png)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 17 bytes
```
ẆċⱮ“£Ḟœ“ċẈ“¡ç1Ḋı»
```
[Try it online!](https://tio.run/##y0rNyan8///hrrYj3Y82rnvUMOfQ4oc75h2dDGQd6X64qwMksvDwcsOHO7qObDy0@////0qe6rkKWaXFJQoFiUXZqSkK@aUlCkmVCiUZqQo5idmp1nCWgoWBQm5mTmqxQlpRfq5CcGJeSaKCW6qeQkhGYol6sUJ5RmpRqkIm0DiISTroRukpAQA "Jelly – Try It Online")
-2 bytes thanks to [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy)
## How it works
```
ẆċⱮ“£Ḟœ“ċẈ“¡ç1Ḋı» - Main link. Takes a string S on the left
Ẇ - Yield all contiguous sublists of S
“£Ḟœ“ċẈ“¡ç1Ḋı» - Compressed string list; ["park", "lake", "Santa Fe"]
Ɱ - Over each string:
ċ - Count the occurrences in the sublists
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 16 bytes
```
`⟇æ
ȴ
ʁ∨ Fe`↵vO
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=r&code=%60%E2%9F%87%C3%A6%0A%C2%BB%C2%A5%0A%CA%81%E2%88%A8%20Fe%60%E2%86%B5vO&inputs=I%27m%20just%20parked%20out%20by%20the%20lake%3B%20the%20lake%2080%20miles%20from%20Santa%20Fe.%20That%27s%20where%20i%27m%20parked%2C%20out%20by%20the%20lake.&header=&footer=)
## Explained
```
`...`↵vo
`...` # the string "park\nlake\Santa Fe"
↵ # split on newlines to form a list
vo # for each in that list, get the count in the input
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~124~~ \$\cdots\$ ~~106~~ 103 bytes
```
*f(int*s){int c[3]={},i;for(;*s;++s)for(i=3;i--;)c[i]+=!wcsncmp(s,L"parklakeSanta Fe"+i*4,4<<i/2);s=c;}
```
[Try it online!](https://tio.run/##7ZZdb9owFIbv@yvOIrESCG35mLQtZdO6dRJSpV200jQ1XLiJAx6Jg2J3wBB/fezYzidpUbXrIQHBx@9z3nPsxPi9me/v952wzbjsCHuLX@DfD6fj7c5hbpikbbcj3G5X2OqajYcu6/Vc279n0@741coX3I@XbeHcWEuSLiKyoLeESwJfqdVlnZEzurxk5wPbFWPf3e0VPSaMt23YngC@VFaQVEhxP4UxbG@syWkMPx@FBMWjASSPEh42IOcUFN0truDtBcQsogLCNIkhT3sGd3MiTwWs5jSlwBBnSM4h6sxytIfDl/EgJIuiZ0x4/JrN5nLzVH6Pf@IBaAKTkvFT0D6OlORxj09C2CSPpzhxlfCApkpnCphkKpyDTCXNKDXCRFVcdEaaDtAjJkub/1Lik@kyUGYbyUQ2qSqrnDNhlExUpud1vqi3h6ujKTpTxj7O8fiXRHUcUhrT@IGmughIoiAT36HjhGtkqartrKzCcqVnpZG8lEaXS5sv3Ums0eq67@ou@b@smiSSmAZkY@6YWcI5gTj5heErJKZKDjxZ1cwpmWrrQgV0k3Uhpk6P5xmcvCnVbjg10nfC9F2Pj0tFzD3V4ccW6EdjV1asPNEzUyBuwfrW@5Zzi8Y1R67KvGpVq32sPsAa23pSaQFIddOo8uaqpxDSSNbJjBfkZ5@4yyVBuD5CIoIqfZDcEtQpqZYbRkYqgJq3c/PDBOh6SX1Jg745TwYODB3o75wiMMgCFw4MRhgaYawIDk2wj@NG1ckjJlDQK7zyclj66IA/p/6CpkZneevrgbd@9xnfbywHqr@HViZTO0Ydw6gP6BplF252eYlL8ZsmYTvPZJ9nA4U/24VuV8/Oj9bCiUCUOWJ1fOoW4SWeMzJsW57VioRnQe8DoDlhu3WAj4Cw3RimOFy05xCt6lgSoXL3y9GyxKw8LG2onVddV621RCtAT@yj6tp7Cz/VX4@KFT1ZJXo91iEYoyv8LmfsGvVCS3hcobI1UvqcuTvZ7f/4YURmYt9b/QU "C (gcc) – Try It Online")
Saved ~~a~~ 2 bytes and fixed a bug thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
Inputs a string.
Return a pointer to an array of occurrence counts for `park`, `lake`, and `Sante Fe`.
[Answer]
# JavaScript (ES6), 57 bytes
```
s=>["park","lake","Santa Fe"].map(w=>s.split(w).length-1)
```
[Try it online!](https://tio.run/##5ZTNbpwwFIX3PMXVbABpgtoHmEiN2kissphIVVV14QwXcMbYE/tOEE8/9TUwMEMSpeuu@BHn8znH1zyLV@F2Vh7oRpsCT@Xm5Da3v1cHYfer9UqJPfrLVmgScI@rP1kjDkm7uXWZOyhJSZtmCnVF9c3X9KQ6K3cONmDx5SgtJnHp4jSzKIp7qXDb6V3yJc3IbMlKXSVptDPaGYWZMlVSJr0@TU953IAjqRSwDyzAHAmeOqAagS1FP2RVUweNpzoorWlgtBh90wUEvSSSOoYaLcLz0dF7rCgvoTPH2H/WGl2gZVUbZPmgiRjIugExl@cUu/OTvxH8jO/7Oxv892hvLjVgBsOeK2jB5CWplq4X@uv09RDwM4Veb0hghGUG8keU6Lvhlv1oNNg8oQ32waiiVz56q0YH3Fny2Ae8SDbtbDV5GDJcNzv5@9zUyEW9l47nM/HfbiNjnGmwEF04FZXRWkBjXjG68zDLUtCmnbtiDTe55/eh1xCgjxeN7PVYxbyD9ZzzU8hwpEtjmRe9Af5gR34tpm/mYtlTH8zP2sWMPYzQsavFi7tpSd7Dqbn5T@l6dPNZbiA@FRyr5hqhREUXVKnP1L8 "JavaScript (Node.js) – Try It Online")
```
s=>[(g=w=>s.split(w).length-1)`park`,g`lake`,g`Santa Fe`]
```
[Try it online!](https://tio.run/##5ZTPbqMwEMbvfoq5AVKKug9ApVbdSpz2kEqrqlopbhjAjbFT2yni6bMeA4GEtuqe98Qf8f3mm2/GvPJ3brdG7N2V0gUey@xos5vnuMra7Mamdi@Fi9sklagqV1/9SDZ7bnabVbWRfId0XXPlODzg5s9RdkZsLWRg8O0gDMZRaaMkNciLByFx3altfJ2kTq@dEaqKE7bVymqJqdRVXMa9PkmOedSAdUJKoGpYgD44eOnA1QhUl/0UVe06aDzVQml0A6MNdqsKCHrhnFAR1GgQXg/WfcZieQmdPkT@s1arAg2p2iDLBw0jIOkGxFyeu8ienvwNp2f83N/J4L@39mGpATMY9lzuFkwq6Wphe6G/Tl8PDX4n0MuBBEYoM5C/orB7TSn71WiweUET7IOWRa989Fa1CriT5LFv8KyzabLV5GHo4TLZyd/3tkYs4j13PN@J/3aMhLG6wYJ34VRUWikOjX5HdudhhqSgdDt3RRpKckfvQ66hgb49NrJXYxTzDFZzzm8uwpEutSEe@wD8xUSeFts3c7HMqW/M79rZjv0aoWNWixd3U0ma4ZTc/Kd0ubr5rG9wdCqorZpihBKlO6MKdaL@BQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 33 bytes
```
g;"park
lake
Santa Fe"ṇᵗz{{sᵈ}ᶜ}ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bG8v/p1koFiUXZXDmJ2alcwYl5JYkKbqlKD3e2P9w6vaq6uvjh1o7ah9vm1D7cOuH/fyVP9VyFrNLiEgWQntQUhfzSEoWkSoWSjFQFkAHWcJaChYFCbmZOarFCWlF@rgLMYD2FkIzEEvVihfKM1KJUhUygcRCTdNCN0lMCAA "Brachylog – Try It Online")
I'm not sure if this feels very golfable, or not even remotely golfable... `⟨s≡⟩ᶜ` happens to tie `{sᵈ}ᶜ`, so maybe there's some shenanigan to pull there, but that seems doubtful.
```
g; Wrap the input in a list, and pair it with
"..." "park\nlake\nSanta Fe"
ṇᵗ split on newlines.
z Cycling zip.
{ }ᵐ For each pair [input, park/lake/Santa Fe]:
{ }ᶜ in how many ways
sᵈ is park/lake/Santa Fe a substring of the input?
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 59 51 bytes
```
grep -Eo 'park|lake|Santa Fe'|sort|uniq -c|awk NF=1
```
[Try it online!](https://tio.run/##5ZS9boMwFIV3P8XdWJKhD9ChUROJpR0aqerolAu4ATu1TRES70655s@EJErnTvyI8/mc42sO3KRNk2g8wXqrIDhxfawzfsT6jUvLYYdBbZS2dSHFN6w/a14e4WX3@NA0YZCDsSLLgEQYgSosHCqwKQIR2FYkqa0gFxkaiLXKYWCyJxmB0wtrhQwgRY3wVRh7jcXCGCpVBO1npZIRalKVThb2GkZA0vUIXx7awIxP7Q2nZ7zubzT492gXl@oxveGWy@2CSUvaVJhO2F6nr/uA9xR6viGO4Zbpybco7FlRy6Axx/yA2tkHlUWdct9aVdLhRsm@CzhLNu1sMnnoM5w3O/m7b2rEot65Y38m/u02EsaoHCNeuVORKCk55OoH2aaFaZKCVKXvijTU5JHeu15dgC4eG9iroQq/g5XPeefCHelYaeKxC@AbO/KxmD7PxbKnLlg7a7MZex2gQ1eLF5tpSdrDqTn/p3Q@uqGXGyydCoqVUo0QY2ZnVCFH6i8 "Bash – Try It Online")
*-8 bytes thanks to [user41805](https://codegolf.stackexchange.com/users/41805/user41805)'s nice awk trick!*
Returns in order "lake", "park", "Santa Fe".
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 21 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
`pk
lake
S Fe`·£èX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=YHCHawpsYWtlClPCHCBGZWC3o%2bhY&input=IkknbSBqdXN0IHBhcmtlZCBvdXQgYnkgdGhlIGxha2U7IHRoZSBsYWtlIDgwIG1pbGVzIGZyb20gU2FudGEgRmUuIFRoYXQncyB3aGVyZSBpJ20gcGFya2VkLCBvdXQgYnkgdGhlIGxha2UuIg)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 49 bytes
```
p %w[park lake Santa\ Fe].map{|r|$_.scan(r).size}
```
[Try it online!](https://tio.run/##7ZRNT4QwEIbv/oo5aNBkJR5NPGnUhJMHNzFGjOlKWerClLRFgq5/XewHn8u62Xj2RqDzzPu@M0UUi6quczgqn3IiVpCSFYV7goqEcEuf/Yzkn2uxPnzx5SvBY3HiS/ZBv@o68DJ4K6QCU0Yj4IWCRQUqoZZx0T3B@RlkLKUSYsEzx9ZoH@YJUZ6EMqGCAtM4R5ptovwD00sqlqa/NAvxhi0TVW3rE@IlRmAJTCmGHth@O6SHGGIQQ8ULTx8sOUZUmDonNGiq9BnNNKUNZUQIjLMuAeWc0h0ie5l/sbi1XQNqZGsyUVOq6aoSJl0lk4Pjrc@9st2cjqXYTg17NyfEa24SB0Ezmi2osCaAp1FTPNeKOVpkXzXaoMZhP@llL6S1Mkm5l7nvJrFJ1GPdwy35H6slSZ7RiFTuxiw5IoGMv@vPV5ooTDkgL0fiTJmJdWU@2JCtEeczxLbDrA1lmMZsRHogzN76mAtDbDWN4bsG9DjZyoGULZk5g3oFx6t313K74KZvrvq@ZqrDHIc/sMlaB4MIQJlLY@wlJlOIaarGZIYd@ZvninGU9Sn@AA "Ruby – Try It Online")
[Answer]
# [Clojure](https://clojure.org/), 55 bytes
```
#(for[r[#"park"#"lake"#"Santa Fe"]](count(re-seq r %)))
```
[Try it online!](https://tio.run/##5ZRPT8JAEMXv@ykmJYaSIPFo4kmiJj150MQYwmGhU7rS7uJ2K/LpcWf7b6FA9OyJ0nR@896b2V1m6qPUuA9jTCDZD8JE6ZmeDYIN1@tgEGR8jfbnhUvD4QmD@TxcqlKaUON1gZ@g4Wo0Gu1HLIwV/Z/B94wF0TCHj7IwQBSMQZUGFjswKQIB79onuL2BXGRYQKJVDk2bCbym3AwL2KaoEYTFVaTxMWoSVN0KI7LsTDv2KFap2Z1qxO5lDK5eGCPkEFy/C9IZixLYqXJoP9sqGaOmqkpmVNcwAlJdjfDLI3LVujeVSzyvrxX4d2snW9WYWrDlctNjUkuTiqIqFIX3dW3wN4EeD8QxXJuafInCHhSlDBpzzBeonXxQWVxVvlqpSjpcW3KwMbWzbrKrTkPt4TjZTt/vtkb04j1U7O/Evx0jYQqVY8x37lSslJQccvWFbGphmkpBqq2vimooyTW9d7k6A5U91rDHTRR@BmOf88aFO9L2RiMeOwG@MJH33vZ5Kvo5Vcbsrh3s2HMDbbLqvZh2LWmGXXL@pXS8upHnGwydCrKVUoyQYGYOqEK21IDN5yzc2CvLZBLCBL7p7v4B "Clojure – Try It Online")
[Answer]
# [PHP](https://www.php.net/), 73 bytes
```
foreach([park,lake,'Santa Fe']as$r)echo~-count(explode($r,$argv[1])).' ';
```
[Try it online!](https://tio.run/##PcyxCsIwFIXhVzlDIAlEwVnBTXB2LB0u6W0ibXNDjKKLrx7toMsZfg5fjrkdjvm7oxQmH02XqUxupomdvlCqhBPrnm6qWPZR3hsv91QNP/MsAxtVnKISHt2ut3arofettbNeEOSaAqpg9bB6@HH/urzgqYDSAKYKwrj@Pg)
[Answer]
# [PHP](https://php.net/) -F, ~~71~~ ~~66~~ 65 bytes
```
foreach([park,lake,"Santa Fe"]as$w)echo~_.substr_count($argn,$w);
```
[Try it online!](https://tio.run/##Xc3NCoJAFAXgV7mIoMEkLQODdkLr2kXI1a6N6fwwcwdp06M3KVGLNocDB75jpY27vZ2zM46wlfnZohvEiAOJ5IiaESpKLujTaUWtNM@68KHx7OrWBM15iu6mxTyWMR4yBffgGRaCrmACQ/MAlgSLV/4abDeg@pE8dM4o@N4UcJLImYdJkiPoZ@4jiX@qeBnLvdE@rqs3 "PHP – Try It Online")
Just using dedicated function and usual tricks..
EDIT: 5 bytes saved using a `foreach` like in [Guillermo Phillips's answer](https://codegolf.stackexchange.com/a/231829/90841)
EDIT 2: another byte the dust thanks to Guillermo Phillips again!
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 39 bytes
```
{+/`park`lake`"Santa Fe"=/:`$(4'x),8'x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJy9zU0LgjAAh/H7PsUfEWYk2ttBNroGnesmwhZtaGrGnDQR++wlUYc+QLfn9Hs0G+axuElTikqWSngHebUSO+VtYyb8YEPdLEyoGwmxbPDT/mGYBuC4aEoeCC2LijveczPLRmJTb09rXLrWYjLVGU1ncephc4VpwL+FZIG6qFQLbZoan2+EYy4tbXHPlVEoXtxbCn+pyOMrrLHMCIn/un0CpIpjbQ==)
* `(4'x),8'x` build a list containing all 4-length sliding windows, and all 8-length sliding windows, of the input
* ``$` convert the slices from strings to symbols
* ``park`lake`"Santa Fe"=/:` build a matrix with each of its three columns indicating whether or not each slice of the input is equal to one of the search terms
* `+/` sum column-wise, returning the number of times `park`, `lake`, and `Santa Fe` appear in the input (respectively)
[Answer]
# [Perl 5](https://www.perl.org/), 44 bytes
```
for$w("park","lake","Santa Fe"){say s/$w//g}
```
[Try it online!](https://tio.run/##XcyxCsIwGATgVzlCoQptE4eC4F5wcNIXiPjXxqZJSVJLEV/d2CI6ON0Nd19PTpcx1tYl44r10rUsY1q2NMdRmiBREVs/vJzgeTJyfn3GuE873AYfsOzpAjsEnCeEhrBcd7@GrUCnNHnUznb4ggVOjQypx9iQI6iZ@0jZP1W8bB@UNT7mRsT8cC@LjXgD "Perl 5 – Try It Online")
[Answer]
# [WolframLanguage (Mathematica)](https://www.wolfram.com/mathematica/), 50 bytes
```
(f|->f~StringCount~#&/@{"park","lake","Santa Fe"})
```
The above won't work in tio.run because |-> is too new (introduced in MMA v. 12.2, while tio.run uses MMA 12.0).
Thus here's a 51-byte version that does:
```
(f=#;f~StringCount~#&/@{"park","lake","Santa Fe"})&
```
[Try it online!](https://tio.run/##5ZRPa8JAEMXv@RRDBG1BbI8FEaz9A55aUCileFibTbI1u1s2Y0VK/ep2Z5OYxFhrzz0lhH2/mfdmNpJhzCVD8cq20WB7Fg5a/XAzQSNUdKOXCjet9sXw039nZuF3/YQtuH1MmEIG99z/Om9vH@1ZHEYv/rgj4W2ZItBhHoBeIszXYAsA6frFC1xdghQJTyE0WkIB601jhp0UVjE3HISFZZzuHqfnz7xazRRFkvxQ1LsTUYzrQ/W8axWA0wtEoTrg6h4x4I1DWOtlx55aaRVwQ6Ks23Eu8YhHspxQU5O5XQaYmeW/t/d3Ywcr5Zi8X8tl2GBSSYxFmglFWjmd@zslzv1xOIYrk5OPUW41ZQyGSy7n3LjuQSdBJpzaTrVytJ2itja5sXKsUdlCbmEv17K70zZGNMKtN1xdiH86Q6KkWvKArd2FiLRSDKT@4N7IsgwpQelVtSnSUI4L@u5Sdf1n7rwC3S2SqEbQrXKemHCXOdSGeAe4R@bx3Ni8ShPNlDJfds9q@/VQQIukGh9GZUmaYDnzys9of2vHFdeAdCHIVUwhQsgTrEGF2kH92fYb)
[Answer]
# [Zsh](https://www.zsh.org), 45 bytes
```
for x (park lake Santa\ Fe)grep -o $x F|wc -l
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dc2xDoIwFIXhnac4gwk6dHcycbCJs6tLkQutFEra2wjGN3EhGh-Kt1HB1elM_3fuz2vQw2MjX5ELsR5F4Tw6LFvlK1hVEQ6qYXWEpFXpqYVwWHSQt8sJws7R8JvR7tMagY21-PaUw0VG1oM1TViyM6XmHrWxFFB4V8_8R0-2TY6pN8ymSaHJE84x8B9rPn0D)
[Answer]
# Excel, 63 bytes
```
Cells A3:C3 = park, lake, Santa Fe (16 bytes)
=(LEN(A1)-LEN(SUBSTITUTE(A1,A3:C3,"")))/{4,4,8} (47 bytes)
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnFdK4ZBRIJbqvADm?e=bpuFwo)
The easiest way to count occurrences of a substring is to substitute the substring with "" and then divide the difference in length by the length of the substring.
## Self contained formula, 68 bytes
```
=(LEN(A1)-LEN(SUBSTITUTE(A1,{"park","lake","Santa Fe"},"")))/{4,4,8}
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 24 bytes
```
*M`park
*M`lake
Santa Fe
```
[Try it online!](https://tio.run/##5VRBboMwELz7FXtDqvKJRm0lDlUPjVT1VkcswQ22I7NpxOup1xgwIYnSc0/Glmd2ZnaNQ1JGdt3D69dBur3way33KN6lIQkv2HV5pqEhVdfAF7AAeyTYtkAVQrj6rHYVtaBVjQ2UzmoYwOLRFBDwinyZDCp0CN/Hhq5xibyE1h4zf@1kTYGOUacAyyNGMCHjIkUKzylrxp3/kLzH6/pGgX@3drFUpImCPa@kBSeXpEo1PdCv0@1o8J5AzxsSOEKZyHyLRTxZThkcatRbdEE@2LrokRsv1ZpAN0I2vcGZs6mzu0lD9HCe7KTvvqlRi3jnitOZ@LdtZJrGaixkG17FzhojQdsfFGtP5hgKxp5SVYzhJPd8HnINBnp747NfDVGkGaxSng@pwpMurWM@cYH4Rkc@F9OXqFjm1BvzszabsbeBdMhqcbCeSnIPp@TSn9L56OaJbyB@FWyr4hihxJpmrMqMrL8 "Retina 0.8.2 – Try It Online") Link is to verbose version of code. Explanation:
```
*M`park
```
Explicitly print the count of matches of the word `park` without changing the input buffer.
```
*M`lake
```
Explicitly print the count of matches of the word `lake` without changing the input buffer.
```
Santa Fe
```
Count the matches and implicitly print the result.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
IE⪪”&/‽∕“⎇⊙g…3CπΦP6”¶№θι
```
[Try it online!](https://tio.run/##5ZRRb4IwFIXf@ytueAET9gv2NN2W8LBsiSbLMvdQpUhnaV0pGn496y0gIGrc83xBCOfrOae3rFOq14qKqnrTXJpgRnMTvNBdMN8JbgJvR/V2KQXdsqWcU2koPDMvBG8pvUkIM1VYzU8IfGJ/91X16XkeifwMcsOFAFSzGFRhYFWCSRkgiTzxTWpKyLhgOSRaZdCiyYOMwem5MVz6kDLN4LvIzSUWiRIoVeHb1w5Kxkyj6uBkUaNxhlDXIPryyPj58c7@oXjPLvs7Gvx7tLNLNZjGsOVSM2LikibleS201@7tJuAthZ5uiGO4ZRryNQp5VNgyaJaxbMW0sw9KxLVyYa0q6XBHyaIOOEjW7eym89BkOG2283fb1PBRvUPH/Zn4t9uImFxlLKalOxUbJSWFTO0ZmVqYRilIdei7Qg02ucXnrlcXoI5HWnbYVtHvIOxz3il3RzpRGnnkDPjKjnyMpq/nYtxTHczO2mDGXlto29XowbRbEvewa67/UTod3aiXGwyeCoyVYo2QMGEGVC47qv1aflV3e/EL "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
”...” Compressed string `park\nlake\Santa Fe`
⪪ ¶ Split on newlines
E Map over each substring
№ Count of
ι Current substring
θ In original input
I Cast to string
Implicitly print
```
] |
[Question]
[
This is the robbers' thread for 'Almost Illegal Strings'.
See the [cop's thread](https://codegolf.stackexchange.com/q/214705/48931) for information on participating. A section from the post is included here for convenience.
>
> ## The Robbers' Challenge
>
>
> Find an uncracked answer. Write a program in the language specified that contains as a contiguous substring the almost illegal string specified and does not error. Your program may not use any character in the set of banned characters, unless it is part of the almost illegal string. Your program does not need to be exactly what the cop had in mind. Post an answer to the robber's thread and leave a comment on the cops' answer to crack it.
>
>
>
[Answer]
# [Python 2](https://docs.python.org/2/), 7 bytes, cracks [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [post](https://codegolf.stackexchange.com/a/214813/44718)
```
0xbin()
```
[Try it online!](https://tio.run/##K6gsycjPM/r/36AiKTNPQ/P/fwA "Python 2 – Try It Online")
The answer is easy to understand if syntax highlighting for above snippet works correctly.
So bad. The syntax highlighting *did* work correctly. But SO changed their render library... Anyway, above code is:
```
0xb in ()
```
[Answer]
# [Haskell](https://www.haskell.org/), [doge doge's answer](https://codegolf.stackexchange.com/a/214865/56656), 26 bytes
```
main=print()where{3
#""=3}
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0RDszwjtSi12phLWUnJ1rj2/38A "Haskell – Try It Online")
The idea here is that within a `{}` block whitespace rules are weakened a good deal. With that we can turn `#"` into the declaration of an infix function and write the rest of our program with no issues. From there we use `where` attached to our `main` function to start the block.
I don't really know why these blocks have weaker rules. I am just learning about this now as well. But for some reason I had a suspicion it might work and it does.
[Answer]
# [R](https://www.r-project.org/), cracks [Robin Ryder's challenge](https://codegolf.stackexchange.com/a/215086/95126)
```
try(x %'"% y,T)
```
[Try it online!](https://tio.run/##K/r/v6SoUqNCQVVdSVWhUidE8/9/AA "R – Try It Online")
The 'almost illegal' string we're trying to use is `'"`.
`try` attempts to run the code contained in its first argument. The second argument, `silent` (not explicitly named here) is set to `T`RUE to prevent output if the result is an error.
The first argument here attempts to apply the (nonexistant) `%'"%` function to (nonexistant) variables `x` and `y`.
The `%...%` notation - known as SPECIAL in [R](https://www.r-project.org/) - allows us to incorporate characters that are usually forbidden for variables and function names, like `'"` in this case.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes, cracks [caird coinheringaahing's](https://codegolf.stackexchange.com/a/214814/68942)
```
“
«{”
```
[Try it online!](https://tio.run/##y0rNyan8//9RwxwurkOrqx81zP3/HwA "Jelly – Try It Online")
**EDIT**
I actually don't know why this works lmao
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes, cracks [caird coinheringaahing's](https://codegolf.stackexchange.com/a/214816/85334)
```
¬´{0¬°
```
[Try it online!](https://tio.run/##y0rNyan8/5@L69DqaoNDC///BwA "Jelly – Try It Online")
Instead of string literal weirdness, this uses the fact that arity mismatches don't cause errors until things are actually evaluated--`{` doesn't try to turn a monad into a dyad so much as it calls a Python lambda assumed to have one argument from a Python lambda with two arguments, and `0¬°` repeats it zero times.
[Answer]
# [Python 3](https://docs.python.org/3/), cracks [qwatry's challenge](https://codegolf.stackexchange.com/a/218612/94093)
Illegal text: `int(A,B,C)`, with all ASCII but `~+2()` and newlines banned.
```
ùî¢ùîµùî¢ùî†(ùî†ùî•ùîØ(22+22+22+~2+2)+ùî†ùî•ùîØ(22+22+22+~2+2+~2+~2+2)+ùî†ùî•ùîØ(22+22+22)+ùî†ùî•ùîØ(22+22+22+~2+2+~2+~2+2)+ùî†ùî•ùîØ(22+22+22+2+2+~2)+ùî†ùî•ùîØ(22+22+22+~2+2+~2+~2+2)+ùî†ùî•ùîØ(22+22+2+2))
ùî≠ùîØint(A,B,C)
```
[Try it online!](https://tio.run/##K6gsycjPM/7//8PcKYuAeCuUXqABIoB4KRCv1zAy0oagOiCpqY1bDkTgUUOBVm2IEvJNAIprcgEF1oIEM/NKNBx1nHScNf//BwA "Python 3 – Try It Online")
Python 3 normalizes Unicode identifiers, so "ùî£ùîûùî´ùî†ùî∂ ùî≤ùî´ùî¶ùî†ùî¨ùî°ùî¢" is turned into "fancy unicode".
This turns it into
```
exec(chr(22+22+22+~2+2)+chr(22+22+22+~2+2+~2+~2+2)+chr(22+22+22)+chr(22+22+22+~2+2+~2+~2+2)+chr(22+22+22+2+2+~2)+chr(22+22+22+~2+2+~2+~2+2)+chr(22+22+2+2))
print(A,B,C)
```
And when we expand the `chr` statements, we get `'A=B=C=0'`:
```
exec('A=B=C=0')
print(A,B,C)
```
And you can figure it out from there.
I would love to say I discovered it, but nah. This isn't the first time normalization memes have been posted here.
Also, I brute forced the ASCII arithmetic instead of calculating it, so it is not optimized. üòÇ
[Answer]
# [Julia](http://julialang.org/), 12 bytes, cracks [@binarycat's answer](https://codegolf.stackexchange.com/a/214924/92901)
```
`\?"""Óàã:"`
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/PyHGXklJ6V1Ht5VSwv//AA "Julia 1.0 – Try It Online")
Backticks in Julia delimit shell commands, as in Perl or Ruby. But unlike Perl or Ruby, the command isn't actually executed; rather, a `Cmd` object representing the command is created. Hence it doesn't matter that `\?"""Óàã:"` isn't a valid shell command.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 21 bytes, cracks @dogedoge's [first answer](https://codegolf.stackexchange.com/a/214867/92901)
```
%q(=end
#{"""'}
=end)
```
[Try it online!](https://tio.run/##KypNqvz/X7VQwzY1L4VLuVpJSUm9lgvE0fz/HwA "Ruby – Try It Online")
Wraps the almost illegal string in a single-quoted string (which doesn't allow interpolation).
---
# [Ruby](https://www.ruby-lang.org/), 23 bytes, cracks @dogedoge's [first](https://codegolf.stackexchange.com/a/214867/92901) and [second](https://codegolf.stackexchange.com/a/214870/92901) answers
```
/#{'}=end
#{"""'}
=end/
```
[Try it online!](https://tio.run/##KypNqvz/X1@5Wr3WNjUvhUu5WklJSb2WC8TR//8fAA "Ruby – Try It Online")
Here's an alternative that doesn't use `%` (in response to a comment). This time we wrap in a regexp, interpolating a single quote to close the `"""'` sequence that occurs later.
---
# [Ruby](https://www.ruby-lang.org/), 28 bytes, cracks @dogedoge's [third answer](https://codegolf.stackexchange.com/a/214873/92901)
```
<<S
#{'}=end
#{/"""'}
=end
S
```
[Try it online!](https://tio.run/##KypNqvz/38YmmEu5Wr3WNjUvBcjQV1JSUq/lAvOC//8HAA "Ruby – Try It Online")
Now the wrapper is a here doc. This approach also works for the first two cops (which don't include the `/`).
[Answer]
# [Julia](http://julialang.org/), 12 bytes, cracks [@dogedoge's answer](https://codegolf.stackexchange.com/a/214866/92901)
```
"""?"""::Any
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/X0lJyR6Irawc8yr//wcA "Julia 1.0 – Try It Online")
Define a (triple-quoted) string and assert it to be of type `Any` (`String` also works).
[Answer]
# Desmos, 5 bytes, cracks [Aiden Chow's answer](https://codegolf.stackexchange.com/a/214955/91569)
```
\{\}
```
[Answer]
# Rust `-Z unstable-options --pretty normal`, cracks [@Deadbeef's answer](https://codegolf.stackexchange.com/a/218719/94093)
```
const x:! =1;
```
Not sure if this is the intended interpretation of "you may pass any flags to rustc if you like." or a loophole.
I could just do `--help` but this one actually parses the file and needs a *sorta* valid Rust program.
Specifically, the `--pretty` option on Nightly will just format the code instead of compiling it.
[Answer]
# [Python 3](https://docs.python.org/3/), cracks [qwatry's revised answer](https://codegolf.stackexchange.com/a/219496/85334)
```
x: 1=2
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8JKwdDW6P9/AA "Python 3 – Try It Online")
or
```
x: 1+1=2
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8JKwVDb0Nbo/38A "Python 3 – Try It Online")
(not entirely sure which it's supposed to be but it works either way).
I completely forgot how *flexible* type hints are until I ~~cheated~~ searched [the grammar](https://docs.python.org/3/reference/grammar.html) for the `=` character.
[Answer]
# Desmos, to crack [HitchHacker's](https://codegolf.stackexchange.com/a/218525/72733) cop
There is in fact a way to crack this answer without using notes. Type the closing parenthesis `)` after the expression, then go back one character and type the closing bracket `]`. The result, `sort(3,2])`, should be interpreted as `sort([3,2])`.
[](https://i.stack.imgur.com/zsfAJ.png)
[Answer]
# [JavaScript](https://www.javascript.com), cracks [Etheryte's answer](https://codegolf.stackexchange.com/a/220563/94066)
```
void$=Array();console.log(...void$)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f@/LD8zRcXWsagosVJD0zo5P684PydVLyc/XUNPTw8sqfn/PwA "JavaScript (Node.js) – Try It Online")
This seems way too easy... Uses spread syntax `...expression` to use the elements of `void$` (initialized to `Array()`, an empty array `[]`) as separate arguments to `console.log`. Since it's empty, it uses no arguments, which is perfectly valid as well; it just calls `console.log()`.
[Answer]
# [JavaScript](https://www.javascript.com), cracks [Etheryte's revised answer](https://codegolf.stackexchange.com/a/220563/94066)
```
eval(...void 0||Array())
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f/fsagosVJDT0@vLD8zRcGgpgYioKn5/z8A "JavaScript (Node.js) – Try It Online")
[Answer]
# Desmos, cracks [HitchHacker's answer](https://codegolf.stackexchange.com/a/218525/96155)
```
\sort(3,2
```
Desmos programs are normally [scored](https://codegolf.meta.stackexchange.com/questions/19316/scoring-desmos-equations) based on the text pasted into the textbox. Pasting in invalid-formatted text simply does nothing, which doesn't meet the error criteria of showing a "danger sign" laid out by HitchHacker. The easiest way to do this is by using a `\` before sort. Desmos doesn't recognize "sort" as an escapable sequence like `\left` or `\operatorname` or even `\sin` so it simply ignores the whole program.
[Answer]
# Python 3, cracks [Makonede's answer](https://codegolf.stackexchange.com/a/220511/46076)
Code contains unprintable characters, so is provided as a hexdump:
```
00000000: 2300 0400 040a 3f22 2222 3f27 2727 3f #.....?"""?'''?
```
Derived from [feersum's comment on an identical Python answer to the original find an illegal string challenge](https://codegolf.stackexchange.com/questions/133486/find-an-illegal-string#comment331528_133489). I made it slightly shorter and adjusted it to the banned characters in this challenge, but have no idea how or why this works.
[Try it online!](https://tio.run/##S0oszvj/n6uiIkVBt0hBLzOvoLREryQzX6FGoaCyJCM/z/j/fwMosFIwMjYwUDAwgRCJCsZpRkYKRkAAYpkrGJkDCeM0BSBQ1gMBeyUlJXt1dXV7AA "Bash – Try It Online")
[Answer]
# Desmos, cracks [HitchHacker answer](https://codegolf.stackexchange.com/a/218525/72733)
The solution is in the answer, **note** is the key: instead of evaluating it as an expression the *illegal string* is put in a note ¯\\_(ツ)\_/¯
[](https://i.stack.imgur.com/JywdS.png)
[Answer]
# [Python 3](https://docs.python.org/3/), cracks [Makonede's challenge](https://codegolf.stackexchange.com/a/219280/94093)
```
raiser=3
```
[Try it online!](https://tio.run/##K6gsycjPM/7/n6soMbM4tcgWyAQA "Python 3 – Try It Online")
Should've banned `=`...
[Answer]
# [Python 3](https://docs.python.org/3/), cracks [Makonede's second challenge](https://codegolf.stackexchange.com/a/219329/94093)
```
raise`TAB`SystemExit
```
[Try it online!](https://tio.run/##K6gsycjPM/7/n6soMbM4lTO4srgkNde1IrPk/38A "Python 3 – Try It Online")
I am sure this is another unintended loophole…
[Answer]
# [Python 3](https://docs.python.org/3/), cracks [Makonede's revised second challenge](https://codegolf.stackexchange.com/a/219329/94093)
```
raiser:str
```
[Try it online!](https://tio.run/##K6gsycjPM/7/n6soMbM4tciquKTo/38A "Python 3 – Try It Online")
Uses a type annotation. I think this is the actual solution you meant. üòè
[Answer]
# [Python 3](https://docs.python.org/3/), cracks [qwatry's answer](https://codegolf.stackexchange.com/a/219496/95792)
```
foo1=2
```
[Try it online!](https://tio.run/##K6gsycjPM/7/Py0/39DW6P9/AA "Python 3 – Try It Online")
The string to crack is `1=2`.
[Answer]
# [Zsh](https://www.zsh.org/), cracks [pxeger's post](https://codegolf.stackexchange.com/a/214882/100411), cracked after being safe.
Did I get the rules correctly?
```
a=1;: "
#include <cstdlib>
#include <iostream>
int main() {
srand(time(NULL));
hello();
return rand() % 2;
}
/*
main
a=0
\
print "$((1/$a))"
*/
void hello() std::cout << "Hello, World!" << std::endl;
"
```
[Try it online!](https://tio.run/##TY5NC8IwDIbv/opYJ7RDmPO4D88ehjfx4qWuhRW6VtrOg@Jvr81kYA4JeZK8eV9@iJG3ZV0BgdVGmV5PQkLT@yC0uh//mbI@OMnHBGGlTICRK0MZvFOfwjtuBA1qlPR86TrG6h8fpNaWLp2TYXIG5l0GWzgk/kHBIscFlMTK2z2WG6aHw2cko7QsMs5YMpoXePK0SizykAxXVW@nAE0D5IR0B1frtFgTRPNcGqHRCInxCw "Zsh – Try It Online")
[Answer]
# [Vim](https://www.vim.org/), 6 bytes, cracks [Aaron Miller's](https://codegolf.stackexchange.com/a/231057/100411)
```
<C-w>n<Esc><Esc>ZQ
```
## What it does
* Make a new window first.
* Close it by last four keys.
---
# [Vim](https://www.vim.org/), 5 bytes, cracks [Aaron Miller's](https://codegolf.stackexchange.com/a/231056/100411)
```
<C-w>n<Esc>ZQ
```
Same as above.
[Answer]
# Vyxal, 16 bytes, Cracks [A Username's answer](https://codegolf.stackexchange.com/a/231511/78850)
```
Q
«Wi«»Wi»`Wi`Wi
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=Q%0A%C2%ABWi%C2%AB%C2%BBWi%C2%BB%60Wi%60Wi&inputs=&header=&footer=)
Ez. Just quit before you get to the unavoidable stuff.
] |
[Question]
[
I have encountered this type of puzzle, that usually involves apples, several times. It goes as follows:
>
> There is a certain number of apples in a basket. Ava takes a third of the apples. Bob takes a quarter of the apples that are left. Finally, Dennis takes one-sixth of the apples left. In the end, there are 10 leftover apples. How many apples were in the basket?
>
>
>
The answer to the above task is 24.
## Task
Given a list of positive integers and an integer representing the apples left in the end, return the number of apples originally in the basket.
## Specs
* The \$n\$th element of the list represents the \$\frac 1 k\$ share of apples the \$n\$th person took in the apples left over.
* There will always exist one integer solution, but the step calculations might result in rational numbers
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins.
## Test cases
```
[3, 4, 6], 10 -> 24
[2], 14 -> 28
[6], 30 -> 36
[4, 3], 20 -> 40
[5, 8, 7], 9 -> 15
[2, 9, 4, 8], 7 -> 24
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~5~~ 4 bytes
```
Ė⌐Π/
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLEluKMkM6gLyIsIiIsIlsyLCA5LCA0LCA4XVxuNyJd)
Based on @Sean's Raku answer. I feel stupid for not seeing this 4 byte solution sooner.
```
Ė reciprocal (1/x)
⌐ complement (1-x)
Π product
/ divide
```
[Answer]
# [Raku](https://raku.org/), 23 bytes
```
{$^n/[*] 1 X-(1 X/@^a)}
```
[Try it online!](https://tio.run/##LYxBDoIwFESvMiGN@TVfEQoVFhiPYWKEsLArFIIrgpy9/oKbyZvJzAzPsbP@NWHnUPlZ1e/4vn8gwe1AIvG1bvXiP@2ESDXHQdqkUV0wO3xVs0Rw/Qgiw8gYVjOSkwhRyoGzlW1gs@XSMgLp5nJGwTgLl/8VyvWp0CH2Pw "Perl 6 – Try It Online")
* The number of apples is passed as the parameter `$^n`, and the list of integers as the parameter `@^a`.
* `1 X/ @^a` produces the list of reciprocals of the integers.
* `1 X- (1 X/ @^a)` subtracts each reciprocal from 1.
* `[*]` multiples together all of those fractions.
[Answer]
# [R](https://www.r-project.org), 21 bytes
```
\(x,n)prod(x/(x-1),n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhZbYzQqdPI0C4ryUzQq9DUqdA01gVyI3M3laRrJGsY6CiY6CmaaOgqGBprKCkCga6dgZMIFkjMCiZpARCEAJGcBlgPpMDZAkzM2A8sBDTQGShshpIFyJgZgOVMdBQsdBXOgtCVUFihnaAqxDygIdo6FJkiJMtQtEOcuWAChAQ)
Uses the fact that \$\frac{1}{1-\frac{1}{x}} = \frac{x}{x-1}\$ and then multiplies everything together using `prod`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~17~~ 16 bytes
```
##&@@(#/--+#)#2&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1lZzcFBQ1lfV1dbWVPZSO2/f1qaQ3BqiZVVeVFmSSpXQFFmXkm0sq5dmoODcqxaXXByYl5dNVd1tbGOiY5ZrQ6noUGtDpBrBGRyGpqA2SBhTmOIuImOMYhnBOGZ6ljomAP5lhA9OpZAQyyAfPNartr/AA "Wolfram Language (Mathematica) – Try It Online")
```
--+# {3,4,6}-1
#/ {3,4,6}/{2,3,5}
##&@@( ) Sequence[3/2,4/3,6/5]
#2 Sequence[3/2,4/3,6/5]*10
Times[3/2,4/3,6/5,10] (=24)
```
[Answer]
# [J](http://jsoftware.com/), 8 bytes
```
%[:*/1-%
```
[Try it online!](https://tio.run/##y/r/P03B1kpBNdpKS99QV/V/anJGvoKhgUKagrGCiYIZF4RvAuQbQdjGIDmouBGIbaJgDOFZAjmmChYK5hCuOUgPUNBEweI/AA "J – Try It Online")
Takes the number of remaining apples as left argument and the list as right argument.
* The first `%` (division) forms a dyadic hook, and divides the left argument by the result of applying `[:*/1-%` to the right argument (monadically).
+ The second `%` takes the reciprocals of the numbers in the list.
+ `1` `-` subtracts each reciprocal from 1.
+ `*/` takes the product; a cap (`[:`) is used to do so monadically.
[Answer]
# TI-Basic, ~~15~~ 13 bytes
```
Prompt A,B
B/prod(1-ʟA⁻¹
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 5 bytes
```
tq/hp
```
Try it out at [MATL Online](https://matl.io/?code=tq%2Fhp&inputs=%5B3%2C+4%2C+6%5D%0A10&version=22.7.4)
```
% Implicitly retrieve the first input, an array
t % Duplicate the first input (x)
q % Subtract 1 (x - 1)
/ % Divide (element-wise) the two values on the stack (x / (x - 1))
h % Implicitly retrieve the second input and append to the array
p % Compute the product of all elements
% Implicitly display the result
```
[Answer]
# [Desmos](https://desmos.com/calculator), ~~39~~ 28 bytes
*-11 bytes thanks to [@Greg Martin](https://codegolf.stackexchange.com/users/56178/greg-martin) with an amazing insight!*
```
f(l,k)=k/e^{ln(1-1/l).total}
```
Port of most of the other answers here. ~~Taking the product of a list in Desmos is super annoying; there should be an equivalent of `total` for products lol.~~ Thanks to Greg Martin, `total` can be used in a very creative way to take the product of a list!
[Try It On Desmos!](https://www.desmos.com/calculator/2fmnh9jlv8)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/b1uvckprxp)
[Answer]
# [Python](https://www.python.org), 45 bytes
*-9 bytes thanks to `att`*
Avoids the use of `math.prod`; utilises the walrus `:=` operator instead.
```
lambda l,n:round([n:=n*x/~-x for x in l][-1])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY1NCsIwEEb3nmKWrUzQ_qgx0JOMWVRKsBAnpbRQN17ETUH0Tt7GpOkm8-ZNvpnXt3sMN8fz21SXzzgYIX_C1vdrU4NFVr0buUmIVcXbafcUExjXwwQtg9UkMp2uoTF4nwgTIioQSoSjRsj2_iHKA5YLBltE6_8UHvLYHRAkwsnzOWY8LHukDlqrDUDXtzwkJrEInK7H5znWPw)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
D</P*
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fxUY/QOv//2gjHQVLHQUTHQWLWC5zAA "05AB1E – Try It Online")
Port of AndrovT's Vyxal answer.
#### Explanation
```
D</P* # Implicit input
D # Duplicate
< # Decrement
/ # Divide
P # Product
* # Multiply
# Implicit output
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 18 bytes
```
#2/Times@@(1-1/#)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9lIPyQzN7XYwUHDUNdQX1lT7X9AUWZeSbRCWnS1sY6CiY6CWa2OgqFBrEIsF0LGCCRmgioGUmeMpg6o3RgobIQmbKqjYKGjYA6UsUQzFygCttQCKGcOlPsPAA "Wolfram Language (Mathematica) – Try It Online")
Unnamed function that takes the list as its first input and the final number of applies as its second input. Same formula as most other answers here. One trivium: unless I'm overlooking some possibility, it's shorter to use `Times` here than its abbreviation `1##&` because the precedence of `/` would require extra parentheses in the second case.
[Answer]
# [Arturo](https://arturo-lang.io), ~~29~~ 24 bytes
```
$=>[&*∏map&'x->x//x-1]
```
[Try it](http://arturo-lang.io/playground?1b1RQX)
This answer assumes potential floating point issues are okay. Let me know if that is a bad assumption. This uses a new feature in 0.9.82 that was released today. Function arguments no longer need to be named. The first instance of `&` is the first argument and the second instance of `&` is the second.
[Answer]
# [Python](https://www.python.org) NumPy, 35 bytes
```
lambda l,n:n*l.prod()//(l-1).prod()
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ldLdTsMgFADgxMvFhzjZbmBSBy2FzmS-gg8wzdLZVmdaSgi76LN408ToO-nTWNq5RKlLxg3h5-McDrx-6MY-16p9K1b373tbBMnnrEyrbZZCSdSNmpfX2tQZwosFKgOGD6Nh69fFZWHqCtS-0g3sKl0bC_X2JX-0G5KaVD3lk4k2O2VRgQ7zaB0R4ATEAybAKHgNY5hBcAsh92nYI-6jPzTxaR8vGon3m0bCp122kdPhuP6hnPo0JpAQkE4vT1AWj9y1I32lEqflGWUSfN5V6mrNEs6F5JzKSNJlHDPBXCbsGHVk_XjY8HwoJCFlJLONzlfTu6kr_z95UDp8irYd-m8)
Takes a numpy vector and a number.
A bit uninspired. On the plus side: has no accuracy issues.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
İCP÷@
```
[Try it online!](https://tio.run/##y0rNyan8///IBueAw9sd/h9erq8Z@f9/dLSxjoKJjoJZrI6CoQGQiI42AjFNwEyQqDFEFKjGGMgwgvBMdRQsdBTMgWxLiB4gA2yORSxIGAA "Jelly – Try It Online")
Port of Sean's Raku answer.
#### Explanation
```
İCP÷@ # Implicit input
İ # Reciprocal (1 / z)
C # Complement (1 - z)
P # Product
÷@ # Divide
# Implicit output
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 10 bytes
```
{x+x%y-1}/
```
[Try it online!](https://ngn.codeberg.page/k#eJxVjU1ugzAUhPc+xVs0UlANNrb5fVJP0Z2FFJeYBAUCBSqBovTsdSJo1dnNN6OZKr/Nr/Nu8cM7I+Q9v73o5XvIKwhgxkN3wf2hMnWDMy44eMXddfQ+5ChBQeyhUAEvnkghFc6nq5ccqctlvHrBUYH0UPEVZBhBComHYbSSBAVkbjbdZgkj52nqx5yxsjvaU9dUwTiZ8mLn8myuJxuUXcs+v+w41d11ZCJKYpUxM3zU02CGxTd931j/WDe2bQ0hWlJQFOKCQsjByX8DoYgWD6DgVw+cEv3oSf4Py5hotyBdIvgfVpzoiEJKIXFJtuEwctvOP19TlyTb5Q+qVVmW)
* `{...}/` set up an implicitly seeded reduce, seeded with `x` (the number of remaining apples) and run over `y` (the list of integers)
+ `x%y-1` divide `x` by `y` minus one
+ `x+` add this to the above, and pass into the next iteration of the reduce
An alternative answer that is also 10 bytes is:
```
{x%/1-1%y}
```
* `1-1%y` subtract the reciprocals of `y` from one
* `x%/` beginning with `x`, do a divide-reduce over the above
[Answer]
# JavaScript, 27 bytes
```
(x,n)=>x.map(c=>n*=c/~-c)|n // 27
(x,n)=>x.map(c=>n+=n/~-c)|n // 27
```
The first formula is obvious: if we get \$\frac{1}{x}\$ so there left \$\frac{x-1}{x}\$ and we need to divide reminder to \$\frac{x-1}{x}\$ and it is the same to multiply reminder to \$\frac{x}{x-1}\$
The second formula is the same as first just in another format:
\$
n \* \frac{x}{x - 1} = n \* (\frac{x - 1 + 1}{x - 1}) = n \* (1 + \frac{1}{x - 1}) = n + \frac{n}{x-1}
\$
Try it:
```
f1=(x,n)=>x.map(c=>n*=c/~-c)|n
;f2=(x,n)=>x.map(c=>n+=n/~-c)|n
;[
[[3, 4, 6], 10], // 24
[[2], 14], // 28
[[6], 30], // 36
[[4, 3], 20], // 40
[[5, 8, 7], 9], // 15
[[2, 9, 4, 8], 7], // 24
].map(([a,b]) => console.log(f1(a,b), f2(a,b)))
```
## UPD 31 -> 29
Thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco) for the [tip](https://codegolf.stackexchange.com/questions/257649/infinite-apple-dilemma#comment569490_257674) to reduce bytes count
## UPD 29 -> 27
Thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) for the [tip](https://codegolf.stackexchange.com/questions/257649/arbitrary-apple-dilemma/257674?noredirect=1#comment569621_257674) to reduce bytes count
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
*VË/ÓDÃ×
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=KlbLL9NEw9c&input=MTAKWzMsIDQsIDZd)
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, ~~24~~ 21 bytes
```
[ dup 1 v-n v/ Π * ]
```
[Try it online!](https://tio.run/##Xc9LDoIwEAbgPaf43ZqAPAqCJmyNGzfGlXHRQIkEeYQWEkO4iyfySlhK2TiTTjL9Mn1kNBF1O92u58vpgIK1FXuhpOJp9WwWrpplp6vypE4ZmpYJ8W7avBKgnNcJx9EYDMgY4NiyeCAIMMrEBmYMl6xKZHEXmWPRUKs3zwZ/6gVa3VmJPFu7UmJrjeTyEWKvWanja92rayM5HipfXzVOd6RdAwe9WaHf4fvBFo8pWz4Wl7QBFzQprOkH "Factor – Try It Online")
Port of @pajonk's [R answer](https://codegolf.stackexchange.com/a/257662/97916).
```
! 10 { 3 4 6 }
dup ! 10 { 3 4 6 } { 3 4 6 }
1 ! 10 { 3 4 6 } { 3 4 6 } 1
v-n ! 10 { 3 4 6 } { 2 3 5 }
v/ ! 10 { 1+1/2 1+1/3 1+1/5 }
Π ! 10 2+2/5 (product)
* ! 24
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes
```
I÷×ηΠθΠ⊖θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzOvxCWzLDMlVSMkMze1WCNDRyGgKD@lNLlEo1BTE8FxSU0uSs1NzStJTQFJAIH1///R0UY6CpY6CiY6ChaxOgrmsf91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Variant of @pajonk's answer that doesn't suffer from floating-point errors.
```
η Second input
× Multiplied by
θ First input
Π Product
÷ Integer divided by
θ First input
⊖ Vectorised decrement
Π Product
I Implicitly print
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 40 bytes
```
x=>n=>n*eval([x.join`*`,...x].join`/~-`)
```
[Try it online!](https://tio.run/##VY7NboMwEITvPIVvtokxDpCEqiK59QV6dJGwHEOJXJsCieilr04X@hN1tZf5ZjWzF3VTg@7bboycP5u5LuapODrY0NyUJXLiF9@6KqwY53wqv1X8GVV0fgx6835te0NwPWDKe6POT601zx9OE8HwdazzFXdWaUPil5LFDcMlJUDf1KhfgUkensipiGjcLLAjUK@9G7w13PqGrF/gmuDNtMEUU0pnmTKUMbQvGdoKBBMdUZIFMllAhv5mwXkgl7tU/MPpPpCQkIKTiDvORCB3DOUMHcB5@MXbHWSDXltzcA4/lV8 "JavaScript (Node.js) – Try It Online")
[37 with small error](https://tio.run/##VY7NboMwEITvPIVv9hJjCJCEqoLc@gI9ukixHEOJHKDgRPTSV6cL6o8y2st@s5rZi7qrUQ9N74K2O5u5yucpL1oc39yVZZO4qp65vHDhV@BAXLqmPfknmJ@9wXzcmsEwWo0UxGDU@aWx5vWz1Szi9OaqbMW9Vdqw8K3kYc1pCQzpVTn9jkwK/8iOeQBhDWsRduuuHTtrhO1qtr5AK0Y304YCBYBZJpyknOxLTrYRQQUFiVNPxgtIyZ8WnHlyuUuiB5zsPYkJCTpx9I/TyJM7TjJODug8/eLtDrNxX1szdA4/ld8)
[Answer]
# [Perl 5](https://www.perl.org/), 33 bytes
```
sub{$a=pop;$a*=$_/($_-1)for@_;$a}
```
[Try it online!](https://tio.run/##fZBLb4JAFIXX5Vec6FjBDC0vH5Vg3Tepm@4oIVaH1kiFAH2F@NvpHVDULspm5p7znXvvkIosHlbvP2CRV@UfLyVbemmSumw58Fh4q7JQN7UoyeYhSfvKVYhBZJQycSQ9glsWBCMTnyLLBZpUk/m/s9KtIZR5Gm9WYh5y3eIWZ6GvW4GE5akN5GkG@HrbxMTMTHceHqNl4/1t7hs3N6xLZeDS9L1Coqr4gG9zOByjgMM0QJ83g@UAAa9dS@oO2k@6k9aVKdu4cO1R61JbmwDLOLmO0bpDjgnHmIC7o2sOT3NJrhebEDA@30orFYnLHy@@U3ig52DOQvcgq2DFcityDhaLqIBGyJkN9poUJF2zSCX9Em2gNNvsiqjT00c5UANT9HTTogqSo8pa053Gi1Uh1seaGtfX512HK1fNdl4z7x79ZNvHFP3HxRMWD30COv5hfNA5LMDrJ/E64ir76hc "Perl 5 – Try It Online")
[Answer]
# F#, 39 bytes
```
let i=Seq.foldBack(fun n c->c*n/(n-1.))
```
[Try it online!](https://tio.run/##jVDBTsQgFLzzFZNNTIppq7td3d0020S9evNo9oAtTYiUrkDjxX@vgJbWRBM5PHgzb2aA1mR1r/k4Sm4hjk/8LW972dyz@jVpBwWFOqvqS3WVqGydUxrmLDf2gRlucCRw6znUcCpKbEvcnlKsr2d04/vt3Hu@WPBOUjhos4BuSuxL7Bx6WPiUOISAvcN3AT@F@lHhURibd@yMcO9EDd0L1yaF5h0TquGaIqui1cT/ULayZ5amSKLG019oUFJCSHw8cZz/r39l/sKlEJhuMQsInXyFdfl/GfujGaSNAaGctVC2VfGVq4s7MNXAbVkFoYQVTOKdGYes4tS3e@xjyALxWYSOnw)
A partial-application solution. The function `i` takes two parameters and applies them directly to `Seq.foldBack` - the source, and the initial state. In this case, the source is the collection of divisions made on the apples (eg. `[4, 3]`), and the initial state is the remaining apples (eg. `20`).
`Seq.foldBack` threads an accumulator through the collection, starting with an initial state, then applying the function specified using the next value in the sequence to that state (in this case, calculating the apple count from the next division), and so on until the sequence is finished. Because it's `Seq.foldBack`, it goes through the collection in reverse order. It returns the result of the accumulator: the initial number of apples.
For those who are curious, the reason for the `1.` instead of just plain `1` is that F# is very very strongly typed. You cannot subtract an integer from an float. Both have to be the same type. `1` is an integer, and `1.` is a float.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~18~~ 9 bytes
```
q*$*Yg/Dg
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhYrC7VUtCLT9V3SIXyYcLSxjoKJjoJZ7CJDA4gQAA)
Takes the list on the command line and the number on STDIN.
*-9 thanks to @DLosc*
#### Explanation
```
q*$*Yg/Dg # Implicit input
q # The number
* # multiplied by
$*Y # the product of
g/ # the list divided by
Dg # the list minus one
# Implicit output
```
Old:
```
Fig/BN-g{o:o*i}o*q # Implicit input
Fi # for i in ...
g/ # ... the list divided by ...
BN-g # ... the list minus one ...
{ } # ... do:
o: # set o to ...
o*i # ... o times i
o*q # output o times the number
```
(`o` is automatically initialised to 1)
[Answer]
# [Haskell](https://www.haskell.org), 22 bytes
```
foldr(\k a->k*a/(k-1))
```
Accepts the number, and then the list: `foldr(\k a->k*a/(k-1)) 10 [3, 4, 6]` is 24.
[Attempt This Online!](https://ato.pxeger.com/run?1=RY89bsJAEIV7n-IJpfBGswr-ARwpzgnoKI0VrbAtkBfb8i5Kk5ukoUHJCXKX9ByE2awcqid97828mc-vvTJtrfV3MZO7YZiVlwY5tpeTbWT20_S6GsNtCyVf20f1FLYyEsKbv1dbG_u2U6Y2PFIEQBgWCSElLEtCNBeEOBXkjdih1KFsQi6VuFSynBDPJkxjR9P5RBeEjLBi45l5tPjfyeCvL2Nr5evKIBjdOQ06KOQ5enxwVlEnqBd4kbifXQZHdeg4PZzsxo7rDg8w-_6dRWmNQ4XR_3o-e70B)
[Answer]
# [Haskell](https://www.haskell.org), ~~33~~ 31 bytes
*-2 bytes thanks to [@Lynn](https://codegolf.stackexchange.com/users/3852/lynn)*
```
p=product
x#n=p x/p(pred<$>x)*n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RZBNbsIwEIX3PsWTYGFXRkASIEiYE3TXJYqqKAkiIjiWf0SQepNu2FQ9BufgBhwDu1HKaqTvvZl5M9-_h9wcq6a5Xn-c3U_SmxJKt6UrLOlGUih0U0WVrsrNeNuxN9m77g9bGftZ5KYyENgRgNJdzJFwLDOO-YxxRAnjvRAFlASUDii44uCKlwPyvbGnUaDJbKALjpRj5YW15_PF_0wP_valXlr16zJCdIjjZOG0voCOGGoIgRZfoDVvGTYTvKJn5JTX0ncoZz-sfpcYwxzasy9506Auoft7h-88AQ)
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~6.5~~ 6 bytes
```
/*`*$@`*+-1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWq_W1ErRUHBK0tHUNISJQiU3RStFGOpY6JjoWsUo6CkrmSrFQGQA)
```
/ Divide
* multiply
`* product
$ the list
@ the number
`* product
+ add
-1 -1
the list [vectorized]
```
] |
[Question]
[
Given an input string, write a program that outputs the total number of lines and curves it has.
## The Challenge
* Take input from `STDIN`, or any other input method.
* Output to `STDOUT`, or any other output method, the total number of lines and curves contained in the string, *in that order*, based on the below table in the code snippet.
* Any non-alphanumeric characters should be ignored.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins.
## Clarifications
* The lines and curves are determined by the font used on Stackexchange for `code blocks`.
* Circles (like `O, o, 0`) and dots (`i, j`), are considered to be 1 curve each.
* Input can be a string, list of characters, stream of characters, bytecodes etc.
* Output can be an array of integers, tuple of integers, comma-separated string, etc. *The two numbers must be separate,* so `104` is not valid, but `10,4`, `10 4`, `10\n4`, `[10,4]`, `(10, 4)`, and so on is.
* Heading and trailing whitespace is perfectly acceptable.
### Sample Input and Output
```
# Format: str -> line, curve
hi -> 4, 2
HELLO WORLD -> 20, 4
l33+ 5pEak -> 13, 8
+=-_!...?~`g@#$%^ -> 1, 2
9001 -> 5, 3
O o O o O o -> 0, 6
```
### Character Table
```
Char | Lines | Curves
0 | 1 | 1
1 | 3 | 0
2 | 1 | 1
3 | 0 | 2
4 | 3 | 0
5 | 2 | 1
6 | 0 | 1
7 | 2 | 0
8 | 0 | 2
9 | 0 | 1
A | 3 | 0
B | 1 | 2
C | 0 | 1
D | 1 | 1
E | 4 | 0
F | 3 | 0
G | 2 | 1
H | 3 | 0
I | 3 | 0
J | 1 | 1
K | 3 | 0
L | 2 | 0
M | 4 | 0
N | 3 | 0
O | 0 | 1
P | 1 | 1
Q | 0 | 2
R | 2 | 1
S | 0 | 1
T | 2 | 0
U | 0 | 1
V | 2 | 0
W | 4 | 0
X | 4 | 0
Y | 3 | 0
Z | 3 | 0
a | 0 | 2
b | 1 | 1
c | 0 | 1
d | 1 | 1
e | 1 | 1
f | 1 | 1
g | 1 | 2
h | 1 | 1
i | 3 | 1
j | 1 | 2
k | 3 | 0
l | 3 | 0
m | 3 | 2
n | 2 | 1
o | 0 | 1
p | 1 | 1
q | 1 | 1
r | 1 | 1
s | 0 | 1
t | 1 | 1
u | 1 | 1
v | 2 | 0
w | 4 | 0
x | 4 | 0
y | 1 | 1
z | 3 | 0
```
[Answer]
## Haskell, ~~214~~ ~~199~~ ~~188~~ 175 bytes
```
g 0=[]
g n=mod n 5:g(div n 5)
d#s=sum[n|c<-d,(i,n)<-zip['0'..]$g s,c==i]
f s=(s#0x300BBD37F30B5C234DE4A308D077AC8EF7FB328355A6,s#0x2D5E73A8E3D345386593A829D63104FED5552D080CA)
```
[Try it online!](https://tio.run/##LZBda4MwFIbv/RVnbYdKVWJimjgaNjUJu@go7GYX4jqpq5VWJ3MbpYz9dVexF4f3Aw4vPPu8O7wfj31fAhJpZpTQiPqjgAboXWkV1c/gbKOYdqL7rtPmd7t0C8eqnMZeuueqTU1kel42K6FztkJUmbGDTljdFJ0IQnEsCdMExTTBJJAqiAjiEjEWJVxppmOCOaE0WjjDA5ZUMRJxRSQJKOELGl4SDuWC@CjQSlJKsUQcJZHd13nVgIA6b582YLWfVfMFHuxsSA2Ayb6aOIM@qtVqDS/r55UciyMhc6Ctyg9jngt3c@N53v3fW/kwnd2@jnWIkD@6NXzA9SaZ4bpwHR4XrQsCGBmYZ3PAgE4@CzjFCdMBCTRGkc/jOI5CyjAKk1hzzakKsCY8Ucru/wE)
The numbers of lines and curves are the digits of base-5 numbers and stored as base-16 numbers. Function `g` translates back to base-5.
Edit: -13 bytes thanks to @cole.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~78~~ ~~69~~ 65 bytes
*-4 bytes thanks to Kevin Cruijssen, Go and check out [his even better 05AB1E answer](https://codegolf.stackexchange.com/a/188804/85908)*
```
žKÃÇ48-©•7ć_qýÊΣŸßαŽ_ì¡vFÛ–ÄÔ™”súyån!₁ζB?òrβÂ@µk₆¼×¬°•5в2ä`®èrè‚O
```
[Try it online!](https://tio.run/##AYYAef9vc2FiaWX//8W@S8ODw4c0OC3CqeKAojfEh19xw73Dis6jxbjDn86xxb1fw6zCoXZGw5vigJPDhMOU4oSi4oCdc8O6ecOlbiHigoHOtkI/w7JyzrLDgkDCtWvigobCvMOXwqzCsOKAojXQsjLDpGDCrsOocsOo4oCaT///bDMzKyA1cEVhaw "05AB1E – Try It Online")
Outputs as [Curve, Line]
I'm really bad at 05AB1E I just found out. Can definitely save more bytes if I can get 05AB1E to do `è` across my list of lists
---
## Explanation
```
žKÃ #Filter out non alpha-nums
Ç48- #Convert to ascii and subtract 48 so "0" is 0 etc.
© #Store that for later
•...•5в #De-compress compressed list
2ä #Split into 2 chunks (lines + curves)
` #Separate them onto the stack
® #Get the value that we stored
èrè #Apply indexing to both lists
‚ #Put our indexed values back into a list
O #Sum our lists
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 45 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ØBċþSḋ“yƘ.ṪñF[)µṡṭɗḌyė$Ṫk“¢⁶KɱzV$QḂḥỵṙu’b5,3¤
```
A monadic Link accepting a list of characters which yields a list of (two) integers.
**[Try it online!](https://tio.run/##AWgAl/9qZWxsef//w5hCxIvDvlPhuIvigJx5xpgu4bmqw7FGWynCteG5oeG5rcmX4biMecSXJOG5qmvigJzCouKBtkvJsXpWJFHhuILhuKXhu7XhuZl14oCZYjUsM8Kk////bDMzKyA1cEVhaw "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///wDKcj3Yf3BT/c0f2oYU7lsRl6D3euOrzRLVrz0NaHOxc@3Ln25PSHO3oqj0xXAUpkA9UcWvSocZv3yY1VYSqBD3c0Pdyx9OFuoNKZpY8aZiaZ6hgfWvL/4e4tR/ccbj866eHOGSqPmtaouP//n5HJ5eHq4@OvEO4f5OPClWNsrK1gWuCamM2lbasbr6inp2dfl5DuoKyiGsdlaWBgyOWvkK8AxQA "Jelly – Try It Online").
### How?
```
ØBċþSḋ“...“...’b5,3¤ - Link: list of characters, T
ØB - base-chars = "01...9A...Za...z'
þ - outer product with T using:
ċ - count occurrences
S - sum -> [n(0), n(1), ..., n(9), n(A), ..., n(Z), n(a), ..., n(z)]'
¤ - nilad followed by link(s) as a nilad:
“...“...’ - list of two large integers (encoded in base 250)
5,3 - five paired with three = [5,3]
b - to base -> [[Lines(0), Lines(1), ...], Curves(0), Curves(1), ...]
ḋ - dot-product
```
[Answer]
# [Scala](http://www.scala-lang.org/), 235 bytes
```
val a=('0'to'9')++('A'to'Z')++('a'to'z')
def f(s:String)=s.filter(a.contains(_)).map(c=>"gdgkdhfckfdlfgedhddgdcedfgkhfcfceeddkgfggglgilddnhfgggfggceegd"(a.indexOf(c))-'a').map(x=>(x%5,x/5)).foldLeft((0,0))((x,y)=>(x._1+y._1,x._2+y._2))
```
[Try it online!](https://tio.run/##LY/fT8IwEMff91ecE7I2gzogPGAcSiKJDzMk8mDig1h7bamr3cKqGRL817ELPnwvn9yP7901glt@qt4/pPDwyI0D2XrpsIFFXcPh9M0t8JwkWeKrZJbQNCXJouOXM/OOfxIaoVSgSHO99jvjNM0bpoz1ckc4E5XzwbkhG0rZJ6@JyOexRl3iVolSoVVa4hZRo5CodBmySkiJWGqltbbaWES37TgoVDTGwdY4lO1KEUHpMNxxtm7zOWn700F7NQ3LVGWxkMoTkg0ySglpB3vadbDNKN2HMAg07mhM6QlUtQNiHdwMwVRsXX3thGSNR@OYlr4wTjYU6vCft440ce9g3RGGc@gdVBijx5jC8bQ10cOyKFbwvHoq7iM7maQwrZe8jNJ8uLlgjN3@vum7y17/NZpl2ShaQQX/@gM "Scala – Try It Online")
Not so small, probably can be golfed further.
Note: The 52-character string literal is like a dictionary which maps a character to another character which denotes number of lines and curves according to the following table:
```
Curves|Lines
|0 1 2 3 4
----------------
0|a b c d e
1|f g h i j
2|k l m n o
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~159~~ 154 bytes
For any character `lines*4 + curves` gives value from 0 to 16. Base-36 is used to encode these values (1 character = 1 value).
-5 bytes thanks to @Chas Brown
```
lambda s:map(sum,zip(*(divmod(int("5c52c918210000000c615gc9cc5c8gc15291818ggcc00000025155565d6cce915551558gg5c"[ord(x)-48],36),4)for x in s if'/'<x<'{')))
```
[Try it online!](https://tio.run/##VY3BSsNAFEX3fsUYlczYNGYmfSGRFl1YcBEIuOmitRrfmOlgkxmSKtGCvx5TKoU8uHDvOYtnv3cbU4mumK26bV6@yZw0t2VuafNZej/a0msq9VdpJNXVjjqAIDDhseDB8TDioDBBBIwVchC95LFSiEcvgANABDJCfE8OvU/vAZ2lqSVt2XgSP3thxLwJK0xNWqIr0hBduDfutJ26e5cx1tn68L6gzkY7jJ2d5uM8TTOyyJ7ShwHfhuGIgJ3nHwM8mo1fzn3fv/t9VfcXl1frgU2CgA9ARgz5T8@7Pw "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 141 bytes
This is a port of my Python3 solution.
This version outputs a list of long ints, so it looks like `[4L, 2L]` instead of `[4, 2]`.
```
lambda s:map(sum,zip(*(divmod(int("8BK5NLC8RS10XWUX12BG408C2UELUAFEOVARZKCHEEDDMXG09L48ZG",36)/13**(ord(x)-48)%13,3)for x in s if'/'<x<'{')))
```
[Try it online!](https://tio.run/##Vc3RS4NAAAbw9/6KyxreOefuPBe32KhNLwe7EgybjKgMsR1NPXQLt6B/3Qoi8OF7@H7fw6cOu01Z2G02fWy3Sf6aJqC@zBMF631uHqWCBkzlR16mUBY7qLH5cnQnXBbeExyvopjYc9/BzLUjLqLZDQ8eZuF66S4497zb2Mdj4bC1r5n0Ag0JNQxYVils0MBhqEeoSVFWVqABsgA1kJk@1CfNRP/UEUKtqn4fM6htpIbQyX9dcCECsApC4XV8S2kfjBRP3jvcnw6eTy3Luvp6ebs@O@89ddYxxqQDASjBX368/QY "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 51 bytes
```
ØBiⱮị“Æƭ&¶*ṪḳAøƬsøD<~²ṂvṠỤṣT3rdʠ¬⁻ÇṆṇ.ÑƑaȮż’b5¤s2¤S
```
[Try it online!](https://tio.run/##y0rNyan8///wDKfMRxvXPdzd/ahhzuG2Y2vVDm3Terhz1cMdmx0P7zi2pvjwDhebukObHu5sKnu4c8HD3Use7lwcYlyUcmrBoTWPGncfbn@4s@3hzna9wxOPTUw8se7onkcNM5NMDy0pNjq0JPi/NdBUBV07hUcNc61BSvepcD3cveVw@6OmNZH//2dkcnm4@vj4K4T7B/m4cOUYG2srmBa4JmZzadvqxivq6enZ1yWkOyirqMZxWRoYGHL5K@QrQDEA "Jelly – Try It Online")
A monadic link that takes a string as input and returns a list of integers as `[lines, curves]`
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~251 219~~ 217 bytes
*-34 bytes from @Expired Data* **:o**
```
_=>_.map(a=>(p+=~~"13103202003101432331324301020202443301011111313332011101124413"[(x=a.charCodeAt()-48)>16?(x-=7)>41?x-=6:x:x])&(o+=~~"10120110210211001001000011211010000021111121120021111111100010"[x]),p=o=0)&&[p,o]
```
[Try it online!](https://tio.run/##NY1PawIxEMW/iuSwJHR3mckELUJWSit4KAi9eFgWCVv/tFgTVGRPfvV1RrdhHvwyb3jvN1zDuT39pEtxjN@bfuv7ta/W5V9IOvhKpxd/uykkBLJgARjQkSVCso4AQbbWORJGeewQ3zKx2EFSte58KNt9OL1zx9tFm8K9mgrHM90VfmIqhzOG8bSbdo3JdHyWAkoMWBkEeA5IqmQLioGPv/1n6ZVDVXNUnnz0YLKsTnls@jYez/GwKQ9xp7e6VguVqznrc9CSNWKtBv4a9h@qMaa/Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 160 bytes
```
$
¶$`
T`dLl`13103202003101432331324301020202443301011111313332011101124413`^.*
T`dLl`10120110210211001001000011211010000021111121120021111111100010`.*$
.
$*
%`1
```
[Try it online!](https://tio.run/##NYzBCsIwDIbveYqKHciGJWnqwYPowaGHwkAEb9qBosOhIp59LB/AF6uNuvAHvuT/k/vh0VzqmA0WIWp4v3SAddj7NhATskWLmIAcW2Zi6xgJZWudY2GSSg6nbKLUySEOW5N3j5DEQisixJ9QkpIXFIO@s@1YfkkwmFyDAZ1DFijGUwPL0vtKbaqVn0PLXKjRrazPUEyGu54xZvoMx1lfZ1sYp3uo1FX9@wM "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
$
¶$`
```
Duplicate the input string.
```
T`dLl`13103202003101432331324301020202443301011111313332011101124413`^.*
```
Count each character's lines on the first line.
```
T`dLl`10120110210211001001000011211010000021111121120021111111100010`.*$
```
Count each character's curves on the second line.
```
.
$*
%`1
```
Sum the digits separately on each line.
[Answer]
# [R](https://www.r-project.org/), ~~164~~ 153 bytes
```
function(s,`!`=utf8ToInt,x=(!"
")[match(!s,c(48:57,65:90,97:122),0)])c(sum(x%%5),sum(x%/%5))
```
[Try it online!](https://tio.run/##JcnNCoJAFAVgxsUVdHEL5gF0QJiBiUwyf8hdQYEgRNAiAkMQXaiQCr79NNHicD7O@ajaOW4cVc99NbVDz0dZumU2T3V8H679JJeMuwwQDLSJZRA0CVC0EQEtigQMvRKLUkQDCACYsDIR1/bPOvoBZOLZvaeq4e4oK76P0zCShzBNfJlE6S4IhPTFS1R8nDu@eF4o5F9bTaFqzpqWCUv35ZznhfMobvmJCfUF "R – Try It Online")
I had the same idea as [nimi's answer](https://codegolf.stackexchange.com/a/188452/67312) using a base 5 encoding but encodes as ASCII characters instead of base 16. Uses `nomatch = 0` in [`match`](https://codegolf.stackexchange.com/questions/188162/matchmaker-matchmaker-make-me-a-match) to eliminate non-alphanumeric characters.
Returns `curves lines`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 60 bytes
```
IE⟦”)⊞∧cⅉ→ÞYγμ◧⊞¶u№¶⊘¶∕«⁸””)∨⧴|υ;↷dLτIüO¦:”⟧Σ⭆Φθ№⭆ι⍘ξφλ§ι⍘λφ
```
[Try it online!](https://tio.run/##XU7BCsIwDL37FWWnDiukzTx50qHgQRB2FA9Fpw7rNrdO9vc16Q6CgSbv5b2Gd3nY7tJYF8Kxq2ovc9t7ebCtPCUaNaABAwAaNBdqRNoQomeyjCihDA1NNBmSj/2kICZKJCSyG4w28T91ujZhPsKHmcbJFKJngpCclSiGlyw8Jbtzpl3lfNnJtxJ5M1DYn1IpsbF9OS3kqMQtTZVw3NZ@X1/L8c/ioiXWKgSHOBfLdmufs7D4uC8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
E⟦”)⊞∧cⅉ→ÞYγμ◧⊞¶u№¶⊘¶∕«⁸””)∨⧴|υ;↷dLτIüO¦:”⟧
```
This is an array of two strings `13103202000101111131333201110112441331014323313243010202024433` and `10120110212111112112002111111110001002110010010000112110100000`. The strings are then mapped over.
```
Φθ№⭆ι⍘ξφλ
```
The elements of the input are filtered over whether they are contained within the (62) characters of the default base conversion alphabet.
```
⭆...§ι⍘λφ
```
The elements that remain are then converted from base (62) and this is then indexed into the mapped string.
```
I...Σ...
```
The digits are summed and cast back to string for implicit print.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~165~~ ~~159~~ ~~148~~ 146 bytes
For any character (including non-alphanumeric) `lines*3 + curves` gives value from 0 to 12, so we can use long base-13 number to encode data. To make it shorter it is converted to base-36.
Thanks to @Chas Brown for great advices.
-2 bytes by converting lambda to program.
```
print(*map(sum,zip(*(divmod(int("8BK5NLC8RS10XWUX12BG408C2UELUAFEOVARZKCHEEDDMXG09L48ZG",36)//13**(ord(x)-48)%13,3)for x in input()if'/'<x<'{'))))
```
[Try it online!](https://tio.run/##Lc5dT4MwAIXh@/6KWl1oGQO6soWZGd2gsmRVEgyO7EIlYR@NAxrGFtTEv44j8STv1bl51Fe9LwvWbssKSigLWKXFboPH5BZACDfn9IARQq2qZFFjPU8VPp5y41sqrONMnvMyw92D3Ply9Cw8N3qhdrKKEzqcB47tesOYi3j2yMPXWbReegvOff8pCeyJcNx1gAw2JpZFma7jsspwQwaOS3qUGYx0oqYTyUKdakzkVrO0aTPVfjRyWXthkXYvwYILEcJVGAkfHBjrw5Hi6Sfo3w3er0zTvP/92D1c3/TewMS2KQhhCf/7Aw "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~179~~ ~~166~~ ~~165~~ 163 bytes
```
lambda s:[sum(p[:max(0,p.find(c))].count(',')for c in s)for p in',02BDJPbdefghjpqrtuy,57GLRTVnv,14AFHIKNYZiklmz,EMWXwx',',02569CDGJOPRSUbcdefhinopqrstuy,38BQagjm']
```
[Try it online!](https://tio.run/##NY5dT8IwFECf7a@4Rk23UJaxMQQS/ARBnA5BRQXUMRwrbF1lm4IP/vXZkvDQ5PY0PffwTRrEzMj9xjgP3Wg6cyGpj5IsUvioHrlrRSdc8ymbKZ6qTjQvzliqYIJVP16BB5RBsh25GDHRjYtmtzedffrzYMG/Vmm2IdZx2@4/PLFvUiqfX3Wub@5eXukyjH5J63b4/LMWMvHPqtQum@2u0@sPHqeeEASUxcKQSIVZvbh354sIT/JBY5RpCQ@pqIDiCWAV5PpMlmCMAyphmYCBOi3bdmDo9O2mZIZOoIxC0yyAxVvuUrKSSaCKCo3i@76maad/H/Ozg8Ojt@2TVNR0vSQvFgETORDD7ggmdBWxcNcyZlidICRbEhLLmkEd7fEVZakA4CuJSiBGKBeJ@B8 "Python 2 – Try It Online")
Returns a list `[curves, lines]`.
[Answer]
# [Python 2](https://docs.python.org/2/), 525 bytes
```
l=c=0;e=[(1,1),(3,0),(1,2),(0,2),(3,0),(2,1),(0,1),(2,0),(0,2),(0,1),(3,0),(1,2),(0,1),(1,1),(4,0),(3,0),(2,1),(3,0),(3,0),(1,1),(3,0),(2,0),(4,0),(3,0),(0,1),(1,1),(0,2),(2,1),(0,1),(2,0),(0,1),(2,0),(4,0),(4,0),(3,0),(3,0),(0,2),(1,1),(0,1),(1,1),(1,1),(1,1),(1,2),(1,1),(3,1),(1,2),(3,0),(3,0),(3,2),(2,1),(0,1),(1,1),(1,1),(1,1),(0,1),(1,1),(1,1),(2,0),(4,0),(4,0),(1,1),(3,0)]
d='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
for i in input():
if i in d:
p=d.find(i);l+=e[p][0];c+=e[p][1];
print l,c
```
[Try it online!](https://tio.run/##bVJrT8IwFP2@X1GnZpvMpd0AxaXxBYo6neIDlUzFPaAyt4pDwQ/@9Vk2EiojaU/vPb333NOkdJL040hP3djzsSRJaYhdDE0fd2SkIkWVDRUyRKrOEGaYM3p2CzPUMwbOaopdKIunWM54XsHgGH5irsnX8zr5rGUe0EIvr2BwPhHXi5agzvmZM8Y/tUUPRZ0iX/Q2f7UjeFiCSDfKlerWdm3/4LDeODpunpyeWecX9uVV6/rm9q59//DYfXU9P@j1ydsgfI9i@jH8TEZf3@PJjyQE8RAQQCK26CiRlR0BkCBnPBYDij0tIJEnE8UMS9jvUKcDHdOdhcgxBTokUQJC1U3ZjxD8se/K0/@hbFRTsU9EQWw2LMsGbbtl1VkWGkYJVGijO2BJCW8@r2iatvv70ttbXVt/YlwNQsQOG8RgtsU/ "Python 2 – Try It Online")
Similar approach to the reference implementation but somewhat shorter.
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=sum -p`, 180 bytes
```
say sum y/0-9A-Za-z/13103202003101432331324301020202443301011111313332011101124413/r=~/./g;$_=sum y/0-9A-Za-z/10120110210211001001000011211010000021111121120021111111100010/r=~/./g
```
[Try it online!](https://tio.run/##ZY29DsIwDIRfpQMbSuOfZKCoAwMbjCwsqANCFYFGTRjKwKMTbFAnIkf@nDtf4nkMvpTUTVV63KrJglltzLEzT4uMwAQEIICOiRmZHAOCvpJzrIx6RGHxCskVBdmO7cvW9rJenNq/ZED1AmkhwK9AVzVAUQX8zjSzhqtxTi4lMC8rH7fd9T3E3A/3VMze1@KRvutTbppD7oP@X0wMHw "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 53 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•xþ¢*>ÌŸÑå#÷AUI'@æýXÁи<¥èå–ΘηžÎà₅åǚĕ5вR2ôžKISk®KèøO
```
[Try it online](https://tio.run/##AW4Akf9vc2FiaWX//@KAonjDvsKiKj7DjMW4w5HDpSPDt0FVSSdAw6bDvVjDgdC4PMKlw6jDpeKAk86YzrfFvsOOw6DigoXDpcOHxaHDhOKAojXQslIyw7TFvktJU2vCrkvDqMO4T///bDMzKyA1cEVhaw) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkv3/Rw2LKg7vO7RIy@5wz9EdhyceXqp8eLtjqKe6w@Flh/dGHG68sMPm0NLDKw4vfdQw@dyMc9uP7jvcd3jBo6bWw0sPtx9deLgFaILphU1BRoe3HN3nXRmcfWidN1D5Dv//Ov8zMrk8XH18/BXC/YN8XLhyjI21FUwLXBOzubRtdeMV9fT07OsS0h2UVVTjuCwNDAy5/BXyFaAYAA).
**Explanation:**
```
•xþ¢*>ÌŸÑå#÷AUI'@æýXÁи<¥èå–ΘηžÎà₅åǚĕ
'# Compressed integer 101629259357674935528492544214548347273909568347978482331029666966024823518105773925160
5в # Converted to base-5 as list: [1,0,2,0,0,2,1,0,1,2,0,3,2,0,1,1,0,3,1,1,0,3,0,3,0,4,0,4,0,2,1,0,0,2,1,0,1,2,2,0,1,1,1,0,0,3,0,4,0,2,0,3,1,1,0,3,0,3,1,2,0,3,0,4,1,1,1,0,2,1,0,3,0,3,1,1,0,4,0,4,0,2,1,1,1,1,1,0,1,1,1,1,1,1,1,0,1,2,2,3,0,3,0,3,2,1,1,3,1,1,2,1,1,1,1,1,1,1,1,0,1,1,2,0]
R # Reverse this list (due to the leading 0)
2ô # Split it into pairs: [[0,2],[1,1],[0,1],[1,1],[1,1],[1,1],[1,2],[1,1],[3,1],[1,2],[3,0],[3,0],[3,2],[2,1],[0,1],[1,1],[1,1],[1,1],[0,1],[1,1],[1,1],[2,0],[4,0],[4,0],[1,1],[3,0],[3,0],[1,2],[0,1],[1,1],[4,0],[3,0],[2,1],[3,0],[3,0],[1,1],[3,0],[2,0],[4,0],[3,0],[0,1],[1,1],[0,2],[2,1],[0,1],[2,0],[0,1],[2,0],[4,0],[4,0],[3,0],[3,0],[1,1],[3,0],[1,1],[0,2],[3,0],[2,1],[0,1],[2,0],[0,2],[0,1]]
žK # Push builtin string "abc...xyzABC...XYZ012...789"
IS # Push the input, split into characters
k # Get the index of each of these characters in the builtin-string
®K # Remove all -1 for non-alphanumeric characters that were present
è # Use these indices to index into the earlier created pair-list
ø # Zip/transpose; swapping rows/columns
O # Sum both inner lists
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•xþ¢*>ÌŸÑå#÷AUI'@æýXÁи<¥èå–ΘηžÎà₅åǚĕ` is `101629259357674935528492544214548347273909568347978482331029666966024823518105773925160` and `•xþ¢*>ÌŸÑå#÷AUI'@æýXÁи<¥èå–ΘηžÎà₅åǚĕ5в` is `[1,0,2,0,0,2,1,0,1,2,0,3,2,0,1,1,0,3,1,1,0,3,0,3,0,4,0,4,0,2,1,0,0,2,1,0,1,2,2,0,1,1,1,0,0,3,0,4,0,2,0,3,1,1,0,3,0,3,1,2,0,3,0,4,1,1,1,0,2,1,0,3,0,3,1,1,0,4,0,4,0,2,1,1,1,1,1,0,1,1,1,1,1,1,1,0,1,2,2,3,0,3,0,3,2,1,1,3,1,1,2,1,1,1,1,1,1,1,1,0,1,1,2,0]`.
[Answer]
# [Python 3](https://docs.python.org/3/), 697 bytes
```
def f(s):
l=0;c=0;d={'0':(1,1),'1':(3,0),'2':(1,2),'3':(0,2),'4':(3,0),'5':(2,1),'6':(0,1),'7':(2,0),'8':(0,2),'9':(0,1),'A':(3,0),'B':(1,2),'C':(0,1),'D':(1,1),'E':(4,0),'F':(3,0),'G':(2,1),'H':(3,0),'J':(1,1),'K':(3,0),'L':(2,0),'M':(4,0),'N':(3,0),'O':(0,1),'P':(1,1),'Q':(0,2),'R':(2,1),'S':(0,1),'T':(2,0),'U':(0,1),'V':(2,0),'W':(4,0),'X':(4,0),'Y':(3,0),'Z':(3,0),'a':(0,2),'b':(1,1),'c':(0,1),'d':(1,1),'e':(1,1),'f':(1,1),'g':(1,2),'h':(1,1),'i':(3,1),'j':(1,2),'k':(3,0),'l':(3,0),'m':(3,2),'n':(2,1),'o':(0,1),'p':(1,1),'q':(1,1),'r':(1,1),'s':(0,1),'t':(1,1),'u':(1,1),'v':(2,0),'w':(4,0),'x':(4,0),'y':(1,1),'z':(3,0)};
for i in s:
if i in d:
l+=d[i][0];c+=d[i][1];
return l,c
```
A simple first attempt. I put the table into a dictionary, looped through the string, incremented some counters, and returned a tuple. Input is a string.
[Try it online!](https://tio.run/##PZJtU4JAFIU/w6/YphpgJAdEK3WY3rScoiizrBwr40U2CQghs6b@Oi2bcz4w8@w5995zd4dkmQVxZBSF6/nEl@dKSxRCU2s77HPNb0mTWrKu6ooq6YwMVWNU41qNkcFI41SH22BU4x3b3C1ph2ulu4uOJtwD9B5i8hHcDjboMqrzumN0nCCtB@0UHWfQLGxwjikXcG2kXaL3Cpv2kXGNugHm3UC7hTZExh3oHmkPoAkyXpDrYJ4LzQP5oCneKoBG@eSSXuHOkBaC3jiVboS7xchNMO8dlILmqMug5aAPvMECN/8ELVH3tdrlpy0KfpwSSmhE5uznE6j/f3DLgxBWTHdExyNt3HZWqI9ZT@pleRqRUHWKRUBDjwzS3GuRJKVRJvsyjZI8kxVFKQIq9rqWZZOh3bc6YmgYFdJIupOZWDG3ntaq1ere7/N0f31j81Fsapou2iQmq@8P "Python 3 – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 157 bytes
```
x=>(x=x.Where(n=>n<123&n>47)).Sum(n=>p[n-48]/5)+" "+x.Sum(n=>p[n-48]%5);var p=@"
";
```
[Try it online!](https://tio.run/##ZY7fS4NQFMe7PtyBezgF/gG3WwtF529rsWl7yCgQhHrwIfph4qZsuw2d4VP/ujlmD9aBLxy@nw@ck5TjpMybu4olswefVZu0iD/W6SzJ4sJTyl2Rs6W3cJva9cTardUoS4tUZK7HZoZpXTDPvpIk9ana7LvtMxvbkxfNkWRKqFz/6UeONP2KC7J15xQD5mCIeA4dHQYGCAswBMDAC4Aw10LECwLAgXMYYYwH@HgAcDLc721ajoFOm6jId2mQs1RciDTLqSRNNc1WiMn3yL0fBCGJwsfgdq8QTTN1hdh9aW1ZMnG2frzqHMNSyKTvyO747VRV1Zvv9@X87Hz0@qv@O3mt60YHHYVYfRiST9Klc9p3Lpsf "C# (Visual C# Interactive Compiler) – Try It Online")
] |
[Question]
[
**The challenge**
Create a function which takes an array of numbers and subtract from each element the lowest element in the array that has not yet been subtracted from another.
* After using the lowest value, It can not be used again.
* Numbers in the array are decimal numbers, and not necessarily integers.
**Example:**
```
Input: [6, 4, 7, 8, 9, 2, 1, 4]
Next lowest value: Output:
[6, 4, 7, 8, 9, 2, 1, 4] [6, 4, 7, 8, 9, 2, 1, 4]
^ ^
6-1 = 5
[6, 4, 7, 8, 9, 2, -, 4] [5, 4, 7, 8, 9, 2, 1, 4]
^ ^
4-2 = 2
[6, 4, 7, 8, 9, -, -, 4] [5, 2, 7, 8, 9, 2, 1, 4]
^ ^
7-4 = 3
[6, -, 7, 8, 9, -, -, 4] [5, 2, 3, 8, 9, 2, 1, 4]
^ ^
8-4 = 4
[6, -, 7, 8, 9, -, -, -] [5, 2, 3, 4, 9, 2, 1, 4]
^ ^
9-6 = 3
[-, -, 7, 8, 9, -, -, -] [5, 2, 3, 4, 3, 2, 1, 4]
^ ^
2-7 = -5
[-, -, -, 8, 9, -, -, -] [5, 2, 3, 4, 3,-5, 1, 4]
^ ^
1-8 = -7
[-, -, -, -, 9, -, -, -] [5, 2, 3, 4, 3,-5,-7, 4]
^ ^
4-9 = -5
Final output: [5, 2, 3, 4, 3, -5, -7, -5]
```
**Test Cases**
`Input: [6, 4, 7, 8, 9, 2, 1, 4] => Output: [5, 2, 3, 4, 3, -5, -7, -5]`
`Input: [4, 7, 4, 9, -10, 8, 40] => Output: [14, 3, 0, 2, -18, -1, 0]`
`Input: [0.25, -0.5, 8, 9, -10] => Output: [10.25, 0, 7.75, 1, -19]`
`Input: [3, 4, 9, 1, 1, 1, -5] => Output: [8, 3, 8, 0, -2, -3, -14]`
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes win.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
_Ṣ
```
[Try it online!](https://tio.run/##y0rNyan8/z/@4c5F////jzbTUTDRUTDXUbDQUbDUUTDSUTAEisQCAA "Jelly – Try It Online")
or [Try all test cases](https://tio.run/##y0rNyan8/z/@4c5F/w@3P2pa4w3Ekf//R0eb6SiY6CiY6yhY6ChY6igY6SgYAkVidbiiIcImYGFdQwOwChMDkIyBnpEpUMxAzxSmDSgPkjCGqTeEIV3T2FgA)
```
_ # Subtract from...
Ṣ # The input array sorted
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
tS-
```
[Try it online!](https://tio.run/##y00syfn/vyRY9///aDMdBRMdBXMdBQsdBUsdBSMdBUOgSCwA "MATL – Try It Online")
```
(implicit input as an array)
t # duplicate
S # sort
- # element-wise subtract
(implicit output)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
Ṡz-O
```
[Try it online!](https://tio.run/##yygtzv7//@HOBVW6/v///4820THXMdGx1NE1NNCx0DExiAUA "Husk – Try It Online")
**Explanation**
```
-- input, e.g. [6,4,7,8,9,2,1,4]
O -- sort [1,2,4,4,6,7,8,9]
Ṡz- -- element wise difference to input: [6-1,4-2,7-4,8-4,9-6,2-7,1-8,4-9]
-- return result [5,2,3,4,3,-5,-7,-5]
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~93~~ ~~80~~ 68 bytes
```
[H|T]/[A|B]/[X|Y]:-X is H-A,(T=[],Y=T;T/B/Y).
X*Y:-msort(X,S),X/S/Y.
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P9qjJiRWP9qxxglIRtRExlrpRihkFit46DrqaITYRsfqRNqGWIfoO@lHaupxRWhFWunmFucXlWhE6ARr6kToB@tH6gFNMdAzMtVR0DXQA5IWOgqWQLahQaxWhB4A "Prolog (SWI) – Try It Online")
[Answer]
# Ruby, 32 chars
```
->a{a.zip(a.sort).map{|x,y|x-y}}
```
[Answer]
# JavaScript (ES6), 44 bytes
```
a=>[...a].map(x=>x-a.sort((a,b)=>b-a).pop())
```
[Try it online!](https://tio.run/##Zc9LDoMgEAbgfU/BEhJmBB9VF3oR4wKtNm2sGDWNt7cwxk1NCGQG@Ph5m69Z2vk1rTDaR7f3xW6KskJEU@PHTHwryg0MLnZeOTeyEUXZgBE42YkLsbd2XOzQ4WCfvOfVXbJYslSyTLJcslAy7Tq1ECwIWJVQJ6IzbgZXQ@rX@vbnHEhMCGhFXqxORx/3FXGgMz@58qIoDP0TCpMzkLM8cijHtlNSTBNKCjq/INGZQ5/D5fUGIRklyYgBn8b/S8f1/gM "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // given the input array a[]
[...a] // create a copy of a[]
.map(x => // for each integer x in the copy:
x - // update x by ...
a.sort((a, b) => // sorting the original array in descending order
b - a // (we only need to sort it once, but it's shorter to do it here)
).pop() // taking the element at the top of a[] and subtracting it from x
) // end of map()
```
[Answer]
# Java 10, 83 bytes
```
a->{var b=a.clone();java.util.Arrays.sort(b);for(int i=0;i<a.length;a[i]-=b[i++]);}
```
Modifies the input-array instead of returning a new one to save bytes.
[Try it online.](https://tio.run/##dZBfa8IwFMXf/RT3McU2VKf7Q9bBPsB88VF8uG2ji4uJJNcOkX72LqYWBiqEQC7n5Hfu2WGD2a7@6SqN3sMXKnMeAShD0m2wkrC4PAEaq2qoWG2PpZarNWAiwrwdhcsTkqpgAQYK6DD7ODfooCyQV9oayRKxCxB@JKX5p3N48txbR6xMxMY6FlCgilyod@Rami19C1ypdVaUKzUerxPRduKCOQRywFxpMc8@pGVLcspsY6Q@KklPzMhfGMKen1OYpfCSwmsKbylMU5iESRtXuKfvxbMoziZ59M3yx/qcT@dBmfP5gAiux/Kn4e/JcLJ5e9Nn3DCa/5Xeb2h4xfD6/fLkSe65PRI/hCJIG3ZTN9m@pGC6YtruDw)
**Explanation:**
```
a->{ // Method with double-array parameter and no return-type
var b=a.clone(); // Create a copy of the input-array
java.util.Arrays.sort(b); // Sort this copy
for(int i=0;i<a.length; // Loop over the indices
a[i]-= // Subtract from the `i`'th item in the input-array:
b[i++]);} // The `i`'th item of the sorted array
```
[Answer]
# [R](https://www.r-project.org/), 18 bytes
```
(x=scan())-sort(x)
```
[Try it online!](https://tio.run/##K/r/X6PCtjg5MU9DU1O3OL@oRKNC87@ZgomCuYKFgqWCkYKhgsl/AA "R – Try It Online")
Does what it says :)
[Answer]
# Python 3, ~~42~~ 40 bytes
~~`lambda a:[b-c for b,c in zip(a,sorted(a))]`~~
```
lambda a:[a.pop(0)-b for b in sorted(a)]
```
[Answer]
# [Haskell](https://www.haskell.org/), 34 bytes
```
import Data.List
zipWith(-)<*>sort
```
[Try it online!](https://tio.run/##y0gszk7NyfmfmVuQX1Si4JJYkqjnk1lcwpVmG/O/KrMgPLMkQ0NX00bLrhgo/z83MTNPwVahoCgzr0RBRSFNIdpMR8FER8FcR8FCR8FSR8FIR8EQKBL7/19yWk5ievF/3eSCAgA "Haskell – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~8~~ ~~6~~ 4 bytes
```
í-Uñ
```
[Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=7S1V8Q&input=WzAuMjUsIC0wLjUsIDgsIDksIC0xMF0)
---
## Explanation
```
:Implicit input of array U
c :Flatten (simply creates a 2nd copy of the array because JavaScript's sort mutates the original array)
í :Interleave
Un :U sorted
- :Reduce each pair by subtraction
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
{-
```
[Try it online](https://tio.run/##MzBNTDJM/f@/Wvf//2gzHRMdcx0LHUsdIx1DHZNYAA) or [verify all test cases](https://tio.run/##MzBNTDJM/X9u66GVh9b9r9b9H3to9//oaDMdEx1zHQsdSx0jHUMdk1gdhWiQgAlQQNfQAChhYgASM9AzMtXRNdAzBSsFyoAEjcHKDMFQ1zQ2FgA).
**Explanation:**
```
{ # Sort the input-array
- # Subtract all values in this sorted array from the input-array
```
[Answer]
# Common Lisp, 46 bytes
```
(lambda(x)(mapcar #'- x(sort(copy-seq x)#'<)))
```
[Try it online!](https://tio.run/##Fcg7DoAgEAXAq7yEgt2CQkP8JF5mRQsSEAQLPD3GKccFX3OnXPz1gDoFifsh1JiiZCcFShs0qqk85FJ@TT1vNFZ6Y@auaYLFjAUrRgywf34)
[Answer]
# [J](http://jsoftware.com/), 4 bytes
```
-/:~
```
[Try it online!](https://tio.run/##NctBCsIwEEbhfU7xcBMEnU5qUttAz5JFMRQ3LrrWq6cxEGb3vX/eJR@roES03If4K1dzEWxexXLjG8mHMa9t/5CZ8DyZWRhx@M5/9BWT0xq9dlcZA0kltJdae3i0uWuXQjkB "J – Try It Online")
## Explanation:
From the argument subtract `-` the sorted `/:~` argument
[Answer]
# [Coconut](http://coconut-lang.org/), 23 bytes
```
a->map((-),a,sorted(a))
```
[Try it online!](https://tio.run/##PY7LDoMgEEX3fsUsuoBkIGChj4X@iHVBLCYmVYzgrv9OEUOT2cw5dzJ3cINb9hDH5hUNa2ezEsIoGvRuC/ZNDKUxWB88NNDdEBTCHeGB8ESoEWQiPUJ3YpUxkyInlDiM4LVOTHBdzpI/xLXkZRmm@6o6n31bSFUu5DP5AJzDSP9o3aYl5DU19/ts4w8 "Coconut – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 15 bytes
```
{@^a [[email protected]](/cdn-cgi/l/email-protection)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPu/2iEuUSFK1yFRrzi/qKT2f3EiSEIj2kxHwURHwVxHwUJHwVJHwUhHwRAoEqtpzQVTAZE2AUvrGhqAVZoYxGr@BwA "Perl 6 – Try It Online")
Anonymous function that takes one list and returns a list.
[Answer]
# [Julia 0.6](http://julialang.org/), 12 bytes
```
A->A-sort(A)
```
[Try it online!](https://tio.run/##NY1BCsMgFET3nmKWCXyDJpq0ixY8h7gopAVDMOU3Pb8VizCrN2@Y7bvHx5z5lp28O/k5@Oxcn18HwyEmeD8TDGEhXAhXwkjQZAJB@D82FUutqmFUrdQw2gLVYNuuCLWZ2kK3SBsCxJtjOvfUcbnvxTOt@Qc "Julia 0.6 – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 8 bytes
```
{x-x@<x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6qu0K1wsKmo5eJKt0pzSMiy50pXijbTUTDRUTDXUbDQUbDUUTDSUTAEisQqgeQgEiZgCV1DA7AaEwOInIGekSlQ1EDPFKYVqAIiZQzTYwhDuqaxSgAxlxpa)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 bytes
```
íNc n
®r-
```
[Try it online!](https://tio.run/##y0osKPn///Bav2SFPK5D64p0//@PNtNRMNFRMNdRsNBRsNRRMNJRMASKxAIA "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)
```
ÿ◙┘¿N
```
[Run and debug it](https://staxlang.xyz/#p=980ad9a84e&i=[6,+4,+7,+8,+9,+2,+1,+4]%0A[4,+7,+4,+9,+-10,+8,+40]%0A[0.25,+-0.5,+8,+9,+-10]+%0A[3,+4,+9,+1,+1,+1,+-5]&a=1&m=2)
To show how it works, here's the unpacked, commented version.
```
m for each element execute, then pop and print:
xo sort the original input
i@ index into array using iteration index
- subtract
```
[Run this one](https://staxlang.xyz/#c=m+++%09for+each+element+execute,+then+pop+and+print%3A%0A++xo%09sort+the+original+input%0A++i%40%09index+into+array+using+iteration+index%0A++-+%09subtract&i=[6,+4,+7,+8,+9,+2,+1,+4]%0A[4,+7,+4,+9,+-10,+8,+40]%0A[0.25,+-0.5,+8,+9,+-10]+%0A[3,+4,+9,+1,+1,+1,+-5]&a=1&m=2)
[Answer]
# SmileBASIC, 49 bytes
```
DEF R A
DIM B[0]COPY B,A
SORT B
ARYOP 1,A,A,B
END
```
The input array is modified in place.
`ARYOP` does operations on entire arrays at once. In this case it subtracts `B` from `A` and stores the result in `A`.
[Answer]
# [PHP](https://php.net/), 86 bytes
```
function f($a){$b=$a;sort($b);return array_map(function($x,$y){return $y-$x;},$b,$a);}
```
[Try it online!](https://tio.run/##hc3dCoJAEAXg@55ikAF3YRQ17YetfJCKWMtQSF02BUV8dlssoYsgGOZiON8clalxFyuz7015rfOqhDtDyXtM9ijFs9I1w4QLndaNLkFqLbtLIRWb4wxbwo73nwB2DrZiIEzIfBHDmF6zCvJCPapbymyyyfw/rghCgjXBhmBLEBD45nLmHFywTqUlFj/Z24STcXxv4qH3l3luEBngudFcaPBftZyb/Hmc6BvFh/EF "PHP – Try It Online")
[Answer]
# [Tcl](http://tcl.tk/), 49 bytes
```
proc S L {lmap n $L m [lsort -r $L] {expr $n-$m}}
```
[Try it online!](https://tio.run/##HY07CsMwEER7nWIwbmUkR8rvDO5cmhTBpJNsISsQWPbsylpss/PmwZQ11JryvmLGBArxnbChnxCxhGPPBTpLfIE@vyTfpvvIXJsnvqIrHG6444ERFo4VndlJ1tYId0aQGUYPbQbfRCmEXZpk22nPikHpWw50Mv7EMp@rHdc/ "Tcl – Try It Online")
[Answer]
# [Factor](https://factorcode.org), 23 bytes
```
[ dup natural-sort v- ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY4xDoJAEEV7T_EvsAQQFPUAxsbGWBmLDS5KhAWXWRJDOInNNngFz-JtXECdKebnvfxkHs-Ex1Qo8zb73Wa7XuIqlBQZck4Xpxa9q1AqQXQvVSoJlbhpIWNRoSoUpfKM1aSZwE6DGQLMEWEBH57N7Zf3NLCUea61gfsXruOHYK4TDqVe_8x0KHjDstDittOUsOh1wEmXkJy04hnrf0DNcBxtl_MSzpiNGe8H)
] |
[Question]
[
When given a a list of values and a positive integer `n`, your code should output the cartesian product of the list with itself `n` times.
For example, in pseudocode your function could be similar to:
```
for x1 in list:
for x2 in list:
for x3 in list:
...
for xn in list:
print x1, x2, x3, ... , xn
```
Example:
```
repeated_cart([1,2,3], 3)
1 1 1
1 1 2
1 1 3
1 2 1
1 2 2
1 2 3
1 3 1
1 3 2
1 3 3
2 1 1
2 1 2
2 1 3
2 2 1
2 2 2
2 2 3
2 3 1
2 3 2
2 3 3
3 1 1
3 1 2
3 1 3
3 2 1
3 2 2
3 2 3
3 3 1
3 3 2
3 3 3
```
Built in functions (or functions from imported libraries) that compute the Cartesian product or Cartesian power are not allowed due to the resulting code being somewhat boring.
Inputs and outputs should be delimited but can be taken in any reasonable method. The order the output is given does not matter but duplicates are not allowed.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins
[Answer]
# [Haskell](https://www.haskell.org/), 21 bytes
```
l#n=mapM(\_->l)[1..n]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0c5zzY3scBXIyZe1y5HM9pQTy8v9n9uYmaegq0CSEKhoCgzr0RBRSHaUMdIxzhW2fg/AA "Haskell – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 41 bytes
```
function(l,n)unique(t(combn(rep(l,n),n)))
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNHJ0@zNC@zsDRVo0QjOT83KU@jKLUALAxEmpr/0zQMrYx1jDX/AwA "R – Try It Online")
`combn` is definitely not a cartesian product built-in, as it computes all `n`-combinations of its input.
# [R](https://www.r-project.org/), 40 bytes
```
function(l,n)expand.grid(rep(list(l),n))
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNHJ08ztaIgMS9FL70oM0WjKLVAIyezuEQjRxMoo/k/TcPQyljHWPM/AA "R – Try It Online")
`expand.grid` is probably a cartesian product built-in.
[Answer]
# [Common Lisp](http://www.clisp.org/), 146 bytes
```
(defun f(l n)(if(< n 2)(loop for x in l collect(list x))(loop for a in l nconc(loop for b in(f l(1- n))collect(cons a b)))))(princ(f(read)(read)))
```
[Try it online!](https://tio.run/##TY6xCoRADER/ZcqkuEJt72c0bmAhJMvqgX@vETnupkgxvBdGrG7tPGkt@nEoGZypKr3hGJksokGj40B1GCTMiuyU1o6D/4D5AVzC5dcu2ZLCaHjlY/7qCW1pLHyHWq/pKPUyr/xc5tw0YMTEmC4 "Common Lisp – Try It Online")
ungolfed
```
(defun nloops (lst n)
(if (< n 1)
'(())
(if (< n 2)
(loop for x in lst collect (list x))
(loop for a in lst
nconc (loop for b in (nloops lst (1- n))
collect (cons a b))))))
```
[Answer]
# [Perl 6](https://perl6.org), 16 bytes
```
{[X,] $^a xx$^b}
```
[Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszcWVW6mglpyfkqpg@786OkInVkElLlGhokIlLqn2v15BaYlCWn6RAkiBhoKGoY6RjrGmjoKxguZ/AA "Perl 6 – Try It Online")
## Expnded:
```
{ # bare block lambda with placeholder parameters $a and $b
[X,] #reduce using Cross meta op combined with comma op
$^a xx $^b # list repeat $a, by $b times
}
```
[Answer]
# [K (ngn/k)](https://github.com/ngn/k), 10 bytes
```
{x@+!y##x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqrrCQVuxUlm5ovZ/WrShgpGCsbVx7H8A "K (ngn/k) – Try It Online")
`{` `}` is a function with arguments `x` and `y`
`#x` the length of `x`
`y##x` the length of `x` repeated `y` times
`!y##x` all length-y tuples over 0,1,...,length(x)-1 as a transposed matrix
`+` transpose
`x@` elements of `x` at those indices
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~18~~ 12 bytes
```
{⍺[↑,⍳⍵⍴≢⍺]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/@lHvruhHbRN1HvVuftS79VHvlkedi4BisbX/3R61TcAtzfWobypQgaGCkYKxgomCG5BU@A8A "APL (Dyalog Classic) – Try It Online")
-6 bytes thanks to @ngn !
[Answer]
# [Perl 5](https://www.perl.org/), 33 bytes
```
say for glob(join',',("{$_}")x<>)
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVIhLb9IIT0nP0kjKz8zT11HXUdDqVolvlZJs8LGTvP/f0MdIx1jLuN/@QUlmfl5xf9183L@6/qa6hkYGgAA "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~69~~ 58 bytes
```
f=lambda a,n:n and[v+[i]for v in f(a,n-1)for i in a]or[[]]
```
[Try it online!](https://tio.run/##FcnBCoAgDADQX9kxaR3UW9CXjB0WIgk1RUTo6y2v75W3XVndGPG45TmDgKDuCqKB@kqJY67QISnE5Z/NmglpgnCuRMyj1KTtf7Lo0DN6Mz4 "Python 2 – Try It Online")
Takes a list `a` and an integer `n`; returns a list of lists.
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 72 bytes
```
R-1-R.
L-N-R:-O is N-1,L-O-M,findall([H|T],(member(H,L),member(T,M)),R).
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P0jXUDdIj8tH1083yErXXyGzWMFP11DHR9df11cnLTMvJTEnRyPaoyYkVkcjNzU3KbVIw0PHR1MHyg7R8dXU1AnS1Ptvr6sQbahjpGMcq2usG6SjUF6UWZKqAZIBAA "Prolog (SWI) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 53 bytes
```
f=->l,n{n<2?l:l.flat_map{|i|f[l,n-1].map{|j|[i,*j]}}}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y5HJ686z8bIPscqRy8tJ7EkPjexoLomsyYtGiijaxirB@Zn1URn6mhlxdbW1v4vUEiLjjbUMdIxjgWi/wA "Ruby – Try It Online")
Recursive approach, not so short, but guaranteed to be free of any built-ins.
It's tempting to use permutation methods, but this probably doesn't count, and the docs actually state no guarantees of the order correctness, although seems to work in practice:
# [Ruby](https://www.ruby-lang.org/), 35 bytes
```
->l,n{[*l.repeated_permutation(n)]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5HJ686WitHryi1IDWxJDUlviC1KLe0JLEkMz9PI08ztvZ/gUJadLShjpGOcSwQ/QcA "Ruby – Try It Online")
[Answer]
# Racket, 92 bytes
```
(define(f l n)(if(> n 0)(apply append(map(λ(r)(map(λ(e)(cons e r))l))(f l(- n 1))))'(())))
```
[Try It Online](https://tio.run/##NcsxDsIwDAXQvaf4KkO/ByQKO3eJ2gRFBDdyC1KXXow7cKWQImF92f7DMzfc/VIOyekN9itN4ehDVM@ABBXGwCsUJ6HLOa2o2@vIh8v8vGny/7xwmHSGh4kkkd3zWGUvdTpyP6Xha4ojdgQOT7MV2aIuAe02b9oKquvY44yL1FTyBQ)
## Ungolfed
```
(define (f l n)
(if (> n 0)
(apply append
(map
(λ (r)
(map (λ (e) (cons e r)) l)
)
(f l (- n 1))
)
)
'(())
)
)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ ~~9~~ 7 bytes
```
³;þẎƊ’¡
```
[Try it online!](https://tio.run/##ASEA3v9qZWxsef//wrM7w77huo7GiuKAmcKh//9bMSwyLDNd/zM "Jelly – Try It Online")
## Explanation
```
³;þẎƊ’¡
³;þẎ **Implements** the cartesian product of a value with the input
Ɗ Groups those together
’¡ Repeat (n-1) times
```
[Answer]
# Pure [Bash](https://www.gnu.org/software/bash/) (no external utilities), 57
```
printf -vn %0$1d
a=${n//0/{$2\}}
eval echo ${a//\}{/\},{}
```
Input is given as command-line parameters; 1st is `n`, 2nd is a comma-separated list.
```
printf -vn %0$1d ;# Create a string of n "0"s in the variable v
a=${n//0/{$2\}} ;# Replace each "0" with "{a,b,...m}"
eval echo ${a//\}{/\},{} ;# Replace each "}{" with "},{" and evaluate the resulting brace expansion
```
[Try it online!](https://tio.run/##S0oszvhfnFqioKurYKxgqGOkY/y/oCgzryRNQbcsT0HVQMUwhSvRVqU6T1/fQL9axSimtpYrtSwxRyE1OSNfQaU6UV8/prYaiHWqa///BwA "Bash – Try It Online")
[Answer]
# Java 10, 19 + 135 = 154 bytes
```
import java.util.*;
```
```
List<List>f(Set l,int n){var o=new Stack();if(n<1)o.add(new Stack());else for(var t:l)for(var i:f(l,n-1)){i.add(t);o.add(i);}return o;}
```
[Try It Online](https://tio.run/##TZDNToQwFEbX8BR32RqmCboDZhJ3muiKpXFRoTBlSkvaC2ZCeHa8MJoxafp/T8/XTk7y0NWXVfeD8wgdrcWI2oiHPI6H8cvoCiojQ4B3qS3M8fqmAxZbd2pYqRBMoi2C5fMkPbijVd9QoqwujOe6YbZIuROyrtm/A54rExQ0zrOtCDPD/@Y6a5hJ7CHlfNZ7HfL8BtA8X7zC0Vtw@bLGcfTrF1AiDZPTNfRkyUr02rYfnyB9GzhJR9HGtmMf4AibyD3niwxnilGc2H3v2Xt5DUKGLeYu/mpRtcoTck4TeEzgaaEUxCVv2MUNZDt5@ybGBSWn1@gev70fldeAqhduRDGQHRrLzE5YYmrL@gM)
## Ungolfed
```
List<List> f(Set l, int n) {
var o = new Stack();
if (n < 1)
o.add(new Stack());
else
for (var t : l)
for (var i : f(l, n - 1)) {
i.add(t);
o.add(i);
}
return o;
}
```
## Acknowledgments
* port to Java 10 thanks to Kevin Cruijssen
[Answer]
# Oracle SQL, 177 bytes
Create a collection type (31 bytes):
```
CREATE TYPE t IS TABLE OF INT;
```
Then use the query (146 bytes):
```
WITH n(a,b,c)AS(SELECT a,b,t()FROM i UNION ALL SELECT a,b-1,c MULTISET UNION t(COLUMN_VALUE)FROM n,TABLE(n.a)WHERE b>=0)SELECT c FROM n WHERE b=0
```
Assuming that the input parameters are in the table `i` with columns `a` and `b`:
```
CREATE TABLE i (a t,b INT) NESTED TABLE a STORE AS t_a;
INSERT INTO i VALUES ( t(1,2,3), 3 );
```
[SQL Fiddle](http://sqlfiddle.com/#!4/e06757/13)
**[Results](http://sqlfiddle.com/#!4/e06757/13/0)**:
```
| C |
|-------|
| 1,1,1 |
| 1,1,2 |
| 1,1,3 |
| 1,2,1 |
| 1,2,2 |
| 1,2,3 |
| 1,3,1 |
| 1,3,2 |
| 1,3,3 |
| 2,1,1 |
| 2,1,2 |
| 2,1,3 |
| 2,2,1 |
| 2,2,2 |
| 2,2,3 |
| 2,3,1 |
| 2,3,2 |
| 2,3,3 |
| 3,1,1 |
| 3,1,2 |
| 3,1,3 |
| 3,2,1 |
| 3,2,2 |
| 3,2,3 |
| 3,3,1 |
| 3,3,2 |
| 3,3,3 |
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ẋœ!ṛQ
```
[Try it online!](https://tio.run/##ASgA1/9qZWxsef//4bqLxZMh4bmbUf/Dp@G5osKl4oG84bmX//9bMSwyXf81 "Jelly – Try It Online")
Completely different method to [Adalynn](https://codegolf.stackexchange.com/users/55550/adalynn)'s [existing answer](https://codegolf.stackexchange.com/questions/165664/cartesian-product-of-a-list-with-itself-n-times/165666#165666), plus two bytes shorter, so I thought I'd post a separate answer.
The Footer in the TIO link simply runs the above link then checks to see if the result is the same as the Cartesian power builtin. Remove it to see the full output
Same as the old version is length, but more tacit.
## How it works
```
ẋœ!ṛQ - Main link. Takes a list l on the left and n on the right
ẋ - Repeat l n times; Call this m
ṛ - Right; Yield the right argument n
œ! - Yield all permutations of m of length n
Q - Remove duplicates
```
The previous answer, `ẋ⁹œ!Q` used a `2-0, 2, 1` chain, where the `⁹` was necessary to prevent the `œ!` chaining to the `ẋ`. In this version, we have a `2, 2, 2, 1` chain. As it is at the start of the chain, the special `2,2,2` pattern is matched, meaning we execute the first three dyads, then deduplicate whatever that results in.
For three dyads `x (f g h) y`, we calculate `(x f y) g (x h y)` with this `2,2,2` pattern. `f` here is `ẋ`, meaning we repeat the list in `x` `y` times. `h` is `ṛ`, which takes two arguments and returns the right one `y`. Therefore, we're passing the repeated list to `œ!` on the left and `y` on the right, thus getting the permutations of length `y`.
[Answer]
# [J](http://jsoftware.com/), ~~17~~ 10 bytes
-7 bytes thanks to Jonah!
```
>@,@{@(#<)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/7Rx0HKodNJRtNP9rcilwpSZn5CsYK6QpGCoYAWkI3wTIV09MKlb/DwA "J – Try It Online")
## Original soluton:
# [J](http://jsoftware.com/), 17 bytes
```
]{~(##)#:#@]i.@^[
```
## How it works?
I enumerate all the `n`-digit numbers in a number system with base the length of the list.
```
i. - creates a list from zero to (not including)
#@] - the length of the list
@^ - to the power of
[ - n (left argument)
(##) - creates a list of n times the length of the list (for the bases)
#: - converts all the numbers into lists of digits in the new base
]{~ - use the digits as indices into the list
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Y6vrNJSVNZWtlB1iM/Uc4qL/a3IpcKUmZ@QrGCukKRgqGAFpCN8EyFdPTCpW/w8A "J – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 38 bytes
```
@(x,n)x(dec2base(0:n^numel(x)-1,n)-47)
```
Anonymous function that takes a row vector of values and an integer.
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999Bo0InT7NCIyU12SgpsThVw8AqLy6vNDc1R6NCU9cQKKdrYq75P00j2tBAR8EIiI2B2MQgFsjQ/A8A "Octave – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 61 bytes
```
N=$1
shift
IFS=,
printf echo\\t%${N}s ""|sed "s/ /{$*},/g"|sh
```
[Try it online!](https://tio.run/##S0oszvj/389WxZCrOCMzrYTL0y3YVoeroCgzryRNITU5Iz8mpkRVpdqvtlhBSammODVFQalYX0G/WkWrVkc/HSgC1P7f@L/Rf8P/BgA "Bash – Try It Online") I found repeating strings and joining lists with commas surprisingly hard to do in bash.
[Answer]
# [Javascript (Node)](https://nodejs.org/en/), 75 bytes
```
c=(m,n,a,i)=>a.length-n?m.map((_,j)=>c(m,n,[...a,m[j]],i+1)):console.log(a)
```
Recursive function which outputs the list to the console. Where `a` is an empty array and `i` is 0 (not sure if this still qualifies):
```
c([1,2,3], 3, [], 0);
```
[Try it online!](https://tio.run/##HcpBCsIwEAXQ68zg72DtTqkeJAQZYqgJyaS0xetHcft4WT@6hy2tx2DtFXsPM1UYFInnu0qJthzvwR5Vqq5ET@Sfh/9xIqKoLnuPdBqZr6HZ3kqU0hZS7oHciAsmjwnO48y3/gU)
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 52 bytes
```
c=>g=(n,...l)=>n?c.map(w=>g(n-1,...l,w)):print(...l)
```
[Try it online!](https://tio.run/##HcpLCoAgEADQ68yACeYuGDtItBD7YJ9JVIpOb@H28TZ72@SiD7lJwU9zPC/e57csVByZlYCFlPJAMtw7edoAz8/AjaouHsQuRM8ZaisLDEq0Qo8IGssH "JavaScript (SpiderMonkey) – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 26 bytes
```
q~(_"m*:e_"*\'_*@\~W$~:p];
```
[Try it online!](https://tio.run/##S85KzP3/v7BOI14pV8sqNV5JK0Y9Xsshpi5cpc6qINb6//9oQwUjBeNYBWMA "CJam – Try It Online")
If only CJam had one character commands for cartesian product and flattening.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 5 bytes
```
.nM**
```
[Try it online!](https://tio.run/##K6gsyfj/Xy/PV0vr//9oQx0FIx0F41gA "Pyth – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
ẋf⁰↔U
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwi4bqLZuKBsOKGlFUiLCIiLCJbMSwyLDNdXG4zIl0=)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 46 bytes
```
(l,n)->matrix(#l^n,n,i,j,l[i--\#l^(n-j)%#l+1])
```
[Try it online!](https://tio.run/##DcjBCoAgDADQXxlIsNF2iM71I1ZggTGxIeKhv7fe8ZVQVe7SIyzQMbORrE9oVV90@TA2Vk6cvYpsf6BJosHlcdqpl6rWMKIPDCfDtTPMRP0D "Pari/GP – Try It Online")
] |
[Question]
[
Given a non-empty list of integers, output every possible partitioning of the list where each partition is a non-empty sublist.
So for the list `[1, 2, 3, 4]` the result is:
```
[[1, 2, 3, 4]]
[[1, 2, 3], [4]]
[[1, 2], [3, 4]]
[[1, 2], [3], [4]]
[[1], [2, 3, 4]]
[[1], [2, 3], [4]]
[[1], [2], [3, 4]]
[[1], [2], [3], [4]]
```
The order of the lists in the output does not matter, so `[[1, 2, 3, 4]]` could be first, last, or wherever. The order of the elements must be preserved.
This is code-golf, so shortest answer wins.
---
Related: [Partition a list!](https://codegolf.stackexchange.com/questions/76355/partition-a-list)
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~27~~ 19 bytes
Byte count assumes ISO 8859-1 encoding.
```
+1%`,
;$'¶$`];[
;
,
```
[Try it online!](https://tio.run/nexus/retina#@69tqJqgw2Wton5om0pCrHU0lzWXzv//0YY6RjrGOiaxAA "Retina – TIO Nexus")
### Explanation
Of course this computes all partitions using string processing. The basic idea is that we can generate all partitions by deciding for each `,` individually whether or not we want to split the list there. This kind of stuff can be done in Retina by matching each `,` in turn and using a replacement which gives both possible outputs.
The input acts as the base case: the partition where all elements are still in a single list.
```
+1%`,
;$'¶$`];[
```
Now we repeatedly (`+`) match the first (`1`) comma (`,`), on each line (`%`) (treating that line as a separate string, which is relevant for `$'` and ``$1 ` in the substitution).
That comma gets replaced with:
```
; A semicolon. This is just a stand-in for the comma, so we know we've already
processed it and it won't be substituted again by the next iteration.
$' Everything after the match. This completes the first (unchanged) version of
the current line.
¶ A linefeed. Since the next iteration will scan for all lines again, this doubles
the number of strings we're working with.
$` Everything before the match. This completes the second (split) version of
the current line.
];[ A semicolon around which we split the list.
```
Remember that everything in front of the match and after the match remains in the string anyway, so the full result is actually `$`;$'¶$`];[$'` which explains why we insert the suffix and prefix in that order.
This loop stops once all commas are gone.
```
;
,
```
Finally, replace the semicolons with commas again to match the input format.
[Answer]
# Pure Bash, 28
```
eval echo [${1//:/{:,]:[\}}]
```
Here, lists are colon-separated, and contained in square brackets. For example in the question, the input list would be `1:2:3:4` and the output is:
```
[1:2:3:4] [1:2:3]:[4] [1:2]:[3:4] [1:2]:[3]:[4] [1]:[2:3:4] [1]:[2:3]:[4] [1]:[2]:[3:4] [1]:[2]:[3]:[4]
```
[Try it online](https://tio.run/nexus/bash#K0ktLklOLE61VTK0MrIytjJR4ipOLVHQ1VVQUimByin9Ty1LzFFITc7IV4hWqTbU17fSr7bSibWKjqmtjf3/HwA).
* `${1//:/REPLACEMENT}` replaces the colons in `$1` with `{:,]:[\}`
* This generates a brace expansion like `[1{:,]:[}2{:,]:[}3{:,]:[}4]`
* The eval (and careful `\` escapes) causes the brace expansion to happen last and give the desired result.
---
If it is necessary to exactly match the given `[[ , , ...]]` format, then we can do this instead:
# Pure Bash, 47
```
eval printf '%s\\n' ${1//, /{\\,\\ ,]\\,\\ [\}}
```
[Try it online](https://tio.run/nexus/bash#K0ktLklOLE61VYqONtRRMNJRMNZRMImNVeIqTi1R0NVVUFIpgSpR@p9alpijUFCUmVeSpqCuWhwTk6euoFJtqK@vo6BfHROjExOjoBMLoaNjamv//wcA).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 2 bytes
```
./
```
With input `[1, 2, 3, 4]` (for instance).
**Explanation**: `./` is the partition operator. It returns all divisions of the input list into disjoint sub-lists. The input is implicitly fed to the program.
[Test it online!](http://pyth.herokuapp.com/?code=.%2F&input=%5B1%2C%202%2C%203%2C%204%5D&debug=0)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
Œæʒ˜Q
```
[Try it online!](https://tio.run/nexus/05ab1e#@3900uFlpyadnhP4/3@0oY6CkY6CsY6CSSwA "05AB1E – TIO Nexus")
```
Œæʒ˜Q Main link. Argument l
Œ Get all sublists of l
æ Powerset of those lists
ʒ˜Q Filter: Keep the lists that when flattened equal the input
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~82~~ ~~72~~ 66 bytes
```
f=lambda l:[k+[l[i:]]for i in range(len(l))for k in f(l[:i])]or[l]
```
[Try it online!](https://tio.run/nexus/python3#NYxLDsIwDAXX7SmirmKRTflsInESy4tUJMiqcasQev1ACmznzbyarhIe0y0Y8TgfUJA9UVqyYcNqctB7tBLVCkCjc6PJCnomoCWjUG28xGdpk8ULOYOjO7qTOxP4vlsza7ED6/oqfnC7Cn3Xqu37tpOP@VM3@EdQ3w "Python 3 – TIO Nexus")
*-5 bytes thanks to @JonathanAllan*
[Answer]
# [Haskell](https://www.haskell.org/), ~~59~~ ~~55~~ 49 bytes
```
p[x]=[[[x]]]
p(x:r)=do a:b<-p r;[(x:a):b,[x]:a:b]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/vyC6ItY2OhpIxsZyFWhUWBVp2qbkKyRaJdnoFigUWUcDhRI1rZJ0gCqsgKKx/3MTM/MUbBVyEwt8FQqKMvNKFFQUChSiDXWMdIx1TGL/AwA "Haskell – Try It Online")
Recursive solution. Usage example: `p [1,2,3]` returns `[[[1,2,3]],[[1,2],[3]],[[1],[2,3]],[[1],[2],[3]]]`.
-6 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)!
[Answer]
# [J](http://jsoftware.com/), 42 bytes
```
<@(</."1)~<:@#_&(][:;<@(,~"{~0 1+>./)"1)0:
```
Generates all sublist partitons by creating the keys for partition sublists of length 1 and iterating to the length of the input list. Each partition sublist is then formed by selecting from the keys.
For example, here is the process of creating the keys for a length 4 list.

[Try it online!](https://tio.run/nexus/j#@5@mYGulYOOgYaOvp2SoWWdj5aAcr6YRG21lDRTUqVOqrjNQMNS209PXBEobWHFxpSZn5CukKRgqGCkYK5j8/w8A "J – TIO Nexus")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes
```
~c
```
[Try it online!](https://tio.run/nexus/brachylog2#e9S24VFT48NdnY@6lv6vS/7/P9pQR8FIR8FYR8EkFgA "Brachylog – TIO Nexus")
Function submission that produces output via acting as a generator. (The TIO link contains extra code to make this into a full program, for testing purposes.)
Incidentally, although not technically a builtin, this is so commonly used in Brachylog that a) it probably deserves a single-byte representation, and b) the `c` builtin can take a parameter to make assertions about its *input* (whereas with most builtins, a parameter talks about how to produce the *output*).
## Explanation
```
~c
~ Find a value with the following properties:
c concatenating its elements produces {the input}
```
[Answer]
# [J](http://jsoftware.com/), ~~26~~ 24 bytes
```
<@(<;.1)~2#:@(+i.)@^<:@#
```
[Try it online!](https://tio.run/nexus/j#@5@mYGulYOOgYWOtZ6hZZ6Rs5aChnamn6RBnY@WgzMWVmpyRr5CmYKhgpGCsYPL/PwA "J – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
ŒṖ
```
[Try it online!](https://tio.run/nexus/jelly#@3900sOd0/4fbgfRMx41rYlUeLhj@6OGOQrOiTk5CjmZedkKiXkpCokFBTmVCgGVJRn5eQpp@UW5iSUlmXnpev//RxvqKBjpKBjrKJjEAgA "Jelly – TIO Nexus")
[Answer]
# APL, 26 bytes
```
{⊂∘⍵¨1,¨↓⍉(X⍴2)⊤⍳2*X←⍴1↓⍵}
```
Test:
```
{⊂∘⍵¨1,¨↓⍉(X⍴2)⊤⍳2*X←⍴1↓⍵} 1 2 3 4
┌─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐
│┌─────┬─┐│┌───┬───┐│┌───┬─┬─┐│┌─┬─────┐│┌─┬───┬─┐│┌─┬─┬───┐│┌─┬─┬─┬─┐│┌───────┐│
││1 2 3│4│││1 2│3 4│││1 2│3│4│││1│2 3 4│││1│2 3│4│││1│2│3 4│││1│2│3│4│││1 2 3 4││
│└─────┴─┘│└───┴───┘│└───┴─┴─┘│└─┴─────┘│└─┴───┴─┘│└─┴─┴───┘│└─┴─┴─┴─┘│└───────┘│
└─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘
```
Explanation:
* `X←⍴1↓⍵`: `X` is the length of `⍵` (the input list) with its first element dropped
* `⍳2*X`: the numbers [1..2^X]
* `(X⍴2)⊤`: base-2 representation of those numbers, with `X` positions (i.e. `X` itself will wrap around to `0`).
* `↓⍉`: rotate the matrix and split it along the lines (`⊤` gives as a result a matrix with the numbers along the columns), giving an array of bit vectors
* `1,¨`: prepend a 1 to each bit vector.
* `⊂∘⍵¨`: for each bit vector, split `⍵` at each 1.
[Answer]
# [Haskell](https://www.haskell.org/), 45 bytes
```
foldr(\h t->map([h]:)t++[(h:y):z|y:z<-t])[[]]
```
[Try it online!](https://tio.run/##DcoxEoIwEAXQq/yCIhmSQrHKiDfwBMsWGTCEMUAG0sB4dldf/aLf36@UJLSdhDUNm@oiin3MPiuK7HSpa1LRHdqdn8Odd1tYEzHL7KcFLf7xibxNS0GFALoYXA0agxvLtw/Jj7vYPucf "Haskell – Try It Online")
I found this solution a while back in [thinking about a Haskell tip](https://codegolf.stackexchange.com/questions/19255/tips-for-golfing-in-haskell#comment239515_98446).
[Answer]
# [Python](https://docs.python.org/), 90 bytes
[outgolfed by ovs](https://codegolf.stackexchange.com/a/121405/53748) (making something I thought I'd tried work :p)
```
def f(a):r=[[a]];i=len(a)-1;exec("for s in f(a[:i]):s+=[a[i:]];r+=[s]\ni-=1\n"*i);return r
```
A recursive function which builds up the list of partitions from slices of the input with the tail reached when the slices are of length 1.
**[Try it online!](https://tio.run/nexus/python3#NY3NDoMgEITP@hSEE1Q82J8LhCdZOZgWk02arVnQ9O0t2PY2mXzfzP6Is5jVpC17gCkEh/4ZqRT94OI73pWcXyySQKoYWAzaps7DBGgLzSWmMBL2fhhJnlA7jnllErxXMceUq6vgFoyAwZzNxVzLRtssjJSVRFrWbKU5UN021dq@d0dTyB@66b@k9w8 "Python 3 – TIO Nexus")**
The `exec` saves 4 bytes over a `while` or 3 over a `for` loop (below) since it means only two `\n`s rather than two levels of indentation, allowing the whole function to be on one line (while the order of slicing does not matter).
```
def f(a):
r=[[a]]
for i in range(1,len(a)):
for s in f(a[:i]):s+=[a[i:]];r+=[s]
return r
```
[Answer]
# [Python 3](https://docs.python.org/3/), 67 bytes
```
f=lambda x,n=1:x[n:]and[y+[x[n:]]for y in f(x[:n])]+f(x,n+1)or[[x]]
```
[Try it online!](https://tio.run/nexus/python3#Jco7CoAwDADQWU@R0dIsVadCTxIyVEpB0FSKQzx9/W1veC2HLe5LiqAowXkl8Rwl0WXpM@dS4YJVIA9KXtiwfYRinSmVSJnbW/Qv5BBGhAlhZuP77qirnIOadgM "Python 3 – TIO Nexus")
[Answer]
# Haskell, 59 bytes
```
x#[]=[[[x]]]
x#(a:b)=[(x:a):b,[x]:a:b]
foldr((=<<).(#))[[]]
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~62~~ 57 bytes
```
->l{(0..2**l.size).map{|x|l.chunk{1&x/=2}.map &:last}|[]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nWsNAT89ISytHrzizKlVTLzexoLqmoiZHLzmjNC@72lCtQt/WqBYkrKBmlZNYXFJbEx1b@7/CNi06WstQT88iNparQCG6AqxdpyL2PwA "Ruby – Try It Online")
### How it works:
* The number of partitions is 2^(n-1): I iterate on binary numbers in that range, take the groups of zeros and ones and map them as subsets of the initial list.
* Instead of fiddling with the range, I make it double and discard duplicates at the end. Now I can also discard the first binary digit and make the chunk function shorter.
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 32 bytes
```
f(a:b++c:d)=(a:b):f(c:d)
f a=[a]
```
[Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NI9EqSVs72SpF0xbE1LRK0wBxuNIUEm2jE2P/5yZm5inYKqQpRBvqKBjpKBjrKJjE/gcA "Curry (PAKCS) – Try It Online")
Curry supports non-deterministic operations which can return different values for the same input. This is a non-deterministic function whose different return values are the all sublist partitions.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 15 bytes [SBCS](https://github.com/abrudz/SBCS)
Extracted from [this answer](https://codegolf.stackexchange.com/a/246130/64121) of mine. Assumes index origin 0.
```
{⊂∘⍵¨~,⍳1+×⍳≢⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37U1fSoY8aj3q2HVtTpPOrdbKh9eDqQetS5CChWCwA&f=e9Q31dP/UdsEA640BUMFIwVjBRMgSz0xKTlFXUHhUe9chfL8ouxihfw8heKSosy89GIdkHwFUFIBIl@cnJiTWAQWftS7RkEBLpGYl6JQkpGqkJpbUFKpkJNZXAIA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
ÞSṗ'f⁰⁼
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnlPhuZcnZuKBsOKBvCIsIiIsIlsxLCAyLCAzLCA0XSJd)
well it has a 2-byte builtin `øṖ` but it doesn't return all of the partitions...
## How?
```
ÞSṗ'f⁰⁼
ÞS # Get all sublists of the (implicit) input
ṗ # Powerset
' # Filter for:
f # Flatten
⁰⁼ # Is it equal to the input? (non-vectorizing)
```
[Answer]
## JavaScript (ES6), 87 bytes
```
([e,...a],b=[],c=[e],d=[...b,c])=>1/a[0]?[...f(a,b,[...c,a[0]]),...f(a,d,[a[0]])]:[d]
```
Explanation: `b` is the list of previous sublists, `c` is the current sublist, (which starts off as the first element of the array, since that must be in the first sublist) while `d` is the list of all sublists. The rest of the array elements are then recursively processed. In each case there are two options: either the next element is appended to the current sublist, or the current sublist is completed and the next element starts a new sublist. The recursive results are then concatenated together. When the array is exhausted, the list of list of all sublists is the result.
[Answer]
# APL(NARS) 38 char, 76 bytes
```
{k←↑⍴⍵⋄x←11 1‼k k⋄y←⍵⋄∪{x[⍵;]⊂y}¨⍳↑⍴x}
```
this use the Nars function 11 1‼k k but is very slow, unusable for arg array of 9 elements already...
```
P3←{k←↑⍴⍵⋄x←11 1‼k k⋄y←⍵⋄∪{x[⍵;]⊂y}¨⍳↑⍴x}
⍴∘P3¨{1..⍵}¨⍳8
1 2 4 8 16 32 64 128
P3 'abcd'
abcd abc d ab cd a bcd ab c d a bc d a b cd a b c d
```
this below is the function that not use the built in:
```
r←h w;k;i
r←⊂,⊂w⋄k←↑⍴w⋄i←1⋄→B
A: r←r,(⊂⊂,i↑w),¨h i↓w⋄i+←1
B: →A×⍳i<k
h 'abcd'
abcd a bcd a b cd a b c d a bc d ab cd ab c d abc d
⍴∘h¨{1..⍵}¨⍳8
2 4 8 16 32 64 128
```
we se the type each result:
```
o h ,1
┌──────┐
│┌1───┐│
││┌1─┐││
│││ 1│││
││└~─┘2│
│└∊───┘3
└∊─────┘
o h 1 2
┌2───────────────────┐
│┌1─────┐ ┌2────────┐│
││┌2───┐│ │┌1─┐ ┌1─┐││
│││ 1 2││ ││ 1│ │ 2│││
││└~───┘2 │└~─┘ └~─┘2│
│└∊─────┘ └∊────────┘3
└∊───────────────────┘
```
I don't know how it works, it is only heuristic try...
Possible I make some error; both the functions build the partitions of the list whatever input and not only 1 2 ... n.
[Answer]
# Axiom, 251 bytes
```
C==>concat;A==>List Any;px(a:A):A==(k:=#a;r:=copy[a];k<=1=>r;i:=1;repeat(i>=k=>break;x:=a.(1..i);y:=a.((i+1)..k);z:=px(y);t:=[x,z.1];for j in 2..#z repeat(w:=(z.j)::A;m:=#w;v:=[x];for q in 1..m repeat v:=C(v,w.q);t:=C(t,[v]));r:=C(r,copy t);i:=i+1);r)
```
If someone find something better...ungof and test:
```
pp(a:List Any):List Any==
k:=#a;r:=copy[a];k<=1=>r;i:=1
repeat
i>=k=>break
x:=a.(1..i);y:=a.((i+1)..k);z:=pp(y);
t:=[x,z.1]
for j in 2..#z repeat
w:=(z.j)::List Any
m:=#w; v:=[x]
for q in 1..m repeat
v:=concat(v,w.q);
t:=concat(t,[v])
r:=concat(r,copy t);
i:=i+1
r
(7) -> px []
(7) [[]]
Type: List Any
(8) -> px [1]
(8) [[1]]
Type: List Any
(9) -> px [1,2]
(9) [[1,2],[[1],[2]]]
Type: List Any
(10) -> px [1,2,3]
(10) [[1,2,3],[[1],[2,3]],[[1],[2],[3]],[[1,2],[3]]]
Type: List Any
(11) -> px [1,2,3,4,5,6]
(11)
[[1,2,3,4,5,6], [[1],[2,3,4,5,6]], [[1],[2],[3,4,5,6]],
[[1],[2],[3],[4,5,6]], [[1],[2],[3],[4],[5,6]], [[1],[2],[3],[4],[5],[6]],
[[1],[2],[3],[4,5],[6]], [[1],[2],[3,4],[5,6]], [[1],[2],[3,4],[5],[6]],
[[1],[2],[3,4,5],[6]], [[1],[2,3],[4,5,6]], [[1],[2,3],[4],[5,6]],
[[1],[2,3],[4],[5],[6]], [[1],[2,3],[4,5],[6]], [[1],[2,3,4],[5,6]],
[[1],[2,3,4],[5],[6]], [[1],[2,3,4,5],[6]], [[1,2],[3,4,5,6]],
[[1,2],[3],[4,5,6]], [[1,2],[3],[4],[5,6]], [[1,2],[3],[4],[5],[6]],
[[1,2],[3],[4,5],[6]], [[1,2],[3,4],[5,6]], [[1,2],[3,4],[5],[6]],
[[1,2],[3,4,5],[6]], [[1,2,3],[4,5,6]], [[1,2,3],[4],[5,6]],
[[1,2,3],[4],[5],[6]], [[1,2,3],[4,5],[6]], [[1,2,3,4],[5,6]],
[[1,2,3,4],[5],[6]], [[1,2,3,4,5],[6]]]
Type: List Any
(12) -> [[i,#px i] for i in [[],[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5,6]] ]
(12)
[[[],1],[[1],1],[[1,2],2],[[1,2,3],4],[[1,2,3,4],8],[[1,2,3,4,5,6],32]]
Type: List List Any
(13) -> [#px(i) for i in [[],[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5,6]] ]
(13) [1,1,2,4,8,32]
Type: List NonNegativeInteger
```
If this is too much space say that and I remove examples...
] |
[Question]
[
## Background
[Quaternion](https://en.wikipedia.org/wiki/Quaternion) is a number system that extends complex numbers. A quaternion has the following form
$$ a + bi + cj + dk $$
where \$ a,b,c,d \$ are real numbers and \$ i,j,k \$ are three *fundamental quaternion units*. The units have the following properties:
$$ i^2 = j^2 = k^2 = -1 $$
$$ ij = k, jk = i, ki = j $$
$$ ji = -k, kj = -i, ik = -j $$
Note that **quaternion multiplication is not commutative**.
## Task
Given a *non-real* quaternion, compute at least one of its square roots.
### How?
According to [this Math.SE answer](https://math.stackexchange.com/a/382440), we can express any non-real quaternion in the following form:
$$ q = a + b\vec{u} $$
where \$ a,b\$ are real numbers and \$ \vec{u} \$ is the imaginary unit vector in the form \$ xi + yj + zk \$ with \$ x^2 + y^2 + z^2 = 1 \$. Any such \$ \vec{u} \$ has the property \$ \vec{u}^2 = -1 \$, so it can be viewed as the imaginary unit.
Then the square of \$ q \$ looks like this:
$$ q^2 = (a^2 - b^2) + 2ab\vec{u} $$
Inversely, given a quaternion \$ q' = x + y\vec{u} \$, we can find the square root of \$ q' \$ by solving the following equations
$$ x = a^2 - b^2, y = 2ab $$
which is identical to the process of finding the square root of a complex number.
Note that a negative real number has infinitely many quaternion square roots, but **a non-real quaternion has only two square roots**.
## Input and output
Input is a non-real quaternion. You can take it as four real (floating-point) numbers, in any order and structure of your choice. Non-real means that at least one of \$ b,c,d \$ is non-zero.
Output is one or two quaternions which, when squared, are equal to the input.
## Test cases
```
Input (a, b, c, d) => Output (a, b, c, d) rounded to 6 digits
0.0, 1.0, 0.0, 0.0 => 0.707107, 0.707107, 0.000000, 0.000000
1.0, 1.0, 0.0, 0.0 => 1.098684, 0.455090, 0.000000, 0.000000
1.0, -1.0, 1.0, 0.0 => 1.168771, -0.427800, 0.427800, 0.000000
2.0, 0.0, -2.0, -1.0 => 1.581139, 0.000000, -0.632456, -0.316228
1.0, 1.0, 1.0, 1.0 => 1.224745, 0.408248, 0.408248, 0.408248
0.1, 0.2, 0.3, 0.4 => 0.569088, 0.175720, 0.263580, 0.351439
99.0, 0.0, 0.0, 0.1 => 9.949876, 0.000000, 0.000000, 0.005025
```
Generated using [this Python script](https://tio.run/##hVFda8IwFH3Pr7iwhybxGq26gYKDfvyLsYc0bWc3G7VWUMZ@e3eT1qGMMSiXe0/OOTm53V/azc7Ouy4vSii5xgwN5mLFwMIaeCYzGIGRhmoucyGlemSQIRiEnAjZxFLvSj6xDA5Oo0dWhu8DtSnaU2PhoJpCbxEyeVBVrd9I9NPlQ8eYy1CfttcUGGGMCaYuzeCjZQRjcompGplQzWWKBMcUMKNDFzb1cOLgxAORTx97pWenHoi8JvFWcX97Wbf8LFbDbcHnaqHC8gvhzyZQ5a6pdcvlWVwdZvcWS/XUC/5o7iyY0cfiSGt8YcCnCCEC1alAGsNf43iA/DzzZ@OZg2/47vPjVDmqcjQ1d2Xh4eWy93RIKNgrozSgobLgo9Du901lW@5WowVCsH4OsH9myaUWQjB4@I9zA3H3h6WH5YzUJD5qW7UXMJvCfHTdNw). Only one of the two correct answers is specified for each test case; the other is all four values negated.
## Scoring & winning criterion
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest program or function in bytes in each language wins.
[Answer]
## [APL (NARS)](http://www.nars2000.org/), 2 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")
`√`
NARS has built-in support for quaternions. ¯\\_(⍨)\_/¯
[Answer]
# [Python 2](https://docs.python.org/2/), 72 bytes
```
def f(a,b,c,d):s=((a+(a*a+b*b+c*c+d*d)**.5)*2)**.5;print s/2,b/s,c/s,d/s
```
[Try it online!](https://tio.run/##ZY49DoMwDIXn5hQeE2MCpO0AFSepOuSHqEgIEGHp6VOSdqhUyX7W@/xkeX3tz2VWMbrBg@eaDFlyogs957rgGnVh0BQWbeHQCUR5FajyvK3bOO8QKkWmCmSPdlWIVochQA93BrwmaAgOrQUdtvmz5Rdlr/KuVAn/5FNlW8sUlSkmz0kuGbft52YijWAPxvyywQTjDPmXjp08x0nENw "Python 2 – Try It Online")
More or less a raw formula. I thought I could use list comprehensions to loop over `b,c,d`, but this seems to be longer. Python is really hurt here by a lack of vector operations, in particular scaling and norm.
**[Python 3](https://docs.python.org/3/), 77 bytes**
```
def f(a,*l):r=a+sum(x*x for x in[a,*l])**.5;return[x/(r*2)**.5for x in[r,*l]]
```
[Try it online!](https://tio.run/##dVDRasMwDHyOv0JvsT3VS9JukIzsR0IevDahhSQtjgseY9@eWco2VkbBCN3pfEh3effH87RdlkPXQy8t6kFVrrYP83WUQQfozw4CnKaGRq3S2jy9uM5f3dSER@l0wdSvypGqXfZ27maooREgM4QcIdZMYYT5P7j5phgXPNsURP/R02OYGZIakpktlR3TZbl6EpMr0QrBB41ehngP7wvpR7Uzef@JcLdJTbxktF7qoH4ciluL0jyvH@40NxaCghliMMCJVCKx@IZ7PNSDSBxHRKEzpURycafJS9p6UAhp/ZriukGUKrV8AQ "Python 3 – Try It Online")
Solving the quadratic directly was also shorter than using Python's complex-number square root to solve it like in the problem statement.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 19 bytes
```
Sqrt
<<Quaternions`
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2Yb8z@4sKiEy8YmsDSxJLUoLzM/rzjhf0BRZl6JQ5oDQjDaUM9AR0EBjYz9DwA "Wolfram Language (Mathematica) – Try It Online")
Mathematica has Quaternion built-in too, but is more verbose.
---
Although built-ins look cool, do upvote solutions that don't use built-ins too! I don't want votes on questions reaching HNQ be skewed.
[Answer]
# JavaScript (ES7), ~~55~~ 53 bytes
Based on the direct formula [used by xnor](https://codegolf.stackexchange.com/a/176055/58563).
Takes input as an array.
```
q=>q.map(v=>1/q?v/2/q:q=((v+Math.hypot(...q))/2)**.5)
```
[Try it online!](https://tio.run/##bY9LC8IwEITv/RW5dVfb7cMHqKSe9OYvkB5CH7ZFm0ZD0F8fjdqDICxz@GaGZTphxK24toMOe1lWtuZW8UzRRQxgeJZEamuiNFJrxQHM9CB0Q81jkBqISCFGKU4mtEC7OXqMHVkcsCRwGrM8eJPkHwm/dETpOxGmzvktuhtJTK5DLkwzJ/PRWa0@Lxx8xb3co1ped6JoQDCesUL2N3mu6CxPUIPAzz7nGNJy396rEpaI1Mm2Bz9gPiLaJw "JavaScript (Node.js) – Try It Online")
### How?
Given an array \$q=[a,b,c,d]\$, this computes:
$$x=\sqrt{\frac{a+\sqrt{a^2+b^2+c^2+d^2}}{2}}$$
And returns:
$$\left[x,\frac{b}{2x},\frac{c}{2x},\frac{d}{2x}\right]$$
```
q => // q[] = input array
q.map(v => // for each value v in q[]:
1 / q ? // if q is numeric (2nd to 4th iteration):
v / 2 / q // yield v / 2q
: // else (1st iteration, with v = a):
q = ( // compute x (as defined above) and store it in q
(v + Math.hypot(...q)) // we use Math.hypot(...q) to compute:
/ 2 // (q[0]**2 + q[1]**2 + q[2]**2 + q[3]**2) ** 0.5
) ** .5 // yield x
) // end of map()
```
[Answer]
# [Haskell](https://www.haskell.org/), 51 bytes
```
f(a:l)|r<-a+sqrt(sum$(^2)<$>a:l)=(/sqrt(r*2))<$>r:l
```
[Try it online!](https://tio.run/##XY7BCoMwEETvfsUePCStSTXtRdH@Qb8gWAhFqZiITeyt/546tlAoLAPzZtjduwljZ22MPTOV5S9fC7MPD7@w8HQpuypep2ckDTts2O8UB/OVjTcTukANaZ1nVGS0at5mpIt/J74EVm2JUKC/MgYul@hJlOQRcgIty886gKJtk8SZYVoPOzNfaPbDtFAKQz1tP8U3 "Haskell – Try It Online")
A direct formula. The main trick to express the real part of the output as `r/sqrt(r*2)` to parallel the imaginary part expression, which saves a few bytes over:
**54 bytes**
```
f(a:l)|s<-sqrt$2*(a+sqrt(sum$(^2)<$>a:l))=s/2:map(/s)l
```
[Try it online!](https://tio.run/##XY7dCsIwDIXv9xS56EWr3V/1ZmPzDXyCUiHIhsN2zGXe@e51mYIghEO@k0OSG9K98z7GXmLt1YualB7zIsxO4p47Sc8g5MWoRpw4oVrKTR1wkjkpH69IHUEL1hYaSg2rFk6DLf8p/TqMZpukht1fmIupyDiXcSg7sBzZrarPOjZK55Ik4DCuh9dPzjDNw7iAYIAetp/iGw "Haskell – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes
```
≔X⊗⁺§θ⁰XΣEθ×ιι·⁵¦·⁵η≧∕ηθ§≔θ⁰⊘ηIθ
```
[Try it online!](https://tio.run/##TY3NDoIwEITvPkWP26QS/Dt5InLQgwlRb4RDhYZuUkBoi7593YbEeJnNzjeZqbWc6kGaEDJrse2hGN5qgnzwT6MaKIy3kLlL36gPjIKlXLAlcfcdXOUrmg/slAUUDDknniaH3xVM8@OKckv7DVvtIMcZG0VIsJHogv5HBDtLM9O85sSLCXsHJ2kdjPSHUJZpson92yi7KPuqCuvZfAE "Charcoal – Try It Online") Link is to verbose version of code. Port of @xnor's Python answer. Explanation:
```
≔X⊗⁺§θ⁰XΣEθ×ιι·⁵¦·⁵η
```
Square all of the elements of the input and take the sum, then take the square root. This calculates \$ | x + y\vec{u} | = \sqrt{ x^2 + y^2 } = \sqrt{ (a^2 - b^2)^2 + (2ab)^2 } = a^2 + b^2 \$. Adding \$ x \$ gives \$ 2a^2 \$ which is then doubled and square rooted to give \$ 2a \$.
```
≧∕ηθ
```
Because \$ y = 2ab \$, calculate \$ b \$ by dividing by \$ 2a \$.
```
§≔θ⁰⊘η
```
Set the first element of the array (i.e. the real part) to half of \$ 2a \$.
```
Iθ
```
Cast the values to string and implicitly print.
[Answer]
# Java 8, 84 bytes
```
(a,b,c,d)->(a=Math.sqrt(2*(a+Math.sqrt(a*a+b*b+c*c+d*d))))/2+" "+b/a+" "+c/a+" "+d/a
```
Port of [*@xnor*'s Python 2 answer](https://codegolf.stackexchange.com/a/176055/52210).
[Try it online.](https://tio.run/##jZHBbsIwDIbvPIXFKW3atA27IMTeAC4cqx6cpGNlJWVNQJomnr0LaQuDadpy@OJIv@3fzg5PGO/UWydrNAZWWOnPCUClbdm@oCxhfXkCbGxb6S1IopqjqEvAaAjEGMgxUMHCpZwnDsairSSsQcMSOoKRiJwsiJ8JLldoX5l5by3hIUF6e2KIVISCylBSFarAnYTTKUypSNDfcrhVgt3i0ufgGrs@Q7tTUynYu0lI7zovAIN@DFsaSyBlaQSQeaYjvetRkf2p@GeN@KHSnYLfsmM@qn/1ceWDj8zX4J4zz6fvivn83qNn9uOP/NJ8Qv@NjLHr1jYfxpZ71hwtO7iF2loTzSTBPC0iwDzz5J6zIhhKn7sv)
**Explanation:**
```
(a,b,c,d)-> // Method with four double parameters and String return-type
(a= // Change `a` to:
Math.sqrt( // The square root of:
2* // Two times:
(a+ // `a` plus,
Math.sqrt( // the square-root of:
a*a // `a` squared,
+b*b // `b` squared,
+c*c // `c` squared,
+d*d)))) // And `d` squared summed together
/2 // Then return this modified `a` divided by 2
+" "+b/a // `b` divided by the modified `a`
+" "+c/a // `c` divided by the modified `a`
+" "+d/a // And `d` divided by the modified `a`, with space delimiters
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
nOtsн+·t©/¦®;š
```
Port of [*@xnor*'s Python 2 answer](https://codegolf.stackexchange.com/a/176055/52210).
[Try it online](https://tio.run/##yy9OTMpM/f8/z7/E88Je7UPbSw6t1D@07NA666ML//@PNtAz1DHQMwJiYyA2iQUA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/h5nl4gou9ksKjtkkKSvb/8/xLii/s1T60veTQSv1Dyw6tsz668L/O/2gFAz0DHQUFQzBpACNjuaKhQlgk8OvQRdMHkjBCqNU1gilCtwNOQuwwBOswApPGYNIEKGFpiWotmDSMBQA).
**Explanation:**
```
n # Square each number in the (implicit) input-list
O # Sum them
t # Take the square-root of that
sн+ # Add the first item of the input-list
· # Double it
t # Take the square-root of it
© # Store it in the register (without popping)
/ # Divide each value in the (implicit) input with it
¦ # Remove the first item
®; # Push the value from the register again, and halve it
š # Prepend it to the list (and output implicitly)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes
```
{s=#+Norm@{##},##2}/(2s)^.5&
```
Port of [@xnor's Python 2 answer](https://codegolf.stackexchange.com/a/176055/52210).
[Try it online!](https://tio.run/##XYxBCsIwEEWvMjBQFJOYRF10UckJxH2pEMRiF6nQZjfM2dOOCoIwfPjvPybF/HykmId7LD00UGhucHd5TSkQIitEz/uNn7c3c6rKdRrG3MoA@gx9i9h1UEEIAYisAqdgTcsKyP03/SVS/XvRXuhPlpNmjXhGJHOQOAqt6887AY65LA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# C# .NET, 88 bytes
```
(a,b,c,d)=>((a=System.Math.Sqrt(2*(a+System.Math.Sqrt(a*a+b*b+c*c+d*d))))/2,b/a,c/a,d/a)
```
Port of [my Java 8 answer](https://codegolf.stackexchange.com/a/176072/52210), but returns a Tuple instead of a String. I thought that would have been shorter, but unfortunately the `Math.Sqrt` require a `System`-import in C# .NET, ending up at 4 bytes longer instead of 10 bytes shorter.. >.>
The lambda declaration looks pretty funny, though:
```
System.Func<double, double, double, double, (double, double, double, double)> f =
```
[Try it online.](https://tio.run/##jZFNa8MwDIbv/RU62onz5e5S2vQy2GmFQQc7hBwU210DabzF7mCM/vYsMenapnSbwY/AvJJeS8IEQjeqFRUaA0@Nfm1w9zUBMBZtKWD9aazahQ/7Wiyk3heVYnArkt8FdAkbSFuCrGCCSZouCcF0aLBCuw3X740l3CPoX72ih37hFb7whC89SbsTcVZEyER3ZYS0nU9Otj90KWGFZU1o/xmAZ2UsgTiMGUDiGB9J52eK5E/FP2sEo0oXCn7KDvhRfdPHD0c@EleDO04d784Vs9mlR8fEKQ7jUbmEN@x2b4ZtZTngMLthGfe6NrpS4UtTWvVY1opsCGZxzjBLevAe05wOHQ7tNw)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 49 bytes
```
{;(*+@^b>>².sum**.5*i).sqrt.&{.re,(@b X/2*.re)}}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2lpDS9shLsnO7tAmveLSXC0tPVOtTE294sKiEj21ar2iVB0NhySFCH0jLSBbs7b2vzVXcWKlQpqGXrShnp5xrCaQYRCrqZCWX8SloWCgZ6CjoGAIJg1gpKYOUMYQv4wumjxYxgihWtcIpgrDNDgJljHQMwTrMQKTxmDSBCRjaYlqN5g01NT5DwA "Perl 6 – Try It Online")
Curried function taking input as `f(b,c,d)(a)`. Returns quaternion as `a,(b,c,d)`.
### Explanation
```
{; } # Block returning WhateverCode
@^b>>².sum**.5 # Compute B of quaternion written as q = a + B*u
# (length of vector (b,c,d))
(*+ *i) # Complex number a + B*i
.sqrt # Square root of complex number
.&{ } # Return
.re, # Real part of square root
(@b X/2*.re) # b,c,d divided by 2* real part
```
] |
[Question]
[
Let's say that this array is how many press-ups I've achieved each day in the last 28 days:
```
[
20,20,20,30,30,30,30,
35,35,40,40,40,45,45,
50,50,50,50,50,50,50,
60,70,80,90,100,110,120
]
```
As you can see, it's taken a steep upward trend in the last week, and that's the part of this data I'm most interested in. The further in the past it is, the less I want that data to feature in my 'average' number of press-ups.
To that end, I want to work out an 'average' where each week is worth more than the previous week.
---
Background information, not part of this problem.
Normal average:
The sum of all values / the number of values
For above:
1440 / 28 = 51.42857142857143
---
Weighted average:
Split the array into 4 groups of 7, and start up a new array.
* Add the first group to the array.
* Add the second group to the array twice.
* Add the third group to the array thrice.
* Add the fourth group to the array four times.
Sum all of the new array, and divide by the length of the *new* array.
For above:
Convert the array to this:
```
[
20,20,20,30,30,30,30, # first week once
35,35,40,40,40,45,45,
35,35,40,40,40,45,45, # second week twice
50,50,50,50,50,50,50,
50,50,50,50,50,50,50,
50,50,50,50,50,50,50, # third week thrice
60,70,80,90,100,110,120,
60,70,80,90,100,110,120,
60,70,80,90,100,110,120,
60,70,80,90,100,110,120 # Fourth week four times
]
```
Then run a normal average on that array.
4310 / 70 = 61.57142857142857
Note that it's higher than the normal average value because of the upward trend in the last week.
---
The rules:
* The input is a flat array of 28 nonnegative integers.
* Any language you'd like to write in.
* Output a number.
* I always like to see [TIO](https://tio.run) links.
* Try to solve the problem in the smallest number of bytes.
* The result should be a decimal accurate to at least 4 decimal places (either truncated or rounded up from the test case values is fine) or an exact fraction.
---
Test cases:
# Case 1: Upward trend
```
[
20,20,20,30,30,30,30,
35,35,40,40,40,45,45,
50,50,50,50,50,50,50,
60,70,80,90,100,110,120
]
```
Normal average: 51.42857142857143
Weighted average: 61.57142857142857
# Case 2: Leaving the lull behind
(I had a bad week, but it was a while ago)
```
[
50,50,50,50,50,50,50,
10,10,10,10,10,10,10,
50,50,50,50,50,50,50,
50,50,50,50,50,50,50
]
```
Normal average: 40
Weighted average: 42
# Case 3: Giving up
I had a bad week, it's pulling my average down fast.
```
[
50,50,50,50,50,50,50,
50,50,50,50,50,50,50,
50,50,50,50,50,50,50,
10,10,10,10,10,10,10
]
```
Normal average: 40
Weighted average: 34
# Case 4: Averaging out
Okay, so I'm just playing around here, I thought it might be the same value for the normal and weighted averages, but, of course, it was not.
```
[
60,60,60,60,60,60,60,
30,30,30,30,30,30,30,
20,20,20,20,20,20,20,
15,15,15,15,15,15,15
]
```
Normal average: 31.25
Weighted average: 24.0
---
## Bonus problem:
What combination of 28 values would have the same normal average and weighted average?
---
Happy golfing!
[Answer]
# [Python 3](https://docs.python.org/3/), 38 bytes
```
lambda x:sum(x+x[7:]+x[14:]+x[21:])/70
```
[Try it online!](https://tio.run/##lZDdCsIwDIWv7VPkssWA2Z/Tgk8ydzGR4cD9MCfUp5@pwznpVIQvKRwSTnqaW3eqq6DPYQf7/pyVh2MGRl@upTRLk8Q65e6Fj8f3dKpWMfV53YKBogIpIBEAPuFAMIH1IEImpCeRhfWI0IX1NWFMuCHcEnrE5XH5JCDFwejTop1z@DI/p/92@Vefu@rlwp91saG9xziGOYY8xbpE6MAuQmmxaNqi6mQujVL9HQ "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes
Saved 1 byte thanks to *Mr. Xcoder*
```
7ô.s˜ÅA
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f/PCWY9v8/c0N9P//jzYy0IEgY2RkCkImBjBkCkKmBliQmYGOuYGOhYGOpYGOoQEQGwKxkUEsAA "05AB1E – Try It Online")
**Explanation**
```
7ô # split list into groups of 7
.s # push suffixes
˜ # flatten
ÅA # arithmetic mean
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
s7ṫJFÆm
```
[Try it online!](https://tio.run/##y0rNyan8/7/Y/OHO1V5uh9ty/x9uf9S0JvL//@hoLgUFIwMdCDJGQkBxY1MdIDIxgCFTEAKKmxroYCKguJmBjrmBjoWBjqWBjqEBEBsCsZEBl0IsUDYaj0aQOgyERz02ccK2kCqOzVUIW4CexUSgQEMNRnhgwgMZGYFsMdXBQEBbuGIB "Jelly – Try It Online")
### How it works
```
s7ṫJFÆm Main link. Argument: A (array of length 28)
s7 Split the array into chunks of length 7.
J Indices; yield [1, ..., 28].
ṫ Tail; yield the 1st, ..., 28th suffix of the result to the left.
Starting with the 5th, the suffixes are empty arrays.
F Flatten the resulting 2D array.
Æm Take the arithmetic mean.
```
[Answer]
# [R](https://www.r-project.org/)+pryr, ~~32~~ 28 bytes
and the same average score week over week would result in equality of the means.
```
pryr::f(s%*%rep(1:4,e=7)/70)
```
[Try it online!](https://tio.run/##bcNBCoAgEAXQffcQNCb6WmZJnSbMrdiq009KBC2C9zLHteOUr@z9IU/RihyS1H6ksDnVOyiOcpcG9Bi@bDXiZSuLHxPIgWbQAtIodWmgVMM3 "R – Try It Online")
Saved 4 bytes by using dot product thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).
Pure R would have two more bytes using `function`
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
7es4:*s70/
```
[Try it online!](https://tio.run/##y00syfn/3zy12MRKq9jcQP///2gjAx0IMkZGpiBkYgBDpiBkaoAFmRnomBvoWBjoWBroGBoAsSEQGxnEAgA "MATL – Try It Online")
I haven't posted a MATL answer in ages! Figured I might participate as part of [LOTM May 2018](https://codegolf.meta.stackexchange.com/q/16337/31716)!
Explanation:
```
7e % Reshape the array into 7 rows (each week is one column)
s % Sum each column
4: % Push [1 2 3 4]
* % Multiply each columnar sum by the corresponding element in [1 2 3 4]
s % Sum this array
70/ % Divide by 70
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
AΣΣṫC7
```
[Try it online!](https://tio.run/##yygtzv7/3/Hc4nOLH@5c7Wz@////aCMDHQgyRkamIGRiAEOmIGRqgAWZGeiYG@hYGOhYGugYGgCxIRAbGcQCAA "Husk – Try It Online")
Uses the trick [Dennis used](https://codegolf.stackexchange.com/a/163991/59487) to outgolf my Jelly submission. Instead of repeating each chunk **N** times, it retrieves the suffixes of the list of chunks, which after flattening will yield the same result, except for the order.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
s7x"J$FÆm
```
[Try it online!](https://tio.run/##y0rNyan8/7/YvELJS8XtcFvu////o7kUFIwMdCDIGAkBxY1NdYDIxACGTEEIKG5qoIOJgOJmBjrmBjoWBjqWBjqGBkBsCMRGBlyxAA "Jelly – Try It Online")
### How it works
```
s7x"J$FÆm – Takes input from the first command line argument and outputs to STDOUT.
s7 – Split into groups of 7.
" – Apply vectorised (zipwith):
x J$ – Repeat the elements of each list a number of times equal to the list's index.
F – Flatten.
Æm – Arithmetic mean.
```
[Answer]
# [Haskell](https://www.haskell.org/), 35 bytes
```
(/70).sum.zipWith(*)([1..]<*[1..7])
```
Bonus: if `a,b,c,d` are the weekly sums, normal average is the same as weighted average iff:
```
(a + b + c + d)/4 = (a + 2b + 3c + 4d)/10 <=>
10(a + b + c + d) = 4(a + 2b + 3c + 4d) <=>
5(a + b + c + d) = 2(a + 2b + 3c + 4d) <=>
5a + 5b + 5c + 5d = 2a + 4b + 6c + 8d <=>
3a + b - c - 3d = 0
```
One solution is when first and last week have same sums, and likewise second and third weeks have the same sum, but there are infinitely many solutions if your biceps are up to it. Example: [15,10,10,10,10,10,5,20,20,20,25,25,20,20,30,20,20,20,20,20,20,10,10,20,0,10,10,10]
[Try it online!](https://tio.run/##ZclBDoIwEAXQPaeYhQsgYx1ARInsvIML7AINSGPBxpaNh7cOMSYmJu/PJP/3jb21WvuuOvlwVVAk7DSIpzJH5fowjsI6EULu4/kVMvJDo0aowDzU6EBABwtwrXVBMF8e6gAgJfzIfnCf5cjW9JXPuM8J/3G/ISwIt4Q7woQ4CSclXmRZ1of7dNat9K9Lp5ur9cuLMW8 "Haskell – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 49 bytes
```
a=>a.map((x,i)=>(I+=d=-~(i/7),s+=x*d),s=I=0)&&s/I
```
[Try it online!](https://tio.run/##ZcjBCoJAFIXhvU/hSmbyqldtshbXvc8QLQZHY8IcaSJc9erTjQiC4Dsc@C/6oX1/s8s9m50ZwkhBU6vzq16EWMFKakWXkqHsKWzRSPAprRvDTx2hTBJfdKF3s3fTkE/uLEZxjOK4Qviof3CvFbAtfqk37grhH/cdQoOwRzgglMgreRVGJynDCw "JavaScript (Node.js) – Try It Online")
---
Non generics solution
# [JavaScript (Node.js)](https://nodejs.org), 39 36 bytes
```
a=>a.reduce((s,x,i)=>s+x*-~(i/7))/70
```
[Try it online!](https://tio.run/##ZchBDoIwEEDRPadgOdUBBrBWF@UixkVTiikh1FA1rLx6HWNMTEze3/zRPEy0i7/eijn0Lg06Gd2ZcnH93TqAiCt6obu4XTfFE3ylhKgUJRvmGCZXTuECA5yyPG8IP9of/FuJbEdf8o2/JPzHf0@oCA@ER8KauJprKDsLkV4 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ñI"%"╟
```
[Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=a449222522c7&i=[20,20,20,30,30,30,30,35,35,40,40,40,45,45,50,50,50,50,50,50,50,60,70,80,90,100,110,120]%0A%0A[50,50,50,50,50,50,50,10,10,10,10,10,10,10,50,50,50,50,50,50,50,50,50,50,50,50,50,50]%0A%0A[50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,10,10,10,10,10,10,10]%0A%0A[60,60,60,60,60,60,60,30,30,30,30,30,30,30,20,20,20,20,20,20,20,15,15,15,15,15,15,15]&a=1&m=1)
### Unpacked (7 bytes) and explanation:
```
7/|]$:V
7/ Split into groups of seven.
|] Suffixes
$:V Flatten and average. Implicit print as fraction.
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~10~~ 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
äΔ6◙█µøΓ
```
[Run and debug it](http://stax.tomtheisen.com/#p=84ff360adbe600e2&i=[20,20,20,30,30,30,30,35,35,40,40,40,45,45,50,50,50,50,50,50,50,60,70,80,90,100,110,120]%0A[50,50,50,50,50,50,50,10,10,10,10,10,10,10,50,50,50,50,50,50,50,50,50,50,50,50,50,50]%0A[50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,10,10,10,10,10,10,10]%0A[60,60,60,60,60,60,60,30,30,30,30,30,30,30,20,20,20,20,20,20,20,15,15,15,15,15,15,15]%0A&a=1&m=2)
Explanation (unpacked):
```
7/4R:B$:V Full program, implicit input
7/ Split into parts of length 7
4R Push [1, 2, 3, 4]
:B Repeat each element the corresponding number of times
$ Flatten
:V Average
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 33 bytes
```
@(x)sum(reshape(x,7,4)*(1:4)')/70
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzuDRXoyi1OCOxIFWjQsdcx0RTS8PQykRTXVPf3OB/mka0kYEOBBkjIQVjUx0gMjGAIVMQUjA10MFECmYGOuYGOhYGOpYGOoYGQGwIxEYGsZr/AQ "Octave – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
I∕ΣE⪪A⁷×Σι⊕κ⁷⁰
```
[Try it online!](https://tio.run/##ZcoxC8IwEIbhvb@i4wVOuLbWKo66dBCEupUOIQ0Y2sTQpv378VQEQXje4T5O3eWkHnKM8ToZF@Ak5wBns5peQ7NYuEgPjR9NgNr5JYDAtOJuxur5/WD4qp2atNUu6B4GUZEQ4hhj2yZpmhN@FD94L0pkW/oqX3gvCf/xviOsCPeEB8KMuIzLKem6uFnHJw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
A Input array
⪪ ⁷ Split into subarrays of length 7
E Loop over each subarray
ι Subarray
Σ Sum
κ Loop index
⊕ Incremented
× Product
Σ Sum results
⁷⁰ Literal 70
∕ Divide
I Cast to string
Implicitly print
```
[Answer]
# [K4](https://kx.com/download/) / [K (oK)](https://github.com/JohnEarnest/ok), ~~19~~ ~~16~~ 14 bytes
**Solution:**
```
+/(1+&4#7)%70%
```
[Try it online!](https://tio.run/##y9bNz/7/X1tfw1BbzUTZXFPV3EDVyEABgoyRkSkImRjAkCkImRpgQWYGCuYGChYGCpYGCoYGQGwIxEYG//8DAA "K (oK) – Try It Online")
**Example:**
```
+/(1+&4#7)%70%50 50 50 50 50 50 50 10 10 10 10 10 10 10 50 50 50 50 50 50 50 50 50 50 50 50 50 50
42
```
**Explanation:**
Evaluation is perform right-to-left. Divide 7 1s, 7 2s, 7 3s and 7 4s by 70 divided by the input; then sum up.
```
+/(1+&4#7)%70% / the solution
70% / 70 divided by the input
( )% / the stuff in brackets divided by this...
4#7 / draw from 7, 4 times => 7 7 7 7
& / 'where' builds 7 0s, 7 1s, 7 2s, 7 3s
1+ / add one
+/ / sum (+) over (/) to get the total
```
[Answer]
Excel: 33 bytes
(3 bytes saved from @wernisch's answer by running data on 2 lines from A1:N1 and A2:N2)
```
=AVERAGE(A1:N2,H1:N2,A2:N2,H2:N2)
```
Apologies for not including this as a comment. I don't have enough reputation to do so.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~11~~ 10 bytes
```
xÈ/#F*ÒYz7
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=eMgvI0Yq0ll6Nw==&input=WwogIDUwLDUwLDUwLDUwLDUwLDUwLDUwLAogIDUwLDUwLDUwLDUwLDUwLDUwLDUwLAogIDUwLDUwLDUwLDUwLDUwLDUwLDUwLAogIDEwLDEwLDEwLDEwLDEwLDEwLDEwCl0=)
---
## Explanation
```
È :Pass each element at index Y through a function
/#F : Divide by 70
Yz7 : Floor divide Y by 7
Ò : Negate the bitwise NOT of that to add 1
* : Multiply both results
x :Reduce by addition
```
[Answer]
# [Arturo](https://arturo-lang.io), 40 bytes
```
$[a][i:0(sum map a'x[x*1+i/7i:i+1])//70]
```
[Try it](http://arturo-lang.io/playground?53TEFW)
[Answer]
# [Triangularity](https://github.com/Mr-Xcoder/Triangularity), 49 bytes
```
....)....
...D7)...
..14)21..
.WM)IEtu.
}u)70s/..
```
[Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/Xw8INEEEFxC7mGtCWIYmmkaGIFa4r6ana0mpHldtqaa5QbG@nt7//9FGBjoQZIyMTEHIxACGTEHI1AALMjPQMTfQsTDQsTTQMTQAYkMgNjKIBQA "Triangularity – Try It Online")
### Explanation
```
)D7)14)21WM)IEtu}u)70s/ – Full program.
)D7)14)21 – Push the literals 0, 7, 14, 21 onto the stack.
WM } – Wrap the stack to a list and run each element on a separate
stack, collecting the results in a list.
)IEt – Crop the elements of the input before those indices.
u – Sum that list.
u – Then sum the list of sums.
)70 – Push the literal 70 onto the stack.
s/ – Swap and divide.
```
[Answer]
# [Perl 5](https://www.perl.org/) `-pa`, 28 bytes
```
$\+=$_/70*int$i++/7+1for@F}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lRttWJV7f3EArM69EJVNbW99c2zAtv8jBrbb6/38jAwUIMkZGpiBkYgBDpiBkaoAFmRkomBsoWBgoWBooGBoAsSEQGxn8yy8oyczPK/6vW5AIAA "Perl 5 – Try It Online")
Input is space separated rather than comma separated.
[Answer]
# APL+WIN, 13 bytes
Prompts for array as a vector of integers:
```
(+/⎕×7/⍳4)÷70
```
Explanation:
```
7/⍳4) create a vector comprising 7 1s, 7 2s, 7 3s and 7 4s
+/⎕× prompt for input, multiply by the vector above and sum result
(....)÷70 divide the above sum by 70
```
[Answer]
# Java 8, 57 bytes
```
a->{int r=0,i=35;for(;i-->7;)r+=i/7*a[i-7];return r/70d;}
```
[Try it online.](https://tio.run/##rZLPbsIwDMbvPIWP7ZYWQ9d1U1TeYFw4Ig5ZG6awkqI0ZZpQn71z/02goolNk34@JF9if7GzE0fh7dL3OslEUcCLUPo0AVDaSrMViYRlswRI8/I1k5A4pKw3IFxO2xUFUVhhVQJL0BBDLbzFiQ6BiZGpOAj5NjcOV563iLhr7mM1je7EWnnRhhtpS6PBTCNMeVXzLt2BKlG6PusxVynsyZazskbpt7Z452n1WVi59/PS@geSbKYd7SeOlh/QuuxOAcyRdQRn9FoQMuIBB8KGXguRjem1R2QRsidkz8hmSDGjmGPlto253dtPNZqUI264d037V2N/1a496NfGqPNjhmlezvhi0t@/4JzBWMhG9MaqSVV/AQ)
**Explanation:**
```
a->{ // Method with integer-array parameter and double return-type
int r=0, // Result-sum, starting at 0
i=35; // Index-integer, starting at 35
for(;i-->7;) // Loop `i` downwards in the range (35,7]
r+= // Add the following to the result-sum:
i/7 // `i` integer-divided by 7,
*a[i-7]; // multiplied by the item at index `i-7`
return r/70d;} // Return the result-sum, divided by 70.0
```
[Answer]
# [J](http://jsoftware.com/), 16 bytes
```
70%~1#.]*7#4{.#\
```
## Explanation:
```
#\ finds the lengths of all successive prefixes (1 2 3 4 ... 28)
4{. takes the first 4 items (1 2 3 4)
7# creates 7 copies of each element of the above list
]* multiplies the input by the above
1#. sum
70%~ divide by 70
```
[Try it online!](https://tio.run/##jc6xCsIwFIXhvU9xMEixaDg3bRotOAlOTs46iaW4@AAFXz2mYEDwIoXvH@/hPuLClj32HUqsQXSpjcXhfDrGwOVLjL1WwTSjNZe4KlDcb8MTPRw/6m9@0jDzE09FSwRiS@wIYUpSjnldvRGNn@vv9HzaE3m6paLWOI34X/EN "J – Try It Online")
[Answer]
## Clojure, ~~48~~ 46 bytes
```
#(/(apply +(for[i[0 7 14 21]v(drop i %)]v))70)
```
This ended up being shorter than mapcat + subvec combination.
[Answer]
# TI-Basic, 25 bytes
```
mean(Ansseq(sum(I>{0,7,21,42}),I,1,70
```
Alternate solution, 39 bytes
```
Input L1
For(I,1,70
Ans+L1(I)sum(I>{0,7,21,42
End
Ans/70
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 65 bytes
```
->r{(b=(0..r.size/7).map{|a|r[a*7..-1]}.flatten).sum/b.size.to_f}
```
[Try it online!](https://tio.run/##lZFBa8IwGIbv@RXfTR0xfm3tuhUcyA677LpTKSPFVAu1ljRRNvW3d0mHUm2VDZ7v8uYjecgrdfJVpzCDevwi98NkNkTGJKuybzEJRmzNy/2BH2TEHwLGxk58ZGnOlRLFiFV6PUmaTaY2n@mxLrWqYPDKKwFOCB/ljssFKCmKxYA0Z2kUEQAX6S9eC5N7PjVM8YRvMbmPtIvJH5EGSJ@QPiN10IxjxkUSx81rhLR83BDeBd9mxRLUSkCu8xwSscqu1G49ZW/ucGe/L@/18kJ4yxotXf7J5L95n3mvyTSE@VZIvrQyG60ubMxXd7GVXZZ4rvJccRtr49MOJ5v6Bw "Ruby – Try It Online")
[Answer]
# Excel, ~~36~~ 33 bytes
-3 bytes thanks to @tsh.
```
=SUM(1:1,H1:AB1,O1:AB1,V1:AB1)/70
```
Input in first row (`A1` to `AB1`).
[Answer]
# [Julia 0.6](http://julialang.org/), 27 bytes
```
p->repeat(1:4,inner=7)'p/70
```
[Try it online!](https://tio.run/##lZBBCsIwEEX3OUV2tjDipG0aFepFpIsuWojUEEK9g0fwfF4kTpSWSqoivNk8JvzMP1163ZS@4xX3dn1wrW2bIRH7ArQxratUurIbhf7c2MQ6bYbe3K@3DnjCjozzDOFFPoN8LoEocEQGyEuEGPIlgkLYIuwQBNIImgxZDc@YT8/CVsSX/SX/K@Nfv/SnMYPOjAl1vRc41TjVOydkSIhgNUtT5h8 "Julia 0.6 – Try It Online")
The `repeat` call forms a column matrix of 28 values, containing seven 1's, then seven 2's, etc. We then transpose it with `'`, then do a matrix multiplication with the input (mutiplication is implicit here). Since it's a matrix multiplication of a 1x28 matrix with a 28x1 matrix, we end up with a single value, which is the weighted sum we need. Divide that by `70` to get our weighted mean.
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 36 bytes
```
[ [ 7 /i 1 + * ] map-index Σ 70 / ]
```
[Try it online!](https://tio.run/##bc5PCoJAGAXw/ZzirYv0UzP7c4Bo0yZaiQsZv3DIRhtHKKLTdJ@uNGkUtAh@b/V48A65tLVx@91mu17ilNvS67SSdcFo@dyxltziyEZz9W7RGLb22hilLVbiBoGQPqIfAlE8mNJXPBCI6Q@BGSEhzAkLQkB9gj4hCdxdihQJfIUAY4yQ9T@aidIFX/B8DCsfmZN5VcFzLw "Factor – Try It Online")
] |
[Question]
[
# Input
A bound m <= 4294967295.
# Output
Consider values sampled uniformly at random from integers in the range 0 to m, inclusive.
Your output should be the expected (average) number of trailing zeros in the binary representation of the sampled value. Your answer should be exact, for example given as a fraction.
# Example
* m = 0. The answer is 1. 0 will be sampled with prob 1.
* m = 1. The answer is 1/2. 0 with prob 1/2 and 1 with prob 1/2.
* m = 2. The answer is 2/3. 0 and 2 have one trailing zero.
* m = 3. The answer is 1/2. 0 and 2 have one trailing zero.
[Answer]
# [Python](https://docs.python.org/2/), 36 bytes
```
lambda m:(m+1-bin(m).count('1'),m+1)
```
[Try it online!](https://tio.run/##Fcg7DsIwEAXAPqd4XXaF@QS6SLkJzTrBYCl@jiynyOkNTDnbUT@Z9xamZ1st@cWQRkmn4ewjJellzjur9EOv7rfaQi4gIlGM75c8bjp2MAePCUGoHbYSWUEH@bc6hDVbFVNc4dsX "Python 2 – Try It Online")
A formula!
$$ f(m) = 1 - \frac{\text{#ones in bin}(m)}{m+1} = \frac{m+1-\text{#ones in bin}(m)}{m+1}$$
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 bytes
```
{1+⍵,+/⌊⍵÷2*⍳32}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgmG/9OAZLWh9qPerTra@o96uoCMw9uNtB71bjY2qv3/P03BgCtNwRCIjYDYGAA "APL (Dyalog Unicode) – Try It Online")
\$\frac{1+\sum\_{i=1}^{32}\left\lfloor\frac{m}{2^i}\right\rfloor}{1+m}\$. returns denominator,numerator. uses `⎕io=1`.
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), ~~13~~ 12 bytes
```
{1+x,x-/2\x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqtpQu0KnQlffKKai9n@JVbVKdGVdkVWaQoV1Qn62tUZCWmJmjnWFdaV1kWZsLVdJtIG1oYJhLJBhaG0EYRhZGysYgRjG1iYQhqGRsYmpNYg0UwCRBrH/AQ "K (ngn/k) – Try It Online")
like [xnor's](https://codegolf.stackexchange.com/a/209870/24908)
`{` `}` function with argument `x`
`2\` binary digits
`x-/` reduction with minus, using `x` as initial value
`x,` prepend `x`
`1+` add 1 to both in the pair
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 9 bytes
```
-\1∘+,1⊥⊤
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/XzfG8FHHDG0dw0ddSx91Lfmf9qhtwqPevkddzYfWGz9qm/iob2pwkDOQDPHwDP6fdmiFwqPezYZmAA "APL (Dyalog Extended) – Try It Online")
Yet another port of [xnor's Python answer](https://codegolf.stackexchange.com/a/209870/78410). A tacit function that takes `n` and returns `(denom, num)`.
### How it works
```
-\1∘+,1⊥⊤ ⍝ Input: n
1⊥⊤ ⍝ Popcount(n)
1∘+, ⍝ Pair with n+1
-\ ⍝ Minus scan; convert (a,b) to (a,a-b)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
:B!P&X>qtswnhQ
```
The code uses brute force: computes the binary expansion of all the numbers in the specified range and counts trailing zeros.
Output is numerator, then denominator.
[Try it online!](https://tio.run/##y00syfn/38pJMUAtwq6wpLg8LyPw/39DAwA). You can also see the [first outputs](https://tio.run/##y00syflvpeTw38pJMUAtwq6wpLg8LyPwf5hDmLqunYJ6RnnGfyMDAA), or [plot them](https://matl.suever.net/?code=%3A%22%40%0A%3AB%21P%26X%3EqtswnhQ%0AZ%7D%2F%5DvXG&inputs=200&version=22.3.0) to see some interesting trends (more on this below).
## How the code works
```
: % Implicit input: m. Range [1 2 ... m]. Note that 0 is not included
B % Convert to binary. Gives a matrix, with the binary expansion of each
% number on a different row, left-padded with zeros if needed
! % Transpose
P % Flip vertically. Now each binary expansion if in a column, reversed
&X> % Argmax of each column. This gives a vector with the position of the
% first 1 (the last 1 in the non-reversed expansion) for each number
q % Subtract 1, element-wise. This gives the number of trailing zeros
% in the binary expansion of each number
t % Duplicate
s % Sum
w % Swap
n % Number of elements
h % Concatenate both numbers horizontally
Q % Add 1 to each number, to account for the fact that 0 has not been
% considered. Implicit display
```
## Some interesting properties of the sequence
Let \$a(m)\$ denote the sequence. Then
1. \$a(m) = m/(m+1)\$ when \$m\$ is a power of \$2\$.
2. If \$m\$ is a power of \$2\$, \$a(n) < a(m)\$ for all \$n\ < 2m, n \neq m\$.
3. \$\lim\sup\_{m \rightarrow \infty} a(m) = 1\$.
### Proof of 1
Let \$m\$ be a power of \$2\$. Consider the set \$\{1,2,\ldots,m\}\$. In this set, \$m/2\$ members are multiples of \$2\$, and thus have at east a trailing zero. \$m/4\$ members are multiples of \$4\$, and contribute one additional trailing zero, etc. There is only one multiple of \$m\$. So the total number of trailing zeros is \$m/2 + m/4 + \cdots + 1 = m-1\$, and the fraction of trailing zeros in the set \$\{1,2,\ldots,m\}\$ is \$(m-1)/m\$. Therefore in the set \$\{0,1,2,\ldots,m\}\$ it is \$m/(m+1)\$.
### Proof of 2
The proof uses mathematical induction.
For \$m=2\$ the claimed property holds.
Let \$m\$ be an arbitrary power of \$2\$. Assume that the property holds for \$m/2\$. Combined with property 1 this implies that, for all \$k<m\$, \$a(k) \leq a(m/2) = m/(m+2) < m/(m+1)\$.
Consider the numbers \$m+1, m+2, \ldots, 2m-1\$. Their trailing zeros are the same as those of \$1, 2, \ldots, m-1\$ respectively (the binary expansions only differ in a leading string formed by a one and some zeros, which doesn't affect). For \$k<m\$, using property 1 again the term \$a(m+k)\$ can be expressed as \$(m+j)/(m+1+k)\$, where \$j\$ is the total number of trailing zeros in \$\{m+1,\ldots,m+k\}\$, or equivalently in \$\{1,\ldots,k\}\$. Since \$a(k) = j/k < m/(m+1)\$, it holds that \$(m+j)/(m+1+k) < m/(m+1)\$.
Therefore the property is satisfied for \$m\$.
### Proof of 3
From proerties 1 and 2, \$\lim\sup\_{n \rightarrow \infty} a(n) = \lim\_{m \rightarrow \infty} m/(m+1) = 1\$.
[Answer]
# [J](http://jsoftware.com/), 13 12 10 bytes
```
1-+/@#:%>:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DXW19R2UrVTtrP5rcnGlJmfkK6QpGShUWClk6hma/QcA "J – Try It Online")
*-12 bytes thanks to the forumula of xnor*
*-2 bytes thanks to Bubbler's idea of making the input extended precision rather than converting inside my verb*
## how
One minus `1-` the sum of `+/@` the binary representation of the input `#:` divided by `%` the input plus one `>:`.
# original
# [J](http://jsoftware.com/), 24 bytes
```
(,1#.i.&1@|.@#:"0@i.)@>:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NXQMlfUy9dQMHWr0HJStlAwcMvU0Heys/mtycaUmZ@QrpClk6hma/QcA "J – Try It Online")
Outputs as (denominator, numerator)
[Answer]
# JavaScript (ES6), ~~35~~ 33 bytes
Outputs the fraction as `[numerator, denominator]`.
```
n=>[(g=k=>k?g(k&k-1)-1:++n)(n),n]
```
[Try it online!](https://tio.run/##FYyxDsIgFEX3fsWdLISiNjEOVeqHEIamFqI0D9oaF@Ouv@mPIJ3OcO659@7ZLf18iw9J4TokqxKpVjOnvGr9xTG/8bLmsm6EIM6IV2SSDTMjKOxPIJxxPGQKwfEqgD7QEsZhOwaXNwJlA11mMh0rTCZXNr/w1Rj8vh@sMmKHiRfv9Ac "JavaScript (Node.js) – Try It Online")
The recursive formula for the numerator was initially derived from [A101925](https://oeis.org/A101925), which itself is defined as [A005187](https://oeis.org/A005187)(n) + 1:
```
(g=n=>n&&g(n>>1)+n)(n)-n+1
```
Once golfed some more, it turns out to be equivalent to [@xnor's formula](https://codegolf.stackexchange.com/a/209870/58563).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
!Ò2¢s‚>
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f8fAko0OLih81zLL7/98IAA "05AB1E – Try It Online")
The number of trailing zeros is the same as the multiplicity of \$2\$ in the prime factorization (for \$n \ne 0\$). This means we just need to count the number of times \$2\$ divides \$m!\$.
```
! factorial
Ò prime factorization
2¢ count 2's
s‚ swap and pair (with input)
> increment both
```
If output as `[denominator, numerator]` is fine, [`!Ò2¢‚>`](https://tio.run/##yy9OTMpM/f9f8fAko0OLHjXMsvv/3wgA) works at 6 bytes.
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
An implementation of [xnor's formula](https://codegolf.stackexchange.com/a/209870/58563).
```
b1¢(0‚>+
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/yfDQIg2DRw2z7LT//zcAAA "05AB1E – Try It Online")
There may be a shorter way to count set bits than `b1¢`.
```
implicit input m
b to binary bin(m)
1¢ count 1's bin(m).count('1')
( negative -bin(m).count('1')
0‚ pair with 0 [-bin(m).count('1'), 0]
> increment [1-bin(m).count('1'), 1]
+ add input [m+1-bin(m).count('1'), m+1]
implicit output
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~65~~ 64 bytes
```
lambda m:(sum(bin(i+1)[:1:-1].find('1')for i in range(m))+1,m+1)
```
[Try it online!](https://tio.run/##XYpBCsIwEADvvmJv2aVWXQQPgfqRmENKjS6YtCT1ICFvj8Wjcxtmls/6nOO5@eHWXi6Mk4OgMb8DjhJROiajWfdsD17ihIoV@TmBgERILj7uGIg63oftbH@FL6R3sJFhAI9CP1mSxBW9KlKhv0LJFbBkc7LHbNhWUtS@ "Python 3 – Try It Online")
Returns the fraction as tuple `(denominator, numerator)`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes
```
1-DigitCount[#,2,1]/(#+1)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n27731DXJTM9s8Q5vzSvJFpZx0jHMFZfQ1nbUFPtf0BRZl6JvkO6voNCUGJeemq0gY6JUez//wA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
,KhQ-K/.BQ"1
```
[Try it online!](https://tio.run/##K6gsyfj/X8c7I1DXW1/PKVDJ8P9/IwA "Pyth – Try It Online")
Explanation:
```
, // Print the following two evaluations as [X,Y]
KhQ // Denominator = input + 1 and store it in K
/.BQ"1 // Convert input to binary and count 1's
-K // K(input + 1) - number of binary ones
```
Outputs `[denominator, numerator]`
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 37 bytes
```
1&l:{:})?\:2%0=?v&!
;n,+1{&/,2&+1&<
```
[Try it online!](https://tio.run/##S8sszvj/31Atx6raqlbTPsbKSNXA1r5MTZFLQcE6T0fbsFpNX8dITdtQzeb///@6ZQpG5gA)
No built-ins to deal with binary representations, so a costly mod`%` loop is necessary.
A trick used here is to just let the stack grow, since that makes a counter instantly available with only a single `l` command.
[Answer]
# [PHP](https://php.net/), 44 bytes
```
fn($m)=>[$m-substr_count(decbin($m++),1),$m]
```
[Try it online!](https://tio.run/##HUy7CoMwFN3zFRe5gyEpVTqq7VToUKi7FcGYoIU8iDqVfnsas5wH5@FmF@qbmx0hqJqgTI6aNtcO9Wndx3Xzg7C72fJJinE5QsYoLylH3YeKKOtzQA0NFNXBNVySYAwofAmAFLONnkP23jIOn9WaQRphJxl3Pu5QpQMKNHVSC31X9OeIZc@hfbTD/fWsyC/8AQ "PHP – Try It Online")
It's [@xnor's formula](https://codegolf.stackexchange.com/a/209870/84624) with a minor optimization.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
BS’ạ,‘
```
A monadic Link accepting an integer which yields a pair of integers, `[numerator, denominator]`.
**[Try it online!](https://tio.run/##y0rNyan8/98p@FHDzIe7Fuo8apjx//9/Q3MA "Jelly – Try It Online")** Or see [0-40 inclusive](https://tio.run/##y0rNyan8/98p@FHDzIe7Fuo8apjx/@iew@2PmtYcnfRw5wwgDUTu//8XJealp2oY6CiYGGoCAA "Jelly – Try It Online").
---
Or, also for 6:
```
!Ḥọ2,‘
```
[Answer]
# x86\_64 machine code, 15 bytes
```
f3 48 0f b8 c7 popcnt rax,rdi # rax = number of 1's in m
48 ff c7 inc rdi # increment denominator
48 89 fe mov rsi,rdi # rsi = rdi (m + 1)
48 29 c6 sub rsi,rax # rsi = rsi (m + 1) - rax (popcount of m)
c3 ret
```
Input: `m` in `rdi`, output: `[ rsi, rdi ]`. Works for values `m <= 4294967295`.
[Try it online!](https://tio.run/##ZZHrTsMwDIV/L09hUSGGgArQuGwSTwITSlu3ipRLSVIovHyxk7IO2I8ozY7PsT/LENBU@vOqq@upVDaifg2fNsoRrOs9tmoUJY4RvYXe0/@tKBsZpWhN3EEZIr11cHKq9QB8vNgTUUYqOFTJ6JQoO@0qDUYqK/jYiQIihkiervPSQO0ahAq1@xBAP@PewTfqEp59UBeP@1VBCmOkbUAriyB9FyA61iR9LbVOSbAiqafun@Dtw/kGlO2HCO9SD/jbmUQsbRRJuWCdNOBaMOeLZ/y63yRP/joyGC@5lN4btM4oS9k@NzRCS9eZFRdolPMsxGy/eEjyuF6ScgVH5duaZm/UnnICd0u@uS2P8Y9HnhnjQLTRe0pPNK8P8gKQwP3jPRWZzg4MXRLLAtwQ09PzT66C/c/6GIbgY5ese9fXNuYmWHcgbwdToWeUZzdnbG2SXtk6QVtxbu3RIFUf8VvGmpPZMKT90PRrAxdwkxmEoZpFeYlZROcsgqu8Uu7QDZSybJV4rI540cqYPnoxTdPmdrvZ3j/cbu@@AQ "Assembly (gcc, x64, Linux) – Try It Online")
*Or original 16-bit version...*
# x86-16 machine code, ~~19~~ 17 bytes
Binary:
```
00000000: 8bd0 33db d1e8 7301 4375 f942 8bc2 2bc3 ..3...s.Cu.B..+.
00000010: c3 .
```
Listing:
```
8B D0 MOV DX, AX ; save m for denominator
33 DB XOR BX, BX ; BX is bit count of 1's
POP_COUNT:
D1 E8 SHR AX, 1 ; shift LSb into CF
73 01 JNC IS_ZERO ; if a 0, don't increment count
43 INC BX ; increment count of 1 bits
IS_ZERO:
75 F9 JNZ POP_COUNT ; if AX not 0, keep looping
42 INC DX ; increment denominator
8B C2 MOV AX, DX ; AX = DX (m + 1)
2B C3 SUB AX, BX ; AX = AX (m + 1) - BX (popcount of m)
C3 RET
```
Callable function, input `m` in `AX` output `[ AX, DX ]`. Works for values `m <= 65534` (platform max int).
Test program output:
[](https://i.stack.imgur.com/CaWAf.png)
[Answer]
# [Python 3](https://docs.python.org/3/), 76 bytes
```
lambda m:(sum(len(bin(i))-len(bin(i).strip("0"))-1 for i in range(m+1)),m+1)
```
Fraction is returned as a tuple `(numerator,denominator)`
Non-golfed version:
```
def trailing_zeroes(m):
#this is the running total for the total number of trailing zeroes
total = 0
#this loops through each the number in the range
for i in range(m+1):
#calculates number of trailing zeroes
zeroes = len(bin(i))-len(bin(i).strip("0"))-1
#adds the number of trailing zeroes to the running total
total += zeroes
#returns the numerator and the denominator as a tuple
return (total, m+1)
```
[Try it online!](https://tio.run/##K6gsycjPM/5fYRvzPycxNyklUSHXSqO4NFcjJzVPIykzTyNTU1MXwdYrLinKLNBQMlACChsqpOUXKWQqZOYpFCXmpadq5GobamrqgMj/aDKmhppWXApAUFCUmVeikalTATL4PwA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
I⟦⁻⊕θΣ⍘N²⊕θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI9o3M6@0WMMzL7koNTc1ryQ1RaNQU0chuDRXwymxODW4BKg0HShdUFriV5qblFqkAZQ10tQEkqh6YjU1rf//N/qvW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Port of @xnor's Python answer. Explanation:
```
θ Input `m` as a string
⊕ Cast to integer and increment
N Input `m` as an integer
⍘ ² Convert to base 2 as a string
Σ Sum the digits
⁻ Subtract
θ Input `m` as a string
⊕ Cast to integer and increment
⟦ Make into a list
I Cast to string
Implicitly print on separate lines
```
[Answer]
# [Io](http://iolanguage.org/), 55 bytes
```
method(I,list(I-I toBase(2)occurancesOfSeq("1")+1,I+1))
```
[Try it online!](https://tio.run/##DcuxCsIwEIDhvU9xdLqjERrdBBe3gFDQ1eWIFxuoOU3S54/55@@P2gKcL/BsH6mrvtCZLZaK7uCg6pWL4JHU@z1z8lKW8JAfjnakyRo3WaJ25/QWmLvG00zA5dZ/CJqF/QoI0QzQCxgJvjmmuqWB2h8 "Io – Try It Online")
[Answer]
# Java 8, 27 bytes
```
n->-n.bitCount(n++)+n+"/"+n
```
Port of [*@xnor*'s Python answer](https://codegolf.stackexchange.com/a/209870/52210), so make sure to upvote him as well!
[Try it online.](https://tio.run/##LY69DoJQDIV3nqJhuuQG1FXExclBFkd1uFx@UoRCoJAYw7NjEZY2zTmn3ynNaPwyfc@2Mn0PN4P0dQCQOOtyYzOIlxPgzh1SAVZdRSmyDsgLRZgcGT0bRgsxEEQwk3/2KUiQL81ArEhrT5N2d66mOVzs7ZBUYt9SY4Mp1IJVK@LxAuOtzLzplBQBjPYh4Ck6LEve/UWp9Ok5q4Nm4KCVJFekULvHJwspsAq9reE0/wA)
**Explanation:**
```
n-> // Method with Integer as parameter and String return-type
- // Take the negative value of:
n.bitCount(n++) // The amount of 1-bits in integer `n`
// (and increase `n` by 1 afterwards with `n++`)
+n // And add (the now incremented) `n` to this
+"/" // Append a "/" String
+n // And append `n`
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
âΣ~bα⌠+
```
Port of [*@xnor*'s Python answer](https://codegolf.stackexchange.com/a/209870/52210), so make sure to upvote him as well!
[Try it online.](https://tio.run/##y00syUjPz0n7///wonOL65LObXzUs0D7/38DLkMuIy5jLhMuUy4zLnMuCy5LLkMDAA)
**Explanation:**
```
â # Convert the (implicit) input-integer to a list of binary digits
Σ # Sum that list to get the amount of 1-bits
~ # Bitwise-NOT that (-n-1)
b # Push -1
α # Pair the two together
⌠ # Increment both values in the pair by 2
+ # And add the (implicit) input-integer to both
# (after which the entire stack joined together is output implicitly)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~52~~ 49 bytes
Saved 3 bytes thanks to [Mukundan314](https://codegolf.stackexchange.com/users/91267/mukundan314)!!!
```
f(int*m,int*n){*n=++*m-__builtin_popcount(*m-1);}
```
[Try it online!](https://tio.run/##JUtLCsMgEN3nFEMgQeNIm003xp6kIK3BMlAnEpJV8Ow2tm/xeF@v396XEgTxNkSszPIY2Co1RO3ca6fPRuzSkvyy8ybOdJQml/gkFvJoICxrPQPZKzJGQ9N4M0pR7U6wJfMTQfSM0Ef5t2k9T0G03Qz6Dt186eYHtwiEEBG4rnKTyxc "C (gcc) – Try It Online")
Port of [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [Python answer](https://codegolf.stackexchange.com/a/209870/9481).
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
A:1↑İr
```
[Try it online!](https://tio.run/##yygtzv6fm18erPOoqfG/o5Xho7aJRzYU/f//P9pAx1DHSMc4FgA "Husk – Try It Online") This function just takes the average of the start of the [ruler sequence](https://oeis.org/A007814).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Adapted from [xnor's solution](https://codegolf.stackexchange.com/a/209870/58974). Input is a single integer array, output is `[numerator, denominator]`.
```
ËÒ-¤è1Ãp°U
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=y9ItpOgxw3CwVQ&input=Wzhd)
[Answer]
# APL, 17 bytes
```
{⍵+1-+⌿2⊥⍣¯1⊢⍵,0}
```
The solution is not as concise as the previous ones, but it has its merits. It does not depend on the APL dialect or on the index origin. In addition, it returns the result in the intuitively expected form: nominator, denominator.
] |
[Question]
[
You have to make something that takes in one input from a default I/O method (as an integer), and prints out the sum of all the permutations of that number (not necessarily unique)
For example:
`10` would return `11` because `10` can have 2 permutations (`10` and `01`), and the sum of those two numbers would be `11`
`202` would have 6 permutations (`202`, `220`, `022`, `022`, `202`, `220`), so the sum would be `888`.
The input is positive, and the input can be taken as any type, but your program's output must be a number.
Standard loopholes are not allowed, and as usual, since this is code golf, the shortest answer in bytes wins!
[Answer]
# Japt `-x`, 1 byte
Takes input as a string.
```
á
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=4Q==&input=IjIwMiIKLXg=)
---
## Explanation
```
á :Get permutations
:Implicitly reduce by addition and output
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~10~~ 6 bytes
```
{m!1b}
```
[Try it online!](https://tio.run/##S85KzP1fWPe/OlfRMKn2f91/JUMDJQA "CJam – Try It Online")
## Explanation
```
{ } Anonymous block taking input as string on stack
m! Find all permutations
1b Implicitly convert each to integer and sum
```
[Answer]
# [Python 2](https://docs.python.org/2/), 66 bytes
```
n=s=0
P=1
for c in input():s+=int(c);n+=1;P*=n
print 10**n/9*s*P/n
```
[Try it online!](https://tio.run/##FYwxDoQgEAB7XkG3uhay3DVq9g/8gXCR5LISwaivR0wmU0wx6S7rJraea/wHTXO4ggeAKpzZKMekftuuvY7SSEfp@jkPHKV0vl9kYFocsqi0t6TJIMo4YUY3Sn03QAYUWGObyX6@8AA "Python 2 – Try It Online")
Takes input as a string.
---
# [Python 2](https://docs.python.org/2/), 70 bytes
```
f=lambda k,P=1,n=0,s=0:f(k/10,P*-~n,n+1,s+k%10)if k else 10**n/9*s*P/n
```
[Try it online!](https://tio.run/##DchBDsIgEADAe1@xFxOga9hFLzbhD3yhxpIScCWCMV78OjrHqZ@@P8SNEX1Z79fbChmDZxRP2DwtUWXLhMEcv4IyM7Y5H5h0ipBhK20DJmPEXkwzwcp476n8b6nPJB2iSlJfXWk9mCZHbmJ3Ov8A "Python 2 – Try It Online")
An arithmetic method. The base case is hard to deal with because the `/n` causes division by zero for the inital value `n=0`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
œO
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6GT///@NDIwA "05AB1E – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 30 bytes
```
*.comb.permutations>>.join.sum
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX0svOT83Sa8gtSi3tCSxJDM/r9jOTi8rPzNPr7g09781V3FipUKahpGBkeZ/AA "Perl 6 – Try It Online")
It would be nice if this was just `*.permutations.sum` but Perl 6 doesn't treat strings as lists of characters.
### Explanation
```
*.comb.permutations>>.join.sum
*.comb # Convert to list of digits
.permutations # Get all permutations of the list
>>.join # Join all lists of digits
.sum # Get the sum of all numbers
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~63~~ 62 bytes
```
f=lambda n,k=1,s=0:n>9and k*f(n/10,k+1,s+n%10)or 10**k/9*(s+n)
```
[Try it online!](https://tio.run/##TclNCoAgEEDhfadwE/gHzVgbA7uLEVJYk5ibTm9tgnaP76W7rCeZWoPb/TEvnpGODvXlYKTJelpYlIFTh6Cjel1RiyDOzBCkjJ2V/CVRU96osMBBNF/irw2Y3zD9IOoD "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~59~~ 57 bytes
```
sum(gamma(n<-nchar(x<-scan()))*x%/%10^(0:n)%%10)*10^n%/%9
```
[Try it online!](https://tio.run/##K/r/v7g0VyM9MTc3USPPRjcvOSOxSKPCRrc4OTFPQ1NTU6tCVV/V0CBOw8AqT1MVyNLUAvLygIKW/40MjP4DAA "R – Try It Online")
Mathematical approach suggested by Peter Taylor and decribed by [Arnauld](https://codegolf.stackexchange.com/a/174347/78274).
-2 bytes by J. Doe.
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 35 bytes
```
:digits|:permutation|:sum+(:join|Z)
```
[Try it online!](https://tio.run/##y9ItTar8n2b73yolMz2zpLjGqiC1KLe0JLEkMz@vxqq4NFdbwyorPzOvJkrzf4FCmp6GkYGR5n8A "J-uby – Try It Online")
-3 from Jordan.
[Answer]
# [J](http://jsoftware.com/), 18 bytes
```
1#.(A.~i.@!@#)&.":
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N9QWU/DUa8uU89B0UFZU01Pyeq/JpeSnoJ6mq2euoKOQq2VQloxFxdXanJGvkKagqGBgoICjGNkYPQfAA "J – Try It Online")
## Explanation:
```
": - convert to string
&. - do the verbs in () then convert back to number
i. - make a list from 0 to
@! - factorial
@# - of the number of digits in the input
A.~ - find all permutations, using the list above as permutation index
1#. - find the sum by base-1 convertion
```
## Alternative:
Using the formula suggested by Peter Taylor:
# [J](http://jsoftware.com/), 30 bytes
```
1#.("."0*9%~!@<:@#*_1+10^#)@":
```
[Try it online!](https://tio.run/##NcexCoAgFAXQ/X3FTQnT4vF0SxL8khoiiZYG5/p1mzrbuVqpiSGIkOY1D4qVuLl/u7zErN3mRy@rtlnFZkkxTElsMOGJKJWIjv28UeAFwJ8goX0 "J – Try It Online")
[Answer]
# JavaScript (ES6), 53 bytes
Recursive version, inspired by @tsh.
```
f=(n,s=i=0,p='')=>n?(i++||1)*f(n/10|0,s+n%10,p+1):s*p
```
[Try it online!](https://tio.run/##ZcrBCsIwDIDhu@8hS9aqSR0IQvRZxlylMtJixFPfve4qg//08b/G72jTO5XPQfNjblHWQL1JEvJFug7lpndIztXK2EfQE1Mlb073vB6O8Wp9aVNWy8t8XPITIlwQd//CtKFAYbuF84DYfg "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~61~~ 60 bytes
*Saved 1 byte thanks to @l4m2*
```
n=>![...n+(x=s=p='')].map((d,i)=>(p+=1,x=x*i||1,s-=d))-s*p*x
```
[Try it online!](https://tio.run/##ZcqxDsIgEADQ3b9w6h2FS0GTTtcfMQ6ktAZT4SLGMPTfcTZdX97Tf32Z31E@JuWwtJVb4ul8I6LUQ@XCwl2Hd3p5AQg6Ik8gPVtduaq471YXwwHRFCWqtjmnkreFtvyAFUbE07/Y4UBucMfmLlfE9gM "JavaScript (Node.js) – Try It Online")
### How?
This is based on the formula suggested by [Peter Taylor](https://codegolf.stackexchange.com/users/194/peter-taylor) in the sandbox:
$$\left(\sum\_{i=1}^n{a\_i}\right)\frac{10^n-1}{9}(n-1)!$$
where \$a\_i\$ is the \$i\$th digit of the input number and \$n\$ is the total number of digits.
The result of the expression \$(10^n-1)/9\$ is a number consisting of the digit \$1\$ repeated \$n\$ times, which is what is computed in \$p\$. The factorial is stored in \$x\$ and the opposite of the sum is stored in \$s\$.
[Answer]
# [Haskell](https://www.haskell.org/), 62 bytes
```
import Data.List
f::Int->Int
f=sum.map read.permutations.show
```
Unfortunately, `f` must be annotated with a type to avoid ambiguity.
[Answer]
# [MY](https://bitbucket.org/zacharyjtaylor/my-language), 12 bytes
```
⍞℘⌊Σ88ǵ'ƒ⇥(↵
```
[Try it online!](https://tio.run/##ASIA3f9tef//4o2e4oSY4oyKzqM4OMe1J8aS4oelKOKGtf//MjAy "MY – Try It Online")
Some of MY's stupid builtin decisions are coming in handy.
```
⍞℘⌊Σ88ǵ'ƒ⇥(↵
⍞ Input
℘ 's permutations
⌊ as integers.
Σ Sum of that
88ǵ'ƒ⇥( to standard base 10 form
↵ output.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 76 bytes
```
s=map(int,`input()`);n=len(s);t=sum(s)*int('1'*n)
while~-n:n-=1;t*=n
print t
```
[Try it online!](https://tio.run/##JY3BCoMwEETP5itySyIVTNqTkqO99tIP0NoFpbqGdaX10l9PI70MD94wE3YeFnSxX57gSSkVVz93QY/Ip3bEsLE2ranRT4B6NTX7dZsT5KmglVU5GvEexgm@BVZYeFtz7lEESl5yTIPi7@WdNqhExrSnzOADvTxORcIeAsvmdm2IFjrsg6B7RVsKVzph3fnyAw "Python 2 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-nl`, 41 bytes
```
p$_.chars.permutation.sum{|x|x.join.to_i}
```
[Try it online!](https://tio.run/##KypNqvz/v0AlXi85I7GoWK8gtSi3tCSxJDM/T6@4NLe6pqKmQi8rPzNPryQ/PrP2/39DAy4jA6N/@QUgJcX/dfNyAA "Ruby – Try It Online")
Full program taking input from stdin.
## [Ruby](https://www.ruby-lang.org/), 45 bytes
```
->n{n.digits.permutation.sum{|x|x.join.to_i}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOk8vJTM9s6RYryC1KLe0JLEkMz9Pr7g0t7qmoqZCLys/M0@vJD8@s7b2f4FCWrShQSwXiDYyMIr9DwA "Ruby – Try It Online")
Function taking input as integer. `digits` can be shortened to `chars` if input is acceptable as string, and `chars` can be completely removed if input is an array of characters.
[Answer]
# [Python 2](https://docs.python.org/2/), 76 bytes
```
lambda x:sum(map(int,x))*int('1'*len(x))*reduce(int.__mul__,range(1,len(x)))
```
[Try it online!](https://tio.run/##LYvBCsMgEER/ZW@7BinR9hTonxTEJtoKuhETIf16Y6CXGR7zJv/278q6eXjCq0Wb3ouFY9pqomQzBd7lIcTQm1DhEB3TxcUtdXbXfDMm1WiMLJY/jpT8K6L5tUCAwIBqRIl61D2Vvj9wyqU/wVMQ7QQ "Python 2 – Try It Online")
[xnor's answer](https://codegolf.stackexchange.com/a/174349/76162) is shorter, but I thought I'd have a go at a one-liner
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
DŒ!ḌS
```
[Try it online!](https://tio.run/##y0rNyan8/9/l6CTFhzt6gv///29kYAQA "Jelly – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
I↨χEθΠEθ∨μΣθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwymxOFXD0EBHwTexQKNQRyGgKD@lNLlEA8r1L9LI1VEILs3VKNSEAuv//40MjP7rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Based on Peter Taylor's formula. `ΠEθμ` doesn't quite calculate \$ (n - 1)! \$ as Charcoal's indices range from \$ 0 \$ to \$ n - 1 \$ so `∨` is used to replace the \$ 0 \$ with the sum of digits of the input, thus implicitly multiplying the two. The outer mapping then creates an array of the length of the original input with that product as elements which is then passed to base 10 conversion which effectively multiplies the product by the appropriate repunit.
```
θ Input
E Map over characters
θ Input
E Map over characters
μ Current index
∨ Logical Or
θ Input
Σ Digital sum
Π Product
χ Predefined variable 10
↨ Base conversion
I Cast to string
Implicitly print
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~89~~ 71 bytes
```
g(x,s,p,f,i){for(s=x%10,p=f=i=1;x/=10;s+=x%10)p=p*10+1,f*=i++;x=s*p*f;}
```
[Try it online!](https://tio.run/##bctBC4MgGMbx8/oU0gg0bdMu23Dua@yyS1i2F8okDYLoq89F547P7@Gvi1brGFs8M88cMwzIYoYRezVngjOnjAIl5HxVgktPdyVOuVxwKpjJFVAqZ@Vzlxu5xjNY3U11g54@1DBcvq8EbEB9BRYTtCQnN27b4DSrPzZlqMWcEHnAt2N@3I@95OV@jE2YRou4TNb406arWh@Ltx0K6F0HGkKxhX8 "C (gcc) – Try It Online")
-18 bytes thanks to @nwellnhof
[Answer]
# APL(NARS), 25 chars, 50 bytes
```
{+/10⊥⍉⍎¨w[110 1‼↑⍴w←⍕⍵]}
```
test:
```
f←{+/10⊥⍉⍎¨w[110 1‼↑⍴w←⍕⍵]}
f¨202 1024 505
888 46662 2220
```
110 1‼k would return as built in all the permutations of 1..k .
[Answer]
# Scala (74 bytes)
```
def%(i:Int)=s"$i".indices.permutations.map(_.map(i+"").mkString.toInt).sum
```
[Try it online](https://tio.run/##RYuxCsIwEEB3vyIECwnCUTsKDo4dnPwAiekpp80l9K4giN8eq4vLg/fgSQxjqPlyx6jmGIgNPhV5EHMoxbzqgNfG0a5n9Xuxa7JAPFBEgYJTmjUoZRZIobjzj7Sx1kN6nHQivoHm7woyp1qWoCO7xnVt5/3q79t20Xf9AA)
Since permutation on digits will drop the repeated digits, we have to permute on indices.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~5~~ 4 bytes
```
sv.p
```
[Try it online!](https://tio.run/##K6gsyfj/v7hMr@D/fyUjAyMlAA "Pyth – Try It Online") Takes input as a string.
Explanation:
```
sv.pQ - Full program. Implicit Q added.
Q - Input
.p - All permutations of it
v - Evaluate each (list of strings into integers)
s - Sum the list
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 4 bytes
```
ǰᒆƖƩ
```
[Try it online!](https://tio.run/##K6gs@f//@IaHk9qOTTu28v9/IwMjAA "Pyt – Try It Online")
**Explanation:**
```
Implicit input
ǰ Join (becomes string)
ᒆ All permutations of it
Ɩ List of strings to int
Ʃ Sum the array
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `Ṡs`, 3 bytes
```
ṖvI
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=%E1%B9%A0s&code=%E1%B9%96vI&inputs=123&header=&footer=)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
pᶠ+
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v@DhtgXa//8bGRj9jwIA "Brachylog – Try It Online")
### Explanation
```
ᶠ Find all:
p permutations
+ Sum
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
ṁdPd
```
[Try it online!](https://tio.run/##yygtzv7//@HOxpSAlP///xsZGAEA "Husk – Try It Online")
### Explanation
```
ṁdPd
d digits of input
P get all permutations
ṁ (flat/concat/sum)-map
d interpret as digits
```
[Answer]
# [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), 111 bytes
[Try it online!](https://tio.run/##Xcq9CsIwEADg3acoBIKCmppdySCC4FCkTkeGQy8/YBJMr88fBcHB8YMvIQdKyPGOze3bWBifcKolHaOPPCmzHKimmT@j5AmEVdsxVMIHiM3hnJk81W81QtuVlXDL8TUTWKnMFbMnc6HsOZi/vO6Elc2B7rXtlBpqzLxwsOt/am8)
```
Total[FromDigits/@(Permutations[#]/.Thread[#->IntegerDigits@#2])]&[Unique[]&/@Range@Length@IntegerDigits@#, #]&
```
---
Appendix:
Don't allow duplicate(i.e. Multinomial Permutation) \$\quad \$ (50 bytes). [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyS/JDEn2q0oP9clMz2zpFjfISC1KLe0BKggP6842jOvJDU9tQgiF60cGxur9j8t2sjAKFZBXz@gKDOvhCst2tAAzvsPAA)
```
Total[FromDigits/@Permutations[IntegerDigits[#]]]&
```
[Answer]
# [Racket](https://racket-lang.org) -- 93 bytes
```
#!racket
(for/sum([l(permutations(string->list(~a(read))))])(string->number(apply string l)))
```
[Try it online!](https://tio.run/##K0pMzk4t@f9fWbEIzOLSSMsv0i8uzdWIztEoSC3KLS1JLMnMzyvWKC4pysxL17XLySwu0ahL1ChKTUzRBIJYTbhUXmluUmqRRmJBQU6lAkRQIQeo5P9/IwMjAA "Racket – Try It Online")
---
## Explanation
User input is a number. We split the number into its individual digits and then we permutate the list of digits. We loop through all the permutations and rejoin them to form a number. Once we have iterated through the entire list, we return the sum of resulting numbers of the permutations.
```
#lang racket
(for/sum ([lst (permutations (string->list (~a (read))))])
(string->number (apply string lst)))
```
Let's do an example with input `50`.
1. Split input into separate digits: `'(5 0)`
2. Obtain all permutations of digits: `'((5 0) (0 5))`
3. Convert all permutations back into numbers: `'(50 05)` or `'(50 5)`
4. Once all permutations are numbers, add the numbers together: `(+ 50 5)`
5. Return the sum: `55`
] |
[Question]
[
This is a [code-shuffleboard](/questions/tagged/code-shuffleboard "show questions tagged 'code-shuffleboard'") [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") challenge, where the answers will aim to, together, output the lyrics to [this](https://www.youtube.com/watch?v=dQw4w9WgXcQ) beloved 80s song.
[This](https://tio.run/##7ZTPTsMwDMbveQrftkl7iUlIUy9wRBzTxW3KUnvKn1V9@uGkG6xD3EBigltlO19@/r6owelgMZxOz7jwCMQQotfUog8QGRwfUb1wgj3xANEi@OQwgCYDgcEwVGoDTXIOdtz3XeyR4iLAYHWEatHLkY72HbXATdEZODlDiwgtxtwM0HjuRW8EFnkPbRpVBa8pRBg0kYaIIj7KUSsEWbJBdKKothyjhl7vsbQTGYGOQqbUIx6zFOfzbXc8DxxmdScAuWx4oFnDJwLtWfTKmgYD@jI6m3q/d@fHWSPoUb7Y1CPO6mUPubbDImvTWVSJ80KYDSZAvbNnIxr22WLHsqo458Gi9tnbGlEAdza7WqeYmzm6yJKdHXNqGaGLqqLQGYQBoRbJKcIczEWj5RIMCcFHvq3uJ8ChPIiJ/eAmxY3Uu6asrcMeZPI2lAfO4ZZd@@LPBa2WtilwiHcW0F3BLp/Yrq8xV1@VVp8WWwPdVNRy@w3Hrp74b3/hf@zf8w/7M7Cn0xs) is the full lyrics of the song, line by line. The first answer will contain a program that will output the first line of the song (`We're no strangers to love`). The second will do the same, but for the second line (`You know the rules and so do I`) and so on. Some answers (the 7th, 14th, 22nd, 29th, 36th, 45th, 51st, 54th, 61st and 68th) will output a blank line.
Each answers' program, however, must be **irreducible**, meaning that it must not output the correct line if any non-zero number of characters (not necessarily consecutive) are removed.
* `print("We're no strangers to love")` is an irreducible Answer 1 in Python 3
* `if 1: print("We're no strangers to love")` is not, as we can remove `if 1:` and it'll still output the first line
* `print("We're no str" + "angers t" + "o love")` is also not, as the two `" + "`s can be removed, and it'll still produce the correct output.
---
Let \$\bar x\_i\$ be the arithmetic mean of the lengths of the first \$i\$ lines, to 1 decimal place. This sequence begins \$26, 28, 32, 34, 34.6, 33\$ and converges to \$\bar x\_{74} = 24.3\$ by the end of the song. Each answer has a score, which will eventually determine the overall winner. The score for the \$i\$th answer is defined as:
>
> If the \$i\$th answer is \$n\$ bytes long, its score is \$|n - \bar x\_i|\$
>
>
>
So, if the first answer is 10 bytes long, its score is \$16\$, and if the 72nd answer is 2 bytes long, its score is \$|2 - 24.2| = 22.2\$. A user's overall score is the arithmetic mean of the scores of all their answers. The user with the lowest overall score wins.
[The full sequence](https://tio.run/##7ZRNThwxEIX3PkXtBiQ2OQIS0mg2YRll6R5Xt5uxq5B/ptUXQJyAEyBOwCpZgrgHJ@mUPQOhQdklUhDsWlXl56/es/oMnRun6fHn7eOPy7sL/3B9dxO@3F8tp2n6houAQAwxBU0dhgiJwfEW1XfOsCEeIFmEkB1G0GQgMhiGlTqGNjsHa/a@Tx4pLSIMVidYLbwc6WnTUwfcVp2BszO0SNBhKs0IbWAveiOwyAfo8qhWcJZjgkETaUgCDaMctUJQJFtEJ4pqySlp8HqDtZ3JCHQSMqW@4rZIcTnf9dv9wPms7gSglA0PNGuETKADi15d02DEUEdnU8/3rsM4a0Q9yhebZsRZve4h1/ZYZW3eiypxXgiLwQSo13ZvRMuhWOxYVhXnAljUoXjbIArg2hZXm5xKs0SXWLKzY0mtIPRJrSj2BmFAaERyF2EJ5kmj4xoMCcHvfDvtd4BDfRA79nO3UzyWet/WtXXcgEy@DuWES7h1V1/9eUJrpG0qHOI7C@hdwR6csj16iXn4p9Lhm8WOgF5V1MHyLxx78cT/9xf@wf49n7D/BvYX) of \$\bar x\_i\$; the left column is \$i\$, the right is \$\bar x\_i\$. Collapse the "Arguments" element for easier viewing.
---
### Rules
* You may either:
+ Output the line to STDOUT, or your language's closest alternative; or,
+ Return the line from a function
* You should take no input, aside from an [optional empty input](https://codegolf.meta.stackexchange.com/q/12681/66833)
* Each language may only be used once. This includes different versions of a language, such as Python 2 and Python 3. Generally, if two languages are considered versions of each other, such as [Seriously and Actually](https://github.com/Mego/Seriously), then only one is allowed to be used.
* You may not post 2 answers in a row
* You must wait 1 hour between answers
* The challenge will end when the 74th answer is posted, at which point I will accept an answer of the winner's choice
---
Please format your answer as the following:
```
# [Num]. [Lang], score [score]
code
[Try it online!]
[Everything else]
```
[Answer]
# 4. [Husk](https://github.com/barbuz/Husk), score 0
```
¨You wouldn't get this fromȦ?ØoĠÜy
```
[Try it online!](https://tio.run/##yygtzv7//9CKyPxShfL80pyUPPUShfTUEoWSjMxihbSi/NwTy@wPz8g/suDwnMr//wE "Husk – Try It Online")
Just wanted to use Husk before someone else could steal it. Simply a (partially) compressed string.
[Answer]
# 7. [Subleq](https://esolangs.org/wiki/Subleq), 28 bytes (7 32-bit words), score 0.3
```
6 3 3
0 0 3
4
```
[Subleq Emulator](http://mazonka.com/subleq/online/hsqjs.cgi)
I am new to Subleq so hopefully this is right. The first line changes the 3 in address 5 to -1 which makes the second line exit producing no output. Deleting a word causes an infinite loop. For example, 0 0 0 goes to 0.
[Answer]
# 2. [05AB1E](https://github.com/Adriandmen/05AB1E), score 0
```
“Youƒ€ the rules and so do I
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcOcyPzSY5MeNa1RKMlIVSgqzUktVkjMS1EozldIyVfw/P8fAA "05AB1E – Try It Online")
```
“... # trimmed program
“... # push "You know the rules and so do I"
# implicit output
```
I accidentally opened Settings (Win+I) while typing this explanation.
[Answer]
# 1. [Jelly](https://github.com/DennisMitchell/jelly), score 0
```
“ŒßỤẸ:IŀėṪƝƓɠi?ṅRṭḄṁ3Ġ»ḣ26
```
[Try it online!](https://tio.run/##AT4Awf9qZWxsef//4oCcxZLDn@G7pOG6uDpJxYDEl@G5qsadxpPJoGk/4bmFUuG5reG4hOG5gTPEoMK74bijMjb//w "Jelly – Try It Online")
```
“ŒßỤẸ:IŀėṪƝƓɠi?ṅRṭḄṁ3Ġ» We're no strangers to love abcd
ḣ26 first 26 chars
```
[Answer]
# 3. [Vyxal](https://github.com/Lyxal/Vyxal), score 0
```
`A ƛ‡ commitment's w∷⟇ I'm ʀ¨ of
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60A%20%C6%9B%E2%80%A1%20commitment%27s%20w%E2%88%B7%E2%9F%87%20I%27m%20%CA%80%C2%A8%20of&inputs=&header=&footer=)
[Answer]
# 5. [Labyrinth](https://github.com/m-ender/labyrinth), 131 bytes, score 96.4
```
73.32.106.117.115.116.32.119.97.110:..97.32.116.101.108:..32.121.111.117.32.104.111.119.32.73.39.109.32.102.101:..108.105.110.103.@
```
[Try it online!](https://tio.run/##LY0xDoAwDAN/FMUtFMLEV2ACCTEgFl4fnMBwan2tk2NZn2s/7819qFKLQJsAA@lJSwUTC6OTxCUVfynISBeiMABZzSndHy1ijDZK@94CsMc2iT3Ks8rs/gI "Labyrinth – Try It Online")
Here goes a suboptimal language choice, as it can't win against those zero scores anyway.
It is hard to reuse a number in Labyrinth (except for adjacent ones) because each digit command alters the current top of the stack, rather than pushing a new number.
[Answer]
# 10. [Japt](https://github.com/ETHproductions/japt), 29 bytes, score 0.8
```
`Nev€ gna run ÂИ „d Ürt yŒ
```
[Try it online!](https://tio.run/##AS0A0v9qYXB0//9gTmV2woAgZ8KNbmEgcnVuIMOCw5DCmCDChGQgw5wYcnQgecKM//8 "Japt – Try It Online")
Just compressed the string, outputs `Never gonna run around and desert you`
Somehow the compressor is very nice and fits my need, exactly 28 bytes of string while compressed and adding a leading backtick to decompress gives 29 bytes, then leading to a nice optimal score
Though I think the HTML trick was better
[Answer]
# 9. [R](https://www.r-project.org/) version >= 4.1, Score 1.8
```
\()"Never gonna let you down"
```
A function taking no arguments and returning a string. No TIO link because R 4.1 isn’t yet on TIO.
Apologies for getting the wrong line initially!
[Answer]
# 12. [HTML](https://html.spec.whatwg.org/), score 1.7909090909090892
```
Never gonna say goodbye
```
I deleted my older HTML answer 1 hour ago so posting this now
[Answer]
# Line 14, `" "`
# [Python 3](https://docs.python.org/3/), 0 bytes, score 26
```
[nothing here]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EIzmjSMPQQFPz////JgYGAA "Python 3 – Try It Online")
Gotta get Python in here somewhere.
[Answer]
# 8. [Splinter](https://esolangs.org/wiki/Splinter), Score 18.4
```
\N\e\v\e\r\ \g\o\n\n\a\ \g\i\v\e\ \y\o\u\ \u\p
```
[Try it online!](https://deadfish.surge.sh/splinter#XE5cZVx2XGVcclwgXGdcb1xuXG5cYVwgXGdcaVx2XGVcIFx5XG9cdVwgXHVccA==)
Note: Apologies for the edit, I thought we were aiming for a higher score.
**this** outputs `Never gonna give you up`
[Answer]
# 11. Unary, 25247105318448659498226527583287720106787200954491263487845422435915430598123234439645367425137855414888675036 bytes - Score very close to that
Since it's impossible to beat those 0-pointers...
Compiles to `+[>>>-[-->+<<+<]<<+]>+++.<<<<+++.>.<.<<.>------.>++.<<---.-..>>------.<.>++++++.++.>.<----.<.>>+++.<<<+.++++++.>.<.-----.` in brainfrick - [Try it online!](https://tio.run/##NYxRCoAwDEMPFJoTlFxk7EMFQQQ/BM9f143mIw2vJPu7Xc/5HXcEmiRrZoI7vA/rAkAfyiv6yJRNUfOVyUgV9eQprkbBWkqOWluViB8 "brainfuck – Try It Online")
[Answer]
# 15. [Stax](https://github.com/tomtheisen/stax), score 0.5
```
üy ♫ε╖nÖG°∟2♦︎½►±ç╧∟X)÷A•σ←
```
[Run and debug it](https://staxlang.xyz/#p=8179200eeeb76e9947f81c3204ab10f187cf1c5829f64107e51b&i=)
Prints “We've known each other for so long”.
[Answer]
# 6. [JavaScript (Node.js)](https://nodejs.org), score 0
```
_=>'Gotta make you '+"understand"
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1k7dPb@kJFEhNzE7VaEyv1RBXVupNC8ltai4JDEvRel/cn5ecX5Oql5OfrpGmoam5n8A "JavaScript (Node.js) – Try It Online")
```
_=>'...'+"..." # trimmed program
_=> # return function taking an optional argument _ that returns...
'...' # literal...
+ # concatenated with...
"..." # literal
```
[Answer]
# 20. [Bubblegum](https://esolangs.org/wiki/Bubblegum), score 1.1
```
00000000: e54c 1a26 90b8 f59b c710 0b14 f216 4647 .L.&..........FG
00000010: e7b7 bf31 1a85 6a0a 7a05 e8 ...1..j.z..
```
[Try it online!](https://tio.run/##VcwxDoMwDEbhnVP8E6NlQxIHDtAuXCJGCRKiI0svH0CtkPj292w32/Kyf2rlvxHZuxmSuoCBLaL4wTCrMNjEoXQS4IJTgCZq6fZ6N7@DXA81hZVezlH0CIkTNLFHjng4QyFa6UtU6wE "Bubblegum – Try It Online")
Uses the BB96 encoding to encode "And if you ask me how I'm feeling"
[Answer]
## 24. [Excel](https://www.microsoft.com/en-us/microsoft-365/excel), Score ~~0~~ 3
```
Never gonna let you down
```
*+3 score due to reducibility error*
[Answer]
# 19. [Grok](https://github.com/AMiller42/Grok-Language), 50 bytes, score 22.1
```
hqj`ti yalp annog er'ew dna emag eht wonk eWi
W{lY
```
[Try it Online!](http://grok.pythonanywhere.com?flags=&code=hqj%60ti%20yalp%20annog%20er%27ew%20dna%20emag%20eht%20wonk%20eWi%0AW%7BlY&inputs=)
Explanation:
```
h # Start the IP moving left
`ti yalp annog er'ew dna emag eht wonk eWi # Push the string 'We know the game and we're gonna play it' to the stack.
j # Change the IP to move down
l # Change the IP to move right
Y # Duplicate the top of the stack to the register
W # Print the value in the register as a character
{ # If the top of the stack is 0, rotate IP direction clockwise
q # Terminate program
```
[Answer]
# 13. [DOG](https://esolangs.org/wiki/DOG), Score 15
```
bark "Never gonna tell a lie and hurt you "
```
I can't figure out how to adapt the interpreter to TIO, so you'll have to download it.
[Answer]
# 16. [PHP](https://php.net/), 34 bytes, Score 7.4
```
<?="Your heart's been aching but";
```
[Try it online!](https://tio.run/##K8go@P/fxt5WKTK/tEghIzWxqES9WCEpNTVPITE5IzMvXSGptETJ@v9/AA "PHP – Try It Online")
PHP was of course needed here, for this very difficult line, and it has not enough pride left to care so much about its score anymore!
[Answer]
# 17. [Underload](https://github.com/catseye/stringie), score 0.5
```
(You're too shy to say it)S
```
[Try it online!](https://tio.run/##K81LSS3KyU9M@f9fIzK/VL0oVaEkP1@hOKMSSCsUJ1YqZJZoBv//DwA "Underload – Try It Online")
Fairly simple.
```
(You're too shy to say it)S
(You're too shy to say it) Push this string to the top of the stack.
S Print the top of the stack.
```
[Answer]
# 21. [COW](https://esolangs.org/wiki/COW), Score 4474.4
```
OOOMoOMoOMoOMoOMoOMoOMoOMoOMMMmoOMMMMMMmoOMMMMOOMOomOoMoOmoOmoomOoMMMmoOMMMMMMmoOMMMMOOMOomOoMoOmoOmoomOoMMMmoOMMMMMMmoOMMMMOOMOomOoMoOmoOmooOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomOomOomOoMMMmoOmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOomOomOoMMMmoOmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomOomOomOoMMMmoOmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOomOomOoMMMmoOmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOomOomOoMMMmoOmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomOomOomOoMMMmoOmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomOomOomOoMMMmoOmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomOomOomOoMMMmoOmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOomOomOoMMMmoOmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomOomOomOoMMMmoOmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOomOomOoMMMmoOmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOomOomOoMMMmoOmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomOomOomOoMMMmoOmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOomOomOoMMMmoOmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomOomOomOoMMMmoOmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoomOoOOOmoOOOOmOomOoMMMmoOMMMMOOMOomoOMoOmOomoomOomOoMMMmoOmoOMMMMOOMOomoOMoOmOomoomoOMoOMoOMoOMoOMoOMoomOo
```
[Try it online](https://frank-buss.de/cow.html)(program will need to be pasted in)
Outputs `Don't tell me you're too blind to see`
[Answer]
# 22. [C# (.NET Core)](https://www.microsoft.com/net/core/platform), score 1.7
```
class P{static void Main(){}}
```
[Try it online!](https://tio.run/##Sy7WTc4vSv3/PzknsbhYIaC6uCSxJDNZoSw/M0XBNzEzT0Ozurb2/38A "C# (.NET Core) – Try It Online")
A minimal C# program that does nothing. I think any less than this and there’s no valid entry point.
[Answer]
# 25. [Quarterstaff](https://github.com/Destructible-Watermelon/Quarterstaff), score 98.6
```
111>o101>a110>b114>r78!a!118!a!r!32!103!o!b!b!97!32!r!117!b!32!97!r!o!117!b!100!32!97!b!100!32!100!a!115!a!r!116!32!121!o!117!
```
[Try it online!](https://tio.run/##PYxRDoAgDEPPshusoKI/3AUS@SVOPD9uSMySra/Nej1J2il3S6X0DiBWMGICOGZgiRJ2SgTYFvKOwJ4qZZ0jGIuGQUmlGqLZx2Ce3q/tWNc6uoBtmA7zp/cX "Quarterstaff – Try It Online")
[Answer]
# 18. Deadfish~, 291.8 score
```
{{i}ddd}iiic{iiii}dddciiiiic{d}cdddddcic{{d}iii}ic{{i}d}dddc{dd}iic{{d}iii}ic{iiiiii}iiiiiic{i}iiiciiiiic{d}ddc{{d}iii}ddc{{i}ddd}iiiiiciiicic{i}ddc{{d}i}iiic{{i}d}dddc{d}dddddc{d}iiic{ii}dc{{d}ii}iiic{{i}ddd}iiiiiic{{d}ii}dddc{iiiiii}iiiiiiciiicc{i}dc{{d}ii}iic{{i}ddd}ic{i}ddcddddddciiiiic{d}iiic{{d}iii}dc{{i}dd}dcdc
```
[Try it online!](https://deadfish.surge.sh/#Wksd9XuybL/6Jgv/gJvZ//4m3oqbL7/5v6Tb0VMBQJlEBN7/NvRf5sv/oIImX+beqJsvv/m9//83omL5t6UTZf/QJt6X/zAUCCTL5t6Umy/+pl/n//8BN6Jt6L5sv988)
[Answer]
# 23. [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak),Score 4370.9
```
(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0NDc3hDzWHvQ2r6dTS0Rv03mgNGQ2PUt6N@Gs2fo7E66rvRVsNoiTNae476ZdS3o37R/P//v64jAA "Brain-Flak – Try It Online")
Sorry about the mess. I have no idea how to efficiently get large numbers in Brain-flak.
Outputs `Never gonna give you up`
] |
[Question]
[
## The Challenge
Given a [rational number](https://en.wikipedia.org/wiki/Rational_number), determine the smallest number which is a positive integer multiple of it. Eg.
```
Given: 1.25
x1: 1.25
x2: 2.5
x3: 3.75
x4: 5
Thus: Answer is 5
```
## Clarifications
Inputs will be a rational number in the range of `(0,100]` of which the Decimal Representation has no more than 4 digits after the point.
Output must be an integer that is the total after multiplication (`5` in the example, rather than `4`).
I/O may be in any [Standard Format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), including as a Fraction type.
Be careful if using repeated addition with floats, as `0.3 + 0.3...` results in `2.9999...`.
## Test Cases
```
1.25 -> 5
4.0 -> 4
0.3 -> 3
4.625 -> 37
3.1428 -> 7857
```
## Rules
* [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 fewest bytes wins!
* Have Fun!
[Answer]
# [Vyxal 2.4.1](https://github.com/Vyxal/Vyxal), 2 bytes
```
ƒh
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C6%92h&inputs=0.3&header=&footer=)
A version downgrade improves my byte count somehow.
Well not somehow. 2.4.1 and earlier versions didn't use exact numbers/rationals under the hood, so there was still a "convert decimal to numerator and denominator" built-in (because I've always wanted some form of rationals).
This is a back port of the Factor answer which half ported my original answer.
Takes input as floats because, well, only float input was supported in 2.4.1.
Converts to numerator, denominator. Then gets the first item of that.
## [Vyxal >=2.6](https://github.com/Vyxal/Vyxal), 35 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.375 bytes
```
S\//h
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBPSIsIiIsIlNcXC8vaCIsIiIsIjEuMjVcbjAuMzMzMzMzMzMzM1xuMC4zXG40XG40LjYyNSJd)
Maths? No thank you!
Takes input as either a fraction object or a float. Both are interpreted as rational implicitly so it doesn't really matter.
Simply casts input to string (which'll be a fraction because vyxal 2 be like that), split on `/` and get the first item.
[Answer]
# [J](https://www.jsoftware.com), 4 bytes
```
1&*.
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8EuJT0FdYU0BVsrBXUdBQMFKyDW1VNwDvJxW1pakqZrscRQTUsPwrzpq8mVmpyRD1RuqGdkCmOb6BkYGMA4BnrGCHEzhCKgBmMTFI4hxNAFCyA0AA)
LCM with 1 to get the numerator of a fractional value.
J has a built-in to extract the numerator/denominator from a number too, but is longer to get just the numerator:
# [J](https://www.jsoftware.com), 6 bytes
```
0{2&x:
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8EuJT0FdYU0BVsrBXUdBQMFKyDW1VNwDvJxW1pakqZrscyg2kitwgrCuemryZWanJEP1GCoZ2QKY5voGRgYwDgGesYIcTOEIqAGYxMUjiHE0AULIDQA)
[Answer]
# Excel, 37 bytes
```
=0+TEXTBEFORE(TEXT(A1,"0/00000"),"/")
```
Input in cell `A1`.
[Answer]
# [Factor](https://factorcode.org), 9 bytes
```
numerator
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70sLTG5JL9owU2F0GBPP3crhdzEkgyFgqLUkpLKgqLMvBIFay4uE21TfYulpSVpuhYr80pzU4sSgVog_IV6EHrBAggNAA)
Same idea as lyxal's [Vyxal answer](https://codegolf.stackexchange.com/a/265234/97916), just no need for string manipulation.
Less "cheaty," perhaps? This version takes floats as input instead of ratios:
---
# [Factor](https://factorcode.org) + `math.floating-point`, 26 bytes
```
[ double>ratio numerator ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70sLTG5JL9owU3r0GBPP3crhezUorzUHIXcxJIMhYKi1JKSyoKizLwSsIBeWk5-YklmXrpuQT5IzJqLy0TPzMh0aWlJmq7FrmiFlPzSpJxUuyKgonyFvNLcVCArv0ghFqJgWXJiTo6CHoSzYAGEBgA)
And my original answer for posterity:
---
# [Factor](https://factorcode.org), 34 bytes
```
[ 0 [ 1 + 2dup * ratio? ] loop * ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70sLTG5JL9owc2g0GBPP3crhdzEkgyF7NSivNQcheLUwtLUvOTUYoWCotSSksqCosy8EgVrLq5qLgUgMNQ21DcBsyCksb6hAYSrbapvwVW7tLQkTdfiplK0goFCtIKhgraCUUppgYKWQlFiSWa-vUKsQk5-PogfC1G5NDexQEEPwl6wAEIDAA)
* `0` push zero — this is our multiplier
* `[ ... ratio? ] loop` do `...` while top of stack is a ratio (a number like 5/5 promotes itself to integer automatically)
* `1 +` increment the multiplier
* `2dup *` multiply but keep the input and multiplier on the stack too
* `*` at this point, the input and correct multiplier are on the stack so multiply them
[Answer]
# [Julia](https://julialang.org), 11 bytes
```
~x=lcm(x,1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FqvrKmxzknM1KnQMNSEiN6uUFVwrEnMLclK5HIoz8ssV6jTM9fVNDTS5uJQVQlKLS4q5HBKLi1OLSoAypvr6JpoKtrYKpkiCJvr6hmBBEyRBY6CgAVhUwRhZGGi2BVTYHOICmNsA)
Takes [rational number](https://docs.julialang.org/en/v1/manual/complex-and-rational-numbers/#Rational-Numbers) inputs. Julia also has the function `rationalize` for converting floating point values.
# [Julia 0.6](http://julialang.org/), 33 bytes
```
>(x,i=1)=isinteger(i*x)?i*x:x>i+1
```
[Try it online!](https://tio.run/##yyrNyUw0@//fTqNCJ9PWUNM2szgzryQ1PbVII1OrQtMeSFhV2GVqG/5XVnCtSMwtyEnlcijOyC9XsNMw0DM00eTiUlYISS0uKeZySCwuTi0qAUoY6hmZGmgq2NoqmCKJmugZGEBETZBEDfSMoaIKxiiKzYxMocLm/wE "Julia 0.6 – Try It Online")
Recursive approach which takes an iterator as its own optional argument. The `>` operator is overloaded, since it has lower precedence than `+`, which saves a set of parentheses. Spaces are required around ternary operators beginning in Julia 1.0.The function `isinteger` is a good fit; `last("$(i*x)")<'1'` would be another (longer) approach.
[Answer]
# [R](https://www.r-project.org), ~~39~~ 31 bytes
```
\(x,y=x*1:1e6)y[!(y+1e7)%%1][1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGqvNLc1KLEkvwi26WlJWm6FvtjNCp0Km0rtAytDFPNNCujFTUqtQ1TzTVVVQ1jow1jIapuKsL1aRjqGZlqciH4xnqGJkYWmhCFCxZAaAA)
Correctly handles difficult inputs that otherwise suffer from floating-point inaccuracies.
---
# [R](https://www.r-project.org), 25 bytes (non-competing)
```
\(x,y=x*1:1e6)y[!y%%1][1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGqvNLc1KLEkvwi26WlJWm6FjtjNCp0Km0rtAytDFPNNCujFStVVQ1jow1jIfLr4Ro0DPWMTDUhogsWQGgA)
Original answer: fails due to floating-point inaccuracies for `3.1428`, and probably other difficult inputs.
[Answer]
# Google Sheets, 31 bytes
`=+split(text(A1,"#/#####"),"/")`
Put the input in cell `A1` and the formula in `B1`.
Uses number formatting like the [Excel answer](https://codegolf.stackexchange.com/a/265241/119296) to get a fraction, then takes advantage of an undocumented feature of the unary plus operator `+`, i.e., [`uplus()`](https://support.google.com/docs/answer/3093608), to get the numerator.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 26 bytes
```
->d{(1..).find{_1/d%1==0}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuha7dO1SqjUM9fQ09dIy81Kq4w31U1QNbW0NamshCm5qFyikRRvqGZkaxHKBmCZ6BgZQpoGesQFc1MzINBaiZcECCA0A)
## Original: [Ruby](https://www.ruby-lang.org/), 31 bytes
```
f=->d,x=1{d*x%1>0?f[d,x+1]:d*x}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboW-9Nsde1SdCpsDatTtCpUDe0M7NOigXxtw1groEAtRNVN7QKFtGhDPSNTg1guENNEz8AAyjTQMzaAi5oZmcZCtMAsAAA)
The more obvious `f=->d{d.to_r.numerator}` does not seem to work for 0.300.
Thanks Value Ink for the tips, but I think that it should be a separate answer.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 25 bytes
```
n->numerator(bestappr(n))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWO_N07fJKc1OLEkvyizSSUotLEgsKijTyNDUh8jftgPycSo08BV07hYKizLwSIFMJxFFSSAMp01GINtQzMjXQUTDRMzAAUgZ6xgZgnpmRaSzUlAULIDQA)
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 26 bytes
```
($\=$_*++$i)=~/\./&&redo}{
```
[Try it online!](https://tio.run/##K0gtyjH9/19DJcZWJV5LW1slU9O2Tj9GT19NrSg1Jb@2@v9/Qz0jUwMFXTsF03/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online")
[Answer]
# [Maxima](http://maxima.sourceforge.net/), 17 bytes
[Try it online!](https://tio.run/##FYtBCoAgEAC/snhyYRMz65DUR8TDRgRBKxEF/d7yNAPDCL@7cCmbzjhO@RF98f07liB86oNlWVnHnAjOa89/IlDQzKAI6oNIEFvjegJvrLUE1nQV3gyuTxjKBw)
```
f(n):=num(rat(n))
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 3 bytes [SBCS](https://github.com/abrudz/SBCS)
```
∧∘1
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9Sx/FHHDEMA&f=S1Mw1DMyNeBKUzDRMzAA0QZ6xgYQvpmRKQA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
LCM between input and 1. This is actually really similar to a problem in the APL Competition, [1:7 Let's Be Rational](https://www.dyalogaplcompetition.com/?goto=P17).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 6 bytes
```
*fsI*Q
```
Takes input as a float.
[Try it online!](https://tio.run/##K6gsyfj/Xyut2FMr8P9/Ez0zI1MA "Pyth – Try It Online")
```
*fsI*Q
f Find the first integer, starting at 1 and counting upward, such that
*Q The integer multiplied by the input
I Is unchanged when
s Cast to an integer
* Multiply the result (the denominator) by the input
```
---
Same length:
```
fsIcTQ
```
Finds the numerator directly using division.
[Answer]
# [Rust](https://www.rust-lang.org/), ~~39~~ 38 bytes
-1 thanks to @corvus\_192
```
|mut x|{let n=x;while x%1.>0.{x+=n};x}
```
[Try it online!](https://tio.run/##FctBCoAgEAXQfaf4BYFSSAWtxO7SokiwIdJowDy71fIt3nn5kFfCPlsSErEA3BLgTX72K4Cf@JMM63uzbgHXvZo6FbkxlDSnDOjvHKel4KgUVUxVCy96NYxS6iLlFw "Rust – Try It Online")
Closure naively loops and increments `x` by its intial value until it becomes a whole number.
[Answer]
# Python 3, 53 bytes
Trivial solution (thanks to lyxal for the comment).
```
lambda n:Fraction(n).numerator
from fractions import*
```
Originally (65 bytes, returns a `float` which can be converted to an `int` while being the same value):
```
def x(n,i=1):
while not str(i*n).endswith('.0'):i+=1
return i*n
```
20 bytes from SuperStormer:
```
lambda n:n.numerator
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 1 byte
```
·πá
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6Fosf7mxfUpyUXAzlL1hqYqJvaALhAAA)
`·πá` = 'numerator' = 'Get the numerator of a number'
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~35~~ 24 bytes
```
{while($1*++a%1);$1*=a}1
```
[Try it online!](https://tio.run/##SyzP/v@/ujwjMydVQ8VQS1s7UdVQ0xrIsk2sNfz/31DPyBQA "AWK – Try It Online")
(Several improvements by @Dominic van Essen to my original answer: -11 bytes)
---
## Original answer: [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 35 bytes
```
{while($1*++a>int($1*a));print$1*a}
```
[Try it online!](https://tio.run/##SyzP/v@/ujwjMydVQ8VQS1s70S4zrwTETNTUtC4oAnJA7Nr//w31jEwB "AWK – Try It Online")
[Answer]
# [Python](https://docs.python.org), 20 bytes
```
lambda n:n.numerator
```
An unnamed function that accepts a `Fraction` object and returns the integer.
**[Try it online!](https://tio.run/##RczBCsIwEATQe79iySkBCbG1Ygr12K/wErXBgNmE7fYgpd9eW6g4p8cMTP7wK2F1ybT49ra8Xbw/HWCDGsfYk@O0DpQieHIPDgkHCDEnYuj2AtwAXVH4RMD9wBAQZCfFUZe1EeoAq0/amJ@Nrsy/P5f1bmu1tVYo1RSwJlNAll5M2@cM7RUmLzerWajlCw "Python 3.8 (pre-release) – Try It Online")**
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 39 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.875 bytes
```
{D⌊≠|+
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBPSIsIiIsIntE4oyK4omgfCsiLCIiLCIxLjI1XG4wLjNcbjAuMzMzMzMzMzMzMzMzMzNcbjQuNjI1XG40Il0=)
Posting as a separate answer because it doesn't use any fraction string cheese :p
Takes input as either a fraction or a float, as both are implicitly converted to rationals.
## Explained
```
{D⌊≠|+­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢​‎⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌­
{ | # ‎⁡While
⌊≠ # ‎⁢ The floor of the top of the stack doesn't equal the top of the stack
D # ‎⁣ (triplicate before the check so there's a copy left over)
+ # ‎⁤Add the input to the top of the stack
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
≔I⁻θ.ηF⊟⪪θ.F25F¬﹪ηIκ≧÷IκηIη
```
[Try it online!](https://tio.run/##PY7BDoIwEETvfkXT026CHIh44WTk4gFD9AsaULqx6da28PtVqeE2ybzMm0ErP7AyKZ1CoMnCWYUIHdk5wLsQspSIhdDY7J7sBfTs4O4Mxa1EsRayquU/Xvk7wONsGHQh1r0X/sBOuSy50aQjXGxsaaHxsUFZ1HuyMf/QiE1Kh/JY1Wm/mA8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔I⁻θ.η
```
Remove the decimal point from the input and cast it to integer.
```
F⊟⪪θ.
```
Loop over each decimal place.
```
F25F¬﹪ηIκ≧÷Iκη
```
Divide the integer by 2 and/or 5 if possible.
```
Iη
```
Output the resulting integer.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~95~~ 71 bytes
```
\.(\d+)$
$1,$.1*0
.*5,0
$.(*2*),0
.*[2468],0
$.(*5*),0
}`0,0
,
^0+|,0*
```
[Try it online!](https://tio.run/##LYg7CoAwEAX7PUeEuC7LSzTBG3gIPyhoYWMhlnr2@MFmmJl9OdZtcimzthlTp7abi9yQcWLUMUg5CMioZc@5vN36Ktb9P8M3rxEPhQYUp4ApJac@gCoFQNASr0cfbg "Retina – Try It Online") Link includes test cases. Explanation:
```
\.(\d+)$
$1,$.1*0
```
On the first pass, delete the decimal point but keep track of how many digits there were after it. (It's golfier to repeat this stage but it has no effect on subsequent passes.)
```
(.*5),0
$.(*2*),0
```
Try doubling the number to create a trailing zero to match.
```
(.*[2468]),0
$.(*5*),0
```
Try multiplying the number by `5` to create a trailing zero to match.
```
0,0
,
```
Remove a pair of matching zeros.
```
}`
```
Repeat until there are no more trailing zeros to remove or the number ends in `1`, `3`, `7` or `9`.
```
^0+|,0*
```
Delete any leading zeros and any remaining working digits.
[Answer]
# T-SQL, 51 bytes
```
DECLARE @2 real=4.625
DECLARE @ REAL=@2
WHILE @>floor(@)SET @+=@2
PRINT @
```
[Answer]
# Swift 2.2, floating-point, 65 bytes
```
func f(x:Float,y:Float=1)->Float{return x*y%1==0 ?x*y:f(x,y:y+1)}
```
Back in Swift 2, `%` was supported for floating-point types. I also can't figure out what `Decimal` was called back then.
[Try it on SwiftFiddle!](https://swiftfiddle.com/jpmazbi6ubb2to7lqs2z7vkocm)
## Swift 5.8 + Foundation, decimal, 109 bytes
```
func f(x:Decimal,y:Decimal=1)->Decimal{var z=x,w=x*y
NSDecimalRound(&z,&w,0,.up)
return w==z ?w:f(x:x,y:y+1)}
```
Rounding mode doesn't matter; I chose `.up` because it's the shortest. The function signature of `NSDecimalRound` makes more sense in Objective-C where you only work with `NSDecimal*` and not the struct directly.
[Try it on SwiftFiddle!](https://swiftfiddle.com/7dkq6avb3vb4ldkwm36kid7khu)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞.ΔI/DïQ
```
[Try it online](https://tio.run/##yy9OTMpM/f//Ucc8vXNTPPVdDq8P/P/fWM/QxMgCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf8fdczTOzfl0Dp9l8PrA//X6vyPNtQzMtUx0TPQMdAzBtJmQJ6xnqGJkUUsAA).
**Explanation:**
```
‚àû # Push an infinite positive list: [1,2,3,...]
.Δ # Pop and find the first integer that's truthy for:
I/ # Divide the current integer by the input-decimal
D # Duplicate the decimal
ï # Cast/floor its copy to an integer
Q # Check if both are the same value
# (after which the found integer is output implicitly as result)
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 31 bytes
```
f=(n,m=n)=>(m+1e9)%1?f(n,m+n):m
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P81WI08n1zZP09ZOI1fbMNVSU9XQPg0kpp2naZX7v6AoM69EI4HLUM/I1EBB105BpTpNA8zRrOUy0TMwgAuCOUBBAz1jhCCYA1ZpZmSKUAnkAAWN9IwVFGCCQA5QKEHzPwA "JavaScript (V8) – Try It Online")
Take float
# [JavaScript (V8)](https://v8.dev/), 4 bytes
```
x=>x
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvu/wtau4n9BUWZeiUYCl6m@iYKunYJKdZqGqY6JZi2Xib4hTMBExxAoYKxvaAATMdYxNAAJmetbwIXMdSyAQkZgZQowUSOoygTN/wA "JavaScript (V8) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 16 bytes
Builtin solution posted as a separate answer from [G B's answer](https://codegolf.stackexchange.com/a/265250/52194) per their suggestion. Takes a `Rational` as input.
```
proc &:numerator
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhYbCorykxXUrPJKc1OLEkvyiyDCNx3LMzJzUhXSU0uKuRQSdZIUbBVU4vWKC3IySzT0FbR17RT0NbkUChSKbNOiE_VK8uOLYnWAHNskEDuTKzUvBWLQgpv2hnpGpgoKCkAtplwmegYKELYJl4GeMZRtDBQ3AykCsc25jPUMTYwsQBxzC1NziDkA)
## [Ruby](https://www.ruby-lang.org/) `-n`, 18 bytes
The same idea but takes input from STDIN via `-n` and prints the answer.
```
p$_.to_r.numerator
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6eUuyCpaUlaboWmwpU4vVK8uOL9PJKc1OLEkvyiyASUPkFOw31jEy5TPQMuAz0jIG0GZBnrGdoYmQBUQAA)
] |
[Question]
[
# Introduction
I stumbled across this (useless) pattern the other day while I was watching TV.
I named it "the 9 pattern" because the first number to use it was 9.
The gist of it is, you enter a number (let's say **x**), and then you get back:
* **x**
* **x** + (**x** / 3) [let's call this **y**]
* two-thirds of **y** [let's call this **z**]
* **z** + 1
So, if I put inside this pattern the number **9** as **x**, this is what would come out:
* 9 (**9**)
* 12 (**9** + **9** / 3) [9 over 3 is 3, and 9 + 3 is 12]
* 8 (**12** times two-thirds) [a third of 12 is 4, and 4 \* 2 is 8]
* 9 (**8** + 1 is 9)
# Challenge
Write me a function (in any programming language) that takes in a number, and outputs an integer array using the pattern.
Somewhat like this psuedo-code:
```
function ninePattern(int myInt) returns IntegerArray {
int iterationA = myInt + (myInt / 3);
int iterationB = iterationA * (2 / 3);
int iterationC = iterationB + 1;
IntegerArray x = [myInt, iterationA, iterationB, iterationC];
return x;
}
```
# Clarifications
Discussions have been arousing in comments regarding the specifications of the question. This section is meant to clarify some of those.
## "better to count in bytes than characters"
I picked characters because (for me, at least) it would be easier to judge. Of course, I can't change that now. (lots of answers are already posted)
## "rounding"
Rounding follows this rhyme:
>
> If it's 5 or more, raise the score
>
> If it's 4 or less, let it rest
>
>
>
Simply, put, if it is something like 4.7 or 3.85, round them to 5 and 4 respectively.
### Examples
```
Input => Result
9 => [9, 12, 8, 9]
8 => [8, 11, 7, 8]
6 => [6, 8, 5, 6]
23 => [23, 31, 21, 22]
159 => [159, 212, 141, 142]
```
If, however, the numbers are something like 2.3 or 10.435446, round them to 2 and 10 respectively.
## "language support"
You are free to not use functions and/or arrays **IF AND ONLY IF** the language of your choice does not support them. If it does (even if it will increase your characters count), **you must use them**.
[Answer]
# MarioLANG, ~~659~~ ~~621~~ ~~591~~ ~~582~~ ~~556~~ ~~543~~ ~~516~~ ~~458~~ ~~418~~ ~~401~~ ~~352~~ ~~308~~ 369 bytes
rounding is quite expensive :/
[**Try it online**](http://mariolang.tryitonline.net/#code=Oz4-WyFbKCBbKCBbKCBbKCBbKCBbPCgoWyEpKSkhKygoKC08PiggPigoKwo6Ij09Iz09PT09PT09PT09PT09PT0iPT09Iz09ICM9PT09PSIiWyAiPT0KKSggIC1bISk-PlshWykgIFspWzwoIT4pWzwpKSA-KSkpIFshIS1bISgoCiAoICApIiM9Ij09Iz09PT09PT0iPSM9PT0iPTw9Ij09PT09IyM9PSM9PTwKICsgICs-KSApLSs8PispWyEpKyEgKykpIVstWyk-WyBbKFstWyFbPDw6CiArICApLSsgKSg9IiI9PT0jPT0jICA9PSM9PT0pIj09PT09PT0jPT09PT0KICsgID4hPikhPiAgISgtIDwgITorOikpPCAgKSkhKCgrKykpKTwgCiApICAiIyI9Iz09PSM9PT0iID09PT09PSIgPT09Iz09PT09PT0iCiAhCj0jPT09PT09PT09PT09PT09PT09PT09PT09&input=MjM)
```
;>>[![( [( [( [( [( [<(([!)))!+(((-<>( >((+
:"==#================"===#== #=====""[ "==
)( -[!)>>[![) [)[<(!>)[<)) >))) [!!-[!((
( )"#="==#======="=#==="=<="=====##==#==<
+ +>) )-+<>+)[!)+! +))![-[)>[ [([-[![<<:
+ )-+ )(=""===#==# ==#===)"=======#=====
+ >!>)!> !(- < !:+:))< ))!((++)))<
) "#"=#===#===" ======" ===#======="
!
=#========================
```
Well this was more fun than expected, this is probably not optimal but I guess i'm getting there.
**Explanation time:**
(for the **352** bytes version)
first we get the argument and print it :
```
;
:
```
simple enough
we then move to the bulk of the program : the division **input / 3**
```
;>>[![ [( [( [<result
:"==#======================"======
) -[!)>>[![ [<((((!
) )"#="==#=========="====#
+( +>) ) +>(+)[!)+))!
+( )-+ ) -"====#====#
+ >!>)! >! - <
"#"=# "#===="
!
=#
```
which is a slightly modified conversion of the brainfuck division
```
[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]
```
which take for input
```
n 0 d 0 0
```
and give you back
```
0 n d-n%d n%d n/d
```
once we got the division we use it to get the sum of **n** and **n/d** and print it
```
;>>[![ [( [( [< !+(((-<
:"==#======================"===)#====="
) -[!)>>[![ [<((((! >))) [!(((
) )"#="==#=========="====# ="=====#==:
+( +>) ) +>(+)[!)+))!
+( )-+ ) -"====#====#
+ >!>)! >! - <
"#"=# "#===="
!
=#
```
we then need to do another division : **( 2 \* ( n + n / d ) ) / 3**
so we get **( 2 \* ( n + n / d )**
```
;>>[![ [( [( [< !+(((-<
:"==#======================"===)#====="
) -[!)>>[![ [<((((! >))) [!(((
) )"#="==#=========="====# ="=====#==:
+( +>) ) +>(+)[!)+))! 2*2n/d>[ -[![ <
+( )-+ ) -"====#====# ======"======#====
+ >!>)! >! - < !((++))<
"#"=# "#====" #======"
!
=#
```
and put it with 3 back into the division
```
;>>[![ [( [( [< !+(((-<
:"==#======================"===)#====="
) -[!)>>[![ [<((((! >))) [!(((
) )"#="==#=========="====# ="=====#==:
+( +>) ) +>(+)[!)+))! )>[ -[![ <
+( )-+ ) -"====#====# )"======#====
+ >!>)! >! - < +++))!((++))<
"#"=# "#====" ===========#======"
!
=#=================
```
at that point everything explose, mario is stuck in an infinite loop doing division on bigger and bigger number, forever.
and to fix that we need a way to diferenciate between the first and the second division, it end up that, oh joy, we do have a way
```
;>>[![ [( [( [<([!)!+(((-<
:"==#======================"==#)#====="
) -[!)>>[![ [<((((!))< >))) [!(((
) )"#="==#=========="====#)="="=====#==:
+( +>) ) +>(+)[!)+))!!:+:)))>[ -[![ <
+( )-+ ) -"====#====#======)"======#====
+ >!>)! >! - < +++))!((++))<
"#"=# "#====" ===========#======"
!
=#=================
```
basically we look if the x in
```
x 0 n d-n%d n%d n/d
```
is 0, if it is it mean we are on the first division
else we are on the second division, and we just print the result of the division, add 1 then print it again
and *voilà* easy as pie.
[Answer]
# Emotinomicon 99 bytes, 33 characters
```
üò∑üò≠,üò≤üÜôüÜôüòºüÜôüò®üòé‚è¨üòéüÜôüòç‚ûó‚ûïüÜôüò®üòé‚è¨üòéüòâ‚úñüòç‚ûóüÜôüò®üòé‚è¨üòéüòÖ‚ûïüò®
```
Explanation:
```
üò∑ clear output
üò≠ begin quote string
,
üò≤ end quote string
üÜô duplicate top of stack
üÜô duplicate top of stack
üòº take numeric input
üÜô duplicate top of stack
üò® pop N and output as a number
üòé reverse stack
⏬ pops and outputs top of stack as character
üòé reverse stack
üÜô duplicate top of stack
üòç push 3 to the stack
‚ûó divide top two elements on stack
‚ûï add top two elements on stack
üÜô duplicate top of stack
üò® pop N and output as a number
üòé reverse stack
⏬ pops and outputs top of stack as character
üòé reverse stack
üòâ push 2 to the stack
‚úñ multiply top two elements on stack
üòç push 3 to the stack
‚ûó divide top two elements on stack
üÜô duplicate top of stack
üò® pop N and output as a number
üòé reverse stack
⏬ pops and outputs top of stack as character
üòé reverse stack
üòÖ push 1 to the stack
‚ûï add top two elements on stack
üò® pop N and output as a number
```
[Answer]
# MATL, 14 bytes
```
Xot4*3/tE3/tQv
```
[**Try it Online**](http://matl.tryitonline.net/#code=WG90NCozL3RFMy90UXY&input=Nw)
Pretty simple, `v` concatenates the stack into an array. `Xo` converts to an integer data-type, and all operations thereafter are integer operations.
[Answer]
# [Cheddar](https://github.com/cheddar-lang/Cheddar), 27 bytes
```
b=8/9*$0
[$0,$0+$0/3,b,b+1]
```
`$0` is variable with input. Cheddar just isn't a golfy language ¯\\_(ツ)\_/¯ , also this is non-competing because Cheddar's input functionality was made after this challenge.
Ungolfed:
```
IterationB := 8 / 9 * $0 // 8/9ths of the Input
[ $0, // The input
$0 + $0 / 3, // Input + (Input/3)
IterationB, // (see above)
IterationB + 1 // above + 1
]
```
[Answer]
# Java, 86 82 84 85 characters
```
class c{int[]i(int I){int a=I+(I/3),b=(int)(a*(2d/3d));return new int[]{I,a,b,b+1};}}
```
The letter `d` placed right after an integer makes the integer a `double`.
Ungolfed:
```
class c{
int[] i(int I) {
int a = I + (I / 3),
b = (int)(a * (2d / 3d));
return new int[]{I, a, b, b + 1};
}
}
```
Without the class (`class c{}` is 8 chars long), it downsizes to 76 characters:
```
int[]i(int I){int a=I+(I/3),b=(int)(a*(2d/3d));return new int[]{I,a,b,b+1};}
```
More accurate version in 110 chars (118 with the enum) - it uses `float`s because ain't nobody got space for casting [`Math#round(double)`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#round-double-):
```
int[]i(int I){float a=I+(I/3f),b=(a*(2f/3f));return new int[]{I,Math.round(a),Math.round(b),Math.round(b+1)};}
```
[Answer]
# Java, ~~56~~ 80 Bytes
As some users pointed out, this solution (as some others in java) does not round data properly. So now I'm presenting slightly longer solution which should return correct result
```
int[]h(int a){int[]b={a,Math.round(a+a/3f),a=Math.round(a*8f/9),++a};return b;}
```
or 60 bytes lamda version
```
a->new int[]{a,Math.round(a+a/3f),a=Math.round(a*8f/9),++a}
```
~~Golfed version~~
```
int[]g(int a){int[]b={a,a+a/3,a*8/9,a*8/9+1};return b;}
```
and ungolfed
```
int[] g(int a) {
int[] b = { a, a + a / 3, a * 8 / 9, a * 8 / 9 + 1 };
return b;
}
```
or 36 bytes defined as lambda
```
a->new int[]{a,a+a/3,a*8/9,a*8/9+1}
```
[Answer]
# Scratch, 33 bytes
[](https://i.stack.imgur.com/6LaaO.png)
(source: [cubeupload.com](https://i.cubeupload.com/NAvX3i.png))
Asks for input, sets `a` to input rounded, sets `b` and `c` to their respective changes, then says all four numbers, seperated by commas.
[Answer]
# Java, 64 bytes
```
int[]f(int i){return new int[]{i,i+=i/3+0.5,i-=i/3-0.5,i+=1.5};}
```
### Notes
* This has the required rounding build in, not sure if you can do it shorter if mixed with @user902383's solution.
### Ungolfed
```
int[] f(int i) {
return new int[]{
i,
i += i / 3 + 0.5,
i -= i / 3 - 0.5,
i += 1.5};
}
```
### Output with i=9
```
[9, 12, 8, 9]
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 15 bytes
Code:
```
Ð3/+D·3/D>)1;+ï
```
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w5AzLytEwrczL0Q-KTE7K8Ov&input=OQ).
[Answer]
## Java 8 lambda, ~~109~~ ~~81~~ ~~79~~ 75 characters
Because... you know... even Java can be golfed...
```
a->{int b=(int)(.5+a*4./3),c=(int)(.5+b*2./3);return new int[]{a,b,c,++c};}
```
Lambda ungolfed into class:
```
class C {
static int[] a(int a) {
int b = (int) (.5 + a * 4. / 3),
c = (int) (.5 + b * 2. / 3);
return new int[]{a, b, c, ++c};
}
}
```
~~I assume I'm allowed to use longs as they are also an integer type.
Sadly one needs to correctly round integers and thus a "short" cast doesn't work. By using longs we don't need to cast the rounding results back to ints.~~
### Update
Using the nice little + 0.5 and casting afterwards trick we keep the correct rounding and save 2 chars!
Also this trick doesn't require the use of long any longer thus we can switch back to ints shaving of 4 more chars.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt#L187), 14 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
3/+_∞3/_)Γ2∩+i
```
[Try it online.](https://tio.run/##y00syUjPz0n7/99YXzv@Ucc8Y/14zXOTjR51rNTO/P/fksuCy4zLyJjL0NQSAA)
**Explanation:**
```
3/ # Divide the (implicit) input by 3
+ # Add it to the (implicit) input
_ # Duplicate this
‚àû # Double the copy
3/ # Divide it by 3
_ # Duplicate this
) # Increase the copy by 1
Γ # Wrap four values into a list (since the stack only contains three, it
# will use the implicit input as fourth):
2‚à©+ # Add 1/2 to each
i # And cast each float to an integer, removing any decimal values
# [int(i+1/2),int(i+i/3+1/2),int((i+i/3)*2/3+1/2),int((i+i/3)*2/3+1+1/2)]
# (after which the entire stack joined together is output implicitly)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 52 bytes
```
f=lambda n,i=4:1//i*[n+1]or[n]+f(round(i*n/3),i%3+1)
```
[Try it online!](https://tio.run/##BcFBCoAgEAXQq8wm0BwQsyKDThItipAG6htSi05v793fcyT4UuJ0rte2rwSWqR2dtVLPMG5JecZiosrpxa6khvWapfLG6RJTJpCAAg/cc@PZdWGkOwseFRW0Lj8 "Python 3 – Try It Online")
Contrary to the previous Python answer, this one rounds in between cycles.
Every next value can be calculated using `i*n/3`, where `n` is the current value and `i` is taken from `[4,2,3]`. To complete the sequence, `1` is added to the result of the final iteration.
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), 18 chars
```
D4*3/D2*3/D1+ZMrZv
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhabXEy0jPVdjECEoXaUb1FUGUQCKr9goSWEAQA)
(This is actually a bit less in bytes but the challenge asks for chars, not bytes.)
This is a full program since Thunno doesn't have functions.
#### Explanation
```
D4*3/D2*3/D1+ZMrZv # Implicit input
D # Duplicate
4*3/ # Push x*(4/3)
D # Duplicate
2*3/ # Push y*(2/3)
D # Duplicate
1+ # Push z+1
ZMr # Push the stack
Zv # Round each number
# Implicit output
```
[Answer]
# Mathematica - 21 bytes
Just got Mathematica from my brothers RPi, so trying it out for fun, and what better way than a PPCG challenge.
```
{#,4#/3,8#/9,8#/9+1}&
```
Defines an anonymous function. Try it out like:
```
In[26]:= x:={#,4#/3,8#/9,8#/9+1}&
In[27]:= x[9]
Out[27]= {9, 12, 8, 9}
```
[Answer]
## Python 3, 45 bytes
```
f=lambda i:map(round,[i,i*4/3,i*8/9,i*8/9+1])
```
[See this code running on ideone.com](http://ideone.com/qSiE4c)
[Answer]
## Lua, 52 Bytes
This program takes a number by command-line argument and return the corresponding array.
Programs in lua are technically functions, as the interpreter will always encapsulate them in a function. This is also this mechanic that is used when you "call" codes in other files (it basically uses `loadfile`/`dofile`).
```
m=math.floor x=...z=m(x*8/9)return{x,m(x*4/3),z,z+1}
```
[Answer]
## Actually, 21 bytes
```
`;;3@/+;32/*;uk1½+♂≈`
```
This program declares a function that performs the required operations on the top stack value.
[Try it online!](http://actually.tryitonline.net/#code=YDs7M0AvKzszMi8qO3VrMcK9K-KZguKJiGAu&input=OQ) (the extra `.` at the end evaluates the function and prints the result)
Explanation:
```
`;;3@/+;32/*;uk1½+♂≈`
;; make two copies of x
3@/+ divide by 3, add that to x to get y
;32/* make a copy of y and multiply by 2/3 to get z
;u make a copy of z and add one
k push stack as a list
1¬Ω+ add 0.5 to each element
♂≈ apply int() to each element (make integers from floats by flooring; this is equivalent to rounding half-up because of adding 0.5)
```
[Answer]
# Mathcad, [tbd] bytes
[](https://i.stack.imgur.com/SEu30.jpg)
---
Mathcad codegolf byte equivalance is yet to be determined. Taking a keyboard count as a rough equivalent, the solution is approx 40 bytes.
[Answer]
## Pyke, 11 bytes
```
D}[}3/bD)[h
```
[Try it here!](http://pyke.catbus.co.uk/?code=D%7D%5B%7D3%2FbD%29%5Bh&input=8)
```
- implicit input()
D - a,b = ^
} - b*=2
[}3/bD) - macro:
} - tos*=2
3/ - tos/=3
b - tos = round(tos)
D - old_tos = tos = tos
- macro
[ - macro
h - d +=1
```
[Answer]
# C++0x - 95 102 185 189 109 129 chars
```
int * n(int p){static int a[3];a[0]=p;a[1]=round(p+(p/3));a[2]=round((a[1]/3)*2);a[3]=a[2]+1;return a;}
```
* This requires the **cmath** header to work.
## Degolfed
```
#include <cmath>
int * ninePattern(int p) {
static int a[3]; // pattern array
a[0] = p; // sets first iteration
a[1] = round(p + (p / 3)); // sets second iteration
a[2] = round((a[1] / 3) * 2); // sets third iteration
a[3] = a[2] + 1; // sets fourth iteration
return a; // returns array
}
```
[Answer]
# [Arturo](https://arturo-lang.io), 55 bytes
```
$[x][map@[x,y:round x+x//3y,1+dup round 2*y//3]=>floor]
```
[Try it](http://arturo-lang.io/playground?lck3Op)
[Answer]
# JavaScript, 47 bytes
```
(a,r=Math.round)=>[a,a=r(a*4/3),a=r(a*2/3),++a]
```
Try it:
```
f=(a,r=Math.round)=>[a,a=r(a*4/3),a=r(a*2/3),++a]
console.log(JSON.stringify(f(9)));
console.log(JSON.stringify(f(8)));
console.log(JSON.stringify(f(6)));
console.log(JSON.stringify(f(23)));
console.log(JSON.stringify(f(159)));
```
[Answer]
# Javascript, 51 bytes
I convert my java solution to JavaScript and skimmed it down little bit.
```
var r=Math.round,g=a=>[a,a=r(a+a/3),a=r(a*2/3),++a]
```
[Answer]
**Erlang, 80 bytes**
```
-module(f).
-export([f/1]).
f(X)->Y=X+(X/3),Z=trunc(Y*(2/3)),[X,trunc(Y),Z,Z+1].
```
To run, save as *f.erl*, compile and call the function. It will return a list of ints:
```
fxk8y@fxk8y:/home/fxk8y/Dokumente/erlang/pcg# erl
Erlang/OTP 18 [erts-7.0] [source] [64-bit] [smp:4:4] [async- threads:10] [kernel-poll:false]
Eshell V7.0 (abort with ^G)
1> c(f).
{ok,f}
2> f:f(9).
"\t\f\b\t"
3>
```
Note that Erlang automatically converts *int*s to ASCII chars if you are in the ASCII value range because Erlang doesn't have a *char* type. Calling the function with 100 gives you the better readable *[100,133,88,89]*.
Ungolfed:
```
-module(f).
-export([f/1]).
f(X) ->
Y = X+(X/3),
Z = trunc(Y*(2/3)),
[X, trunc(Y), Z, Z+1].
```
[Answer]
# Erlang, 46 bytes
Answer inspired by @fxk8y (I couldn't post a comment to his answer)
```
F=fun(X)->Z=round(X*4/9),[X,Z*3,Z*2,Z*2+1]end.
```
Also you can see the results with:
```
2> io:fwrite("~w~n", [F(9)]).
[9,12,8,9]
ok
```
[Answer]
# Pyth, 20 bytes
```
m.RdZ[Jc*4Q3Kc*2J3hK
```
Explanation:
```
(Implicit print)
m For each d in array, d =
.RdZ Round d to zero decimal places
[ The array of
J The result of setting J to
c The float division of
*4Q Input * 4
3 and 3
,
K The result of setting K to
c The float division of
*2J J * 2
3 and 3
, and
hK K + 1.
(Implicit end array)
```
[Test here](https://pyth.herokuapp.com/?code=m.RdZ%5BJc%2a4Q3Kc%2a2J3hK&input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&debug=0)
[Answer]
# Jolf, 17 bytes
```
Ώ‘Hγ+H/H3Βώ/γ3hΒ’
```
Defines a function `Ώ`. It takes input implicitly, so it also doubles as a full program. [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=zo_igJhIzrMrSC9IM86Sz44vzrMzaM6S4oCZ&input=OQ)
[Answer]
## Mathematica, 51 bytes
```
FoldList[#2@#&,{#,Round[4#/3]&,Round[2#/3]&,#+1&}]&
```
Anonymous function that conforms to the current (at time of posting) version of post, which implies rounding at every step.
[`FoldList`](https://reference.wolfram.com/language/ref/FoldList.html) is a [typical operation](https://en.wikipedia.org/wiki/Fold_%28higher-order_function%29) in programming. It is invoked as `FoldList[f, list]` and applies the two-argument function `f` repeatedly to the result (or the first element of the list in the first iteration), taking the next element of the list as its second argument.
Ungolfed:
`#2 @ # &` is an anonymous functions that applies its second argument to the first. Therefore, the list argument of `FoldList` consists of the successive functions to be applied to the input.
```
FoldList[#2 @ # &,
{#, (* note the absence of '&' here,
this '#' stands for the argument
of the complete function and is
covered by the & at the end *)
Round[4 # / 3] &, (* anonymous function that rounds 4/3 of its input *)
Round[2 # / 3] &, (* ditto, 2/3 *)
# + 1 & (* add one function *)
}] & (* and the '&' makes the entire
thing an anonymous function,
whose argument is the '#' up
at the top. *)
```
Because input is integer and the divisions are by 3, there will never be a result like 4.5, therefore there's no need to worry about rules of rounding when the last digit is a `5`: it will always be clearly closer to one integer, or another.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 33 bytes
```
(⌽,{1+⊃⍵})∘{⍵,⍨3÷⍨2×⊃⍵}(3÷⍨4∘×),⊢
```
[Answer]
# Desmos, 37 bytes
```
a=9
b=a+\frac{a}{3}
c=\frac{2}{3}b
d=c+1
```
[Try it online](https://www.desmos.com/calculator/9pflf60hgv)
Yay for unconventional languages!
] |
[Question]
[
# Taken from: OEIS-[A071816](http://oeis.org/A071816)
Your task, given an upper bound of `n`, is to find the number of solutions that satisfy the equation:
```
a+b+c = x+y+z, where 0 <= a,b,c,x,y,z < n
```
The sequence starts out as described on the OEIS page, and as below (1-indexed):
```
1, 20, 141, 580, 1751, 4332, 9331, 18152, 32661, 55252, 88913, 137292, 204763, 296492, 418503, 577744, 782153, 1040724, 1363573, 1762004, 2248575, 2837164, 3543035, 4382904, 5375005, 6539156, 7896825, 9471196, 11287235, 13371756
```
---
For `n = 1`, there's only one solution: `(0,0,0,0,0,0)`
For `n = 2`, there are 20 ordered solutions `(a,b,c,x,y,z)` to `a+b+c = x+y+z`:
```
(0,0,0,0,0,0), (0,0,1,0,0,1), (0,0,1,0,1,0), (0,0,1,1,0,0), (0,1,0,0,0,1),
(0,1,0,0,1,0), (0,1,0,1,0,0), (0,1,1,0,1,1), (0,1,1,1,0,1), (0,1,1,1,1,0),
(1,0,0,0,0,1), (1,0,0,0,1,0), (1,0,0,1,0,0), (1,0,1,0,1,1), (1,0,1,1,0,1),
(1,0,1,1,1,0), (1,1,0,0,1,1), (1,1,0,1,0,1), (1,1,0,1,1,0), (1,1,1,1,1,1).
```
---
# I & O
* Input is a single integer denoting `n`.
* Output is a single integer/string denoting `f(n)`, where `f(...)` is the function above.
* The indexing is exactly as described, no other indexing is acceptable.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 6 bytes
```
ṗ6ḅ-ċ0
```
**O(n6)** solution.
[Try it online!](https://tio.run/nexus/jelly#@/9w53SzhztadY90G/z//98UAA "Jelly – TIO Nexus")
### How it works
```
ṗ6ḅ-ċ0 Main link. Argument: n
ṗ6 Cartesian power 6; build all 6-tuples (a, x, b, y, c, z) of integers in
[1, ..., n]. The challenge spec mentions [0, ..., n-1], but since there
are three summands on each side, this doesn't matter.
ḅ- Unbase -1; convert each tuple from base -1 to integer, mapping (a, ..., z)
to a(-1)**5 + x(-1)**4 + b(-1)**3 + y(-1)**2 + c(-1)**1 + z(-1)**0, i.e.,
to -a + x - b + y - c + z = (x + y + z) - (a + b + c). This yields 0 if and
only if the 6-tuple is a match.
ċ0 Count the number of zeroes.
```
[Answer]
## Mathematica 17 or 76 Bytes
Using the formula:
```
.55#^5+#^3/4+#/5&
```
(Saved 3 bytes per @GregMartin and @ngenisis)
Rather than using the formula, here I literally compute all the solutions and count them.
```
Length@Solve[a+b+c==x+y+z&&And@@Table[(0<=i<#),{i,{a,b,c,x,y,z}}],Integers]&
```
[Answer]
# [Haskell](https://www.haskell.org/), 48 bytes
I didn't notice the formula before writing this, so it's definitely not the shortest (or fastest) general method, but I thought it was pretty.
```
f n=sum[1|0<-foldr1(-)<$>pure[1..n]`mapM`[1..6]]
```
[Try it online!](https://tio.run/nexus/haskell#HctLCoMwFEbhrfwDBzrw4vXVCtoddAUSMDQJFZpEosFJ954@ZocPjpWrm1Z36CAfRxbd6YPaycot35/@JENBS1XQn5OBm/ZoZ35XY2n8SwXOy2LMblsMemYiJ5bvel9@3QuREqNGgxYdelxwxQCuwAyuwQ24BXcf "Haskell – TIO Nexus")
`f n` generates all lists of 6 elements from `[1..n]`, then counts the ones whose alternating sum is 0. Uses the fact that `a+b+c==d+e+f` is the same as `a-(d-(b-(e-(c-f))))==0`, and also that it doesn't matter if we add a 1 to all the numbers.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
l6:"G:gY+]X>
```
[Try it online!](https://tio.run/nexus/matl#@59jZqXkbpUeqR0bYff/v6EBAA "MATL – TIO Nexus")
### Explanation
I couldn't miss the chance to use convolution again!
This makes use of the following characterization from OEIS:
>
> `a(n) = largest coefficient of (1+...+x^(n-1))^6`
>
>
>
and of course polynomial multiplication is convolution.
```
l % Push 1
6:" % Do the following 6 times
G:g % Push a vector of n ones, where n is the input
Y+ % Convolution
] % End
X> % Maximum
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ṗ3S€ĠL€²S
```
Not as short as @Dennis's, but it finishes in under 20 seconds for input `100`.
[Try it online!](https://tio.run/nexus/jelly#@/9w53Tj4EdNa44s8AGShzYF////3xQA "Jelly – TIO Nexus")
### How it works
```
ṗ3S€ĠL€²S Main link. Argument: n
ṗ3 Cartesian power; yield all subsets of [1, ..., n] of length 3.
S€ Sum each.
Ġ Group indices by their values; for each unique sum S, list all indices whose
values are equal to S.
L€ Length each; for each unique sum S, yield the number of items in the original
array that sum to S.
² Square each; for each unique sum S, yield the number of pairs that both sum to S.
S Sum; yield the total number of equal pairs.
```
[Answer]
# Pyth, ~~13~~ 12 bytes
```
JsM^UQ3s/LJJ
```
Saved one byte thanks to Leaky Nun.
Explanation
```
JsM^UQ3s/LJJ
^UQ3 Get all triples in the range.
JsM Save the sums as J.
/LJJ Count occurrences of each element of J in J.
s Take the sum.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 28 bytes
```
lambda n:.55*n**5+n**3/4+n/5
```
[Try it online!](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqiQZ6VnaqqVp6Vlqg0kjPVNtPP0Tf8XFGXmlWhEp2lkaiqk5RcpZCpk5ikUJealp2oY6hgZaMZq/gcA "Python 3 – TIO Nexus")
[Answer]
# TI-BASIC, [19 bytes](https://codegolf.meta.stackexchange.com/a/4764/59183)
```
:Prompt X
:.05X(11X^4+5X²+4
```
Evaluates the OEIS formula.
[Answer]
# [Oasis](https://github.com/Adriandmen/Oasis), 17 bytes
```
5m11*n3m5*nz++20÷
5 n 5 implicit n for illustration
m n**5
11 n**5 11
* 11*n**5
n 11*n**5 n
3 11*n**5 n 3
m 11*n**5 n**3
5 11*n**5 n**3 5
* 11*n**5 5*n**3
n 11*n**5 5*n**3 n
z 11*n**5 5*n**3 4*n
+ 11*n**5 5*n**3+4*n
+ 11*n**5+5*n**3+4*n
20 11*n**5+5*n**3+4*n 20
÷ (11*n**5+5*n**3+4*n)÷20
```
[Try it online!](https://tio.run/nexus/oasis#@59nmmtoqJVnnGuqlVelrW1kcHj7////TQE "Oasis – TIO Nexus")
Oasis is a stack-based language optimized for recurring sequences. However, the recursion formula would be too long for this case.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes
```
{>ℕ|↰}ᶠ⁶ḍD+ᵐ=∧D≜ᶜ
```
[Try it online!](https://tio.run/nexus/brachylog2#ASoA1f//ez7ihJV84oawfeG2oOKBtuG4jUQr4bWQPeKIp0TiiZzhtpz//zEw/1o "Brachylog – TIO Nexus")
### Explanation
```
{ |↰}ᶠ⁶ Generate a list of 6 variables [A,B,C,D,E,F]...
>ℕ ...which are all in the interval [0, Input)
ḍD Dichotomize; D = [[A,B,C],[D,E,F]]
+ᵐ= A + B + C must be equal to D + E + F
∧
D≜ᶜ Count the number of possible ways you can label the elements of D while
satisfying the constraints they have
```
[Answer]
# JavaScript, 24 bytes
```
x=>11*x**5/20+x**3/4+x/5
```
Uses the formula from the OEIS page.
[Try it online!](https://tio.run/nexus/javascript-node#DcU5DsIwAEXBnpNkeYr9vWQpzEUQBUKEJmBLaXx7wzSzp1bTVRrqMETj7PjfmzBWE1tJN@HwBCIzCysbskjIIY8CimhGC1rRhrP3yzN/z3y8piO/uzJ9HqXb@779AA)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~25~~ ~~23~~ 21 bytes
```
@(n).55*n^5+n^3/4+n/5
```
[Try it online!](https://tio.run/nexus/octave#S7PV09P776CRp2loqJUXZ6pvZKCdF2esb6Kdp2/6P03DUJMrTcMIRBiDCBPN/wA "Octave – TIO Nexus")
Uses the formula from the OEIS-entry. Saved ~~two~~ four bytes by rearranging the formula and using `.55` instead of `11/20`, thanks to fəˈnɛtɪk.
[Answer]
# Python 2.7, 109 105 99 96 bytes
Thanks ETHproductions and Dennis for saving a few bytes:
```
from itertools import*
lambda s:sum(sum(x[:3])==sum(x[3:])for x in product(range(s),repeat=6))
```
[Answer]
## Mathematica, 52 bytes
Kelly Lowder's implementation of the OEIS formula is way shorter, but this computes the numbers directly:
```
Count[Tr/@#~Partition~3&/@Range@#~Tuples~6,{n_,n_}]&
```
Well, it actually counts the number of solutions with `1 <= a,b,c,x,y,z <= n`. This is the same number, since adding 1 to all the variables doesn't change the equality.
Explanation: `Range@#~Tuples~6` makes all lists of six integers between 1 and n, `#~Partition~3&/@` splits each list into two lists of length 3, `Tr/@` sums these sublists, and `Count[...,{n_,n_}]` counts how many pairs have the same sum. I got very lucky with the order of precedence between `f @`, `f /@` and `~f~`!
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 41 bytes
```
@(n)round(max(ifft(fft(~~(1:n),n^2).^6)))
```
[Try it online!](https://tio.run/nexus/octave#@@@gkadZlF@al6KRm1ihkZmWVqIBwnV1GoZWeZo6eXFGmnpxZpqamv/TFGwVEvOKrbnSNAw1dRTSNIzApCmYNDSACBlo/gcA "Octave – TIO Nexus")
Similar to my [MATL answer](https://codegolf.stackexchange.com/a/118057/36398), but computes the convolution via a discrete Fourier transform (`fft`) with a sufficient number of points (`n^2`). `~~(1:n)` is used as a shorter version of `ones(1,n)`. `round` is necessary because of floating point errors.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 17 bytes
```
ri,6m*{3/::+:=},,
```
Input of `11` times out on TIO, and `12` and higher run out of memory.
[Try it online!](https://tio.run/nexus/cjam#@1@UqWOWq1VtrG9lpW1lW6uj8/@/OQA "CJam – TIO Nexus")
**Explanation**
```
ri e# Read an int from input.
, e# Generate the range 0 ... input-1.
6m* e# Take the 6th Cartesian power of the range.
{ e# Keep only the sets of 6 values where:
3/ e# The set split into (two) chunks of 3
::+:= e# Have the sums of both chunks equal.
}, e# (end of filter)
, e# Get the length of the resulting list.
```
[Answer]
## Clojure, 79 bytes
```
#(count(for[r[(range %)]a r b r c r x r y r z r :when(=(+ a b c)(+ x y z))]1))
```
Tons of repetition in the code, on larger number of variables a macro might be shorter.
] |
[Question]
[
Two numbers are considered [amicable](https://en.m.wikipedia.org/wiki/Amicable_numbers) if the proper divisor sum of the first is the same as the second number, the second number's proper divisor sum is equal to the first number, and the first and second numbers aren't equal.
\$s(x)\$ represents the aliquot sum or proper divisor sum of \$x\$. 220 and 284 are amicable because \$s(220) = 284\$ and \$s(284) = 200\$.
Your task is, unsurprisingly, to determine whether two inputted numbers are amicable or not. The inputs will be positive integers and you may output two distinct, consistent values for amicable or not.
This is OEIS sequence [A259180](https://oeis.org/A259180)
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins.
## Test cases
```
input, input => output
220, 284 => 1
52, 100 => 0
10744, 10856 => 1
174292, 2345 => 0
100, 117 => 0
6, 11 => 0
495, 495 => 0
6, 6 => 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
QfÆṣ⁼
```
A monadic link taking a list of two integers which returns 1 if they are a pair of amicable numbers and 0 otherwise.
**[Try it online!](https://tio.run/##y0rNyan8/z8w7XDbw52LHzXu@X90z@H2R01r/v@PjlZQUDAyMtABURYmsTpcCiARBVMjkIihgQFExNDA3MREB0hZmJqBRQzNTYwsQWqMjE1MYbqAysG6DM3h5iiYgUSAQjARE0tTHQiFrkbBLDYWAA "Jelly – Try It Online")**
### How?
```
QfÆṣ⁼ - Link: pair of numbers L, [a, b] e.g. [220,284] or [6,6] or [6,11] or [100,52]
Q - de-duplicate L [220,284] [6] [6,11] [100,52]
Æṣ - proper divisor sum of L (vectorises) [284,220] [6] [6,1] [117,46]
f - filter keep left if in right [220,284] [6] [6] []
⁼ - equal to L? 1 0 0 0
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~65~~ ~~63~~ 66 bytes
-2 bytes thanks to Mr. Xcoder
```
lambda c:[sum(i*(n%i<1)for i in range(1,n))for n in c]==c[::-1]!=c
```
[Try it online!](https://tio.run/##HY3LDsIgFET3fMV1YUoNJoD0IRF/BFlUbJXE3jYtLvx6lO7mnElm5m98TSjTYG7p3Y33Rwde2/Uz0nCguA8XUQ7TAgECwtLhs6eCYbk5zM47Y7zV@ijczvgU@zWuYMDeiJWSM5CtcozYSjIQnOcoeKNUpraqN26UPP9reVJV5ppl7Ui@8Pli29QE5iVgBM8Kcy3YQH2Zfg "Python 2 – Try It Online")
[Answer]
# Python 2, 71 67 bytes
-4 bytes thanks to xnor
+9 bytes thanks to caird coinheringaahing
```
lambda c:[sum(i for i in range(1,x)if x%i<1)for x in c]==c[::-1]!=c
```
partly inspired by [this answer]
[Answer]
# J, ~~51 28 27~~ 24 Bytes
-Lots of bytes thanks to @cole
-1 more byte thanks to @cole
```
~.-:[:|.(1#.i.*0=i.|])"0
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/6/R0raKtavQ0DJX1MvW0DGwz9WpiNZUM/mtyWSuEFJWWZFRypSZn5CukKaSWpRZVKhgZGSgYWZgoWCsYGpibmABJC1MzoFq3xJziVDS1pkZAaQOQUnMTI0sjBSNjE1Mgz0zB0BBImViagjFIwOw/AA)
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 178 bytes
```
{(({})(<>))<>({<<>(({})<<>{(({})){({}[()])<>}{}}>)<>([{}](({}[()])))>{[()]((<{}{}>))}{}{}}{}<>)<>}<>(({}<>)<>[({}{}<>)])({<{}({<({}<>[{}])>{()(<{}>)}{}})>(){[()](<{}>)}}<{}{}{}>)
```
[Try it online!](https://tio.run/##NY2xCoIxDIRfxfFuEKQ4OIS8SOnwOwiiOLiGPHu9tAjlctwlX@/f4/k5P97Ha84AIglz0hxhkgo0d8OQdnCozsj0WuuRA/@c9CgDWGhDoKypZ7Wcm7h8R@x4UF9FSlZVPFHAQnjdJx3c2B3lgpeds7XLqd2uPw "Brain-Flak – Try It Online")
[Answer]
# Python 3, 84 bytes
```
d=lambda n:sum(i*(n%i<1)for i in range(1,n))
f=lambda a,b:(d(a)==b)*(d(b)==a)*(a^b)>0
```
Straightforward solution. d sums up divisors (n%i<1 evaluates to 1 iff i divides n). a^b is nonzero iff a!=b. The LHS of the inequality is thus 0 iff the numbers are not amicable and >0 otherwise.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~64 60 59~~ 58 bytes
```
->c{c.map{|i|(1...i).sum{|j|i%j<1?j:0}}==c.rotate&&c==c&c}
```
[Try it online!](https://tio.run/##VZDRTsMgFIbveYqTLXaaIClI281YfRDWiw6pwpxrWppogGevlMRYuTgn/8d3CDBMp@@5q4/z/bN0klza3nntbykhRN@Rcbo4b7y@MU/0xTzmIdS1JMPVtlZlmYwhk2G2arQj1CCQYCzHwPYcgx0m1WAkCoaB5pF27ceYCM0rzhe4L8o/j1acHaLLHnjxT46jlFYrVC5glfkhDqSyVsrfiBrUT/F@O/0ZOwVInQG8XS0sS331Slr1ukseSq8hqpXvEL8CG3z2kA7YbJ0OR7t1JtVOiLjbNCmcwybMPw "Ruby – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
≠.{fk+}ᵐ↔
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8f9S5QK86LVsbxHnUNuX//2iFaCMjAx0jC5NYnWhTIx1DAwMgw9DA3MQEyLYwNQPxzE2MLI10jIxNTMFyBjqGhuZAlhmQBlImlqY6QAwWMItViAUA "Brachylog – Try It Online")
Takes input as a list and outputs through success or failure.
```
The input
≠ which contains no duplicate values
. is the output variable,
{ }ᵐ and its elements'
k proper
f divisor
+ sums
↔ reversed
are also the output variable.
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 80 bytes
Refactored [reffu's solution](https://codegolf.stackexchange.com/a/153508/78410).
```
: d { n } 0 n 1 do n i mod 0= i * - loop ;
: f 2dup <> -rot 2dup d swap d d= * ;
```
[Try it online!](https://tio.run/##RUxLDsIgFNxzikmXJjSA0K/tXYwENVEhbY0L49nxASayePNlnF@2Cz@7BDEOsHjjgQ8EXQnrCa64ewsxEdmB4@Z9wMgGOCj7DDjM4IvfirBYX8cEdqLySIOhBNmuUVdAVZDPxBzx00JzTCkBQHWabmBGIT8pkhvApGi1zkZnGirIVqueSmqvTfpQipTLNg80@A1IZK17k3XBf14wxPgF "Forth (gforth) – Try It Online")
### How it works
```
: d { n -- divsum } \ Takes a number and gives its divisor sum (excluding self)
\ Store n as a local variable
0 n 1 do \ Push 0 (sum) and loop through 1 to n-1...
n i mod 0= \ If n % i == 0, push -1 (built-in true in Forth); otherwise push 0
i * - \ If the value above is -1, add i to the sum
loop ; \ End loop and leave sum on the stack
: f ( n1 n2 -- f ) \ Main function f. Takes two numbers and gives if they are amicable
2dup <> \ Are they not equal? ( stack: n1 n2 n1<>n2 )
-rot \ Move the boolean under n1 n2 ( stack: n1<>n2 n1 n2 )
2dup d swap d \ Copy two numbers, apply d to both and swap
\ ( stack: n1<>n2 n1 n2 n2.d n1.d )
d= \ Compare two 2-cell numbers for equality; n1=n2.d && n2=n1.d
* ; \ Return the product of the two booleans
```
[Answer]
# [Desmos](http://desmos.com/calculator), ~~214~~ 65+102=167 bytes
This is more of a fun answer, not a competitive one:
## Expression 1, 65 bytes:
```
g(N)=\sum_{n=1}^{N-1}\left\{\operatorname{mod}(N,n)=0:n,0\right\}
```
## Expression 2, 102 bytes:
```
f(M,N)=\left\{\left\{g(N)=M:1,0\right\}+\left\{g(M)=N:1,0\right\}+\left\{M=N:0,1\right\}=3:1,0\right\}
```
[](https://i.stack.imgur.com/fTnYS.png)
[Try It On Desmos!](https://www.desmos.com/calculator/62sybbgi6v)
I feel like this could definitely be golfed a lot. Too bad I can't take out those `\left`'s and `\right`'s, because they are in front of brackets(Desmos won't allow me to for some reason).
[Answer]
# [Haskell](https://www.haskell.org/), 53 bytes
*-2 bytes thanks to BMO. -1 byte thanks to Ørjan Johansen.*
```
a!b=a==sum[i|i<-[1..b-1],b`mod`i<1,a/=b]
a#b=a!b&&b!a
```
[Try it online!](https://tio.run/##Vc3BDoIwEATQO1@xDYYTIFtrxYR@CSFhN5jYQMGI3vz3uhw7x5eZzJP2@bEsMZJiR87t39D7n@@qHuuaKxxKHsM2jb7Dks6Oh4xyKSouClYUA/kVHExbBpLX268fOAFCDpjIReSWiBWxiWjdiOnWJHq1x9bcdfqArTlONDbxDw "Haskell – Try It Online")
## Ungolfed with [UniHaskell](https://github.com/totallyhuman/unihaskell) and `-XUnicodeSyntax`
```
import UniHaskell
equalsOmega ∷ Int → Int → Bool
a `equalsOmega` b = a ≡ sum [i | i ← 1 … pred b, i ∣ b, a ≢ b]
areAmicable ∷ Int → Int → Bool
areAmicable a b = (a `equalsOmega` b) ∧ (b `equalsOmega` a)
```
[Answer]
# JavaScript (ES6), 53 bytes
Takes input in currying syntax `(a)(b)`. Returns `0` or `1`.
```
a=>b=>a!=b&a==(g=n=>--a&&a*!(n%a)+g(n))(a=g(a)-b?1:b)
```
### Demo
```
let f =
a=>b=>a!=b&a==(g=n=>--a&&a*!(n%a)+g(n))(a=g(a)-b?1:b)
console.log(f(220)(284)) // => 1
console.log(f(52)(100)) // => 0
console.log(f(100)(117)) // => 0
console.log(f(6)(6)) // => 0
```
### How?
We use the function **g** to get the sum of the proper divisors of a given integer.
We first compute **g(a)** and compare it with **b**. If **g(a) = b**, we compute **g(b)** and compare it with **a**. Otherwise, we compute **g(1)**, which gives **0** and can't possibly be equal to **a**.
We additionally check that **a** is not equal to **b**.
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~153~~ 146 bytes
```
DEFINE('D(X)I')
DEFINE('A(M,N)')
A A =EQ(D(M),N) EQ(D(N),M) ~EQ(N,M) 1 :(RETURN)
D I =LT(I,X - 1) I + 1 :F(RETURN)
D =EQ(REMDR(X,I)) D + I :(D)
```
[Try it online!](https://tio.run/##jY4xC8IwEEbny6@4rXcYh4I4FDoE7goHJmpMobOz2MHdv17TDp3dHo/Hx/d5z8/5dVpAdLCk1AhNbA27XQSKPnHD0FHRR@E/UhcgYK93EopcDW6Y2EfGb@W0QosdZS1jTuwEDPtLIfMTHrFlNDxgC92wFyDbYNYomSZvzCi1sfpKeFmPwXUst7FgH@jsz@w0yfID "SNOBOL4 (CSNOBOL4) – Try It Online")
Defines a function `A` that computes the amicability of two numbers, returning `1` for amicable and the empty string for not. The algorithm is the same as my previous answer so I leave the old explanation below.
```
DEFINE('D(X)I') ;*function definition
M =INPUT ;*read M,N as input
N =INPUT
OUTPUT =EQ(D(M),N) EQ(D(N),M) ~EQ(N,M) 1 :(END) ;* if D(M)==N and D(N)==M and N!=M, output 1. goto end.
D I =LT(I,X - 1) I + 1 :F(RETURN) ;* function body: increment I so long as I+1<X, return if not.
D =EQ(REMDR(X,I)) D + I :(D) ;* add I to D if D%%I==0, goto D
END
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
```
&-FQqFms{*MyP
```
+4 bytes to check if values are distinct, I feel like that shouldn't be part of the challenge...
Can almost certainly be golfed a lot
[Try it online!](https://tio.run/##K6gsyfj/X01XTyuw0C23uFrLtzLg//9oMx0Fs1gA "Pyth – Try It Online")
---
```
&-FQqFms{*MyP Full program, takes input from stdin and outputs to stdout
-FQ Q0 - Q1 is true, meaning elements are distinct
& and
m Q for each element of the input list, apply
yPd take the powerset of the prime factors
{*M multiply each list and deduplicate
s and sum the list (this represents S(n)+n )
qF and fold over equality, returning whether the two elements are equal
```
[Answer]
# APL+WIN, ~~49~~ ~~54~~ ~~41~~ ~~40~~ 35bytes
Rewritten to reject equal integer inputs
Prompts for screen input of a vector of the two integers.
```
(≠/n)×2=+/n=⌽+/¨¯1↓¨(0=m|n)×m←⍳¨n←⎕
```
[Answer]
# APL NARS, 38 bytes, 18 chars
```
{≠/⍵∧∧/⍵=⌽-⍵-11π⍵}
```
11π⍵ find the sum of divisors of ⍵ in 1..⍵; note that the question want (11π⍵)-⍵ and in APLsm
```
-⍵-11π⍵=-(⍵-11π⍵)=(11π⍵)-⍵
```
the test
```
t←{≠/⍵∧∧/⍵=⌽-⍵-11π⍵}
t 284 220⋄t 52 100⋄t 10744 10856 ⋄t 174292 2345
1
0
1
0
t 100 117⋄t 6 11⋄t 495 495⋄t 6 6
0
0
0
0
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~7~~ ~~12~~ 10 bytes
Takes input as an array of 2 numbers.
```
®â¬xÃeUâ w
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=ruKseMNlVeIgdw==&input=WzYsNl0=)
---
* Added 3 bytes to handle `[6,11]`.
* Added another 3 bytes after the challenge was updated to require input validation. (Boo-urns on both fronts!)
* Saved 1 byte thank to Oliver.
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), ~~91~~ 86 bytes
```
: d { n } 0 n 1 do n i mod 0= i * - loop ;
: f { a b } a b = 1+ a d b = b d a = * * ;
```
[Try it online!](https://tio.run/##RYzNCsIwEITveYrBY6UliUl/qe/SGqqCmlAVD@Kz10kqmMB@s7uzM/n5ccqPU8SytHB444YPJKuC88QZV@8ge4oMOS7eB3QQLSZ6B4x0x9pDbSlckiM5kBl/x9gA7Z4B99cQUKDYAJuV@Z5qoj7M6ITQWgLQtWENwmqkp2ScBgglK2PSoLYlDaoyuqFJ74yNB6uRe1WlgBK/AIXUm8amfuV/vzIsyxc "Forth (gforth) – Try It Online")
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/) No Locals, 94 bytes
**A more "Forthy" version that doesn't use local variables**
```
: d 0 over 1 do over i mod 0= i * - loop nip ;
: f 2dup = 1+ -rot 2dup d -rot d = -rot = * * ;
```
[Try it online!](https://tio.run/##RYzNDsIgEITvPMWkxxoaQOhv6rsYEW2iQrDq4@MWTOTAfDs7O87H9covbpOURlgI@Pc5QsL6QgvunuyZoAbHzfuAxxIwsREOyr4CZsgdePRrGW1hS36GmQ5rTFQfSuD5OQY0aCqgKsoPRI74FKmYKQFA9Zr@wIxCflJsbgCTotM6G71pKSA7rQYKqb0220EJ0l52uaDFr0Aiz3oweS763xcNKX0B "Forth (gforth) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 67 bytes
```
function(a,b)sum(which(!a%%1:a))-a==b&sum(which(!b%%1:b))-b==a&b!=a
```
[Try it online!](https://tio.run/##TclBCoAgEADAe6@oQ7ELBipREe1jdgPRQwaV9HzLW7eBObOr1z67FLc7HBFYCV5ph8eHzUPDbWsWRuyZSLpfSAn5Qoi4k4Y4O7BWKzsPWDkwWitjpsLxA@YX "R – Try It Online")
returns `TRUE` for amicable, `FALSE` for not.
[Answer]
# [Perl 6](http://perl6.org/), 53 bytes
```
{([!=] $_)&&[eqv] .map: {set +$_,sum grep $_%%*,^$_}}
```
[Try it online!](https://tio.run/##JYpLDoIwGISvMppCfBDT/rYFFLgIwYZFcSMRQU0I4ey1yGIy3zw62z@0a0eEDXI37cpNXoGZfRiW9vWtcGrr7oJpsG8cmYmGT4t7bzt/CYJDdGNmnt1Qj9gyg7zA1Phl3qJ59siIOCiRRYRMEQTnCwkeS@lDovQ/xpJSAp2lWlcOIeIFtYfFZargtVa6uLof "Perl 6 – Try It Online")
Takes input as a list of two numbers.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~87~~ 96 bytes
```
param($a,$b)filter f($n){(1..($n-1)|?{!($n%$_)})-join'+'|iex}(f $a)-eq$b-and(f $b)-eq$a-and$a-$b
```
[Try it online!](https://tio.run/##HcdBCsIwEEDRq0QYaYaaYoMLdz2KTHCCkZjGKLTQ9uxj6ubzXx4nLp8HxyiSqdBLA53AoQ/xy0V5DQkX3XddHdPjOiyHeke44YbmOYbUtM0aeN60V0Bo@A3OULrvdH/SzlpwImLtWez18gM "PowerShell – Try It Online")
Takes input `$a,$b`. Defines a `filter` (here equivalent to a function) that takes input `$n`. Inside we construct a range from `1` to `$n-1`, pull out those that are divisors, `-join` them together with `+` and send that to `Invoke-Expression` (similar to `eval`).
Finally, outside the filter, we simply check whether the divisor-sum of one input is equal to the other and vice-versa (and input validation to make sure they're not equal). That Boolean value is left on the pipeline and output is implicit.
[Answer]
# Pyth, 12 bytes
```
q{_msf!%dTtU
```
Takes input as a list.
[Try it online](http://pyth.herokuapp.com/?code=q%7B_msf%21%25dTtU&input=%5B220%2C%20284%5D&debug=0)
### Explanation
```
q{_msf!%dTtU
m Q For each element d of the (implicit) input...
tUd ... get the range [1, ..., d - 1]...
f!%dT ... filter those that are factors of d...
s ... and take the sum.
{_ Reverse and deduplicate...
q Q ... and check if the end result is the same as the input.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes
```
ÙÑO¥`_`
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8MzDE/0PLU2IT/j/P9pMR8EsFgA "05AB1E – Try It Online")
[Answer]
## Batch, 127 bytes
```
@if %1==%2 exit/b
@set/as=t=%1+%2
@for /l %%i in (1,1,%s%)do @set/as-=%%i*!(%1%%%%i),t-=%%i*!(%2%%%%i)
@if %s%%t%==00 echo 1
```
Outputs `1` if the parameters are amicable. Works by subtracting all factors from the sum of the input numbers for each input number, and if both results are zero then the numbers are amicable.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~45 38 44 36 35~~ 20 bytes
```
{(≠/⍵)∧(⌽⍵)≡+/¨¯1↓¨(0=⍵|⍨⍳¨⍵)/¨⍳¨⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqjUedC/Qf9W7VfNSxXONRz14ws3Ohtv6hFYfWGz5qm3xohYaBLVC05lHvike9mw@tAKnQPwRn1wINUjAyMlAwsjDhSlMwNVIwNDAAMgwNzE1MgKSFqRmIZ25iZKlgZGxiCpYyUDA0NAeyzIA0kDKxNAVhsIAZAA "APL (Dyalog Unicode) – Try It Online")
Infix Dfn, fixed for the equal inputs case.
Thanks @Uriel for 8 bytes; @cole for 1 byte; @Adám for 15 bytes.
### How?
```
{(≠/⍵)∧(⌽⍵)≡+/¨¯1↓¨(0=⍵|⍨⍳¨⍵)/¨⍳¨⍵} ⍝ Main function, infix. Input is ⍵.
{ ⍳¨⍵} ⍝ Generate the range [1,n] for each element of ⍵.
/¨ ⍝ Replicate into each the resulting vectors of:
( ⍵|⍨⍳¨⍵) ⍝ ⍵ modulo each element of the ranges;
0= ⍝ Equals 0?
¯1↓¨ ⍝ Drop the last element of each
+/¨ ⍝ Sum of each
(⌽⍵)≡ ⍝ Check if the results match the inverse of ⍵.
∧ ⍝ Logical AND.
(≠/⍵) ⍝ Inputs are different
```
---
@Adám has also helped me with a ~~22~~ 20 byte tacit function that's equivalent to the Dfn:
```
≠/∧⌽≡(+/∘∊⍳⊆⍨0=⍳|⊢)¨
```
[Try it online!](https://tio.run/##ndLPSsNAEAbwe5/iO6aoZLPmT3voA3jyGQoSLwW9iuk1JMGIIIIXofVibh5KLwUveZR5kTizDSHVNK0uJLuzO98PwmZ6Ozu7upvObq4ryt8QUvx0T8mHbVG@oXRB@Xp4ap3YZVF@OhQ/l4WlJnwEPogoLyhflUVdD@1yt@bGNS8288EPOl3YnbCk0LCmatBtNaGHL1kw@fhyccmk6sHB4yAszUAL3stR8kpJ1kNSFh9AISgEBTrI7L1Fog2i5o6VJBMZ8J8OagY7itnBkJ3jEBkS4Sh/F@TfWUW118FIt0HY@wtD6XKvI3eQLttan1RJ3lz6ryR3blNNSPqrEFor6JE7COFpOErxwlGB6/J75PlSBa4eQ5@7njlScJyAVz7PPLljTx6z4X8D "APL (Dyalog Unicode) – Try It Online")
### How?
```
≠/∧⌽≡(+/∘∊⍳⊆⍨0=⍳|⊢)¨⍝ Tacit fn, takes one right argument.
( )¨ ⍝ For each element e of the argument
⍳|⊢ ⍝ e modulo range [1,e]
0= ⍝ Equals 0? This generates a boolean vector
⍨ ⍝ Swap arguments for the following op/fn
⊆ ⍝ Partition. This partitions the right vector argument according to 1-runs from a left boolean vector argument of same size.
⍳ ⍝ Range [1,e]
∊ ⍝ Enlist; dump all elements into a single vector.
∘ ⍝ And then
+/ ⍝ Sum the elements
⌽≡ ⍝ Check if the resulting sums match the inverse of the argument
∧ ⍝ Logical AND
≠/ ⍝ The elements of the argument are different.
```
[Answer]
# [Red](http://www.red-lang.org), 117 bytes
```
d: func[n][s: 0 repeat i n / 2[if n // i = 0[s: s + i]]]
a: func[n m][either(m = d n)and(n = d m)and not n = m[1][0]]
```
[Try it online!](https://tio.run/##TctNDoMgEAXgvad4S5suhCn4l/QS3ZJZmIIpC6hBe34rTbQuhryPeZOcXR/OwvBqe4yf@DSRzdxDILnJDQs8IiqQ8WMO1eY7RG7MuMIzczHshwhsnF9eLpVha1nEyxBtGX855Iz4XpAdjGQjmNcp@bhgAJEAtarYrQlSiINSNEptb6vr/1@jqCPQTelTT0DK5nC96YDqdJ7Tsl6/ "Red – Try It Online")
[Answer]
# [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 87 bytes
```
a->b->a!=b&f(a)==b&f(b)==a
int f(int n){int s=0,d=0;for(;++d<n;)s+=n%d<1?d:0;return s;}
```
[Try it online!](https://tio.run/##lY8/T8MwEMX3fgozgGxKLSck/YObsiExICF1RAxO7FQuiRPZl6Kq6mcPTki7sITB907n@@m924uDmFW1Mnv5tWp1WVcW0N4PaQO6oPd88meWNyYDXZnus27SQmcoK4Rz6E1og04ThF4NvAxLa9@/WyV1JkBtUI6SVsw26WwjbpL0LseCJL2mXgXXBlCOu2rIqROXsAeZMJ5XFvPpVK4NJ26amFu5Dp7lE@NWQWMNcvzccu885HEgwMuh0hKVPhXegtVm9/GJhN050odEv3nLxKjvvsWE9@Pt0YEqadUArT0FhcElzamo6@KIw5ARCsoBDpcRGUPE4QAEjI0CAraIoiuzjOfjqEUUri5W4WMUj/S6nBMEi1HE/Lo/aj1axQPQdf8xuJzt33lybn8A "Java (OpenJDK 9) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
∆KUṘ⁼
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oiGS1XhuZjigbwiLCIiLCJbMjIwLCAyODRdXG5bNTIsIDEwMF1cblsxMDc0NCwgMTA4NTZdXG5bMTc0MjkyLCAyMzQ1XVxuWzEwMCwgMTE3XVxuWzYsIDExXVxuWzQ5NSwgNDk1XVxuWzYsIDZdIl0=)
] |
[Question]
[
Let `n` be the number of times your program has been executed. If `n` is a power of 2, then print `2^x` where `n = 2^x`; otherwise, simply output the number. Example run:
```
[1st time] 2^0
[2nd time] 2^1
[3rd time] 3
[4th time] 2^2
[5th time] 5
```
and so on. This is a popularity contest, so the answer with the most upvotes wins..
[Answer]
## Java - API Abuse
There are plenty of computers online that can count, so why store the count myself?
Full-on abuse of the Stack API to get quota and remaining quota to see how many times it's been run today:
```
public static void main(String[] args) throws Exception {
URLConnection c = new URL("http://api.stackexchange.com/2.2/info?site=stackoverflow").openConnection();
c.setRequestProperty("Accept-Encoding", "gzip");
GZIPInputStream gz = new GZIPInputStream(c.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(gz));
String reply = r.readLine();
r.close();
reply = reply.substring(reply.indexOf("quota_max"), reply.length()-1);
String[] t = reply.split("[:,]");
int runs = Integer.parseInt(t[1]) - Integer.parseInt(t[3]);
if((runs & (runs -1)) == 0){
int exp = 0;
while(runs % 2 == 0){
runs = runs >> 1;
exp++;
}
System.out.println("2^" + exp);
} else {
System.out.println("" + runs);
}
}
```
Obviously this only works with a fresh daily quota for your IP, and only *up to* the quota. If you want support for higher numbers, post a [feature-request] to raise `quota_max` to `MAX_INT`.
[Answer]
# JavaScript
`alert((n=Math.log((l=localStorage).m=~~l.m+1)/Math.log(2))==(n|0)?"2^"+n:l.m)`
Successive alerts are as follows:
```
2^0
2^1
3
2^2
5
6
7
2^3
9
...and so on.
```
[Answer]
## C – writing to the executable
This C code updates the string `data` in the executable, so essentially this is self-modifying code. If you run it over 9,999,999 times, you get interesting stuff.
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char **argv){
// 'abcdefghijklmnopqrstuvwxyz1' << that's 27 characters inside the quotes
const char *data="Da best marker in da world 1\0\0\0\0\0\0";
FILE *f;
int i,n,m;
char c;
long int pos;
m=n=strtol(data+27,NULL,10);
i=0;
while(1){
if(n==0){
printf("This code should never have been reached... Unless you've messed with my executable.\n");
return 1;
}
if(n==1){
printf("2^%d\n",i);
break;
}
if(n&1){
printf("%d\n",m);
break;
}
i++;
n>>=1;
}
f=fopen(argv[0],"r+b");
i=0;
c=fgetc(f);
while(!feof(f)){
if(data[i]==c){
i++;
if(i==27)break;
} else i=0;
c=fgetc(f);
}
if(i!=27)return 1;
n=0;
pos=ftell(f);
c=fgetc(f);
while(c!='\0'){
n=10*n+c-'0';
c=fgetc(f);
}
n++; //The big increment!
fseek(f,pos,SEEK_SET);
fprintf(f,"%d",n);
fflush(f);
fclose(f);
return 0;
}
```
[Answer]
# Java
The following code modifies it's own class file to store the new run count. This was especially fun when you had no idea how the byte code looks, but after countless hours of Googling and Testing it finally works! :)
Demo (using 7 as starting value for demo purposes):
```
[timwolla@/data/workspace/java]javac Runs.java
[timwolla@/data/workspace/java]java Runs
7
[timwolla@/data/workspace/java]java Runs
2^3
[timwolla@/data/workspace/java]java Runs
9
[timwolla@/data/workspace/java]java Runs
10
```
Code:
```
import java.io.*;
import java.util.*;
class Runs {
public static void main(String[] args) throws Exception {
// RUN-- makes the string easy to find in the byte code
String runString = "RUN--1";
// extract the number
int runs = Integer.parseInt(runString.substring(5));
// output the number properly
int power = 0;
boolean outputted = false;
while (Math.pow(2, power) <= runs) {
if (Math.pow(2, power) == runs) {
outputted = true;
System.out.println("2^"+power);
}
power++;
}
if (!outputted) System.out.println(runs);
// increase run count
runs++;
// build new string
String newRunString = runString.substring(0, 5) + runs;
// get folder of class file
String folder = Runs.class.getProtectionDomain().getCodeSource().getLocation().getFile();
// append class file name
String me = folder + "/Runs.class";
// and open it up
RandomAccessFile in = new RandomAccessFile(me, "rw");
int read;
int state = 0;
while ((read = in.read()) != -1) {
char c = (char) read;
// state machine to find the RUN--
switch (state) {
case 0:
// 2 bytes before: upper byte of the two byte length
if (c == ((runString.length() >> 8) & 0xFF)) state++;
break;
case 1:
// 1 byte before: lower byte of the two byte length
if (c == (runString.length() & 0xFF)) state++;
else state = 0;
break;
case 2:
if (c == 'R') state++;
else state = 0;
break;
case 3:
if (c == 'U') state++;
else state = 0;
break;
case 4:
if (c == 'N') state++;
else state = 0;
break;
case 5:
case 6:
if (c == '-') state++;
else state = 0;
break;
case 7:
// we found run, now: Modify byte code
// back to the bytes that determine the length
in.seek(in.getFilePointer() - 8);
// expand the file if neccessary
int lengthChange = (newRunString.length() - runString.length());
in.setLength(in.length() + lengthChange);
// write new length
in.writeByte(((newRunString.length() >> 8) & 0xFF));
in.writeByte((newRunString.length() & 0xFF));
// length changed, shift all the following bytes by one
if (lengthChange > 0) {
long target = in.getFilePointer();
in.seek(in.length() - 1 - lengthChange);
while (in.getFilePointer() > target) {
in.write(in.read());
in.seek(in.getFilePointer() - 3);
}
in.seek(target);
}
// write new string
in.writeBytes(newRunString);
return;
case 8:
}
}
}
}
```
[Answer]
# perl
Here's a short bit of perl to do it. Where should the data be stored? Why in the program file itself, of course! =)
```
$b = sprintf '%b', $x=x();
print $b=~/^10*$/ ? "2^".(length($b)-1) : $x, "\n";
open F, "+<", $0;
seek F, -3-length $x, 2;
print F $x+1, " }\n";
sub x { 1 }
```
Originally I had used the magic DATA file handle like so, but I feel the above is "purer":
```
$b = sprintf '%b', $x = <DATA>;
print $b =~ /^10*$/ ? "2^".(length($b)-1)."\n" : $x;
open F, "+<", $0;
seek F, -length $x, 2;
print F $x+1, "\n";
__DATA__
1
```
[Answer]
# dg
Here I present you a portable code! At every run a `#` is added at the end, making a progress bar! Also, you can move the code to another machine and resume from where you were.
```
import '/math'
with fd = open __file__ 'r' =>
code = fd.read!
times = code.count('#') - 2
with fd = open __file__ 'w' =>
fd.write $ code.rstrip! + '#'
exp = math.log2 times
if exp.is_integer! => print $ '2^{}'.format $ int exp
otherwise => print times
#
```
After 18 times:
```
import '/math'
with fd = open __file__ 'r' =>
code = fd.read!
times = code.count('#') - 2
with fd = open __file__ 'w' =>
fd.write $ code.rstrip! + '#'
exp = math.log2 times
if exp.is_integer! => print $ '2^{}'.format $ int exp
otherwise => print times
###################
```
[Answer]
**Sinatra-based Ruby Example**
This server-based solution stores a personal counter for each user in a cookie.
Try it at <http://every-2-to-the-n-times.herokuapp.com/>
```
require 'sinatra'
require 'sinatra/cookies'
# https://github.com/sinatra/sinatra-contrib/issues/113
set :cookie_options, :domain => nil
get '/' do
x = cookies[:x].to_i || 1
cookies[:x] = x + 1
# power of 2 test from http://grosser.it/2010/03/06/check-if-a-numer-is-a-power-of-2-in-ruby/
return (x & (x - 1) == 0) ? "2^#{Math.log2(x).to_i}" : x.to_s
end
```
[Answer]
## Bash
Simple self-editing shell script.
```
n=1;e=0;p=1
sed -i s/"n=$n"/"n=`expr $n + 1`"/g $0
if [[ $n -eq $p ]];then
echo 2^$e
sed -i s/"p=$p"/"p=`expr $p \* 2`"/g $0
sed -i s/"e=$e"/"e=`expr $e + 1`"/g $0
else
echo $n
fi
```
[Answer]
# Bash
I like [dfernig](https://codegolf.stackexchange.com/users/15604/dfernig)'s [Bash solution](https://codegolf.stackexchange.com/questions/22821/every-2n-times/22950#22950), but I would like to post mine as well:
```
n=$(expr `cat $0|wc -c` - 170)
if [ $(echo "obase=2;$n"|bc|grep -o 1|wc -l) == 1 ]
then echo -n "2^"; echo "obase=2;$n"|bc|grep -o 0|wc -l;
else echo $n; fi
echo "" >> $0
```
I think the solution can be considered different, because
* the code actually executed doesn't change
* the program dinamically calculates if **n** is a power of 2
The "memory" is the script size (initially 171 bytes), which is increased by 1 with the append of a newline at each execution.
Powers of 2 are recognized by converting the program size (minus 170, of course) to binary, and then counting the ones: if there is exactly one one, then **n** is a power of 2. The exponent is the number of zeros in binary.
[Answer]
# Java solution
Uing the java preferences API to store the run amount; and precalculated the powers of 2 for a hashmap to compare
```
import java.util.HashMap;
import java.util.prefs.Preferences;
class Pow
{
public static void main(String[]a)
{
int rt = Integer.valueOf(Preferences.userRoot().get("Pow.run", "1"));
HashMap<String,Integer> powof2 = new HashMap<>();
//pregenerating the powers of 2;
for (int i = 0; i < 46340; i++)//highest power of 2 before int overflow
{
powof2.put(((int)Math.pow(2, i))+"",i);
}
if(powof2.containsKey(rt+""))
{System.out.println("2^"+powof2.get(rt+""));}
else
{
System.out.println(rt);
}
rt++;
Preferences.userRoot().put("Pow.run", ""+(rt));
}
}
```
[Answer]
## Javascript
I chose to not use the obvious `log2` solution but work with bitwise operators to find the single bit position in the binary representation of power of 2 numbers.
```
Number.prototype.singleBitPosition = function() {
var r=1, k;
if (this==0) return -1;
while(this==(k=this>>r<<r)) r++; //set r last bits to zero and compare
return k?-1:r; //if k is zero, there is one single bit to 1 in number representation ie power of 2
};
var n;
if (n === undefined) n=0;
n++;
var e = n.singleBitPosition();
if (e > 0) {
console.log('2^'+(e-1));
} else {
console.log(n);
}
```
[Answer]
## Ruby
Alright, I think I'll try this now. It searches itself for the definition of `n`.
```
def p2 n
n == 1 ? 0 : p2(n >> 1) + 1
end
n = 1
if (n != 0) & (n & (n - 1) == 0) || n == 1
puts("2^" + (p2(n).to_s))
else
puts n
end
contents = File.read(__FILE__)
newContents = contents.gsub(/(?<=n \= )[0-9]+/) {|n| (n.to_i + 1).to_s}
File.write(__FILE__, newContents)
```
(tested in Ruby 1.9.3)
[Answer]
# Fortran 77
**Code:**
```
program twok
rewind 1
read(1,'(I20,I3)',end=10,err=30)n,k
go to 20
10 n=-1
k=0
20 n=n+1
if (n .eq. 2**k) then
if (k.le.9) then
write(*,'(A3,i1)')' 2^',k
else
write(*,'(A3,i2)')' 2^',k
endif
k=k+1
else
write(*,*)n
endif
if (n .lt. 0) then
n=-1
k=0
endif
rewind 1
write(1,'(I20,I3)')n,k
30 continue
end
```
**Result:**
```
$ ./a.out ! $ ./a.out
2^0 ! 2^1
$ ./a.out !
2^1 ! $ while true
$ ./a.out ! > do
3 ! > ./a.out | grep "2^"
$ ./a.out ! > done
2^2 ! 2^2
$ ./a.out ! 2^3
5 ! 2^4
$ ./a.out ! 2^5
6 ! ...
... ! 2^12
$ ./a.out ! 2^13
2147483647 ! ^C # (after about 5 minutes)
$ ./a.out ! $ ./a.out
2^31 ! 14718
$ ./a.out ! $ ./a.out
0 ! 14719
$ ./a.out ! $
2^0 !
```
[Answer]
# C
One of the "proper" ways to do it (without using files, that is).
You can give it `reset` on the command line to set it back to zero. You can also move or copy the executable around. Moving the executable resets it, and multiple copies of the executable are independent.
```
#include <stdio.h>
#include <sys/msg.h>
#include <sys/shm.h>
int main(int argc, char **argv) {
// get a shared memory segment associated with our program
long key = ftok(argv[0], 1);
long id = shmget(key, sizeof(long), 0666 | IPC_CREAT);
long *num = (long*) shmat(id, NULL, 0);
// reset parameter
if (argc == 2 && !strcmp(argv[1], "reset")) {
*num = 0;
}
if (*num & *num-1) {
// not a power of two
printf("%li\n", *num);
} else {
// power of two
int exp = 0;
int n=*num;
while (n >>= 1) exp++;
printf("2^%d\n", exp);
}
++*num;
// detach from shared memory
shmdt(num);
return 0;
}
```
[Answer]
Sparkling, 423 characters (yet another self-modifying code). Save it as `count.spn` then run `spn count.spn`:
```
var n =
19
;
var l = log2(n);
if l == floor(l) {
printf("2 ^ %d\n", floor(l));
} else {
printf("%.0f\n", n);
}
var f = fopen("count.spn", "rb");
var g = fopen("count.spn.2", "wb");
var line = fgetline(f);
fprintf(g, "%s", line);
fprintf(g, "%d\n", n + 1);
fgetline(f);
while (line = fgetline(f)) != nil {
fprintf(g, "%s", line);
}
fclose(f);
fclose(g);
```
[Answer]
Here's a quick Python 3 solution, which uses a data file to store `n` and `x` between runs:
```
try:
with open("count.txt") as f:
n, x = map(int, f.readline().split())
except FileNotFoundError:
n = x = 0
n += 1
if n == 2**x:
print("2^{}".format(x))
x += 1
else:
print(n)
with open("count.txt", "w") as f:
f.write("{} {}".format(n, x))
```
The output of running it 16 times:
```
2^0
2^1
3
2^2
5
6
7
2^3
9
10
11
12
13
14
15
2^4
```
[Answer]
# Python 2
```
import inspect
import math
file_name = inspect.getfile(inspect.currentframe())
n = int(open(file_name).readlines()[-1].strip())
l = math.log(n, 2)
if int(l) == l:
print '2^%d' % (l)
else:
print n
with open(file_name, 'a') as f:
f.write('%d\n' % (n + 1))
1
```
[Answer]
# C#
```
static void Main()
{
ulong cnt = ++Properties.Settings.Default.NumberOfExecutions ;
int? log2 = Log2( cnt ) ;
Console.WriteLine( log2.HasValue ? "2^{0}" : "{1}" , log2 , cnt ) ;
Properties.Settings.Default.Save() ;
return ;
}
static int? Log2( ulong m )
{
int? n = null ;
if ( m > 0 )
{
n = 0 ;
// find the first set bit
ulong mask = 0x0000000000000001ul ;
while ( mask != 0 && 0ul == (m&mask) )
{
mask <<= 1 ;
++n ;
} ;
// if the mask is identical to m,
// we've got a power of 2: return n, otherwise null
n = mask == m ? n : null ;
}
return n ;
}
```
This does, though, require that you define a settings property in your Visual Studio project:

[Answer]
# C/POSIX
This program uses the number of hard links to its own executable as counter of how often it was called. It creates the new hard links in the directory it was started from (because that way it's guaranteed to be on the same file system), which therefore needs write permission. I've omitted error handling.
You better make sure that you have no important file with the same name as one of the created hard links on that directory, or it will be overwritten. If e.g. the executable is named `counter`, the hard links will be named `counter_1`, `counter_2` etc.
```
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
/* get persistent counter */
struct stat selfstat;
stat(argv[0], &selfstat);
int counter = selfstat.st_nlink;
/* determine digits of counter */
int countercopy = counter;
int digits = 1;
while (countercopy /= 10)
++digits;
/* increment persistent counter */
char* newname = malloc(strlen(argv[0]) + digits + 2);
sprintf(newname, "%s_%d", argv[0], counter);
link(argv[0], newname);
/* output the counter */
if (counter & (counter-1)) // this is zero iff counter is a power of two
printf("%d\n", counter);
else
{
/* determine which power of 2 it is */
int power = 0;
while (counter/=2)
++power;
printf("2^%d\n", power);
}
return 0;
}
```
Example run (the first line resets the counter, in case the executable has already been run):
```
$ rm counter_*
$ ./counter
2^0
$ ./counter
2^1
$ ./counter
3
$ ./counter
2^2
$ ./counter
5
$ ./counter
6
$ ./counter
7
$ ./counter
2^3
$ ./counter
9
$ ls counter*
counter counter_2 counter_4 counter_6 counter_8 counter.c
counter_1 counter_3 counter_5 counter_7 counter_9 counter.c~
```
[Answer]
# Fortran 95
A file named "a" (without extension) keeps track of the run of the program.
```
logical::l
inquire(file="a",exist=l)
open(unit=11,file="a")
if (l) then
read(11,*)n
close(unit=11,status="delete")
open(unit=11,file="a")
n=n+1
write(11,*)n
do i=1,n
if (2**i==n) then
write(*,"(A2,I1)")"2^",i
goto 1
endif
enddo
print*,n
else
print*,"2^0"
write(11,*)1
endif
1 end
```
] |
[Question]
[
One way to generalize the concept of a range from the integers to the Gaussian integers (complex numbers with integer real and imaginary part) is taking all numbers contained in the rectangle enclosed by the two ends of the range. So the range between two Gaussian integers `a+bi` and `c+di` would be all Gaussian integers `x+iy` with `min(a,c)<=x<=max(a,c)` and `min(b,d)<=y<=max(b,d)`.
For instance the range from `1-i` to `-1+2i` would be the following set of numbers:
`-1-i, -1, -1+i, -1+2i, -i, 0, i, 2i, 1-i, 1, 1+i, 1+2i`
Your task is given two numbers `a+bi` and `c+di` to return the 2D range spanned by `a+bi` to `c+di`
## Examples
```
1 5 -> [1,2,3,4,5]
5 1 -> [5,4,3,2,1]
-1 -3 -> [-3,-2,-1]
1+i 1+i -> [1+i]
1-i -1+2i -> [-1-i, -1, -1+i, -1+2i, -i, 0, i, 2i, 1-i, 1, 1+i, 1+2i]
1-i 2+i -> [1-i, 1, 1+i, 2-i, 2, 2+i]
-2-i -1+3i -> [-2-i, -2, -2+i, -2+2i, -2+3i, -1-i, -1, -1+i, -1+2i, -1+3i, -i, 0, i, 0+2i, 0+3i, 1-i, 1, 1+i, 1+2i, 1+3i]
```
## Rules
* You can use pairs of integers to Input/Output Complex numbers
* If your language has a built-it for generating this range, please consider adding a non built-in answer as well
* The elements in the range can be sorted in any order
* Each element can only appear once in the range
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest solution (per language) wins
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes
```
ṡΠ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLhuaHOoCIsIiIsIlsxLCAtMV1cblstMSwgMl0iXQ==)
```
ṡ # Vectorised range
Π # Cartesian product
```
[Answer]
# [J](https://www.jsoftware.com), 20 bytes
```
<.+"1[:(#:,@i.)1+|@-
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxxUZPW8kw2kpD2UrHIVNP01C7xkEXIrVJkys1OSNfwVAh3kghTSHeWMEEIrFgAYQGAA)
For positive integers `x` and `y`, `i.(x,y)` creates a matrix of
```
0 1 2 ... y-1
y y+1 y+2 ... 2y-1
...
(x-1)y (x-1)y+1 (x-1)y+2 ... xy-1
```
Then `(x,y)#:` converts each number `iy + j` to a pair `(i,j)`.
```
<.+"1[:(#:,@i.)1+|@- Input: two pairs of integers
|@- Elementwise absolute difference
1+ Add 1 to each
[:( ) Apply monadically:
,@i. Create 2D range and flatten
#: Base convert as described above
<.+"1 Add elementwise minimum of two inputs to each row
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 18 bytes
```
++/(!1--)\(&;|)@\:
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs9LW1tdQNNTV1YzRULOu0XSIseLiSos2VNA1tAZiBaNYMM/IWgHONrBWMFUwiAUAeKYMgQ==)
-1 thanks to ovs.
# [K (ngn/k)](https://codeberg.org/ngn/k), 19 bytes
```
{+a+!1+(x|y)-a:x&y}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rWTtRWNNTWqKip1NRNtKpQq6zl4kqLNlTQNbQGYgWjWDDPyFoBzjawVjBVMIgFANiWDmg=)
A function that takes two complex numbers as integer pairs `x` and `y`.
`!(x,y)` generates a two-row matrix whose columns are the cartesian pairs of `0..x` and `0..y` (excluding x and y).
[Answer]
# [J](https://www.jsoftware.com/), 47 bytes
The following dyad does the job, taking as left and right arguments the range edges:
```
([:>@,@{(<.<@:+i.@(+_1+2*0&<:)@:-~)/"1@,.)&.:+.
```
J uses ajb for denoting the number a+b\*i, for instance:
```
1j1 ([:>@,@{(<.<@:+i.@(+_1+2*0&<:)@:-~)/"1@,.)&.:+. 2j2
1j1 1j2 2j1 2j2
```
See this [Demonstration on the J playground](https://jsoftware.github.io/j-playground/bin/html2/#code=NB.%20name%20the%20solution%0Agr%20%3D%3A%20%28%5B%3A%3E%40%2C%40%7B%28%3C.%3C%40%3A%2Bi.%40%28%2B_1%2B2*0%26%3C%3A%29%40%3A-%7E%29%2F%221%40%2C.%29%26.%3A%2B.%0ANB.%20single%20application%0A1j2%20gr%20_1j_1%0A1j1%20%28%5B%3A%3E%40%2C%40%7B%28%3C.%3C%40%3A%2Bi.%40%28%2B_1%2B2*0%26%3C%3A%29%40%3A-%7E%29%2F%221%40%2C.%29%26.%3A%2B.%202j2%0ANB.%20examples%20checking%0Aex%20%3D%3A%20_2%20%5D%5C%201%205%20_1%20_3%201j1%201j1%201j_1%20_1j2%201j_1%202j1%201j_1%20_1j3%0ANB.%20count%20of%20gaussian%20integers%20and%20themselves%20in%20boxes%0A%20%20%20%28%2C.%7E%20%20%20%20%20%20%20%23%26.%3E%29%20%3C%40%20%20%2F%3A%7E%20%20%40%3Agr%20%2F%20%20%20%20%20%20%20%221%20%20%20%20%20%20ex%0ANB.%20prepend%20counts%20%20box%20sorted%20gr%20between%20rows%20of%20ex) (press the "run" button on the upper right of the editor).
## Explanation
```
([: >@,@{ (<.<@:+i.@(+_1+2*0&<:)@:-~) /"1@,.) &.:+.
__ _____ ___________________________ ___ __ _____: under complex decompose
cap | | | \combine real and imag parts
| | \insert verb in () in each row
| \ verb creating boxed real/imag ranges (explained below)
\ open raveled Carthesian product between boxed coordinate ranges
<. <@:+ i.@(+_1+2*0&<:)@:-~ fork; takes x, y and returns a boxed range.
___ ____ __ ____________ __
| | | | \_ difference between y and x
| | | \_ adjust diff s.t. works for empty and reversed ranges
| | \_ range from 0 to y-1
| \_ add min and range and box the result
\_ min of x and y
```
[Answer]
# [Raku](https://raku.org/), 41 bytes
```
{($^x.re...$^y.re)X+(($x.im...$y.im)X*i)}
```
[Try it online!](https://tio.run/##XcpBCoMwEAXQq3wkSNKYYJR2pTmHUFS6MBCotKQbg/Xs6SiFQjf/z5uZ5xTulzRH5A5tWjkbFh0mrTUbIg2ik5yzRft5X0Vq0Z282NLrFpGx8Vr2UKA2PVqL1eHNxi2DewQ0RpYeZwpboFGHVP2lkcZjjwOKQA/VT9XfqfY2fQA "Perl 6 – Try It Online")
This anonymous function takes two complex numbers are arguments.
`$^x.re ... $^y.re` is the range of integers between the real parts of the arguments; `...` is smart enough to make a decreasing range as appropriate. Similarly, `$x.im ... $y.im` is the range of integers between the imaginary parts of the arguments. `X* i` multiplies each element of the latter range by `i`, and `X+` crosses the two ranges together with addition.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
rp/
```
A dyadic Link that accepts the two pairs of real and imaginary parts and yields a list of pairs of real and imaginary parts.
**[Try it online!](https://tio.run/##y0rNyan8/7@oQP/////RRjq6JrH/o011zGMB "Jelly – Try It Online")**
### How?
```
rp/ - Link: [R1, I1]; [R2, I2]
r - inclusive range -> [[R1..R2], [I1..I2]]
/ - reduce by:
p - Cartesian product
```
---
`rŒp` does the same thing, where `Œp` is the Cartesian product of the items of `[[R1..R2], [I1..I2]]`.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 49 bytes
```
eval echo \{${1%,*}..${2%,*}},\{${1#*,}..${2#*,}}
```
[Try it online!](https://tio.run/##TchBCsIwEIXhvad4YNyUSemkuPIotYtoBiIEA1bqIs3ZY2I3Lob53n@ziy8f/wiCl1iHgG3DNEEFzPPFRSzyhtZ1F1ltgNx9xDWpxCfqct@rZBoy/dqxo7015OLiUwrTgDMNB92gxyomRr36NaNms8v8pfEL "Bash – Try It Online")
[Answer]
# [Desmos](https://desmos.com/calculator), 44 bytes
```
f(A,B)=[(X,Y)forX=[A.x...B.x],Y=[A.y...B.y]]
```
Complex numbers \$a+bi\$ are represented with coordinate pairs \$(a,b)\$. Input is two coordinate pairs, output is a list of coordinate pairs.
[Try It On Desmos!](https://www.desmos.com/calculator/nmkwlrn3gv)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/u8vnvtrygm)
[Answer]
# [R](https://www.r-project.org), 30 bytes
```
\(a,b,c,d)expand.grid(a:c,b:d)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZBRCsIwDIbx1VMUfFlZIm3qQAS9ggdQHzbnpC8iouBdfJmC1_AgnsYkHUNQlrTNn6_Nz273U_to5s_LucHpa52VUMEWaru7HstDPd6fYp2Vsy1Us9om6D1YNpkHBwU4a4wZceLCrDwQBJhAsRk2GQqAQQjpK8AlEqCXvgf90n29ncekowbZTkePEQwrnLmecpKN04HhVSplGFFCgP4p0hmjzuE3RlIQRxqsziSC7WhUgnVOnUxpMuVBffz35VO3t-dUdqr-2JQ1xE36r22b9g8)
Takes input as four numbers `a,b,c,d` and returns a matrix with real and imaginary parts in columns.
---
# [R](https://www.r-project.org), 35 bytes
```
\(x,y)outer(x:y,Im(x):Im(y)*1i,`+`)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZDBCsIwDIbx6lMMvLQ2gTVVEEHvPoMOdnHQgwhjwvYsXqbgQ-nTmKZubmhpkzb_R_q311vZ3ovN41IVuHrODqqGRp8v1bFU9bqB3UnVes2x0XPrITe5juhrUhbKQhLH8pP1LMFtsrdA4GABy2xaKOwodCMIHSAB2sBYw81FDLtBI-NFxk5Ga8h_W1jkeriA67JjlROvFBKO4SQMI0IEYNyRxhcOYQoH4hldIA1tON-7EI7fwktcUHRBzARP_z3aqPZWUymnUv2xHKLzWfz6to35DQ)
Input and output as complex numbers.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 58 bytes
```
->a,b{r,i=a.zip b;[*r.min..r.max].product [*i.min..i.max]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY9RTsMwDIbfcwo_8LCtTkayTUJDLQ8co1RVu6UQqduqLIXB6El4mQRchhvsNrhJBYvk_PHn37by8WXb8vX0WcUP362r-M15yZMCy6NFExfizTRQ3qYTKzZmKwRJcchEY3frduUgnZjAjefdMMEZiEEa9vJkag2P2u0Z0EjUhK9ysW9q40ZTGN0t4Z0n42g6pvbmqJ-LGnLZMWjAkrVKC2H1yiGUXjPvut9tmlofyIi56hBsHGumt-uw-3T-kRDOIghPIJWocIZzXGSMD2U--6vyGXKFXGZMRsbTQX1rZIjzwLmMlBmaiCGBPiL_ohIJxTUC3X3mPWTxjt7wP0pdrLh0qT5R2Nez8KVf)
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 29 bytes
```
";"zip Q*
,""sort"1+"' ,_ a>b
```
[Try it here!](https://replit.com/@molarmanful/try-sclin) Inputs/outputs pairs representing complex numbers.
For testing purposes:
```
[1 1_ ] [1_ 3] ; >A
";"zip Q*
,""sort"1+"' ,_ a>b
```
## Explanation
Prettified code:
```
\; zip Q*
, () sort 1.+ ' ,_ a>b
```
* `\; zip` zip inputs...
+ `, () sort` pair and sort ascending
+ `1.+ '` increment second number in pair
+ `,_ a>b` exclusive range from pair
* `Q*` Cartesian product
An inclusive range function would actually provide a substantial byte-save here, entirely removing the need to sort/increment pairs.
[Answer]
# Excel, 155 bytes
```
=LET(
a,+A1:A2,
b,HSTACK(SORT(IMREAL(a)),SORT(IMAGINARY(a))),
c,LAMBDA(d,LET(e,INDEX(b,1,d),+SEQUENCE(1+INDEX(b,2,d)-e,,e))),
TOCOL(COMPLEX(c(1),TOROW(c(2))))
)
```
Inputs are complex numbers in cells `A1` and `A2`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
Fθ⊞υ⊟ιIΣE…·⌊υ⌈υE…·⌊⌊θ⌈⌈θ⟦λι
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjfnpeUXKWgUaioElBZnaJTqKATkF2hkampacwUUZeaVaDgnFpdoBJfmavgmFmh45iXnlBZnlqUGJealp2r4ZuZl5gKlSjV1FHwTK6BsMAenWhhdqImkCUYDBYGi0Tk6CpmxmiBgvaQ4KbkY6tbl0Uq6ZTlKsVuio6MNdRR0DWOBanWBLKPY2FiIEgA) Link is to verbose version of code. Uses pairs of integers for I/O, and takes a pair of pairs as input. Explanation:
```
Fθ⊞υ⊟ι
```
Separate out the imaginary parts.
```
IΣE…·⌊υ⌈υE…·⌊⌊θ⌈⌈θ⟦λι
```
Form inclusive ranges over the imaginary and real parts and make into pairs.
Previous 19-byte answer only worked with ascending ranges:
```
IΣE…·⊟θ⊟ηE…·ΣθΣη⟦λι
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjeTA4oy80o0nBOLSzSCS3M1fBMLNDzzknNKizPLUoMS89JTNQLyCzQKNXUUQHSGJpCBRQ1IK0gNiAaric7RUciM1QQB6yXFScnFUAuXRyvpluUoxW6MjjbUUdA1jAUqNdJRMIyNhcgDAA) Link is to verbose version of code. Uses pairs of integers for I/O. Explanation:
```
…· Inclusive range from
⊟θ First imaginary part to
⊟η Second imaginary part
E Map over values
…· Inclusive range from
Σθ First real part to
Ση Second real part
E Map over values
λ Real part
ι Imaginary part
⟦ Make into pair
Σ Flatten 1 level
I Cast to string
Implicitly print
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
:i:Z*
```
Input: two cell arrays of two numbers each. Output: pairs of numbers separated by newlines.
[**Try it online!**](https://tio.run/##y00syfn/3yrTKkrr//9qXSMFXcNarmpdQwXjWgA "MATL – Try It Online")
### Explanation
```
: % Implicit input: cell array of two numbers. Range
i: % Input: cell array of two numbers. Range
Z* % Cartesian product. Implicit display
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ø€Ÿ`â
```
Input as a pair of pairs of regular integers.
[Try it online](https://tio.run/##yy9OTMpM/f//8I5HTWuO7kg4vOj//@hoIx1dk1idaFMd89hYAA).
**Explanation:**
```
ø # Zip/transpose the (implicit) input 2x2-block, swapping rows/columns
€ # Map over both pairs:
Ÿ # Convert the pair to a ranged list
` # Pop and push both lists separately to the stack
â # Pop both, and create all possible pairs with the cartesian product
# (after which the result is output implicitly)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
I/O as pairs of integers
```
ÕËrõÃrï
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1cty9cNy7w&input=W1sxLC0xXSxbLTEsMl1dCi1R)
```
ÕËrõÃrï :Implicit input of 2D integer array
Õ :Transpose
Ë :Map
r : Reduce by
õ : Inclusive range
à :End map
r :Reduce by
ï : Cartesian product
```
[Answer]
# [Haskell](https://www.haskell.org) + [hgl](https://www.gitlab.com/wheatwizard/haskell-golfing-library), 9 bytes
```
sQ<<zW eR
```
Takes two lists of length two as input.
```
>>> (sQ<<zW eR) [1,2] [-3,3]
[[1,2],[1,3],[0,2],[0,3],[-1,2],[-1,3],[-2,2],[-2,3],[-3,2],[-3,3]]
```
## Explanation
* `zW eR` zip with the reversable range
* `sQ` generalized cartesian product
## Reflection
* There should be a builtin for cartesian product. `l2(,)` is way too long.
* At this point `Uc` should be promoted to `U`. `Uc` is frequently used and its not like there is anything else that is going to use the `U` character.
* There should be a couple of things in terms of arrows that could be implemented for this.
[Answer]
# [Mathematica](https://www.wolfram.com/wolframscript/), 100 bytes
100 bytes, it can be golfed much more.
[Try it online!](https://tio.run/##hVCxasMwEN31FUfWngc5dKkxGFIKGQolFDqII8hFaQS2U2QNASP/unuy5XjsIr137947nVrtr6bV3n7raboofcb6TC/lW6O9N131qevGKDcebu1vY@6jxcHhyVR6fLfdyKBOTN9nFnCweGyTzqBOjPXIAk3e9P6ge9NDCYMAGCTCM8JJdz9GRUwBYzljnO1XIaJMJknCExwR0rXQsEpZrGWxlkeUNlHLJmkP5RAssdXFVk4KjO2C88DCNmmOy5dJ/2bN9i1KpigRCiFeb4oTv6y/qsHx7heoKlg/QykJRQE5LXMBPpztvNrFxh0CR8cTyhIM2P5BNvueiNhI86vXMj4a@iBo@gM)
```
f[a_,b_]:=Flatten@Table[r~Complex~i,{r,Re@a~Min~Re@b,Re@a~Max~Re@b},{i,Im@a~Min~Im@b,Im@a~Max~Im@b}]
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 89 bytes
```
f=(x,y,X,Y=y)=>y-Y?f(x,y,X)|f(x,y+(Y>y||-1),X,Y):x-X?f(x,y)|f(x+(X>x||-1),y,X):print(x,y)
```
[Try it online!](https://tio.run/##JYsxCsAgEAS/4@FZiE0QNN/QMgQEUwQxIgr@/YLaLTOzz1Wv784xFVEPomBYw44OvelgbBf@DJvAWIMzb/sYQsKMQDfhdrE8Z862bedFpxzfsiwFJlGiQgX0Aw "JavaScript (V8) – Try It Online")
Silly
] |
[Question]
[
In this challenge, all bots are wizards. At the beginning of each round, they create a wand which has a certain chance of successfully stunning another wizard. They then fight, by choosing one bot to attack in each turn. The last bot remaining wins.
### Results
500 games, 1000 rounds each
```
Revenge!: 132101.68886125216
JustEnough: 125373.84608578209
Copycat: 118350.98257686458
Climber: 100280
UpperMiddleClassHunter: 99618.4944296837
Golden: 92541.83731532418
Bully: 84120
TallPoppyLoper: 81359.05734216684
A Wizard Arrives Precisely When He Means To: 81218.40354787472
The Wild Card: 77687.08356861532
My First Bot: 74766.78481191777
Roulette Wheel: 67559.90399160102
Don't Kill Me: 58361.64359801064
Marginally Lower Threat: 40538.27420692073
Simple Threat Neutralizer: 13957
ThereCanOnlyBeOneStrongest: 13000
The Terminator: 3701
SimpleSimon: 3295
Peace Lover: 0
Pacifist: 0
```
### Game details
* A game consists of a number of rounds
* At the beginning of each round, all bots choose the success chance of their wand (0 to 1, inclusive, defaults to 0 if invalid)
* A round will last until one bot remains, or all remaining bots have a 0% chance of winning
+ In each turn, every bot must choose a bot to attack
+ If an attack succeeds (based on the wand's success chance), the bot who is attacked is eliminated for the rest of the round
* The last bot alive wins `1/sqrt(chance)` points (up to a maximum of 20), where `chance` is the wand's success chance
* If all remaining bots are eliminated in the same turn, no points are awarded
* The bot with the most points after a certain number of games wins
### Bot format
Each bot should consist of two JavaScript functions, the first of which is run once per turn. This function will be provided three arguments:
* Itself as an object (see below for format)
* An array containing all other non-eliminated bots
+ Each bot is formatted as an object
+ Each bot contains a `uid` property, which is an integer ID randomly chosen for each game
+ Each bot contains a `wand` property, which contains their wand's success chance
+ Each bot contains a `attacked` property, which contains the UID of the last bot they attempted to attack (or null if first turn)
* A storage object
+ Can be used for storage between turns or rounds (resets for each game)
The return value of this function should be the UID of the bot to attack.
A second function will choose its wand's success chance before the first turn of each round, and will be provided one argument, its storage object.
### Example bot
Example bot will attack a random (valid) bot that another bot attacked last turn, even itself. Always chooses a 75% wand success chance.
```
//Turn
function (self, others, storage) {
var attacked = others.map(bot => bot.attacked).filter(uid => others.find(bot => bot.uid == uid));
return attacked[Math.random() * attacked.length | 0] || others[0].uid;
}
//Wand
function (storage) {
return 0.75;
}
```
### Controller
```
//Bots go in this object:
var bots = {
"Example bot": [
function (self, others, storage) {
var attacked = others.map(bot => bot.attacked).filter(uid => others.find(bot => bot.uid == uid));
return attacked[Math.random() * attacked.length | 0] || others[0].uid;
},
function (storage) {
return 0.75;
}
]
};
//games: Number of games to run
//rounds: Number of rounds per game
//turns: Max turns per game
//log: 0 (no logging), 1 (errors only), 2 (detailed logging)
function runGames(games = 100, rounds = 100, turns = 1000, log = 0) {
let p = performance.now();
let botData = [];
for (let bot in bots)
botData.push({
name: bot,
turn: bots[bot][0],
round: bots[bot][1],
uid: 0,
alive: !0,
wand: 0,
attacked: 0,
points: 0,
storage: {}
});
for (let g = 0; g < games; g++) {
let uids = new Array(botData.length).fill(0).map((a, b) => b);
let round = 0;
for (let j, i = uids.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
[uids[i], uids[j]] = [uids[j], uids[i]];
}
for (let i = 0; i < botData.length; i++) {
botData[i].uid = uids[i];
botData[i].storage = {};
}
for (let r = 0; r < rounds; r++) {
let turn = 0;
if (log >= 2)
console.log("[0] Starting round " + (g + 1) + "-" + (r + 1));
for (let b, i = 0; i < botData.length; i++) {
b = botData[i];
try {
b.wand = Math.max(0, Math.min(1, Number(b.round(
b.storage
))));
} catch(e) {
b.wand = 0;
if (log)
console.warn("[" + turn + "] " + b.name + "[1]:\n" + (e.stack || e.message));
}
if (Number.isNaN(b.wand))
b.wand = 0;
if (log >= 2)
console.log("[" + turn + "] " + b.name + " (" + b.uid + "): " + (b.wand * 100) + "%");
b.alive = !0;
b.attacked = null;
}
do {
let attacks = [];
let max, alive = [];
turn++;
for (let b, i = 0; i < botData.length; i++) {
b = botData[i];
if (!b.alive)
continue;
try {
attacks[i] = b.turn(
{
uid: b.uid,
wand: b.wand,
attacked: b.attacked
},
botData.filter(a => a.alive && a.uid != b.uid).map(a => ({
uid: a.uid,
wand: a.wand,
attacked: a.attacked
})).sort((a, b) => a.uid - b.uid),
b.storage
);
} catch(e) {
attacks[i] = !1;
if (log)
console.warn("[" + turn + "] " + b.name + "[0]:\n" + (e.stack || e.message));
}
}
for (let b, i = 0; i < botData.length; i++) {
b = botData[i];
if (!b.alive)
continue;
if (!botData.find(a => a.alive && a.uid === attacks[i])) {
b.alive = !1;
if (log >= 2)
console.log("[" + turn + "] " + b.name + " (" + b.uid + "): Invalid bot (" + attacks[i] + ")");
attacks[i] = undefined;
}
b.attacked = attacks[i];
}
for (let b, i = 0; i < botData.length; i++) {
b = botData[i];
if (attacks[i] === undefined)
continue;
if (Math.random() < b.wand) {
if (log >= 2)
console.log("[" + turn + "] " + b.name + " (" + b.uid + "): Attacked " + botData.find(a => a.uid == attacks[i]).name + " (" + attacks[i] + ")");
botData.find(a => a.uid == attacks[i]).alive = !1;
} else if (log >= 2) {
console.log("[" + turn + "] " + b.name + " (" + b.uid + "): Failed to attack " + botData.find(a => a.uid == attacks[i]).name + " (" + attacks[i] + ")");
}
}
alive = botData.filter(a => a.alive);
if (alive.length == 1)
alive[0].points += Math.min(20, 1 / Math.sqrt(alive[0].wand));
if (alive.length <= 1) {
if (log >= 2)
console.log("[" + turn + "] Winner of round " + (g + 1) + "-" + (r + 1) + ": " + (alive.length ? alive[0].name : "No winner"));
break;
}
} while (turn < turns);
}
}
console.log(games + " game(s) completed (" + ((performance.now() - p) / 1000).toFixed(3) + "s):\n" + botData.map(a => [a.name, a.points]).sort((a, b) => b[1] - a[1]).map(a => a[0] + ": " + a[1]).join("\n"));
}
```
### Rules
* Accessing the controller or other bots is not allowed
* There's no time limit, but keep within reason
* Any bots that error or choose an invalid bot to attack are eliminated
* Deadline: **Challenge finished** ~~Friday, April 3, 12:00 UTC (8:00 EDT)~~
**Clarification:** Wand success chance is only chosen at the beginning of each round, not once per turn.
[Answer]
# Golden
Uses the golden ratio, which, if my calculations are correct, is a Nash equilibrium solution to the two-player game. Attacks the most deadly if there is still more than one opponent.
```
"Golden": [
function(self, others, storage) {
var targ;
for (var i in others) {
if (targ == null || others[targ].wand < others[i].wand)
targ = i
}
return others[targ].uid;
},
function(storage) {
return 0.381966;
}
]
```
[Try it online!](https://tio.run/##7Vlbj9pGFH7nV8wiNRpnWWO2atrCbqokbaNKzapqouaB8jDAAN4YDx0Pu9km/Pb0nJmx8WVsjEirVioPYM8cn8t3rmNu2R1LZjLcqItkE865XIv4HX/41O8/FyohS0HCmKhVmBAxveUzNezcMUmmuHdNPnQIfLo/vGfrTcRxtTskY72In8U2nqlQxDTh0aJHhFpxmfRIooRkS@7Zx9MP8mVKsdk7Pgfehtpfsw0FvuT6KbL3UwLPX4SR4pJuwznuWepFGM/z5Hr3msCP540K0iRXWxlnAsevmFr5ksVzsaYeeZxt@BGPl2pFPpJgQj5@tILGwQR571nueg6r3XZayYH/9Ve55/XVxHDp/sLZjJOfxR2XTkCtdnTNe4RF4V1FxkzEiQK38TUgqSlSvErgnAE6a46XJXwMB4uCRGcjNweXvcvyrAq8MrWXXL1i798y46SkrHUOHe2ONXtPfd9H0nIc3AOPskt3NVJXLNEi9TP1IkvctT140U4ImPaGSfhODpmmzbE4pqqVgamaVvXNRoZrJh@sVHBQToXMb06vJhx@53XPop@bPPirTpLfWLTllEnJHhps1fvV3MLVfGI1QmxZ0ZLoovke5maJomym5x3MWTJbCZHwFysWzzity9y6tH0d6jL4ZiU5U@SGb5WE3PuzRRJrzEvSbPbWpF2L5F2biAIe@WzS/Fpk04kFwOXBjJmDS5ZyVmtvbOptjVAX@Wdy76DOvW9W4FtokGHMoLL/3@nadrqBH9SmzEsRzXl8IpYK8rto80JIQnErxPHFsHCVqXBBKD6N0MXbKMrZjcsTE2dX6VpoFrwKH52vmg8JGwq3BaQg4eQx4stvBt8@eVIH8HOw6qGx/rSCGYK@UEvCGGuJO3Jd1URlnSaL3/qUNrLcYWwZVaLYrueDuAJtFQKUaavBIZiD4LI6r3V2I5iUl2zNkyG52a6nXBKxIHqBKEHkNu70@1Js43mBwKyQDdwhLdCgFCCBKYDoy/xeJJZDEhAaCwKXyzBeej0yIJRLKaAyizh6gIVLQudcsTCCopKSdTqZqaDKS1SLGuWuySAIeqki9s5I1jdwB0zgOkgRibhCP33PFIPlsW3aOtPsFuaaHl8ymCy9v9kmK1oENgY1hkjQKwYKqKCXkzF8TaD8FPe1wnmCQYkAnA5gFdf0BDwkZ6Vl9H6V1pbDysZGhLFKKss2bobkwz7Xd14JHA3kCH6uTGzA5fl5PtSQCDRH8GN@T57hhERT9ExM60YQ0cDT@UZZj0w9nTu5REE2GiEtr1Moh7h324OKqLtElikX0PBg8SnqF15clOP/Nk35RSSEpOW0oyE5J4Nyto9RAFTLnpY0vp1MMGLstV0MJ5NyOhVUDQ1kIUBWxAHWitjlAg0rtO6EqYxRHZV1Gx5id416SKOHBD1MssB1VT5S6kJRwD1tMZhJT6/JZbVx4JQlIu4DBe3iyPMaCpmC1LVu7AK8dKkxhq/uhb6XLsz3idg7EjuNDDyxR2dU2VfywfGUftIW7v2QCaUjaxKDnq16dOpri6iTiWFkfeKk8CpnIu0vMmNqtqLcO6RdMHLuW@94tVqlDrpnMgYPIf7az@CMifbO1MdKhvdQioa/x9pDHGyBKoLjBPch3xPsLC79nROJQcwPkxt2Q6e2nx5tXnPgVYOvyTRCzT3mFtx6QxOYVvxjbBg6Pr/oOoyc@rr@gpZngXN3PwrjDNZ08p0Lh58x6A2PJNeYyhQQmfZlSQ0R2n5@Xl0/LbHaJFfqrTOLVGM0QnHYcjeP@iTdNzYsiqiOj@bWJyN@PjTuZr1WR0XvIK1ptiZiDlPvu/A@Phof2jXzTL1lx06GjZPZuHz0CC7NedoYYzqspqEtQWDHgMCOBoG1BMHz/ERIlZsOjGUX1rADIDVWYF2F3YF3sAxX4u9sMKolPFiTj63LwdF12V2bd//h2mB4ZFkAjdidA3gA23vKa3Jorq4f9mZDG/oc7ein@A6UmetTiN7MRRtSdL1Ru8CEEYUDPHzeNigqPWzPbvSviqC8mdc5Q0@JqOJx4MqW96ag@WfC4VnqDr3hiHr7uiwX6SVuR8RPS/6HkmVHeJTwIkANQJ4Cz4/mLYESVsG/HaY2tTTFp6FVe@4p1/zBZc@zoO7AHViaDN9nmpM8Oc@9zLoM8I1K3ywkf0ALzahdr7Ockq9Qco3H2oV9k0/fhnGce3nUdDLEezuhFxT8bg@B9iLQ3Ahyrxl369rgVHL27lAl25H7FYQUoVrfK/MiySufq8133kjzLgqjCa9o4sEu/oeiYOgxLTuNhmwiGzOtPMzy1o@TyswzhZMYjDwMfnKjHMPjdYaM2bwFDrQLktD63ad@/4TXZPiiL30Yz0Of/gI)
[Answer]
# Revenge!
A bot that always takes revenge on the bot that attacked it the most thus far, with just a 0.5% wand success rate:
```
'Revenge!': [
function(self, others, storage){
// Initialize attackLog the first round:
if(storage.attackLog == null)
storage.attackLog = {};
// Update the attackLog:
others.forEach(other => {
if(storage.attackLog[other.uid] == null)
storage.attackLog[other.uid] = 0;
if(other.attacked == self.uid)
storage.attackLog[other.uid]++;
});
// Filter from the remaining bots the one that attacked you the most thus far:
var attackedMostBy = null;
var maxAttackedBy = 0;
others.forEach(other => {
if(storage.attackLog[other.uid] > maxAttackedBy){
attackedMostBy = other;
maxAttackedBy = storage.attackLog[other.uid];
}
});
// If the bots that are left never attacked you: just attack one at random:
return attackedMostBy == null ? others[Math.random()*others.length|0].uid
// Else: take revenge on the bot that attacked you the most thus far:
: attackedMostBy.uid;
},
function(storage){
// 0.25% is the lowest wand success rate that is still within the max of 20 boundary,
// so we'll use twice that wand success rate of 0.5% for a score of roughly 14.1 each
return 0.005;
}
]
```
[Try it with all current bots.](https://tio.run/##7Vvdc9u4EX/XXwF7JgkZyzLlXu7Okp2bOE3SdJJc5pI2D64eIAmS4FCkSlJWdLH/9nQXHyQAQpSU5DrttH6wRWCx2C/8dheUr@kNzUcZXxTHNz9/OTm5TIucTFPCE1LMeE7S4TUbFb3WDc3IEOcuyOcvh88@0fkiZjhy2CNXLQI/k2UyKniaBDmLJ22SFjOW5W2SF2lGpywknwUV/iAvWhR09JGNgZ@k7MzpIgB@5OIxsu1ogrAz4XHBsmDJxzinqCc8GZvkYvaCwJ8w7Jc7ZaxYZkm52dVrWsw6GU3G6TwIycNyohOzZFrMyC2JBuT2Vm1yFQ2Qr2R313a0rOuldos6Pz1Sa1qDduvw/YyR9yyb84TCmv/by92t24ki017vuIit97OM0YK8YcsiozH/ndVNp@QJ5qwN0crmJnN8BmPhH20RR/0D0H/O8KNhgVGa5AWZ008fQGtYLywAj0Gn0xG8HLOvgCysrVd2yvLNElQO9YmhTBOUjDwcVkJCXC2lDa@kMzZs6CMPN/qLjGZpmrOnM5qMWODzmumyt4yOGHmV3mxxEvjxxgoBaS7lKzG7v7O@2tgln1LUKSteS@vg6tyU1FDdjAkk2xYTd56dZjQX2wha/zY@3@GHZsagwnuawe@8SQUhtrKTFsVV3lbBtvki43OardVOYHhj29IfNU/lDP6ON60TJ3iDV34TGPR3Gi9ZQLOMrjfoJebqsIWjJmZ5TajPnLOdrWqIJ8yhcNUKv@FYWUh4uYzj9cYDtTVvQMaxUIwnGLH@9OHGbFF6qEwgmwFF7lOHL8Wk5g81bnrEspitLu6jDNaUdKPo1Eq7L9J4zJKvTLcoYaXOJM1IgMMc6yK51A1APiEBrsKsmoDfjLSIwwNprnM9xuVAaPHQhgerc8/RU6paXL@qPvnTz92zH380jfU05vOhB7zL1Oq1lBrqjJZZxpJC428ec/BVZMTDJEvnz5Ii4wwjqmQO5zK0rYhGhpITq8y7vjUDPhAuWFAOJBM80yGSXuEApLIBrBEfu4O@DxmA1GNSPgkOtBb5KM1YbnvEnkPZK02Csh74hEfi6hM6ow2xHJooti2a3LplUyzZkkjvQzi5w8ANYwskGWyMLYOovznMKqF3CC2wo2PGz17vIXyA85zACUlN1JMTMuY3fMxQWiJ4kuFaPCRLDFVkIxqSYgZV4ihdxmNIqjeMrNKkxs2xkioqBuToor6z8VMmevFhka4CjXttctw9OQ3b5DQKyUkTD0ICR1sNe0ekGzbYHxCt67QRGXtKk1@TeH3Jfk3YuyJLkynLt7Rg/0vQ1q33EfA7TXa3kC1I9O1SvKUjPuH7OElxQUvvDe1WwNA4fpsuFutX6YJ9Td@JftexO@P4aa1DoHLuZy9eluQCx10o2BpxOlYVm0ssOmoZAX8qgo7oHhDdsiVrJIxpXjxx22mMWt0lNK7@yOP4aboU2S7qb0QatQLYAl213F5wR7yl/A4Gqm@zQf@71nc4/HUTQT9GMH5Eb3b/PjlwBaovURL6XO3RxjRz4/SRPm4ejbflUs1Q4k3F87xxSxvYPm@HORvqvp@nJzTOWVMr813h9DdIsawoGPkwYyxWcFIW6c1oYsvjtgOqw3C6ASgBZJOl2gWSLkXtAKhGANXSBFJp3lLqGHJ4d5btAQSLu3fUOTv76VG1V15kUgxwCJBNGbnqnvwQRW3SHbS0KV6DQDwBQdbkVbqCWkTeVe1nEzAmXsXILkrbIGPjJdTOAW0PQywqywoEBmRWhQIzNNerS1mnSxM9mu7Q9DahaRG1tOYMNe56Y3dDn52dlYb66zIvniXpcjrbI/00AJY@DMpowqtOrT1fxgVfxBy8coFXiwY6VFCmtXtMTu1C1VmtO8pN25@d9b/2XKMwTsUEuAO92TZ4aajGNJ/H9fLMB7sGVvV9k4669ZLvoWkvLwuzhFCigdHCZkvWMXMjgrrG2FCXKDWjPxIsTZUM3Hzwek2e8ywvCKT/BzZC2GfAYQ0tVbFeMKNbSlDLB8tkzCY8YeMHZegaBFUJqHgotUqSQbnK1rsiMJQnDDIMadimsWB2MaMBm4X3pb2ekA/8d5qNyZMsgzyXk7cZG3Gw1BozT0L@wshrRpOcvE8bzVlCitwMGsp3BXaR2ELSucjzuoWM2aTotSwVl/NLC1glYCisAV4vmLi2lutXvJjJVh5KvekMWjLSje6JiyuSL0cjlueQTAom90BgyEXvBk0cbnGlbix0k4zr3kOfOktjdTj6xgKNXRfoBJv2GIm7@gzU9rFzRCreDqlTeWExUm0pqPkEJhd89JFQInMEgbyLditmKUSGZK/68FRdTPZa1qnQAtiZ5mFNodsqdvxRU/rxZTKCdJtLV2bgybG@EwgAeHnCCy5eGIE8pCuIJuIACtLQdrRcfuE@K2j9Bdb37LmjbmmclxNyDQlOmgRS1SqVlqAQZSKkQBYlaS0U0FzdKLrX8iCIDr7zC3KKIhj7oQeZ2GAuY5kmvn2X3i3HbMEAPDDwk8p2zZcX8NOrqpAuOXEsdSzuKdriEMvrDHmKf2M34FV2sOcRfWk6D4PpVTp1PdhrOTdOFaWTBTwEVT8Ku/1tMRaumBm7Se76qKTZMzqaSRDF86Kh0Le77HnkxVItHTVTV3CqEdt8ZVV2WruxOzpS@BtWmj4XZ17cXkrPszmFg1KeXRjCKBZ3aeXO63QpZuapeEe3zKHjyCoM03SvYfoSW/3qxkIUYvST7rLFrFLxWy372GZslG81ecSqKuW7AjVto1fd1SwpD6Fx9ahPHUkg5DPLej2JD3JIGBjoJQJaIOlKXqKPr2F6aGWk27I8F9I9g3zdg3LnI7pYnEB91vHmdWf3bgMEW@AdYTuCcvoe4TLaYuibYFsPLqKMQJQX0G@bmVXdASMC0GyNOeg00qzzlKzYA6BH4CtWfKT41NnDsqgDYmCJThVPGMuwR4EKo/tDp0sYBKZboDzS0Pblro87ApCq8oEAhtBW6@RkSucs75E35fW0GECgz5YJzAvwsgjkCFnAE9ICDe6XI@B@IuKjORcDOJGIBEkK1ptCAzqFZrBLApZlaZaDn@M1XkiTYMwKymPwsCZrtcq2DUR5gWIFUrgLTEJtLYh6kjuLB3iKBWxGZtsKWv8ZlLZLFxKoKex5xAvkMpQUfWexzGeB3YckIEYPCdrWMIoghsVl/QDqSnteJgKDoOsQQEiCsewxcW/SIwfOMAZJnVZFeG1ikfKkyGvDKtp7kF@qHiN0jCN7EPhzLmMDPh4dma0EEoHkaPyErbACputAW08eePH9njiIQvHmKaBtIm8Khsa7BGSjC5vIue7Dues2dKbiyz9lNXlMun0YfIzy8eNjt1281i@RJ3EKVap7aRBw8TYjtHu4K9wAmtK22OnqWryju1Kf1SAfDHzvQEpRuTQZB5PZdoAx23ZGoKmXW0pFeOpvolJuc26XPXJkUo4M5JCHBT7X90dKARm1u2FsVPEkQaV9Wn8zgl@PSGPWAYrgEL/G8w7a0ALTs3TjIZg3mAobw6/DY/Gc@WxeHcT2nrYTloEVlXXqHXkBwOu9Rygvm6paEaCj/NoBFIgS9YKhrBuDjWlmqH3ipQhDV2HZp45oAcUEC7dJF3lvKbR3wo1SaQetaJaAh9D@ws/gjIHwzrCDSIbPAEW9fyTCQwx0wcx/e0tYB857jvkw3HbRoQWSFuvw/A19E6jbv3Bv9ZoDrx58TaqRQD7j2YLHsCcDc6hvgyBhiPi8d@hRcljeWx9E3tnqlUxVSPotNE49fsaglzzMntqlgMhUX0PbQIS66wr6@x2sXQ6X9taBslRjNAI4@F5zNR/SKrHl8sXUsIPqBo013@etFaHItSIq2ltpZbKVEbOdusrCVXw0Lrpr5qm9pa5AKCZOquLy/n34KL9qKJWRGVbQBDsage5jBLq3EeiORgjDTp5mhVEdSM2OlWJbjNSIwAKF/YG3FYZr8XfQ7W8k3IrJ@@JytDcu@7H57r8YGySP8hRAIvafAfxaX@WpsMmhBq5v92ZDGvoe6ehlcgPCjEUXIiaNaEOKw7C/W2CWl@y7BkUth1Xs@v9REWSqeWEo@i0RZbcD5wrem4Lm3xMO5bc8xIQn6tV/QRiR7nDbI3525L/tsKh3LpaBGgz5LeZ5Lm8Jyov7P9xMu2Cptk9Dqg79Va7894Hq7UjXH1iCDF9UyU4evwNY9imn@J6fnMiB/J@QQktq9wvSG3c@x503eGy3sG/y6QeeJMblUVNniM@qQrcE/KUygfAi0LxJyUowPtyUBocZox@3vqIlqxmEFAmEvOfyIqn2HUf521RS3kVhNOGnIA9hFr@7V0DRI1O2joayIruiQnio5ZUfB7WaZwidGJQ8FP4YpRzF9rq0jJy8Bg7BIeyE2t@1Wl9/SfblXw) It seems to be doing quite well, since it's usually in second place.
[Answer]
# Climber
Always target the bot who, by our calculation, looks to have the highest score. Keeps a 1% wand for the 10 point payout if he wins.
```
"Climber": [
function(me, them, storage) {
storage.current = them.slice(0);
fromEntries = function(arr){
var obj = {};
for(var pair of arr) obj[pair[0]] = pair[1];
return obj
}
if(!storage.scores)
storage.scores = fromEntries(them.map(x => [x.uid, 0]));
var targ;
for (var i in them) {
if (targ == null || storage.scores[targ] < storage.scores[them[i].uid])
targ = them[i].uid;
}
return targ;
},
function(storage) {
if(storage.scores){
for(var bot of storage.current)
// divide the score by the number of bots that could have won
storage.scores[bot.uid] +=
Math.max(Math.pow(bot.wand, -1/2), 20) /
(storage.current.length + 1);
}
return 0.01;
}
]
```
[Answer]
# Bully
```
"Bully": [
function attack(self, others, storage) {
minWand = Math.min(...others.map(bot => bot.wand));
targets = others.filter(bot => bot.wand === minWand);
return targets[Math.random() * targets.length | 0].uid;
},
function wandChance(storage) {
return 0.0025;
}
]
```
Only targets the "weakest" bots, aka bots with the lowest wand success chance.
[Test all current bots!](https://tio.run/##7VvrdxO5Ff/uv0LJOSwzxHHs7LKQhLAHKLulBZYDtHxw/UGxZVthPOPOI8Yb8rfTe/UaSSOPHdjtaU@bD4ktXUn3pd99zOSSXtFinPNleXj18MvR0dOsLMgsIzwl5ZwXJLu4ZOPytHNFc3KBc@fk@sv@8090sUwYjuyfkmGHwM@0Ssclz9KoYMm0S7JyzvKiS4oyy@mMxeRaUOEP7kXLko4/sgnsJyl7C7qMYD9y/hi37WmCuDflScnyqOITnFPUU55ObHIxe07gTxyfmZNyVlZ5ag4bvqLlvJfTdJItopjcMxO9hKWzck4@k/6IfP6sDhn2R7iv3O6m60nZlEud1u89uK/WdEbdzv77OSPvWb7gKYU1/9eXf9qg1@/b@nrHhW@9n@eMluQ1q8qcJvw31lSd4idasC54K1vYm@N3UBb@0RrxxN8D@RcMP1oaGGdpUZIF/fQBpIb1QgPwNer1emIvT@0rIIsb65We8mIzB7VBQ2wo1URmo8AOK8EhrpbcxkNpjA0HhsjjjfYi43mWFezZnKZjFoWsZpvsDaNjRl5mV1uMBHa8clxAqkvZSsze3lhfrWyzj2F1xspXUju4urA5tUS3fQLJtvnETeCkOS3EMYI2fEzIdvihfWMQ4T3N4XfRJoJgW@lJs@IL74rg6nyZ8wXN1@okULx1rLFHw1IFg7@TTevEDd5glbcCg/5Ok4pFNM/peoNcYq4JWzhqY1ZQhfrOece5osZ4wzwKX6z4G66Vg4RPqyRZb7xQW@MGRBwHxXiKHhsOH77PlsZCJoBsBhR5ThO@1CYNe6hx2yKOxlxx8RylsLag2@8fO2H3lyyZsPQrwy1yWIszzXIS4TDHvEgu9R2QT0mEqzCqpmA3Kyzi8Eiq65Ee43IgdvbQiget88DVU6I6u35VfvL9w8HJjz/aynqW8MVFALxNaA1qSg31xlWes7TU@FskHGzVt/xhmmeL52mZc4YeZTaHexm7WkQlQ8qJWebNmTMDNhAmWFIOJFO80zGSDnEAQtkI1oiPg9FZCBmANKBSPo32tBTFOMtZ4VrEnUPea0kikw98wisx/ITG6IIvxzaKbfMmP2/Z5EsuJ9L64E7@MOyGvgWcjDb6lkV0ttnNaqZ3cC3Qo6fG66D1ED7AeJ7jxKTB6tERmfArPmHILRF7kou1@JJW6Kq4jShIyjlkieOsSiYQVK8YWWVpYzdPSyqpGJGD8@bJ1o8J9OLDMltFGve65HBwdBx3yXE/JkdtexASedJq2Dsgg7hF/4BoA6@MyNkzmv6aJuun7NeUvSvzLJ2xYksJ9r8EbYNmHQG/s3R3DbmM9L@dizd0zKf8Nkb6PVhw0oj3NEneZMvl@mW2ZLcpQDu2B2gvnnP8tDbOUNv5Ogidhr4B6eZWwvmiHiX4yYUlmy7PqnTyOgO6vgWwu3qx9n/Fz1NMZBos4U9N0BMVCSJmXrFWwo88SZ4Be6VkbhP@qBXD@qYIGDq3tnIX35DAZWFJwaRJUF1ObYMW2WaQWo3@yIF2Xb@42EG97SJu0ORN5yugqYFN9VFGF3u1L5HvviNBCuG9MLm3mXVNrfgPudQWuW3H2JnUsYOnp235gbe5gVJ7/0c7s@KC@PV2SHc99Y/xoSmFC9BWwn17hnzilBJvIbtgZcnIhzljiQJQU5@0VxQuS34lpIorrxCC7EfWl6pSIlkl0ibAcQI4nqWQRRQdJZHFR/BkWRmBT/lng5QnD@7XZxVlLtkA@wDZjJHh4OiHfr9LBqOOVsUrYIinwMiavMxWkIbJNt3tdALKxC6ULCC1DnI2qaBsiGj3IsZ82iRfMCATCsitY3u96kd7BaooT3Vxqo@JbY2opQ1jqHHfGrsr@uTkxCjqL1VRPk@zajb/moDbREN9N5TShFW9MmNRJSVfJhysco5dVQtEapjU0j0mx26O7q3WxfSm409OvjpUIDNesgiQBGXpNrRpSUT1Po@bmWkItS3oOgtNeuI2s917tr6CW9g5k2INlBa3a7IJoRsB1VfGhrCvxOz/kXhpi2Th5t1Xa/Izz4uSQF5z10UI9w54W0M1Wa6XzCoUU5TyLmQpbMpTNrlrXNciqJNetYcSy5CMzCpX7prAEl5mWS3HtCbqPma0YLOwvtTXE/KB/0bzCXmS5xDqCvImZ2MOmlpj5EnJnxl5xWhakPdZqzoNpMjDoJZ@V2IBjdUzXYgUQFfPCZuWpx1HxGrx1AFWCRgKa2CvX5jo2Mv1K17OZRcDctjZHKpRMujfET07UlTjMSsKCCYlk2cgMBSibIX6FY8YqmaN7g/guvdQos@zRF2OM2uBxq5zNIJLe4jEA30HGue4MSITD8bUrTx3NlIVOYj5BCaXfPyRUCJjBIG4i3or5xl4htxetSAy1ZM97Ti3QjPgRpp7DYE@174T9hpjxxfpGMJtIU0p0nbdDokAeHnKSy6elQE/ZCCIpuICCtLYNbRcfu5/V9D6E6w/decOBkY5L6bkEgKcVAmEqlUmNUHBy4RLAS@K04YroLoG/f6dTgBBtPM9OifHyIJ1HlqQiQMW0pdpGjq3Ch45YUsG4IGOn9a6a@/bwM9pnYUMyJGnqUPRoumKSyw7OfIWv2VXYFW2d8sr@sI2HjrTy2zmW/C04zXbakovCgQIRLGrT/vbciJMMbdOk7vrq5Llz@l4LkEU74uGwtDpMlNXxawfjtqpazjViG1XtKaK2227gwOFv3Et6c/izovGrbQ8W1C4KObuwhB6sWgjmpPXWSVmFpl4PFkVUHTkNYZpulcw/RRbGyjxmZkGf3miKMSsEvFbNfvY3dhK3xr8iFV1yPcZajtGr7ppaFJeQqvrqm8dScHlc0d7pxIf5JBQMNBLBHRA0ufcoE@oYLrnRKTPJj0X3D2HeH0K6c5HNLG4gfquY9N5Z/NuAwSX4R1huw/p9B3CpbclUDfBsQFcRB6BqCih/LYjq2p/IwLQfI0x6Livty4ysmJ3gR6Br1zxsdqnuT0s6/eADUzRqdoTxnKsUSDDGPzQGxAGjuknKPdraMNXWT5wCLfPIEu5Jb79lbElnJvwopRRVGcQc5SAiCg@y6vJDAI2ncEVLcqOznNNi4albMFZUWfRakClEh66ZVVuzlOEwYsIl/DaLZXcrprdSvJZ6UGgS6oJK2CReJvmOlQ2aeJlVcwVod/6D2AWlv1GRwu6lg84Lhikgizh4oUiNukEzrGuuD5ZpT6frHeC8NGVSoWQoVqST7F769E8eDIVOd4hL@ZN9@radx30jbovVhn4kOJAucYK8llNKu91sjZ2divyx26tZDW5tFAmHwSMjTd10HfruVilg5eTqMMa@2xgRr9fsAUS3rJC5dHaZsJTqRwroBaTbgsOaiUr7W7/VumT0KLgMwDXAApEU3oFtikgUCUV7DBOIJvNMScDcIhNCKv0WwNa4Dq64cjraiHTc2O6SpXwzvT9jtOvljT3XZofQjQPXJofQzQPXZrvQzQnLs2DIM2xx9FxkMojehgkeuBRDTpuBYa3IpgQi7QVazzxgghmJ1Q1/zqBfoQ6Qlle@asZlGj95eYMz4W0VxV7BDCRdjpHRzO6YMUpeW2eo4oB5CKvUpgX7uYQyBGyhG9ICzR4YoHp8SciPtpzCaSSpE@iNINYN5uBMHEXqomI5XkGjpelyRqfnJJowkrKEwBZTdbpmCYbsPILshVJ5s6xZOhqRtQ3ebL4At8SkeT27SYjSP0nENotNEmkprBDJd50MsCh6CVMu12jFNg4RYKuM4wsiGHxVHk07I/ceZm2WwQDjwCgB5TljolG9ynZ84bR@E1aFagaE8uMp2XRGFaedArVQB2AYk85smMEfx5J34CPBwd24weJgHNUfspW2K@g60hrTwKheBE1ifqxiDMR7RLZ172wIh9uo8vQvvfkB@cuu4QT8ZaqgddDMjiDwcfIHz889Jt7lxq3pkmW5ZGP2REXj91jt@M2xAOGfNQVJw0vxcskQ/VZDfLRKPSw3rDKpco4qMzVA4y5urMcTT3aUCLCt7NNVMps3iPLAB@55CMHPuRlgc/N85FSgEbjcSWCGd6kx1CBNx/h43t8WcJ6QBHt4/um7zBQIVxJM@6DeqOZ0DH82j8U3/OQzuuL2L2l7oRmYEWtnWb/tIQ0Odj1NY8G6soeoMO8HwflvES96EJW@dHGouBC2yRIEce@wLKrOKYlZJws3sZdP9hT1taJN3KlDbSieQoWQv0LO4MxRsI6Fz1EMvwOUHT6j1RYiIEsmJBBisV6cN8LTFXibW1pzZDUWI8Xr@nrSD2riW8tXrvjNZ2vTTQSye94t@BrfCod80L37iFgCP@8sx8Q8sI8aNzrB2frV/Hrsj@soUkWsDM6vdzD7oD6FOCZ6n3pDUQou@53/H4Xa5fLZaoypalWbwRwCL070X5J68CGoIjs9FDcqLVCv95av4tYK7yiu5VWBlvpMdup6yhc@0fropv2PbW1VNVGMXBS5ZdQhFL1TrwURkZYQRPtqAR6GyXQWyuB7qiEOO4VWV5a2YGU7FAJtkVJrQgsUDjseFthuOF/e4OzjYRbMfm2uNy/NS6Hsfnmvxgb5B7mFkAgDt8BLP1rS8VtBrVwfbs1W8LQ7xGOXqRQfsM3rELEpOVtSLEfn@3mmOaR6K5O0Yhh9XZn/1EeZIt5bgn6LR7llgOPFLy3Oc2/xx10c14SBrxe/bue5enebrfwnx3333ZZburmh1FQiyK/RT0/yy6Becz6h6tpFyzV@mkJ1XE4y5X/51Y/yx6EHUuQ4WsFspLHl9VNnXKMb2WRIzlQ/BNCqKH2/5Nn48mP8OQNFtvN7dts@oGnqdU8aqsM8bvK0B0Gf6pVIKwINK8zshIb728Kgxc5ox@3vlBDVnNwKRIJfh/JRlKzI9/xhZS9KPQm/BQVMcziS@YlJD0yZGtvMBnZkArmIZdXdhw1cp4LqMQg5aHwx0rlKJbXRjNy8hJ2iPbhJJT@ptNpNMnu79ok@/Iv)
[Answer]
# Upper Middle Class Hunter
```
"UpperMiddleClassHunter": [
function(self, others, storage) {
var myOthers = others;
myOthers.sort((a, b) => a.wand - b.wand);
return myOthers[myOthers.length * 0.8 | 0].uid;
},
function(storage) {
return 0.333;
}
],
```
It hunts the upper middle class bots knowing that the supreme bots will kill each other and be targets from other bots and so it doesn't need to target them. Nor will it hunt the lower bots as they also are targeted by others. Instead hunt the bots that are not the strongest but could be a threat.
It attacks with a 1/3 chance of winning, seeking a balance to kill of the threatening bots, but still gain a reasonable score if winning a round.
Its simplicity hides its effectiveness... in my tests it is either winner or runner up after 500 games.
[Answer]
# Peace Lover
**Not** a troll entry! *...probably.*
```
function attack(me, alive) {
const them = alive.filter(bot => bot.uid !== me.uid);
const attackers = them.filter(bot => bot.attacked === me.uid);
function getMaxWand(bots) {
return Math.max(...bots.map(bot => bot.wand));
}
function hasWand(wand) {
return bot => bot.wand === wand;
}
function getTargets(bots) {
return bots.filter(hasWand(getMaxWand(bots)));
}
const primaryTargets = getTargets(attackers);
const secondaryTargets = getTargets(them);
function getRandomValue(array) {
return array[Math.random() * array.length | 0];
}
return (getRandomValue(primaryTargets) || getRandomValue(secondaryTargets)).uid;
}
function chooseChance() {
return 0;
}
```
Points its useless wand according to an improved version of the heuristic of [this other entry of mine](https://codegolf.stackexchange.com/a/201784/74965).
**Note:** This entry didn't work properly because of a bug in the controller, but along with the bug fix came a limit of a measly `20` instead of the `Infinity` that can be inferred from the spec imposed on the score per win...
[Answer]
# JustEnough
Targets the strongest of the lowest third of opponents using a wand that is slightly stronger.
Otherwise, targets the first opponent with almost full power unless less than three opponents exist, then use almost no power.
```
"JustEnough": [
function(self, others, storage) {
var targ;
storage.wand = 0.002;
var multiplier = 1.01;
if (others.length > 2){
multiplier = 1.25;
storage.wand = 0.99;
}
for (var i in others) {
if ( others[i].wand < 0.3)
{
if (targ == null || others[i].wand > others[targ].wand) {
targ = i;
storage.wand = others[targ].wand * multiplier ;
if (storage.wand > .99) storage.wand = 0.99;
}
}
}
if (targ == null)
{
targ = 0;
}
return others[targ].uid;
},
function(storage) {
return storage.wand;
}
]
```
Bot derived from MegaTom's entry: [Golden](https://codegolf.stackexchange.com/a/202820/20193)
[Answer]
# My First Bot
This is my first attempt at entering a KotH competition and I don't know what I'm doing.
It literally just hits everyone in turn for a damage value which seemed to be returning good results.
```
'My First Bot': [
function(self, others,storage) {
if(typeof storage.n == 'undefined'){
storage.n = 0;
}
if(others[storage.n]){
return others[storage.n].uid;
} else {
storage.n = 0;
return others[0].uid;
}
},
function(storage) {
return 0.009;
}
]
```
[Answer]
# [A Wizard Arrives Precisely When He Means To](https://www.youtube.com/watch?v=cZr3csN9tRc)
```
'A Wizard Arrives Precisely When He Means To': [
function(self, others, storage){
// Store the amount of bots left:
storage.numBots = others.length;
// Get the bots within the highest 10% wand success rate:
var strongOnes = [];
for(var wandTreshold = 0.9; strongOnes.length == 0; wandTreshold -= 0.1)
var strongOnes = others.filter(o => o.wand >= wandTreshold);
// And pick a random one of those strong bots to attack:
return strongOnes[Math.random()*strongOnes.length|0].uid;
},
function(storage){
// Increase the round number (or initialize at 1 the first round):
storage.round = storage.round == null ? 1 : storage.round+1;
// If just one or two bots are left: increase wand success rate to 100%
return storage.numBots <= 2 ? 1
// If there are more than two bots are left: use wand success rate dependent on the round
: Math.max(1 / storage.round - 0.01, 0.001);
}
]
```
This bot does a couple of things:
1. It lowers its own wand success rate \$SR\$ based on the round number \$r\$, using the formula: \$SR\_r\text{ (in %)}=\frac{1}{round}\times100-1\$, which will progress like this: \$SR\_r=[99, 49, 32\frac{1}{3}, 24, 19, 15\frac{2}{3}, 13\frac{2}{7}, 11\frac{1}{2}, 10\frac{1}{9},9, ...]\$, unless this is below 0.1%, in which case it'll use that instead. Also, it will use a 100% wand success rate, if there are just two or three bots (including itself) left in play.
2. It will attack a random bot within the top 10% ranged wand success rate (i.e. \$[90\%, 100\%]\$ until all those are eliminated, then \$[80\%, 90\%)\$ until all those are eliminated, etc. So let's say the bots left have a wand success rate of `[83%, 75%, 50%, 1%, 25%, 82.5%, 50%, 50%, 72.5%, 85%]` it will pick a random both in the range \$[80\%, 90\%)\$, thus one of the bots `[83%, 82.5%, 85%]`.
From the current bots, this bot usually ends up somewhere in the middle, so not too great, but also not last: [Try it with all current bots](https://tio.run/##7Vrdc9u4EX/XXwF7JgkZyzLl3pclKzdJmktzk@QyF0/zoOoBkiAJDkWqIGVF5/hvT3cBkATAD0lOrtNOqwebBBaL3d8u9gPSNb2hyUTwVXp689OXs7NncZqQeUx4RNIFT0g8vmaTtNe6oYKMcW5Abr8cv/hEl6uQ4chxjwxbBD6zdTRJeRx5CQtnbRKnCyaSNknSWNA588mtpMIP8qJpSicf2RT4KcrOkq484EcGT5BtJyPwOzMepkx4az7FOU0949HUJJezAwL/fL@f7yRYuhZRvtnwDU0XHUGjabz0fPI4n@iELJqnC/KZBCPy@bPeZBiMkK9id9d2tCzrpXcLOj9@r9e0Ru3W8dWCkSsmljyisOb/eLm7dTtBYOL1nkvfuloIRlPylq1TQUP@BytDp@XxlqwN3sqWJnN8B7DwX4aIo/4R6L9k@GggMImjJCVL@ukDaA3rJQLw6nU6HcnLgX0DZH5pvcZJJPUSFAatEkND4@WMKjhspIS4WknrD5UxajasIvdr7UUmizhO2PMFjSbMq7KaabJ3jE4YeR3f7DAS2PHGcgEFl7aVnD3cWPcGO@eTizpn6RuFDq5OTEkN1U2fQLJdPnFXsdOCJnIbSVu9TZXt8KGZMahwRQX8TZpUkGJrnDJRXOVtFWzMV4IvqdjqnQB4Y9vcHiVLJQz@T@vWyRNcY5XfZQz6Ow3XzKNC0G2NXnKuHLZw1IxZlRBmZ87ZzlbVxxPmULhq@V9xrKxI@GwdhtvaA7Uzb0DGsaIYj9Bjq9OH67NpbqE8gdQHFLVPOXxpJiV76HHTIhZitrq4jwasKekGwbmVdl/G4ZRF90y3KGGhziwWxMNhjnWRWuo6IJ8RD1dhVo3AbkZaxOGRgusyG@NqwLd4ZMAD6rzi6GlVLa73qk/@8lP34ocfTLCeh3w5rgjeeWqtREoPdSZrIViUZvE3CTnYKjD8YSbi5YsoFZyhR@XM4Vz6NooIMpScWGXe9a0ZsIE0wYpyIJnhmfaRdIgDkMpGsEY@dkf9qsgApBWQ8pl3lGmRTGLBEtsi9hzKXmji5fXAJzwSw09ojDb4sm9GsV3e5NYtdb5kS6KsD@7kDgM39C2QZFTrWwZRv97NCqH3cC3A0YHxttJ6GD7AeI7j@KQk6tkZmfIbPmUoLZE8yXgrX6I1uiqykQ1JuoAqcRKvwykk1RtGNnFU4uagpIuKETkZlHc2Pnmilw@reONlca9NTrtn536bnAc@OWviQYjnaJuFvRPS9Rvwh4jWddoIwZ7T6Lco3D5jv0XsfSriaM6SHS3Y/1Jo65b7CPgbR/sjZAsSfL0U7@iEz/ghRtJcEOmDQ7vlMDQM38Wr1fZ1vGL36TvR7pnvLjg@bTMXKIx7Wxkvc3IZx91QsNPjMl/VbJ5h0VHKCPgpCDqye8DoJtaskTCkSfrUbafRa7MuoXH1Rx6Gz@O1zHZBvzbS6BXAFuiK5faCO1JZyu8BUHmbGv3vWt/g8Jchgn6MoP/I3uzhQ3LkClReoiWsMnWFNibMjdMn2XGr0HhXLs0YqnhT8Lxs3NIObLe7w5wd6r6dpWc0TFhTK/NNw@nvkGJZmjLyYcFYqMNJXqQ3RxNbHrcd0B2G0w1ACaCaLN0ukHgtaweIagSiWhxBKk1aWh1DjsqdVXsAzuLuHXQuLn78vtgrSYUSAwwCZHNGht2z74KgTbqjVgbFGxCIRyDIlryON1CLqLuqwzABMPEqRnVRGQaCTddQO3u0PfaxqMwrEBhQWRUKTN9cry9lnS5N9mhZh5Zt45uI6KUlY@hx1xr7A31xcZED9es6SV9E8Xq@OCD9NASs7DBo0KRVnVp7uQ5Tvgo5WGWAV4tGdChCWabdE3JuF6rO6qyjrNv@4qJ/33ONwjgVE8Qd6M12hZeGaizj86RcnlWFXSNW9asmHXXLJd9jE69KFmYJoUUD0PxmJMsxszaCumDU1CVazeDPDJamSkbcfPRmS37hIkkJpP9HdoSwz4DDGlqqdLtiRrcUoZaP1tGUzXjEpo9y1zUIihJQ89Bq5SSjfJWtd0FgKE8YZBjSsE1jwezGjIbYLK2v8HpKPvA/qJiSp0JAnkvIO8EmHJDaYuaJyN8YecNolJCruBHOPKSozaChfJ9iF4ktJF3KPJ@1kCGbpb2WpeJ6@cwKrCpg6FgDvF4yeW2t1m94ulCtPJR68wW0ZKQbPJAXVyRZTyYsSSCZpEztgYEhkb0bNHG4xVDfWGRNMq67gj51EYf6cPSNBVnsGqARbNpTJO5mZ6C0j50jYvntkD6VA4uRbktBzacwueKTj4QSlSMI5F3ELV3E4BmKve7DY30x2WtZpyITwM40j0sKfS58p9prcju@iiaQbhNlSgGWnGZ3Ah4EXh7xlMsvjEAe0pVEM3kAJalvG1otH7jvOrT@DOt79txJNwfn1YxcQ4JTkECq2sQKCQpeJl0KZNGSllwB4eoGwYNWRQTJnO9yQM5RBGM/tCCTGyyVL9Ooat915ZZTtmIQPNDxowK75ssL@PSKKqRLzhykTuU9RVseYnWdgaf4y10fBYbd9BkjU5rSVuvsbE6XLOmRt/kdjhxANMQ6gnnJ1SJQIwRaWEkLNAhWglJ9IvLRnAvjeY8ExItiAo9Qpc2hYuoSjwkRiwQUD7d4a0O8KUspD6GTycharby2AVFeolieEm6Almpngug3tbN8gTdggifVrO1A67@C0vb5Jp6ewsJAfsuSw6/pO6t1svDsZB2BGD0kaFvDKIIcljdaIwi@9rwU2CToOgRw3AAse0w2Fz1y5AyjN5VpdWtXmljFHIrz0rB2nR608kUi9h1wVKKGf5fKN@Dx5MTMt0gEkiP4EdtgmqBbL0NPxRL5JXjoBb68noXimahyemxcuCGb7PQHTk@Mc9dtKN/kN@R5yD2FjggGn6B8/PTUramus29aZmEModytrD0ur/x8u9AZ4gZQubXlTsNreZE91M96kI9GVReFuahcQcYBMhsHGLOxMxxN3wBrFeGtX0elzeZcwVTIIZQcAuRQhwWey/sjpYx3pQsUrObwJEE6Oi9fH@J3iHHIOkDhHeN33e@hVkvh6GozHgO83lxiDH@OT@W7qMK8OIjtA7GTyMCKAp1y2ZqKbXWxnXdkRUCF0JF/NwdRVEU9b6yCq1cbmseZTSopfN9VWBVzE5pOFh7zd0kXVJbymXX8WqkyA22oiMBCiL@0MxhjJK0z7mAkw3cIRb1/RNJCDHSBKIJtDOvAeU8w1/u7uoFMIIVYhydv6VtPt8j@weo1O17Z@ZpUI556x7MFr35POeY4a5kgYUj/fHBcoeQ4v9w5Cipni3vL4n64GqFpXGFndHrFwyw8XQrwTP1bjRoi1P3kpDz@dQdrn8OVWetII9XojRAcqu6Cmw9pkdgSdXs77qC6XmOddLuzipK5VnpFeyetSrbKY3ZTF1m48I/GRXfNPDNr6T6BYuKk2i8fPoRH9XscpYzKsJLG2xMEeggI9GAQ6J4g@H4niUVqVAdKs1Ot2A6QGiOwjMLVjrczDJf876jbryXcGZMPjcvBwXG5Ojbf/RfHBsUjPwWQiKvPAP72pbCU32RQI67vtmZDGvoW6ehVdAPCTGUXIicNb0OKY7@/n2PmN1H7OkUphxXs@v9RHmSqOTAU/RqPstuBSx3em5zm3@MO@VehcqLC6/VPhQ1Pd7gd4D978t91WPTFpAVQA5BfA88v6pYgv93602HaJ5Zm@DSkar@6ylW/sS2uELvVjiXJ8DZXdfL4Q5m8TznHL8PImRpI/gkpNKd2f0VYu/Ml7lxjsf3cvsmmH3gUGZdHTZ0hvusK3RLw5wICaUWgeRuTjWR8XJcGx4LRjzu/xyCbBbgU8aS8l@oiqfRDIPXXVFLdRaE34ZOX@DCLP3BJoehRKTvzhrwiG1IpPNTy2o6jUs0zhk4MSh4K/4xSjmJ7nSOjJq@Bg3cMO6H2d63W/S/JvvwL).
[Answer]
# The Terminator
**Turn**
```
function (self, others, storage) {
var attacked = others.map(bot => bot.attacked).filter(uid => others.find(bot => bot.uid == uid));
return attacked[Math.random() * attacked.length | 0] || others[0].uid;
}
```
**Wand**
```
function (storage) {
return 1.00;
}
```
[*Listen, and understand! That The Terminator is out there! It can't be bargained with. It can't be reasoned with. It doesn't feel pity, or remorse, or fear. And it absolutely will not stop... ever, until you are dead!*](https://memes.getyarn.io/yarn-clip/fff0b1b5-a282-4f12-a324-6a9b35a2e03a)
[Answer]
# Simple Threat Neutralizer
Just to get this challenge going a bit, perhaps...
```
function attack(me, them) {
them = them.filter(bot => bot.uid !== me.uid);
const maxWand = Math.max(...them.map(bot => bot.wand));
const attackers = them.filter(bot => bot.attacked === me.uid);
return (attackers.filter(bot => bot.wand === maxWand)[0] || them.filter(bot => bot.wand === maxWand)[0]).uid;
}
function chooseChance() {
return 1;
}
```
Chooses bots with a simple danger heuristic - first bots that have attacked it in the previous turn, then all the rest. Sort by most powerful wand and target the first in the array.
[Answer]
# Roulette Wheel
Every action taken is uniformly random.
```
"Roulette Wheel": [
function (self, others, storage) {
return others[Math.random() * others.length | 0].uid //Random target out of all opponents
},
function (storage) {
return 0.0025 + Math.random() * 0.9975 //Random strength in range [1/400, 1]
}
]
```
[Answer]
# Tall Poppy Loper
Has a major case of [Tall Poppy Syndrome](https://en.wikipedia.org/wiki/Tall_poppy_syndrome) and will elminate that bot.
It also has an irrational fear of others' potential so will elminate bots that threaten its supremancy.
```
"TallPoppyLoper": [
function(self, others, storage) {
if (storage.history == null )
{
storage.history = {};
storage.selfuid = self.uid;
storage.roundNo = 0;
for (var i in others) {
var historyBot = {};
historyBot.alive = true;
historyBot.killCount = 0;
storage.history[others[i].uid] = historyBot;
}
}
else if (self.attacked === null)
{
storage.roundNo = storage.roundNo + 1;
}
for (var i in others) {
storage.history[others[i].uid].alive = true;
}
var targ;
for (var i in others) {
if (others[i].attacked != self.uid && others[i].attacked !=null && !storage.history[others[i].attacked].alive) {
storage.history[others[i].uid].killCount = storage.history[others[i].uid].killCount + 1;
}
if (targ == null || storage.history[others[targ].uid].killCount < storage.history[others[i].uid].killCount)
{
targ = i
}
}
for (var i in others) {
storage.history[others[i].uid].alive = false;
}
return others[targ].uid;
},
function(storage) {
return 0.95;
}
]
```
Bot derived from MegaTom's entry: [Golden](https://codegolf.stackexchange.com/a/202820/20193)
[Answer]
# Don't Kill Me
Survives by staying the *second* most dangerous wizard throughout the game, so **there's always a bigger fish to fry**. Scores pretty high.
```
"Don't Kill Me": [
function attack(self, others, storage) {
storage.left = others.length
maxWand = Math.max(...others.map(bot => bot.wand))
storage.safeWand = Math.max(...others.filter(bot => bot.wand != maxWand).map(bot => bot.wand))
return others.filter(bot => bot.wand === maxWand)[0].uid
},
function wandChance(storage) {
return storage.safeWand ? ((storage.left > 1) ? storage.safeWand : 0.01) : 0.1
}
]
```
[Try it Online!](https://tio.run/##7Vvdc9u4EX@u/grYM0nIWJYp3@XuLFnJJLkkTRvnMknaPLh6gCRIgkORKknZ1tn@29NdfJAACVJSkuu00/rBJonFYr/w212QvqCXNB0nfJkdXv7y5ejoWZylZBYTHpFszlMSjy7YOOu1LmlCRjg2IDdf9l9c08UyZPhkv0fOWwR@pqtonPE48lIWTtskzuYsSdskzeKEzphPbgQV/iAvmmV0/JlNgJ@k7Czo0gN@ZPAY2XY0gd@Z8jBjibfiExxT1FMeTUxyMTog8Mf3@/lKCctWSZQvdn5Gs3knodEkXng@eZgPdEIWzbI5uSXBkNzeqkXOgyHylezu2iUtq3qp1YLOz4/UnNaw3dr/NY4eZOSvPAzJGauYS8lQb7U/qWuQcZoV5pIS52sv6PUn0AvGhY5w63U6Hbdpr4DQ9/Opmn9Kp6yeh/JCiQ3ZG@il/Q3LKOs0sxsMCn7K/Nr6ttWQ@vmcRmPW4ImKZk@I51nmfEy6PjytEPbAiwEM4d@u4cuPc0Y@smTBIwpT/h/75dW6nSAwY/8DFzjxcZ4wmpG3bJUlNOS/s6R2HyxYG5CHLUzmeA/Gwj@OwEH19zBuGF4aFhjHUZrV7AzByxmw5fnKTklaL0HhUJcYyjRezmjL4Edn1CzoIvdr/UXG8zhOmdouLq@ZLnvH6JiRN/HlBieBHy@tEJDmUr4So7s766uNnfPJRZ2x7ExaB2enpqSG6mZMINmmmLhzrDSnqVhG0LqXcfkOL5oZgwofaQK/0yYVhNjKTlqUsvK2CrbNlwlf0GStVgLDG8vm/qh4KmXwd1I3T@zgGq@8Fxj0dxqumEeThK5r9BJjVdjCpyZmOU2o91xpOVtVH3dYiaKslv8N28pCwmerMFzvnv3z/M4jC8V4tCm/F3bJcg9tkXzlOlX4Ukwq/lDPTY9YFvuKtA2pNzi2SqhXcThh0VemW5SwUGcaJ8TDxxxrXDm1HIB8SjychVk1Ar8ZaREfD6W5TvUzLh/4Fg9teLA6d2w9qxpSXL@q1vzhl@7JTz@Zxnoe8sXIAd55anVaSpdA41WSsCjT@JuGHHwVGPEwTeLFiyhLOMOIypnDvvRtK6KRoX3AjuGub42AD4QLlpQDyRT3tI@k5/gAUtkQ5ojL7rDvQgYgdZiUT729vJAbxwlLbY/YYyh7oYmX1wPXuCXOr9EZbYhl30SxTdFUrlvqYsmWRHofwqn8GLhhbIEkw9rYMoj69WFWCL1FaIEdS2a8cXoP4QOcVwocn1REPToiE37JJwylJYInGa3FTbTCUEU2ornM5lAljuNVOIGkesnIVRxVuJWspIqKITkYVFc2fvJELy6W8ZWnca9NDrtHx36bHAc@OWriQYhX0lbD3gH0EQ32x2aib7cRCXtOo9@icP2M/RaxD1kSRzOWbmin/5egrVvtI@B3HG1vIVuQ4NuleEfHfMp3cZLigpbeGdqtgKFh@C5eLtdv4iX7mr4T/a5jd87xaq1DoHDujRMvc3KB42Uo2BhxOlYVm2dYdFQyAv4UBB3RPSC6JSvWSBjSNHtabqcxanWX0Dj7Mw/D5/FKZLugX4s0agawBbpiuj3hjjhL@S0MVF2mRv@71nfY/FUT4RkOxo/oze7fJ3tlgapTlIQuVzu0Mc3cOHygt5tD4025VDOUeFPwPG1c0ga2m80wZ0Pd9/P0lIYpa2plviucvocUy7KMkU9zxkIFJ3mR3owmtjzldsA6ncy7ASgBZJOl2gUSr0TtAKhGANXiCFJp2lLqGHI4V5btAQRLee2gc3Ly86NirTRLpBjgECCbMXLePfoxCNqkO2xpU5yBQDwCQdbkTXwFtYg8q9rNJmBMPIqRXZS2QcImK6idPdoe@VhU5hUIPJBZFQpM35yvDthLXZro0XSHppfxTYuoqRVnqOdlb2xv6JOTk9xQf1ml2YsoXs3mO6SfBsDSm0EZTXi1VGsvVmHGlyEHrwzwaNFAhwLKtHaPybFdqJZm646ybvmTk/7X7msUplQxAe5Ab7YJXhqqMc3ncbU8c8GugVV912BJ3WrJ99C0l5OFWUIo0cBofrMlq5hZi6BlY9TUJUrN4I8ES1MlAzcfnK3JS56kGYH0/8BGCHsPlFhDS5Wtl8zoliLU8sEqmrApj9jkQR66BkFRAioeSq2cZJjPsvUuCAzlCYMMQxqWaSyYy5jRgM3C@9JeT8kn/jtNJuRpkkCeS8m7hI05WGqNmScif2bkjNEoJR/jRnPmkCIXg4byQ4ZdJLaQdCHyvG4h8bVOr2WpuFo8s4BVAobCGuD1ioljazn/imdz2cpDqTebQ0tGusE9cXBF0tV4zNIUkknG5BoIDKno3aCJwyXO1YmFbpJx3kfoU@dxqDZH35igsWuATrBpD5G4q/dAZR07R8Ti7ZDalQOLkWpLQc2nMLjk48@EEpkjCORdtFs2jyEyJHvVh8fqYLLXsnaFFsDONA8rCt0WseOOmtyPr6MxpNtUujIBT070mYAHwMsjnnHxwgjkIV1BNBUbUJD6tqPl9EH5XkHrE5jfs8cOurlxXk/JBSQ4aRJIVVextASFKBMhBbIoSSuhgObqBsG9lgNBdPCdDsgximCshx5kYoGFjGUaudZdOZecsCUD8MDAjwrbNR9ewE@vqEK65KhkqUNxTtEWm1geZ8hd/J5dglfZ3o5b9LXpPAymN/Gs7MFeq3TiVFCWsoCDoOhHYbW/LSfCFXNjNcldb5U4eUHHcwmiuF80FLpWlz2PPFiqpKNm6gJONWKbr6zyTms7dgcHCn/9QtOXYs@L00vpebagsFHyvQuPMIrFWVq@8jpeiZFFLN7RrVLoOJICwzTdGQw/w1a/OLEQhRi91l22GFUqfqtlH9uMjfKtIo@Y1Tc/d7AEalpGz7qrWFJuQuPoUe86EkHIJ5b1ehIf5CNhYKCXCGiBZFnyHH1cDdNDKyPdGh88gHQvIF/3oNz5jC4WO1DvdTx53dq9mwDBFnhL2A6gnL5HuIy2EPomWNaBiygjEKUZfvxiZFZ1BowIQJM15qDjQLNOY3LFHgA9Al92xceKT5U9TAs6IAaW6FTxhGcJ9ihQYXR/7HQJg8AsFyiPFLR9uevjgoCjqnogACG01To6mtEFS3vkbX46LR4gzierCMYFdlkE8glZwh3SAg0ulyLeXhNxaY6FgE0kIF4Ug/Fm0H/OoBfsEo8lSZyk4OZwjefRxJuwjPIQHKzJWq28awNRXqFYnhRugDmorQVRd3JlcQN3oUDNwOxaQetfQWm7ciGeGsKWR7w/ziNJ0XeWq3Tu2W1IBGL0kKBtPUYRxGNxVj@EstIel3nAIOiWCCAiwVj2M3Fs0iN7pccYI1VaFeCVgWXMoyytPFbB3oP0UrQYfsk4sgWBP6cyNuDy4MDsJJAIJEfjR@wKC2C69rT15H4Xn/eEXiC/nPJom8iDgpHxKgHZ6LomKJ324dhFGxpT8e1PXkwekm4fHj5G@fjhYblbvNDvkKdhDEVq@czA4@Jlhm@3cOe4APSkbbHS@YV4RXeurtVDPhy6XoHkonJpMg4ms@0Az2zbGYGm3m0pFeGuX0el3FY6XHbIkUg5EpBDbha4rq6PlAIxKkfD2KfiToJC@7j6YgS/johD1gEKbx@/4vkAXWiG2Vm6cR/M682EjeHX/qG4T1w2LzZie0fbCcvAjMI61YY8A9x1HiPkZ01FqQjQkX91APWhRD1vJMtGrzbLjLRPnBS@X1ZYtqljmkEtwfxN0gXOQwrtHb9WKu2gK5pE4CG0v/AzOGMovDPqIJLhPUBR7x@R8BADXTDx394S1oH9nmI69Dedc2iBpMU6PH1L33qj8peR26rXHHjV4GtSjXjyHvcW3Po9GZgjfRgECUPE5719h5Kj/Nh6L3COFm9kijrSbaFJ7PAzBr3kYbbUZQqITPUVWg0R6q4L6O@3sbbZXNpbe8pSjdEI4OB6y9W8SYvElsr3UqMOqus1lnw3GwtCkWtFVLQ30spkKyNmM3WRhYv4aJx018xTe0udgFBMnFTF5f37cCm/NJTKyAwraLwtjUB3MQLd2Qh0SyP4fieNk8yoDqRmh0qxDUZqRGCBwu7A2wjDlfjb6/ZrCTdi8q64HOyMy25svvsvxgbJI98FkIjdewC/6is85Tc51MD1zd5sSEPfIx29ji5BmInoQsSgEW1Ise/3twvM/Ix926Co5LCCXf8/KoJMNQeGot8SUXY7cKrgvSlo/j3hkH/kIQYcUa/@CcKI9BK3HeJnS/6bNot65WIZqMGQ32Kel/KUID@3/8PNtA2Wavs0pGrfXeXK/x4oXo503YElyPA9lezk8RPAvE85xtf85Eg@SP8JKTSnLn8fXbvyKa5c47Htwr7Jp594FBmHR02dId6rCt0S8ElhAuFFoHkbkyvBeL8uDY4SRj9vfENLruYQUsQT8p7Kg6TKJ47yt6mkPIvCaMIrL/VhFD/dy6DokSlbR0NekZ1TITzU8sqPw0rNM4JODEoeCn@MUo5ie51bRg5eAAdvH1ZC7e9arcoh2Q/bHpJ9@Rc)
[Answer]
# The Wild Card
Chooses a wand success chance at random from the set {0.1, 0.2, ..., 0.9}, favouring values closer to 0.5. Each turn, it makes a decision to either attack a bot who previously attacked it or attack at random.
```
'The Wild Card': [
function(self, others, storage){
// Keep a list of the bots who we hold grudges against
if (!storage.enemies) storage.enemies = [];
// Update our list of enemies
others.forEach(o =>{
if (o.attacked === self.uid && !storage.enemies.includes(o.uid)){
storage.enemies.push(o.uid);
}
});
// Filter out bots that have been eliminated
storage.enemies = storage.enemies.filter(x => others.map(o => o.uid).includes(x));
if (Math.random() > storage.wand || storage.enemies.length === 0){
// Our wand couldn't beat a random number
return others[Math.random() * others.length | 0].uid
}
// Our wand was stronger than a random number - attack one of our "enemies"
return storage.enemies[Math.random() * storage.enemies.length | 0];
},
function(storage){
// Reset the enemies list at the start of each round
storage.enemies = [];
// Randomly assign a wand success rate (favours values closer to 0.5)
var u = Math.random();
var randNum = 0.9
if (u < 0.3) randNum = 0.5
else if (u < 0.5) randNum = 0.4
else if (u < 0.7) randNum = 0.6
else if (u < 0.8) randNum = 0.3
else if (u < 0.9) randNum = 0.7
else if (u < 0.925) randNum = 0.2
else if (u < 0.95) randNum = 0.8
else if (u < 0.975) randNum = 0.1
// Store our wand success rate to use when choosing a target
storage.wand = randNum;
return randNum;
}
],
```
[Try it against current bots](https://tio.run/##7Rtrd9M49nt@hdpzAJumadIZBprSzgGGmWWHdjjALh@6@aAkSmJw7KwfLZnS387eq5clWXbSMrNn9@z2QxNLV7pP3ZeVj/SS5pMsWhX7l0@@Hhw8T4uczFMSJaRYRDlJxx/ZpBh2LmlGxjh3Qq6/7r78TJermOHI7pBcdAj8zcpkUkRpEuQsnnVJWixYlndJXqQZnbOQXHMo/MO9aFHQySc2hf0EZG9JVwHsR05OcdueAgh7syguWBaU0RTnJPQsSqYmOJ89IfARhscaU8aKMks0soszWix6GU2m6TIIyUM90YtZMi8W5Avpj8iXLxLJRX@E@4rtbroOl3W@JLZ@7/EjuaYz6nZ23y8Yec@yZZRQWPN/ebnYBr1@35TXu4jb1vtFxmhBzllZZDSOfmd10Ul6giXrgrWypbk5PoOw8ENJxGF/B/hfMvxqSGCSJnlBlvTzB@Aa1nMJwGPQ6/X4Xo7YrwAsrK2XcsryZgoqhfrIkKIJ9EaeHa44hbhaUBteCGU0IPSBh436IpNFmubsxYImExb4tGaq7A2jE0Zep5cblAR6vLRMQIhL6orP3l5Zdxa23keTOmfFmZAOrs5NSg3WTZtAsE02cePBtKA5R8Nh/Wh8usMv7RsDC@9pBv/zNhY42VJOihSXeZsFW@arLFrSbC0xgeANtFofNU3lDD6nTev4CW7Qylvug/5O45IFNMvouoEvPld3Wzhq@iyvCNWZc9DZrIZ4whwIl63wG46V5Qmfl3G8bjxQG@MGRBzLi0UJWqw/fLg2W2gN6QDS7FAEnrr7kpvU9CHHTY1YErPZRTxSYG1Bt98/tMLuL2k8Zckdwy1SWLEzSzMS4HCEeZFY6hpgNCMBrsKomoDejLCIwyMhrqdqLBIDobWHEjxIPfIcPcmqteud8pPvngyOfvjBFNaLOFqOPc5bh1avpORQb1JmGUsK5X/zOAJd9Q17mGXp8mVSZBFDi9Kbw7kMbSmikCHlxCzz5tiaAR1wFaxoBCAzPNMhgl7gAISyEazhXwejY59nAFCPSKNZsKO4yCdpxnJbI/Yc0l5xEuh84DMeiYvPqIwu2HJoerFN1uTmLU22ZFMitA/m5A7DbmhbQMmo0bYMoONmM6uI3sK0QI6OGK@92kP3AcpzDCckNVIPDsg0uoymDKklfE8yXvOHpERTxW14QVIsIEucpGU8haB6ychVmtR2c6Qkk4oR2TupYzb@dKDnX1bpVaD8XpfsDw4Owy457IfkoG0PQgKHW@X29sggbJE/eLSBU0Zk7AVNfkvi9XP2W8LeFVmazFm@oQT7X3Jtg3odAf/TZHsJ2YT0v52KN3QSzaLbKOmPIMFKI97TOH6Trlbr1@mK3aYA7ZgWoKx4EeG3tTaGSs/XXtep4WsuXZ9KwM/rUYLfbLdkwmVpmUzPU4DrGw52WytW9i/peY6JTI0k/KsAerwiQY@ZlawV8FMUxy@AvEIQ1@R/5IqL6qRwN3RibGUvviGew8LinAmVoLis2gY1skkhlRjdkT1lum5xsYV421lskORN5w6uqeabKlRaFjuVLZH794kXglsvTO40k66gJf0@k9rAt2kYW4NaenDktCk/cDbXrtTc/@nWpNhO/HqzS7ct9c@xoRmFA9BWwn17hnxklRJvIbtgRcHIhwVjsXSguj5pryhsktxKSBZXTiEE2Y@oL2WlRNKSp03gxwn48TSBLCLvSI4MOryYRWUENuXiBi6PHj@qcOVFJsgA/QDYnJGLwcH3/X6XDEYdJYozIChKgJA1eZ1eQRom2nS3kwkIE7tQooBUMsjYtISyIaDdcYj5tE6@YEAkFJBbh@Z62Y92ClRenqriVKEJTYnIpTVlyHFXG9sL@ujoSAvqr2VevEzScr64S8Cte0N1NqTQuFadMmNZxkW0iiPQygl2VQ0nUrlJxd0pObRzdGe1Kqab0B8d3TlUIDFOsgguCcrSTd6mJRFV@5zWM1Of1zZc17Fv0mG3nu0@NOXl3cLMmSRpILSwXZJ1F9roUF1hNIR9yWb/z/SXJkuG33xwtiY/R1leEMhrHtgewj4DztZQTRbrFTMKxQS5fABZCptFCZs@0KZrAFRJr9xDsqVBRnqVzXcFYDAvsqwWNK2JuuszWnwz176Q1zPyIfqdZlPyLMsg1OXkTcYmEUhqjZEnIX9h5IzRJCfv01ZxapcikEEt/a7AAhqrZ7rkKYCqnmM2K4Ydi8Vy@dxyrMJhSF8De/3CeMderL@KioXoYkAOO19ANUoG/Xu8Z0fycjJheQ7BpGACBzqGnJetUL8iigvZrFH9AVz3Hkr0RRrLw3FsLFC@6wSVYMPuI/BAnYEaHjtGpPzFmDyVJ9ZGsiIHNp/B5CqafCKUiBhBIO6i3IpFCpYhtpctiFT2ZIcd61QoAuxI87DG0JfKdvxWo/X4KplAuM2FKnnartohATjeKImKiL8rA3rIgAPN@AHkoKGtaLH8xH2WrvVHWD@05/YGWjivZuQjBDghEghVV6mQBAUr4yYFtEhKa6aA4hr0@/c6Hg@ijO/pCTlEEgx8qEHGESyFLdPEh7f0opyyFQPngYafVLJr79vA37DKQgbkwJHUPm/RdPkhFp0ccYrfskvQKtu55RF9ZSoPjel1Onc1OOw4zbYK0okCHgBe7Cpsf1tNuSoWBjaxuzoqafaSThbCieJ5Ua7Qh11k6rKYdcNRO3TlTpXHNitaXcVtt93envS/YcXpz/zM88at0DxbUjgo@uzCEFoxbyNqzOu05DPLlL@eLHMoOrLKhym4M5h@jq0N5PhYT4O9PJMQfFay@K2SPbU3NtK3Gj18VRXyXYLa0KhVNzVJikNodF3VqSMJmHxmSW8o/IMY4gIGeOEBLSfpUq69j69gemhFpC86PefUvYR4PYR05xOqmJ9Addax6by1ejc5BJvgLd12H9LpeyQS1hZD3QRoPX4RaQSgvIDy24yssv2NHoBma4xBh321dZ6SK/YA4NHxFVfRRO5T3x6W9XtABqboVO4JYxnWKJBhDL7vDQgDw3QTlEeVa8OrLB8iCLcvIEu5pX/7lbEV4I2jvBBRVGUQC@SA8Cg@z8rpHAI2ncMRzYuOynN1i4YlbBmxvMqi5YBMJRzvlpaZxicBvQcRDuG1XSrZXTWzleSS0oNAF5dTlsMifpvm2lc2KeBVmS8koNv69/gsLPur08bfbowZ5IEsjvhtIjbteJAY51uhlXnPZ@NCEL63knkQUlOx8Vm/vkJJ2DXyqV29GG0nhUlnaOD1DFEAT7@VIr0T72qSB8Aa3u/R2ZXIYxpKk@36Jh2jvDExXtFcZmMgVJ44OFghlhueCqwFLWdX8rTrS1TkXI2wBnmoSwcb/MRblsvkWumSmy8VYzkUaMKWwWqNDKb9LIjuDhxwmufRHFmvu4ZgRi@B5RyiV1zCDpMYUtwMEzXwGKGOa6W6SqAYrkIejpyXS5Gza@spZV1vTT/qWE1sAfPIhvneB/PYhvnBB/PEhvnOB3Nkwzz2whw6FB16oRygJ16gxw7UoGOXZamyUzdL5rksFn781gimLFR2BDueJoVEITUv7VUPqr7UTykevV8xwpyxu98tUbh5@HdKRTPt8Fyja7uAUts/pzPWvEfDpZSd6pLbBjSWl9ny0lzlae50U6XG2Y8kCCxxnpJBCKM1wCEvOEL@OVBtlq83x2hJUN3Imp5A6KOdzsHBnC5ZPiTn@nU5H0C7ysoE5rkDsQDECFnBE8ICDFKcYxX0mfCv5lwMFQPpkyBJIaWZz8E8wy4UjQHLshRcSZrEa3xBToIpK2gUQyxVYJ2OFhmQ8guSFQjiTrAy7CpC5JPAzB/gKea1TN/sJQPXPwHTdj@BBHIKG5H8QpvWhIQX0dhuDiZAxhAButYwksCH@eWBEViBPS@qMwNg4ACAzYCw7DH@PmNIdpxhtKI6rMxHahOrNEqKvDYsjWcIRV@VZ4SOcERjED6eCtuAr3t7pskiEFCOwk/YFbal6DpQ0hOHnd83joO@OGkB7RLRvh8bCQ5uo7oNfecFH8597JKI8MvIOmDuk8ExDJ4ifdH@vtvD/aj8wSxO0yxwo3AQ8dsVod1YvUAEF9GoyzFdfOR3hi7kdzkYjUa@Oxma1EiILAKR2XKAMVt2hqHJN1iSRXg6boKSanPeTHvoyAQdGdAhDgt8r@NHSO50am@lMTzhSTo9IYf1mxp4XTONwR2l82AXrxW/w9QDA5BQ4y6IN5hzGcO/3X3@nPlkXh3E7i1lxyUDKyrp1NvkBVRD3ua@fgNURQ1wHfoa5KArvV4wFs2coLH2GyudeCHC0GVYNI8ntIDCgoWbqOt7Xx0o7YSNVCkFXdEsAQ2h/LmeQRkjrp1xDz0ZPoMrGv4j4RqCWMKTXMjbWQ/Oe44RKtz09kERJCTWi/Jzeh6M3Ui6LXvthlc3vjbWSCCe8WzBYzgUhjlWr2ggYHD7vLfrYXKs3yfv9L2z1S8uqu6OX0LT1KNnNHqxh9nodiHAMuW1@AYg5F21tf64g7XN4dLFt5RUqzWCc/BdkWk/pFVgQ6eI5PSQ3aC1EXO9sU3DYy23iu5GWBFshcVshq6icGUfrYtu2vdU2pKJJ8XASaVd3r8PX8VPHwQzIsJymGBLIdDbCIHeWgh0SyGEYS9Ps8LIDgRn@5KxDUJq9cDcC/sNb6MbrtnfzuC4EXCjT76tX@7f2i/7ffPNf7FvEHvoUwCB2H8GsASrNBW2KdTw65u12RKG/ohw9Cq5BGKmvArhk4a1IcRueLydYeo339saRS2GVdsd/0dZkMnmicHot1iUXQ48le69zWj@Peag3sEIQI/Vy19lGpbu7HYL@9ly/02H5aZqZ2kBtQjyW8Tzs@gS6Lfpf7qYtvGlSj4toTr0Z7ni54zVlYWB37A4GLaVRCWPv0nQdcohXr4jB2Ig/yeEUA3t/mCrEfNTxNygse3Mvk2nH6IkMZpHbZUhPssM3SLwx0oEXIsAc56SK77xblMYHGeMftp4b4pcLcCkSMDpfSoaSfUXLx2XSdGLQmvCb0Eewiz@lqCApEeEbGUNOiO7oJx4yOWlHke1nGcMlRi@aIAPI5WjWF5ryYjJj7BDsAuYkPubTqfWJHu0bZPs678A)
[Answer]
# Copycat
Attempts to make it to the late stages of a round, then copy the average wand strength of the remaining bots when there are 1 or 2 other bots left.
Targets bots with wand strength between 0.1 and 1 (exclusive).
```
"Copycat": [
function(self, others, storage) {
// Copy the strategy of the bots that make it to the end
if (others.length == 2){
storage.strength = (others[0].wand + others[1].wand) / 2;
} else if (others.length == 1) {
storage.strength = others[0].wand;
}
// Filter out the highest and lowest strength bots
var filteredOthers = others.filter(a => a.wand < 1 && a.wand > 0.1);
if (filteredOthers.length > 0)
return filteredOthers[Math.random() * filteredOthers.length | 0].uid;
return others[Math.max(0, others.length - 2)].uid;
},
function(storage) {
// Prevent overfitting: discard the copied strategy with 1/10 probability
if (!storage.strength || Math.random() <= 0.1){
storage.strength = 0.025;
}
return storage.strength;
}
],
```
[Try it against the other bots](https://tio.run/##7RtbdxM3@jn@FUrOocwQx7FDKcS59AClLVsCHKDLQ9YPY1u2FcYz3plxghvy29nv020kjWbshHbP7tnlgdjSJ@m73yRfRJdRPsrYoti7fPJ1f/9ZWuRkmhKWkGLGcpIOL@io6Lcuo4wMce6EXH/defE5mi9iiiM7fXLeIvBvskxGBUuTIKfxpE3SYkazvE3yIs2iKQ3JNYfCf7hXVBTR6BMdw34CsjOPFgHsR05OcduOAgg7ExYXNAuWbIxzEnrCkrEJzmdPCPwJwyN9UkaLZZbow87PomLWyaJknM6DkDzQE52YJtNiRr6Q7oB8@SIPOe8OcF@x3U3bobJKlzyt23n8SK5pDdqtnQ8zSj7QbM6SCNb8n1/uab1Ot2vy6z3juvVhltGoIK/pssiimP1Bq6yT@ARz2gZtpXNzc/wOzMI/iiMO@dtA/5ziR4MDozTJCzKPPn8EqmE95wB8DTqdDt/LYfsVgIWV9ZJPWV6PQSlQHxqSNYHeyLPDFccQVwtsw3MhjJoDfeBhrbzIaJamOX0@i5IRDXxSM0X2lkYjSl6ll2uEBHK8tFRAsEvKis/eXlh3ZrbeR6M6pcWZ4A6uzk1MDdJNnUCwdTpx4zlpFuX8GA7rP8YnO/zQvDGQ8CHK4P@8iQSOtuSTQsUl3ibB5vkiY/MoW8mTgPHGsVoeFUnlFP6O69ZxC66Ryjvug/4exUsaRFkWrWro4nNVt4Wjps/yslDZnHOcTWqIFuZAuGSF32BWlid8tozjVa1BrY0bEHEsL8YS1Fh/@HB1ttAS0gGk3qGIc6ruS25SkYccNyViccwmF8@RDGsKut3ugRV2f0njMU3uGG4Rw5KcSZqRAIcZ5kViqauAbEICXIVRNQG5GWERhweCXcdqjImB0NpDMR64zjymJ0m1dr1TfvLwSe/whx9MZj2P2Xzocd46tHo5JYc6o2WW0aRQ/jePGciqa@jDJEvnL5IiYxQ1Sm8OdhnaXEQmQ8qJWebNkTUDMuAiWEQMQCZo0yGCnuMAhLIBrOEfe4Mjn2cAUA9L2STYVlTkozSjuS0Rew5xLykJdD7wGU3i/DMKow26HJpebJ02uXlLnS7ZmAjpgzq5w7Ab6hZgMqjVLQPoqF7NSqQ3UC3go8PGa6/00H2A8BzFCUkF1f19MmaXbEwRW8L3JMMV/5IsUVVxG16QFDPIEkfpMh5DUL2k5CpNKrs5XJJJxYDsnlRPNv7pQM8/LNKrQPm9Ntnr7R@EbXLQDcl@0x6EBA61yu3tkl7YwH/waD2njMjo8yh5k8SrZ/RNQt8XWZpMab6mBPtfcm29ah0B/6fJ5hyyEel@OxZvoxGbsNsI6c9AwUojPkRx/DZdLFav0gW9TQHaMjVAafGM4aeVVoZSztde16nhKy5dWyWcz@tRgp9st2TCZekyGb9OAa5rONhNtVjpv8TnGSYyFZTwXwnQ4RUJesxsSRsBP7E4fg7oFQK5Ov8jV5yXlsLd0Imxlb34hniMhcY5FSJBdlm1DUpknUBKNroju0p13eJiA/Y2k1jDyZvWHVxTxTeVR2lebJe6RL77jnghuPbC5HY96gpa4u9TqTV0m4qxMaglB4dP6/IDZ3PtSs39jzdGxXbi1@tduq2pf40OTSIwgKYS7tsz5EOrlHgH2QUtCko@ziiNpQPV9UlzRWGj5FZCsrhyCiHIfkR9KSslki552gR@nIAfTxPIIvKWpMjAw3uyqIxAp9yzgcrDx4/Ks/IiE2iAfABsSsl5b//7brdNeoOWYsUZIMQSQGRFXqVXkIaJNt3teALMxC6UKCAVDzI6XkLZEETtYYj5tE6@YEAkFJBbh@Z62Y92ClRenqriVB0TmhyRSyvCkOOuNDZn9OHhoWbU35Z58SJJl9PZXQJu1Rsq25BM41J1yoz5Mi7YImYglRPsqhpOpHSTirpTcmDn6M5qVUzXHX94eOdQgcg4ySK4JChL13mbhkRU7XNazUx9XttwXUe@SYfcarb7wOSXdwszZ5KoAdPCZk5WXWitQ3WZURP2JZndv9JfmiQZfvP@2Yr8zLK8IJDX3Lc9hG0DztZQTRarBTUKxQSpvA9ZCp2whI7va9U1AMqkV@4hydIgA73KprsEMIgXWVbDMY2JuuszGnwzl77g11Pykf0RZWPyNMsg1OXkbUZHDDi1wsiTkF8pOaNRkpMPaSM7tUsRh0Et/b7AAhqr52jOUwBVPcd0UvRbFonL@TPLsQqHIX0N7PUL5R17sf6KFTPRxYAcdjqDapT0uvd4z47ky9GI5jkEk4KKM9Ax5LxshfoVjziXzRrVH8B1H6BEn6WxNI4jY4HyXScoBBt2D4F7ygYq59gxIuUXY9IqT6yNZEUOZD6FyQUbfSIRETGCQNxFvhWzFDRDbC9bEKnsyfZbllUoBOxI86BC0JdSd/xao@X4MhlBuM2FKHnartohAThelrCC8bsywIf0ONCEGyAHDW1Bi@Un7nfpWn@E9X17brenmfNyQi4gwAmWQKi6SgUnItAyrlKAi8S0ogrIrl63e6/l8SBK@Y5PyAGiYJyHEqT8gLnQ5Sjxnbv0HjmmCwrOAxU/KXnX3LeBf/0yC@mRfYdTe7xF0@ZGLDo5worf0UuQKt2@pYm@NIWHyvQqnboS7LecZlsJ6UQBDwAvdtVpvy/GXBQz4zSxuzKVNHsRjWbCiaK9KFfoO11k6rKYdcNRM3TpTpXHNitaXcVttt3urvS/YUnpz9zmeeNWSJ7OIzAUbbswhFrM24j65FW65DPzlF9PLnMoOrLShym4M5h@hq0NpPhIT4O@PJUQfFaS@K2cPbU3NtK3Cj58VRnyXYSajlGrbiqcFEZodF2V1ZEEVD6zuNcX/kEMcQYDvPCAlpN0Mdfex1cwPbAi0hednnPsXkC87kO68wlFzC1Q2To2nTcW7zqHYCO8odvuQjp9jzChbTHUTXCsxy8ijgCUF1B@m5FVtr/RA0TZCmPQQVdtnafkit4HeHR8xRUbyX2q28OybgfQwBQ9knvCWIY1CmQYve87PUJBMd0E5VHp2vApy0cG4fY5ZCm39G@/UbqAc2OWFyKKqgxihhQQHsWn2XI8hYAdTcFE86Kl8lzdoqEJnTOal1m0HJCphOPd0mWmz5OAXkMEI7y2SyW7q2a2klxUOhDo4uWY5rCIv6a59pVNCnixzGcS0G39e3wWlv2ltfHbjSGFPJDGjL8mouOW5xDDvtWxMu/5bDwIwnsrmQchNiUZn/X1FXLCrpFP7erFaDupk3SGBl7PYAXQ9GYp0jtxV5PcB9LwfY/OrkQeU1OabNY3aRnljXniVZTLbAyYyhMH51SI5YanAm1BzdmRNO34EhU5V0Gshh/q0cEaP/GO5jK5VrLk6huJsRwKNKHLoLVGBtNsC6K7AwYe5TmbIulV1xBMoksgOYfoFS9hh1EMKW6GiRp4jFDHtaV6SqAILkMejrxezkXOrrVnKet6a/pRy2piC5hHNsz3PpjHNswPPpgnNsxDH8yhDfPYC3PgYHTghXKAnniBHjtQvZZdlqVKT90smeeyWPjxVyOYskSyI9jyNCnkEVLyUl/1oOpL/ZSi6f2GEeaM3v1tiTqbh3@nVDTTDs8zuqYHKJX982hC6/eoeZSyXT5yW3OM5WU2fDRXepo7vVSpUPYjCQKLnaekF8JoBbDPC46Q/@0Z7enfFwuanbHxOKbPY7DyX6HAp3d9aDpfveEAWqhGFimnOnmaFdioJaJTGwk27cm2q/QKqtkqF53r1dIlYgP6SfXtz@aPWB4@tF6wpIvVKLrNc@QtMEBcJX0rGt10ZaUmPOzOMaNkBdqjcMzj1la1nQoqgv3ULUt3VUP9RN9RdWX7cFcFtp7qUe6Tg6PW1k3pPCr79zjSNQfY@@NOLU6gkUmYPRrEQeahehMkubWFOiDsgI4dTVD2ERlCPyY9zIoi1eLEJgx4IM4he5uy8dwNW1tbUo42TCWc@rcolWbLkyagi@i2nRRhD8SzmaIh197yCgJiLZQ1E1YU4Hr7ZMzyETbnkI@jdMEgOdRag8k66e33umSRpcNoyGJWrAQXtivSgrTJpvNYNK/qpQt2j/14EOpWrTuR0KVNfL05whgDCiu7fQSS4qjV2t@fRnOa98lr/ZCGD6CGZ8sE5nlqYQGIEQJ@hsMCDB6eY3/kM@Efzbk4BXZ1SZCkoGTTKXAvbIOeBDTLUtCnNIlX@HSGBGNaRCymYw3WamlnCqj8gmgFArkT7Bm1FSLymziZf4FvMe9ydM1bJqD6JyDa7jSSQE7hFQV/6qqZKuFFnm5fGySARh8B2tYwosCH@bOiAVigPS/6NgZAzwEAnQRm2WP8prNPtp1htLEqrKxUKhOLlCVFXhmWCtMn18a1QugwR1wZwJ9joRvwcXfXdMMIBJgj8xN6hQ3raBUo7gmb479EiIOuiMFluBgapQ9uo/qQXefqH@cu2oQR/jMFw5J7RzB4ivixvT33dudCZQqTOE2zwHUoAePvrkL7yuUcDzhngzY/6fyCvyY8l5/lIBsMfK@1NKpMsIwBy2w@wJjNO0PR5N22JBG@HdVBSbE5b1Y8eGQCjwzwEMYCn6vnIyT3H5X3Kuiz0JJOMaJVWiL4kDuNIVFJp8EO/uDgPRYlmJoKMe4Ae4Mp5zH8t7PHv2c@npeG2L4l7zhnYEXJneoFWpGt/Nd@@m6YmMFCP5DutaXXC4aizRvUdoWGSiZeiDB0CRbXSpCjjGYBDddh1/VeKirphLVYKQFdRVkCEkL@czmDMAZcOsMOejL8Dq6o/4@ESwjjB5a/EJpoB@w9x2AYrruXVAgJjnVY/jp6HQzdHHtT8poVr6p8TaSRQHxH24KvYV8o5lBd3kLA4Pp5b8dD5FC/NNnuemfL32KVfV8/h8apR86o9GIP8wrMhQDNlD@YqQFC2lXD@88zrE2MS7flJKcatRGcg@/xXLORloENnSKi00Fyg8YW7fXaBi6PtVwr2mthRbAVGrMeuozCpX40Lrpp3lNJy065hTrwfFv8KEoQIyIshwk2ZEJ0GyZEt2ZCtCETwrBaTCJle5KwNUxq9MDcC/sVb60brujfdu@oFnCtT76tX@7e2i/7ffPNf7FvEHtoK4BA7LcBbM6UkgqbBGr49fXSbAhDf0Y4eplcAjJjXoXwSUPbEGInPNpMMfWbmE2VohLDyu2O/qM0yCTzxCD0WzTKqbtVx6pBaf496qBuZwWgR@vl77UNTXd2u4X@bLj/OmMxelWaQQ2M/Bb2/Cy6BPqdzV/Opk18qeJPQ6gO/Vmu@KGz2dnzIsHBsKUnKnn8tZKuUw7wWS7ZFwP5PyGEamj3p5y1Jx/LnuLd1b5Jph9ZkhjNo6bKEL/LDN1C8MeSBVyKAPM6JVd84526MDjMaPRp7YtKcjUDlSIBx/dYNJKqV7Itl0jRi0Jtwk9BHsIs/sqogKRHhGylDTojO4848pDLSzkOKjnPECoxvIKEP0YqF2F5rTkjJi9gh2AHTkLqb1qtSpPs0WZNsl749V8 "JavaScript (V8) – Try It Online")
[Answer]
# There Can Only Be One Strongest
Simply chooses the strongest remaining bot and attacks at full power!
```
"ThereCanOnlyBeOneStrongest": [
function(self, others) {
var targ;
for (var i in others) {
if (targ == null || others[targ].wand < others[i].wand)
targ = i
}
return others[targ].uid;
},
function(storage) {
return 1;
}
]
```
Bot derived from MegaTom's entry: [Golden](https://codegolf.stackexchange.com/a/202820/20193)
[Answer]
# Simple Simon
Simply chooses the first bot in the collection of other opponents and attacks at full power
```
"SimpleSimon": [
function(self, others) {
return others[0].uid;
},
function(storage) {
return 1;
}
]
```
Bot derived from MegaTom's entry: [Golden](https://codegolf.stackexchange.com/a/202820/20193)
[Answer]
# Marginally Lower Threat
```
"Marginally Lower Threat": [
function (self, others, storage) {
let maxwand = others.reduce((a,b) => Math.max(a,b.wand), 0)
let maxbots = others.filter(b => b.wand == maxwand)
return maxbots[Math.random() * maxbots.length | 0].uid
},
function (storage) {
return 0.999
}
]
```
If bots are going to target the strongest remaining, then why not be just a little less than the strongest? Targets a random strongest bot each turn.
[Answer]
# Pacifist
Thinks wizard battles are not cool and will not target anyone.
```
"Pacifist": [
function(self, others) {
return others[0].uid;
},
function(storage) {
return 0;
}
]
```
Bot derived from MegaTom's entry: [Golden](https://codegolf.stackexchange.com/a/202820/20193)
] |
[Question]
[
Assume an simple keyboard with this layout:
```
1 2 3 4 5 6 7 8 9 0
A B C D E F G H I J
K L M N O P Q R S T
U V W X Y Z . , ? !
```
Peter's keyboard pattern can be generated by starting at the top left of the keyboard, and displays the first three characters and a newline. It shifts over one character and displays the second, third, and fourth key. Once it reaches the end of a row it continues at the end of the next row and goes backwards, until it reaches the start of that row and then goes forward on the next row, and so on until it reaches the beginning of the last row.
This is Peter's keyboard pattern:
```
123
234
345
456
567
678
789
890
90J
0JI
JIH
IHG
HGF
GFE
FED
EDC
DCB
CBA
BAK
AKL
KLM
LMN
MNO
NOP
OPQ
PQR
QRS
RST
ST!
T!?
!?,
?,.
,.Z
.ZY
ZYX
YXW
XWV
WVU
```
Write a program which accepts no input and displays Peter's keyboard pattern. **The program must be smaller than 152 bytes**, i.e. the size of the string it outputs.
This is code golf, so the shortest solution wins.
[Answer]
## Perl, 63 chars
```
say for"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU"=~/(?=(...))/g
```
This solution uses the `say` function (available since Perl 5.10.0 with the `-E` switch, or with `use 5.010`). Without it, the best I can do is 67 chars (and an extra newline at the end of the output):
```
print"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU"=~/(?=(...))/g,$,=$/
```
---
Earlier 65-char solution:
```
s//1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU/;s!(?=(...))!say$1!eg
```
Replacing `say$1` with `print$1.$/` lets the code run on older perls, at the cost of 5 extra characters.
[Answer]
## J, 66 62 45 characters
Turns out I was being too clever by half.
```
3]\'1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU'
```
is all I needed all along.
Previously:
```
_2}.|:>(];1&|.;2&|.)'1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU'
```
and:
```
38 3$($:@}.,~3$])^:(3<#)'1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU'
```
[Answer]
## APL, 43 characters
```
⍪3,/(1⌽⎕D),(⌽10↑⎕A),(10↑10⌽⎕A),'!?,.',6↑⌽⎕A
```
This works on [Dyalog APL](http://www.dyalog.com). I managed to save a couple characters by generating the output string (everything after `⊃`). I'll write up an explanation when I get some time!
Here's how the output looks:
```
⍪3,/(1⌽⎕D),(⌽10↑⎕A),(10↑10⌽⎕A),'!?,.',6↑⌽⎕A
123
234
345
456
567
678
789
890
90J
0JI
JIH
IHG
HGF
GFE
FED
EDC
DCB
CBA
BAK
AKL
KLM
LMN
MNO
NOP
OPQ
PQR
QRS
RST
ST!
T!?
!?,
?,.
,.Z
.ZY
ZYX
YXW
XWV
WVU
```
Explanation, from right to left:
* First, we construct the string seen in all of the other entries:
+ `6↑⌽⎕A`: `⎕A` gives us a string of the uppercase alphabet, from A to Z. We then reverse it (`⌽`) and take (`↑`) the first 6 characters of it, giving us `'ZYXWVU'`. (In retrospect, this approach doesn't end up saving any characters, but I'll leave it because it fits in better.)
+ `'!?,.',`: We concatenate (`,`) the string `'!?,.'` with the previous result.
+ `(10↑10⌽⎕A),`: We take the first 10 characters (`10↑`) of the alphabet, which is first rotated ten times (`10⌽`), and concatenate this with the previous result. As an example of rotation, `5⌽'abcdef'` (the string `'abcdef'` rotated 5 times) gives us `'cdefab'`.
+ `(⌽10↑⎕A),`: Take the first 10 characters of the alphabet and reverse them, and concatenate this with the previous string.
+ `(1⌽⎕D),`: `⎕D` gives us the digits as a string, from 0 to 9, inclusive. We then rotate ('⌽') this string by 1, yielding `'1234567890'`. As before, we concatenate this with the previous result.
* Now that we have our string built (which saved us 3 characters from the APL representation, due to surrounding quotes), we do some magic to build our final output:
+ `3,/`: We take the string, in groups of three characters, and concatenate them.
+ To finish it off, we use `⍪` to ravel our vector of strings (really a vector of character vectors) along the first dimension. This has the effect of changing its shape from `38` to `38 1` (a 38x1 matrix).
[Answer]
**R (75 characters)**
```
embed(strsplit("1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU","")[[1]],3)[,3:1]
```
What does this do?
* `strsplit` splits a string into substrings, in this case individual characters
* `embed` is a really useful function that turns a vector into an array of overlapping elements
* The rest is just indexing and sorting columns in the right order.
This produces and prints an array of characters:
```
> embed(strsplit("1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU","")[[1]],3)[,3:1]
[,1] [,2] [,3]
[1,] "1" "2" "3"
[2,] "2" "3" "4"
[3,] "3" "4" "5"
[4,] "4" "5" "6"
[5,] "5" "6" "7"
[6,] "6" "7" "8"
[7,] "7" "8" "9"
[8,] "8" "9" "0"
[9,] "9" "0" "J"
[10,] "0" "J" "I"
[11,] "J" "I" "H"
[12,] "I" "H" "G"
[13,] "H" "G" "F"
[14,] "G" "F" "E"
[15,] "F" "E" "D"
[16,] "E" "D" "C"
[17,] "D" "C" "B"
[18,] "C" "B" "A"
[19,] "B" "A" "K"
[20,] "A" "K" "L"
[21,] "K" "L" "M"
[22,] "L" "M" "N"
[23,] "M" "N" "O"
[24,] "N" "O" "P"
[25,] "O" "P" "Q"
[26,] "P" "Q" "R"
[27,] "Q" "R" "S"
[28,] "R" "S" "T"
[29,] "S" "T" "!"
[30,] "T" "!" "?"
[31,] "!" "?" ","
[32,] "?" "," "."
[33,] "," "." "Z"
[34,] "." "Z" "Y"
[35,] "Z" "Y" "X"
[36,] "Y" "X" "W"
[37,] "X" "W" "V"
[38,] "W" "V" "U"
```
[Answer]
### Scala 70 chars:
```
"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU".sliding(3,1).mkString("\n")
```
[Answer]
## Mathematica, 73
I independently arrived at the same method as everyone else:
```
Grid@Partition[Characters@"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU",3,1]
```
[Answer]
# Groovy, 73
```
(0..37).each{println"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU"[it..it+2]}
```
All the clever stuff I tried turned out to be longer than doing it the dumb way.
[Answer]
## Python, 73
```
for i in range(38):print"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU"[i:i+3]
```
[Answer]
# C, 98 104 characters
Since no one else has done so yet, I thought I would try actually generating the string on the fly, using some kind of run-length encoding for ascending and descending runs.
EDIT: After a number of iterations, here's finally a "clever" solution that ties with the shortest "dumb" solution in C at 98 characters:
```
char*s="0º.ÿK»Jº ü=ÿ*ø[×",a[99],*p=a,i;main(j){for(;i-=i<8?j=*s++,*s++:8;puts(p++))p[2]=j+=i%4-1;}
```
The code requires an 8-bit Latin-1 encoding (ISO-8859-1 or Windows-1252), which should work fine on all commonly used platforms, but saving the source with some less popular 8-bit code page, or UTF-8 will not work.
The data string was created by the following piece of emacs lisp:
```
(require 'cl)
(apply 'concat
(let ((last-remainder 0))
(loop for (begin count step twiddle)
in '((?1 9 +1 4) (?0 1 +2 4) (?J 10 -1 4) (?K 10 +1 0)
(?! 1 +1 4) (?? 1 +2 4) (?, 2 +2 4) (?Z 6 -1 8))
append (prog1 (list (char-to-string (- begin step))
(char-to-string
(logand 255 (- last-remainder
(+ (* 8 (- count 1)) (+ step 1)
twiddle)))))
(setq last-remainder (+ (logand twiddle 7) step 1))))))
```
The "twiddle" bit is used to avoid unprintable ASCII control characters in the encoded data string, and to ensure that `i==0` only at the end of the output.
## C, 98 characters
However, even in C you can get a short program by simply printing consecutive triplets from the original string:
```
main(){char s[]="12,34567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU",*p=s+2;for(;*p=p[1];puts(p-3))*++p=0;}
```
[Answer]
## Ruby ~~69~~ ~~65~~ 62
Based on Groovy example
```
38.times{|i|p"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU"[i,2]}
```
[Answer]
## Haskell, 80
```
mapM_(putStrLn.take 3.(`drop`"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU"))[0..37]
```
[Answer]
# [Kotlin](https://kotlinlang.org), ~~140~~ 71 bytes
```
"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU".windowed(3).map{println(it)}
```
[Try it online!](https://tio.run/##y84vycnM@59WmqeQm5iZp6GpUP1fydDI2MTUzNzC0sDL08PdzdXF2cnR28fXzz8gMCg4RNFeRy8qMiI8LFRJrzwzLyW/PDVFw1hTLzexoLqgKDOvJCdPI7NEs/Z/7X8A "Kotlin – Try It Online")
I just realized it's easier to use the string itself instead of generating it using ranges.
[Answer]
**Javascript, 103**
```
for(a='1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU';a.length>2;a=a.substring(1))console.log(a.substr(0,3))
```
[Answer]
# Haskell, 94
```
main=putStr.unlines.take 38$take 3`map`iterate tail"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU"
```
[Answer]
# Perl, 73 characters:
```
print substr('1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU',$_,3),$/for 0..37
```
# Perl, 66 characters:
```
say substr"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU",$_,3for 0..37
```
when called by:
```
perl -E 'say substr"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU",$_,3for 0..37'
```
[Answer]
## D 124 chars
```
import std.stdio;void main(){enum s="1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU";
foreach(i;3..s.length){writeln(s[i-3..i)]);}}
```
[Answer]
### JavaScript, 83 chars
```
for(i=0;i<38;)console.log('1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU'.substr(i++,3))
```
Decided to see if I could beat [stephencarmody's solution](https://codegolf.stackexchange.com/a/4064/3191). This is what I came up with.
[Answer]
## Smalltalk ~~102~~ 99
```
1to:38 do:[:i|x:='1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU'copyFrom:i to:i+2.Transcript cr show:x]
```
I don't know Smalltalk very well so it's a little bit strange to me. It's compiles with `gst` others are not tested.
[Answer]
# Q (66 63 chars)
```
(((!)38),'3)sublist\:"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU"
```
[Answer]
## Prolog, 131
This is probably why you never see Prolog entries.
The newline is required (actually, any whitespace will do but there has to be whitespace).
```
z(S,L):-append(_,X,L),append(S,_,X),length(S,3).
:-forall(z(X,"1234567890JIHFEDCBAKLMNOPQRST!?,.ZYXWVU"),writef("%s\n",[X])),halt.
```
[Answer]
# [///](http://esolangs.org/wiki////), 151 bytes
```
123
234
345
456
567
678
789
890
90J
0JI
JIH
IHG
HGF
GFE
FED
EDC
DCB
CBA
BAK
AKL
KLM
LMN
MNO
NOP
OPQ
PQR
QRS
RST
ST!
T!?
!?,
?,.
,.Z
.ZY
ZYX
YXW
XWV
WVU
```
[Try it online!](http://slashes.tryitonline.net#code=MTIzCjIzNAozNDUKNDU2CjU2Nwo2NzgKNzg5Cjg5MAo5MEoKMEpJCkpJSApJSEcKSEdGCkdGRQpGRUQKRURDCkRDQgpDQkEKQkFLCkFLTApLTE0KTE1OCk1OTwpOT1AKT1BRClBRUgpRUlMKUlNUClNUIQpUIT8KIT8sCj8sLgosLloKLlpZClpZWApZWFcKWFdWCldWVQ)
Can't golf it more? This is, in a sense, <152 bytes.
[Answer]
# [Jelly](//github.com/DennisMitchell/jelly), ~~41~~ 40 [bytes](//github.com/DennisMitchell/jelly/wiki/Code-page)
```
ØAḣ⁵Ṛ
ØDṫ2;0;¢;“KLMNOPQRST!?,.ZYXWVU”ṡ3Y
```
[Try it online!](http://jelly.tryitonline.net#code=w5hB4bij4oG14bmaCsOYROG5qzI7MDvCojvigJxLTE1OT1BRUlNUIT8sLlpZWFdWVeKAneG5oTNZ)
Might (still) be golfable...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 23 bytes
```
ØDṙ1;ØA;“.,?!”s⁵UÐeFṡ3Y
```
[Try it online!](https://tio.run/##AS0A0v9qZWxsef//w5hE4bmZMTvDmEE74oCcLiw/IeKAnXPigbVVw5BlRuG5oTNZ//8 "Jelly – Try It Online")
Generates the keyboard top to bottom left to right, then boustrophedonizes it afterwards.
```
ØD "0123456789"
ṙ1 rotated once to the left
; concatenated with
ØA the uppercase alphabet
;“.,?!” concatenated with ".,?!".
s Chop it into slices of length
⁵ 10,
U (vectorized) reverse
Ðe the slices at even 1-indices,
F smash the slices back together,
ṡ3 take every contiguous sublist of length 3,
Y and join on newlines.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 26 bytes
```
Ị↺,Ạ,".,?!"ụḍ₄{i↔ⁱ⁾}ᶠcs₃ẉ⊥
```
[Try it online!](https://tio.run/##AUIAvf9icmFjaHlsb2cy///hu4rihros4bqgLCIuLD8hIuG7peG4jeKChHtp4oaU4oGx4oG@feG2oGNz4oKD4bqJ4oql//8 "Brachylog – Try It Online")
Essentially a translation of my Jelly answer. A full program which prints the desired output with a trailing newline.
```
Ị "0123456789"
↺ rotated once to the left
, concatenated with
Ạ the alphabet (lowercase)
,".,?!" concatenated with ".,?!",
ụ uppercased,
ḍ₄ sliced into quarters.
c Concatenate
{ }ᶠ every possible result from
i taking a slice with its 0-index
↔ and reversing it
ⁱ⁾ a number of times equal to the index.
ẉ Print with a newline
s₃ a substring of length 3 from the concatenation,
⊥ then try again with a different substring.
```
If a trailing newline is unacceptable:
# [Brachylog](https://github.com/JCumin/Brachylog), 27 bytes
```
Ị↺,Ạ,".,?!"ụḍ₄{i↔ⁱ⁾}ᶠcs₃ᶠ~ṇ
```
[Try it online!](https://tio.run/##AUUAuv9icmFjaHlsb2cy///hu4rihros4bqgLCIuLD8hIuG7peG4jeKChHtp4oaU4oGx4oG@feG2oGNz4oKD4bagfuG5h////1o "Brachylog – Try It Online")
Outputs as a function.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žhÀAu".,?!"«Tô2Å€R}J«ü3»
```
[Try it online.](https://tio.run/##ASwA0/9vc2FiaWX//8W@aMOAQXUiLiw/ISLCq1TDtDLDheKCrFJ9SsKrw7wzwrv//w)
Minor alternative:
```
Au".,?!"«TôžhÀšεNFR]Jü3»
```
[Try it online.](https://tio.run/##ASoA1f9vc2FiaWX//0F1Ii4sPyEiwqtUw7TFvmjDgMWhzrVORlJdSsO8M8K7//8)
**Explanation:**
```
žh # Push builtin "0123456789"
À # Rotate it once to the left: "1234567890"
Au # Push the uppercase alphabet
".,?!"« # Append ".,?!" to it
Tô # Split it into parts of size 10:
# ["ABCDEFGHIJ","KLMNOPQRST","UVWXYZ.,?!"]
2Å€ } # For every 2nd item (0-based index modulo 2 == 0):
R # Reverse it
# ["JIHGFEDCBA","KLMNOPQRST","!?,.ZYXWVU"]
J # Join the list together to a single string again:
# "JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU"
« # Merge it to the digits:
# "1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU"
ü3 # Create overlapping triplets
» # Join the list by newlines
# (after which it is output implicitly with trailing newline)
Au".,?!"«Tô # Same as above: ["ABCDEFGHIJ","KLMNOPQRST","UVWXYZ.,?!"]
žhÀ # Same as above: "1234567890"
š # Prepend it to the list:
# ["1234567890","ABCDEFGHIJ","KLMNOPQRST","UVWXYZ.,?!"]
ε # Map each string to:
NF # Loop the 0-based map-index amount of times:
R # Reverse the string every iteration
] # Close both the loop and map
J # Join the list together to a single string again:
# "1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU"
ü3» # Same as above
# (after which it is output implicitly with trailing newline)
```
[Answer]
## Q, 63
```
{(x;3)sublist"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU"}'[(!)38]
```
[Answer]
# x86-16 machine code, PC DOS, 64 bytes
Binary:
```
00000000: b409 bb1b 01ba 1801 bf0a 24b1 2687 3fcd ..........$.&.?.
00000010: 2187 3f42 43e2 f6c3 3132 3334 3536 3738 !.?BC...12345678
00000020: 3930 4a49 4847 4645 4443 4241 4b4c 4d4e 90JIHGFEDCBAKLMN
00000030: 4f50 5152 5354 213f 2c2e 5a59 5857 5655 OPQRST!?,.ZYXWVU
```
Listing:
```
BB 011B MOV BX, OFFSET KB+3 ; pointer to end of 3 char substring
BA 0118 MOV DX, OFFSET KB ; pointer to beginning of 3 char substring
BF 240A MOV DI, 240AH ; string '$' + 0AH
B1 26 MOV CL, 38 ; number of lines
B4 09 MOV AH, 9 ; DOS API output string function
CLOOP:
87 3F XCHG DI, WORD PTR[BX] ; swap string term and LF char after 3 chars
CD 21 INT 21H ; write substring to console
87 3F XCHG DI, WORD PTR[BX] ; swap back
42 INC DX ; increment string start pointer
43 INC BX ; increment string end pointer
E2 F6 LOOP CLOOP ; loop until 38 lines
C3 RET ; return to DOS
KB:
DB '1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU'
```
It's a bit of a naïve approach, but still fits well below the spec size (and is a nice power of 2). Loops through the string and swaps the relative 4th and 5th character with a LF followed by a string terminator and then outputs it.
Standalone DOS executable COM program. Output:
Head:
[](https://i.stack.imgur.com/XDSJz.png)
Tail:
[](https://i.stack.imgur.com/jnK7c.png)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 27 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
;9õ pUB".,?!" ¬ò10 ËzEÑìã3
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=Ozn1IHBVQiIuLD8hIiCs8jEwIMt6RdHDrOMz)
```
;9õ pUB".,?!" ¬ò10 ËzEÑìã3
9õ :Range [1,9]
p :Push
U : 0
; B : Uppercase alphabet
".,?!" : String literal
¬ :Join
ò10 :Partitions of length 10
Ë :Map each string a 0-based index E
z : Rotate clockwise 90 degrees
EÑ : E*2 times
à :End map
¬ :Join
ã3 :Substrings of length 3
:Implicit output, joined with newlines
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) 6+, 62 bytes
```
0..37|%{'1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU'|% s*g $_ 3}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/30BPz9i8RrVa3dDI2MTUzNzC0sDL08PdzdXF2cnR28fXzz8gMCg4RNFeRy8qMiI8LFS9RlWhWCtdQSVewbj2/38A "PowerShell – Try It Online")
where `s*g` is the shorcut for the `Substring` method.
] |
[Question]
[
Write a program which takes an input (which may or may not be prime), and lists the immediate prime following and preceding it.
**Example input:**
```
1259
```
**Example output:**
```
1249 1277
```
Shortest program wins. Must execute within 10 seconds on a modern desktop PC. Inputs will be limited to 10,000 maximum.
[Answer]
## *Mathematica*, 19
```
#~NextPrime~{-1,1}&
```
[Answer]
## Mathematica: 28 chars
```
(k=NextPrime;{k[#,-1],k@#})&
```
Usage
```
%[1259]
{1249, 1277}
%[121231313159]
{121231313129, 121231313191}
```
[Answer]
## Perl 5.10 (perl -E), 65 chars
Half the credit (at least) should go to @J B.
```
$m=<>;for(-1,1){$n=$m;0while(1x($n+=$_))=~/^1$|(^11+)\1+$/;say$n}
```
[Answer]
## Python - 93
Based on [answer by fR0DDY](https://codegolf.stackexchange.com/questions/632/output-nearby-primes/643#643). I basically merged lines 4 and 5, and shortened line 2 by using a different method.
```
n=input()-1
m=n+2
f=lambda n:any(n%x<1for x in range(2,n))
exec"n-=f(n);m+=f(m);"*m
print n,m
```
[Answer]
## J, 22 characters
```
(_4&p:,4&p:)(".stdin)_
```
[Answer]
**Python ~~116~~ ~~111~~ 109 Characters**
```
n=input()-1
m=n+2
f=lambda n:any(pow(b,n-1,n)>1for b in(3,5,7,13))
while f(n):n-=1
while f(m):m+=1
print n,m
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 6 bytes
```
¯4 4⍭⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//9B6EwWTR71rH3Ut@p/2qG3Co96@R13Nj3rXPOrdcmi98aO2iY/6pgYHOQPJEA/P4P9pCoZGppYA "APL (Dyalog Extended) – Try It Online")
I wish I knew a way to shorten this further.
`¯4` and `4` when passed to `⍭` give the closest primes to the right argument(`⊢`).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Æp,Æn
```
[Try it online!](https://tio.run/##y0rNyan8//9wW4HO4ba8////GxqZWgIA "Jelly – Try It Online")
[Answer]
# Swift ~~190~~ ~~187~~ ~~185~~ 110
Swift is very bad in code-golf, but I tried it anyway :D
It's getting shorter and shorter...(Thanks to [@HermanLauenstein](https://codegolf.stackexchange.com/users/70894/herman-lauenstein) for removing 75 bytes)
```
var a=Int(readLine()!)!;for b in[-1,1]{var n=a,c=0;while c<1{n+=b;c=1;for i in 2..<n{if n%i<1{c=0}}};print(n)}
```
[Answer]
# Haskell: 99
```
s(z:y)=z:s[x|x<-y,mod x z>0];f(x:y:z:w)=(x,z):f(y:z:w);p x=(head.filter(\(c,v)->c<x&&v>x).f.s)[2..]
```
Example
```
Main> p 1259
(1249,1277)
```
[Answer]
**Python, 116 139 chars (double indent is tab-char)**
Uses good ole Sieve of Eratosthenes
**Edits** and (thanks a TON @JPvdMerwe). Should work with primes now.
```
l=n=input();a=range(n*2)
for i in a[2:]:a=[k for k in a if k==i or k%i]
for g in a:
if g>n:print l,g;break
if i!=n:l=g
```
**Original**
```
a=range(9999)
j=lambda a,n:[i for i in a if i==n or i%n]
for i in a[2:]:a=j(a,i)
o=n=input();
for i in a:
if o<n and i>n:
print o,i
o=i
```
[Answer]
### Scala 119:
```
def p(n:Int)=(2 to n-1).exists(n%_==0)
def i(n:Int,v:Int):Int=if(!p(n+v))n+v else i(n+v,v)
Seq(-1,1).map(i(readInt,_))
```
ungolfed:
```
def notPrime (n:Int) =
(2 to n-1).exists (n % _ == 0)
def itPrime (n: Int, vector:Int) : Int =
if (! notPrime (n+vector)) n+vector
else itPrime (n+vector, vector)
def nearbyPrime (value: Int) =
Seq (-1, 1).map (sign => itPrime (value, sign))
```
21.2s to run **all** 9998 ints from 3 to 10.000
[Answer]
## Python (123)
```
import Primes as p
j=i=int(input())
n=p.primes(i*2)
while not i in n[:]:
i+=1
print(i)
while not j in n[:]:
j-=1
print(j)
```
**NOTE: The `Primes` module was written by me but it existed before this question was asked. It was NOT written for this. Nevertheless, this was deemed unfair, so here is the updated version.**
## Python(215)
```
j=i=int(input())
import math as m
s=list(range(i*2))
for n in s[:]:
for l in range(1,int(m.ceil(m.sqrt(n)))):
if(n%l)==0and l!=1and n in s:s.remove(n)
while not i in s:i+=1
print(i)
while not j in s:j-=1
print(j)
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
èëïy▌Ü╚
```
[Run and debug it](https://staxlang.xyz/#p=8a898b79dd9ac8&i=1259)
ASCII equivalent:
```
^:Px:pLJ
```
Built-ins.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 79 bytes
```
f=(n,d)=>d?p(n)?n:f(n+d,d):[f(n-1,-1),f(n+1,1)]
p=(n,i=1)=>++i*i>n||n%i&&p(n,i)
```
[Try it online!](https://tio.run/##VctBCoMwEIXhvfeoZpooTGiJEaIHKQXFaInIJNTSlXdPk2V3j4//bdN3Oua3C5@avF1iXA0jYcH0dgiMYKBuZcRtou6RVo2iRhDZUCA8i5B7ZzA9OHdX19N50sWVZcgOcfZ0@H1pdv9iK0N519Bs3tEoRmMqlDctUCpVQfFfat0qgPgD "JavaScript (Node.js) – Try It Online")
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn), [22 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)
```
ét█ï▀¢│B¬Ÿ6├¼òa¡b←Æ╚ÑÕ
```
[Try it!](https://zippymagician.github.io/Arn?code=azooKHY6Iy5eMik6aSlbdj8tLWsgdj8oaysy&input=MTI1OQ==)
# Explained
Unpacked: `k:((v:#.^2):i)[v?--k v?(k+2`
One of the major weaknesses of Arn (along with operator precedence lmao)
```
: Assign variable
k with name of k
( Begin expression
(
:
v
#. List of primes from 0 to
_ Variable initialized to STDIN; implied
^ exponentiated by
2 Literal two
) End expression
:i Index of
_ implied
)
[ Begin sequence
v
? Indexed by
--k k minus 1
v
?
(
k
+ Plus
2
) implied
] End of sequence; implied
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~98~~ ~~89~~ 87 bytes
-9 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
```
N,i;g(n,d){for(i=N=n+=d;--i>1;)N*=N%i>0;N?printf("%d ",n):g(n,d);}f(n){g(n,-1);g(n,1);}
```
[Try it online!](https://tio.run/##S9ZNT07@/99PJ9M6XSNPJ0WzOi2/SCPT1s82T9s2xVpXN9PO0FrTT8vWTzXTzsDaz76gKDOvJE1DSTVFQUknT9MKosu6Nk0jT7MaxNE11AQbBaRq/wPVKuQmZuZpAM3VMDQytQQJAgA "C (gcc) – Try It Online")
# Full program version, [C (gcc)](https://gcc.gnu.org/), ~~116~~ ~~107~~ 105 bytes
-9 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
```
N,i;g(n,d){for(i=N=n+=d;--i>1;)N*=N%i>0;N?printf("%d ",n):g(n,d);}main(n){scanf("%d",&n);g(n,-1);g(n,1);}
```
[Try it online!](https://tio.run/##S9ZNT07@/99PJ9M6XSNPJ0WzOi2/SCPT1s82T9s2xVpXN9PO0FrTT8vWTzXTzsDaz76gKDOvJE1DSTVFQUknT9MKosu6NjcxM08jT7O6ODkxDyytpKOWpwk2VNcQQgOp2v//DY1MLQE "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
ÅMsÅN»
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cKtv8eFWv0O7//83NDK1BAA "05AB1E – Try It Online")
```
ÅMsÅN» # full program
» # join...
ÅM # nearest prime less than...
# implicit input...
» # with...
ÅN # nearest prime greater than...
s # implicit input...
» # by a newline
# implicit output
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/219219/edit).
Closed 2 years ago.
[Improve this question](/posts/219219/edit)
# Challenge
In this simple challenge, you have to print the public IP address of `google.com`.
# Rules
* You have to output either the IPv6 or IPv4 address, and do it by somehow using internet.
* Output does not strictly need to be the IP address, your answer will be valid if the correct IP address is somewhere in the output, like `Hello - google.com - 142.250.67.78` is a valid output.
* You can use DNS queries and any kind of web APIs or web scraping.
* Standard loopholes apply, except usage of URL shorteners, wanna see how creative you can get ;-)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins!!
[Answer]
# [Zsh](https://www.zsh.org/), 40 bytes
```
echo {0..255}.{0..255}.{0..255}.{0..255}
```
[Try it online!](https://tio.run/##qyrO@P8/NTkjX6HaQE/PyNS0Vg834/9/AA "Zsh – Try It Online")
Since the output only needs to *contain* the IP address, we can just enumerate all of them! This probably isn't the shortest option, but it's funny!
[Answer]
## Windows Batch, 15 bytes
```
ping google.com
```
### Example run
```
C:\>ping google.com
Pinging google.com [8.7.198.46] with 32 bytes of data:
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Ping statistics for 8.7.198.46:
Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
```
[Answer]
# Bash, 14 bytes
Requires `dnsutils`.
```
dig google.com
```
[Answer]
# Java 8, 47 bytes
```
v->java.net.InetAddress.getByName("google.com")
```
[(Don't) try it online](https://tio.run/##jY@xCsJADIZ3nyI4XQfvBURBQdDBOogu4nBeY716TUovrYr47PWk4iwkgX/4fr4UpjWjIrt21psQYG0cPQcAjgTrs7EI6ScCbE4FWgGr9uwyaBOQS823AEXkNaHoHV2Jb7TkIIu7xUoc0ziir7hxghhxFlIgmHTtaPrjVvHMsqzGEHSOMn@kpkQ1zJlzj9pyOUw6gHHfUjUnH1u@Ze1HpYzGaiu1o/xwBPOfWP/T9hEES82N6Cry4kmRtooa75Okd391bw) (local run outputs `google.com/142.250.179.206`).
**Explanation:**
```
v-> // Method with empty unused parameter & InetAddress return
java.net.InetAddress // Create and return an InetAddress-instance
.getByName("google.com") // for hostname "google.com"
```
When this `InetAddress`-instance is printed, it will use [its `InetAddress.html#toString()` method](https://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html#toString()) by default, which prints in the format `hostname / literal IP address`.
[Answer]
# Powershell 5, 26 bytes
```
resolve-dnsname google.com
```
luckily, powershell has a CMDlet for this!
Somehow this does not work on TIO, but on powershell 5
```
Name Type TTL Section IPAddress
---- ---- --- ------- ---------
google.com AAAA 149 Answer 2404:6800:4007:805::200e
google.com A 273 Answer 142.250.67.78
```
[](https://i.stack.imgur.com/9IOSw.png)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 41 bytes
```
require'resolv';Resolv.getaddress'goo.gl'
```
[Try it online!](https://tio.run/##KypNqvz/vyi1sDSzKFW9KLU4P6dM3ToITOulp5YkpqQABYvV0/Pz9dJz1P//BwA "Ruby – Try It Online")
Or as an alternative:
`dig goo.gl`
`wget goo.gl`
[Answer]
# [C (gcc)](https://gcc.gnu.org/) (`-m32`), 67 bytes
To avoid having to include any header files, I flatten the structure and manually dereference the first entry of the `h_addr_list` member of the `hostent` structure. Replace `google.com` with `localhost` to test in tio.run.
```
f(){puts(inet_ntoa(**(((int***)gethostbyname("google.com"))[4])));}
```
[Try it online!](https://tio.run/##RYxBCsMgEAC/suTkCkmg7S1PKaVaa4ygboibhhLy9Vp76nFgZkzrjCl9D4udgzYWlCNywXaGooLN8wQqkNFhoswKmIBtZvAJ2FO3rKmMAvd55Sx8snxPTFpIKURFllKis/xLH@@koxXN/94gXi83RByOUl2I2ifxIv9E2KFOBzjKx4xBu1zaeD6VdvsC "C (gcc) – Try It Online")
[Answer]
# Bash + dnsutils, 15 bytes
```
host google.com
```
[Answer]
# PHP, 20 bytes
```
<?=`ping google.co`;
```
For some reason `google.co` returns exactly the same IP as `google.com`.
[Answer]
# MATLAB/Octave, 26 bytes
```
resolvehost goo.gl address
```
This solution uses [`resolvehost`](https://www.mathworks.com/help/instrument/resolvehost.html) which is part of the Instrumentation Toolbox ([`instrument-control`](https://wiki.octave.org/Instrument_control_package) in Octave). We provide a second input (`'address'`) to specify that we want the IP address.
Also we avoid using parentheses because both inputs should be interpreted as strings already so we can save 5 bytes by not using parentheses, quotes, and commas:
Long form: `resolvehost('goo.gl','address')`
Notes:
* On Octave at least, we cannot shorten `address` (in many MATLAB/Octave commands you can shorten string literals). I don't have MATLAB available to me with this toolbox so it's possible this could be shortened in MATLAB.
* We could alternately use the second output without a second input: `[,a]=resolvehost('goo.gl')` which would be the same length as this answer but we have to use parentheses and quotes. Also the empty first output is only valid in Octave. In MATLAB we would have to do `[~,a]=resolvehost('goo.gl')` which is 1 byte longer.
[Answer]
## Golang, 77 bytes
```
package main;import(."net";."fmt");func main(){Print(LookupIP("google.com"))}
```
[Answer]
# Mathematica, 23 Bytes
```
HostLookup["google.co"]
```
Like with most things in life, Mathematica/Wolfram Language has a builtin for it. Requires version 11 or above.
[Answer]
# Bash, ~~164 bytes~~ 127 bytes
```
base64 -d<<<3dYBIAABAAAAAAABBmdvb2dsZQNjb20AAAEAAQAAKRAAAAAAAAAMAAoACCjxxt05OkuU|nc 1.1.1.1 -u 53|hexdump -e '4/1 "%0.2d.""\n"'
```
Why use `dig` when you can use netcat.
Example Run:
```
221.214.129.128.
00.01.00.01.
00.00.00.01.
06.103.111.111.
103.108.101.03.
99.111.109.00.
00.01.00.01.
192.12.00.01.
00.01.00.00.
01.29.00.04.
142.250.182.238. //Google's IP
00.00.41.04.
208.00.00.00.
```
EDIT: Saved a lot of bytes thanks to @DigitalTrauma
[Answer]
# Python 3, ~~58~~ 54 bytes
-4 bytes by Arnauld, who got better reading skills than me...
```
from socket import*
print(gethostbyname('google.com'))
```
[Answer]
# [Standard ML](https://smlnj.org/sml97.html), 35 bytes
```
OS.Process.system"ping google.com";
```
I never used it before, but it turns out there is a [`OS` structure](https://smlfamily.github.io/Basis/os.html#OS:SIG:SPEC) in the basis library which lets you execute arbitrary commands in the system's default shell.
[Answer]
# Windows Batch, 19 bytes
```
nslookup google.com
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 57 bytes
A full program that prints the first A record (IPv4).
```
require('dns').lookup('google.com',(_,s)=>console.log(s))
```
[(Don't) Try it online!](https://tio.run/##DcjRDYAgDAXAcdomyAa6iiFACIo8pOL66H3e4V6nvuf2LBUhztnjPXKPTKEqiS3AORpTAlKJ1uMiw7tRWTePqvivILGKzPkB "JavaScript (Node.js) – Try It Online")
[Answer]
# [PHP](https://php.net/), 31 bytes
```
<?=gethostbyname('google.com');
```
[(Cannot) Try it online!](https://tio.run/##K8go@P/fxt42PbUkI7@4JKkyLzE3VUM9PT8/PSdVLzk/V13T@v9/AA "PHP – Try It Online")
Works on my localhost, still trying to golf it
[Answer]
# [Perl 5](https://www.perl.org/), 53 bytes
```
say join".",map ord,gethostbyname("google.com")=~/./g
```
[Try it offline](https://tio.run/##BcExDoAgDADArxAmTbDgwOgTfARqgxigBFhYfLr1rmCNlrm5IR4KWYJUyRVB9VIe@02tHyO7hJP0RD4inJTkvL0atGf@qPRAufGyW1gNmB8 "Perl 5 – Try It Online") with `perl -E'say join".",map ord,gethostbyname("google.com")=~/./g'`
[Answer]
# [Python 3](https://docs.python.org/3/), 46—47 bytes
```
from socket import*
getaddrinfo('google.co',0)
```
[TIO](https://tio.run/#) doesn't let me run it, but the Jupyter and normal compiler returns this:
```
[(<AddressFamily.AF_INET: 2>, 0, 0, '', ('173.194.220.100', 0)),
(<AddressFamily.AF_INET: 2>, 0, 0, '', ('173.194.220.113', 0)),
(<AddressFamily.AF_INET: 2>, 0, 0, '', ('173.194.220.101', 0)),
(<AddressFamily.AF_INET: 2>, 0, 0, '', ('173.194.220.102', 0)),
(<AddressFamily.AF_INET: 2>, 0, 0, '', ('173.194.220.139', 0)),
(<AddressFamily.AF_INET: 2>, 0, 0, '', ('173.194.220.138', 0))]
```
While the end result leads to google.com, the .com version of this code would return entirely different ip-ranges. Which would add +1 to the byte amount if you consider this not fair.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 44 bytes
A function that prints the IP among other things
```
_=>System.Net.Dns.GetHostEntry("google.com")
```
[Can't Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXoqMQXFlckpqr55daoucZ4JFfXOKaV1JUaaeQBlShYPs/3tYOSYVLXrGee2oJXJmGUnp@fnpOql5yfq6S5n9rLq6AIqCpGiDNGgaamtb/AQ "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# Shell / cURL: 12 bytes
```
curl g.co -v # 12
curl goo.gl -v # 14
curl google.co -v # 17
curl google.com -v # 18
```
IPs
```
$ nslookup google.com
Non-authoritative answer:
Name: google.com
Address: 172.217.23.238
Name: google.com
Address: 2a00:1450:4014:80d::200e
$ nslookup g.co
Non-authoritative answer:
Name: g.co
Address: 172.217.23.238
Name: g.co
Address: 2a00:1450:4014:80d::200e
```
[Answer]
# [Visual Basic .NET (.NET Core)](https://www.microsoft.com/net/core/platform), ~~60~~ 53 bytes
```
Console.WriteLine(Net.Dns.GetHostEntry("google.com"))
```
[Try it online!](https://tio.run/##HcyxCsIwEIDhPU8ROiWDeQepRQUVIYNzEo8aSO4kdxX69FE7/cvP94m7RA36ub6pCWu/skBV9yWWnPRYArPeK/8KDZ7aL1FfQ0Zj@0jIVMA9Wha4ZARzA3EHZHcEORHLhNJWM8xE829LVAdr@4Qbov7d7P4F "Visual Basic .NET (.NET Core) – Try It Online")
-7 bytes thanks to @JoelCoehoorn
] |
[Question]
[
Write the shortest program or function which generates these 1000 numbers or a sequence (0- or 1-indexed) which begins with them.
```
[0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0,
1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1,
0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0,
1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1,
0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0,
1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1,
0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0,
1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1,
0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0,
1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1,
0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0,
1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1,
0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0,
1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1,
0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1,
1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0,
0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1,
1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0,
0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1,
1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0,
0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1,
1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0,
0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1,
1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0,
0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1,
1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0,
0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1,
1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0,
0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1,
1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0,
0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1,
1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0,
0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1,
1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0,
0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1,
1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0,
0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1,
1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0,
0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1,
1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0,
0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1,
1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
*Saved 1 byte thanks to @Dennis*
```
ȷḶ×⁽q£:ȷ5Ḃ
```
[Try it online!](https://tio.run/##AR0A4v9qZWxsef//yLfhuLbDl@KBvXHCozrItzXhuIL//w "Jelly – Try It Online")
### How?
I first noticed that the pattern alternates between runs of length 4 and length 3, skipping the length-4 step every few runs. This led me to look for a number which could be divided into the current index, then taken mod 2 and floored—i.e. retrieving the least significant bit—to give the bit at that index in the series. After much trial and error, I found that `3.41845` does exactly that, but multiplying by its approximate reciprocal (`.29253`) is a byte shorter.
```
ȷḶ×⁽q£:ȷ5Ḃ Main link. Arguments: none
ȷ Yield 1e3, i.e. 1000.
Ḷ Lowered range; yield [0, 1, 2, ..., 999].
×⁽q£ Multiply each item by 29253.
:ȷ5 Floor-divide each item by 1e5, i.e. 100000.
Ḃ Take each item mod 2.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~34 29 26~~ 22 bytes
```
$.+=184while p$./629%2
```
[Try it online!](https://tio.run/##KypNqvz/X0VP29bQwqQ8IzMnVaFARU/fzMhS1ej/fwA "Ruby – Try It Online")
Quick explanation: this works because of the magic number 629. I noticed that the sequence starts repeating after the 629th element, and I tried to "improve" some existing answer, using only integer math. I found that the other "magic number" (0.29253) is actually 184/629.
[Answer]
# [Dyalog APL](https://www.dyalog.com/), ~~99~~ ~~83~~ 82 bytes
```
a←{⍵/0 1}¨(↓3 2⍴4 3 3)
{a⊢←↓⍉↑a{⍺∘{⍵/⊂⍺}¨⍵}¨↓3 3⍴⍵}¨(9/5)∘⊤¨1386531 496098
1000⍴∊a
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ooz3tf@KjtgnVj3q36hsoGNYeWqHxqG2ysYLRo94tJgrGCsaaXNWJj7oWAdUAxR/1dj5qm5gIVL3rUccMsKZHXU1AHlAfkAMiQZqNgZohXA1LfVNNoNJHXUsOrTA0tjAzNTZUMLE0M7C04DI0MDAAKezoSgQ55H8aAA "APL (Dyalog Classic) – Try It Online")
Definitely not the intended solution as this still has a lot of hardcoded data, but it's a start.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 31 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Given the pattern there is probably an even shorter way...
```
ĖŒṙḂ
“ṁ⁽⁺ḄæI’BḤ+3żḂ$ẎÇo2Ç+3Çḣȷ¬
```
**[Try it online!](https://tio.run/##AUkAtv9qZWxsef//xJbFkuG5meG4ggrigJzhuYHigb3igbrhuITDpknigJlC4bikKzPFvOG4giThuo7Dh28yw4crM8OH4bijyLfCrP// "Jelly – Try It Online")**
### How?
Exploits the repeating run length structure that is apparent to a depth of three.
```
ĖŒṙḂ - Link 1, make runs of bits: list of lengths e.g. [5,3,5,3,3]
Ė - enumerate [[1,5],[2,3],[3,5],[4,3],[5,3]]
Œṙ - run-length decode [1,1,1,1,1,2,2,2,3,3,3,3,3,4,4,4,5,5,5]
Ḃ - bit (modulo by 2) [1,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,1,1,1]
“ṁ⁽⁺ḄæI’BḤ+3żḂ$ẎÇo2Ç+3Çḣȷ¬ - Main link: no arguments
“ṁ⁽⁺ḄæI’ - literal 234931870193324
B - to binary = [1,1,0,1,0,1,0,1,1,0,1,0,1,0,1,1,0,1,0,1,0,1,1,0,1,0,1,0,1,0,1,1,0,1,0,1,0,1,1,0,1,0,1,0,1,1,0,0]
Ḥ - double = [2,2,0,2,0,2,0,2,2,0,2,0,2,0,2,2,0,2,0,2,0,2,2,0,2,0,2,0,2,0,2,2,0,2,0,2,0,2,2,0,2,0,2,0,2,2,0,0]
+3 - add three = [5,5,3,5,3,5,3,5,5,3,5,3,5,3,5,5,3,5,3,5,3,5,5,3,5,3,5,3,5,3,5,5,3,5,3,5,3,5,5,3,5,3,5,3,5,5,3,3]
$ - last two links as a monad:
Ḃ - bit = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
ż - zip = [[5,1],[5,1],[3,1],[5,1],[3,1],[5,1],[3,1],[5,1],[5,1],[3,1],[5,1],[3,1],[5,1],[3,1],[5,1],[5,1],[3,1],[5,1],[3,1],[5,1],[3,1],[5,1],[5,1],[3,1],[5,1],[3,1],[5,1],[3,1],[5,1],[3,1],[5,1],[5,1],[3,1],[5,1],[3,1],[5,1],[3,1],[5,1],[5,1],[3,1],[5,1],[3,1],[5,1],[3,1],[5,1],[5,1],[3,1],[3,1]]
Ẏ - tighten = [5,1,5,1,3,1,5,1,3,1,5,1,3,1,5,1,5,1,3,1,5,1,3,1,5,1,3,1,5,1,5,1,3,1,5,1,3,1,5,1,3,1,5,1,5,1,3,1,5,1,3,1,5,1,3,1,5,1,3,1,5,1,5,1,3,1,5,1,3,1,5,1,3,1,5,1,5,1,3,1,5,1,3,1,5,1,3,1,5,1,5,1,3,1,3,1]
Ç - call the last Link (1) as a monad
- = [1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,0]
o2 - OR 2 = [1,1,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,1,1,2,1,1,1,2,1,1,1,2]
Ç - Link 1... = [1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,0]
+3 - add three = [4,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,4,3,3,4,3,4,3,3,4,3,4,3,3]
Ç - Link 1... = [1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0]
ȷ - literal 1000
ḣ - head = [1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1]
¬ - NOT = [0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,0]
```
[Answer]
# Java 8, ~~75~~ ~~64~~ 62 bytes
```
v->{for(int i=0;i<1e3;)System.out.print((int)(i++*.29253)%2);}
```
Prints the entire sequence without delimiter to save bytes, because they will only be `0` and `1` anyway.
Ports of [*@ETHproductions*' Jelly answer](https://codegolf.stackexchange.com/a/162777/52210), because I doubt I find anything shorter..
[Try it online.](https://tio.run/##LY5NDoIwEIX3nmI2Jq2GRiEuTMUbyIbEjXFRSzHFUggtJIZw9joIyUwm8/O@eZUYRFQVnyCNcA5uQttxA6CtV10ppIJsbgGGRhcgyX0uA@U4mzAxnBdeS8jAQgphiK5j2XQE9aDTA9eXo0o4zb/Oq5o1vWdthzsyH1Ci9/sdi8/xKaHbmPIp8IXZ9i@DzBX9f12jMZJ7FL8fT0EXU5ZJYntjVj9T@AE)
**Explanation:**
```
v->{ // Method with empty unused parameter and no return-type
for(int i=0;i<1e3;) // Loop `i` in range [0,1000)
System.out.print( // Print:
(int)(i++*.29253) // `i` multiplied with 0.29253,
// and then truncated of their decimal values by casting to int
%2);} // Modulo-2 to result in either 0 or 1
```
---
Old answer returning the resulting array (**75 bytes**):
```
v->{int i=1000,r[]=new int[i];for(;i-->0;)r[i]=(int)(i*.29253)%2;return r;}
```
[Try it online.](https://tio.run/##7VbPS8MwFL77VzwKQqJr6CY7aOjGDh6dh4Igo4eYZZqapTNJq2P0b6/p2sFAhgreLPkB773k@97hg/dlrGRhtnytuWLWwh2TencGILUTZsW4gHkT7hOLFDh6yOUSSkx9svLHb@uYkxzmoCGGugwnO/8WZDyMomhgFmmsxfv@u0zpKjeIyjCcRBQbn4iRL2AkL8joejS@wucjaoQrjAZDq5q2BJviSXmCjqdsGlj7NlHijNTPi5Th4xbFx0ZwJ5a@mQNxuosG7Rru1/fR8JdRj/g3@P8TsddSr6Venb06ey39ELGiRwOfcVcw1Yx7wpEulMJtNdlaJ9YkLxzZeKPglEbBzAhwL2LbXGDZWkwhuESZ90CkcFKRmTFsa4l484gWHazEoOPA0@DxNglugvl9gE@znK58IXJ5a2JQR9D5qqr@BA)
**Explanation:**
```
v->{ // Method with empty unused parameter and integer-array return-type
int i=1000, // Index `i`, starting at 1000
r[]=new int[i]; // Result-array of size 1000
for(;i-->0;) // Loop `i` in range (1000,0]
r[i]= // Set the item in the array at index `i` to:
(int)(i*.29253) // `i` multiplied with 0.29253,
// and then truncated of their decimal values by casting to int
%2; // Modulo-2 to result in either 0 or 1
return r;} // Return the resulting integer-array
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 96 bytes
I searched for a cellular automaton that looks at the 4 neighbors to the left and produces the walking left pattern seen in the data when you Partition the data into length 7 and keep every third row.
This cellular automaton will run for 29 generations each of which is triplicated, matching the sequence perfectly for characters 1 to 629. However the sequence starts repeating at the 630th character rather than continuing the observed pattern, so extra code is needed to handle the repeat of the truncated pattern. I generate the main pattern twice to get to 1258 characters.
```
Most@Flatten[{#,#,#}&/@CellularAutomaton[{271,2,-{{4},{3},{2},{1}}},{0,0,0,0,1,1,1},29]]~Table~2
```
Without that glitch we could do it in a shorter 74 bytes. The 47 is the number of generations needed to get to 1000 characters (this actually goes to 1008=48\*7\*3)
```
{#,#,#}&/@CellularAutomaton[{271,2,-{{4},{3},{2},{1}}},{0,0,0,0,1,1,1},47]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73ze/uMTBLSexpCQ1L7paWQcIa9X0HZxTc3JKcxKLHEtL8oGK84FyRuaGOkY6utXVJrU61cZAbATEhrW1QNJABwINQbBWx8gyNrYuJDEpJ7XO6H9AUWZeiUPafwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 42 bytes
```
x=184
while x/629%2:print(x//629%2);x+=184
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8LW0MKEqzwjMydVoULfzMhS1ciqoCgzr0SjQh/C1bSu0AYp@v8fAA "Python 3 – Try It Online")
Port of [G.B.](https://codegolf.stackexchange.com/a/162814/109916)'s answer.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~41~~ 33 bytes, port
Thank Rick Hitchcock for 4+ bytes
```
f=i=>i>999?'':(i*.29253&1)+f(-~i)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/e9m@z/NNtPWLtPO0tLSXl3dSiNTS8/I0sjUWM1QUztNQ7cuU/O/dXJ@XnF@TqpeTn66hpuGpuZ/AA "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 121 bytes, original
```
_=>'8888y888'[s='replace'](/8/g,'aaa3yyy')[s](/y/g,'aaa3aa3')[s](/a/g,34)[s](/./g,t=>(_=+!+_+[]).repeat(t)).slice(3,1003)
```
[Try it online!](https://tio.run/##NYzBCsMgEES/pad1MTUp9hAo5pifkCCLlZAiMUQp@PV2oe0wA493mBe9KftzO8p1T8/QZtOcmWDkVB7YbOAMRyQfYBH92K8dEJGutQLazKr@FfeniJW@f1kxFzMJZ@RFOmkXVPwXqIiCqHLcfBC6uw2Dxvbwac8pBhXTKmaB2D4 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~13~~ 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
í?♫~╘äqx-G▄
```
[Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=a13f0e7ed48471782d47dc&i=&a=1)
Port to Stax of @ETHproductions's [Jelly answer](https://codegolf.stackexchange.com/a/162777/73884) (before its modification) with some modifications by @recursive to save two bytes.
[Answer]
# [Z80Golf](https://github.com/lynn/z80golf), 27 bytes
```
00000000: 018d 2b7b 1f1f e601 f630 ff09 3001 1313 ..+{.....0..0...
00000010: 7bfe 9220 ee7a fe04 20e9 76 {.. .z.. .v
```
[Try it online!](https://tio.run/##VYwxCsMwEAT7vGL7wLEnGcnybyJy58bgzoX8eFlO0mRYFqaZNnPdN@@dPxZQ5zdCzRXq6rBEhadIuLMgcqhGjYDI85QbfiaPb0FHI1c3lBAIs/yCGycEWkFO@GMEIO2@o/cL "Z80Golf – Try It Online")
Translated from this C code:
```
for (n = 0; n >> 16 != 1170; n += 11149 + 65536)
putchar('0'|n>>18&1);
```
Disassembly:
```
ld bc, 11149
loop:
ld a, e
rra
rra
and 1
or '0'
rst $38 ; putchar
add hl, bc ; Add 11149 to n = DEHL.
jr nc, just_one ; Add 65536 to n, possibly with carry from low 16 bits.
inc de
just_one:
inc de
ld a, e
cp 1170 & 255
jr nz, loop
ld a, d
cp 1170 >> 8
jr nz, loop
halt
```
This is essentially a fixed-point arithmetic approach: (11149 + 65536) / 218 ≈ 0.29253, the constant used by other answers.
[Answer]
# [J](http://jsoftware.com/), 17 bytes
```
2|<.0.29253*i.1e3
```
A J port of ETHproduction's Jelly answer.
[Try it online!](https://tio.run/##y/r/36jGRs9Az8jSyNRYK1PPMNX4f2pyRr5CvKlBbAymHAA "J – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 bytes
```
A³Ç*.29#ý f u
A³ // Given 10³,
Ç // map over it as a range, returning the given number
*.29253 // times the constant,
f u // floored and mod-2.
```
Japt version of [ETHproduction's Jelly answer](https://codegolf.stackexchange.com/a/162777/16484).
Bug fixed thanks to [Oliver](https://codegolf.stackexchange.com/users/61613/oliver).
[Try it here.](https://ethproductions.github.io/japt/?v=1.4.5&code=QbPHKi4yOSP9IGYgdQ==&input=)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
Eφ§01×·²⁹²⁵³ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDD0MDAQEfBscQzLyW1QkPJwFBJRyEkMze1WEPPyNLI1FhHIVMTCKz///@vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
φ Predefined variable 1000
E Map over implicit range
ι Current value
·²⁹²⁵³ Literal constant `0.29253`
× Multiply
01 Literal string `01`
§ Cyclically index
Implicitly print each result on its own line
```
Thanks to @ASCII-only for allowing indexing to accept floats which are cast to integer (and then automatically reduced modulo 2 in this case).
[Answer]
# C, ~~55~~ ~~53~~ 52 bytes
```
f(i,j){for(i=0;j=.29253*i,i++-1e3;)putchar(j%2+48);}
```
Port of Kevin Cruijssen's Java [answer](https://codegolf.stackexchange.com/a/162805/79343). Try it online [here](https://tio.run/##S9ZNT07@/z9NI1MnS7M6Lb9II9PWwDrLVs/I0sjUWCtTJ1NbW9cw1dhas6C0JDkjsUgjS9VI28RC07r2f25iZp4GUJMGiAMA).
Thanks to [vazt](https://codegolf.stackexchange.com/users/78276/vazt) for golfing 2 bytes and to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech) for golfing one more.
Ungolfed version:
```
f(i, j) { // function taking two dummy arguments (implicitly int) and implicitly returning an unused int
for(i = 0; j = .29253*i, i++ - 1e3; ) // loop 1000 times, multiply i with 0.29253, truncating to an integer
putchar(j % 2 + 48); // modulo the truncated integer by 2, yielding 0 or 1, then convert to ASCII (48 is ASCII code for '0') and print
}
```
[Answer]
# [///](https://esolangs.org/wiki////), 63 bytes
```
/b/000111//A/b1b//B/b0b//C/0BA1//X/CACACACA0bCBCBCB/0bXXCBXCAC0
```
[Try it online!](https://tio.run/##JcjBCcBQCATRknYtQW3C618I5JCb/WMM4R0Gpp/T99UzEEiaGeCQCQiImwTD9xbSf1TGB1RVRu3jzAs "/// – Try It Online")
[Answer]
# Deadfish~, 1301 bytes
```
{iiiii}ddccccicccdccccicccdccccicccdccciccccdccciccccdccciccccdcccicccdccccicccdccccicccdccciccccdccciccccdccciccccdcccicccdccccicccdccccicccdccciccccdccciccccdccciccccdcccicccdccccicccdccccicccdccciccccdccciccccdccciccccdcccicccdccccicccdccccicccdccccicccdccciccccdccciccccdcccicccdccccicccdccccicccdccccicccdccciccccdccciccccdcccicccdccccicccdccccicccdccccicccdccciccccdccciccccdcccicccdccccicccdccccicccdccccicccdccciccccdccciccccdccciccccdcccicccdccccicccdccccicccdccciccccdccciccccdccciccccdcccicccdccccicccdccccicccdccciccccdccciccccdccciccccdcccicccdccccicccdccccicccdccciccccdccciccccdccciccccdcccicccdccccicccdccccicccdccccicccdccciccccdccciccccdcccicccdccccicccdccccicccdccccicccdccciccccdccciccccdcccicccdccccicccdccccicccdccccicccdccciccccdccciccccdcccicccdccccicccdccccicccdccccicccdccciccccdccciccccdcccicccdccccicccdccccicccdccccicccdccciccccdccciccccdccciccccdcccicccdccccicccdccccicccdccciccccdccciccccdccciccccdcccicccdccccicccdccccicccdccciccccdccciccccdccciccccdcccicccdccccicccdccccicccdccciccccdccciccccdccciccccdcccicccdccccicccdccccicccdccccicccdccciccccdccciccccdcccicccdccccicccdccccicccdccccicccdccciccccdccciccccdcccicccdccccicccdccccicccdccccicccdccciccccdccciccccdcccicccdccccicccdccccicccdccccicccdccciccccdccciccccdccciccccdcccicccdccccicccdccccicccdccciccccdccciccccdc
```
] |
[Question]
[
Given two integers, which may be negative, zero, or positive, \$a\$ and \$b\$ (taken in any reasonable format, **including inputting a plain complex number**), convert it to \$a + bi\$ where \$i\$ is the imaginary number (square root of negative one). Then, raise it to the power of a third (positive integer) input variable, \$c\$ as to \$(a + bi)^c\$. You should then end up with something like \$d + ei\$. You must then output, or return, \$d\$ and \$e\$ in any reasonable format (**including outputting a plain complex number**).
Input and output may be taken or outputted in any order.
Examples:
```
5, 2, 2 -> 21, 20
1, 4, 2 -> -15, 8
-5, 0, 1 -> -5, 0
```
[Answer]
# Mathematica, 17 bytes
```
ReIm[(#+#2I)^#3]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277PyjVMzdaQ1lb2chTM07ZOFbtf0BRZl6JgkN6tKmOghEQxXLBRQx1FExQRXSBigx0FAxj/wMA "Wolfram Language (Mathematica) – Try It Online")
-8 bytes from alephalpha
but........
rules have changed......
so
# Mathematica, 5 bytes
```
Power
```
[Answer]
# [Python 3](https://docs.python.org/3/), 3 bytes
```
pow
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzvyC//H9afpFCok6STrJCZp5CtKmOghEQxepEG@oomEBYukBBAx0Fw1grLgWFgqLMvBKNNI1E7SQtwyydZE3N/wA "Python 3 – Try It Online")
Input and output as complex numbers.
---
# [Python 3](https://docs.python.org/3/), 47 bytes
```
def f(a,b,c):n=(a+b*1j)**c;return n.real,n.imag
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI1EnSSdZ0yrPViNRO0nLMEtTSyvZuii1pLQoTyFPryg1MUcnTy8zNzH9f1p@kQJYtUJmnkK0qY6CERDF6kQb6iiYQFi6QEEDHQXDWCsuBYWCosy8Eg2YBZr/AQ "Python 3 – Try It Online")
Input and output as integers
---
# [Python 2](https://docs.python.org/2/), ~~62~~ 60 bytes
*-2 bytes thanks to @Leonhard*
```
a,b,c=input();d=1;e=0
exec'd,e=a*d-b*e,a*e+b*d;'*c
print d,e
```
[Try it online!](https://tio.run/##K6gsycjPM/qfnJ@SaqukpPQ/USdJJ9k2M6@gtERD0zrF1tA61daAK7UiNVk9RSfVNlErRTdJK1UnUStVO0krxVpdK5mroCgzr0QBKPsfaABYqQLIOC3j/9GmOgpGQBTLFW2oo2ACYekCBQ10FAxjAQ "Python 2 – Try It Online")
does not use complex number type
[Answer]
# Javascript (ES6), ~~51~~ 50 bytes
```
a=>b=>g=c=>c?([x,y]=g(c-1),[x*a-b*y,a*y+b*x]):"10"
```
* Takes input in currying form: `f(a)(b)(c)`
* Returns the result as an array: `[d, e]`
**Explanation**
```
a=>b=>g=c=> // Input in currying syntax
c?( // If `c` != 0:
[x,y]=g(c-1), // Set [x, y] to the result of f(a)(b)(c-1)
[x*a-b*y,a*y+b*x] // Return (a + bi) * (x + yi)
): // Else: (when c = 0)
"10" // Return [1, 0] (to end the recursion)
```
```
f=a=>b=>g=c=>c?([x,y]=g(c-1),[x*a-b*y,a*y+b*x]):"10"
```
```
<div oninput="o.innerText=f(a.value)(b.value)(c.value)"><input id=a type=number value=0><input id=b type=number value=0><input id=c type=number value=1 min=1><pre id=o>
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 36 bytes
```
f(a,b,c)=divrem((a+b*x)^c%(x^2+1),x)
```
[Try it online!](https://tio.run/##K0gsytRNL/j/P00jUSdJJ1nTNiWzrCg1V0MjUTtJq0IzLllVoyLOSNtQU6dC839BUWZeiUaahqmOghEQaWpywUQMdRRMUEV0gYoMdBQMNTX/AwA "Pari/GP – Try It Online")
---
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 36 bytes
```
f(a,b,c)=[real(d=(a+b*I)^c),imag(d)]
```
[Try it online!](https://tio.run/##K0gsytRNL/j/P00jUSdJJ1nTNrooNTFHI8VWI1E7SctTMy5ZUyczNzFdI0Uz9n9BUWZeiUaahqmOghEQaWpywUQMdRRMUEV0gYoMdBQMNTX/AwA "Pari/GP – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 byte
```
*
```
[Try it online!](https://tio.run/##y0rNyan8/1/r////GqbaRlma/40A "Jelly – Try It Online")
Thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) for alerting me of rule updates (-6 as a result).
Thanks to [someone](https://codegolf.stackexchange.com/users/36445/someone) for alerting me of rule updates (-2 as a result).
First argument: `(a+bj)`
Second argument: `c`
Returns: `(d+ej)`
[Answer]
# [Actually](https://github.com/Mego/Seriously), 1 byte
```
ⁿ
```
[Try it online!](https://tio.run/##S0wuKU3Myan8//9R4/7//424NIy0TbM0AQ "Actually – Try It Online")
Note that the rules have changed and complex numbers are valid I/O types (unfortunately this turns the post into a "perform this exponentiation" challenge). Original answer below.
# [Actually](https://github.com/Mego/Seriously), 3 bytes
```
Çⁿ╫
```
[Try it online!](https://tio.run/##S0wuKU3Myan8//9w@6PG/Y@mrv7/34jLhMsQAA "Actually – Try It Online")
Returns the values separated by a newline. Takes the inputs in reverse order and returns the results in reverse order (See the tio link).
```
Çⁿ╫ - Full program. Reversed inputs.
Ç - Return a+bi.
ⁿ - Exponentiation.
╫ - Pushes the real and imaginary parts of a.
```
[Answer]
# [R](https://www.r-project.org/), 3 bytes
This is becoming boring. If input and output is allowed as a complex number, there is a builtin for a power function.
```
`^`
```
For example:
```
> (5+2i)^2
[1] 21+20i
> (1+4i)^2
[1] -15+8i
> (-5+0i)^1
[1] -5+0i
```
or
```
> `^`(5+2i,2)
[1] 21+20i
> `^`(1+4i,2)
[1] -15+8i
> `^`(-5+0i,1)
[1] -5+0i
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20~~ ~~19~~ ~~17~~ 16 bytes
```
‚UTSsFXâP`(‚RŠ‚+
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UcOs0JDgYreIw4sCEjSAvKCjC4Ck9v//JlyGXEYA "05AB1E – Try It Online") Takes three separate inputs in the order `b, a, c` and outputs an array `[d, e]`. Edit: Saved 2 bytes thanks to @Datboi. Saved 1 byte thanks to @Adnan. Explanation:
```
‚ Join a and b into a pair
U Store in variable X
T Push 10 to the stack
S Split into the pair [d, e] = [1, 0]
s Swap with c
F Repeat the rest of the program c times
X Get [a, b]
â Cartesian product with [d, e]
P Multiply each pair together [da, db, ea, eb]
` Push each product as a separate stack entry
( Negate eb
‚ Join with ea into a pair [ea, -eb]
R Reverse the pair [-eb, ea]
Š Push under da and db
‚ Join them into a pair [da, db]
+ Add the two pairs [da-eb, db+ea]
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~62~~ 38 bytes
```
a=>c=>System.Numerics.Complex.Pow(a,c)
```
[Try it online!](https://tio.run/##jY6xCoMwFEX3fEXolKDNIHSyugiFQltKLXRO04c8iIkksVbEb7cdHFyEbvfCOZer/FZZB1PTPjUqqrT0nhYD8UGGXy97H6AWh9ao/ZwvbQ0OlReFrRsNn3jJoAnxCpfnTTbJLFdZvkKIq@2YjBWfUjL/mW@8Lb7oWaJhnAyzXVjjrQbxcBjghAZYwwx0dGWc7eKEc5ZwcQOpxd2WwaGpGI82dBP9qR5rWaGRrl/4PCUjGacv "C# (.NET Core) – Try It Online")
[Answer]
# Pyth, ~~5~~ ~~12~~ ~~5~~ 2 bytes
```
^E
```
Takes in `c` first, followed by `a+bj`.
~~7 bytes of boilerplate because apparently output as an imaginary number is disallowed.~~ It's been re-allowed! Hurrah! And with taking in a complex number being a reasonable input, we can cut out an additional 3 bytes!
Previous solutions:
```
^.jEE
```
When complex numbers were not reasonable inputs.
```
m,edsd]^.jEE
```
When complex numbers were not reasonable outputs.
[Test Suite.](http://pyth.herokuapp.com/?code=%5EE&input=2%0A5%0A2&test_suite=1&test_suite_input=2%0A5%2B2j%0A%0A2%0A1%2B4j%0A%0A1%0A-5%2B0j%0A&debug=0&input_size=3)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte
```
m
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/9/9/Iy4NU22jLE0A "05AB1E – Try It Online")
Input: `c\n(a+bj)`
Output: `(d+ej)`
[Answer]
# J, ~~10~~, ~~7~~, 1 byte~~s~~
```
^
```
Takes `c` as the right argument and the complex number `ajb` (how you represent `a + bi` in J) as the left argument.
[Try it online!](https://tio.run/##y/r/P81WL44rNTkjX8E0y0ghTcEIwjHMMkFw4k2zDIA8w///AQ)
## Other Solutions
### 7 bytes
Takes the complex number input as a list.
```
^~j./@]
```
### 10 bytes
This outputted the `a + bi` in the list `a b`.
```
+.@^~j./@]
```
I wanted to try something cute like `^~&.(j./)` but the inverse of `j./` is obviously not defined. Actually, `^~&.(+.inv)` works and you can make that `^&.(+.inv)` which is also 10 bytes if you reverse the order in which you take the args.
[Answer]
# TI-BASIC, ~~25~~ ~~22~~ 8 bytes
Takes the complex number and the exponent as input, and stores output in `Ans` as a complex number. Drastic drop in bytes due to loosened restrictions on input/output.
```
Prompt C,E
C^E
```
[Answer]
# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) subroutine, 199 187 185 bytes
```
A2 03 B5 FB 95 26 CA 10 F9 88 D0 01 60 A5 26 85 61 A5 27 85 62 A5 FB 85 63 A5
FC 85 64 A9 20 85 6F D0 36 18 A5 6D 65 65 85 28 A5 6E 65 66 85 29 A5 4B 85 26
A5 4C 85 27 50 CF 38 A5 6D E5 65 85 4B A5 6E E5 66 85 4C A5 28 85 61 A5 29 85
62 A5 FB 85 63 A5 FC 85 64 06 6F A9 00 85 65 85 66 A2 10 46 62 66 61 90 0D A5
63 18 65 65 85 65 A5 64 65 66 85 66 06 63 26 64 CA 10 E6 A9 FF 24 6F 70 B9 30
02 F0 9E A5 65 85 6D A5 66 85 6E 24 6F 30 14 A5 28 85 61 A5 29 85 62 A5 FD 85
63 A5 FE 85 64 06 6F D0 B4 A5 26 85 61 A5 27 85 62 A5 FD 85 63 A5 FE 85 64 06
6F B0 A0
```
* *-12 bytes with improved "spaghetti" structure*
* *-2 bytes changing the register to pass the exponent, so we can make use of zeropage addressing mode in the initial copy loop*
This is position-independent code, just put it somewhere in RAM and call it with a `jsr` instruction.
The routine takes the (complex) base as two 16bit signed integers (2's complement, little-endian) in `$fb/$fc` (real) and `$fd/$fe` (imaginary), and the exponent as an unsigned 8bit integer in the `Y` register.
The result is returned in `$26/$27` (real) and `$28/$29` (imaginary).
---
### Explanation
This is still an interesting challenge on the 6502 CPU as there are no instructions for even multiplying. The approach is straight forward, implementing a complex multiplication and executing it as often as required by the exponent. Golfing is done by avoiding subroutines, instead creating kind of a "branch spaghetti", so the code for doing a simple 16bit multiplication that's needed multiple times is reused with the lowest possible overhead. Here's the commented disassembly:
```
.cexp:
A2 03 LDX #$03 ; copy argument ...
.copyloop:
B5 FB LDA $FB,X
95 26 STA $26,X
CA DEX
10 F9 BPL .copyloop ; ... to result
.exploop:
88 DEY ; decrement exponent
D0 01 BNE .mult ; zero reached -> done
60 RTS
.mult: ; multiply (complex) result by argument
A5 26 LDA $26 ; prepare to multiply real components
85 61 STA $61 ; (a*c)
A5 27 LDA $27
85 62 STA $62
A5 FB LDA $FB
85 63 STA $63
A5 FC LDA $FC
85 64 STA $64
A9 20 LDA #$20 ; marker for where to continue
85 6F STA $6F
D0 36 BNE .mult16 ; branch to 16bit multiplication
.mult5:
18 CLC ; calculate sum (a*d) + (b*c)
A5 6D LDA $6D
65 65 ADC $65
85 28 STA $28 ; and store to imaginary component of result
A5 6E LDA $6E
65 66 ADC $66
85 29 STA $29
A5 4B LDA $4B ; load temporary result (a*c) - (b*d)
85 26 STA $26 ; and store to real component of result
A5 4C LDA $4C
85 27 STA $27
50 CF BVC .exploop ; next exponentiation step
.mult3:
38 SEC ; calculate difference (a*c) - (b*d)
A5 6D LDA $6D
E5 65 SBC $65
85 4B STA $4B ; and store to temporary location
A5 6E LDA $6E
E5 66 SBC $66
85 4C STA $4C
A5 28 LDA $28 ; prepare to multiply real component of result
85 61 STA $61 ; with imaginary component of argument
A5 29 LDA $29 ; (a*d)
85 62 STA $62
A5 FB LDA $FB
85 63 STA $63
A5 FC LDA $FC
85 64 STA $64
06 6F ASL $6F ; advance "continue marker"
.mult16:
A9 00 LDA #$00 ; initialize 16bit multiplication
85 65 STA $65 ; result with 0
85 66 STA $66
A2 10 LDX #$10 ; bit counter (16)
.m16_loop:
46 62 LSR $62 ; shift arg1 right
66 61 ROR $61
90 0D BCC .m16_noadd ; no carry -> nothing to add
A5 63 LDA $63 ; add arg2 ...
18 CLC
65 65 ADC $65
85 65 STA $65
A5 64 LDA $64
65 66 ADC $66
85 66 STA $66 ; ... to result
.m16_noadd:
06 63 ASL $63 ; shift arg2 left
26 64 ROL $64
CA DEX ; decrement number of bits to go
10 E6 BPL .m16_loop
A9 FF LDA #$FF ; check marker for where to continue
24 6F BIT $6F
70 B9 BVS .mult3
30 02 BMI .saveres ; have to save result to temp in 2 cases
F0 9E BEQ .mult5
.saveres:
A5 65 LDA $65 ; save result to temporary
85 6D STA $6D
A5 66 LDA $66
85 6E STA $6E
24 6F BIT $6F ; check "continue marker" again
30 14 BMI .mult4
.mult2:
A5 28 LDA $28 ; prepare to multiply imaginary components
85 61 STA $61 ; (b*d)
A5 29 LDA $29
85 62 STA $62
A5 FD LDA $FD
85 63 STA $63
A5 FE LDA $FE
85 64 STA $64
06 6F ASL $6F ; advance "continue marker"
D0 B4 BNE .mult16 ; branch to 16bit multiplication
.mult4:
A5 26 LDA $26 ; prepare to multiply imaginary component of
85 61 STA $61 ; result with real component of argument
A5 27 LDA $27 ; (b*c)
85 62 STA $62
A5 FD LDA $FD
85 63 STA $63
A5 FE LDA $FE
85 64 STA $64
06 6F ASL $6F ; advance "continue marker"
B0 A0 BCS .mult16 ; branch to 16bit multiplication
```
---
### Example program using it (C64, assembly source in [ca65](https://cc65.github.io/doc/ca65.html)-syntax):
```
.import cexp
CEXP_A = $fb
CEXP_AL = $fb
CEXP_AH = $fc
CEXP_B = $fd
CEXP_BL = $fd
CEXP_BH = $fe
CEXP_RA = $26
CEXP_RAL = $26
CEXP_RAH = $27
CEXP_RB = $28
CEXP_RBL = $28
CEXP_RBH = $29
.segment "LDADDR"
.word $c000
.segment "MAIN"
jsr $aefd ; consume comma
jsr $ad8a ; evaluate number
jsr $b1aa ; convert to 16bit int
sty CEXP_AL ; store as first argument
sta CEXP_AH
jsr $aefd ; ...
jsr $ad8a
jsr $b1aa
sty CEXP_BL ; store as second argument
sta CEXP_BH
jsr $b79b ; read 8bit unsigned into X
txa ; and transfer
tay ; to Y
jsr cexp ; call our function
lda CEXP_RAH ; read result (real part)
ldy CEXP_RAL
jsr numout ; output
ldx CEXP_RBH ; read result (imaginary part)
bmi noplus
lda #'+' ; output a `+` if it's not negative
jsr $ffd2
noplus: txa
ldy CEXP_RBL
jsr numout ; output (imaginary part)
lda #'i'
jsr $ffd2 ; output `i`
lda #$0d ; and newline
jmp $ffd2
numout:
jsr $b391 ; convert to floating point
jsr $bddd ; format floating point as string
ldy #$01
numout_loop: lda $ff,y ; output loop
bne numout_print ; until 0 terminator found
rts
numout_print: cmp #' ' ; skip space characters in output
beq numout_next
jsr $ffd2
numout_next: iny
bne numout_loop
```
---
## [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%22cexp.prg%22:%22data:;base64,AMAg/a4giq0gqrGE+4X8IP2uIIqtIKqxhP2F/iCbt4qoIFrApSekJiBCwKYpMAWpKyDS/4qkKCBCwKlJINL/qQ1M0v8gkbMg3b2gAbn/ANABYMkg8AMg0v/I0PCiA7X7lSbKEPmI0AFgpSaFYaUnhWKl+4VjpfyFZKkghW/QNhilbWVlhSilbmVmhSmlS4UmpUyFJ1DPOKVt5WWFS6Vu5WaFTKUohWGlKYVipfuFY6X8hWQGb6kAhWWFZqIQRmJmYZANpWMYZWWFZaVkZWaFZgZjJmTKEOap/yRvcLkwAvCepWWFbaVmhW4kbzAUpSiFYaUphWKl/YVjpf6FZAZv0LSlJoVhpSeFYqX9hWOl/oVkBm+woA==%22%7D,%22vice%22:%7B%22-autostart%22:%22cexp.prg%22%7D%7D)
**Usage:** `sys49152,[a],[b],[c]`, e.g. `sys49152,5,2,2` (Output: `21+20i`)
[Answer]
# [Dyalog APL](https://www.dyalog.com/), 10 bytes
```
⎕*⍨⊣+¯11○⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBKYKGo/6pmo96l3xqGux9qH1hoaPpnc/6lqkqWDEZcTFZYhT2gQkfWg9bv0GXIYA)
`a` is left argument, `b` is right argument, and `c` via input prompt.
Returns a complex number in the format `dJe`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 1 byte
```
^
```
Inputs are `a+jb`, `c`.
[**Try it online!**](https://tio.run/##y00syfn/P@7/f1NtoywuIwA)
## Old version: non-complex input and output, 8 bytes
```
J*+i^&Zj
```
Input order is `b`,`a`, `c`.
[**Try it online!**](https://tio.run/##y00syfn/30tLOzNOLSrr/38jLlMuIwA "MATL – Try It Online")
### Explanation
```
J Push imaginary unit
* Multiply by implicit input b
+ Add implicit input a
i Take input c
^ Power
&Zj Push real and imaginary parts. Implicitly display
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 34 bytes
```
#define f(a,b,c)cpow((a)+1i*(b),c)
```
[Try it online!](https://tio.run/##hctBCsIwEEDRvacIlcKMTsAUu/IqbtIxEwJJLK3gQry6MYKibnT5PzzWnrmU5cFJyE4JWBqIkcfjGcDi2oQVDFhPCfmkkg0Z8LIYp1oCqmlFtbLPDSmenI0g0FNHHVYRkvXvVrj7pQxtv9Sz/yjd04bMB3uNh7uWG0u0fi46pjs "C (gcc) – Try It Online")
[Answer]
# Casio-Basic, 6 bytes
```
a^b
```
Change to the rules to allow input and output as complex numbers made this significantly shorter.
3 bytes for the function, +3 to enter `a,b` in the parameters box.
[Answer]
# [8th](http://8th-dev.com/), 38 bytes
**Code**
```
c:new dup >r ( r@ c:* ) rot n:1- times
```
**SED** (Stack Effect Diagram) is: `c a b -- (a + bi) ^ c`
*Warning*: `a + bi` is left on **r-stack**, but this doesn't affect subsequent computations.
**Ungolfed version with comments**
```
needs math/complex
: f \ c a b -- (a + bi) ^ c
c:new \ create a complex number from a and b
dup \ duplicate a + bi
>r \ store a + bi on r-stack
( r@ c:* ) rot n:1- times \ raise ( a + bi ) to c
;
```
**Example and usage**
```
: app:main
\ rdrop is not strictly required
2 5 2 f . cr rdrop
2 1 4 f . cr rdrop
1 -5 0 f . cr rdrop
bye
;
```
**Output of the previous code**
```
c:1:data:{"real":21,"imag":20}
c:1:data:{"real":-15,"imag":8}
c:2:data:{"real":-5,"imag":0}
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/) / MATLAB, 6 bytes
```
@power
```
Anonymous function that inputs two numbers and outputs their power.
[**Try it online**!](https://tio.run/##y08uSSxL/Z9mq6en99@hIL88teh/moaptlGWjpEmV5qGobYJlKVrqm2QpWOo@R8A)
## Old version: non-complex input and output, 30 bytes
```
@(a,b,c)real((a+j*b)^c./[1 j])
```
Anonymous function that inputs three numbers and outputs an array of two numbers.
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999BI1EnSSdZsyg1MUdDI1E7SytJMy5ZTz/aUCErVvN/moapjpGOkSZXmoahjgmEoWuqY6BjqPkfAA)
[Answer]
# [Perl 6](https://perl6.org), ~~29 26 20 19~~ 11 bytes
```
{$_=($^a+$^b*i)**$^c;.re,.im}
```
[Try it](https://tio.run/##K0gtyjH7n1upoJacn5KqYPu/WiXeVkMlLlFbJS5JK1NTS0slLtlaryhVRy8zt/Z/cWmSQkpmcUFOYqWChkKNs4JmNZeCAlC7Q1FqcWlOiYKVrQLIIIicNVCuGKjSWc8ns7hErwBol46CUkyJrZ2Ckg5My6HdekX5pXkpaGoQCsBiXLVcMHtNdYx0jKzhXEMdE2SurqmOgY6h9X8A "Perl 6 – Try It Online")
```
{(($^a+$^b*i)**$^c).reals}
```
[Try it](https://tio.run/##K0gtyjH7n1upoJacn5KqYPu/WkNDJS5RWyUuSStTU0tLJS5ZU68oNTGnuPZ/cWmSQkpmcUFOYqWChkKNs4JmNZeCAlCvQ1FqcWlOiYKVrQLIFIicNVCuGKjSWc8ns7hErwBokY6CUkyJrZ2Ckg5My6HdekX5pXkpaGoQCsBiXLVcMHtNdYx0jKzhXEMdE2SurqmOgY6h9X8A "Perl 6 – Try It Online")
```
((*+* *i)** *).reals
```
[Try it](https://tio.run/##K0gtyjH7n1upoJacn5KqYPtfQ0NLW0tBK1NTC0hq6hWlJuYU/7fmKi5NUkjJLC7ISaxU0FCocVbQrOZSUADqcyhKLS7NKVGwslUAmQCRswbKFQNVOuv5ZBaX6BUALdFRUIopsbVTUNKBaTm0W68ovzQvBU0NQgFYjKuWC2avqY6RjpE1nGuoY4LM1TXVMdAxtP4PAA "Perl 6 – Try It Online")
```
((*+* *i)***).reals
```
[Try it](https://tio.run/##K0gtyjH7n1upoJacn5KqYPtfQ0NLW0tBK1NTS0tLU68oNTGn@L81V3FpkkJKZnFBTmKlgoZCjbOCZjWXggJQm0NRanFpTomCla0CyACInDVQrhio0lnPJ7O4RK8AaIeOglJMia2dgpIOTMuh3XpF@aV5KWhqEArAYly1XDB7TXWMdIys4VxDHRNkrq6pjoGOofV/AA "Perl 6 – Try It Online")
With the change of output restrictions it can be further reduced:
```
(*+* *i)***
```
[Try it](https://tio.run/##K0gtyjH7n1upoJacn5KqYPtfQ0tbS0ErU1NLS@u/NVdxaZJCSmZxQU5ipYKGQo2zgmY1l4ICUHlMUWpxaU6Jgq0CSB9EyhooVQxU6Kznk1lcolcANFpHQSmmxNZOQUlHAaJBryg1Maf40G69ovzSvBQ0hQhVICGuWi6Y1aY6RjpG1nCuoY4JMlfXVMdAx9D6PwA "Perl 6 – Try It Online")
The `***` part is parsed as `** *` because the `**` infix operator is longer than the `*` infix operator.
## Expanded:
```
# __________________ 1st parameter
# / _______________ 2nd parameter
# / / ______ 3rd parameter
# / / /
# V V V
( * + * * i) ** *
# ^ ^^
# \ \________ exponentiation
# \_____________ multiplication
```
[Answer]
# R, 25 bytes
simplest - since outputting complex is allowed.
```
function(a,b,c)(a+b*1i)^c
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 9 bytes
Returns an anonymous function that takes a complex number and integer and returns a complex number.
```
proc &:**
```
This is equivalent to `->x,y{x**y}` (11 bytes).
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhYrC4rykxXUrLS0IPyb6gUKbtGm2kaZOgpGsVwgjqG2CYKja6ptAOQZxkKUL1gAoQE)
] |
[Question]
[
Some decimal numbers cannot be precisely represented as binary floats due to the internal representation of the binary floats. For example: rounding 14.225 to two decimal digits does not result in 14.23 as one might expect but in 14.22.
**Python**:
```
In: round(14.225, 2)
Out: 14.22
```
Assume, however, that we have a string representation of 14.225 as '14.225', we should be able to achieve our desired rounding '14.23' as a string representation.
This approach can be generalized to arbitrary precision.
# Possible Python 2/3 Solution
```
import sys
def round_string(string, precision):
assert(int(precision) >= 0)
float(string)
decimal_point = string.find('.')
if decimal_point == -1:
if precision == 0:
return string
return string + '.' + '0' * precision
all_decimals = string[decimal_point+1:]
nb_missing_decimals = precision - len(all_decimals)
if nb_missing_decimals >= 0:
if precision == 0:
return string[:decimal_point]
return string + '0' * nb_missing_decimals
if int(all_decimals[precision]) < 5:
if precision == 0:
return string[:decimal_point]
return string[:decimal_point+precision+1]
sign = '-' if string[0] == '-' else ''
integer_part = abs(int(string[:decimal_point]))
if precision == 0:
return sign + str(integer_part + 1)
decimals = str(int(all_decimals[:precision]) + 1)
nb_missing_decimals = precision - len(decimals)
if nb_missing_decimals >= 0:
return sign + str(integer_part) + '.' + '0' * nb_missing_decimals + decimals
return sign + str(integer_part + 1) + '.' + '0' * precision
```
[Try it online!](https://tio.run/nexus/python2#tZTdaoMwFMfvfYpDb5LMVlTYjax9EZGQzigBjZLYwZ7eJWrjx@zoBsuFQs7H/3dOTtKLum1UB/pTe17OC1DNTeZUd0rIEo@/I7SKvwstGkkSD8xiWnPVYSE7PJvgcoaQDPaialg3RRNv2MqNW80q2jYmCs4wGoNCyByjAI1xotj6neEUjZqT3elZWzib7FK8uyk5pfZ2d8EHo2a/IYKXOdsIyaqKTgDaMaYrJD9KssFXXmkttDYOy5AZ7wQVl3iZ0dW4F3pZVfObQtNkBZg9LnwoeUfcu4PZA10Spw4iI/AGr/8JuPHyXXo/ykZALUqjBeiErPwUFWZW3u7xSnNACMZiZMdLrmjLlJ02dtXDtO4DEXcyj2q6k1oC30rjlYAPEVlO@TQ8@Fs/k2VDXdRzo/SHMfoZm2wuw14@35XkPdmHRzesN8SUSlZzSm13D5TWTEhKDwNvq2yztq8PNu9SwFT5kUYZOQ7z6XZic26k76Mgjl/7@As "Python 2 – TIO Nexus")
**Usage**:
```
# No IEEE 754 format rounding
In: round_string('14.225',2)
Out: '14.23'
# Trailing zeros
In: round_string('123.4',5)
Out: '123.40000'
In: round_string('99.9',0)
Out: '100'
# Negative values
In: round_string('-99.9',0)
Out: '-100'
In: round_string('1',0)
Out: '1'
# No unnecessary decimal point
In: round_string('1.',0)
Out: '1'
# No unnecessary decimal point
In: round_string('1.0',0)
Out: '1'
In: for i in range(8):
print(round_string('123456789.987654321',i))
Out: 123456790
123456790.0
123456789.99
123456789.988
123456789.9877
123456789.98765
123456789.987654
123456789.9876543
```
# Task
**Input argument 1**: a string containing
* at least one digit (`0`, `1`, `2`, `3`, `4`, `5`,`6`, `7`, `8`, `9`),
* at most one decimal point (`.`) which must be preceded by at least one digit,
* an optional minus (`-`) as first character.
**Input argument 2**: a non-negative integer
**Output**: the correctly rounded (base 10) string
rounding = [Round half away from zero](https://en.wikipedia.org/wiki/Rounding#Tie-breaking)
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The lowest number of bytes wins!
[Answer]
# Perl, ~~22~~ 20 bytes
```
printf"%.*f",pop,pop
```
Using:
```
perl -e 'printf"%.*f",pop,pop' 123456789.987654321 3
```
It is Dada’s version of code. Previous:
```
printf"%*2\$.*f",@ARGV
```
[Answer]
# PHP, ~~33~~ 31 bytes
PHP rounds correctly too (at least on 64 bit):
```
printf("%.$argv[2]f",$argv[1]);
```
takes input from command line arguments. Run with `-r`.
# PHP, no built-ins, 133 bytes
```
[,$n,$r]=$argv;if($p=strpos(_.$n,46))for($d=$n[$p+=$r],$n=substr($n,0,$p-!$r);$d>4;$n[$p]=(5+$d=$n[$p]-4)%10)$p-=$n[--$p]<"/";echo$n;
```
Run with `-nr` or [test it online](http://sandbox.onlinephpfunctions.com/code/e2b9c11b733f4d151d14f055112527645a19cf58).
**breakdown**
```
[,$n,$r]=$argv; // import arguments
if($p=strpos(_.$n,46)) // if number contains dot
for($d=$n[$p+=$r], // 1. $d= ($r+1)-th decimal
$n=substr($n,0,$p-!$r); // 2. cut everything behind $r-th decimal
$d>4; // 3. loop while previous decimal needs increment
$n[$p]=(5+$d=$n[$p]-4)%10 // B. $d=current digit-4, increment current digit
)
$p-=$n[--$p]<"/"; // A. move cursor left, skip dot
echo$n;
```
A null byte doesn´t work; so I have to use `substr`.
[Answer]
## Ruby 2.3, 12 + 45 = 57
Uses the `BigDecimal` built-in, but it needs to be required before use, which is cheaper to do as a flag.
the flag: `-rbigdecimal`
the function:
```
->(s,i){BigDecimal.new(s).round(i).to_s('f')}
```
Ruby 2.3 by default uses `ROUND_HALF_UP`
[Answer]
# Javascript (ES6), 44 bytes
```
n=>p=>(Math.round(n*10**p)/10**p).toFixed(p)
```
### Try it online:
```
const f = n=>p=>(Math.round(n*10**p)/10**p).toFixed(p)
console.log(f('14.225')(2));
[...Array(8).keys()].map(i=>console.log(f('123456789.987654321')(i)))
console.log(f('123.4')(5))
```
[Answer]
# Python, ~~114~~ ~~105~~ ~~103~~ ~~96~~ ~~91~~ 89 bytes
Saved 5 bytes thanks to *Kevin Cruijssen*
Saved 2 bytes thanks to *Krazor*
```
from decimal import*
d=Decimal
lambda x,y:d(x).quantize(d('0.'[y>0]+'1'*y),ROUND_HALF_UP)
```
[Try it online!](https://tio.run/nexus/python3#TYtNC4IwAEDv@xW7bbMxdDq/wCCQ6BAVgacIWU1joNOGgfrnLehQ7/h4b6lt10JV3XUrG6jbvrODA1SWfw2os0a2NyXhSKdU4ZGw50uaQc8VVhi5DF2mtXtdIQ85E6HnY3HIy91mvy2LE1l6q82Aa4y8gHEuEOWEgLqzcIbaQCvNo8IxSQH88Gu5H4gwihOWxFEoAp97iM6f8b9gAaKCkOUN "Python 3 – TIO Nexus")
[Answer]
## REXX, 24 bytes
```
arg n p
say format(n,,p)
```
Since REXX always uses text representation of numbers, correct rounding of numbers is free.
[Try it online!](https://tio.tryitonline.nz/nexus/rexx#@59YlK6Qp1DAVZxYqZCWX5SbWKKRp6NToPn//39DEz0jI1MFIwA)
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 4 bytes
Dyalog APL uses enough internal precision.
```
⎕⍕⍎⍞
```
[Try it online!](https://tio.run/nexus/apl-dyalog#fYy7EcMgDEB7pmACDoT4LeRV7AZ3KZMVvINH0SIE4gtHgk86CtB7D9rWpdD@oFzPTvlVaFuL/MwiDCoAJ0BSfsr2sKIjsAqFu0i76zqdpqSS0Bcc1ucxgPMYkfnq3EbpeQcWnQ@x/huDd2ihdxdJmnXNr6t4G0a7kcTq9l@PkfVx8kNgAzcH3rGFvyuQTcJtYt8 "APL (Dyalog Unicode) – TIO Nexus")
`⍎⍞` execute string input
`⎕⍕` get numeric input and use that as precision for formatting
[Answer]
# BASH, ~~26~~ ~~23~~ 21 bytes
```
bc<<<"scale=$2;$1/1"
```
## usage
save to round\_string.sh, chmod +x round\_string.sh
```
./round_string.sh 23456789.987654321 3
```
edit:no need to load library
[Answer]
# AHK, 25 bytes
```
a=%1%
Send % Round(a,%2%)
```
Again I am foiled by the inability of AHK to use passed in parameters directly in functions that accept either a variable name or a number. If I replace `a` with `1` in the `Round` function, it uses the value `1`. If I try `%1%`, it tries to use the first argument's *contents* as a variable name, which doesn't work. Having to set it as another variable first cost me 6 bytes.
[Answer]
## Batch, 390 bytes
```
@echo off
set s=%1
set m=
if %s:~,1%==- set m=-&set s=%s:~1%
set d=%s:*.=%
if %d%==%s% (set d=)else call set s=%%s:.%d%=%%
for /l %%i in (0,1,%2)do call set d=%%d%%0
call set/ac=%%d:~%2,1%%/5
call set d=00%s%%%d:~,%2%%
set z=
:l
set/ac+=%d:~-1%
set d=%d:~,-1%
if %c%==10 set c=1&set z=%z%0&goto l
set d=%m%%d:~2%%c%%z%
if %2==0 (echo %d%)else call echo %%d:~,-%2%%.%%d:~-%2%%
```
Explanation. Starts by extracting the sign, if applicable. Then, splits the number into integer and fraction digits. The fraction is padded with `n+1` zeros to ensure it has more than `n` digits. The `n`th (zero-indexed) digit is divided by 5, and this is the initial carry. The integer and `n` fraction digits are concatenated, and the carry added character by character. (The extra zeros guard against carry ripple.) After the carry stops rippling the number is reconstructed and any decimal point inserted.
[Answer]
# TI-Basic, ~~53~~ 16 bytes
TI-Basic does not use IEEE and the below method works for 0-9 (inclusive) decimal positions.
```
Prompt Str1,N
toString(round(expr(Str1),N
```
Thanks to @JulianLachniet for showing that CE calcs have the `toString(` command which I was not aware of (Color Edition calcs OS 5.2 or higher are required).
P.S. I did have a second line with `sub(Str1,1,N+inString(Str1,".` but then I realized it was useless.
[Answer]
# Java 7, ~~77~~ ~~72~~ 71 bytes
```
<T>T c(T n,int d){return(T)"".format("%."+d+"f",new Double(n+""));}
```
-1 byte thanks to *@cliffroot*
**72-byte answer:**
```
String c(String n,int d){return n.format("%."+d+"f",new Double(n));}
```
Unlike Python, Java already rounds correctly and already returns a String when you use `String.format("%.2f", aDouble)` with the `2` replaced with the amount of decimals you want.
EDIT/NOTE: Yes, I'm aware `new Float(n)` is 1 byte shorter than `new Double(n)`, but apparently it fails for the test cases with `123456789.987654321`. [See this test code regarding Double vs Float.](https://tio.run/nexus/java-openjdk#@5@ck1hcrOBbzaWgUFCalJOZrFBcklgCpMryM1MUchMz8zSCS4oy89KjYxUSNUHKFBSCK4tLUnP18ktL9AqAUiU5MDV6aflFuYklGkqqesZpSjoKeanlCi75QGNTNZQMjYxNTM3MLSz1LC3MzUxNjI0MlTQ1Na1JN9EtJx8kgsfAWq7a//8B)
**Explanation:**
```
<T> T c(T n, int d){ // Method with generic-T & integer parameters and generic-T return-type (generic-T will be String in this case)
return (T)"".format("%."+d+"f", // Return the correctly rounded output as String
new Double(n+"")); // After we've converted the input String to a decimal
} // End of method
```
**Test code:**
[Try it here.](https://tio.run/nexus/java-openjdk#jZDBaoNAEIbvPsUwUNhl7WI2mihJeuq1p3grPWzVlAVdg44pJfjsdoQUehIPw8DMxzfDPxW17Xt4g3sA0JMlV8Axf8mhEDn40HmCUt67iobOi1wi6kvbNZYEPmlUpcILhr76htd2@Kwr4RWilIcxYNuVJ2x7SG@tK6Gxzoszdc5/vX@AlfNRgPNPT1Wj24H0lVdUe1EI3MTamARDMCxc4sxWx4wly1iW6YypaJl6XodtViB6DRP9hzhZMQfu4ATRgdsRUm5KPXJaSCBOdvuUX0/3uyTemvk/96cdg7nGafoF)
```
class M{
static <T>T c(T n,int d){return(T)"".format("%."+d+"f",new Double(n+""));}
public static void main(String[] a){
System.out.println(c("14.225", 2));
System.out.println(c("123.4", 5));
System.out.println(c("99.9", 0));
System.out.println(c("-99.9", 0));
System.out.println(c("1", 0));
System.out.println(c("1.", 0));
System.out.println(c("1.0", 0));
for(int i = 0; i < 8; i++){
System.out.println(c("123456789.987654321", i));
}
}
}
```
**Output:**
```
14.23
123.40000
100
-100
1
1
1
123456790
123456790.0
123456789.99
123456789.988
123456789.9877
123456789.98765
123456789.987654
123456789.9876543
```
[Answer]
## Python (2/3), 394 bytes
```
def rnd(s,p):
m=s[0]=='-'and'-'or''
if m:s=s[1:]
d=s.find('.')
l=len(s)
if d<0:
if p>0:d=l;l+=1;s+='.'
else:return m+s
e=(d+p+1)-l
if e>0:return m+s+'0'*e
o=''
c=0
for i in range(l-1,-1,-1):
x=s[i]
if i<=d+p:
if i!=d:
n=int(x)+c
if n>9:n=0;c=1
else:c=0
o+=str(n)
else:
if p>0:o+=x
if i==d+p+1:c=int(x)>4
if c:o+='1'
return m+''.join(reversed(o))
```
Works for arbitrary precision numbers.
[Answer]
## JavaScript (ES6), 155 bytes
```
(s,n)=>s.replace(/(-?\d+).?(.*)/,(m,i,d)=>i+'.'+(d+'0'.repeat(++n)).slice(0,n)).replace(/([0-8]?)([.9]*?)\.?(.)$/,(m,n,c,r)=>r>4?-~n+c.replace(/9/g,0):n+c)
```
Explanation: The string is first normalised to contain a `.` and `n+1` decimal digits. The trailing digit, any preceding `9`s or `.`s, and any preceding digit, are then considered. If the last digit is less than 5 then it and any immediately preceding `.` are simply removed but if it is greater than 5 then the `9`s are changed to `0`s and the previous digit incremented (or 1 prefixed if there was no previous digit).
[Answer]
# [Python 3](https://docs.python.org/3/) + SymPy, 54 bytes
```
from sympy import*
lambda s,p:'%.*f'%(p,S(s).round(p))
```
[Try it online!](https://tio.run/nexus/python3#XY3LCoMwEEXX5itmI0kkDZomvqBf0W03Fk0JNA@iXfj1VhQsdnnOnblXww0ey7uzz76DkYUWpzzTOCWB3clIefQf15NAKdLRWxhnG2YwNvg4ZUs/aNgP1k/aoiRE4yaiN6QI7RkuJBdCYSboYcSVS8zUIZqGN5jlB1/@RXECfqZ8Q@0jGDAOYudeA6lpCyj5DUpVVvXaWlelklexFhq6fAE "Python 3 – TIO Nexus")
[Answer]
# Scala, 44 bytes
```
(s:String,p:Int)=>s"%.${p}f"format s.toFloat
```
Test:
```
scala> var x = (s:String,p:Int)=>s"%.${p}f"format s.toFloat
x: (String, Int) => String = <function2>
scala> x("14.225",2)
res13: String = 14.23
```
[Answer]
# [Wonder](https://github.com/wonderlang/wonder), 10 bytes
```
@@fix#1E#0
```
Usage:
```
@@fix#1E#0
```
Set decimal precision and add trailing zeros if necessary.
[Answer]
# J, ~~22~~ 17 bytes
```
((10 j.[)]@:":".)
NB. 2 ((10 j.[)]@:":".) '12.45678'
NB. 12.46
```
Thanks to @Conor O'Brien for correcting my understanding of the rules.
```
t=:4 :'(10 j.x)":".y'
NB. Examples
NB. 4 t'12.45678'
NB. 12.4568
NB. 4 t'12.456780'
NB. 12.4568
NB. 4 t'12.4567801'
NB. 12.4568
NB. 2 t'12.45678'
NB. 12.46
NB. 2 t'12.4567801'
NB. 12.46
NB. 2 (10 j.[)":". '_12.4567801'
NB. _12.46
format
x t y
where x is a digit number of decimal places required and y
is the character string containing the value to be rounded.
```
] |
[Question]
[
Write a program which generates keyboard events which type `Hello, World!`.
It doesn't have to be platform-independent.
It can't leave any keys pressed. For example, in Java, `Robot.KeyPress('H');` will leave `H` pressed, so you must release it with `Robot.KeyRelease('H');`
You may assume that the caps lock is off when your program is run. Capital letters can be typed either by holding shift and pressing the letter, or by toggling caps lock. For the `!`, you'll probably have to use the shift method.
Shortest code wins.
[Answer]
# AppleScript, 50 bytes
```
tell app"System Events"to keystroke"Hello, World!"
```
Thanks to marinus for the suggestion.
[Answer]
# Autohotkey, 20 bytes
```
send Hello, World{!}
```
***Please don't count this one.*** I don't want to cheat out people who have actually done this with a language not meant for sending keystrokes. This answer is just for completion :P
[Answer]
# C (Linux), 186 bytes
```
#include<sys/ioctl.h>
#include<fcntl.h>
#include<stdio.h>
main(){char*s="Hello, World!",d[99],*c;fscanf(popen("tty","r"),"%s",d);int D=open(d,O_RDWR);for(c=s;*c;c++)ioctl(D,TIOCSTI,c);}
```
After applying ugoren's suggestions:
## 111 bytes
```
main(D){char*c,d[99];fscanf(popen("tty","r"),"%s",d);D=open(d,2);for(c="Hello, World!";*c;)ioctl(D,21522,c++);}
```
[Answer]
# Emacs Lisp, 34 bytes
`(execute-kbd-macro"Hello, World!")`
[Answer]
# C in Windows 7, 201 bytes
```
#include<windows.h>
#include<winable.h>
#define S SendInput(1,&k,28);
int k[7]={1};main(i){char*s="^HELLO, ^WORLD^1";for(i=0;i<16;i++){k[2]=0;if(s[i]>90){k[1]=16;S i++;}k[1]=s[i];S k[2]=2;S k[1]=16;S}}
```
Program result:
```
C:\My\Directory>type.exe
C:\My\Directory>Hello, World!
```
[Answer]
# AutoIt3, 21 bytes
```
Send("Hello, World!")
```
[Answer]
# VBScript, 54 bytes
```
createobject("wscript.shell").sendkeys "Hello, World!"
```
[Answer]
# Tcl, 46 bytes
```
package r Expect;spawn bash;send Hello,\ World
```
# Expect, 29 bytes
```
spawn bash;send Hello,\ World
```
[Answer]
# Ducky Script for USB Rubber Ducky, 22 bytes
```
String "Hello, World!"
```
[Answer]
# PowerShell, 55 bytes
```
(New-Object -c wscript.shell).sendkeys('Hello, World!')
```
[Answer]
# InstantEXE 3.0, 20 bytes
```
Keys "Hello, World!"
```
[Answer]
## Python 3,67 bytes
```
from pynput.keyboard import*
s=Controller()
s.type("Hello, World!")
```
*No module named pynput on tio*
] |
[Question]
[
# Objective
Given a permutation of 4 distinct items, classify the permutation by the normal subgroup(s) it belongs.
# Input/Output Format
You gotta choose the followings as the hyperparameters for your submission:
* The 4 distinct items.
* The permutation serving as the identity permutation.
The input format is to accept a permutation of the items you chose. The items must be computably distinguishable.
The output format is flexible; you can output anything as long as the classes are computably distinguishable.
Standard loopholes apply.
In any case, an input not fitting into your format falls into *don't care* situation.
# Classification
For example, suppose you chose the numbers `0`, `1`, `2`, and `3` as the 4 items, and chose the string `0123` as the identity permutation.
* The identity permuation `0123` is classified as the member of the trivial group \$\textbf{0}\$.
* The permutations consisting of two non-overlapping swaps are classified as members of the Klein-four group \$K\_4\$ minus the trivial group. Those are `1032`, `2301`, and `3210`.
* The permutations that fixes exactly one item are classified as members of the alternating group \$A\_4\$ minus the Klein-four group. Those are `0231`, `0312`, `1203`, `1320`, `2013`, `2130`, `3021`, and `3102`.
* The remaining permuations are classified as members of the symmetric group \$S\_4\$ minus the alternating group.
# Examples
Let's say you chose the string `READ` as the identity permutation, and chose to output the classes as numbers `0`, `1`, `2`, and `3`, respectively to the list above.
* Given the string `ADER`, output `3`.
* Given the string `ADRE`, output `1`.
* Given the string `RADE`, output `2`.
* Given the string `READ`, output `0`.
[Answer]
# JavaScript (ES6), 23 bytes
Expects a permutation of the string `"4567"` and returns `0` ... `3`.
```
s=>962578>>s%530%13*2&3
```
[Try it online!](https://tio.run/##bVI9D4JAFNv9GZdgwESj8D50gMTZwcXRhSAohnCGI/z983Tyo2vTtK/tu5dT6aqhfYzL3l5q3@Te5cVOUtZtUbiIs3W0yRbpPPOV7Z3t6lVnr7E5De3Ulp1JZp9wExtiUZMksy/cnPsD/XOZVF7cH1iUGMAqTEh5D5RJFEmQMjJkIUWwCqHziBFbWBFbSWAYJkFhjuOtHhyqFVYVxBXmhKbBE@YUeHnIA9chWG0YB7aijFuBQ4R5IFveD@Gf "JavaScript (Node.js) – Try It Online")
### How?
Below is a view of the lookup bitmask and where each possible input is mapped once the expression \$(n \bmod 530)\bmod 13\$ is applied.
```
00 00 11 10 10 11 00 00 00 01 00 10
11 10 9 8 7 6 5 4 2 1 0
| | | | | | | | | | |
| | | | | | | | | | +--> 7654
| | | | | | | | | +-----> 4657, 7564
| | | | | | | | +--------> 4567
| | | | | | | +--------------> 5746, 6754, 7645
| | | | | | +-----------------> 4765, 6547
| | | | | +--------------------> 4675, 6457, 6574, 7465
| | | | +-----------------------> 5476
| | | +--------------------------> 6745
| | +-----------------------------> 4756, 5647, 5764, 7546
| +--------------------------------> 5674, 7456
+-----------------------------------> 4576, 5467, 6475
```
[Answer]
# [Python](https://www.python.org) NumPy, 26 bytes
```
lambda A:(2*A-A@A).trace()
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY5NCsIwFIT3OcVbJiUVW11IoWDOUYtE22ig-SF9hXbtMdwURA_hTbyN0urC1cA3H8NcH37As7PjTeW7e4cq3jwbaQ6VBJHRNBKx2Aq2wCCPNWWz8Lqo4AzYzvgBtPEuIFRansiENdYBnWvaX-XrYDqUqJ1tia72kE82XUdFUjKiXICo56Dtn0mLJU94ylclywj4oC3Sniv6GSj6kn2vjOOcbw)
Uses as the four distinct items the vectors `[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]`. With this convention the input, conveniently, becomes a permutation matrix.
Outputs `2 x # fixed points A - # fixed points AA`. This maps the identity to 4, the rest of the Klein four group to -4, the rest of the alternating group to 1 and everything else to 0.
# [Python](https://www.python.org), 48 bytes
```
lambda A:sum(2*(A[a]==a)-(A[A[a]]==a)for a in A)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3DXISc5NSEhUcrYpLczWMtDQcoxNjbW0TNXWBLBAbzEnLL1JIVMjMU3DUhOoLTSvKz1XILEktKsnPzylWyMwtyC8qUShILcotLUksyczPK-YC6dKq0AHpQxbXiDbQMdQx0jGO1bTiUigoyswr0ajQSdOo0IQavmABhAYA)
Same logic but uses items `0,1,2,3` and indexing instead of matrix operations.
[Answer]
# [J](https://www.jsoftware.com), 14 bytes
```
5|1#.2^~#@>@C.
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZCxCsIwEIZx7VMcbbEW25hLEaSlJSg4iYNrQQexSBcX3Yov4lIHV3dfxacxd-cgDiG5__58_yW3e9u_fAVRA2UOUQIacrdSBYvNavm4nJt09px2GCizvQa2sgsl4nuQwHquwMPOjuu8VRMbUtcTdWcCVeehLYMhq7F32B9P0Dg2goHsW_oI1QidmIEpSKd-QZWz6fjXpbntmmRGshPIFXSgC7rgGkkxrOmCgUaQFGP-kCjBWi4Im-1sFrYREgpLQngQnlHSmC5pPFomw8lLnBbLp_W97B8)
Found while experimenting with the cycle decomposition of each permutation.
* Category 1 (`0 1 2 3`) has four individual cycles of length 1.
* Category 2 (e.g. `1 0 3 2`) has two cycles of length 2.
* Category 3 (e.g. `0 2 3 1`) has one cycle of length 3 and another cycle of length 1.
* Category 4 (e.g. `0 1 3 2` or `1 2 3 0`) has either
+ three cycles of length 1, 1, 2, or
+ a single cycle of length 4.
By squaring and summing the cycle lengths, we get
* Category 1: 4
* Category 2: 8
* Category 3: 10
* Category 4: 6 or 16
Now we can take these values modulo 5 to get 4, 3, 0, 1 for each category.
```
5|1#.2^~#@>@C. Takes a permutation containing 0, 1, 2, 3
C. Cycle decomposition
#@>@ Length of each cycle
2^~ Square
1#. Sum
5| Modulo 5
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ỤƑḤ_=JSƊ
```
A monadic Link that accepts a permutation of `[1, 2, 3, 4]` and yields:
| classification | output |
| --- | --- |
| \$e\$ | -2 |
| rest of \$K\_4\$ | 2 |
| rest of \$A\_4\$ | -1 |
| rest of \$S\_4\$ | 0 |
**[Try it online!](https://tio.run/##y0rNyan8///h7iXHJj7csSTe1iv4WNf//woQ8D/aWEfBREfBUEfBKBYA "Jelly – Try It Online")** Or see [all cases](https://tio.run/##VVCxDQIxDOyZwgOkceKWBWgprYiKBv0CtDRIdFAxwJcMAKJE/B7/i4QktmURpYidO9/5DvthOJYyv8fpOj/H3XqznS7lc15Oj3q/t/l1LyCnMDMGiAFSAMo5rIC5VrVHtZcDcOrPBmoVdWRDKBiFqt/Ci0qVsa2nlbBRx4owaSXfqCIy1iTFUXLJ6P7QHJEbMGq0QeR2TCTaXsnt2BrJJMkTiH/mbEWy8NDT6VlVq/kH "Jelly – Try It Online").
### How?
```
ỤƑḤ_=JSƊ - Link: list of integers from [1..4], P
Ƒ - is (P) invariant under the application of:
Ụ - grade-up -> 1-indexed indices sorted by value
Ḥ - double -> X = 2 or 0
Ɗ - last three links as a monad - f(P):
J - range of length -> [1,2,3,4]
= - (P) equals (that) (vectorises)
S - sum -> Y
_ - (X) minus (Y)
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 33 bytes
```
p->if(permsign(p)>0,permorder(p))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWNxULdO0y0zQKUotyizPT8zQKNO0MdEC8_KKU1CIgVxOqUDUtvwgkrmGio1AAREWZeSUaQIaSgq6dgpKOQhpILVTxggUQGgA)
Takes input as a `VecSmall` of integers 1, 2, 3, 4.
If the input is an odd permutation, returns `0`. Otherwise returns its order.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~22~~ 19 bytes
```
§SAKS0⊘ΣEθ⁺⁼ικ⁼ι⌕θκ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMOxxDMvJbVCQynY0TvYQElHwSMxpyw1RSO4NFfDN7FAo1BHISCntFjDtbA0MadYI1NHIVtTRwHBc8vMSwEpytaEAuv//6OjjXUUjHQUDHUUDGJj/@uW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of 4 integers `0..3` (+2 bytes to take input as a string of digits) and outputs a code letter `0KAS` (-5 bytes to port @Albert.Lang's answer, and probably also the same length to port @JonathanAllan's answer). Explanation: Calculates the number of elements of cycle length `1` plus the number of elements of cycle length `1` or `2` (so elements of cycle length `1` get counted twice) and looks up the result.
```
SAKS0 Literal string `SAKS0`
§ Indexed by
θ Input list
E Map over elements
ι Current element
⁼ Equals
κ Current index
⁺ Plus
ι Current element
⁼ Equals
⌕ Index of
κ Current index in
θ Input list
Σ Take the sum
⊘ Halved
Implicitly print
```
| Cycles | Order | Sign | Length 1 | Length 2 | Total | Classification |
| --- | --- | --- | --- | --- | --- | --- |
| 1+1+1+1 | 1 | `+` | 4 | 0 | 8 | `0` |
| 2+1+1 | 2 | `-` | 2 | 2 | 6 | `S` |
| 2+2 | 2 | `+` | 0 | 4 | 4 | `K` |
| 3+1 | 3 | `+` | 1 | 0 | 2 | `A` |
| 4 | 4 | `-` | 0 | 0 | 0 | `S` |
* My original answer counted the number of elements of cycle length `1` and then distinguished between `2+2` and `4` by checking for an element of cycle length `2` rather than counting the number of such elements.
* @alephalpha's answer checks the sign of the permutation and returns `0` if it's `-` or the order if it's `+`.
* @Albert.Lang's answer subtracts the number of elements of cycle length `2` from the number of elements of cycle length `1`.
* @JonathanAllan's answer subtracts the number of elements of cycle length `1` from `2` if the order is a factor of `2` or `0` if it is not.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 14 bytes
```
{5!#,/(x@)\'x}
```
[Try it online!](https://ngn.codeberg.page/k#eJwtjjEOwzAMA3e/QkWGxECBSjK61Esf0tlvCBD07xXJbiZFH7le1/O23R/H+e6f/fy2tswtLG20tR9RYlhOaPgTqs7ecXXaZSIUiOFjCTwQ9EkdcJKeT4JSKODzjwoVuYJiMsaQmClCiCE4B3CTWkhVCycNjdLy8voPAzMqbw==)
Port of [my own J solution](https://codegolf.stackexchange.com/a/256066/78410).
The K code above executes the process a bit differently:
```
{5!#,/(x@)\'x} Takes a permutation containing 0, 1, 2, 3
( )\'x For each number in x, repeat and collect all values:
x@ Index into x
#,/ Length of flattened list
5! Modulo 5
```
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics`, ~~70~~ 61 bytes
```
[ "READ"<permutations> index "0332233123322323133223313"nth ]
```
[Try it online!](https://tio.run/##LU7LCoJAFN37FQc/QNLZVQiCEm1aGK3CxaS3HMpxnLliEX27TY/NeXLgnGXNvZ0P@@1us0QnuY3qvjspLX2sagdHw0i6JvcrjbSOrE/Z4UpW0w3GEvPDWKUZw4RVEAzTE1lelB7KAqWXKIssx2s@IvyocG3IdiNLVr12KZRu6I5wIUSSCBEnX05E/Pci1Nyi8utGXRSnqOBPmt6RP2UQzW8 "Factor – Try It Online")
-9 bytes by using the string from corvus\_192's [Scala 2 answer](https://codegolf.stackexchange.com/a/256045/97916).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
<èāQ·Iā-0¢-
```
-7 bytes by porting [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/256126/52210), since I've been unable to find anything short myself.
`[1,2,3,4]` is the identity permutation. Outputs:
* `-2` for this identity permutation itself;
* `2` for the three members of \$K\_4\$;
* `-1` for the eight members of \$A\_4\$;
* `0` for the remaining twelve members of \$S\_4\$.
[Try it online](https://tio.run/##yy9OTMpM/f/f5vCKI42Bh7Z7HmnUNTi0SPf//2gjHUMdEx3jWAA) or [verify all test cases](https://tio.run/##LU67DcJADF0lSu1I2HclUhoWoLauAImCigIp0pVpGIARqNiAPmQSFjnsF3fPz@93u5/O10ub6lTHvvs9nl0/1kPbf9/rfFw@dZ2H3fIaGjVVZRJKlEshVSGmTMmgMYbFkN2mYPzZlWBdJ1C62y4g1zLcnpqBnGXkuHtL9J4UiRKN@MKDDVBCF9kpcpAXGznWYGH0IT36toVYGhyWlVL@).
**Explanation:**
```
< # Decrease each value in the (implicit) input-permutation by 1
è # 0-based index each into the (implicit) input-permutation
ā # Push a list in the range [1,length]: [1,2,3,4]
Q # Check if the two lists are equal
· # Double this check (2 or 0)
I # Push the input-permutation again: [z,y,x,w]
ā # Push list [1,2,3,4] again
- # Decrease the values at the same positions of the two lists: [z-1,y-2,x-3,w-4]
0¢ # Count how many 0s are in the list (how many item were already at the correct
# position)
- # Subtract this amount from the earlier doubled check
# (after which the result is output implicitly)
```
---
**Original straight-forward approach (18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)):**
```
{œIk•Lû¾hΔ>¬o∊Ì•sè
```
`"abcd"` is the identity permutation. Outputs:
* `1` for this identity permutation itself;
* `3` for the three members of \$K\_4\$;
* `2` for the eight members of \$A\_4\$;
* `0` for the remaining twelve members of \$S\_4\$.
[Try it online](https://tio.run/##yy9OTMpM/f@/@uhkz@xHDYt8Du8@tC/j3BS7Q2vyH3V0He4BihUfXvH/f1JiSjIA) or [verify all test cases](https://tio.run/##JY29CQJBFIRbOV58NXgN2MGxwfsRFIMLDg4WEyMRMVIrMDKwA8HgFlOL2EbWt2P0mJk38w0jy2ZVpjjFjpp8uDTUxbL7XOM27@/L9Jrf6@9tMT@HfDyls3tjepS29D2xqFFoexI2pZbUWPyYCsNmtarZpKaibPWYcv1lqUrFqjJWNIX13xQMumsYQOohBhQVL4LJYDgSc76AORCdC@UsCuEH).
**Explanation:**
```
{ # Sort the characters of the (implicit) input-permutation string
œ # Pop and get all its permutations
Ik # Pop and get the index of the input-permutation
•Lû¾hΔ>¬o∊Ì• # Push compressed integer 100220032002200230022003
s # Swap so the earlier index is at the top
è # Index it into the the earlier integer to get a digit
# (which is 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 `•Lû¾hΔ>¬o∊Ì•` is `100220032002200230022003`.
[Answer]
# [Scala 2](https://www.scala-lang.org/), ~~61~~ 60 bytes
```
s=>"033223312332232313322331"("abcd".permutations indexOf s)
```
Takes a permutation of "abcd" and returns an ascii digit by indexing into the given string.
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sODkxJ9FoweayxByFNKvgkqLMvHRbO-eMxCLbpaUlaboWN22Lbe2UDIyNjYyMjQ2NwLSRsSGUb6ykoZSYlJyipFeQWpRbWpJYkpmfV6yQmZeSWuGfplCsCTFkszUXVwHQ6BKNNA0loPJEJU2ozIIFEBoA)
[Answer]
# [Haskell](https://www.haskell.org), ~~89 8~~ 87 bytes
```
import Data.List
f s="033223312332232313322331"!!head(elemIndices s$permutations"abcd")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWNyMycwvyi0oUXBJLEvV8MotLuNIUim2VDIyNjYyMjQ2NwLSRsSGUb6ykqJiRmpiikZqTmuuZl5KZnFqsUKxSkFqUW1qSWJKZn1eslJiUnKKkCTF_e25iZp6CrUJBUWZeiYKKQpqCElA2UQkiC3MFAA)
A port of my [scala answer](https://codegolf.stackexchange.com/a/256045).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 91 bytes
```
s=>eval(`try{${s.slice(1)}}catch{3}`);bcd=0;adc=dab=cba=1;cdb=dbc=cad=dca=abd=bda=acb=bac=2
```
[Try it online!](https://tio.run/##jZLLasJgEIX3PoeQZKFoXYbxWZw5Ey8lmOIfBAl59vTQVVvOwlXgY/6Zc8mnP73gcfsaN/chu@VsS7Fj9/S@Po2P17Seyrb0N3T1vpln@IjrdJhPTRtI27WesPQwhNu@RYZlwOBpCTePtEh@ERYO@1gw3MvQd9t@uNTnunJuqZpm9RtXm@ov4Fzwzv85YvC0wEk172x16hXPnRYEDrpSmEaVNHpXmHEoxUxIYYb2lpGQ8XBpSn/yGG9Jf5CK6UM24jJSFiLTyNBpyAJYi5zGz0@wfAM "JavaScript (Node.js) – Try It Online")
Input a string with letter "a", "b", "c", "d". Output 0~3.
[Answer]
# [Python 3](https://docs.python.org/3/), 84 bytes
```
lambda s:locals().get(s[1:],3)
bcd=0
adc=dab=cba=1
cdb=dbc=cad=dca=abd=bda=acb=bac=2
```
[Try it online!](https://tio.run/##DcxBDoIwFATQfU/hjjYxRmBHMidRF/Png5pUILYbT185wHv7r762dWwL7i3zY85TmfIm5hLT5TnXWG799DiPKZgc10AXnAYZ0Qe5wU0QHS6C5jgOUAajMLT9@15rXGLHw3cptT8 "Python 3 – Try It Online")
Essentially a port of [tsh's JS answer](https://codegolf.stackexchange.com/a/256036).
[Answer]
# [Julia 1.0](http://julialang.org/), ~~26~~ 24 bytes
```
!s=962578>>2(s%530%13)&3
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/X7HY1tLMyNTcws7OSKNY1dTYQNXQWFPN@H9BUWZeSU6ehqKGiamZuaYmF0LA1MTcDEXAxNwUTcAUpOI/AA "Julia 1.0 – Try It Online")
Port of [Arnuald's JS answer](https://codegolf.stackexchange.com/a/256047/109916).
-2 thx to @Steffan
[Answer]
# [Python 3](https://docs.python.org/3/), 31 bytes
```
lambda s:962578>>2*(s%530%13)&3
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYytLMyNTcws7OSEujWNXU2EDV0FhTzfh/QVFmXolGmoaJqZm5piYXjGtqYm6GxDUxN0XhmoJk/wMA "Python 3 – Try It Online")
Port of [Arnuald's JS answer](https://codegolf.stackexchange.com/a/256047/109916).
[Answer]
# [Python 3](https://docs.python.org/3/), 159 bytes
```
lambda x,y:{'1032':1,'2301':1,'3210':1,'0231':2,'0312':2,'1203':2,'1320':2,'2013':2,'2130':2,'3021':2,'3102':2,'0123':0}.get(''.join(map(str,map(x.find,y))),3)
```
I couldn't really interpret the logic. So I went with an overkill approach.
[Try it online!](https://tio.run/##bYu9DoIwFEZ3n4LttklD7s9G4kAiL9DZBYMoRn6CHSDGZ6@lHXRguifn3G9a3X0cxLfHs3/W/aWps8WsxRsIhaEgAyxIEYQJIyBLMBxAiCMQoyQQxgiMlAyTJCPIaSWEaYXE4Qc/@e3qFED@GLtB9fWkXm42213ythsas2qtjWg/zd3gVKugPFUWTAa2Kk@g9eEv2Go32DDZD5v4Bf8F "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 105 bytes
```
def f(s):
bcd=0;adc=dab=cba=1;cdb=dbc=cad=dca=abd=bda=acb=bac=2
try:return eval(s[1:])
except:return 3
```
[Try it online!](https://tio.run/##dZDLCsIwEEX3/Yrs2i4Ea3eV@RJxMY8UBamlRtGvjxdFJANdtdxJMufc@ZVO16nP2eIYxubWDlUQNdru2ZSMhVSYur2akImSspEpE4uRGL4qJKy0q0JaXsMS032ZQnzwpbkduuHYViE@Nc7pN@rzvJyn1IxNzVhUt231DepN/fvFTLD@P0OgYCkCA9jabQZucZjBXgQCkTKAVbkQimUA35IA8mWAJlaRxAnhsjlG9xxec4zqCEDkWmInjpKchYm3cNWgKndCP9XnNw "Python 3 – Try It Online")
Port of [tsh's JS answer](https://codegolf.stackexchange.com/a/256036/114446). Input as a string with letters `a`, `b`, `c`, `d`. Output as a number, 0 to 3.
] |
[Question]
[
Given a PPCG User ID, output that user's current username.
# Examples
```
Input -> Output
61563 -> MD XF
2 -> Geoff Dalgas
12012 -> Dennis
foo ->
-3 ->
```
# Rules
* Input/output can be taken via any allowed means.
* The output must be the full username with proper capitalization and spacing, nothing more and nothing less.
* If the input is not a valid UserID, or the user does not exist, your program should output nothing or error output.
* Your program must work for any valid user, even one created after this challenge.
* Your program does not have to work for the Community user.
* Your program does not have to work for deleted users.
* URL shorteners are disallowed.
# Scoring
Shortest code in each language wins.
[Answer]
# Bash, ~~120~~ ~~112~~ ~~106~~ ~~102~~ ~~80~~ ~~76~~ 74 bytes
-8 bytes because `wget` is smart enough to redirect HTTP to HTTPS when necessary
-6 bytes thanks to another `sed` suggestion from Cows quack
-26 bytes thanks to Digital Trauma
-4 bytes thanks to Gilles - `codegolf.stackexchange.com/u/123` redirects
-2 bytes thanks to Digital Trauma's answer's `wget` flags
```
wget -qO- codegolf.stackexchange.com/u/$1|sed -nr 's/.*>User (.*) -.*/\1/p'
```
No TIO link since the TIO arenas can't access the internet.
Thanks to the answers [here](https://unix.stackexchange.com/q/383241/194482) and the people [in chat](https://chat.stackexchange.com/rooms/240/the-nineteenth-byte) for helping me with this. I used an approach similar to HyperNeutrino's.
1. `wget -qO- codegolf.stackexchange.com/users/$1` downloads the user's profile page and prints the file to STDOUT. `-q` does it quietly (no speed information).
2. `sed -nr 's/.*User (.*) -.*/\1/p'` searches for the first string `User<space>`, then prints up until it reaches the end of the name, found using `sed` magic.
---
Previous answer that I wrote more independently (102 bytes):
```
wget codegolf.stackexchange.com/users/$1 2>y
sed '6!d' <$1|cut -c 13-|cut -d '&' -f1|sed 's/.\{23\}$//'
```
1. `wget codegolf.stackexchange.com/users/$1 2>y` saves the user profile HTML to a file titled with their UserID and dumps STDERR to `y`.
2. `cat $1` pipes the file into the parts that cut away the useless HTML.
3. `sed '6!d'` (in the place of `head -6 | tail -1`) gets the sixth line by itself.
4. `cut -c 13-` strips away the first 13 characters, getting the username to start at the first character of the string.
5. `cut -d '&' -f1` cuts everything after the `&`. This relies on the fact that an ampersand is not allowed to be in a username, nor an HTML title.
Now the string is `<username> - Programming Puzzles`
6. `sed 's/.\{23\}$//'` was a [suggestion](https://chat.stackexchange.com/transcript/message/39160570#39160570) from cows quack to remove the last 15 bytes of a file. This gets the username by itself.
[Here's a full bash script.](https://gist.github.com/aaronryank/f2fc4a92db325bb49506cc8352a6e782/a0e6bc47d2c6b0188c3f5c8bcfbfd7f08913278d)
[Answer]
# Bash + GNU utilities, 66
* 3 bytes saved thanks to @Arnauld.
* 4 bytes saved thanks to @Gilles.
```
wget -qO- codegolf.stackexchange.com/u/$1|grep -Po '"User \K[^"]+'
```
Uses `-P`CRE regex flavour to do a `\K` [match start reset](http://www.pcre.org/original/doc/html/pcrepattern.html#resetmatchstart) for much shorter output filtering.
---
If your system already has `curl` installed, we can use @Gilles' suggestion:
# Bash + curl + GNU utilities, 64
```
curl -L codegolf.stackexchange.com/u/$1|grep -Po '"User \K[^"]+'
```
[Answer]
# Python 2 + requests, 108 bytes
```
from requests import*
t=get('http://codegolf.stackexchange.com/u/'+input()).text
print t[49:t.index('&')-23]
```
### note
once SE goes fully `https`, the `http` needs to be changed to `https`, which will make this 113 bytes.
The beginning of a user profile looks like this:
```
<!DOCTYPE html>
<html>
<head>
<title>User MD XF - Programming Puzzles & Code Golf Stack Exchange</title>
```
The username starts at index 49 and the ampersand occurs 23 characters to the right of where it ends ( `- Programming Puzzles`)
-3 bytes thanks to StepHen/Mego by removing the unused `re` import
-1 byte thanks to Uriel
-4 bytes thanks to Makonede
[Answer]
# JavaScript (ES6), ~~111~~ 75 bytes
Only works when run through the PPCG domain. Returns a `Promise` object containing the username.
```
i=>fetch("/users/"+i).then(r=>r.text()).then(t=>t.slice(44,t.search`&`-23))
```
* Thanks to [Downgoat](https://codegolf.stackexchange.com/users/40695/downgoat) for confirming that the alternative method I was toying with was valid, thus allowing me to save 36 bytes.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~35~~ 34 bytes
Doesn't work online because of internet restrictions.
### Code
```
’ƒËŠˆ.‚‹º.ŒŒ/†š/ÿ’.w'>¡4è5F¦}60F¨
```
### Explanation
The compressed string:
```
’ƒËŠˆ.‚‹º.ŒŒ/†š/ÿ’
```
pushes the following string:
```
codegolf.stackexchange.com/users/<input>
```
Whereas `<input>` is the user input. After this, we read all data using `.w` and do some string manipulation tricks on the data:
```
'>¡4è5F¦}60F¨
'>¡ # Split on '>' (Usernames aren't allowed to have '>' so we're safe)
4è # Take the 5th element (which is in the header of the HTML page)
5F¦} # Remove the first 5 characters, which is "User "
60F¨ # Remove the last 60 characters, which is:
" - Programming Puzzles & Code Golf Stack Exchange</title"
# Implicitly output the username
```
When run locally, I get the following output:
[](https://i.stack.imgur.com/t7Laq.png)
[Answer]
# [Cubically](//git.io/cubically) + Bash, ~~1654~~ ~~1336~~ 1231 bytes
-423 bytes thanks to TehPers
This needs three Cubically scripts (named `1`, `2` and `3`) and 1 bash script.
The Cubically scripts are *really* long because I haven't thought of a good way to implement loops yet.
Bash (84 bytes):
```
ln -s rubiks-lang /bin/r
r 1 <<<$1 2>y|xargs wget 2>y
cat $1|r 2 2>y|rev|r 3 2>y|rev
```
This pipes the first Cubically script into `wget`, then the saved file into the second Cubically script, then reverses that output, pipes it into the third Cubically script, then reverses it.
`1` (385 bytes):
```
+5/1+551@6:5+3/1+552@66:4/1+552@6:5+2/1+552@6:4/1+51@6:2/1+5@66:5+51@6:3/1+552@6:1/1+551@6:2/1+551@6:4/1+551@6:3/1+552@6:5+52@6:3/1+551@6:1/1+5@6:5+2/1+552@6:5+3/1+552@6:5+2/1+55@6:5+51@6:5+3/1+551@6:2/1+551@6:3/1+553@6:5+51@6:5/1+551@6:5+2/1+55@6:2/1+552@6:4/1+551@6:2/1+551@6:1/1+5@6:5+51@6:3/1+552@6:1/1+552@6:2/1+5@6:5+53@6:5+2/1+552@6:2/1+551@6:5+1/1+552@6:5+2/1+552@6:2/1+5@6$7%7
```
This prints `https://codegolf.stackexchange.com/users/`, then the first integer of input.
`2` (~~680~~ 505 bytes):
```
~7777777777777777777777777777777777777777777777777
F1R1
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
~7@7:5=7&6
```
This reads the unnecessary data from the saved file as input, then prints up until the ampersand in `Programming Puzzles & Code Golf`.
`~7@7` reads a character and prints it. `F1R1` and `:5=7` check if the input is the ampersand. `&6` exits if it is.
`~7@7:5=7&6` is repeated 45 times because there are 15 bytes of unnecessary data and a 30-byte max StackExchange username.
3 (~~505~~ ~~446~~ 342 bytes):
```
U3D1R3L1F3B1U1D3
~777777777777777777777777
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
~7-1=7&6@7
```
Very similar to the last script, this reads the first few unnecessary bytes, then `cat`s until EOF. This also works due to the max SE username.
[Answer]
# [Swift 3](https://github.com/apple/swift), 233 bytes
```
import Foundation;func f(i:String){let s=try!String(contentsOf:URL(string:"http://codegolf.stackexchange.com/users/"+i)!,encoding:.utf8);print(s[s.index(s.startIndex,offsetBy:44)...s.index(s.characters.index(of:"&")!,offsetBy:-24)])}
```
Sample runs:
```
f(i:"8478") // Martin Ender
f(i:"12012") // Dennis
f(i:"59487") // Mr. Xcoder
```
[Answer]
# [Python 2](https://docs.python.org/2/), 116 bytes
Just thought it's nice to have a standard library answer (that's actually quite decent in length).
```
from urllib import*
f=urlopen('http://codegolf.stackexchange.com/users/'+input()).read()
print f[49:f.index('&')-23]
```
When SE goes fully `https`, we need to add 1 more byte, switching `urlopen('http://...` with `urlopen('https://...`.
[Answer]
# [Stack Exchange Data Explorer](https://data.stackexchange.com), 47 bytes
```
SELECT DISPLAYNAME FROM USERS WHERE ID=##N##--N
```
[Try it online!](https://data.stackexchange.com/codegolf/query/707693/whats-my-name)
[Answer]
## PHP, 163 bytes
---
```
<?php $a=new DOMDocument;@$a->loadHTML(implode(0,file("http://codegolf.stackexchange.com/users/$argv[1]")));echo$a->getElementsByTagName('h2')->item(0)->nodeValue;
```
[Answer]
# Powershell, ~~165~~ ~~142~~ ~~137~~ 127 bytes
*~~23~~ ~~28~~ 38 bytes saved thanks to [AdmBorkBork](https://codegolf.stackexchange.com/users/42963/admborkbork)!*
Creates a file named `0` as a side effect.
```
((iwr"codegolf.stackexchange.com/u/$args").AllElements|?{$_.class-like"user-c*"})[1].innerhtml-match"(.+?) ?<|.+">0
$matches[1]
```
Works by going to the proper webpage, and selecting the "user-card-name" element, then extracting the proper text out of the innerhtml.
## Testing
```
PS C:\Users\Conor O'Brien\Documents\powershell> .\whats-my-name-137085.ps1 61563
MD XF
PS C:\Users\Conor O'Brien\Documents\powershell> .\whats-my-name-137085.ps1 2
Geoff Dalgas
PS C:\Users\Conor O'Brien\Documents\powershell> .\whats-my-name-137085.ps1 12012
Dennis
PS C:\Users\Conor O'Brien\Documents\powershell> .\whats-my-name-137085.ps1 foo
Invoke-WebRequest : current community chat Programming Puzzles & Code Golf
Programming Puzzles & Code Golf Meta your communities Sign up or log in to customize your list. more stack
exchange communities company blog Stack Exchange Inbox Reputation and Badges sign up log in tour help Tour
Start here for a quick overview of the site Help Center
Detailed answers to any questions you might have Meta
Discuss the workings and policies of this site About Us
Learn more about Stack Overflow the company Business
Learn more about hiring developers or posting ads with us
Programming Puzzles & Code Golf Questions Tags Users Badges Unanswered Ask Question
Page Not FoundWe're sorry, we couldn't find the page you requested.
Try searching for similar questions
Browse our recent questions
Browse our popular tags
If you feel something is missing that should be here, contact us.
about us tour help blog chat data legal privacy policy work here advertising info mobile contact us feedback
Technology Life / Arts Culture / Recreation Science Other
Stack Overflow
Server Fault
Super User
Web Applications
Ask Ubuntu
Webmasters
Game Development
TeX - LaTeX
Software Engineering
Unix & Linux
Ask Different (Apple)
WordPress Development
Geographic Information Systems
Electrical Engineering
Android Enthusiasts
Information Security
Database Administrators
Drupal Answers
SharePoint
User Experience
Mathematica
Salesforce
ExpressionEngine® Answers
Blender
Network Engineering
Cryptography
Code Review
Magento
Software Recommendations
Signal Processing
Emacs
Raspberry Pi
Programming Puzzles & Code Golf
Ethereum
Data Science
Arduino
more (26)
Photography
Science Fiction & Fantasy
Graphic Design
Movies & TV
Music: Practice & Theory
Worldbuilding
Seasoned Advice (cooking)
Home Improvement
Personal Finance & Money
Academia
Law
more (17)
English Language & Usage
Skeptics
Mi Yodeya (Judaism)
Travel
Christianity
English Language Learners
Japanese Language
Arqade (gaming)
Bicycles
Role-playing Games
Anime & Manga
Puzzling
Motor Vehicle Maintenance & Repair
more (32)
MathOverflow
Mathematics
Cross Validated (stats)
Theoretical Computer Science
Physics
Chemistry
Biology
Computer Science
Philosophy
more (10)
Meta Stack Exchange
Stack Apps
Area 51
Stack Overflow Talent
site design / logo © 2017 Stack Exchange Inc; user contributions licensed under cc by-sa 3.0 with attribution
required rev 2017.8.1.26652
At C:\Users\Conor O'Brien\Documents\powershell\whats-my-name-137085.ps1:1 char:3
+ ((Invoke-WebRequest -URI("codegolf.stackexchange.com/users/"+$args[0])).AllEleme ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], We
bException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Cannot index into a null array.
At C:\Users\Conor O'Brien\Documents\powershell\whats-my-name-137085.ps1:2 char:1
+ $matches[1]
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
PS C:\Users\Conor O'Brien\Documents\powershell> .\whats-my-name-137085.ps1 -3
Invoke-WebRequest : current community chat Programming Puzzles & Code Golf
Programming Puzzles & Code Golf Meta your communities Sign up or log in to customize your list. more stack
exchange communities company blog Stack Exchange Inbox Reputation and Badges sign up log in tour help Tour
Start here for a quick overview of the site Help Center
Detailed answers to any questions you might have Meta
Discuss the workings and policies of this site About Us
Learn more about Stack Overflow the company Business
Learn more about hiring developers or posting ads with us
Programming Puzzles & Code Golf Questions Tags Users Badges Unanswered Ask Question
Page Not FoundWe're sorry, we couldn't find the page you requested.
Try searching for similar questions
Browse our recent questions
Browse our popular tags
If you feel something is missing that should be here, contact us.
about us tour help blog chat data legal privacy policy work here advertising info mobile contact us feedback
Technology Life / Arts Culture / Recreation Science Other
Stack Overflow
Server Fault
Super User
Web Applications
Ask Ubuntu
Webmasters
Game Development
TeX - LaTeX
Software Engineering
Unix & Linux
Ask Different (Apple)
WordPress Development
Geographic Information Systems
Electrical Engineering
Android Enthusiasts
Information Security
Database Administrators
Drupal Answers
SharePoint
User Experience
Mathematica
Salesforce
ExpressionEngine® Answers
Blender
Network Engineering
Cryptography
Code Review
Magento
Software Recommendations
Signal Processing
Emacs
Raspberry Pi
Programming Puzzles & Code Golf
Ethereum
Data Science
Arduino
more (26)
Photography
Science Fiction & Fantasy
Graphic Design
Movies & TV
Music: Practice & Theory
Worldbuilding
Seasoned Advice (cooking)
Home Improvement
Personal Finance & Money
Academia
Law
more (17)
English Language & Usage
Skeptics
Mi Yodeya (Judaism)
Travel
Christianity
English Language Learners
Japanese Language
Arqade (gaming)
Bicycles
Role-playing Games
Anime & Manga
Puzzling
Motor Vehicle Maintenance & Repair
more (32)
MathOverflow
Mathematics
Cross Validated (stats)
Theoretical Computer Science
Physics
Chemistry
Biology
Computer Science
Philosophy
more (10)
Meta Stack Exchange
Stack Apps
Area 51
Stack Overflow Talent
site design / logo © 2017 Stack Exchange Inc; user contributions licensed under cc by-sa 3.0 with attribution
required rev 2017.8.1.26652
At C:\Users\Conor O'Brien\Documents\powershell\whats-my-name-137085.ps1:1 char:3
+ ((Invoke-WebRequest -URI("codegolf.stackexchange.com/users/"+$args[0])).AllEleme ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], We
bException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Cannot index into a null array.
At C:\Users\Conor O'Brien\Documents\powershell\whats-my-name-137085.ps1:2 char:1
+ $matches[1]
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
PS C:\Users\Conor O'Brien\Documents\powershell>
```
[Answer]
# [Python](https://docs.python.org/) + [`requests`](https://docs.python-requests.org), 126 bytes
```
lambda n:get('http://api.stackexchange.com/users/%d?site=codegolf'%n).json()['items'][0]['display_name']
from requests import*
```
Accessing the API is longer than reading the actual page apparently...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 37 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
A port of [HyperNeutrino's Python 2 answer](https://codegolf.stackexchange.com/a/137087/53748) - go give credit!
```
“3¬ẋṙẉṀḷo°ɓẏ8YyŒÇḣðk¦»;ŒGṾṫ51ṣ”&Ḣḣ-23
```
A monadic link taking a number and returning a list of characters; as a full program prints the result.
Note: not sure quite why the result of `ŒG` needs to be forced to become a string (done here with `Ṿ`) :/
### How?
```
“3¬ẋṙẉṀḷo°ɓẏ8YyŒÇḣðk¦» = compression of:
"code"+"golf"+"."+"stack"+"exchange"+".com/"+"user"+"s/"
```
codegolf.stackexchange.com/users/
```
“...»;ŒGṾṫ51ṣ”&Ḣḣ-23 - Main link: number, n
“...» - "codegolf.stackexchange.com/users/"
; - concatenate with n
ŒG - GET request (should be to string & looks like it on output)
Ṿ - uneval (force to a string - shrug)
ṫ51 - tail from index 51 (seems the ŒG result is quoted too, so 51 not 50)
ṣ”& - split on '&'
Ḣ - head (get the first chunk)
ḣ-23 - head to index -23 (discard the last 23 characters)
```
[Answer]
# Mathematica, 126 bytes
```
StringTake[#&@@StringCases[Import["https://codegolf.stackexchange.com/users/"<>ToString@#,"Text"],"r "~~ __ ~~" - P"],{3,-4}]&
```
**input**
>
> [67961]
>
>
>
**output**
>
> Jenny\_mathy
>
>
>
[Answer]
# [Stratos](https://github.com/okx-code/Stratos), 22 bytes
```
f"¹⁸s/%²"r"⁷s"@0s"³_⁴"
```
[Try it!](http://okx.sh/stratos/?code=f%22%C2%B9%E2%81%B8s%2F%25%C2%B2%22r%22%E2%81%B7s%22%400s%22%C2%B3_%E2%81%B4%22&input=2)
Explanation:
```
f"¹⁸s/%?" Read the data from the URL:
http://api.stackexchange.com/users/%?site=codegolf
where % is replaced with the input
r Get the JSON array named
"⁷s" items
@0 Get the 0th element
s"³_⁴" Get the string "display_name"
```
] |
[Question]
[
Given a positive square number as input. Output the number of values between the input and next highest square.
### Example
Input: 1
Output: 2
Reason: The numbers 2 and 3 are between 1 and 4, the next highest square
Input: 4
Output: 4
Reason: The numbers 5, 6, 7, 8 are between 4 and 9
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~38~~, 22 bytes
```
{([[]](({})))}{}([]<>)
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/v1ojOjo2VkOjulZTU7O2ulYjOtbGTvP/f0MzAA "Brain-Flak – Try It Online")
I'm *very* proud of this answer. IMO, one of my best brain-flak golfs.
## How does it work?
As many other users have pointed out, the answer is simply *sqrt(n) \* 2*. However, calculating the square root in brain-flak is very very nontrivial. Since we know the input will always be a square, we can optimize. So we write a loop that subtracts
```
1, 3, 5, 7, 9...
```
from the input, and track how many times it runs. Once it hits 0, the answer is simply the last number we subtracted minus one.
Originally, I had pushed a counter on to the other stack. However, we can use the main stack itself as a counter, by increasing the stack height.
```
#While TOS (top of stack, e.g. input) != 0:
{
#Push:
(
#The negative of the height of the stack (since we're subtracting)
[[]]
#Plus the TOS pushed twice. This is like incrementing a counter by two
(({}))
)
#Endwhile
}
#Pop one value off the main stack (or in other words, decrement our stack-counter)
{}
#And push the height of the stack onto the alternate stack
([]<>)
```
In python-y pseudocode, this is basically the following algorithm:
```
l = [input]
while l[-1] != 0: #While the back of the list is nonzero
old_len = len(l)
l.append(l[-1])
l.append(l[-1] - old_len)
l.pop()
print(len(l))
```
[Answer]
## Mathematica, 8 bytes
```
2Sqrt@#&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvvfKLiwqMRBWe1/moK@g4JGUGJeemq0oUFsnJGmgr6@QkBRZl7JfwA "Mathics – Try It Online") (Using Mathics.)
The difference between **n2** and **(n+1)2** is always **2n+1** but we just want the values between them excluding both ends, which is **2n**.
This can potentially be shortened to `2#^.5&` depending on precision requirements.
[Answer]
## [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
½Ḥ
```
[Try it online!](https://tio.run/##y0rNyan8///Q3oc7lvz//98SAA "Jelly – Try It Online")
Port of my Mathematica answer (take square root, then double). This is limited to inputs which can be represented exactly as a floating-point number. If that's an issue, the three-byte solution `ƽḤ` works for arbitrary squares (which Dennis posted first but then deleted).
[Answer]
# [Julia 0.5](http://julialang.org/), 8 bytes
```
!n=2n^.5
```
[Try it online!](https://tio.run/##DcVRCkBAFAXQb1ZxKUU9yjDKB1mIlGJqpEsy63@cn3OE069WNeFguFRW3fWA8EReC1pBL6g7gbGCpiviaLofz9flaWYCyhF/M1MBBQmLeOemHw "Julia 0.5 – Try It Online")
[Answer]
# dc, 5
```
?2*vp
```
[Try it online](https://tio.run/##S0oszvifll@kUJJaXJKcWJyqkJmnYKhgomBprZCSz6UABAVFmXklaQpKqsUKunYKSgoqMKVg2dTkjHyEkEKNQkqygm6qgvp/eyOtsoL/6lwp@Xmp/w).
---
Previously I misread the question. This version works for any positive integer input, not just perfect squares:
# dc, 12
```
?dv1+d*1-r-p
```
[Try it online](https://tio.run/##RYpBCoAgFAX3nuIhhVC4ENoFdRbz/8iNikqr7m4RRLOcmc2Wo@0xo3KpzhaGDzCYZlAUeEjZh7pD9gV6gUT3jW9ld8Rf4QI5aIZqK51mpMHorFNTgmLgdgM).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
*I missed the "input will be square" caveat, but this will work for all non-negative integers...* [Martin Ender already gave the 2 byte solution](https://codegolf.stackexchange.com/a/126684/53748).
```
½‘Ḟ²’_
```
A monadic link returning the count.
**[Try it online!](https://tio.run/##ARkA5v9qZWxsef//wr3igJjhuJ7CsuKAmV////80 "Jelly – Try It Online")**
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~5~~ 3 bytes
```
¬*2
```
[Try it online!](https://tio.run/##y0osKPn//9AaLaP//y0B "Japt – Try It Online")
Square root of the input, then multiply by 2.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 20 bytes
*Shout out to DJMcMayhem's amazing (albiet slightly longer) answer [here](https://codegolf.stackexchange.com/questions/126676/number-of-values-between-input-and-next-highest-square/126704#126704)*
```
{({}()[({}()())])}{}
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/v1qjulZDMxpMamhqxmrWVtf@/29oYgIA "Brain-Flak – Try It Online")
## Explanation
This code works by counting down from the square number by odd increments. Since every square is the sum of consecutive odd numbers this will reach 0 in n1/2 steps. The trick here is we actually keep track of our steps in an *even* number and use a static `()` to offset it to the appropriate odd number. Since the answer is 2n1/2, this even number will be our answer. So when we reach 0 we remove the zero and our answer is sitting there on the stack.
[Answer]
# Mathematica, 17 bytes
```
(Sqrt@#+1)^2-#-1&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvtfI7iwqMRBWdtQM85IV1nXUO1/QFFmXomCQ5qCgyEXgm3yHwA "Mathics – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~25~~ 10 bytes
```
@(n)2*n^.5
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI0/TSCsvTs/0f5qGoSZXmoaJ5n8A "Octave – Try It Online")
Saved 15 bytes by using Martin's much better approach. The range consists of `2*sqrt(n)` elements. The function does exactly that: Multiplies `2` with the root of the input.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
½‘R²Ṫ_‘
```
[Try it online!](https://tio.run/##y0rNyan8///Q3kcNM4IObXq4c1U8kPX//38TAA "Jelly – Try It Online")
Explanation:
```
½‘R²Ṫ_ Input: 40
½ Square root 6.32455532...
‘ Increment 7.32455532...
R Range [1, 2, 3, 4, 5, 6, 7]
² Square [1, 4, 9, 16, 25, 36, 49]
Ṫ Tail 49
_‘ Subtract input+1 8
```
[Answer]
# [Python 3](https://docs.python.org/3/), 16 bytes
```
lambda n:2*n**.5
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPykgrT0tLz/R/Wn6RQqZCZp6CoY6JFZcCEBQUZeaVaChV1yro2ilU1yrpAZXkJpZoZOoopGlkampq/gcA "Python 3 – Try It Online")
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), 2 bytes
```
√d
```
[Try it online!](https://tio.run/##y8/I/f//UceslP//TQA "Ohm – Try It Online")
[Answer]
## JavaScript ES6, 10 bytes
```
n=>n**.5*2
```
[Try it online!](https://vihan.org/p/tio/?l=javascript-node&p=y0ktUUizVciztcvT0tIz1TLi4krOzyvOz0nVy8lP10jTMNTUtEYTMgEK/QcA) `Math.sqrt` is pretty long which is why we use `**.5`
[Answer]
# TI-Basic, 3 bytes
```
2√(Ans
```
Simplest approach...
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
t·
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/5ND2//8tuQA "05AB1E – Try It Online")
Another port of Martin Ender's submission ...
[Answer]
# [Add++](https://github.com/SatansSon/AddPlusPlus), ~~22~~ 20 bytes
```
+?
_
S
+1
^2
-1
-G
O
```
[Try it online!](https://tio.run/##S0xJKSj4/1/bniueK07PlEvbkCvOiEvXkEvXncv//3@T/4YA "Add++ – Try It Online")
Do you want to know how it works? Well, fear not! I'm here to educate you!
```
+? Add the input to x (the accumulator)
_ Store the input in the input list
S Square root
+1 Add 1
^2 Square
-1 Subtract 1
-G Subtract the input
O Output as number
```
[Answer]
# MATL (~~8~~ 7 bytes)
I'm sure this can be reduced significantly (edit: thanks Luis), but a naive solution is:
```
X^QUG-q
```
[Try it online!](https://tio.run/##y00syfn/PyIuMNRdt/D/fyNTAA "MATL – Try It Online")
## Explanation:
```
X^ % Take the square root of the input (an integer)
QU % Square the next integer to find the next square
G- % Subtract the input to find the difference
q % Decrement solution by 1 to count only "in between" values.
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 9 bytes
```
n->2*n^.5
```
[Try it online!](https://tio.run/##K0gsytRNL/ifZvs/T9fOSCsvTs/0f0FRZl6JRpqGoabmfwA "Pari/GP – Try It Online")
[Answer]
# [PHP](https://php.net/), 44 bytes
```
<?=count(range($argn,(sqrt($argn)+1)**2))-2;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkomTNZW8HFLNNzi/NK9EoSsxLT9UAS@poFBcWlUDYmtqGmlpaRpqaukbW//9/zcvXTU5MzkgFAA "PHP – Try It Online")
[Answer]
## [Alice](https://github.com/m-ender/alice), 10 bytes
```
2/*<ER
o@i
```
[Try it online!](https://tio.run/##S8zJTE79/99IX8vGNYgr3yHz/39LAA "Alice – Try It Online")
### Explanation
Again, computes **2 sqrt(n)**. The layout saves two bytes over the standard solution:
```
/o
\i@/2RE2*
```
Breakdown of the code, excluding redirection of the IP:
```
2 Push 2 for later.
i Read all input.
i Try reading more input, pushes "".
2 Push 2.
R Negate to get -2.
E Implicitly discard the empty string and convert the input to an integer.
Then take the square root of the input. E is usually exponentiation, but
negative exponents are fairly useless in a language that only understands
integers, so negative exponents are interpreted as roots instead.
* Multiply the square root by 2.
o Output the result.
@ Terminate the program.
```
[Answer]
# [Go](https://golang.org/), 56 bytes
```
import."math"
func f(n float64)float64{return 2*Sqrt(n)}
```
[Try it online!](https://tio.run/##ZYxBCoNADEX3c4owq6QLoUV6jkJPEMTYoU7GhrgSzz5a666rz3883lDqxN2bhx4yJw0pT8UcomSP9XeamNlfMcisHQgqyFjY7y2du1jvsyncLs@POSqt9VC/PaQlAMBeax6W1EdFwSvRP2x3uNYN "Go – Try It Online")
[Answer]
# [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~19~~ 9 bytes
```
?sqr(:)*2
```
*Saved a bunch by copying @MartinEnder's approach.*
No TIO link for QBIC, unfortunately.
## Explanation
```
? PRINT
sqr( ) The square root of
: the input
*2 doubled
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 3 bytes
```
√2*
```
[Try it online!](https://tio.run/##S0wuKU3Myan8//9Rxywjrf//TQA "Actually – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~4~~ 3 bytes
Crossed out 4 is still 4 :c
```
t2*
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/xEjr/38TAA "05AB1E – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 21 bytes
```
.+
$*
(^1?|11\1)+
$1
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYtLI87QvsbQMMZQE8g15Pr/39DAAAA "Retina – Try It Online") Explanation: Works by taking the square root of the number based on @MartinEnder's triangular number solver. After matching the square number, `$1` is the difference between the square number and the previous square number, in unary. We want the next difference, but exclusive, which is just 1 more. To achieve this, we count the number of null strings in `$1`.
[Answer]
# T-SQL, 22 bytes
```
SELECT 2*SQRT(a)FROM t
```
Input is via a pre-existing table, [per our standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341).
[Answer]
# [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/) / JShell, 17 bytes
```
n->2*Math.sqrt(n)
```
[Try it online!](https://tio.run/##bVDBTsMwDL3nK3xM0RZpEyBNhZ0QEodx6RFxCGm6pqROSdyNCfXbS@jaqRLzIU6e/d6zU8mDXLpGY5V/bnpTN84TVBEULRkrMiURtU/Zv0rRoiLjULwgPY/3lLGm/bBGgbIyBNhJg/DDIMaIB5IU08GZHOpY5Rl5g/u3d5B@H5Kx@S9GZwhjfgTUxwnl2SmQroXBJL0wjqWxGvhIEKUMr/qb4ng8mQsP4me6a0k00Z8sciWt4j0ut@ubnaRShC9PHJN@MU0g8KI2M@3Y@byyZO7iU8MgPPukh6cB30KxgGgNOB/Oa2o9QiFk09gTn9brWNev4BY2sLqH9d0v "Java (OpenJDK 9) – Try It Online")
Note: This would require `import java.util.function.*;` to get `IntFunction<T>` in Java 8 or Java 9, but the `java.util.function` package is imported by default in JShell.
[Answer]
# Haskell, 9 bytes
```
(*2).sqrt
```
[Try it online](https://tio.run/##y0gszk7Nyfn/X0PLSFOvuLCo5H9uYmaegq1CZl5JalFicomCioKGkRZUDgA)
Input and output will be treated as Float values.
[Answer]
# Noether, 7 bytes
```
I.5^2*P
```
[**Try it here!**](https://beta-decay.github.io/noether?code=SS41XjIqUA)
Just the same as every other answer: outputs two times the square root.
] |
[Question]
[
You will be given a two-dimensional array and a number and you are asked to find whether the given matrix is [Toeplitz](https://en.wikipedia.org/wiki/Toeplitz_matrix) or not. A matrix is a Toeplitz matrix if every descending diagonal, going from left to right, has only one distinct element. That is, it should be in the form:

## Input Format:
You will be given a function which will take `two-dimensional` matrix as argument.
## Output Format:
Return `1` from the function if the matrix is **Toeplitz**, else return `-1`.
## Constraints:
```
3 < n,m < 10,000,000
```
where `n` is the number of rows while `m` will be the number of columns.
## Sample Test Case:
```
Sample Input :
4
5
6 7 8 9 2
4 6 7 8 9
1 4 6 7 8
0 1 4 6 7
Sample Output :
1
```
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
## Mathematica, 42 bytes
```
2Boole[#==ToeplitzMatrix[#&@@@#,#&@@#]]-1&
```
Mathematica doesn't have a built-in to check whether something is a Toeplitz matrix, but it does have a built-in to generate one. So we generate one from the first column (`#&@@@#`) and the first row (`#&@@#`) of the input and check whether it's equal to the input. To convert the `True`/`False` result to `1`/`-1` we use `Boole` (to give `1` or `0`) and then simply transform the result with `2x-1`.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 30 bytes
I'm assuming I don't have to handle 1,000,000x1,000,000 matrices as it says in the challenge. This works for matrices that don't exceed the available memory (less than 1 TB in my case).
```
@(x)x==toeplitz(x(:,1),x(1,:))
```
[Try it online!](https://tio.run/nexus/octave#S7PV09P776BRoVlha1uSn1qQk1lSpVGhYaVjqKlToWGoY6Wp@b9CwTbaTMFcwULBUsGIy0QByuYyVICyuQwUoOxYay6uzDSFNKCBOgopmcUFGuohRaWp6prWCqk5xalQIbdEIFtdUyc1L@U/AA "Octave – TIO Nexus")
This takes a matrix `x` as input and creates a Toeplitz matrix based on the values on the first column, and the first row. It will then check each element of the matrices for equality. IF all elements are equal then the input is a Toeplitz matrix.
The output will be a matrix of the same dimensions as the input. If there are any zeros in the output then that's considered falsy be Octave.
**Edit:**
Just noticed the strict output format:
This works for 41 bytes. It might be possible to golf off a byte or two from this version, but I hope the output rules will be relaxed a bit.
```
@(x)2*(0||(x==toeplitz(x(:,1),x(1,:))))-1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ŒDE€Ạ
```
[Try it online!](https://tio.run/nexus/jelly#@390kovro6Y1D3ct@P//f3S0mY65joWOpY5RrA6XQrSJDpQP5hnqQPlgnoEOlB8bCwA "Jelly – TIO Nexus")
Following the definition [here](https://en.wikipedia.org/wiki/Toeplitz_matrix).
```
ŒDE€Ạ
ŒD all diagonals
€ for each diagonal ...
E all elements are equal
Ạ all diagonal return true
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
Œ2ùvy`¦s¨QP
```
[Try it online!](https://tio.run/nexus/05ab1e#@390ktHhnWWVCYeWFR9aERjw/390tJmOuY6FjqWOUayOQrSJDpQL4hjqQLkgjoEOlBsbCwA "05AB1E – TIO Nexus")
**Explanation**
```
Œ # get all sublists of input
2ù # keep only those of length 2
v # for each such pair
y` # split to separate lists
¦ # remove the first element of the second list
s¨ # remove the last element of the first list
Q # compare for equality
P # product of stack
```
[Answer]
# [Haskell](https://www.haskell.org/), 43 bytes
```
f(a:b:t)|init a==tail b=f$b:t|1>0= -1
f _=1
```
[Try it online!](https://tio.run/nexus/haskell#Rcq9CsIwEADgvU9xQ4cWrqUR8SeQ7s6OIchVk3qgEeKBS989li5ZP743cTQcxSe6S/19fn596Jvk6aH1VRLHuRutvaxh9sm5NoeG9KSlXTiyABkjxC@YTKhXXdQ4GOhUFeBmVM7WHhCOCCeEM8LOYQV2j1BwE4VQcJMBoaBzfw "Haskell – TIO Nexus")
[Answer]
## Mathematica, 94 bytes
```
l=Length;If[l@Flatten[Union/@Table[#~Diagonal~k,{k,-l@#+1,l@#[[1]]-1}]]==l@#+l@#[[1]]-1,1,-1]&
```
input
>
> {{6, 7, 8, 9, 2}, {4, 6, 7, 8, 9}, {1, 4, 6, 7, 8}, {0, 1, 4, 6,
> 7}}
>
>
>
another one based on **Stewie Griffin**'s algorithm
## Mathematica, 44 bytes
```
If[#==#[[;;,1]]~ToeplitzMatrix~#[[1]],1,-1]&
```
[Answer]
# Java 7, ~~239~~ ~~233~~ ~~220~~ 113 bytes
```
int c(int[][]a){for(int i=a.length,j;i-->1;)for(j=a[0].length;j-->1;)if(a[i][j]!=a[i-1][j-1])return -1;return 1;}
```
-107 bytes after a tip of using a more efficient algorithm thanks to *@Neil*.
**Explanation:**
[Try it here.](https://tio.run/nexus/java-openjdk#pY7BasMwDIbvfQrtZoMS6jG6DdO9wU49Gh@8NO0UUqckykoJfvZMzcx2HtVB@sUHH3/VhmGA90BxmikyVEq2884HPR26/vYBbUPZ1vHIn9hYKoo3Y/WNNdvg1j4j2/wAOqjgyLvGPwimwkiUpfuaxz5CYWxOxqYZ4Dx@tFTBwIHlfHW0h5OUUTvuKR6dB@mxApnddeD6VHYjl2dB3EYV68vSXOmyWp5cffrN0waf8QVf8THhYvnP/FmeMHvushjMnrssa8yelLS2IkqrNH8D)
```
int c(int[][]a){ // Method with integer-matrix parameter and integer return-type
for(int i=a.length,j;i-->1;) // Loop over the rows (excluding the first)
for(j=a[0].length;j-->1;) // Loop over the columns (excluding the first)
if(a[i][j]!=a[i-1][j-1]) // If the current cell doesn't equal the one top-left of it:
return -1; // Return -1
// End of columns loop (implicit / single-line body)
// End of rows loop (implicit / single-line body)
return 1; // Return 1
} // End of method
```
[Answer]
# [Haskell](https://www.haskell.org/), 51 bytes
`t` takes a list of lists of integers and returns an integer.
```
t m=1-sum[2|or$zipWith((.init).(/=).tail)=<<tail$m]
```
[Try it online!](https://tio.run/nexus/haskell#RcqxCsIwEIDh3ae4IUMC12iLaC2Nu7ODQ8gQNLQHJpX0RBDfvWqXTj98/NFTMpQ4ZH9lMfbDS7OWOfhb05w5U@qKo7Wn39CF7JyaGKIpi/EZbfUZsnjT40LcS6kpESst10Zp9nRXpm3/FdFNk7U7hD1CjXBAqByuwG4RFpylRFhwlg3Cgs59AQ "Haskell – TIO Nexus")
This could have been 39 or 38 bytes with truthy/falsy output.
The idea to use `init` was inspired by Emigna's 05AB1E answer, which uses a very similar method; before that I used a nested zipping.
# How it works
* `zipWith((.init).(/=).tail)=<<tail` is a point-free form of
`\m->zipWith(\x y->tail x/=init y)(tail m)m`.
* This combines each consecutive pair of rows of `m`, checking if the first with first element removed is different from the second with second element removed.
* The `or` then combines the checks for all pairs of rows.
* `1-sum[2|...]` converts the output format.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~6~~ 4 bytes
```
ΛE∂↔
```
[Try it online!](https://tio.run/##yygtzv7//9xs10cdTY/apvz//z862kzHXMdCx1LHKFYn2kQHygOyDXWgPCDbQAfKi40FAA "Husk – Try It Online")
[-2 bytes](https://chat.stackexchange.com/transcript/message/55721763#55721763) from Zgarb.
My first Husk answer! (Language Of The Month)
Takes matrix as command line argument.
Returns length of longest diagonal for true, and 0 otherwise.
## Explanation
```
ΛE∂↔
↔ reverse the rows
∂ get antidiagonals
Λ Check if all elements satisfy condition:
E Are all the elements equal?
```
[Answer]
## JavaScript (ES6), ~~65~~ 54 bytes
```
a=>a.some((b,i)=>i--&&b.some((c,j)=>c-a[i][j-1]))?-1:1
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 54 bytes
```
->a,b,m{m.reduce{|x,y|x[0..-2]==y[1,b]?y:[]}.size<=>1}
```
Exactly as specified, can be golfed more if flexible input/output is accepted.
## Explanation:
Iterate on the matrix, and compare each line with the line above, shifted by one to the right. If they are different, use an empty array for the next iteration. At the end, return -1 if the final array is empty, or 1 if it's at least 2 elements (since the smallest possible matrix is 3x3, this is true if all comparisons return true)
[Try it online!](https://tio.run/nexus/ruby#S7P9r2uXqJOkk1udq1eUmlKanFpdU6FTWVMRbaCnp2sUa2tbGW2okxRrX2kVHVurV5xZlWpja2dY@79AIS3aWMdYJxoobaRjHKsD5AFZQBrI0zGMjY3lwq/EBKjkPwA "Ruby – TIO Nexus")
[Answer]
# PHP, 70 bytes
```
<?=!preg_match('/\[([\d,]+?),\d+\],\[\d+,(?!\1)/',json_encode($_GET));
```
[Answer]
# Python, 108
```
r=range
f=lambda x,n,m:all([len(set([x[i][j] for i in r(n) for j in r(m) if j-i==k]))==1 for k in r(1-n,m)])
```
Not efficient at all since it touches every element `n+m` times while filtering for diagonals. Then checks if there are more than one unique element per diagonal.
[Answer]
# Axiom, 121 bytes
```
f(m)==(r:=nrows(m);c:=ncols(m);for i in 1..r-1 repeat for j in 1..c-1 repeat if m(i,j)~=m(i+1,j+1)then return false;true)
```
m has to be a Matrix of some element that allow ~=; ungolf it
```
f m ==
r := nrows(m)
c := ncols(m)
for i in 1..(r - 1) repeat
for j in 1..(c - 1) repeat
if m(i,j)~=m(i + 1,j + 1) then return(false)
true
```
[Answer]
# [R](https://www.r-project.org/), 48 bytes
```
pryr::f(all(x[-1,-1]==x[-nrow(x),-ncol(x)])*2-1)
```
[Try it online!](https://tio.run/##LclNCoAgEEDhfSeZiRloIvqBPEm0CEEISkGM9PQm2O7jPZ/Nytk8VofTWYh4XBfEjYVYdqWKrHdv6cRWu7Jwx7ZnyWnl@wj@jKBhpIGEOpqoav61/OqrkAZsUmMgYf4A "R – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 148 bytes
```
m(1`\d+
$*#
1`#\n\d+\n
@
+`(#*)#@([^#\n]*(#*)\n)(.*)$
$1# $2$1@$4 #$3
@
+`##
# #
+(+s`^(\d+)\b(.*)^\1\b
$1$2#
s`.*^\d.*^\d.*
-1
)%`^[^- ]+ ?
\s+
1
```
[Try it online!](https://tio.run/nexus/retina#LYxLCoRADET3dYpAMtAflInT81uN9zA2jbgdN94fbaE3xavwUsffabE1QgJDC9tWi20YEYvj4Hl0U67XOVzNNu/64AWiTDKIjpKI5VH16jODiRFd3Et2dcfbcunZ1Jb6IgNjL33ItrZAp/C3kqfc0RzpB9geoceR8MSL3vShLw1I1BhKjXGnxic "Retina – TIO Nexus")
An N×M input matrix
```
6 7 8 9 2 0
4 6 7 8 9 2
1 4 6 7 8 9
0 1 4 6 7 8
```
is first converted to an N×(N+M-1) matrix by aligning the diagonals this way:
```
# # # 6 7 8 9 2 0
# # 4 6 7 8 9 2 #
# 1 4 6 7 8 9 # #
0 1 4 6 7 8 # # #
```
and then the first column is repeatedly checked to contain a single unique number, and removed if this is so. The matrix is Toeplitz iff the output is blank.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
```
T&Xd"@Xz&=v
```
[Try it online!](https://tio.run/##y00syfmf8D9ELSJFySGiSs227H8sl716SVFpSUalOletelpiTnEqkBXrEvI/2kzBXMFCwVLByNpEAcq2NlSAsq0NFKDsWK5oXUOilaqnpaaqWyuop2UqgKl8CFWaqw6SLMlPLcjJLKkCiSVCOSB2MZQDYmdDOeqxAA "MATL – Try It Online")
The straightforward "construct a Toeplitz matrix and check against it" method, that the top few answers use, somehow felt boring to me (and [it looks like](https://matl.suever.net/?code=t1Z%29y1Y%29%26YT%3D&inputs=%5B%27mice%27%3B%27emic%27%3B%27nemi%27%5D&version=20.9.1) that would be 1 byte longer anyway). So I went for the "check each diagonal only contains one unique value" method.
`T&Xd` - Extract the diagonals of the input and create a new matrix with them as columns (padding with zeros as needed)
`"` - iterate through the columns of that
`@Xz` - push the iteration variable (the current column), and remove (padding) zeros from it
`&=` - [broadcast equality check](https://codegolf.stackexchange.com/a/95057/8774) - this creates a matrix with all 1s (truthy) if all the remaining values are equal to one another, otherwise the matrix contains some 0s which is falsy
`v` - concatenate result values together, to create one final result vector which is either truthy (all 1s) or falsey (some 0s)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
I *think* this is right.
```
äÏÅeX¯JÃ×
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=5M/FZVivSsPX&input=W1s2LDcsOCw5LDJdLCBbNCw2LDcsOCw5XSwgWzEsNCw2LDcsOF0sIFswLDEsNCw2LDddXQ)
```
äÏÅeX¯JÃ× :Implicit input of 2D-array
ä :Consecutive pairs
Ï :Reduced by
Å : Slice the first element off the second array
e : Check for equality with
X : First array
¯J : Slice off the last element
à :End reduce
× :Reduce by multiplication
```
[Answer]
## Clojure, 94 bytes
```
#(if(=(+ %2 %3 -1)(count(set(for[Z[zipmap][i r](Z(range)%)[j v](Z(range)r)][(- i j)v]))))1 -1)
```
] |
[Question]
[
A Tiefling is a character race, from Dungeons and Dragons, that has this list of possible traits:
* small horns
* fangs or sharp teeth
* a forked tongue
* catlike eyes
* six fingers on each hand
* goat-like legs
* cloven hoofs
* a forked tail
* leathery or scaly skin
* red or dark blue skin
* cast no shadow or reflection
* exude a smell of brimstone.
---
Given a list of Tiefling traits as input, randomly pick 1d4 + 1 (**uniform distribution from 2-5**) traits from that list and output them.
This challenge uses the [standard definition of random](https://codegolf.meta.stackexchange.com/a/1325/9534), and the number and trait selection from the list must *separately* conform to definition 1 from [here](https://codegolf.meta.stackexchange.com/a/10909/9534):
* All possible [numbers] should be produced with the same probability;
* All possible [traits] should be produced with the same probability;
You are allowed to pick randomly from the list by first shuffling it and taking the top 1d4+1 traits, so long as the shuffle does not favour any item in the list. Repeat selections of the same trait are not allowed.
Here is a non-golfed implementation in Javascript:
```
const dice = (n, s, a, doSum) => {
const die = () => Math.floor(Math.random() * s) + 1;
const dieResults = Array.from(Array(n)).map(each => {
return die();
});
const sum = dieResults.reduce((sum, curr) => sum + curr + a, 0);
// logging not required here
console.log(`rolled '${dieResults.join(` + ${a}, `)} + ${a}${doSum ? ` = ${sum}`:''}'`);
return doSum ? dieResults.reduce((sum, curr) => sum + curr + a, 0) : dieResults.map(each => each + a);
};
const shuffleSlice = (num, array) => array
.map(value => ({
value,
sort: Math.random()
}))
.sort((a, b) => a.sort - b.sort)
.map(({
value
}) => value).slice(0, num);
// you can take the list as a string or an actual list
const tieflingTraits = "small horns; fangs or sharp teeth; a forked tongue; catlike eyes; six fingers on each hand; goat-like legs; cloven hoofs; a forked tail; leathery or scaly skin; red or dark blue skin; cast no shadow or reflection; exude a smell of brimstone".split(/;\s+/);
// calling the function
console.log(shuffleSlice(dice(1, 4, 1, true), tieflingTraits))
// outputs like
// ['goat-like legs', 'cast no shadow or reflection', 'a forked tongue']
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest in bytes wins.
[Answer]
# [Factor](https://factorcode.org/) + `dice`, 22 bytes
```
[ ROLL: 1d4+1 sample ]
```
[Try it online!](https://tio.run/##ZVDRSsQwEHzvVwz3KgoHPp0fIMKhoPgkPuwlmyY0zZZNqlfEb6/p2YLgPs7M7s6MI1NE59eXh8f7A2wwjI41cYRSstJjUC5lGjSkgrum@WpQZ5d7ihFeNOXdL@IotRmiyJ50QGEufqUITrRjiyKpHXlFDZUYOgZPvN3I4QwXUstaLyUwGQ9fbax0K1SuLzuR223HRPngVK2Iy//@UYgrFpmKZ50uDg3FCbkLaSW1aituSTuc4sh/OUO5IMkSy8rnIlN2kU0Jskn4PFoGIfdcSxGHk4Y@17A16nczv@H56Xg8YG9vr/bI1A@R8T6bpcGb@Qc "Factor – Try It Online")
A quotation (anonymous function) that takes a list of strings as input and outputs a uniformly random sample of 1d4+1 items of said list.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~ 7 ~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ẋṫ4XN¤
```
A monadic Link that accepts a list of lists of characters and yields another with 2-5 random entries.
**[Try it online!](https://tio.run/##TU@7UQQxDM1dhRogow5iCHW2/LnVSozkhdsKmKEOMtJLgAwq2UoW35GQvv87EvO679vn6/bxfnt/9/22b1/nn5eHffcZmaGqiYeMUhzUwCvaI3SiXgNCVpsoQVcpC4WIndtEQCt58HaC3KSQDZ8AYaxQUVIoiv3mqmMqHiLrE8mo0ez/ErFxYMJeydZrb0RewacmwQY/kIQ2wYEX@kMjegfRy8CkzxeBUWaKvakEOi2JAMHncRc0w8Ha7GM2/QI "Jelly – Try It Online")**
### How?
```
Ẋṫ4XN¤ - Link: list, A
Ẋ - get a shuffled copy of A
¤ - nilad followed by link(s) as a nilad:
4 - four
X - random choice from 1-4
N - negate
·π´ - tail (the shuffled copy) from (that) 1-indexed index
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 22 bytes
```
?O`
,3G`¶
?&0A`¶
?&0A`
```
[Try it online!](https://tio.run/##TU9LTgMxDN37FF6xAgnEASpWLLlC3czLJJrURnYGOhfjAFxsSIuEWFl6fl9HrypP@354O9L98@vx@4sOd48vf3ff4yytcTHXoCw6B5tzFPF37kAvJJzNF0zcTecVlKS3uoCxISjqhXPVGT50ypBUuIhONJv0hxuvYQ5KzT6gI8Zy/HOU2qhBeoFvt9wkbeNYqpKP/0Am8YVPbcUvmiQ6q10LTvZ5JThyQ@rVlHBZJ7BwnDEmWeaT13OM2vgB "Retina – Try It Online") Explanation:
```
?O`
```
Uniformly shuffle the input.
```
,3G`¶
```
Keep the first four (0-indexed) newline characters, which also ends up keeping the first five lines.
```
?&0A`¶
```
50% chance to delete the first newline character including the first two lines.
```
?&0A`
```
50% chance to delete the first line.
[Answer]
# [Raku](https://raku.org/), 18 bytes
```
*.pick(pick 2..5:)
```
[Try it online!](https://tio.run/##TY/BTsQwDETv@Yo5sS3SVoAEB1Yr8SVI3tRpQlOnilPYSvvvJV0uXHyYefaMZ87xbZtWPDict8duDnZs9oGXrnt9b7cTlFa45gO32xkxCGvbfaUgzeGEQwuXMj6fnzadKEb4lEWNIxkU1VBPeUZhLt7Qjo7coyQZFjaWSgwjg1dWo@EKF2TgXPcETNbDk/RmSFSOdy7yoMbG9M1SY5LTfxcpRBOZiue83nMtxRU6BjG5@lXpKY@4xIX/VEtaIGkv2KefHcjsItsSkhi@Lj2DoBPXl5LDJYdJa23@BQ "Perl 6 – Try It Online")
`pick 2..5:` picks a random number from 2 to 5, then gives that as an argument to the `pick` method on the input list, randomly choosing that many elements from it.
[Answer]
# [Goruby](https://codegolf.stackexchange.com/questions/363/tips-for-golfing-in-ruby/9289?r=SearchResults&s=1%7C19.2465#9289), 16 bytes
```
->a{a.s rn 2..5}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=pVbdbts2FMZu_RSnThpLri0n2woMQb20HdJtNyvQAruY4RmURNlsKFIgKTe25bzIbnKxXQ7Y8_RpdkhK8k_TosNyEdLnj-fnO-fojz9VGa_uP3T-PoEfpb1DoSgvUwpDWBhT6MvRaM7MooyjROYjK-H_xVzGo5xoQ9VoLnk2q_UiFXcSTrSG1_E7mpgOwPPnTmBB9ALGsNl2kLakKpaaDuD01-s3L1-_vUZOcx2AYBxlUppBTs1CprOcac3EHPIB9MkAzmJkAxhU2jM-gQnyNeVZ5DyYwhSqagw5MckCtWfemA7ycHI-dRZYhkbOzsDbA5jNNBXpbBYY-1AIm6pP1FxXNRsgjmImUjQW0SXhQbdQMtlUzgX3TEoMqeD0Dj07JMK2G0YJ4Tw4vQvtu6d3e0Ydwz0V1tStOynXtCYYuDpyz-YhhEvQZUGVFxdpp_m_l9g62Z0mp8f50CjT6w0gx9N6QmJOG6b3RyFn9PvJRkdGznQ012UcjKJRuOkGUf8q7MITeEPn9LaIqE5IQYPTs3C7HTndPJorWgQqjLRUZoYQSyVUrMkp8yadU1YI1U2pqKUUwdmlZmsawrNnwI4irIPx5ZZCmxYkySfAkQy-ABvJAJw1IoxuYWKAiBQURceEZ8_m1ASmTg5hmsIvJKfXSkk1gG4pmGCGEY7Op609ONkk2-7ApZiq4CI8imSB6aFomsSxoktGDJPiC2pjJXxd3E9ZqllC0KExBFcvoujqtxDGYxTZw3weIYjpbeDVVnkDuouoLIxEssv6plpXaBkLKlyx7QRA9Hu_1qEt0KYyCsPc9YegtwZKwSkOgODgfSeIPthfrZOtnuNC38ba0up8exZ7ALeOg6mxdXKRWNO6aaCPOshPlQcwdJxXn9YWK9aqH2bYgrUIAr5QbElMq4SNuFOvjdcizTuLgNhq_oTljO3lPV4Se3nU8xUoSqOhe7IhW8q5HCBg4q1UPHXAOfQ5CywiLs7PvWZduRyLJiprpveKrdcvy_W605uwsej3v308vHg6YE8uvplWldjurCFKiQZNVu75xn4qZ-8XjPvcnYO7w4pRfpQ7lCuFqTN7Du5-IOdkfR5fKEVW7YuSpzNXtBq6nuoo7yQT-4qvCFbxB3v9pLb1pe2Bbvfjx38WBieUag1QkizAsJxaFSYSt_SuRZlTZbGwr_oWgSbmreYIdMGZ6exeJR4xlhr0ent9HbiQsdvsAEh2WBnCA6THbGJtqRVCnghd4MiGjBNjqGjORzhM8oIgEuvzEaCDMsEZZI9pGNmwNpU16pvSrinouqt19mRjWVu_a-wC4TK5adrforONxvafLrkdoyT6rBpOd04SGpDI1q2hYsN6A7smaurv_-qCuOHgJbGNscNqLYzuJugl_Z5dcTXN4cJrY18_8EJdPyPV3hRxIn6bOAftqKAouLNEj6QbjhsU7rQZ3O5j4uClhyH5n4o_uazTOMXRMrm0Jv5nNW0lP1e4Nqp9_9Gzwg66-mx5Db2J8aA9Vnksmw-23ZfM4Wv2Q8ktfkWTZdUiJ1lG7UeNnbj2u-YhT_f7ORv_VZps-N0_w-_JhkQacEl8HUVPt5784auhm6PZZIJaXZ2jR4C7VejuwBIyIuYYrMKFS1QBhmKCPIdAJtUNbmwjxbyknpgQw9kNBbqitQHNbiHDgUAVmhF-kCzwA8Fz55KYodPgdF5rJFwusYkXUmb6-CnCuCdxSsyCYvdb1zCNK9A3THieQkkkp0TdQMxLusfCNWpASBtNKt9bKUUzjrXCLe0l6K0dbQR0jlsFZAaxYrnGGG2E06nP2v29P_8F)
# [Ruby](https://www.ruby-lang.org/), 23 bytes
```
->a{a.sample rand 2..5}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZBBTsQwDEXFllNYs6ZdICGxgYuMZuGmThM1jSs7GaZCnIRNheAM3IXTkE66QKwi_fft_O_3T8ndsn7Yp6-cbPP43TzjK7aK0xwIBGMP92378Fbpz00z56Rgj8dbgINOGAI4lqiHu02wGAcFFlCHMkMiSq4SBMsyUg-J45CpigZT8CMBLbQvUH8B6-NAUtZEIDQOXAlR6cCYmutEoGGfMIHPFEsItvr_K_ShSoEwOZLlGs1gWEBHHyuT4ixyjzJCFzL9QQY1QeStTc8vm0vIBjLJ8-6gS-4JEHSicgm20ImftHTcGp5O9WrrWt9f)
[Answer]
# Excel (ms365), 52 bytes
```
=TAKE(SORTBY(A1:A12,RANDARRAY(12)),RANDBETWEEN(2,5))
```
[](https://i.stack.imgur.com/w9xNg.png)
[Answer]
# [Python](https://www.python.org) (Full program), 58 bytes
* -1 byte thanks to @The Fifth Marshal
```
from random import*;print(sample([*open(0)],randint(2,5)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TU9LTsQwDN3nFF62oxkJISEhOApi4UmdJmpqV3Y6TM_Cphu40xyAe5BOWbCy9N7z-3x-T0uJwuv6NZdwer69BJURFLmrJ42TaDm8Tpq4NIbjlKl5O8hE3Dy078dNtjGPx6e2bXeHP6P19mMj5gxRlM0F5N5AFCyiTlCISnQIQXSgDopwP5PzWHIaCGghc5auEBL3pPWPgdBHiDXP9YLldNdl6s35LBfiGiPB_jliyi4Tlki63HM95gVsSOy08hXpUAc455l21KMVYNkKdvKxCZRCJl-SsKPr3BEg2Eh1kgQ4axqt1qZ97S8)
# [Python](https://www.python.org) (Function), 51 bytes
* -7 bytes thanks to @Jonathan Allan
```
lambda a:sample(a,randint(2,5))
from random import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TU9LTsMwEN37FLNrglqEQEiIqiehLKbJOLZij60ZB5qzsKmE4E49APfAaVmwGunN-35857m4xKdPu9t_TcVuns4PAeOhR8BnxZgDNbgW5N5zae7Xj21rrKQIC1SPjzlJufmTbj1n2MFL8Ey3okV8blZ7XrVgk8CCgmdImbi5a19NlsXUNlXVtleL0_lHI4YALgmrsciDQtWqQ8lQiIozuLiN1ENJPExkOizBjwQ0kxr1R7CeB5KqYyDsHLja1QwJy-bCCzSo6UJ6I64xyeo_R_TBBMLiSOZLbodhBh09G6n_ivQoIxzCRFe0Qy3AaSnYp_eFIGQDdcUnNnScegIEjVQnJQsH8VFrbbqu_QU)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~6~~ ~~5~~ 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ö¬o2+4ö
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9qxvMis09g&input=WyJzbWFsbCBob3JucyIsImZhbmdzIG9yIHNoYXJwIHRlZXRoIiwiYSBmb3JrZWQgdG9uZ3VlIiwiY2F0bGlrZSBleWVzIiwic2l4IGZpbmdlcnMgb24gZWFjaCBoYW5kIiwiZ29hdC1saWtlIGxlZ3MiLCJjbG92ZW4gaG9vZnMiLCJhIGZvcmtlZCB0YWlsIiwibGVhdGhlcnkgb3Igc2NhbHkgc2tpbiIsInJlZCBvciBkYXJrIGJsdWUgc2tpbiIsImNhc3Qgbm8gc2hhZG93IG9yIHJlZmxlY3Rpb24iLCJleHVkZSBhIHNtZWxsIG9mIGJyaW1zdG9uZSJdLVI)
```
ö¬o2+4ö :Implicit input of array
ö¬ :Random permutation
o :Pop & return this many elements
2+ : Two plus
4ö : Random integer in range [0,4)
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + [coreutils](https://www.gnu.org/software/coreutils/), 20
```
shuf -n$[RANDOM%4+2]
```
[Try it online!](https://tio.run/##TY@xTgNBDER7f4ULqFAaxA9EogUkWpTCt@u9XZ3PRvYeyX192ISG9s3YMzNR1Os16lbwoA9fn8f314@3x5en59OgK4lgNdeAQjoHmmNU8m/szL0CYTFfOGM3nTeGRF3awsg7B0S7YGk6s487RaZUsZJmmI364e4TngOS2A/riLES/z5SExCmXtn3e24i2TGWpuBDHySTLzjJxn80UXRUuxXMdr4ZnItw6s0U@LJlRsJYeUyygpO3NUZthl8 "Bash – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
WS⊞υι≔⟦⟧θF⁺²‽⁴⊞θ‽⁻υθθ
```
[Try it online!](https://tio.run/##TY@7bsMwDEV3fQVHGXCWolunjh0KGO0YdGBk2hJMU4ko5fH1LpOiRUdd3cdhiFhCRt62S0xM4N/k2OpnLUlm33UwNI2@9ZC6F/eqmmbx@68eTvaccgE/cFP/1MMHyphX/9z9Zk5/2nsS87R7qLPYYNXVW8G26YrMEHMRdRPKrGCVakRHqEQ1OgQbWWiEmmVu5AJWTgsB3UidpitMhknFcgKEIUK0STdnrLuHj2lWFzifSWwmT/qvERM7JqyRyu2xG5BvoEsSV@zflBHLAgdu9KMG1AqS74BjvtwNhSamUFMWR9c2EiDoSnZSnuBQ0qqGTW7bnfkb "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
WS⊞υι
```
Read in the list of possible traits.
```
≔⟦⟧θ
```
Start with no traits selected.
```
F⁺²‽⁴
```
Repeat `2-5` times uniformly randomly.
```
⊞θ‽⁻υθ
```
Pick a trait uniformly randomly from the list of traits not already picked.
```
θ
```
Output the final list of picked traits.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~17~~ 14 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
mÅvαá├mÅ~;3w⌠<
```
[Try it online.](https://tio.run/##VU87UgMxDL2Kum2gooSbMBSKLX9mZYuxvEm2oaOjTJkCjsAZ0nOIXGSRM0NBJ72P9F7BnqJw2LZyed//fF@@rqezjW@PD4frx@fTtj1PWpAZkrSq090UsEYFaaAJ2yt0op4MRgjSZvLQpcaFDHHYOc8EtNLwaT5CyDVSM3cFQpcgYfVGRcF@f9MyxaF1LHuq9lKC/ruNmW1nstTU1lsKh7yCzrka0UxjmMc2w44X@sMdaocqI7KXw5A0CkyuZxk0HRdPgKCFrKgE2LVc1IrQ9PIL)
I really hate this language sometimes.. -\_- This should in theory have been `áv3w⌠<` (6 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)), but due to a number of bugs, it ended up as 17 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) instead.
**Explanation:**
*Explanation of the intended solution, and why it didn't work due to bugs:*
```
√° # Sort the (implicit) input-list by:
v # A random integer in the range [-2147483648,2147483647]
3w # Push a random integer in the range [0,3]
⌠ # Increase it by 2 (to have the range [2,5] instead)
< # Only keep that meany leading items from the shuffled list
# (after which the entire stack is output implicitly as result)
```
*Bugs:*
1. ~~MathGolf changes all spaces in string inputs to `", "` ([try it online with explicit print](https://tio.run/##VY/NbsNACIRfBfncPlHUA1nP/sh4iWCdxk/vspFy6JFvBpjZedSikq/rcV23xXcWoarWfflaMvfipEZe2R40gFEDM2W1DSsN7eVAkMRD2gbCibnn7UW59QKL7U7gVKlyX0MqyuP77RWU6U2iT/R4qdn/3eYmMQsiIOx8p0gsJ/nWeggWnmAr20Z3OfDhiX1Q1xl51d9pMWRBGk2njNexgph8RxTVTHdru0cRLD9/)). This bug is likely because MathGolf supports multiple inputs both separated by commas and spaces, so when a string or string-list is used that contains spaces, it incorrectly splits them, before interpreting the splitted string as string again..
This is fixed with the leading `mÆ',-` (only works because the input-strings are all without commas)~~
EDIT: Apparently using `'` quotes for strings instead of `"` fixes this issue.
2. MathGolf's sort-by builtin `√°` apparently evaluates its body once in some cases, because `√°v` and `√°f` both result in an unsorted list and act similar as `√°1` would.
This is fixed by replacing it with `mÅvαá├mÅ~;`:
```
m # Map over the (implicit) input-list,
√Ö # using 2 characters as inner code-block:
v # Push a random integer from the range [-2147483648,2147483647]
α # Pair the string and random integer together
√° # After the map: sort by:
‚îú # The left (a third bug, should have been `‚î§` for right..) item: the random integer
m # After the sort-by: map again,
√Ö # using 2 characters as inner code-block:
~ # Dump the string and random integer to the stack
; # And discard the random integer
```
After which we can use the `3w⌠<` explained above to finish the program.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 25 bytes
Input comes from the pipeline.
```
random -c(random -mi 2 6)
```
[Try it online!](https://tio.run/##VY/BbsMwDEN/hbeswHrZYf@jOnJsRLEKyVkboP@e2QY2oDeBfJLIuz7YPLHIOflGIkhqxadPTJHK4lCDJ7I7KnNNXSdEtZVnVC3Lzl0KVCWvDD54rHp@IuaytNPQAqaQkKjM3VuU6nXQwsugg@gPl/ZYo78/oCxdEKaa2I4RJpAc8DWX7lijmjiTrbjJzv9GIK8o2rPP@uiMcRQONevw@bnPDIJvrTo04mZ589aIJ7xOa1l1wzV8/E1bxhe@L@f5Cw "PowerShell – Try It Online")
**Ungolfed:**
```
Get-Random -Count (Get-Random -Minimum 2 -Maximum 6)
```
Straightforward; Get-Random with "-Count x" will randomly select x objects from the pipeline input.
The verb "Get-" can (in dire situations as code golf) be dropped from cmdlet names *<Verb>-<Noun>*; if PS finds no program or cmdlet named "<*noun*>", it will add "Get-" and try to find that. **Disclaimer** Use this for golfing only, never in normal scripts; it'll slow down the script (because it will try to find *<noun>*.exe in the path first every time), and may start unrelated programs on other systems.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.rY5ŸΩ£
```
Very straight-forward, but can't find anything shorter. (I initially read the challenge description wrong as 1-4 random outputs, which would be possible in 4 bytes. 2-5 however is a bit longer.)
[Try it online.](https://tio.run/##VY89TsVADISvYqUGOg6DEIWzmf1RNmtkb@DlPK/iBtRItFwpeJ9EQelvZmyPGM8F5/mgT4/fnz8fX9fzfJ5s41opizab7qbILRmJkmXWV@pAz46ZouiKhbq0tMNJ4F7LCsKBkbNyoVhagnq6EThkytwWl5Jwv795K9LwhipvaH5Sov3bzaX6XME9Q4/bF4HrQbaW5oK6x9nCutJcd/zxwNapyXh5kfdhUcSK0IsMGZd9ATHZBi8qkWYtm3kRTC@/)
**Explanation:**
```
.r # Randomly shuffle the (implicit) input-list
Y5≈∏ # Push a list in the range [2,5]: [2,3,4,5]
Ω # Pop and get a random value from this list
£ # Only leave that many items from the shuffled list
# (after which the result is output implicitly)
```
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), ~~35~~ 24 bytes
Port of [my Ruby answer](https://codegolf.stackexchange.com/a/252440/11261).
```
~:sample&(-:rand^(2..5))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZBBasMwEEXptqcYsigJxFkUCiXQbS4R0jKWR5bqsWQ0UhtvepFuTCF36Fl6msqRF6UrwX9_Rv_P5-X1JdXj9HV4uqSoq8fvj71gPzDdrat9QNc8r-93u4fNpuCfm2pIUeBwPN4CrKRHZjA-OFltZ0GjawV8ADEYBohE0RSCoH3oqIHoXZuoiAoj246ARloWiD2Dtq6lkNc4IFQGTI5RaOsxVtcJpnaZUOzfyOUQXsv_r9BykZgwGgrjNZpCHkE66woL2ZnlBkMHNSf6gxRKBOfnNo1_n12BNJOK1i8OOqeGAEF6ypfwGupge8kd54anU7naNJX3Fw)
[Answer]
# APL (Dyalog Unicode), 23 bytes (15 chars)
```
{⍵[(≢⍵)?⍨1+?4]}
```
Explanation:
```
{ } ‚çù defun:
1+?4 ‚çù roll a d4, add 1
(≢⍵)?⍨ ⍝ generate random indices
‚çµ[ ] ‚çù index them into ‚çµ to get final traits
```
] |
[Question]
[
*Inspired by the [Codewars Kata](https://www.codewars.com/kata/replace-with-alphabet-position/train/python).*
Your goal is to take an input string such as this one:
```
"'Twas a dark and stormy night..."
```
and return a string containing the position of each character in the alphabet, separated by spaces and ignoring non-alphabetical characters, like this:
```
"20 23 1 19 1 4 1 18 11 1 14 4 19 20 15 18 13 25 14 9 7 8 20"
```
For an additional challenge, you can replace any numerical characters in the original string with themselves + 27. For example, `"25"` would become `"29, 32"`. This is completely optional.
You must use 1-indexing (`'a'==1`, `'b'==2`, etc)
Additional rules:
* You must return a string, not an array.
* Trailing whitespace is OK.
The winner has the lowest byte count.
Good luck!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), (5?) 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Rightmost two bytes are output formatting
```
áÇ32%ðý
```
A port of [my Jelly answer](https://codegolf.stackexchange.com/a/165824/53748), but O5AB1E is more terse for the alphabet filtering.
**[Try it online!](https://tio.run/##MzBNTDJM/f//8MLD7cZGqoc3HN77/796SHlisUKiQkpiUbZCYl6KQnFJflFupUJeZnpGiZ6eHgA "05AB1E – Try It Online")**
### How?
```
áÇ32%ðý - take input implicitly
á - filter keep alphabetical characters
Ç - to ordinals
32 - thirty-two
% - modulo (vectorises)
ð - push a space character
ý - join
```
[Answer]
# Java 8, ~~82~~ ~~78~~ ~~72~~ ~~69~~ 62 bytes
```
s->{for(int c:s)System.out.print(c>64&~-c%32<26?c%32+" ":"");}
```
-13 bytes thanks to *@OlivierGrégoire*.
[Try it online.](https://tio.run/##LY7BagIxEIbvfYqfQG2CbA62eHDVUnrWi72VHqazq0bdRJJoWWT76tuxCjMM88N88@3oTMWu2vd8oJSwIOcvD4DzuY5r4hrL6wqcg6vAmrcUP7@QTClpJy2VMmXHWMJjhj4V88s6RC0E8CSZVZty3dhwyvYYJdQ8H78Mfgt@fB5NR@PX6xwqqIlSpuz68sY8nr4Pwryj/583oqZXWRgbMSBz8/KWtXr6@KEEQkVxD/KV3IXYtPBus83WWmVzeBfztxip1eYu3/V/)
**Explanation:**
```
s-> // Method with character-array parameter and no return-type
for(int c:s) // Loop over its characters as integers
System.out.print( // Print:
c>64&~-c%32<26? // If the current character is a letter:
c%32+" " // Print the position in the alphabet with a trailing space
: // Else:
"");} // Print nothing
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~62~~ ~~60~~ 49 bytes
-5 bytes thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king).
-8 bytes thanks to [pLOPeGG](https://codegolf.stackexchange.com/users/72200/plopegg).
After these improvements, this answer is now similar to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)'s [answer](https://codegolf.stackexchange.com/a/165827/64121).
```
print(*[ord(c)%32for c in input()if c.isalpha()])
```
[Try it online!](https://tio.run/##DcIxDoAgDADAr3QxggODfMXNODQQpFELKTXG16OXq6/mwr73KsRqprVINMEOfk5FIADxv95qLCUIjhqeNaOxm@19XB5sgBBRDkCO0LTI9QLTntU59wE "Python 3 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~55~~ 50 bytes
```
cat(utf8ToInt(gsub("[^A-Za-z]","",scan(,"")))%%32)
```
[Try it online!](https://tio.run/##K/r/PzmxRKO0JM0iJN8zr0Qjvbg0SUMpOs5RNypRtypWSUdJSac4OTFPA8jQ1NRUVTU20vyvpB5SnliskKiQkliUrZCYl6JQXJJflFupkJeZnlGip6en9B8A "R – Try It Online")
Reads input from stdin, ~~converts to uppercase,~~ removes non-~~uppercase~~ alphabetic letters, converts to code points, ~~subtracts to 64~~ mods by 32, and prints to stdout, separated by spaces.
*Thanks to Kevin Cruijssen for the golf!*
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 24, 20, 14 13 bytes
-4 bytes thanks to Zacharý (and Mr. Xcoder)!
-6 bytes thanks to Adám!
-1 byte thanks to ngn!
```
⎕A⍳⎕A∩⍨≡819⌶⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHfVMdH/VuBlMdKx/1rnjUudDC0PJRz7ZHXYuAShTU1dVDyhOLFRIVUhKLshUS81IUikvyi3IrFfIy0zNK9PT01AE "APL (Dyalog Unicode) – Try It Online")
## Explanation:
```
≡819⌶⊢ - to uppercase
⎕A∩⍨ - intersect with the letters A-Z (args swapped to preserve the order)
⍳ - index in
⎕A - the A-Z letters list
```
## My initial solution:
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 24 20 bytes
```
{⍵/⍨27>⍵}⎕A⍳1(819⌶)⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wSN6ke9W/Uf9a4wMrcDsmof9U11fNS72VDDwtDyUc82zUddizSBKhXU1dVDyhOLFRIVUhKLshUS81IUikvyi3IrFfIy0zNK9PT01AE "APL (Dyalog Unicode) – Try It Online")
## Explanation:
```
⍳ indices of
1(819⌶)⊢ the right argument (⊢) changed to uppercase
⎕A in the list of uppercase letters
{⍵/⍨ } copy (filter) those items from the list of indeces
27>⍵ which are smaller than 27 (all non A-Z chars will have index 27)
```
Don't laugh at me, I'm new to APL :)
[Answer]
# [Python 2](https://docs.python.org/), (45?) 55 bytes
11 bytes added to format the output, which also makes this incompatible with Python 3)
```
lambda s:' '.join(`ord(c)%32`for c in s if c.isalpha())
```
Another port of my Jelly answer.
**[Try it online!](https://tio.run/##FcuxDsIgEAbg3af408QAC0PdTPoWjg49QeS0BcJdYvr0GL/9a4fmWuaRlvvYaH9EglwNjH9XLnatPdrgzpd5TbUjgAsEnBA8C20tk3Vu6FMUCyZz@5KAEKl/QCVCtPb9QOFXVu/9dGqdiyLZ/3DjBw "Python 2 – Try It Online")**
---
Non-formatted version (returning a list of integers):
```
lambda s:[ord(c)%32for c in s if c.isalpha()]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~69~~ ~~55~~ 54 bytes
```
t=>t.match(/[a-z]/gi).map(i=>parseInt(i,36)-9).join` `
```
[Try it online!](https://tio.run/##DcixCsIwEADQX7mtCZh0EASHdHd3K0KPNE2vtrmQHIr@fPSNb8MXVl8oi0k8h7a4Jm4Qe6D4VfUjmu@jj6T/kRW5IWOp4ZZE0el80eaq7caUJpia51R5D3bnqBbV3d9YAWHG8gRMM1ThcnwgUVzFWttp3X4 "JavaScript (Node.js) – Try It Online")
# Explanation :
```
t => // lambda function accepting a string as input
t.match(/a-z/gi). // returns all parts of string that match as an array
map(i=> // map over that array with argument i
parseInt(i,36) // convert to base 36
- 9 // and subtract 9 from it
). // end map
join` ` // convert to space separated string
```
---
11 bytes saved thanks to @Kevin
1 more bytes thanks to @Neil
---
You can add support for numericals for some additional bytes (thanks to @neil)
# [JavaScript (Node.js)](https://nodejs.org), 62 bytes
```
t=>t.match(/[^_\W]/g).map(i=>(parseInt(i,36)+26)%36+1).join` `
```
[Try it online!](https://tio.run/##Dci7DsIgFADQX2ExhVRptAkb3d1NHHz1Biilj0sDNxq/Hj3jmeAN2aSw0QGjdWXQhXRHcgUyI29uz9f9@mi8@MfGg@74Bim7MxIP@1aJ@qTErlX1UcgpBuxZX0zEHBcnl@j5wKvLBzIDZiHNDNCyTDGtX4bBjySlrIQoPw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), (7?) 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Rightmost byte is output formatting
```
fØẠO%32K
```
A full program accepting a string in Python format which prints the result to STDOUT
**[Try it online!](https://tio.run/##y0rNyan8/z/t8IyHuxb4qxobef///19JPaQ8sVghUSElsShbITEvRaG4JL8ot1IhLzM9o0RPT08JAA "Jelly – Try It Online")**
### How?
```
fØẠO%32K - Main Link: list of characters (created from the string input)
ØẠ - yield the alphabet = ['A','B',...,'Z','a','b',...,'z']
f - filter keep (discard non alphabet characters)
O - ordinals ('A':65, 'Z':90, 'a':97, 'z':122, etc.)
32 - literal thirty-two
% - modulo (65:1, 90':26, 97:1, 122:26, etc.)
K - join with spaces (makes a list of characters and integers)
- implicit print
```
[Answer]
# Japt v2.0a0 `-S`, ~~12~~ 10 bytes
```
r\L ¨c uH
```
[Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=clxMIKyuYyB1SA==&input=IidUd2FzIGEgZGFyayBhbmQgc3Rvcm15IG5pZ2h0Li4uIgotUw==)
---
## Explanation
```
r :Remove
\L : Non-letter characters
¬ :Split to array
® :Map
c : Character code
u : Modulo
H : 32
:Implicitly join with spaces and output
```
[Answer]
# x86 opcode, 35 bytes
```
0080h: AC 3C 24 75 04 88 45 FF C3 0C 20 2C 60 76 F1 D4
0090h: 0A 0D 30 30 86 E0 3C 30 74 01 AA 86 E0 AA B0 20
00a0h: AA EB DD
f: lodsb
cmp al, '$'
jnz @f
mov [di-1], al
ret
@@:
or al, 32
sub al, 96
jbe f
aam
or ax, 3030H
xchg ah, al
cmp al, 48
jz @f
stosb
@@:
xchg ah, al
stosb
mov al, 32
stosb
jmp f
```
Assuming the result contain at least one letter, and no `{|}~`
40 bytes, allowing all ASCII chars
```
0080h: AC 3C 24 75 04 88 45 FF C3 0C 20 2C 60 76 F1 3C
0090h: 1A 77 ED D4 0A 0D 30 30 86 E0 3C 30 74 01 AA 86
00a0h: E0 AA B0 20 AA EB D9
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~9~~ ~~10~~ 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
üpÉÿ%}},√
```
[Run and debug it](https://staxlang.xyz/#p=81709098257d7d2cfb&i=%22%27Twas+a+dark+and+stormy+night...%22&a=1)
*-1 byte thanks to @recursive*
Explanation:
```
v{VaIvm0-J Full program, unpacked, implicit input
v Lowercase
{ m Map:
VaI Index in lowercase alphabet (0-based, -1 for not found)
^ Increment
0- Remove zeroes
J Join by space
Implicit output
```
### [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
É▌Xl»↔"
```
[Run and debug it](https://staxlang.xyz/#p=90dd586caf1d22&i=%27Twas+a+dark+and+stormy+night...&a=1&m=2)
This one outputs newline-separated. Unpacked: `vmVaI^|c`. Similar, but with map, which implicitly outputs with trailing newline.
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~152~~ 117 bytes
-35 bytes thanks to *@Lynn*.
```
[N
S S N
_Create_Label_LOOP][S S S N
_Push_0][S N
S _Duplicate_0][T N
T S _Read_STDIN_as_character][T T T _Retrieve][S N
S _Duplicate_input][S S S T S S S S S N
_Push_32][T S T T _Modulo][S N
T _Swap_top_two][S S S T T T T T T N
_Push_63][T S T S _Integer_divide][T S S N
_Multiply][S N
S _Duplicate][S S S T T S T T N
_Push_27][S T S S T N
_Copy_1st][S S S T N
_Push_1][T S S S _Add][T S T S _Integer_divide][T S S N
_Mulitply][N
T S N
_If_0_Jump_to_Label_LOOP][T N
S T _Print_as_number][S S S T S S S S S N
_Push_32_space][T N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP]
```
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/##PU1JCoAwDDwnrxi8eOtr/ECwoiJWsYXi62uniiEZmCVJXtY0xdPGqRQFatdRiApEpHEIAU0hgk4tCvT0S9FXCkIub/KLKDeb@V9r31RL6fohW4TB27XBgkdMx7XfCOu8JOdc9wA) (with raw spaces, tabs and new-lines only).
**Explanation in pseudo-code:**
```
Start LOOP:
Character c = STDIN as character
Integer n = (c modulo-32) * (c integer-divided by 63)
Integer m = 27 integer-divided by (n + 1) * n;
If(m == 0):
Go to next iteration of LOOP
Else:
Print n as integer to STDOUT
Print a space to STDOUT
Go to next iteration of LOOP
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
láÇ96-ðý
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/5/DCw@2WZrqHNxze@/@/ekh5YrFCokJKYlG2QmJeikJxSX5RbqVCXmZ6Romenh4A "05AB1E – Try It Online")
or, if we can return an array:
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
láÇ96-
```
Explanation:
```
l Lowercase
á Only letters
Ç Codepoints
96- Subtract 96.
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/5/DCw@2WZrr//6uHlCcWKyQqpCQWZSsk5qUoFJfkF@VWKuRlpmeU6OnpAQA "05AB1E – Try It Online")
or if you want it to count numbers:
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
```
lAžh«DŠÃSk>ðý
```
[Try it online!](https://tio.run/##AT8AwP8wNWFiMWX//2xBxb5owqtExaDDg1NrPsOww73//ydUd2FzIGEgZGFyayBhbmQgc3Rvcm15IG5pZ2h0Li4uMjU "05AB1E – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
Handles numbers as well
```
žKÃlvžKlÙyk>ðJ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6D7vw805ZUAq5/DMymy7wxu8/v8PKTcpVkhUSEksylZIzEtRMC0xKMqtVMgzTM8o0dPTAwA "05AB1E – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
≔⁺β⭆χιβF↧S¿№βι«I⊕⌕βι→
```
[Try it online!](https://tio.run/##LczRCoIwGAXga32KH2/6ByZ1W1chBEGCVC/wO6eOdJNtKhE9@5rU5eF85/CODNfUe3@yVrYKy36yWKVwd0aqtqAR97sUJGMpVOwYN9oAXvUiDCcr8KLGyf0oMsZANoC5npRbL8II3nFUhtZhTtYFzo0YhHKixrNU9V@xcBwVehZ4uMm2cyF@vE82j4UsENRknkCqBuu0GV6gVpNlWRL77dx/AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁺β⭆χιβ
```
Append the digits to the predefined lowercase letters variable.
```
F↧S
```
Loop over the lowercased input.
```
¿№βι«
```
If the current character is a letter or digit,
```
I⊕⌕βι
```
print its 1-indexed index,
```
→
```
and leave a space for the next value.
[Answer]
# [Red](http://www.red-lang.org), 93 bytes
```
func[s][a: charset[#"a"-#"z"]parse lowercase s[any[copy c a(prin[-96 + to-char c""])| skip]]]
```
[Try it online!](https://tio.run/##FctBCsIwEEbhvaf4mS5UpF0K9hjibpjFkKS2VJOQpJSKd4929/jgJWfr3VmWw9DXYfGGs7D2MKOm7Ao3pNQ29CGJO@AVVpeM/iuz@o1NiBsM9BTT5Lm9XXFBCe2@wxDJ@Ys8T1FE6gA6PlbNUFhNM9Rb5BLSe4OfnmPpuo7qDw "Red – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 47 bytes
With additional challenge of parsing digits:
```
print map{(ord(uc)-64)%43," "}<>=~/([A-Z\d])/gi
```
[Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvRCErPzNPSUFJJzexoFpDI78oRaE0WVPXzERT1cS41sbOtk5fI9pRNyomJVZTPz3z/3/1kPLEYoVEhZTEomyFxLwUheKS/KLcSoW8zPSMEj09PQA "Perl 5 – Try It Online")
Reduced to 38 bytes by ignoring digits
```
print map{ord()%32," "}<>=~/([A-Z])/gi
```
[Answer]
# [PHP](https://php.net/), 70 bytes
```
for(;$c=$argv[1][$i++];)if(($c=ord($c))>64&($c%=32)>0&$c<27)echo"$c ";
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVkm1VEovSy6INY6NVMrW1Y601M9M0NIDC@UUpQEpT087MRA3IULU1NtK0M1BTSbYxMtdMTc7IV1JJVlCy/m9v9/@/ekh5YrFCokJKYlG2QmJeikJxSX5RbqVCXmZ6Romenh4A "PHP – Try It Online")
-5 bytes thanks to Kevin
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 35 bytes
```
$_="@{[map{(-64+ord uc)%43}/\w/g]}"
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lbJoTo6N7GgWkPXzEQ7vyhFoTRZU9XEuFY/plw/PbZW6f//xKTklNS09IzMrOyc3Lz8gsKi4pLSsvKKyioDQyNjE1MzcwtLvX/5BSWZ@XnF/3V9TfUMDA3@6xYAAA "Perl 5 – Try It Online")
Includes the extra portion about the digits.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) 2.0 `-S`, 9 bytes
```
f\l ®c %H
```
[Run it online](https://ethproductions.github.io/japt/?v=2.0a0&code=ZlxsIK5jICVI&input=IidUd2FzIGEgZGFyayBhbmQgc3Rvcm15IG5pZ2h0Li4uIgotUw==)
## Explanation:
```
f\l ®c %H Input: "Hello..."
f Match:
\l [A-Za-z] ["H","e","l","l","o"]
® Map Z over the results:
c char-code of Z [72,101,108,108,111]
%H mod 32 [8,5,12,12,15]
-S Join the chars with a space 8 5 12 12 15
```
[Answer]
# [Perl 6](https://perl6.org), 32 bytes (alpha), 41 bytes (alpha+digit)
```
{~(.uc.comb(/<:L>/)».ord X-64)}
```
[Try it (32 bytes alpha)](https://tio.run/##K0gtyjH7X1qcqlBmppdszcWVW6mglpyfkqpg@7@6TkOvNFkvOT83SUPfxsrHTl/z0G69/KIUhQhdMxPN2v/FiZUKILUaSuoh5YnFCokKKYlF2QqJeSkKxSX5RUCj8jLTM0r09PSUNPUKgDYBzYfrMTLFFFOPV4cK/gcA "Perl 6 – Try It Online")
```
{~((.uc.comb(/<:L+:N>/)».ord X-64)X%43)}
```
[Try it (41 bytes alpha + digit)](https://tio.run/##K0gtyjH7X1qcqlBmppdszcWVW6mglpyfkqpg@7@6TkNDrzRZLzk/N0lD38bKR9vKz05f89BuvfyiFIUIXTMTzQhVE2PN2v/FiZUKIE0aSuoh5YnFCokKKYlF2QqJeSkKxSX5RUAz8zLTM0r09PSUNPUKgFYCLYLrMTLFFFOPV4cK/gcA "Perl 6 – Try It Online")
## Expanded:
### 32 bytes alpha
```
{ # bare block lambda with implicit parameter $_
~( # coerce to string (space separated)
.uc # uppercase
.comb( / <:L > / )\ # get letters as a sequence
».ord # get the ordinal of each
X- 64 # subtract 64 from each
)
}
```
### 41 bytes alpha + digit
```
{ # bare block lambda with implicit parameter $_
~( # coerce to string (space separated)
(
.uc # uppercase
.comb( / <:L + :N > / )\ # get letters and numbers as a sequence
».ord # get the ordinal of each
X- 64 # subtract 64 from each
) X% 43 # modulus 43 for each
)
}
```
[Answer]
# [Tcl](http://tcl.tk/), 93 bytes
```
puts [lmap c [split $argv ""] {if [string is alp $c] {expr ([scan $c %c]-64)%32} {continue}}]
```
[Try it online!](https://tio.run/##DctBDsIgEAXQq/w0bdSFLNR4EneExWRakUgpgWnVNJwd2b7kCfta4yoZ2s8UwdA5eifoKdkNXWewu2dDSS5YuAzyET03nr4x4agzU2iAgc35fjsN10vBzksQF9apFFNrPTw@1CJGSm9QGJFlSfMPwdmXKKX@ "Tcl – Try It Online")
[Answer]
## PHP 108 105 Bytes
[Try it online](https://tio.run/##HY1BDoIwFET3nKJpTKhJKQdAJN7BlUbrj9TSWOjPbyOBy2N1lvPeZHDA7dDhgMUOyH5afp4hMmA90JvB1LOYAo0Lm5wdklKKN0V3zIs2Jkok3Ig@9EZwxmVudETvkvix4MNsSCAZq8mgh2e26uv9VF2gWm81l2Up/5/7HAlEsOiXdygIJpvdB5drJk2xbV8) (108 Bytes)
[Tri it online](https://tio.run/##HY1BDsIgFET3PQUhJsUE2wPU2kt0Z7T@CAKRws@H2LSXr@gs583LoMX9PKDF6gBkPj0fF0gMmAJ6MwiKpRxpXllwxuamaXhXDZdi9ClTJuFm9FFpwRmXpZkSepcFkjYTafTwLKi93uG03Vou6/o3ytHHRZP4Hx5LJBDBOr28Q0EQTHEeXG6FdPv@BQ) (105 Bytes)
-3 Bytes, thanks to @manassehkatz
(Change the level of strtolower and remove A-Z from regex)
**Code, tried to avoid any loop**
```
<?=strtr(implode(" ",str_split(preg_replace(
"/[^a-z]/",'',strtolower($argv)))),array_flip(range("`",z)));
```
**Explanation**
```
$string = preg_replace("/[^a-z]/",'',strtolower($argv))
//the string only contains letters
$string = implode(" ",str_split($string));
//the string has a space after every letter
$string = strtr($string, array_flip(range("`",z)));
//replace every letter acording to the array
$replacementArray = array_flip(range("`",z));
//this array contains the ansi characters from "`" to the "z"
//array_flip to change the keys with the values
//final array ["`"=>0,"a"=>1, "b"=>2...."z"=>26]
```
[Answer]
# [Python 3](https://docs.python.org/3/), 84 bytes
```
print(*filter(int,['abcdefghijklmnopqrstuvwxyz'.find(c)+1for c in input().lower()]))
```
[Try it online!](https://tio.run/##DcxBDsIgEEDRq8wOUENivIo74wKhFCwdcDot4uWR5C/e6pfGIeOt90IRWZ58TDyRHL48hHlZN/k5xPeSVszlQxvvR/22n9A@opNWna8@E1iIOCo7S6VTruOgnkr1Lu7VbGDAGVrAoIONM60NMM6BtdZ/ "Python 3 – Try It Online")
[Answer]
# Python 2, [110 bytes](https://mothereff.in/byte-counter#a%3D%22abcdefghijklmnopqrstuvwxyz%22%3B%20print%20%22%20%22.join%28%5Bstr%28a.index%28l%29%20%2B%201%29%20for%20l%20in%20list%28input%28%29.lower%28%29%29%20if%20l%20in%20a%5D%29) [104 bytes](https://mothereff.in/byte-counter#a%3D%22abcdefghijklmnopqrstuvwxyz%22%3Bprint%22%20%22.join%28%5Bstr%28a.index%28l%29%2B1%29for%20l%20in%20list%28input%28%29.lower%28%29%29if%20l%20in%20a%5D%29), with user input
```
a="abcdefghijklmnopqrstuvwxyz";print" ".join(str(a.index(l)+1)for l in list(input().lower())if l in a)
```
[Try it Online!](https://tio.run/##JclBDsIgEADAr2y4CDEh0avxF35gFdpuSxdcttL6eTw41ymHTpmvvePd4PMV4jBONC9p5VzeUnX7tP34mlsRYjVg/JyJbVWx6IlD3G1y54sbskACYkhU1RKXTa3zKbco1jka/omud3N6NKyAEFAWQA5QNct6ANM4qffe/AA)
---
# Python 2, [105 bytes](https://mothereff.in/byte-counter#a%3D%22abcdefghijklmnopqrstuvwxyz%22%3B%20return%20%22%20%22.join%28%5Bstr%28a.index%28l%29%20%2B%201%29%20for%20l%20in%20list%28t.lower%28%29%29%20if%20l%20in%20a%5D%29) [104 bytes](https://mothereff.in/byte-counter#a%3D%22abcdefghijklmnopqrstuvwxyz%22%3B%20print%20%22%20%22.join%28%5Bstr%28a.index%28l%29%20%2B%201%29%20for%20l%20in%20list%28t.lower%28%29%29%20if%20l%20in%20a%5D%29) [96 bytes](https://mothereff.in/byte-counter#a%3D%22abcdefghijklmnopqrstuvwxyz%22%3Bprint%22%20%22.join%28str%28a.index%28l%29%2B1%29for%20l%20in%20list%28t.lower%28%29%29if%20l%20in%20a%29), where `t` is predefined:
```
a="abcdefghijklmnopqrstuvwxyz";print" ".join(str(a.index(l)+1)for l in list(t.lower())if l in a)
```
[Try it Online!](https://tio.run/##Jcg7DsIwEAXAqzy5wRaSJWhRbkGHKBaczybOOtgLSbi8KZhyll2HJOeqaGAO15UKCIHyBJKAoinPO4T7Qb33plJj6PEMbdcPPE5xlrS8ctH3Z932r7lgySwKA@PHxGJvRbMlzxLazUaHI04OXcqIYEHkolZ9TGubrXPg7v90d7X@AA)
Let's break it down with a more readable version:
```
alphabet = "abcdefghijklmnopqrstuvwxyz"
foo = [str(alphabet.index(letter) + 1) for letter in list(t.lower()) if letter in alphabet]
print " ".join(foo)
```
First, we define `alphabet` as being, well, the alphabet.
Next, we use list comprehension to:
1. Make a list where each item is a lowercase character from `t`
2. For each letter, if it is not in the alphabet, discard it.
3. If it is, find its index in the alphabet,
4. add one to it (because we start counting at 1)
5. and make it a string.
Finally, we join it all together and print it.
---
**Edit:** Changed to `print` (and lost portability) to save bytes and make it work outside a function
**Edit 2:** Added a version with `input()` instead of predefined variables
**Edit 3:** Removed 8 bytes in Solutions 1 and 2 thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 63 bytes
```
"$(([char[]]"$args".ToUpper()|%{$_-($_,64)[$_-in65..90]})-ne0)"
```
[Try it online!](https://tio.run/##DcxBCsIwEADAryxLxATs0oMW/Ed7CqEsNjTFmoRNoYj69tjbnCan3UsJfl1rRaW1fQQW6xwqlrkg9WnI2Ys239NHjY1W46W7Gntwid2N6N66n2mibw3WYzj3OxdgmFiewHGCsiV5vSEuc9iICP8 "PowerShell – Try It Online")
*(Seems long ...)*
Takes input `$args`, converts it `.ToUpper`case, casts it as a `char`-array, feeds that into a `for each` loop. Inside the loop, we subtract either itself or 64 from the (ASCII int) value, based on whether or not the current value is `-in` the range `65` to `90` (i.e., it's an ASCII capital letter). Those values are left on the pipeline, and we use a `-n`ot`e`qual to eliminate the non-letter values (because they're all zero). Those numbers are encapsulated in a string as the default stringification of an array is to space-separate it, so we get that pretty cheaply. That string is left on the pipeline and output is implicit.
[Answer]
# MS-SQL, 133 bytes
```
SELECT STRING_AGG(ASCII(substring(upper(s),number+1,1))-64,' ')FROM
spt_values,t WHERE type='P'AND substring(s,number+1,1)LIKE'[a-z]'
```
[Per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341), input is taken via a pre-existing table **t** with varchar field **s**.
SQL 2017 or later is required. Must also be run in the `master` database, because I'm taking advantage of a system table called `spt_values`, which (when filtered by `type='P'`) contains counting numbers from 0 to 2047.
Basically I'm joining a number table with the input string using `SUBSTRING()`, which returns a separate row for each individual character. This is filtered for only letters using `LIKE'[a-z]'`, then we get their ASCII value and subtract 64. These numbers are joined back into a string using the (new to SQL 2017) function `STRING_AGG`.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes
```
jdfTmhxGr0
```
I'm pretty sure this can be golfed a little bit...
-2 bytes if I can output as a list, some answers seem to but it's not in the spec
[Try it online!](https://tio.run/##K6gsyfj/PyslLSQ3o8K9yOD/fyX1kPLEYoVEhZTEomyFxLwUheKS/KLcSoW8zPSMEj09PSUA "Pyth – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 67 bytes
```
c;f(char*s){for(;*s;)(c=tolower(*s++)-96)>0&c<27&&printf("%d ",c);}
```
[Try it online!](https://tio.run/##FctRCgIhEADQqwxCNrqtRB9FWJ2iCwxj7i61GqOwRHR2q//3uB@YW2MfkUcSW8w7ZkFvizfI55ofebkJ2tJ1pj/uzWWr@bQ7aP2UKdWIahVAbdj4T5tpSvjrqNbXhQoQBJI7UApQapb5BWkaxuqcU3/@BQ "C (gcc) – Try It Online")
Converts each char to lowercase, offsets its code by -96 and, if it falls in the range of the 1-indexed alphabet, prints the offset code
[Answer]
# [jq](https://stedolan.github.io/jq/), 45 bytes
```
[gsub("\\W";"")|explode[]%32|@text]|join(" ")
```
---
```
gsub("\\W";"") # remove non-alpha characters
|explode[] # get decimal values of characters
%32 # get positions in alphabet
|@text # convert back to string
[ ]|join(" ") # join with a space
```
[**Try it online**](https://tio.run/##yyr8/z86vbg0SUMpJiZcyVpJSbMmtaIgJz8lNTpW1dioxqEktaIktiYrPzNPQ0lBSfP/fyX1kPLEYoVEhZTEomyFxLwUheKS/KLcSoW8zPSMEj09PaV/@QUlmfl5xf91iwA)
] |
[Question]
[
# Introduction
When playing Mario Kart the other day, an interesting question popped up when a Grand Prix with my 2 roommates, 9 AI drivers and myself seemed to be fairly close and therefore exciting until the very end.
We asked ourselves: How close can the point difference between first and last place (#1 and #12) after exactly N races be?
This Code Golf challenge occured to me after the underlying problem for the distribution of the minimum difference in points was answered [here](https://gaming.stackexchange.com/a/385505/254790) by user *mlk*.
# Challenge
Mario Kart races consist of 12 racers which in every race receive the points represented in this 1-indexed array: `[15, 12, 10, 8, 7, 6, 5, 4, 3, 2, 1, 0]`.
In a Grand Prix, the points for each driver from every of the N races are simply added up to form the final point distribution. The difference between the lowest and the highest number of points in this final point distribution is called *point difference* (alas between places #1 and #12).
Your task is to write a program which takes as input the number of races N (`1 <= N <= 32`) and outputs the corresponding point difference.
The first 13 correct inputs and outputs can be found below. You will find that after the special cases `N = 1` and `N = 2`, the correct answer will be `0` if `N` is divisible by 12 and `1`if not.
# Example Input and Output
As the desired output is correctly defined for every natural number, here are the input/output examples until the repeating pattern described above begins:
```
1 -> 15
2 -> 4
3 -> 1
4 -> 1
5 -> 1
6 -> 1
7 -> 1
8 -> 1
9 -> 1
10 -> 1
11 -> 1
12 -> 0
13 -> 1
```
# Goal
This is Code Golf, so shortest answer in bytes wins!
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
[Answer]
# JavaScript (ES7), 19 bytes
```
n=>14/n**n+1^n%12<1
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1s7QRD9PSytP2zAuT9XQyMbwf1p@kUaegq2CobVCnoKNgrEBkNbW1lSo5lJQSM7PK87PSdXLyU/XyNNRSNPI09S05qr9DwA "JavaScript (Node.js) – Try It Online")
We compute:
$$\left\lfloor\frac{14}{n^n}+1\right\rfloor$$
which is \$\lfloor 14/1+1\rfloor=15\$ for \$n=1\$, \$\lfloor 14/4+1 \rfloor=4\$ for \$n=2\$, or \$1\$ for \$n>2\$.
We then XOR the result with \$1\$ if \$n \bmod 12=0\$.
[Answer]
# [Python 3](https://docs.python.org/3/), 28 bytes
```
lambda x:max(26-x*11,x%12>0)
```
[Try it online!](https://tio.run/##DcdBCoAgEADAc71iL8FuWKRCh6Be0sUoyzALM7DXW3Ob6w3b6WTS/ZisOqZZQewOFVG0VSw5Z7HgYmgo6dODAePAK7cuyBnIhro8u7xxAe/g0VBt9@cOKIiB/kvpAw "Python 3 – Try It Online")
-4 bytes thanks to ovs
If the boolean output is invalid (in Python, `True == 1` and `False == 0`), add `+` before the `max` to turn it into an int.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 11 bytes
```
12Ḋ⌐₄?11*-∴
```
[Try it online!](https://lyxal.pythonanywhere.com/)
Port of hyper-neutrino's Python answer
## How it works
```
12Ḋ⌐₄?11*-∴ - Program. N is on the stack
12Ḋ - Is N divisible by 12, 12 | N?
⌐ - Logical NOT
₄?11 - Push 26, N, 11
* - Yield 11×N
- - Yield 26 - 11×N
∴ - Maximum of (26 - 11 × N) and ¬(12 | N)
```
[Answer]
# [Vim](https://www.vim.org), ~~29~~ 28 bytes
*Thanks to @kops for -1 byte.*
```
C<C-r>=ma<S-Tab>[!!(<C-r>"%12),26-11*<C-r>"])
```
[Try it online!](https://tio.run/##K/v/31nINjexQiNaUVFDSEnV0EhTx8hM19BQS0gpVpPr/38jAA "V (vim) – Try It Online")
Vim port of @hyper-neutrino's python answer. In TIO, I couldn't figure out how to make `Shift`+`Tab` work, so it is 29 bytes there, but in Vim, you can use `Shift`+`Tab` to autocomplete `max(`, which is 1 less byte.
[Answer]
# PowerShell 7, 34 bytes
```
param($n)$n-1?$n-2?1-!($n%12):4:15
```
No TIO because PS7 (and so the ternary operator) is not supported.
[Answer]
# [Python 3](https://docs.python.org/3/), 35 bytes
```
lambda x:x<3and 26-x*11or x%12and 1
```
[Try it online!](https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRocKqwsY4MS9FwchMt0LL0DC/SKFC1dAIJGL4Pw3Iy1TIzFMoSsxLT9UwNtK04uIsKMrMK9HI1DbUUUgDUZqa/wE "Python 3 – Try It Online")
-3 bytes thanks to [hyper-neutrino](https://codegolf.stackexchange.com/users/68942/hyper-neutrino)
-1 byte thanks to [ophact](https://codegolf.stackexchange.com/users/100690/ophact)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ ~~12~~ 11 bytes
```
%12a*`14:‘Ʋ
```
[Try it online!](https://tio.run/##y0rNyan8/1/V0ChRK8HQxOpRw4xjm/4bG1kfbld51LTG/T8A "Jelly – Try It Online")
This used [hyper-neutrino's method](https://codegolf.stackexchange.com/a/225003/66833) and now uses a version of [Arnauld's](https://codegolf.stackexchange.com/a/225012/66833), so be sure to give them an upvote!
A direct translation of Arnauld's answer also comes out to 11 bytes:
```
*`14:‘_12ḍ$
```
[Try it online!](https://tio.run/##y0rNyan8/18rwdDE6lHDjHhDo4c7elX@GxtZH25XedS0xv0/AA "Jelly – Try It Online")
## How they work
```
%12a*`14:‘Ʋ - Main link. Takes N on the left
%12 - N % 12
Ʋ - Previous 4 links as a dyad f(N):
*` - N to the power N
14: - Floor divide 14 by that
‘ - Increment
a - If N % 12 is non-zero, replace it by f(N)
```
```
*`14:‘_12ḍ$ - Main link. Takes N on the left
*` - Raise N to its own power
14: - Floor divide 14 by N to the N
‘ - Increment it
$ - Previous 2 links as a monad f(N):
12ḍ - Is N divisible by 12?
_ - Subtract f(N) from the incremented division
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
A port of [hyper-neutrino's answer](https://codegolf.stackexchange.com/a/225003/64121).
```
«₂s-I12Ö_‚à
```
[Try it online!](https://tio.run/##AS4A0f9vc2FiaWX/MTMgRU5E/8Kr4oKCcy1OMTLDll/igJrDoP9OIsO/IC0@IMO/Iiz/ "05AB1E – Try It Online") (No, `END` does not actually end the program.)
**Commented:**
```
« # concatenate the input with itself
# this is the same as multiplying by 11 for small integers
₂s- # subtract this from 26
I # push the input again
12Ö_ # does 12 divide not divide the input? Booleans are represented as 0 and 1.
‚ # pair both values
à # take the maximum
```
Constructing the infinite list and indexing into it takes 12 bytes:
```
₄;16вλèN12Ö_
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UVOLtaHZhU3ndh9e4WdodHha/P//hkYA "05AB1E – Try It Online")
[Answer]
# [Snap!](https://snap.berkeley.edu/snap/snap.html), 6 blocks
[](https://i.stack.imgur.com/j7sgP.png)
straightforward implementation of the question, self explanatory
[Answer]
# JavaScript, 27 bytes
```
n=>n<3?[,15,4][n]:+!!(n%12)
```
bet you that I will get more upvotes on this answer than on some of my more complex ones.
*-6 thanks to @CommandMaster*
[Answer]
# MMIX, 32 bytes (8 instrs)
jxd
```
00000000: 1dff000c feff0006 7b01ff01 31ff0001 ø”¡€“”¡©{¢”¢1”¡¢
00000010: 6301ff0f 31ff0002 6301ff04 f8020000 c¢”Đ1”¡£c¢”¥ẏ£¡¡
```
Disassembly:
```
pdif DIV $255,$0,12
GET $255,rR // t = n % 12
ZSNZ $1,$255,1 // i = (bool)t
CMP $255,$0,1
CSZ $1,$255,15 // if(n == 1) i = 15
CMP $255,$0,2
CSZ $1,$255,4 // if(n == 2) i = 4
POP 2,0 // return i
```
Straight-line code!
[Answer]
# [Husk](https://github.com/barbuz/Husk), 15 bytes
```
!:15:4↓2J0C11∞1
```
[Try it online!](https://tio.run/##yygtzv7/X9HK0NTK5FHbZCMvA2dDw0cd8wz///9vZAIA "Husk – Try It Online")
The caveman approach: manually create the infinite list and index into it.
## Explanation
```
!:15:4↓2J0C11∞1
∞1 infinite list of 1s
C11 cut in pieces of 11
J0 join with zeroes
↓2 drop 2 elements
:4 prepend 4
:15 prepend 15
! index into it
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 15 bytes
```
12Ḋ⌐₄?11*-?2≤e*
```
[Try it Online!](https://lyxal.pythonanywhere.com/?flags=&code=12%E1%B8%8A%E2%8C%90%E2%82%84?11*-?2%E2%89%A4e*&inputs=2&header=&footer=)
```
12Ḋ # Is the input divisible by 12
⌐ # Negate that. So stack contains 0 for numbers divisible by 12 and 1 otherwise
₄?11*- # 26-11*n
?2≤e # Is the input less than equal to 2?
e # Take exponent
* # Multiply the two numbers in the stack and print the result.
```
[Answer]
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 79 bytes
```
> Input
> 26
> 11
> 12
> 1
>> 3⋅1
>> 2-6
>> 1∣4
>> 5-8
>> 7»9
>> Output 10
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hMtOwcgMSBgagggjEMFlZ6dg/Ki7Fcww0jUDUYaPOhabgBimuhYgyvzQbksQ7V9aAjREwdDg/38jEwA "Whispers v2 – Try It Online")
Same formula as my other answers, implemented in the verbosity of Whispers
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 38 bytes
```
$args|%{26-$_*11;+!!($_%12)}|sort -b 1
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkqZgq1D9XyWxKL24RrXayExXJV7L0NBaW1FRQyVe1dBIs7amOL@oREE3ScHwfy0Xl6GenrGBQo2CqkI1lwIQqBQlJqcWAw1RiYfyU4tLc0qAAmpAsyGyYInogGDn0uKS/Fz/pKzU5JJYB4h@EAiCGYFQDQIumWlpYFGwiWDhWq7a/wA "PowerShell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 25 bytes
```
lambda x:2/x*7/x+(x%12>0)
```
[Try it online!](https://tio.run/##Nc5PC4IwFADw@z7Fu8RzpelMs4QJXYIo6At4MXI00DnUg336pZu9y4/H@6u/46dTsRG8NE3Vvt4VTHkcTtssnHbetGFxEVEjuh4aqWqQChCRQVAAS0m8mJCDTUniSB1HR@Y4Oc4OFq2yVbsoIsxtmi/sB93I0cNSIc0JzCH9Dji0lfakGn37zb9pGUJKbZvu57Kt@oBBEODM844gBQhPUuAcOqiboQa8Xm4PND8 "Python 2 – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 36 bytes
```
.+
$*_
^(_{12})+$
0
___+
1
__
4
_
15
```
[Try it online!](https://tio.run/##K0otycxL/K@nzaWipqJ1aBsXl4peApehYwKXqoZ7AlhcK54rTiO@2tCoVlNbhcuAKz4@XpvLEEhxmXDFcxma/v9vaAwA "Retina 0.8.2 – Try It Online") Link includes test suite that outputs the answers from `1` to `N`. Explanation:
```
.+
$*_
```
Convert `N` to unary.
```
^(_{12})+$
0
```
The result is `0` if `N` is a multiple of `12`, ...
```
___+
1
```
... `1` if `N>2`, ...
```
__
4
```
... `4` if `N=2`, ...
```
_
15
```
... and `15` if `N=1`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
I⌈⟦‹⁰﹪N¹²⁻²⁶ײθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexIjO3NDfaJ7W4WMNAR8E3P6U0J1/DM6@gtMSvNDcptUhDU0fB0EgTSPpm5pUWaxiZ6SiEZOamAlk6CoWamrGamtb//xv91y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @ovs's 05AB1E answer.
```
N Input as a number
﹪ ¹² Modulo 12
‹⁰ Is greater than 0
θ Input as a string
ײ Duplicated i.e. multiplied by 11
⁻²⁶ Subtracted from 26
⟦ Pair into a list
⌈ Take the maximum
I Cast to string
Implicitly print
```
[Answer]
# [Zsh](https://www.zsh.org/), 27 bytes
Boring ternary math function.
```
()(($1<3?26-11*$1:$1%12>0))
```
[Try it online!](https://tio.run/##qyrO@F@cWpJfUKKQnJRYnFrMlVaal1ySmZ9XrKDrq5DGlRbzX0NTQ0PF0MbY3shM19BQS8XQSsVQ1dDIzkBT8z9XWn6RQrKCRrWhnp6xUa2mQkFRZl6JgoqGhkKaRrKmAlAJAA "Zsh – Try It Online")
---
## [Zsh](https://www.zsh.org/) `--cbases`, 29 bytes
```
k=e3
<<<$[0x$k[$1]+!!($1%12)]
```
[Try it online!](https://tio.run/##qyrO@F@cWpJfUKKQnJRYnFrMlaahqfE/2zbVmMvGxkYl2qBCJTtaxTBWW1FRQ8VQ1dBIM/a/JhdXWn6RQrKCRrWhnp6xUa2mQpqCSvJ/AA "Zsh – Try It Online")
More interesting, using hexadecimal `0xe` and `0x3` to add 14 and 3 to the first two cases.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 27 bytes
```
f(n){n=n<3?26-n*11:n%12>0;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOs82z8bY3shMN0/L0NAqT9XQyM7AuvZ/bmJmnkamZnVBUWZeSZqGkmqKlYJqSkyekk6mThpQQtM608bYSE0NrE5bO1MTqAcA "C (gcc) – Try It Online")
[Answer]
# [Lua](https://www.lua.org/), 52 bytes
```
function f(n)return 14/n^n+1|((n%12<1)and 1 or 0)end
```
[Try it online!](https://tio.run/##BcFBCoAwDATAr@QiJAhqxKNvEYpNoSBbCC1e/HuceUaKKAN3rw1UGOLWh4P0WHFh1o8Zk@6nSkImpea0iSFHbcvrtRsXVpGIHw "Lua – Try It Online")
] |
[Question]
[
Inspired by [this StackOverflow question](https://stackoverflow.com/questions/52990870/splitting-double-quatation-comma-lines-in-java/).
## Input:
We'll take three inputs:
* A delimiter-character `D` to split on
* A character `I` between two of which we ignore the delimiter character (I know, that sounds vague, but I'll explain it below)
* A string `S`
## Output:
A list/array containing the substrings after the split.
## Example:
```
Input:
D = ','
I = '"'
S = '11020199,"Abc ",aduz,,444,bieb,dc,2 ,2222.00,whatever 5dc,222.22,22.00,"98,00","12,000,000",21-09-2018, 06:00,",-,"'
Output:
['11020199', 'Abc ', 'aduz', '', '444', 'bieb', 'dc', '2 ', '2222.00', 'whatever 5dc', '222.22', '22.00', '98,00', '12,000,000', '21-09-2018', ' 06:00', ',-,']
```
Why? Splitting on comma would normally also split `98,00`, `12,000,000` and `,-,` in two/three pieces. But because they are within the `I` input character, we ignore ignore the split here.
## Challenge rules:
* You can assume there will always be an even amount of `I` characters in the input-string.
* You can assume the character `I` will always have a `D` next to it (except when it's the first or last character of the input) which can still be properly split. So you won't have something like `D = ','; I = '"'; S = 'a,b"c,d"e,f'`, nor anything like this `D=','; I='"'; S='a",b,"c'`.
* The input-string `S` could contain none of either `D` or `I`. If it contains no `D`, we output a list with the entire input-string as only item.
* The output list won't contain the character `I` anymore, even when it contained no `D` (as you can see at the `"Abc "` becoming `'Abc '` in the example above).
* It is possible that the substring within `I` contains only `D`. For example: `D = ','; I = '"'; S = 'a,",",b,"c","d,e,,",f'` would result in `['a', ',', 'b', 'c', 'd,e,,', 'f']`.
* You can assume that `D` will never be at the start or end of `S`, so you won't have to deal with trailing / leading empty items.
* When an input has two adjacent `D`, we'll have an empty item. I.e. `D = ','; I = '"'; S = 'a,"b,c",d,,e,"",f'` would result in `['a', 'b,c', 'd', '', 'e', '', 'f']`.
* You can assume the inputs and outputs will only contain printable ASCII in the range `[32, 126]` (so excluding tabs and newlines).
* You are also allowed to output all items new-line delimited instead of returning/outputting a list/array (especially for those languages that don't have lists/arrays; i.e. Retina).
* You are allowed to output the list in reversed order if it saves bytes. You are not allowed to output it in sorted or 'shuffled' order, though. So `D = ','; I = 'n'; S = 'a,2,b,3,c'` can be output as `[a,2,b,3,c]` or `[c,3,b,2,a]`, but not as `[2,3,a,b,c,]` or `[a,3,b,c,2]` for example.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
```
Input:
D = ','; I = '"'; S = 'a,"b,c",d,,e,"",f'
Output:
['a', 'b,c', 'd', '', 'e', '', 'f']
Input:
D = ','; I = '"'; S = '11020199,"Abc ",aduz,,444,bieb,dc,2 ,2222.00,whatever 5dc,222.22,22.00,"98,00","12,000,000",21-09-2018, 06:00,",-,"'
Output:
['11020199', 'Abc ', 'aduz', '', '444', 'bieb', 'dc', '2 ', '2222.00', 'whatever 5dc', '222.22', '22.00', '98,00', '12,000,000', '21-09-2018', ' 06:00', ',-,']
Input:
D = ' '; I = ','; S = 'this is a test , to see if you understand it, or not , hmmm, I think I have too many commas , or not , perhaps..'
Output:
['this', 'is', 'a', 'test', ' to see if you understand it', 'or', 'not', ' hmmm', 'I', 'think', 'I', 'have', 'too', 'many', 'commas', ' or not ', 'perhaps..']
Input:
D = 'x'; I = 'y'; S = 'contains no lowercase X nor Y'
Output:
['contains no lowercase X nor Y']
Input:
D = '1'; I = '3'; S = '3589841973169139975105820974944592078316406286208948254211370679314'
Output: ['58984197', '69', '9975105820974944592078', '64062862089482542', '', '70679', '4']
Input:
D = ' '; I = 'S'; S = 'regular split on spaces'
Output:
['regular', 'split', 'on', 'spaces']
```
[Answer]
# [R](https://www.r-project.org/), 34 bytes
Regular unmodified `scan` with the appropriate arguments for `text`, `sep` and `quote` should do it.
```
function(D,I,S)scan(,t=S,"",,,D,I)
```
[Try it online!](https://tio.run/##LY5BCoNADEX3nmLIRoVvyQRbnIKLghvXnkBHpW4sWG2hl59maAPhwUtI/hbmOszH6vflsWYNWnT50/drhr3uQARAZR4aU5sUadJGUpp0CmtZ2DoHug3eEPrx@ABlWWJYpgGjhxiI1okZ73u/T69pM@fo1YngNyFXgZlAVpQcmyC2YFfo@QqGL9e4hgL6eP6HDF8 "R – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 64 bytes
```
c;f(d,i,s)char*s;{for(;*s;s++)*s==i?c=!c:putchar(d-*s|c?*s:10);}
```
[Try it online!](https://tio.run/##XU7BTsMwDL3zFSaXtZ07pdFA66pp4sg/9JKlKY1QkqlOh8bYtxcXLgjbcV7sZ@eZ8s2YeTZNn3XokHIz6LGg5tbHMWsY0HqdF3Q4uKM5PJr9eUoLI@vKgr7MsaB9JfPmPnvtQpbfHvpshexihaKqpJJVXWMrXk4GWoG6mz4Rt9stnpw9YWdQASq2jZT4MehkL3aEp6XONaXwt9OKeodS8oJWVIqRXA4/VVXKuuRPdgjyef9DxZKTyBsWSploA8NFFPzIQpEGR8ChIVlKgJAikLXgerjGCabQ2ZGSDh24hBBHCHFhDd57hFfg8fDO96AvlkcjeB2uYKL3muAP/2zHQZ9ps/mn5D5/Aw "C (gcc) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 57 bytes
```
(d,i,s)=>s.replace(c=/./g,e=>i==e?(c^=1,''):d!=e|c?e:`
`)
```
[Try it online!](https://tio.run/##XY7BbsMgDIbvewqPC4nkpCRqp6YTrXaptHeIJlHwGrYGokA7ddq7Z6S7VMNg4Pdv@D7URQU92iEWzhua9nLKDFoMudyGcqThpDRlWi7KxRFJbq2UtMv0m6yQ83xjHiX96B1teOt4Pmnvgj9RefLHbJ9xTME4sqoStaiaBlv2ctDQMlTm/I24XC7xYOmARmMNWKdRCoFfnYp0oRFWs560usa/SsuaNQqRHmhZVaeTmFe61lUhmiJ9skYQT5ubFYuUWJ4/P9xjJdA5@D850cKNF1nsbIA0FUQKERCih0AE9h2u/gxnZ2gMUTkDNiL4EZyfXV3f9wivkNrdZ9o7daHU6qFX7gra970KcOcfaOzUEMpyRpx@AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 18 bytes
```
FxcxQb?!:oOo?xRanx
```
Takes inputs as command-line arguments. [Try it online!](https://tio.run/##JYzNCsIwEIRfJZ72MpHNEqXppXjxKvoGSRqwF1uKP8GXX1McGAa@GWaZFtVzzfWahl0/X@ah3uKjqiqU1DkWdiGATikbQhxfX8B7jzSVhDFDDKRpz4zPPT7Lu6zmsPHGRPBvKHRgJpCTlryZIM5ysO2@g@Fjv81gQT8 "Pip – Try It Online")
Completely different approach: process the string one character at a time and output the desired results newline-delimited.
### How?
```
a,b,c are cmdline args (respectively representing D,I,S); o is 1;
n is newline (implicit)
We use o for a flag indicating whether or not to change D into newline
Fxc For each character x in c:
xQb? If x equals b (the ignore character),
!:o Logically negate o in-place
O Else, output the following (with no trailing newline):
o? If o is truthy,
xRan x, with a (the delimiter) replaced with newline
x Else, x unchanged
```
[Answer]
# Python 2, 67 bytes
```
import csv
lambda D,I,S:next(csv.reader(S,delimiter=D,quotechar=I))
```
[Try it online!](https://tio.run/##fYzNasMwEITvfgqhiyUYh5VwSxzwoZBLzj6GHmRLwYL4p6qctnl5V07uGdgd@GZ35r/YT6NeVz/MU4is@75lVzO01rAjTmgOo/uNItFdcMa6IBpYd/WDjy7UR3wtU3Rdb0J9knK91C9fz82nlNkjq/04L1HIbA5@jOwiHlSuIkcOlvNtKUWaVFWBf7Qd4zB2uQNlWaL1roXtoBl00o4IP72J7uYCe9t4YlrjmfBqDyIOrnRy2oZDq4KqItXvwej9sJ2hAM/lPw "Python 2 – Try It Online")
# Python 2, 71 bytes
```
D,I,S=input()
k=1
for p in S.split(I):print p.replace(D*k,'\n'*k),;k^=1
```
[Try it online!](https://tio.run/##JUzNCsIwGLv7FB@9dBvZ@FqmbMoOghfPXkXYT2VlUsusir783DCQBJIQ/wn93elpOuCIU2Wdf4YoXg2VWl3vI3myjk7Zw99siI7x1o/WBfLZaPytbk10SAbIs5PJEGM3XCo1TZGEBEmxiFKsWZUlxL5pSaDunl8gz3M01jToWmiCnpEx493XwbzMSOslnzOt8W9EWYBZQCg9Oy8U0CrlMp3vCxBvtssMKYSMfw "Python 2 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 24 bytes
```
y=Yso~yi=*~*cO10Zt2G[]Zt
```
Inputs are `S`, `I`, `D`.
[Try it online!](https://tio.run/##y00syfn/v9I2sji/rjLTVqtOK9nf0CCqxMg9Ojaq5P9/9UQdpSSdZCWdFB2dVB0lJZ00dS51JSDWUQcA) Or [verify all test cases](https://tio.run/##TZDfS8MwEMff/SuO@FAYt5GkaZsIexAE8ckHfZgTwazNbHFtRpP9qA/71@dVRXbkwyX3/d4lpLVxc34/D/OX4E9DM5@cJuWj4Mso71/flvGcXP9HsrhbHp/PiUW2wpJhheiQMVwnVwkjkBCCSy6MQXa7KoGhrXZfiEopXDVuhVWJElBSzDjHQ22j27sesrFONSnxV2FGI@cMmZCU@QhDKabcTGm8RuD5zWjDKbKL22PdBKBlIboQASF6CM5Bs4bB72DXVa4P0XYVNBHB99D50VW3bYvwANTefVKu7d5Rq4fWdgOUvm1tgAv/1vW13YbZ7O9aIErfRdt0gSyw8QfXlzY4WNCxhxfSB@JIpJk2WglTpCI3IjWmyATPtOSmUEapzEheaNIUz6XOJddGaZkpKURa8LwwqVDjlPGrid597Da2h7DdNBF8RxtbukDK08@7vgE).
### How it works
Consider inputs `D = ','`; `I = '"'`; `S = 'a,"b,c",d,,e,"",f'`.
```
y % Implicit inputs: S, I. Duplicate from below
% STACK: 'a,"b,c",d,,e,"",f', '"', 'a,"b,c",d,,e,"",f'
= % Is equal? Element-wise
% STACK: 'a,"b,c",d,,e,"",f', [0 0 1 0 0 0 1 0 0 0 0 0 0 1 1 0 0]
Ys % Cumulative sum
% STACK: 'a,"b,c",d,,e,"",f', [0 0 1 1 1 1 2 2 2 2 2 2 2 3 4 4 4]
o~ % Parity, negate
% STACK: 'a,"b,c",d,,e,"",f', [1 1 0 0 0 0 1 1 1 1 1 1 1 0 1 1 1]
y % Duplicate from below
% STACK: 'a,"b,c",d,,e,"",f', [1 1 0 0 0 0 1 1 1 1 1 1 1 0 1 1 1], 'a,"b,c",d,,e,"",f'
i= % Input: D. Is equal? Element-wise
% STACK: 'a,"b,c",d,,e,"",f', [1 1 0 0 0 0 1 1 1 1 1 1 1 0 1 1 1], [0 1 0 0 1 0 0 1 0 1 1 0 1 0 0 1 0]
*~ % Multiply, negate (equivalent to NAND). Element-wise
% STACK: 'a,"b,c",d,,e,"",f', [1 0 1 1 1 1 1 0 1 0 0 1 0 1 1 0 1]
* % Multiply, element-wise. Characters are converted to ASCII code
% STACK: [97 0 34 98 44 99 34 0 100 0 0 101 0 34 34 0 102]
c % Convert to char (character 0 is shown here as '·')
% STACK: 'a·"b,c"·d··e·""·f'
O10 % Push 0 and then 10
% STACK: 'a·"b,c"·d··e·""·f', 0, 10
Zt % Replace character 0 by character 10 (newline; shown here as '¶')
% STACK: 'a¶"b,c"¶d¶¶e¶""¶f'
2G[] % Push second input (I) and then [] (empty array)
% STACK: 'a¶"b,c"¶d¶¶e¶""¶f', '"', []
Zt % Replace character given by input I by empty; that is, remove it. Implicit display
% STACK: 'a¶b,c¶d¶¶e¶¶f'
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 16 bytes
```
qV mÏu ?X:XrWRÃq
```
[Try it!](https://ethproductions.github.io/japt/?v=1.4.6&code=cVYgbc91ID9YOlhyV1LDcQ==&input=JzExMDIwMTk5LCJBYmMgIixhZHV6LCw0NDQsYmllYixkYywyICwyMjIyLjAwLHdoYXRldmVyIDVkYywyMjIuMjIsMjIuMDAsIjk4LDAwIiwiMTIsMDAwLDAwMCIsMjEtMDktMjAxOCwgMDY6MDAsIiwtLCInCiciJwonLCcK)
Basically the same strategy as DLosc's newer Pip answer, sets aside the "quoted" sections then replaces the delimiter with a newline in the rest of the string, resulting in a newline delimited output
Full explanation:
```
qV Split on I
m à For each segment:
Ïu ? If the segment has an odd index (quoted)...
X Keep it as-is
: Otherwise:
XrWR Replace each D in the segment with a newline
q Join it all to a single string
```
Note that even if the first item is quoted, it will still end up at index 1 not index 0. If `q` finds a delimiter as the first character, it makes the first item in the split (index 0) an empty string, so the contents of the quote correctly become the second item (index 1). [Here](https://ethproductions.github.io/japt/?v=1.4.6&code=cVYgbc91ID9YOlhyV1LDcQ==&input=JyJhLGIiLGMnCiciJwonLCcK) is a demo of correctly dealing with a leading quote.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 45 bytes
```
L$`(?=.*¶(.)¶(.))(\2(.*?)\2|(.*?))(\1|¶)
$4$5
```
[Try it online!](https://tio.run/##K0otycxLNPz/30clQcPeVk/r0DYNPU0woakRY6Shp2WvGWNUA6aBAoY1h7ZpcqmYqJj@/5@oo5Skk6ykk6Kjk6qjpKSTxqXDpQQA "Retina – Try It Online") Explanation:
```
(?=.*¶(.)¶(.))(\2(.*?)\2|(.*?))(\1|¶)
```
Look ahead to find the values of `D` and `I` on the following two lines. Then, if we find an `I` then eat it and match the characters to the next `I` and `D`, otherwise just match characters to the next `D` or the end of the line.
```
L$`
$4$5
```
List captures 4 and 5 from each match; 4 is the capture between two `I`s while 5 is the capture between two `D`s.
[Answer]
# Powershell, 71 bytes
```
param($d,$i,$s)$s-split{(1-($script:a+=$i-ceq$_)%2)*($d-ceq$_)}|% *m $i
```
Less golfed test script:
```
$f = {
param($d,$i,$s)
$s-split{
$script:a+=$i-ceq$_
(1-$a%2)-and($d-ceq$_)
}|% Trim $i
}
@(
,(',','"',
'',
'')
,(',','"',
'a,"b,c",d,,e,"",f',
'a', 'b,c', 'd', '', 'e', '', 'f')
,(',','"',
'11020199,"Abc ",aduz,,444,bieb,dc,2 ,2222.00,whatever 5dc,222.22,22.00,"98,00","12,000,000",21-09-2018, 06:00,",-,"',
'11020199', 'Abc ', 'aduz', '', '444', 'bieb', 'dc', '2 ', '2222.00', 'whatever 5dc', '222.22', '22.00', '98,00', '12,000,000', '21-09-2018', ' 06:00', ',-,')
,(' ',',',
'this is a test , to see if you understand it, or not , hmmm, I think I have too many commas , or not , perhaps..',
'this', 'is', 'a', 'test', ' to see if you understand it', 'or', 'not', ' hmmm', 'I', 'think', 'I', 'have', 'too', 'many', 'commas', ' or not ', 'perhaps..')
,('x','y',
'contains no lowercase X nor Y',
'contains no lowercase X nor Y')
,('1','3',
'3589841973169139975105820974944592078316406286208948254211370679314',
'58984197', '69', '9975105820974944592078', '64062862089482542', '', '70679', '4')
,(' ','S',
'regular split on spaces',
'regular', 'split', 'on', 'spaces')
) | % {
$d,$i,$s,$expected = $_
$result = &$f $d $i $s
"$("$result"-eq"$expected"): $result"
}
```
Output:
```
True:
True: a b,c d e f
True: 11020199 Abc aduz 444 bieb dc 2 2222.00 whatever 5dc 222.22 22.00 98,00 12,000,000 21-09-2018 06:00 ,-,
True: this is a test to see if you understand it or not hmmm I think I have too many commas or not perhaps..
True: contains no lowercase X nor Y
True: 58984197 69 9975105820974944592078 64062862089482542 70679 4
True: regular split on spaces
```
Explanation:
* The script block in the `-split{...}` specifies rules for applying the delimiter. See [about\_split](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_split).
* `$script:a=...` sets the variable `a` in outer [scope](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes).
* `-ceq` means [case-sensitive equation](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators).
* `|% trim $i` calls a [method `trim` with argument `$i`](https://docs.microsoft.com/en-gb/dotnet/api/system.string.trim?view=netframework-4.7.2#System_String_Trim_System_Char___).
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 109 bytes
```
D =INPUT
I =INPUT
S =INPUT
S S (I ARB . OUTPUT I | ARB . OUTPUT) (D | RPOS(0)) REM . S DIFFER(S) :S(S)
END
```
[Try it online!](https://tio.run/##VY1BC4JAEIXP@iveUUGkQ6egQ6HCHlJx9QdsubFSuyvuGgj9d5sORcEw8/jmPZ4z9mzv23UNMuxZWXdtGLCv4h/FSUYMh@aIFFXXEgPD8w/EiDJCTV3xaBPHaPIT/XiQsaLIm4jHwY7TDvMyW1eESejV4EAj4KXzSOAtnJQYrljsjNn0cnJemB6DT2AnGPt2Ka11Qu0UNze6SjwkRS20MAsuVmvh8OMf5aTE6NL0BQ "SNOBOL4 (CSNOBOL4) – Try It Online")
Suppose that `D =','` and `I ='"'`. Then the pattern `(I ARB . OUTPUT I | ARB . OUTPUT) (D | RPOS(0))` matches strings that look like `".*"` or `.*` followed either by `,` or by the end of the string, and OUTPUTs the arbitrary (`.*`) characters, setting the unmatched REMainder to `S` and iterating so long as `S` is not empty.
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-n`, ~~29~~ 24 bytes
```
cR Xa[na]@(bN{$`})^n||:b
```
Takes inputs as command-line arguments. [Try it online!](https://tio.run/##JYzNCsIwEIRfJQdhFSayWaI0PekLePAkiGKSFuylFPEHtD77muLAMPDNMEM3qOa9OcRjH0@bedp9Zpfv4tyPY51U1fYKJXWOhV0IoG3KhhCbxxvw3iN1bUKTIQZStGTG6xrv7bO9mdXECxPBv6FQgZlATkryZII4y8GW@wqG1/U0gwX9AA "Pip – Try It Online")
Strategy: outside `I` pairs, replace `D` with newline (since we're guaranteed that newlines won't appear in the string). Then split on newline and strip `I`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
;`j⁵œṣ⁴œṣḊṖYʋ€Ðo³Y
```
A full program taking the three arguments `D`, `I`, `S` which prints each item on a line.
**[Try it online!](https://tio.run/##y0rNyan8/986IetR49ajkx/uXPyocQuYfrij6@HOaZGnuh81rTk8If/Q5sj///@r66j/V1cCYkNDAyMDQ0tLHSXHpGQFJZ3ElNIqHR0TExOdpMzUJJ2UZB0jBR0jINAzMNApz0gsSS1LLVIwBYkDxYyMdCAySpYWOgYGSjpKhkZA2gCElXSMDHUNLHWBxlvoKBiYWYGU6ejqKKkDAA "Jelly – Try It Online")** (Footer joins with newlines)
### How?
Surround with an extra `D` on each side, split at `I`s, split the odd-indexed items at `D`s then remove their heads and tails and join them with newlines, finally join the result with newlines.
[Answer]
# [PHP](https://php.net/), 50 bytes
```
function q($D,$I,$S){return str_getcsv($S,$D,$I);}
```
[Try it online!](https://tio.run/##TVJRb9owEH5ufsXJigRIB7KNQ@LSaZq0lz7zsgmhygTTWCNOZjt0rOpvpwdjEra/O/m@73y2zn3Tn5@@9mT3g6@T6zz8HuffMX/GfDV5DzYNwUNM4eXVpjoex/kKr/Rk@XHOne@HFOELrLOH9QhpMoIQXHKhNbJv2xoYmt3wF1EphVtnt7irUQJKGjPO8a0xyR5tgOISp5iU@I9hukLOGTIhyfMLGEox5XpKx1cIfPF4keEU2WiD9zcwyLZYM9whWmQM9zcergocpcZFoGUg2ZgAIXUQrQW3h1M3wOB3NsRk/A5cQugC@O6iatq2RXgGSve/yDfmaCm1g9b4E9Rd25oId/rehsb0cTa7lf9DpU@EuvPJOB9JBofuzYbaRAs/aBvg500rSDe/oKh0pYQu52KhxVzrshC8qCTXpdJKFVrysiJO8YWsFpJXWlWyUFKIeckXpZ4Ldff4FSHY1@FgAsT@4BJQw2NvahtHm2yzzLJ9F6ypm/H/3tKLcjd5zx764Hx6CWP6Hm7NN0hWXK3cTCbL7OP8CQ "PHP – Try It Online") Uses a [built-in function](http://php.net/manual/en/function.str-getcsv.php).
If rearranging the inputs is allowed (`(S,D,I)` so it matches the `str_getcsv` signature), I have a [44 byte version](https://tio.run/##TVHfa9swEH6u/4pDGGLDxUiy/EPLxhjspc952SihKLZSm8WyK8npstK/PZPbFCLpu0P3fafTcVM3Xb5@n4I9zKbx/WjgOcmyLJ7SV6v9bA04bx@ftG/c6Ups3i5xb6bZO/gGD9HdwwrDJgGMUU6ZlEh@7BsgqNr5H6IQAve93mPbIAfkYWWU4kunvD5pC8USDzHO8YMhskZKCRLGg6cLCHK2pnIdnq8RaPllkeEayWqHtz9QSPbYEGwRNRKChysP7wpc@a53EI4Cr50HBD@C0xr6A5zHGWbTauu8Mi30HmG0YMZF1Q3DgHAPId38Cb5TJx1SRxiUOUMzDoNycKOftO3U5LLsWv5vKH0OaEbjVW9ckMFxfNG2UU7Dr3C18PuqZUGXLyhqWQsmq5yVkuVSVgWjRc2prIQUopCcVnXgBC15XXJaS1HzQnDG8oqWlcyZuGl@G2D103xUFtx07D2EUbtJNdqtdtFuE0WH0WrVdMnnbENHx975JP6J8T3G2zR9je4m2xv/aJPnJN7iO5Omm@jt8h8).
] |
[Question]
[
What you need to do is create a function/program that takes a decimal as input, and outputs the result of repeatedly taking the reciprocal of the fractional part of the number, until the number becomes an integer.
More specifically, the process is as follows:
1. Let x be the input
2. If x is an integer, output it.
3. Otherwise: \$x \leftarrow \frac{1}{\mathrm{frac}(x)}\$. Go back to 2.
\$\mathrm{frac}(x)\$ is the fractional component of \$x\$, and equals \$x - \left\lfloor x \right\rfloor\$. \$\left\lfloor x \right\rfloor\$ is the floor of x, which is the greatest integer less than \$x\$.
Test cases:
```
0 = 0
0.1 = 1/10 -> 10
0.2 = 1/5 -> 5
0.3 = 3/10 -> 10/3 -> 1/3 -> 3
0.4 = 2/5 -> 5/2 -> 1/2 -> 2
0.5 = 1/2 -> 2
0.6 = 3/5 -> 5/3 -> 2/3 -> 3/2 -> 1/2 -> 2
0.7 = 7/10 -> 10/7 -> 3/7 -> 7/3 -> 1/3 -> 3
0.8 = 4/5 -> 5/4 -> 1/4 -> 4
0.9 = 9/10 -> 10/9 -> 1/9 -> 9
1 = 1
3.14 = 157/50 -> 7/50 -> 50/7 -> 1/7 -> 7
6.28 = 157/25 -> 7/25 -> 25/7 -> 4/7 -> 7/4 -> 3/4 -> 4/3 -> 1/3 -> 3
```
Summary for 0 to 1 at increments of 0.1: 0, 10, 5, 3, 2, 2, 2, 3, 4, 9, 1
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins.
Clarifications:
* "Bonus points" for no round-off error
* Should work for any non-negative rational number (ignoring round-off error)
* You can, but don't have to output the steps taken
* You can take input as a decimal, fraction, or pair of numbers, which can be in a string.
Sorry for all the issues, this is my first question on this website.
[Answer]
# Mathematica, 36 bytes
```
Last@*ContinuedFraction@*Rationalize
```
### Demo
```
In[1]:= f = Last@*ContinuedFraction@*Rationalize
Out[1]= Last @* ContinuedFraction @* Rationalize
In[2]:= f[0]
Out[2]= 0
In[3]:= f[0.1]
Out[3]= 10
In[4]:= f[0.2]
Out[4]= 5
In[5]:= f[0.3]
Out[5]= 3
In[6]:= f[0.4]
Out[6]= 2
In[7]:= f[0.5]
Out[7]= 2
In[8]:= f[0.6]
Out[8]= 2
In[9]:= f[0.7]
Out[9]= 3
In[10]:= f[0.8]
Out[10]= 4
In[11]:= f[0.9]
Out[11]= 9
In[12]:= f[1]
Out[12]= 1
```
[Answer]
# J, 18 bytes
```
%@(-<.)^:(~:<.)^:_
```
In J, the idiom `u ^: v ^:_` means "Keep applying the verb `u` while condition `v` returns true.
In our case, the ending condition is defined by the hook `~:<.`, which means "the floor of the number `<.` is not equal `~:` to the number itself" -- so we'll stop when the main verb `u` returns an int.
`u` in this case is another hook `-<.` -- the number minus its floor -- whose return value is fed into `@` the reciprocal verb `%`.
[Try it online!](https://tio.run/##XcnBCkBAFIXh/TzFSQnFNGMIN1OehIVMsrGw5tWHXLOxOP19nc27A5ag8MzHQ1r0Mhspvejt5DMRSSTOUoIcJ8EdQizzuqMCLByUbNlafdbsOvwl2wSbnxt2F9yxG7aRuvI3 "J – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 101 bytes
```
lambda s:g(int(s.replace(".","")),10**s[::-1].index("."))
g=lambda a,b:a and(b%a and g(b%a,a)or b//a)
```
[Try it online!](https://tio.run/##Xc7NDsIgDAfwu09BSExgQTbc/CLZk6gHEIZLJiNsB316lMWD9tL2l@bfNLzm@@jr1LWXNKiHNgpN0pHez2Ti0YZB3SzBHDOMKWWiKorpLOVGXHnvjX3mFaUr136zimn5qd4QvV46cnliio4R6bJUNIWYj3cEV7zK2R8L4C1wDdwA74D3wAfgI/Dpz2L5L70B "Python 3 – Try It Online")
Format: the string must contain a decimal point.
[Answer]
# [Perl 6](http://perl6.org/), 42 bytes
```
{($_,{1/($_-.floor)}...*.nude[1]==1)[*-1]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkMlXqfaUB9I6eql5eTnF2nW6unpaenllaakRhvG2toaakZr6RrG1v63VihOrFRIA6rUNzTQVEjLL1Iw1NMzNPgPAA "Perl 6 – Try It Online")
The `nude` method returns the **nu**merator and **de**nominator of a rational number as a two-element list. It's shorter to get the denominator this way than to call the `denominator` method directly.
[Answer]
# [PHP](https://php.net/), 69 bytes
```
for(;round(1e9*$a=&$argn)/1e9!=$o=round($a);)$a=1/($a-($a^0));echo$o;
```
[Try it online!](https://tio.run/##JYpNCsIwEIX3vYVhkI7FNgE3ZTp4kSIErSabTAi6kp49Tu3i/fG9HHKdrjnkBnx5JTa2vxhqnlJaiGwJ4sROvWPbO/zuJ4hUtwcV@aRH65bxBJ6Pf4iDzgOD8A7BI6FSN2g9q24WkZZ7EBCqW5r5DXFOhtb6Aw "PHP – Try It Online")
# [PHP](https://php.net/), 146 bytes
```
for($f=.1;(0^$a=$argn*$f*=10)!=$a;);for(;1<$f;)($x=($m=max($a,$f))%$n=min($a,$f))?[$f=$n,$a=$x]:$f=!!$a=$m/$n;echo($o=max($a,$f))>1?$o:min($a,$f);
```
[Try it online!](https://tio.run/##TYzLCsIwFET3/kXLCDel1AZ3vb3mQ0QhiDEu8qCr/H3aCqK7OczMyT7X2WSfD7DLK0o7DueWq0sLwcmgmcY7rHzKDq4TPapmQ1a8b1jPcKwIRQhBgi0E28MpdUSU8I5fNNdNh9jvrnKbNmiaPYcTIj8fPhHS//2iDdL0E3CtKw "PHP – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 47 bytes
This beats [Wheat Wizard's answer](https://codegolf.stackexchange.com/a/152377/71256) because `GHC.Real` allows us to pattern match on rationals using `:%`, aswell as having a shorter name
```
import GHC.Real
f(x:%1)=x
f x=f$1/(x-floor x%1)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMHdw1kvKDUxhytNo8JK1VDTtoIrTaHCNk3FUF@jQjctJz@/SKECKP4/NzEzz7agKDOvRCVNwVjP0OQ/AA "Haskell – Try It Online")
`f` takes a `Rational` number as input, although ghc allows them to be written in a decimal format, within a certain precision.
[Answer]
# [Haskell](https://www.haskell.org/), ~~40~~ 34 bytes
Edit:
* -6 bytes: @WheatWizard pointed out the fraction can probably be given as two separate arguments.
(Couldn't resist posting this after seeing Haskell answers with verbose imports – now I see some other language answers are also essentially using this method.)
`!` takes two integer arguments (numerator and denominator of the fraction; they don't need to be in smallest terms but the denominator must be positive) and returns an integer. Call as `314!100`.
```
n!d|m<-mod n d,m>0=d!m|0<1=div n d
```
[Try it online!](https://tio.run/##LcxNCoMwEIbhfU8RpYuEqCS1v6CepJtgAgbNGKK2FLx7Wjuuno@Bdzo19WYYolMWaguzCaqdjwsMFsxUOOXp0@eN5zwleUNSzqdufFO6QLuE8KEJYzQYpYlnjBX/KEKiV1flbtQEiM5cI2qduFVUstb2td1ipCKTgh2oRE5IiZyRC3JFbsgdeez5/qaUW/NbXw "Haskell – Try It Online")
* Ignoring type mismatch, the fractional part of `n/d` (assuming `d` positive) is `mod n d/d`, so unless `mod n d==0`, `!` recurses with a representation of `d/mod n d`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
®İ$%1$©¿
```
[Try it online!](https://tio.run/##y0rNyan8///QuiMbVFQNVQ6tPLT/////BnqGAA "Jelly – Try It Online")
Floating-point inaccuracies.
[Answer]
# [Python 3](https://docs.python.org/3/) + [sympy](http://www.sympy.org/en/index.html), 67 bytes
```
from sympy import*
k=Rational(input())
while k%1:k=1/(k%1)
print(k)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehuDK3oFIhM7cgv6hEiyvbNiixJDM/LzFHIzOvoLREQ1OTqzwjMydVIVvV0Crb1lBfA8jQ5Cooyswr0cjW/P/fQM8cAA "Python 3 – Try It Online")
Sympy is a symbolic mathematics package for Python. Because it is symbolic and not binary, there are no floating point inaccuracies.
[Answer]
# JavaScript ES6, 25 bytes
```
f=(a,b)=>a%b?f(b,a%b):a/b
```
Call `f(a,b)` for `a/b`
[Answer]
# [Haskell](https://www.haskell.org/), ~~62~~ 61 bytes
```
import Data.Ratio
f x|denominator x==1=x|u<-x-floor x%1=f$1/u
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRLyixJDOfK02hoiYlNS8/NzMvsSS/SKHC1tbQtqKm1Ea3QjctJx8kompom6ZiqF/6PzcxM8@2oCgzr0QlTcPY0ETV0MBA8z8A "Haskell – Try It Online")
Uses Haskell's `Data.Ratio` library for arbitrary precision rationals. If only the builtin names were not so long.
[Answer]
# JavaScript, 70 bytes
```
x=>(y=(x+'').slice(2),p=(a,b)=>b?a%b?p(b,a%b):a/b:0,p(10**y.length,y))
```
If we can change input type to a string, then it may save 5 bytes.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 18 bytes
```
{1e¯9>t←1|⍵:⍵⋄∇÷t}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/2jD10HpLu5JHbRMMax71brUC4kfdLY862g9vL6n9nwYUx6@ESwEIyoByBgp6hgp6Rgp6xgp6Jgp6pgp6Zgp65gp6Fgp6lgqGCsZ6hiZgtY/6pgJVl@kcWpF2aEUZlwLXfwA "APL (Dyalog Classic) – Try It Online")
# APL NARS, 18 chars
-1 byte thanks to Uriel
test
```
f←{1e¯9>t←1|⍵:⍵⋄∇÷t}
v←0 .1 .2 .3 .4 .5 .6 .7 .8 .9 1 3.14
⎕←v,¨f¨v
0 0 0.1 10 0.2 5 0.3 3 0.4 2 0.5 2 0.6 2 0.7 3 0.8 4 0.9 9 1 1 3.14 7
```
[Answer]
# Smalltalk, 33 bytes
```
[(y:=x\\1)>0]whileTrue:[x:=1/y].x
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ç▄é⌠á◙àù
```
[Run and debug it](https://staxlang.xyz/#p=87dc82f4a00a8597&i=0%2F1%0A1%2F10%0A2%2F10%0A3%2F10%0A4%2F10%0A5%2F10%0A6%2F10%0A7%2F10%0A8%2F10%0A9%2F10%0A10%2F10%0A314%2F100%0A628%2F100&a=1&m=2)
"Bonus points" for no precision errors. No floating point arithmetic used. This (finally) makes use of stax's built-in rational type.
] |
[Question]
[
Inspired by [this question](https://codegolf.stackexchange.com/questions/1977/what-is-the-average-of-n-the-closest-prime-to-n-the-square-of-n-and-the-closes).
Given a list containing numbers, print:
* The sum and product of the numbers in the list
* The average and median
* The differences between each term in the list (e.g. `[1,2,3] -> [1,1]: 1+1=2, 2+1=3`)
* The list, sorted ascending
* The minimum and maximum of the list
* The standard deviation of the list
For reference:
**Standard Deviation**
$$\sigma=\sqrt{\frac1N\sum^N\_{i=1}(x\_i-\mu)^2}$$
Where \$\mu\$ is the mean average, \$x\_i\$ is the \$i\$th term in the list, and \$N\$ is the length of the list.
Shortest code wins. Good luck!
[Answer]
# Q, 41
```
{(+/;*/;avg;med;-':;asc;min;max;dev)@\:x}
```
[Answer]
# TI-BASIC, 41 bytes
`1-Var Stats` is [one byte](http://tibasicdev.wikidot.com/one-byte-tokens), and `Σx`, `x̄`, etc. are two bytes each.
```
Ans→L₁
1-Var Stats
SortA(L₁
Disp Σx,prod(Ans),x̄,Med,ΔList(Ans),L₁,minX,maxX,σx
```
If changing the output order is allowed, a close-paren can be saved, bringing the score to 40 bytes.
[Answer]
## J, 73 70 characters
```
((+/;*/;a;(<.@-:@#{/:~);2&-~/\;/:~;<./;>./;%:@:(a@:*:@:(-a)))[a=.+/%#)
```
Usage:
```
((+/;*/;a;(<.@-:@#{/:~);2&-~/\;/:~;<./;>./;%:@:(a@:*:@:(-a)))[a=.+/%#)1 2 3 4
+--+--+---+-+-------+-------+-+-+-------+
|10|24|2.5|3|1 1 1 1|1 2 3 4|1|4|1.11803|
+--+--+---+-+-------+-------+-+-+-------+
```
[Answer]
# Q (87 chars)
```
(sum;prd;avg;{.5*(sum/)x[((<)x)(neg(_)t;(_)neg t:.5*1-(#)x)]};(-':);asc;min;max;dev)@\:
```
eg.
```
q) (sum;prd;avg;{.5*(sum/)x[((<)x)(neg(_)t;(_)neg t:.5*1-(#)x)]};(-':);asc;min;max;dev)@\: 10 9 8 7 6 5 4 3 2 1
55
3628800
5.5
5.5
10 -1 -1 -1 -1 -1 -1 -1 -1 -1
`s#1 2 3 4 5 6 7 8 9 10
1
10
2.872281
```
[Answer]
### Ruby 187
```
O=->l{g=l.size
r=l.sort
s=l.inject(:+)+0.0
m=s/g
p s,l.inject(:*),m,g%2>0?r[g/2]:(r[g/2]+r[g/2-1])/2.0,l.each_cons(2).map{|l|l[1]-l[0]},r,r[0],r[-1],(l.inject(0){|e,i|e+(i-m)**2}/g)**0.5}
```
*Usage syntax:* `O[<array>]` (for example, `O[[1,2,3]]`)
Outputs all the required values to the console, in the order specified in the question.
*IdeOne examples:*
* with odd number of elements: <http://ideone.com/83ouj>
* with even number of elements: <http://ideone.com/7PTRq>
[Answer]
# [Julia 0.6](http://julialang.org/), 66 bytes
```
x->map(f->f(x),[sum,prod,mean,median,diff,sort,extrema,std])|>show
```
[Try it online!](https://tio.run/##HcdBDsIgEEbhvSeB5O9Cq3Zh5CINC8zMKEagARpZeHdsunkv33v9eHftcn/w08feBhPcomQwoprGXNaAJSdCYBe3kN9GXgQl5QpuNXNwKJWs/pnySt/OkQ6i5iNOmDDijIvVt757Fyb7Bw "Julia 0.6 – Try It Online")
# [Julia 0.6](http://julialang.org/), 88 bytes (uncorrected std dev, as in op)
```
x->map(f->f(x),[sum,prod,mean,median,diff,sort,extrema,x->std(x,corrected=false)])|>show
```
[Try it online!](https://tio.run/##HYuxDsIgGAZ3nwSSr4NW7WDaF2kYsPy/Ygo0QCOD746ky11uuM@@Wn2vPD7pZX0t3eT0JribWBSJOe0OWwwGjrRvMLbJWGakEDOo5EhOo20pG1GwhBhpyWRG1msiqeRvSu/wreTNicV8xgUDelxxU/JRjz4Kg/oD "Julia 0.6 – Try It Online")
[Answer]
### Scala ~~208~~ ~~202~~ 188:
```
val w=l.size
val a=l.sum/w
val s=l.sortWith(_<_)
Seq(l.sum,l.product,a,s((w+1)/2),(0 to w-2).map(i=>l(i+1)-l(i)),s,l.min,l.max,(math.sqrt((l.map(x=>(a-x)*(a-x))).sum*1.0/w))).map(println)
```
Test:
```
scala> val l = util.Random.shuffle((1 to 6).map(p=>math.pow(2, p).toInt))
l: scala.collection.immutable.IndexedSeq[Int] = Vector(64, 8, 4, 32, 16, 2)
scala> val a=l.sum/l.size
a: Int = 21
scala> val s=l.sortWith(_<_)
s: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 8, 16, 32, 64)
scala> Seq(l.sum,l.product,a,s((s.size+1)/2),(0 to l.size-2).map(i=>l(i+1)-l(i)),l.sortWith(_<_),l.min,l.max,(math.sqrt((l.map(x=>(a-x)*(a-x))).sum*1.0/l.size))).map(println)
126
2097152
21
16
Vector(-56, -4, 28, -16, -14)
Vector(2, 4, 8, 16, 32, 64)
2
64
21.656407827707714
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes
```
_ÆmÆḊ÷L½$
Wẋ9SPÆmÆṁIṢṂṀÇ9ƭ€
```
[Try it online!](https://tio.run/##y0rNyan8/z/@cFvu4baHO7oOb/c5tFeFK/zhrm7L4ACI6M5Gz4c7Fz3c2fRwZ8Phdstjax81rfn//3@0oY6CkY6CcSwA "Jelly – Try It Online")
## How it works
```
_ÆmÆḊ÷L½$ - Helper link. Takes a list l on the left
Æm - Yield the mean of l
_ - Subtract the mean from each element of l
ÆḊ - Calculate the norm
$ - Run the previous two commands over l:
L - Length of l
½ - Square root
÷ - Divide the norm by the square root of l's length
Wẋ9SPÆmÆṁIṢṂṀÇ9ƭ€ - Main link. Takes a list l on the left
W - Yield [l]
ẋ9 - Repeat 9 times
9ƭ€ - Generate a 9 element list by running the previous 9 commands over l
and collecting the results together:
S - Sum
P - Product
Æm - Mean
Æṁ - Median
I - Forward increments
Ṣ - Sort
Ṃ - Minimum
Ṁ - Maximum
Ç - Helper link (standard deviation)
```
[Answer]
# Python 3.8, ~~174~~ ~~167~~ ~~148~~ 147 bytes
*-7 bytes thanks to @wasif*
*-19 bytes thanks to `math.prod()`*
*-1 bytes thanks to @The Fifth Marshal*
```
lambda l:[sum(l),math.prod(l),mean(l),median(l),[m-n for n,m in zip(l,l[1:])],sorted(l),min(l),max(l),stdev(l)]
import math
from statistics import*
```
[Try it online!](https://tio.run/##JY3BCsIwEETv/Yo9thIF8SL9lZDDalK6kE1Cdi3qz8fWnGaGmceUj6453e6lthaRHx4hzlZePMbJMOp6KTX7fwiYunrqzvI5wZIrJMNACb5Uxmiivc5uckZy1dBJ6iC@DxH1YduNG4jLvoHjZVhqZhBFJVF6CvTu1NoP)
[Answer]
# C++14, ~~340~~ 383 bytes
As generic unnamed lambda. First parameter `L` is the list as `std::list` of floating point type and second parameter is the desired output stream, like `std::cout`.
```
#import<cmath>
#define F(x);O<<x<<'\n';
#define Y l=k;++l!=L.end();
#define A auto
[](A L,A&O){A S=L;A l=L.begin(),k=l;A n=L.size();A s=*l,p=s,d=s*s,h=n/2.;for(S.sort(),Y s+=*l,p*=*l,d+=*l**l);for(l=S.begin();--h>0;++l)F(s)F(p)F(s/n)F(*l)for(Y)O<<*l-*k++<<","F(' ')for(A x:S)O<<x<<","F(' ')F(S.front())F(S.back())F(sqrt((d-s*s/n)/(n-1)))}
```
Compiles with a warning, C++ does not allow `"` directly followed by literals like `F`. Program still running.
* -1 & -2 bytes thanks to Zacharý
Ungolfed:
```
#include<iostream>
#include<list>
#import<cmath>
#define F(x);O<<x<<'\n';
#define Y l=k;++l!=L.end();
#define A auto
auto f=
[](A L, A&O){
A S=L; //copy the list for later sorting
A l=L.begin(), //main iterator
k=l; //sidekick iterator
A n=L.size();
A s=*l, //sum, init with head of list
p=s, //product, same
d=s*s, //standard deviation, formula see https://en.wikipedia.org/wiki/Algebraic_formula_for_the_variance
h=n/2.; //for the median later
for(
S.sort(), //now min/med/max is at known positions in S
Y //l=k;++l!=L.end(); //skip the headitem-loop
s += *l, //l points the next element which is fine
p *= *l, //since the head given at definiten
d += *l * *l //needs the sum of the squares
);
for(
l=S.begin(); //std::list has no random access
--h>0; //that's why single increment loop
++l //until median is crossed
)
F(s) //;O<<s<<'\n'; //sum
F(p) //product
F(s/n) //average
F(*l) //median (in S)
for(Y) //l=k;++l!=L.end(); //set l back to L
O<<*l-*k++<<"," //calc difference on the fly
F(' ')
for(A x:S) //output sorted list
O<<x<<","
F(' ')
F(S.front()) //minimum
F(S.back()) //maximum
F(sqrt((d-s*s/n)/(n-1))) //standard deviation
}
;
using namespace std;
int main() {
list<double> l = {10,3,1,2,4};
f(l, cout);
}
```
[Answer]
# [Perl 5](https://www.perl.org/), 204 + 1 = 205 bytes
```
@L=sort{$a<=>$b}@F;$p=1;$s+=$_,$p*=$_,$a+=$_/@F for@L;for(0..$#F){$o=($F[$_]-$a)**2/@F;push@d,$F[$_]-$F[$_-1]if$_}$o=sqrt$o;$m=@F%2?$F[@F/2]:$F[@F/2]/2+$F[@F/2-1]/2;say"$s $p$/$a $m$/@d$/@L$/@L[0,-1]$/$o"
```
[Try it online!](https://tio.run/##NYvBDoIwEER/pcExUQQKVS/Wak894RcYQmrUaKK2UjwY4q9bi9HD7MzuvLWH5jL3XpbCmabtoJdihd1LKg4rCg43EagT2Phrut@oVORoGlnyMEd5lmGgxh2MGEFtUVcp9DiOWcC4fbiT3Cf/e29pUZ2PqF@Bd/emheG4CqmGbB1qqSirFv9A2eQXwxNl3OlnBEdgQaEJrqByH1T22uZJgEJhIu8LwsiUzN7Gtmdzcz7dzLO8yH2qPw "Perl 5 – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 90 bytes
```
[| s | s Σ s Π s mean s median s differences s [ > ] sort s minmax s population-std .s ]
```
[Try it online!](https://tio.run/##JY4xCgIxEEV7T/Ev4ILaKdiKjY1YLVuEZFaD2SRkZkFR7yJ4H68Us7GYN38@n@H3SktI@XTcH3ZrXCl5cnBBK8cYlFwqGhYllsXqv9mM3upgCDGRyD0m6wUcklh/xmb2wAJLrPDK7ROMab6fCe@CgZSvy9gqjO17SuQ1cblabNHVV1PG@kHdioghjq40CH7OYtAwulwaOmhHKuUf "Factor – Try It Online")
Should be pretty self-explanatory, I hope. Factor has a built-in for each of these, but only a few have short aliases. While cleaving is cool, it's much shorter to go with locals here. Locals are also shorter than storing the words in a list and using `[ execute ] with each` on them, which would eventually catch up if the list had been re-used even more.
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 39 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage)
```
←ĐĐĐĐĐĐĐŞ⇹Ʃ3ȘΠ4Șµ5Ș₋⇹6Ș↕⇹7ȘṀ↔Đе-²Ʃ⇹Ł/√
```
This outputs, in order, the median, the product, the differences, the list reversed, the sum, the maximum and minimum, the mean, and the standard deviation.q
[Try it online!](https://tio.run/##K6gs@f//UduEIyjw6PxH7TuPrTQ@MePcApMTMw5tNT0x41FTN1DQDMhomwpkmJ@Y8XBnw6O2KSD1h7bqHtp0bCVQ@Gij/qOOWf//RxvqGOkY65jomOqYxwIA)
Explanation:
```
←ĐĐĐĐĐĐĐ Push the array onto the stack 8 times
ş Sort in ascending order
⇹ Stack management
Ʃ Sum
3Ș Stack management
Π Product
4Ș Stack management
µ Mean (as a float)
5Ș Stack management
₋ Differences
⇹6Ș Stack management
↕ Minimum and maximum
⇹7Ș Stack management
Ṁ Median
↔ Stack management
Đе-²Ʃ⇹Ł/√ Standard Deviation
```
[Answer]
# APL NARS, 119 chars, 182 bytes
```
{m←(s←+/w)÷n←⍴w←,⍵⋄s,(×/w),m,(n{j←⌊⍺÷2⋄2|⍺:⍵[1+j]⋄2÷⍨⍵[j]+⍵[j+1]}t),(⊂¯1↓(1⌽w)-w),(⊂t←w[⍋w]),(⌊/w),(⌈/w),√n÷⍨+/(w-m)*2}
```
test
```
h←{m←(s←+/w)÷n←⍴w←,⍵⋄s,(×/w),m,(n{j←⌊⍺÷2⋄2|⍺:⍵[1+j]⋄2÷⍨⍵[j]+⍵[j+1]}t),(⊂¯1↓(1⌽w)-w),(⊂t←w[⍋w]),(⌊/w),(⌈/w),√n÷⍨+/(w-m)*2}
⎕fmt h 0
┌9──────────────────────┐
│ ┌0─┐ ┌1─┐ │
│0 0 0 0 │ 0│ │ 0│ 0 0 0│
│~ ~ ~ ~ └~─┘ └~─┘ ~ ~ ~2
└∊──────────────────────┘
⎕fmt h 3
┌9──────────────────────┐
│ ┌0─┐ ┌1─┐ │
│3 3 3 3 │ 0│ │ 3│ 3 3 0│
│~ ~ ~ ~ └~─┘ └~─┘ ~ ~ ~2
└∊──────────────────────┘
⎕fmt h 1 2 3
┌9───────────────────────────────────────┐
│ ┌2───┐ ┌3─────┐ │
│6 6 2 2 │ 1 1│ │ 1 2 3│ 1 3 0.8164965809│
│~ ~ ~ ~ └~───┘ └~─────┘ ~ ~ ~~~~~~~~~~~~2
└∊───────────────────────────────────────┘
⎕fmt h 1 2 3 4
┌9────────────────────────────────────────────────┐
│ ┌3─────┐ ┌4───────┐ │
│10 24 2.5 2.5 │ 1 1 1│ │ 1 2 3 4│ 1 4 1.118033989│
│~~ ~~ ~~~ ~~~ └~─────┘ └~───────┘ ~ ~ ~~~~~~~~~~~2
└∊────────────────────────────────────────────────┘
⎕fmt h 1 2 7 3 4 5
┌9──────────────────────────────────────────────────────────────────┐
│ ┌5──────────┐ ┌6───────────┐ │
│22 840 3.666666667 3.5 │ 1 5 ¯4 1 1│ │ 1 2 3 4 5 7│ 1 7 1.972026594│
│~~ ~~~ ~~~~~~~~~~~ ~~~ └~──────────┘ └~───────────┘ ~ ~ ~~~~~~~~~~~2
└∊──────────────────────────────────────────────────────────────────┘
```
[Answer]
# Ocaml - 288 bytes
Assuming the given list is a non-empty list of floats (to avoid conversions), and that the returned median is the weak definition of the median :
>
> `median l = n` such that half the elements of `l` are smaller or equal to `n` and half the elements of `l` are greater or equal to `n`
>
>
>
```
open List
let f=fold_left
let z=length
let s l=f(+.)0. l
let a l=(s l)/.(float_of_int(z l))let rec i=function|a::[]->[]|a::b->(hd b -. a)::(i b)let r l=let t=sort compare l in(s,f( *.)1. l,a t,nth t((z t)/2+(z t)mod 2-1),t,i l,nth t 0,nth t((z t)-1),sqrt(a(map(fun n->(n-.(a l))**2.)l)))
```
The readable version is
```
open List
let sum l = fold_left (+.) 0. l
let prod l = fold_left ( *. ) 1. l
let avg l = (sum l) /. (float_of_int (length l))
let med l =
let center = (length l) / 2 + (length l) mod 2 -1 in
nth l center
let max l = nth l 0
let min l = nth l ((length l) - 1)
let dev l =
let mean = avg l in
sqrt (avg (map (fun n -> (n -. mean)**2.) l))
let rec dif =
function
| a::[] -> []
| a::b -> ((hd b) - a) :: (dif b)
let result l =
let sorted = sort compare l in
(
sum sorted,
prod sorted,
avg sorted,
med sorted,
sorted,
dif l,
max sorted,
min sorted,
dev sorted
)
```
[Answer]
# PHP, 213 bytes
```
function($a){echo$s=array_sum($a),_,array_product($a),_,$v=$s/$c=count($a);foreach($a as$i=>$x){$d+=($x-$v)**2;$i&&$f[]=$x-$a[$i-1];}sort($a);var_dump(($a[$c/2]+$a[$c/2+~$c%2])/2,$f,$a,$a[0],max($a),sqrt($d/$c));}
```
[Try it online](http://sandbox.onlinephpfunctions.com/code/a40998f587795001270390346fae88e56699140b).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 27 (or 25?) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
**If the order is mandatory:**
```
O,P,ÅA,Åm,¥,{R,ß,à,ÅA-nÅAt,
```
[Try it online.](https://tio.run/##yy9OTMpM/f/fXydA53CrIxDn6hxaqlMdpHN4vs7hBSAx3TwgUaLz/3@0oY6RjnEsAA)
**If the order doesn't matter:**
```
O,P,Åm,¥,{R,ß,à,ÅA=-nÅAt,
```
Does the average just before the standard deviation, every other operation is in the same order.
[Try it online.](https://tio.run/##yy9OTMpM/f/fXydA53Brrs6hpTrVQTqH5@scXgDkO9rq5gHJEp3//6MNdYx0jGMB)
**Explanation:**
```
O # Sum the (implicit) input-list
, # Pop and print it with trailing newline
P, # Same for the product
ÅA, # Same for the average
Åm, # Same for the median
¥, # Same for the deltas / forward differences
{R, # Same for the descending sort (sort + reverse)
ß, # Same for the minimum
à, # Same for the maximum
# Same for the standard deviation:
ÅA # Get the average of the (implicit) input-list
- # Subtract it from each value in the (implicit) input-list
n # Square each
ÅA # Take the average of this list
t # Take the square-root of that
, # And print it as well
```
] |
[Question]
[
**Input:**
A string (or the closest thing to that in your language)
**Output:**
The same string but converted to sentence case
**Rules:**
* For this challenge, sentence case can be considered "`The first letter of each sentence is capitalized. The rest are lowercase.`" (i.e. proper nouns do not have to be capitalized)
* If the input does not include a period, it is treated as one sentence.
* The other 2 punctuation marks used to end a sentence in english (`?` and `!`) can be considered periods
* If a letter immediately follows a punctuation mark the same rules still apply (i.e. the first letter is capitalized and all following letters are lowercased until the next punctuation mark)
**Sample test cases:**
```
"hello world." // "Hello world."
"CODEGOLF IS FUN." // "Codegolf is fun."
"no period" // "No period"
"the ball was red. so was the balloon." // "The ball was red. So was the balloon."
"I love codegolf.stackexchange.com" // "I love codegolf.Stackexchange.Com"
"heLLo! hOW are yOU toDay? hOpEfulLy yOu are okay!" // "Hello! How are you today? Hopefully you are okay!"
```
**This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins!**
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
l.ª
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/R@/Qqv//SzJSFZISc3IUyhOLFYpSU/QUivPBbJhEfn6eHgA "05AB1E – Try It Online")
Nothing like a good old built-in answer! This converts the string to lowercase and then performs sentence case.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte
```
¡
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiwqEiLCIiLCJoZWxsbyB3b3JsZC5cbkNPREVHT0xGIElTIEZVTi5cbm5vIHBlcmlvZFxudGhlIGJhbGwgd2FzIHJlZC4gc28gd2FzIHRoZSBiYWxsb29uLlxuSSBsb3ZlIGNvZGVnb2xmLnN0YWNrZXhjaGFuZ2UuY29tXG5oZUxMbyEgaE9XIGFyZSB5T1UgdG9EYXk/IGhPcEVmdWxMeSB5T3UgYXJlIG9rYXkhIl0=)
"Nothing like a good old built-in answer!" I suppose not younger lyxal, I suppose not.
Alternatively, a non-trivial 24 byte answer:
```
`([.?!])`ṡλ⇩⌈:Th~iǐȦṄ;Ẇṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiYChbLj8hXSlg4bmhzrvih6nijIg6VGh+aceQyKbhuYQ74bqG4bmFIiwiIiwiaGVsbG8gd29ybGQuXG5DT0RFR09MRiBJUyBGVU4uXG5ubyBwZXJpb2RcbnRoZSBiYWxsIHdhcyByZWQuIHNvIHdhcyB0aGUgYmFsbG9vbi5cbkkgbG92ZSBjb2RlZ29sZi5zdGFja2V4Y2hhbmdlLmNvbVxuaGVMTG8hIGhPVyBhcmUgeU9VIHRvRGF5PyBoT3BFZnVsTHkgeU91IGFyZSBva2F5ISJd)
## Explained
```
`([.?!])`ṡλ⇩⌈:Th~iǐȦṄ;Ẇṅ
` `ṡ # Split the input on the regex "[.?!]", keeping the thing that causes splits (wrapping something in `()` when regex splitting keeps it in the split list)
λ ;Ẇ # To each second item of that list (guaranteed to not be punctuation), starting at index 0:
⇩⌈ # Split the lowercase version of the string on spaces
:Th~i # Get the first word by getting the first truthy index in the splitted string (because it may contain `""`s) and get the item at that index
ǐȦṄ # Replace the word at that index with a title-cased version of the string, and join the list on spaces.
ṅ # Join the result on nothing
```
[Answer]
# [Python 3](https://docs.python.org/3/), 67 bytes
*-7 bytes thanks to Surculose Sputum*
If other punctuation like `!` or `?` are allowed.
```
lambda s:re.sub(r'\w[\w ]+',lambda x:x[0].capitalize(),s)
import re
```
[Try it online!](https://tio.run/##RYy9asMwFEZ3PcXnKRINpqWboXio8welHkqnOINcy7HgRldISpX05d1QWrodzoHjr2li9ziPT91M@tQPGrEKpoznXoZFl/ddxuFusfxtl@qyvz@UH9rbpMl@GamWUQl78hwSgpnzZMngoRLwwbokR2mdPyeplJonQ8TIHGgoxXPbrDbtyxq7N6zfX0vhGN4Ey4NIk0GviZB1vD2HGpF/@C8wu1ps/29FUaBh7EDt5wpHptG6Y42riTfXtN8 "Python 3 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 53 bytes
```
lambda s:'. '.join(map(str.capitalize,s.split('. ')))
```
[Try it online!](https://tio.run/##Nco9C8IwEIDhPb/iNlOQgI4FJ7UiiB3ETZCrSenJNReSSNA/Xz/A7YXnDc88iF9O/eoyMY6dRUj1zMDM3IW8HjHolKO5YaCMTC83TyYFpqy/U1VVUxmIHSxqBSGSz9DriOVKPjyy/vDgmAWKRLZGrdvNdtceGtifoDkfjfICwUUSq/LgoENmKJggOmsgya//IOLNGw "Python 2 – Try It Online")
[Answer]
# [Erlang (escript)](http://erlang.org/doc/man/escript.html), 77 bytes
If non-periods are allowed... well, that greatly golfs my program!
```
g(H)->[string:titlecase(string:lowercase(I))||I<-re:split(H,"(\\W[\\W ]+)")].
```
[Try it online!](https://tio.run/##hY/BasMwDIbvfQrNJ5slfoAwusPWLoHQHMrYIcnBa7TUoNrBFuTSd0@9scJg0Ap0@fR/gh8DGTfmGA/BTrysllGWKl@3kYN1Y8GWCQ8movwF5GcMP6BS6nyunvKARZzIsiwzIbvuo00L/aMSqtfLyVgn215Bvl5BGuuLrzlYRjlKcUQiD7MPNGihVJaOjqTK/idfmtfNW1NvodrD9n13J@08TBisH27Hyk1dNxqiOU2EwBgZvovdlsyu4RLDw/PVu6/wEeHTECXDDhl0IqbSJsKVe@90J/780MsF)
## Explanation
```
g(H)-> % Define a function.
re:split(H,"(\\W[\\W ]+)") % Split the operand on "sentences", keeping the items reserved for splitting.
% I.e. none of the items from the string is missing after the split
||I<- ] % For every item in a sentence,
[string:titlecase(string:lowercase(I))
% Title case the sentence.
. % End the function.
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 101 bytes
```
s=>(s.reduce((a,c)=>c=='.'?(r+=c,'Upp'):c>' '?(r+=c['to'+a+'erCase'](),'Low'):(r+=c,a),'Upp',r=''),r)
```
[Try it online!](https://tio.run/##bdDBbsIwDAbg@57C6sWJGsJ9UrpDgW0SggNwmnYIaQpFURwlZX38roJtmmhvkX9/VuyL/tLJxCa0M0@V7WvVJ1WwJKOtrsYypoXhqjBKocQXFnNlBB5CQP5sCoSf0ge2hLnO0cZSJ4ufjAtcUzd03YnmdyWiQuQi8t6QT@SsdHRiNcvO1jmCjqKrZCZTcE3Lhk7OYT6H7O1/@vRAy@1i@bpdr@B9B6vDZoKXw2YncjU0CeqrH4/wBMHGhqqx3fxFj6g9Wzhq56DTCYZzSUh0e/8GRH7iM/sR200w6L8B "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 13 bytes
```
.+
$T
\b .
$L
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8F9Pm0slhCsmSUGPS8Xn//@M1JycfIXy/KKcFD0uZ38XV3d/HzcFz2AFt1A/Pa68fIWC1KLM/BSukoxUhaTEnByF8sRihaLUFD2F4nwwGyaRn5@nBwA "Retina – Try It Online")
## Explanation
General approach is to convert every word to title-case, then un-convert the words that shouldn't have been converted
`.+` Matches the entire string, `$T` converts it to title case (every word lowercase with an uppercase first character
`\b .` - `\b` Matches the position between a word-character and a non-word character (i.e. the end of a word without a full stop) followed by a space and any other character `.`
`$L` converts this to lowercase
[Answer]
# perl -p, 33 bytes
```
$_=lc=~s/(^|\pP)\s*\K\pL/uc$&/erg
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3jYn2bauWF8jriamIEAzplgrxjumwEe/NFlFTT@1KP3//4zUnJx8hfL8opwUPS5nfxdXd38fNwXPYAW3UD89rrx8hYLUosz8FK6SjFSFpMScHIXyxGKFotQUPYXifDAbJpGfn6fHlZafrwPkFYGIqn/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online")
This lowercases the string, then upper cases any letter following either the beginning of the string, or after a punctuation character (skipping any whitespace in between). This does turn a string `"foo, bar, baz"` into `"Foo, Bar, Baz"`, but that's how I read the requirement about all punctuation.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~80~~ \$\cdots\$ ~~87~~ 76 bytes
Added 13 bytes to fix a bug kindly pointed out by [Abigail](https://codegolf.stackexchange.com/users/95135/abigail).
```
c;b;f(char*s){for(b=1;c=*s;b|=ispunct(c))*s++=isalpha(c)?b?b=0,c&95:c|32:c;}
```
[Try it online!](https://tio.run/##bVFNU8IwFLzzK95k1OkHH0WHg8TKAUWdceCAniiHNk1oZkrTSdphFPrba1vaiuC7JG@zu0n2kd6GkDwn2MNMI4ErDaXvmZCaZw8xsQ2FvYPNVZxGJNGIrhvKNIveDePALfqJN/Fsq0tu7kdjcri7HROc5VuXR5oO@w4UVXlCQlWiVmuwa7QsFNAwFLATMvT7qAsDA9DrKQTG4Jc8XTw9vyzeZ/C2hNnnvBFMhU83ImTAFbA0OhNFAmIqufBr9rzt/9CSgILnhiHsXAWS@n1Qoto3B0JEzYUfF9zlP9wLe3cr0igpX3k1HKHW6QyuVRluowMvZYzK1dCyrPURLqfDS1GRpoWL5QEU/6aCaVXK@qDuquR1DKbJ9ZPYVSJJ/KUdfbv1ZPhaxy0jloU905CDrpWDoPcIDip@f1Sc8Jh2ATXSUuhE56Ksk@U/ "C (gcc) – Try It Online")
**How**
Capitalises the first letter and every letter after a punctuation mark. Every other letter is converted to lower case. Simply prints everything else.
[Answer]
# [Python 3](https://docs.python.org/3/), 117 bytes
```
import re
f=lambda s:''.join(map(lambda p:re.sub(r'[a-z]',lambda m:m[0].upper(),p.lower(),1),re.split(r'([.?!])',s)))
```
[Try it online!](https://tio.run/##dZJBb9pAEIXv/IqBHOyV6KpVblQoSgiBSCSuSqIeKIe1PcZO1jur3XXA/fN0TYAUk95Gb97neTtjXbuc1OV2W5SajAODnWwoRRmnAuwgCPgLFSoshQ73oh4Y5LaKQxMsxJc/y6C/b5SDcvF1ySut0YSsr7mk9a76xvoNomXhPBQu@FV3yYK@ZYxtU8zAIYYbNtCmUM4X3w26yijYdDoXMCneUHmHdZAIi7YjrEUfs2GysJejlARrMjLlPcZgOITe9F@t5R9Ft@NJNLuD@zncPT8emRGluCKZQWEhq9QZpwj8qwpKD8DjUWg5XY4QCylhLaxfZsrB0q4@NIjUcezTmXn@iRlaI@5B0htCss/MrRPJK26SXKgV8oTKw@fbxvmJceSNZ@uczagLefQLhEGoo2dwdCvqKy/pcVbJWe3FatekV1F3T3behSmt30GqPJg24JQ0elDWO/EDbI473jgj/n9cwWOeHCZc8xs@6n12fg6wIkrjGk/SeHmyl9v7Cx7gGn5GN9HTcVNBCQIMxeR8svc/MfitfjRgCs2FPlLygG3/Ag "Python 3 – Try It Online")
For some reason, I made a solution that handles a few extra test cases that OP may or may not have cared about :) This is much longer than the current shortest Python solution, but I'd be sad to just throw this code away, so here it is!
Extra test cases:
```
"a.b.c" // "A.B.C"
(no space after punctuation)
"hello. goodbye" // "Hello. Goodbye"
(more than one space after punctuation)
"I'M A ROBOT" // "I'm a robot"
(punctuation other than sentence terminator)
```
Commented solution:
```
f = (
lambda string:
''.join(map(
# Capitalize first letter in part
lambda part: re.sub(
r'[a-z]',
lambda match: match[0].upper(),
part.lower(),
1
),
# Split on punctuation
re.split(r'([.?!])',string)
))
)
```
[Answer]
# [Go](https://go.dev), 192 bytes
```
import(y"bytes";."regexp";u"unicode")
type k=[]byte
func f(s k)k{return MustCompile(`\w[\w ]+`).ReplaceAllFunc(s,func(b k)k{return append(k{byte(u.ToUpper(rune(b[0])))},y.ToLower(b[1:])...)})}
```
A port of [@dingledooper's answer](https://codegolf.stackexchange.com/a/204825/77309).
[Attempt This Online!](https://ato.pxeger.com/run?1=hZLfatswFMZhd_VTnOpKYp263Y2VMUbarAGvLkvDLtJAZVv-gxVJyNJcE_IkuwmDPcTu9hrb00y2w5L9AV9ZfDrn953PR5-_5Gr3TbOkYjmHNStlUK61MhZQtrboq7PZs5c_vg8ablHcWl6jC4oMz_mjRhcOOVkmKuWIBLbVHKrXy1VXFWROJpDhGipSbQy3zkh472o7UWtdCo4f7pvlfQOrpw-EfuBasIS_FWLqu3B91jXj-LiVac1liqtNB8eO3qmFVww2TnIcL5-vCCHbs9broWq8Hi9fvFoRSinZku2Q4-eTWT9UFxMT2AQn5-eArrkQChplREpRcOJj01tTSiskrq0_5DjDQySMiuNab0gGxMTnz5XIoKzBO4xiJtHl1bsonMJsDtPFzTHqRoFPVap0jCF_Fx6a7woOMRMCGlaD4SmFuerPdn-h1Phw9h9I_R_IwXQGQn3ikOz_AZ1b_5r4Y1IwmXPqtz1m-Deg_gOQeMDBrF_WKVyrBpjh0CoHVqWsfeMlzTMnRNuL3aWqWHs6vtEw9MAi-jgAo4UHXnbAItJXHhh6YHQM7IfZv6jdbvj-Ag)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 19 bytes
```
T`L`l
T`l`L`^.|\W .
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyTBJyGHKyQhB0jH6dXEhCvo/f@fkZqTk69Qnl@Uk6LH5ezv4uru7@Om4Bms4Bbqp8eVl69QkFqUmZ/CVZKRqpCUmJOjUJ5YrFCUmqKoUJwPZsMk8vPz9AA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`L`l
```
Lowercase everything.
```
T`l`L`^.|\W .
```
Uppercase the first character and any character that follows a non-word character and a space. It might not be the world's best heuristic but it works on the test case.
[Answer]
# [Red](http://www.red-lang.org), 81 bytes
```
func[s][parse lowercase s[any[any" "p: change skip(p/1 - 32)thru["."|"!"|"?"]]]s]
```
[Try it online!](https://tio.run/##NZDBTsMwDIbvfQo3JzisCLjtwA5sg0kVlUAThyiHLHGbqiGOkpZSiXcvYVstWfL/2Zb8O6Ce31EDF1m9nuvBKR4F9zJEBEsjBiVTFbl0038yYH4NykjXJNq1/sbf3cMKHh9uexMGzgr2y/KUGyaEiGKuKaBUBmIfWtcAzyAFe0VrCUYKVhfsgp6r7e6lKvdw@ID98W3BjsBjaElfdW8QTtJaGGWEgLqASOd6aRC5ZfeQHHwjKNLYkK2L2EvV4c/l@kLR13XOYFlSDqb6BBkQpuoIPW3ltEnI7@rBllOCw7lJnZxylqUXJT89cEV@Wsyx1ROD@qqEmP8A "Red – Try It Online")
[Answer]
# [Vim](https://www.vim.org/), ~~20~~ 19 bytes
*Saved 1 byte by using `~` to toggle casing instead of `vU`.*
```
v$uqq~/[.!?]
w@qq@q
```
[Try it online!](https://tio.run/##K/v/v0yltLCwTj9aT9E@lqvcobDQofD//4xUH598RYUM/3CFxKJUhUr/UIWSfJfESnugUIFrWmmOTyVQsBQsmZ@dWKlX4pFZrBDs6leSmpfsqpCRWKyQ568QXJDonKqQlJrmH5SqkBmiBwA "V (vim) – Try It Online")
Explanation:
```
v$u # Selects whole line and changes it to lowercase
qq # Starts recording macro q
~ # Toggles uppercase on current character
/[.!?] # Jumps to next . ! or ?
w # Jumps to next non-whitespace character
@q # Calls macro q recursively
q@q # Ends macro q and calls it
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
v r"^.|%W ."_u
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=diByIl4ufCVXIC4iX3U&input=ImhlTExvISBoT1cgYXJlIHlPVSB0b0RheT8gaE9wRWZ1bEx5IHlPdSBhcmUgb2theSEi)
] |
[Question]
[
Given the output of the cop's program (`o`), the byte-count (`n`) and the number of unique bytes (`c`) used, come up with a corresponding piece of code that is `n` bytes long with `c` unique bytes which matches the cop's output `o`.
---
# This is the ***robbers thread***. Post solutions that you cracked here.
# [The COPS thread is located here](https://codegolf.stackexchange.com/q/147635/36398).
---
Robbers should post solutions like this:
```
#[Language], `n` Bytes, `c` Unique Bytes (Cracked)[Original Link to Cop Thread]
[Solution]
(Explanation)
```
---
# Rules
* You may not take any input for your program.
* The program must use at least 1 byte, but cannot exceed 255 bytes.
* The output itself is also limited to 255 bytes.
* The program must have consistent output results when executed multiple times.
* If your submission is not cracked within 7 days, you may mark it as "safe".
+ When marking it safe, post the intended solution and score it as `c*n`.
# Winning
* The uncracked post with the lowest `c*n` score, wins the cop's thread.
* Whomever cracks the most wins the robbers thread, with earliest crack breaking the tie.
* This will be decided after 10 safe answers, or a few weeks.
# Caveats
* If you feel cocky, you may tell the user the algorithm using a ***spoiler*** tag.
---
Note: Also, please remember to upvote cracks, they're usually the impressive part.
[Answer]
# Java 8, 97 Bytes, 34 Unique Bytes, [Kevin Cruijssen](https://codegolf.stackexchange.com/a/147659/73904)
```
interface Fillerrrrrrrrrrr{static void main(String...a){System.out.println(1.4241570377303032);}}
```
[Try it online!](https://tio.run/##RcgxDoMwDEDRq2SEoRYQqgzdewFOYIFBpsFBwSAhlLMHtv63/RkPfIWVZB5@ObMoxRF7Ml/2nuK/a1NU7s0ReDALshSdRpYJALC8unNTWiDsCutz1UtRQ9u09dtV1jlbPZryk1LONw "Java (OpenJDK 8) – Try It Online")
Super innovative crack, spent hours on it
[Answer]
# [MATL](https://github.com/lmendo/MATL), 4 bytes, 4 unique bytes, [Stewie Griffin](https://codegolf.stackexchange.com/a/147648/36398)
```
1X2p
```
[**Try it online!**](https://tio.run/##y00syfn/3zDCqOD/fwA)
### Explanation
```
1X2 % Push predefined literal: string 'double'
p % Product of array. For strings it uses code points. Implicit display
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes, 3 unique, [Luis Mendo](https://codegolf.stackexchange.com/a/147650/67312)
```
FFFTZF
```
[Try it online!](https://tio.run/##y00syfn/383NLSTK7f9/AA "MATL – Try It Online")
I immediately recognized the output
```
1+0i 0+1i -1+0i 0-1i
```
as the 4-th roots of unity, and I knew that the `fft` on `[0 0 0 1]` would result in this.
It took me quite a while to figure out that `FFFT` would push `[0 0 0 1]` ~~and I'm still not sure how it works.~~ EDIT: Luis Mendo explained that `F` and `T` are "sticky", so a sequence of `F` and `T` will automatically `horzcat` them together, hence, `FFFT` pushes `[0 0 0 1]`.
This is expressed succinctly in the documentation (once I looked it up):
>
> For logical row vectors the square brackets can be omitted; that is, the notation
> `[T F T]` or `[TFT]` can be simplified to `TFT`. A separator may be needed if a new
> logical array follows: `TFT TT`. But it’s not necessary in other cases: `TFT3.5`.
>
>
>
[Answer]
# [Haskell](https://www.haskell.org/), 29 bytes, 15 unique, [Laikoni](https://codegolf.stackexchange.com/a/147876/71256)
```
f<$>[1..74]
f 47='4'
f f1='3'
```
[Try it online!](https://tio.run/##y0gszk7NyflfXFKUmZeuYKsQ8z/NRsUu2lBPz9wklitNwcTcVt1EHchIM7RVN1b/n5uYmQdUVlBaElxSpADR9v9fclpOYnrxf93kggIA "Haskell – Try It Online")
I previously had the two nearly solutions:
```
do;d<-[2..74];'3':['4'|d==47] -- 29,16
do;d<-[-41..31];'3':['4'|d==4] -- 30,15
```
[Answer]
# [Haskell](https://www.haskell.org/), [Laikoni](https://codegolf.stackexchange.com/a/147734/71256)
```
0x90090009
```
[Try it online!](https://tio.run/##y0gszk7NyfmfqWCrEPPfoMLSwACIDCz/5yZm5gHFCooy80oUMv//S07LSUwv/q@bXFAAAA "Haskell – Try It Online")
I feel like I got lucky here...
[Answer]
# JavaScript (ES6), [Brian H.](https://codegolf.stackexchange.com/a/147662/58563)
*Thanks [@Milk](https://codegolf.stackexchange.com/users/58106/milk) for fixing the last trailing '5'*
```
f=f=>1/44.4
console.log(f())
```
Unique characters: `.`, `/`, `1`, `4`, `=`, `>`, `f`
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 8 bytes, 3 unique, [Jenny\_mathy](https://codegolf.stackexchange.com/a/147732)
```
7!!!/77!
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/99cUVFR39xc8f///7oFRZl5JQA "Wolfram Language (Mathematica) – Try It Online")
Breakdown: `Factorial[7!!] / Factorial[77]` where `!!` is double factorial.
First I notice the long sequence of `0` at the end so I guess it may be some kind of factorial. `FactorInteger` gives the largest factor `103`, so I try `n/103!`, and get the next largest (negative) prime factor is `73`. Tweaking the factors for some time gives `105!/77!`, then I think "there are already 3 symbols `7`, `!` and `/`, so the way to create 105 must be from those symbols!". So I tried `7!!` (which is one of a few things to try) and get 105 as the correct result.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 62 total bytes, 6 unique, [Wheat Wizard](https://codegolf.stackexchange.com/a/147636/57100)
```
(((((((()()()){}){}){}){}){}){(({})[()])}{})({{()({}[()])}{}})
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/XwMKNEFQs7oWFWloAMloDc1YzVogQ6O6GqiquhYmUKv5/z8A "Brain-Flak – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 5 bytes, 5 unique bytes, [Shaggy's submission](https://codegolf.stackexchange.com/a/147727/73884)
```
10l Ä
```
[Try it online!](https://tio.run/##y0osKPn/39AgR@Fwy///AA "Japt – Try It Online")
Simple enough: 3628801 is 10! (`10l`) plus one (`Ä`).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes, 6 unique, [Erik the Outgolfer](https://codegolf.stackexchange.com/a/147651/53748)
- For some reason I started with a trailing zero in the result. Without it I would have given
`8,16!PP`
as a solution.
---
```
8,⁴!PP0
```
**[Try it online!](https://tio.run/##y0rNyan8/99C51HjFsWAAIP//wE "Jelly – Try It Online")**
### How?
```
8,⁴!PP0 - Main link of a program taking no arguments and no input
⁴ - literal sixteen
8 - literal eight
, - pair = [8,16]
! - factorial (vectorises) = [8!, 16!] = [40320, 20922789888000]
P - product = 40320 × 20922789888000 = 843606888284160000
P - product (no effect) = 843606888284160000
0 - literal zero (just gets printed)
- leaving STDOUT displaying 8436068882841600000, as required
```
...`8,⁴!’P` for 6 bytes, 6 unique would have been much harder to crack since the result of `843585965494231681` (**40319 × 2092278988799**) does not look so factorial-based.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), 3 unique [Erik the Outgolfer](https://codegolf.stackexchange.com/a/147761/53748)
```
ȷc⁵
```
**[Try it online!](https://tio.run/##y0rNyan8///E9uRHjVv//wcA "Jelly – Try It Online")**
### How?
```
ȷc⁵ - Main link: no arguments, no input
ȷ - literal one-thousand
⁵ - literal ten
c - choose (A.K.A. binomial coefficient) = 263409560461970212832400 as required.
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 7 Bytes, 5 Unique Bytes, [AdmBorkBork](https://codegolf.stackexchange.com/a/147716/64121)
```
1PB#---
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/3zDASVlXV/f/fwA "PowerShell – Try It Online")
The output `1125899906842624` is equal to `2^50` and `2^50 Bytes` is equal to `1 Pebibyte`.
The actual code is just 3 bytes, therefore I added a comment at the end.
[Answer]
# Excel, 22 bytes, 16 unique bytes, [EngineerToast](https://codegolf.stackexchange.com/a/147672)
A possible solution is:
```
=BAHTTEXT(2^(480-300))
```
The unique characters are `=BAHTEX()^02348-`.
I recognized that BAHTTEXT was used when seeing the output. By translating the output back from Thai to English, I was able to find the value of the number. I guessed it to be a power of 2, which it indeed is (namely 2180). The expression 480-300=180 was then constructed to make sure the solution contains 22 bytes with 16 unique.
[Answer]
# [Alice](https://github.com/m-ender/alice), 9 bytes, 8 unique bytes, [Leo](https://codegolf.stackexchange.com/a/147886/69059)
```
/Yr@
\no/
```
[Try it online!](https://tio.run/##S8zJTE79/18/ssiBKyYvX///fwA "Alice – Try It Online")
Unfolded, this is `nrYo@`.
```
n negate the implicit empty string: creates the string "Jabberwocky".
r range expansion: produces a string that starts with J,
goes up in ASCII order to w, down to c, and then up to y.
Y separate this string into even and odd positions
o output the even positions
@ terminate
```
Incidentally, the orientation of the mirrors in the first column is completely irrelevant, so this could easily be reduced to 7 unique bytes.
[Answer]
# [Haskell, Laikoni, 30 bytes, 17 unique](https://codegolf.stackexchange.com/a/148105/3852)
```
show.length.show=<<['\0'..'0']
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `d`, 4 bytes, 4 unique, cracks [emanresu A's answer](https://codegolf.stackexchange.com/a/233768/101522)
```
ka¦²
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=d&code=ka%C2%A6%C2%B2&inputs=&header=&footer=)
[Answer]
# [J](http://jsoftware.com/), 8 bytes, 6 unique bytes, [Bolce Bussiere](https://codegolf.stackexchange.com/a/149613/78410)
```
;p.p:i.9
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WuoKNQa6VgoADE/60L9AqsMvUs/2v@TwMA "J – Try It Online")
Output:
```
23 _0.677447j0.296961 _0.677447j_0.296961 0.125003j0.726137 0.125003j_0.726137 _0.379097j0.630438 _0.379097j_0.630438 0.518498j0.521654 0.518498j_0.521654
```
The obvious hint is that, in the given output, complex numbers always appear as conjugate pairs. It made me suspect the `p.` verb, which converts between plain polynomial and multiplier-and-roots forms.
So I tried:
```
p. 23;(...those complex numbers)
2 3 5 7.00001 11 13 17 19 23
```
Yes, my thought was correct. The list of primes is easy. Monadic `;` flattens the list of boxed arrays to simple linear one. The resulting expression has two p's and two dots, so the byte count is perfect.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 4 bytes, 3 unique bytes, [Tom Carpenter](https://codegolf.stackexchange.com/a/147743/36398)
```
j^7j
```
[Try it online!](https://tio.run/##y08uSSxL/f8/K8486/9/AA "Octave – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), 6 unique, [Mr. Xcoder](https://codegolf.stackexchange.com/a/147667/53748)
```
7x7²¤ḌḤ²
```
**[Try it online!](https://tio.run/##ARgA5/9qZWxsef//N3g3wrLCpOG4jOG4pMKy//8 "Jelly – Try It Online")**
### How?
```
7x7²¤ḌḤ² - Main link: no arguments & no input
7 - literal 7
¤ - nilad followed by link(s) as a nilad:
7 - literal 7
² - square -> 49
x - repeat elements -> [7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7]
Ḍ - convert from a decimal list -> 7777777777777777777777777777777777777777777777777
Ḥ - double -> 15555555555555555555555555555555555555555555555554
² - square -> 241975308641975308641975308641975308641975308641926913580246913580246913580246913580246913580246916
- implicit print
```
] |
[Question]
[
In this challenge, You have to bring ASCII art (which are usually 2D) to 3D!
# How?
like this,
```
X X DD
X D D
X X DD
```
to...
```
X X DD
X X DD D
X X DDDD
X XDDD
X X DD
```
# Then How do we do *that*?
Given the ascii art and `N`, repeat this `N` times.
* for every character (we will call this `A`):
* let `B` be the character which is exactly 1 right and 1 up from `A`
* if `B` is a space or is undefined:
* set `B` to `A`.
# Specs
* The first input can be a string with newline characters or a list of strings representing the 2D ASCII art.
* You are allowed to use `%END%` to tag the end of input, but this is not required.
* The second input will be `N`. It will be a positive integer.
* all the lines of the strings will be the same length.
# Examples
Input: `("###\n###",1)`
Output:
```
###
####
###
```
# Rules
Basic [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
also, If you have questions, be sure to ask in the comments!
[Answer]
## Perl, 81 bytes
**75 bytes code + 6 for `-i -n0`.
Note that the `\e` characters are ASCII `\x1b` but `\e` is used for ease of testing.**
Please note that this solution uses ANSI escape sequences and requires a compatible terminal, as well as using the `-i` commandline argument to pass in the number of 'dimensions' you'd like.
```
$n=s/^//mg-1;s/ /\e[1C/g;print(s/^/\e[${^I}C/grm."\e[${n}A"),--$^I for($_)x$^I
```
### Usage:
In a Linux compatible terminal, run `PS1=` first to ensure your prompt doesn't overwrite the displayed image.
```
perl -i10 -n0e '$n=s/^//mg-1;s/ /\e[1C/g;print(s/^/\e[${^I}C/grm."\e[${n}A"),--$^I for($_)x$^I' <<< '
ROFL:ROFL:ROFL:ROFL
_^___
L __/ [] \
LOL===__ \
L \________]
I I
--------/
'
ROFL:ROFL:ROFL:ROFL
ROFL:ROFL:ROFL:ROFL
ROFL:ROFL:ROFL:ROFL
ROFL:ROFL:ROFL:ROFL\
ROFL:ROFL:ROFL:ROFL\_]
ROFL:ROFL:ROFL:ROFL\_]
ROFL:ROFL:ROFL:ROFL\_]/
ROFL:ROFL:ROFL:ROFL\_]/
ROFL:ROFL:ROFL:ROFL\_]/
ROFL:ROFL:ROFL:ROFL\_]/
LOL==___^___]_\_\_]/
LOL==__/ \_[]_\_\_]/
LOL===__ \______\_]/
L \________]/
I---I---/
--------/
perl -i3 -n0e '$n=s/^//mg-1;s/ /\e[1C/g;print(s/^/\e[${^I}C/grm."\e[${n}A"),--$^I for($_)x$^I' <<< 'X X DD
X D D
X X DD
'
X X DD
X X DD D
X X DDDD
X XDDD
X X DD
```
[Answer]
## CJam, ~~25~~ 24 bytes
```
{{' 1$f+La@+..{sS@er}}*}
```
An unnamed block that expects a list of strings and the number of repetitions on the stack and leaves a new list of strings instead.
[Test it here.](http://cjam.aditsu.net/#code=qN%2F%202%0A%0A%7B%7B'%201%24f%2BLa%40%2B..%7BsS%40er%7D%7D*%7D%0A%0A~N*&input=X%20X%20DD%0A%20X%20%20D%20D%0AX%20X%20DD) (Includes a test wrapper that reads the string from STDIN for convenience.)
### Explanation
```
{ e# Repeat this block N times...
' e# Push a space character.
1$ e# Copy the current grid.
f+ e# Prepend the space to each line of the grid.
La e# Push [[]].
@+ e# Pull up the other copy of the grid and prepend the [].
e# We've now got two copies of the grid, one shifted right by
e# a cell and one shifted down by a cell. We now want to replace
e# spaces in the latter with the corresponding character in the
e# former.
..{ e# For each pair of characters in corresponding positions...
s e# Turn the character in the down-shifted grid into a string.
S e# Push " ".
@ e# Pull up the character from the right-shifted grid.
er e# Replace spaces with that character.
}
}*
```
[Answer]
## APL, 49 bytes
```
{⎕UCS 32⌈{s+(s=0)×1⊖¯1⌽s←0⍪⍵,0}⍣⍺⊣(32∘≠×⊣)⎕UCS↑⍵}
```
Input: vector of character vectors.
Example:
```
2 {⎕UCS 32⌈{s+(s=0)×1⊖¯1⌽s←0⍪⍵,0}⍣⍺⊣(32∘≠×⊣)⎕UCS↑⍵} 'X X DD' ' X D D' 'X X DD'
X X DD
X X DD D
X X DDDD
X XDDD
X X DD
```
How it works:
* `↑⍵` turns the argument into a matrix of chars
* `⎕UCS` from char to integer
* `(32∘≠×⊣)` substitute the spaces (32) with zeroes
* `...⍣⍺⊣` apply ⍺ (the left argument) times the function on the left
* `s←0⍪⍵,0` border with zeroes on top and on the right the argument
* `1⊖¯1⌽` rotate 1 up and 1 right
* `s+(s=0)×` sum to the original the shifted version but only on top of the zeroes of the original
* `32⌈` turns back the zeroes into 32s
* `⎕UCS` from integer to char
[Answer]
# [MATL](https://github.com/lmendo/MATL), 24 bytes
```
:"ct32>*TTYatFTEqYSy~*+c
```
Input format is
```
2
{'X X DD', ' X D D', 'X X DD'}
```
So the other example is
```
1
{'###', '###'}
```
The output contains extra whitespace, which is allowed by the challenge.
[**Try it online!**](http://matl.tryitonline.net/#code=OiJjdDMyPipUVFlhdEZURXFZU3l-Kitj&input=Mgp7J1ggWCBERCcsICcgWCAgRCBEJywgJ1ggWCBERCd9)
---
If a 2D char array is acceptable as input (I've asked the OP twice...), the first `c` can be removed, so **23 bytes**:
```
:"t32>*TTYatFTEqYSy~*+c
```
Input format in this case is (all strings have equal lengths, which may require right-padding with spaces):
```
2
['X X DD '; ' X D D'; 'X X DD ']
```
[**Try it online!**](http://matl.tryitonline.net/#code=OiJ0MzI-KlRUWWF0RlRFcVlTeX4qK2M&input=MgpbJ1ggWCBERCAnOyAnIFggIEQgRCc7ICdYIFggREQgJ10)
---
### Explanation
```
: % Input number n implicitly. Generate [1 2 ... n]
" % For loop: repeat n times
c % Convert to char array. In the first iteration it inputs a cell array of
% strings implicitly and converts to a 2D char array, right-padding with
% spaces. In the next iterations it does nothing, as the top of the stack
% is already a 2D char array
t32>* % Convert characters below 32 into 0
TT % Push array [1 1]
Ya % Pad the 2D char array with one zero in the two directions (up/down,
% left/right), on both sides
t % Duplicate
FTEq % Push array [-1 1]
YS % Circularly shift the 2D char array one unit up and one unit right
y % Push a copy of the non-shifted 2D array
~ % Logical negate: nonzero entries become 0, zero entries become 1. This
% will be used as a mask for entries that need to be changed. Since the
% values at those entries are zero, we can simply add the new values. We do
% that by multiplying the mask by the shifted array and adding to the
% non-shifted array
* % Multiply element-wise
+ % Add element-wise
c % Convert the 2D array back to char
% End for
% Implicitly display
```
[Answer]
## [Convex](https://github.com/gamrcorps/convex), 23 bytes
Byte count assumes CP-1252 encoding.
```
{{' 1$f+La@+..{sS@Ë}}*}
```
An unnamed block that expects a list of strings and the number of repetitions on the stack and leaves a new list of strings instead.
[Try it online!](http://convex.tryitonline.net/#code=cU4vIDIKCnt7JyAxJGYrTGFAKy4ue3NTQMOLfX0qfQoKfk4q&input=WCBYIERECiBYICBEIEQKWCBYIERE)
This is a direct port of [my CJam answer](https://codegolf.stackexchange.com/a/86302/8478) to Convex (which is heavily based on CJam). The only difference is that Convex uses `Ë` instead of `er` for transliteration, saving one byte. Thanks to GamrCorps for letting me know about it.
[Answer]
# Pyth, ~~54~~ 33 bytes
```
ju+++dhG.bsmh|-d;;.t,Y+dNdtGGeG.*
```
[Test suite.](http://pyth.herokuapp.com/?code=ju%2B%2B%2BdhG.bsmh%7C-d%3B%3B.t%2CY%2BdNdtGGeG.%2a&test_suite=1&test_suite_input=%5B2%2C%5B%22X+X+DD%22%2C%22+X++D+D%22%2C%22X+X+DD%22%5D%5D%0A%5B1%2C%5B%22%23%23%23%22%2C%22%23%23%23%22%5D%5D%0A%5B9%2C%5B%22+ROFL%3AROFL%3AROFL%3AROFL%22%2C%22+++++++++_%5E___%22%2C%22+L++++__%2F+++%5B%5D+%5C%5C++++%22%2C%22LOL%3D%3D%3D__++++++++%5C%5C+%22%2C%22+L++++++%5C%5C________%5D%22%2C%22+++++++++I+++I%22%2C%22++++++++--------%2F%22%5D%5D&debug=0)
[Answer]
## JavaScript (ES6), 128 bytes
```
f=(a,n)=>n?f((a=[``,...a].map(s=>[...s||` `])).map((b,i)=>i--&&b.map((c,j)=>a[i][++j]>' '?0:a[i][j]=c))&&a.map(b=>b.join``),n-1):a
```
Accepts and returns an array of strings, prepends an extra row for the output, ensures each row contains at least a space, splits them all up into characters, loops though trying to copy the characters to the row above and column to the right, then recursively calls itself to complete the loop.
[Answer]
# Python 2, 116 bytes
```
S=' '
def f(a,d):e=[S*len(`a`)];exec"a=[''.join(t[t[1]>S]for t in zip(S+x,y+S))for x,y in zip(a+e,e+a)];"*d;return a
```
I’ll golf this more soon.
[Answer]
# Ruby, 95 bytes
```
->a,n{n.downto(0){|i|f="<Esc>[1C"
$><<a.gsub(/^/,f*i).gsub(" ",f)+(i>0?"<Esc>[#{a.lines.size-1}A":"")}}
```
Each `<Esc>` is a literal ESC character (`0x1b`).
## Usage
Assign the lambda to a variable e.g. `func`.
```
art = <<END
X X DD
X D D
X X DD
END
func[art, 2]
# Prints:
# X X DD
# X X DD D
# X X DDDD
# X XDDD
# X X DD
```
## Ungolfed
```
->(art, num) {
num.downto(0) do |i|
forward = "\e[1C"
$> << art.gsub(/^/, forward * i).gsub(" ", forward) +
(i > 0 ? "\e[#{art.lines.size - 1}A" : "")
end
}
```
The `forward` escape sequence, `\e[1C`, moves the cursor forward (right) 1 space and `\e[<n>A` moves it up `n` lines. Basically what this code does is print the "layers" back to front, replacing spaces with the `forward` sequence to avoid overwriting the other layers with a space.
] |
[Question]
[
In [special relativity](https://en.wikipedia.org/wiki/Special_relativity), the velocity of a moving object relative to another object that is moving in the opposite direction is given by the formula:
\begin{align}s = \frac{v+u}{1+vu/c^2}.\end{align}
```
s = ( v + u ) / ( 1 + v * u / c ^ 2)
```
In this formula, \$v\$ and \$u\$ are the magnitudes of the velocities of the objects, and \$c\$ is the speed of light (which is approximately \$3.0 \times 10^8 \,\mathrm m/\mathrm s\$, a close enough approximation for this challenge).
For example, if one object was moving at `v = 50,000 m/s`, and another object was moving at `u = 60,000 m/s`, the velocity of each object relative to the other would be approximately `s = 110,000 m/s`. This is what you would expect under Galilean relativity (where velocities simply add). However, if `v = 50,000,000 m/s` and `u = 60,000,000 m/s`, the relative velocity would be approximately `106,451,613 m/s`, which is significantly different than the `110,000,000 m/s` predicted by Galilean relativity.
## The Challenge
Given two integers `v` and `u` such that `0 <= v,u < c`, calculate the relativistic additive velocity, using the above formula, with `c = 300000000`. Output must be either a decimal value or a reduced fraction. The output must be within `0.001` of the actual value for a decimal value, or exact for a fraction.
## Test Cases
Format: `v, u -> exact fraction (float approximation)`
```
50000, 60000 -> 3300000000000/30000001 (109999.99633333346)
50000000, 60000000 -> 3300000000/31 (106451612.90322581)
20, 30 -> 7500000000000000/150000000000001 (49.999999999999666)
0, 20051 -> 20051 (20051.0)
299999999, 299999999 -> 53999999820000000000000000/179999999400000001 (300000000.0)
20000, 2000000 -> 4545000000000/2250001 (2019999.1022226212)
2000000, 2000000 -> 90000000000/22501 (3999822.2301231055)
1, 500000 -> 90000180000000000/180000000001 (500000.9999972222)
1, 50000000 -> 90000001800000000/1800000001 (50000000.972222224)
200000000, 100000000 -> 2700000000/11 (245454545.45454547)
```
[Answer]
## Mathematica, 17 bytes
```
+##/(1+##/9*^16)&
```
An unnamed function taking two integers and returning an exact fraction.
### Explanation
This uses two nice tricks [with the argument sequence `##`](https://codegolf.stackexchange.com/a/45188/8478), which allows me to avoid referencing the individual arguments `u` and `v` separately. `##` expands to a *sequence* of all arguments, which is sort of an "unwrapped list". Here is a simple example:
```
{x, ##, y}&[u, v]
```
gives
```
{x, u, v, y}
```
The same works inside arbitrary functions (since `{...}` is just shorthand for `List[...]`):
```
f[x, ##, y]&[u, v]
```
gives
```
f[x, u, v, y]
```
Now we can also hand `##` to operators which will first treat them as a single operand as far as the operator is concerned. Then the operator will be expanded to its full form `f[...]`, and only then is the sequence expanded. In this case `+##` is `Plus[##]` which is `Plus[u, v]`, i.e. the numerator we want.
In the denominator on the other hand, `##` appears as the left-hand operator of `/`. The reason this multiplies `u` and `v` is rather subtle. `/` is implemented in terms of `Times`:
```
FullForm[a/b]
(* Times[a, Power[b, -1]] *)
```
So when `a` is `##`, it gets expanded afterwards and we end up with
```
Times[u, v, Power[9*^16, -1]]
```
Here, `*^` is just Mathematica's operator for scientific notation.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
sG3e8/pQ/
```
[**Try it online!**](http://matl.tryitonline.net/#code=c0czZTgvcFEv&input=WzIwMDAwMDAwMCwgMTAwMDAwMDAwXQ)
```
s % Take array [u, v] implicitly. Compute its sum: u+v
G % Push [u, v] again
3e8 % Push 3e8
/ % Divide. Gives [u/c, v/c]
p % Product of array. Gives u*v/c^2
Q % Add 1
/ % Divide. Display implicitly
```
[Answer]
# Jelly, 9 bytes
```
÷3ȷ8P‘÷@S
```
[Try it online!](http://jelly.tryitonline.net/#code=w7czyLc4UOKAmMO3QFM&input=&args=NTAwMDAwMDAsIDYwMDAwMDAw) Alternatively, if you prefer fractions, you can [execute the same code with M](http://m.tryitonline.net/#code=w7czyLc4UOKAmMO3QFM&input=&args=NTAwMDAwMDAsIDYwMDAwMDAw).
### How it works
```
÷3ȷ8P‘÷@S Main link. Argument: [u, v]
÷3ȷ8 Divide u and v by 3e8.
P Take the product of the quotients, yielding uv ÷ 9e16.
‘ Increment, yielding 1 + uv ÷ 9e16.
S Sum; yield u + v.
÷@ Divide the result to the right by the result to the left.
```
[Answer]
**Python3, 55 31 29 bytes**
Python is awful for getting inputs as each input needs `int(input())`
but here is my solution anyway:
v,u=int(input()),int(input());print((v+u)/(1+v\*u/9e16))
Thanks to @Jakube I don't actually need the whole prgrame, just the function. Hence:
```
lambda u,v:(v+u)/(1+v*u/9e16)
```
Rather self explanatory, get inputs, computes. I've used c^2 and simplified that as 9e16 is shorter than (3e8\*\*2).
**Python2, 42 bytes**
```
v,u=input(),input();print(v+u)/(1+v*u/9e16)
```
Thanks to @muddyfish
[Answer]
# J, ~~13~~ 11 bytes
```
+%1+9e16%~*
```
## Usage
```
>> f =: +%1+9e16%~*
>> 5e7 f 6e7
<< 1.06452e8
```
Where `>>` is STDIN and `<<` is STDOUT.
[Answer]
## Matlab, 24 bytes
```
@(u,v)(u+v)/(1+v*u/9e16)
```
Anonymous function that takes two inputs. Nothing fancy, just submitted for completeness.
[Answer]
# CJam, 16 Bytes
```
q~_:+\:*9.e16/)/
```
I'm still sure there are bytes to be saved here
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 11 bytes
```
+÷1+9E16÷⍨×
```
The fraction of the sum and [the increment of the divides of ninety quadrillion and the product]:
```
┌─┼───┐
+ ÷ ┌─┼──────┐
1 + ┌────┼──┐
9E16 ÷⍨ ×
```
`÷⍨` is "divides", as in "ninety quadrillion divides *n*" i.e equivalent to *n* divided by ninety quadrillion.
[Answer]
# Haskell, 24 bytes
As a single function that can provide either a floating point or fractional number, depending on the context in which it's used...
```
r u v=(u+v)/(1+v*u/9e16)
```
Example usage in REPL:
```
*Main> r 20 30
49.999999999999666
*Main> default (Rational)
*Main> r 20 30
7500000000000000 % 150000000000001
```
[Answer]
# [Noether](https://github.com/beta-decay/Noether), 24 bytes
***Non-competing***
```
I~vI~u+1vu*10 8^3*2^/+/P
```
[**Try it here!**](https://beta-decay.github.io/noether?code=SX52SX51KzF2dSoxMCA4XjMqMl4vKy9Q&input=NTAwMDAKNjAwMDA)
Noether seems to be an appropriate language for the challenge given that [Emmy Noether](http://en.wikipedia.org/wiki/Emmy_Noether) pioneered the ideas of symmetry which lead to Einstein's equations (this, `E = mc^2` etc.)
Anyway, this is basically a translation of the given equation to reverse polish notation.
[Answer]
## Pyke, 12 bytes
```
sQB9T16^*/h/
```
[Try it here!](http://pyke.catbus.co.uk/?code=sQB9T16%5E%2a%2Fh%2F&input=50000%2C+60000&warnings=0)
[Answer]
# Pyth, 14 bytes
```
csQhc*FQ*9^T16
```
[Test suite.](http://pyth.herokuapp.com/?code=csQhc%2aFQ%2a9%5ET16&test_suite=1&test_suite_input=50000%2C+60000%0A50000000%2C+60000000%0A20%2C+30%0A0%2C+20051%0A299999999%2C+299999999%0A20000%2C+2000000%0A2000000%2C+2000000%0A1%2C+500000%0A1%2C+50000000%0A200000000%2C+100000000&debug=0)
Formula: `sum(input) / (1 + (product(input) / 9e16))`
Bonus: [click here!](http://pyth.herokuapp.com/?code=K%2C%2asQJ%2a9%5ET16%2B%2aFQJ%25%22%25s+-%3E+%25s+%28%25s%29%22%5BPt%60Qj%5C%2F%2FRiFKKcFK&test_suite=1&test_suite_input=50000%2C+60000%0A50000000%2C+60000000%0A20%2C+30%0A0%2C+20051%0A299999999%2C+299999999%0A20000%2C+2000000%0A2000000%2C+2000000%0A1%2C+500000%0A1%2C+50000000%0A200000000%2C+100000000&debug=0)
[Answer]
# Javascript 24 bytes
Shaved off 4 bytes thanks to @LeakyNun
```
v=>u=>(v+u)/(1+v*u/9e16)
```
Pretty straightforward
[Answer]
# Julia, 22 bytes
```
u\v=(u+v)/(1+u*v/9e16)
```
[Try it online!](http://julia.tryitonline.net/#code=dVx2PSh1K3YpLygxK3Uqdi85ZTE2KQoKQHByaW50ZigiJWYiLCA1MDAwMDAwMFw2MDAwMDAwMCk&input=)
[Answer]
# TI-Basic, 21 bytes
```
Prompt U,V:(U+V)/(1+UV/9ᴇ16
```
[Answer]
# TI-BASIC, 12 bytes
```
:sum(Ans/(1+prod(Ans/3ᴇ8
```
Takes input as a list of `{U,V}` on `Ans`.
[Answer]
# Microscript II, 28 bytes
```
1s16Es9*s>Fs>Fs<d*</+s<o<+</
```
[Answer]
## PowerShell, 34 bytes
```
param($u,$v)($u+$v)/(1+$v*$u/9e16)
```
Extremely straightforward implementation. No hope of catching up with anyone, though, thanks to the 6 `$` required.
[Answer]
# Oracle SQL 11.2, 39 bytes
```
SELECT (:v+:u)/(1+:v*:u/9e16)FROM DUAL;
```
[Answer]
# T-SQL, 38 bytes
```
DECLARE @U REAL=2000000, @ REAL=2000000;
PRINT FORMAT((@U+@)/(1+@*@U/9E16),'g')
```
[Try it online!](https://data.stackexchange.com/stackoverflow/query/499940/calculate-the-relativistic-velocity)
Straightforward formula implementation.
[Answer]
# dc, 21 bytes
```
svddlv+rlv*9/I16^/1+/
```
This assumes that the precision has already been set, e.g. with `20k`. Add 3 bytes if you can't make that assumption.
A more accurate version is
```
svdlv+9I16^*dsc*rlv*lc+/
```
at 24 bytes.
Both of them are reasonably faithful transcriptions of the formula, with the only notable golfing being the use of `9I16^*` for c².
[Answer]
## PHP, 44 45 bytes
Anonymous function, pretty straightforward.
```
function($v,$u){echo ($v+$u)/(1+$v*$u/9e16);}
```
[Answer]
## Actually, 12 bytes
```
;8╤3*ì*πu@Σ/
```
[Try it online!](http://actually.tryitonline.net/#code=OzjilaQzKsOsKs-AdUDOoy8&input=MjAwMDAwMCwgMjAwMDAwMA)
Explanation:
```
;8╤3*ì*πu@Σ/
; dupe input
8╤3*ì* multiply each element by 1/(3e8)
πu product, increment
@Σ/ sum input, divide sum by product
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 24 bytes
```
u->v->(u+v)/(1+u*v/9e16)
```
[Try it online!](https://tio.run/##ZZDJbsIwEIbvPMUICSkGY2JKwlZyqnrriSPKwQ02Mg1JFNuREMqzp87SNqE@zPLN2DO/r6xg8@v5q5K3LM01XG1OjJYxESaJtEwTMt2PopgpBR9MJvAYAWTmM5YRKM20dUUqz3CzNeeoc5lcTiGw/KJQ0wrw3r3z@pbaaxw/560LAhBwqMw8KOaBY2YFWjh0ZqbFYsupj6p989a56T2FdoTmSis4dEMAHuDxFQafr6DEPbau2brPli6GF7dPLFi6rkcHXdvu4L9wUK@nLbk/ZP4/RrFdwnsGw4X4BgPlGygbVLZaRZo7P3obtbtWM/qVfLwrzW8kNZpk9uO1cMYT4goMtd1Z64lJMsbNtZMbdgG1gSAsy@K701VQP6UhQu0G9TrlqKy@AQ "Java (JDK) – Try It Online")
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 39 bytes
```
: f 2dup + s>f * s>f 9e16 f/ 1e f+ f/ ;
```
[Try it online!](https://tio.run/##S8svKsnQTU8DUf//WymkKRillBYoaCsU26UpaIFJy1RDM4U0fQXDVIU0bRDD@r@RJRQoIFhpCml6XEYGUKBgCGeBJP4DAA "Forth (gforth) – Try It Online")
### Code Explanation
```
: f \ start a new work definition
2dup + \ get the sum of u and v
s>f \ move to top of floating point stack
* s>f \ get the product of u and v and move to top of floating point stack
9e16 f/ \ divide product by 9e16 (c^2)
1e f+ \ add 1
f/ \ divide the sum of u and v by the result
; \ end word definition
```
[Answer]
# Math++, 26 bytes
```
?>u
?>v
(v+u)/(1+v*u/9e16)
```
[Answer]
# ForceLang, 116 bytes
```
def r io.readnum()
set s set
s u r
s v r
s w u+v
s c 3e8
s u u.mult v.mult c.pow -2
s u 1+u
io.write w.mult u.pow -1
```
] |
[Question]
[
[PARI/GP](http://pari.math.u-bordeaux.fr/) is a free computer algebra system. It is designed for (algebraic) number theory, not golfing, but that's part of the attraction. Unsurprisingly, it fares best at mathematical tasks; its support for string manipulation is primitive. (Having said that, advice for golfing non-mathematical tasks is also welcome.)
As usual, please post one tip per answer.
These tips should be at least *somewhat* specific to PARI/GP; advice which applies to 'most' languages belongs at [Tips for golfing in <all languages>](https://codegolf.stackexchange.com/q/5285/2605). Some general tips which don't need to be included:
1. Compress whitespace. (In GP all whitespace outside of strings is optional.)
2. Use single-character variables. (There are 50 choices, a-z and A-Z except I and O.)
3. Use `<` and `>` rather than `<=` and `>=` when possible.
4. Chain assignments. (`a=b=c` or `a+=b*=c`)
[Answer]
Use operators to replace commands (or longer operators!) when possible.
`length(v)` → `#v` (saves 5-7 bytes)
`matsize(M)[2]` → `#M` (saves 9-11 bytes)
`matsize(M)[1]` → `#M~` (saves 8-10 bytes)
`floor(x)` → `x\1` (saves 3-5 bytes)
`round(x)` → `x\/1` (saves 2-4 bytes)\*
`shift(x,n)` → `x>>n` or `x<<n` (saves 2-6 bytes)
`sqr(x)` → `x^2` (saves 1-3 bytes)
`deriv(x)` → `x'` (saves 4-6 bytes)
`mattranspose(M)` → `M~` (saves 11-13 bytes)
`factorial(n)` → `n!` (saves 8-10 bytes)
`&&` → `&` (saves 1 byte; note that this syntax is deprecated)
`||` → `|` (saves 1 byte; only works in older versions)
\* Prior to 2.8.1 (2016) the `\/` operator did not work correctly on t\_REAL numbers—update if you haven't!
[Answer]
* In a string context (e.g. the arguments of `print` or `Str`), commas are unnecessary:
```
i=99
print(i" bottles of beer on the wall")
```
This is even true if one of the arguments is an assignment. The following is equivalent to the above:
```
print(i=99" bottles of beer on the wall")
```
* Unassigned variables evaluate to their name in a string context:
```
for(i=1,2,print(i" bottl"e" of beer on the wall.");e=es)
```
produces:
```
1 bottle of beer on the wall.
2 bottles of beer on the wall.
```
* In a multi-line context `{ ... }`, the closing brace is unnecessary.
```
print({"this is line one
this is line two")
```
---
**Documentation**
In REPL:
`?*` - show all commands.
`?<command>` - show brief documentation for a command.
Online documentation:
<http://pari.math.u-bordeaux.fr/dochtml/html.stable/>
[Answer]
Some replacements:
* `poldegree(f)` -> `#f'`
* `subst(f,x,y)` -> `x=y;eval(f)` if `x` is not used elsewhere
* `subst(f,x,0)` -> `f%x` but its type is `t_POL` instead of `t_INT`
* `polcoeff(s+O(x^(n+1)),n)` -> `Pol(s+O(x^n*x))\x^n` but its type is `t_POL`
* `polcoeff(s+O(x^(n+1)),n)` -> `Vec(s+O(x^n++))[n]` if the constant term of `s` is nonzero
* `Vecrev(v)~` -> `Colrev(v)`
* `Pol(s+O(x^n))` -> `s%x^n` if `s` is a rational function (e.g., `1/(1-x)`) and `n > 0`
* `(1-x^n)/(1-x)` -> `x^n\(x-1)`
* `matrix(n,n,i,j,e)` -> `matrix(n,,i,j,e)`
* `a[2..#a]` / `a[2..-1]` -> `a[^1]`
* `a[1..-2]` -> `a[^#a]`
* `if(cond0,a,if(cond1,b,c))` -> `if(cond0,a,cond1,b,c)`
* `ceil(x)` -> `-x\-1`
[Answer]
Use set-builder notation to replace apply and select.
`apply(x->thing1(x)&&thing2(x),select(condition,v))` → `[thing1(x)&&thing2(x)|x<-v,condition(x)]`
or
`apply(x->thing1(x)&&thing2(x),v)` → `[thing1(x)&&thing2(x)|x<-v]`
but if you're applying a named function, `apply` is better, since the arguments are implicit:
`[functionName(x)|x<-v]` → `apply(functionName,v)`
[Answer]
Use specialized loops.
GP provides (at least) the following loops: `for`, `forcomposite`, `fordiv`, `forell`, `forpart`, `forprime`, `forstep`, `forsubgroup`, `forvec`, `prod`, `prodeuler`, `prodinf`, `sum`, `sumalt`, `sumdiv`, `sumdivmult`, `suminf`, `sumnum`, `sumnummonien`, `sumpos`.
So don't write `s=0;for(i=1,9,s+=f(i));s` when you could write `sum(i=1,9,f(i))`, don't write `for(n=1,20,f(prime(n)))` when you could write `forprime(p=2,71,f(p))`, and certainly don't write `apply(v->print(v),partitions(4));` instead of `forpart(v=4,print(v))`.
`prodeuler` can be useful as a product over the primes, but note that it returns a `t_REAL` rather than a `t_INT`, so rounding at the end may be necessary depending on the task.
`sumdiv` can be a real lifesaver compared to a simple loop over `divisors`.
`forvec` is a replacement for a whole collection of loops. You can replace (ungolfed)
```
{
for(i=0,9,
for(j=i,99,
for(k=i,200,
f(i,j,k)
)
)
);
}
```
with
```
forvec(v=[[0,9], [0,99], [0,200]],
call(f, v)
,
1 \\ increasing sequences only
)
```
[Answer]
# Know your built-ins
Like other computer algebra systems, PARI/GP also has a lot of built-ins for number theory, linear algebra, polynomials, and other branches of algebra.
The easy way to find a built-in is looking at the reference card.
* [Reference card for 2.15.1 (the newest version)](https://pari.math.u-bordeaux.fr/pub/pari/manuals/2.15.1/refcard.pdf)
* [Reference card for 2.13.3 (the version on ATO)](https://pari.math.u-bordeaux.fr/pub/pari/manuals/2.13.3/refcard.pdf)
* [Reference card for 2.11.1 (the version on TIO)](https://pari.math.u-bordeaux.fr/pub/pari/manuals/2.11.1/refcard.pdf)
Many built-ins have a prefix to indicate the types they work on. For example:
* Built-ins for matrices usually have the prefix `mat`
* Built-ins for polynomials usually have the prefix `pol`
* Built-ins for power series usually have the prefix `ser`
When you are looking for a built-in, you can type the prefix in the REPL, and press `tab`. The command-line completion will tell you what functions it has.
To see the help message of a built-in in the REPL, just type `? functionname`. For a more detailed help message, sometimes with examples, type `?? functionname`.
[Answer]
Avoid `return` when possible.
The final value in the function is returned, so don't write `...;return(x)` but just `...;x`.
If you must use `return`, note that the bare for `return` yields the PARI value `gnil`, which is falsy (coerced into a GP `0` or PARI `gen_0` as needed), so you can usually write `return` rather than `return(0)`.
And (almost?) needless to say, but if you have two values to choose from, much better to return `if(condition,x,y)` than `if(condition,return(x));y`.
[Answer]
# Truthy and Falsy
There isn't a Boolean type in PARI/GP. Truthy and falsy are defined as the following:
* Values that equal to `0` are falsy. This includes real number `0.0`, complex number `0.0+0.0*I`, polynomial `0*x`, power series `0+O(x^3)`, modulo object `Mod(0,3)`, and many others.
* Vector and matrices that are empty or only contains falsy values are falsy. This includes nested falsy vectors like `[0, [0, 0, [[]]]]`.
* Everything else is truthy. In particular, lists, maps, strings, and `Vecsmall`s are always truthy even if they are empty or only contains falsy values.
The simplest way to convert `a` to the "default" truthy / falsy value (i.e., `1` / `0`) is `!!a`.
When testing equality with `==`, every falsy value is equal to `0`. If you need to distinguish between different falsy values, use `===`.
## Use `-` to test equality
For `a` and `b` that can subtract, we can do:
* `if(a==b,c,d)` => `if(a-b,d,c)`
* `a==b&&c` => `a-b||c` if we only need the side effect of `c`.
* `a==b||c` => `a-b&&c` if we only need the side effect of `c`.
Be careful when testing vector equality: only vectors that have the same length can subtract.
## Any and All
There isn't built-in `any` or `all` function in PARI/GP.
When checking if a predicate is true for all or any integers in a range, we can just use `sum` or `prod`.
When checking if any item in a vector is truthy, we don't need a function: the vector itself is truthy if and only if any item in it is truthy.
When checking if all item in a vector is truthy, the following has the same length:
```
vecprod(a)
![!i|i<-a]
```
## Initialize with truthy/falsy
When using functions like `for`, `sum`, `prod`, we usually initialize some variable to `0` and `1`. If the previous expression returns the opposite truthy/falsy value, we can just use it. For example:
```
a=some_truthy_value;for(i=0,n,do_something())
=>
for(i=!a=some_truthy_value,n,do_something())
```
[Answer]
# String replace
PARI/GP doesn't have a string replace built-in, but when you want to replace every occurrence of `a` in `s` by `b`, you can do `strjoin(strsplit(s,a),b)`.
`strjoin` and `strsplit` are introduced in PARI/GP 2.13.0, so they are not supported on TIO.
[Answer]
# Default parameters
In PARI/GP, function parameters default to `0`. This can be useful when you need to initialize a variable to `0`.
For example, instead of `f(x)=i=0;...`, you can write `f(x,i)=...`.
] |
[Question]
[
Your goal is to compute the set intersection of two lists of integers. The intersection is defined as the unique un-ordered group of integers found at least once in both input list.
# Input
The input may be in any format desired (function parameter, stdio, etc.), and consists of two lists of integers. You many not assume anything about each list other than they may contain any non-negative number of integers (i.e. they are unsorted, possibly may contain duplicates, may have different lengths, and may even be empty). It is assumed that each integer will fit in your language's native signed integer type, may be more than 1 decimal digit long, and are signed.
Example input:
```
1 4 3 9 8 8 3 7 0
10 1 4 4 8 -1
```
# Output
The output is any list-like of integers representing the set intersection of the two lists to any format desired (return value, stdio, etc.). There is no requirement that the output be sorted, though you are welcome to provide an implementation that happens to always be sorted. The output must form a valid un-ordered set (e.g. it must not contain any duplicate values).
Example test cases (note that the order of the output is not important):
First two lines are the input lists, third line is the output. `(empty)` denotes the empty list.
```
(empty)
(empty)
(empty)
1000
(empty)
(empty)
3 1 2 4 3 1 1 1 1 3
3 1 -1 0 8 3 3 1
1 3
1 2 1
3 3 4
(empty)
```
# Scoring
This is code golf; shortest answer in bytes wins.
Standard loop-holes are prohibited. You may use any built-in features not designed for set-like operations.
Prohibited built-in features:
* set creation/removing duplicates
* set difference/intersection/union
* Generalized membership testing (e.g. anything similar to the `in` keyword in Python, `indexOf`-like functions, etc). Note that the use of "foreach item in list" constructs are allowed (assuming they don't violate any of the other restrictions), despite the fact that Python re-uses the `in` keyword to create this construct.
* These prohibited built-ins are "viral", i.e. if there's a larger built-in containing any of these sub-features, it is similarly prohibited (e.g. filtering by membership in a list).
Any built-ins not on the above list are allowed (ex. sorting, integer equality testing, list append/remove by index, filtering, etc.).
For example, take the following two example snippets (Python-like code):
```
# prohibited: filters by testing if each value in tmpList is a member of listA
result = tmpList.filter(listA)
# ok: filtering by a lambda which manually iterates over listA and checks for equality
def my_in_func(val, slist):
for a in slist:
if(val == a):
return True
return False
result = filter(lambda v: my_in_func(val, listA), tmpList)
```
You are welcome to implement any of these set-like features yourself and they will count towards your score.
Your solution should complete in a reasonable amount of time (say, less than a minutes on whatever hardware you have for two lists ~length 1000 each).
[Answer]
## Haskell, ~~45~~ 42 bytes
```
y#(e:s)=[e|any(==e)y,all(/=e)s]++y#s
_#x=x
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v1JZI9WqWNM2OrUmMa9Sw9Y2VbNSJzEnR0MfyCqO1dauVC7mileusK34n5uYmWebks@lAAQFRZl5JSrRxjqGOkY6JjogGgKNY5XBorqGOgY6FkAJICcWWYuhnp6hgYEBUJmlpQGQDSRj/wMA "Haskell – Try It Online")
Edit: -2 bytes thanks to @Ørjan Johansen, -1 byte thanks to @dfeuer.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 18 bytes
```
YY_iti!=Xa)hStdfQ)
```
[**Try it online!**](http://matl.tryitonline.net/#code=WVlfaXRpIT1YYSloU3RkZlEp&input=WzMgMSAyIDQgMyAxIDEgMSAxIDNdClszIDEgLTEgMCA4IDMgMyAxXQ)
This works in two steps. First the intersection is computed, possibly with duplicates. This is based on comparing all elements of one array with all elements of the other, and keeping elements of the first that are present in the second.
Then duplicates are removed. For this, the array from the previous step is sorted, and entries are kept if different from the preceding. A `-inf` value is prepended so that the first (i.e. lowest) value is not lost.
```
YY_ % push -infinity
it % take first input. Duplicate
i! % take second input. Transpose
= % test all combinations of elements of the two inputs for equality
Xa % row vector that contains true for elements of first array that
% are present in the second, possibly duplicated
) % index into first array to keep only those elements. Now we need
% to remove duplicates
h % append -infinity
S % sort
tdf % duplicate. Find entries that differ from the preceding
Q) % add 1 and index into array to keep only non-duplicates
```
[Answer]
# Jelly, 13 bytes
```
=S¥Ðf
ṂrṀ{ç³ç
```
[Try it online!](http://jelly.tryitonline.net/#code=PVPCpcOQZgrhuYJy4bmAe8OnwrPDpw&input=&args=WzMsIDEsIDIsIDQsIDMsIDEsIDEsIDEsIDEsIDNd+WzMsIDEsIC0xLCAwLCA4LCAzLCAzLCAxXQ)
### How it works
```
ṂrṀ{ç³ç Main link. Arguments: A (list 1), B (list 2)
Ṃ Yield m, the minimum of A.
Ṁ{ Yield M, the maxmimum of A.
r Create an inclusive range from m to M.
f³ Apply the helper link with right argument A.
f Apply the helper link with right argument B.
=S¥Ðf Helper link. Arguments: n (integer in range), L (list, A or B)
= Test all elements of L for equality with n.
S Add the results.
¥ Combine the two previous links into a dyadic chain.
Ðf Filter by the result of the sums.
```
[Answer]
# [golflua](http://mniip.com/misc/conv/golflua/), 68 chars
```
\f(a,b)k={}~@_,v p(a)~@_,w p(b)?w==v k[w]=w$$$~@_,v p(k)I.w(v," ")$$
```
which is called as
```
> f({1,2,3,4},{3,4,5})
3 4
> f({3,1,2,4,3,1,1,1,1,3},{3,1,-1,0,8,3,3,1})
3 1
```
In regular Lua, this would be
```
function foo(a,b)
local k={}
for i,v in pairs(a)
for j,w in pairs(b)
if v==w then
k[v] = v
end
end
end
for i,v in pairs(k)
print(v," ")
end
end
```
So basically I'm iterating over the each element of the two tables and only storing the equivalent values. By using the value as the key (`k[w]=w`), I'm eliminating all duplicates. We then output the new table by iterating over the [index & value of `pairs`](https://stackoverflow.com/q/12584258/)
[Answer]
## JavaScript (ES6), 66 bytes
```
(a,b)=>a.filter((e,i)=>b.some(f=>e==f)&a.slice(0,i).every(f=>e-f))
```
Without using `indexOf`, as I'm not convinced that it's permitted.
[Answer]
# Pyth, ~~12~~ 11 bytes
```
eMrSsq#RQE8
```
[Demonstration](https://pyth.herokuapp.com/?code=eMrSsq%23RQE8&input=%5B3%2C+1%2C+2%2C+4%2C+3%2C+1%2C+1%2C+1%2C+1%2C+3%5D%0A%5B3%2C+1%2C+-1%2C+0%2C+8%2C+3%2C+3%2C+1%5D&debug=0)
Explanation:
```
eMrSsq#RQE8
Implicit: Q is one of the lists.
q#RQE For every element in the first list, filter the second list on
equality with that element.
s Concatenate. We now have the intersection, with duplicates.
rS 8 Sort and run length encode, giving counts and elements.
eM Take just the elements.
```
[Answer]
# bash + GNU coreutils, 184 Bytes
```
[ -z "$1" ] && exit
p='{if(a[$0]++==0)print $0}'
while read A; do
while read B; do
[ $A = $B ] && echo $A
done < <(grep -oP '\d*'<<<$1|awk "$p")
done < <(grep -oP '\d*'<<<$2|awk "$p")
```
Invocation:
```
./codegolf.sh '12 4 654 12 3 56' '4 4 56 33 3 3 3'
```
Output:
```
4
56
3
```
No output if intersection is empty.
This script does not sort and makes sanity check if first set is empty. Explanation:
```
[ -z "$1" ] && exit # Exit if first set is empty
p='{if(a[$0]++==0)print $0}' # The AWK program we will use
while read A; do # read the list with two
while read B; do # encapsulated loops
[ $A = $B ] && echo $A # if they match, then print
done < <(grep -oP '\d*'<<<$1|awk "$p")
done < <(grep -oP '\d*'<<<$2|awk "$p")
# the process substitution greps the numbers and pipes them to awk. Our awk program makes them unique without sorting; it uses associative arrays with index names same as lines (our numbers here).
```
Bonus to know: You could change to `grep -o .` to do this with random strings instead of numbers.
[Answer]
# Perl 6, ~~26~~ 37 bytes
```
{%(@^a.grep(any(@^b)):p.invert).keys}
```
**usage**
```
> my &f = {%(@^a.grep(any(@^b)):p.invert).keys}
-> @a, @b { #`(Block|559823336) ... }
> f([3,1,2,4,3,1,1,1,1,3], [3,1,-1,0,8,3,3,1])
(1 3)
```
**Cheeky non-competing answer**
```
> [3,1,2,4,3,1,1,1,1,3] ∩ [3,1,-1,0,8,3,3,1]
set(3, 1)
```
or if you like it in a boring ol' `f` function
```
> my &f = &infix:<∩>
sub infix:<∩> (|p is raw) { #`(Sub+{<anon|130874592>}+{Precedence}|102325600) ... }
> f([3,1,2,4,3,1,1,1,1,3], [3,1,-1,0,8,3,3,1])
set(3, 1)
```
[Answer]
# [Retina](http://github.com/mbuettner/retina), 63 bytes
The last two lines remove duplicates. The input is two space-delimited lists separated by a comma. The output is whitespace-delimited.
```
+`( -?\d+)\b(.*,.*)\1\b
$1_$2
-?\d+\b|_|,
+`(-?\d+)(.*)\1
$1$2
```
[**Try it online**](http://retina.tryitonline.net/#code=K2AoIC0_XGQrKVxiKC4qLC4qKVwxXGIKJDFfJDIKLT9cZCtcYnxffCwKCitgKC0_XGQrKSguKilcMQokMSQy&input=MiA0IDMgMSAxIDEgMSAzLCAzIDEgLTEgMCA4IDMgMyAx)
If duplicates in the output are allowed, my program would be 42 bytes.
[Answer]
# [Jq 1.5](https://stedolan.github.io/jq/), 99 bytes
```
def f(a;b):(a+b|min)as$m|[range($m;a+b|max)|[]]|.[a[]-$m][0]=1|.[b[]-$m][1]=1|.[[[1,1]]]|map(.+$m);
```
Expanded
```
def f(a;b):
(a+b|min) as $m # find smallest value in either array
| [range($m;a+b|max)|[]] # create array of [] for indices [min,max]
| .[ a[]-$m ][0]=1 # store 1 in [0] at corresponding indices of a
| .[ b[]-$m ][1]=1 # store 1 in [1] at corresponding indices of b
| .[[[1,1]]] # find all the indices where we stored a 1 for a and b
| map(.+$m) # convert back from indices to values
;
```
This avoids using `{}` objects and since jq does not have bit operations this emulates them with an array.
[Try it online!](https://tio.run/##hU/LjoMgFN33K1i4gBQa0U7RMfMlhAVmamNT0FFMu/Dbx7mAxtk1kXjOPY8L959l@b42qMG6qskn1sd6Nq0lekzMLAdtb1ecmCqM9YvMUqn5JLVULDFKpuqLA61XyiOVklOuwGh0j0/HxJBqabC8qAqBgi6K0ANwgBlFOUVnL5wp@gCNIrHKKUAQ8wJspXdEFKfp3uELQhC@4AObCCwq@WrNwrpsU2CZ79sDfrC1govDJg4Ky4pyZSI84J/GRTzes0VFvGRexv@GeRHC5R7O0rWgeBt9Fz/Mrhvd0Nrb8tv1ru3suDBmp8eDtbafHJBBP1k3OSB/ "jq – Try It Online")
[Answer]
# Axiom, 411 bytes
```
b(x,v)==(l:=1;h:=#v;repeat(l>h=>break;m:=(l+h)quo 2;x<v.m=>(h:=m-1);x>v.m=>(l:=m+1);return m);0);g(a,b)==(if #a>#b then(v:=a;w:=b)else(v:=b;w:=a);c:=sort(v);for x in w repeat(if binSearch(x,c)~=0 then return 1);0)
f(a:List INT,b:List INT):List INT==(r:List INT:=[];#a*#b=0=>r;x:=sort(a);y:=sort(b);i:=1;repeat(i>#x=>break;v:=x.i;binSearch(v,y)=0=>(i:=i+1);r:=concat(r,v);while i<=#x and x.i=v repeat i:=i+1);r)
```
ungolf and test
```
--suppose v.1<=v.2<=....<=v.#v as the default function sort() produce
-- binary serch of x in v, return the index i with v.i==x
-- return 0 if that index not exist
--traslated in Axiom from C book
--Il Linguaggio C, II Edizione
--Brian W.Kerninghan, Dennis M.Ritchie
binSearch(x,v)==
l:=1;h:=#v
repeat
l>h=>break
m:=(l+h)quo 2
x<v.m=>(h:=m-1)
x>v.m=>(l:=m+1)
return m
0
--N*log(N)+n*log(n)+N*n*log(n) so it is N*n*log(n) or n*N*log(N)
ListIntersection(a:List INT,b:List INT):List INT==
r:List INT:=[];#a*#b=0=>r
x:=sort(a);y:=sort(b)
i:=1
repeat
i>#x=>break
v:=x.i
binSearch(v,y)=0=>(i:=i+1)
r:=concat(r,v)
while i<=#x and x.i=v repeat i:=i+1
r
(5) -> f([],[])
(5) []
Type: List Integer
(6) -> f([1000],[])
(6) []
Type: List Integer
(7) -> f([3,1,2,4,3,1,1,1,1,3],[3,1,-1,0,8,3,3,1])
(7) [1,3]
Type: List Integer
(8) -> f([1,2,1],[3,3,4])
(8) []
Type: List Integer
```
[Answer]
# Axiom, 257 bytes
```
W(x,y)==>while x repeat y;f(a,b)==(r:List INT:=[];#a*#b=0=>r;x:=sort(a);y:=sort(b);i:=1;j:=1;repeat(j>#y=>break;W(i<=#x and x.i<y.j,i:=i+1);i>#x=>break;W(j<=#y and y.j<x.i,j:=j+1);j>#y=>break;v:=y.j;if x.i=v then(r:=concat(r,v);W(j<=#y and y.j=v,j:=j+1)));r)
```
This without the use of binsearch... But i don't know the big O...
Unglofed and results:
```
--N*log(N)+n*log(n)+???
ListIntersection(a:List INT,b:List INT):List INT==
r:List INT:=[];#a*#b=0=>r
x:=sort(a);y:=sort(b)
i:=1;j:=1
repeat
j>#y=>break
while i<=#x and x.i<y.j repeat i:=i+1
i>#x=>break
while j<=#y and y.j<x.i repeat j:=j+1
j>#y=>break
v:=y.j;if x.i=v then
r:=concat(r,v)
while j<=#y and y.j=v repeat j:=j+1
r
(3) -> f([3,1,2,4,3,1,1,1,1,3],[3,1,-1,0,8,3,3,1])
(3) [1,3]
Type: List Integer
(4) -> f([],[])
(4) []
Type: List Integer
(5) -> f([1,2,1],[3,3,4])
(5) []
Type: List Integer
```
Not executed many tests so could be bugged...
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
pEÐfḢ€ĠḢ€$ị$
```
[Try it online!](https://tio.run/##y0rNyan8/7/A9fCEtIc7Fj1qWnNkAYRWebi7W@X////GOoY6RjomOiAaAo3BYrqGOgY6FkBhEMcEAA "Jelly – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
mo←←kIfE*
```
[Try it online!](https://tio.run/##yygtzv7/Pzf/UdsEIMr2THPV@v//f7SxjqGOkY6JDoiGQONYiKiuoY6BjgVQAsiJBQA "Husk – Try It Online")
```
m Map
o←← taking the first element from the first element
kI over lists of identical values from
* the Cartesian product of the two input lists
f filtered by
E both elements of a pair being equal.
```
Looking in Husk's source code on GitHub, `k` ("keyon") is implemented as the composition of sorting the list and grouping adjacent values, so although I can't actually find the implementation of "groupOn" it's probably safe to assume that it doesn't do anything setty, since Haskell is a functional language and grouping adjacent equal values is a pretty straightforward reduce-over-a-linked-list operation. (I *can* find the implementation of `k`'s other type signature "keyby", which I could use here by changing `I` to `=`, but I don't know Haskell so I can't tell how exactly it works.)
Also, a nice little Brachylog answer I came up with before I realized set operations of all sorts were disallowed: `⟨∋∈⟩ᵘ`
[Answer]
# R, ~~141~~ 83 bytes
~~```
l=sapply(strsplit(readLines(file("stdin"))," "),as.numeric)
r=rle(sort(unlist(l)))[[2]]
r[sapply(r,function(x)any(x==l[[1]])&any(x==l[[2]]))]
```~~
Improved by [Giuseppe](https://codegolf.stackexchange.com/questions/74888/set-intersection-of-two-lists/182527?noredirect=1#comment439267_182527)
```
function(a,b){r=rle(sort(c(a,b)))[[2]];r[sapply(r,function(x)any(x==a)&any(x==b))]}
```
Try online [~~here~~](https://tio.run/##RUzLCsIwELz7FSEH2YUqtvUglPyBfxByCG0KCzGW3RTar48pCjKHeTAzXEo04pcl7iCZZYmUgYOfnpSCwEwxgJY8UdKIjVYaGy/XtL4C04gDG64FeXOGNUWSDBERre2cG9j@frmZ1zRmeifY0KcdNmOita1zeP7bOkF0pfSqVZ26q4O/6E@HvrTqph41ruYD) [here](https://tio.run/##TYvbCoMwEER/ZZ/KLqxQLw@FNl8S8rCGBgSJslpQxG@PlxYpzMBhOKMpwCtL4RP92HQRhWta1Gj7xqHTEf25EFlbOPdUO0jftzMqX4@JJM44GSN0@9F@cGsKKGDAY8mQMxQMFcOXr5TEUP9J2d47w@MUj4kobQ)
[Answer]
# Python3, 51 bytes
```
lambda a,b:[v for v in a if{n:1 for n in b}.get(v)]
```
If the input lists can contain duplicates:
## Python3, 67 bytes
```
lambda a,b:list({v:1 for v in a if {n:1 for n in b}.get(v)}.keys())
```
[Answer]
# [PHP](https://php.net/), ~~78~~, 77 bytes
```
function($a,$b){foreach($a as$x)foreach($b as$y)$x==$y?$c[$x]=$x:0;return$c;}
```
[Try it online!](https://tio.run/##ZU/BasMwDD3PXyGGIDVo4Kw9jLmhp8EOg/VuTEk9l2R0dkhSSCn99sxOmlA2kEHvPb0nqyqqfr2pigqwzPrDyZm29G6BOeGeXw6@trkpAoS8wY7PeB/xmWOXZXjeoFHY6Qy7VyFr255qh0Zee8mwtU3bQAaKAShQmm4PNI1MKoT4zy4JUoJnghXB2M@1jJMj95QCCYKXYSZSk3QXP6RMQqiVpoe4iGnJ2HQO3P6ZN6EDDpdgtqbw8N14t7PO@C@7wFYJzQkeh/qjpFHZvm93b58fcnInKiEof6pjHEooACzjLhUvHkxhV/AlOpnNdylX1v8C "PHP – Try It Online")
No frills, but rule-compliant (I think).
***Output***
```
[], []
[]
[1000], []
[]
[3,1,2,4,3,1,1,1,1,3], [3,1,-1,0,8,3,3,1]
[3,1]
[1,2,1], [3,3,4]
[]
```
] |
[Question]
[
Write the shortest code to create a [deadlock](https://en.wikipedia.org/wiki/Deadlock). Code execution must halt, so this doesn't work:
```
public class DeadlockFail extends Thread{ //Java code
public static void main(String[]a){
Thread t = new DeadlockFail();
t.start();
t.join();
}
//this part is an infinite loop; continues running the loop.
public void run(){while(true){}}
}
```
It doesn't need to be [certain that the code goes into deadlock](https://stackoverflow.com/questions/8880286/write-a-program-that-will-surely-go-into-deadlock), just [almost surely](http://en.wikipedia.org/wiki/Almost_surely) (if you run for infinite time, it will deadlock).
[Answer]
## Dyalog APL (10)
```
⎕TSYNC⎕TID
```
`⎕TSYNC` makes the thread wait until the given thread ends, `⎕TID` gives the current thread.
Dyalog APL can recognize deadlocks though, so it immediately responds with
```
DEADLOCK
```
The fun thing is, you don't even need to spawn any extra threads, making the UI thread wait for itself is plenty.
If this is cheating and new threads are actually required, you can do it in 27 characters:
```
{∇⎕TSYNC&{⎕TSYNC⎕TID+1}&0}0
```
`F & x` runs `F` in a new thread on value `x`, and returns the thread ID. So:
* `{⎕TSYNC⎕TID+1}&0` creates a thread that will synchronize with the thread whose ID is one higher than its own,
* `⎕TSYNC&` creates a new thread that will synchronize with the previous thread, and which gets an ID one higher than the thread that was just created (assuming nothing else is creating threads).
* `∇` causes an infinite loop (so we keep creating threads until there's a deadlock).
This will deadlock as soon as the second thread gets created before the first one starts running, which is pretty soon:
```
9:DEADLOCK
```
[Answer]
## Go, 42
```
package main
func main(){<-make(chan int)}
```
Apologies, downvoter, for not providing how it works.
This creates an anonymous channel of ints and reads from it. This pauses the main thread until a value gets sent down the channel, which obviously never happens since no other threads are active, and thus, deadlock.
[Answer]
# Ruby, 39 characters
```
T=Thread;t=T.current;T.new{t.join}.join
```
The idea to use a cross-join shamelessly stolen from [Johannes Kuhn's Java answer](https://codegolf.stackexchange.com/a/15488/7209).
We can shave off four characters (getting to **35**) if we tune the code to a specific environment. JRuby's console IRB is single-threaded:
```
T=Thread;T.new{T.list[0].join}.join
```
---
---
This is my previous solution:
getting a thread stuck on a mutex is easy:
```
m=Mutex.new;2.times{Thread.new{m.lock}}
```
but this isn't a proper deadlock, because the second thread is technically not waiting for the first thread. "hold and wait" is a neccessary condition for a deadlock according to Wikipedia. The first thread doesn't wait, and the second thread doesn't hold anything.
# Ruby, ~~97~~ 95 characters
```
m,n=Mutex.new,Mutex.new
2.times{o,p=(m,n=n,m)
Thread.new{loop{o.synchronize{p.synchronize{}}}}}
```
this is a classic deadlock. Two threads compete for two resources, retrying if they succeed. Normally they get stuck within a second on my machine.
But, if having infinitely many threads (none of which consumes CPU infinitely and some of which deadlock) is OK,
# Ruby, ~~87~~ 85 characters
```
m,n=Mutex.new,Mutex.new
loop{o,p=(m,n=n,m)
Thread.new{o.synchronize{p.synchronize{}}}}
```
According to my test, it fails after the thread count reaches about 4700. Hopefully it doesn't fail until each thread had a chance to run (thus either deadlocking or finishing and freeing space for a new one). According to my test, the thread count doesn't drop after the failure occurs, meaning that a deadlock did occur during the test. Also, IRB died after the test.
[Answer]
# Python, 46
```
import threading as t
t.Semaphore(0).acquire()
```
(self-deadlock)
[Answer]
# Bash + GNU coreutils, 11 bytes
```
mkfifo x;<x
```
Creates a stray FIFO `x` in the current directory (so you'll need to not have a file by that name). FIFOs can be deleted the same way as regular files, so it shouldn't be hard to clear up.
A FIFO has a write side and a read side; attempting to open one blocks until another process opens the other, and this seems to have been intentionally designed as a synchronization primitive. Given that there's only one thread here, as soon as we try to open it with `<x`, we get stuck. (You can unstick the deadlock via writing to the FIFO in question from another process.)
This is a different kind of deadlock from the one when there are two resources, and two threads each have one and needs the other; rather, in this case, there are zero resources and the process needs one. Based on the other answers, I think this counts, but I can understand how a deadlock purist might want to disallow the answer.
Come to think of it, I can actually think of three deadlock-like situations:
1. The "traditional" deadlock: two threads are each waiting for a lock to be released, that's held by the other thread.
2. A single thread is waiting for a lock to be released, but it holds the lock itself (and thus is blocking itself from being able to release it).
3. A single thread is waiting for a synchronization primitive to be released, but the synchronization primitive starts in a naturally locked state and has to be unlocked externally, and nothing's been programmed to do that.
This is a deadlock of type 3, which is in a way fundamentally different from the other two: you could, in theory, write a program to unlock the synchronization primitive in question, then run it. That said, the same applies to deadlocks of type 1 and 2, given that many languages allow you to release a lock you don't own (you're not *supposed* to and would have no reason to do so if you had a reason to use the locks in the first place, but it works…). Also, it's worth considering a program like `mkfifo x;<x;echo test>x`; that program's sort-of the opposite of a type 2 deadlock (it's trying to open both ends of the FIFO, but it can't open one end until after it opens the other end), but it was made from this one via adding extra code that never runs after this one! I guess the problem is that whether a lock is deadlocked or not depends on the *intention* behind the use of the lock, so it's hard to define objectively (especially in a case like this where the only purpose of the lock is to produce a deadlock intentionally).
[Answer]
# C#, 100
```
class C{static C(){var t=new System.Threading.Thread(Main);t.Start();t.Join();}static void Main(){}}
```
See: [The no-lock deadlock](http://ericlippert.com/2013/01/31/the-no-lock-deadlock/)
[Answer]
# Bash with glibc, 6 Bytes
Sorry to revive an old thread, but couldn't resist.
As root:
```
pldd 1
```
From [man pldd](http://man7.org/linux/man-pages/man1/pldd.1.html):
>
> BUGS
>
> Since glibc 2.19, pldd is broken: it just hangs when executed. It is unclear if it will ever be fixed.
>
>
>
[Answer]
## Java, 191
```
class B extends Thread{public static void main(String[]a)throws Exception{new B().join();}Thread d;B(){d=Thread.currentThread();start();}public void run(){try{d.join();}catch(Exception e){}}}
```
Ungolfed:
```
class B extends Thread {
Thread d;
public static void main(String[] args) throws Exception {
new B().join();
}
B() { // constructor
d = Thread.currentThread();
start();
}
public void run() {
try {
d.join();
} catch (Exception e) {
}
}
}
```
Starts a new Thread and `join` on it (wait until this thread has finished), while the new Thread does the same with the original Thread.
[Answer]
## Tcl, 76
```
package r Thread;thread::send [thread::create] "thread::send [thread::id] a"
```
Deadlock.
This creates a new Thread, and tells the other thread to send my thread a message (script to execute).
But sending a message to an other Thread usually blocks until the script has been executed. And while it is blocking, no messages are processed, so both Threads wait for the other to process their message.
[Answer]
alternative java with monitor-abuse (248 charas)
```
class A{public static void main(String args[]) throws Exception{final String a="",b="";new Thread(new Runnable(){public void run(){try {synchronized(b){b.wait();}} catch (Exception e) {}a.notify();}}).start();synchronized(a){a.wait();}b.notify();}}
```
[Answer]
# Scala, 104 bytes
```
class A{s=>lazy val x={val t=new Thread{override def run{s.synchronized{}}};t.start;t.join;1}};new A().x
```
The lazy val initialization block suspends until a condition is fulfilled. This condition can only be fulfilled by reading the value of lazy val x - another thread that is supposed to complete this condition cannot do so. Thus, a circular dependency is formed, and the lazy val cannot be initialized.
[Answer]
# Kotlin, 35/37/55 bytes
General theme: `Thread.currentThread().join()`.
Excluding JVM bugs / very specialized code against this submission this shoud never return as the current execution thread is now disabled waiting for itself to die.
---
### Evil property: 35 bytes (non-competing): 35 bytes
`val a=Thread.currentThread().join()`
Putting this anywhere a property declaration is valid will deadlock whoever is initializing it. In the case of a top-level property, that will be the classloader initializing the mapped JVM class for that file (by default `[file name]Kt.class`).
Non-competing because "put this as a top level property anywhere" is restrictive.
---
### Function: 37 bytes
`fun a()=Thread.currentThread().join()`
---
### main(): 55 bytes
`fun main(a:Array<String>)=Thread.currentThread().join()`
[Answer]
# PowerShell, ~~36~~ ~~28~~ 23 bytes
```
gps|%{$_.waitforexit()}
```
Self-deadlock. We get all processes with `Get-Process` and then wait patiently for each of them to exit ... which will happen approximately never, since the process will be waiting on itself.
Edit - Saved 5 bytes thanks to Roman Gräf
[Answer]
# [The Waterfall Model](https://esolangs.org/wiki/The_Waterfall_Model) (Ratiofall), 13 bytes
```
[[2,1],[1,1]]
```
[Try it online!](https://tio.run/##K08sSS1KS8zJ@f8/OtpIxzBWJ9oQSMb@/w8A "The Waterfall Model – Try It Online")
Here's a fun off-the-wall answer. This is the simplest possible infinite loop in The Waterfall Model (variables in The Waterfall Model repeatedly decrement whenever nothing else is happening; this program defines a variable that increments itself whenever it decrements, so there's no way anything can ever happen).
The question asks for a deadlock, not an infinite loop. However, we can exploit the behaviour of specific implementations. At optimisation level 2 or higher (the default is 3), the interpreter Ratiofall will detect the infinite loop, and optimise it… into a deadlock! So at least if we consider languages to be defined by their implementation (which is usually the case on this site), this program does indeed define a deadlock, rather than an infinite loop.
You can see evidence of the deadlock from the time report on the Try it Online! link above:
```
Real time: 60.004 s
User time: 0.006 s
Sys. time: 0.003 s
CPU share: 0.01 %
Exit code: 124
```
The program ran for 60 seconds (until TIO automatically terminated it), but for most of that time, there was no CPU usage, no time spent by the program running, and no time spent by the kernel on behalf of the program.
To get even stronger evidence, you can run Ratiofall under a system-call-level debugger such as `strace`; doing this on Linux will show the interpreter blocking on a `futex` system call that attempts to take a lock which will never be released.
[Answer]
# C (Linux only), 31 Bytes -- [Try it online!](https://ideone.com/pL6ONL)
```
main(a){syscall(240,&a,0,a,0);}
```
System call 240 (0xf0) is [futex(2)](http://man7.org/linux/man-pages/man2/futex.2.html), or fast userspace mutex. The documentation states that the first argument
is a pointer to the futex, the second argument is the operation (0 means FUTEX\_WAIT, that is, wait until another thread unlocks the futex). The third argument is the value you expect the futex to have while still locked, and the fourth is the pointer to the timeout (NULL for no timeout).
Obviously, since there's no other thread to unlock the futex, it will wait forever in self-inflicted deadlock. It can be verified (via `top` or other task manager) that the process uses no CPU time, as we should expect from a deadlocked thread.
[Answer]
# [Julia 0.6](http://julialang.org/), 13 bytes
Language newer than question. Wait on a task (like a go-routine, will currently be on the same thread, in future versions of Julia it may be on another thread) which is not scheduled to run.
```
wait(@task +)
```
[Try it online!](https://tio.run/##yyrNyUw0@/@/PDGzRMOhJLE4W0Fb8/9/AA "Julia 0.6 – Try It Online")
[Answer]
# BotEngine, 3x3=9 (9 bytes)
```
v
lCv
> <
```
Step 5 ends with two bots waiting indefinitely for each other to move... one bot can't move because it's waiting for the other to move out of the bottom right square, and the other bot can't move because it's waiting for the first bot to move out of the bottom center square.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 24 bytes
```
Semaphore.new(0).acquire
```
[Try it online!](https://tio.run/##K0gtyjH7/z84NTexICO/KFUvL7Vcw0BTLzG5sDSzKPX/fwA "Perl 6 – Try It Online")
Create a semaphore with zero permits and then try to acquire it.
] |
[Question]
[
Your task today will be to take an existing file and append zeros to it until it reaches a certain size.
You must write a program or function which takes the name of a file in the current directory `f` and a number of bytes `b`. While maintaining the original content of `f`, you must write zeroes ***(null bytes, not ascii 0s)*** to the end so that its new size is `b` bytes.
You may assume that `f` only has alphanumeric ascii in its name, that you have full permissions over it, that it initially is not larger than `b`, but may be as large as `b`, and that there is infinite free disk space.
You may not assume `f` is nonempty, or that it does not already contain null bytes.
Other existing files should not be modified and new files should not exist after execution ends.
## Test Cases
```
Contents of f | b | Resulting contents of f
12345 | 10 | 1234500000
0 | 3 | 000
[empty] | 2 | 00
[empty] | 0 | [empty]
123 | 3 | 123
```
[Answer]
# Bash + coreutils, 13
```
truncate -s$@
```
Input from the command-line - the first parameter is the file size and the second is the filename.
From `man truncate`:
>
> If a FILE is shorter, it is extended and the extended part (hole) reads as zero bytes.
>
>
>
[Try it online](https://tio.run/##S0oszvifmpyRr6DklJqWX5RqpcRVUJSZV5KmYGhkbGKqYAeh9UoqSrgqKlKQeMWpJQq6ugqGBgix/yVFpXnJiSWpCrrFKg5gc7kghjumlaQWAc1GMeI/AA).
[Answer]
# Groovy, ~~54~~ ~~47~~ ~~43~~ 41 bytes
```
{a,b->(c=new File(a))<<'\0'*(b-c.size())}
```
*-6 thanks to manatwork's idea of removing the loop; that was my original idea, don't know why I thought it wouldn't work and opted for a loop... It definitely works, just tested it.*
# Ungolfed:
```
{
a,b-> // Two inputs: a is the File name, b is the desired size.
File c = new File(a) // Make and store the file.
c << '\0'*(b-c.size()) // Append the difference between b and c.size() in nullbytes.
}
// Usually a close would be required, but, in Groovy,
// because private data isn't so protected, if a File
// Object goes out of scope, the attached Stream is
// automatically flushed to disk.
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~33~~ 17 bytes
```
⎕⎕NRESIZE⍞⎕NTIE¯1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdtaIkNS/l/6O@qUDkF@Qa7Bnl@qh3HogT4ul6aL0hSNF/BTDQeNTVpJ6RmpOTr1CeX5SToq4JUhYQGqJeklpcoldSUaLOBVGp7p@TolCcWZVqpa5jBFLk6efmj6EKYjcXTJjLyACm3S@1nLB2dafKklSFssSc0tRioEKgulDnYAWINxxdFIBuV7AwAFNADAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~59~~ ~~57~~ 54 bytes
-5 bytes thanks to chepner
```
def g(n,b):f=open(n,'a');f.write('\0'*b);f.truncate(b)
```
[Answer]
# PHP, 66 bytes
```
for($p=fopen($f=$argv[1],a);filesize($f)<$argv[2];)fputs($p,"\0");
```
Takes input from command line arguments; run with `-nr`.
---
These 55 bytes might, but most probably will not, work:
```
fseek($p=fopen($argv[1],"w+"),$argv[2]);fputs($p,"\0");
```
[Answer]
# Java (Oracle JRE), 55 bytes
```
f->b->new java.io.RandomAccessFile(f,"rw").setLength(b)
```
The spec of `setLength(int)` says that the appended bytes are undefined, but practically the Oracle JRE appends only the `0` byte (that's why I specified it).
The resource is automatically closed by the JVM so we don't need to do it ourself.
## Test
```
public class Pcg125661 {
interface F {
B f(String f);
}
interface B {
void b(int b) throws java.io.IOException;
}
public static void main(String[] args) throws java.io.IOException {
F a = f->b->new java.io.RandomAccessFile(f,"rw").setLength(b);
a.f("a").b(100);
}
}
```
[Answer]
# AHK, 48 bytes
```
FileGetSize,s,%1%
2-=s
Loop,%2%
FileAppend,0,%1%
```
`1` and `2` are the first two parameters in an AHK script.
`FileGetSize` works in bytes by default.
It's not exciting, but it's simple: Get the size, subtract it from the desired size, and add that many zeroes.
[Answer]
# [Perl 6](http://perl6.org/), 40 bytes
```
{$_=$^a.IO;.open(:a).put("\0"x($^b-.s))}
```
`$^a` and `$^b` are the parameters to the function--the file name and the length, respectively.
[Answer]
# [Python 2](https://docs.python.org/2/), 68 bytes
```
def g(f,b):
with open(f,'r+')as c:c.write('\x00'*(b-len(c.read())))
```
[Try it online!](https://tio.run/##XY5BDsIgEEX3nILdMIoNrbrpWdxQyrQkTUuQBD09TtI0Rv9mNv/N@/Gd523tagl5llv0qwICLaEASvuU1AvJoaakkL2Ctrve7oB19CQnRXpALnxZ0pDOgAy63h3M42UMnNRwWbjhmuTtqJBTp93VGhTi359@/DGFNfOKneUTF@uO19w2POkD "Python 2 – Try It Online") (When printing the file's content, the code replaces null bytes with ASCII 0's for visibility.)
[Answer]
## PowerShell, 69 bytes
```
param($f,$s)@(gc $f -en by)+,[byte]0*($s-(gi $f).length)|sc $f -en by
# ^ filename
# ^desired size
# ^ get content as byte stream
# ^force it to an array even if there's 0 or 1 byte
# ^append a byte array of nulls..
# ^..desired size - file size
# write to file with -encoding byte ^
```
`$f` for the file, `$s` for the destination size, save as .ps1 and run
```
.\Add-NullBytesToFile.ps1 .\test.txt 10
```
---
It's a shell, so there should be a really small loop adding 1 byte with `>>` output redirection and append, right? Well, no, because `>>` only outputs UCS2-LE multibyte encoding so there's no way to add a single byte to a file with it .. unless you're using PSv5.1 and you can change that but that makes it too long to be competitive:
```
$PSDefaultParameterValues['Out-File:Encoding']='utf8';while((gi $f).length-lt$c){[byte]0>>$f}
```
Maybe there's a .Net Framework approach? There should be, but I can't make it actually write any bytes, or error. But it's longer anyway:
```
param($f,$s)[io.file]::WriteAllBytes($f,[byte[]](,0)*($c-(gi $f).length), $True)
```
[Answer]
## Mathematica 50 Bytes
Import/Export
```
Export[#,Import[#,c="Byte"]~Join~Table[0,{#2}],c]&
```
Usage
```
%["test1", 5]
```
[Answer]
# q, 29 bytes
Function which takes file name in format `:/foo/bar.baz` and length as an integer.
```
{hopen[x](0|y-hcount x)#0x00}
```
Example:
```
{hopen[x](0|y-hcount x)#0x00}[`:test.txt;100]
```
[Answer]
# C, 56 bytes
```
fseek(f,0,2);int i;for(;ftell(f)<b;)putc(0,f);fclose(f);
```
The program finds the file's size, and how many bytes to append. The file then adds `fs - b` extra bytes to the end.
[Answer]
# C#, 90 bytes
```
using System.IO;s=>n=>File.AppendAllText(s,new string('\0',(int)new FileInfo(s).Length-n))
```
] |
[Question]
[
# Introduction
The childhood song *Eeny, meeny, miny, moe* was often used to select who was "it" when playing tag. Everyone would stand in a circle and point at one person selected at random. They would sing:
>
> Eeny, meeny, miny, moe,
>
> Catch a tiger by the toe.
>
> If he hollers, let him go,
>
> Eeny, meeny, miny, moe.
>
>
>
As they sung each word, they pointed at the next person in the circle. The person being pointed to when the final "moe" was sung would be "it". The children would immediately stand up and scatter.
# Goal
Implement the shortest program in bytes that takes an input, the number of children, and lists the words that were sung when they were being pointed at.
The winner will be selected in one week.
# Input
From STDIN, a single, positive integer, the number of children. This may be more than the number of words in the song.
# Output
Writes to STDOUT a list where each line represents a child and contains the word sung while they were being pointed at. If there are too many children, empty lines may be omitted.
# Requirements
* Always start with the first child.
* Display the words without punctuation.
* The final "moe" should be emphasised as "MOE!" including punctuation.
# Example
## Input
```
3
```
## Output
```
Eeny moe tiger toe hollers go miny
meeny Catch by If let Eeny MOE!
miny a the he him meeny
```
## Input
```
7
```
## Output
```
Eeny by him
meeny the go
miny toe Eeny
moe If meeny
Catch he miny
a hollers MOE!
tiger let
```
## Input
```
1
```
## Output
```
Eeny meeny miny moe Catch a tiger by the toe If he hollers let him go Eeny meeny miny MOE!
```
## Input
```
21
```
## Output
```
Eeny
meeny
miny
moe
Catch
a
tiger
by
the
toe
If
he
hollers
let
him
go
Eeny
meeny
miny
MOE!
```
[Answer]
# Pyth, ~~103~~ ~~89~~ 84 chars
*Saved 18 bytes with string compression, thanks to @Dennis and @FryAmTheEggman*
*Saved another byte thanks to @isaacg*
Warning: there are many unprintables in the code; use the links below to try it.
```
VQjd%Q>cs[J."@y)òÎ5O¹c×Ú"."@yæ\J}ÇZH66¥ÓÀD¸¶=ðÉ §J%ÔþÖúÅ="J"MOE!")\@N
```
[Try it online](http://pyth.herokuapp.com/?code=VQjd%25Q%3Ecs[J.%22%40y%05%29%C3%B2%C3%8E5O%C2%89%12%C2%B9c%C3%97%C3%9A%22.%22%40y%0F%C3%A6%5C%1B%C2%99J%7D%C3%87ZH6%11%C2%89%C2%846%C2%A5%C3%93%1F%C3%80D%C2%B8%C2%B6%3D%C3%B0%C3%89%1B%09%C2%A7J%25%14%C3%94%C3%BE%10%C3%96%13%C3%BA%C3%85%3D%C2%92%22J%22MOE!%22%29%5C%40N&input=3&debug=0test_suite_input=2%0A3%0A4%0A5%0A6&debug=0) | [Test suite](http://pyth.herokuapp.com/?code=VQjd%25Q%3Ecs[J.%22%40y%05%29%C3%B2%C3%8E5O%C2%89%12%C2%B9c%C3%97%C3%9A%22.%22%40y%0F%C3%A6%5C%1B%C2%99J%7D%C3%87ZH6%11%C2%89%C2%846%C2%A5%C3%93%1F%C3%80D%C2%B8%C2%B6%3D%C3%B0%C3%89%1B%09%C2%A7J%25%14%C3%94%C3%BE%10%C3%96%13%C3%BA%C3%85%3D%C2%92%22J%22MOE!%22%29%5C%40N&input=3&test_suite=1&test_suite_input=2%0A3%0A4%0A5%0A6&debug=0)
Could probably be golfed. Suggestions welcome!
### How it works
```
VQjd%Q>cs[J."..."."..."J"MOE!")\@N Implicit: Q = eval(input)
VQ For each item N in range 0...int(Q):
[ ) Create an array out of the following:
J."..." Set J to this string, decompressed. ("Eeny@meeny@miny@")
."..." This string, decompressed. ("moe@[[email protected]](/cdn-cgi/l/email-protection)@him@go@")
J J.
"MOE!" "MOE!".
s Join the array with the empty string.
c \@ Split the result on "@".
> N Cut off the first N items.
%Q Take every Qth item.
jd Join with spaces.
```
[Answer]
# [TeaScript](http://github.com/vihanb/teascript), 82 bytes
```
D`${a="Ey Ú9y ·ny "}¶e C® a g by e e If Ò@s ¤t m go ${a}MOE!`q.KαtΣj═)j╝
```
Decompress, chunk, transpose, join, output.
## Explanation
```
// Implicit: x = input
D`...blah...` // Decompress "Eeny miny moe..."
q // Split
Kα // chunk into x-size blocks (α == x)
t // Transpose
Σ // Loop through lines
j═) // Join with spaces
j╝ // Join with newline
```
[Try it online](http://vihan.org/p/TeaScript/#?code=%22D%60E%C2%81y%20%C3%9A9y%20%C2%B7ny%20%C2%B6e%20C%C2%85%C2%AE%20a%20%C2%93g%C2%80%20by%20%C2%90e%20%C2%91e%20If%20%C2%94%20%C2%97%C3%92@s%20%C2%A4t%20%C2%96m%20go%20E%C2%81y%20%C3%9A9y%20%C2%B7ny%20MOE!%60qK(x)t%CE%A3j%E2%95%90)j%E2%95%9D%22&inputs=%5B%223%22%5D&opts=%7B%22int%22:true,%22ar%22:false,%22debug%22:false%7D)
---
**Non-competing 81 byte**
The `α` wasn't getting chained `.` so I had to bug fix this
```
D`${a="Ey Ú9y ·ny "}¶e C® a g by e e If Ò@s ¤t m go ${a}MOE!`qKαtΣj═)j╝
```
[Answer]
# Jelly, 84 bytes
```
“£Dṡ“Ṙ©“Ė“¡Ḳ⁵“=U“¡Ẹ⁵“¡Ṇm“ȯf“ŀQ“ÞṖċ¥“ṅ_“Ẉ1“¡æḷ“¡ƒmxĠ“¡ṇƭEỤr“¡Þ¦»ṫ-2;;“MOE!”W¤sƓZj€⁶j⁷
```
[Try it online!](http://jelly.tryitonline.net/#code=4oCcwqNE4bmh4oCc4bmYwqnigJzEluKAnMKh4biy4oG14oCcPVXigJzCoeG6uOKBteKAnMKh4bmGbeKAnMivZuKAnMWAUeKAnMOe4bmWxIvCpeKAnOG5hV_igJzhuogx4oCcwqHDpuG4t-KAnMKhxpJteMSg4oCcwqHhuYfGrUXhu6Ry4oCcwqHDnsKmwrvhuastMjs74oCcTU9FIeKAnVfCpHPGk1pq4oKs4oG2auKBtw&input=Mw)
[Answer]
# JavaScript (ES6), 167 bytes
```
l=Array(n=+prompt()).fill``;`${s=`Eeny meeny miny `}moe Catch a tiger by the toe If he hollers let him go ${s}MOE!`.split` `.map((w,i)=>l[i%n]+=w+` `);alert(l.join`
`)
```
## Explanation
```
l=Array( // l = array of lines
n=+prompt() // n = input number
).fill``; // initialise l as empty strings
`${s=`Eeny meeny miny `}moe Catch a tiger by the toe If he hollers let him go ${s}MOE!`
.split` `.map((w,i)=> // for each word w
l[i%n]+=w+` ` // add it to the lines
);
alert(l.join`
`) // output the lines
```
[Answer]
## Haskell, ~~160~~ 157 bytes
```
import Data.Lists
unlines.map unwords.transpose.(`chunksOf`(["moe Catch a tiger by the toe If he hollers let him go","MOE!"]>>=words.("Eeny meeny miny "++)))
```
Prepend `"Eeny meeny miny "` to the other parts (`"moe Catch ..."` and `"MOE!"`), concatenate both strings, split into words, take chunks of required size, transpose and concatenate again into a single string.
@Mauris found 3 bytes by factoring out the common substring "Eeny meeny miny " and making `f` pointfree.
[Answer]
## Ruby, 160 bytes
```
puts (a=[*%w[Eeny meeny miny moe Catch a tiger by the toe If he hollers let him go Eeny meeny miny MOE!].each_slice(gets.to_i)])[0].zip(*a[1..-1]).map{|x|x*' '}
```
All my attempts at "compressing" the string have just made it longer. ~~Still trying...~~
```
puts # output to STDOUT...
(a= # assign this stuff to the variable a
[* # convert to array...
%w[blah blah] # %w splits on spaces
.each_slice(gets.to_i) # split into slices of input number
]
)[0] # take the first element of a
.zip(*a[1..-1]) # zip it with the remaining elements
# because transpose complains about ragged 2D arrays
.map{|x|x*' '} # join all sub-arrays on space
# puts automatically inserts newlines for us
```
[Answer]
# Python 2, ~~154~~ 147 bytes
**EDIT:** Thanks Joe Willis!
```
i=input()
s='Eeny meeny miny '
for j in range(i):print' '.join((s+'moe Catch a tiger by the toe If he hollers let him go '+s+'MOE!').split()[j::i])
```
This uses the trick that [0::n] prints the nth element of the list.
[Try it here](http://ideone.com/Vsgb9g)
[Answer]
# JavaScript (ES6), 189 bytes:
```
a=prompt(),b=Array(a--).fill``,c=0;"Eeny meeny miny moe Catch a tiger by the toe If he hollers let him go Eeny meeny miny MOE!".split` `.map(v=>(b[c]+=v+' ',c+=c>a-1?-c:1));alert(b.join`\n`)
```
# Explanation:
```
a=prompt(), //Get the STDIN
b=Array(a--).fill``, //Make an array based on how many kids there are
c=0; //Start the iteration variable
"Eeny meeny miny moe Catch a tiger by the toe If he hollers let him go Eeny meeny miny MOE!"
.split` `.map(
v=>(
b[c] += v + ' ',
c += c > a - 1 ? -c : 1
)
);alert(b.join`\n`)
```
[Answer]
## Python 3, ~~279~~ ~~278~~ ~~272~~ 173 bytes
(thanks to Mathias Ettinger who literally saved me **100+ BYTES!**)
```
s=" Eeny meeny miny moe Catch a tiger by the toe If he hollers let him go Eeny meeny miny moe!";w=s.split();i=input();i=int(i)
for z in range(i):W=w[z::i];print(" ".join(W))
```
If anyone has tips or sugestions I'd really appreciate them. Thanks!
[Answer]
# Mathematica, 154 bytes
```
StringRiffle[Thread@Partition[StringSplit@"Eeny meeny miny moe Catch a tiger by the toe If he hollers let him go Eeny meeny miny MOE!",#,#,1,""],"
"," "]&
```
Uses the split-chunk-transpose-join-output method of most of the other answers.
[Answer]
# MATLAB, 167 bytes/characters:
```
n=input('');s='Eeny meeny miny ';s=strsplit([s 'moe Catch a tiger by the toe If he hollers let him go ' s 'MOE!']);f=@fprintf;for i=1:n f('%s ',s{i:n:end});f('\n');end
```
# Explanation:
```
n=input(''); % Grab the input (number of children)
s='Eeny meeny miny '; % Common string portion
% Build the full string and split into cell array at spaces
s=strsplit([s 'moe Catch a tiger by the toe If he hollers let him go ' s 'MOE!']);
f=@fprintf; % Just a shorthand for later (only saves 1 char here)
for i=1:n % Loop to the number of children
f('%s ',s{i:n:end}); % Print each nth word, shifted by child
f('\n'); % Start each child's words on a new line
end
```
Won't be winning any awards for the length of this one, but it was fun. :-)
[Answer]
# Japt, ~~90~~ ~~87~~ 86 bytes
```
Uo mW{V=`EydÚ9yd·nyd` +`¶C®»dgdbydÈIfddÒ@sd¤tdmdgod{V}MOE!` qd f@Y%U¥W} m¸·
```
Lots of unprintables. [Try it online!](http://ethproductions.github.io/japt?v=master&code=VW8gbVd7Vj1gRYF5ZNo5eWS3bnlkYCArYLaCQ4Wuu2STZ4BkYnlkyAKRgklmZJRkl9JAc2SkdGSWbWRnb2R7Vn1NT0UhYCBxZCBmQFklVaVXfSBtuLc=&input=Mw==)
### How it works
```
// Implicit: U = input
Uo mW{ } // Create the range 0...U and map each item W to:
V=`...` // Set V to this string, decompressed. "Eenydmeenydmined"
+`...{V}MOE!` // Concatenate it with this string, decompressed, with V inserted.
qd // Split at "d"s.
f@Y%U¥W // Filter to only the items where (index % U == W).
m¸ // Map each item by joining with spaces.
· // Join the result with newlines.
```
I've tried compressing the string with different delimiters. The only thing more efficient than spaces would be a lowercase letter, but most of these are already used, and thus, can't be used to split the string. Here's how much compression is achieved with the remaining ones:
```
space -> 69 bytes
c -> 66 (including a null byte)
d -> 65
j -> 69
k -> 69
p -> 68
q -> 69
s -> 61 (but there's an s in "hollers")
u -> 65
w -> 67
x -> 69
y -> 69
```
Currently I'm using `d`. It may be possible to save a byte with `s`, substituting some other letter in `hollers`.
] |
[Question]
[
Given a large number (in base 10), such as 1234567891011121314151617, find prime "subnumbers" in it.
A prime "subnumber" is a consecutive sequence of digits (taken from the input), which represents a prime number (in base 10).
* **Input**:
A number (either a string, a file, or whatever you like).
* **Output**:
All prime subnumbers separated somehow (either in a list, a file, comma-separated strings...)
If the result is empty, you can take any convention you like (hardcoded string, empty string, gibberish, but program should not crash.
* **Example**
1234 -> 2, 3, 23
6542 -> 5, 2
14 -> [.. empty output]
This is code-golf. The shortest program wins!
[edit] : additional rule, program must be explained! Not everybody is fluent in Jelly :)
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 3 bytes
```
Œʒp
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6KRTkwr@/zc2MTUzBwA "05AB1E (legacy) – Try It Online")
Substrings of the input that are prime.
[Answer]
# [Perl 6](http://www.perl6.org/), 28 bytes
```
{grep &is-prime,+«m:ex/.+/}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Or0otUBBLbNYt6AoMzdVR/vQ6lyr1Ap9PW392v/FiZUKSirxCrZ2CtVpCirxtUoKaflFCjaGRsYmCmamJkYKhiZ2/wE "Perl 6 – Try It Online")
The `:ex` ("exhaustive") flag to the match operator `m` makes it return every possible match of `.+` (ie, every substring of one or more characters), even overlapping ones. The hyperoperator `+«` turns that list of `Match` objects into numbers, which are then filtered for primeness by `grep &is-prime`.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes
-1 byte thanks to [Kroppeb](https://codegolf.stackexchange.com/users/81957/kroppeb).
```
sᶠṗˢ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/jhtgUPd04/vej/f0MjY5P/UQA "Brachylog – Try It Online")
`ᶠ`ind all `s`ubstrings, `ˢ`elect the `ṗ`rimes
[Answer]
# [Python 2](https://docs.python.org/2/), ~~66~~ 65 bytes
```
P=k=1
n=input()
while~n+k:
if`k`in`n`>0<P%k:print k
P*=k*k;k+=1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8A229aQK882M6@gtERDk6s8IzMntS5PO9uKSyEzLSE7ITMvIS/BzsAmQDXbqqAoM69EIZtLIUDLNlsr2zpb29bw/39DQwA "Python 2 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~13~~ 10 bytes
*Thanks @Shaggy -3 bytes*
```
ò fj f@søX
```
---
```
ò fj f@søX Full program
implicity input
ò inclusive range [this - 1]
fj filter primes and
f@søX values contained in input
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=8iBmaiBmQHP4WA==&input=MTIzNCAtUQ==)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 [bytes](https://github.com/DennisMitchell/jelly)
-1 thanks to Kevin Cruijssen (`Ẓ` is an alias for `ÆP`)
```
ẆḌẒƇ
```
A monadic Link accepting a list of digits\* which yields a list of prime integers.
\* going by "either a string, a file, or whatever you like" - to take an integer, prefix the code with a `D`
**[Try it online!](https://tio.run/##y0rNyan8///hrraHO3oe7pp0rP3////RhjpGOsY6JjqmOmY65joWOpY6hjoGQAyCRkBsDMQmQGwKxGZAbB4LAA "Jelly – Try It Online")**
### How?
```
ẆḌẒƇ - Link: list of integers (digits) e.g. [1,2,3,4]
Ẇ - non-empty contiguous substrings [[1],[2],[3],[4],[1,2],[2,3],[3,4],[1,2,3],[2,3,4],[1,2,3,4]]
Ḍ - convert to decimal (vectorises) [1,2,3,4,12,23,34,123,234,1234]
Ƈ - filter keep if:
Ẓ - is prime? [2,3,23]
```
[Answer]
# Java 8, ~~148~~ 147 bytes
```
n->{for(int l=n.length(),i=l,j;i-->0;)for(j=l;j>i;){long k=2,x=new Long(n.substring(i,j--));for(;k<x;x=x%k++<1?0:x);if(x>1)System.out.println(x);}}
```
[Try it online.](https://tio.run/##hVDLboMwELznK1ZIlWwFo5g8KsUxPVdq00OOVQ8OIanBMQiblCri26kh5NBHVB8s7ezM7sym4iRIusvaWAlj4FlIfR4BSG2Tci/iBNZdCXDK5Q5itLGl1AcwmDm0GbnPWGFlDGvQwKHVJDrv8xI5PSiuA5Xog31H2Jdc@SmThEQThjtGyhVLI8nwWeVuYsZDv@Y6@YAnVyIdmGpr@mVI@ikhGLNOxbJVzWpe32Xj8Yo@TJY1ZnKP6ojizaexyTHIKxsUTmeVRq7ZNC3rbBbVVjmbg9s@zdFlHQK9voHAl6A2MRZ5NJzOvD7kFVnMZ@F3hP5g0JBO6YzO6YLee78O1K/sicMNpS4qOyz9w7v32PWX4I0vRHaT@FLZjnk1o4MY/Scht97Vd9N@AQ)
**Explanation:**
```
n->{ // Method with String parameter and no return-type
for(int l=n.length(), // Length of the input-String
i=l,j; // Temp-integers
i-->0;) // Loop `i` in the range [length, 0)
for(j=l;j>i;){ // Inner loop `j` in the range [length, 0)
for(long k=2, // Set `k` to 2
x=new Long(n.substring(i,j--)
// Take the substring [`i`, `j`) from the input,
); // convert it to a long, and set it as `x`
k<x; // Inner loop as long as `k` is still smaller than `x`
x=x%k++<1? // If `x` is divisible by `k`:
0 // Set `x` to 0
: // Else:
x); // Leave `x` unchanged
if(x>1) // If `x` is now larger than 1 (a.k.a. If `x` is a prime):
System.out.println(x);}}
// Print `x` with a trailing newline to STDOUT
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
&XfXUtZp)
```
[Try it online!](https://tio.run/##y00syfn/Xy0iLSK0JKpA8/9/dUMjYxN1AA "MATL – Try It Online")
### Explanation
```
&Xf % Implicit input: string. Push cell array of non-empty substrings
XU % Convert to number. Vectorizes
t % Duplicate
Zp % Isprime. Vectorizes.
) % Index. Keeps substrings indicated by the previous result. Implicit display
```
[Answer]
# Bash + GNU Core Utils: ~~80~~ 77 Bytes
```
for i in $(seq `tee a|wc -c`)
{
grep -oE .{$i}<a|factor|grep -oP ': \K\d+$'
}
```
This cannot be the shortest, but I am having trouble coming up with anything better. Help wanted!
By sticking to only POSIX, I got 82:
```
for i in $(seq `tee a|wc -c`)
{
grep -oE .{$i}<a|factor|awk -F\ 'NF<3{print$2}'
}
```
[Answer]
# [R](https://www.r-project.org/), 60 bytes
```
function(v)Filter(function(i)grepl(i,v)&sum(!i%%1:i)==2,1:v)
```
[Try it online!](https://tio.run/##PcgxCoAwDEDRvbdwUBJwSVsVhK5eRBoJaJWqvX5EB6fP@1k5KN9pvmRPUHCS9YoZ/iO45HisIG3B5rw3qKSuaRQMwbY0FlQGss6jYeg7b9/SJ@/o0@C7waGqeQA "R – Try It Online")
Not really efficient, inspired by @ovs python 2 answer
[Answer]
# [Curry (KiCS2)](https://www-ps.informatik.uni-kiel.de/kics2/), ~~61~~ 58 bytes
-3 bytes thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)!
Takes input as a string, returns integers. `f` is function which can return any of the results.
```
p n|n>1&&all((>0).mod n)[2..n-1]=n
f(_++a:b++_)=p$read$a:b
```
You can try this on [Smap](https://smap.informatik.uni-kiel.de/smap.cgi?new/curry) (select `KiCS2 2.2.0 /all-values`) by adding:
```
main = f "1234"
```
`p` is a primality test function which returns it's input if it is a prime, and doesn't return anything otherwise.
`f(_++a:b++_)` matches non-empty substrings of the input in `a:b` and `f` returns the value of `p` applied to `a:b` converted to integer.
Local output:
```
> f "1234"
[...]
Evaluating expression: f "1234"
2
23
3
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `Ṡ`, 4 bytes
```
ǎE~æ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuaAiLCIiLCLHjkV+w6YiLCIiLCIxMjM0Il0=)
```
ǎE~æ # 'Ṡ' flag makes Vyxal take all input as strings
ǎ # All substrings
E # Convert to numbers
~æ # Remove non-primes
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~115~~ 114 bytes
```
f=lambda s:s and[n for n in[int(s[j:])for j in range(len(s))]if n>1and all(n%i for i in range(2,n))]+f(s[:-1])or[]
```
[Try it online!](https://tio.run/##RYwxDgIhFAV7T/EbAz9qAa4WJHoRQoHZRdngYwPbeHpECy3fZOYtr/WRoVsLl@Sft9FTNZU8RgsKuRAowkasstrZOP6guSMqHvdJpgmyMrsYCFfVK/IpSWzjt41/Ue/RtV3oN@agHOdiXVtKP6YghdLHQfDmt8@nQQtubw "Python 2 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
```
Select[PrimeQ@*FromDigits]@*Subsequences
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/A/ODUnNbkkOqAoMzc10EHLrSg/1yUzPbOkONZBK7g0qTi1sDQ1Lzm1@D9QRV5JdFp0taGOgpGOgrGOgkltbCwXXNhMR8EUKAaURBE2hKj7DwA "Wolfram Language (Mathematica) – Try It Online")
Input and output are lists of digits. In the case of no prime subnumbers the empty list `{}` is returned.
Uses `@*` for [`Composition`](http://reference.wolfram.com/language/ref/Composition.html) of functions. [`Subsequences`](http://reference.wolfram.com/language/ref/Subsequences.html) gives a list of all subsequences of the input, and `Select[PrimeQ@*FromDigits]` is an operator form of [`Select`](http://reference.wolfram.com/language/ref/Select.html) which returns a list of all elements for which `PrimeQ@*FromDigits` returns `True`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
foṗiQ
```
[Try it online!](https://tio.run/##yygtzv7/Py3/4c7pmYH///9XMjQyNlECAA "Husk – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 108 bytes
```
import StdEnv,Data.List
$s=nub[n\\u<-inits s,n<-map(toInt o toString)(tails u)|n>1&&all(\m=n/m*m<n)[2..n-1]]
```
[Try it online!](https://tio.run/##Jc3NCoJAEADge0@xhyiNtMb@QTvVIegQeFQPk1os7MyGOwZBz94WdPxOX21aZE@26U2rCDV7TQ/bicqlOfJzekDB@KydDIYu4/5acFn2aaRZi1NuymlE@AjEnliUVWJz6TTfw0BQG6f68M17GI3QmKCkjGc0oZTDIoljjqCqfC74uzI1VMUYksVytd5sdzAHgAQWsIQVrGEzrvynvhm8Ox@dzv7wYiRd/3ExKDfb0Rc "Clean – Try It Online")
[Answer]
# Pyth, 8 bytes
```
fP_TsM.:
```
[Test suite](https://pyth.herokuapp.com/?code=fP_TsM.%3A&test_suite=1&test_suite_input=%221234%22%0A%226542%22%0A%2214%22&debug=0)
Takes the input as a string, outputs a list of integers. Can also take input as an `int` [by adding ``` at the end](https://pyth.herokuapp.com/?code=fP_TsM.%3A%60&test_suite=1&test_suite_input=1234%0A6542%0A14&debug=0) for an extra byte.
Explanation:
```
fP_TsM.: | Full code
fP_TsM.:Q | with implicit variables added
| Print (implicit)
.:Q | list of all substrings of the input
sM | converted to integers
fP_T | filtered for prime numbers
```
And ``` just converts `int` to `str`.
[Answer]
## Matlab, 89 bytes
```
function[m]=f(x),m=1;for i=1:length(x),m=[m;str2num(combnk(x,i))];end,m=m(isprime(m));end
```
[Try it Online!](https://tio.run/##JclBDoMgEADAr3hzN/GCsT1IeAnxUCnUjd3FIDT8Htv0OhNdfnx8a6GIyxTF8mICVBzYKB1i6sio@e3llbe/WtZnTqMUBhd5lR3qQIiL9vL8NgOdRyL2wIg/awH6@20ae2wX)
] |
[Question]
[
A [common year](https://simple.wikipedia.org/wiki/Common_year) is a year that is not a leap year and where the first and last day of the year are on the same day. A [special common year](https://en.wikipedia.org/wiki/Common_year_starting_on_Monday) is one that starts on a Monday and so ends on a Monday as well.
Your challenge is to create a program/function that when given a year as input finds the nearest special common year, outputting itself if it is a common year. If the year is as close to the one before it as the one next to it output the larger one.
**Input**
An integer representing the year to test against in the range `1600 <= x <= 2100`.
**Output**
An integer representing the nearest special common year.
**Test cases**
```
2017 -> 2018
2018 -> 2018
1992 -> 1990
1600 -> 1601
2100 -> 2103
1728 -> 1731 (lies between 1725 and 1731)
```
**Notes**
All 54 years in the given range are already shown in the linked Wikipedia article. I will also provide them here for reference:
```
1601, 1607, 1618, 1629, 1635, 1646, 1657, 1663, 1674, 1685, 1691
1703, 1714, 1725, 1731, 1742, 1753, 1759, 1770, 1781, 1787, 1798
1810, 1821, 1827, 1838, 1849, 1855, 1866, 1877, 1883, 1894, 1900
1906, 1917, 1923, 1934, 1945, 1951, 1962, 1973, 1979, 1990
2001, 2007, 2018, 2029, 2035, 2046, 2057, 2063, 2074, 2085, 2091
2103 (Needed for 2097 to 2100)
```
[Answer]
# PHP, 67 Bytes
```
for(;date(LN,mktime(0,0,0,1,1,$y=$argn+$i))>1;)$i=($i<1)-$i;echo$y;
```
[Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zNTI0MLD@n5ZfpGGdkliSquHjp5ObXZKZm6phoAOChkCoUmkLVqytkqmpaWdoramSaauhkmljqKmrkmmdmpyRr1Jp/f8/AA "PHP – TIO Nexus")
or
```
for(;date(LN,strtotime("1/1/".$y=$argn+$i))>1;)$i=($i<1)-$i;echo$y;
```
[Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zNTQ3srD@n5ZfpGGdkliSquHjp1NcUlSSX5KZm6qhZKhvqK@kp1JpC1asrZKpqWlnaK2pkmmroZJpY6ipq5JpnZqcka9Saf3/PwA "PHP – TIO Nexus")
Expanded
```
for(;
date(LN,mktime(0,0,0,1,1,$y=$argn+$i)) # N is 1 for Monday and L is 0 for Non leap year
>1;) # loop so long as expression is not 1
$i=($i<1)-$i; # set $i 0,1,-1,2,-2 ...
echo$y; # Output Year
```
[date](http://php.net/manual/en/function.date.php)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~129~~ ~~124~~ 118 bytes
```
a=[11,11,6]*13
a[29:29]=a[19:19]=12,
a[10:10]=6,6
n=input()
o=[2401-n]
for i in a*2:o+=o[-1]-i,
print n+min(o,key=abs)
```
[Try it online!](https://tio.run/nexus/python2#DchNCgMhDEDhvadwOT8RTFpsFXIScWGhhVAah5npoqe3wlt8vF45I8IolAUvpmaKiWLhmjEmHECCcdEn9IUDBKMsun3PaTaNM109Oi3m1XYrVtTWhVJbuWWHxQmYbRc9ra4f0anB@/nj@jjm3vFG9z8 "Python 2 – TIO Nexus") or [Try all test cases](https://tio.run/nexus/python2#FY7dCsMgDIXv@xS5618KxoJtBfci4oVjFWRMi@sufPouhXBITvhOcr32AKFLvW7AG6uQiMsNNPNspdBSOOMtCU3ckMTbnknP5IxC1UA2lpSgKbkGQi4QISbwg9R5NNlO5MbITNnPX0mQxk9MXbZa8wLfezX@@e2vm6s3xwdpQZYVadskcrJASSy0yNXxj0eJ6YSK7fRoMXS1v/4 "Python 2 – TIO Nexus")
First, the sequence is generated (reversed) on `a`, then `2401 - input_year` is used as starting value to be subtracted over the sequence.
This way the list `o` will contain the differences between all the common years and the input, the nearest year will be the number that is nearest to zero (positive or negative), then will be extracted with `(min, key=abs)` and added back to the input.
## With `datetime`, 119 bytes
```
lambda i:i+min([y-i for y in range(2200,1500,-1)if datetime(y,1,1).weekday()<1and y%400],key=abs)
from datetime import*
```
[Try it online!](https://tio.run/nexus/python2#FY7NCsMgEITveYq9NT8ruNuSRMG@iHiwNIKUarHpwadPDQzDzMAHczy3AKFPg@7AG0uETbMb6dq6ZaVZOeMtKU0tEOM5k9QknZlx7iAbyzdJIrkOQi4QISbwI@s8mWwFOREbU7b9VxKk6R1Tn/G1VeMf3@E4iXoSliUt2GxFUoqRZimRqRktvLr27lNi2qHiRdwvGPo6HH8 "Python 2 – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 41 bytes
```
6xD<Š)•HΘ%A°,SΔA)u•3вè.pO0¸ì1601+DI-ÄWQϤ
```
[Try it online!](https://tio.run/nexus/05ab1e#AT8AwP//NnhEPMWgKeKAokjOmCVBwrAsU86UQSl14oCiM9Cyw6gucE8wwrjDrDE2MDErREktw4RXUcOPwqT//zE3Mjg "05AB1E – TIO Nexus")
**Explanation**
```
6xD<Š) # push the list [11,6,12]
•HΘ%A°,SΔA)u• # push the number 20129386383114231907032071
3в # convert to a base-3 digit list
è # use this to index into the first list
.p # get list of prefixes
O # sum each sublist
0¸ì # prepend 0
1601+ # add 1601 to each
D # duplicate
I- # subtract input from each
Ä # calculate absolute value
WQÏ # keep only the years that have the
# smallest absolute difference from input
¤ # get the last one
```
[Answer]
## JavaScript (ES6), 77 bytes
```
f=(y,z=y,d=m=>new Date(y,m,!m||31).getDay()-1)=>d(0)|d(11)?f(z<y?z-1:z+1,y):y
```
```
<input type=number value=2001 oninput=o.textContent=f(+this.value)><pre id=o>2001
```
[Answer]
## Mathematica, 70 bytes
```
Max@Nearest[Select[Range[7!],!LeapYearQ@{#}&&DayName@{#}==Monday&],#]&
```
Generates a list of all special common years up to year 5040 (= 7!) and then finds the nearest one to the input, taking the maximum in case of a tie.
[Answer]
# Java 7, 217 bytes
```
import java.util.*;int c(int y){return d(y,1);}int d(int y,int x){Calendar c=Calendar.getInstance(),d=Calendar.getInstance();c.set(y,0,1);d.set(y,11,31);return c.get(7)==d.get(7)&c.get(7)==2?y:d(y+x,x>0?-++x:-(--x));}
```
**Explanation:**
[Try it here.](https://tio.run/nexus/java-openjdk#hU5NT4QwEL3zK@ZkWoGGYiK7S3APnjxw2qPxUNtmUwOF0GGFEH47FsV4MsxhPt68mfdM3TYdwoe4Cdajqdh9HshKOAfltBiLIMmaRzp1GvvOgiJjxGk@r6j62UVrHuj0LCptlehAFr8tu2p8sQ6FlZrQSP2zyCVzGv3nZP2ttoHz6MGPm7BcT0hGi0Jt3d0flJ7Hk3cWDtHwlJzjMBxOMYnjgXqnC0Dbv1dGgpdDX26NUVALY8kFO2Ovr28g6BSAjxJqKMDqTyi9q2/oMjrUNWt6ZK1nY2VJzSRJE57RXcphh8KPx3SP8pgke0J8l8KzdPMyB/PyBQ)
```
import java.util.*; // Required import for Calendar
int c(int y){ // Method with integer parameter and integer return-type
return d(y,1); // Call second method with additional parameter
} // End of method (1)
int d(int y,int x){ // Method (2) with two integer parameters and integer return-type
Calendar c=Calendar.getInstance(), // Create two Calendar instances
d=Calendar.getInstance();
c.set(y,0,1); // Set one to 01 January yyyy
d.set(y,11,31); // and one to 31 December yyyy
return c.get(7)==d.get(7) // If both are the same day of the week
&c.get(7)==2? // and it is a Monday:
y // Return the input-year
: // Else:
d(y+x, // Recursive-call with year + `x`
x>0?-++x:-(--x)); // and change `x` to the next to check
// +1,-2,+3,-4,+5,-6,etc.
} // End of method (2)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~32~~ 31 bytes
```
`G@2&\wEq*-XJtQv24KUhBh9XO77-}J
```
[Try it online!](https://tio.run/nexus/matl#@5/g7mCkFlPuWqilG@FVElhmZOIdmuGUYRnhb26uW@v1/7@huZEFAA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S4jw/J/g6WCkFlPuWqilG@FVElhmZOIdmuGUYRnhb26uW@v1P9Yl5L@RgaE5F5Cw4DK0tDTiMjQzMOAyMgQShuZGFgoA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“Þıİs|9ṗ[¿¶F’ṃ“©€¿‘⁽£d;+\ạÐṂ⁸Ṁ
```
A monadic link taking and returning an integer year.
**[Try it online!](https://tio.run/nexus/jelly#AUcAuP//4oCcw57EscSwc3w54bmXW8K/wrZG4oCZ4bmD4oCcwqnigqzCv@KAmOKBvcKjZDsrXOG6ocOQ4bmC4oG44bmA////MjAxNw)** or see a [test suite](https://tio.run/nexus/jelly#@/@oYc7heUc2HtlQXGP5cOf06EP7D21ze9Qw8@HOZqDUoZWPmtYc2v@oYcajxr2HFqdYa8c83LXw8ISHO5seNe54uLPh/9E9h9uBarKAGKheQddO4VHD3Mj//6ONDAzNdRSApIWOgqGlpRGQNDMwAIoYgkhDcyOLWAA "Jelly – TIO Nexus").
### How?
Much like other answers this builds the list of years required for the input domain from the increments, and finds the maximal year of minimal absolute difference from the input.
```
“Þıİs|9ṗ[¿¶F’ṃ“©€¿‘⁽£d;+\ạÐṂ⁸Ṁ - Main link: number y
⁽£d - augmented base 250 literal = 1601
“Þıİs|9ṗ[¿¶F’ - base 250 literal = 20129386383114231907032071
“©€¿‘ - code page index list = [6,12,11]
ṃ - base decompression = [6,11,11,6,11,11,6,11,11,6,12,11,11,6,11,11,6,11,11,6,11,12,11,6,11,11,6,11,11,6,11,6,6,11,6,11,11,6,11,11,6,11,11,6,11,11,6,11,11,6,11,11,6,12]
; - concatenate = [1601,6,11,11,6,11,11,6,11,11,6,12,11,11,6,11,11,6,11,11,6,11,12,11,6,11,11,6,11,11,6,11,6,6,11,6,11,11,6,11,11,6,11,11,6,11,11,6,11,11,6,11,11,6,12]
+\ - reduce with addition = [1601,1607,1618,1629,1635,1646,1657,1663,1674,1685,1691,1703,1714,1725,1731,1742,1753,1759,1770,1781,1787,1798,1810,1821,1827,1838,1849,1855,1866,1877,1883,1894,1900,1906,1917,1923,1934,1945,1951,1962,1973,1979,1990,2001,2007,2018,2029,2035,2046,2057,2063,2074,2085,2091,2103]
⁸ - link's left argument, y
ÐṂ - filter keep if maximal:
ạ - absolute difference
Ṁ - maximum (alternatively tail, Ṫ, since increasing)
```
[Answer]
# C#, 183 bytes
To get the ball rolling a bit, here's an implementation I've done of my own. I'm pretty sure it can still be golfed down so if anyone wants to feel free to post as a new answer.
```
namespace System.Linq{n=>Enumerable.Range(1,9999).Where(y=>!DateTime.IsLeapYear(y)&(int)new DateTime(y,1,1).DayOfWeek==1).GroupBy(y=>Math.Abs(n-y)).OrderBy(g=>g.Key).First().Last();}
```
[Try it online!](https://tio.run/nexus/cs-mono#hVLRTsIwFH3nK67EmC5Aw3wwMTASFTFGCAZNiDE@XMbdaGQdtkXTLPt27CC6gJidh@b29pzTc9NuwEFiQnqFIcGT1YYSPhTyo1acZNu1QLhEreFRpbHC5LdbnhfQBo0I4TMVcxihkEwbJWT8@gaoYu3tcfeVBQZrGXaFNE1wSw8iCEBC0PvDK3Ar1wkpnC2JT1DGxPwmXDp4R9kl@HRBiph1vnDSR0PPIiF@r4eEqxdCxWyVQ4kzYC6oJ@kLfpyYbYJL4nu8j3YcTYneIQjcvirWnUrXq2u7CzZCs@BXM80ktMB6leKxmpNy4rgQx/yBKofgA6G0YZW0IRasTu0PL0rVdnpwgcG/aLc7ruoGcO4XZaNxJEF29LKbVOrUveJUCUPu2xE7rWc2h1YPssi9Rl531x@K8r1O7T/PCeF8a3lgUcp3Vb7ZfAM "C# (Mono) – TIO Nexus")
Full/Formatted version, this also shows all outputs for the given range when ran.
```
namespace System.Linq
{
class Program
{
static void Main(string[] args)
{
Func<int, int> f = n =>
Enumerable.Range(1, 9999)
.Where(y => !DateTime.IsLeapYear(y)
& (int)new DateTime(y, 1, 1).DayOfWeek == 1)
.GroupBy(y => Math.Abs(n - y))
.OrderBy(g => g.Key)
.First()
.Last();
for (int y = 1600; y <= 2100; ++y)
{
Console.WriteLine($"{y} -> {f(y)}");
}
Console.ReadLine();
}
}
}
```
[Answer]
# Ruby, 145 bytes
```
f=->i{i+(1.upto(i).map{|m|Time.new(y=i+m).monday?&&Time.new(y,6).friday?? m:Time.new(y=i-m).monday?&&Time.new(y,6).friday?? -m :nil}.find{|a|a})}
```
Defines a lambda taking the start year as input - `f[2017] => 2018`
Gotta love the Ruby standard library! `wday==1` is the same length as `monday?` and infinitely less cool :). The special common year check is done by the fact that in a common year starting Monday, 1st June is a Friday ("friday" being the equal-shortest day name!)
Unfortunately, it's not so good at searching in both directions.
] |
[Question]
[
# Objective
Given an unlabelled binary tree, decide whether it is contiguous in indices.
# Indices
This challenge gives one-indexing on binary trees. The exact definition expresses all indices in binary numeral:
* The root is indexed `1`.
* For every node, to get the index of its left child, replace the most significant `1` by `10`.
* For every node, to get the index of its right child, replace the most significant `1` by `11`.
For illustration:
[](https://i.stack.imgur.com/2MEp6.jpg)
A binary tree is **contiguous in indices** iff the indices of its nodes have no gaps.
Note that every binary tree with contiguous indices is balanced.
# I/O Format
Flexible.
# Examples
`L` indicates a leaf. `[ , ]` indicates a branch.
## Truthy
```
L
[L,L]
[[L,L],L]
[[L,L],[L,L]]
[[[L,L],L],[L,L]]
[[[L,L],L],[[L,L],L]]
```
## Falsy
```
[L,[L,L]]
[[[L,L],L],L]
[[[L,L],[L,L]],[L,L]]
[[[L,L],L],[L,[L,L]]]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ ~~10~~ ~~9~~ ~~8~~ 7 bytes
```
ŒṪ’UḄṬP
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7Vz1qmBn6cEfLw51rAv4fbteM/P9fIycxNyklUcHHKpqLy0eHK9pHxycWSEFoJCaYBHPhUtiEYKxYsFFYVPggcaHS2I2GiMZyccVqahhqAgA "Jelly – Try It Online")
*-1 thanks to Jonathan Allan--funny that I used `ŒṪ` earlier, but never tried removing `Ż` with it*
~~Very~~ *Embarrassingly* naive solution, using `ŒṪ` "generate multidimensional truthy indices" to directly produce the indices, then `Ṭ` "untruth" to lay them out... if I was sure it works at all, since this doesn't actually produce the stated labeling scheme or represent non-leaf nodes at all. I actually thought it didn't work for a bit, but then I realized my counterexample wasn't a binary tree to begin with.
Requires that the leaf value is truthy.
```
ŒJ Generate multidimensional 1-indices of truthy values.
’ Decrement to 0-indices,
U and reverse, so the deepest index is most significant
Ḅ when they're converted from binary.
Ṭ Generate the shortest array of 1s and 0s that has 1s at exactly those indices,
P and check that it doesn't contain any 0s.
```
Since there's no leading 1, this identifies every non-leaf node with its leftmost descendant, but this seems not to matter.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 55 bytes
-6 bytes thanks to [@att](https://codegolf.stackexchange.com/users/81203/att).
```
Length[l=If[0>##,0,#+2#0@##2]&@@@#~Position~_List]l&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@98nNS@9JCM6x9YzLdrATllZx0BHWdtI2cBBWdkoVs3BwUG5LiC/OLMkMz@vLt4ns7gk9v2ELTlq/wOKMvNKopUVdO0UAkszU0ui06KVY2NjFdQU9B24FKp9dLgUQKSCTy2YBWWicyE0VAxJDR4JBKcWZgdOxT5oYjCF@O2FStbW/gcA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~37~~ 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Δ€`}\NÝ"€"×€"Dÿƶ˜s"J.V\)ø<í2δβ>{āQ
```
Port of [*@UnrelatedString*'s Jelly answer](https://codegolf.stackexchange.com/a/260694/52210), but unfortunately 05AB1E lacks a multi-dimensional indices builtin, so we'll have to do that manually at the cost of 26 bytes.. :/
Uses `1` as leaves.
[Try it online](https://tio.run/##yy9OTMpM/f//3JRHTWsSamP8Ds9VArKUDk8HkS6H9x/bdnpOsZKXXliM5uEdNofXGp3bcm6TXfWRxsD//6Ojow11DGNBCM6KBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWWiy/9zUx41rUmojfE7PFcJyFI6PB1Euhzef2zb6TnFSl56YTGah3fYHF5rdG7LuU121UcaA//r/I9W8lHSUQCTQBwLZCLYGAJwFlgYTSF@SVR@LNRKvHpg1mO1n7BTECpiYwE).
**Explanation:**
```
Δ€`}\N # Determine the depth-1 of the (implicit) multi-dimensional input-list:
Δ # Loop until the result no longer changes:
€` # Flatten it one level down
}\ # After the loop: discard the resulting flattened list
N # And push the last (0-based) index of the loop instead
Ý # Pop and push a list in the range [0,depth-1]
"€"× # Map each to that many "€" as string
€ # Then map each string to:
"Dÿƶ˜s" # String "Dÿƶ˜s", where `ÿ` is replaced with the "€"-string
J # Join this list of strings together
.V # Evaluate and execute it as 05AB1E code:
D # Duplicate the multi-dimensional list of 1s
€ # Zero or more `€`: map to a certain depth:
ƶ # Multiply each value by its 1-based index
˜ # Flatten the multi-dimensional list
s # Swap, so the multi-dimensional list of 1s is at the top again
\ # Discard the last multi-dimensional list of 1s
) # Wrap all flattened lists on the stack into a list
ø # Zip/transpose; swapping rows/columns
< # Decrease everything from 1-based to 0-based indices
í # Reverse each inner list of multi-dimensional indices
δ # Map over each list:
2 β # Convert it from a base-2 list to an integer
> # Increase each 0-based value by 1 to a 1-based value
{ # Sort it
ā # Push a list in the range [1,length] (without popping the list)
Q # Check if the two lists are the same, in which case there are no gaps
# (which is output implicitly as result)
```
Determining the depth of a ragged-list (`Δ€`}\N`) I've done before in [this challenge](https://codegolf.stackexchange.com/a/240671/52210).
Determining the multi-dimensional indices of a ragged-list (`Δ€`}\NÝ"€"×€"Dÿƶ˜s"J.V\)ø<`) I've done before in [this challenge](https://codegolf.stackexchange.com/a/249515/52210).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
F№⭆¹θ1⊞υ∨¬ιE²§υ⊘⁻ικ⁼θ⊟υ
```
[Try it online!](https://tio.run/##HYw9C8IwFEV3f8Wj0ws8h7g6iQg6VAOOkiG01QZD0nwV/31MerjDhXO5w6zC4JQp5e0C4Nllm/CZgrafXi3ICTwj6HjHGIgcZ8wEj4B3l1BX0TYHglO62XH6NXlVZp1G7LXNETXBl20cd6J@Jrz4rExETyDcgrmZUl4VTly2bEXKsl/NHw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list using `1` for leaves (note that Charcoal takes a list of inputs, so there's an extra set of `[]`s) and outputs a Charcoal boolean, i.e. `-` for contiguous, nothing if not. Explanation: Port of my Retina 0.8.2 answer.
```
F№⭆¹θ1
```
Count the number of leaves.
```
⊞υ∨¬ιE²§υ⊘⁻ικ
```
Generate the balanced tree with that number of leaves.
```
⁼θ⊟υ
```
Compare it to the input.
[Answer]
# JavaScript (ES6), 69 bytes
Expects a nested list of `1`'s. Returns a Boolean value.
```
a=>!((m=F=(a,v,q)=>+a||a.map(b=>F(b,v+=q,q*2),m|=1<<v))(a,1,1),m&m+2)
```
[Try it online!](https://tio.run/##jY/LDoIwEEX3/oUbaaWSlDXDki9ghywGBB@hlJdNTPj3WiEkPlDZTCbnnjtpL6iwTZtz1e1Kech0DhrBXxMiIACCTLGagm9j36MjsCIJ@AFJmLKhZvXWpUz0wD1PUWpkzrgBG2G7VKeybGWROYU8EisKm2t3usUWXT3znHD6TiJzJP6kA/6RDHMunYpLjGl7WC@atS@jAIt25gem8/8y/56O5WXvHyVj6Ts "JavaScript (Node.js) – Try It Online")
### Commented
```
a => !( // a[] = input array
( m = // m = bit mask to store node indices
F = ( // F is a recursive function taking:
a, // a[] = current node
v, // v = node index
q // q = highest power of 2 such that q ≤ v
) => //
+a || // stop if this is a leaf
a.map(b => // otherwise, for each child node b[]:
F( // do a recursive call:
b, // pass the child node
v += q, // add q to v
q * 2 // double q
), // end of recursive call
m |= // update the bit mask m ...
1 << v // ... so that the current node index is marked
) // end of map()
)(a, 1, 1), // initial call to F with a[] = input and v = q = 1
m & m + 2 // test whether m has any bit in common with m + 2
) // (if not, the only 0 in m is the trailing 0)
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 48 bytes
```
$
¶$`
T`[,]`_`^.+
+`(L+)(\1L?)
[$2,$1]
^(.+)¶\1$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX4Xr0DaVBK6QhGid2IT4hDg9bS7tBA0fbU2NGEMfe02uaBUjHRXDWK44DT1tzUPbYgxV/v/34Yr20fGJ5YoGU0gsMAniwSSwicBYsSBTMOV9EDyIJHZTIYKxAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Pretty sure this works, but I don't know how to prove it.
```
$
¶$`
```
Duplicate the input.
```
T`[,]`_`^.+
```
Flatten one copy.
```
+`(L+)(\1L?)
[$2,$1]
```
Turn into a balanced tree.
```
^(.+)¶\1$
```
Check whether this equals the original tree.
[Answer]
# [Haskell](https://www.haskell.org/), 53 bytes
```
data T=T T T|L
h L=[0]
h(T l r)=[1+d|d<-h l,h r==[d]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PyWxJFEhxDZEAQhrfLgyFHxsow1iuTI0QhRyFIo0baMNtVNqUmx0MxRydDIUimxto1NiY//nJmbm2RYUZeaVqGSohADV@ij4aIIpKFvzPwA "Haskell – Try It Online")
[Answer]
# Python3, 232 bytes:
```
def b(x,c,r,d):
if isinstance(x,list):d[c]=d.get(c,[])+[r];b(x[0],c+1,'10'+r[1:],d);b(x[1],c+1,'11'+r[1:],d)
def f(t):d={};b(t,0,'1',d);K=sorted([int(i,2)for j in d for i in d[j]]);return all(K[j]+1==K[j+1]for j in range(len(K)-1))
```
[Try it online!](https://tio.run/##nVDBTsQgED3LV5BeAMs2xb2YbvoFbfwB5FBbWNkQ2gAajfHbK7Tprok9eWHezJt5vJnpM7yO9vg4uXkepIIv@IP21NGBVABqBbXX1ofO9jISRvtAqoH3oh6Kswy4p1yQnDtxinO8FLTPGUWsRLnjrBJRZSHYRrAbAdJvCie9@us7tgVaxg6UZprajy7IAXNtA9b0gajRwQvUFg4wQb1AfhGCnJwMb87CzhjcxErO6jrGnInrjOvsWWIjLW7IgREye1jDLMtAC3hLWwH4En6h5U3ZRuxVNiRA0rraUtoE6fDTaCX1hZ@MDhg9W0TiRe8mlzZSWL53BuvCycl08bSoRRSirM1iFyEArG3ogO6PJdmXTgtEB399tbdsJfe3WYsiqvzL4/wD)
[Answer]
# [julia](https://julialang.org/), 47 bytes
Expects a nested list of `0`s.
Truthy output: `true` or a positive integer of the total number of leaves
Falsy output: a negative integer
```
c(t)=t==0||(0<=-(c.(t)...)<2)*(+(c.(t)...,1))-1
```
The criterion is that a tree is truthy if, for each neighbouring pair of subtrees \$T\_1, T\_2\$ with the same parent node, the number of leaves in \$T\_1\$ must be equal to or exactly one more then the number of leaves in \$T\_2\$
The function `c` returns `true` on a leaf. Otherwise, we compute recursively `-(c.(t)...)` (which is equivalent to `c(t[1]) - c(t[2])`).
This will be either 0 or 1 if `t` is truthy or sometimes if both `t[1]` and `t[2]` are falsy.
In any case, if the condition holds, we return `+(c.(t)...,1)-1` (equivalent to `c(t[1]) + c(t[2])`), which is the total number of leaves if `t` is truthy and negative otherwise. If the condition fails, we return `-1`.
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6Fjf1kzVKNG1LbG0Namo0DGxsdTWS9YAienp6mjZGmloa2nC-jqGmpq4hRNstxhU-CrYKBlxcyRo-mgo1dgoFRZl5JTl5CliBskJJUWkqUG20j45PLH71ygpGIIVglXgVKysYIxSCSRyKlRVMwAphRuJUrKxgiqYQxkJTrKxgxgXxDT57IUbqGqKaictLaCohBmM1H9NMuEOwqIREGCy-AQ)
] |
[Question]
[
Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
It's time to prepare an advent calendar, but I've only got a large sheet of rectangular paper, randomly colored red and green like this:
```
GRRRGRRGRG
GGRGGGRRGR
GRRGRGRGRG
GGRRGRGRGG
GRGGRGRGGG
RRGRGRGRRG
RRRGRGRGGG
RGGRGGRRRG
RGGGRRRRRG
GRGRRRGRRG
```
Out of this paper, I want to cut out a 5-by-5 region which is colored in a checkerboard fashion:
```
GRRRGRRGRG
GGRGGGRRGR
GRR**GRGRG**RG
GGR**RGRGR**GG
GRG**GRGRG**GG
RRG**RGRGR**RG
RRR**GRGRG**GG
RGGRGGRRRG
RGGGRRRRRG
GRGRRRGRRG
```
The exact coloring doesn't matter (the top left cell can be either green or red).
But if I'm unlucky, the piece of paper might not have such a region at all. In that case I will have to repaint some cells; I want to cut out a region which minimizes the amount of paint to make it checkered.
**Task:** Given a sheet of paper, output the minimum number of cells I need to recolor to get a checkered 5-by-5 grid.
Assume that both the width and height of the given paper are at least 5. You may choose to use any two distinct characters or numbers instead of R and G respectively.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
RGRGR
GRGRG
RGRGR
GRGRG
RGRGR => 0
GRRRGRRGRG
GGRGGGRRGR
GRRGRGRGRG
GGRRGRGRGG
GRGGRGRGGG
RRGRGRGRRG
RRRGRGRGGG
RGGRGGRRRG
RGGGRRRRRG
GRGRRRGRRG => 0
RGRGRG
GRGRGR
RGRGRG
RRRRRR
RGRGRG => 2
RRRRR
RRRRG
RRRGG
RRGGG
RGGGG => 10
GGGGG
GGGGG
GGGGG
GGGGG
GGGGG => 12
RRGGGRRRGR
RRRGGRRRGR
RGGGGRRRGG
GRRGRRRRGG
GGGRGGRRGR
RRGGRGGGGG
GGRRRRRGRR
GGRGRRRRGR
GGRRRGGGGR
GRRGGGRGRR => 9
```
[Answer]
# [J](http://jsoftware.com/), 45 41 40 39 38 bytes
```
[:<./@(,,25-,)5 5+/@,@(=2|#\+/#\);._3]
```
[Try it online!](https://tio.run/##xVDBagIxEL3nK0aFJmGzyRrZgmkXlhY6l@IhV108iKK9eNCj@OvbycQttbTnsmR4efPmvcl@9PNRmHaPozCXUoyt3EETQIKBCgKd0sJrfH/rl@HZulYZ4@vS6BrqwrWmVY2/TFaFm6z0k13Pul6LxYuFLDZKmVBa7S@Fux5srdUypKlr0GPvyKLjGSHO29O5sbDd7I9tQ8OwA4lRPhwsCbwQFSRFWqgSEekTqeAvWN@LMUZiuY9UkLHIzMBmhMkmI/K69ZPt0E8JLGGWrRiyLmsp3P/cNAso9Hbjqa8bTUzvHpebcUjmVXI0ZvX3AGT2r/q/v6L/BA "J – Try It Online")
Perfect problem for J's subarray, or tiling verb:
* `5 5...;._3]`For every 5 x 5 tiling of the input (which we take as a binary matrix), do the following
* `=2|#\+/#\` Create a template checkerboard `2|#\+/#\` and return where the current tile is equal to that `=`. (see penultimate step to understand why checking equal instead of not-equal is ok here)
* `+/@,@` And sum
* `[:...(,,25-,)` Cat that result with 25 minus that result. This gives us "both possible checkerboards", because if one checkerboard misses in `x` places, the other will miss in `25 - x` places.
* `<./@` Take the min
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-x`, ~~68~~ 54 bytes
*-12 thanks to Dlosc's suggestions*
```
Fx,#g-4Fz,#@g-4lAL:[25-Y$+:%_=BMEFL:_@>zH5Mg@>xH5y];Nl
```
Input is a binary matrix.
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJGeCwjZy00RnosI0BnLTRsQUw6WzI1LVkkKzolXz1CTUVGTDpfQD56SDVNZ0A+eEg1eV07TmwiLCIiLCJbMDswOzA7MDswXSBbMDswOzA7MDswXSBbMDswOzA7MDswXSBbMDswOzA7MDswXSBbMDswOzA7MDswXSIsIi14Il0=)
Here's some [code](https://tio.run/##NY0xCsMwDEV3n0JkkU1Kly4lxbN2rSFDoClRKY5xHUpP79qOu3w9nr6Q/8Z1c5erDyl9VnktoGWw4vwetTGDAh/ERY0j9njD83MTp8d3DLrY2dqOO2PgsQWYQRzIZHqc8LS4u0VAkxIzEXFOViX/SM2SoiIaZkfUupWpWq575oJHl1U7p4LHjzx@) to convert a matrix of `R` and `G` to a binary matrix that can be used in Pip.
### How? (Outdated until I find time to update)
`T#g-5<Uv{. . .}`: Repeat until `T` the length `#` of the input matrix `g` minus 5 `-5` is less than `v` incremented (modify in-place) `<Uv`. The initial value of `v` is `-1`. This essentially loops from `v=0` to `v=#g-5`.
`Y-1T#@g-5<Uy{. . .}`: Set `Y` the variable `y` to `-1`. Then repeat until `T` the length `#` of the first element `@` of the input matrix `g` minus 5 `-5` is less than `y` incremented (modify in-place) `<Uy`.This essentially loops from `y=0` to `y=#@g-5`.
`FL:_@>yH5Mg@>vH5`: Get all the elements starting from index `v` (`@>v`) of the input matrix `g` and then get the first `5` elements of the resulting matrix `H5`. For each `M` row `_` in the resulting matrix, get all the elements starting from index `y` (`@>y`) of the row `_` and then get the first `5` elements of the resulting list `H5`. Then flatten `FL` the resulting matrix. This essentially creates a flattened 5-by-5 sub-matrix with `g[v][y]` (not real Pip code, just pseudocode) as the top left corner.
`z:_%2=BMZ,25. . .`: Zip `MZ` the range `,` from 0 to `25` with the flattened sub-matrix described previously, and map the zipped pairs to the block `_%2=B`, with values from `,25` being `_` and values from the flattened matrix being `B`. Test if the value from the range `_` modulo `2` (`%2`) is equal to `=` the value from the flattened matrix `B`. Set `:` the resulting list to `z`: This essentially tests the 5-by-5 sub-matrix against a checkered 5-by-5 matrix (which, when flattened, is the alternating list `0,1,0,...,1`, represented by taking the range `,25` and taking modulo `2` of that list), and sees how many places it "misses". This will give how many values need to change within the 5-by-5 submatrix in order to get a checkered matrix.
`lAL:[$+:z25-z]`: Extend `AL` the list `l` with the list `[$+:z25-z]`, which consists of two values `$+:z` and `25-z`. Sum `$+` the list `z`, modifying in-place `:`. `25-z` takes the sum and subtracts it from `25`. The initial value of `l` is the empty list `[]`. This essentially keeps track of how many changes are needed to change from the specific 5-by-5 submatrix to a checkered matrix. The reason we also append `25-z` to the list is to handle the fact that there are two possible checkered matrices that we can change the sub-matrix into, and that changing the submatrix into one of the checkered matrices may be more efficient than changing it to the other checkered matrix. It just so happens that the number of changes needed in order to change the sub-matrix into one possible checkered matrix is `25` minus the numbers of changes needed for the other possible checkered matrix.
`Nl`: Takes the minimum of the list `l` and implicitly outputs the result.
[Answer]
# [Python](https://www.python.org), ~~130~~ ~~128~~ 111 bytes
* -2 bytes thanks to Neil, thanks to order of operations
* -9 bytes thanks to 72.100.97.109
Python is extraordinarily bad at working with multidimensional arrays without numpy. Or maybe I just missed something obvious.
```
lambda a:min(sum(y+a[x+i//5][y//2+i%5]+i&1for i in r(25))for x in r(len(a)-4)for y in r(2*len(a[0])-8))
r=range
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVBBasMwEKRXPaIIQ2opxnUbYggBnXXXVdFBpXGtYMtGdiB-Sy-G0v4peU2slRMoBMRqdnZmd6Xvv3boy8aOPwXb_R77It2cm0rXH58a621tLOmONRkSLU-JybJcySHLVolZ5CoxL-9F47DBxmJHVjmlPj2FtNpbomm6Bm6YJUtg5Zui6YZS5JjT9msfxl6enks2T-62Uh4Yi0WMvf3g7Ubh-7TutWsr05N4Z2OqEGqdsT0pSEmiKOJCCO4PR3wKHDAKzI0NaIKCB8TRrS48FHcWWghgoRVA0IF2mkenl_zfAFQoSH2A5qEZf-zwBb_Ywzg7wjeNY7iv)
## Short Explanation
Basically there are 4 loops. The outer loop `for x in r(len(a)-4)for y in r(len(a[0])-4)` find the top left corner of every 5 by 5 square. We multiply this by 2 to get a extra bit.
The inner loop sums the number of squares in that area that do not fit the grid. We add a lot of terms and then &1 them. This basically is equivolent to XORing all their last bits. We need to swap based on the position within the square as well as the last binary digit of `y`. If this is not equal to the grid at that position (also XOR) we include it in the sum.
Finally, we get the minimum value of all of this.
[Answer]
# [Python](https://www.python.org), 111 bytes (@att)
```
lambda A:25-max(map(abs,sum(map(g,*map(g,*A)),[])))>>1
g=lambda*a,c=0:[c:=x+y-c for x,y in zip(a,5*(0,)+a)][4:]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dVHLasMwEKRXfcXik-TIxQkNtAYZchKBnHx1fVDcOjXEDxwHkkL_ofdeAqX9p_ZrKu3KvZTaIM-OZmcffvvsz-NT117eK3X_cRyr6Par25tm-2BglSyWUWNOvDE9N9uDPBwbxDsZ-s9KCJkXQog0nbOdosTQyFLFSV4m6jQ7RyVU3QAneYa6hefaWsllyGMpZkYU-U1S-LKva1CQF8ypN07b9Y8tj0XCoK5gc30YB5vsQtjIsLNiy_X7euSBSgNh6TXMFPCQz6NFyEulAh0ILF46u18HIYW0amvaOTPoh7odecXXwto6H6BOqK_L99VLpu3L3KHZHwwqhZhZJrMB0toeGjEjZmIJaZdNyFr4e-c23TtjlCCLVghRh1pfc3KmnnyE4ilywgVjnsqmMliX6mjUzN0E7vnvRBE6UT86IyMPtWc1TeyhnwK1tBRNe6AxcFGEmU_Xfmd044re0W_4AQ)
### [Python](https://www.python.org), 115 bytes
```
lambda A:25-max(map(abs,sum(map(g,zip(*map(g,A))),[])))>>1
g=lambda a,c=0:[c:=x+y-c for x,y in zip(a,5*(0,)+a)][4:]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dVFNS8NAEMXr_oohp910I2mxoIEN9LQUeso15rCNpgaaD5oUWsH_4N1LQfQ_6a9xd2bjRWxgePP2zZuPvn325_Gpay_vlbr_OI5VdPs17E2zfTCwShbLqDEn3piem-0gh2ODeCef656HBFdCCJkXNqbpnO2ULzayVHGSl4k6zc5RCVV3gJM8Q92CKzZyGfJYipkRRX6TFL716xoU5AVz6o3Tdv1jy2ORMKgr2FwP48EWuxQ2Muys2HL9vh55oNJAWHoNMwU85PNoEfJSqUAHApuXzu7XQUghrdqads4M-kPdjrzia2FtnQ_QJDTX5fvqJdP2Yy5o9geDSiFmlslsgrS2QSNmxEwsIe2qCVkL_-7cpndnjBJk0Qoh6lDre07ONJPPUDxlTrhgzFPZ1Ab7Uh-NmrnbwP3-iyhCJ5pHZ2Tkofaspo099Fuglo6i6Q60Bh6KMPPl2t-MXlzTO_obfgA)
Takes a list of tuples of spins (+/-1).
### How?
The standard tool for matching a pattern that may be shifted is convolution. Using "spins" (+1,-1) instead of "booleans" (1, 0) and convolving the input with a 5x5 checkerboard template yields 25 at each offset that has a perfect match (and -25 for a perfect anti-match). Each mismatched square removes 2; when the value becomes negative it will be more economical to match the negative template.
This hopefully explains the (25-|x|) / 2 in `f`.
In addition, we use the fact that the checkerboard made of `1`s and `-1`s is a "rank-1-matrix" meaning that it can be written as the outer product of two vectors which in this case, conveniently, happen to be the same vector v=[1,-1,1,-1,1]. Using this the 2D convolution with the checkerboard template can be broken down into two 1d convolutions, one for each axis.
Further, because of the special structure of v we can write the convolution as a running difference. This is essentially what `g` does.
[Answer]
# [R](https://www.r-project.org), ~~106~~ 104 bytes
```
\(x,g=12){for(i in 5:ncol(x))for(j in 5:nrow(x))g=min(g,m<-sum(x[j-4:0,i-4:0]==matrix(1:0,5,5)),25-m);g}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dVLRSsMwFAUf8xVxMkighbVYmNP4evG1-OZkjGFrRpOONsOK-CW-TMGP0q8xyU0GbqyF25Nz77n35tCPz273VYnvranS6c_znA1JLbKcv1VtxySVmhYzvWobNnDuqHWguvbFUbVQUrM6UTdpv1VseFinl7NJIl18FEItTScHllmqSArOk7xIFb-u33He79l5CQvTLiYZFbTa6pWRrWaKU8P65WbTvLKnhvWm6zeNNEwlo7ke2S5WPL1v77ThfDzOScViFzYqwb7EBSBH2GovqLilE_JPA2Vpk74MbACPCTKRRQSuGyLbMuRd95h3g3yJZ30rD32drz2xQ5yEO4eTF8dTFOYHQiwp4xp-L9wD9prs8MbuISfiXnQ0Ce8DJQ4KEAIL6FiAwQVfi6YC-og2eKMRkyCH4Dlm4hJX-Kfsdvj9Aw)
Based on [Jonah's explanation in the J answer](https://codegolf.stackexchange.com/a/255206/55372).
Takes input as a binary matrix.
[Answer]
# JavaScript (ES6), 115 bytes
Expects a matrix filled with `"0"`'s and `"1"`'s.
```
f=(m,x=0,[r,...a]=m)=>m[4]?r[x+4]?Math.min((g=n=>t=n--&&(r[x]+n-m[n/5|0][x+n%5]&1)+g(n))(25),25-t,f(m,x+1)):f(a):25
```
[Try it online!](https://tio.run/##dZBNjtMwFMf3OcXTSNS2krhpRRYUubMCr9h4lmlAVpp0gmKnOAENAm6AxIYl3IPzzAU4QvFXhBggiZz38fP/fbyW7@TUmP4853o8tpdLx7DK7liRVSajlMqaKcL2qnpcX5vqLrW/F3K@parXGJ@YZvuZ6TxfrbDN1qnOVaXX5ceitqx@VNarDUlPWBOCtyXJtmU@Z50rkG4I2XVYkt22vJj2zdvetBh1EyLUtPL4vB/am/e6wQWh83gzm16fMKHTeehnfHXQB31FaDeaZ7K5xROwPXxIAIZ2hgpeZaAy0FADg4kqOVtkjauXdUociA/HlKzJU8srS6jfolZSyXOQq@zsU@39xvn2YIAEgmtAGwQ7QAUiXsQVNa29BHYwH2lGPY1DS4fxhF0mBWTfFLxjZbQT@fnjy/23r/b0YvffP3u5T@QiBBc8cYdI@EPbtbJJHmT5n@Q/GfE3UyQ24qr5sBVxQoHzTIwGi7vbwbISMe/UlrxvxH1i6Ul403OejTUX5dBT9Dy8eA7cJkkMiaWMrxvq8LAIN4F7/nd6yCuFfrgIQtHkMcrDxNGMU3g2LIWHPYQx/KKCncTrPO4sZFzRJ78A "JavaScript (Node.js) – Try It Online")
### Commented
Nested `map()` loops tend to be lengthy. So we don't use any explicit loop and go 100% recursive instead.
```
f = ( // f is a recursive function taking:
m, // m[] = input matrix
x = 0, // x = position in the current row
[ r, // r[] = current row
...a ] = m // a[] = remaining rows
) => //
m[4] ? // if there's still at least 5 rows:
r[x + 4] ? // if there's still at least 5 columns:
Math.min( // get the minimum:
( g = n => // g is a recursive function taking a counter n
t = // save the result in t
n-- && ( // if n is not 0 (decrement it afterwards):
r[x] + // take the value at the top-left corner
n - // add n
m[n / 5 | 0] // subtract the value of the cell at
[x + n % 5] // (x + (n mod 5), floor(n / 5))
& 1 // isolate the least significant bit
) + g(n) // add the result of a recursive call
)(25), // initial call to g with n = 25
25 - t, // also try 25 - t
f(m, x + 1) // do a recursive call to f with x + 1
) // end of Math.min()
: // else:
f(a) // do a recursive call to f for the next row
: // else:
25 // stop the recursion
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~57~~ 56 bytes
```
WS⊞υEι﹪⁺℅κ⁺λLυ²≔⟦⟧ηF⁻Lυ⁴F⁻Lθ⁴⊞ηΣE✂υι⁺⁵ι¹Σ✂λκ⁺⁵κ¹I⌊⁺η⁻²⁵η
```
[Try it online!](https://tio.run/##ZU@7bgMhEOzvKygXiRSx4iqVlWIVKVZOXGmlQOfLgQ5zzgHJ5@Pl4aRIs8zOzGqGUattXJVN6UcbOzF4ddcYhrAZNwPnrI9eQxTsqK5g6FnP0a7Q2@jhfTsbpywsXLBCWMHeJjcHOuCcyB3N5@7gvZkdnD4E07R@rhuDo3Hk/zUL9kRR/5WvppQSWrAhXiAXGawZp9zKtOQ9QfI@8uqpOtVZ/vSl6LxU6ul3AV6UDznPXOik2Cii5u/2uWwxpyQlIkqassvzDrGx2GEmGiQOsXkLxsLKokuZYfXKrp1jhjUjG9LDt70B "Charcoal – Try It Online") Takes input as a list of newline-terminated strings of `G`s and `R`s (although `0`s and `1`s also work). Explanation:
```
WS⊞υEι﹪⁺℅κ⁺λLυ²
```
Read in the strings, but replace each character with a bit according to the parity of the sum of its character code, row and column.
```
≔⟦⟧θF⁻Lυ⁴F⁻Lθ⁴⊞θΣE✂υι⁺⁵ι¹Σ✂λκ⁺⁵κ¹
```
Collect all of the `5×5` regions and count the bits in each region.
```
I⌊⁺θ⁻²⁵θ
```
Subtract all of the counts from `25` and output the minimum of both sets of counts.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ ~~18~~ 17 bytes
```
Z5ƤẎ5Ƥ€Ẏ;¬$¬Ðe€§Ṃ
```
[Try it online!](https://tio.run/##y0rNyan8/z/K9NiSh7v6gOSjpjVAhvWhNSqH1hyekArkHlr@cGfT/6OTH@5c/KhxHxfXoa0Pd2x6uGPRw91bbB81zA063K4Z@f9/kDsQcoEIdy4MtoKtnYIBF1AkCMgBC7sDCXcwmwsiAhOFsNxBuiEsoBFQeZBpMHmQwWAlYFGwUWAmWB1YLdROmMkQN0F5YMUwHkihERcXVCgIZg3YXog97mA1hiAfgAAuEqzIaAC8aQkA "Jelly – Try It Online")
*-1 thanks to Jonathan Allan*
Expects a binary matrix. Feels... inelegant.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 79 bytes
```
@(a)min([b=conv2(mod(a+(1:rows(a))'+(1:rows(a')),2),~~e(5,5),"valid"),25-b](:))
```
[Try it online!](https://tio.run/##jVHbCoJAEH3vK8QXd2iSGcGXlqD/EB@8QlAKFfbWr5vlrjtuECGic@bMOXPpq3sxNGMbHII4jsejKuBy6lRWHqq@GxJ16WtVbBXvr/3jNiUhckEEgAng89moFFPAcCjOpzqcwHRX5moPMLYqYyT8vNp8kfRPLIfNVPYO2CQthQyFHKpF3uNJlLStZKeh/Uo2GH/xnDMvPBIxG19Gr@95mHVzbnqJO6EVbgVcir1O7RwkuiK7RPPoP/@cm5yOFl8fI49H4h4SW@/P6sl7krib2KAmJE@P9cpxVll8BT@H8QU "Octave – Try It Online")
Takes input as a binary matrix.
---
# [Octave](https://www.gnu.org/software/octave/), 56 bytes, by [@Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)
```
@(x)min(25-abs(conv2(x,j.^((t=0:2:8)+t'),'valid'))(:))/2
```
[Try it online!](https://tio.run/##pVJhC4IwEP3er/CbO9qtHAThEPofYWCWYJR@SMR/vyRz220GQTA2d@/d893u2rIr@quuoiwSQugDG@BRN0zusDg/Wdk2vWQDv4kTY122TWW6h3UXA4/74l5fYgCWAmykrtgx4ZjwaVPma9zUL0AOq1HifTUMS0TLRAIqSlxI8TC0Frz4ZCiQMvEvCdSak4E0Zm0R4ueYyg9LcJ/OQx1hD5rFLBoWYotF3y/aZjhL/XG1htB/KE480TAu8ZH23IuH3TC/CGYIvTlxVRXSGXDnjbqZdR1XNDcH/QI "Octave – Try It Online")
Takes input as a matrix with `1` and `-1`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2Fø€ü5}εε˜Â«āÉα2äO]ß
```
Input as a binary-matrix.
[Try it online](https://tio.run/##yy9OTMpM/f/fyO3wjkdNaw7vMa09t/Xc1tNzDjcdWn2k8XDnuY1Gh5f4xx6e//9/dLShjoEOFMfqRMPZOoZAHqqcoQ4cosnFAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCkU6nDpeSYXFKamAMXs6981DAvyD3kUcNCPadHTWuCD6@3Vfpv5HZ4B5BzeI9p7bmt57aennO46dDqI42HO89tNDq8xD/28Pz/SnphSv6lJVBTdA5ts/8frRTkDoQxeSDSPSYPC09JR8k9KAjIgIi5A0l3MAekDKwCJg5huoO1Q5ggM6BKwObBlIDNBquCiINNhLDBasHqgRbDDYe6C8YHK4bzQQqh/CC4PRCroTa5g9SAKLBDcVFgcyBOcQ@CmgJju0PF3aG@hrGhvoCoh4SNOzQ0IN6AhFgQ1ByoIe6w0IPIKcUCAA).
**Explanation:**
```
2Fø€ü5} # Create all overlapping 5x5 blocks of the (implicit) input-matrix:
2F } # Loop 2 times:
ø # Zip/transpose; swapping rows/columns
# (which will use the implicit input-matrix in the first iteration)
€ # Map over each inner list:
ü5 # Create overlapping quintuplets
εε ] # Nested map over each block:
˜ # Flatten the 5x5 block to a single list
 # Bifurcate it; short for Duplicate & Reverse copy
« # Merge the reversed copy to the list
ā # Push a list in the range [1,length] (without popping): [1,50]
É # Convert it to a list of [1,0,1,0,1,0,...] with an is_odd check
α # Get the absolute difference at the same positions of the two lists
2ä # Split the list back into two parts of length 25 each
O # Sum each inner list, resulting in a pair [c,25-c]
# (where `c` is the amount of bits that has to be changed to get a
# checkered 5x5 block with 1s at the corners)
]ß # After the nested map: pop and push the flattened minimum
# (which is output implicitly as result)
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 145 bytes
```
L$v`(?<=(.)*)(.{5}).*¶(?<7-1>.)*(.{5}).*¶(?<1-7>.)*(.{5}).*¶(?<7-1>.)*(.{5}).*¶(?<1-7>.)*(.{5})
00$2$3$4$5$6
,T,2,`d`10
%O`.
01
0¶1
N$`
$.&
\G.\B
```
[Try it online!](https://tio.run/##hY09DsIwDEZ3n8OgtkqjpFC68COxeEEgWR07uFIZWBgQYkFcqwfoxULShgExsHx@ev4s3873y7W1rhZi6dwBH5Ls1ptEp1ma6Gf5SnU29F5Vud16@eVsXv24vz0wBgtc4BJLXIGqVaGkE2tgdhINxoIZegtHFEA9h4Z0s3eOmYjYJ0PID1K0BBRERO@IYndkGi2Pe@aAU5chnlPA6Ycfbw "Retina – Try It Online") Takes input as a newline-separated list of binary strings but header converts from strings of `G` and `R` for convenience. Explanation:
```
L$v`(?<=(.)*)(.{5}).*¶(?<7-1>.)*(.{5}).*¶(?<1-7>.)*(.{5}).*¶(?<7-1>.)*(.{5}).*¶(?<1-7>.)*(.{5})
00$2$3$4$5$6
```
Extract all of the 5×5 regions as flattened strings, but prefix two `0`s because it's golfier not to have any zero-length strings later.
```
,T,2,`d`10
```
Toggle alternate bits. The ideal case is now either one `0` bit or one `1` bit (one of the `0` bits added above would have been toggled to `1`).
```
%O`.
```
Sort the bits within each string of 25 bits.
```
01
0¶1
```
Separate the strings of `0` and `1` bits.
```
N$`
$.&
```
Sort ascending by length.
```
\G.\B
```
Subtract `1` and convert the minimum to decimal.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 70 bytes
```
a->(25-vecmax(abs(g(g(a)))))/2
g(a)=Mat(Vec(x^5\(x+1)*Pol(a~))[5..-5])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN90Sde00jEx1y1KTcxMrNBKTijXSgTBREwT0jbhATFvfxBKNsNRkjYo40xiNCm1DTa2A_ByNxDpNzWhTPT1d01hNiGm3mE0SCwpyKjUSFXTtFAqKMvNKgEwlEEdJRyENZKqOQnS0oY6uoQ6EsIazgIQ1MRKxQBPAHLg8QpkuQp0uiqQ1qkIsWtDkdBEOQBOHOAfDKLg4Dg2oTkPSoYsqhnAWikIoBfI8pgeQgw1NFslYNCmIUQg5TE8gPKqL7lZdWDQgIWsKuDDHoAWGLsJpWIR1sanXRY1rNHHMWIBbgZF2kDWhGAVNT7qYlqAqR3EfkqtQ9cbCMs-CBRAaAA)
Takes input as a matrix with `1` and `-1`. Based on [@Luis Mendo's comment of my Octave answer](https://codegolf.stackexchange.com/questions/255202/cgac2022-day-5-preparing-an-advent-calendar/255222#comment565703_255222).
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 82 bytes
```
a->vecmin(concat(m=matrix(#a~-4,#a-4,x,y,sum(j=0,24,(a[x+j\5,y+j%5]+j)%2)),-m)%25)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVLBaoQwEIV-ieyyEHECk2WFQnA_Yq9WSpBalGrFukUv-xs99CKU0m9qv6ZaEzOmUHrQzLx5M28mk9ePWjX57X09vGVe9H5uM379eVL8-HyXlnnF0scqVS0ro1K1Td6xrbrwA2zV-Ough6dzyYoIYX8ApuIuKG5C6INiFyZB4e_2vg-8HM_Qnyt_Xb2oun7omfL40aubvGpHczM5G_AypsYEL44FIPx8Up-A8k8sGbMmU-iQIaAmoEUliTs8iqI0mcLWkG6m0Jj4xbPKYuEh8YXWFeD0PY2ybs1OTnFbZoXP6TZg1YWeSzhd4pyExpH_tIwSnQoXTRdDh4dkDxRb35upR_eIZF_k5pZdE1SuFOcqiy7hJ4l-n8Mwn98)
Takes input as a binary matrix.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 18 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{12.5-⌈/|,5-/5-⌿⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=qzY00jPVfdTToV@jY6qrD2Luf9S7tRYA&f=fVGhEcNADOOdIsx3ZSkvFvcQGaUsoFuUFYYnm2SSfi3ZKfj0Hvj1lmS/PQ23bdnn1/oer@Z23x9Pc7Rjg30DWuzjy9SRwr3lxEMLCBTikFWGd9CW9/AWi4WSxapBVCaMBYJPTbepo2z@pF7C4@elr0@OH22p1@wMJ1KAlP/xpCr/CM@SBaAMcq4FNCNpuADkxDkkLcbTTVaoLTFrHw&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
Input a matrix with `0.5` and `¯0.5`.
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~142~~ 138 bytes
-4 bytes thanks to @ceilingcat
```
#define l(n,m)for(int n=m;n--;)
c;j;f(*r,*t,w,h){*r=99;l(y,h-4)l(x,w-4)l(i,2){j=i,c=0;l(Y,5)l(X,5)c+=t[(Y+y)*w+X+x]!=j,j=!j;*r>c?*r=c:0;}}
```
[Try it online!](https://tio.run/##dVBLb9swDL77V6getkq2AqRDO6DT1B112cmnBm0PqWLXNhw1sJXaQeC/Po96dXEf9IMSv4/kR8qFbNbqaZq@bPKiUjlqsKJbUjy3uFIaKb5larFgJJKsZgVOWppo2tOSHJOWX1@zBh9oubgkDR5ob31Fv5NjzSsq@RLgFb2C4C38Zcr1HV6lB5L06W06PJzxmtb8rGZJeyN/Qz35c8nGcXp5rjZI5502EhI4DZoio6Z3riTRMUJgFn7cF4ijXnab/Q4bLmEWhBGQneEA8JKB@4VKcGlKLO5KzJiDYw7A7MEF5pxtbLfXsly3GHrfHVCCepSi4cE3DjYHofTbAEfn4vx/zhidlO9wHPt6Y5gVtbn2s@FvcKamIjVbKT111wKtwHGbd/tGQ8uvm3t1r2JqUoETjVFkCm3XlcJhi3bTf@JMfPJA9hW8voVniywDyODCfZYacsLdgbOITZuB/m595uiuNjS@WJpv3tonnzZ0Zs@Q9OOd2ix7pdgOQbX4eLbP7EN25qULr95p9zEhXgE/bpDgSwZVfuws7EO4gHenmxinv7Jo1k/d9A8 "C (clang) – Try It Online")
] |
[Question]
[
Welcome to Code Bots 2!
You've learned your lesson since the last Code Bots. You've tried to figure out more ways to fit more actions in less lines, and now you finally have it. You're going to make an event-driven Code Bot.
Your bot must consist of 24 lines. Each line follows one of the two formats:
```
Condition:Action
```
or
```
Action
```
Your bot also have enough storage to store 5 integers named `A` through `E`. An integer can store values from 0 to 23.
Each turn, you will execute line `C`, *unless* one of the conditions is true. If so, then `C` will then contain the line number of the conditional that is true, and then that line will be executed. At the end of each turn, `C` will be incremented.
There are the available conditions:
1. `Start` is true only on the first turn. You must have this in your code exactly once
2. `BotAt(N)` is true if there is a bot at the location defined by N
3. `Equals(A,B)` is true if A equals B. They can be different types, if so, they will not be equal.
4. `Modified(A)` is true if `A` was copied to during the last turn. `A` must be a variable name, a line, or a condition
5. `Any(C1,C2,...)` is true if any of the conditions are true
6. `None(C1,C2,...)` is true if none of the conditions are true
7. `All(C1,C2,...)` is true if all of the conditions are true
8. `Not(C)` is true if C is false. `C` must be a condition.
Variables can be in one of the following formats. The first 9 are numerical, and can be be used for whenever N is used in this page.
1. `A`,`B`,`C`,`D`,`E`
2. A number from 0 to 23
3. `This` will return the line number it is currently on
4. `Add(N1,N2,...)` will return the sum of all values
5. `Sub(N1,N2)` will return N1 minus N2
6. `Mult(N1,N2,...)` will return the product of all values
7. `Div(N1,N2)` will return N1 divided by N2
8. `Mod(N1,N2)` will return N1 mod N2
9. `OVar(N)` will accept a variable name, and will return the opponent's variable
10. `Line(N)` will return the Nth line in your code
11. `Type(N)` will return the Nth line type in your code (the types are the names of the actions)
12. `Cond(N)` will return condition on the Nth line
13. `CondType(N)` will return the condition type on the Nth line (the types are the names of the conditions)
14. `OLine(N)` will return the Nth line in your opponent's code
15. `OType(N)` will return the Nth line type in your opponent's code
16. `OCond(N)` will return the condition on the Nth line
17. `OCondType(N)` will return the condition type on the Nth line
`A` and `B` are for your personal use, `C` is used to determine which line to execute in your code, and `D` is used as a direction. Each value of `D` refer to a different square and direction pair.`E` produces a random value each time. `D` and `E` will be initialized to a random value, otherwise `0`.
The direction used will be `[North,East,South,West][D%4]`. Your opponent is the bot in the immediate square in that direction.
There are 4 actions available to you:
1. `Move` will move you 1 square forward in the `D`th direction. If there is a bot there, you will not move.
2. `Copy(A,B)` will copy the variable `A` to `B`. `B` cannot be a numerical value, except for a variable name. `A` and `B` cannot be of different types. Copying a line does not copy the condition.
3. `Flag` does nothing. **The bot with the most flags in your code will get a point. The bot with the most points wins.**
4. `If(C,L1,L2)` will perform the line on `L1` if `C` is true, else performs `L2`. `C` is a condition, and `L1` and `L2` must be lines.
# The Big Picture
50 copies of every bot will be placed in the world. Your goal is to get your flag into as many bots as possible. For each bot that has more of your flag type than any other flag type, you get a point.
The bots will be placed as follows:
```
B...B...B...B...
..B...B...B...B.
B...B...B...B...
```
There will be 10 games run, and points will be averaged across all of the games, determining who the winner is.
# Side Notes
If multiple conditions apply, then the one that most immedately follows `Start` will be executed
The bots will be closely packed but you will not start neighboring another bot. (It techincally will be the same format as the last CodeBots)
As this challenge was not posted in the sandbox (to give nobody an advantage), I reserve the right to change small details for fairness, or additional capabilities. Also, if there is a bug in the CodeBots runner, I will change it, even if a bot depended on that bug for its success. I am trying to be as *fair* as possible.
Recursive `If` statements will not be executed
If your bot is shorter than 24 lines, the remaining lines will be filled with `Flag`
Remember when copying to your own `C`, that `C` is incremented at the end of your turn.
The CodeBots interpreter can be found [here](https://github.com/thenameipicked/CodeBots2Java). It includes a .jar file for easy execution. Simply add your bot to the bots folder
# Scores
1. 893.9 Borg
2. 1.3 LazyLioness
3. 0.9 Defender
4. 0.5 Flagger
5. 0.4 CliqueBot
6. 0.4 Insidious
7. 0.3 Attacker
8. 0.3 Gard
9. 0.3 SingleTarget
10. 0.2 FreezeBot
11. 0.2 Sentinel
12. 0.2 Driveby
13. 0.0 AntiInsidious
14. 0.0 MoveBot
15. 0.0 CliqueBorg
16. 0.0 Calculator
17. 0.0 TestBot
18. 0.0 Imitator
## UPDATE
Lines of code are now rotated when you view your opponent's code. That means, your opponent's line 1 may be line 14 (or whatever line). A bot will have a fixed offset which will offset his lines by `X` amount *when viewed by an opponent*. The opponent's `C` variable will also be offset by the same `X` amount. `X` will not change within the same game, but it will change from game to game.
[Answer]
# Borg
Converts all other bots into clones of itself. Resistance is futile.
```
Start:Copy(2,A) # Cloning will begin at line 2
All(Not(BotAt(D)),Not(Equals(2,A))):Copy(2,A) # Reset A if the opp left before we were done
Not(BotAt(D)):Move
All(Equals(Line(Sub(This,3)),OLine(0)),Equals(Line(Sub(This,2)),OLine(1)),Equals(Line(Sub(This,1)),OLine(2)),Equals(Line(This),OLine(3)),Equals(Line(Add(This,1)),OLine(4)),Equals(Line(Add(This,2)),OLine(5)),Equals(Line(Add(This,3)),OLine(6)),Equals(Line(Add(This,4)),OLine(7)),Equals(Line(Add(This,5)),OLine(8))):Copy(E,D) # Check if cloning is complete
All(Equals(A,2),Not(Equals(OCond(1),Cond(Add(This,4))))):Copy(Cond(Add(This,4)),OCond(1)) # Copy freeze cond to OLine(1) before cloning starts
All(Equals(A,2),Not(Equals(OLine(1),Line(Add(This,3))))):Copy(Line(Add(This,3)),OLine(1)) # Copy freeze line
Not(Equals(Cond(Add(Sub(This,6),A)),OCond(A))):Copy(Cond(Add(Sub(This,6),A)),OCond(A)) # Copy Cond(A) to OCond(A)
Not(Equals(Line(Add(Sub(This,7),A)),OLine(A))):Copy(Line(Add(Sub(This,7),A)),OLine(A)) # Copy Line(A) to OLine(A)
Equals(A,A):Copy(Add(A,1),A) # Increment A. It will wrap around all 24 lines before the completion check matches
```
*Edit: Small fix to reset A if the opponent moves before I'm done with him. Doesn't seem to affect the score but it makes me feel better.*
*Edit #2: Added a more complete check to ensure the cloning process has completed properly (line 3)*
*Edit #3: Update to handle the new random offsets. The difficulty here was that new clones would have their code located at random offsets which means they don't know the location of their own lines. That means that all references to my own lines must be relative (to `This`). Opponent line numbers can still be absolute since they are random anyway.*
[Answer]
# Flagger
*Shoot for the moon*
```
Start:Flag
```
And the rest gets auto-filled with flag.
[Answer]
# Calculator
This bot doesn't understand the goal of this challenge, so he decided to calculate some numbers for the enemy.
```
Equals(Mod(OVar(E),5),0):Copy(Add(OVar(A),OVar(B)),OVar(D))
Equals(Mod(OVar(E),5),1):Copy(Sub(OVar(A),OVar(B)),OVar(D))
Equals(Mod(OVar(E),5),2):Copy(Mult(OVar(A),OVar(B)),OVar(D))
Equals(Mod(OVar(E),5),3):Copy(Div(OVar(A),OVar(B)),OVar(D))
Equals(Mod(OVar(E),5),4):Copy(Mod(OVar(A),OVar(B)),OVar(D))
Start:Move
```
[Answer]
# CliqueBot
```
Flag
Start: Copy(11,B)
Not(Equals(Line(20),Line(21))): If(Equals(Line(21),Line(22)),Line(7),Line(8))
Not(Equals(Line(21),Line(22))): If(Equals(Line(20),Line(21)),Line(9),Line(10))
All(BotAt(D),Not(Equals(11,OVar(B)))): If(Equals(Line(20),OLine(OVar(C))),Line(10),Line(11))
Any(BotAt(D),Equals(E,B)): Copy(Add(D,1),D)
Equals(1,1): Move
Copy(Line(21),Line(20))
Copy(Line(20),Line(21))
Copy(Line(21),Line(22))
If(Equals(Line(20),OLine(Sub(OVar(C),1))),Line(5),Line(12))
Copy(Line(20),OLine(OVar(C)))
Copy(Line(20),OLine(E))
```
Recognizes friends via their `B` value, fills everyone else's lines with flags. Also goes to some length to preserve the integrity of one of its own flags (this part is cute but probably not very useful).
~~Edit: Unsurprisingly, there appears to be a bug here somewhere, judging by the score.~~
Suspect that lines are 0-indexed and my code is 1-indexed. Should really have checked that earlier. Added a Flag at the beginning to bump everything up one.
[Answer]
# Defender
```
Start:Copy(0,A)
Copy(0,B)
Flag
Flag
All(Modified(Line(2)),Equals(A,0)):Copy(1,A)
Copy(Line(3),Line(2))
Copy(0,A)
Copy(10,C)
All(Modified(Line(3)),Equals(B,0)):Copy(1,B)
Copy(Line(2),Line(3))
Copy(0,B)
BotAt(D):Copy(Line(2),OLine(E))
```
[Answer]
# MoveBot
```
Start:Move
Copy(E,D)
Copy(-1,C)
```
[Answer]
# Attacker
```
Start:Move
BotAt(D):Copy(Line(Add(Mod(E,6),4)),OLine(E))
Any(BotAt(0),BotAt(1),BotAt(2),BotAt(3)):Move
None(BotAt(0),BotAt(1),BotAt(2),BotAt(3)):Copy(E,D)
```
[Answer]
# Single Target
```
Start:Move
All(BotAt(D),Not(Equals(OVar(D),D))): Copy(D,OVar(D))
BotAt(D):Copy(Line(E),OLine(E))
Equals(A,A):Move
```
Will hunt you down and fill you with flags!
[Answer]
# Insidious
```
Start:Flag # comments --> # why move when we can fit another flag here?
Equals(E,0):Copy(Add(D,Sub(Mult(2,Mod(E,2)),1)),D) # 1/24 chance to turn left or right
All(BotAt(D),Not(Equals(OCond(Sub(OVar(C),1)),Cond(Add(This,4))))):Copy(Cond(Add(This,4)),OCond(Sub(OVar(C),1))) # Copy the freeze condition
All(BotAt(D),Not(Equals(OLine(Sub(OVar(C),1)),Line(Add(This,4))))):Copy(Line(Add(This,4)),OLine(Sub(OVar(C),1))) # Copy the flag-copying line
All(BotAt(D),Not(Equals(OLine(Add(OVar(C),0)),Line(Add(This,Add(4,Mod(E,14))))))):Copy(Line(Add(This,Add(4,Mod(E,14)))),OLine(Add(OVar(C),0))) # copy one of my flags to them
BotAt(D):Copy(Add(D,Sub(Mult(2,Mod(E,2)),1)),D) # turn left or right if we've infected our target
Equals(A,A):Move # move if all else fails, also infection freeze condition
Copy(Line(Add(This,1)),Line(Add(This,Mod(E,22)))) # infection line 1
Flag # first of many flags
```
Similar idea to the bot by the same name in the previous contest. Move until I hit another bot, then freeze it into a loop overwriting its own code with my flags. This time the infected bots overwrite random lines instead of sequential lines, making the infection process a little less effective but much faster.
[Answer]
# Gard
```
Start: Move
BotAt(D):IF(Equals(Line(7),OLine(C)),Line(6),Line(5))
BotAt(Add(D,1)):Copy(Add(D,1),D)
BotAt(Add(D,2)):Copy(Add(D,2),D)
BotAt(Add(D,3)):Copy(Add(D,3),D)
Copy(Line(7),OLine(OVar(C)))
Copy(Cond(7),OCond(Sub(OVar(C),1)))
```
Attacks any robot next to it.
[Answer]
# Freeze Bot
```
Start:Move
All(BotAt(D),Not(Equals(OCond(1),Cond(5)))):Copy(Cond(5),OCond(1))
All(BotAt(D),Not(Equals(OLine(1),Line(6)))):Copy(Line(6),OLine(1))
All(BotAt(D),Equals(Mod(OVar(A),24),0)):Copy(Add(D,1),D)
BotAt(D):Copy(Line(20),OLine(OVar(A)))
Equals(A,A):Move
Copy(Add(A,1),A)
```
Traps you in a loop Incriminating your own `A` variable, then fills you with flags and moves on to the next victim.
[Answer]
# Imitator
```
Start:Move
BotAt(D):If(OCond(0),OLine(0),Line(2))
If(OCond(1),OLine(1),Line(3))
If(OCond(2),OLine(2),Line(4))
If(OCond(3),OLine(3),Line(5))
If(OCond(4),OLine(4),Line(6))
If(OCond(5),OLine(5),OLine(OVar(C)))
Not(BotAt(D)):If(BotAt(Add(D,1)),Line(8),Line(0))
Copy(Add(D,1),D)
```
Predicts what you would do, then does that.
[Answer]
# Lazy Lioness
Originally just "Lioness", my first submission to the contest earned the title "lazy" by literally doing nothing when introduced into the simulator.
Her lethargy is in fact due to a bug (or possibly my misunderstanding the event model) wherein the conditions in the first three lines (a simple parity check for ensuring that flags are not overwritten) occasionally, inexplicably evaluate `true`, locking leo in a lemniscate loop. Several other conditions (particularly those that rely on the `BotAt()` condition) also evaluate `true` at times when no adjacent bot(s) are present. Finally, `Move` and `Copy` directives are clearly ignored when stepping through the simulator. Since my conditional logic chains are somewhat epic, there's plenty of room for bugs in my code *and* in the simulator. ;)
In any case, I submit Lazy Lioness as a test case for either error diagnosis or simulator debugging, which will hopefully lead to the emergence of not-so-lazy Lioness that I can then simulate and refine as my first bona fide submission to the Bots v2 competition.
**It Does Nothing**
```
All(Not(Equals(Line(18),Line(21))),Equals(Line(21),Line(22))):Copy(Line(21),Line(18))
All(Not(Equals(Line(21),Line(22))),Equals(Line(22),Line(18))):Copy(Line(22),Line(21))
All(Not(Equals(Line(22),Line(18))),Equals(Line(18),Line(21))):Copy(Line(18),Line(22))
All(Any(BotAt(Add(D,1)),BotAt(Add(D,2)),BotAt(Add(D,3))),Not(BotAt(D))):Move
All(Any(All(BotAt(D),BotAt(Add(D,2))),All(BotAt(D),BotAt(Add(D,1))),All(BotAt(Add(D,1)),BotAt(Add(D,2)))),Not(BotAt(Add(D,3)))):Copy(Add(D,3),D)
Any(All(Any(All(BotAt(D),BotAt(Add(D,2))),All(BotAt(D),BotAt(Add(D,3))),All(BotAt(Add(D,2)),BotAt(Add(D,3)))),Not(BotAt(Add(D,1)))),All(BotAt(Add(D,1)),BotAt(D),Any(Equals(OCond(2),Cond(20)),Equals(OLine(2),Line(19))))):Copy(Add(D,1),D)
All(BotAt(Add(D,3)),BotAt(D),Any(Equals(OCond(2),Cond(20)),Equals(OLine(2),Line(19)))):Copy(Add(D,3),D)
All(BotAt(D),Not(Equals(OCond(2),Cond(20))),Not(Equals(OLine(2),Line(19)))):Copy(Cond(20),OCond(2))
All(BotAt(D),Equals(OCond(2),Cond(20)),Not(Equals(OLine(3),Line(18)))):Copy(Line(18),OLine(3))
All(BotAt(D),Equals(OCond(2),Cond(20)),Not(Equals(OLine(4),Line(21)))):Copy(Line(21),OLine(4))
All(BotAt(D),Equals(OCond(2),Cond(20)),Not(Equals(OCond(0),Cond(22)))):Copy(Cond(22),OCond(0))
All(BotAt(D),Equals(OCond(2),Cond(20)),Not(Equals(OLine(0),Line(17)))):Copy(Line(17),OLine(0))
All(BotAt(D),Equals(OCond(2),Cond(20)),Not(Equals(OCond(1),Cond(21)))):Copy(Cond(21),OCond(1))
All(BotAt(D),Equals(OCond(2),Cond(20)),Not(Equals(OLine(1),Line(20)))):Copy(Line(20),OLine(1))
All(BotAt(D),Equals(OCond(2),Cond(20)),Not(Equals(OLine(2),Line(19)))):Copy(Line(19),OLine(2))
All(BotAt(D),Not(Equals(OCond(2),Cond(20))),Equals(OLine(2),Line(19))):Copy(Add(D,A),D)
Equals(E,1):Copy(Add(A,2),A)
Any(Equals(E,4),Equals(E,8)):Copy(Add(D,E,A),D)
Not(Equals(A,A)):Flag
Not(Equals(A,A)):Copy(Line(3),OLine(E))
Equals(A,A):Move
Any(Equals(E,4),Equals(E,5),Equals(E,6),Equals(E,7),Equals(E,8),Equals(E,9)):Flag
Any(Equals(E,10),Equals(E,11),Equals(E,12),Equals(E,13)):Flag
Start:Copy(1,A)
```
[Answer]
# sentinel
improvment on `Gard`. Hits nearby bots with flags on the first 8 lines. (that is, all the most used ones)
```
flag
flag
Start:Copy(11,B)
All(BotAt(D),Not(Equals(OLine(Mod(E,8)),Line(0))),Not(BotAt(Add(D,1,Mod(E,3))))):If(Equals(OVar(D),Add(D,2)),Line(7),Line(8))
BotAt(Add(D,1)):Copy(Add(D,1),D)
BotAt(Add(D,2)):Copy(Add(D,2),D)
BotAt(Add(D,3)):Copy(Add(D,3),D)
copy(D,OVar(D))
copy(Line(Mod(E,2)),OLine(Mod(E,8)))
Not(Equals(Line(0),Line(1))):copy(Line(Add(9,Mod(E,16))),Line(Mod(E,2)))
```
[Answer]
# CliqueBorg
```
Flag
BotAt(D): Copy(Line(Sub(This,1)),OLine(E))
Equals(1,1): Copy(Line(Sub(This,2)),Line(Add(This,Mod(E,21))))
Start: Move
All(BotAt(D),Not(Equals(OLine(Sub(OVar(C),1)),Line(3)))):Copy(Line(3),OLine(Sub(OVar(C),1)))
All(BotAt(D),Not(Equals(OCond(Sub(OVar(C),1)),Cond(3)))):Copy(Cond(3),OCond(Sub(OVar(C),1)))
All(BotAt(D),Not(Equals(OLine(Sub(OVar(C),2)),Line(2)))):Copy(Line(2),OLine(Sub(OVar(C),2)))
All(BotAt(D),Not(Equals(OCond(Sub(OVar(C),2)),Cond(2)))):Copy(Cond(2),OCond(Sub(OVar(C),2)))
All(BotAt(D),Not(Equals(OLine(Sub(OVar(C),3)),Line(1)))):Copy(Line(1),OLine(Sub(OVar(C),3)))
All(BotAt(D),Not(Equals(OCond(Sub(OVar(C),3)),Cond(4)))):Copy(Cond(4),OCond(Sub(OVar(C),3)))
```
Trying to combine CliqueBot and Borg technology to create a bot that recognizes copies of itself despite the line offset. It also starts its copying process at the last executed line of code on the opposing bot, rather than line 0, which is more likely to freeze it in place but also more likely to result in a corrupted copy (in fact, I'm not sure this even works, I haven't tested it and it's pretty complex).
[Answer]
# Driveby
One last try before the deadline.
```
Flag
Flag
BotAt(D):Copy(Line(Sub(This,1)),OLine(E))
Equals(1,1):Copy(Line(Sub(This,2)),Line(Add(This,Mod(E,21))))
Start:Move
All(BotAt(D),Not(Equals(OLine(Sub(OVar(C),1)),Line(3)))):Copy(Line(3),OLine(Sub(OVar(C),1)))
All(BotAt(D),Not(Equals(OCond(Sub(OVar(C),1)),Cond(3)))):Copy(Cond(3),OCond(Sub(OVar(C),1)))
All(BotAt(D),Not(Equals(OLine(Sub(OVar(C),2)),Line(2)))):Copy(Line(2),OLine(Sub(OVar(C),2)))
All(BotAt(D),Not(Equals(OCond(Sub(OVar(C),2)),Cond(2)))):Copy(Cond(2),OCond(Sub(OVar(C),2)))
All(BotAt(D),Not(Equals(OLine(Sub(OVar(C),3)),Line(1)))):Copy(Line(1),OLine(Sub(OVar(C),3)))
All(BotAt(D),Not(Equals(OCond(Sub(OVar(C),3)),Cond(4)))):Copy(Cond(4),OCond(Sub(OVar(C),3)))
BotAt(D):Copy(Add(D,1),D)
Equals(1,1):Move
```
] |
[Question]
[
Given a set of `n` elements, the challenge is to write a function who lists all the combinations of `k` elements of in this set.
## Example
```
Set: [1, 7, 4]
Input: 2
Output: [1,7], [1,4], [7,4]
```
## Example
```
Set: ["Charlie", "Alice", "Daniel", "Bob"]
Input: 2
Output ["Daniel", "Bob"], ["Charlie", "Alice"], ["Alice", "Daniel"], ["Charlie", "Daniel"], ["Alice", "Bob"], ["Charlie", "Bob"]
```
## Rules (Edited)
* The order of the output is of your choice.
* The input may be any type of data. But the output should be the same type as the input. If the input is a list of integers, the output should be a list of integers as well. If the input is a string (array of characters), the output should be a string as well.
* The code should work with any number of input variables.
* You can use any programming language.
* The answer should be able to use anything (string, int, double...) as input and output as well.
* Any built-in functions that is related to combinations and permutations are forbidden.
* Shortest code wins (in terms of bytes).
* Tiebreaker: votes.
* Duration: 1 week.
P.S. Be careful about the *extreme* inputs such as negative numbers, 0, etc.
[Answer]
# Haskell - 57 46 bytes
Bring it on, golfscripters.
```
0%_=[[]]
n%(x:y)=map(x:)((n-1)%y)++n%y
_%_=[]
```
Use case (same function works polymorphicaly):
>
> 2%[1,2,3,4] ➔ [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
>
>
> 3%"cheat" ➔ ["che","cha","cht","cea","cet","cat","hea","het","hat","eat"]
>
>
> 2%["Charlie", "Alice", "Daniel", "Bob"] ➔
> [["Charlie","Alice"],["Charlie","Daniel"],["Charlie","Bob"],["Alice","Daniel"],["Alice","Bob"],["Daniel","Bob"]]
>
>
>
[Answer]
# Python (72)
```
f=lambda S,k:S and[T+S[:1]for T in f(S[1:],k-1)]+f(S[1:],k)or[[]]*(k==0)
```
The function `f` takes a list `S` and number `k` and returns a list of all sublists of length `k` of `S`. Rather than listing all subsets and then filtering by size, I only get the subsets of the needed size at each step.
I'd like to get `S.pop()` to work in order to combine getting `S[:1]` with passing `S[1:]` later, but it seems to consume the list too much.
To preempt the objection any such Python solution breaks the rule that "The code should work in any number of input variables" because of recursion limits, I'll note that the [Stackless Python implementation](http://www.stackless.com/) has no recursion limits (though I haven't actually tested this code with it).
Demonstration:
```
S = [1, 2, 6, 8]
for i in range(-1,6):print(i, f(S,i))
#Output:
-1 []
0 [[]]
1 [[1], [2], [6], [8]]
2 [[2, 1], [6, 1], [8, 1], [6, 2], [8, 2], [8, 6]]
3 [[6, 2, 1], [8, 2, 1], [8, 6, 1], [8, 6, 2]]
4 [[8, 6, 2, 1]]
5 []
```
[Answer]
# Mathematica 10, 70 chars
Just a translation of the Haskell answer.
```
_~f~_={};_~f~0={{}};{x_,y___}~f~n_:=Join[Append@x/@f[{y},n-1],{y}~f~n]
```
Usage:
>
> In[1]:= f[{1, 7, 4}, 2]
>
>
> Out[1]= {{7, 1}, {4, 1}, {4, 7}}
>
>
>
[Answer]
# [Haskell + Data.List](https://www.haskell.org/), 44 bytes
```
0%_=[[]]
n%y=do{a:b<-tails y;(a:)<$>(n-1)%b}
```
[Try it online!](https://tio.run/##BcHBCkBAEADQu6@YZIsDkRvWydEfSBoRk90hOxfJt6/3dnTHaowne523QIeCWU9OfK4mPQzjGLB69HK@WM1NKkjGwVPHWCVN1MacFomaP2@RGDRcN7FABCUoCGV1QryF/gc "Haskell – Try It Online")
---
The 46 byte answer is pretty hard to beat but if you have `tails` from `Data.List` you can do 44 bytes.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
EΦEX²Lθ⮌↨ι²⁼ΣιηΦ…θLι§ιμ
```
[Try it online!](https://tio.run/##TY5NC8IwDIb/SukphXrZ1dPmBwgKQ49jhzqDC2St67rpv6/tQPASnudNSNL1xnfOcIy1JxvgYl5wJA7oV6zdO1GhxRntM/QwKqXFFRf0E0JlUiEtCpXTwzgbnuA2D0BJ@5z9bUpzZTjZB35g1GLI3Z/T6kptY2wauUsfMaHUQpZM3Qp7Ywk5U@Xusk0n27hZ@As "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
² Literal 2
X Raised to power
L Length of
θ Input array
E Mapped over implicit range
ι Current index
↨ Converted to base
² Literal 2
⮌ Reversed
Φ Filtered on
Σ Digital sum of
ι Current base 2 value
⁼ Equal to
η Input `k`
E Mapped to
θ Input array
… Chopped to length
L Length of
ι Current base 2 value
Φ Filtered on
ι Current base 2 value
§ Indexed by
μ Current index
```
[Answer]
# Python - 129
s is a list, k is the size of the combinations to produce.
```
def c(s, k):
if k < 0: return []
if len(s) == k: return [s]
return list(map(lambda x: [s[0]]+x, c(s[1:], k-1))) + c(s[1:], k)
```
[Answer]
# Python, 102
```
p=lambda s:p(s[1:])+[x+[s[0]]for x in p(s[1:])]if s else[s];c=lambda s,k:[x for x in p(s)if len(x)==k]
```
Call c to run:
>
> c([5, 6, 7], 2) => [[6, 7], [5, 7], [5, 6]]
>
>
>
It gets all the permutations of the list s and filters the ones with length k.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth/blob/master/pyth.py), 28
```
DcGHR?+m+]'HdctGtHcGtHH*]Y!G
```
This is (heavily) based on the Haskell answer.
Explanation:
```
DcGH def c(G,H):
R return
? Python's short circuiting _ if _ else _
m+]'Hd map to [head(H)]+d
ctGtH c(G-1,tail(H))
m+]'HdctGtH map [head(H)]+d for d in c(tail(G),tail(H))
+m+]'HdctGtHcGtH (the above) + c(G,tail(H))
? H (the above) if H else (the below)
*]Y!G [[]]*(not G)
```
Note: While the most recent version of Pyth, 1.0.9, was released tonight, and is therefore ineligible for this challenge, the same code works fine in 1.0.8.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
goLε¹ybRÏ}ʒgQ
```
Inspired by [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/178718/52210), so make sure to upvote him!
[Try it online](https://tio.run/##yy9OTMpM/f8/Pd/n3NZDOyuTgg73156alB74/3@0knNGYlFOZqqSjoKSY05mMpjhkpiXmZoDYjnlJynFchkBAA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/W/spuSZV1BaUmyloGTveXhCqL2SQmJeCojjEqaj5F9aApQEyf1Pz/c5tzWiMinocH/tqUnpkYH/a3UObbP/H22oo2Cuo2ASy2XEFa3knJFYlJOZqqSjoOSYk5kMZrgk5mWm5oBYTvlJSmB1hgZ6BjoKFnrGOgq6JnqGFjoKQK5SbmZFagpIXXlmSQaILi4pysxLLwbqMQYA).
If builtins were allowed this could have been 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage):
```
.Æ
```
[Try it online](https://tio.run/##yy9OTMpM/f9f73Db//9GXNFKzhmJRTmZqUo6CkqOOZnJYIZLYl5mag6I5ZSfpBQLAA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/W/spuSZV1BaUmyloGTv6WKvpJCYlwJm6ij5l5YAZUAS//UOt/3XObTN/n@0oY6CuY6CSSyXEVe0knNGYlFOZqqSjoKSY05mMpjhkpiXmZoDYjnlJymB1Rka6BnoKFjoGeso6JroGVroKAC5SrmZFakpIHXlmSUZILq4pCgzL70YqMcYAA).
**Explanation:**
```
g # Get the length of the first (implicit) input-list
o # Take 2 to the power this length
L # Create a list in the range [1, 2**length]
ε # Map each integer `y` to:
¹ # Push the first input-list again
ybR # Convert integer `y` to binary, and reverse it
Ï # And only keep values at truthy indices of `y` (so where the bit is a 1)
}ʒ # After the map: filter the list of lists by:
g # Where the length of the inner list
Q # Is equal to the (implicit) input-integer
# (then the result is output implicitly)
.Æ # Get all `b`-element combinations in list `a`,
# where `b` is the first (implicit) input-integer,
# and `a` is the second (implicit) input-list
# (then the result is output implicitly)
```
[Answer]
# APL(NARS), 80 chars, 160 bytes
```
{h←{0=k←⍺-1:,¨⍵⋄(k<0)∨k≥i←≢w←⍵:⍬⋄↑,/{w[⍵],¨k h w[(⍳i)∼⍳⍵]}¨⍳i-k}⋄1≥≡⍵:⍺h⍵⋄⍺h⊂¨⍵}
```
test and how to use it:
```
f←{h←{0=k←⍺-1:,¨⍵⋄(k<0)∨k≥i←≢w←⍵:⍬⋄↑,/{w[⍵],¨k h w[(⍳i)∼⍳⍵]}¨⍳i-k}⋄1≥≡⍵:⍺h⍵⋄⍺h⊂¨⍵}
o←⎕fmt
o 5 f 1 2 3 4
┌0─┐
│ 0│
└~─┘
o 4 f 1 2 3 4
┌1─────────┐
│┌4───────┐│
││ 1 2 3 4││
│└~───────┘2
└∊─────────┘
o 3 f 1 2 3 4
┌4──────────────────────────────────┐
│┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐│
││ 1 2 3│ │ 1 2 4│ │ 1 3 4│ │ 2 3 4││
│└~─────┘ └~─────┘ └~─────┘ └~─────┘2
└∊──────────────────────────────────┘
o 2 f 1 2 3 4
┌6────────────────────────────────────────┐
│┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐│
││ 1 2│ │ 1 3│ │ 1 4│ │ 2 3│ │ 2 4│ │ 3 4││
│└~───┘ └~───┘ └~───┘ └~───┘ └~───┘ └~───┘2
└∊────────────────────────────────────────┘
o 1 f 1 2 3 4
┌4──────────────────┐
│┌1─┐ ┌1─┐ ┌1─┐ ┌1─┐│
││ 1│ │ 2│ │ 3│ │ 4││
│└~─┘ └~─┘ └~─┘ └~─┘2
└∊──────────────────┘
o 0 f 1 2 3 4
┌0─┐
│ 0│
└~─┘
o ¯1 f 1 2 3 4
┌0─┐
│ 0│
└~─┘
o 3 f (0 0)(1 2)(3 ¯4)(4 ¯5)
┌4────────────────────────────────────────────────────────────────────────────────────────────────┐
│┌3────────────────────┐ ┌3────────────────────┐ ┌3─────────────────────┐ ┌3─────────────────────┐│
││┌2───┐ ┌2───┐ ┌2────┐│ │┌2───┐ ┌2───┐ ┌2────┐│ │┌2───┐ ┌2────┐ ┌2────┐│ │┌2───┐ ┌2────┐ ┌2────┐││
│││ 0 0│ │ 1 2│ │ 3 ¯4││ ││ 0 0│ │ 1 2│ │ 4 ¯5││ ││ 0 0│ │ 3 ¯4│ │ 4 ¯5││ ││ 1 2│ │ 3 ¯4│ │ 4 ¯5│││
││└~───┘ └~───┘ └~────┘2 │└~───┘ └~───┘ └~────┘2 │└~───┘ └~────┘ └~────┘2 │└~───┘ └~────┘ └~────┘2│
│└∊────────────────────┘ └∊────────────────────┘ └∊─────────────────────┘ └∊─────────────────────┘3
└∊────────────────────────────────────────────────────────────────────────────────────────────────┘
o 4 f (0 0)(1 2)(3 ¯4)(4 ¯5)
┌1──────────────────────────────┐
│┌4────────────────────────────┐│
││┌2───┐ ┌2───┐ ┌2────┐ ┌2────┐││
│││ 0 0│ │ 1 2│ │ 3 ¯4│ │ 4 ¯5│││
││└~───┘ └~───┘ └~────┘ └~────┘2│
│└∊────────────────────────────┘3
└∊──────────────────────────────┘
o 1 f (0 0)(1 2)(3 ¯4)(4 ¯5)
┌4────────────────────────────────────┐
│┌1─────┐ ┌1─────┐ ┌1──────┐ ┌1──────┐│
││┌2───┐│ │┌2───┐│ │┌2────┐│ │┌2────┐││
│││ 0 0││ ││ 1 2││ ││ 3 ¯4││ ││ 4 ¯5│││
││└~───┘2 │└~───┘2 │└~────┘2 │└~────┘2│
│└∊─────┘ └∊─────┘ └∊──────┘ └∊──────┘3
└∊────────────────────────────────────┘
o 2 f ('Charli')('Alice')('Daniel')('Bob')
┌6──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│┌2─────────────────┐ ┌2──────────────────┐ ┌2───────────────┐ ┌2─────────────────┐ ┌2──────────────┐ ┌2───────────────┐│
││┌6──────┐ ┌5─────┐│ │┌6──────┐ ┌6──────┐│ │┌6──────┐ ┌3───┐│ │┌5─────┐ ┌6──────┐│ │┌5─────┐ ┌3───┐│ │┌6──────┐ ┌3───┐││
│││ Charli│ │ Alice││ ││ Charli│ │ Daniel││ ││ Charli│ │ Bob││ ││ Alice│ │ Daniel││ ││ Alice│ │ Bob││ ││ Daniel│ │ Bob│││
││└───────┘ └──────┘2 │└───────┘ └───────┘2 │└───────┘ └────┘2 │└──────┘ └───────┘2 │└──────┘ └────┘2 │└───────┘ └────┘2│
│└∊─────────────────┘ └∊──────────────────┘ └∊───────────────┘ └∊─────────────────┘ └∊──────────────┘ └∊───────────────┘3
└∊──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
o ¯2 f ('Charli')('Alice')('Daniel')('Bob')
┌0─┐
│ 0│
└~─┘
```
the output seems ok... but bug are possible...
In practice it return void set as Zilde if input alpha out of range; if alpha is 1 it return the elements all one in its set (is it right?);
This below it seems a couple of char less but 2x slower above:
```
f←{(⍺>≢⍵)∨⍺≤0:⍬⋄1=⍺:,¨⍵⋄{w[⍵]}¨k/⍨{∧/</¨¯1↓{⍵,¨1⌽⍵}⍵}¨k←,⍳⍺⍴≢w←⍵}
```
[Answer]
# JS - 117 188
```
(a,b,c=[])=>((d=(e,f,g=[])=>f*e?g.push(e)+d(e-1,f-1,g)+g.pop
()+d(e-1,f,g):f||c.push(g.map(b=>a[b-1])))(a.length,b),c)
```
>
> (<source code>)(['Bob','Sally','Jonah'], 2)
>
>
> [['Jonah','Sally']['Jonah','Bob']['Sally','Bob']]
>
>
>
**Array method madness**
```
combination = (arr, k) =>
Array
.apply(0, { length: Math.pow(k+1, arr.length) })
.map(Number.call, Number)
.map(a => a
.toString(arr.length)
.split('')
.sort()
.filter((a, b, c) => c.indexOf(a) == b)
.join(''))
.filter((a, b, c) => a.length == k && c.indexOf(a) == b)
.map(x => x.split('').map(y => arr[+y]))
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 141 bytes
```
l=>l.Any()?A(l.Skip(1)).Select(x=>l.Take(1).Union(x)).Union(A(l.Skip(1))):new object[][]{new object[]{}};B=(n,l)=>A(l).Where(x=>x.Count()==n)
```
Sadly, Tio/Mono doesn't seem to support generic type **T** declaration, so I'm forced to lose a few bytes with the **object** type instead.
```
//returns a list of all the subsets of a list
A=l=>l.Any()?A(l.Skip(1)).Select(x=>l.Take(1).Union(x)).Union(A(l.Skip(1))):new object[][]{new object[]{}};
//return the subsets of the required size
B=(n,l)=>A(l).Where(x=>x.Count()==n);
```
[Try it online!](https://tio.run/##pZBBS8QwEIXv@yuGnDIYAyuCYJtKuyooe1tlD6WHtgQ3bpxKm2Kl9LfXdFWs4EHx9mbmvW8yKZvjsjHjdUtlaMgJWJvGhVXxqEsXCbi5ovZJ13lhdTjXH4YogiRYHMI/TH8Tj0GNVkVWxvTK8SLmVm725pkvEeVGW@/i3TS@y/faN@U9mYp4h59qHsBz0i/wzk6zNOvnZT8MQaI4CYsq8imU252u9UTv5KpqyXFUinAMFtvaOL02pDlLGRxB42pDD/K2MsRZJiBlAhJ@ImDiz/@LI/SwFHAm4BSGrwNARd8hwhP8DejhLGP435Vstctra7Q3sdia8iAuczLaTiqpCvan54xv "C# (Visual C# Interactive Compiler) – Try It Online")
] |
[Question]
[
The task is to to compete for the **shortest regex** (in **bytes**) in your preferred programming language which can distinguish between English and Spanish with minimum ~~**`60%`**~~ **`90%`** accuracy.
[Silvio Mayolo](https://codegolf.stackexchange.com/a/207418/95389)'s submission (pinned as `Best Answer`) has secured his spot as the winner of original contest against any chance of being contested. In order to provide room for further submissions, he has generously allowed the scoring requirement to be pushed to 90% accuracy.
# Links to wordlists have been replaced due to concerns voiced in the comments.
The following word lists (based on [these](https://github.com/words/an-array-of-spanish-words)) must be used: [English](https://github.com/GirkovArpa/english-spanish-wordlists/blob/master/en_clean.json), [Spanish](https://github.com/GirkovArpa/english-spanish-wordlists/blob/master/es_clean.json)
The Spanish wordlist is already transliterated into ASCII, and there is no word present in either which is also present in the other.
A naive approach to distinguishing Spanish from English might be to match if the word ends in a vowel:
# `[aeiou]$` `i` 9 bytes
Here's a live example, where `6` of `8` words are successfully identified, for `75%` accuracy:
```
const regex = /[aeiou]$/i;
const words = [
'hello',
'hola',
'world',
'mundo',
'foo',
'tonto',
'bar',
'barra'
];
words.forEach(word => {
const match = word.match(regex);
const langs = ['English', 'Spanish'];
const lang = langs[+!!match];
console.log(word, lang);
});
```
[Answer]
# Any Language, 0.3677 (60.6064%, 1 byte)
```
a
```
No, I'm not joking. The single-character regular expression `a` successfully identifies Spanish words over English given your input files 60.6064% of the time, which makes it a valid submission.
Here's a complete, runnable Perl script that checks the percentage of this regular expression, assuming you've downloaded `english.json` and `spanish.json` into the same folder as the script.
```
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
my @english;
my @spanish;
my $fh;
open $fh, '<', 'english.json';
while (<$fh>) {
push @english, $1 if /"(\w+)"/;
}
close $fh;
open $fh, '<', 'spanish.json';
while (<$fh>) {
push @spanish, $1 if /"(\w+)"/;
}
close $fh;
my $correct = 0;
my $total = 0;
my $re = qr/a/;
for (@english) {
$total++;
$correct++ unless /$re/;
}
for (@spanish) {
$total++;
$correct++ if /$re/;
}
say "$correct / $total (@{[100*$correct/$total]}%)";
```
[Answer]
# 50 bytes, 90.02% accurate
`(a(d?|is|r|se?)|dor|eis|ese|je|n|[ns]te|os?|res?)$`
For 18,004 out of the 20,000 words in `es_clean.json` and `en_clean.json`, this regex matches iff the input word is Spanish.
] |
[Question]
[
The problem over [here](https://codegolf.stackexchange.com/questions/205129/produce-the-string-deno-from-the-string-node) introduces an new type of strings: if you split the string into equal halfs and swap the pairs, it produces the same output as sorting the string. We call that a half-sort.
Given a purely ASCII string, check if the string is in a half-sort.
## An example of a half-sort string
The string `node` is a half-sort string, because if you sort by codepoints (note that the codepoints are in *decimal*, not *binary*):
```
n 110
o 111
d 100
e 101
```
That gets turned into:
```
d 100
e 101
n 110
o 111
```
You'll see that the `node` to `deno` conversion is exactly moving the right half to the left position.
## Specification
* For odd-length strings, splitting should make the first half longer.
* Sorting a string means sorting the string based on the codepoints of the characters.
## Reference program & test cases
[Here](https://tio.run/##yy9OTMpM/f@/utjo8JIgr8D///PyU1IB) is the reference program I made for checking my test cases.
```
node -> True
rum -> True
aaa -> True
deno -> False
rim -> False
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~45~~ 42 bytes
*-3 bytes thanks to @dingledooper*
```
lambda s:sorted(s)==s+[s.pop(0)for c in s]
```
[Try it online!](https://tio.run/##RY1BDoIwEEX3nGJ2lgjExB0JLD2BO3VR6RAnKe2kU4ycHgsYWb7332R4ii/vznPf3Gerh6fRILX4ENEoyZtGjjep2LM65b0P0AE5kMdMA6cGZJJs0ZYcrssklURDrs5ACsAPYxehgUGzkhjSFoiLNa@ELUV1KNtDnqc6VZYkpqfZfodvbdVGSQeU0S66XysO5KLaZPGLZucNQtnCNYyYhXGAP2itdzDo/AIXbSV1tHUrfQE "Python 3 – Try It Online")
Takes input as a list of characters. Returns `True` if the list is half-sorted, `False` otherwise.
**How**
`[s.pop(0)for c in s]` gets the first half of the list. After this is evaluated, `s` only has the later half left.
Thus `s+[s.pop(0)for c in s]` is the list with the 2 halves swapped. Note that this works because Python evaluates anything inside square brackets first.
I then check if the swapped list is sorted, aka compare it with `sorted(s)`.
[Answer]
# [J](http://jsoftware.com/), ~~20~~ ~~18~~ ~~15~~ 14 bytes
*-1 thanks to Jonah.*
Goes the other way around: sorts the string ('node' -> 'deno'), rotates it back ('deno' -> 'node') and checks if this equals the input. Fits better J trains.
```
-:<.@-:@#|./:~
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/da1s9Bx0rRyUa/T0rer@a/5PU1DPy09JVecCMopKc8F0YmIimE5JzcuHSGTmqgMA "J – Try It Online")
### How it works
```
-:<.@-:@#|./:~
/:~ sort input
<.@-:@# length of input, halved and floored
|. rotate sorted input by that amount
-: input equal to that?
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
qSzs_c2z
```
[Try it online!](https://tio.run/##K6gsyfj/vzC4qjg@2ajq//@8/JRUAA "Pyth – Try It Online")
---
Luckily, Pyth offers most of what we need out of the box, so we just need to call the operations necessary.
```
Sz # Sort the input
c2z # Chop the input into two equal pieces (first longer if needed)
_ # Reverse the chopped elements
s # Join them back together
q # Check for equality
```
[Answer]
# perl -plF//, 49 bytes
```
push@F,splice@F,0,(@F+1)/2;$_="@F"eq"@{[sort@F]}"
```
[Try it online!](https://tio.run/##K0gtyjH9/7@gtDjDwU2nuCAnMzkVyDDQ0XBw0zbU1DeyVom3VXJwU0otVHKoji7OLypxcIutVfr/Py8/JZWrqDSXKyU1L5@rKDP3X35BSWZ@XvF/3ZwCN319AA "Perl 5 – Try It Online")
Splits a line of input into characters, which are placed in `@F`. We remove the first half and tag it to the end. We then check whether the array is the same if we sort it -- if the result is the same, the string was a half sort, if not, it wasn't.
Outputs 1 for a half sort, the empty string when not.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒHṚFṢƑ
```
A monadic Link accepting a list of characters which yields `1` (truthy) if a half-sort and `0` (falsey) otherwise.
**[Try it online!](https://tio.run/##ARkA5v9qZWxsef//xZJI4bmaRuG5osaR////cnVt "Jelly – Try It Online")**
### How?
Fairly straightforward in Jelly, pretty much just implements the challenge specification directly...
```
ŒHṚFṢƑ - Link: list of characters (full Unicode, but works with ASCII only too)
ŒH - split it into two halves (first half 1-longer if odd in length)
Ṛ - reverse
F - flatten back to a list of characters
Ƒ - is invariant under?:
Ṣ - sort
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
{I2äRJQ
```
[Try it online](https://tio.run/##yy9OTMpM/f@/2tPo8JIgr8D///PyU1IB) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/6kqjw0uCvAL/6/yPVsrLT0lV0lEqKs0FkimpefkgTmaeUiwA).
**Explanation:**
```
{ # Sort the characters in the (implicit) input
I # Push the input again
2ä # Split it into 2 equal-sized parts (first part will be longer for odd lengths)
R # Reverse this pair
J # Join them back together to a string
Q # And check if both strings are equal
# (after which the result is output implicitly)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
≔⪫⮌⪪θ⊘⊕Lθωθ¬⊙θ∧κ‹ι§θ⊖κ
```
[Try it online!](https://tio.run/##RYxNCsIwFIT3niLLF4gn6CrgwkoRqScIyaMNTV/Mj1FPHxNc@MHADMOMXlXUXrlaZUp2Ibh4SzBjwZgQ7g9nMwTBzsoVNDCSjrgj5eYnpCWvEHhHsFdT4MPhFi1luPoMkj59KsnAJtiEKYFtMY9k8N2bE/7fNv5jqDU@93os7gs "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for true, nothing for false. Explanation:
```
≔⪫⮌⪪θ⊘⊕Lθωθ
```
Split the string into half, reverse, and join.
```
¬⊙θ∧κ‹ι§θ⊖κ
```
Check whether any characters are less than their predecessor.
[Answer]
# APL+WIN, ~~39~~ 36 bytes
Prompts for input of string:
```
(⍴s)=+/1,2≤/⎕av⍳(-⍴s)↑s,(⌈.5×⍴s)↑s←⎕
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5rPOrdUqxpq61vqGP0qHOJPlA6sexR72YNXbDEo7aJxToaj3o69EwPT4eLALUD1f0HGvA/jUs9Lz8lVZ0LyCgqzQXTiYmJYDolNS8fIpEJlOACAA "APL (Dyalog Classic) – Try It Online")
Explanation:
```
(⌈.5×⍴s)↑s take the front half of the string rounding up for odd number length
(-⍴s)↑s,prepend the original string and take trailing characters up to
the original length of string
⎕av⍳ get code points
(⍴s)=+/1,2≤/ check that successive code points are ascending, sum the
result and compare to length of string; equal = 1 = true, not equal = 0 = false
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~82~~ 81 bytes
```
i;e;r;l;f(char*s){l=strlen(s);for(r=1,e=i=~-l/2;++i%l-e;)r&=s[-~i%l]/s[i%l];e=r;}
```
[Try it online!](https://tio.run/##TU9da4QwEHy/X7EIlliV@yj3ULbpS@mvUB@Crm1E45FYCIj31@3qne2FDcPuzgyzZfpVlvOskdBii7Uov5V9dtHYSjfYloxwEda9FVYeE5JaXtN2f8I41mGbEkb2SbosvXJX7F22AJK0OM2d0kZEMO6A32oKNitAwhjk/vOU@9cP/ucggcf@JZjwQTGQG9xdZfqKFrb96RZQSi1QkenXqe42qTYDkL@QH6hatTAeE7jVgetO46NALNyGKQdkeIMzQhw3W@rNzDOhFrcsTRHh3/JieV2LIHSQvkNYQehyw2k2agI@4atZL/8TNcVmMe2m@Rc "C (gcc) – Try It Online")
[Answer]
# [Python 3.8](https://docs.python.org/3/), ~~68~~ 46 bytes
```
lambda s:sorted(s)==s[(h:=-~len(s)//2):]+s[:h]
```
An unnamed function accepting a list of characters which yields `True` if a half-sort and `False` otherwise.
**[Try it online!](https://tio.run/##HcxNCsIwEEDhtZ5idslga0E3EogXqV1EktJA80NmXEipV49tVx@8xctfnlK8P3Kpo37V2YS3NUCKUmFnJaHWsyeW1MtJ6fY3u7jFrruhGi7Uq2nAOqYC7IjBR5AiJutEA6J8wo4xZse6mI7qg0B1PuXiI0uxrNA@YVnFdZsEw3L/NDAeImL9Aw "Python3.8 – Try It Online")**
---
Turns out the straightforward way is terser!
Original 68 byter in Python 2:
```
lambda s:all(i==~-len(s)/2for i in range(len(s))if(s[1:]+s)[i]<s[i])
```
[Try it online!](https://tio.run/##JYxBDoIwEEXXeorZtRNBI0siXARZjKHVJu2UtHVhCF69Utz8l/y8vPmTXp6brLt7tuQeE0FsyVppuu5bW8Uy4qXRPoABwxCIn0r@bzRaxuHajqeIgxlvcRvMRU0qpmJLwX5SogIR3q6AiAomxX5/jRPYHg9zMJykWFaoe1hWcd4ijpIsnQr0TkTMPw "Python 2 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 33 bytes
```
->a{a.rotate(-~a.size/2)==a.sort}
```
[Try it online!](https://tio.run/##DcY7DoAgEAXAq2xjogWY2ONFCMVT12ghmBVD/F4dnWpk7448mqxaXNASIiKX6oXe5pPrpjLmb5D45CJZHwYm2RcCQAP7QDIvTjP66aI73bTSaJPuJ8jm6Mkf "Ruby – Try It Online")
Takes input as an array of characters (which feels like cheating). Simply rotates the array by half its length and checks whether this is equal to the sorted array.
[Answer]
# [Clojure](https://clojure.org/), 48 bytes
```
#(=(sort %)(flatten(reverse(partition-all 2%))))
```
[Try it online!](https://tio.run/##FYsxCsMwDAD3vkI4BOShS/e8JGQQtQwujpTKSsnvXeeGGw7uXfVzGndMnCH3CRdsag5zxFzJnQWNf2yN8SDz4kXlSbXCa46DHh@YtPEX1gvWIJo4QLBzHyai4cSidyp72DY8rIhXAcxw3fsf "Clojure – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
s½Ṙ∑=
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJzwr3huZjiiJE9IiwiIiwibm9kZSJd)
```
s # Input Sorted
½ # Split into two halves
Ṙ∑ # And concatenated reversed
= # Equals original input?
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
oḍ↔c?
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WU9B51rFBKS8wpBrJrH@7qrH24dcL//Ic7eh@1TUm2//8/WikvPyVVSUcpMTERSBaV5gLJlNS8fBAnE8RJTEoGkknJYOlUkEh5Bkg2Jz8vPbVIobikKDMvHchPTUvPAKpNATIdHR1BZKIj2FwwCRVRVIoFAA "Brachylog – Try It Online")
Outputs through success or failure.
```
o The input sorted
ḍ and split in half (with the *second* half longer if the length is odd),
↔ with those halves reversed
c and concatenated,
? is the input.
```
] |
[Question]
[
For reference as to what the tower of Hanoi is, either Google it or look on the [Wikipedia](http://en.wikipedia.org/wiki/Tower_of_Hanoi) page.
Your code should be able to do 2 things, and they are the following:
* Accept user input that specifies the number of discs at the starting point of the Hanoi tower
* Create output in a fashion of your choosing (so long as it is somehow logical) to show the solution to the tower puzzle.
An example of logical output would be the following (using a 4 disc start):
`L1L2C1L1R-2R-1L1L2C1C-1R-2C1L1L2C1`
`L` represents the left peg, `C` represents the center peg and `R` represents the right peg and the numbers are how far to move the disk on that peg and in what direction. Positive numbers represent the number of pegs moving towards the rightmost peg (because the disks start on the leftmost peg).
The [rules to tower of Hanoi](http://en.wikipedia.org/wiki/Tower_of_Hanoi) are simple:
* Only one disk may be moved at a time.
* Each move consists of taking the upper disk from one of the pegs and sliding it onto another peg, on top of the other disks that may already be present on that peg.
* No disk may be placed on top of a smaller disk.
The disks start on the leftmost peg, largest on the bottom, smallest on the top, naturally.
[Answer]
## Python, 76 chars
```
def S(n,a,b):
if n:S(n-1,a,6-a-b);print n,a,b;S(n-1,6-a-b,b)
S(input(),1,3)
```
For instance, for N=3 it returns:
```
1 1 3 (move disk 1 from peg 1 to peg 3)
2 1 2 (move disk 2 from peg 1 to peg 2)
1 3 2 (move disk 1 from peg 3 to peg 2)
3 1 3 ...
1 2 1
2 2 3
1 1 3
```
[Answer]
## Perl - 54 chars
```
for(2..1<<<>){$_--;$x=$_&-$_;say(($_-$x)%3,($_+$x)%3)}
```
Run with `perl -M5.010` and enter the number of discs on stdin.
Output format:
One line per move, first digit is from peg, second digit is to peg (starting from 0)
Example:
```
02 -- move from peg 0 to peg 2
01
21
02
10
12
02
```
[Answer]
## GolfScript (31 25 24 chars)
```
])~{{~3%}%.{)3%}%2,@++}*
```
With thanks to Ilmari Karonen for pointing out that my original `tr`s/permutations could be shortened by 6 chars. By decomposing them as a product of two permutations I managed to save one more.
Note that factoring out the `3%` increases length by one character:
```
])~{{~}%.{)}%2,@++}*{3%}%
```
---
Some people have really complicated output formats. This outputs the peg moved from (numbered 0, 1, 2) and the peg moved to. The spec doesn't say to which peg to move, so it moves to peg 1.
E.g.
```
$ golfscript hanoi.gs <<<"3"
01021201202101
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
↑≠⁰İr
```
[Try it online!](https://tio.run/##yygtzv7//1HbxEedCx41bjiyoej////GAA "Husk – Try It Online")
Each `n` in the output represents moving disk `n` to the next available peg (wrapping cyclically).
### Explanation
```
İr The ruler sequence [0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, ...]
↑ Take while...
≠⁰ ... not equal to the input.
```
[Answer]
## Perl, 75 79 chars
Totally stealing Keith Randall's output format:
```
sub h{my($n,$p,$q)=@_;h($n,$p^$q^h($n,$p,$p^$q),$q*say"@_")if$n--}h pop,1,3
```
Invoke with `-M5.010` for the `say`.
(I think this can be improved if you can find a way to make use of the function's return value instead of just suppressing it.)
[Answer]
# SML, 63
```
fun f(0,_,_)=[]|f(n,s,t)=f(n-1,s,6-s-t)@[n,s,t]@f(n-1,6-s-t,t);
```
call function `f(n,s,t)` with:
* n number of disks
* s starting point
* t goal point
[Answer]
## Bash (64 chars)
```
t(){ tr 2$1 $12 <<<$s;};for((i=$1;i--;))do s=`t 1`01`t 0`;done;t
```
Posting this one despite being more than twice the length of the GolfScript one because I like the reuse of `t` to serve as `echo $s`.
[Answer]
# Scala,~~92~~ ~~88~~ 87 chars
```
def?(n:Int,a:Int,b:Int){if(n>0){?(n-1,a,a^b)
print(n,a,b);?(n-1,a^b,b)}};?(readInt,1,3)
```
**Output format**
Say number of disk=3 then,
```
(1,1,3)(2,1,2)(1,3,2)(3,1,3)(1,2,1)(2,2,3)(1,1,3) (disk number,from peg, to peg)
\---------------------------/
Move 1 ... Move n
```
[Answer]
## C, 98 92 87 chars
Implements the most trivial algorithm.
Output is in the form `ab ab ab` where each pair means "move the top disc from peg a to peg b".
**EDIT**: Moves are now encoded in hex - 0x12 means move from peg 1 to peg 2. Saved some characeters.
**EDIT**: Reads the number from stdin, rather than parameter. Shorter.
Example:
`% echo 3 | ./hanoi`
`13 12 32 13 21 23 13`
```
n;
h(d){n--&&h(d^d%16*16,printf("%02x ",d,h(d^d/16))),n++;}
main(){scanf("%d",&n);h(19);}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
2*Ṗọ2
```
[Try it online!](https://tio.run/##y0rNyan8/99I6@HOaQ939xr9///fFAA "Jelly – Try It Online")
`0` move the smallest disk one space to the right (wrapping back to the start if necessary)
`1` move the second-smallest disk to the only other legal column
`2` move the third-smallest disk to the only other legal column
etc.
## Algorithm
We can see the solution of the Towers of Hanoi problem recursively; to move a stack of size *n* from *A* to *B*, move a stack of size *n*-1 from *A* to *C*, then the disk of size *n* from *A* to *B*, then move a stack of size *n*-1 from *B* to *C*. This produces a pattern of the following form (in the output format used by this program):
```
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2 …
```
We can observe that this sequence is [A007814](http://oeis.org/A007814) on the OEIS. Another possible definition of the sequence is "the *k*th (1-based) element of the sequence is the number of zeroes at the end of the number *k* when it's written in binary". And that's what the program here is calculating.
## Explanation
First, we calculate the number of moves in the solution, 2*n*-1. It turns out to be shortest to actually calculate one extra move and discard it later, so this is `2*`, i.e. 2 to the power of something. (The only input we've taken so far is the command line argument, so that gets used by default.)
Next, we use Jelly's builtin for calculating the number of zeroes at the end of a number in base *b*; that's `ọ*b*`. As we're calculating in binary, it's `ọ2`. All we need to do is to apply this builtin to the numbers from 1 to 2*n*-1 inclusive.
There are two simple ways to iterate over a range of numbers in Jelly, `€` and `R`, and my earlier attempts at this problem used one of these. However, in this case, it's possible to go slightly shorter: `Ṗ`, when given a number as input, will let you do an iteration that stops one element short (in general, `Ṗ` is a builtin used to process all but one element of something). That's exactly what we want in this case (because `2*` generates one too many elments), so using it to link `2*` and `ọ2` into `2*Ṗọ2` gives us a 5-byte solution to the problem.
[Answer]
## Awk, 72 chars
```
function t(n,a,b){if(n){t(n-1,a,a^b);print n,a,b;t(n-1,a^b,b)}}t($0,1,3)
```
Output format is same as [Keith Randall](https://codegolf.stackexchange.com/users/67/keith-randall)'s one.
```
awk -f tower.awk <<< "3"
1 1 1
2 1 1
1 1 1
3 1 3
1 1 1
2 1 3
1 1 3
```
[Answer]
### Bash script, ~~100~~ 96 chars
```
t(){ [[ $1<1 ]] && return
t $(($1-1)) $2 $(($2^$3))
echo $@
t $(($1-1)) $(($2^$3)) $3
}
t $1 1 3
```
Output format is same as [Keith Randall](https://codegolf.stackexchange.com/users/67/keith-randall)'s one.
```
1 1 3
2 1 2
1 3 2
3 1 3
1 2 1
2 2 3
1 1 3
```
**Edit**: Saved 4 chars by [peter](https://codegolf.stackexchange.com/users/194/peter-taylor)'s comment.
[Answer]
# J, 23 bytes
## binary numbers solution
```
2&(+/@:~:/\)@#:@i.@^~&2
```
This solution uses the binary counting method described [in this video](https://www.youtube.com/watch?v=2SUvWfNJSsM).
Which is to say, I generate the binary digits from `1` up to `2^n`, then take infixes of length 2 and compare each bit to the corresponding bit of the previous number, and check if they're unequal. The number of unequal bits is the output for that move.
Output, eg, for 3 disks, where smallest disk is labeled 1:
```
1 2 1 3 1 2 1
```
`1` means "move the smallest disk one peg right, looping back to the first peg if needed"
`n`, for all other `n`, means "move disk `n` to a legal peg" (there will always be exactly one)
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/43UNLT1HazqrPRjNB2UrRwy9Rzi6tSM/mtyKekpqKfZWqkr6CjUWimkFXNxpSZn5CukKRj/BwA "J – Try It Online")
## recursive solution
```
((],[,])$:@<:)`]@.(1=])
```
Same output as the above solution, but the logic here makes the recursive nature of the problem clearer.
Visualizing it as a tree also emphasizes this point:
```
4
/ \
/ \
/ \
/ \
/ \
/ \
/ \
3 3
/ \ / \
/ \ / \
/ \ / \
2 2 2 2
/ \ / \ / \ / \
1 1 1 1 1 1 1 1
```
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/zU0YnWidWI1VawcbKw0E2Id9DQMbWM1/2tyKekpqKfZWqkr6CjUWimkFXNxpSZn5CukKRj/BwA "J – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 73 bytes
Putting R on the map. Inspired by [Keith Randall's answer][1] with simplified input, print only end and start peg to save 2 bytes. Also 0-indexed pegs.
```
f=function(n,s=0,e=2){if(n){f(n-1,s,3-s-e)
print(c(s,e))
f(n-1,3-s-e,e)}}
```
[Try it online!](https://tio.run/##JckxCsAgDEDR3ZMkEKGts6eRBFxiMXYSz55Ku3z4vO4uWR4tozYFJcsHcb5wVgHFuRNPMkrRImO4e9UBBYwYMfz40f61XCChvw "R – Try It Online")
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 19 bytes
```
3|(-⍪0 1⍪2∘-)⍣⎕,⍨⍪⍬
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/4b12joPupdZaBgCCSNHnXM0NV81LsYqEjnUe8KoNCj3jX/gQr/p3GZAgA "APL (Dyalog Classic) – Try It Online")
output is a 2-column matrix of ints in {0,1,2} - from peg, to peg
[Answer]
# [K (ngn/k)](https://github.com/ngn/k), 23 bytes
```
{3!x{-x,(,0 2),1+x}/()}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqtpYsaJat0JHQ8dAwUhTx1C7olZfQ7P2f5qC6X8A "K (ngn/k) – Try It Online")
[Answer]
# JavaScript (ES6), 45b
```
h=(n,f,a,t)=>n?h(--n,f,t,a)+f+t+h(n,a,f,t):''
```
e.g. calling `h(4, 'A', 'B', 'C')` (move 4 discs from peg A to peg C using auxiliary peg B)
returns `'ABACBCABCACBABACBCBACABCABACBC'` (move a disc from peg A to peg B, move a disc from peg A to peg C, move a disc from peg B to peg C, etc.)
] |
[Question]
[
>
> This is a follow-up of
> [CodeGolf - Ignore the noise #1](https://codegolf.stackexchange.com/questions/50381/quickgolf-ignore-the-noise-1)
> the only problem being that Barry has made things even worse for us. Lets see what happened
>
>
>
### Update
I've added code to create random input and expected output because I'm not that good at explaining what I want, and I guess that sometimes words are more misleading than code (isn't that always?)
### Description
Another method in *Dumb Corp*'s API gives us the current price a provider is giving us for an item, the optimal price we would be making maximum sales with and the tendency of that price compared to previous prices as a string `UP` or `DOWN`. We need to decide if we should remove the item from the shop or wait.
### Input
```
80,90,UP
150,100,DOWN
65,65,UP
1618,1618,DOWN
840,1200,DOWN
54,12,UP
30,1,UP
```
For a huge input sample demo with expected output, put the following code (js) in your browsers console and it should output valid random input for testing.
```
var output = "";
var result = "";
for(i=10;i--;){
var currentPrice = Math.floor(Math.random() * 10000) + 1;
var optimalPrice = Math.floor(Math.random() * 10000) + 1;
var tendency = Math.round(Math.random())?"UP":"DOWN";
var tresult = "WAIT\n";
if((currentPrice > optimalPrice && tendency == "UP") ||
(currentPrice < optimalPrice && tendency == "DOWN")){
tresult = "STOP\n";
}
output +=currentPrice+","+optimalPrice+","+tendency+"\n";
result +=tresult;
}
console.log(output);
console.log(result);
```
As always we will have a variable `G` as our input, however if your language makes it easier for you to simply read the input, that's also fine. The format is constant, and follow the format `int,int,string`
### Desired Output
You're the brains of this operation, Barry should be doing this calculation on the server, but we can't count on him as you should know. You need to output `WAIT` if the tendency is towards the optimal price, or `STOP` if the tendency is towards loses.
In other words, with the `80,90,UP` as input, we know that there is a product with current price of 80 and optimal price of 90 with a tendency to rise up, so we should `WAIT`. On the other hand, `840,1200,DOWN` means the product price is going down and our optimal price is higher, so we should stop losses by outputting `STOP`.
If the two prices are identical, output `WAIT` regardless of the tendency.
Each product in a new line, single word per line:
```
WAIT
WAIT
WAIT
WAIT
STOP
STOP
STOP
```
Please, when possible, provide a way of verifying that your code is working since we can't all know just by looking at the syntax. As always, **use as few characters as possible** and remember that you're not competing against other languages necessarily, your competing against languages with similar syntax
[Answer]
# Perl, 35
```
#!perl -pl
/,/;$_=$`-$'&&$`>$'^/D/?STOP:WAIT
```
Test [me](http://ideone.com/Zwmujl).
[Answer]
# CJam, ~~31~~ ~~29~~ 27 characters
```
"㫅㍸ꕆ敟鸢Ꝓ約䢫솓儓隆뻨"2G#b128b:c~
```
This is just an encoded version of the following code (in order to make use of the scoring by characters):
```
r{',/:~3<)(f*~<"STOP""WAIT"?Nr}h
```
[Run all test cases here.](http://cjam.aditsu.net/#code=r%7B'%2C%2F%3A~3%3C)(f*~%3C%22STOP%22%22WAIT%22%3FNr%7Dh&input=80%2C90%2CUP%0A150%2C100%2CDOWN%0A65%2C65%2CUP%0A1618%2C1618%2CDOWN%0A840%2C1200%2CDOWN%0A54%2C12%2CUP%0A30%2C1%2CUP)
There might be a way to shorten this by encoding `STOP` and `WAIT`, but I'm quite happy with the rest.
## Explanation
The code is surrounded by a loop which reads on line at a time, processes it, then pushes a newline, and reads the next line... The loop terminates once `r` returns an empty string (i.e. after all lines have been processed). That's this bit:
```
r{ ... Nr}h
```
As for processing each line, I'm making use of the fact that upper case letters are variables in CJam, so I can eval some of the input.
```
',/:~3<)(f*~<"STOP""WAIT"?
',/ e# Split the input on commas.
:~ e# Eval each of the three resulting strings. The first two
e# will yield the prices, the third will dump a bunch of
e# values corresponding to the variables DNOPUW in the array.
3< e# Truncate to three elements, so we only get the prices and
e# the values corresponding to U (0) and D (13).
)( e# Slices off that variable value and decrement it, to get
e# something negative for UP and positive for DOWN.
f* e# Multiply both numbers by that value. So if we had UP then
e# both numbers will be negative now, otherwise they'll just
e# be scaled without affecting their relative size.
~< e# Unwrap the array and check which element is larger.
"STOP""WAIT"? e# Select the desired output string based on this boolean.
```
So the catch is that for `UP` we invert the relative sizes of the prices, so that we can cover all cases with a single inequality at the end.
[Answer]
# Perl, ~~77~~ 73 bytes
```
while(<>){@p=split",";print($p[0]<$p[1]and$p[2]=~/D/?"STOP":"WAIT")."\n"}
```
Here's how it works:
* `while(<>)` parses every line.
* `@p=split","` splits it by every comma. It's using the default Perl operator, `$_` (which is where the line is stored.)
* `print (ternary)` determines what to print.
* `$p[0]<$p[1]and$p[2]=~/D/` asks if the current price is less than the price we want, and it's going down (by checking for a D.)
* `(condition)?(if):(else)` is the ternary operator.
* If our condition earlier matched, it'll output `STOP`. Otherwise, it'll output `WAIT`.
I'm assuming there is no trailing newline on the input - a trailing newline produces an extra `WAIT`.
Thanks to Alex A. for helping me save 4 bytes!
[Answer]
# C, 85
```
c;main(i,j){for(;scanf("%d,%d,%c%*s",&i,&j,&c)>0;)puts(i-j&&i>j^c<70?"STOP":"WAIT");}
```
Test [me](http://ideone.com/eVxRXY).
[Answer]
# R, ~~95~~ 108
R and strings, not really friends:)
```
eval(parse(t=sub("U","<",sub("D",">",gsub("(.*),(.*),(.).*","cat(if(\\1\\3=\\2)'WAIT\n'else'STOP\n')",G)))))
```
Input is the character vector `G` then changes each string into an `if` statement that is evaluated.
**Edit** Messed up my interpretation of the rules. Fix cost a few characters.
```
> G=c(
+ '80,90,UP',
+ '150,100,DOWN',
+ '65,65,UP',
+ '1618,1618,DOWN',
+ '840,1200,DOWN',
+ '54,12,UP',
+ '30,1,UP'
+ )
> eval(parse(t=sub("U","<",sub("D",">",gsub("(.*),(.*),(.).*","cat(if(\\1\\3=\\2)'WAIT\n'else'STOP\n')",G)))))
WAIT
WAIT
WAIT
WAIT
STOP
STOP
STOP
>
```
[Answer]
**Ruby - 89 Chars**
```
G.split.map{|a|b,c,d=a.split(?,);puts (b.to_i>=c.to_i)^(e=d[2])&&(b!=c||e)?'STOP':'WAIT'}
```
[RubyFiddle](http://rubyfiddle.com/riddles/99ebf/4)
With help from to bluetorange!
[Answer]
# Python 3, ~~89~~ ~~84~~ 82 bytes
```
for l in G:a,b,c=l.split(',');print('WSATIOTP'[a==b or(int(a)<int(b))^(c<'U')::2])
```
Explanation:
```
for l in G: #For every line in G:
a,b,c=l.split(','); #Split the line into three strings.
print() #Print the contained expression.
'WSATIOTP' #'WAIT' and 'STOP' interleaved.
[ ::2] #Select every other character.
or #If either expression is true, pick 'WAIT'
a==b
( )^( ) #Select 'WAIT' if exactly one is true.
int(a)<int(b) #If first number < second number.
c<'U' #If c is 'DOWN'
```
[Answer]
# Matlab, ~~100~~ 90 bytes
Not as small as I'd like - especially the conversion from boolean to the strings is very long. I tried to shave off a few bytes by switching to Octave, but apparently %c is not supported for textscan yet in Octave.
```
B=textscan(G,'%f,%f,%c%s\n');xor(B{1}>=B{2},B{3}==85);C(a)={'STOP'};C(~a)={'WAIT'};char(C)
```
Personally I think it is nice that this solution is the only one so far that does not use split :)
EDIT: originally solved the equals situation way too complex.
[Answer]
## Javascript ECMAScript 6, 112b
```
var O="";for(let E of G.split("\n"))[A,B,C]=E.split(","),O+=("U"<C||-1)*(A-B)>0?"STOP\n":"WAIT\n";console.log(O)
```
Only on ECMAScript 6 compatible browsers
### Explanation
```
("U"<C||-1)*(A-B)>0?"STOP\n":"WAIT\n"
```
It makes use of the fact that if we ask if 0 is true it will return false, so we can say 1 for `UP`, -1 for `DOWN`. Then we multiply that by the difference of current price and optimal price to make both of them work for the *greater than 0* part
If condition is met, return `STOP`, otherwise (including equal values) return `WAIT`
Needs further golfing
[Answer]
# Javascript (*ES6*), 82 80 79 bytes
*Edit: -2 using @JuanCortés multiplication method*
*Edit: -1 using a trick to reduce the multiplication method*
```
alert(G.replace(/(.+),(.+),(.)+/g,(x,c,o,t)=>(c-o)*~{P:-2}[t]>0?'STOP':'WAIT'))
```
**Commented:**
```
alert( // alert final output after replacement
G.replace(/(.+),(.+),(.)+/g, // capture group for sections of each line
// (.)+ captures only the last character
// . doesn't match newlines, so this runs for each line
(x,c,o,t)=> // use a function to calculate each replacement string
(c - o) // calculate difference, negative for o>c
* // multiply by
~{ P: -2 }[t] // { P: -2 }[t] returns -2 for UP ('P') -2, else undefined
// ~-2 => 1, ~undefined => -1
> 0 // if result > 0 (muplication of negatives or positives)
? 'STOP' : 'WAIT' // return corresponding replacement string
)
)
```
**Snippet Demo:**
```
function run(){
G = input.value;
/* start solution */
alert(G.replace(/(.+),(.+),(.)+/g,(x,c,o,t)=>(c-o)*~{P:-2}[t]>0?'STOP':'WAIT'))
/* end solution */
}
```
```
<textarea id="input" cols="25" rows="7">80,90,UP
150,100,DOWN
65,65,UP
1618,1618,DOWN
840,1200,DOWN
54,12,UP
30,1,UP</textarea><br />
<button id="run" onclick="run();">Run</button>
```
**Revision History:**
```
// 80
alert(G.replace(/(.+),(.+),(.)+/g,(x,c,o,t)=>(c-o)*(t>'N'||-1)>0?'STOP':'WAIT'))
// 82
alert(G.replace(/(.+),(.+),(.)+/g,(x,c,o,t)=>+c>o&t>'N'|+c<o&t<'P'?'STOP':'WAIT'))
```
[Answer]
# C- 91 Bytes
Because C has to be there somewhere
Now looks very similar to @nutki version although working out whether to output "STOP" or "WAIT" is diffferent.
Ungolfed-
```
main(i,j)
{
char c[5];
while(scanf("%i,%i,%s",&i,&j,c)+1)
puts((j-i)*(*c-70)<0?"STOP":"WAIT");
}
```
Golfed-
```
main(i,j){char c[5];while(scanf("%i,%i,%s",&i,&j,c)+1)puts((j-i)*(*c-70)<0?"STOP":"WAIT");}
```
The old one
```
Ungolfed-
int main()
{
int i,j;
char *c="";
while(scanf("%i,%i,%s",&i,&j,c)+1)
{
if(i<j)
{
if(*c-68)
printf("WAIT\n");
else
printf("STOP\n");
}
if(i>j)
{
if(*c-68)
printf("STOP\n");
else
printf("WAIT\n");
}
if(i==j)
printf("WAIT\n");
}
return 0;
}
Golfed
#define W printf("WAIT\n");
#define S printf("STOP\n");
int main(){int i,j;char *c="";while(scanf("%i,%i,%s",&i,&j,c)+1){if(i<j){if(*c-68)W else S}if(i>j){if(*c-68)S else W}if(i==j)W}return 0;}
```
I'll continue to try to cut it down
[Answer]
# Python 3 - ~~108~~ ~~106~~ ~~102~~ 97B
```
for l in G:a,b,c=l.split(',');s=int(a)-int(b);d=c<'E';print(['WAIT','STOP'][(s<0)*d+(s>0)*(1-d)])
```
Work in progress...
] |
[Question]
[
I was working on a math question with a friend of mine, and we decided to write a script that finds the answer. The original question is as follows:
>
> The difference of two natural numbers is 2010 and their greatest common denominator is 2014 times smaller than their lowest common multiply. Find all the possible solutions.
>
>
>
We started writing the program independently of each other, and when it worked we decided to golf it up to get the least amount of bytes we could manage. We ended up with this beautiful line of code at a marvelous 89 bytes.
```
from fractions import*;print[i for i in range(10**6)if i*(i+2010)/gcd(i,i+2010)**2==2014]
```
We wanted to see if anyone manages to write a shorter piece of code, that enumerates the first 1 million i's. If you are brave enough to compete, you may use any language you like, but we would prefer Python 2 to be able to compare your code with ours.
Usual rules apply, shortest bytes win.
The standard code golf loopholes apply. [Standard "loopholes" which are no longer funny](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny)
Have fun!
[Answer]
# Mathematica, 8 bytes
```
{4,5092}
```
Proof that 4 and 5092 are the only solutions: The original problem can be rewritten as
>
> x (x + 2010) = 2014 GCD(x, x+2010)2
>
>
>
Let's write *x* as 2a2 3a3 5a5… and *x* + 2010 as 2b2 3b3 5b5… Then the equation becomes
>
> 2a2+b2 3a3+b3 5a5+b5… = 2014 22min(a2,b2) 32min(a3,b3) 52min(a5,b5)…
>
>
>
Since 2014 = 2 × 19 × 53, we have
>
> ap + bp = 2min(ap, bp) + { 1 if p ∈ {2, 19, 53}, 0 else }
>
>
>
Thus
>
> ap = bp if p ≠ 2, 19, 53
>
> ap = bp±1 else
>
>
>
Thus
>
> x + 2010 = 2±1 19±1 53±1 x
>
>
>
There are only 8 possible choices, and we could easily check that 4 and 5092 are the only positive integer solutions.
Wait, I hear people screaming standard loophole…
# Mathematica, 45 bytes
```
Select[Range[9^7],2014GCD[#,s=#+2010]^2==s#&]
```
[Answer]
## [Pyth](https://github.com/isaacg1/pyth) ~~27~~ 25
```
J2010fq+J4/*T+TJ^iTJ2U^T6
```
[Try it online.](http://isaacg.scripts.mit.edu/pyth/index.py)
This uses your algorithm fairly naively... I might be able to come up with something better...
Basically filters out values that don't meet the criterion from `range(10**6)`
Thanks to @xnor for pointing out in chat that `gcd(x,x+2010)==gcd(x,2010)`
[Answer]
# Python 3, 84 bytes
FryAmTheEggman's already suggested how to make your solution 88 bytes so I won't post that. But I thought I'd show how you can get even fewer bytes in Python 3:
```
from fractions import*
x=10**6
while x:y=x+2010;x*y-gcd(x,y)**2*2014or print(x);x-=1
```
*(Thanks for FryAmTheEggman for tips)*
This doesn't work in Python 2 because `print`'s not a function.
I'm not sure if we're allowed, but if we could use `9**9` instead of `10**6` that'd be another byte.
[Answer]
# R, 75 chars
```
for(a in 1:1e6){q=1:a;b=a+2010;if(a*b/max(q[!a%%q&!b%%q])^2==2014)print(a)}
```
With line breaks:
```
for(a in 1:1e6){
q=1:a
b=a+2010
if(a*b/max(q[!a%%q&!b%%q])^2==2014)print(a)
}
```
[Answer]
## GolfScript (41 bytes)
>
> The difference of two natural numbers is 2010 and their greatest common denominator is 2014 times smaller than their lowest common multiple. Find all the possible solutions.
>
>
>
Call the numbers `am` and `bm` where `gcd(a, b) = 1` and wlog `b > a`. Then the difference is `m(b-a) = 2010`, and `lcm(am, bm) = abm = 2014m` so `ab=2014`.
Factors of 2014 are
```
1 * 2014
2 * 1007
19 * 106
38 * 53
```
and those which have differences that divide into 2010 are
```
1007 - 2 => m = 2, solution is 4, 2014
53 - 38 => m = 134, solution is 5092, 7102
```
Since I'm operating in a language which doesn't have built-in GCD or LCM, I think this analysis probably shortens the program:
```
44,{).2014{.2$/\@%!}:,~\2$- 2010,***}%0-`
```
where `44` is `floor(sqrt(2014))`.
It is possible to get quite close using a naïve loop:
```
10 6?,1>{.2010+.2${.@\%.}do;.*2014*@@*=},`
```
[Answer]
# Perl6 ~~61~~ ~~58~~ ~~56~~ ~~54~~ 52
A fairly direct translation of your source gives
```
for ^10**6 ->\i{i.say if i*(i+2010)/(i gcd(i+2010))**2==2014}
```
`gcd` is an infix op in Perl6.
`^10**6` is short for `0 ..^ 10**6`, where the `^` means exclude this number from the range.
---
Of course `i gcd (i+2010)` is the same as `i gcd 2010` so I can save 3 characters
```
for ^10**6 ->\i{i.say if i*(i+2010)/(i gcd 2010)**2==2014}
```
If I use `$_` instead of `i` I can save another couple of characters. ( `.say` is short for `$_.say` )
```
for ^10**6 {.say if $_*($_+2010)/($_ gcd 2010)**2==2014}
```
I can save another couple of characters by using `... && .say` instead of `.say if ...`, because I don't need a space on both sides of `&&` like I do for `if`.
```
for ^10**6 {$_*($_+2010)/($_ gcd 2010)**2==2014&&.say}
```
Since I did both of the previous "optimizations" I can use the statement modifier form of `for`, which means I can remove `{` and `}`.
```
$_*($_+2010)/($_ gcd 2010)**2==2014&&.say for ^10**6
```
I think that is as short as I can go without using a different algorithm.
[Answer]
# J, 26 bytes
```
I.((*.=+.*4--)2010+])i.1e6
4 5092
```
Those damned 2-byte verbs... :)
[Answer]
# Dyalog APL, 29 characters
```
a←⍳10 ⍝ the integers up to 10
a
1 2 3 4 5 6 7 8 9 10
2010+a ⍝ corresponding integers at distance 2010
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
a∨2010+a ⍝ GCD-s between elements of a and 2010+a
1 2 3 2 5 6 1 2 3 10
⍝ All APL functions (e.g. + and ∨) are prefix-or-infix, right-associative,
⍝ and of the same precedence.
a∧2010+a ⍝ LCM-s
2011 2012 2013 4028 2015 2016 14119 8072 6057 2020
⍝ For which of them is the LCM 2014 times the GCD?
(a∧2010+a)=2014×a∨2010+a
0 0 0 1 0 0 0 0 0 0
⍝ 0 means false, 1 means true
⍝ Filter the elements of "a" corresponding to the 1-s
((a∧2010+a)=2014×a∨2010+a) / a
4
⍝ Let's abstract this as a function by using curlies.
⍝ Omega (⍵) stands for the right argument.
{((⍵∧2010+⍵)=2014×⍵∨2010+⍵) / ⍵} a
4
⍝ Up to a million instead of up to ten:
{((⍵∧2010+⍵)=2014×⍵∨2010+⍵) / ⍵} ⍳1e6
4 5092
⍝ Hey, we can save a few characters by making 2010 the left argument, alpha (⍺)
2010 {((⍵∧⍺+⍵)=2014×⍵∨⍺+⍵) / ⍵} ⍳1e6
4 5092
⍝ Remove a pair of parens by using the switch operator ⍨
⍝ An "operator" occurs to the right of a function and modifies its behaviour.
⍝ In this case A f⍨ B means the same as B f A
⍝ Left and right are swapped, hence "switch".
2010 {⍵ /⍨ (⍵∧⍺+⍵)=2014×⍵∨⍺+⍵)} ⍳1e6
4 5092
⍝ That's 32 characters (modulo whitespace). Not bad, but we can do better.
⍝ A "fork" is a sequence of 3 functions in isolation: f g h
⍝ It is evaluated as: ⍺(f g h)⍵ ←→ (⍺ f ⍵)g(⍺ h ⍵)
⍝ If the first item is an array instead of a function: A f g ←→ {A} f g
⍝ Forks are right-associative: f g h k l ←→ f g (h k l)
2010 {⍵ /⍨ (⍺(⊢∧+)⍵)=2014×(⍺(⊢∨+)⍵)} ⍳1e6
4 5092
⍝ The "right tack" function (⊢) simply returns its right argument
⍝ Let's abuse forks a little further:
2010 {⍵ /⍨ ⍺((⊢∧+)=(2014×(⊢∨+)))⍵} ⍳1e6
4 5092
⍝ ... and more
2010 {⍺ (⊢(/⍨)((⊢∧+)=(2014×(⊢∨+)))) ⍵} ⍳1e6
4 5092
⍝ But {⍺ f ⍵} is equivalent to f
2010 (⊢(/⍨)((⊢∧+)=(2014×(⊢∨+)))) ⍳1e6
4 5092
⍝ Note that now we are not mentioning ⍺ and ⍵ at all.
⍝ This is called "point-free style" or "tacit programming".
⍝ Removing some unnecessary parens and whitespace:
2010(⊢(/⍨)(⊢∧+)=2014×⊢∨+)⍳1e6
4 5092
⍝ How many characters?
⍴'2010(⊢(/⍨)(⊢∧+)=2014×⊢∨+)⍳1e6'
29
```
[Answer]
# PARI/GP, 42 bytes
```
[n|n<-[1..8!],2014*gcd(n,t=n+2010)^2==n*t]
```
I feel that there is an extremely elegant solution using GP's `fordiv` construct but it couldn't compete with this solution for sheer brevity.
[Answer]
## Racket, 72 chars
```
(filter(λ(i)(=(/(*(+ i 2010)i)(expt(gcd(+ i 2010)i)2))2014))(range 1e6))
```
[Answer]
## Haskell, 52 chars
```
show [x|x<-[1..6^8],x*(x+2010)==2014*(gcd x 2010)^2]
```
Works in the Haskell interactive environment GHCi.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 19 bytes
```
g²×⁽¥Æ=×
ȷ6ç+⁽¥µ$$Ƈ
```
[Try it online!](https://tio.run/##y0rNyan8/z/90KbD0x817j209HCb7eHpXCe2mxxerg0WOLRVReVY@///AA)
The TIO link has been modified to only search up to \$10^4\$, as the outputs are both below that, in order to finish within 60 seconds on TIO.
And of course, the "cheaty method" is that, as \$4\$ and \$5092\$ are the only two integers (as [proven by](https://codegolf.stackexchange.com/a/42319/66833) [kennytm](https://codegolf.stackexchange.com/users/32353/kennytm)) for which this is true, this 5 byter works:
```
4,⁽Ñ[
```
[Try it online!](https://tio.run/##y0rNyan8/99E51Hj3sMTo///BwA "Jelly – Try It Online")
## How it works
```
g²×⁽¥Æ=× - Helper link. Takes n on the left and n+2010 on the right
g - gcd(n, n+2010)
² - gcd(n, n+2010)²
⁽¥Æ - Compressed integer; 2014
× - 2014×gcd(n, n+2010)²
× - n²+2010n
= - Are the two equal?
ȷ6ç+⁽¥µ$$Ƈ - Main link. Takes no input
ȷ6 - Yield 1000000
$$Ƈ - Yield [1, 2, ..., 1000000] and keep those, i, for which the following is true:
⁽¥µ - Compressed integer; 2010
+ - i+2010
ç - Call the helper link with i on the left and i+2010 on the right
```
] |
[Question]
[
A skyline is an array of positive integers where each integer represents how tall a building is. For example, if we had the array `[1,3,4,2,5,3,3]` this would be the skyline in ascii art:
```
#
# #
## ###
######
#######
```
A maximal rectangle is a rectangle that cannot be extended in any direction while being contained in the skyline. For example, the following is a maximal rectangle:
```
#
# #
## ###
AAAAAA
#AAAAAA
```
While the following is not:
```
#
# #
## #BB
####BB
#####BB
```
Since you can extend it to the left like so:
```
#
# #
## CCC
###CCC
####CCC
```
This would be a maximal rectangle.
Your task is to take a skyline as input (list of positive integers) and return the area of the smallest maximal rectangle. You can assume the length of the input is at least 1.
# Testcases
```
[1] -> 1
[1,1] -> 2
[2,2,2] -> 6
[3,2,3] -> 3
[3,2,1] -> 3
[6,3,1,5] -> 4
[1,5,5,5] -> 4
[5,5,5,1] -> 4
[1,2,3,4] -> 4
[1,2,3,4,5] -> 5
[1,1,1,5,1,1,1] -> 5
[10,3,1,1,1,1,1,3,10] -> 6
```
This is code-golf, so shortest bytes in any language wins!
[Answer]
# J, 61 bytes
```
0<./@-.~[:,[:(~.*#-I.@~:)"1@|:[:(0-.~#;._1@,~&0)"1@|.@|:#"+&1
```
[Try it online!](https://tio.run/##XY9Ba8JAEIXv@RWPBLS2m@mOm3jYVggKQqGo9Oqhh3ZD0kOFNiiC5K/HcRMlymOXfd/sPGZ@mpCGOaYWQyhoWDkxYf7xvmj0Kz1nMdUbqzb2oabHKH6jrLajkLOjFaSlGL3QJ2eqHmiPSSpR@DTgZhS4r2ILxhQ5uDXj1qjOTrwdK1ELjAdGgLkHXUvSJaRn9ZEH978kRyUtSvvo0nqBZ6X@5iBYzgi/zn2j2mLn/sr8gKpw/w77siqwWvdnZy1xfJW8dX@CiSzASG92EWBgmhM "J – Try It Online")
*I believe the final test case should be 6 and that 6 3 1 5 should return 4. Needs to be verified by OP.*
Grotesquely long, but perhaps an interesting idea...
## how
Consider `6 3 1 5`.
* `#"+&1` Expand into a sideways bar chart of ones:
```
1 1 1 1 1 1
1 1 1 0 0 0
1 0 0 0 0 0
1 1 1 1 1 0
```
* `|.@|:` Rotate it regular-ways:
```
1 0 0 0
1 0 0 1
1 0 0 1
1 1 0 1
1 1 0 1
1 1 1 1
```
* `[:(0-.~#;._1@,~&0)"1` For each row, count the runs of ones:
```
1 0
1 1
1 1
2 1
2 1
4 0
```
* `|:` Transpose:
```
1 1 1 2 2 4
0 1 1 1 1 0
```
* `[:(~....I.@~:)"1` For each row, get the nub (uniq) and the nub sieve positions (ie, positions of first occurence of each). Eg with row 1:
```
1 1 1 2 2 4 - Row 1
1 2 4 - Uniq
0 3 5 - Positions of first occurrences
```
* `#-` Subtract the positions from length:
```
0 3 5 - Positions of first occurrences
6 3 1 - Length minus positions
```
* `*` Multiply those by the uniq values: gives us sizes of maximal rectangles. (Remember we're still showing just 1 row even though there are multiple)
```
1 2 4 - Uniq
6 3 1 - Length minus positions
-------------
6 6 4 - Elementwise product
```
* `0<./@-.~[:,` Flatten, remove zeroes, take the min.
```
4
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 56 bytes
```
Min[(aTr/@Pick[a+0(l=SplitBy[#,#<a&]),Min/@l,a])/@#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@983My9aI/H9pIUhRfoOAZnJ2dGJ2gYaObbBBTmZJU6V0co6yjaJarGaOkCF@g45OomxmvoOyrFq/wOKMvNKopUVdO0U0qKVY2MV1BT0HRSqqw1rdRSqDXUUwLSRjgIIgZjGYKYxgglTaApBIJ4pjAeTA@nQUTBB5UEVg@wAI1MYA6LLAKzKEBWBRAxA0mYwWVOoSyCSxrW1/wE "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Port of [*@Jonah*'s J answer](https://codegolf.stackexchange.com/a/242991/52210):
```
Å1ζRεÅγsÏ}ζεDÙþ©kygα®*}ß
```
[Try it online](https://tio.run/##AT8AwP9vc2FiaWX//8OFMc62Us61w4XOs3PDj33Ots61RMOZw77CqWt5Z86xwq4qfcOf//9bMSwzLDQsMiw1LDMsM10) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w62G57YFndt6uPXc5uLD/bXntp3b6nJ45uF9h1ZmV6af23honVbt4fn/df5HRxvqGOuY6BjpmAJp41gdhWhDMKEDpoyAEkYghjGQYQxjQFWYgiCICWbARI1A5iExIUqA5oGU6EDNNTQAShnCIZBtABI2A4uaQuwxBDsoFgA).
A port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/243019/52210) is 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) as well:
```
0.øŒʒD¦¨ß‹Á2£P}妨Wsg*}ß
```
[Try it online](https://tio.run/##yy9OTMpM/f/fQO/wjqOTTk1yObTs0IrD8x817DzcaHRocUDtua0gkfDidK3aw/P//4821DHWMdEx0jEF0saxAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/A73DO45OOjXJ5dCyQysOz3/UsPNwo9GhxQG157aCRMKL07VqD8//r/M/OtpQx1jHRMdIxxRIG8fqKEQbggkdMGUElDACMYyBDGMYA6rCFARBTDADJmoEMg@JCVECNA@kRAdqrqEBUMoQDoFsA5CwGVjUFGKPIdhBsQA).
**Explanation:**
```
Å1 # Map each value in the (implicit) input-list to a list of that
# many 1s
ζ # Zip/transpose; swapping rows/columns,
# using a space as filler by default for rows of unequal length
R # Reverse the rows
ε # Map over each row:
Åγ # Run-length encode it, pushing a list of values and lengths
# separated to the stack
s # Swap so the values are at the top
Ï # Only leave the lengths at truthy (==1) positions
}ζ # After the map: zip/transpose with space filler again
ε # Map over each row:
D # Duplicate the current list
Ù # Uniquify the items in the copy
þ # Remove all spaces by only keeping digits
© # Store this in variable `®` (without popping)
k # Get the first 0-based index of each unique value in the list
α # Calculate the absolute difference of each index with
yg # the length of the current row-list
®* # Multiply the values to list `®` at the same positions
}ß # After the map: pop and push the flattened minimum
# (which is output implicitly as result)
```
```
0.ø # Surround the (implicit) input-list with leading/trailing 0
Œ # Pop and push all sublists
ʒ # Filter this list of lists by:
D # Duplicate the sublist
¦¨ # Remove the first and last items in the copy
ß # Pop and push the minimum
‹ # Check for each value in the list if this minimum is larger
Á # Rotate the list of checks once towards the right
2£ # Pop and leave just the first two
P # Product to check if both of them are truthy
}ε # After the filter: map over the remaining sublists:
¦¨ # Remove the first and last items again
W # Push the minimum (without popping the list)
# (this will be an empty string for empty lists)
s # Swap so the list is at the top
g # Pop and push its length
* # Multiply the length by this minimum
}ß # After the map: pop and push the minimum integer (ignoring any
# empty strings)
# (which is output implicitly as result)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ø0jẆµḢ»Ṫ<aṂ)ȦƇ§Ṃ
```
A monadic Link accepting a list of positive integers that yields a positive integer.
**[Try it online!](https://tio.run/##y0rNyan8///wDIOsh7vaDm19uGPRod0Pd66ySXy4s0nzxLJj7YeWA1n///@PNtcxBEJjIATSsQA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///wDIOsh7vaDm19uGPRod0Pd66ySXy4s0nzxLJj7YeWA1n/D7c/alrz/390tGEsl060oQ6YMtIBQhDDGMgwhjHAUmY6xjqGOqYQxaYgCGKCGTpQI4BadEyQmDDVIGgKJiEKDcBGwSCQbQCxCcQGWhoLAA "Jelly – Try It Online").
### How?
```
Ø0jẆµḢ»Ṫ<aṂ)ȦƇ§Ṃ - Link: list of positive integers, H
Ø0 - [0,0]
j - join with S -> [0,h1,h2,...,hn,0]
Ẇ - all contiguous sublists
µ ) - for each sublist, S:
Ḣ - remove & yield the head from S
Ṫ - remove & yield the tail from S (yields 0 if S was empty)
» - maximum
< - less than? (vectorises across the altered S)
Ṃ - minimum (of the altered S; 0 if S is empty)
a - logical AND (vecorises)
Ƈ - filter keep those for which:
Ȧ - any and all? (i.e. non-empty and all non-zero)
§ - sums
Ṃ - minimum
```
---
Also at 16 ([TIO](https://tio.run/##y0rNyan8/9/u0cZ1jxpmJj7cufhR0xqDh7v6Du081v5wZ9Ph6T7HuoBCQOb/w@1Axv//0dGGsVw60YY6YMpIBwhBDGMgwxjGAEuZ6RjrGOqYQhSbgiCICWboQI0AatExQWLCVIOgKZiEKDQAGwWDQLYBxCYQG2hpLAA "Jelly – Try It Online")), and perhaps more elegant:
```
>Ɱ’aṣ€0Ẏ¹ƇṂ×LƊ€Ṃ - Link: H
Ɱ’ - map across decremented values of H with:
> - H greater than? (vectorises)
a - logical AND H (vectorises)
ṣ€0 - split each at zeros
Ẏ - tighten
¹Ƈ - keep the truthy (i.e. non-empty) ones
Ɗ€ - for each:
Ṃ - minimum
L - length
× - multiply
Ṃ - minimum
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 64 bytes
*-2 bytes by Arnauld*
```
a=>Math.min(...a.map((n,i)=>(g=d=>a[i+=d]>=n&&g(d)+n)(-1,g(1))))
```
[Try it online!](https://tio.run/##hc9LDoMgEAbgfU/hygwRUXztsCfoCYwLImptFEw1vb5FEzShmjILSL4fhnnxD5@qdzfOvlSiXhq2cJY/@PwkQyeBEMLJwEcAiTvEcmiZYDkvOo@JMmfSdVsQyJMIfIpboEivpVJyUn1NetVCAwUtEXKCwHHozRa8W2RbhHUZzWyNtcZG4zOll0pxupbxxPZNj/vJ733dGyf//OiQnsyN119s@3Uq1M/QvfQ5NNm7nc226DHT8gU "JavaScript (Node.js) – Try It Online")
Simply find the *smallest* one from all *maximal* rectangles:
```
* * * * # * *
* * * * # * * * * # * * * *
** *** ## *** *# *** ** *** ** #** ** ### ** ###
****** ##**** *#**** ###### ***#** ***### ***###
####### *##**** **#**** *###### ****#** ****### ****###
```
Above example show all possible maximal rectangles with height \$a\_i\$.
[Related](https://codegolf.stackexchange.com/a/242997/44718)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
⊞θ⁰FLθFιF⬤⟦⊖κι⟧›⌊✂θκι¹§θλ⊞υ×⁻ικ⌊✂θκι¹I⌊υ
```
[Try it online!](https://tio.run/##dU7LCsIwELz7FTluYAVr9eSpKIigUNBb6aGkqw1NUsxD/PuYFPHmXoadmZ1ZMXRWTJ2KsQ5ugCeyFd8t7pNlcCbz8IninM27/GKlFDQHEpY0GU89jByZbJEdLXWeLFykkTpouCopKEeOSUdW8OSr/Mn09M6s4mnYXBuQ3aQml0@Dg2TOmf9zePqxttJ42HfO/wpDFmJsmgJL3OAatwnLto3Ll/oA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞θ⁰
```
Push a guard value to the input array. (This also simplifies the iteration as in my answer to the linked question I had to increment variables all over the place but here I effectively get a free increment.)
```
FLθFι
```
Loop over all of the sublists of the original array.
```
F⬤⟦⊖κι⟧›⌊✂θκι¹§θλ
```
Check that the minimum of this sublist is greater than both of its neighbours.
```
⊞υ×⁻ικ⌊✂θκι¹
```
Calculate the size of this maximal rectangle.
```
I⌊υ
```
Output the minimum of all the sizes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
>Ḣ×\׫\ŒɠÄ×QƲ
ŻÇÐƤẎ¹ƇṂ
```
[Try it online!](https://tio.run/##y0rNyan8/9/u4Y5Fh6fHHJ5@aHXM0UknFxxuOTw98NgmrqO7D7cfnnBsycNdfYd2Hmt/uLPp/@F2zcj//6MNY3WiDXVApJEOEAJpYyBtDKUhsqYgCGSBaagYUI2OCYIFlgeaowNSDaZBfAOglCEcAtkGQFEzsKAp2AaQoHEsAA "Jelly – Try It Online")
*Should* work now. Filters each suffix to the longest prefix which wouldn't contain suffixes of other suffixes' rectangles, computes the area of each maximal rectangle sharing its left edge with each of those substrings, and returns the smallest non-zero such area.
```
>Ḣ×\׫\ŒɠÄ×QƲ Monadic helper link: compute areas from "maximal zone" of suffix
Ḣ Remove the first item
> and compute the mask of which remaining items are greater.
×\ Zero any ones after the first zero,
× then multiply with corresponding elements of
«\ the cumulative minima.
Œɠ Compute the lengths of runs of equal minima,
Ä take the cumulative sums of those,
× and multiply with corresponding elements of
QƲ the nub of the cumulative minima.
ŻÇÐƤẎ¹ƇṂ Main link
Ż Prepend a 0.
ÇÐƤ Call the helper on each suffix,
Ẏ concatenate the resulting lists of areas,
¹Ƈ remove 0s,
Ṃ and return the minimum.
```
[Answer]
*Doesn't work as intended... yet*
# [Husk](https://github.com/barbuz/Husk), ~~16 bytes~~
```
▼M₁¹
*⁰▲mLfo=⁰▼Q
```
[Try it online!](https://tio.run/##yygtzv7//9G0Pb6PmhoP7eTSetS44dG0Tbk@afm2YOaewP///0cb6hjrmOgY6ZgCaeNYAA "Husk – Try It Online")
### Explanation
```
▼M₁¹ translates to ▼M₁⁰⁰
M₁⁰⁰ for each number in the input, call the second line with (each number N, the whole input A)
▼ take the minimum of the results
*⁰▲mLfo=⁰▼Q translates to *⁰▲mLfo=⁰▼Q²
Q² each contiguous sublist of A
fo=⁰▼ filter out the sublists where it's minimum value is N
mL take the lengths
*⁰▲ multiply N with the maximum of the lengths
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes
```
aMin[SequenceCases[a,b_/;Min@b==#:>Tr[0b+#]]&/@a]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@z/x/aSFvpl50cGphaWpecmpzonFqcXRiTpJ8frWQHGHJFtbZSu7kKJogyRt5dhYNX2HxNj/AUWZeSXRygq6dgpp0UBRBTUFfQeF6mrDWh2FakMdBTBtpKMAQiCmMZhpjGDCFJpCEIhnCuPB5EA6dBRMUHlQxSA7wMgUxoDoMgCrMkRFIBEDkLQZTNYU6hKIpHFt7X8A "Wolfram Language (Mathematica) – Try It Online")
```
/@a for each height:
SequenceCases[a,b_ :>Tr[0b+#]] areas of maximal rectangles
/;Min@b==# with that height
Min[ ] smallest
```
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 24 bytes.
```
nM(mn*×l)<(bn*^fgF^.ge)
```
In the interested of transparency, since hgl is under heavy development some features used in this answer were only merged into master recently. I wanted to make this answer to show them off.
## Explanation
There are two parts to this first is `bn*^fgF^.ge` this takes every element of the list and gives contiguous sections where all elements are above that height.
So for example `[1,9,3,5,6,7,5]`:
```
[9]
[9] [7]
[9] [6,7]
[9] [5,6,7,5]
[9,3,5,6,7,5]
[1,9,3,5,6,7,5]
```
Note that there are some duplicates, e.g. `[9]` appears here several times. In addition they are not actually output in this order show here but this is fine for demonstration purposes.
Each list here represents the footprint of a box which cannot be widened. The height of that box is then the minimum element that appears in the footprint.
The second part is `nM(mn*×l)`. This takes each element produced in the first step and multiplies its length by its minimum to get the size of the box. It takes the overall minimum as the result.
## Reflections
This feels a tad long, we have some really powerful tools here like `nM` and `fgF`, but we mostly get bogged down in other stuff. Unfortunately I have few thoughts on how this could be improved.
] |
[Question]
[
*Inspired by [this Numberphile video](https://www.youtube.com/watch?v=R4OvBB9KHMA).*
---
## What is planing?
In order to 'plane' a sequence of digits, you need to:
1. Identify the lengths of the 'runs' (adjacently repeated digits) in the sequence. Non-repeated digits count as runs of one.
2. Decrease the length of each run by one. Runs of length 1 become length 0.
3. Reconstruct the sequence, using the new lengths for the runs. Runs that are now length 0 are deleted altogether.
For example, planing the sequence \$1, 1, 2, 3, 3, 3, 4, 4, 5, 6\$ would give us:
1. The length of the runs is demonstrated below:
```
1 1 2 3 3 3 4 4 5 6
|____||_||_______||____||_||_|
2 1 3 2 1 1
```
2. Decreasing the length of the runs gives us:
```
1 1 2 3 3 3 4 4 5 6
|____||_||_______||____||_||_|
2 1 3 2 1 1
becomes: 1 0 2 1 0 0
(0s removed): 1 2 1
```
3. Using these lengths to reconstruct the original sequence, e.g. the first run is now length 1, the second length 0, etc., gets us our 'planed' sequence:
```
1 3 3 4
|_||____||_|
1 2 1
```
Note that the planing operation can also have a strength: the above example used a strength of \$1\$, but a strength of \$2\$ would decrease the length of each run by 2, strength \$3\$ by 3, etc.. In cases where this would make the length of a run go negative, the length just becomes 0.
E.g. with the above example and a strength of \$2\$, we get:
```
Input: 1 1 2 3 3 3 4 4 5 6
|____||_||_______||____||_||_|
Run lengths: 2 1 3 2 1 1
Lengths - 2: 0 -1 1 0 -1 -1
Rounded to 0: 0 0 1 0 0 0
Output sequence:
3
|_|
1
```
## Challenge
Given a limit \$n\$, a strength \$s\$ and a base \$b\$, output the base-10 result of having 'planed' each of the numbers from 1 to \$n\$ in base \$b\$ with the strength \$s\$.
The basic steps to complete this are as follows:
1. Make a list \$x\$ of numbers 1 to \$n\$, including both 1 and \$n\$.
2. Convert each number \$x\$ in the list to base \$b\$.
3. Treating each digit of the base-\$b\$ number as an item of a sequence, plane the sequence with strength \$s\$.
4. Reading the sequence as a set of digits (or 0, in case of an empty sequence), convert the planed sequence back from base \$b\$ digits to a base 10 number.
5. Output this number and repeat for all values in \$x\$.
## Examples
Given \$b\$ = 4, \$n\$ = 250, and \$s\$ = 2:
```
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,5,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,10,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
```
\$b\$ = 2, \$n\$ = 112, and \$s\$ = 3:
```
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,3,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0]
```
\$b\$ = 12, \$n\$ = 1024, and \$s\$ = 1:
```
[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,1,13,1,1,1,1,1,1,1,1,1,1,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,2,2,26,2,2,2,2,2,2,2,2,2,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,3,3,3,39,3,3,3,3,3,3,3,3,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,4,4,4,4,52,4,4,4,4,4,4,4,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,5,5,5,5,5,65,5,5,5,5,5,5,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,6,6,6,6,6,6,78,6,6,6,6,6,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0]
```
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
* Standard loopholes apply.
* I/O may be taken/given in any acceptable, valid format. Each number in the sequence should be delimited in some way by a non-numeric digit, but the precise delimiting is up to you.
* You may assume \$b>1\$, \$n>1\$, and \$s>0\$. You may also assume reasonable upper bounds for these, depending on the capacity for number types in your language.
* If you wish, input arguments may have an offset (e.g. an input of \$1\$ to \$b\$ represents base 2), but this must be stated in your answer and should not impede the ability of your code to cover the whole range of allowed inputs.
* Output may be given as floats, ints, strings, etc., but all values must represent a numeric, base-10 value - so e.g. no `NaN`s in place of 0s.
### Test code
For reference, here is the (shoddily-written and ungolfed) code I used to generate the above examples (in console JS):
```
// called as f(length, base, strength)
const f = (l, b, s) => {
return JSON.stringify(
Array(l)
.fill(0)
.map((e, i) => i + 1)
.map(e =>
e.toString(b)
.split('')
.reduce((a, e, i, A) => (A[i - 1] && A[i - 1] === e) ?
[...a.slice(0, -1), [a.slice(-1)[0][0], a.slice(-1)[0][1] + 1]] :
[...a, [e, 1]], [])
.map(e => [e[0], Math.max(0, e[1] - s)])
.map(e => e[0].repeat(e[1]))
.join('')
)
.map(e => parseInt(e, b) || 0),
null,
1
)
}
```
Note that this implementation is not a complete/valid one, as it only works for \$b \le 36\$. As per the instructions, complete answers should be able to handle any base in theory, up to the integer limit of your language.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
*How* is Japt winning this (so far) despite the need for an essentially unnecessary byte in the `,`? It's making me feel like I've done something wrong!
```
õÈìV,ÈòÎcsW
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9cjsVizI8s5jc1c&input=MjUwCjQKMg)
```
õÈìV,ÈòÎcsW :Implicit input of integers U=n, V=b & W=s
õ :Range [0,U]
È :Map
ìV : Convert to base V digit array
, : Does nothing (more accurately, prevents the V from becoming the first parameter of the next function)
È : Pass through the following function and convert back to decimal
ò : Partition between elements where
Î : The sign of their difference is truthy (not zero)
c : Flat map
sW : Slice off the first W elements
```
Or, to avoid that pesky comma, we can reverse the second 2 inputs and do this, where `NÌ` is the last element of the array of all inputs:
```
õÈìNÌÈòÎcsV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9cjsTszI8s5jc1Y&input=MjUwCjIKNA)
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~32~~ 23 bytes ([SBCS](https://github.com/abrudz/SBCS))
Full program. Prompts for \$n\$ then \$s\$, then \$b\$.
```
∊⎕(⊣⊥∘∊⎕↓¨⊤⊂⍨1,2≠/⊤)¨⍳⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKNdoQBIdj3qm6rxqGvxo66ljzpmQPiP2iYfWvGoa8mjrqZHvSsMdYwedS7QB/I1gaK9m4EKQLr/K4BBAZeRqQGXEZcJl66uLhdMzNDQiMsYKIoiZmBkwmXIZWgEAA "APL (Dyalog Extended) – Try It Online")
`‚éï`‚ÄÉprompt for \$n\$
`‚ç≥`‚ÄÉgenerate \$x\$, the **i**ndices 1 through \$n\$
`⎕(`…`)¨` establish the following tacit function, then apply it using each element of \$x\$ as right argument, and a prompted-for \$b\$-value as left argument:
‚ÄÉ`‚ä§`‚ÄÉencode \$x\_i\$ in base \$b\$
 `2≠/` pairwise difference
‚ÄÉ`1,`‚ÄÉprepend 1, giving a mask of starting positions of runs
 `⊤⊂⍨` use that to partition \$x\_i\$ re-encoded in base \$b\$
 `⎕↓¨` prompt for \$s\$ and use that to drop the first that many elements from each run
‚ÄÉ`‚àò‚àä`‚ÄÉenlist (flatten), then:
 `⊣⊥` evaluate in base \$b\$
`‚àä`‚ÄÉenlist (flatten)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
LIвεγIδ.$˜²β
```
[Try it online!](https://tio.run/##ASQA2/9vc2FiaWX//0xJ0LLOtc6zSc60LiTLnMKyzrL//zI1MAo0CjI "05AB1E – Try It Online")
```
L # push range [1 .. n]
I–≤ # convert each number to base b (represented as lists of digits)
ε # for each list of digits:
γ # group equal adjacent digits
Iδ.$ # remove s digits from each group
Àú # flatten into a single list of digits
²β # convert back from base b
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
Ḋ¡€F
b€ŒgÇ€ḅ
```
[Try it online!](https://tio.run/##y0rNyan8///hjq5DCx81rXHjSgKSRyelH24H0g93tP7//9/I1OC/yX8jAA "Jelly – Try It Online")
## How it works
```
Ḋ¡€F - Helper link. Takes a list of grouped digits D
€ - Over each group:
¬° - Do the following S times:
Ḋ - Dequeue; remove the first element
F - Flatten
b€ŒgÇ€ḅ - Main link. Takes n on the left and b on the right
b€ - Convert each integer 1 to n to base b
Œg - Over each, group adjacent equal digits
Ç€ - Run the helper link over each list of groups
·∏Ö - Convert each back from base b
```
[Answer]
# [R](https://www.r-project.org/), ~~107~~ 104 bytes
```
function(x,b,s)Map(function(n,l=0:n,r=rle(n%/%b^l%%b))sum(rep(r$v,t<-pmax(r$l-s,0))*b^(1:sum(t)-1)),1:x)
```
[Try it online!](https://tio.run/##bY1NCsIwEEb3nsPAjEwxiboJ9gheodKUCIV0TPMjuX2sG0Fw9/jeBy@24Ed29@TW4nhyfXsUnvL8ZKhkKeFtDPCdmHwvDVPso3fA4ijs4IWwiKksEF2AuH9RvnZhGevGvkskEQ92AGU@l4ydQiRlKrbCfk4ZfvugL5LOpBF3/71SmjSdNt/e "R – Try It Online")
Goes out-of-range for the last test-case: add [+7 bytes](https://tio.run/##dY5NCsIwEIX3nsPAjEwxiXVT7BG8QqUpUQpxGvMjvX2MG0HQ3eN9H7wXincj20u0j2x5sn25Zp7SvDCsZCjiefTwqZhcLzu33GoySKEPzgKLvTCDE8IgxnyHYD2E7ZPSqfH3ca3ZNZEk4s4MoLq3krBRiKS6FUtmN8cE3zdAHyW1pBE3v7lSmjQd/nOpW6pOnSkv) to extend the range of amenable calculations and fix this.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~14~~ 12 bytes
```
ɾvτƛ⁰nĠvȯf¹β
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C9%BEv%CF%84%C6%9B%E2%81%B0n%C4%A0v%C8%AFf%C2%B9%CE%B2&inputs=250%0A4%0A2&header=&footer=)
```
…æ # 1...n
vτ # Foreach, base convert
∆õ # Foreach...
⁰ # Strength
nĠ # Each one grouped
vȯ # Trim each
f # Flatten
¹β # Convert back
```
[Answer]
# JavaScript (ES6), 92 bytes
*Saved 1 byte thanks to @Shaggy*
Expects `(b)(s)(n)`.
```
b=>s=>F=n=>n?[...F(n-1),(t=0,p=g=x=>x?g(x/b|0,x%=b,x==p?k++:k=1,p=x,k>s?t=t*b+x:0):t)(n)]:[]
```
[Try it online!](https://tio.run/##hcq7DoIwFADQ3a9gMdxrS20RF5JbNn4CGQCF8EhLpDEd/HfsbExMznim5tVs3XNcXWLs/bH3tLekN9IlGdKmqIQQJZhEIQdHkq80kCftiwH8uX1L7o/Uck@0FjNj@UwqFM9nvRWO3KllPpeYOwSDdV7Ve2fNZpeHWOwAPUQZQooQpVeJYrKjgZjHGLEovpkYD185zEvISqX/czigAplmP/L@AQ "JavaScript (Node.js) – Try It Online")
### Commented
```
b => s => // outer functions taking b and s
F = n => // F = inner recursive function taking n
n ? // if n is not equal to 0:
[ ...F(n - 1), // do a recursive call to F with n - 1
( // and append the next value to the array:
t = 0, // t = final value converted back from base b
p = // p = previous term in the sequence
g = x => // g is a recursive function taking x
x ? // if x is not equal to 0:
g( // do a recursive call to g ...
x / b | 0, // ... using floor(x / b)
x %= b, // reduce x modulo b
x == p ? // if it's equal to the previous term:
k++ // increment k
: // else:
k = 1, // reset k to 1
p = x, // update the previous term p to x
k > s ? // if k is greater than the strength:
t = t * b // update t to t * b + x
+ x // (i.e. add the digit x in base b)
: // else:
0 // do nothing
) // end of recursive call
: // else (x = 0):
t // return t
)(n) // initial call to g with x = n
] // end of array
: // else (n = 0):
[] // stop the main recursion
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 28 bytes
```
{(y/*'(1=#'?:')#z':y\)'1+!x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6rWqNTXUtcwtFVWt7dS11SuUreqjNFUN9RWrKjl4kqLNjI1sDaxNo5VqFMwIBIaEq3SiGiVxiTYbgrExLmBFvYT638jIDQk3gnUdwBRAQBKAoaGRtZG1iaEkgB+Ww0J+gC3fkOwbnOKfE2U/QAiAn+I)
Takes three arguments: `n => x`, `b => y`, and `s => z`. `s` needs to be offset by +1 (i.e. to apply a strength of `2`, pass in `3`).
* `(...)'1+!x` call the code in parenthesis on each value from `1..n`
* `y\` convert each value to base `b`, returning a list of digits
* `z':` take `s`-length rolling windows of the converted digits
* `(1=#'?:')#` filter out rolling windows containing more than one distinct digit
* `*'` take the first digit of each remaining rolling window
* `y/` convert back to original base
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes
```
b€Œr_⁵ݤŒṙḅ
```
[Try it online!](https://tio.run/##ASoA1f9qZWxsef//YuKCrMWScl/igbXFu8KkxZLhuZnhuIX///8yNTD/NP9bMl0 "Jelly – Try It Online")
Takes three arguments in the form `n b [s]`.
*-1 byte thanks to @cairdcoinheringaahing*
## Explanation
```
b€Œr_⁵ݤŒṙḅ Main dyadic link
b€ Convert each to base b (implicitly casting n to [1..n])
Œr Run-length encode
_ Subtract [vectorized]
¤ (
⁵ The third argument
Ż Prepend a 0
¤ )
Œṙ Run-length decode
·∏Ö Convert from base b
```
[Answer]
# Scala, 155 bytes
```
b=>s=>1.to(_)map{y=>(0+:Seq.unfold(y){q=>Option.when(q>0)(q%b,q/b)}:\(0,0,0)){case(d,(c,p,a))=>if(d==p)(c+1,d,a)else(1,d,(a/:Seq.fill(c-s)(p))(_*b+_))}._3}
```
[Try it in Scastie!](https://scastie.scala-lang.org/vCGPOAcOTmau7tvijj7NPA)
It's been a while since I wrote an answer as complex as this. Takes `(b)(s)(n)`. Explanation coming soon.
Ungolfed:
```
b => s => n =>
//Make a range [1,n]
1.to(n) map { y => //Perform these operations on each y
//Build a list of digits in base b (reversed)
val toBaseB = Seq.unfold(y) { //Start with y as the quotient
q => //q is the quotient at each iteration
//If q is still greater than 0, add another digit
Option.when(q > 0)(
q % b, //The next digit is q mod b
q / b //The next quotient is the floor of q√∑b
)
}
//Plane and convert back to decimal here
((0 +: toBaseB) //First prepend a 0 so that the last digit of toBaseB is counted
:\ (0, 0, 0) //First accumulator (count 0, prev item 0, sum 0)
) {
//d is the current digit, p is the previous digit,
//c is the current run length,
//and a is the sum (partially converted to decimal)
case (d, (c, p, a)) =>
if (d == p) //If the run's still going
(c + 1, d, a) //Increase the run length
else //Otherwise
(1, d, //Set the run length to 1 and set p to the new d
//Add the current run to the sum
//Make a sequence of (c-s) p's
//Convert to decimal, and add the previous sum (a) to that
(a /: Seq.fill(c - s)(p))(_ * b + _)
)
}._3 //Only get the sum (planed sequence converted to decimal)
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
RbŒgṫ⁵$Ḋ$€F$€ḅ
```
[Try it online!](https://tio.run/##y0rNyan8/z8o6eik9Ic7Vz9q3KrycEeXyqOmNW4g4uGO1v///xuZGvw3@W8EAA "Jelly – Try It Online")
```
RbŒgṫ⁵$Ḋ$€F$€ḅ Main Link; takes [n, b, s]
R Range from 1 to n
b Base convert (each) into base b
Œg Group equal runs (vectorizes)
( )-$€ For each number
( )-$ - For each run
ṫ⁵$ - Tail; remove the first s-1 items
Ḋ - Dequeue; remove the first element
F - Flatten
·∏Ö Convert (each) back from base b
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
möB⁰ṁ↓²gB⁰ḣ
```
[Try it online!](https://tio.run/##yygtzv7/P/fwNqdHjRse7mx81Db50KZ0MGfH4v///xv/N/pvaGgEAA "Husk – Try It Online")
```
m # map the following function
·∏£ # across all the integers from 1 to arg3
# the 'plane' function:
ö # composition of 4 commands
B⁰ # get the digits in base arg2
g # group equal values
ṁ↓² # drop the first arg1 elements from each group, and flatten
B⁰ # interpret as digits in base arg2
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
NθNηIEEN↨⊕ιη↨Φι∧¬‹μθ⬤…⮌…ιμθ⁼νλη
```
[Try it online!](https://tio.run/##TY3LCsIwEEX3/YosZyAurMuualEQtIh/ENOBBJK0ebTg18dUEbu4i3vmXEYqEeQoTM4XN82pn@2TAnhsqm1Xpd@Ddgk6ERPcxPTJVkHOjiJSYTKQJZdoAF2gwt/lrE0qouasdQP0Y4IrxQiWM786rTHQvaShTo0TPGihUEZ/UnZ29XzJyc/CRHCcGUT8fkFscj5UdbXf13m3mDc "Charcoal – Try It Online") Link is to verbose version of code. Takes inputs in the order `s`, `b`, `n`. Explanation:
```
NθNη
```
Input `s` and `b`.
```
N Input `n`
E Map over implicit range
⊕ι Current index, 1-indexed
↨ η Convert to base `b`
E Map over list
ι Current base conversion
Φ Filtered where
μ Current position
¬‹ θ Is not less than `s`
‚àß Logical And
…⮌…ιμθ Last `s` elements
⬤ All satisfy
ν Inner element
⁼ Equal to
λ Outer element
↨ η Convert from base `b`
I Cast to string
Implicitly print each result on its own line
```
] |
[Question]
[
Let's say you have a stack, which at the start contains `a b c` in this order (`a` is on the top). You are given the required output stack, in any reasonable format (a list, a string, etc.), e.g. `[a, c, b]` (here `a` is on the top, below it `c` and below it `b`). You can also take the input reversed if you want, e.g. `[b, c, a]` where a is in the top
Your task is to output the **shortest** sequence of operations to achieve that stack formation, and you may assume that there is such sequence, and it's shorter than 10 moves:
* `s` - swap the top two elements of the stack, `a b c -> b a c`
* `d` - duplicate the top element of the stack, `a b c -> a a b c`
* `t` - swap (or rotate) the top three elements of the stack, `a b c -> b c a`
You may call the input/operations whatever you want, as long as it's consistent.
### Examples
```
['a', 'c', 'b'] -> st
([a b c] [b a c] [a c b])
['a','a','b','c'] -> d
['a','b','a','b','c'] -> sdtsdt
([a b c] [b a c] [b b a c] [b a b c] [a b b c] [a a b b c] [a b a b c]) (sdttdt is also valid)
['c','b','a'] -> ts
```
This is an example ungolfed algorithm which solves it: <https://pastebin.com/9UemcUwj>
# Score
This is a codegolf, so the shortest answer wins. good luck!
[Answer]
# [Python 2](https://docs.python.org/2/), 117 bytes
Simple BFS brute-force algorithm, outputs to STDERR.
```
t=input()
l=[('abc','')]
for s,o in l:s==t>exit(o);l+=(s[1:3]+s[0]+s[3:],o+'t'),(s[0]+s,o+'d'),(s[1::-1]+s[2:],o+'s')
```
[Try it online!](https://tio.run/##JY3LCsMgEEX3@Qp3M6KFmuwskx8RF@mLCqKhM4X2623EzYVzOXD2n7xqmVsTSmX/COopU0DYrjewADpOz/pWbKtKRWXPRLI@vkmw6ks2hBycX6LhcO6z@GirAQFtcVwd7wOd9yfXrXlYDLq1I9RTfw "Python 2 – Try It Online")
Combined with [Surcoloses way](https://codegolf.stackexchange.com/a/203262/64121) of generating the new stacks, this gets to 97 bytes: [Try it online!](https://tio.run/##FYy7DoMwDAB3viIbieKBxxYUfsTy0FYgLEUxIq5Uvj4ly013d956SJ5q1cj5/Kp1XYpo@9f70wOSo26XyxQQw9mkUGLUdfuxWnFL8o9ZkNcxMPmCQwMHAvHI5FrILRthgplqfaZt@wc "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 79 bytes
Expects `460` instead of `abc`. Output format: \$1\$ = **s**wap, \$2\$ = **d**uplicate and \$3\$ = ro**t**ate.
Same logic as the main version, but with a less readable input format which was chosen to optimize the lookup table.
```
f=s=>([a,b,c]=s,d=s.slice(3))?a-b?f(c+a+b+d)+3:f(b+c+d)+2:[[13,31,3,1,33][s%7]]
```
[Try it online!](https://tio.run/##NY/BasMwDIbveQpdhm3sKHQ@DDrSnnbeAxgzbDnpUjI7xKH07TMn2UAC6df3I@nuHi7TPExLHVPo1rVvc3vhximvyLZZhTZjHgfquBbi6mp/7TlJJ70MQupzz72krXw9G3PSSp@UViW1Nfnlzdr13VQAzHliCgCaBuq9J//f52UX/ogihMNwCBsQlhKbSN4xOFxLrmyFfZo/HH3zDO0FKMWcxg7HdOMGEXuece6m0ZXbG2xuCmjDGJWZQ89wiKF7fpZ3hBAggTGLP27icae@yk5mohV4T0PkjBVo/QU "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~100 ... 84~~ 81 bytes
Expects `012` instead of `abc`. Output format: \$1\$ = **s**wap, \$2\$ = **d**uplicate and \$3\$ = ro**t**ate.
```
f=s=>([a,b,c]=s,d=s.slice(3))?a-b?f(c+a+b+d)+3:f(b+c+d)+2:[[3,33,31,,,13,1][s&7]]
```
[Try it online!](https://tio.run/##NY/NboQwDITvPIVPTaIEI8qh0lbZPfXcB4iiKj@wZUUThFHVt6cBWskHz@gbefxw347CMs5rnXLst23QpK/cOOVVsJpU1IQ0jaHnnRA3V/vbwIN00ssoZHcZuJdhX58vxnSqK9MqpdpOtdbQ04u126upAJjzgSkAaBqoDx38v6b1MP6IYsQzcBo7ENcyuxm8Y3CmVqpshUNe3lz45AT6CiEnylOPU75zg4gDJ1z6eXKlfYPNXUHYsaMLjin2P@/lGSEESGDM4pebeTqIj3KPmWQFPvKYOGMF2n4B "JavaScript (Node.js) – Try It Online")
## How?
This solves the problem by starting with the input string and transforming it back into `"012"`.
### Step 1
The first step of the algorithm is to reverse *duplicate* and *rotate* operations until the string is exactly 3-character long.
We can notice that given an input string of length \$n\$, there are necessarily \$n-3\$ *duplicate*.
We can reverse a *duplicate* operation whenever the first 2 characters of the string are equal.
If the first 2 characters are not equal and the string is still longer than 3 characters, it means that we have to reverse a *rotate*. (It can't be a *swap* because the first 2 characters would still be different.)
We need to reverse at most 2 consecutive *rotate* before we can reverse the next *duplicate*. (If it still doesn't work after 2 reversed *rotate*, it means that the input is invalid.)
### Step 2
Once we have a string \$s\$ which is 3-character long, we use a lookup table to figure out how `"012"` can be turned into \$s\$ with as few operations as possible:
```
"012" : no operation
"021" : "st" because t(s("012")) = t("102") = "021"
"102" : "s" because s("012") = "102"
"120" : "t" because t("012") = "120"
"201" : "tt" because t(t("012")) = t("120") = "201"
"210" : "ts" because s(t("012")) = s("120") = "210"
```
The lookup table works by coercing the string to an integer an applying a modulo \$8\$.
```
string | mod 8
--------+-------
"012" | 4
"021" | 5
"102" | 6
"120" | 0
"201" | 1
"210" | 2
```
## Commented
```
f = s => // s = input string
( //
[a, b, c] = s, // split the first 3 characters as a, b and c
d = s.slice(3) // d = all remaining characters after the 3 first ones
) ? // if d is not empty:
a - b ? // if a is not equal to b:
f(c + a + b + d) // reverse a 'rotate' by re-ordering the first 3 characters
+ 3 // append a "3"
: // else:
f(b + c + d) // reverse a 'duplicate' by removing the leading character
+ 2 // append a "2"
: // else:
[ // make sure the following result can be coerced to a string:
[ // lookup table:
3 // 0: "120" -> "t" encoded as "3"
33, // 1: "201" -> "tt" encoded as "33"
31, // 2: "210" -> "ts" encoded as "31"
, // 3: not used
, // 4: "012" -> no operation
13, // 5: "021" -> "st" encoded as "13"
1 // 6: "102" -> "s" encoded as "1"
] //
[s & 7] // compute s mod 8
] //
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 105 bytes
```
f=lambda r,i=0,j=1,s="abc",*l:(t:=i%4)and f(r,i//4,j,s[t>1:t]+s[0]+s[t:],*l,t)or f(r,j,j+1)if s!=r else l
```
[Try it online!](https://tio.run/##PY/BasMwEETv/oqtoGA5m8ROAikGBUpPoe2lyS2EINsyXSPLRlIO@XpXVmkvy@7M24EZH/57MNuX0U7Uj4P14B4OwSo33G2tknCtnPJW1XfraDCaevJpkWfZnid/VCR@nX/p6@P4eTzfTufXt3eEdJNl2w0uC86nVmjZV40EiyRy7ESBTjBZ1QwzXaa@FPS849I00KYBWa932KG7@ENR@uvCXfJ5@PIaaPR8sBHrsFsUnFpwT8KC0k6BntpgajIKyEAs4hsyZQJgQUQjKJbGlAdJBykExfXkZ4CxVTeQSdmtcZ5d6ApzHs1hesZGSyYURmDLA8P4xadQI5F1lci4VPOsK/kD "Python 3.8 (pre-release) – Try It Online")
**Input**: A string representing the goal stack, where the first character of the string is the top of the stack.
**Output**: A tuple of `0,1,2` representing `d,s,t` respectively.
This is a brute-force recursive search that simply tries all possible operation sequences of increasing size.
---
***102 bytes*** if the solution doesn't have to deal with the edge case `"abc"`
```
f=lambda r,i=0,j=1,s="abc",*l:(t:=i%4)and f(r,i//4,j,s[t>1:t]+s[0]+s[t:],*l,t)or(s==r)*l or f(r,j,j+1)
```
[Try it online!](https://tio.run/##PY9Pa8MwDMXv@RTCMLBTt03awkbAhbFT2XZZewulOH/KFFw7yO6hnz5zPLaLkJ5@T@KNj/Dt7PZlpAlvo6MA/uElUO/dndo@i9PK94H69k4enTV4w8DLIs@fRfZHJeJ38y99fRw@D6fL8fT69i6Bb/J8u5HLUojpqoy@NZ0GkqgKOahSesV00zKZm4qHSuHTTmjbwZVHZL3eyUH6OuzLKpwXvi7mEqpzpGUQjrhXikRuwFFyDHJYlPFNHA3aHtBCShE6tFUGQKDSIiqEIxdRMlGK1tQewwwwthocWs4unQ@sxjPM93A@ZmZsJLQxrQS23DOZXGKKGTLdNplOTTPXttE/ "Python 3.8 (pre-release) – Try It Online")
---
**How**:
Given the stack `s` as a string, and an operation `t = 1, 2, or 3` reperesenting `d, s, t` respectively, the resulting stack is:
```
s[t>1:t]+s[0]+s[t:]
```
A sequence of operations can be encoded as a single integer `j`, and decoded using division and mod. The solution simply increment `j`, then test if `j` can produces the goal stack. This guarantees that the result sequence is the shortest.
The argument `i` keeps track of the remaining operations in the current sequence. `l` is the tuple of operations performed.
[Answer]
# [Haskell](https://www.haskell.org/), ~~111~~ 110 bytes
```
g s=[b|(a,b)<-zip f o,a==s]!!0
f="abc":(f>>=k)
k w@(a:b:c:s)=[b:c:a:s,a:w,b:a:c:s]
o="":[x++[w]|x<-o,w<-"tds"]
```
[Try it online!](https://tio.run/##LY3LCoMwEEX3fsU4qwRj6ToY6Qe0qy4li5m0WvFJY4kU/91G6OocLhzui3z37Pt9b8CbijdBimWRf9sZapgUGeNtmp6T2iCxQy3qsjSdTDoIF0GatdNexjCStFekg@JocbXJZBB1tWZZFey2FvmkQpHj8vBo94HaEQwMNN9AzJ/lvryv46mRUCE5RgVIx99B/otjiuEP "Haskell – Try It Online")
Finds the position of the target stack in an infinite list of possible stacks `f`, then uses the result to index into the infinite list of operations `o`.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~88~~ ~~82~~ 79 bytes
```
^(.)(\1[a-c]+)
$2d
}`^(.)(.)(\1|\2)([a-c]+)
$3$1$2$4t
abc
ac|bac?
s
a
bc?|c
t
```
[Try it online!](https://tio.run/##PcmhDoQwEEVR/76jJNMQSNrFI/kIYMObWQQGAZXl20tArLni3GNN285SiQxL@UrrZQojG5trDxd/uJYXX89T9PKfHxdcdF0C1QBaVlqPEwTU@mxIpdAUfD71qSlv "Retina 0.8.2 – Try It Online") Link includes test cases. Uses @xnor's direct approach. Explanation:
```
^(.)(\1[a-c]+)
$2d
```
If the first two characters are the same, then they must have just been duplicated, so output a `d` and remove the first character. (The `[a-c]` ensures that the outputs collect in reverse order.)
```
^(.)(.)(\1|\2)([a-c]+)
$3$1$2$4t
```
If the third character is one of the first two, then try rotating the stack.
```
}`
```
Repeat the above stages until the three characters are all different, in which case they should be the last three.
```
abc
```
If they are `abc` then there is nothing left to do.
```
ac|bac?
s
```
`acb`, `bac`, and `cba` all need a swap. For `bac` this completes the operations; `acb` needs a rotation after the swap, while `cba` needs a rotation before the swap. Leaving a `b` or `c` behind will achieve this later.
```
a
```
Remove any remaining `a`s as they have nothing left to contribute.
```
bc?|c
t
```
Any remaining `b`s and `c`s indicate rotations, except that `bc` is just one rotation.
Previous brute-force 82-byte solution:
```
$
¶abc:
{`^(.+)¶(.+¶)*\1:(.*)(¶.+)*$
$3
(.)(.)(.)(.*:.*)
$2$1$3$4s¶$1$&d¶$2$3$1$4t
```
[Try it online!](https://tio.run/##NUy7DYQwDO09hw85QYoUoMoCtwRCcQIFDcUdHXt5AC8WTIH09L7S@23nfnD70Dc3BBUuNcGVFwq9UzFWcX6OiYJ3pGKtR8ARKLgXPtkGOGDEEae/ipluNRksR5zO1rgWYLsGLg/Xwjc "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 6 bytes thanks to @someone. Explanation:
```
$
¶abc:
```
Append the initial position to the input.
```
{`
```
Repeat until a solution is found.
```
^(.+)¶(.+¶)*\1:(.*)(¶.+)*$
$3
```
If the input matches an output stack, delete everything except the output sequence.
```
(.)(.)(.)(.*:.*)
$2$1$3$4s¶$1$&d¶$2$3$1$4t
```
For each position, compute the three positions arising from applying each of the three operators.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~21~~ ~~18~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
g…sŠD׿é.Δ₁`r.V)Q
```
-1 byte by taking the input as `256` (`₁`) for `abc` respectively, instead of `ABC` (`žR`) I had prior.
Takes the input in reversed order using the characters `256` for `abc` respectively.
Outputs `s` for swap; `D` for duplicate; and `Š` for triple swap/rotate.
[Try it online](https://tio.run/##ASsA1P9vc2FiaWX//2figKZzxaBEw5fDpsOpLs6U4oKBYHIuVilR//9bNSw2LDJd) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVL6P/0Rw3Lio8ucDk8/fCywyv1zk151NSYUKQXphkR@L9W5390tKmOmY5RrE60mY6pjhESyxTMBtFmsbEA).
**Explanation:**
```
g # Get the length of the (implicit) input-list
…sŠD # Push the string "sŠD"
× # Repeat it the length amount of times
æ # Take the powerset of this
é # Sort them by length
# i.e. input-length=3 → ["","s","Š","D","s","Š","D","s","Š","D","sŠ","sD","ŠD","ss","Šs","Ds","sŠ","ŠŠ","DŠ","sŠ","sD","ŠD","DD","sD","ŠD","ss","Šs","Ds","ss","Šs","Ds","sŠ","ŠŠ","DŠ","sŠ","ŠŠ","DŠ","sŠ","sD","ŠD","DD","sD","ŠD","DD","sD","ŠD","sŠD","sŠs","sDs","ŠDs","sŠŠ","sDŠ","ŠDŠ","ssŠ","ŠsŠ","DsŠ","sŠD","sDD","ŠDD","ssD","ŠsD","DsD","sŠD","ŠŠD","DŠD","sŠD","sŠs","sDs","ŠDs","sss","Šss","Dss","sŠs","ŠŠs","DŠs","sŠs","sDs","ŠDs","DDs","sDs","ŠDs","sŠŠ","sDŠ","ŠDŠ","ssŠ","ŠsŠ","DsŠ","sŠŠ","ŠŠŠ","DŠŠ","sŠŠ","sDŠ","ŠDŠ","DDŠ","sDŠ","ŠDŠ","ssŠ","ŠsŠ","DsŠ","ssŠ","ŠsŠ","DsŠ","sŠD","sDD","ŠDD","ssD","ŠsD","DsD","sŠD","ŠŠD","DŠD","sŠD","sDD","ŠDD","DDD","sDD","ŠDD","ssD","ŠsD","DsD","ssD","ŠsD","DsD","sŠD","ŠŠD","DŠD","sŠD","ŠŠD","DŠD","sŠD","sŠDs","sŠDŠ","sŠsŠ","sDsŠ","ŠDsŠ","sŠDD","sŠsD","sDsD","ŠDsD","sŠŠD","sDŠD","ŠDŠD","ssŠD","ŠsŠD","DsŠD","sŠDs","sŠss","sDss","ŠDss","sŠŠs","sDŠs","ŠDŠs","ssŠs","ŠsŠs","DsŠs","sŠDs","sDDs","ŠDDs","ssDs","ŠsDs","DsDs","sŠDs","ŠŠDs","DŠDs","sŠDs","sŠDŠ","sŠsŠ","sDsŠ","ŠDsŠ","sŠŠŠ","sDŠŠ","ŠDŠŠ","ssŠŠ","ŠsŠŠ","DsŠŠ","sŠDŠ","sDDŠ","ŠDDŠ","ssDŠ","ŠsDŠ","DsDŠ","sŠDŠ","ŠŠDŠ","DŠDŠ","sŠDŠ","sŠsŠ","sDsŠ","ŠDsŠ","sssŠ","ŠssŠ","DssŠ","sŠsŠ","ŠŠsŠ","DŠsŠ","sŠsŠ","sDsŠ","ŠDsŠ","DDsŠ","sDsŠ","ŠDsŠ","sŠDD","sŠsD","sDsD","ŠDsD","sŠŠD","sDŠD","ŠDŠD","ssŠD","ŠsŠD","DsŠD","sŠDD","sDDD","ŠDDD","ssDD","ŠsDD","DsDD","sŠDD","ŠŠDD","DŠDD","sŠDD","sŠsD","sDsD","ŠDsD","sssD","ŠssD","DssD","sŠsD","ŠŠsD","DŠsD","sŠsD","sDsD","ŠDsD","DDsD","sDsD","ŠDsD","sŠŠD","sDŠD","ŠDŠD","ssŠD","ŠsŠD","DsŠD","sŠŠD","ŠŠŠD","DŠŠD","sŠŠD","sDŠD","ŠDŠD","DDŠD","sDŠD","ŠDŠD","ssŠD","ŠsŠD","DsŠD","ssŠD","ŠsŠD","DsŠD","sŠDsŠ","sŠDsD","sŠDŠD","sŠsŠD","sDsŠD","ŠDsŠD","sŠDss","sŠDŠs","sŠsŠs","sDsŠs","ŠDsŠs","sŠDDs","sŠsDs","sDsDs","ŠDsDs","sŠŠDs","sDŠDs","ŠDŠDs","ssŠDs","ŠsŠDs","DsŠDs","sŠDsŠ","sŠDŠŠ","sŠsŠŠ","sDsŠŠ","ŠDsŠŠ","sŠDDŠ","sŠsDŠ","sDsDŠ","ŠDsDŠ","sŠŠDŠ","sDŠDŠ","ŠDŠDŠ","ssŠDŠ","ŠsŠDŠ","DsŠDŠ","sŠDsŠ","sŠssŠ","sDssŠ","ŠDssŠ","sŠŠsŠ","sDŠsŠ","ŠDŠsŠ","ssŠsŠ","ŠsŠsŠ","DsŠsŠ","sŠDsŠ","sDDsŠ","ŠDDsŠ","ssDsŠ","ŠsDsŠ","DsDsŠ","sŠDsŠ","ŠŠDsŠ","DŠDsŠ","sŠDsŠ","sŠDsD","sŠDŠD","sŠsŠD","sDsŠD","ŠDsŠD","sŠDDD","sŠsDD","sDsDD","ŠDsDD","sŠŠDD","sDŠDD","ŠDŠDD","ssŠDD","ŠsŠDD","DsŠDD","sŠDsD","sŠssD","sDssD","ŠDssD","sŠŠsD","sDŠsD","ŠDŠsD","ssŠsD","ŠsŠsD","DsŠsD","sŠDsD","sDDsD","ŠDDsD","ssDsD","ŠsDsD","DsDsD","sŠDsD","ŠŠDsD","DŠDsD","sŠDsD","sŠDŠD","sŠsŠD","sDsŠD","ŠDsŠD","sŠŠŠD","sDŠŠD","ŠDŠŠD","ssŠŠD","ŠsŠŠD","DsŠŠD","sŠDŠD","sDDŠD","ŠDDŠD","ssDŠD","ŠsDŠD","DsDŠD","sŠDŠD","ŠŠDŠD","DŠDŠD","sŠDŠD","sŠsŠD","sDsŠD","ŠDsŠD","sssŠD","ŠssŠD","DssŠD","sŠsŠD","ŠŠsŠD","DŠsŠD","sŠsŠD","sDsŠD","ŠDsŠD","DDsŠD","sDsŠD","ŠDsŠD","sŠDsŠD","sŠDsŠs","sŠDsDs","sŠDŠDs","sŠsŠDs","sDsŠDs","ŠDsŠDs","sŠDsŠŠ","sŠDsDŠ","sŠDŠDŠ","sŠsŠDŠ","sDsŠDŠ","ŠDsŠDŠ","sŠDssŠ","sŠDŠsŠ","sŠsŠsŠ","sDsŠsŠ","ŠDsŠsŠ","sŠDDsŠ","sŠsDsŠ","sDsDsŠ","ŠDsDsŠ","sŠŠDsŠ","sDŠDsŠ","ŠDŠDsŠ","ssŠDsŠ","ŠsŠDsŠ","DsŠDsŠ","sŠDsŠD","sŠDsDD","sŠDŠDD","sŠsŠDD","sDsŠDD","ŠDsŠDD","sŠDssD","sŠDŠsD","sŠsŠsD","sDsŠsD","ŠDsŠsD","sŠDDsD","sŠsDsD","sDsDsD","ŠDsDsD","sŠŠDsD","sDŠDsD","ŠDŠDsD","ssŠDsD","ŠsŠDsD","DsŠDsD","sŠDsŠD","sŠDŠŠD","sŠsŠŠD","sDsŠŠD","ŠDsŠŠD","sŠDDŠD","sŠsDŠD","sDsDŠD","ŠDsDŠD","sŠŠDŠD","sDŠDŠD","ŠDŠDŠD","ssŠDŠD","ŠsŠDŠD","DsŠDŠD","sŠDsŠD","sŠssŠD","sDssŠD","ŠDssŠD","sŠŠsŠD","sDŠsŠD","ŠDŠsŠD","ssŠsŠD","ŠsŠsŠD","DsŠsŠD","sŠDsŠD","sDDsŠD","ŠDDsŠD","ssDsŠD","ŠsDsŠD","DsDsŠD","sŠDsŠD","ŠŠDsŠD","DŠDsŠD","sŠDsŠD","sŠDsŠDs","sŠDsŠDŠ","sŠDsŠsŠ","sŠDsDsŠ","sŠDŠDsŠ","sŠsŠDsŠ","sDsŠDsŠ","ŠDsŠDsŠ","sŠDsŠDD","sŠDsŠsD","sŠDsDsD","sŠDŠDsD","sŠsŠDsD","sDsŠDsD","ŠDsŠDsD","sŠDsŠŠD","sŠDsDŠD","sŠDŠDŠD","sŠsŠDŠD","sDsŠDŠD","ŠDsŠDŠD","sŠDssŠD","sŠDŠsŠD","sŠsŠsŠD","sDsŠsŠD","ŠDsŠsŠD","sŠDDsŠD","sŠsDsŠD","sDsDsŠD","ŠDsDsŠD","sŠŠDsŠD","sDŠDsŠD","ŠDŠDsŠD","ssŠDsŠD","ŠsŠDsŠD","DsŠDsŠD","sŠDsŠDsŠ","sŠDsŠDsD","sŠDsŠDŠD","sŠDsŠsŠD","sŠDsDsŠD","sŠDŠDsŠD","sŠsŠDsŠD","sDsŠDsŠD","ŠDsŠDsŠD","sŠDsŠDsŠD"]
.Δ # Then find the first string which is truthy for:
₁ # Push the builtin 256
` # Pop and push them separated to the stack
r # Reverse the stack, so the order is [6,5,2,string]
.V # Execute the string as 05AB1E code
) # Wrap all values on the stack into a list
Q # And check that it's equal to the (implicit) input-list
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 126 bytes
```
->s{*w='',321;(a,b,*w=w;w<<a+?d<<b*10+(k=b%10)<<a+?s<<b+k*10-(z=b%100)+z/10<<a+?t<<b+k*100-(x=b%1000)+x/10)until w[1]==s;w[0]}
```
[Try it online!](https://tio.run/##Nc1BDsIgEIXhq3SjhUKVgSWgByEsSkwTU20agVBrPDsixs0k7/8W84jumUed@5N/dUm3LRUcJBqoo2UmmZQayPmilOuAETRptwOGa/QlkqnkHm01M0y2I7CK4Y9F158WXgvjOIfrrUkGrNZeJsPsOy8x@MZwAd/39XCgwIU93IcF7UecPw "Ruby – Try It Online")
] |
[Question]
[
You are given an array/list/vector of pairs of integers representing cartesian coordinates \$(x, y)\$ of points on a 2D Euclidean plane; all coordinates are between \$−10^4\$ and \$10^4\$, duplicates are allowed. Find the area of the [convex hull](https://en.wikipedia.org/wiki/Convex_hull) of those points, rounded to the nearest integer; an exact midpoint should be rounded to the closest even integer. You may use floating-point numbers in intermediate computations, but only if you can guarantee that the final result will be always correct. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest correct program wins.
The *convex hull* of a set of points \$P\$ is the smallest convex set that contains \$P\$. On the Euclidean plane, for any single point \$(x,y)\$, it is the point itself; for two distinct points, it is the line containing them, for three non-collinear points, it is the triangle that they form, and so forth.
A good visual explanation of what a convex hulls, is best described as imagining all points as nails in a wooden board, and then stretching a rubber band around them to enclose all the points:
[](https://i.stack.imgur.com/0c83c.png)
Some test cases:
```
Input: [[50, -13]]
Result: 0
Input: [[-25, -26], [34, -27]]
Result: 0
Input: [[-6, -14], [-48, -45], [21, 25]]
Result: 400
Input: [[4, 30], [5, 37], [-18, 49], [-9, -2]]
Result: 562
Input: [[0, 16], [24, 18], [-43, 36], [39, -29], [3, -38]]
Result: 2978
Input: [[19, -19], [15, 5], [-16, -41], [6, -25], [-42, 1], [12, 19]]
Result: 2118
Input: [[-23, 13], [-13, 13], [-6, -7], [22, 41], [-26, 50], [12, -12], [-23, -7]]
Result: 2307
Input: [[31, -19], [-41, -41], [25, 34], [29, -1], [42, -42], [-34, 32], [19, 33], [40, 39]]
Result: 6037
Input: [[47, 1], [-22, 24], [36, 38], [-17, 4], [41, -3], [-13, 15], [-36, -40], [-13, 35], [-25, 22]]
Result: 3908
Input: [[29, -19], [18, 9], [30, -46], [15, 20], [24, -4], [5, 19], [-44, 4], [-20, -8], [-16, 34], [17, -36]]
Result: 2905
```
[Answer]
# SQL Server 2012+, 84 bytes
```
SELECT Round(Geometry::ConvexHullAggregate(Geometry::Point(x,y,0)).STArea(),0)FROM A
```
Makes use of the geometry functions and aggregates in SQL Server.
Coordindates are from table `A` with columns `x` and `y`.
[Answer]
# Java 10, ~~405~~ ~~...didn't fit anymore; see edit history..~~ ~~317~~ 316 bytes
```
P->{int n=P.length,l=0,i=0,p,q,t[],h[][]=P.clone(),s=0;for(;++i<n;)l=P[i][0]<P[l][0]?i:l;p=l;do for(h[s++]=P[p],q=-~p%n,i=-1;++i<n;q=(t[1]-P[p][1])*(P[q][0]-t[0])<(t[0]-P[p][0])*(P[q][1]-t[1])?i:q)t=P[i];while((p=q)!=l);for(p=i=0;i<s;p-=(t[0]+h[++i%s][0])*(t[1]-h[i%s][1]))t=h[i];return Math.round(.5*p/~(p%=2))*~p;}
```
-52 bytes thanks to *@OlivierGrégoire*
-3 bytes thanks to *@PeterTaylor*
[Try it online.](https://tio.run/##pVPLcptAELzrKzYHV@1as4R9oEcQyRfEpSofKR2IhAUOXiFAdqVU@NeVmQX7A/BBzDKz9HT3jJ6z10w@H/7e9lXWtux3VrrrjLHSdXnzlO1z9kCvjFUnd2R7jvl0l@7YVsSY7mf4eGCOJey2lT@vWGUu2QZV7o5dAVUSQom/Gs6An0FBn2J5j2A5F9AmYfx0ang8n5cbF4sq2ablLg13m21aUfxV/qjiOqniw4nRxSJt53NESOsdnBP5Xt85bCDVCHBOeJeqnaQ6RnHPt@mZcGSHD7HhFIZq@FlVVMXL2OssOs8gfivKKue8Ts7iW1IJT7JOUEpcbtq4lolHmhcp9r1rRzTfukh9AvEQqyCsJu8ujUNjuyJoThd34EF0X39/5/VdooW4f6/j/hZ7jxnDUF/@VOWetV3WYXg9lQf2gkPhj11TuiNanzXHVgxDefzXdvlLcLp0QY3VrnLc5W9@iFwELtj713Fm12sUglSm74WIp3wudQRSL3q4GouH5WSgEEIEUaD8M5xOaIF6LIJIuwJpIzxpBTqaDGjBELMIzJJQ1Qrsmg5rlPsFtYo80xbUynM1YLyJhErwBqRZTYZXCKMIRkUQedboiiVrMWqfsXqwGsP6C9M3gMtDDT4O2IB80hp8P9wNiMKhkVTaZwxdmdrSqFEa6hk14Qoamrgm1RhRGsqjK7iThg7ohyF2NgQzXa1dwiBJg6Z@ZgHGT08tgd6J0KcZ3mRDtodjyvgUktXT90Z/DnYFfk3w32sXw6B1OGyUtH5dR5OspyY1XlyNm@DNQs5I74NIP@vZ7T8)
[Or **299 bytes without rounding..**](https://tio.run/##pVPbcpswEH3PV6gPmYF65eqGL5Vpv6AZz@SR4YHaxJASGQN2puOhv@7uCuIPIA/WCq109pyz69fskvHX/Z/brsralv3KSnd9YKx0Xd68ZLucPdEnY/vj@XeVs12AmSRNUrYNLSb6B1yemGMxu235jytmmYu38yp3h66AKhZQ4q@GE@AzKOgppnfV0eVBCG0s7MuxCexsVm6cDat4m5RpItLNNqko/iy/V7aOK7s/MrpYJO1shghJncIp5v/qR4cFuBwBTnHQJTLllMcYfg22yYlweIdLuAkoDFlxz0rK4mWsdQo7z8C@F2WVB0Edn8IvcRXaS9awLBZ7zxYV2XLT2ozHHnBWJFj@sR1BPYMi8QcIi5AFQTZ5d24cy74p29@sN5UxDDUaW@5Y22Udhsux3LM37ELw3DWlO6DTWXNow6ELz3/bLn@bH8/dvMZsV7nA5e@@a0E4d/Od/xxbdL1GArjUfR@GdspzriLgatHDVRvcLCcDCRAIIkH6VUwntEA9BkG4WQE3Ee6UBBVNBjSgiVkEekmocgVmTZs1yv2EWkmeKQNy5blq0N5EQiV4DVyvJsNLhJEEIyOIPGt0xZC1GJU/MWqwGsP6E93XgMNDBT42WIB8Ugp8PZwNiMRQiEvlTzRdmVpSy1Ea6hk14Qhq6rgi1RhRGsqjKziTmjbohyZ2RoCertYsYZCkQFE9vQDtuyeXQN9E6G6GN1mT7WI80v4Iyarpc6PujV2BHxP895rF0Gglhonixo/raJLx1LjCi6txErxZyBnpfRDpH3p2@w8).
**Explanation:**
There are three steps to do:
1. Calculate the points for the Convex Hull based on the input-coordinates (using [Jarvis' Algorithm/Wrapping](https://www.geeksforgeeks.org/convex-hull-set-1-jarviss-algorithm-or-wrapping/))
2. Calculate the area of this Convex Hull
3. Banker's rounding..
To calculate the coordinates that are part of the Convex Hull, we use the following approach:
Set point \$l\$ and \$p\$ to the left-most coordinate. Then calculate the next point \$p\$ in a counterclockwise rotation; and continue doing so until we've reached back at the initial point \$l\$. Here a visual for this:
[](https://i.stack.imgur.com/k61t4.png)
As for the code:
```
P->{ // Method with 2D integer array as parameter & long return-type
int n=P.length, // Integer `n`, the amount of points in the input
l=0, // Integer `l`, to calculate the left-most point
i=0, // Index-integer `i`
p, // Integer `p`, which will be every next counterclockwise point
q, // Temp integer `q`
t[], // Temp integer-array/point
h[][]=P.clone(), // Initialize an array of points `h` for the Convex Hull
s=0; // And a size-integer for this Convex Hull array, starting at 0
for(;++i<n;) // Loop `i` in the range [1, `n`):
l= // Change `l` to:
P[i][0]<P[l][0]? // If i.x is smaller than l.x:
i // Replace `l` with the current `i`
:l; // Else: leave `l` unchanged
p=l; // Now set `p` to this left-most coordinate `l`
do // Do:
for(h[s++]=P[p], // Add the `p`'th point to the 2D-array `h`
q=-~p%n, // Set `q` to `(p+1)` modulo-`n`
i=-1;++i<n; // Loop `i` in the range [0, `n`):
;q= // After every iteration: change `q` to:
// We calculate: (i.y-p.y)*(q.x-i.x)-(i.x-p.x)*(q.y-i.y),
// which results in 0 if the three points are collinear;
// a positive value if they are clockwise;
// or a negative value if they are counterclockwise
(t[1]-P[p][1])*(P[q][0]-t[0])<(t[0]-P[p][0])*(P[q][1]-t[1])?
// So if the three points are counterclockwise:
i // Replace `q` with `i`
:q) // Else: leave `q` unchanged
t=P[i]; // Set `t` to the `i`'th Point (to save bytes)
while((p=q) // And after every while-iteration: replace `p` with `q`
!=l); // Continue the do-while as long as `p` is not back at the
// left-most point `l` yet
// Now step 1 is complete, and we have our Convex Hull points in the List `h`
for(p=i=0; // Set `p` (the area) to 0
i<s // Loop `i` in the range [0, `s`):
;p-= // After every iteration: Decrease the area `p` by:
(t[0]+h[++i%s][0])// i.x+(i+1).x
*(t[1]-h[i%s][1]))// Multiplied by i.y-(i+1).y
t=h[i]; // Set `t` to the `i`'th point (to save bytes)
return Math.round(.5*p/~(p%=2))*~p;}
// And return `p/2` rounded to integer with half-even
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 27 bytes
```
Round@*Area@*ConvexHullMesh
```
[Try it online!](https://tio.run/##hVK5asNQEOz9FaqNHtYeugqDQpo0gZA/EImMDbYMjhwC4n27soekuEs3Hs3Ozs7zpR2O3aUdTh/tdNhP79d7/9lsn25d22yfr/139/NyP59fu6/j9HY79cOuOeyacTOOeZYmASjGVH4EzOUXFjFNRmKF5X8fCh1n5QNXgjlXjJAmmLtE5JQpKRZUmhJEybXBWs1cKEnANqCMQOWeJEO@1pQ2JFygyodAaTAaZEHu/pqKQbEidJZRbE2ooF4uEze538b@oI5ZVhStO8n54p8tBgHQWTKpmRGsYWT9mkHLI@sILa0iDSOJTKqNkkG9hiwBSxs0Z@RyDh40DZoTSRjyjkA@G2crH07xs8nKyFaanNZQODePDyXK03jJ@sfgYikWs@VlAs@PuRzK8/qAOlKtL@AnazrJEOMmTr8 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# JavaScript (ES6), ~~191~~ 189 bytes
Implements the [Jarvis march](https://en.wikipedia.org/wiki/Gift_wrapping_algorithm) (aka gift wrapping algorithm).
```
P=>(r=(g=p=>([X,Y]=P[p],Y*h-X*v)+(P.map(([x,y],i)=>q=(y-Y)*(P[q][0]-x)<(x-X)*(P[q][1]-y)?i:q,q=P[++p]?p:0,h=X,v=Y)|q?g(q):V*h-H*v))(v=h=0,([[H,V]]=P.sort(([x],[X])=>x-X)))/2)+(r%1&&r&1)/2|0
```
[Try it online!](https://tio.run/##fVLLbiIxELzvV8xlkQ02@DUvtA7XHDlFgywfUDYBoiTzIEIg5d/ZbpuZRDurvdX0VFdVd/tle9oeH7tD88Hf699P12d7Xds70lmysw0AV7GNt2vXeLaZ7nk1PdEZWc/ftg0h7swunh2ovWstufANnZK1a70Tnp/pL3LmVV@Rnl/o6rBsWQtas1njV81SsL2t2Mlu6Ge72pGWLh/A4R4cKDnZvRWMOHfPHjz4z49194GOnrnKgyOKU7pQkKb7KSeTbiLh61NcH@v3Y/36NH@td@QZBFLBEi6195Qmi0UifvxN4CoFhso8S5w2CPP/kDNUM8jlpgBsUsRKskSlfZsR40YQ1gKpYKbz0C@h35QBlmjbt6eZGrXDEDIkVCAki@ivQSrGDv1BCmpcF72UKvNipCWRLQNbQpo0hsHBjESMSMWqUeAWiAjKQVbK4h97BG9YdFD7gqgW5lUgEQ1g2WArel0uVazqQO09tMhHHloO0SHskBgvqMNRVJgNEUaH/IGKZ9UB4uw6BDOwUj1MlAk9djP5bXqO2VUw0BBdx/1L@B1qIcm3wePudNioGMo6ljGrGm6tSzHepPp2IHgj8a74jE3WH02J/jFwc3tV/VrMLRVX2FIM140LwtAQ7euBiPT6Bw "JavaScript (Node.js) – Try It Online")
Or [**170 bytes**](https://tio.run/##fVJNb@owELy/X5GjDTbYXucL1eXaI6cqKPIB9QN46muSUiGQ@t95uzZJq6bqJRptZmdmd/13c9wcHt727bt8bR6fLs/usnK3bOta/NaVWHu3qlsv1pOdrCZHPmWr2b9Ny1h9Emcv9tzddo6d5ZpP2KrufK28PPEbdpJVX9Fenvlyv@hEh1rTaeuX7UKJnavE0a35R7fcso4v7tHhDh04O7qdU4LV9Z249@g/OzRv7@ToRV15dCRxzufm8tC8HpqXp9lLs2XP2JAqkUgN3nOezOeJ@vOdIE2KDJN5kdRgCea/kDNSs8SVtkBsU8JGi8SkfZtV40YUBkVUNIM89Gvst2WAJdn27WlmRu04hA4JDQrpIvoDSsXYoT9IYU1C0UuZMi9GWprYOrA1pkljGBrMasKETKxag26BSKAcZLUuftgjeuOig9onJLUwr0GJaIDLRlvV60ptYhUCtfcAlY88QA/RMeyQmC4I4SgmzEaIomP@QKWzQoA0O4RgFlcKw0SZgrGbza/TS8puggFgdIj71/g71EKSL4PH3UHYqBrKEMuU1Qy3hlKNN2m@HAjfSLwrPWOb9Uczqn8M0l5fVb8We00lDbUUw3Xjgig0Rvt8ICq9/Ac) without the cumbersome rounding scheme.
[Answer]
# [R](https://www.r-project.org/), ~~85~~ ~~81~~ 78 bytes
```
function(i,h=chull(i),j=c(h,h[1]))round((i[h,1]+i[j[-1],1])%*%diff(-i[j,2])/2)
```
[Try it online!](https://tio.run/##lZLNTsMwEITv@xRREVICNnh3nT@JXHmJqgdoGyWoKqi0Em9fZp2Ga8sldix79pudPZz77MWf@9N@fRw/9/nohm49nHa7fCzcR7fOBzcseVUUh8/TfpPn43JwvHoclx9Lzytsi/uH@83Y97nHmZNV8SzFuc8P27fN0/HtfbfNh@7VfW@/uoVbuOP259gtqAwu86y0KIrsLgtE1x54KfFCKtJoa/2Pl5WViuRjg00sSdhlUl4EYrhBAiU1EAC0Js@QiS351jguKmUl11VgmSsSiHEDGoUc7CSZlvDntbnISVs31/XYnnJLDLASXOYzMtkCez4KChHbt511mZtbWg0YZIN8ptUUaxIoQR4ZoFxIwp5luu3nPERDfb2C8kQO3InZwtVIkhyRkQOfvGWtkoyqUkQDdbZSBb2hUKytB97QJZKCHD32jNNIqfbsEv3S1L8wHWg5TZzMCWsbbmidzJFgRpCpDXmsUkASUvI@2hgl69EgvNidZkoPHTA0kPzNQSjPvw "R – Try It Online")
Takes input as a 2-column matrix - first for `x`, second for `y`. R's `round` actually uses banker's rounding method, so we are quite lucky here.
The code uses a built-in function to determine, which points form the convex hull, and then applies the standard formula \$\sum\_{i}{(x\_{i-1}+x)\cdot(y\_{i-1}-y\_i)}/2\$ to get the polygon surface area.
Thanks to Giuseppe for -3 bytes.
[Answer]
# [R + sp package], 55 bytes
```
function(x)round(sp::Polygon(x[chull(x),,drop=F])@area)
```
[Try it at RDRR](https://rdrr.io/snippets/embed/?code=f%3D%0Afunction(x)round(sp%3A%3APolygon(x%5Bchull(x)%2C%2Cdrop%3DF%5D)%40area)%0Af(rbind(c(-25%2C%20-26)))%0Af(rbind(c(-25%2C%20-26)%2C%20c(34%2C%20-27)))%0Af(rbind(c(-6%2C%20-14)%2C%20c(-48%2C%20-45)%2C%20c(21%2C%2025)))%0Af(rbind(c(4%2C%2030)%2C%20c(5%2C%2037)%2C%20c(-18%2C%2049)%2C%20c(-9%2C%20-2)))%0Af(rbind(c(0%2C%2016)%2C%20c(24%2C%2018)%2C%20c(-43%2C%2036)%2C%20c(39%2C%20-29)%2C%20c(3%2C%20-38)))%0Af(rbind(c(19%2C%20-19)%2C%20c(15%2C%205)%2C%20c(-16%2C%20-41)%2C%20c(6%2C%20-25)%2C%20c(-42%2C%201)%2C%20c(12%2C%2019)))%0Af(rbind(c(-23%2C%2013)%2C%20c(-13%2C%2013)%2C%20c(-6%2C%20-7)%2C%20c(22%2C%2041)%2C%20c(-26%2C%2050)%2C%20c(12%2C%20-12)%2C%20c(-23%2C%20-7)))%0Af(rbind(c(31%2C%20-19)%2C%20c(-41%2C%20-41)%2C%20c(25%2C%2034)%2C%20c(29%2C%20-1)%2C%20c(42%2C%20-42)%2C%20c(-34%2C%2032)%2C%20c(19%2C%2033)%2C%20c(40%2C%2039)))%0Af(rbind(c(47%2C%201)%2C%20c(-22%2C%2024)%2C%20c(36%2C%2038)%2C%20c(-17%2C%204)%2C%20c(41%2C%20-3)%2C%20c(-13%2C%2015)%2C%20c(-36%2C%20-40)%2C%20c(-13%2C%2035)%2C%20c(-25%2C%2022)))%0Af(rbind(c(29%2C%20-19)%2C%20c(18%2C%209)%2C%20c(30%2C%20-46)%2C%20c(15%2C%2020)%2C%20c(24%2C%20-4)%2C%20c(5%2C%2019)%2C%20c(-44%2C%204)%2C%20c(-20%2C%20-8)%2C%20c(-16%2C%2034)%2C%20c(17%2C%20-36))))
A function which takes a n x 2 matrix and returns the rounded area. This uses the `sp` package. The `drop=F` is needed to handle the one co-ordinate case. RDRR used for demo since TIO lacks the `sp` package.
] |
[Question]
[
Implement the Discrete Fourier Transform (DFT) for a sequence of any length. This may implemented as either a function or a program and the sequence can be given as either an argument or using standard input.
The algorithm will compute a result based on standard DFT in the forward direction. The input sequence has length `N` and consists of `[x(0), x(1), ..., x(N-1)]`. The output sequence will have the same length and consists of `[X(0), X(1), ..., X(N-1)]` where each `X(k)` is defined by the relation below.
$$X\_k\overset{\text{def}}{=}\sum\_{n=0}^{N-1}x\_n\cdot e^{-2\pi ikn/N}$$
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest solution wins.
* Builtins that compute the DFT in forward or backward (also known as inverse) directions are not allowed.
* Floating-point inaccuracies will not be counted against you.
## Test Cases
```
DFT([1, 1, 1, 1]) = [4, 0, 0, 0]
DFT([1, 0, 2, 0, 3, 0, 4, 0]) = [10, -2+2j, -2, -2-2j, 10, -2+2j, -2, -2-2j]
DFT([1, 2, 3, 4, 5]) = [15, -2.5+3.44j, -2.5+0.81j, -2.5-0.81j, -2.5-3.44j]
DFT([5-3.28571j, -0.816474-0.837162j, 0.523306-0.303902j, 0.806172-3.69346j, -4.41953+2.59494j, -0.360252+2.59411j, 1.26678+2.93119j] = [2, -3j, 5, -7j, 11, -13j, 17]
```
### Help
There was a previous [challenge](https://codegolf.stackexchange.com/questions/12420/too-fast-too-fourier-fft-code-golf) for finding the DFT using a FFT algorithm for sequences with lengths equal to a power of 2. You may find some tricks there that might help you here. Keep in mind that this challenge does not limit you to any complexity and also requires your solution to work for sequences of any length.
[Answer]
# Python 3, 77 bytes
```
lambda x,e=enumerate:[sum(t/1j**(4*k*n/len(x))for n,t in e(x))for k,_ in e(x)]
```
Test it on [Ideone](http://ideone.com/X0BXlP).
The code uses the equivalent formula

[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
LR’µ×'÷L-*²³÷S€
```
[Try it online!](http://jelly.tryitonline.net/#code=TFLigJnCtcOXJ8O3TC0qwrLCs8O3U-KCrA&input=&args=MSwwLDIsMCwzLDAsNCww&debug=on)
### How it works
```
LR’µ×'÷L-*²³÷S€ Main link. Argument [x(0), ..., x(N-1)].
L Length; yield N.
R Range; yield [1, ..., N].
’ Decrement; yield [0, ..., N-1].
µ Begin a new, monadic chain. Argument: [0, ..., N-1]
×' Spawned multiply [0, ..., N-1] with itself, yielding the matrix
of all possible products k×n.
÷L Divide each product by N.
-* Compute (-1)**(kn÷L) for each kn.
² Square each result, computing (-1)**(2kn÷L).
³÷ Divide [x(0), ..., x(N-1)] by the results.
S€ Compute the sum for each row, i.e., each X(k).
```
[Answer]
# J, ~~30~~ 20 bytes
3 bytes thanks to [@miles](https://codegolf.stackexchange.com/users/6710/miles).
Uses the fact that `e^ipi = -1`.
The formula becomes `X_k = sum(x_n / ((-1)^(2nk/N)))`.
```
+/@:%_1^2**/~@i.@#%#
```
### Usage
```
>> DCT =: +/@:%_1^2**/~@i.@#%#
>> DCT 1 2 3 4 5
<< 15 _2.5j3.44095 _2.5j0.812299 _2.5j_0.812299 _2.5j_3.44095
```
where `>>` is STDIN and `<<` is STDOUT.
"Floating-point inaccuracies will not be counted against you."
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 30 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⍵∘{+/⍺÷0j1*(4×⍵×⍳≢⍺)÷≢⍺}¨⍳≢⍵}
```
Adapted from the formula presented in [this Python answer](https://codegolf.stackexchange.com/a/82658) by [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31dP/UdsEAwA&c=q37Uu/VRx4xqbf1HvbsObzfIMtTSMDk8HSgKIjY/6lwEFNc8vB3CqD20Aia4tRYA&f=JY67CQMxEERbUXYnOMT@pW3IgcpwaHDmChwZJ9eDSlEl3pNZBmYezDLz@d3n431s83Xfjlsenx3TuhwGEoU4JAkuQBEkad61j5MLNa2YxgmloUmVvixXtOgVJWawxRjY4WINDCutsjmLRVmKoCt3Kurist6xASn9EcaYQma1RXZG9PwD&i=AwA&r=tryAPL&l=apl-dyalog&m=dfn&n=f)
# [APL(Dyalog Unicode)](https://dyalog.com), 31 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⍵∘{+/⍺×*a÷⍨○0J¯2×⍵×⍳a←≢⍺}¨⍳≢⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31dP/UdsEAwA&c=q37Uu/VRx4xqbf1HvbsOT9dKPLz9Ue@KR9O7DbwOrTc6PB0oDSI2Jz5qm/CocxFQUe2hFUA@mL21FgA&f=JY67CQMxEERbUXYnOMT@pW3IgcpwaHDmChwZJ9eDSlEl3pNZBmYezDLz@d3n431s83Xfjlsenx3TuhwGEoU4JAkuQBEkad61j5MLNa2YxgmloUmVvixXtOgVJWawxRjY4WINDCutsjmLRVmKoCt3Kurist6xASn9EcaYQma1RXZG9PwD&i=AwA&r=tryAPL&l=apl-dyalog&m=dfn&n=f)
A dfn submission, assumes `⎕IO←0`.
Ungolfed:
```
X ← {+/⍺×*(○0J¯2×⍵×⍳≢⍺)÷≢⍺}
f ← {⍵∘X¨⍳≢⍵}
```
APL translated to Python:
```
from math import *
def f(sequence):
def X(n):
return sum(
sequence[b] # ⍺
* e ** # ×*(...)
(
pi*-2j # ○0J¯2
* n # ×⍵
* b # ×⍳≢⍺
/ len(sequence) # ÷≢⍺
)
for b in range(len(sequence))
)
return [X(i) for i in range(len(sequence))] # ⍵∘X¨⍳≢⍵
```
First it binds the sequence to a dfn, and runs the resulting function on each element in the range from \$0\$ to \$N\$ -- `{⍵∘{...}¨⍳≢⍵}`.
In the inner dfn it sums -- `+/` -- the sequence -- `⍺` -- times \$e\$ to the power of -- `×*(...)` -- \$\pi\$ times \$-2i\$ -- `○0J¯2` -- times \$k\$ -- `⍵` -- times each \$n\$ from \$0\$ to \$N\$ -- `⍳≢⍵` -- divided by \$N\$ -- `÷≢⍺`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~20~~ 16 bytes
```
-1yn:qt!Gn/E*^/s
```
Input is a column vector, i.e. use semicolon as separator:
```
[1; 1; 1; 1]
[1; 0; 2; 0; 3; 0; 4; 0]
[1; 2; 3; 4; 5]
[5-3.28571j; -0.816474-0.837162j; 0.523306-0.303902j; 0.806172-3.69346j; -4.41953+2.59494j; -0.360252+2.59411j; 1.26678+2.93119j]
```
This uses the formula in [Leaky Nun's answer](https://codegolf.stackexchange.com/a/82650/36398), based on the facts that exp(*iπ*) = −1, and that MATL's power operaton with non-integer exponent produces (as in most programming languages) the [principal branch](http://mathworld.wolfram.com/CubeRoot.html) result.
[**Try it online!**](http://matl.tryitonline.net/#code=LTF5bjpxdCFHbi9FKl4vcw&input=WzE7IDA7IDI7IDA7IDM7IDA7IDQ7IDBd)
Due to Octave's weird spacing when displaying complex numbers, the real and imaginary parts in each entry of the output are separated by a space, as are consecutive entries. If that looks too ugly, add a `!` at the end of the code (17 bytes) to have each entry of the output on a different line.
### Explanation
```
-1 % Push -1
y % Get input implicitly. Push a copy below and one on top of -1
n:q % Row vector [0 1 ... N-1] where N is implicit input length
t! % Duplicate and transpose: column vector
Gn % Push input length
/ % Divide
E % Multiply by 2
* % Multiply, element-wise with broadcast. Gives the exponent as a matrix
^ % Power (base is -1), element-wise. Gives a matrix
/ % Divide matrix by input (column vector), element-wise with broadcast
s % Sum
```
[Answer]
# Pyth, 30
```
ms.e*b^.n1****c_2lQk.n0d.j0)QU
```
[Test Suite](http://pyth.herokuapp.com/?code=ms.e%2ab%5E.n1%2a%2a%2a%2ac_2lQk.n0d.j0%29QU&input=%5B1%2C+1%2C+1%2C+1%5D&test_suite=1&test_suite_input=%5B1%2C+1%2C+1%2C+1%5D%0A%5B1%2C+0%2C+2%2C+0%2C+3%2C+0%2C+4%2C+0%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%5D%0A%5B5-3.28571j%2C+-0.816474-0.837162j%2C+0.523306-0.303902j%2C+0.806172-3.69346j%2C+-4.41953%2B2.59494j%2C+-0.360252%2B2.59411j%2C+1.26678%2B2.93119j%5D&debug=0)
Very naive approach, just an implementation of the formula. Runs into various minor floating point issues with values which should be additive inverses adding to result in values that are slightly off of zero.
Oddly `.j` doesn't seem to work with no arguments, but I'm not sure if I'm using it correctly.
[Answer]
# Pyth, 18 bytes
Uses the fact that `e^ipi = -1`.
The formula becomes `X_k = sum(x_n / ((-1)^(2nk/N)))`.
```
ms.ecb^_1*cyklQdQU
```
[Test suite.](http://pyth.herokuapp.com/?code=ms.ecb%5E_1%2acyklQdQU&input=%5B1%2C+1%2C+1%2C+1%5D&test_suite=1&test_suite_input=%5B1%2C1%2C1%2C1%5D%0A%5B1%2C0%2C2%2C0%2C3%2C0%2C4%2C0%5D%0A%5B1%2C2%2C3%2C4%2C5%5D%0A%5B5-3.28571j%2C-0.816474-0.837162j%2C0.523306-0.303902j%2C0.806172-3.69346j%2C-4.41953%2B2.59494j%2C-0.360252%2B2.59411j%2C1.26678%2B2.93119j%5D&debug=0)
[Answer]
# Julia, 45 bytes
```
~=endof
!x=sum(x./im.^(4(r=0:~x-1).*r'/~x),1)
```
[Try it online!](http://julia.tryitonline.net/#code=fj1lbmRvZgoheD1zdW0oeC4vaW0uXig0KHI9MDp-eC0xKS4qcicvfngpLDEpCgpwcmludGxuKCFbMSwgMSwgMSwgMV0sICJcbiIpCnByaW50bG4oIVsxLCAwLCAyLCAwLCAzLCAwLCA0LCAwXSwgIlxuIikKcHJpbnRsbighWzEsIDIsIDMsIDQsIDVdLCAiXG4iKQpwcmludGxuKCFbNS0zLjI4NTcxaW0sIC0wLjgxNjQ3NC0wLjgzNzE2MmltLCAwLjUyMzMwNi0wLjMwMzkwMmltLCAwLjgwNjE3Mi0zLjY5MzQ2aW0sIC00LjQxOTUzKzIuNTk0OTRpbSwgLTAuMzYwMjUyKzIuNTk0MTFpbSwgMS4yNjY3OCsyLjkzMTE5aW1dLCAiXG4iKQ&input=)
The code uses the equivalent formula

[Answer]
## Python 2, 78 bytes
```
l=input();p=1
for _ in l:print reduce(lambda a,b:a*p+b,l)*p;p*=1j**(4./len(l))
```
The polynomial is evaluated for each power `p` of `1j**(4./len(l))`.
The expression `reduce(lambda a,b:a*p+b,l)` evaluates the polynomial given by `l` on the value `p` via Horner's method:
```
reduce(lambda a,b:a*10+b,[1,2,3,4,5])
=> 12345
```
Except, out input list is reversed, with constant term at the end. We could reverse it, but because `p**len(l)==1` for Fourier coefficients, we can use a hack of inverting `p` and multiplying the whole result by `p`.
Some equal-length attempts:
```
l=input();i=0
for _ in l:print reduce(lambda a,b:(a+b)*1j**i,l,0);i+=4./len(l)
l=input();i=0
for _ in l:print reduce(lambda a,b:a*1j**i+b,l+[0]);i+=4./len(l)
```
As a function for 1 byte more (79):
```
lambda l:[reduce(lambda a,b:a*1j**(i*4./len(l))+b,l+[0])for i in range(len(l))]
```
An attempt at recursion (80):
```
f=lambda l,i=0:l[i:]and[reduce(lambda a,b:(a+b)*1j**(i*4./len(l)),l,0)]+f(l,i+1)
```
Iteratively simulating `reduce` (80):
```
l=input();p=1;N=len(l)
exec"s=0\nfor x in l:s=s*p+x\nprint s*p;p*=1j**(4./N);"*N
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~86~~ 78 bytes
```
k;d(a,b,c)_Complex*a,*b;{for(k=c*c;k--;)b[k/c]+=a[k%c]/cpow(1i,k/c*k%c*4./c);}
```
[Try it online!](https://tio.run/##tZLbauMwEIbv@xRDICD5FJ1to/XVPkbWLLJqB@E4CUlKly159bqSvVt2oSmFtBfWeH5J82s@yaYba8ex1/fIJE1i8c/v@@GwbX9FJoka/dTtj6ivbGR1n6YaN@t@Zeu4Mut@aeuVPewfEXWJFyMvRCJbWawv498iYNaU1PruNW/m3O3OMBi3Q/jpDvwiUvuKNAwsDLyuqPYTwRzCWgcVEO3DNxA@xDFgCDsBDkc/3yFYLLt42TlYJGCPrdkis3Y19okbzGZOAIeaF/8dHs4ntFhM@T0Ck0CTgMC3Wjb/WjZvWf7YzaZ/mvV9Ej11T/XUOvNB1BX3QdWVCEuHdji1ZxROSBI4ud/tvoPm6lmLz8MD//Mpbvb8OJ93mn7FRWdcbMbFA64Jnrx2TPllaCS@1fPz0MiUZ6yQOXUzo5RkBVUiF@GH51QxN1MjmWScE@V1TnhJJj28yKwgiubM11ElF8rNWFORCVpKHrNMlqIUQZZTea4Ik2zW6WTr3y7NmFJ54dWSU1q6a4DyL7uUHN/q@dFLuYzPttuazWlMt8ML "C (gcc) – Try It Online")
This assumes the output vector is zeroed out before use.
[Answer]
# Python 2, 89 bytes
Uses the fact that `e^ipi = -1`.
The formula becomes `X_k = sum(x_n / ((-1)^(2nk/N)))`.
```
lambda a:[sum(a[x]/(-1+0j)**(x*y*2./len(a))for x in range(len(a)))for y in range(len(a))]
```
[Ideone it!](http://ideone.com/JEFwdH)
[Answer]
# Mathematica, ~~49~~ ~~48~~ 47 bytes
```
Total[I^Array[4(+##-##-1)/n&,{n=Length@#,n}]#]&
```
Based on the formula from @Dennis' [solution](https://codegolf.stackexchange.com/a/82658/6710).
[Answer]
# Axiom, 81 bytes
```
g(x)==(#x<2=>x;[reduce(+,[x.j/%i^(4*k*(j-1)/#x)for j in 1..#x])for k in 0..#x-1])
```
using the formula someone post here. Results
```
(6) -> g([1,1,1,1])
(6) [4,0,0,0]
Type: List Expression Complex Integer
(7) -> g([1,2,3,4])
(7) [10,- 2 + 2%i,- 2,- 2 - 2%i]
Type: List Expression Complex Integer
(8) -> g([1,0,2,0,3,0,4,0])
(8) [10,- 2 + 2%i,- 2,- 2 - 2%i,10,- 2 + 2%i,- 2,- 2 - 2%i]
Type: List Expression Complex Integer
(11) -> g([1,2,3,4,5])
(11)
5+--+4 5+--+3 5+--+2 5+--+
\|%i + 5%i \|%i - 4\|%i - 3%i\|%i + 2
[15, --------------------------------------------,
5+--+4
\|%i
5+--+4 5+--+3 5+--+2 5+--+
\|%i + 3%i \|%i - 5\|%i - 2%i\|%i + 4
--------------------------------------------,
5+--+4
\|%i
5+--+4 5+--+3 5+--+2 5+--+
\|%i + 4%i \|%i - 2\|%i - 5%i\|%i + 3
--------------------------------------------,
5+--+4
\|%i
5+--+4 5+--+3 5+--+2 5+--+
\|%i + 2%i \|%i - 3\|%i - 4%i\|%i + 5
--------------------------------------------]
5+--+4
\|%i
Type: List Expression Complex Integer
(12) -> g([1,2,3,4,5.])
(12)
[15.0, - 2.5 + 3.4409548011 779338455 %i, - 2.5 + 0.8122992405 822658154 %i,
- 2.5 - 0.8122992405 822658154 %i, - 2.5 - 3.4409548011 779338455 %i]
Type: List Expression Complex Float
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~43~~ 39 bytes
```
@(x)j.^(-4*(t=0:(s=rows(x))-1).*t'/s)*x
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzSy9OQ9dES6PE1sBKo9i2KL@8GCiqqWuoqadVoq5frKlV8T9Nw1STK00j2lDBAARj1aE8MITxdBQMdBSMwKQxmDTRASv9DwA "Octave – Try It Online")
Multiplies the input vector by the DFT matrix.
[Answer]
# [Raku](http://raku.org/), 40 bytes
```
{^$_ .map: ((1.roots($_)X**-*)Z*$_).sum}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Ok4lXkEvN7HASkFDw1CvKD@/pFhDJV4zQktLV0szSgvI1Csuza39X5xYqaAEVGtrp1CdBlJxaDdQdWleioaBnoGhZq2SQlp@kYKNoQIY2umAmAYKRkBsDMQmCgYQISMg10TB1O4/AA "Perl 6 – Try It Online")
* `$_` is the input list.
* `^$_` is the sequence of integers from zero to one less than the size of the list.
* `.map:` maps those indices over the following anonymous function, where the `*` which follows `X**-` assumes the value of each successive index.
* `1.roots($_)` returns the N complex roots of unity, where N is the size of the input list `$_`.
* `X** -*` cross-exponentiates those roots with the negative of the current index into the input list.
* `Z* $_` zips-with-multiplication those powers of the roots of unity with the input list.
* `.sum` sums the zipped list.
] |
[Question]
[
Given 3 positive integers `a`, `b`, and `n` (whose maximum values are the maximum representable integer value in your language), output a truthy value if `a ≡ b (mod n)`, and falsey otherwise. For those unfamiliar with congruency relations, `a ≡ b (mod n)` is true iff `a mod n = b mod n` (or, equivalently, `(a - b) mod n = 0`).
## Restrictions
* Built-in congruence testing methods are forbidden
* Built-in modulo operations are forbidden (this includes operations such as Python's `divmod` function, which return both the quotient and the remainder, as well as divisibility functions, residue system functions, and the like)
## Test Cases
```
(1, 2, 3) -> False
(2, 4, 2) -> True
(3, 9, 10) -> False
(25, 45, 20) -> True
(4, 5, 1) -> True
(83, 73, 59) -> False
(70, 79, 29) -> False
(16, 44, 86) -> False
(28, 78, 5) -> True
(73, 31, 14) -> True
(9, 9, 88) -> True
(20, 7, 82) -> False
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code (in bytes) wins, with earliest submission as a tiebreaker.
[Answer]
# Jelly, 5 bytes
```
_ÆD⁵e
```
Making heavy use of [*Anything else that is not forbidden is allowed.*](https://codegolf.stackexchange.com/questions/71905/congruence-relations#comment176135_71905)
[Try it online!](http://jelly.tryitonline.net/#code=X8OGROKBtWU&input=&args=Nw+Mw+NA)
### How it works
```
_ÆD⁵e Main link. Left input: a. Right input: b. Additional input: n
_ Subtract b from a.
ÆD Compute all divisors of the difference.
⁵e Test if n is among the divisors.
```
[Answer]
## Python 2, 27 bytes
```
lambda a,b,n:(a-b)/n*n==a-b
```
Checks if `a-b` is a multiple of `n` by dividing by `n`, which automatically floors, and seeing if multiplying back by `n` gives the same result.
[Answer]
# Julia, 24 bytes
```
f(a,b,n,t=a-b)=t÷n==t/n
```
This is a function that accepts three integers and returns a boolean.
We simply test whether *a* - *b* integer divded by *n* is equal to *a* - *b* float divided by *n*. This will be true when there is no remainder from division, i.e. *a* - *b* | *n*, which implies that *a* - *b* (mod *n*) = 0.
[Answer]
## Pyth, 7 bytes
```
!@UQ-FE
```
Uses Pyth's cyclic indexing.
```
UQ range(first line). [0,...,Q-1]
-FE Fold subtraction over the second line.
@ Cyclic index UQ at -FE
! Logical NOT
```
[Answer]
## Haskell, 23 bytes
```
(a#b)n=div(a-b)n*n==a-b
```
Usage example: `(28#78)5` -> `True`.
Same method as in [@xnor's answer](https://codegolf.stackexchange.com/a/71907/34531).
[Answer]
## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), ~~14~~ 11 bytes
```
nn-n$d:*=N.
```
[Try it here!](http://play.starmaninnovations.com/minkolang/?code=nn-n%24d%3A*%3DN%2E&input=17%205%203) Input is expected as `a b n`.
### Explanation:
```
n Take number from input -> a
n Take number from input -> a, b
- Subtract -> a-b
n Take number from input -> a-b, n
$d Duplicate stack -> a-b, n, a-b, n
: Integer division -> a-b, n, (a-b)//n
* Multiply -> a-b, (a-b)//n*n
= 1 if equal, 0 otherwise
N. Output as number and stop.
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 9 bytes
```
Sdt:i*0hm
```
Input format is
```
[a b]
n
```
[**Try it online!**](http://matl.tryitonline.net/#code=U2R0OmkqMGht&input=WzI4IDc4XQo1Cg)
```
S % implicitly input [a, b]. Sort this array
d % compute difference. Gives abs(a-b)
t: % duplicate and generate vector [1,2,...,abs(a-b)]; or [] if a==b
i* % input n and multiply to obtain [n,2*n,...,abs(a-b)*n]; or []
0h % concatenate element 0
m % ismember function. Implicitly display
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 20
```
^(1+) \1*(1*) \1*\2$
```
Input is given in unary, space-separated, in order `n a b`. Output 1 for truthy and 0 for falsey.
[Try it online.](http://retina.tryitonline.net/#code=XigxKykgXDEqKDEqKSBcMSpcMiQ&input=MTExIDEgMTE)
---
If you prefer decimal input then you can do this:
```
\d+
$&$*1
^(1+) \1*(1*) \1*\2$
```
[Try it online.](http://retina.tryitonline.net/#code=XGQrCiQmJCoxCl4oMSspIFwxKigxKikgXDEqXDIk&input=MiA1IDc)
[Answer]
# APL, 15 bytes
```
{(⌊d)=d←⍺÷⍨-/⍵}
```
This is a dyadic function that accepts *n* on the left and *a* and *b* as an array on the right.
The approach here is basically the same as in my Julia [answer](https://codegolf.stackexchange.com/a/71909/20469). We test whether *a* - *b* / *n* is equal to the floor of itself, which will be true when *a* - *b* (mod *n*) = 0.
[Answer]
# JavaScript (ES6), 27 bytes
@CᴏɴᴏʀO'Bʀɪᴇɴ posted a version which does not work; here is the "common algorithm" that people are using in a form which "works":
```
(a,b,n)=>n*(0|(a-b)/n)==a-b
```
The word "works" is in scare quotes because the shortcut we're using for `Math.floor()` implicitly truncates a number to be in the signed 32-bit range, so this cannot handle the full 52-bit-or-whatever space of integers that JavaScript can describe.
[Answer]
## CJam, 7 bytes
```
l~-\,=!
```
Input order is `n a b`.
[Test it here.](http://cjam.aditsu.net/#code=l~-%5C%2C%3D!&input=14%2073%2031)
### Explanation
```
l~ e# Read input and evaluate to push n, a and b onto the stack.
- e# Subtract b from a.
\, e# Swap with n and turn into range [0 1 ... n-1].
= e# Get (a-b)th element from that range, which uses cyclic indexing. This is
e# equivalent to modulo, and as opposed to the built-in % it also works correctly
e# for negative (a-b).
! e# Negate, because a 0 result from the previous computation means they are congruent.
```
[Answer]
## Python 3, 27 bytes
```
lambda a,b,n:pow(a-b,1,n)<1
```
`pow(x,y,n)` calculates `(x**y)%n`, so this is just `(a-b)**1%n`.
[Answer]
## ES6, 28 bytes
```
(a,b,n)=>!/\./.test((a-b)/n)
```
Works by looking for a decimal point in (a-b)/n which I'm hoping is allowed.
[Answer]
## Seriously, 10 bytes
```
,,,-A│\)/=
```
Takes input as `N\nA\nB\n` (capital letters used to distinguish from newlines).
[Try it online](http://seriously.tryitonline.net/#code=LCwsLUHilIJcKS89&input=NQoyNQo1)
This uses the same method as [@AlexA's answer](https://codegolf.stackexchange.com/a/71909/45941)
Explanation (capital letters used as variable names for explanatory purposes):
```
,,,-A│\)/=
,,, push N, A, B
-A push C = abs(A-B)
│ duplicate entire stack (result is [N, C, N, C])
\)/= 1 if C//N == C/N (floored division equals float division)
```
[Answer]
## F#, 24 bytes
```
fun a b n->(a-b)/n*n=a-b
```
Implements the same check as [@xnor's answer](https://codegolf.stackexchange.com/questions/71905/congruence-relations/71907#71907).
] |
[Question]
[
## The challenge
The program must return all numbers included into a group (comma and hyphen separated sequence) of numbers.
## Rules
* `s` is the sequence string;
* all numbers included in `s` are **positive**;
* numbers will always **increase**;
* numbers will **never repeat**
* when you answer, show the output for `s="1,3-5,9,16,18-23"`
## Examples
```
input(s) outputs
-----------------
1 1
1,2 1,2
1-4 1,2,3,4
1-4,6 1,2,3,4,6
1-4,8-11 1,2,3,4,8,9,10,11
```
Good luck. =)
[Answer]
## Perl 25 26 25
`$_` is the sequence string
```
s/-/../g;$_=join",",eval
```
Sample session:
```
[~/] $ perl -M5.010 -pe 's/-/../g;$_=join",",eval' <<< "1,3-5,9,16,18-23"
1,3,4,5,9,16,18,19,20,21,22,23
```
Added 1 character to the character count for the `-n``-p` option (thanks Gareth, ..kinda).
[Answer]
## GolfScript (24 chars)
```
','/{~.,!{~)),>~}*}%','*
```
E.g.
```
$ golfscript.rb expand.gs <<<"1,3-5,9,16,18-23"
1,3,4,5,9,16,18,19,20,21,22,23
```
I actually have four 24-char solutions, but I chose this one because it doesn't have any alphanumeric characters.
### How it works
```
# On the stack: a string such as "1,3-5,9,16,18-23"
','/
# Split on commas to get ["1" "3-5" "9" "16" "18-23"]
{
# This is executed for each of those strings in a map
# So stack holds e.g. "1" or "3-5"
# Evaluate the string.
# If it's a single number, this puts the number on the stack.
# Otherwise it's parsed as a positive number followed by a negative number.
~
# Stack holds e.g. 1 or 3 -5
# Duplicate the last element on the stack and make a list of that length.
# If it's negative or zero, the list will be empty
.,
# Negate. An empty list => 1; a non-empty list => 0
!
# If the string was a single number "n", the stack now holds n 0
# If the string was a range "m-n", the stack now holds m -n 1
# The following block will be executed 0 times for "n" and once for "m-n"
{
# Here we rely on twos-complement numbers satisfying ~n = -n -1
# Stack: m -n
~))
# Stack: m -(-n)-1+2 = m n+1
,
# Stack: m [0 1 2 ... n]
>
# Stack: [m m+1 ... n]
~
# Stack: m m+1 ... n
}*
}%
# On the stack: e.g. [1 3 4 5 9 16 18 19 20 21 22 23]
','*
# Joined by , to give the desired output
```
[Answer]
## golfscript, 46 45
My first ever golf script program, took hours to complete.
```
{','/{'-'/{~}%.,1-{))+{,}/\-~}{~}if}%","*}:r;
# call:
"1,3-5,9,16,18-23"r
# return:
1,3,4,5,9,16,18,19,20,21,22,23
```
You can try it at <http://golfscript.apphb.com/>
My best throw at explaining this atrocity:
```
{...}:r; # makes a function block ... and names it r
','/ # slices the top element of stack from each ','
# so we get ["1" "3-5" "9" "16" "18-23"]
{...}% # makes a function block ... and calls it for
# each element in the list
'-'/{~}% # slices the list by '-' and evals each element
# from string to int. ["1"] becomes [1],
# ["3-5"] becomes [3 5]
.,1- # adds the length of the list -1 on top of the stack
# so for [1] the stack becomes [1] 0, for [3 5]
# it becomes [3 5] 1
# next we add two function blocks, they, like the 0/1 just before
# are used by an if clause a tiny bit later. First block is for
# lists that have a 1 on top of them, the latter for ones with 0.
# First block, we have something like [3 5]
))+ # pops the top element of the array, increments
# it and puts back. [3 6]
## It seems {...}%~ is same as {...}/
## this is why these two are not in the code any more
{,}% # , makes a list from 0 to n-1, where n is the parameter
# so we get [[0 1 2] [0 1 2 3 4 5]]
~ # Dumps the outer array, [0 1 2] [0 1 2 3 4 5]
\ # swaps the two arrays
- # set complement [3 4 5]
~ # dumps the array, so the elements are left in the stack
# Second block, we have something like [16]
~ # just dumps the array, 16
# Blocks end
if # takes the top three elements of the stack, evaluates the
# first (0 or 1), runs second if true (anything but
# [], "", 0 or {} ), otherwise the third.
","* # joins an array with ","
```
**edit 1:** changed the last {}%~ to {}/, also my description was likely wrong.
[Answer]
# [R](https://www.r-project.org/), 44 bytes
```
`-`=seq;eval(parse(t=c("c(",scan(,""),")")))
```
[Try it online!](https://tio.run/##K/r/P0E3wbY4tdA6tSwxR6Mgsag4VaPENllDCYh0ipMT8zR01NU1dZQ0lTQ1Nf8b6hjrmupY6hia6Rha6BoZ/wcA "R – Try It Online")
Redefine `-` to mean `seq` (i.e. `:`), surround the input with `c()` and evaluate the corresponding expression.
[Answer]
# K, 47
```
","/:,/${x+!1+y-x}.'2#'a,'a:"I"$'"-"\:'","\:0:0
```
Test case
```
k)","/:,/${x+!1+y-x}.'2#'a,'a:"I"$'"-"\:'","\:0:0
1,3-5,9,16,18-23
"1,3,4,5,9,16,18,19,20,21,22,23"
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
⁾-ryṣ”,VF
```
[Try it online!](https://tio.run/##y0rNyan8//9R4z7dosqHOxc/apirE@b2/3D7o6Y1//9HKxkq6SgZ6hiBSF0TCKljBqUtdA0h0sa6pjqWOoZmOoYWukbGSrEA "Jelly – Try It Online")
```
y Replace
⁾-r hyphens with the letter r,
ṣ”, split on commas,
V evaluate every element,
F and flatten.
```
The range dyad `r` takes two arguments on either side of it and produces an inclusive range between them.
[Answer]
## J, 53 43 41 39 38 characters
```
;(}.[:i.1+])/&.>".'- ,;'charsub 1!:1[1
```
Takes input from the keyboard:
```
;(}.[:i.1+])/&.>".'- ,;'charsub 1!:1[1
1-4,8-11
1 2 3 4 8 9 10 11
```
Output for the requested test case:
```
;(}.[:i.1+])/&.>".'- ,;'charsub 1!:1[1
1,3-5,9,16,18-23
1 3 4 5 9 16 18 19 20 21 22 23
```
[Answer]
# [Hassium](http://HassiumLang.com), 173 Bytes
This was pretty long and might not be competing since there is a trailing , at the end.
```
func main(){p="1,2,3,5-8".split(",")for(c=0;c<p.length;c++){e=p[c]if(e.contains("-")){p=e.split("-")for(x=p[0].toInt();x<=p[1].toInt()print(x++ +",")){}}else print(e+",")}}
```
Run online and see expanded [here](http://HassiumLang.com/Hassium/index.php?code=7669e900236a52c9cf109d3ebd779b26)
[Answer]
## Perl (37)
```
$_=<>;s/^/say join',',/;s/-/../g;eval
```
[Answer]
## Python 2.7, 147 138 Bytes
```
z,f=input().split(','),[]
for i in z:
x=i.split('-')
if len(x)>1:f+=range(int(x[0]),int(x[1])+1)
else:f+=[int(x[0])]
print str(f)[1:-1]
```
Usage:
```
>>>python nums.py
"1,3-5,9,16,18-23"
1, 3, 4, 5, 9, 16, 18, 19, 20, 21, 22, 23
```
Not the best program...
[Answer]
## MATLAB, 47 bytes
```
disp(eval(['[',strrep(input(''),'-',':'),']']))
```
This snippet reads a string input from the command window, replaces '-' by ':', adds square brackets to the string and then evaluates it, so that the input will be expanded to a full array of numbers.
Example input:
```
'1,3-5,9,16,18-23'
```
Example output:
```
1 3 4 5 9 16 18 19 20 21 22 23
```
I believe this output is allowed, as the challenge only say that all numbers in a group should be displayed.
[Answer]
## [Perl 6](http://perl6.org), 36 bytes
```
$_=get;say join ',',EVAL S:g/\-/../
```
```
1,3,4,5,9,16,18,19,20,21,22,23
```
[Answer]
## PowerShell, ~~79~~ 71 bytes
```
('('+($args[0]-replace'-','..'-replace',','),(')+')'|iex|%{$_})-join','
```
[Try it online!](https://tio.run/##PYnBCoJAEEDvfkUsm7OLM9K4FXboSyJEYkxlSVkPBeq3bx4i3um9Nw5vCVMr3kfdXOdowEBmdB2e0@1wpyCjrx8CBAh5Dn/HDYsGbAYWlk4@y37W1WqpH7rX9uKaJKludorpiCUxIzv1K@johBfkM3JJhVPxCw "PowerShell – Try It Online")
The inner part changes "1,5-9,12" into a "(1),(5..9),(12)" format that PowerShell understands, then executes that with iex, which creates an array of arrays. Then iterate through each inner array, then finally join all outer array elements together
Borrows code from my "Help Me Manage My Time" [answer](https://codegolf.stackexchange.com/a/64236/42963)
### Usage
```
PS C:\Tools\Scripts\golfing> .\return-each-number-from-a-group-of-numbers.ps1 '1,3-5,9,16,18-23'
1,3,4,5,9,16,18,19,20,21,22,23
```
*-8 bytes thanks to Veskah*
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~40~~ 31 bytes
**Solution**
```
,/{{x+!1+y-x}. 2#.:'"-"\x}'","\
```
[Try it online!](https://tio.run/##y9bNz/7/X0e/urpCW9FQu1K3olZPwUhZz0pdSVcppqJWXUlHKUbJUMdY11THUsfQTMfQQtfIWOn/fwA "K (oK) – Try It Online")
**Explanation:**
Managed more golfing whilst adding the explanation...
```
,/{{x+!1+y-x}. 2#.:'"-"\x}'","\ / the solution
","\ / split input on ","
{ }' / apply lambda to each
"-"\x / split x on "-"
.:' / value (.:) each (')
2# / 2 take (dupe if only 1 element)
{ }. / diadic lambda, 2 args x and y
y-x / y subtract x
1+ / add 1
! / range 0..n
x+ / add x
,/ / flatten
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
ṁȯ…mix'-x',
```
[Try it online!](https://tio.run/##yygtzv7//@HOxhPrHzUsy82sUNetUNf5//@/oa6JjoWuoSEA "Husk – Try It Online")
[Answer]
## Clojure, 110 bytes
```
#(clojure.string/join","(for[s(.split %",")[a b][(map read-string(.split s"-"))]r(if b(range a(inc b))[a])]r))
```
Dealing with strings isn't much fun :(
[Answer]
# [Python 2](https://docs.python.org/2/), 112 bytes
Pretty simple and straightforward answer.
```
L=[]
for s in input().split(','):
if'-'in s:a,b=map(int,s.split('-'));L+=range(a,b+1)
else:L+=[int(s)]
print L
```
[Try it online!](https://tio.run/##NcpBCsMgEAXQvacYstEhWrC0UCzewBuELCyYVkiNOHbR09vZFP7i8/@r3/46ynmM4JdVbEcDglw49dMVnqjuuSupJToBeZNG8kku6od/x6py6Zr@yEjEe5h9i@WZFJPZooC0U3K8LmwV4Spq4wZhjMmai74Za7W9Tj8 "Python 2 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-p`, 33 bytes
```
gsub(/(\d+)-(\d+)/){[*$1..$2]*?,}
```
[Try it online!](https://tio.run/##KypNqvz/P724NElDXyMmRVtTF0zqa1ZHa6kY6umpGMVq2evU/v9vqGuiY8YFIi10DQ25DHWMdU11LHUMzXQMLXSNjP/lF5Rk5ucV/9ctAAA "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 bytes
```
q, c@OvXr-'ò
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cSwgY0BPdlhyLSfy&input=IjEsMy01LDksMTYsMTgtMjMi)
[Answer]
# [Python 2](https://docs.python.org/2/), 90 bytes
```
lambda s:sum((range(u[0],u[-1]+1)for u in[map(int,t.split('-'))for t in s.split(',')]),[])
```
[Try it online!](https://tio.run/##NcpNCsIwEEDhvaeYXWZwUkyLooIniVlENBpo0pCfRU8fi@D2fS@t9bPEsbvbvc82PJ4WyrW0gJhtfL@w6YPhpqUye0VuydDARx1sQh8r16Gk2VcUUtBP66ZQ/pUFGWJtqKe87eBQKJ7kkS@sTqzOcpwE7foX "Python 2 – Try It Online")
[Answer]
## Lua (126 bytes)
Just for fun:
```
(("1,3-5,9,16,18-23"):gsub("(%d+)-(%d+)",function(a,b)t={}for i=a,b do t[#t+1]=math.ceil(i)end return table.concat(t,",")end))
```
] |
[Question]
[
Given a list of numbers \$[a\_1, a\_2, ... a\_n]\$, compute the sum of all the matrices \$A\_i\$ where \$A\_i\$ is defined as follows (\$m\$ is the maximum of all \$a\_i\$):
$$
\begin{array}{c|cc}
& 1 & 2 & \cdots & i-1 & i & i+1 & \cdots & n \\
\hline
1 & 0 & 0 & \cdots & 0 & a\_i & a\_i & \cdots & a\_i \\
2 & 0 & 0 & \cdots & 0 & a\_i & a\_i & \cdots & a\_i \\
\vdots & & \vdots & & \vdots & & \vdots & & \vdots \\
a\_i & 0 & 0 & \cdots & 0 & a\_i & a\_i & \cdots & a\_i \\
a\_{i+1}& 0 & 0 & \cdots & 0 & 0 & 0 & \cdots & 0 \\
\vdots & & \vdots & & \vdots & & \vdots & & \vdots \\
m & 0 & 0 & \cdots & 0 & 0 & 0 & \cdots & 0 \\
\end{array}
$$
## Example
Given the input `[2,1,3,1]` we construct the following matrix:
$$
\left[\begin{matrix}
2 & 2 & 2 & 2 \\
2 & 2 & 2 & 2 \\
0 & 0 & 0 & 0 \\
\end{matrix}\right]
+
\left[\begin{matrix}
0 & 1 & 1 & 1 \\
0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 \\
\end{matrix}\right]
+
\left[\begin{matrix}
0 & 0 & 3 & 3 \\
0 & 0 & 3 & 3 \\
0 & 0 & 3 & 3 \\
\end{matrix}\right]
+
\left[\begin{matrix}
0 & 0 & 0 & 1 \\
0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 \\
\end{matrix}\right]
=
\left[\begin{matrix}
2 & 3 & 6 & 7 \\
2 & 2 & 5 & 5 \\
0 & 0 & 3 & 3 \\
\end{matrix}\right]
$$
## Rules and I/O
* you may assume the input is non-empty
* you may assume all the inputs are non-negative (0≤)
* the input can be a \$1×n\$ (or \$n×1\$) matrix, list, array etc.
* similarly the output can be a matrix, list of lists, array etc.
* you can take and return inputs via any [default I/O format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* your submission may be a full program or function
## Test cases
```
[0] -> [] or [[]]
[1] -> [[1]]
[3] -> [[3],[3],[3]]
[2,2] -> [[2,4],[2,4]]
[3,0,0] -> [[3,3,3],[3,3,3],[3,3,3]]
[1,2,3,4,5] -> [[1,3,6,10,15],[0,2,5,9,14],[0,0,3,7,12],[0,0,0,4,9],[0,0,0,0,5]]
[10,1,0,3,7,8] -> [[10,11,11,14,21,29],[10,10,10,13,20,28],[10,10,10,13,20,28],[10,10,10,10,17,25],[10,10,10,10,17,25],[10,10,10,10,17,25],[10,10,10,10,17,25],[10,10,10,10,10,18],[10,10,10,10,10,10],[10,10,10,10,10,10]]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 5 bytes
```
ẋ"z0Ä
```
[Try it online!](https://tio.run/##y0rNyan8///hrm6lKoPDLf8Ptz9qWuMOxFmPGvcd2nZo2///0UY6hjrGOoaxOgrRBiACzDIGEUY6RmC2joEOREbHCKjSRMcUzDEA6jMA8s11LGIB "Jelly – Try It Online")
### How it works
```
ẋ"z0Ä Main link. Argument: A (array)
e.g. [2, 1, 3, 1]
ẋ" Repeat each n in A n times.
e.g. [[2, 2 ]
[1 ]
[3, 3, 3]
[1 ]]
z0 Zipfill 0; read the result by columns, filling missing elements with 0's.
e.g. [[2, 1, 3, 1]
[2, 0, 3, 0]
[0, 0, 3, 0]]
Ä Take the cumulative sum of each row vector.
e.g. [[2, 3, 6, 7]
[2, 2, 5, 5]
[0, 0, 3, 3]]
```
[Answer]
# [R](https://www.r-project.org/), 80 bytes
```
n=sum((a=scan())|1);for(i in 1:n)F=F+`[<-`(matrix(0,max(a),n),0:a[i],i:n,a[i]);F
```
[Try it online!](https://tio.run/##FcYxCoAwDADAr2RMMEKrW7VrPyGCQRAyNEJV6ODfK950pTWL15MRJV67GBK9nqbjLKigBj4YpZi6bZn7DbPcRSs6zlJRiI3YBVl0ZQ3Gf2hKbQAPI/j2AQ "R – Try It Online")
Takes input from stdin; prints a `0x1` matrix for input `0`, which prints out like
```
[,1]
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~70~~ ~~66~~ 51 bytes
```
g x=[scanl1(+)[sum[n|n>=r]|n<-x]|r<-[1..maximum x]]
```
[Try it online!](https://tio.run/##rY3BasMwDIbvfgoddtiYXCwnWVNo@gZ7AqODGaMLjb2SrBBY9uyZnDqDQWGXgWzp//RLevPD6bXr5vkIY@OGFx87un98cMMluDjFQ9PzFPd65Knfa0ebTfBjGy4BRuY5@DZCA8Gfn@Hct/ED7uAIziJhgcRKfWrlDIM@gGN478E5ZuXoSiSLKLIoGPMTaNFmbLEUmP7kRYNm9cuJxf8rp@1opSyxWq@IekIySJXYjHQr3CGVizDS3CLZLIzM7X5qIzvSQhnNxnrdKYiWKNHKwTST2DUKtHKm/pNJbNFW/8kk6hvM3GSs9Nf8DQ "Haskell – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 8 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Full program. Prompts stdin for list, prints matrix to stdout.
Uses [Dennis's method](https://codegolf.stackexchange.com/a/165301/43319).
```
+\⍉↑⍴⍨¨⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L92zKPezkdtEx/1bnnUu@LQikd9U0ES/xXAoIDLSMdQx1jHkAvG1zFAMJFEjbkQGozgbGMdAyT1hjpGQKNMdEwRIgZA0w2AguY6FgA "APL (Dyalog Unicode) – Try It Online")
`⎕` stdin
`⍴⍨¨` **r**eshape-selfie of each
`↑` mix list of lists into matrix, filling with 0s
`⍉` transpose
`+\` cumulative row-wise sum
The `⍉` doesn't make any computational difference, so it could potentially be left out and `\` changed to `⍀` to sum column-wise instead of row-wise.
[Answer]
# JavaScript (ES6), ~~88~~ 79 bytes
Returns `[]` for `[0]`.
```
f=(a,y,b=a.map((_,x)=>a.map(c=>y>=c|x--<0?0:s+=c,s=0)|s))=>s?[b,...f(a,-~y)]:[]
```
[Try it online!](https://tio.run/##ZVDtTsMwDPzPU/RnItzMSVvYJtI9SBShLKwINJZpQWiVJl69OFtpBVGcj/Odz1be3ZeL/vR2/CwP4WU3DJ1mDnrYaic@3JGxZzhz3d6A123fan85l@UTbnAd77WHqJFfIidR3JgtCCE6cii/e27Xxg4@HGLY78Q@vLKOGbScF4tFYWwRToUx1t79U8hfBb0ysprIysK4M5ECNckU1CRKZ@4FCDj7Aa3k9@fOpwNFRA3NPCXhB5AIsqEyJL6BFcj6CpDIR5BqBEiVq@mN5JI3IKOxbDn3oKS8Rg2KRkgeKXeLChS1Xdr093b4AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 85 bytes
```
lambda x:[[sum(n*(n>j)for n in x[:i+1])for i in range(len(x))]for j in range(max(x))]
```
[Try it online!](https://tio.run/##RYxBDsIgEEX3noJdQWdBqUbTpF6EssDYKk2ZNi0meHpk2Lj4mTcvM3/9hveCKo1dn2brH0/LYqv1/vEcjxzvkxiXjSFzyKJu3ak2RTgSm8XXwOcBeRTCkJ7@2ttYdArDHvZOawU1NFAb0DKHZpOjQBGBhGJB5ZszXIhlfpB5vcLNmAPVB6ovfe26OQwsQNVjBSMPolD6AQ "Python 2 – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 64 bytes
```
@(x,k=a=0*(x+(1:max(x))'))eval"for i=x;a(1:i,++k:end)+=i;end,a";
```
[Try it online!](https://tio.run/##jY1hS8MwEIa/91eEwTCxZ7lkretWIv6PkA@htlBWNxAdBfG31zeztggDRy7Jvc/de3eq38O5GVubZdn4LAc62GD5Xg6p1PvXMMhBqTulmnPoV@3pTXR2qAJKHaXpYd8cX1Rquwo/hVU11sKKT8ee1uLhSTgv4HDO@8TpX4YMcjNLZNMFNmTmgqEcOL6xn5h48RBO9Pz54xYySHMqlm3Qj6SZNJhj1Avakc4vglHckjaTYDh3c86YEkfCOjWWy1RAfYmcDJZGV2Q/sSGDReW/DLElU9zM1jc0IsorjK8yn3xVSd30fftxlC3VavwG "Octave – Try It Online")
### Explanation:
Yet again: Expressions in the argument list and eval are used in one function :)
This takes `x` as input, and creates two identical matrices filled with zeros, with the dimensions `k=a=zeros(length(x),max(x))`. This is achieved by adding the horizontal vector `x` with a vertical vector with `1:max(x)`, implicitly expanding the dimensions to a 2D-array, then multiplying this with zero. `~(x+...)` doesn't work unfortunately, since that forces `a` to be a logical array throughout the rest of the function.
`for i=x` is a loop that for each iteration makes `i=x(1)`, then `i=x(2)` and so on. `a(1:i,k++:end)` is the part of the matrix that should be updated for each iteration. `1:i` is a vector saying which rows should be updated. If `i=0`, then this will be an empty vector, thus nothing will be updated, otherwise it's `1, 2 ...`. `++k:end` increments the `k` matrix by one, and creates a range from the first value of this matrix (`1,2,3...`) and up to the last column of the `a` matrix. `+=i` adds the current value to `a`. `end,a` ends the loop and outputs `a`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes
```
Thread@Accumulate@PadRight[#~Table~#&/@#]&
```
[Try it online!](https://tio.run/##HclNCsIwEIbhqwwEshrpj4pulHiDIt2VLMY0tYHGRUlXIb16nAaGD@Z5PYXZegrOUJ7gkft5tTSqlzGb3xYKVnU0vt13DoPYe/osdheyUkLL3K3uxwqnJ0yD0BokVApirBNCbI45H9MitOVBqPlKZEJguCBcC3BpSme8IdxTyn8 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Java 10, ~~142~~ ~~135~~ 134 bytes
```
a->{int l=a.length,i=0,j,s,m=0;for(int q:a)m=q>m?q:m;int[][]r=new int[m][l];for(;i<m;i++)for(j=s=0;j<l;j++)r[i][j]=s+=i<a[j]?a[j]:0;return r;}
```
-7 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##rZHRbsIgFIbvfYpz2UZKULdsEdHsAeaNuzO9OGvRlQFVoC7G9Nk7WucTrAmQA5zz8f8HhRfMVPndFRq9h3es7G0CUNkg3QELCdt@Oxzs830ORTJEgCmP522ccfiAoSpgCxYEdJitbzEJtECqpT2GL6KIJ0YwfqhdXw/nJaZGnNdmc14afkEHTlj5M7xi8r3Oh0xusmzNeNrHSvhYr1aaq@k0dX2WyoWfCrPCGG36Zcm4k6FxFhxvO37Xdmo@ddT2J/FSVyWYaDLZBVfZ4@Dk7nB39UEaWjeBnuJV0DZRsTm0CZWmb87h1dNSytNHfS9NLC2Sh@j8xto0HXryb9JsNNJiNNKczMdTRRgZsVtkThbkiTyP6HUWieP9woxFIIvIF/L6gLaTtvsF)
```
a->{ // Method with integer-array parameter and integer-matrix return-type
int l=a.length, // Length of the input-array
i,j, // Index integers
s, // Sum integer
m=0;for(int q:a)m=q>m?q:m;
// Determine the maximum of the input-array
var r=new int[m][l];
// Result-matrix of size `m` by `l`
for(;m-->0;) // Loop `i` over the rows
for(j=s=0; // Reset the sum to 0
j<l;j++) // Inner loop `j` over the columns
r[m][j]=s+= // Add the following to the sum `s`, add set it as current cell:
m<a[j]? // If the row-index is smaller than the `j`'th value in the input:
a[j] // Add the current item to the sum
: // Else:
0; // Leave the sum the same by adding 0
return r;} // Return the result-matrix
```
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 39 bytes
```
{.$):M;;{[.](*[0]M*+M<}%zip{{\.@+}*]}%}
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPlf979aT0XTytfaujpaL1ZDK9og1ldL29emVrUqs6C6OkbPQbtWK7ZWtfZ/XcL/aCMFQwVjBcNYAA "GolfScript – Try It Online")
Uses [Dennis's algorithm](https://codegolf.stackexchange.com/a/165301/41024).
[Answer]
# [Ruby](https://www.ruby-lang.org/), 50 bytes
```
->a{(1..a.max).map{|n|w=0;a.map{|r|w+=(r<n)?0:r}}}
```
[Try it online!](https://tio.run/##JYyxDsIwDET3fkXHVhyRk4JAQOBDrAxh6EZVRaoa1OTbg0OHO9@z7AvL@1tGW45Pv3VaKa8@PvZi85amtFq6@x1CWg@2C4@pf9Et5JwLs4HGAO3AJKpzEBmYmkD4b2Hk5oRzzSQPJHjB1bm9N6amnVuOGDk61@TyAw "Ruby – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 60 bytes
```
a->matrix(vecmax(a),#a,i,j,vecsum([a[k]|k<-[1..j],a[k]>=i]))
```
[Try it online!](https://tio.run/##HYzRCsIwDEV/JcyXFtKxTkUfXH@k5CGIk25OSp0ywX@vaSFc7jkXEjkFc495hAEyG7fwmsKmPrfrwptijTvGgBOKeL0X5dnP9Jsvxtu2nQgLuiGQ1pljfHwVg3EQU3iuUpsCDYzyRyN435GkLbEv0SP0FRA6uTqKQhBxQDhWIYutu8gTwplI5z8 "Pari/GP – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÔËÆD
z ®å+
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1MvGRAp6IK7lKw&footer=V2ewSgpWaVfUIGMg%2bSDyV2wpbbgKUmlYaTFYPc7K5y0paVggcFggtw&input=WwpbMiwxLDMsMV0KWzBdClsxXQpbM10KWzIsMl0KWzMsMCwwXQpbMSwyLDMsNCw1XQpbMTAsMSwwLDMsNyw4XQpdLW1S) (includes all test cases)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
m∫T0m´R
```
[Try it online!](https://tio.run/##yygtzv7/P/dRx@oQg9xDW4L@//8fbaRjqGOsYxgLAA "Husk – Try It Online")
Dennis' method.
[Answer]
# k, 24 Bytes
```
{+\'+(x#'x),'(x-|/x)#'0}
```
Dennis algorithm
## Sample
```
{+\'+(x#'x),'(x-|/x)#'0}2 1 3 1
(2 3 6 7;2 2 5 5;0 0 3 3)
```
numeric arrays in k are represented as a sequence of values without separators, so `2 1 3 1` is the same as `[2,1,3,1]` in other languages.
k Use the syntax `(..;..;..)` to represent an heterogeneous or multi-level list, so `(2 3 6 7;2 2 5 5;0 0 3 3)` is the same as `[[2,3,6,7],[2,2,5,5],[0,0,3,3]]` in other languages
## Explanation
* `{..x..}` defines an anobymous function with implicit arg x
* `+\array` is the cummulative sum of the elems of the array
* `f'matrix` applies f to each row ('=each) of the matrix preserving matrix shape, so `+\'matrix` calculates cummulative sum of the elems of each row of the matrix
* `n#x` signifies take n copies of x value. if n and x are
both arryas of the same length, `n#'x` applies `#` to each pair, so
`2 1 3 1#'2 1 3 1` is the same as `(2#2; 1#1; 3#3; 1#1)` and
evaluates to `(2 2;,1;3 3 3;,1)`. NOTE one-item list is represented as `,item`
* `a,b` joins (catenates) arrays a and b. `a,'b` applies `,` to each corresponding items of a and b: if both are matrices of the same shape, catenates each corresponding pair of rows
* `|/array` applies binary operator `|` (max) over the elements of the array (reduce), so `|/2 1 3 1` is equivalent to `2|1|3|1` and reduces to 3
* `(x-|/x)` substract to each element of x the maximum of the array, so `2 1 3 1 - |/2 1 3 1` is the same as `2 1 3 1 - 3` and evaluate to `-1 -2 0 -2`
* `array#'0` is "take n copies of 0" for each value n in array. It really uses "abs(n) take 0", so we don't worry about sign. `-1 -2 0 -2#'0` evaluates to `(,0;0 0;();0 0)`. NOTE.- `()` is the empty array
k applies unary operators and binary operators right to left, and parenthesis indicate precedence. NOTE.- k uses one-letter symbols, with two meanings (unary op or binary op) depending of context (example `+` as binary op is sum, but as unary op is flip (transpose).
* `#'` is a binary op modified by `'` adverb. Its arguments are `(x-|/x)` and `0`.
+ Evaluates `x-|/x` first. `|` it's a binary op (max), but adverb `/` convert it to unary (max over x), and evaluates to `3`. The resulting `x-3` is a binary op (minus), with args `x`and `3`, and evals to `-1 -2 0 -2`
+ `-1 -2 0 -2#'0` evals to `(,0;0 0;();0 0)`
* The actual expr is `+\'+(x#'x),'(,0;0 0;();0 0)`. `,` is a binary op (join) modified by `'` adverb (each): we need to evaluate the left arg `(x#'x)`
+ `x#'x` is `2 1 3 1#'2 1 3 1`, and applies binay op `#` (take) to each pair. The result is `(2 2;,1;3 3 3;,1)`
+ `(2 2;,1;3 3 3;,1),'(,0;0 0;();0 0)` applies binary op `,` modified by (') each, and join each pair of corresponding values. The result is `(2 2 0;1 0 0;3 3 3;1 0 0)`
* `+` is a monad operator that transpose (flip) the matrix, so the result is `(2 1 3 1;2 0 3 0;0 0 3 0)`
* `+\'matrix` calculates cummulative sums of each row of the matrix, so eval to `(2 3 6 7;2 2 5 5;0 0 3 3)
] |
[Question]
[
The *prime cluster* of an integer **N** higher than **2** is defined as the pair formed by the highest prime **strictly** lower than **N** and the lowest prime **strictly** higher than **N**.
Note that following the definition above, if the integer is a prime itself, then its prime cluster is the pair of the primes *preceding* and *succeeding* it.
# Task
Given two integers integers **N**, **M** (**N, M ≥ 3**), output a [truthy / falsy value](https://codegolf.stackexchange.com/tags/decision-problem/info) based on whether **N** and **M** have the same prime cluster.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the aim is to reduce your byte count as much as possible. Thus, the shortest code in every [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073) wins.
# Test cases / Examples
For instance, the prime cluster of **9** is `[7, 11]`, because:
* **7** is the highest prime strictly lower than **9**, and
* **11** is the lowest prime strictly higher than **9**.
Similarly, the the prime cluster of **67** is `[61, 71]` (note that **67** is a prime).
**Truthy pairs**
```
8, 10
20, 22
65, 65
73, 73
86, 84
326, 318
513, 518
```
**Falsy pairs**
```
4, 5
6, 8
409, 401
348, 347
419, 418
311, 313
326, 305
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ ~~4~~ ~~3~~ ~~5~~ 4 bytes
```
rÆPE
```
[Try it online!](https://tio.run/##y0rNyan8/7/ocFuA6////y3@GxoAAA "Jelly – Try It Online") or [Try all test cases](https://tio.run/##JY29DcJQDIR7pvAAlnj@eYkZANHSR6@kQanoaClYhYYtsgmLGNtpTp9Pd@f7bV2f7o/tfT379uHj7/W9uC8LgCEANTwAALdg5uKpY0nyLFiSbFOwabJwsJAld4pMJxtxxKhGCPYyZAEqpO2EIVRljceic/mU/j4kRDkqY/wB "Jelly – Try It Online").
### How it works
```
rÆPE Main link. Arguments: N, M
r Yield the range of integers between N and M, inclusive.
ÆP For each integer, yield 1 if it is prime, 0 otherwise.
E Yield 1 if all items are equal (none in the range were prime,
or there's only one item).
```
Works because two numbers have different prime clusters iff there is a prime between them, or either number is itself prime; *unless* both numbers are the same, in which case `E` returns `1` anyway (all items in a single-item array are equal).
[Answer]
# [Perl 6](https://perl6.org), 52 bytes
```
{[eqv] @_».&{(($_...0),$_..*)».first(*.is-prime)}}
```
[Test it](https://tio.run/##hVBLasMwEN37FEMwQUoVYVnyp5gWr3qC7EIITiqDwUkcywkU45N114u5o0gtdNWV3sy8z2g63bfpfDMa7ik/FsHpA5bHy7uGl3nc6ut9B@X@65MvR0LCPec8osy@K4rNuunNQFa8Meuub06aTtOM@nLob6gHEgCQnIFAjYVxxCCOHU4TBmnicCYZZNLhPGWQK4dljIUUuasSgbTkUdHHmmVdteY3R@HQW6ODQyp6ZqAi4e0U7iJV5mfCzn7MpRA2Sjpze42NNkMRdG119v958oFFUF9631u/AoGwYhAegMKITo0Bez2CzfBAGWyQxmCxdaTdIpic3O3@v/7N8v4azN8 "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with implicit slurpy input 「@_」
[eqv] # see if each sub list is equivalent
@_».&{ # for each value in the input
(
( $_ ... 0 ), # decreasing Seq
$_ .. * # Range
)».first(*.is-prime) # find the first prime from both the Seq and Range
}
}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 103 95 91 bytes
```
lambda*z:len({*z})<2or[1for i in range(min(z),max(z)+1)if all(i%k for k in range(2,i))]<[0]
```
[Try it online!](https://tio.run/##RY7LcsIwDEXX9Vdow4wNWviVBwx8iZvpGJq0HhKHSbKAMP321AoLVjqS7pXu7TH99tEszelzaX13/vbb@dDWkT@385846n5wqukHCBAiDD7@1LwLkc8CO39PZadEaMC3LQ@bK5Dy@lZqDEJURyerZarH6evix3qEEzjmSgQlK2ROSwStifIMIc@ICoNQGKIyRygtkdEJjSqJM5UE2YttotWdhGsv9whWqtVj0xtji3WuaP7yGKXoFn2oGKPQd3xQ7HfKA/u4DSFOvOFpJ8TyDw "Python 3 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~57~~ 54 bytes
```
->n,m{[*n..m,*m..n].all?{|x|?1*x=~/^(11+)\1+$/}||n==m}
```
[Try it online!](https://tio.run/##hY7NToQwFIX38xQ3RBJlaodLy48mdR7CZa0JoxAWgKZAMhOKr469sHThql9O7vl67HS5rbVaH1961s066jnvWNRx3htetu15dld3xuiqfk7v94jHhzc83p0W53qlumUd7TQ2N1CgdcEAY8NAJzGDJCHKUgZZSpQLBrkgKjIGhSQSiUeBBXGK/iD1bA512Q67Ufpo0/gGvTJ@YiBj3MrS/ydkvuVI@S4SiCQVXvQ9jQMEr83X1H7CpQK/tXoODvtkXpUfDczOOtjvwgHCIQi1ZbWOrDHLnz4NI8E28P/@@gs "Ruby – Try It Online")
Uses the horrible regex primality test from [my answer](https://codegolf.stackexchange.com/a/57668/11071) (which I had forgotten about until I clicked on it) to the related question [Is this number a prime?](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime). Since we have N, M ≥ 3, the check for 1 can be removed from the pattern, making the byte count less than using the built-in.
Note: The regex primality test is pathologically, hilariously inefficient. I believe it's at least O(n!), though I don't have time to figure it right now. It took twelve seconds for it to check 100,001, and was grinding for five or ten minutes on 1,000,001 before I canceled it. *Use/abuse at your own risk.*
[Answer]
# [Retina](https://github.com/m-ender/retina), 58 bytes
```
\b(.+)¶\1\b
.+
$*
O`
+`\b(1+)¶11\1
$1¶1$&
A`^(11+)\1+$
^$
```
[Try it online!](https://tio.run/##K0otycxL/P8/JklDT1vz0LYYw5gkLi49bS4VLS7/BC7tBKCEIUjC0DDGkEvFEMhQUeNyTIjTMAQKxxhqq3DFqfz/b2xkyWVsaAEA "Retina – Try It Online") Explanation:
```
\b(.+)¶\1\b
```
If both inputs are the same, simply delete everything, and fall through to output 1 at the end.
```
.+
$*
```
Convert to unary.
```
O`
```
Sort into order.
```
+`\b(1+)¶11\1
$1¶1$&
```
Expand to a range of all the numbers.
```
A`^(11+)\1+$
```
Delete all composite numbers.
```
^$
```
If there are no numbers left, output 1, otherwise 0.
[Answer]
# PARI/GP, 28 bytes
```
v->s=Set(v);#s<2||!primes(s)
```
[Try it online with all test cases!](https://tio.run/##bc/BDsIgDAbgu0@B8QJJl1AKA6PzJTwaDx42s4OGjGWnvTvCxazGW/O19C/xMY3NM@ahy0tzSd21n@WiTod0Nuu6j9P46pNMKpfqPctB3gII1Heldl8xGoQxjFoHonWMPIHwxCi0IIJlRKYYYWDosLx1W9w0bWnx7LKUgdVHEFYjD7LlI2Q9n8Q6@ZNOiPUk@nOnrsn5Aw)
Returns `0` or `1` (usual PARI/GP "Boolean" values).
Explanation:
`v` must be a vector (or a column vector, or a list) with the two numbers `N` and `M` as coordinates. For example `[8, 10]`. Then `s` will be the "set" made from these numbers, which is either a one-coordinate vector (if `N==M`), or a two-coordinate vector with *sorted* entries otherwise.
Then if the number `#s` of coordinates in `s` is just one, we get `1` (truthy). Otherwise, `primes` will return a vector of all primes in the closed interval from `s[1]` to `s[2]`. Negation `!` of that will give `1` if the vector is empty, while negation of a vector of one or more non-zero entries (here one or more primes) will give `0`.
[Answer]
# JavaScript (ES6), ~~57~~ 56 bytes
Takes input in currying syntax `(a)(b)`. Returns `0` or `1`.
```
a=>b=>a==b|!(g=k=>a%--k?g(k):k<2||a-b&&g(a+=a<b||-1))(a)
```
### Test cases
```
let f =
a=>b=>a==b|!(g=k=>a%--k?g(k):k<2||a-b&&g(a+=a<b||-1))(a)
console.log('Truthy')
console.log(f(8)(10))
console.log(f(20)(22))
console.log(f(65)(65))
console.log(f(73)(73))
console.log(f(86)(84))
console.log(f(326)(318))
console.log(f(513)(518))
console.log('Falsy')
console.log(f(4)(5))
console.log(f(6)(8))
console.log(f(409)(401))
console.log(f(348)(347))
console.log(f(419)(418))
console.log(f(311)(313))
```
### How?
```
a => b => // given a and b
a == b | // if a equals b, force success right away
!(g = k => // g = recursive function taking k
a % --k ? // decrement k; if k doesn't divide a:
g(k) // recursive calls until it does
: // else:
k < 2 || // if k = 1: a is prime -> return true (failure)
a - b && // if a equals b: neither the original input integers nor
// any integer between them are prime -> return 0 (success)
g(a += a < b || -1) // else: recursive call with a moving towards b
)(a) // initial call to g()
```
[Answer]
# [R](https://www.r-project.org/), ~~63~~ 46 bytes
*-17 by Giuseppe*
```
function(a,b)!sd(range(numbers::isPrime(a:b)))
```
[Try it online!](https://tio.run/##HcZBCoAgEADAe6@o2y5skIki0iP6gpaGBw00379Rp5nKcdxmjr0cT7oLOPI4tROqK1eA0rMPtVmb2l5TDuCsR0SOYEgsOERQQpIS5qumH7lqkotCfgE "R – Try It Online")
Pretty simple application of [ETHProductions' Jelly solution](https://codegolf.stackexchange.com/a/147258/72784). Main interesting takeaway ~~is~~ was that with R boolean vectors `any(x)==all(x)` is equivalent to `min(x)==max(x)`.
[Answer]
# C (gcc), ~~153~~ 146 bytes
```
i,B;n(j){for(B=i=2;i<j;)B*=j%i++>0;return!B;}
#define g(l,m,o)for(l=o;n(--l););for(m=o;n(++m););
a;b;c;d;h(e,f){g(a,b,e)g(c,d,f)return!(a-c|b-d);}
```
-7 from Jonathan Frech
Defines a function `h` which takes in two `int`s and returns `1` for truthy and `0` for falsey
[Try it online!](https://tio.run/##dZHNcoIwEMfvPMXWDjOJLDOEoNKu9MBrWA4YPkQFO0h7oTw7TSyDXjxssr/9bzbZjXJLpcaxwpgaduR9cWlZHFWRT9X2SDxeRke7cpwPj9q8@26bl5gG6zXLi6rJoWRnrPHCzaFzdNEVXPfMiZMJ1LeA49QmYKW0J0UZHViOBe9LluIec14yhZkOTMVZ6qrfvZtxGsaq6aDLr911l@xkAhH0FkAfovAQxIAGfO36/ozrFYKxCTcSwdiE4RrDYCbpr1GKcOaVkLh64AB1IW@qi@HsB94bBp6YWQYhymBz14XWxT1fCqHvkYatgSzTVJ1WDTNO2pYKQR3SFpZLDT/81qMeHtz0k27aI71tQUgCxzn9JwB8tVov2MLO0M7ewc4givT62Sxwmtkp2XnJAwgNB/ZM4w/kJ/q7APRzxz8 "C (gcc) – Try It Online")
`n` is a function that returns 1 if its argument is not prime.
`g` is a macro that sets its first and second arguments to the next prime less than and greater than (respectively) it's third argument
`h` does `g` for both inputs and checks whether the outputs are the same.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ÆpżÆnE
```
[Try it online!](https://tio.run/##y0rNyan8//9wW8HRPYfb8lz///8fbWxoqKNgbGgcCwA "Jelly – Try It Online")
-2 thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis).
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~18+16 = 34~~ 24 bytes
```
⎕CY'dfns'
∧/=/4 ¯4∘.pco⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@jvqnOkeopaXnF6lyPOpbr2@qbKBxab/KoY4ZeQXI@UBak7L8CGKRxWegoGBpwwXhGBjoKRkZwrpmpjoKZKZxrbqyjYG4M51qY6ShYmMC5xkZAvrGhBVzA1BCo3hRJwATIRZgN1IyQMbDUUTAxMEQYZgJ0mLGJOUKFIUgFkmHGhoYg64zR7DcwBQA "APL (Dyalog Unicode) – Try It Online")
Thanks to [Adám](https://judaism.stackexchange.com/users/3073/adam) for 10 bytes.
The line `⎕CY'dfns'` (**C**OP**Y**) is needed to import the [*dfns*](http://dfns.dyalog.com/) (**d**ynamic **f**unctio**ns**) collection, included with default Dyalog APL installs.
### How it works:
```
∧/=/4 ¯4∘.pco⎕ ⍝ Main function. This is a tradfn body.
⎕ ⍝ The 'quad' takes the input (in this case, 2 integers separated by a comma.
pco ⍝ The 'p-colon' function, based on p: in J. Used to work with primes.
4 ¯4∘. ⍝ Applies 4pco (first prime greater than) and ¯4pco (first prime smaller than) to each argument.
=/ ⍝ Compares the two items on each row
∧/ ⍝ Applies the logical AND between the results.
⍝ This yields 1 iff the prime clusters are equal.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~87~~ 86 bytes
```
lambda*v:v[0]==v[1]or{1}-{all(v%i for i in range(2,v))for v in range(min(v),max(v)+1)}
```
[Try it online!](https://tio.run/##VYzLasMwEEX38xWzKZZSBfTyowH/RXdpFiq1YoEsG8VWakK@3ZWhULo6w7n3zrTO/RjkZtuPzZvh88sc0imd@aVt01lcxvgQz@PDeE/Si0M7RnToAkYTrh2RLFG6u/TnBhdIomww3xmvgj63e@98h@9x6U6A6CxacnBhWmZC6W4Qp@jCjMUcl7lfi6w6f@v@Rdb421psDUPBQXKGUkJVMqxKqBXDWkFTMWw0KJmpRAOlyL7Mh86APQTN3xhqLkDp/EjpGrTYTS4pIfaZ@t3z8gc "Python 2 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~103 bytes~~ 100 bytes
```
i,j,p,s;f(m,n){s=1;for(i=m>n?i=n,n=m,m=i:m;i<=n;i++,p?s=m==n:0)for(p=j=2;j<i;)p=i%j++?p:0;return s;}
```
[Try it online!](https://tio.run/##fZBBboMwEEXX4RQjpEggBsXGkFAcl10v0C6zSZPQGMWOhWFRRTk7NVGlSpXJ@v35@m8O6dfhMI4SWzRoeRMp1PHNCsqbaxdJoV51LYVGLRQqISvF5VZoLpMETW2FEkJXJJ6yRrQi4@1W8tgIuWyTpDYV4d2pHzoNlt9HqXtQe6mjOLgFi9UKPrqhP3@D2cvOBgsz9DYK38/X4XKEzxP0D1rtdJqmYcxdoHMNTRQujzsdIjRRiUBJ7EUZQcgyP1sXCOvCzzYMYcP8rFwjlLmfscxBRks/LairLX7pQ/1tf7H/zHf6z72Z8DP13PXN2LmRfpKTF4Sc0BmD3L2T5ZuZWzrdzvkxSid79uw35LH3Pv4A "C (gcc) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 81 bytes
A straightforward solution:
```
p z=[x|x<-z,all((0/=).mod x)[2..x-1]]!!0
c x=(p[x-1,x-2..],p[x+1..])
x!y=c x==c y
```
[Try it online!](https://tio.run/##bZHBa4MwFMbv@SueZYcEY5cYbR0sg10Kg@603USGdEpLrRWjLJb97@7F06bz8Mj3@957@dRjbs5FVY1jAzed2m/7GNx4XlWUinvN1pfrJ1iWhuu1DWSWeZ4gB7CaNilqbgM0Mo7Cl3hgxHqDdj6WYewK0xmdEsCHvrd9wYEmHKRgjP@BoeAQhnO6iTls4jndKg5bNafJhkMSzakKESuZzHkscUn8i@/yyjgjQryAbvWyUzxwiIRcGCrCV1TRdjkh3cQ/lyopXUq1NKb4AhNNPCOkBGo5DAw0WPBgIMR9Y8hrg1pD03dvXbuv4Q7M8fqFzPdhBQE8YcXjBGmJPxTVtPNUQulG9bSjOxY1dtLrma2gwBBO7J5f9mw1dZNLfqrxnkvevH4A7etD37YDuAxsqmb8AQ "Haskell – Try It Online")
[Answer]
# Mathematica, 39 27 26 bytes
```
Equal@@#~NextPrime~{-1,1}&
```
Expanded:
```
& # pure function, takes 2-member list as input
#~NextPrime~{-1,1} # infix version of NextPrime[#,{-1,1}], which
# finds the upper and lower bounds of each
argument's prime clusters
Equal@@ # are those bounds pairs equal?
```
Usage:
```
Equal@@#~NextPrime~{-1,1}& [{8, 10}]
(* True *)
Equal@@#~NextPrime~{-1,1}& [{6, 8}]
(* False *)
Equal@@#~NextPrime~{-1,1}& /@ {{8, 10}, {20, 22}, {65, 65},
{73, 73}, {86, 84}, {326, 318}, {513, 518}}
(* {True, True, True, True, True, True, True} *)
Equal@@#~NextPrime~{-1,1}& /@ {{4, 5}, {6, 8}, {409, 401},
{348, 347}, {419, 418}, {311, 313}}
(* {False, False, False, False, False, False} *)
```
Contributions: -12 bytes by [Jenny\_mathy](https://codegolf.stackexchange.com/users/67961/jenny-mathy), -1 byte by [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender)
[Answer]
# [J](http://jsoftware.com/), 15 bytes
```
-:&(_4&p:,4&p:)
```
How it works:
```
&( ) - applies the verb in the brackets to both arguments
4&p: - The smallest prime larger than y
_4&p: - The largest prime smaller than y
, - append
-: - matches the pairs of the primes
```
[Try it online!](https://tio.run/##VY7BDsIgDIbve4rGw3DJNJQCmyS7@gTezWIkczFxGXrw4LMjDHbYgYavf/v/Hb110BngEJ4/mHJ/leVk6lgqXxW7IzDbGQY1/AxYVxT32/ACdpk/7@ELU/@YHUu9FiwgT3/BAwiRQKsAWiVoKEBDeUUHaGUCEpEI24QK46RakZ37p9sGyqjniOiTu/wUQHLMrjLeRbLJKi7q6kqISyZtTuDK/wE "J – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
α╖ª»º√π├╔
```
[Run and debug it](https://staxlang.xyz/#p=e0b7a6afa7fbe3c3c9&i=%5B8,+10%5D%0A%5B20,+22%5D%0A%5B65,+65%5D%0A%5B73,+73%5D%0A%5B86,+84%5D%0A%5B326,+318%5D%0A%5B513,+518%5D%0A%5B4,+5%5D%0A%5B6,+8%5D%0A%5B409,+401%5D%0A%5B348,+347%5D%0A%5B419,+418%5D%0A%5B311,+313%5D%0A%5B326,+305%5D&m=2)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŸpË
```
Port of [*@ETHproductions*'s Jelly answer](https://codegolf.stackexchange.com/a/147258/52210), so make sure to upvote him!
[Try it online](https://tio.run/##yy9OTMpM/f//6I6Cw93//0db6BgaxAIA) or [verify all test cases](https://tio.run/##NYwxCgJBDEWvsmz9i2SSzMRqDzJMoWBhpSAIewEbO09jL17Ei4yZBav3@LzkfN0fTsd@W5d5@t6f07ys/fO6vB8dvVYHU0NNhJSC2ZAtWARFgp7hGpSUIexhxgLbTDHKCIbTDko8SnWIlrFxbFspzHEt/z9krf0A).
**Explanation:**
```
Ÿ # Create an inclusive ranged list of the (implicit) input-pair
p # Check for each value in the list whether it's a prime (1 if truthy; 0 if falsey)
Ë # Check if all values are the same (so either all truthy or all falsey)
# (after which the result is output implicitly)
```
] |
[Question]
[
**Introduction**
Today I went fishing alone with my canoe, unfortunately I fell asleep and the stream brought me away, I lost my oars, now it's night and I am lost in the ocean! I can't see the coast so I must be far away!
I have my cell phone but is malfunctional because it got wet by the salty water, I can't talk or hear anything because the mic and phone speaker are broken, but I can send SMS to my friend who is on the coast's beach!
My friend has a very powerful torch and he raised it on top of bamboo's canes to show me the right direction, but I can’t row because I have no oars, so I must tell him how far I am so he can send someone to catch me!
My friend told me that he is keeping the torch at 11.50 meters on the sea level, and I can see the light right over the horizon. Now I only remember from the school that the Earth radius should be 6371 Km at the sea level, and I’m sittin in my canoe so you can assume that my eyes are at sea level too.
**Task**
Since the currents are moving me moment by moment, my friend is raising the torch from time to time (now it’s at 12.30 meters), please write a full program or function that will help me to calculate the distance from my friend’s position!
Here is a diagram (not to scale):
[](https://i.stack.imgur.com/FhOkf.png)
The orange point labelled `M` is me, the red point labelled `T` is the torch. The green line is the linear distance between `M` and `T`
**Input**
Take from standard input the torch height `h` in meters at the sea level, which I see right on top of the horizon, in the form of a floating point number with two decimals precision (with the accuracy of 1 centimeter or 0.01 meters), in the range from 0 to 100 included.
**Output**
You should return the euclidean length of the green line with the accuracy of 1 cm. For example if you output in meters, should be with two decimals (at least). The output can be either meters or kilometers, but respecting the accuracy.
**Test cases:**
All values in meters.
```
11.5 > 12105.08
13.8 > 13260.45
```
**Rules**
Shortest code wins.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~13~~ ~~12~~ 10 bytes
Saved 2 bytes thanks to Emigna.
Since there is no trigonometric functions to be called using OP's assumption that the earth is locally a plane, it becomes possible to make an 05AB1E solution.
```
•1#oC•+¹*t
For understanding purposes input is referred to as 'h'
•1#oC• Push 12742000 [ = 2*R, where R is the radius of earth]
+ Compute 2*R+h
¹* Multiply by h. Result is (2*R*+h)*h
t Take the square root of it and implicitly display it
```
[Try it online!](http://05ab1e.tryitonline.net/#code=4oCiMSNvQ-KAoivCuSp0&input=MTMuOA)
[Answer]
# Python, ~~34~~ 26 bytes:
(*-8 bytes thanks to Osable!*)
```
lambda i:(i*(i+12742))**.5
```
An anonymous lambda function. Takes input in kilometers and outputs in kilometers. Invoke as `print(<Function Name>(<Input>))`.
[Answer]
# PHP, 34 bytes
```
<?=sqrt((12742e3+$h=$argv[1])*$h);
```
**breakdown**
```
r^2+x^2=(r+h)^2 # Pythagoras base
r^2+x^2=r^2+2rh+h^2 # right term distributed
x^2= 2rh+h^2 # -r^2
x =sqrt(2rh+h^2) # sqrt
```
so far, this is identical to the old Mathematica answer
```
sqrt(2*6371e3*$h+$h*$h) # to PHP
sqrt(14742e3*$h+$h+$h) # constants combined
sqrt((14742e3+$h)*$h) # conjugation to save a byte
((14742e3+$h)*$h)**.5 # same size
```
now all that´s left to do is to add input `=$argv[1]` and output `<?=` - done
[Answer]
# dc, ~~16~~ 11 bytes:
```
?d12742+*vp
```
Prompts for input through command line in kilometers and then outputs distance in kilometers.
## Explanation
```
? # Prompt for input
d # Duplicate the top-of-stack value
12742 # Push 12,742 onto the stack
+ # Pop the top 2 values of the stack and push their sum
* # Pop top 2 values of the stack and push their product
v # Pop the remaining value and push the square root
p # Output the result to STDOUT
```
This takes advantage of the following:
```
((6371+h)**2-6371**2)**.5
=> ((6371**2+12742h+h**2)-6371**2)**0.5
=> (h**2+12742h)**0.5
=> (h*(h+12742))**0.5
```
[Answer]
# jq, 18 characters
```
(12742e3+.)*.|sqrt
```
Yet another copy of the same formula.
Sample run:
```
bash-4.3$ jq '(12742e3+.)*.|sqrt' <<< 11.5
12105.087040166212
```
[On-line test](https://jqplay.org/jq?q=(12742e3%2b.)*.|sqrt&j=11.5)
[Answer]
# Haskell, 22 bytes
```
d h=sqrt$h*(h+12742e3)
```
Usage:
```
Prelude> d 11.5
12105.087040166212
```
---
### Pointfree: (23 bytes)
```
sqrt.((*)=<<(+12742e3))
```
[Answer]
## R, 29 bytes
```
h=scan();sqrt(h^2+2*h*6371e3)
```
Takes input from stdin
[Answer]
## Mathematica, 16 bytes
Either of these works for both input and output in kilometres:
```
(12742#+#*#)^.5&
```
```
((12742+#)#)^.5&
```
This is a simple application of Pythagoras to the problem:
```
x*x + R*R = (R+h)*(R+h)
=> x*x = (R+h)*(R+h) - R*R
= R*R + 2*R*h + h*h - R*R
= 2*R*h + h*h
=> x = √(2*R*h + h*h)
```
[Answer]
# Jelly, 9 bytes in Jelly's code page
I decided to have a go at writing the program in a golfing language. I actually found a more efficient algorithm than the one other people are using (at least over short distances like the one in the question), but it requires literal floating-point numbers which Jelly doesn't seem to be able to compress, so Pythagoras it is.
```
+“Ȯịż’×µ½
```
Explanation:
```
“Ȯịż’ 12742000, compressed base-250
+ add to argument
× multiply with original argument
µ separator to avoid what would otherwise be a parsing ambiguity
½ square root everything seen so far
implicit output at EOF
```
The need for the `µ` separator irks me, but I think it's unavoidable; Jelly has already saved a byte over 05AB1E via being able to guess what arguments many of the commands need, but in this case it can't correctly guess to the end, so I needed to give it a hint.
# Jelly, 7 bytes in Jelly's code page
```
דȮịż’½
```
As I explained in my [other answer](https://codegolf.stackexchange.com/a/101091/62131), the series approximation to the Pythagoras approximation actually produces better results over the lengths included in the question (at least, they're closer to the example outputs), and also has a shorter formula. While I was writing it, I realised that instead of calculating the square root of 12742000 in advance, I could multiply the number by 12742000 first, and then square root both at the same time. This is basically equivalent to the other formula without the addition, and as such, it can be produced from the previous program via removing the addition from it. This saves two bytes, as it now parses unambiguously and so we don't need a `µ` any more.
[Answer]
# Ruby, 23
23 bytes, in Km
```
->h{(h*h+h*12742)**0.5}
```
25 bytes, in m
```
->h{(h*h+h*12742e3)**0.5}
```
[Answer]
# Tcl, 49 bytes:
```
set A [get stdin];puts [expr ($A*($A+12742))**.5]
```
Well, I am brand new to Tcl, so any tips for golfing this down is highly appreciated. Like my other answers, prompts for command line input in kilometers and outputs in kilometers. Essentially a Tcl adaptation of my existing `dc` and `python` answers.
[Answer]
# x86\_64+SSE machine code, 16 bytes
The bytes of the program are on the left (in hexadecimal), there's a disassembly on the right to make it a bit easier to read. This is a function that follows the normal x86\_64 convention for functions taking and returning a single-precision floating point number (it takes the argument in %xmm0 and returns its answer in the same register, and uses %xmm1 and %eax as temporaries; these are the same calling conventions a C program will use, and as such you can call the function directly from a C program, which is how I tested it).
```
b8 80 19 5f 45 mov $0x455f1980,%eax
66 0f 6e c8 movd %eax,%xmm1
0f 51 c0 sqrtps %xmm0,%xmm0
0f 59 c1 mulps %xmm1,%xmm0
c3 retq
```
Even with a disassembly, though, this still needs an explanation. First, it's worth discussing the formula. Most people are ignoring the curvature of the earth and using Pythagoras' formula to measure the distance. I'm doing it too, but I'm using a series expansion approximation; I'm only taking the term relating to the first power of the input, and ignoring the third, fifth, seventh, etc. powers, which all have only a very small influence at this short distance. (Besides, the Pythagoras approximation gives a low value, whereas the later terms in the series expansion serve to reduce the value; as such, by ignoring a minor factor that would serve to push the approximation in the wrong direction, I actually happen to get a more accurate result by using a less accurate formula.) The formula turns out to be √12742000×√h; as a single-precision floating-point number, √12742000 is `0x455f1980`.
The next thing that might confuse people is why I'm using vector instructions for the square root and the multiply; `%xmm0` and `%xmm1` can hold four single-precision floating point numbers each, and I'm operating on all four. The reasoning here is really simple: their encoding is one byte shorter than that of the corresponding scalar instructions. So I can make the FPU do a bunch of extra work square-rooting and multiplying zeroes in order to save myself two bytes, in a method that's very reminsicent of the typical golfing language algorithm. (I called x86 assembler the golfing language of assemblers in chat a while back, and I still haven't changed my mind on that.)
From there, the algorithm's very simple: load `%xmm1` with √12742000 via `%eax` (which is shorter in terms of bytes than loading it from memory would be), square-root the argument (and three zeroes), multiply corresponding elements of `%xmm1` and `%xmm0` (we only care about the first element), then return.
[Answer]
# Minkolang v0.15, 22 bytes
```
ndd*$r'12742000'*+1MN.
```
[Try it online!](http://play.starmaninnovations.com/minkolang/?code=ndd*%24r%2712742000%27*%2B1MN%2E&input=13%2E8)
```
n gets input in the form of a number
dd duplicates it twice
* multiplies 2 of the duplicates with each other
STACK: [h, h*h]
$r swap top two stack values
STACK: [h*h, h]
'12742000'* push this number and multiply the original input by it
STACK: [h*h, h*12742000]
+1M adds the two values and takes their square root
STACK: [sqrt(h*h+h*12742000)]
N. output as a number and end program
```
[Answer]
# JavaScript (ES6), ~~31~~ 25 bytes
Displays the value in metres
```
//the actual code
f=h=>(h*h+12742e3*h)**0.5
console.log(f(11.5));
console.log(f(13.8));
```
] |
Subsets and Splits